3 * @file include/NotificationsManager.php
4 * @brief Methods for read and write notifications from/to database
5 * or for formatting notifications
8 use Friendica\Core\Pconfig;
9 use Friendica\Core\System;
11 require_once 'include/html2plain.php';
12 require_once 'include/probe.php';
13 require_once 'include/datetime.php';
14 require_once 'include/bbcode.php';
15 require_once 'include/Contact.php';
18 * @brief Methods for read and write notifications from/to database
19 * or for formatting notifications
21 class NotificationsManager {
24 public function __construct() {
29 * @brief set some extra note properties
31 * @param array $notes array of note arrays from db
32 * @return array Copy of input array with added properties
34 * Set some extra properties to note array from db:
35 * - timestamp as int in default TZ
36 * - date_rel : relative date string
37 * - msg_html: message as html string
38 * - msg_plain: message as plain text string
40 private function _set_extra($notes) {
42 foreach($notes as $n) {
43 $local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']);
44 $n['timestamp'] = strtotime($local_time);
45 $n['date_rel'] = relative_date($n['date']);
46 $n['msg_html'] = bbcode($n['msg'], false, false, false, false);
47 $n['msg_plain'] = explode("\n",trim(html2plain($n['msg_html'], 0)))[0];
56 * @brief Get all notifications for local_user()
58 * @param array $filter optional Array "column name"=>value: filter query by columns values
59 * @param string $order optional Space separated list of column to sort by. prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
60 * @param string $limit optional Query limits
62 * @return array of results or false on errors
64 public function getAll($filter = array(), $order="-date", $limit="") {
65 $filter_str = array();
67 foreach($filter as $column => $value) {
68 $filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
70 if (count($filter_str)>0) {
71 $filter_sql = "AND ".implode(" AND ", $filter_str);
74 $aOrder = explode(" ", $order);
76 foreach($aOrder as $o) {
86 $asOrder[] = "$o $dir";
88 $order_sql = implode(", ", $asOrder);
91 $limit = " LIMIT ".$limit;
93 $r = q("SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
97 if (dbm::is_result($r))
98 return $this->_set_extra($r);
104 * @brief Get one note for local_user() by $id value
107 * @return array note values or null if not found
109 public function getByID($id) {
110 $r = q("SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
114 if (dbm::is_result($r)) {
115 return $this->_set_extra($r)[0];
121 * @brief set seen state of $note of local_user()
124 * @param bool $seen optional true or false, default true
125 * @return bool true on success, false on errors
127 public function setSeen($note, $seen = true) {
128 return q("UPDATE `notify` SET `seen` = %d WHERE ( `link` = '%s' OR ( `parent` != 0 AND `parent` = %d AND `otype` = '%s' )) AND `uid` = %d",
130 dbesc($note['link']),
131 intval($note['parent']),
132 dbesc($note['otype']),
138 * @brief set seen state of all notifications of local_user()
140 * @param bool $seen optional true or false. default true
141 * @return bool true on success, false on error
143 public function setAllSeen($seen = true) {
144 return q("UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
151 * @brief List of pages for the Notifications TabBar
153 * @return array with with notifications TabBar data
155 public function getTabs() {
158 'label' => t('System'),
159 'url'=>'notifications/system',
160 'sel'=> (($this->a->argv[1] == 'system') ? 'active' : ''),
161 'id' => 'system-tab',
165 'label' => t('Network'),
166 'url'=>'notifications/network',
167 'sel'=> (($this->a->argv[1] == 'network') ? 'active' : ''),
168 'id' => 'network-tab',
172 'label' => t('Personal'),
173 'url'=>'notifications/personal',
174 'sel'=> (($this->a->argv[1] == 'personal') ? 'active' : ''),
175 'id' => 'personal-tab',
179 'label' => t('Home'),
180 'url' => 'notifications/home',
181 'sel'=> (($this->a->argv[1] == 'home') ? 'active' : ''),
186 'label' => t('Introductions'),
187 'url' => 'notifications/intros',
188 'sel'=> (($this->a->argv[1] == 'intros') ? 'active' : ''),
198 * @brief Format the notification query in an usable array
200 * @param array $notifs The array from the db query
201 * @param string $ident The notifications identifier (e.g. network)
203 * string 'label' => The type of the notification
204 * string 'link' => URL to the source
205 * string 'image' => The avatar image
206 * string 'url' => The profile url of the contact
207 * string 'text' => The notification text
208 * string 'when' => The date of the notification
209 * string 'ago' => T relative date of the notification
210 * bool 'seen' => Is the notification marked as "seen"
212 private function formatNotifs($notifs, $ident = "") {
217 if (dbm::is_result($notifs)) {
219 foreach ($notifs as $it) {
220 // Because we use different db tables for the notification query
221 // we have sometimes $it['unseen'] and sometimes $it['seen].
222 // So we will have to transform $it['unseen']
223 if (array_key_exists('unseen', $it)) {
224 $it['seen'] = ($it['unseen'] > 0 ? false : true);
227 // Depending on the identifier of the notification we need to use different defaults
230 $default_item_label = 'notify';
231 $default_item_link = System::baseUrl(true).'/notify/view/'. $it['id'];
232 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
233 $default_item_url = $it['url'];
234 $default_item_text = strip_tags(bbcode($it['msg']));
235 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['date'], 'r');
236 $default_item_ago = relative_date($it['date']);
240 $default_item_label = 'comment';
241 $default_item_link = System::baseUrl(true).'/display/'.$it['pguid'];
242 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
243 $default_item_url = $it['author-link'];
244 $default_item_text = sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']);
245 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
246 $default_item_ago = relative_date($it['created']);
250 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
251 $default_item_link = System::baseUrl(true).'/display/'.$it['pguid'];
252 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
253 $default_item_url = $it['author-link'];
254 $default_item_text = (($it['id'] == $it['parent'])
255 ? sprintf(t("%s created a new post"), $it['author-name'])
256 : sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']));
257 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
258 $default_item_ago = relative_date($it['created']);
262 // Transform the different types of notification in an usable array
263 switch ($it['verb']){
267 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
268 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
269 'url' => $it['author-link'],
270 'text' => sprintf(t("%s liked %s's post"), $it['author-name'], $it['pname']),
271 'when' => $default_item_when,
272 'ago' => $default_item_ago,
273 'seen' => $it['seen']
277 case ACTIVITY_DISLIKE:
279 'label' => 'dislike',
280 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
281 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
282 'url' => $it['author-link'],
283 'text' => sprintf(t("%s disliked %s's post"), $it['author-name'], $it['pname']),
284 'when' => $default_item_when,
285 'ago' => $default_item_ago,
286 'seen' => $it['seen']
290 case ACTIVITY_ATTEND:
293 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
294 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
295 'url' => $it['author-link'],
296 'text' => sprintf(t("%s is attending %s's event"), $it['author-name'], $it['pname']),
297 'when' => $default_item_when,
298 'ago' => $default_item_ago,
299 'seen' => $it['seen']
303 case ACTIVITY_ATTENDNO:
305 'label' => 'attendno',
306 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
307 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
308 'url' => $it['author-link'],
309 'text' => sprintf( t("%s is not attending %s's event"), $it['author-name'], $it['pname']),
310 'when' => $default_item_when,
311 'ago' => $default_item_ago,
312 'seen' => $it['seen']
316 case ACTIVITY_ATTENDMAYBE:
318 'label' => 'attendmaybe',
319 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
320 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
321 'url' => $it['author-link'],
322 'text' => sprintf(t("%s may attend %s's event"), $it['author-name'], $it['pname']),
323 'when' => $default_item_when,
324 'ago' => $default_item_ago,
325 'seen' => $it['seen']
329 case ACTIVITY_FRIEND:
330 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
331 $obj = parse_xml_string($xmlhead.$it['object']);
332 $it['fname'] = $obj->title;
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 is now friends with %s"), $it['author-name'], $it['fname']),
340 'when' => $default_item_when,
341 'ago' => $default_item_ago,
342 'seen' => $it['seen']
348 'label' => $default_item_label,
349 'link' => $default_item_link,
350 'image' => $default_item_image,
351 'url' => $default_item_url,
352 'text' => $default_item_text,
353 'when' => $default_item_when,
354 'ago' => $default_item_ago,
355 'seen' => $it['seen']
368 * @brief Total number of network notifications
369 * @param int|string $seen
370 * If 0 only include notifications into the query
371 * which aren't marked as "seen"
372 * @return int Number of network notifications
374 private function networkTotal($seen = 0) {
378 $sql_seen = " AND `item`.`unseen` = 1 ";
380 $r = q("SELECT COUNT(*) AS `total`
381 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
382 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
383 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
388 if (dbm::is_result($r))
389 return $r[0]['total'];
395 * @brief Get network notifications
397 * @param int|string $seen
398 * If 0 only include notifications into the query
399 * which aren't marked as "seen"
400 * @param int $start Start the query at this point
401 * @param int $limit Maximum number of query results
404 * string 'ident' => Notification identifier
405 * int 'total' => Total number of available network notifications
406 * array 'notifications' => Network notifications
408 public function networkNotifs($seen = 0, $start = 0, $limit = 80) {
410 $total = $this->networkTotal($seen);
415 $sql_seen = " AND `item`.`unseen` = 1 ";
418 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
419 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
420 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
421 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
422 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
423 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
425 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
426 intval(local_user()),
431 if (dbm::is_result($r))
432 $notifs = $this->formatNotifs($r, $ident);
435 'notifications' => $notifs,
444 * @brief Total number of system notifications
445 * @param int|string $seen
446 * If 0 only include notifications into the query
447 * which aren't marked as "seen"
448 * @return int Number of system notifications
450 private function systemTotal($seen = 0) {
454 $sql_seen = " AND `seen` = 0 ";
456 $r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
460 if (dbm::is_result($r))
461 return $r[0]['total'];
467 * @brief Get system notifications
469 * @param int|string $seen
470 * If 0 only include notifications into the query
471 * which aren't marked as "seen"
472 * @param int $start Start the query at this point
473 * @param int $limit Maximum number of query results
476 * string 'ident' => Notification identifier
477 * int 'total' => Total number of available system notifications
478 * array 'notifications' => System notifications
480 public function systemNotifs($seen = 0, $start = 0, $limit = 80) {
482 $total = $this->systemTotal($seen);
487 $sql_seen = " AND `seen` = 0 ";
489 $r = q("SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
490 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
491 intval(local_user()),
496 if (dbm::is_result($r))
497 $notifs = $this->formatNotifs($r, $ident);
500 'notifications' => $notifs,
509 * @brief Addional SQL query string for the personal notifications
511 * @return string The additional sql query
513 private function _personal_sql_extra() {
514 $myurl = System::baseUrl(true) . '/profile/'. $this->a->user['nickname'];
515 $myurl = substr($myurl,strpos($myurl,'://')+3);
516 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
517 $diasp_url = str_replace('/profile/','/u/',$myurl);
518 $sql_extra = sprintf(" AND ( `item`.`author-link` regexp '%s' OR `item`.`tag` regexp '%s' OR `item`.`tag` regexp '%s' ) ",
520 dbesc($myurl . '\\]'),
521 dbesc($diasp_url . '\\]')
528 * @brief Total number of personal notifications
529 * @param int|string $seen
530 * If 0 only include notifications into the query
531 * which aren't marked as "seen"
532 * @return int Number of personal notifications
534 private function personalTotal($seen = 0) {
536 $sql_extra = $this->_personal_sql_extra();
539 $sql_seen = " AND `item`.`unseen` = 1 ";
541 $r = q("SELECT COUNT(*) AS `total`
542 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
543 WHERE `item`.`visible` = 1
546 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 " ,
550 if (dbm::is_result($r))
551 return $r[0]['total'];
557 * @brief Get personal notifications
559 * @param int|string $seen
560 * If 0 only include notifications into the query
561 * which aren't marked as "seen"
562 * @param int $start Start the query at this point
563 * @param int $limit Maximum number of query results
566 * string 'ident' => Notification identifier
567 * int 'total' => Total number of available personal notifications
568 * array 'notifications' => Personal notifications
570 public function personalNotifs($seen = 0, $start = 0, $limit = 80) {
572 $total = $this->personalTotal($seen);
573 $sql_extra = $this->_personal_sql_extra();
578 $sql_seen = " AND `item`.`unseen` = 1 ";
580 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
581 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
582 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
583 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
584 WHERE `item`.`visible` = 1
587 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
588 ORDER BY `item`.`created` DESC LIMIT %d, %d " ,
589 intval(local_user()),
594 if (dbm::is_result($r))
595 $notifs = $this->formatNotifs($r, $ident);
598 'notifications' => $notifs,
607 * @brief Total number of home notifications
608 * @param int|string $seen
609 * If 0 only include notifications into the query
610 * which aren't marked as "seen"
611 * @return int Number of home notifications
613 private function homeTotal($seen = 0) {
617 $sql_seen = " AND `item`.`unseen` = 1 ";
619 $r = q("SELECT COUNT(*) AS `total` FROM `item`
620 WHERE `item`.`visible` = 1 AND
621 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
626 if (dbm::is_result($r))
627 return $r[0]['total'];
633 * @brief Get home notifications
635 * @param int|string $seen
636 * If 0 only include notifications into the query
637 * which aren't marked as "seen"
638 * @param int $start Start the query at this point
639 * @param int $limit Maximum number of query results
642 * string 'ident' => Notification identifier
643 * int 'total' => Total number of available home notifications
644 * array 'notifications' => Home notifications
646 public function homeNotifs($seen = 0, $start = 0, $limit = 80) {
648 $total = $this->homeTotal($seen);
653 $sql_seen = " AND `item`.`unseen` = 1 ";
655 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
656 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
657 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
658 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
659 WHERE `item`.`visible` = 1 AND
660 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
662 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
663 intval(local_user()),
668 if (dbm::is_result($r))
669 $notifs = $this->formatNotifs($r, $ident);
672 'notifications' => $notifs,
681 * @brief Total number of introductions
683 * If false only include introductions into the query
684 * which aren't marked as ignored
685 * @return int Number of introductions
687 private function introTotal($all = false) {
691 $sql_extra = " AND `ignore` = 0 ";
693 $r = q("SELECT COUNT(*) AS `total` FROM `intro`
694 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
695 intval($_SESSION['uid'])
698 if (dbm::is_result($r))
699 return $r[0]['total'];
705 * @brief Get introductions
708 * If false only include introductions into the query
709 * which aren't marked as ignored
710 * @param int $start Start the query at this point
711 * @param int $limit Maximum number of query results
714 * string 'ident' => Notification identifier
715 * int 'total' => Total number of available introductions
716 * array 'notifications' => Introductions
718 public function introNotifs($all = false, $start = 0, $limit = 80) {
719 $ident = 'introductions';
720 $total = $this->introTotal($seen);
725 $sql_extra = " AND `ignore` = 0 ";
727 /// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact
728 $r = q("SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
729 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`,
730 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
731 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
732 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
733 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
735 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
736 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
737 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
738 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
740 intval($_SESSION['uid']),
745 if (dbm::is_result($r))
746 $notifs = $this->formatIntros($r);
751 'notifications' => $notifs,
758 * @brief Format the notification query in an usable array
760 * @param array $intros The array from the db query
761 * @return array with the introductions
763 private function formatIntros($intros) {
766 foreach($intros as $it) {
767 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
768 // We have to distinguish between these two because they use different data.
770 // Contact suggestions
773 $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
776 'label' => 'friend_suggestion',
777 'notify_type' => t('Friend Suggestion'),
778 'intro_id' => $it['intro_id'],
779 'madeby' => $it['name'],
780 'contact_id' => $it['contact-id'],
781 'photo' => ((x($it,'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
782 'name' => $it['fname'],
783 'url' => zrl($it['furl']),
784 'hidden' => $it['hidden'] == 1,
785 'post_newfriend' => (intval(PConfig::get(local_user(),'system','post_newfriend')) ? '1' : 0),
787 'knowyou' => $knowyou,
788 'note' => $it['note'],
789 'request' => $it['frequest'] . '?addr=' . $return_addr,
793 // Normal connection requests
796 $it = $this->getMissingIntroData($it);
798 // Don't show these data until you are connected. Diaspora is doing the same.
799 if($it['gnetwork'] === NETWORK_DIASPORA) {
800 $it['glocation'] = "";
805 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
806 'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? t('Friend/Connect Request') : t('New Follower')),
807 'dfrn_id' => $it['issued-id'],
808 'uid' => $_SESSION['uid'],
809 'intro_id' => $it['intro_id'],
810 'contact_id' => $it['contact-id'],
811 'photo' => ((x($it,'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
812 'name' => $it['name'],
813 'location' => bbcode($it['glocation'], false, false),
814 'about' => bbcode($it['gabout'], false, false),
815 'keywords' => $it['gkeywords'],
816 'gender' => $it['ggender'],
817 'hidden' => $it['hidden'] == 1,
818 'post_newfriend' => (intval(PConfig::get(local_user(),'system','post_newfriend')) ? '1' : 0),
820 'zrl' => zrl($it['url']),
821 'addr' => $it['gaddr'],
822 'network' => $it['gnetwork'],
823 'knowyou' => $it['knowyou'],
824 'note' => $it['note'],
835 * @brief Check for missing contact data and try to fetch the data from
838 * @param array $arr The input array with the intro data
840 * @return array The array with the intro data
842 private function getMissingIntroData($arr) {
843 // If the network and the addr isn't available from the gcontact
844 // table entry, take the one of the contact table entry
845 if ($arr['gnetwork'] == "") {
846 $arr['gnetwork'] = $arr['network'];
848 if ($arr['gaddr'] == "") {
849 $arr['gaddr'] = $arr['addr'];
852 // If the network and addr is still not available
853 // get the missing data data from other sources
854 if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
855 $ret = get_contact_details_by_url($arr['url']);
857 if ($arr['gnetwork'] == "" && $ret['network'] != "") {
858 $arr['gnetwork'] = $ret['network'];
860 if ($arr['gaddr'] == "" && $ret['addr'] != "") {
861 $arr['gaddr'] = $ret['addr'];