Beispiel #1
3
function send_push($device)
{
    $deviceToken = unpack('H*', base64_decode($device["deviceToken"]));
    $deviceToken = $deviceToken[1];
    date_default_timezone_set('Europe/London');
    $push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, '/home/jimbob/final_aps_prod.pem');
    $push->setProviderCertificatePassphrase('FunCrate321');
    $push->connect();
    $message = new ApnsPHP_Message($deviceToken);
    // Set a custom property
    $message->setCustomProperty('mdm', $device['pushMagic']);
    // Set the expiry value to 30 seconds
    $message->setExpiry(30);
    $push->add($message);
    var_dump($message->getPayload());
    // Send all messages in the message queue
    $push->send();
    // Disconnect from the Apple Push Notification Service
    $push->disconnect();
    // Examine the error message container
    $aErrorQueue = $push->getErrors();
    if (!empty($aErrorQueue)) {
        var_dump($aErrorQueue);
    }
}
Beispiel #2
1
Datei: Apns.php Projekt: sjlu/sns
 function send_message($key, $text, $badge = 0)
 {
     $socket = new ApnsPHP_Push($this->environment, $this->certificate_path);
     $socket->setRootCertificationAuthority($this->root_certificate_path);
     $socket->connect();
     $message = new ApnsPHP_Message($key);
     $message->setCustomIdentifier('notification');
     $message->setBadge($badge);
     $message->setText($text);
     $message->setSound();
     $message->setExpiry(30);
     $socket->add($message);
     try {
         $socket->send();
         $socket->disconnect();
     } catch (Exception $e) {
         return false;
     }
     $errors = $socket->getErrors();
     if (!empty($errors)) {
         return false;
     }
     return true;
 }
Beispiel #3
0
 /**
  * Adds a message to the message queue.
  *
  * @param  $message @type ApnsPHP_Message The message.
  */
 public function add(ApnsPHP_Message $message)
 {
     $sMessagePayload = $message->getPayload();
     $nRecipients = $message->getRecipientsNumber();
     $nMessageQueueLen = count($this->_aMessageQueue);
     for ($i = 0; $i < $nRecipients; $i++) {
         $nMessageID = $nMessageQueueLen + $i + 1;
         $this->_aMessageQueue[$nMessageID] = array('MESSAGE' => $message, 'BINARY_NOTIFICATION' => $this->_getBinaryNotification($message->getRecipient($i), $sMessagePayload, $nMessageID, $message->getExpiry()), 'ERRORS' => array());
     }
 }
Beispiel #4
0
 public static function pushIos($environment, $certFile, $devices, $message, $extra = array())
 {
     $extra = (object) $extra;
     $environment = $environment == self::ENVIRONMENT_PROD ? \ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION : \ApnsPHP_Abstract::ENVIRONMENT_SANDBOX;
     $push = new \ApnsPHP_Push($environment, $certFile);
     $push->setLogger(new VoidLogger());
     $push->setRootCertificationAuthority(dirname(__FILE__) . '/../../data/entrust_root_certification_authority.pem');
     $push->connect();
     $result = array();
     foreach ($devices as $device) {
         try {
             $m = new \ApnsPHP_Message($device);
             $m->setText($message);
             if (isset($extra->badge)) {
                 $m->setBadge($extra->badge);
             }
             if (isset($extra->sound)) {
                 $m->setSound($extra->sound);
             }
             $push->add($m);
         } catch (\Exception $e) {
             self::logError("iOS", $device, $e->getMessage(), $certFile, $environment == \ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION);
             $result[$device] = false;
         }
     }
     $push->send();
     $push->disconnect();
     $errors = $push->getErrors();
     if (!empty($errors)) {
         foreach ($errors as $error) {
             $m = $error["MESSAGE"];
             foreach ($m->getRecipients() as $device) {
                 self::logError("iOS", $device, $error["ERRORS"][0]["statusMessage"], $certFile, $environment == \ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION);
                 $result[$device] = false;
             }
         }
     }
     foreach ($devices as $device) {
         if (!isset($result[$device])) {
             $result[$device] = true;
         }
     }
     return $result;
 }
Beispiel #5
0
 /**
  * Adds a device to the system, after sending a test notification to it
  * @param {array} $device
  * @param {string} $device.userId
  * @param {string} $device.deviceId
  * @param {string} [$device.formFactor]
  * @param {string} [$device.platform]
  * @param {string} [$device.version]
  * @param {string} [$device.sessionId]
  * @param {boolean} [$device.sandbox]
  * @param {string} [$device.passphrase]
  * @param {boolean} [$skipNotification=false] if true, skips sending notification
  * @return {Users_Device}
  */
 static function add($device, $skipNotification = false)
 {
     Q_Valid::requireFields(array('userId', 'deviceId'), $device, true);
     $userId = $device['userId'];
     $deviceId = $device['deviceId'];
     if (!$skipNotification) {
         $app = Q::app();
         $sandbox = Q::ifset($device, 'sandbox', null);
         if (!isset($sandbox)) {
             $sandbox = Q_Config::get($app, "cordova", "ios", "sandbox", false);
         }
         $env = $sandbox ? ApnsPHP_Abstract::ENVIRONMENT_SANDBOX : ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION;
         $s = $sandbox ? 'sandbox' : 'production';
         $cert = APP_LOCAL_DIR . DS . 'Users' . DS . 'certs' . DS . $app . DS . $s . DS . 'bundle.pem';
         $authority = USERS_PLUGIN_FILES_DIR . DS . 'Users' . DS . 'certs' . DS . 'EntrustRootCA.pem';
         $logger = new Users_ApnsPHP_Logger();
         $push = new ApnsPHP_Push($env, $cert);
         $push->setLogger($logger);
         $push->setRootCertificationAuthority($authority);
         if (isset($device['passphrase'])) {
             $push->setProviderCertificatePassphrase($device['passphrase']);
         }
         $push->connect();
         $message = new ApnsPHP_Message($deviceId);
         $message->setCustomIdentifier('Users_Device-adding');
         $message->setBadge(0);
         $message->setText(Q_Config::get($app, "cordova", "ios", "device", "text", "Notifications have been enabled"));
         $message->setCustomProperty('userId', $userId);
         $message->setExpiry(5);
         $push->add($message);
         $push->send();
         $push->disconnect();
         $errors = $push->getErrors();
         if (!empty($errors)) {
             $result = reset($errors);
             throw new Users_Exception_DeviceNotification($result['ERRORS'][0]);
         }
     }
     $sessionId = Q_Session::id();
     $user = Users::loggedInUser();
     $info = array_merge(Q_Request::userAgentInfo(), array('sessionId' => $sessionId, 'userId' => $user ? $user->id : null, 'deviceId' => null));
     $device2 = Q::take($device, $info);
     $d = new Users_Device($device2);
     $d->save(true);
     if ($sessionId) {
         $s = new Users_Session();
         $s->id = $sessionId;
         if (!$s->retrieve()) {
             $s->deviceId = $deviceId;
         }
     }
     $_SESSION['Users']['deviceId'] = $deviceId;
     $device2['Q/method'] = 'Users/device';
     Q_Utils::sendToNode($device2);
     return $d;
 }
