PageRenderTime 40ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/application/libraries/Gcm.php

https://gitlab.com/neera.pokhrel.c3/BackendNayapatrika
PHP | 308 lines | 187 code | 62 blank | 59 comment | 19 complexity | 58b9fe28ca5382f7c312ba73948ef914 MD5 | raw file
  1. <?php
  2. /**
  3. *
  4. * @package GCM (Google Cloud Messaging)
  5. * @copyright (c) 2012 AntonGorodezkiy
  6. * info: https://github.com/antongorodezkiy/codeigniter-gcm/
  7. * Description: PHP Codeigniter Google Cloud Messaging Library
  8. * License: BSD
  9. *
  10. * Copyright (c) 2012, AntonGorodezkiy
  11. * All rights reserved.
  12. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  13. * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  14. * 2. 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.
  15. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
  16. * 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 THE COPYRIGHT HOLDER 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.
  17. *
  18. */
  19. class Gcm {
  20. protected $apiKey = '';
  21. protected $apiSendAddress = '';
  22. protected $payload = array();
  23. protected $additionalData = array();
  24. protected $recepients = array();
  25. protected $message = '';
  26. public $status = array();
  27. public $messagesStatuses = array();
  28. public $responseData = null;
  29. public $responseInfo = null;
  30. protected $errorStatuses = array(
  31. 'Unavailable' => 'Maybe missed API key',
  32. 'MismatchSenderId' => 'Make sure you\'re using one of those when trying to send messages to the device. If you switch to a different sender, the existing registration IDs won\'t work.',
  33. 'MissingRegistration' => 'Check that the request contains a registration ID',
  34. 'InvalidRegistration' => 'Check the formatting of the registration ID that you pass to the server. Make sure it matches the registration ID the phone receives in the google',
  35. 'NotRegistered' => 'Not registered',
  36. 'MessageTooBig' => 'The total size of the payload data that is included in a message can\'t exceed 4096 bytes',
  37. 'InvalidPackageName' => 'Make sure the message was addressed to a registration token whose package name matches the value passed in the request.',
  38. 'InvalidDataKey' => 'Check that the payload data does not contain a key (such as from, or gcm, or any value prefixed by google) that is used internally by GCM.',
  39. 'InvalidTtl' => 'Check that the value used in time_to_live is an integer representing a duration in seconds between 0 and 2,419,200 (4 weeks).',
  40. 'InternalServerError' => 'The server encountered an error while trying to process the request.',
  41. 'TopicsMessageRateExceeded' => 'The rate of messages to subscribers to a particular topic is too high. Reduce the number of messages sent for this topic, and do not immediately retry sending.',
  42. 'DeviceMessageRateExceeded' => 'The rate of messages to a particular device is too high. Reduce the number of messages sent to this device and do not immediately retry sending to this device.'
  43. );
  44. /**
  45. * Constructor
  46. */
  47. public function __construct() {
  48. $ci =& get_instance();
  49. $ci->load->config('gcm',true);
  50. $this->apiKey = $ci->config->item('gcm_api_key','gcm');
  51. $this->apiSendAddress = $ci->config->item('gcm_api_send_address','gcm');
  52. if (!$this->apiKey) {
  53. show_error('GCM: Needed API Key');
  54. }
  55. if (!$this->apiSendAddress) {
  56. show_error('GCM: Needed API Send Address');
  57. }
  58. }
  59. /**
  60. * Sets additional data which will be send with main apn message
  61. *
  62. * @param <array> $data
  63. * @return <array>
  64. */
  65. public function setTtl($ttl = '')
  66. {
  67. if (!$ttl)
  68. unset($this->payload['time_to_live']);
  69. else
  70. $this->payload['time_to_live'] = $ttl;
  71. }
  72. /**
  73. * Setting GCM message
  74. *
  75. * @param <string> $message
  76. */
  77. public function setMessage($message = '') {
  78. $this->message = $message;
  79. $this->payload['data']['message'] = $message;
  80. }
  81. /**
  82. * Setting data to message
  83. *
  84. * @param <string> $data
  85. */
  86. public function setData($data = array()) {
  87. $this->payload['data'] = $data;
  88. if ($this->message)
  89. $this->payload['data']['message'] = $this->message;
  90. }
  91. /**
  92. * Setting group of messages
  93. *
  94. * @param <string> $group
  95. */
  96. public function setGroup($group = '') {
  97. if (!$group)
  98. unset($this->payload['collapse_key']);
  99. else
  100. $this->payload['collapse_key'] = $group;
  101. }
  102. /**
  103. * Adding one recepient
  104. *
  105. * @param <string> $group
  106. */
  107. public function addRecepient($registrationId) {
  108. $this->payload['registration_ids'][] = $registrationId;
  109. }
  110. /**
  111. * Setting all recepients
  112. *
  113. * @param <string> $group
  114. */
  115. public function setRecepients($registrationIds) {
  116. $this->payload['registration_ids'] = $registrationIds;
  117. }
  118. /**
  119. * Clearing group of messages
  120. */
  121. public function clearRecepients() {
  122. $this->payload['registration_ids'] = array();
  123. }
  124. /**
  125. * Senging messages to Google Cloud Messaging
  126. *
  127. * @param <string> $group
  128. */
  129. public function send()
  130. {
  131. $this->payload['registration_ids'] = array_unique($this->payload['registration_ids']);
  132. sort($this->payload['registration_ids']);
  133. if (isset($this->payload['time_to_live']) && !isset($this->payload['collapse_key']))
  134. $this->payload['collapse_key'] = 'GCM Notifications';
  135. $data = json_encode($this->payload);
  136. return $this->request($data);
  137. }
  138. protected function request($data)
  139. {
  140. $headers[] = 'Content-Type:application/json';
  141. $headers[] = 'Authorization:key='.$this->apiKey;
  142. $curl = curl_init();
  143. curl_setopt($curl, CURLOPT_URL, $this->apiSendAddress);
  144. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  145. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
  146. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  147. curl_setopt($curl, CURLOPT_HEADER, true);
  148. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  149. curl_setopt($curl, CURLOPT_POST, true);
  150. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  151. $this->responseData = curl_exec($curl);
  152. $this->responseInfo = curl_getinfo($curl);
  153. curl_close($curl);
  154. return $this->parseResponse();
  155. }
  156. protected function parseResponse()
  157. {
  158. if ($this->responseInfo['http_code'] == 200)
  159. {
  160. $response = explode("\n",$this->responseData);
  161. $responseBody = json_decode($response[count($response)-1]);
  162. if ($responseBody->success && !$responseBody->failure)
  163. {
  164. $message = 'All messages were sent successfully';
  165. $error = 0;
  166. }
  167. elseif ($responseBody->success && $responseBody->failure)
  168. {
  169. $message = $responseBody->success.' of '.($responseBody->success+$responseBody->failure).' messages were sent successfully';
  170. $error = 1;
  171. }
  172. elseif (!$responseBody->success && $responseBody->failure)
  173. {
  174. $message = 'No messages cannot be sent. '.$responseBody->results[0]->error;
  175. $error = 1;
  176. }
  177. $this->status = array(
  178. 'error' => $error,
  179. 'message' => $message
  180. );
  181. $this->messagesStatuses = array();
  182. foreach($responseBody->results as $key => $result)
  183. {
  184. if (isset($result->error) && $result->error)
  185. {
  186. $this->messagesStatuses[$key] = array(
  187. 'error' => 1,
  188. 'regid' => $this->payload['registration_ids'][$key],
  189. 'message' => $this->errorStatuses[$result->error],
  190. 'message_id' => ''
  191. );
  192. }
  193. else
  194. {
  195. $this->messagesStatuses[$key] = array(
  196. 'error' => 0,
  197. 'regid' => $this->payload['registration_ids'][$key],
  198. 'message' => 'Message was sent successfully',
  199. 'message_id' => $result->message_id
  200. );
  201. }
  202. }
  203. return !$error;
  204. }
  205. elseif ($this->responseInfo['http_code'] == 400)
  206. {
  207. $this->status = array(
  208. 'error' => 1,
  209. 'message' => 'Request could not be parsed as JSON'
  210. );
  211. return false;
  212. }
  213. elseif ($this->responseInfo['http_code'] == 401)
  214. {
  215. $this->status = array(
  216. 'error' => 1,
  217. 'message' => 'There was an error authenticating the sender account'
  218. );
  219. return false;
  220. }
  221. elseif ($this->responseInfo['http_code'] == 500)
  222. {
  223. $this->status = array(
  224. 'error' => 1,
  225. 'message' => 'There was an internal error in the GCM server while trying to process the request'
  226. );
  227. return false;
  228. }
  229. elseif ($this->responseInfo['http_code'] == 503)
  230. {
  231. $this->status = array(
  232. 'error' => 1,
  233. 'message' => 'Server is temporarily unavailable'
  234. );
  235. return false;
  236. }
  237. else
  238. {
  239. $this->status = array(
  240. 'error' => 1,
  241. 'message' => 'Status undefined'
  242. );
  243. return false;
  244. }
  245. }
  246. }