notification.lib.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. *
  132. * @return string
  133. */
  134. public function formatTitle($title, $senderInfo)
  135. {
  136. $hook = HookNotificationTitle::create();
  137. if (!empty($hook)) {
  138. $hook->setEventData(['title' => $title]);
  139. $data = $hook->notifyNotificationTitle(HOOK_EVENT_TYPE_PRE);
  140. if (isset($data['title'])) {
  141. $title = $data['title'];
  142. }
  143. }
  144. $newTitle = $this->getTitlePrefix();
  145. switch ($this->type) {
  146. case self::NOTIFICATION_TYPE_MESSAGE:
  147. if (!empty($senderInfo)) {
  148. $senderName = api_get_person_name(
  149. $senderInfo['firstname'],
  150. $senderInfo['lastname'],
  151. null,
  152. PERSON_NAME_EMAIL_ADDRESS
  153. );
  154. $newTitle .= sprintf(get_lang('YouHaveANewMessageFromX'), $senderName);
  155. }
  156. break;
  157. case self::NOTIFICATION_TYPE_DIRECT_MESSAGE:
  158. $newTitle = $title;
  159. break;
  160. case self::NOTIFICATION_TYPE_INVITATION:
  161. if (!empty($senderInfo)) {
  162. $senderName = api_get_person_name(
  163. $senderInfo['firstname'],
  164. $senderInfo['lastname'],
  165. null,
  166. PERSON_NAME_EMAIL_ADDRESS
  167. );
  168. $newTitle .= sprintf(get_lang('YouHaveANewInvitationFromX'), $senderName);
  169. }
  170. break;
  171. case self::NOTIFICATION_TYPE_GROUP:
  172. if (!empty($senderInfo)) {
  173. $senderName = $senderInfo['group_info']['name'];
  174. $newTitle .= sprintf(get_lang('YouHaveReceivedANewMessageInTheGroupX'), $senderName);
  175. $senderName = api_get_person_name(
  176. $senderInfo['user_info']['firstname'],
  177. $senderInfo['user_info']['lastname'],
  178. null,
  179. PERSON_NAME_EMAIL_ADDRESS
  180. );
  181. $newTitle .= $senderName;
  182. }
  183. break;
  184. }
  185. if (!empty($hook)) {
  186. $hook->setEventData(['title' => $newTitle]);
  187. $data = $hook->notifyNotificationTitle(HOOK_EVENT_TYPE_POST);
  188. if (isset($data['title'])) {
  189. $newTitle = $data['title'];
  190. }
  191. }
  192. return $newTitle;
  193. }
  194. /**
  195. * Save message notification.
  196. *
  197. * @param int $type message type
  198. * NOTIFICATION_TYPE_MESSAGE,
  199. * NOTIFICATION_TYPE_INVITATION,
  200. * NOTIFICATION_TYPE_GROUP
  201. * @param int $messageId
  202. * @param array $userList recipients: user list of ids
  203. * @param string $title
  204. * @param string $content
  205. * @param array $senderInfo result of api_get_user_info() or GroupPortalManager:get_group_data()
  206. * @param array $attachments
  207. * @param array $smsParameters
  208. */
  209. public function saveNotification(
  210. $messageId,
  211. $type,
  212. $userList,
  213. $title,
  214. $content,
  215. $senderInfo = [],
  216. $attachments = [],
  217. $smsParameters = []
  218. ) {
  219. $this->type = (int) $type;
  220. $messageId = (int) $messageId;
  221. $content = $this->formatContent($messageId, $content, $senderInfo);
  222. $titleToNotification = $this->formatTitle($title, $senderInfo);
  223. $settingToCheck = '';
  224. $avoid_my_self = false;
  225. switch ($this->type) {
  226. case self::NOTIFICATION_TYPE_DIRECT_MESSAGE:
  227. case self::NOTIFICATION_TYPE_MESSAGE:
  228. $settingToCheck = 'mail_notify_message';
  229. $defaultStatus = self::NOTIFY_MESSAGE_AT_ONCE;
  230. break;
  231. case self::NOTIFICATION_TYPE_INVITATION:
  232. $settingToCheck = 'mail_notify_invitation';
  233. $defaultStatus = self::NOTIFY_INVITATION_AT_ONCE;
  234. break;
  235. case self::NOTIFICATION_TYPE_GROUP:
  236. $settingToCheck = 'mail_notify_group_message';
  237. $defaultStatus = self::NOTIFY_GROUP_AT_ONCE;
  238. $avoid_my_self = true;
  239. break;
  240. default:
  241. $defaultStatus = self::NOTIFY_MESSAGE_AT_ONCE;
  242. break;
  243. }
  244. $settingInfo = UserManager::get_extra_field_information_by_name($settingToCheck);
  245. if (!empty($userList)) {
  246. foreach ($userList as $user_id) {
  247. if ($avoid_my_self) {
  248. if ($user_id == api_get_user_id()) {
  249. continue;
  250. }
  251. }
  252. $userInfo = api_get_user_info($user_id);
  253. // Extra field was deleted or removed? Use the default status.
  254. $userSetting = $defaultStatus;
  255. if (!empty($settingInfo)) {
  256. $extra_data = UserManager::get_extra_user_data($user_id);
  257. if (isset($extra_data[$settingToCheck])) {
  258. $userSetting = $extra_data[$settingToCheck];
  259. }
  260. // Means that user extra was not set
  261. // Then send email now.
  262. if ($userSetting === '') {
  263. $userSetting = self::NOTIFY_MESSAGE_AT_ONCE;
  264. }
  265. }
  266. $sendDate = null;
  267. switch ($userSetting) {
  268. // No notifications
  269. case self::NOTIFY_MESSAGE_NO:
  270. case self::NOTIFY_INVITATION_NO:
  271. case self::NOTIFY_GROUP_NO:
  272. break;
  273. // Send notification right now!
  274. case self::NOTIFY_MESSAGE_AT_ONCE:
  275. case self::NOTIFY_INVITATION_AT_ONCE:
  276. case self::NOTIFY_GROUP_AT_ONCE:
  277. $extraHeaders = [];
  278. if (isset($senderInfo['email'])) {
  279. $extraHeaders = [
  280. 'reply_to' => [
  281. 'name' => $senderInfo['complete_name'],
  282. 'mail' => $senderInfo['email'],
  283. ],
  284. ];
  285. }
  286. if (!empty($userInfo['email'])) {
  287. api_mail_html(
  288. $userInfo['complete_name'],
  289. $userInfo['mail'],
  290. Security::filter_terms($titleToNotification),
  291. Security::filter_terms($content),
  292. $this->adminName,
  293. $this->adminEmail,
  294. $extraHeaders,
  295. $attachments,
  296. false,
  297. $smsParameters
  298. );
  299. }
  300. $sendDate = api_get_utc_datetime();
  301. }
  302. // Saving the notification to be sent some day.
  303. $content = cut($content, $this->max_content_length);
  304. $params = [
  305. 'sent_at' => $sendDate,
  306. 'dest_user_id' => $user_id,
  307. 'dest_mail' => $userInfo['email'],
  308. 'title' => $title,
  309. 'content' => $content,
  310. 'send_freq' => $userSetting,
  311. ];
  312. $this->save($params);
  313. }
  314. self::sendPushNotification($userList, $title, $content);
  315. }
  316. }
  317. /**
  318. * Formats the content in order to add the welcome message,
  319. * the notification preference, etc.
  320. *
  321. * @param int $messageId
  322. * @param string $content
  323. * @param array $senderInfo result of api_get_user_info() or
  324. * GroupPortalManager:get_group_data()
  325. *
  326. * @return string
  327. * */
  328. public function formatContent($messageId, $content, $senderInfo)
  329. {
  330. $hook = HookNotificationContent::create();
  331. if (!empty($hook)) {
  332. $hook->setEventData(['content' => $content]);
  333. $data = $hook->notifyNotificationContent(HOOK_EVENT_TYPE_PRE);
  334. if (isset($data['content'])) {
  335. $content = $data['content'];
  336. }
  337. }
  338. $newMessageText = $linkToNewMessage = '';
  339. $showEmail = api_get_configuration_value('show_user_email_in_notification');
  340. $senderInfoName = '';
  341. if (!empty($senderInfo) && isset($senderInfo['complete_name'])) {
  342. $senderInfoName = $senderInfo['complete_name'];
  343. if ($showEmail && isset($senderInfo['complete_name_with_email_forced'])) {
  344. $senderInfoName = $senderInfo['complete_name_with_email_forced'];
  345. }
  346. }
  347. switch ($this->type) {
  348. case self::NOTIFICATION_TYPE_DIRECT_MESSAGE:
  349. $newMessageText = '';
  350. $linkToNewMessage = Display::url(
  351. get_lang('SeeMessage'),
  352. api_get_path(WEB_CODE_PATH).'messages/view_message.php?id='.$messageId
  353. );
  354. break;
  355. case self::NOTIFICATION_TYPE_MESSAGE:
  356. $allow = api_get_configuration_value('messages_hide_mail_content');
  357. if ($allow) {
  358. $content = '';
  359. }
  360. if (!empty($senderInfo)) {
  361. $newMessageText = sprintf(
  362. get_lang('YouHaveANewMessageFromX'),
  363. $senderInfoName
  364. );
  365. }
  366. $linkToNewMessage = Display::url(
  367. get_lang('SeeMessage'),
  368. api_get_path(WEB_CODE_PATH).'messages/view_message.php?id='.$messageId
  369. );
  370. break;
  371. case self::NOTIFICATION_TYPE_INVITATION:
  372. if (!empty($senderInfo)) {
  373. $newMessageText = sprintf(
  374. get_lang('YouHaveANewInvitationFromX'),
  375. $senderInfoName
  376. );
  377. }
  378. $linkToNewMessage = Display::url(
  379. get_lang('SeeInvitation'),
  380. api_get_path(WEB_CODE_PATH).'social/invitations.php'
  381. );
  382. break;
  383. case self::NOTIFICATION_TYPE_GROUP:
  384. $topicPage = isset($_REQUEST['topics_page_nr']) ? (int) $_REQUEST['topics_page_nr'] : 0;
  385. if (!empty($senderInfo)) {
  386. $senderName = $senderInfo['group_info']['name'];
  387. $newMessageText = sprintf(get_lang('YouHaveReceivedANewMessageInTheGroupX'), $senderName);
  388. $senderName = Display::url(
  389. $senderInfoName,
  390. api_get_path(WEB_CODE_PATH).'social/profile.php?'.$senderInfo['user_info']['user_id']
  391. );
  392. $newMessageText .= '<br />'.get_lang('User').': '.$senderName;
  393. }
  394. $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;
  395. $linkToNewMessage = Display::url(get_lang('SeeMessage'), $groupUrl);
  396. break;
  397. }
  398. $preferenceUrl = api_get_path(WEB_CODE_PATH).'auth/profile.php';
  399. // You have received a new message text
  400. if (!empty($newMessageText)) {
  401. $content = $newMessageText.'<br /><hr><br />'.$content;
  402. }
  403. // See message with link text
  404. if (!empty($linkToNewMessage) && api_get_setting('allow_message_tool') == 'true') {
  405. $content = $content.'<br /><br />'.$linkToNewMessage;
  406. }
  407. /*$courseInfo = api_get_course_info();
  408. // Add course info
  409. if (!empty($courseInfo)) {
  410. $sessionId = api_get_session_id();
  411. if (empty($sessionId)) {
  412. $courseNotification = sprintf(get_lang('ThisEmailWasSentViaCourseX'), $courseInfo['title']);
  413. } else {
  414. $sessionInfo = api_get_session_info($sessionId);
  415. if (!empty($sessionInfo)) {
  416. $courseNotification = sprintf(
  417. get_lang('ThisEmailWasSentViaCourseXInSessionX'),
  418. $courseInfo['title'],
  419. $sessionInfo['title']
  420. );
  421. }
  422. }
  423. $content = $content.'<br /><br />'.$courseNotification;
  424. }*/
  425. // You have received this message because you are subscribed text
  426. $content = $content.'<br /><hr><i>'.
  427. sprintf(
  428. get_lang('YouHaveReceivedThisNotificationBecauseYouAreSubscribedOrInvolvedInItToChangeYourNotificationPreferencesPleaseClickHereX'),
  429. Display::url($preferenceUrl, $preferenceUrl)
  430. ).'</i>';
  431. if (!empty($hook)) {
  432. $hook->setEventData(['content' => $content]);
  433. $data = $hook->notifyNotificationContent(HOOK_EVENT_TYPE_POST);
  434. if (isset($data['content'])) {
  435. $content = $data['content'];
  436. }
  437. }
  438. return $content;
  439. }
  440. /**
  441. * Send the push notifications to Chamilo Mobile app.
  442. *
  443. * @param array $userIds The IDs of users who will be notified
  444. * @param string $title The notification title
  445. * @param string $content The notification content
  446. *
  447. * @return int The number of success notifications. Otherwise returns false
  448. */
  449. public static function sendPushNotification(array $userIds, $title, $content)
  450. {
  451. if (api_get_setting('messaging_allow_send_push_notification') !== 'true') {
  452. return false;
  453. }
  454. $gdcApiKey = api_get_setting('messaging_gdc_api_key');
  455. if ($gdcApiKey === false) {
  456. return false;
  457. }
  458. $content = str_replace(['<br>', '<br/>', '<br />'], "\n", $content);
  459. $content = strip_tags($content);
  460. $content = html_entity_decode($content, ENT_QUOTES);
  461. $gcmRegistrationIds = [];
  462. foreach ($userIds as $userId) {
  463. $extraFieldValue = new ExtraFieldValue('user');
  464. $valueInfo = $extraFieldValue->get_values_by_handler_and_field_variable(
  465. $userId,
  466. Rest::EXTRA_FIELD_GCM_REGISTRATION
  467. );
  468. if (empty($valueInfo)) {
  469. continue;
  470. }
  471. $gcmRegistrationIds[] = $valueInfo['value'];
  472. }
  473. if (!$gcmRegistrationIds) {
  474. return 0;
  475. }
  476. $headers = [
  477. 'Authorization: key='.$gdcApiKey,
  478. 'Content-Type: application/json',
  479. ];
  480. $fields = json_encode([
  481. 'registration_ids' => $gcmRegistrationIds,
  482. 'data' => [
  483. 'title' => $title,
  484. 'message' => $content,
  485. ],
  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. }