Beispiel #6
0
 private static function sendToIOS($token, $message)
 {
     /*$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, 'com.appkode.yol');*/
     $push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, ROOT . '/app/config/apns-dev.pem');
     $disabledLogger = new DisabledLogger();
     $push->setProviderCertificatePassphrase('test123');
     $push->setLogger($disabledLogger);
     //        $push->setRootCertificationAuthority(ROOT . '/app/config/apns-dev.pem');
     $push->connect();
     $apnsMessage = new ApnsPHP_Message();
     $apnsMessage->setText($message);
     $apnsMessage->addRecipient($token);
     $push->add($apnsMessage);
     $push->send();
     $push->disconnect();
     $error = $push->getErrors();
     if (is_array($error) && count($error) > 0) {
         self::log('iOS error: ' . "\n" . json_encode($error));
     } else {
         self::log('Push is sent');
     }
 }
Beispiel #7
0
 /**
  * @see AM_Task_Worker_Abstract::_fire()
  * @throws AM_Task_Worker_Exception
  * @return void
  */
 protected function _fire()
 {
     $aTokens = (array) $this->getOption('tokens');
     $sMessage = $this->getOption('message');
     $iBadge = intval($this->getOption('badge'));
     // Instanciate a new ApnsPHP_Push object
     $oPushService = $this->getPushService();
     // Connect to the Apple Push Notification Service
     $oPushService->connect();
     foreach ($aTokens as $sToken) {
         // Instantiate a new Message with a single recipient
         $oPushMessage = new ApnsPHP_Message($sToken);
         $oPushMessage->setText($sMessage);
         $oPushMessage->setBadge($iBadge);
         // Set a custom identifier. To get back this identifier use the getCustomIdentifier() method
         // over a ApnsPHP_Message object retrieved with the getErrors() message.
         $oPushMessage->setCustomIdentifier(sprintf('%s', $sToken));
         // Add the message to the message queue
         $oPushService->add($oPushMessage);
     }
     // Send all messages in the message queue
     $oPushService->send();
     // Disconnect from the Apple Push Notification Service
     $oPushService->disconnect();
     // Examine the error message container
     $aErrorQueue = $oPushService->getErrors();
     if (!empty($aErrorQueue)) {
         $aErrors = array();
         foreach ($aErrorQueue as $aError) {
             /* @var $oMessage ApnsPHP_Message */
             $oMessage = $aError['MESSAGE'];
             //Get last error message
             $aMessageError = array_pop($aError['ERRORS']);
             $aErrors[$oMessage->getCustomIdentifier()] = $aMessageError;
         }
         $this->addOption('errors', $aErrors);
         throw new AM_Task_Worker_Exception('Messages have an unrecoverable errors');
     }
 }
 /**
  * Send the given notification with Apple Push Notification Service Server.
  *
  * @param Notification $notification the notification to send
  * @return boolean true on success, false if there was an error.
  */
 public function send($notification)
 {
     $config = Config::getInstance();
     $appRoot = $config->getString('appRootDir');
     // Instanciate a new ApnsPHP_Push object, with the provider certificate
     $push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, $appRoot . $config->getString('monitoring/notification/push/providerCertificateDir'));
     // Set custom logger
     $push->setLogger(new ApnsPHP_Log_Fruition());
     // Set the Provider Certificate passphrase
     $push->setProviderCertificatePassphrase($config->getString('monitoring/notification/push/passphrase'));
     // Set the Root Certificate Autority to verify the Apple remote peer
     $push->setRootCertificationAuthority($appRoot . $config->getString('monitoring/notification/push/rootCertificateAuthorityDir'));
     // Get recipient list. If no registration id (user did not connect to the
     // mobile app, we stop the process
     $stringRecipients = $notification->getRecipient();
     if (empty($stringRecipients)) {
         Logger::info("No registration id was found. The notification is not sent.");
         return false;
     }
     // Connect to the Apple Push Notification Service
     $push->connect();
     // Create a message for each device
     $message = new ApnsPHP_Message();
     $message->setText($notification->getContent());
     $message->setSound();
     $message->setExpiry(30);
     // 60 seconds
     $recipientList = explode(",", $notification->getRecipient());
     foreach ($recipientList as $registrationId) {
         $message->addRecipient($registrationId);
     }
     // Add the message to the message queue
     $push->add($message);
     // Send all messages in the message queue
     $push->send();
     // Disconnect from the Apple Push Notification Service
     $push->disconnect();
     // Examine the error message container.
     $aErrorQueue = $push->getErrors();
     if (!empty($aErrorQueue)) {
         foreach ($aErrorQueue as $error) {
             foreach ($error['ERRORS'] as $err) {
                 //For statusCode = 8, which is Invalid Token, we delete the token.
                 if ($err['statusCode'] == self::INVALID_TOKEN) {
                     if ($this->handlerErrorCallBack) {
                         $token = $error['MESSAGE']->getRecipient();
                         call_user_func($this->handlerErrorCallBack, $token);
                     }
                 }
                 Logger::error("Sending push notification failed. Error code: " . $err['statusCode'] . ". Message: " . $err['statusMessage']);
             }
         }
         return false;
     }
     //If success
     Logger::info("Notification sent with device token " . $notification->getRecipient());
     return true;
 }
