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\Model\Contact;
14 require_once 'include/dba.php';
15 require_once 'include/html2plain.php';
16 require_once 'include/datetime.php';
17 require_once 'include/bbcode.php';
20 * @brief Methods for read and write notifications from/to database
21 * or for formatting notifications
23 class NotificationsManager
30 public function __construct()
36 * @brief set some extra note properties
38 * @param array $notes array of note arrays from db
39 * @return array Copy of input array with added properties
41 * Set some extra properties to note array from db:
42 * - timestamp as int in default TZ
43 * - date_rel : relative date string
44 * - msg_html: message as html string
45 * - msg_plain: message as plain text string
47 private function _set_extra($notes)
50 foreach ($notes as $n) {
51 $local_time = datetime_convert('UTC', date_default_timezone_get(), $n['date']);
52 $n['timestamp'] = strtotime($local_time);
53 $n['date_rel'] = relative_date($n['date']);
54 $n['msg_html'] = bbcode($n['msg'], false, false, false, false);
55 $n['msg_plain'] = explode("\n", trim(html2plain($n['msg_html'], 0)))[0];
64 * @brief Get all notifications for local_user()
66 * @param array $filter optional Array "column name"=>value: filter query by columns values
67 * @param string $order optional Space separated list of column to sort by.
68 * Prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
69 * @param string $limit optional Query limits
71 * @return array of results or false on errors
73 public function getAll($filter = array(), $order = "-date", $limit = "")
75 $filter_str = array();
77 foreach ($filter as $column => $value) {
78 $filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
80 if (count($filter_str)>0) {
81 $filter_sql = "AND ".implode(" AND ", $filter_str);
84 $aOrder = explode(" ", $order);
86 foreach ($aOrder as $o) {
96 $asOrder[] = "$o $dir";
98 $order_sql = implode(", ", $asOrder);
101 $limit = " LIMIT ".$limit;
104 "SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
108 if (DBM::is_result($r)) {
109 return $this->_set_extra($r);
116 * @brief Get one note for local_user() by $id value
118 * @param int $id identity
119 * @return array note values or null if not found
121 public function getByID($id)
124 "SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
128 if (DBM::is_result($r)) {
129 return $this->_set_extra($r)[0];
135 * @brief set seen state of $note of local_user()
137 * @param array $note note array
138 * @param bool $seen optional true or false, default true
139 * @return bool true on success, false on errors
141 public function setSeen($note, $seen = true)
144 "UPDATE `notify` SET `seen` = %d WHERE ( `link` = '%s' OR ( `parent` != 0 AND `parent` = %d AND `otype` = '%s' )) AND `uid` = %d",
146 dbesc($note['link']),
147 intval($note['parent']),
148 dbesc($note['otype']),
154 * @brief set seen state of all notifications of local_user()
156 * @param bool $seen optional true or false. default true
157 * @return bool true on success, false on error
159 public function setAllSeen($seen = true)
162 "UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
169 * @brief List of pages for the Notifications TabBar
171 * @return array with with notifications TabBar data
173 public function getTabs()
177 'label' => t('System'),
178 'url'=>'notifications/system',
179 'sel'=> (($this->a->argv[1] == 'system') ? 'active' : ''),
180 'id' => 'system-tab',
184 'label' => t('Network'),
185 'url'=>'notifications/network',
186 'sel'=> (($this->a->argv[1] == 'network') ? 'active' : ''),
187 'id' => 'network-tab',
191 'label' => t('Personal'),
192 'url'=>'notifications/personal',
193 'sel'=> (($this->a->argv[1] == 'personal') ? 'active' : ''),
194 'id' => 'personal-tab',
198 'label' => t('Home'),
199 'url' => 'notifications/home',
200 'sel'=> (($this->a->argv[1] == 'home') ? 'active' : ''),
205 'label' => t('Introductions'),
206 'url' => 'notifications/intros',
207 'sel'=> (($this->a->argv[1] == 'intros') ? 'active' : ''),
217 * @brief Format the notification query in an usable array
219 * @param array $notifs The array from the db query
220 * @param string $ident The notifications identifier (e.g. network)
222 * string 'label' => The type of the notification
223 * string 'link' => URL to the source
224 * string 'image' => The avatar image
225 * string 'url' => The profile url of the contact
226 * string 'text' => The notification text
227 * string 'when' => The date of the notification
228 * string 'ago' => T relative date of the notification
229 * bool 'seen' => Is the notification marked as "seen"
231 private function formatNotifs($notifs, $ident = "")
236 if (DBM::is_result($notifs)) {
237 foreach ($notifs as $it) {
238 // Because we use different db tables for the notification query
239 // we have sometimes $it['unseen'] and sometimes $it['seen].
240 // So we will have to transform $it['unseen']
241 if (array_key_exists('unseen', $it)) {
242 $it['seen'] = ($it['unseen'] > 0 ? false : true);
245 // Depending on the identifier of the notification we need to use different defaults
248 $default_item_label = 'notify';
249 $default_item_link = System::baseUrl(true).'/notify/view/'. $it['id'];
250 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
251 $default_item_url = $it['url'];
252 $default_item_text = strip_tags(bbcode($it['msg']));
253 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['date'], 'r');
254 $default_item_ago = relative_date($it['date']);
258 $default_item_label = 'comment';
259 $default_item_link = System::baseUrl(true).'/display/'.$it['pguid'];
260 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
261 $default_item_url = $it['author-link'];
262 $default_item_text = sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']);
263 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
264 $default_item_ago = relative_date($it['created']);
268 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
269 $default_item_link = System::baseUrl(true).'/display/'.$it['pguid'];
270 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
271 $default_item_url = $it['author-link'];
272 $default_item_text = (($it['id'] == $it['parent'])
273 ? sprintf(t("%s created a new post"), $it['author-name'])
274 : sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']));
275 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
276 $default_item_ago = relative_date($it['created']);
279 // Transform the different types of notification in an usable array
280 switch ($it['verb']) {
284 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
285 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
286 'url' => $it['author-link'],
287 'text' => sprintf(t("%s liked %s's post"), $it['author-name'], $it['pname']),
288 'when' => $default_item_when,
289 'ago' => $default_item_ago,
290 'seen' => $it['seen']
294 case ACTIVITY_DISLIKE:
296 'label' => 'dislike',
297 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
298 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
299 'url' => $it['author-link'],
300 'text' => sprintf(t("%s disliked %s's post"), $it['author-name'], $it['pname']),
301 'when' => $default_item_when,
302 'ago' => $default_item_ago,
303 'seen' => $it['seen']
307 case ACTIVITY_ATTEND:
310 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
311 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
312 'url' => $it['author-link'],
313 'text' => sprintf(t("%s is attending %s's event"), $it['author-name'], $it['pname']),
314 'when' => $default_item_when,
315 'ago' => $default_item_ago,
316 'seen' => $it['seen']
320 case ACTIVITY_ATTENDNO:
322 'label' => 'attendno',
323 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
324 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
325 'url' => $it['author-link'],
326 'text' => sprintf(t("%s is not attending %s's event"), $it['author-name'], $it['pname']),
327 'when' => $default_item_when,
328 'ago' => $default_item_ago,
329 'seen' => $it['seen']
333 case ACTIVITY_ATTENDMAYBE:
335 'label' => 'attendmaybe',
336 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
337 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
338 'url' => $it['author-link'],
339 'text' => sprintf(t("%s may attend %s's event"), $it['author-name'], $it['pname']),
340 'when' => $default_item_when,
341 'ago' => $default_item_ago,
342 'seen' => $it['seen']
346 case ACTIVITY_FRIEND:
347 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
348 $obj = parse_xml_string($xmlhead.$it['object']);
349 $it['fname'] = $obj->title;
353 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
354 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
355 'url' => $it['author-link'],
356 'text' => sprintf(t("%s is now friends with %s"), $it['author-name'], $it['fname']),
357 'when' => $default_item_when,
358 'ago' => $default_item_ago,
359 'seen' => $it['seen']
365 'label' => $default_item_label,
366 'link' => $default_item_link,
367 'image' => $default_item_image,
368 'url' => $default_item_url,
369 'text' => $default_item_text,
370 'when' => $default_item_when,
371 'ago' => $default_item_ago,
372 'seen' => $it['seen']
384 * @brief Total number of network notifications
385 * @param int|string $seen If 0 only include notifications into the query
386 * which aren't marked as "seen"
388 * @return int Number of network notifications
390 private function networkTotal($seen = 0)
395 $sql_seen = " AND `item`.`unseen` = 1 ";
399 "SELECT COUNT(*) AS `total`
400 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
401 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
402 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
407 if (DBM::is_result($r)) {
408 return $r[0]['total'];
415 * @brief Get network notifications
417 * @param int|string $seen If 0 only include notifications into the query
418 * which aren't marked as "seen"
419 * @param int $start Start the query at this point
420 * @param int $limit Maximum number of query results
423 * string 'ident' => Notification identifier
424 * int 'total' => Total number of available network notifications
425 * array 'notifications' => Network notifications
427 public function networkNotifs($seen = 0, $start = 0, $limit = 80)
430 $total = $this->networkTotal($seen);
435 $sql_seen = " AND `item`.`unseen` = 1 ";
440 "SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
441 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
442 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
443 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
444 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
445 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
447 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
448 intval(local_user()),
453 if (DBM::is_result($r)) {
454 $notifs = $this->formatNotifs($r, $ident);
458 'notifications' => $notifs,
467 * @brief Total number of system notifications
468 * @param int|string $seen If 0 only include notifications into the query
469 * which aren't marked as "seen"
471 * @return int Number of system notifications
473 private function systemTotal($seen = 0)
478 $sql_seen = " AND `seen` = 0 ";
482 "SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
486 if (DBM::is_result($r)) {
487 return $r[0]['total'];
494 * @brief Get system notifications
496 * @param int|string $seen If 0 only include notifications into the query
497 * which aren't marked as "seen"
498 * @param int $start Start the query at this point
499 * @param int $limit Maximum number of query results
502 * string 'ident' => Notification identifier
503 * int 'total' => Total number of available system notifications
504 * array 'notifications' => System notifications
506 public function systemNotifs($seen = 0, $start = 0, $limit = 80)
509 $total = $this->systemTotal($seen);
514 $sql_seen = " AND `seen` = 0 ";
518 "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
519 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
520 intval(local_user()),
525 if (DBM::is_result($r)) {
526 $notifs = $this->formatNotifs($r, $ident);
530 'notifications' => $notifs,
539 * @brief Addional SQL query string for the personal notifications
541 * @return string The additional sql query
543 private function personalSqlExtra()
545 $myurl = System::baseUrl(true) . '/profile/'. $this->a->user['nickname'];
546 $myurl = substr($myurl, strpos($myurl, '://') + 3);
547 $myurl = str_replace(array('www.','.'), array('','\\.'), $myurl);
548 $diasp_url = str_replace('/profile/', '/u/', $myurl);
549 $sql_extra = sprintf(
550 " AND ( `item`.`author-link` regexp '%s' OR `item`.`tag` regexp '%s' OR `item`.`tag` regexp '%s' ) ",
552 dbesc($myurl . '\\]'),
553 dbesc($diasp_url . '\\]')
560 * @brief Total number of personal notifications
561 * @param int|string $seen If 0 only include notifications into the query
562 * which aren't marked as "seen"
564 * @return int Number of personal notifications
566 private function personalTotal($seen = 0)
569 $sql_extra = $this->personalSqlExtra();
572 $sql_seen = " AND `item`.`unseen` = 1 ";
576 "SELECT COUNT(*) AS `total`
577 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
578 WHERE `item`.`visible` = 1
581 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 ",
585 if (DBM::is_result($r)) {
586 return $r[0]['total'];
593 * @brief Get personal notifications
595 * @param int|string $seen If 0 only include notifications into the query
596 * which aren't marked as "seen"
597 * @param int $start Start the query at this point
598 * @param int $limit Maximum number of query results
601 * string 'ident' => Notification identifier
602 * int 'total' => Total number of available personal notifications
603 * array 'notifications' => Personal notifications
605 public function personalNotifs($seen = 0, $start = 0, $limit = 80)
608 $total = $this->personalTotal($seen);
609 $sql_extra = $this->personalSqlExtra();
614 $sql_seen = " AND `item`.`unseen` = 1 ";
618 "SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
619 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
620 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
621 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
622 WHERE `item`.`visible` = 1
625 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
626 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
627 intval(local_user()),
632 if (DBM::is_result($r)) {
633 $notifs = $this->formatNotifs($r, $ident);
637 'notifications' => $notifs,
646 * @brief Total number of home notifications
647 * @param int|string $seen If 0 only include notifications into the query
648 * which aren't marked as "seen"
650 * @return int Number of home notifications
652 private function homeTotal($seen = 0)
657 $sql_seen = " AND `item`.`unseen` = 1 ";
661 "SELECT COUNT(*) AS `total` FROM `item`
662 WHERE `item`.`visible` = 1 AND
663 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
668 if (DBM::is_result($r)) {
669 return $r[0]['total'];
676 * @brief Get home notifications
678 * @param int|string $seen If 0 only include notifications into the query
679 * which aren't marked as "seen"
680 * @param int $start Start the query at this point
681 * @param int $limit Maximum number of query results
684 * string 'ident' => Notification identifier
685 * int 'total' => Total number of available home notifications
686 * array 'notifications' => Home notifications
688 public function homeNotifs($seen = 0, $start = 0, $limit = 80)
691 $total = $this->homeTotal($seen);
696 $sql_seen = " AND `item`.`unseen` = 1 ";
700 "SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
701 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
702 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
703 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
704 WHERE `item`.`visible` = 1 AND
705 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
707 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
708 intval(local_user()),
713 if (DBM::is_result($r)) {
714 $notifs = $this->formatNotifs($r, $ident);
718 'notifications' => $notifs,
727 * @brief Total number of introductions
728 * @param bool $all If false only include introductions into the query
729 * which aren't marked as ignored
731 * @return int Number of introductions
733 private function introTotal($all = false)
738 $sql_extra = " AND `ignore` = 0 ";
742 "SELECT COUNT(*) AS `total` FROM `intro`
743 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
744 intval($_SESSION['uid'])
747 if (DBM::is_result($r)) {
748 return $r[0]['total'];
755 * @brief Get introductions
757 * @param bool $all If false only include introductions into the query
758 * which aren't marked as ignored
759 * @param int $start Start the query at this point
760 * @param int $limit Maximum number of query results
763 * string 'ident' => Notification identifier
764 * int 'total' => Total number of available introductions
765 * array 'notifications' => Introductions
767 public function introNotifs($all = false, $start = 0, $limit = 80)
769 $ident = 'introductions';
770 $total = $this->introTotal($all);
775 $sql_extra = " AND `ignore` = 0 ";
778 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
780 "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
781 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`,
782 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
783 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
784 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
785 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
787 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
788 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
789 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
790 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
792 intval($_SESSION['uid']),
797 if (DBM::is_result($r)) {
798 $notifs = $this->formatIntros($r);
804 'notifications' => $notifs,
811 * @brief Format the notification query in an usable array
813 * @param array $intros The array from the db query
814 * @return array with the introductions
816 private function formatIntros($intros)
820 foreach ($intros as $it) {
821 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
822 // We have to distinguish between these two because they use different data.
824 // Contact suggestions
826 $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
829 'label' => 'friend_suggestion',
830 'notify_type' => t('Friend Suggestion'),
831 'intro_id' => $it['intro_id'],
832 'madeby' => $it['name'],
833 'contact_id' => $it['contact-id'],
834 'photo' => ((x($it, 'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
835 'name' => $it['fname'],
836 'url' => zrl($it['furl']),
837 'hidden' => $it['hidden'] == 1,
838 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
839 'knowyou' => $knowyou,
840 'note' => $it['note'],
841 'request' => $it['frequest'] . '?addr=' . $return_addr,
845 // Normal connection requests
847 $it = $this->getMissingIntroData($it);
849 // Don't show these data until you are connected. Diaspora is doing the same.
850 if ($it['gnetwork'] === NETWORK_DIASPORA) {
851 $it['glocation'] = "";
856 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
857 'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? t('Friend/Connect Request') : t('New Follower')),
858 'dfrn_id' => $it['issued-id'],
859 'uid' => $_SESSION['uid'],
860 'intro_id' => $it['intro_id'],
861 'contact_id' => $it['contact-id'],
862 'photo' => ((x($it, 'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
863 'name' => $it['name'],
864 'location' => bbcode($it['glocation'], false, false),
865 'about' => bbcode($it['gabout'], false, false),
866 'keywords' => $it['gkeywords'],
867 'gender' => $it['ggender'],
868 'hidden' => $it['hidden'] == 1,
869 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
871 'zrl' => zrl($it['url']),
872 'addr' => $it['gaddr'],
873 'network' => $it['gnetwork'],
874 'knowyou' => $it['knowyou'],
875 'note' => $it['note'],
886 * @brief Check for missing contact data and try to fetch the data from
889 * @param array $arr The input array with the intro data
891 * @return array The array with the intro data
893 private function getMissingIntroData($arr)
895 // If the network and the addr isn't available from the gcontact
896 // table entry, take the one of the contact table entry
897 if ($arr['gnetwork'] == "") {
898 $arr['gnetwork'] = $arr['network'];
900 if ($arr['gaddr'] == "") {
901 $arr['gaddr'] = $arr['addr'];
904 // If the network and addr is still not available
905 // get the missing data data from other sources
906 if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
907 $ret = Contact::getDetailsByURL($arr['url']);
909 if ($arr['gnetwork'] == "" && $ret['network'] != "") {
910 $arr['gnetwork'] = $ret['network'];
912 if ($arr['gaddr'] == "" && $ret['addr'] != "") {
913 $arr['gaddr'] = $ret['addr'];