notification.lib.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. /**
  4. * Notification class
  5. * This class provides methods for the Notification management.
  6. * Include/require it in your code to use its features.
  7. *
  8. * @package chamilo.library
  9. */
  10. class Notification extends Model
  11. {
  12. // mail_notify_message ("At once", "Daily", "No")
  13. const NOTIFY_MESSAGE_AT_ONCE = 1;
  14. const NOTIFY_MESSAGE_DAILY = 8;
  15. const NOTIFY_MESSAGE_WEEKLY = 12;
  16. const NOTIFY_MESSAGE_NO = 0;
  17. // mail_notify_invitation ("At once", "Daily", "No")
  18. const NOTIFY_INVITATION_AT_ONCE = 1;
  19. const NOTIFY_INVITATION_DAILY = 8;
  20. const NOTIFY_INVITATION_WEEKLY = 12;
  21. const NOTIFY_INVITATION_NO = 0;
  22. // mail_notify_group_message ("At once", "Daily", "No")
  23. const NOTIFY_GROUP_AT_ONCE = 1;
  24. const NOTIFY_GROUP_DAILY = 8;
  25. const NOTIFY_GROUP_WEEKLY = 12;
  26. const NOTIFY_GROUP_NO = 0;
  27. // Notification types
  28. const NOTIFICATION_TYPE_MESSAGE = 1;
  29. const NOTIFICATION_TYPE_INVITATION = 2;
  30. const NOTIFICATION_TYPE_GROUP = 3;
  31. const NOTIFICATION_TYPE_WALL_MESSAGE = 4;
  32. const NOTIFICATION_TYPE_DIRECT_MESSAGE = 5;
  33. public $table;
  34. public $columns = [
  35. 'id',
  36. 'dest_user_id',
  37. 'dest_mail',
  38. 'title',
  39. 'content',
  40. 'send_freq',
  41. 'created_at',
  42. 'sent_at',
  43. ];
  44. //Max length of the notification.content field
  45. public $max_content_length = 254;
  46. public $debug = false;
  47. /* message, invitation, group messages */
  48. public $type;
  49. public $adminName;
  50. public $adminEmail;
  51. public $titlePrefix;
  52. /**
  53. * Constructor.
  54. */
  55. public function __construct()
  56. {
  57. $this->table = Database::get_main_table(TABLE_NOTIFICATION);
  58. // Default no-reply email
  59. $this->adminEmail = api_get_setting('noreply_email_address');
  60. $this->adminName = api_get_setting('siteName');
  61. $this->titlePrefix = '['.api_get_setting('siteName').'] ';
  62. // If no-reply email doesn't exist use the admin name/email
  63. if (empty($this->adminEmail)) {
  64. $this->adminEmail = api_get_setting('emailAdministrator');
  65. $this->adminName = api_get_person_name(
  66. api_get_setting('administratorName'),
  67. api_get_setting('administratorSurname'),
  68. null,
  69. PERSON_NAME_EMAIL_ADDRESS
  70. );
  71. }
  72. }
  73. /**
  74. * @return string
  75. */
  76. public function getTitlePrefix()
  77. {
  78. return $this->titlePrefix;
  79. }
  80. /**
  81. * @return string
  82. */
  83. public function getDefaultPlatformSenderEmail()
  84. {
  85. return $this->adminEmail;
  86. }
  87. /**
  88. * @return string
  89. */
  90. public function getDefaultPlatformSenderName()
  91. {
  92. return $this->adminName;
  93. }
  94. /**
  95. * Send the notifications.
  96. *
  97. * @param int $frequency notification frequency
  98. */
  99. public function send($frequency = 8)
  100. {
  101. $notifications = $this->find(
  102. 'all',
  103. ['where' => ['sent_at IS NULL AND send_freq = ?' => $frequency]]
  104. );
  105. if (!empty($notifications)) {
  106. foreach ($notifications as $item_to_send) {
  107. // Sending email
  108. api_mail_html(
  109. $item_to_send['dest_mail'],
  110. $item_to_send['dest_mail'],
  111. Security::filter_terms($item_to_send['title']),
  112. Security::filter_terms($item_to_send['content']),
  113. $this->adminName,
  114. $this->adminEmail
  115. );
  116. if ($this->debug) {
  117. error_log('Sending message to: '.$item_to_send['dest_mail']);
  118. }
  119. // Updating
  120. $item_to_send['sent_at'] = api_get_utc_datetime();
  121. $this->update($item_to_send);
  122. if ($this->debug) {
  123. error_log('Updating record : '.print_r($item_to_send, 1));
  124. }
  125. }
  126. }
  127. }
  128. /**
  129. * @param string $title
  130. * @param array $senderInfo
  131. * @param bool $forceTitleWhenSendingEmail force the use of $title as subject instead of "You have a new message"
  132. *
  133. * @return string
  134. */
  135. public function formatTitle($title, $senderInfo, $forceTitleWhenSendingEmail = false)
  136. {
  137. $hook = HookNotificationTitle::create();
  138. if (!empty($hook)) {
  139. $hook->setEventData(['title' => $title]);
  140. $data = $hook->notifyNotificationTitle(HOOK_EVENT_TYPE_PRE);
  141. if (isset($data['title'])) {
  142. $title = $data['title'];
  143. }
  144. }
  145. $newTitle = $this->getTitlePrefix();
  146. switch ($this->type) {
  147. case self::NOTIFICATION_TYPE_MESSAGE:
  148. if (!empty($senderInfo)) {
  149. $senderName = api_get_person_name(
  150. $senderInfo['firstname'],
  151. $senderInfo['lastname'],
  152. null,
  153. PERSON_NAME_EMAIL_ADDRESS
  154. );
  155. $newTitle .= sprintf(get_lang('YouHaveANewMessageFromX'), $senderName);
  156. }
  157. break;
  158. case self::NOTIFICATION_TYPE_DIRECT_MESSAGE:
  159. $newTitle = $title;
  160. break;
  161. case self::NOTIFICATION_TYPE_INVITATION:
  162. if (!empty($senderInfo)) {
  163. $senderName = api_get_person_name(
  164. $senderInfo['firstname'],
  165. $senderInfo['lastname'],
  166. null,
  167. PERSON_NAME_EMAIL_ADDRESS
  168. );
  169. $newTitle .= sprintf(get_lang('YouHaveANewInvitationFromX'), $senderName);
  170. }
  171. break;
  172. case self::NOTIFICATION_TYPE_GROUP:
  173. if (!empty($senderInfo)) {
  174. $senderName = $senderInfo['group_info']['name'];
  175. $newTitle .= sprintf(get_lang('YouHaveReceivedANewMessageInTheGroupX'), $senderName);
  176. $senderName = api_get_person_name(
  177. $senderInfo['user_info']['firstname'],
  178. $senderInfo['user_info']['lastname'],
  179. null,
  180. PERSON_NAME_EMAIL_ADDRESS
  181. );
  182. $newTitle .= $senderName;
  183. }
  184. break;
  185. }
  186. // The title won't be changed, it will be used as is
  187. if ($forceTitleWhenSendingEmail) {
  188. $newTitle = $title;
  189. }
  190. if (!empty($hook)) {
  191. $hook->setEventData(['title' => $newTitle]);
  192. $data = $hook->notifyNotificationTitle(HOOK_EVENT_TYPE_POST);
  193. if (isset($data['title'])) {
  194. $newTitle = $data['title'];
  195. }
  196. }
  197. return $newTitle;
  198. }
  199. /**
  200. * Save message notification.
  201. *
  202. * @param int $type message type
  203. * NOTIFICATION_TYPE_MESSAGE,
  204. * NOTIFICATION_TYPE_INVITATION,
  205. * NOTIFICATION_TYPE_GROUP
  206. * @param int $messageId
  207. * @param array $userList recipients: user list of ids
  208. * @param string $title
  209. * @param string $content
  210. * @param array $senderInfo result of api_get_user_info() or GroupPortalManager:get_group_data()
  211. * @param array $attachments
  212. * @param array $smsParameters
  213. * @param bool $forceTitleWhenSendingEmail force the use of $title as subject instead of "You have a new message"
  214. */
  215. public function saveNotification(
  216. $messageId,
  217. $type,
  218. $userList,
  219. $title,
  220. $content,
  221. $senderInfo = [],
  222. $attachments = [],
  223. $smsParameters = [],
  224. $forceTitleWhenSendingEmail = false
  225. ) {
  226. $this->type = (int) $type;
  227. $messageId = (int) $messageId;
  228. $content = $this->formatContent($messageId, $content, $senderInfo);
  229. $titleToNotification = $this->formatTitle($title, $senderInfo, $forceTitleWhenSendingEmail);
  230. $settingToCheck = '';
  231. $avoid_my_self = false;
  232. switch ($this->type) {
  233. case self::NOTIFICATION_TYPE_DIRECT_MESSAGE:
  234. case self::NOTIFICATION_TYPE_MESSAGE:
  235. $settingToCheck = 'mail_notify_message';
  236. $defaultStatus = self::NOTIFY_MESSAGE_AT_ONCE;
  237. break;
  238. case self::NOTIFICATION_TYPE_INVITATION:
  239. $settingToCheck = 'mail_notify_invitation';
  240. $defaultStatus = self::NOTIFY_INVITATION_AT_ONCE;
  241. break;
  242. case self::NOTIFICATION_TYPE_GROUP:
  243. $settingToCheck = 'mail_notify_group_message';
  244. $defaultStatus = self::NOTIFY_GROUP_AT_ONCE;
  245. $avoid_my_self = true;
  246. break;
  247. default:
  248. $defaultStatus = self::NOTIFY_MESSAGE_AT_ONCE;
  249. break;
  250. }
  251. $settingInfo = UserManager::get_extra_field_information_by_name($settingToCheck);
  252. if (!empty($userList)) {
  253. foreach ($userList as $user_id) {
  254. if ($avoid_my_self) {
  255. if ($user_id == api_get_user_id()) {
  256. continue;
  257. }
  258. }
  259. $userInfo = api_get_user_info($user_id);
  260. // Extra field was deleted or removed? Use the default status.
  261. $userSetting = $defaultStatus;
  262. if (!empty($settingInfo)) {
  263. $extra_data = UserManager::get_extra_user_data($user_id);
  264. if (isset($extra_data[$settingToCheck])) {
  265. $userSetting = $extra_data[$settingToCheck];
  266. }
  267. // Means that user extra was not set
  268. // Then send email now.
  269. if ($userSetting === '') {
  270. $userSetting = self::NOTIFY_MESSAGE_AT_ONCE;
  271. }
  272. }
  273. $sendDate = null;
  274. switch ($userSetting) {
  275. // No notifications
  276. case self::NOTIFY_MESSAGE_NO:
  277. case self::NOTIFY_INVITATION_NO:
  278. case self::NOTIFY_GROUP_NO:
  279. break;
  280. // Send notification right now!
  281. case self::NOTIFY_MESSAGE_AT_ONCE:
  282. case self::NOTIFY_INVITATION_AT_ONCE:
  283. case self::NOTIFY_GROUP_AT_ONCE:
  284. $extraHeaders = [];
  285. if (isset($senderInfo['email'])) {
  286. $extraHeaders = [
  287. 'reply_to' => [
  288. 'name' => $senderInfo['complete_name'],
  289. 'mail' => $senderInfo['email'],
  290. ],
  291. ];
  292. }
  293. if (!empty($userInfo['email'])) {
  294. api_mail_html(
  295. $userInfo['complete_name'],
  296. $userInfo['mail'],
  297. Security::filter_terms($titleToNotification),
  298. Security::filter_terms($content),
  299. $this->adminName,
  300. $this->adminEmail,
  301. $extraHeaders,
  302. $attachments,
  303. false,
  304. $smsParameters
  305. );
  306. }
  307. $sendDate = api_get_utc_datetime();
  308. }
  309. // Saving the notification to be sent some day.
  310. $content = cut($content, $this->max_content_length);
  311. $params = [
  312. 'sent_at' => $sendDate,
  313. 'dest_user_id' => $user_id,
  314. 'dest_mail' => $userInfo['email'],
  315. 'title' => $title,
  316. 'content' => $content,
  317. 'send_freq' => $userSetting,
  318. ];
  319. $this->save($params);
  320. }
  321. self::sendPushNotification($userList, $title, $content);
  322. }
  323. }
  324. /**
  325. * Formats the content in order to add the welcome message,
  326. * the notification preference, etc.
  327. *
  328. * @param int $messageId
  329. * @param string $content
  330. * @param array $senderInfo result of api_get_user_info() or
  331. * GroupPortalManager:get_group_data()
  332. *
  333. * @return string
  334. * */
  335. public function formatContent($messageId, $content, $senderInfo)
  336. {
  337. $hook = HookNotificationContent::create();
  338. if (!empty($hook)) {
  339. $hook->setEventData(['content' => $content]);
  340. $data = $hook->notifyNotificationContent(HOOK_EVENT_TYPE_PRE);
  341. if (isset($data['content'])) {
  342. $content = $data['content'];
  343. }
  344. }
  345. $newMessageText = $linkToNewMessage = '';
  346. $showEmail = api_get_configuration_value('show_user_email_in_notification');
  347. $senderInfoName = '';
  348. if (!empty($senderInfo) && isset($senderInfo['complete_name'])) {
  349. $senderInfoName = $senderInfo['complete_name'];
  350. if ($showEmail && isset($senderInfo['complete_name_with_email_forced'])) {
  351. $senderInfoName = $senderInfo['complete_name_with_email_forced'];
  352. }
  353. }
  354. switch ($this->type) {
  355. case self::NOTIFICATION_TYPE_DIRECT_MESSAGE:
  356. $newMessageText = '';
  357. $linkToNewMessage = Display::url(
  358. get_lang('SeeMessage'),
  359. api_get_path(WEB_CODE_PATH).'messages/view_message.php?id='.$messageId
  360. );
  361. break;
  362. case self::NOTIFICATION_TYPE_MESSAGE:
  363. $allow = api_get_configuration_value('messages_hide_mail_content');
  364. if ($allow) {
  365. $content = '';
  366. }
  367. if (!empty($senderInfo)) {
  368. $newMessageText = sprintf(
  369. get_lang('YouHaveANewMessageFromX'),
  370. $senderInfoName
  371. );
  372. }
  373. $linkToNewMessage = Display::url(
  374. get_lang('SeeMessage'),
  375. api_get_path(WEB_CODE_PATH).'messages/view_message.php?id='.$messageId
  376. );
  377. break;
  378. case self::NOTIFICATION_TYPE_INVITATION:
  379. if (!empty($senderInfo)) {
  380. $newMessageText = sprintf(
  381. get_lang('YouHaveANewInvitationFromX'),
  382. $senderInfoName
  383. );
  384. }
  385. $linkToNewMessage = Display::url(
  386. get_lang('SeeInvitation'),
  387. api_get_path(WEB_CODE_PATH).'social/invitations.php'
  388. );
  389. break;
  390. case self::NOTIFICATION_TYPE_GROUP:
  391. $topicPage = isset($_REQUEST['topics_page_nr']) ? (int) $_REQUEST['topics_page_nr'] : 0;
  392. if (!empty($senderInfo)) {
  393. $senderName = $senderInfo['group_info']['name'];
  394. $newMessageText = sprintf(get_lang('YouHaveReceivedANewMessageInTheGroupX'), $senderName);
  395. $senderName = Display::url(
  396. $senderInfoName,
  397. api_get_path(WEB_CODE_PATH).'social/profile.php?'.$senderInfo['user_info']['user_id']
  398. );
  399. $newMessageText .= '<br />'.get_lang('User').': '.$senderName;
  400. }
  401. $groupUrl = api_get_path(WEB_CODE_PATH).'social/group_topics.php?id='.$senderInfo['group_info']['id'].'&topic_id='.$senderInfo['group_info']['topic_id'].'&msg_id='.$senderInfo['group_info']['msg_id'].'&topics_page_nr='.$topicPage;
  402. $linkToNewMessage = Display::url(get_lang('SeeMessage'), $groupUrl);
  403. break;
  404. }
  405. $preferenceUrl = api_get_path(WEB_CODE_PATH).'auth/profile.php';
  406. // You have received a new message text
  407. if (!empty($newMessageText)) {
  408. $content = $newMessageText.'<br /><hr><br />'.$content;
  409. }
  410. // See message with link text
  411. if (!empty($linkToNewMessage) && api_get_setting('allow_message_tool') == 'true') {
  412. $content = $content.'<br /><br />'.$linkToNewMessage;
  413. }
  414. // You have received this message because you are subscribed text
  415. $content = $content.'<br /><hr><i>'.
  416. sprintf(
  417. get_lang('YouHaveReceivedThisNotificationBecauseYouAreSubscribedOrInvolvedInItToChangeYourNotificationPreferencesPleaseClickHereX'),
  418. Display::url($preferenceUrl, $preferenceUrl)
  419. ).'</i>';
  420. if (!empty($hook)) {
  421. $hook->setEventData(['content' => $content]);
  422. $data = $hook->notifyNotificationContent(HOOK_EVENT_TYPE_POST);
  423. if (isset($data['content'])) {
  424. $content = $data['content'];
  425. }
  426. }
  427. return $content;
  428. }
  429. /**
  430. * Send the push notifications to Chamilo Mobile app.
  431. *
  432. * @param array $userIds The IDs of users who will be notified
  433. * @param string $title The notification title
  434. * @param string $content The notification content
  435. *
  436. * @return int The number of success notifications. Otherwise returns false
  437. */
  438. public static function sendPushNotification(array $userIds, $title, $content)
  439. {
  440. if (api_get_setting('messaging_allow_send_push_notification') !== 'true') {
  441. return false;
  442. }
  443. $gdcApiKey = api_get_setting('messaging_gdc_api_key');
  444. if ($gdcApiKey === false) {
  445. return false;
  446. }
  447. $content = strip_tags($content);
  448. $content = explode("\n", $content);
  449. $content = array_map('trim', $content);
  450. $content = array_filter($content);
  451. $content = implode(PHP_EOL, $content);
  452. $gcmRegistrationIds = [];
  453. foreach ($userIds as $userId) {
  454. $extraFieldValue = new ExtraFieldValue('user');
  455. $valueInfo = $extraFieldValue->get_values_by_handler_and_field_variable(
  456. $userId,
  457. Rest::EXTRA_FIELD_GCM_REGISTRATION
  458. );
  459. if (empty($valueInfo)) {
  460. continue;
  461. }
  462. $gcmRegistrationIds[] = $valueInfo['value'];
  463. }
  464. if (!$gcmRegistrationIds) {
  465. return 0;
  466. }
  467. $headers = [
  468. 'Authorization: key='.$gdcApiKey,
  469. 'Content-Type: application/json',
  470. ];
  471. $fields = json_encode([
  472. 'registration_ids' => $gcmRegistrationIds,
  473. 'data' => [
  474. 'title' => $title,
  475. 'message' => $content,
  476. ],
  477. 'notification' => [
  478. 'title' => $title,
  479. 'body' => $content,
  480. 'sound' => 'default',
  481. ],
  482. 'collapse_key' => get_lang('Messages'),
  483. ]);
  484. $ch = curl_init();
  485. curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
  486. curl_setopt($ch, CURLOPT_POST, true);
  487. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  488. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  489. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  490. curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
  491. $result = curl_exec($ch);
  492. curl_close($ch);
  493. /** @var array $decodedResult */
  494. $decodedResult = json_decode($result, true);
  495. return intval($decodedResult['success']);
  496. }
  497. }