3 * @file src/Core/NotificationsManager.php
4 * @brief Methods for read and write notifications from/to database
5 * or for formatting notifications
7 namespace Friendica\Core;
9 use Friendica\Core\Pconfig;
10 use Friendica\Core\System;
11 use Friendica\Database\DBM;
12 use Friendica\Object\Contact;
14 require_once 'include/html2plain.php';
15 require_once 'include/datetime.php';
16 require_once 'include/bbcode.php';
19 * @brief Methods for read and write notifications from/to database
20 * or for formatting notifications
22 class NotificationsManager
29 public function __construct()
35 * @brief set some extra note properties
37 * @param array $notes array of note arrays from db
38 * @return array Copy of input array with added properties
40 * Set some extra properties to note array from db:
41 * - timestamp as int in default TZ
42 * - date_rel : relative date string
43 * - msg_html: message as html string
44 * - msg_plain: message as plain text string
46 private function _set_extra($notes)
49 foreach ($notes as $n) {
50 $local_time = datetime_convert('UTC', date_default_timezone_get(), $n['date']);
51 $n['timestamp'] = strtotime($local_time);
52 $n['date_rel'] = relative_date($n['date']);
53 $n['msg_html'] = bbcode($n['msg'], false, false, false, false);
54 $n['msg_plain'] = explode("\n", trim(html2plain($n['msg_html'], 0)))[0];
63 * @brief Get all notifications for local_user()
65 * @param array $filter optional Array "column name"=>value: filter query by columns values
66 * @param string $order optional Space separated list of column to sort by.
67 * Prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
68 * @param string $limit optional Query limits
70 * @return array of results or false on errors
72 public function getAll($filter = array(), $order = "-date", $limit = "")
74 $filter_str = array();
76 foreach ($filter as $column => $value) {
77 $filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
79 if (count($filter_str)>0) {
80 $filter_sql = "AND ".implode(" AND ", $filter_str);
83 $aOrder = explode(" ", $order);
85 foreach ($aOrder as $o) {
95 $asOrder[] = "$o $dir";
97 $order_sql = implode(", ", $asOrder);
100 $limit = " LIMIT ".$limit;
103 "SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
107 if (DBM::is_result($r)) {
108 return $this->_set_extra($r);
115 * @brief Get one note for local_user() by $id value
117 * @param int $id identity
118 * @return array note values or null if not found
120 public function getByID($id)
123 "SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
127 if (DBM::is_result($r)) {
128 return $this->_set_extra($r)[0];
134 * @brief set seen state of $note of local_user()
136 * @param array $note note array
137 * @param bool $seen optional true or false, default true
138 * @return bool true on success, false on errors
140 public function setSeen($note, $seen = true)
143 "UPDATE `notify` SET `seen` = %d WHERE ( `link` = '%s' OR ( `parent` != 0 AND `parent` = %d AND `otype` = '%s' )) AND `uid` = %d",
145 dbesc($note['link']),
146 intval($note['parent']),
147 dbesc($note['otype']),
153 * @brief set seen state of all notifications of local_user()
155 * @param bool $seen optional true or false. default true
156 * @return bool true on success, false on error
158 public function setAllSeen($seen = true)
161 "UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
168 * @brief List of pages for the Notifications TabBar
170 * @return array with with notifications TabBar data
172 public function getTabs()
176 'label' => t('System'),
177 'url'=>'notifications/system',
178 'sel'=> (($this->a->argv[1] == 'system') ? 'active' : ''),
179 'id' => 'system-tab',
183 'label' => t('Network'),
184 'url'=>'notifications/network',
185 'sel'=> (($this->a->argv[1] == 'network') ? 'active' : ''),
186 'id' => 'network-tab',
190 'label' => t('Personal'),
191 'url'=>'notifications/personal',
192 'sel'=> (($this->a->argv[1] == 'personal') ? 'active' : ''),
193 'id' => 'personal-tab',
197 'label' => t('Home'),
198 'url' => 'notifications/home',
199 'sel'=> (($this->a->argv[1] == 'home') ? 'active' : ''),
204 'label' => t('Introductions'),
205 'url' => 'notifications/intros',
206 'sel'=> (($this->a->argv[1] == 'intros') ? 'active' : ''),
216 * @brief Format the notification query in an usable array
218 * @param array $notifs The array from the db query
219 * @param string $ident The notifications identifier (e.g. network)
221 * string 'label' => The type of the notification
222 * string 'link' => URL to the source
223 * string 'image' => The avatar image
224 * string 'url' => The profile url of the contact
225 * string 'text' => The notification text
226 * string 'when' => The date of the notification
227 * string 'ago' => T relative date of the notification
228 * bool 'seen' => Is the notification marked as "seen"
230 private function formatNotifs($notifs, $ident = "")
235 if (DBM::is_result($notifs)) {
236 foreach ($notifs as $it) {
237 // Because we use different db tables for the notification query
238 // we have sometimes $it['unseen'] and sometimes $it['seen].
239 // So we will have to transform $it['unseen']
240 if (array_key_exists('unseen', $it)) {
241 $it['seen'] = ($it['unseen'] > 0 ? false : true);
244 // Depending on the identifier of the notification we need to use different defaults
247 $default_item_label = 'notify';
248 $default_item_link = System::baseUrl(true).'/notify/view/'. $it['id'];
249 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
250 $default_item_url = $it['url'];
251 $default_item_text = strip_tags(bbcode($it['msg']));
252 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['date'], 'r');
253 $default_item_ago = relative_date($it['date']);
257 $default_item_label = 'comment';
258 $default_item_link = System::baseUrl(true).'/display/'.$it['pguid'];
259 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
260 $default_item_url = $it['author-link'];
261 $default_item_text = sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']);
262 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
263 $default_item_ago = relative_date($it['created']);
267 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
268 $default_item_link = System::baseUrl(true).'/display/'.$it['pguid'];
269 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
270 $default_item_url = $it['author-link'];
271 $default_item_text = (($it['id'] == $it['parent'])
272 ? sprintf(t("%s created a new post"), $it['author-name'])
273 : sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']));
274 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
275 $default_item_ago = relative_date($it['created']);
278 // Transform the different types of notification in an usable array
279 switch ($it['verb']) {
283 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
284 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
285 'url' => $it['author-link'],
286 'text' => sprintf(t("%s liked %s's post"), $it['author-name'], $it['pname']),
287 'when' => $default_item_when,
288 'ago' => $default_item_ago,
289 'seen' => $it['seen']
293 case ACTIVITY_DISLIKE:
295 'label' => 'dislike',
296 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
297 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
298 'url' => $it['author-link'],
299 'text' => sprintf(t("%s disliked %s's post"), $it['author-name'], $it['pname']),
300 'when' => $default_item_when,
301 'ago' => $default_item_ago,
302 'seen' => $it['seen']
306 case ACTIVITY_ATTEND:
309 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
310 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
311 'url' => $it['author-link'],
312 'text' => sprintf(t("%s is attending %s's event"), $it['author-name'], $it['pname']),
313 'when' => $default_item_when,
314 'ago' => $default_item_ago,
315 'seen' => $it['seen']
319 case ACTIVITY_ATTENDNO:
321 'label' => 'attendno',
322 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
323 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
324 'url' => $it['author-link'],
325 'text' => sprintf(t("%s is not attending %s's event"), $it['author-name'], $it['pname']),
326 'when' => $default_item_when,
327 'ago' => $default_item_ago,
328 'seen' => $it['seen']
332 case ACTIVITY_ATTENDMAYBE:
334 'label' => 'attendmaybe',
335 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
336 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
337 'url' => $it['author-link'],
338 'text' => sprintf(t("%s may attend %s's event"), $it['author-name'], $it['pname']),
339 'when' => $default_item_when,
340 'ago' => $default_item_ago,
341 'seen' => $it['seen']
345 case ACTIVITY_FRIEND:
346 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
347 $obj = parse_xml_string($xmlhead.$it['object']);
348 $it['fname'] = $obj->title;
352 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
353 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
354 'url' => $it['author-link'],
355 'text' => sprintf(t("%s is now friends with %s"), $it['author-name'], $it['fname']),
356 'when' => $default_item_when,
357 'ago' => $default_item_ago,
358 'seen' => $it['seen']
364 'label' => $default_item_label,
365 'link' => $default_item_link,
366 'image' => $default_item_image,
367 'url' => $default_item_url,
368 'text' => $default_item_text,
369 'when' => $default_item_when,
370 'ago' => $default_item_ago,
371 'seen' => $it['seen']
383 * @brief Total number of network notifications
384 * @param int|string $seen If 0 only include notifications into the query
385 * which aren't marked as "seen"
387 * @return int Number of network notifications
389 private function networkTotal($seen = 0)
394 $sql_seen = " AND `item`.`unseen` = 1 ";
398 "SELECT COUNT(*) AS `total`
399 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
400 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
401 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
406 if (DBM::is_result($r)) {
407 return $r[0]['total'];
414 * @brief Get network notifications
416 * @param int|string $seen If 0 only include notifications into the query
417 * which aren't marked as "seen"
418 * @param int $start Start the query at this point
419 * @param int $limit Maximum number of query results
422 * string 'ident' => Notification identifier
423 * int 'total' => Total number of available network notifications
424 * array 'notifications' => Network notifications
426 public function networkNotifs($seen = 0, $start = 0, $limit = 80)
429 $total = $this->networkTotal($seen);
434 $sql_seen = " AND `item`.`unseen` = 1 ";
439 "SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
440 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
441 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
442 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
443 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
444 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
446 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
447 intval(local_user()),
452 if (DBM::is_result($r)) {
453 $notifs = $this->formatNotifs($r, $ident);
457 'notifications' => $notifs,
466 * @brief Total number of system notifications
467 * @param int|string $seen If 0 only include notifications into the query
468 * which aren't marked as "seen"
470 * @return int Number of system notifications
472 private function systemTotal($seen = 0)
477 $sql_seen = " AND `seen` = 0 ";
481 "SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
485 if (DBM::is_result($r)) {
486 return $r[0]['total'];
493 * @brief Get system notifications
495 * @param int|string $seen If 0 only include notifications into the query
496 * which aren't marked as "seen"
497 * @param int $start Start the query at this point
498 * @param int $limit Maximum number of query results
501 * string 'ident' => Notification identifier
502 * int 'total' => Total number of available system notifications
503 * array 'notifications' => System notifications
505 public function systemNotifs($seen = 0, $start = 0, $limit = 80)
508 $total = $this->systemTotal($seen);
513 $sql_seen = " AND `seen` = 0 ";
517 "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
518 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
519 intval(local_user()),
524 if (DBM::is_result($r)) {
525 $notifs = $this->formatNotifs($r, $ident);
529 'notifications' => $notifs,
538 * @brief Addional SQL query string for the personal notifications
540 * @return string The additional sql query
542 private function personalSqlExtra()
544 $myurl = System::baseUrl(true) . '/profile/'. $this->a->user['nickname'];
545 $myurl = substr($myurl, strpos($myurl, '://') + 3);
546 $myurl = str_replace(array('www.','.'), array('','\\.'), $myurl);
547 $diasp_url = str_replace('/profile/', '/u/', $myurl);
548 $sql_extra = sprintf(
549 " AND ( `item`.`author-link` regexp '%s' OR `item`.`tag` regexp '%s' OR `item`.`tag` regexp '%s' ) ",
551 dbesc($myurl . '\\]'),
552 dbesc($diasp_url . '\\]')
559 * @brief Total number of personal notifications
560 * @param int|string $seen If 0 only include notifications into the query
561 * which aren't marked as "seen"
563 * @return int Number of personal notifications
565 private function personalTotal($seen = 0)
568 $sql_extra = $this->personalSqlExtra();
571 $sql_seen = " AND `item`.`unseen` = 1 ";
575 "SELECT COUNT(*) AS `total`
576 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
577 WHERE `item`.`visible` = 1
580 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 ",
584 if (DBM::is_result($r)) {
585 return $r[0]['total'];
592 * @brief Get personal notifications
594 * @param int|string $seen If 0 only include notifications into the query
595 * which aren't marked as "seen"
596 * @param int $start Start the query at this point
597 * @param int $limit Maximum number of query results
600 * string 'ident' => Notification identifier
601 * int 'total' => Total number of available personal notifications
602 * array 'notifications' => Personal notifications
604 public function personalNotifs($seen = 0, $start = 0, $limit = 80)
607 $total = $this->personalTotal($seen);
608 $sql_extra = $this->personalSqlExtra();
613 $sql_seen = " AND `item`.`unseen` = 1 ";
617 "SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
618 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
619 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
620 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
621 WHERE `item`.`visible` = 1
624 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
625 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
626 intval(local_user()),
631 if (DBM::is_result($r)) {
632 $notifs = $this->formatNotifs($r, $ident);
636 'notifications' => $notifs,
645 * @brief Total number of home notifications
646 * @param int|string $seen If 0 only include notifications into the query
647 * which aren't marked as "seen"
649 * @return int Number of home notifications
651 private function homeTotal($seen = 0)
656 $sql_seen = " AND `item`.`unseen` = 1 ";
660 "SELECT COUNT(*) AS `total` FROM `item`
661 WHERE `item`.`visible` = 1 AND
662 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
667 if (DBM::is_result($r)) {
668 return $r[0]['total'];
675 * @brief Get home notifications
677 * @param int|string $seen If 0 only include notifications into the query
678 * which aren't marked as "seen"
679 * @param int $start Start the query at this point
680 * @param int $limit Maximum number of query results
683 * string 'ident' => Notification identifier
684 * int 'total' => Total number of available home notifications
685 * array 'notifications' => Home notifications
687 public function homeNotifs($seen = 0, $start = 0, $limit = 80)
690 $total = $this->homeTotal($seen);
695 $sql_seen = " AND `item`.`unseen` = 1 ";
699 "SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
700 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
701 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
702 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
703 WHERE `item`.`visible` = 1 AND
704 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
706 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
707 intval(local_user()),
712 if (DBM::is_result($r)) {
713 $notifs = $this->formatNotifs($r, $ident);
717 'notifications' => $notifs,
726 * @brief Total number of introductions
727 * @param bool $all If false only include introductions into the query
728 * which aren't marked as ignored
730 * @return int Number of introductions
732 private function introTotal($all = false)
737 $sql_extra = " AND `ignore` = 0 ";
741 "SELECT COUNT(*) AS `total` FROM `intro`
742 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
743 intval($_SESSION['uid'])
746 if (DBM::is_result($r)) {
747 return $r[0]['total'];
754 * @brief Get introductions
756 * @param bool $all If false only include introductions into the query
757 * which aren't marked as ignored
758 * @param int $start Start the query at this point
759 * @param int $limit Maximum number of query results
762 * string 'ident' => Notification identifier
763 * int 'total' => Total number of available introductions
764 * array 'notifications' => Introductions
766 public function introNotifs($all = false, $start = 0, $limit = 80)
768 $ident = 'introductions';
769 $total = $this->introTotal($seen);
774 $sql_extra = " AND `ignore` = 0 ";
777 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
779 "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
780 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`,
781 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
782 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
783 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
784 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
786 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
787 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
788 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
789 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
791 intval($_SESSION['uid']),
796 if (DBM::is_result($r)) {
797 $notifs = $this->formatIntros($r);
803 'notifications' => $notifs,
810 * @brief Format the notification query in an usable array
812 * @param array $intros The array from the db query
813 * @return array with the introductions
815 private function formatIntros($intros)
819 foreach ($intros as $it) {
820 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
821 // We have to distinguish between these two because they use different data.
823 // Contact suggestions
825 $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
828 'label' => 'friend_suggestion',
829 'notify_type' => t('Friend Suggestion'),
830 'intro_id' => $it['intro_id'],
831 'madeby' => $it['name'],
832 'contact_id' => $it['contact-id'],
833 'photo' => ((x($it, 'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
834 'name' => $it['fname'],
835 'url' => zrl($it['furl']),
836 'hidden' => $it['hidden'] == 1,
837 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
838 'knowyou' => $knowyou,
839 'note' => $it['note'],
840 'request' => $it['frequest'] . '?addr=' . $return_addr,
844 // Normal connection requests
846 $it = $this->getMissingIntroData($it);
848 // Don't show these data until you are connected. Diaspora is doing the same.
849 if ($it['gnetwork'] === NETWORK_DIASPORA) {
850 $it['glocation'] = "";
855 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
856 'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? t('Friend/Connect Request') : t('New Follower')),
857 'dfrn_id' => $it['issued-id'],
858 'uid' => $_SESSION['uid'],
859 'intro_id' => $it['intro_id'],
860 'contact_id' => $it['contact-id'],
861 'photo' => ((x($it, 'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
862 'name' => $it['name'],
863 'location' => bbcode($it['glocation'], false, false),
864 'about' => bbcode($it['gabout'], false, false),
865 'keywords' => $it['gkeywords'],
866 'gender' => $it['ggender'],
867 'hidden' => $it['hidden'] == 1,
868 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
870 'zrl' => zrl($it['url']),
871 'addr' => $it['gaddr'],
872 'network' => $it['gnetwork'],
873 'knowyou' => $it['knowyou'],
874 'note' => $it['note'],
885 * @brief Check for missing contact data and try to fetch the data from
888 * @param array $arr The input array with the intro data
890 * @return array The array with the intro data
892 private function getMissingIntroData($arr)
894 // If the network and the addr isn't available from the gcontact
895 // table entry, take the one of the contact table entry
896 if ($arr['gnetwork'] == "") {
897 $arr['gnetwork'] = $arr['network'];
899 if ($arr['gaddr'] == "") {
900 $arr['gaddr'] = $arr['addr'];
903 // If the network and addr is still not available
904 // get the missing data data from other sources
905 if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
906 $ret = Contact::getDetailsByURL($arr['url']);
908 if ($arr['gnetwork'] == "" && $ret['network'] != "") {
909 $arr['gnetwork'] = $ret['network'];
911 if ($arr['gaddr'] == "" && $ret['addr'] != "") {
912 $arr['gaddr'] = $ret['addr'];