I need to implement a web app that consists in publishing events with the option of send notifications to subscribed people. How can I use the codename one libraries from a Web App?
Another question: When a cell phone receive the notification, can the application be opened in a specific window, in this case, the window which contain the event description?
Thank you in advance.
If your web app server is running php, you can use CURL to send push notifications to devices. You can easily do the same with other languages. See below sample php code I used.
Shai mentioned recently that you can include some hidden payload in your push message. You can add some variables to this data which you'll check and use to open the necessary form.
PHP sample code:
$cloudServerURL = "https://push.codenameone.com/push/push";
$token = "Your_Developer_token"; //Can be found under account tab of Dashboard
$auth = "Google_Push_Key";
$certPassword = "Your_Certificate_Password";
$cert = "https://www.dropbox.com/path_to_your_iOS_cert/MyAppDevPush.p12?dl=1"; //Test
//Note the 'dl=1', this will download the certificate, instead of opening it.
//$cert = "https://www.dropbox.com/path_to_your_iOS_cert/MyAppProPush.p12?dl=1"; //Live
$production = "false"; //Test
//$production = "True"; //Live
$burl = "";
$bbAppId = "";
$bbPass = "";
$bbPort = "";
$device = 'device_key';
$type = "3"; //Or other types like (2, 101) as required
$body = "Hello world";
$arguments = 'token=' . $token . '&device=' . $device . '&type=' . $type . '&auth=' . $auth . '&certPassword=' . $certPassword . '&cert=' . $cert . '&body=' . $body . '&burl=' . $burl . '&bbAppId=' . $bbAppId . '&bbPass=' . $bbPass . '&bbPort=' . $bbPort . '&production=' . $production;
$ch = curl_init($cloudServerURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $arguments);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_exec($ch);
$response = unserialize(curl_multi_getcontent($ch));));
curl_close($ch);
Related
I've been tearing my hair out for a while now. What I have so far is cribbed from the Coinbase Pro API documentation.
The Coinbase Pro API requires four different headers, one of them being a signature that's encrypted. I'm having issues forming a valid signature. According to the Coinbase Pro API Documentation:
<?php
// Your code here!
$request_path = "/accounts";
$secret = "ZSTJxPU6g9+QLITr5U4IeKWiaoCMqs9TFnCEavdvIjQOO/TqS4ZuRirtKLKUI4UBAen0TyBEsyDmzOZQQ6SC1w==";
$ch = curl_init("https://api.pro.coinbase.com/time");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch,CURLOPT_USERAGENT,'CoinbaseProAPI');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = json_decode(curl_exec($ch));
curl_close($ch);
$timestamp = $result->epoch;
$timestamp_rounded = intval(ceil($timestamp));
$what = $timestamp_rounded.'GET'.$request_path;
$sig = base64_encode(hash_hmac("sha256", $what, base64_decode($secret), true));
$ch = curl_init("https://api.pro.coinbase.com".$request_path) ;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
curl_setopt($ch,CURLOPT_USERAGENT,'CoinbaseProAPI');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'CB-ACCESS-KEY: 513194d14d510c48fd3ba86edef54969',
'CB-ACCESS-SIGN: '.$sig,
'CB-ACCESS-PASSPHRASE: bbujnpclpsv',
'CB-ACCESS-TIMESTAMP: '.$timestamp,
'Content-Type: application/json'));
$coinbasepro_response = curl_exec($ch) ;
curl_close($ch) ;
echo $coinbasepro_response;
?>
The response I'm getting is an invalid signature. I'm stumped, and any help is appreciated.
Using Cake version 2.4.3 stable
So I am having a time here, I have modified this plug in to save files to the app folder https://github.com/srs81/CakePHP-AjaxMultiUpload/
The uploaded files are being saved to /public_html/app/files
Now the strange thing is, when trying to serve these files to the view, I can read the file name, the file size, but not the file itself, image, pdf, etc.
When I try to access the file via direct url, i get this error :
Error: FilesController could not be found.
How can it be that I can read the file name, the file size, but not the file itself?
There is a need to save the files in the app folder. These files should be protected and therefore only be accessed by users who are logged into the application. I have tried to use cake send file response with no outcome.
Edit : I guess the real question at hand here is how can I read files from APP . DS . 'files' ?
View code :
public function view ($model, $id, $edit=false) {
$results = $this->listing ($model, $id);
$directory = $results['directory'];
$baseUrl = $results['baseUrl'];
$files = $results['files'];
$str = "<dt>" . __("Pictures") . "</dt>\n<dd>";
$count = 0;
$webroot = Router::url("/") . "ajax_multi_upload";
foreach ($files as $file) {
$type = pathinfo($file, PATHINFO_EXTENSION);
$filesize = $this->format_bytes (filesize ($file));
$f = basename($file);
$url = $baseUrl . "/$f";
if ($edit) {
$baseEncFile = base64_encode ($file);
$delUrl = "$webroot/uploads/delete/$baseEncFile/";
$str .= "<a href='$delUrl'><img src='" . Router::url("/") .
"ajax_multi_upload/img/delete.png' alt='Delete' /></a> ";
}
$str .= "<img src='$url' /> ";
$str .= "<a href='$url'>" . $f . "</a> ($filesize)";
$str .= "<br />\n";
}
$str .= "</dd>\n";
return $str;
}
And the upload / save
public function upload($dir=null) {
// max file size in bytes
$size = Configure::read ('AMU.filesizeMB');
if (strlen($size) < 1) $size = 20;
$relPath = Configure::read ('AMU.directory');
if (strlen($relPath) < 1) $relPath = "files";
$sizeLimit = $size * 1024 * 1024;
$this->layout = "ajax";
Configure::write('debug', 0);
$directory = APP . DS . $relPath;
if ($dir === null) {
$this->set("result", "{\"error\":\"Upload controller was passed a null value.\"}");
return;
}
// Replace underscores delimiter with slash
$dir = str_replace ("___", "/", $dir);
$dir = $directory . DS . "$dir/";
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
$uploader = new qqFileUploader($this->allowedExtensions,
$sizeLimit);
$result = $uploader->handleUpload($dir);
$this->set("result", htmlspecialchars(json_encode($result), ENT_NOQUOTES));
}
The only real change from the original plug in is changing WWWROOT to APP to make the switch. Saving works fine and lovely. But its just weird that I can read the file name, file size in the view no problem but cannot view an image, pdf, etc.
The problem:
You cannot display files that are outside the webroot via a direct URL - that's the whole point in putting them above the webroot in the first place - to make them NOT directly accessible.
So building the image src path in the controller first (not good practice anyway) won't change the fact that when that path gets to the browser, and it reads the source of the image as trying to pull an image from above webroot, it won't/can't.
The Solution:
The solution is to use a CakePHP's Sending files (what used to be Media Views). Then, you set your img's "src" to a controller/action. In that action, it basically says "display this action as an image" (or pdf, or whatever else).
Path to use in Controller:
took this from one of my apps which is doing exactly the above, and here's the path I used for a file in 'files' (same level as webroot):
file_exists(APP . 'files' . DS . $your_filename)
Create a symbolic link to your folder inside of the webroot ;-)
I am using the file module to get some files from a form locally and upload to another server. When i try to upload large files it gives me timeout error (i have tried changing php.ini but that's not how i want it to work). That's why I am trying to upload the files via ftp functions. However, i cannot get the source path of the file that i just selected to upload (e.g filepath, not uri). I want to pass this filepath into fopen() function as a source. But i keep getting the error: *ftp_nb_fput() [function.ftp-nb-fput]: Can't open that file: No such file or directory in assets_managed_file_form_upload_submit() (line 303 of FILE_DIRECTORY).*
function assets_managed_file_form_upload_submit($form, &$form_state) {
for ($i = 0; $i < $form_state['num_files']; $i++) {
if ($form_state['values']['files_fieldset']['managed_field'][$i] != 0) {
// Make the file permanent.
$file = file_load($form_state['values']['files_fieldset']['managed_field'][$i]);
$local_path = file_create_url($file->uri);
//drupal_set_message(t("file->uri: " . $file->uri . " local path: " . $local_path));
$file->status = FILE_STATUS_PERMANENT;
$directory = 'private://cubbyhouse/'. $form_state['values']['allowed_user'];
file_prepare_directory($directory, FILE_CREATE_DIRECTORY);
$source = fopen($local_path,"r");
$conn = ftp_connect("FTP SERVER") or die("Could not connect");
ftp_login($conn,"USERNAME", "PASS");
$ftp_directory = TheDirectoryIwantToPutTheFile . $form_state['values']['allowed_user'];
$uri_parts = explode("/",$file->uri);
$filename = $uri_parts[sizeof($uri_parts)-1];
$target = $ftp_directory . "/" . $filename;
//drupal_set_message(t($target . " " . $file->uri));
$ret = ftp_nb_fput($conn,$target,$source,FTP_ASCII);
while ($ret == FTP_MOREDATA)
{
// Do whatever you want
//echo ".";
// Continue upload...
$ret = ftp_nb_continue($conn);
}
ftp_close($conn);
//$file->uri = file_unmanaged_copy($file->uri, $directory, FILE_EXISTS_REPLACE);
$file->uid = $form_state['values']['allowed_user'];
drupal_chmod($file->uri);
file_save($file);
// Need to add an entry in the file_usage table.
file_usage_add($file, 'assets', 'image', 1);
drupal_set_message(t("Your file has been uploaded!"));
}
}
}
I solved the problem. The problem was mainly because I gave the wrong path as the target. it had to be /public_html/...... instead of /home/our_name/public_html
How to create select list, radio buttons, checkboxes with field_create_field() and how to specify the options to be given in these fields
Run this code with the details for an existing field with the properties that you want to copy:
$entity_type = 'node';
$field_name = 'body';
$bundle_name = 'article';
$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">". $output .'</textarea>');
That will produce the PHP code used to create the field/field instance. Then you just need to go through the code and make the changes for your new field/instance.
After that someone registers in a site, a mail is usually sent to his mail account. But to generate this link or what info can be placed in this link so that it can be used to activate the user account??
you can place any thing which can identify a valid user
1- A Hash Value
2- An Encrypted String
3- A Guid
and when user clicks on the link , you can validate the value.
Check this part of code:
Generate code and e-mail:
/* if $acces = 0 everything is perfect so the system send a confirmation mail */
if($acces == 0)
{
print("<br>A mail has been send to " . $mail . "<br><br>") ;
/* prepare the vars */
$activ = $user . $pass ;
$code = md5($activ) ;
/* to how send to mail */
$to = $mail ;
/* prepare the subject */
$subject = "You need to confirm you registration to " . $_SERVER['HTTP_HOST'] ;
/* start writing the message */
$message = "Hello " . $user . ",\r\n\r\n" ;
$message .= "Thank you for registering at " . $_SERVER['HTTP_HOST'] . " Your account is created and must be activated before you can use it.\r\n" ;
$message .= "To activate the account click on the following link or copy-paste it in your browser :\r\n\r\n" ;
$message .= "http://" . $_SERVER['HTTP_HOST'] . "/~carron/registration/register_send.php?user=" . $user . "&activation=" . $code . "\r\n\r\n" ;
$message .= "After activation you may login to http://" . $_SERVER['HTTP_HOST'] . " using the following username and password:\r\n\r\n" ;
$message .= "Username - " . $user . "\r\nPassword - " . $pass . "\r\n" ;
/* To send HTML mail, you can set the Content-type header. */
$headers = "MIME-Version: 1.0";
$headers .= "Content-type: text/html; charset=iso-8859-1";
/* set up additional headers */
$headers .= "To: " . $to . "<br>\n" ;
$headers .= "From: " . $from . $addmail ;
/* writing data in the base */
$query = "INSERT INTO registration (user, pass, activ, mail) VALUES ('$user', '$pass', '$code', '$mail') ;" ;
$result = mysql_query($query, $db);
if ($result == false)
die("Failed " . $query);
else
{
/* everything went well so we can mail it now */
mail($to, $subject, $message, $headers);
}
}
Check activation:
/* controle if the validation link is right */
$x = 0 ;
$query = "SELECT user, pass, activ, mail FROM registration WHERE user = '" . $username . "';" ;
$result = mysql_query($query, $db);
if ($result == false) die("Failed " . $query);
while ($fields = mysql_fetch_row($result))
{
for ($i=0, $max=sizeof($fields) ; $i < $max ; $i++)
{
$tmp[$i] = $fields[$i] ;
}
/* the activation link is right so we can update
the datas in the data base */
if($activation == $tmp[2] AND $username == $tmp[0])
{
$x = 1 ;
$query2 = "UPDATE registration SET activated = '1' WHERE user = '" . $username . "' AND activ = '" . $activation . "' ;" ;
$result2 = mysql_query($query2, $db);
if ($result2 == false)
die("Failed " . $query2);
}
else
$x = -1 ;
}
/* give a confirmation message to the user */
if($x == 1)
print($username . " your activation has been done perfectly<br> Thank you...") ;
else
print($username . " your activation has not been done corectly<br> Please try again later...") ;
Script from PHPclasses.org
The idea is to have a link that only the recipient of the email knows. So when that link is visited on your site, you know that someone has read the email you sent and clicked on the link and so you can presume that the person who registered and the person who read the email are the same.
As such, you just need a link that can't be easily guessed. Pick something random (and record it in the user's profile) or hash the user name + a seed, or something.
When user registered, you can use uniqid() to create an activate code and stored in database. Then in mail, give a link like: http://....../activate.php?code=[uniqid()]
In activate.php, you can read activate code from database and check it.