notification.lib.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. *
  204. */
  205. public function save_notification(
  206. $type,
  207. $userList,
  208. $title,
  209. $content,
  210. $senderInfo = array(),
  211. $attachments = array()
  212. ) {
  213. $this->type = intval($type);
  214. $content = $this->formatContent($content, $senderInfo);
  215. $titleToNotification = $this->formatTitle($title, $senderInfo);
  216. $settingToCheck = '';
  217. $avoid_my_self = false;
  218. switch ($this->type) {
  219. case self::NOTIFICATION_TYPE_DIRECT_MESSAGE:
  220. case self::NOTIFICATION_TYPE_MESSAGE:
  221. $settingToCheck = 'mail_notify_message';
  222. $defaultStatus = self::NOTIFY_MESSAGE_AT_ONCE;
  223. break;
  224. case self::NOTIFICATION_TYPE_INVITATION:
  225. $settingToCheck = 'mail_notify_invitation';
  226. $defaultStatus = self::NOTIFY_INVITATION_AT_ONCE;
  227. break;
  228. case self::NOTIFICATION_TYPE_GROUP:
  229. $settingToCheck = 'mail_notify_group_message';
  230. $defaultStatus = self::NOTIFY_GROUP_AT_ONCE;
  231. $avoid_my_self = true;
  232. break;
  233. default:
  234. $defaultStatus = self::NOTIFY_MESSAGE_AT_ONCE;
  235. break;
  236. }
  237. $settingInfo = UserManager::get_extra_field_information_by_name($settingToCheck);
  238. if (!empty($userList)) {
  239. foreach ($userList as $user_id) {
  240. if ($avoid_my_self) {
  241. if ($user_id == api_get_user_id()) {
  242. continue;
  243. }
  244. }
  245. $userInfo = api_get_user_info($user_id);
  246. // Extra field was deleted or removed? Use the default status.
  247. $userSetting = $defaultStatus;
  248. if (!empty($settingInfo)) {
  249. $extra_data = UserManager::get_extra_user_data($user_id);
  250. if (isset($extra_data[$settingToCheck])) {
  251. $userSetting = $extra_data[$settingToCheck];
  252. }
  253. // Means that user extra was not set
  254. // Then send email now.
  255. if ($userSetting === '') {
  256. $userSetting = self::NOTIFY_MESSAGE_AT_ONCE;
  257. }
  258. }
  259. $sendDate = null;
  260. switch ($userSetting) {
  261. // No notifications
  262. case self::NOTIFY_MESSAGE_NO:
  263. case self::NOTIFY_INVITATION_NO:
  264. case self::NOTIFY_GROUP_NO:
  265. break;
  266. // Send notification right now!
  267. case self::NOTIFY_MESSAGE_AT_ONCE:
  268. case self::NOTIFY_INVITATION_AT_ONCE:
  269. case self::NOTIFY_GROUP_AT_ONCE:
  270. $extraHeaders = [];
  271. if (isset($senderInfo['email'])) {
  272. $extraHeaders = array(
  273. 'reply_to' => array(
  274. 'name' => $senderInfo['complete_name'],
  275. 'mail' => $senderInfo['email']
  276. )
  277. );
  278. }
  279. if (!empty($userInfo['email'])) {
  280. api_mail_html(
  281. $userInfo['complete_name'],
  282. $userInfo['mail'],
  283. Security::filter_terms($titleToNotification),
  284. Security::filter_terms($content),
  285. $this->adminName,
  286. $this->adminEmail,
  287. $extraHeaders,
  288. $attachments
  289. );
  290. }
  291. $sendDate = api_get_utc_datetime();
  292. }
  293. // Saving the notification to be sent some day.
  294. $content = cut($content, $this->max_content_length);
  295. $params = array(
  296. 'sent_at' => $sendDate,
  297. 'dest_user_id' => $user_id,
  298. 'dest_mail' => $userInfo['email'],
  299. 'title' => $title,
  300. 'content' => $content,
  301. 'send_freq' => $userSetting
  302. );
  303. $this->save($params);
  304. }
  305. self::sendPushNotification($userList, $title, $content);
  306. }
  307. }
  308. /**
  309. * Formats the content in order to add the welcome message,
  310. * the notification preference, etc
  311. * @param string $content
  312. * @param array $senderInfo result of api_get_user_info() or
  313. * GroupPortalManager:get_group_data()
  314. *
  315. * @return string
  316. * */
  317. public function formatContent($content, $senderInfo)
  318. {
  319. $hook = HookNotificationContent::create();
  320. if (!empty($hook)) {
  321. $hook->setEventData(array('content' => $content));
  322. $data = $hook->notifyNotificationContent(HOOK_EVENT_TYPE_PRE);
  323. if (isset($data['content'])) {
  324. $content = $data['content'];
  325. }
  326. }
  327. $newMessageText = $linkToNewMessage = '';
  328. switch ($this->type) {
  329. case self::NOTIFICATION_TYPE_DIRECT_MESSAGE:
  330. $newMessageText = '';
  331. $linkToNewMessage = Display::url(
  332. get_lang('SeeMessage'),
  333. api_get_path(WEB_CODE_PATH).'messages/inbox.php'
  334. );
  335. break;
  336. case self::NOTIFICATION_TYPE_MESSAGE:
  337. if (!empty($senderInfo)) {
  338. $senderName = api_get_person_name(
  339. $senderInfo['firstname'],
  340. $senderInfo['lastname'],
  341. null,
  342. PERSON_NAME_EMAIL_ADDRESS
  343. );
  344. $newMessageText = sprintf(get_lang('YouHaveANewMessageFromX'), $senderName);
  345. }
  346. $linkToNewMessage = Display::url(
  347. get_lang('SeeMessage'),
  348. api_get_path(WEB_CODE_PATH).'messages/inbox.php'
  349. );
  350. break;
  351. case self::NOTIFICATION_TYPE_INVITATION:
  352. if (!empty($senderInfo)) {
  353. $senderName = api_get_person_name(
  354. $senderInfo['firstname'],
  355. $senderInfo['lastname'],
  356. null,
  357. PERSON_NAME_EMAIL_ADDRESS
  358. );
  359. $newMessageText = sprintf(get_lang('YouHaveANewInvitationFromX'), $senderName);
  360. }
  361. $linkToNewMessage = Display::url(
  362. get_lang('SeeInvitation'),
  363. api_get_path(WEB_CODE_PATH).'social/invitations.php'
  364. );
  365. break;
  366. case self::NOTIFICATION_TYPE_GROUP:
  367. $topic_page = intval($_REQUEST['topics_page_nr']);
  368. if (!empty($senderInfo)) {
  369. $senderName = $senderInfo['group_info']['name'];
  370. $newMessageText = sprintf(get_lang('YouHaveReceivedANewMessageInTheGroupX'), $senderName);
  371. $senderName = api_get_person_name(
  372. $senderInfo['user_info']['firstname'],
  373. $senderInfo['user_info']['lastname'],
  374. null,
  375. PERSON_NAME_EMAIL_ADDRESS
  376. );
  377. $senderName = Display::url(
  378. $senderName,
  379. api_get_path(WEB_CODE_PATH).'social/profile.php?'.$senderInfo['user_info']['user_id']
  380. );
  381. $newMessageText .= '<br />'.get_lang('User').': '.$senderName;
  382. }
  383. $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;
  384. $linkToNewMessage = Display::url(get_lang('SeeMessage'), $group_url);
  385. break;
  386. }
  387. $preference_url = api_get_path(WEB_CODE_PATH).'auth/profile.php';
  388. // You have received a new message text
  389. if (!empty($newMessageText)) {
  390. $content = $newMessageText.'<br /><hr><br />'.$content;
  391. }
  392. // See message with link text
  393. if (!empty($linkToNewMessage) && api_get_setting('allow_message_tool') == 'true') {
  394. $content = $content.'<br /><br />'.$linkToNewMessage;
  395. }
  396. // You have received this message because you are subscribed text
  397. $content = $content.'<br /><hr><i>'.
  398. sprintf(
  399. get_lang('YouHaveReceivedThisNotificationBecauseYouAreSubscribedOrInvolvedInItToChangeYourNotificationPreferencesPleaseClickHereX'),
  400. Display::url($preference_url, $preference_url)
  401. ).'</i>';
  402. if (!empty($hook)) {
  403. $hook->setEventData(array('content' => $content));
  404. $data = $hook->notifyNotificationContent(HOOK_EVENT_TYPE_POST);
  405. if (isset($data['content'])) {
  406. $content = $data['content'];
  407. }
  408. }
  409. return $content;
  410. }
  411. /**
  412. * Send the push notifications to Chamilo Mobile app
  413. * @param array $userIds The IDs of users who will be notified
  414. * @param string $title The notification title
  415. * @param string $content The notification content
  416. * @return int The number of success notifications. Otherwise returns false
  417. */
  418. public static function sendPushNotification(array $userIds, $title, $content)
  419. {
  420. if (api_get_setting('messaging_allow_send_push_notification') !== 'true') {
  421. return false;
  422. }
  423. $gdcApiKey = api_get_setting('messaging_gdc_api_key');
  424. if ($gdcApiKey === false) {
  425. return false;
  426. }
  427. $content = str_replace(['<br>', '<br/>', '<br />'], "\n", $content);
  428. $content = strip_tags($content);
  429. $content = html_entity_decode($content, ENT_QUOTES);
  430. $gcmRegistrationIds = [];
  431. foreach ($userIds as $userId) {
  432. $extraFieldValue = new ExtraFieldValue('user');
  433. $valueInfo = $extraFieldValue->get_values_by_handler_and_field_variable(
  434. $userId,
  435. Rest::EXTRA_FIELD_GCM_REGISTRATION
  436. );
  437. if (empty($valueInfo)) {
  438. continue;
  439. }
  440. $gcmRegistrationIds[] = $valueInfo['value'];
  441. }
  442. if (!$gcmRegistrationIds) {
  443. return 0;
  444. }
  445. $headers = [
  446. 'Authorization: key='.$gdcApiKey,
  447. 'Content-Type: application/json'
  448. ];
  449. $fields = json_encode([
  450. 'registration_ids' => $gcmRegistrationIds,
  451. 'data' => [
  452. 'title' => $title,
  453. 'message' => $content
  454. ]
  455. ]);
  456. $ch = curl_init();
  457. curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
  458. curl_setopt($ch, CURLOPT_POST, true);
  459. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  460. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  461. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  462. curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
  463. $result = curl_exec($ch);
  464. curl_close($ch);
  465. /** @var array $decodedResult */
  466. $decodedResult = json_decode($result, true);
  467. return intval($decodedResult['success']);
  468. }
  469. }