How get feedback from APNs when sending push notification - ios6

Now I can send push Token from device that has installed a pass already, but I don't know how the feedback work in this point. From apple docs, Apple Push Notification service (APNs) provides feedback to server to tell if pushToken is valid or not. How to get this feedback ? I try this code, but a lot errors. This is the code:
<?php
$cert = '/Applications/MAMP/htdocs/passesWebserver/certificates.pem';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $cert);
stream_context_set_option($ctx, 'ssl', 'verify_peer', false);
$fp = stream_socket_client('ssl://feedback.sandbox.push.apple.com:2196', $error, $errorString, 60, STREAM_CLIENT_CONNECT, $ctx);
// production server is ssl://feedback.push.apple.com:2196
if (!$fp) {
error_log("Failed to connect feedback server: $err $errstr",0);
return;
}
else {
error_log("Connection to feedback server OK",0);
}
error_log("APNS feedback results",0);
while ($devcon = fread($fp, 38))
{
$arr = unpack("H*", $devcon);
$rawhex = trim(implode("", $arr));
$feedbackTime = hexdec(substr($rawhex, 0, 8));
$feedbackDate = date('Y-m-d H:i', $feedbackTime);
$feedbackLen = hexdec(substr($rawhex, 8, 4));
$feedbackDeviceToken = substr($rawhex, 12, 64);
error_log ("TIMESTAMP:" . $feedbackDate, 0);
error_log ( "DEVICE ID:" . $feedbackDeviceToken,0);
}
fclose($fp);
?>

This should work. You don't need to run this with every push request. Depending on how frequently you update, and the number of devices, you could set a daily or weekly cron job.
$cert_file = '/path/to/combined/cert.pem';
$cert_pw = 'top secret';
$stream_context = stream_context_create();
stream_context_set_option($stream_context, 'ssl', 'local_cert', $cert_file);
if (strlen($cert_pw))
stream_context_set_option($stream_context, 'ssl', 'passphrase', $cert_pw);
$apns_connection = stream_socket_client('feedback.push.apple.com:2196', $error_code, $error_message, 60, STREAM_CLIENT_CONNECT, $stream_context);
if($apns_connection === false) {
apns_close_connection($apns_connection);
error_log ("APNS Feedback Request Error: $error_code - $error_message", 0);
}
$feedback_tokens = array();
while(!feof($apns_connection)) {
$data = fread($apns_connection, 38);
if(strlen($data)) {
$feedback_tokens[] = unpack("N1timestamp/n1length/H*devtoken", $data);
}
}
fclose($apns_connection);
if (count($feedback_tokens))
foreach ($feedback_tokens as $k => $token) {
// code to delete record from database
}

Related

Single Signon with Magento account from drupal

