MessagesWebService.class.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Class for manage the messages web service
  5. * @author Angel Fernando Quiroz Campos <angel.quiroz@beeznest.com>
  6. * @package chamilo.webservices.messages
  7. */
  8. class MessagesWebService extends WebService
  9. {
  10. const SERVICE_NAME = 'MsgREST';
  11. /**
  12. * @var string EXTRA_FIELD_GCM_REGISTRATION Variable name of the user extra field.
  13. * Necessary for register the registration token from the Google Cloud Messaging
  14. */
  15. const EXTRA_FIELD_GCM_REGISTRATION = 'gcm_registration_id';
  16. /**
  17. * Generate the api key for a user
  18. * @param int $userId The user id
  19. * @return string The api key
  20. */
  21. public function generateApiKey($userId)
  22. {
  23. $apiKey = UserManager::get_api_keys($userId, self::SERVICE_NAME);
  24. if (empty($apiKey)) {
  25. UserManager::add_api_key($userId, self::SERVICE_NAME);
  26. $apiKey = UserManager::get_api_keys($userId, self::SERVICE_NAME);
  27. }
  28. return current($apiKey);
  29. }
  30. /**
  31. * Get the user api key
  32. * @param string $username The user name
  33. * @return string The api key
  34. */
  35. public function getApiKey($username)
  36. {
  37. $userInfo = api_get_user_info_from_username($username);
  38. $userId = $userInfo['user_id'];
  39. if ($this->apiKey !== null) {
  40. return $this->apiKey;
  41. } else {
  42. $this->apiKey = $this->generateApiKey($userId);
  43. return $this->apiKey;
  44. }
  45. }
  46. /**
  47. * Check if the api is valid for a user
  48. * @param string $username The username
  49. * @param string $apiKeyToValidate The api key
  50. * @return boolean Whether the api belongs to the user return true. Otherwise return false
  51. */
  52. public static function isValidApiKey($username, $apiKeyToValidate)
  53. {
  54. $userInfo = api_get_user_info_from_username($username);
  55. $userId = $userInfo['user_id'];
  56. $apiKeys = UserManager::get_api_keys($userId, self::SERVICE_NAME);
  57. if (!empty($apiKeys)) {
  58. $apiKey = current($apiKeys);
  59. if ($apiKey == $apiKeyToValidate) {
  60. return true;
  61. }
  62. }
  63. return false;
  64. }
  65. /**
  66. * Get the count of new messages for a user
  67. * @param string $username The username
  68. * @param int $lastId The id of the last received message
  69. * @return int The count fo new messages
  70. */
  71. public function countNewMessages($username, $lastId = 0)
  72. {
  73. $userInfo = api_get_user_info_from_username($username);
  74. $userId = $userInfo['user_id'];
  75. return MessageManager::countMessagesFromLastReceivedMessage($userId, $lastId);
  76. }
  77. /**
  78. * Get the list of new messages for a user
  79. * @param string $username The username
  80. * @param int $lastId The id of the last received message
  81. * @return array the new message list
  82. */
  83. public function getNewMessages($username, $lastId = 0)
  84. {
  85. $messages = array();
  86. $userInfo = api_get_user_info_from_username($username);
  87. $userId = $userInfo['user_id'];
  88. $lastMessages = MessageManager::getMessagesFromLastReceivedMessage($userId, $lastId);
  89. foreach ($lastMessages as $message) {
  90. $hasAttachments = MessageManager::hasAttachments($message['id']);
  91. $messages[] = array(
  92. 'id' => $message['id'],
  93. 'title' => $message['title'],
  94. 'sender' => array(
  95. 'id' => $message['user_id'],
  96. 'lastname' => $message['lastname'],
  97. 'firstname' => $message['firstname'],
  98. 'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
  99. ),
  100. 'sendDate' => $message['send_date'],
  101. 'content' => $message['content'],
  102. 'hasAttachments' => $hasAttachments,
  103. 'platform' => array(
  104. 'website' => api_get_path(WEB_PATH),
  105. 'messagingTool' => api_get_path(WEB_PATH) . 'main/messages/inbox.php'
  106. )
  107. );
  108. }
  109. return $messages;
  110. }
  111. /**
  112. * Create the user extra field
  113. */
  114. public static function init()
  115. {
  116. $extraField = new ExtraField('user');
  117. $fieldInfo = $extraField->get_handler_field_info_by_field_variable(self::EXTRA_FIELD_GCM_REGISTRATION);
  118. if (empty($fieldInfo)) {
  119. $extraField->save([
  120. 'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
  121. 'field_type' => ExtraField::FIELD_TYPE_TEXT,
  122. 'display_text' => self::EXTRA_FIELD_GCM_REGISTRATION
  123. ]);
  124. }
  125. }
  126. /**
  127. * Register the Registration ID (token) obtained from Google Cloud Messaging for a user
  128. * @param Chamilo\UserBundle\Entity\User $user The user
  129. * @param string $registrationId The token registration id from Google Cloud Messaging
  130. * @return int The id after insert or the number of affected rows after update. Otherwhise return false
  131. */
  132. public static function setGcmRegistrationId(Chamilo\UserBundle\Entity\User $user, $registrationId)
  133. {
  134. $registrationId = Security::remove_XSS($registrationId);
  135. $extraFieldValue = new ExtraFieldValue('user');
  136. return $extraFieldValue->save([
  137. 'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
  138. 'value' => $registrationId,
  139. 'item_id' => $user->getId()
  140. ]);
  141. }
  142. /**
  143. * Send the push notifications to MobileMessaging app
  144. * @param array $userIds The IDs of users who will be notified
  145. * @param string $title The notification title
  146. * @param string $content The notification content
  147. * @return int The number of success notifications. Otherwise returns false
  148. */
  149. public static function sendPushNotification(array $userIds, $title, $content)
  150. {
  151. if (api_get_configuration_value('messaging_allow_send_push_notification') !== 'true') {
  152. return false;
  153. }
  154. $gdcApiKey = api_get_configuration_value('messaging_gdc_api_key');
  155. if ($gdcApiKey === false) {
  156. return false;
  157. }
  158. $content = str_replace(['<br>', '<br/>', '<br />'], "\n", $content);
  159. $content = strip_tags($content);
  160. $content = html_entity_decode($content, ENT_QUOTES);
  161. $gcmRegistrationIds = [];
  162. foreach ($userIds as $userId) {
  163. $extraFieldValue = new ExtraFieldValue('user');
  164. $valueInfo = $extraFieldValue->get_values_by_handler_and_field_variable(
  165. $userId,
  166. self::EXTRA_FIELD_GCM_REGISTRATION
  167. );
  168. if (empty($valueInfo)) {
  169. continue;
  170. }
  171. $gcmRegistrationIds[] = $valueInfo['value'];
  172. }
  173. $headers = [
  174. 'Authorization: key=' . $gdcApiKey,
  175. 'Content-Type: application/json'
  176. ];
  177. $fields = json_encode([
  178. 'registration_ids' => $gcmRegistrationIds,
  179. 'data' => [
  180. 'title' => $title,
  181. 'message' => $content
  182. ]
  183. ]);
  184. $ch = curl_init();
  185. curl_setopt($ch, CURLOPT_URL, 'https://gcm-http.googleapis.com/gcm/send');
  186. curl_setopt($ch, CURLOPT_POST, true);
  187. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  188. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  189. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  190. curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
  191. $result = curl_exec($ch);
  192. curl_close($ch);
  193. $decodedResult = json_decode($result);
  194. return $decodedResult->success;
  195. }
  196. }