notification.lib.php 20 KB

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