notification.lib.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. //ofaj
  286. $noReply = api_get_setting('noreply_email_address');
  287. if (empty($noReply) && isset($senderInfo['email'])) {
  288. $extraHeaders = [
  289. 'reply_to' => [
  290. 'name' => $senderInfo['complete_name'],
  291. 'mail' => $senderInfo['email'],
  292. ],
  293. ];
  294. }
  295. if (!empty($userInfo['email'])) {
  296. api_mail_html(
  297. $userInfo['complete_name'],
  298. $userInfo['mail'],
  299. Security::filter_terms($titleToNotification),
  300. Security::filter_terms($content),
  301. $this->adminName,
  302. $this->adminEmail,
  303. $extraHeaders,
  304. $attachments,
  305. false,
  306. $smsParameters
  307. );
  308. }
  309. $sendDate = api_get_utc_datetime();
  310. }
  311. // Saving the notification to be sent some day.
  312. $content = cut($content, $this->max_content_length);
  313. $params = [
  314. 'sent_at' => $sendDate,
  315. 'dest_user_id' => $user_id,
  316. 'dest_mail' => $userInfo['email'],
  317. 'title' => $title,
  318. 'content' => $content,
  319. 'send_freq' => $userSetting,
  320. ];
  321. $this->save($params);
  322. }
  323. self::sendPushNotification($userList, $title, $content);
  324. }
  325. }
  326. /**
  327. * Formats the content in order to add the welcome message,
  328. * the notification preference, etc.
  329. *
  330. * @param int $messageId
  331. * @param string $content
  332. * @param array $senderInfo result of api_get_user_info() or
  333. * GroupPortalManager:get_group_data()
  334. *
  335. * @return string
  336. * */
  337. public function formatContent($messageId, $content, $senderInfo)
  338. {
  339. $hook = HookNotificationContent::create();
  340. if (!empty($hook)) {
  341. $hook->setEventData(['content' => $content]);
  342. $data = $hook->notifyNotificationContent(HOOK_EVENT_TYPE_PRE);
  343. if (isset($data['content'])) {
  344. $content = $data['content'];
  345. }
  346. }
  347. $newMessageText = $linkToNewMessage = '';
  348. $showEmail = api_get_configuration_value('show_user_email_in_notification');
  349. $senderInfoName = '';
  350. if (!empty($senderInfo) && isset($senderInfo['complete_name'])) {
  351. $senderInfoName = $senderInfo['complete_name'];
  352. if ($showEmail && isset($senderInfo['complete_name_with_email_forced'])) {
  353. $senderInfoName = $senderInfo['complete_name_with_email_forced'];
  354. }
  355. }
  356. switch ($this->type) {
  357. case self::NOTIFICATION_TYPE_DIRECT_MESSAGE:
  358. $newMessageText = '';
  359. $linkToNewMessage = Display::url(
  360. get_lang('SeeMessage'),
  361. api_get_path(WEB_CODE_PATH).'messages/view_message.php?id='.$messageId
  362. );
  363. break;
  364. case self::NOTIFICATION_TYPE_MESSAGE:
  365. $allow = api_get_configuration_value('messages_hide_mail_content');
  366. if ($allow) {
  367. $content = '';
  368. }
  369. if (!empty($senderInfo)) {
  370. $newMessageText = sprintf(
  371. get_lang('YouHaveANewMessageFromX'),
  372. $senderInfoName
  373. );
  374. }
  375. $linkToNewMessage = Display::url(
  376. get_lang('SeeMessage'),
  377. api_get_path(WEB_CODE_PATH).'messages/view_message.php?id='.$messageId
  378. );
  379. break;
  380. case self::NOTIFICATION_TYPE_INVITATION:
  381. if (!empty($senderInfo)) {
  382. $newMessageText = sprintf(
  383. get_lang('YouHaveANewInvitationFromX'),
  384. $senderInfoName
  385. );
  386. }
  387. $linkToNewMessage = Display::url(
  388. get_lang('SeeInvitation'),
  389. api_get_path(WEB_CODE_PATH).'social/invitations.php'
  390. );
  391. break;
  392. case self::NOTIFICATION_TYPE_GROUP:
  393. $topicPage = isset($_REQUEST['topics_page_nr']) ? (int) $_REQUEST['topics_page_nr'] : 0;
  394. if (!empty($senderInfo)) {
  395. $senderName = $senderInfo['group_info']['name'];
  396. $newMessageText = sprintf(get_lang('YouHaveReceivedANewMessageInTheGroupX'), $senderName);
  397. $senderName = Display::url(
  398. $senderInfoName,
  399. api_get_path(WEB_CODE_PATH).'social/profile.php?'.$senderInfo['user_info']['user_id']
  400. );
  401. $newMessageText .= '<br />'.get_lang('User').': '.$senderName;
  402. }
  403. $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;
  404. $linkToNewMessage = Display::url(get_lang('SeeMessage'), $groupUrl);
  405. break;
  406. }
  407. $preferenceUrl = api_get_path(WEB_CODE_PATH).'auth/profile.php';
  408. // You have received a new message text
  409. if (!empty($newMessageText)) {
  410. $content = $newMessageText.'<br /><hr><br />'.$content;
  411. }
  412. // See message with link text
  413. if (!empty($linkToNewMessage) && api_get_setting('allow_message_tool') == 'true') {
  414. $content = $content.'<br /><br />'.$linkToNewMessage;
  415. }
  416. // You have received this message because you are subscribed text
  417. $content = $content.'<br /><hr><i>'.
  418. sprintf(
  419. get_lang('YouHaveReceivedThisNotificationBecauseYouAreSubscribedOrInvolvedInItToChangeYourNotificationPreferencesPleaseClickHereX'),
  420. Display::url($preferenceUrl, $preferenceUrl)
  421. ).'</i>';
  422. if (!empty($hook)) {
  423. $hook->setEventData(['content' => $content]);
  424. $data = $hook->notifyNotificationContent(HOOK_EVENT_TYPE_POST);
  425. if (isset($data['content'])) {
  426. $content = $data['content'];
  427. }
  428. }
  429. return $content;
  430. }
  431. /**
  432. * Send the push notifications to Chamilo Mobile app.
  433. *
  434. * @param array $userIds The IDs of users who will be notified
  435. * @param string $title The notification title
  436. * @param string $content The notification content
  437. *
  438. * @return int The number of success notifications. Otherwise returns false
  439. */
  440. public static function sendPushNotification(array $userIds, $title, $content)
  441. {
  442. if (api_get_setting('messaging_allow_send_push_notification') !== 'true') {
  443. return false;
  444. }
  445. $gdcApiKey = api_get_setting('messaging_gdc_api_key');
  446. if ($gdcApiKey === false) {
  447. return false;
  448. }
  449. $content = strip_tags($content);
  450. $content = explode("\n", $content);
  451. $content = array_map('trim', $content);
  452. $content = array_filter($content);
  453. $content = implode(PHP_EOL, $content);
  454. $gcmRegistrationIds = [];
  455. foreach ($userIds as $userId) {
  456. $extraFieldValue = new ExtraFieldValue('user');
  457. $valueInfo = $extraFieldValue->get_values_by_handler_and_field_variable(
  458. $userId,
  459. Rest::EXTRA_FIELD_GCM_REGISTRATION
  460. );
  461. if (empty($valueInfo)) {
  462. continue;
  463. }
  464. $gcmRegistrationIds[] = $valueInfo['value'];
  465. }
  466. if (!$gcmRegistrationIds) {
  467. return 0;
  468. }
  469. $headers = [
  470. 'Authorization: key='.$gdcApiKey,
  471. 'Content-Type: application/json',
  472. ];
  473. $fields = json_encode([
  474. 'registration_ids' => $gcmRegistrationIds,
  475. 'data' => [
  476. 'title' => $title,
  477. 'message' => $content,
  478. ],
  479. 'notification' => [
  480. 'title' => $title,
  481. 'body' => $content,
  482. 'sound' => 'default',
  483. ],
  484. 'collapse_key' => get_lang('Messages'),
  485. ]);
  486. $ch = curl_init();
  487. curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
  488. curl_setopt($ch, CURLOPT_POST, true);
  489. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  490. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  491. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  492. curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
  493. $result = curl_exec($ch);
  494. curl_close($ch);
  495. /** @var array $decodedResult */
  496. $decodedResult = json_decode($result, true);
  497. return intval($decodedResult['success']);
  498. }
  499. }