Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?
/*
This is part of the Reprise framework, not yet released publicly.
Copyright 2013 Marco Arment. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Marco Arment nor the names of Reprise contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL MARCO ARMENT OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Usage example:
ApplePushNotification::register_certificate('production.pem', 'passphrase1234');
ApplePushNotification::send_to_device($device_token, ['alert' => 'Hi!', 'sound' => 'default']);
*/
class ApplePushNotification
{
public static $development_sandbox_mode = false;
public static $max_apns_sent_per_connection = 1000;
public static $local_cert_filename = false;
public static $local_cert_password = false;
private static $connection = false;
private static $connection_error = false;
private static $apns_sent_with_this_connection = 0;
public static function register_certificate($cert_filename, $cert_password, $is_development = false)
{
self::$local_cert_filename = $cert_filename;
self::$local_cert_password = $cert_password;
self::$development_sandbox_mode = $is_development;
}
public static function flush()
{
if (self::$connection) {
fclose(self::$connection);
error_log("[ApplePushNotification] sent " . self::$apns_sent_with_this_connection . " APNs");
self::$connection = false;
self::$apns_sent_with_this_connection = 0;
return true;
}
return false;
}
public static function send_alert_to_device($device_token_hex, $alert_message, $sound = 'default')
{
self::send_to_device($device_token_hex, ['alert' => $alert_message, 'sound' => $sound]);
}
public static function send_to_device($device_token_hex, array $aps_dictionary)
{
$fp = self::connection();
if (! $fp) return false;
$device_token_hex = preg_replace('/[^a-z0-9]/msi', '', $device_token_hex);
if (strlen($device_token_hex) != 64) throw new Exception("Invalid device token [$device_token_hex]");
// Encode the payload as JSON
$payload = json_encode(['aps' => $aps_dictionary]);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $device_token_hex) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (! $result) {
error_log("[ApplePushNotification] APNS write failed");
self::flush();
self::$connection_error = true;
return false;
}
self::$apns_sent_with_this_connection++;
if (self::$apns_sent_with_this_connection >= self::$max_apns_sent_per_connection) self::flush();
return true;
}
private static function connection()
{
if (self::$connection || self::$connection_error) return self::$connection;
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', self::$local_cert_filename);
stream_context_set_option($ctx, 'ssl', 'passphrase', self::$local_cert_password);
// Open a connection to the APNS server
self::$connection = stream_socket_client(
'ssl://gateway.' . (self::$development_sandbox_mode ? 'sandbox.' : '') . 'push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx
);
if (! self::$connection) {
error_log("[ApplePushNotification] Cannot connect to APNS: $err $errstr");
self::$connection_error = true;
}
return self::$connection;
}
public static function query_feedback_service_for_invalid_device_tokens()
{
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', self::$local_cert_filename);
stream_context_set_option($ctx, 'ssl', 'passphrase', self::$local_cert_password);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://feedback.' . (self::$development_sandbox_mode ? 'sandbox.' : '') . 'push.apple.com:2196', $err,
$errstr, 60, STREAM_CLIENT_CONNECT, $ctx
);
$invalid_tokens = array();
while (! feof($fp)) {
$header = fread($fp, 6);
if (strlen($header) != 6) { echo "header too short, got " . strlen($header) . " bytes\n"; continue; }
$hfields = unpack('Ntime/nlen', $header);
$time = $hfields['time'];
$token_len = $hfields['len'];
$token = $token_len ? bin2hex(fread($fp, $token_len)) : '';
$invalid_tokens[$token] = $time;
}
fclose($fp);
return $invalid_tokens;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment