Example #1
1
File: Apns.php Project: 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;
 }
 /**
  * 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;
 }
Example #3
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;
     }
 }
Example #4
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;
 }
Example #5
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;
 }
 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;
 }
Example #7
0
 * obtain it through the world-wide-web, please send an email
 * to aldo.armiento@gmail.com so we can send you a copy immediately.
 *
 * @author (C) 2010 Aldo Armiento (aldo.armiento@gmail.com)
 * @version $Id: sample_push.php 65 2010-12-13 18:38:39Z aldo.armiento $
 */
// 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
Example #8
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);
     }
 }
Example #9
0
 *
 * @author (C) 2010 Aldo Armiento (aldo.armiento@gmail.com)
 * @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';
// Instantiate a new ApnsPHP_Push object
$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, 'Vintelli.pem');
// Set the Provider Certificate passphrase
// $push->setProviderCertificatePassphrase('test');
// Set the Root Certificate Autority to verify the Apple remote peer
$push->setRootCertificationAuthority('Vintelli.pem');
// Connect to the Apple Push Notification Service
$push->connect();
// Instantiate a new Message with a single recipient
$message = new ApnsPHP_Message('e1fc74f98def8ae160e0e1d56d4abb7507a5d2d543962c5f0c0077217eee4ab3');
// 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'));
Example #10
0
 *
 * @author (C) 2010 Aldo Armiento (aldo.armiento@gmail.com)
 * @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';
// Instantiate a new ApnsPHP_Push object
$push = new ApnsPHP_Push(ApnsPHP_Abstract::ENVIRONMENT_SANDBOX, 'pushcert.pem');
// Set the Provider Certificate passphrase
// $push->setProviderCertificatePassphrase('test');
// Set the Root Certificate Autority to verify the Apple remote peer
$push->setRootCertificationAuthority('pushcert.pem');
// Connect to the Apple Push Notification Service
$push->connect();
// Instantiate a new Message with a single recipient
$message = new ApnsPHP_Message('a6ba3a0502ff42cf35bc72f78d4436fd4a0505fd775796c191a471885e623485');
// 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'));
 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);
     }
 }
Example #12
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]);
                            }
                        }
                    }
                }
            }
        }
    }
}
Example #13
0
 /**
  * push
  * @param mixed $registrations
  * @param mixed $data
  */
 public function push($registrations, $data)
 {
     $apns_environment = Config::get('push.apns.environment', 'sandbox');
     $apns_certificate_file = Config::get('push.apns.cert.file', false);
     $apns_certificate_pass = Config::get('push.apns.cert.pass', false);
     if (!$apns_certificate_file) {
         throw new \Exception("APNS config error: 'push.apns.cert.file' not set.");
     }
     $total_failure = 0;
     // Instantiate a new ApnsPHP_Push object
     $push = new \ApnsPHP_Push($apns_environment == 'sandbox' ? \ApnsPHP_Abstract::ENVIRONMENT_SANDBOX : \ApnsPHP_Abstract::ENVIRONMENT_PRODUCTION, $this->getCertificateFile($apns_certificate_file));
     // set custom logger
     $push->setLogger(new APNSLogger());
     // Set the Provider Certificate passphrase
     if ($apns_certificate_pass) {
         $push->setProviderCertificatePassphrase($apns_certificate_pass);
     }
     // Set the Root Certificate Autority to verify the Apple remote peer
     $push->setRootCertificationAuthority($this->getRootCertificationAuthority());
     // Connect to the Apple Push Notification Service
     $push->connect();
     $message = new \ApnsPHP_Message();
     // Add all registrations as message recipient
     foreach ($registrations as $registration) {
         try {
             $message->addRecipient($registration->device_id);
         } catch (\ApnsPHP_Message_Exception $e) {
             Logger::error($e->getMessage());
             $total_failure += 1;
         }
     }
     Logger::debug("Recipients => " . json_encode($message->getRecipients()));
     // Set a custom identifier. To get back this identifier use the getCustomIdentifier() method
     // over a ApnsPHP_Message object retrieved with the getErrors() message.
     if (isset($data['custom_identifier'])) {
         $message->setCustomIdentifier($data['custom_identifier']);
     }
     // Set badge icon to "3"
     if (isset($data['badge']) && is_int($data['badge'])) {
         $message->setBadge((int) $data['badge']);
     }
     // Set text
     $message->setText($data['message']);
     // Play the default sound
     if (!isset($data['sound']) || empty($data['sound'])) {
         $data['sound'] = 'default';
     }
     $message->setSound($data['sound']);
     // Set the expiry value to 30 seconds
     if (isset($data['expiry']) && $data['expiry'] > 0) {
         $message->setExpiry($data['expiry']);
     }
     // Set custom properties
     $invalid_properties = array('_id', 'app_id', 'created_at', 'updated_at', 'sound', 'text', 'badge', 'expiry', 'custom_identifier');
     $custom_properties = array_diff_key($data, array_flip($invalid_properties));
     foreach ($custom_properties as $property => $value) {
         $message->setCustomProperty($property, $value);
     }
     // Add the message to the message queue
     $push->add($message);
     // Send all messages in the message queue
     $stats = $push->send();
     // Disconnect from the Apple Push Notification Service
     $push->disconnect();
     // Examine the error message container
     $error_list = $push->getErrors();
     // Log delivery status
     $errors = $push->getErrors();
     $total_failure += count($errors);
     if ($total_failure > 0) {
         foreach ($errors as $error) {
             Logger::error($error);
         }
     }
     return array('success' => $registrations->count() - $total_failure, 'failure' => $total_failure);
 }