define("SYSDEBUG",true);
define("APPPATH","/pathto/appdir/");
class m_ios_notification {
private $_connection = array();
private $_connection_i = array();
private static $int = null;
private static $timeout = 60;
private static $maxtips = 100;
private function __construct() {
}
function __destruct() {
foreach ($this->_connection as $conn){
if($conn){
fclose($conn);
}
}
}
static function i() {
if(self::$int === null){
self::$int = new m_ios_notification();
}
return self::$int;
return new m_ios_notification();
}
private function get_conn($bid,$feedback=false) {
$SYSDEBUG = SYSDEBUG;
$k = md5("{$bid}|{$feedback}");
if($this->_connection_i[$k]++ >= self::$maxtips){
$this->_connection_i[$k] = 0;
fclose($this->_connection[$k]);
$this->_connection[$k] = null;
}
if(!$this->_connection[$k]){
$pempath = !$SYSDEBUG ? $bid : "{$bid}_debug";
$pempath = APPPATH ."pem/" .$pempath . ".pem";
if(!is_file($pempath)){
return false;
}
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', $pempath);
if($feedback){
stream_context_set_option($ctx, 'ssl', 'verify_peer', false);
$url = !$SYSDEBUG ? 'ssl://feedback.push.apple.com:2196' : 'ssl://feedback.sandbox.push.apple.com:2196';
} else {
$url = !$SYSDEBUG ? 'ssl://gateway.push.apple.com:2195' : 'ssl://gateway.sandbox.push.apple.com:2195';
}
$this->_connection[$k] = stream_socket_client($url, $err, $errstr, self::$timeout, STREAM_CLIENT_CONNECT, $ctx);
if(!$this->_connection[$k]){
throw new Exception("Failed to connect |$err |$errstr |$url |$pempath");
}
}
return $this->_connection[$k];
}
function send_msg($token,$message,$bundleid) {
if(!$token || !$message || !$bundleid){
return -1;
}
$body = array();
$body['aps'] = array(
'alert' => $message,
'badge' => 1,
'sound' => 'b'
);
$body = json_encode($body);
$bodylen = strlen($body);
if($bodylen > 256){
return -2;
}
$msg = chr(0) . pack("n", 32) . pack('H*', $token) . pack("n", $bodylen) . $body;
try {
$conn = $this->get_conn($bundleid);
if(!$conn) {
return -3;
}
} catch (Exception $exc) {
return "-3 -> ".$exc->getMessage();
}
return fwrite($conn, $msg);
}
function get_feedback($bundleid) {
if(!$bundleid || !($conn = $this->get_conn($bundleid, true))){
return false;
}
$list = array();
while(($con = fread($conn,38))){
if(strlen($con)!=38){
continue;
}
$list[] = bin2hex(substr($con, 6,32));
}
return $list;
}
}