Beispiel #9
0
 /**
  * 送信処理
  */
 public function push($tokens, $text, $pem, $options = array())
 {
     // pemファイルの有無
     if (!file_exists(ROOT . DS . APP_DIR . DS . $this->app_cert_path . $pem)) {
         $this->log(__LINE__ . '::' . __METHOD__ . '::' . ' non pem file. => ' . $pem, LOG_ERR);
         return false;
     }
     $push = new ApnsPHP_Push($this->env, ROOT . DS . APP_DIR . DS . $this->app_cert_path . $pem);
     $push->setRootCertificationAuthority(ROOT . DS . APP_DIR . DS . $this->entrust_cert_path);
     $push->connect();
     // 失敗したトークンの一時保存用
     $invalid_tokens = array();
     try {
         foreach ((array) $tokens as $key => $token) {
             try {
                 $message = new ApnsPHP_Message($token['Device']['token']);
                 $message->setText($text);
                 $message->setSound();
                 $message->setCustomIdentifier(isset($options['identifier']) ? $options['identifier'] : $this->identifier);
                 $message->setExpiry(isset($options['identifier']) ? $options['expiry'] : $this->expiry);
                 $push->add($message);
                 $this->log(__LINE__ . '::' . __METHOD__ . '::' . ' Send Token [' . $token['Device']['token'] . ']', LOG_DEBUG);
             } catch (Exception $e) {
                 $this->log(__LINE__ . '::' . __METHOD__ . '::' . ' iOS Notification Error [' . $token['Device']['token'] . ']', LOG_ERR);
                 array_push($invalid_tokens, $token['Device']['token']);
             }
             $push->send();
         }
     } catch (Exception $e) {
         $this->log(__LINE__ . '::' . __METHOD__ . '::' . ' iOS Notification Error: ' . $e->getMessage(), LOG_ERR);
         array_push($invalid_tokens, $token['Device']['token']);
     }
     // 送信失敗していたら対象のトークンを一旦保持
     $aErrorQueue = $push->getErrors();
     $push->disconnect();
     if (!empty($aErrorQueue)) {
         foreach ($aErrorQueue as $info) {
             if (isset($info['ERRORS'])) {
                 foreach ($info['ERRORS'] as $error) {
                     if (isset($error['statusMessage']) && $error['statusMessage'] == 'Invalid token') {
                         $this->log(__LINE__ . '::' . __METHOD__ . '::' . $error['statusMessage'] . ' [' . $token['Device']['token'] . ']', LOG_ERR);
                         array_push($invalid_tokens, $token['Device']['token']);
                     }
                 }
             }
         }
     }
     // 失敗したトークンへは配信しないようにフラグを変更
     if (!empty($invalid_tokens)) {
         $this->allow_disible($invalid_tokens);
     }
     if (empty($aErrorQueue)) {
         return true;
     } else {
         $this->log(__LINE__ . '::' . __METHOD__ . '::' . ' iOS Notification Error: ' . $aErrorQueue, LOG_ERR);
         return false;
     }
 }
 function sendNotificationByApns($deviceToken, $msg, $type, $userId)
 {
     $push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, 'certificate/aps_dist_certi.pem');
     $push->setRootCertificationAuthority('certificate/aps_dist_certi.pem');
     $push->connect();
     $message = new ApnsPHP_Message($deviceToken);
     //        $message = new ApnsPHP_Message("407fa2549e4cb290c4f13059340a36e69679d9e1ba34b40751663819d98281ab");
     $message->setCustomProperty('type', $type);
     $message->setCustomProperty('userId', $userId);
     //        $message->setCustomProperty('channelName',$channelName);
     $message->setText($msg);
     $message->setBadge(1);
     $message->setSound();
     $push->add($message);
     $res = $push->send();
     $push->disconnect();
     //        return true;
     //            echo "sese";
     //            exit;
 }
Beispiel #11
0
function send_push_notification($token, $msg)
{
    // Instantiate a new Message with a single recipient
    $message = new ApnsPHP_Message($token);
    // Set a custom identifier. To get back this identifier use the getCustomIdentifier() method
    // over a ApnsPHP_Message object retrieved with the getErrors() message.
    //$message->setCustomIdentifier("Message-Badge-3");
    // Set badge icon to "3"
    $message->setBadge(1);
    // Set a simple welcome text
    $message->setText($msg);
    // Play the default sound
    $message->setSound();
    // Set a custom property
    //$message->setCustomProperty('acme2', array('bang', 'whiz'));
    // Set another custom property
    //$message->setCustomProperty('acme3', array('bing', 'bong'));
    // Set the expiry value to 30 seconds
    $message->setExpiry(30);
    return $message;
}
 * @author (C) 2010 Aldo Armiento (aldo.armiento@gmail.com)
 * @version $Id$
 */
