notification.lib.php 19 KB

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