I have custom Magento script file as below which does login by just passing email and password to that PHP file.
It works fine when i'm making a call from browser.
But, I want to make this call through Drupal Module which i have created.
As i expected call is happening from Drupal module and i'm getting success message too. But login is not happening.
My hunch is that magento have some login restrictions which happening outside magento root folder.
Please find the source below.
Drupal directory - /www/drupal/
Magento directory - /www/drupal/store/
/www/drupal/store/api_config.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
require_once (dirname(dirname(realpath(__FILE__))).'/store/app/Mage.php');
umask(0);
Mage::app();
Mage::getSingleton('core/session', array('name' => 'frontend'));
$websiteId = Mage::app()->getWebsite()->getId();
$store = Mage::app()->getStore();
$response = array();
/www/drupal/store/api_login.php
<?php
require_once "api_config.php";
$session = Mage::getSingleton('customer/session');
//$session->start();
if (isset($_GET['email']) && !empty($_GET['email']) && isset($_GET['password']) && !empty($_GET['password'] )) {
if (!filter_var($_GET['email'], FILTER_VALIDATE_EMAIL) === false) {
$email = $_GET['email'];
$password = $_GET['password'];
try {
if ($session->login($email, $password )) {
$response['status'] = 'success';
$response['data'] = array($_GET);
$response['message'] = array('User loggedin Successfully.');
} else {
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array('User login failed.');
}
if ($session->getCustomer()->getIsJustConfirmed()) {
$this->_welcomeCustomer($session->getCustomer(), true);
}
} catch (Mage_Core_Exception $e) {
switch ($e->getCode()) {
case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
$value = Mage::helper('customer')->getEmailConfirmationUrl($email);
$message = Mage::helper('customer')->__('This account is not confirmed. Click here to resend confirmation email.', $value);
break;
case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
$message = $e->getMessage();
break;
default:
$message = $e->getMessage();
}
//$session->addError($message);
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array($message);
echo $message;
$session->setUsername($email);
} catch (Exception $e) {
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array($e);
// Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
}
} else {
//$session->addError('Login and password are required.');
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array('Invalid Email address');
}
} else {
//$session->addError('Login and password are required.');
$response['status'] = 'error';
$response['data'] = array($_GET);
$response['message'] = array('Login and password are required.');
}
print_r(json_encode($response, JSON_FORCE_OBJECT));die;
?>
/www/drupal/sites/all/modules/single_signon/single_signon.module
<?php
function single_signon_user_login(&$edit, $account) {
//store variable values
$postData = array();
$postData['email'] = $account->mail;
$postData['password'] = $edit['input']['pass'];
$inc = 1; //count of registration
if (!empty($postData['email']) && !empty($postData['password'])) {
// use of drupal_http_request
$data = http_build_query($postData, '', '&');
//$url = url('http://127.0.0.1/drupal/store/api_login.php?'.$data);
//$headers = array('Content-Type' => 'application/x-www-form-urlencoded');
//print_r($url);
// the actual sending of the data
$JSONresponse = drupal_http_request('http://127.0.0.1/drupal/store/api_login.php?email=john#example.com&password=password');
//print_r($JSONresponse);die;
$response = json_decode($JSONresponse->data, true);
if ($response['status']=='success') {
$inc+=1;
$message = 'Logged in successfully('.$inc.')';
drupal_set_message($message, $type = 'status', $repeat = FALSE); //message goes here
} else {
$message = 'Logged in failed. Due to '.$response['message'].'('.$inc.')';
drupal_set_message($message, $type = 'error ', $repeat = FALSE);
}
} else {
$message = 'Not able to log inside store('.$inc.')';
drupal_set_message($message, $type = 'status', $repeat = FALSE); //message goes here
}
}
?>
Any suggestions for findings to solve this mystery would be really helpful.
I'm not sure to understand it well : You have a php script using data send in the URL (GET) to connect a user in a session. And you would like the Drupal server to use it to connect directly to your Magento.
I think your code is working, but unfortunately it could not help the user to connect to Magento.
As this is the Drupal server asking for the connection, it would be the Drupal server session that will be connected and not the navigation user one.
If the user have to be connected, in his navigator, to the Magento server, it has to be the navigator witch must call the Magento script directly.
It could be done in an iframe or via Ajax I think.
I think you can also find some other solutions, as OAuth, but it will need a lot more of coding.
EDIT
I found some interesting subject about your problem :
Getting logged in user ID from Magento in external script - multiple session issue?
Magento Session from external page (same domain)
Magento external login will not create session cookie
I think you have to manually create the Magento session cookie on the user navigator, from the Drupal script.
You'll need to send back to Drupal the SessionID from Magento, using this method (I think, you'll have to verify) :
$response['sessionId'] = $session->getEncryptedSessionId();
And inside the Drupal script, you'll have to record a new cookie with the Magento session information. Maybe you have to have a look at a working Magento cookie to see how it is defined and what is its name.
if ($response['status']=='success') {
...
setcookie('frontend', $response['sessionId'], time() + 3600 * 24 * 180, '/');
...
}
You'll probably have to declare, in the settings of Magento, the path for cookies at '/'.
Can you give an example of the structure of the session cookie from Magento ?

AngularJS filtering json data

