2 namespace Friendica\Core;
4 * @file src/Core/NotificationsManager.php
5 * @brief Methods for read and write notifications from/to database
6 * or for formatting notifications
9 use Friendica\Core\Pconfig;
10 use Friendica\Core\System;
11 use Friendica\Database\DBM;
13 require_once 'include/html2plain.php';
14 require_once 'include/datetime.php';
15 require_once 'include/bbcode.php';
16 require_once 'include/Contact.php';
19 * @brief Methods for read and write notifications from/to database
20 * or for formatting notifications
22 class NotificationsManager {
25 public function __construct() {
30 * @brief set some extra note properties
32 * @param array $notes array of note arrays from db
33 * @return array Copy of input array with added properties
35 * Set some extra properties to note array from db:
36 * - timestamp as int in default TZ
37 * - date_rel : relative date string
38 * - msg_html: message as html string
39 * - msg_plain: message as plain text string
41 private function _set_extra($notes) {
43 foreach($notes as $n) {
44 $local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']);
45 $n['timestamp'] = strtotime($local_time);
46 $n['date_rel'] = relative_date($n['date']);
47 $n['msg_html'] = bbcode($n['msg'], false, false, false, false);
48 $n['msg_plain'] = explode("\n",trim(html2plain($n['msg_html'], 0)))[0];
57 * @brief Get all notifications for local_user()
59 * @param array $filter optional Array "column name"=>value: filter query by columns values
60 * @param string $order optional Space separated list of column to sort by. prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
61 * @param string $limit optional Query limits
63 * @return array of results or false on errors
65 public function getAll($filter = array(), $order="-date", $limit="") {
66 $filter_str = array();
68 foreach($filter as $column => $value) {
69 $filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
71 if (count($filter_str)>0) {
72 $filter_sql = "AND ".implode(" AND ", $filter_str);
75 $aOrder = explode(" ", $order);
77 foreach($aOrder as $o) {
87 $asOrder[] = "$o $dir";
89 $order_sql = implode(", ", $asOrder);
92 $limit = " LIMIT ".$limit;
94 $r = q("SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
98 if (DBM::is_result($r))
99 return $this->_set_extra($r);
105 * @brief Get one note for local_user() by $id value
108 * @return array note values or null if not found
110 public function getByID($id) {
111 $r = q("SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
115 if (DBM::is_result($r)) {
116 return $this->_set_extra($r)[0];
122 * @brief set seen state of $note of local_user()
125 * @param bool $seen optional true or false, default true
126 * @return bool true on success, false on errors
128 public function setSeen($note, $seen = true) {
129 return q("UPDATE `notify` SET `seen` = %d WHERE ( `link` = '%s' OR ( `parent` != 0 AND `parent` = %d AND `otype` = '%s' )) AND `uid` = %d",
131 dbesc($note['link']),
132 intval($note['parent']),
133 dbesc($note['otype']),
139 * @brief set seen state of all notifications of local_user()
141 * @param bool $seen optional true or false. default true
142 * @return bool true on success, false on error
144 public function setAllSeen($seen = true) {
145 return q("UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
152 * @brief List of pages for the Notifications TabBar
154 * @return array with with notifications TabBar data
156 public function getTabs() {
159 'label' => t('System'),
160 'url'=>'notifications/system',
161 'sel'=> (($this->a->argv[1] == 'system') ? 'active' : ''),
162 'id' => 'system-tab',
166 'label' => t('Network'),
167 'url'=>'notifications/network',
168 'sel'=> (($this->a->argv[1] == 'network') ? 'active' : ''),
169 'id' => 'network-tab',
173 'label' => t('Personal'),
174 'url'=>'notifications/personal',
175 'sel'=> (($this->a->argv[1] == 'personal') ? 'active' : ''),
176 'id' => 'personal-tab',
180 'label' => t('Home'),
181 'url' => 'notifications/home',
182 'sel'=> (($this->a->argv[1] == 'home') ? 'active' : ''),
187 'label' => t('Introductions'),
188 'url' => 'notifications/intros',
189 'sel'=> (($this->a->argv[1] == 'intros') ? 'active' : ''),
199 * @brief Format the notification query in an usable array
201 * @param array $notifs The array from the db query
202 * @param string $ident The notifications identifier (e.g. network)
204 * string 'label' => The type of the notification
205 * string 'link' => URL to the source
206 * string 'image' => The avatar image
207 * string 'url' => The profile url of the contact
208 * string 'text' => The notification text
209 * string 'when' => The date of the notification
210 * string 'ago' => T relative date of the notification
211 * bool 'seen' => Is the notification marked as "seen"
213 private function formatNotifs($notifs, $ident = "") {
218 if (DBM::is_result($notifs)) {
220 foreach ($notifs as $it) {
221 // Because we use different db tables for the notification query
222 // we have sometimes $it['unseen'] and sometimes $it['seen].
223 // So we will have to transform $it['unseen']
224 if (array_key_exists('unseen', $it)) {
225 $it['seen'] = ($it['unseen'] > 0 ? false : true);
228 // Depending on the identifier of the notification we need to use different defaults
231 $default_item_label = 'notify';
232 $default_item_link = System::baseUrl(true).'/notify/view/'. $it['id'];
233 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
234 $default_item_url = $it['url'];
235 $default_item_text = strip_tags(bbcode($it['msg']));
236 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['date'], 'r');
237 $default_item_ago = relative_date($it['date']);
241 $default_item_label = 'comment';
242 $default_item_link = System::baseUrl(true).'/display/'.$it['pguid'];
243 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
244 $default_item_url = $it['author-link'];
245 $default_item_text = sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']);
246 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
247 $default_item_ago = relative_date($it['created']);
251 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
252 $default_item_link = System::baseUrl(true).'/display/'.$it['pguid'];
253 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
254 $default_item_url = $it['author-link'];
255 $default_item_text = (($it['id'] == $it['parent'])
256 ? sprintf(t("%s created a new post"), $it['author-name'])
257 : sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']));
258 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
259 $default_item_ago = relative_date($it['created']);
263 // Transform the different types of notification in an usable array
264 switch ($it['verb']){
268 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
269 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
270 'url' => $it['author-link'],
271 'text' => sprintf(t("%s liked %s's post"), $it['author-name'], $it['pname']),
272 'when' => $default_item_when,
273 'ago' => $default_item_ago,
274 'seen' => $it['seen']
278 case ACTIVITY_DISLIKE:
280 'label' => 'dislike',
281 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
282 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
283 'url' => $it['author-link'],
284 'text' => sprintf(t("%s disliked %s's post"), $it['author-name'], $it['pname']),
285 'when' => $default_item_when,
286 'ago' => $default_item_ago,
287 'seen' => $it['seen']
291 case ACTIVITY_ATTEND:
294 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
295 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
296 'url' => $it['author-link'],
297 'text' => sprintf(t("%s is attending %s's event"), $it['author-name'], $it['pname']),
298 'when' => $default_item_when,
299 'ago' => $default_item_ago,
300 'seen' => $it['seen']
304 case ACTIVITY_ATTENDNO:
306 'label' => 'attendno',
307 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
308 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
309 'url' => $it['author-link'],
310 'text' => sprintf( t("%s is not attending %s's event"), $it['author-name'], $it['pname']),
311 'when' => $default_item_when,
312 'ago' => $default_item_ago,
313 'seen' => $it['seen']
317 case ACTIVITY_ATTENDMAYBE:
319 'label' => 'attendmaybe',
320 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
321 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
322 'url' => $it['author-link'],
323 'text' => sprintf(t("%s may attend %s's event"), $it['author-name'], $it['pname']),
324 'when' => $default_item_when,
325 'ago' => $default_item_ago,
326 'seen' => $it['seen']
330 case ACTIVITY_FRIEND:
331 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
332 $obj = parse_xml_string($xmlhead.$it['object']);
333 $it['fname'] = $obj->title;
337 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
338 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
339 'url' => $it['author-link'],
340 'text' => sprintf(t("%s is now friends with %s"), $it['author-name'], $it['fname']),
341 'when' => $default_item_when,
342 'ago' => $default_item_ago,
343 'seen' => $it['seen']
349 'label' => $default_item_label,
350 'link' => $default_item_link,
351 'image' => $default_item_image,
352 'url' => $default_item_url,
353 'text' => $default_item_text,
354 'when' => $default_item_when,
355 'ago' => $default_item_ago,
356 'seen' => $it['seen']
369 * @brief Total number of network notifications
370 * @param int|string $seen
371 * If 0 only include notifications into the query
372 * which aren't marked as "seen"
373 * @return int Number of network notifications
375 private function networkTotal($seen = 0) {
379 $sql_seen = " AND `item`.`unseen` = 1 ";
381 $r = q("SELECT COUNT(*) AS `total`
382 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
383 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
384 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
389 if (DBM::is_result($r))
390 return $r[0]['total'];
396 * @brief Get network notifications
398 * @param int|string $seen
399 * If 0 only include notifications into the query
400 * which aren't marked as "seen"
401 * @param int $start Start the query at this point
402 * @param int $limit Maximum number of query results
405 * string 'ident' => Notification identifier
406 * int 'total' => Total number of available network notifications
407 * array 'notifications' => Network notifications
409 public function networkNotifs($seen = 0, $start = 0, $limit = 80) {
411 $total = $this->networkTotal($seen);
416 $sql_seen = " AND `item`.`unseen` = 1 ";
419 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
420 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
421 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
422 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
423 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
424 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
426 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
427 intval(local_user()),
432 if (DBM::is_result($r))
433 $notifs = $this->formatNotifs($r, $ident);
436 'notifications' => $notifs,
445 * @brief Total number of system notifications
446 * @param int|string $seen
447 * If 0 only include notifications into the query
448 * which aren't marked as "seen"
449 * @return int Number of system notifications
451 private function systemTotal($seen = 0) {
455 $sql_seen = " AND `seen` = 0 ";
457 $r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
461 if (DBM::is_result($r))
462 return $r[0]['total'];
468 * @brief Get system notifications
470 * @param int|string $seen
471 * If 0 only include notifications into the query
472 * which aren't marked as "seen"
473 * @param int $start Start the query at this point
474 * @param int $limit Maximum number of query results
477 * string 'ident' => Notification identifier
478 * int 'total' => Total number of available system notifications
479 * array 'notifications' => System notifications
481 public function systemNotifs($seen = 0, $start = 0, $limit = 80) {
483 $total = $this->systemTotal($seen);
488 $sql_seen = " AND `seen` = 0 ";
490 $r = q("SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
491 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
492 intval(local_user()),
497 if (DBM::is_result($r))
498 $notifs = $this->formatNotifs($r, $ident);
501 'notifications' => $notifs,
510 * @brief Addional SQL query string for the personal notifications
512 * @return string The additional sql query
514 private function _personal_sql_extra() {
515 $myurl = System::baseUrl(true) . '/profile/'. $this->a->user['nickname'];
516 $myurl = substr($myurl,strpos($myurl,'://')+3);
517 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
518 $diasp_url = str_replace('/profile/','/u/',$myurl);
519 $sql_extra = sprintf(" AND ( `item`.`author-link` regexp '%s' OR `item`.`tag` regexp '%s' OR `item`.`tag` regexp '%s' ) ",
521 dbesc($myurl . '\\]'),
522 dbesc($diasp_url . '\\]')
529 * @brief Total number of personal notifications
530 * @param int|string $seen
531 * If 0 only include notifications into the query
532 * which aren't marked as "seen"
533 * @return int Number of personal notifications
535 private function personalTotal($seen = 0) {
537 $sql_extra = $this->_personal_sql_extra();
540 $sql_seen = " AND `item`.`unseen` = 1 ";
542 $r = q("SELECT COUNT(*) AS `total`
543 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
544 WHERE `item`.`visible` = 1
547 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 " ,
551 if (DBM::is_result($r))
552 return $r[0]['total'];
558 * @brief Get personal notifications
560 * @param int|string $seen
561 * If 0 only include notifications into the query
562 * which aren't marked as "seen"
563 * @param int $start Start the query at this point
564 * @param int $limit Maximum number of query results
567 * string 'ident' => Notification identifier
568 * int 'total' => Total number of available personal notifications
569 * array 'notifications' => Personal notifications
571 public function personalNotifs($seen = 0, $start = 0, $limit = 80) {
573 $total = $this->personalTotal($seen);
574 $sql_extra = $this->_personal_sql_extra();
579 $sql_seen = " AND `item`.`unseen` = 1 ";
581 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
582 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
583 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
584 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
585 WHERE `item`.`visible` = 1
588 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
589 ORDER BY `item`.`created` DESC LIMIT %d, %d " ,
590 intval(local_user()),
595 if (DBM::is_result($r))
596 $notifs = $this->formatNotifs($r, $ident);
599 'notifications' => $notifs,
608 * @brief Total number of home notifications
609 * @param int|string $seen
610 * If 0 only include notifications into the query
611 * which aren't marked as "seen"
612 * @return int Number of home notifications
614 private function homeTotal($seen = 0) {
618 $sql_seen = " AND `item`.`unseen` = 1 ";
620 $r = q("SELECT COUNT(*) AS `total` FROM `item`
621 WHERE `item`.`visible` = 1 AND
622 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
627 if (DBM::is_result($r))
628 return $r[0]['total'];
634 * @brief Get home notifications
636 * @param int|string $seen
637 * If 0 only include notifications into the query
638 * which aren't marked as "seen"
639 * @param int $start Start the query at this point
640 * @param int $limit Maximum number of query results
643 * string 'ident' => Notification identifier
644 * int 'total' => Total number of available home notifications
645 * array 'notifications' => Home notifications
647 public function homeNotifs($seen = 0, $start = 0, $limit = 80) {
649 $total = $this->homeTotal($seen);
654 $sql_seen = " AND `item`.`unseen` = 1 ";
656 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
657 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
658 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
659 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
660 WHERE `item`.`visible` = 1 AND
661 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
663 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
664 intval(local_user()),
669 if (DBM::is_result($r))
670 $notifs = $this->formatNotifs($r, $ident);
673 'notifications' => $notifs,
682 * @brief Total number of introductions
684 * If false only include introductions into the query
685 * which aren't marked as ignored
686 * @return int Number of introductions
688 private function introTotal($all = false) {
692 $sql_extra = " AND `ignore` = 0 ";
694 $r = q("SELECT COUNT(*) AS `total` FROM `intro`
695 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
696 intval($_SESSION['uid'])
699 if (DBM::is_result($r))
700 return $r[0]['total'];
706 * @brief Get introductions
709 * If false only include introductions into the query
710 * which aren't marked as ignored
711 * @param int $start Start the query at this point
712 * @param int $limit Maximum number of query results
715 * string 'ident' => Notification identifier
716 * int 'total' => Total number of available introductions
717 * array 'notifications' => Introductions
719 public function introNotifs($all = false, $start = 0, $limit = 80) {
720 $ident = 'introductions';
721 $total = $this->introTotal($seen);
726 $sql_extra = " AND `ignore` = 0 ";
728 /// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact
729 $r = q("SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
730 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`,
731 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
732 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
733 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
734 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
736 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
737 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
738 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
739 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
741 intval($_SESSION['uid']),
746 if (DBM::is_result($r))
747 $notifs = $this->formatIntros($r);
752 'notifications' => $notifs,
759 * @brief Format the notification query in an usable array
761 * @param array $intros The array from the db query
762 * @return array with the introductions
764 private function formatIntros($intros) {
767 foreach($intros as $it) {
768 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
769 // We have to distinguish between these two because they use different data.
771 // Contact suggestions
774 $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
777 'label' => 'friend_suggestion',
778 'notify_type' => t('Friend Suggestion'),
779 'intro_id' => $it['intro_id'],
780 'madeby' => $it['name'],
781 'contact_id' => $it['contact-id'],
782 'photo' => ((x($it,'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
783 'name' => $it['fname'],
784 'url' => zrl($it['furl']),
785 'hidden' => $it['hidden'] == 1,
786 'post_newfriend' => (intval(PConfig::get(local_user(),'system','post_newfriend')) ? '1' : 0),
788 'knowyou' => $knowyou,
789 'note' => $it['note'],
790 'request' => $it['frequest'] . '?addr=' . $return_addr,
794 // Normal connection requests
797 $it = $this->getMissingIntroData($it);
799 // Don't show these data until you are connected. Diaspora is doing the same.
800 if($it['gnetwork'] === NETWORK_DIASPORA) {
801 $it['glocation'] = "";
806 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
807 'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? t('Friend/Connect Request') : t('New Follower')),
808 'dfrn_id' => $it['issued-id'],
809 'uid' => $_SESSION['uid'],
810 'intro_id' => $it['intro_id'],
811 'contact_id' => $it['contact-id'],
812 'photo' => ((x($it,'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
813 'name' => $it['name'],
814 'location' => bbcode($it['glocation'], false, false),
815 'about' => bbcode($it['gabout'], false, false),
816 'keywords' => $it['gkeywords'],
817 'gender' => $it['ggender'],
818 'hidden' => $it['hidden'] == 1,
819 'post_newfriend' => (intval(PConfig::get(local_user(),'system','post_newfriend')) ? '1' : 0),
821 'zrl' => zrl($it['url']),
822 'addr' => $it['gaddr'],
823 'network' => $it['gnetwork'],
824 'knowyou' => $it['knowyou'],
825 'note' => $it['note'],
836 * @brief Check for missing contact data and try to fetch the data from
839 * @param array $arr The input array with the intro data
841 * @return array The array with the intro data
843 private function getMissingIntroData($arr) {
844 // If the network and the addr isn't available from the gcontact
845 // table entry, take the one of the contact table entry
846 if ($arr['gnetwork'] == "") {
847 $arr['gnetwork'] = $arr['network'];
849 if ($arr['gaddr'] == "") {
850 $arr['gaddr'] = $arr['addr'];
853 // If the network and addr is still not available
854 // get the missing data data from other sources
855 if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
856 $ret = get_contact_details_by_url($arr['url']);
858 if ($arr['gnetwork'] == "" && $ret['network'] != "") {
859 $arr['gnetwork'] = $ret['network'];
861 if ($arr['gaddr'] == "" && $ret['addr'] != "") {
862 $arr['gaddr'] = $ret['addr'];