echo 'd';
date_default_timezone_set('Asia/Tokyo');
error_reporting(-1);
//?
require_once 'ApnsPHP/Autoload.php';
$device_token = '2290c9ec028b078755909849a66d1ae2b83ea854eba2880f035395a2bc8c62de';
$url = 'http://kaicyo.local/Hackason/ResisterContents.php';
$text = 'didUpperSwipeAnyone';
$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, 'push_development.pem');
$push->setRootCertificationAuthority('entrust_root_certification_authority.pem');
$push->connect();
/* コンテンツの送信 */
$message = new ApnsPHP_Message($device_token);
$message->setCustomIdentifier("Message-Badge-3");
//?
$message->setBadge(3);
//?
$message->setText($text);
$message->setSound();
// default sound
// Set a custom property, meta data
$message->setCustomProperty('url', $url);
//$message->setCustomProperty('acme3', array('bing', 'bong'));
$message->setExpiry(30);
// Set the expiry value to 30 seconds
$push->add($message);
$push->send();
$push->disconnect();
Beispiel #13
0
 /**
  * @param array|string $tokens
  * @param $text
  * @param array $payloadData
  * @param array $args
  * @return \ApnsPHP_Message|null
  */
 public function sendMulti($tokens, $text, $payloadData = [], $args = [])
 {
     $tokens = is_array($tokens) ? $tokens : [$tokens];
     // check if its dry run or not
     if ($this->dryRun === true) {
         $this->log($tokens, $text, $payloadData, $args = []);
         return null;
     }
     $message = new \ApnsPHP_Message();
     foreach ($tokens as $token) {
         $message->addRecipient($token);
     }
     //$message->setText($text);
     foreach ($args as $method => $value) {
         if (strpos($message, 'set') === false) {
             $method = 'set' . ucfirst($method);
         }
         $value = is_array($value) ? $value : [$value];
         call_user_func_array([$message, $method], $value);
     }
     $message->setText($text);
     // set a custom payload data
     foreach ($payloadData as $key => $value) {
         $message->setCustomProperty($key, $value);
     }
     // Add the message to the message queue
     $this->add($message);
     // send a message
     $this->getClient()->send();
     $this->errors = $this->getClient()->getErrors();
     $this->success = empty($this->errors) ? true : false;
     return $message;
 }
    $gcpm = new GCMPushMessage($apiKey);
    $gcpm->setDevices($devices);
    $response = $gcpm->send($msg, array('title' => $title));
    $response = json_decode($response);
    if ($response->failure) {
        $payload = array('code' => 400, 'message' => $response->results[0]->error);
    } else {
        $payload = array('code' => 200, 'message' => 'Mensaje enviado con exito');
    }
} else {
    // Instanciate a new ApnsPHP_Push object
    $push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, 'cert/ck.pem');
    // $push->setRootCertificationAuthority('cert/entrust_root_certification_authority.pem');
    // $push->setProviderCertificatePassphrase('abcd1234!');
    $push->connect();
    $message = new ApnsPHP_Message($token_push);
    $message->setCustomIdentifier("Message-Badge-1");
    $message->setBadge(1);
    $message->setText($msg);
    $message->setSound();
    $push->add($message);
    $push->send();
    $push->disconnect();
    // Examine the error message container
    $aErrorQueue = $push->getErrors();
    if (!empty($aErrorQueue)) {
        $code = 400;
        /*$payload = [
          'code' => 400,
          'message' => $aErrorQueue
          ];*/
Beispiel #15
0
 error_log("push-prep - rows result3  row[" . $r . "] PEMFILENAME [ {$PEMFILENAME} ]");
 if (file_exists($PEMFILENAME) == false) {
     error_log("push-prep - rows result3  row[" . $r . "] PEMFILENAME [ {$PEMFILENAME} ] does not exist!!");
     continue;
 }
 // echo "PEMFILENAME $PEMFILENAME";
 // Instanciate a new ApnsPHP_Push object
 //					$push = new ApnsPHP_Push($APNS_ENVIRONMENT,'./pushnotes/server_cerificates_bundle_sandbox.pem');
 $push = new ApnsPHP_Push($APNS_ENVIRONMENT, $PEMFILENAME);
 // Set the Root Certificate Autority to verify the Apple remote peer
 $push->setRootCertificationAuthority('./pushnotes/entrust_root_certification_authority.pem');
 if ($msgpusht && $msgpusht != "" && $msgpusht != "null") {
     // Connect to the Apple Push Notification Service
     $push->connect();
     // Instantiate a new Message with a single recipient
     $message = new ApnsPHP_Message($msgpusht);
     // Set a custom identifier. To get back this identifier use the getCustomIdentifier() method
     // over a ApnsPHP_Message object retrieved with the getErrors() message.
     $message->setCustomIdentifier("Message-Badge-3");
     // Set badge icon to "3"
     $message->setBadge(1);
     // Set a simple welcome text
     $message->setText($notification);
     //$message->setText("test");
     // Play the default sound
     $message->setSound();
     // Set a custom property
     $message->setCustomProperty('msgid', $msgid);
     // Set another custom property
     $message->setCustomProperty('msgdesc', $msgdesc);
     // Set another custom property
Beispiel #16
0
$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, 'push_certs/sandbox.pem');
$logger = new ApnsPHP_Log_Null();
$push->setLogger($logger);
// Set the Provider Certificate passphrase
// $push->setProviderCertificatePassphrase('test');
// Set the Root Certificate Autority to verify the Apple remote peer
//$push->setRootCertificationAuthority('push_certs/entrust_root_sandbox.cer');
// Connect to the Apple Push Notification Service
$push->connect();
$notification_type = $argv[5];
$devices = $API->DB->query_return("SELECT push.*, accounts.push_notifications FROM push LEFT JOIN accounts ON push.account_id=accounts.id WHERE udid IN(" . implode(',', array_map(array($API->DB, 'sqlesc'), explode(',', $argv[6]))) . ")");
foreach ($devices as $d) {
    $push_notificaions = explode(',', $d['push_notifications']);
    if ($push_notificaions[0] != 'none' || !$push_notificaions[0] || in_array($notification_type, $push_notificaions)) {
        // Instantiate a new Message with a single recipient
        $message = new ApnsPHP_Message($d['token']);
        // Set a custom identifier. To get back this identifier use the getCustomIdentifier() method
        // over a ApnsPHP_Message object retrieved with the getErrors() message.
        $message->setCustomIdentifier(uniqid());
        // Set badge icon to "3"
        $newbadge = $d['badge'] + 1;
        $badges[$newbadge][] = $d['udid'];
        $message->setBadge($newbadge);
        // Set a simple welcome text
        if ($argv[1]) {
            $message->setText($argv[1]);
        }
        // Play the default sound
        $message->setSound();
        // Set a custom property
        if ($argv[3]) {
/*
 * Main server run loop
 */
while ($server->run()) {
    $date = date('Y-m-d H:i:s');
    // Check the error queue
    $aErrorQueue = $server->getErrors();
    if (!empty($aErrorQueue)) {
        var_dump($aErrorQueue);
    }
    // get latest queue
    list($deviceToken, $badgeNum, $text) = popQueue();
    // push message if it has correct values
    if ($deviceToken && $badgeNum && $text) {
        // Instantiate a new Message with a single recipient
        $message = new ApnsPHP_Message($deviceToken);
        $message->setBadge((int) $badgeNum);
        $message->setSound();
        $message->setText(urldecode($text));
        // Add the message to the message queue
        $server->add($message);
        _pushLog(array(date('Y-m-d H:i:s'), $deviceToken, $badgeNum));
        // continue to next loop for effectiveness
        continue;
    }
    usleep(500000);
}
/*
 * Pop from queue.
 * Currently using redis
 */
require_once 'ApnsPHP/Autoload.php';
// Instanciate a new ApnsPHP_Push object
$server = new ApnsPHP_Push_Server(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, 'server_cerificates_bundle_sandbox.pem');
// Set the Root Certificate Autority to verify the Apple remote peer
$server->setRootCertificationAuthority('entrust_root_certification_authority.pem');
// Set the number of concurrent processes
$server->setProcesses(2);
// Starts the server forking the new processes
$server->start();
// Main loop...
$i = 1;
while ($server->run()) {
    // Check the error queue
    $aErrorQueue = $server->getErrors();
    if (!empty($aErrorQueue)) {
        // Do somethings with this error messages...
        var_dump($aErrorQueue);
    }
    // Send 10 messages
    if ($i <= 10) {
        // Instantiate a new Message with a single recipient
        $message = new ApnsPHP_Message('1e82db91c7ceddd72bf33d74ae052ac9c84a065b35148ac401388843106a7485');
        // Set badge icon to "i"
        $message->setBadge($i);
        // Add the message to the message queue
        $server->add($message);
        $i++;
    }
    // Sleep a little...
    usleep(200000);
}
Beispiel #19
0
 /**
  * Get the payload dictionary.
  *
  * @return @type array The payload dictionary.
  */
 protected function _getPayload()
 {
     $aPayload = parent::_getPayload();
     $aPayload['aps']['alert'] = array();
     if (isset($this->_sText) && !isset($this->_sLocKey)) {
         $aPayload['aps']['alert']['body'] = (string) $this->_sText;
     }
     if (isset($this->_sActionLocKey)) {
         $aPayload['aps']['alert']['action-loc-key'] = $this->_sActionLocKey == '' ? null : (string) $this->_sActionLocKey;
     }
     if (isset($this->_sLocKey)) {
         $aPayload['aps']['alert']['loc-key'] = (string) $this->_sLocKey;
     }
     if (isset($this->_aLocArgs)) {
         $aPayload['aps']['alert']['loc-args'] = $this->_aLocArgs;
     }
     if (isset($this->_sLaunchImage)) {
         $aPayload['aps']['alert']['launch-image'] = (string) $this->_sLaunchImage;
     }
     return $aPayload;
 }
 protected function sendPushToDevice($cert, $deviceId, $message, $sn = '')
 {
     if (strlen($deviceId) < 64) {
         return;
     }
     $env = APPLICATION_ENV == 'development' ? ApnsPHP_Abstract::ENVIRONMENT_SANDBOX : ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION;
     $env = ApnsPHP_Abstract::ENVIRONMENT_SANDBOX;
     $push = new ApnsPHP_Push($env, $cert);
     $push->setLogger(new ApnsPHP_Log_Null());
     $push->setConnectTimeout(4000);
     $push->setRootCertificationAuthority(APPLICATION_PATH . '/data/entrust_root_certification_authority.pem');
     $push->connect();
     $apnsMessage = new ApnsPHP_Message($deviceId);
     $apnsMessage->setBadge(1);
     $apnsMessage->setText($message);
     $apnsMessage->setSound();
     $apnsMessage->setCustomProperty('sn', $sn);
     $push->add($apnsMessage);
     $push->send();
     //$push->disconnect();
     $aErrorQueue = $push->getErrors();
     if (!empty($aErrorQueue)) {
         var_dump($aErrorQueue);
     }
 }
 protected function raw_send($tokens, $title, $user_info)
 {
     // No devices, do nothing
     if (empty($tokens)) {
         return 0;
     }
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Abstract.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Exception.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Feedback.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Message.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Log/Interface.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Log/Embedded.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Message/Custom.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Message/Exception.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Push.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Push/Exception.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Push/Server.php';
     require_once dirname(__FILE__) . '/../../libs/ApnsPHP/Push/Server/Exception.php';
     require_once dirname(__FILE__) . '/../class-pnfw-apnsphp-logger.php';
     $certificate = get_attached_file(get_option("pnfw_production_ssl_certificate_media_id"));
     $passphrase = get_option("pnfw_production_ssl_certificate_password");
     $environment = ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION;
     if (get_option("pnfw_ios_use_sandbox")) {
         $certificate = get_attached_file(get_option("pnfw_sandbox_ssl_certificate_media_id"));
         $passphrase = get_option("pnfw_sandbox_ssl_certificate_password");
         $environment = ApnsPHP_Abstract::ENVIRONMENT_SANDBOX;
     }
     if (empty($certificate)) {
         pnfw_log(PNFW_IOS_LOG, __("iOS SSL certificate is not correctly set.", 'pnfw'));
         return 0;
     }
     if (empty($passphrase)) {
         pnfw_log(PNFW_IOS_LOG, __("iOS SSL certificate password is not correctly set.", 'pnfw'));
         return 0;
     }
     if (!file_exists($certificate)) {
         pnfw_log(PNFW_IOS_LOG, __("iOS SSL Certificate does not exists.", 'pnfw'));
         return 0;
     }
     $pnfw_ios_payload_sound = get_option('pnfw_ios_payload_sound', 'default');
     try {
         $push = new ApnsPHP_Push($environment, $certificate);
         $push->setLogger(new PNFW_ApnsPHP_Logger());
         $push->setProviderCertificatePassphrase($passphrase);
         foreach ($tokens as &$token) {
             try {
                 $this->notification_sent($token);
                 $message = new ApnsPHP_Message($token);
                 foreach (array_keys($user_info) as $key) {
                     $message->setCustomProperty($key, strval($user_info[$key]));
                 }
                 $message->setText($title);
                 $message->setSound($pnfw_ios_payload_sound);
                 $message->setBadge($this->get_badge_count($token));
                 $push->add($message);
             } catch (Exception $e) {
                 // The only exception here is the invalid token, so delete it
                 $this->delete_token($token);
             }
         }
         unset($token);
         $queued = count($push->getQueue(false));
         // Empty queue, do nothing
         if ($queued == 0) {
             return 0;
         }
         // Connect to the Apple Push Notification Service
         $push->connect();
         // Send all messages in the message queue
         $push->send();
         // Disconnect from the Apple Push Notification Service
         $push->disconnect();
         return $queued;
     } catch (Exception $e) {
         pnfw_log(PNFW_IOS_LOG, strip_tags($e->getMessage()));
         return 0;
     }
 }
// Using Autoload all classes are loaded on-demand
require_once 'ApnsPHP/Autoload.php';
// Instanciate a new ApnsPHP_Push object
$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, 'server_certificates_bundle_sandbox.pem');
// Set the Root Certificate Autority to verify the Apple remote peer
$push->setRootCertificationAuthority('entrust_root_certification_authority.pem');
// Increase write interval to 100ms (default value is 10ms).
// This is an example value, the 10ms default value is OK in most cases.
// To speed up the sending operations, use Zero as parameter but
// some messages may be lost.
// $push->setWriteInterval(100 * 1000);
// Connect to the Apple Push Notification Service
$push->connect();
for ($i = 1; $i <= 10; $i++) {
    // Instantiate a new Message with a single recipient
    $message = new ApnsPHP_Message($i == 5 ? INVALID_TOKEN : VALID_TOKEN);
    // Set a custom identifier. To get back this identifier use the getCustomIdentifier() method
    // over a ApnsPHP_Message object retrieved with the getErrors() message.
    $message->setCustomIdentifier(sprintf("Message-Badge-%03d", $i));
    // Set badge icon to "3"
    $message->setBadge($i);
    // Add the message to the message queue
    $push->add($message);
}
// Send all messages in the message queue
$push->send();
// Disconnect from the Apple Push Notification Service
$push->disconnect();
// Examine the error message container
$aErrorQueue = $push->getErrors();
if (!empty($aErrorQueue)) {
Beispiel #23
0
// include auto-loader
require __DIR__ . '/vendor/autoload.php';
// load configuration
require 'config.inc.php';
// create an instance of the pusher
$pusher = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, APS_CERT_PATH);
$pusher->connect();
// set up our database connection
$db = new PDO(DB_DSN, DB_USER, DB_PASSWORD);
// query for the tokens of all test devices
$devicesStmt = $db->query('select token from devices where is_test_device=1');
// loop through them
while ($deviceToken = $devicesStmt->fetchColumn()) {
    // create a new message
    $message = new ApnsPHP_Message($deviceToken);
    $message->setText('Test push notification');
    $message->setSound('silent.m4a');
    $message->setBadge(1);
    $message->setContentAvailable(true);
    // add it to the queue
    $pusher->add($message);
}
// send all the messages
$pusher->send();
// and disconnect
$pusher->disconnect();
// were there any errors?
$errors = $pusher->getErrors();
if (!empty($errors)) {
    echo "Push errors:\n";
Beispiel #24
0
function SendIOS($tokens, $text, $config)
{
    # Создаём экземпляр Push. Необходимо указывать параметр ENVIRONMENT_PRODUCTION или
    # ENVIRONMENT_SANDBOX в соответствии с сертификатом.
    $push = new ApnsPHP_Push($config['apn']['production'] ? 0 : 1, $config['apn']['production'] ? $config['apn']['sert_prod'] : $config['apn']['sert']);
    # Указываем пароль сертификата если он имеется
    if ($config['apn']['sertPass'] != '') {
        $push->setProviderCertificatePassphrase($config['apn']['sertPass']);
    }
    # Указываем корневой сертификат
    $push->setRootCertificationAuthority($config['apn']['RootCertificat']);
    # Создаём сообщение
    $message = new ApnsPHP_Message();
    # Перебираем массив токенов и добавляем получателей
    $listTokens = array();
    foreach ($tokens as $token) {
        $message->addRecipient($token);
        $listTokens[] = $token;
    }
    # Соединяемся с сервером
    $push->connect();
    # Устанавливаем параметры отправки сообщения
    $message->setSound();
    //$message->setBadge(0)
    $message->setText($text);
    # Устанавливаем сообщение для отправки
    $push->add($message);
    # Отправляем сообщение
    $push->send();
    # Отключаемся от сервера
    $push->disconnect();
    # Проверяем возникшие ошибки во время отправки
    $aErrorQueue = $push->getErrors();
    # Если имеются ошибки
    if (!empty($aErrorQueue)) {
        echo 'Ошибка отправки ios  -  ' . print_r($aErrorQueue, true);
        if (is_array($aErrorQueue)) {
            foreach ($aErrorQueue as $error) {
                if (isset($error['ERRORS']) && is_array($error['ERRORS'])) {
                    foreach ($error['ERRORS'] as $m) {
                        if (isset($m['statusMessage']) && $m['statusMessage'] == 'Invalid token') {
                            $arrayID = $m['identifier'] - 1;
                            if (isset($listTokens[$arrayID])) {
                                # Если найден недействительный токен, удатяем его из БД
                                //echo 'Удаление ошибочного токена';
                                DeleteToken($listTokens[$arrayID]);
                            }
                        }
                    }
                }
            }
        }
    }
}
Beispiel #25
0
 * @version $Id$
 */
// Adjust to your timezone
date_default_timezone_set('Europe/Rome');
// Report all PHP errors
error_reporting(-1);
// Using Autoload all classes are loaded on-demand
require_once 'ApnsPHP/Autoload.php';
// Instanciate a new ApnsPHP_Push object
$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, 'server_certificates_bundle_sandbox.pem');
// Set the Root Certificate Autority to verify the Apple remote peer
$push->setRootCertificationAuthority('entrust_root_certification_authority.pem');
// Connect to the Apple Push Notification Service
$push->connect();
// Instantiate a new Message with a single recipient
$message = new ApnsPHP_Message('1e82db91c7ceddd72bf33d74ae052ac9c84a065b35148ac401388843106a7485');
// Set a custom identifier. To get back this identifier use the getCustomIdentifier() method
// over a ApnsPHP_Message object retrieved with the getErrors() message.
$message->setCustomIdentifier("Message-Badge-3");
// Set badge icon to "3"
$message->setBadge(3);
// Set a simple welcome text
$message->setText('Hello APNs-enabled device!');
// Play the default sound
$message->setSound();
// Set a custom property
$message->setCustomProperty('acme2', array('bang', 'whiz'));
// Set another custom property
$message->setCustomProperty('acme3', array('bing', 'bong'));
// Set the expiry value to 30 seconds
$message->setExpiry(30);
Beispiel #26
0
 /**
  * @inheritdoc
  */
 public function sendPush()
 {
     $failedMessages = [];
     if (!isset($this->registrationTokens) || !count($this->registrationTokens)) {
         $failedMessages = $this->registrationTokens;
         return $this->returnResult($failedMessages, $this->registrationTokens);
     }
     // Instanciate a new ApnsPHP_Push object
     $push = new \ApnsPHP_Push($this->parameters['environment'], $this->certificate);
     // Set the Root Certificate Autority to verify the Apple remote peer
     $push->setRootCertificationAuthority($this->parameters['ca_cert']);
     $push->setLogger($this->logger);
     // Connect to the Apple Push Notification Service
     $push->connect();
     foreach ($this->registrationTokens as $index => $token) {
         try {
             $message = new \ApnsPHP_Message($token);
         } catch (\Exception $e) {
             $this->logger->log("ERROR: Device token " . $token . " has problem : " . $e->getMessage());
             $failedMessages[] = $token;
             continue;
         }
         $badge = $this->badges[$index];
         $category = $this->pushData->getApnsCategory();
         $expiry = $this->pushData->getApnsExpiry();
         $text = $this->pushData->getApnsText();
         $sound = $this->pushData->getApnsSound();
         $customProperties = $this->pushData->getApnsCustomProperties();
         $contentAvailable = $this->pushData->getContentAvailable();
         if (!$this->pushData->isSilent()) {
             // DEFAULT PUSH
             if (isset($badge)) {
                 $message->setBadge($badge);
             }
             if (isset($category)) {
                 $message->setCategory($category);
             }
             if (isset($expiry)) {
                 $message->setExpiry($expiry);
             }
             if (isset($text)) {
                 $message->setText($text);
             }
             if (isset($sound)) {
                 $message->setSound($sound);
             } else {
                 $message->setSound();
             }
             if ($contentAvailable) {
                 $message->setContentAvailable(true);
             }
         } else {
             // SILENT PUSH
             $message->setContentAvailable(true);
             // Set push information to custom payload
             if (isset($text)) {
                 $customProperties['alert'] = $text;
             }
             if (isset($category)) {
                 $customProperties['category'] = $category;
             }
         }
         if (isset($customProperties) && is_array($customProperties)) {
             foreach ($customProperties as $name => $value) {
                 $message->setCustomProperty($name, is_scalar($value) ? $value : json_encode($value));
             }
         }
         // Add the message to the message queue
         $push->add($message);
     }
     // Send all messages in the message queue
     try {
         $push->send();
         // Disconnect from the Apple Push Notification Service
         $push->disconnect();
         // Examine the error message container
         $aErrorQueue = $push->getErrors();
         if (!empty($aErrorQueue)) {
             foreach ($aErrorQueue as $error) {
                 // On récupère la liste des token qui ont généré une erreur
                 $var = $error['MESSAGE'];
                 $failedMessages = array_merge($failedMessages, $var->getRecipients());
             }
         }
         return $this->returnResult($failedMessages, $this->registrationTokens);
     } catch (\Exception $e) {
         return $this->returnResult($this->registrationTokens, $this->registrationTokens);
     }
 }
Beispiel #27
0
 function ios_push($device_array, $push_title, $message_id)
 {
     // ТаймЗона;
     date_default_timezone_set('Europe/Rome');
     // Подключаем внешнюю библеотеку для работы с Apple свервером;
     require_once $_SERVER['DOCUMENT_ROOT'] . '/systems/api/ApnsPHP/Autoload.php';
     // Создаем объект для сообщения и работы с сервером;
     $push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, $_SERVER['DOCUMENT_ROOT'] . '/systems/api/appDistr.pem');
     // Пароль разработчика;
     $push->setProviderCertificatePassphrase('fdu4v9f123');
     // Соединяемся с Яблочным сервером;
     $push->connect();
     foreach ($device_array as $token_temp) {
         // Преобразуем передаваемый IOS токен в человеческий вид;
         // Убираем <> краям;
         $token_temp = substr($token_temp, 1, -1);
         // Убираем пробелы;
         $token_temp_array = explode(' ', $token_temp);
         $token = '';
         for ($i = 0; $i <= count($token_temp_array); $i++) {
             $token = $token . $token_temp_array[$i];
         }
         // Создаем объект сообщения;
         $message = new ApnsPHP_Message($token);
         // Задаем какой-то неведомый параметр;
         $message->setCustomIdentifier("Message-Badge-1");
         // Тип значка?
         $message->setBadge(1);
         // "Я видел некоторое дерьмо" (с);
         $message->setText($push_title);
         // Звук уведомления?
         $message->setSound();
         // Передаем заголовок и ID сообщения;
         $service_message = explode('=', $push_title);
         if ($service_message[0] == 'service') {
             $message->setCustomProperty('service', $service_message[1]);
         } else {
             $message->setCustomProperty('title', $push_title);
             $message->setCustomProperty('message_id', $message_id);
         }
         // сервисное сообщение про обновление бейджей в меню
         //$message->setCustomProperty('service','refresh_badge');
         // Таймаут? Что блин за таймаут?
         $message->setExpiry(30);
         // Добавляем сообщение в сессию;
         $push->add($message);
     }
     // Отправляем сообщение;
     $push->send();
     // Отключаемся от Яблочного сервера;
     $push->disconnect();
 }
Beispiel #28
0
 /**
  * 发送消息到苹果设备
  * @param array $tokens 设备id
  * @param string $text 消息标题
  * @param array $customProperty 自定义属性
  * @param array $badget 消息在设备显示的红点中的数值
  * @param string $sound 声音
  * @throws \Exception
  * @return array 正常,返回空数组;异常,返回['tokens'=>'err msg']这种格式的错误数组
  */
 public function send($tokens = null, $msg_title = '你收到一个新消息', $msg_property = [], $badget = [], $sound = 'default')
 {
     try {
         $this->push->connect();
         $invaliduser = [];
         $err = [];
         foreach ($tokens as $token) {
             try {
                 $message = new \ApnsPHP_Message($token);
                 $message->setCustomIdentifier($token);
                 //设置消息的小图标(红点中显示的数目
                 $message->setBadge(isset($badget[$token]) ? intval($badget[$token]) : 1);
                 //设置消息显示的标题
                 $message->setText($msg_title);
                 // Play the default sound
                 $message->setSound($sound);
                 // Set a custom property
                 foreach ($msg_property as $key => $value) {
                     $message->setCustomProperty($key, $value);
                 }
                 $message->setExpiry(self::MSG_EXPIRY);
                 // Add the message to the message queue
                 $this->push->add($message);
             } catch (\ApnsPHP_Message_Exception $e) {
                 $invaliduser[] = $token;
                 $err[$token] = $e->getMessage();
             }
         }
         // Send all messages in the message queue
         $this->push->send();
         $this->push->disconnect();
     } catch (\ApnsPHP_Exception $e) {
         return Push::ret(Push::ERR_IOS_SEND_FAIL, $e->getMessage());
     }
     $aErrorQueue = $this->push->getErrors();
     if (!empty($aErrorQueue)) {
         foreach ($aErrorQueue as $err) {
             $invaliduser[] = $err['MESSAGE']->getCustomIdentifier();
             $err[$err['MESSAGE']->getCustomIdentifier()] = json_encode($err['ERRORS']);
         }
     }
     if (empty($err)) {
         return Push::ret(Push::ERR_OK, 'ok', []);
     } else {
         return Push::ret(Push::ERR_OK, json_encode($err), $invaliduser);
     }
 }
Beispiel #29
0
 */
// Adjust to your timezone
date_default_timezone_set('Europe/Rome');
// Report all PHP errors
error_reporting(-1);
// Using Autoload all classes are loaded on-demand
require_once 'ApnsPHP/Autoload.php';
// Instanciate a new ApnsPHP_Push object
$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, 'server_cerificates_bundle_sandbox.pem');
// Set the Root Certificate Autority to verify the Apple remote peer
$push->setRootCertificationAuthority('entrust_root_certification_authority.pem');
// Connect to the Apple Push Notification Service
$push->connect();
// Instantiate a new Message with a single recipient
//$message = new ApnsPHP_Message('1e82db91c7ceddd72bf33d74ae052ac9c84a065b35148ac401388843106a7485');
$message = new ApnsPHP_Message('5fd4e4af4aec6b1e61b3d3c1d1165151ac3bfa29ef362bfdb482b3acf7ecea6a');
// Set a custom identifier. To get back this identifier use the getCustomIdentifier() method
// over a ApnsPHP_Message object retrieved with the getErrors() message.
$message->setCustomIdentifier("Message-Badge-3");
// Set badge icon to "3"
$message->setBadge(3);
// Set a simple welcome text
$message->setText('COULD YOU COME DOWN FOR THE PROJECT MEETING?!');
// Play the default sound
$message->setSound();
// Set a custom property
$message->setCustomProperty('acme2', array('bang', 'whiz'));
// Set another custom property
$message->setCustomProperty('acme3', array('bing', 'bong'));
// Set the expiry value to 30 seconds
$message->setExpiry(30);
Beispiel #30
0
 /**
  * Get the payload dictionary.
  *
  * @return @type array The payload dictionary.
  */
 protected function _getPayload()
 {
     $aPayload = parent::_getPayload();
     $aAlert = array();
     if (isset($this->_sText) && !isset($this->_sLocKey)) {
         $aAlert['body'] = (string) $this->_sText;
     }
     if (isset($this->_sActionLocKey)) {
         $aAlert['action-loc-key'] = $this->_sActionLocKey == '' ? null : (string) $this->_sActionLocKey;
     }
     if (isset($this->_sLocKey)) {
         $aAlert['loc-key'] = (string) $this->_sLocKey;
     }
     if (isset($this->_aLocArgs)) {
         $aAlert['loc-args'] = $this->_aLocArgs;
     }
     if (isset($this->_sLaunchImage)) {
         $aAlert['launch-image'] = (string) $this->_sLaunchImage;
     }
     if (count($aAlert)) {
         $aPayload[parent::APPLE_RESERVED_NAMESPACE][self::APPLE_ALERT_PROPERTY] = $aAlert;
     }
     return $aPayload;
 }