function send_to_ios($apnsHost, $apnsCertPath, $device_token, $data) { header('Content-Type: text/html; charset=UTF-8'); $deviceToken = $device_token; /* * $apnsHost * development : gateway.sandbox.push.apple.com * deployment : gateway.push.apple.com */ $apnsPort = 2195; $alert = ''; if (array_key_exists('ios_alert', $data)) { $alert = $data['ios_alert']; } $payload = array('aps' => array('alert' => $alert, 'badge' => 0, 'sound' => 'default')); if (array_key_exists('ios_custom', $data)) { $payload['ios_custom'] = $data['ios_custom']; } $payload = json_encode($payload); $streamContext = stream_context_create(); stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCertPath); $apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext); if ($apns) { $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $deviceToken)) . chr(0) . chr(strlen($payload)) . $payload; fwrite($apns, $apnsMessage); fclose($apns); return TRUE; } //middle.error.log MDI_Log::write('IOS_PUSH_ERROR-' . $this->input->ip_address() . '-' . $this->input->user_agent() . '-' . current_url()); return FALSE; }
/** * Send push notification */ function sendPushOnServer($device_token, $alert, $badge = null) { // Put private key's passphrase here: $passphrase = "123456"; $liveMode = TRUE; $url = $liveMode ? 'ssl://gateway.push.apple.com:2195' : 'ssl://gateway.sandbox.push.apple.com:2195'; // Put your alert message here: //$message = 'Driver accept your request He will come soon!'; $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'pem/STKPEM.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); // Open a connection to the APNS server $fp = stream_socket_client($url, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { echo "Failed to connect: {$err} {$errstr}" . PHP_EOL; die; } else { // Create the payload body $body['aps'] = array('badge' => $badge, 'alert' => (string) $alert, 'sound' => "default"); // Encode the payload as JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $device_token) . pack('n', strlen($payload)) . $payload; // echo $device_token;die; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); fclose($fp); } }
/** * * @param array $dataMessage coleccion de parametros() */ public function sendMessage(array $dataMessage, array $dataConfig) { $context = stream_context_create(); stream_context_set_option($context, 'ssl', 'local_cert', $dataConfig['iphone']['pem']); stream_context_set_option($context, 'ssl', 'passphrase', $dataConfig['iphone']['pass']); $socket = stream_socket_client($dataConfig['iphone']['sandbox'], $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $context); if (!$socket) { exit("Failed to connect: {$err} {$errstr}" . PHP_EOL); } else { } $message = $dataMessage['message']; $devices = $dataMessage['device']; $payload['aps'] = array('alert' => $message, 'key' => $dataMessage['idpromotion']); $payloadJSON = json_encode($payload); for ($i = 0, $size = count($devices); $i < $size; $i++) { $deviceToken = $devices[$i]; $payloadServer = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payloadJSON)) . $payloadJSON; $result = fwrite($socket, $payloadServer, strlen($payloadServer)); } // if (!$result) { // } else { // } fclose($socket); return; }
public function enviariOS($aMensajes) { $response = ['codigoerror' => 0, 'error' => '', 'data' => []]; try { $streamContext = stream_context_create(); stream_context_set_option($streamContext, 'ssl', 'local_cert', $this->certificate); if ($this->certificatepassword != '') { stream_context_set_option($streamContext, 'ssl', 'passphrase', $this->certificatepassword); } $fp = stream_socket_client($this->url, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $streamContext); if (!$fp) { $response['codigoerror'] = 1; $response['error'] = 'Error conectando a APNs: ' . $err; return Response::json($response); } //En este punto ya estamos conectados al APN, mandamos todos los mensajes foreach ($aMensajes as $mensaje) { $payload['aps'] = ['alert' => $mensaje['mensaje'], 'badge' => 0, 'sound' => 'default']; $jsonpayload = json_encode($payload); $msg = chr(0) . pack('n', 32) . pack('H*', $mensaje['token']) . pack('n', strlen($jsonpayload)) . $jsonpayload; $resultado = fwrite($fp, $msg, strlen($msg)); $response['data'][] = ['token' => $mensaje['token'], 'resultado' => $resultado]; } return Response::json($response); } catch (Exception $e) { $response['codigoerror'] = 2; $response['error'] = 'Error conectando a APNs: ' . $e->getMessage(); return Response::json($response); } }
public function sendIosPush($registatoin_ids, $message, array $extra) { set_time_limit(0); header('content-type: text/html; charset: utf-8'); $passphrase = 'password'; $deviceIds = $registatoin_ids; //$message=json_encode($message); //$payload = '{"aps":{"alert":"Hello","sound":"default","extra":"'.json_encode($message).'"}}'; $body['aps'] = array('alert' => $message, 'sound' => "default", 'extra' => json_encode($extra)); $payload = json_encode($body); //$payload=json_encode($message); $this->logger->write("INFO :", "inside ios payload" . $payload); //$result = 'Start' . '<br />'; $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); foreach ($deviceIds as $item) { //sleep(1); $fp = stream_socket_client($this->iosServer, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $item) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if ($fp) { fclose($fp); } } //set_time_limit(30); }
function sendMessage($latestWeibo) { $apnsCert = "ck.pem"; $pass = "******"; $serverUrl = "ssl://gateway.sandbox.push.apple.com:2195"; //之后正式版了,每个用户一个deviceToken要写数据库里 //并且通过这个id区分发给哪个用户 $deviceToken = "865cbcd86a020c346550d2a543f9c2db8877f27023260024f0d9f1bb82802c77"; $badge = 1; $sound = "default"; //中文乱码,要转一下字符集...... $message = iconv("GBK", "UTF-8", "【") . $latestWeibo->user->screen_name . iconv("GBK", "UTF-8", "】又发微博了: ") . $latestWeibo->text; echo "</br> message send: {$message} </br>"; $body = array("aps" => array("alert" => $message, "badge" => $badge, "sound" => $sound)); $streamContext = stream_context_create(); stream_context_set_option($streamContext, "ssl", "local_cert", $apnsCert); stream_context_set_option($streamContext, "ssl", "passphrase", $pass); $apns = stream_socket_client($serverUrl, $error, $errorString, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $streamContext); if (!$apns) { echo "failed : {$error}, {$errorString} </br>"; } $payload = json_encode($body); $msg = chr(0) . pack('n', 32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack('n', strlen($payload)) . $payload; $result = fwrite($apns, $msg); fclose($apns); if ($result) { echo "</br>sending successfully:</br> {$payload} </br>"; } else { echo "send failed </br>"; } }
/** * Send Push Notification * * @param $sToken * @param $message * @return int */ public function pushNotification($sToken, $message) { //check if have push certificate key $sDesUrl = PHPFOX_DIR . 'file' . PHPFOX_DS . 'accountapi' . PHPFOX_DS . 'certificate' . PHPFOX_DS . 'PushAppCerKey.pem'; if (file_exists($sDesUrl)) { $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', $sDesUrl); stream_context_set_option($ctx, 'ssl', 'passphrase', $this->_sPassPhrase); stream_context_set_option($ctx, 'ssl', 'cafile', PHPFOX_DIR . 'file' . PHPFOX_DS . 'accountapi' . PHPFOX_DS . 'cert' . PHPFOX_DS . 'entrust_2048_ca.cer'); // Open a connection to the APNS server $fp = stream_socket_client('ssl://' . $this->_sAPNSUrl, $err, $errstr, 30, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { echo 'Failed to connect:' . $err . ' ' . $errstr; return; } echo 'Connected to APNS' . PHP_EOL . $this->_sAPNSUrl; // Create the payload body $body['aps'] = $message; // Encode the payload as JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $sToken) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); // Close the connection to the server fclose($fp); return $result; } }
function send_message() { // Put your device token here (without spaces): $device_token = $this->get_device_token(); // Put your private key's passphrase here: $passphrase = $this->get_api_key(); // Put your alert message here: $msg_data = $this->get_message(); $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', $this->certificate); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); // Open a connection to the APNS server $fp = stream_socket_client($this->get_post_url(), $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { exit("Failed to connect: {$err} {$errstr}" . PHP_EOL); } // Create the payload body $body['aps'] = array('alert' => $msg_data['message'], 'badge' => 1, 'sound' => 'default'); $body['message'] = array('message_ID' => isset($msg_data['message_id']) ? $msg_data['message_id'] : '', 'message_title' => $msg_data['title'], 'message_type' => isset($msg_data['type']) ? $msg_data['type'] : '', 'message_shortDescription' => isset($msg_data['short_descr']) ? $msg_data['short_descr'] : '', 'message_date' => date('d/m/Y')); // "message":{"message_ID":"1012","message_title":"push message","message_type":"push","message_shortDescription":"sample message","message_date": "12/05/2014"}} // Encode the payload as JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $device_token) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); /* if (!$result) echo 'Message not delivered' . PHP_EOL; else echo 'Message successfully delivered' . PHP_EOL;*/ // Close the connection to the server fclose($fp); }
/** * Open the connection */ protected function connect($endpointType = Certificate::ENDPOINT_TYPE_GATEWAY) { $this->logger->debug('Connecting Apns\\SslSocket to the APNS ' . $endpointType . ' service with certificate "' . $this->getCertificate()->getDescription() . '"'); // Create the SSL context $streamContext = stream_context_create(); stream_context_set_option($streamContext, 'ssl', 'local_cert', $this->certificate->getPemFile()); if ($this->certificate->hasPassphrase()) { stream_context_set_option($streamContext, 'ssl', 'passphrase', $this->certificate->getPassphrase()); } // Verify peer if an Authority Certificate is available if (null !== $this->CACertificatePath) { stream_context_set_option($streamContext, 'ssl', 'verify_peer', true); stream_context_set_option($streamContext, 'ssl', 'cafile', $this->CACertificatePath); } // Open the connection $errorCode = $errorString = null; $this->connection = @stream_socket_client($this->certificate->getEndpoint($endpointType), $errorCode, $errorString, $this->connectTimeout, STREAM_CLIENT_CONNECT, $streamContext); // Check if the connection succeeded if (false == $this->connection) { $this->connection = null; // Set a somewhat more clear error message on error 0 if (0 == $errorCode) { $errorString = 'Error before connecting, please check your certificate and passphrase combo and the given CA certificate if any.'; } throw new \UnexpectedValueException('Failed to connect to ' . $this->certificate->getEndpoint($endpointType) . ' with error #' . $errorCode . ' "' . $errorString . '".'); } // Set stream in non-blocking mode and make writes unbuffered stream_set_blocking($this->connection, 0); stream_set_write_buffer($this->connection, 0); }
/** * For IOS APNS * $params["msg"] : Expected Message For APNS */ private function sendMessageIos($registration_id, $params) { $ssl_url = 'ssl://gateway.push.apple.com:2195'; //$ssl_url = 'ssl://gateway.sandbox.push.apple.com:2195; //For Test $payload = array(); $payload['aps'] = array('alert' => array("body" => $params["msg"], "action-loc-key" => "View"), 'badge' => 0, 'sound' => 'default'); ## notice : alert, badge, sound ## $payload['extra_info'] is different from what your app is programmed, this extra_info transfer to your IOS App $payload['extra_info'] = array('apns_msg' => $params["msg"]); $push = json_encode($payload); //Create stream context for Push Sever. $streamContext = stream_context_create(); stream_context_set_option($streamContext, 'ssl', 'local_cert', $this->iosCert); $apns = stream_socket_client($ssl_url, $error, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext); if (!$apns) { $rtn["code"] = "001"; $rtn["msg"] = "Failed to connect " . $error . " " . $errorString; return $rtn; } //echo 'error=' . $error; $t_registration_id = str_replace('%20', '', $registration_id); $t_registration_id = str_replace(' ', '', $t_registration_id); $apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $t_registration_id)) . chr(0) . chr(strlen($push)) . $push; $writeResult = fwrite($apns, $apnsMessage); fclose($apns); $rtn["code"] = "000"; //means result OK $rtn["msg"] = "OK"; return $rtn; }
public function SendUserOrderMessage($order, $message) { $user = $order->user->get(); $user_apn_token = UserApnToken::getInstanceByUserID($user->getID()); if (!isset($user_apn_token)) { return false; } $deviceToken = str_replace(' ', '', $user_apn_token->token->get()); $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', getcwd() . '/apple_apn/IlluminataDevCerAndKey.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', AppleAPNService::$passphrase); $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { throw new Exception("Failed to connect: {$err} {$errstr}" . PHP_EOL); } $body['aps'] = array('alert' => $message, 'title' => 'Order message', 'type' => strval(AppleAPNService::$MESSAGE_TYPE_USER_ORDER_MESSAGE), 'targetID' => $order->getID(), 'url' => 'http://www.illuminataeyewear.com', 'sound' => 'default'); $payload = json_encode($body); $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; $result = fwrite($fp, $msg, strlen($msg)); fclose($fp); if (!$result) { return false; } else { return true; } //throw new Exception('Message successfully delivered' . PHP_EOL); }
private function reloadUsingStream() { //$this->reloadUsingSocket(); //return; $transport = $this->scheme == 'http' ? 'tcp' : 'ssl'; $addr = $this->host; if ($transport == 'ssl') { $context = stream_context_create(); stream_context_set_option($context, 'ssl', 'verify_host', true); stream_context_set_option($context, 'ssl', 'allow_self_signed', true); $fp = @stream_socket_client("{$transport}://{$addr}:" . $this->port, $errno, $errstr, 15, STREAM_CLIENT_CONNECT, $context); } else { $fp = @stream_socket_client("{$transport}://{$addr}:" . $this->port, $errno, $errstr, 15, STREAM_CLIENT_CONNECT); } if ($fp === false) { return false; } $url = $this->uri; if (strpos($url, '?action=backup_guard_manualBackup') === FALSE) { $url .= '?action=backup_guard_manualBackup'; } $out = "GET " . $url . " HTTP/1.1\r\n"; $out .= "Host: " . $this->host . "\r\n"; $out .= "Connection: Close\r\n\r\n"; @fwrite($fp, $out); sleep(1); @fclose($fp); }
public function query($query = null) { $status = self::STATUS_NOTCONNECTED; $context = $this->_connection; $wrapper = $this->config('wrapper'); if ($context) { if (DevValue::isNotNull($query)) { if (DevArray::isAssoc($query)) { $this->_data = $query; } else { if (is_string($query)) { $data = urlencode($query); stream_context_set_option($context, $wrapper, 'content', $data); $this->_result = file_get_contents($target, false, $context); $this->status($this->_result !== false ? self::STATUS_SUCCESS : self::STATUS_FAILED); return true; } } } $data = HTTP::query($this->_data); stream_context_set_option($context, $wrapper, 'content', $data); $this->_result = file_get_contents($target, false, $context); if ($this->_result !== false) { $status = self::STATUS_SUCCESS; } } $this->status($status); }
/** * Sending Push Notification */ public function sendIosPush($registatoin_ids, $message) { set_time_limit(0); header('content-type: text/html; charset: utf-8'); $passphrase = 'password'; //$message = tr_to_utf($message); $deviceIds = array('68141f71cbae1c493318f17b132215223655c27a2670a580dee074c4cdf96028'); $payload = '{"aps":{"alert":"' . $message . '","sound":"default"}}'; $result = 'Start' . '<br />'; $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); foreach ($deviceIds as $item) { //sleep(1); $fp = stream_socket_client($this->iosServer, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $item) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if ($fp) { fclose($fp); } } //set_time_limit(30); }
public static function sendNotification($device_token, $message) { $passphrase = 'meboopush'; // echo dirname(__FILE__) . 'PushNotificationMeboo.pem'; die; $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', dirname(__FILE__) . '/PushMebooProduction.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); // Open a connection to the APNS server $fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { exit("Failed to connect: {$err} {$errstr}" . PHP_EOL); } // echo 'Connected to APNS' . PHP_EOL; // Create the payload body $body['aps'] = $message; // Encode the payload as JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $device_token) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if (!$result) { // echo 'Message not delivered' . PHP_EOL; } else { // echo 'Message successfully delivered' . PHP_EOL; } // Close the connection to the server fclose($fp); }
/** * Send proxy request * * @param peer.Socket $s Connection to proxy * @param peer.http.HttpRequest $request * @param peer.URL $url */ protected function proxy($s, $request, $url) { static $methods = ['tls://' => STREAM_CRYPTO_METHOD_TLS_CLIENT, 'sslv3://' => STREAM_CRYPTO_METHOD_SSLv3_CLIENT, 'sslv23://' => STREAM_CRYPTO_METHOD_SSLv23_CLIENT, 'sslv2://' => STREAM_CRYPTO_METHOD_SSLv2_CLIENT]; $connect = sprintf("CONNECT %1\$s:%2\$d HTTP/1.1\r\nHost: %1\$s:%2\$d\r\n\r\n", $url->getHost(), $url->getPort(443)); $this->cat && $this->cat->info('>>>', substr($connect, 0, strpos($connect, "\r"))); $s->write($connect); $handshake = $s->read(); if (4 === ($r = sscanf($handshake, "HTTP/%*d.%*d %d %[^\r]", $status, $message))) { while ($line = $s->readLine()) { $handshake .= $line . "\n"; } $this->cat && $this->cat->info('<<<', $handshake); if (200 === $status) { stream_context_set_option($s->getHandle(), 'ssl', 'peer_name', $url->getHost()); if (isset($methods[$this->socket->_prefix])) { $this->enable($s, [$this->socket->_prefix => $methods[$this->socket->_prefix]]); } else { $this->enable($s, $methods); } } else { throw new \io\IOException('Cannot connect through proxy: #' . $status . ' ' . $message); } } else { throw new \io\IOException('Proxy did not answer with valid HTTP: ' . $handshake); } }
function sendNotification($deviceToken, $message, $badges) { // Put your private key's passphrase here: $passphrase = 'stmwtxvp'; // Put your alert message here: $message = 'New tickets have been received!'; //////////////////////////////////////////////////////////////////////////////// $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'apns-dev.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); // Open a connection to the APNS server $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { exit("Failed to connect: {$err} {$errstr}" . PHP_EOL); } echo 'Connected to APNS' . PHP_EOL; // Create the payload body $body['aps'] = array('alert' => $message, 'sound' => 'default', 'badge' => 1); // Encode the payload as JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if (!$result) { echo 'SUCCESS' . PHP_EOL; } else { echo 'FAILED' . PHP_EOL; } // Close the connection to the server fclose($fp); }
function iosPush($token) { try { $deviceToken = $token; $message = 'You are not connected to personnel Tracker! Connect with tracker to continue the service.'; $body['aps'] = array('alert' => $message, 'badge' => 18); $body['category'] = 'message'; $passphrase = 'personneltracker'; $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'ckDistNew.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { exit("Failed to connect: {$err} {$errstr}" . PHP_EOL); } echo 'Connected to APNS' . PHP_EOL; $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if (!$result) { echo 'Message not delivered' . PHP_EOL; } else { echo 'Message successfully delivered' . PHP_EOL; } fclose($fp); } catch (Exception $e) { echo $e->getMessage(); } }
/** * Return a socket object */ function openSocket($proto, $conf) { $errLevel = error_reporting(); error_reporting(0); if ($proto != "ssl://" || $conf[$_SESSION["agent"]]["verifypeer"] != 1 || !function_exists("stream_socket_client")) { /* Not a SSL connection, or simple SSL connection without client certificate and server certificate check or stream_socket_client function not available (PHP 5 only), */ $sock = fsockopen($proto . $_SESSION["XMLRPC_agent"]["host"], $_SESSION["XMLRPC_agent"]["port"], $errNo, $errString); $ret = array($sock, $errNo, $errString); } else { $context = stream_context_create(); stream_context_set_option($context, "ssl", "allow_self_signed", False); stream_context_set_option($context, "ssl", "verify_peer", True); stream_context_set_option($context, "ssl", "cafile", $conf[$_SESSION["agent"]]["cacert"]); stream_context_set_option($context, "ssl", "local_cert", $conf[$_SESSION["agent"]]["localcert"]); $sock = stream_socket_client('tls://' . $_SESSION["XMLRPC_agent"]["host"] . ":" . $_SESSION["XMLRPC_agent"]["port"], $errNo, $errString, ini_get("default_socket_timeout"), STREAM_CLIENT_CONNECT, $context); $ret = array($sock, $errNo, $errString); } error_reporting($errLevel); if ($sock !== False) { /* Setting timeout on a SSL socket only works with PHP >= 5.2.1 */ stream_set_timeout($sock, $conf[$_SESSION["agent"]]["timeout"]); } return $ret; }
public function __construct(array $config = []) { $this->smsc_host = $config['SMSC_HOST']; $this->smsc_port = $config['SMSC_PORT']; $this->smsc_ssl_port = $config['SMSC_SSL_PORT']; $this->smsc_login = $config['SMSC_LOGIN']; $this->smsc_password = $config['SMSC_PASSWORD']; $this->smsc_charset = $config['SMSC_CHARSET']; $this->smsc_use_ssl = $config['SMSC_USE_SSL'] ?: false; $ip = gethostbyname($this->smsc_host); if ($ip == $this->smsc_host) { // dns fail $ip = "212.24.33.196"; } // fixed ip $protocol = $this->smsc_use_ssl ? 'ssl://' : ''; $port = $this->smsc_use_ssl ? $this->smsc_ssl_port : $this->smsc_port; if ($this->smsc_use_ssl) { $context = stream_context_create(); stream_context_set_option($context, 'ssl', 'verify_host', false); stream_context_set_option($context, 'ssl', 'verify_peer', false); stream_context_set_option($context, 'ssl', 'verify_peer_name', false); stream_context_set_option($context, 'ssl', 'allow_self_signed', true); } else { $context = null; } $this->socket = stream_socket_client($protocol . $ip . ":" . $port, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $context); if (!$this->socket) { die("Не могу соединиться: {$errstr} ({$errno})"); } if (!$this->bind()) { throw new \RuntimeException('Socket Error'); } }
/** * Class constructor, tries to establish connection * * @param string $address Address for stream_socket_client() call, * e.g. 'tcp://localhost:80' * @param int $timeout Connection timeout (seconds) * @param array $contextOptions Context options * * @throws HTTP_Request2_LogicException * @throws HTTP_Request2_ConnectionException */ public function __construct($address, $timeout, array $contextOptions = array()) { if (!empty($contextOptions) && !isset($contextOptions['socket']) && !isset($contextOptions['ssl'])) { // Backwards compatibility with 2.1.0 and 2.1.1 releases $contextOptions = array('ssl' => $contextOptions); } $context = stream_context_create(); foreach ($contextOptions as $wrapper => $options) { foreach ($options as $name => $value) { if (!stream_context_set_option($context, $wrapper, $name, $value)) { throw new HTTP_Request2_LogicException("Error setting '{$wrapper}' wrapper context option '{$name}'"); } } } set_error_handler(array($this, 'connectionWarningsHandler')); $this->socket = stream_socket_client($address, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context); restore_error_handler(); // if we fail to bind to a specified local address (see request #19515), // connection still succeeds, albeit with a warning. Throw an Exception // with the warning text in this case as that connection is unlikely // to be what user wants and as Curl throws an error in similar case. if ($this->connectionWarnings) { if ($this->socket) { fclose($this->socket); } $error = $errstr ? $errstr : implode("\n", $this->connectionWarnings); throw new HTTP_Request2_ConnectionException("Unable to connect to {$address}. Error: {$error}", 0, $errno); } }
private function getTWfp() { if (!$this->twfp) { LogUtil::error('iOS push init TW retry: ' . $this->initTWRetryTimes); $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', Yii::getAlias('@app') . '/modules/uhkklp/klpapns.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', 'abc123_'); $this->twfp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 30, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); if (!$this->twfp) { LogUtil::error('iOS push error: ' . $err . '. Info: ' . $errstr); fclose($this->twfp); if ($this->initTWRetryTimes < 5) { $this->initTWRetryTimes = $this->initTWRetryTimes + 1; $this->getTWfp(); } else { $this->initTWRetryTimes = 0; return $err; } } else { LogUtil::error('iOS push init TW success'); $this->initTWRetryTimes = 0; return 200; } } else { LogUtil::error('iOS push init TW get old fp'); return 200; } }
public function ConnectToFeedBack() { if (!$this->mFeedBacksHost || !$this->mCert) { return false; } $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', $this->mCert); stream_context_set_option($ctx, 'ssl', 'passphrase', $this->mpass); $this->mFeedBack = @stream_socket_client($this->mFeedBacksHost, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx); if (!$this->mFeedBack) { return 0; } else { $APNsFeedBack = array(); while ($devcon = fread($this->mFeedBack, 38)) { $arr = unpack("H*", $devcon); $rawhex = trim(implode("", $arr)); $feedbackTime = hexdec(substr($rawhex, 0, 8)); $feedbackLen = hexdec(substr($rawhex, 8, 4)); $feedbackDeviceToken = substr($rawhex, 12, 64); $arr_tmp['fb_time'] = $feedbackTime; $arr_tmp['fb_devi'] = $feedbackDeviceToken; $APNsFeedBack[] = $arr_tmp; } return $APNsFeedBack; } }
function sendMessageToDevice($deviceToken, $message) { // Put your private key's passphrase here: $passphrase = 'pushchat'; // Put your alert message here: //$message = "Welcome to LVL6 game"; //////////////////////////////////////////////////////////////////////////////// $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'apns-dev.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); // Open a connection to the APNS server $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { exit("Failed to connect: {$err} {$errstr}" . PHP_EOL); } // Create the payload body $body['aps'] = array('alert' => $message, 'sound' => 'default'); // Encode the payload as JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if (!$result) { echo 'Message not delivered' . PHP_EOL; } else { echo 'Message successfully delivered' . PHP_EOL; } // Close the connection to the server fclose($fp); }
public function initialize_apns() { try { $this->ctx = stream_context_create(); //stream_context_set_option($ctx, 'ssl', 'cafile', 'entrust_2048_ca.cer'); stream_context_set_option($this->ctx, 'ssl', 'local_cert', $this->getCertificatePath()); stream_context_set_option($this->ctx, 'ssl', 'passphrase', $this->passphrase); // use this if you are using a passphrase // Open a connection to the APNS servers if ($this->defa == 1) { $this->fp = stream_socket_client($this->ssl, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $this->ctx); } else { $this->fp = stream_socket_client($this->sandboxSsl, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $this->ctx); } if ($this->fp) { Log::info('Successfully connected to server of APNS'); //echo 'Successfully connected to server of APNS ckUberForXOwner.pem'; } else { Log::error("Error in connection while trying to connect to APNS"); //echo "Error in connection while trying to connect to APNS ckUberForXOwner.pem"; } } catch (Exception $e) { Log::error($e); } }
protected function sendToMobile($token, $message) { $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', './assets/addition/ck_Vschool_pro.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $this->passphrase); // Open a connection to the APNS server $fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { exit("Failed to connect: {$err} {$errstr}" . PHP_EOL); } $return = 'Connected to APNS' . PHP_EOL; // Create the payload body $body['aps'] = array('alert' => $message, 'sound' => 'default'); // Encode the payload as JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $token) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if (!$result) { $return .= 'Message not delivered' . PHP_EOL; } else { $return .= 'Message successfully delivered' . PHP_EOL; } // Close the connection to the server fclose($fp); return $return; }
private function connect($device_ids, $message) { if (is_string($device_ids)) { $device_ids = (array) $device_ids; } $streamContext = stream_context_create(); @stream_context_set_option($streamContext, 'ssl', 'local_cert', $this->config); $fp = @stream_socket_client($this->url_service, $err, $errstr, 60, STREAM_CLIENT_CONNECT, $streamContext); @stream_set_blocking($fp, 0); if (!$fp) { return false; } if ($device_ids[0] != "test") { $load = array('aps' => array('alert' => $message, 'badge' => 1, 'sound' => 'chime')); $payload = json_encode($load); $apnsMessage = null; foreach ($device_ids as $token) { @($apnsMessage = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $token)) . pack('n', strlen($payload)) . $payload); } fwrite($fp, $apnsMessage); usleep(500000); $ivalidToken = $this->pullMessage($fp); fclose($fp); return $ivalidToken; } return true; }
/** * Get Information about last usage of the Application * for every iPhone Device which is registered to the * Push Service. * * @return Array Feedback */ public function receive() { if ($this->_checkPrivateKey($this->_privateKey) === false) { throw new Exception('You need to set the path to the private key file.'); } # Initialize stream context $streamContext = stream_context_create(); # Load private key stream_context_set_option($streamContext, 'ssl', 'local_cert', $this->_privateKey); # Get private key passphrase if any if ($this->_privateKeyPassphrase !== '') { stream_context_set_option($streamContext, 'ssl', 'passphrase', $this->_privateKeyPassphrase); } # Connect to the Apple Push Notification Service $fp = stream_socket_client(APFeedback::$_ENVIROMENTS[$this->_enviroment], $errorNumber, $errorString, 60, STREAM_CLIENT_CONNECT, $streamContext); # Connection failed? if ($errorString) { throw new Exception('Can\'t connect to Apple Push Feedback Service: ' . $errorString); } while ($data = fread($fp, 38)) { $feedback[] = unpack("N1timestamp/n1length/H*devtoken", $data); } # Return Feedback return $feedback; # Close Connection fclose($fp); }
function sendNotificationIOS() { // Put your device token here (without spaces): $deviceToken = '87d4477b81a7f8f7ba80b3f5f043d83dec3c9b0940c708d24f803ef67600966f'; // Put your private key's passphrase here: $passphrase = 'pushchat'; // Put your alert message here: $message = 'My first push notification!'; //////////////////////////////////////////////////////////////////////////////// $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); // Open a connection to the APNS server $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { exit("Failed to connect: {$err} {$errstr}" . PHP_EOL); } echo 'Connected to APNS' . PHP_EOL; // Create the payload body $body['aps'] = array('alert' => $message, 'sound' => 'default'); // Encode the payload as JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if (!$result) { echo 'Message not delivered' . PHP_EOL; } else { echo 'Message successfully delivered' . PHP_EOL; } // Close the connection to the server fclose($fp); }
public function send($token, $message) { $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', $this->CertPath); stream_context_set_option($ctx, 'ssl', 'passphrase', $this->PassPhrase); $URIPush = $this->isProduction == true ? \KS\APN::URIDevelopment : \KS\APN::URIDevelopment; // Open a connection to the APNS server $fp = stream_socket_client($URIPush, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { fclose($fp); return false; } // Create the payload body $body['aps'] = array('alert' => $message, 'sound' => 'default'); // Encode the payload as JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $token) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if (!$result) { fclose($fp); return false; } // Close the connection to the server fclose($fp); return true; }