I have a column in mysql database called "month" and the values are 1 for January, 2 for February and so on.
In my AngularJS app, I use a get request to pull the json array from my php file. Is there a way to filter "data" so I can request only posts that contain the column month which would allow me to do an if statement, for instance if (month == 1){ filter only data which contain month value of 1}
Here is my code so far:
app.controller('TimeController', function($scope, $filter, $http) {
$http.post('ajax/getQuotes.php').success(function(data){
$scope.monthNumber = $filter('date')(new Date(), 'M');
if ($scope.monthNumber == 1){
}
$scope.quote = data;
angular.element(document.getElementById('log')).html( $scope.monthNumber);
});
This is my PHP code:
<?php
include('../includes/config.php');
try {
//Connect to the database, store the connection as a PDO object into $db.
$db = new PDO("mysql:dbname=".$DB_NAME.";host=".$DB_HOST.";charset=utf8", $DB_USER, $DB_PASS );
//PDO will throw PDOExceptions on errors, this means you don't need to explicitely check for errors.
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//PDO will not emulate prepared statements. This solves some edge cases, and relives work from the PDO object.
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
//Prepare the statement.
$statement = $db->prepare("SELECT * FROM quotes");
//Execute the query
$statement->execute();
//Fetch all of the results.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
//$result now contains the entire resultset from the query.
//create a temp array
$arr = array();
//loop through mysql tables
if ($statement->execute()) {
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$arr[] = $row;
}
}
array_unshift($arr, null);
echo json_encode($arr);
/*** close the database connection ***/
$db = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
Is it possible to do a for each loop and push json data?
$.each { if $scope.quote.month == 1){ items.push ; } }

phplist email not sending webmaster#fall-pac.com : Called Mail() without being connected

I am getting this error (phplist email not sending webmaster#fall-pac.com : Called Mail() without being connected) since upgrading my phplist nothing else has change I have sent a test email from the actual smtp mail box and it works so I know it not the email address I think it must be somthing in my config.php file but cants seem to find what could be causing the issue any help would be great please see my config.php i Have put on pastbin as its to big put here http://pastebin.com/CjRKdu5H
<?php
require("PHPMailer/class.phpmailer.php");
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
//if $mail->SMTPSecure = 'tls';
// use $mail->Port = 465;
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = 'username';
$mail->Password = 'password';
$mail->SetFrom('xyz#some.com', 'Testing');
$mail->Subject = 'Yii Test';
$mail->Body = "hello";
$mail->AddAddress('xyz#some.com');
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo;
return false;
} else {
echo $error = 'Message sent!';
return true;
}
?>

Google API - using the Service Directory

I have an APP in the Google API console. It has the Admin SDK enabled, and also the Marketplace SDK. I have registered it as a service account, and I have the key file, etc. When I try to get users from a certain domain, It always shows me one message - "Error calling GET https://www.googleapis.com/admin/directory/v1/users?domain=mydomain.com: (403) Not Authorized to access this resource/api". The code I have is this:
$client = new Google_Client();
$client->setApplicationName("Client_User_Feed");
$key = file_get_contents('/path/to/key/key-file-privatekey.p12');
$cred = new Google_Auth_AssertionCredentials(
'{code}#developer.gserviceaccount.com',
array('https://www.googleapis.com/auth/admin.directory.user'),
$key
);
$client->setAssertionCredentials($cred);
$service = new Google_Service_Directory($client);
$users = $service->users->listUsers(array('domain' => 'mydomain.com'));
How can I solve this issue?
You need to impersonate an admin user with something like:
$adminUser = 'admin#domain.com';
$cred->sub = $adminUser;
Example code fetching userID:
$client_id = '{code}.apps.googleusercontent.com'; //Client ID from Developers Console
$service_account_name = '{code}#developer.gserviceaccount.com'; //Email Address from Developers Console
$key_file_location = '{path}{file}.p12'; //Path to the P12 key downloaded from Developers Console
$impersonateUser = 'standarduser#domain.com'; //The user's account we are fetching information from
try {
$client = new Google_Client(); //Instantiate the Google Client
$client->setApplicationName("ApplicationName");
$adminService = new Google_Service_Directory($client);
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials( //Instantiate the Auth class
$service_account_name,
array('https://www.googleapis.com/auth/admin.directory.user'), //Set the scope
$key
);
$adminUser = 'admin#domain.com';
$cred->sub = $adminUser; //The sub function of Auth lets us impersonate a user so that our service account ($client_id) can act on the user's behalf
$client->setAssertionCredentials($cred);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($cred);
}
$getUser = getUserId($adminService, $impersonateUser);
$impersonateUser = $getUser['primaryEmail'];
if (isset($impersonateUser) && !empty($impersonateUser)) {
$_SESSION['gmailUserID'] = $impersonateUser;
}
//echo $_SESSION['gmailUserID'] . "<br />";
} catch (Exception $e) {
LogErr($e);
}
function getUserId($adminService, $impersonateUser) {
try {
$userId = $adminService->users->get($impersonateUser);
return $userId;
} catch (Exception $e) {
LogErr($e);
}
}

Receiving email takes upto 3 hours

This is my code I am facing problem in receiving mail it take up to 3 hours. Please help me.
function sendMail($to, $subject, $template, $from,$params,$attachmentFile=array(),$layout='default') {
foreach($params as $key=>$val) {
$this->set("".$key."",$val);
}
$this->Email->sendAs = 'html';
if (is_array($to))
$this->Email->to = $to;
else
$this->Email->to = "<".$to.">";
//$this->Email->to;
$this->Email->subject = $subject;
$this->Email->layout = $layout;
$this->Email->replyTo = "test#gmail.com";
$this->Email->from = "test#gmail.com";
$this->Email->attachments = $attachmentFile;
$this->Email->template = $template; // note no '.ctp'
//echo "<pre>";print_r($this->Email);
//die();
if(!$this->Email->send()) {
return 0;
}
else {
return 1;
}
}
Email is not instant. Sometimes a normal email will take quite a while. I would check what server (be it an SMTP server or plain old sendmail) you are using though and try to send mail through that normally to see how long it takes to make sure that it's not a cakephp configuration issue.

Resources