3 * @file include/NotificationsManager.php
4 * @brief Methods for read and write notifications from/to database
5 * or for formatting notifications
8 use Friendica\Network\Probe;
10 require_once 'include/html2plain.php';
11 require_once 'include/probe.php';
12 require_once 'include/datetime.php';
13 require_once 'include/bbcode.php';
16 * @brief Methods for read and write notifications from/to database
17 * or for formatting notifications
19 class NotificationsManager {
22 public function __construct() {
27 * @brief set some extra note properties
29 * @param array $notes array of note arrays from db
30 * @return array Copy of input array with added properties
32 * Set some extra properties to note array from db:
33 * - timestamp as int in default TZ
34 * - date_rel : relative date string
35 * - msg_html: message as html string
36 * - msg_plain: message as plain text string
38 private function _set_extra($notes) {
40 foreach($notes as $n) {
41 $local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']);
42 $n['timestamp'] = strtotime($local_time);
43 $n['date_rel'] = relative_date($n['date']);
44 $n['msg_html'] = bbcode($n['msg'], false, false, false, false);
45 $n['msg_plain'] = explode("\n",trim(html2plain($n['msg_html'], 0)))[0];
54 * @brief Get all notifications for local_user()
56 * @param array $filter optional Array "column name"=>value: filter query by columns values
57 * @param string $order optional Space separated list of column to sort by. prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
58 * @param string $limit optional Query limits
60 * @return array of results or false on errors
62 public function getAll($filter = array(), $order="-date", $limit="") {
63 $filter_str = array();
65 foreach($filter as $column => $value) {
66 $filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
68 if (count($filter_str)>0) {
69 $filter_sql = "AND ".implode(" AND ", $filter_str);
72 $aOrder = explode(" ", $order);
74 foreach($aOrder as $o) {
84 $asOrder[] = "$o $dir";
86 $order_sql = implode(", ", $asOrder);
89 $limit = " LIMIT ".$limit;
91 $r = q("SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
95 if (dbm::is_result($r))
96 return $this->_set_extra($r);
102 * @brief Get one note for local_user() by $id value
105 * @return array note values or null if not found
107 public function getByID($id) {
108 $r = q("SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
112 if (dbm::is_result($r)) {
113 return $this->_set_extra($r)[0];
119 * @brief set seen state of $note of local_user()
122 * @param bool $seen optional true or false, default true
123 * @return bool true on success, false on errors
125 public function setSeen($note, $seen = true) {
126 return q("UPDATE `notify` SET `seen` = %d WHERE ( `link` = '%s' OR ( `parent` != 0 AND `parent` = %d AND `otype` = '%s' )) AND `uid` = %d",
128 dbesc($note['link']),
129 intval($note['parent']),
130 dbesc($note['otype']),
136 * @brief set seen state of all notifications of local_user()
138 * @param bool $seen optional true or false. default true
139 * @return bool true on success, false on error
141 public function setAllSeen($seen = true) {
142 return q("UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
149 * @brief List of pages for the Notifications TabBar
151 * @return array with with notifications TabBar data
153 public function getTabs() {
156 'label' => t('System'),
157 'url'=>'notifications/system',
158 'sel'=> (($this->a->argv[1] == 'system') ? 'active' : ''),
159 'id' => 'system-tab',
163 'label' => t('Network'),
164 'url'=>'notifications/network',
165 'sel'=> (($this->a->argv[1] == 'network') ? 'active' : ''),
166 'id' => 'network-tab',
170 'label' => t('Personal'),
171 'url'=>'notifications/personal',
172 'sel'=> (($this->a->argv[1] == 'personal') ? 'active' : ''),
173 'id' => 'personal-tab',
177 'label' => t('Home'),
178 'url' => 'notifications/home',
179 'sel'=> (($this->a->argv[1] == 'home') ? 'active' : ''),
184 'label' => t('Introductions'),
185 'url' => 'notifications/intros',
186 'sel'=> (($this->a->argv[1] == 'intros') ? 'active' : ''),
196 * @brief Format the notification query in an usable array
198 * @param array $notifs The array from the db query
199 * @param string $ident The notifications identifier (e.g. network)
201 * string 'label' => The type of the notification
202 * string 'link' => URL to the source
203 * string 'image' => The avatar image
204 * string 'url' => The profile url of the contact
205 * string 'text' => The notification text
206 * string 'when' => The date of the notification
207 * string 'ago' => T relative date of the notification
208 * bool 'seen' => Is the notification marked as "seen"
210 private function formatNotifs($notifs, $ident = "") {
215 if (dbm::is_result($notifs)) {
217 foreach ($notifs as $it) {
218 // Because we use different db tables for the notification query
219 // we have sometimes $it['unseen'] and sometimes $it['seen].
220 // So we will have to transform $it['unseen']
221 if (array_key_exists('unseen', $it)) {
222 $it['seen'] = ($it['unseen'] > 0 ? false : true);
225 // Depending on the identifier of the notification we need to use different defaults
228 $default_item_label = 'notify';
229 $default_item_link = $this->a->get_baseurl(true).'/notify/view/'. $it['id'];
230 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
231 $default_item_url = $it['url'];
232 $default_item_text = strip_tags(bbcode($it['msg']));
233 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['date'], 'r');
234 $default_item_ago = relative_date($it['date']);
238 $default_item_label = 'comment';
239 $default_item_link = $this->a->get_baseurl(true).'/display/'.$it['pguid'];
240 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
241 $default_item_url = $it['author-link'];
242 $default_item_text = sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']);
243 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
244 $default_item_ago = relative_date($it['created']);
248 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
249 $default_item_link = $this->a->get_baseurl(true).'/display/'.$it['pguid'];
250 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
251 $default_item_url = $it['author-link'];
252 $default_item_text = (($it['id'] == $it['parent'])
253 ? sprintf(t("%s created a new post"), $it['author-name'])
254 : sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']));
255 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
256 $default_item_ago = relative_date($it['created']);
260 // Transform the different types of notification in an usable array
261 switch ($it['verb']){
265 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
266 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
267 'url' => $it['author-link'],
268 'text' => sprintf(t("%s liked %s's post"), $it['author-name'], $it['pname']),
269 'when' => $default_item_when,
270 'ago' => $default_item_ago,
271 'seen' => $it['seen']
275 case ACTIVITY_DISLIKE:
277 'label' => 'dislike',
278 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
279 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
280 'url' => $it['author-link'],
281 'text' => sprintf(t("%s disliked %s's post"), $it['author-name'], $it['pname']),
282 'when' => $default_item_when,
283 'ago' => $default_item_ago,
284 'seen' => $it['seen']
288 case ACTIVITY_ATTEND:
291 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
292 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
293 'url' => $it['author-link'],
294 'text' => sprintf(t("%s is attending %s's event"), $it['author-name'], $it['pname']),
295 'when' => $default_item_when,
296 'ago' => $default_item_ago,
297 'seen' => $it['seen']
301 case ACTIVITY_ATTENDNO:
303 'label' => 'attendno',
304 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
305 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
306 'url' => $it['author-link'],
307 'text' => sprintf( t("%s is not attending %s's event"), $it['author-name'], $it['pname']),
308 'when' => $default_item_when,
309 'ago' => $default_item_ago,
310 'seen' => $it['seen']
314 case ACTIVITY_ATTENDMAYBE:
316 'label' => 'attendmaybe',
317 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
318 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
319 'url' => $it['author-link'],
320 'text' => sprintf(t("%s may attend %s's event"), $it['author-name'], $it['pname']),
321 'when' => $default_item_when,
322 'ago' => $default_item_ago,
323 'seen' => $it['seen']
327 case ACTIVITY_FRIEND:
328 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
329 $obj = parse_xml_string($xmlhead.$it['object']);
330 $it['fname'] = $obj->title;
334 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
335 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
336 'url' => $it['author-link'],
337 'text' => sprintf(t("%s is now friends with %s"), $it['author-name'], $it['fname']),
338 'when' => $default_item_when,
339 'ago' => $default_item_ago,
340 'seen' => $it['seen']
346 'label' => $default_item_label,
347 'link' => $default_item_link,
348 'image' => $default_item_image,
349 'url' => $default_item_url,
350 'text' => $default_item_text,
351 'when' => $default_item_when,
352 'ago' => $default_item_ago,
353 'seen' => $it['seen']
366 * @brief Total number of network notifications
367 * @param int|string $seen
368 * If 0 only include notifications into the query
369 * which aren't marked as "seen"
370 * @return int Number of network notifications
372 private function networkTotal($seen = 0) {
376 $sql_seen = " AND `item`.`unseen` = 1 ";
378 $r = q("SELECT COUNT(*) AS `total`
379 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
380 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
381 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
386 if (dbm::is_result($r))
387 return $r[0]['total'];
393 * @brief Get network notifications
395 * @param int|string $seen
396 * If 0 only include notifications into the query
397 * which aren't marked as "seen"
398 * @param int $start Start the query at this point
399 * @param int $limit Maximum number of query results
402 * string 'ident' => Notification identifier
403 * int 'total' => Total number of available network notifications
404 * array 'notifications' => Network notifications
406 public function networkNotifs($seen = 0, $start = 0, $limit = 80) {
408 $total = $this->networkTotal($seen);
413 $sql_seen = " AND `item`.`unseen` = 1 ";
416 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
417 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
418 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
419 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
420 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
421 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
423 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
424 intval(local_user()),
429 if (dbm::is_result($r))
430 $notifs = $this->formatNotifs($r, $ident);
433 'notifications' => $notifs,
442 * @brief Total number of system notifications
443 * @param int|string $seen
444 * If 0 only include notifications into the query
445 * which aren't marked as "seen"
446 * @return int Number of system notifications
448 private function systemTotal($seen = 0) {
452 $sql_seen = " AND `seen` = 0 ";
454 $r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
458 if (dbm::is_result($r))
459 return $r[0]['total'];
465 * @brief Get system notifications
467 * @param int|string $seen
468 * If 0 only include notifications into the query
469 * which aren't marked as "seen"
470 * @param int $start Start the query at this point
471 * @param int $limit Maximum number of query results
474 * string 'ident' => Notification identifier
475 * int 'total' => Total number of available system notifications
476 * array 'notifications' => System notifications
478 public function systemNotifs($seen = 0, $start = 0, $limit = 80) {
480 $total = $this->systemTotal($seen);
485 $sql_seen = " AND `seen` = 0 ";
487 $r = q("SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
488 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
489 intval(local_user()),
494 if (dbm::is_result($r))
495 $notifs = $this->formatNotifs($r, $ident);
498 'notifications' => $notifs,
507 * @brief Addional SQL query string for the personal notifications
509 * @return string The additional sql query
511 private function _personal_sql_extra() {
512 $myurl = $this->a->get_baseurl(true) . '/profile/'. $this->a->user['nickname'];
513 $myurl = substr($myurl,strpos($myurl,'://')+3);
514 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
515 $diasp_url = str_replace('/profile/','/u/',$myurl);
516 $sql_extra = sprintf(" AND ( `item`.`author-link` regexp '%s' or `item`.`tag` regexp '%s' or `item`.`tag` regexp '%s' ) ",
518 dbesc($myurl . '\\]'),
519 dbesc($diasp_url . '\\]')
526 * @brief Total number of personal notifications
527 * @param int|string $seen
528 * If 0 only include notifications into the query
529 * which aren't marked as "seen"
530 * @return int Number of personal notifications
532 private function personalTotal($seen = 0) {
534 $sql_extra = $this->_personal_sql_extra();
537 $sql_seen = " AND `item`.`unseen` = 1 ";
539 $r = q("SELECT COUNT(*) AS `total`
540 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
541 WHERE `item`.`visible` = 1
544 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 " ,
548 if (dbm::is_result($r))
549 return $r[0]['total'];
555 * @brief Get personal notifications
557 * @param int|string $seen
558 * If 0 only include notifications into the query
559 * which aren't marked as "seen"
560 * @param int $start Start the query at this point
561 * @param int $limit Maximum number of query results
564 * string 'ident' => Notification identifier
565 * int 'total' => Total number of available personal notifications
566 * array 'notifications' => Personal notifications
568 public function personalNotifs($seen = 0, $start = 0, $limit = 80) {
570 $total = $this->personalTotal($seen);
571 $sql_extra = $this->_personal_sql_extra();
576 $sql_seen = " AND `item`.`unseen` = 1 ";
578 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
579 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
580 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
581 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
582 WHERE `item`.`visible` = 1
585 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
586 ORDER BY `item`.`created` DESC LIMIT %d, %d " ,
587 intval(local_user()),
592 if (dbm::is_result($r))
593 $notifs = $this->formatNotifs($r, $ident);
596 'notifications' => $notifs,
605 * @brief Total number of home notifications
606 * @param int|string $seen
607 * If 0 only include notifications into the query
608 * which aren't marked as "seen"
609 * @return int Number of home notifications
611 private function homeTotal($seen = 0) {
615 $sql_seen = " AND `item`.`unseen` = 1 ";
617 $r = q("SELECT COUNT(*) AS `total` FROM `item`
618 WHERE `item`.`visible` = 1 AND
619 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
624 if (dbm::is_result($r))
625 return $r[0]['total'];
631 * @brief Get home notifications
633 * @param int|string $seen
634 * If 0 only include notifications into the query
635 * which aren't marked as "seen"
636 * @param int $start Start the query at this point
637 * @param int $limit Maximum number of query results
640 * string 'ident' => Notification identifier
641 * int 'total' => Total number of available home notifications
642 * array 'notifications' => Home notifications
644 public function homeNotifs($seen = 0, $start = 0, $limit = 80) {
646 $total = $this->homeTotal($seen);
651 $sql_seen = " AND `item`.`unseen` = 1 ";
653 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
654 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
655 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
656 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
657 WHERE `item`.`visible` = 1 AND
658 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
660 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
661 intval(local_user()),
666 if (dbm::is_result($r))
667 $notifs = $this->formatNotifs($r, $ident);
670 'notifications' => $notifs,
679 * @brief Total number of introductions
681 * If false only include introductions into the query
682 * which aren't marked as ignored
683 * @return int Number of introductions
685 private function introTotal($all = false) {
689 $sql_extra = " AND `ignore` = 0 ";
691 $r = q("SELECT COUNT(*) AS `total` FROM `intro`
692 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
693 intval($_SESSION['uid'])
696 if (dbm::is_result($r))
697 return $r[0]['total'];
703 * @brief Get introductions
706 * If false only include introductions into the query
707 * which aren't marked as ignored
708 * @param int $start Start the query at this point
709 * @param int $limit Maximum number of query results
712 * string 'ident' => Notification identifier
713 * int 'total' => Total number of available introductions
714 * array 'notifications' => Introductions
716 public function introNotifs($all = false, $start = 0, $limit = 80) {
717 $ident = 'introductions';
718 $total = $this->introTotal($seen);
723 $sql_extra = " AND `ignore` = 0 ";
725 /// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact
726 $r = q("SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
727 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`,
728 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
729 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
730 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
731 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
733 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
734 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
735 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
736 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
738 intval($_SESSION['uid']),
743 if (dbm::is_result($r))
744 $notifs = $this->formatIntros($r);
749 'notifications' => $notifs,
756 * @brief Format the notification query in an usable array
758 * @param array $intros The array from the db query
759 * @return array with the introductions
761 private function formatIntros($intros) {
764 foreach($intros as $it) {
765 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
766 // We have to distinguish between these two because they use different data.
768 // Contact suggestions
771 $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
774 'label' => 'friend_suggestion',
775 'notify_type' => t('Friend Suggestion'),
776 'intro_id' => $it['intro_id'],
777 'madeby' => $it['name'],
778 'contact_id' => $it['contact-id'],
779 'photo' => ((x($it,'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
780 'name' => $it['fname'],
781 'url' => zrl($it['furl']),
782 'hidden' => $it['hidden'] == 1,
783 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
785 'knowyou' => $knowyou,
786 'note' => $it['note'],
787 'request' => $it['frequest'] . '?addr=' . $return_addr,
791 // Normal connection requests
794 $it = $this->getMissingIntroData($it);
796 // Don't show these data until you are connected. Diaspora is doing the same.
797 if($it['gnetwork'] === NETWORK_DIASPORA) {
798 $it['glocation'] = "";
803 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
804 'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? t('Friend/Connect Request') : t('New Follower')),
805 'dfrn_id' => $it['issued-id'],
806 'uid' => $_SESSION['uid'],
807 'intro_id' => $it['intro_id'],
808 'contact_id' => $it['contact-id'],
809 'photo' => ((x($it,'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
810 'name' => $it['name'],
811 'location' => bbcode($it['glocation'], false, false),
812 'about' => bbcode($it['gabout'], false, false),
813 'keywords' => $it['gkeywords'],
814 'gender' => $it['ggender'],
815 'hidden' => $it['hidden'] == 1,
816 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
818 'zrl' => zrl($it['url']),
819 'addr' => $it['gaddr'],
820 'network' => $it['gnetwork'],
821 'knowyou' => $it['knowyou'],
822 'note' => $it['note'],
833 * @brief Check for missing contact data and try to fetch the data from
836 * @param array $arr The input array with the intro data
838 * @return array The array with the intro data
840 private function getMissingIntroData($arr) {
841 // If the network and the addr isn't available from the gcontact
842 // table entry, take the one of the contact table entry
843 if ($arr['gnetwork'] == "") {
844 $arr['gnetwork'] = $arr['network'];
846 if ($arr['gaddr'] == "") {
847 $arr['gaddr'] = $arr['addr'];
850 // If the network and addr is still not available try to probe
851 // the contact url to fetch the missing data
852 if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
853 $ret = Probe::uri($arr["url"]);
856 if ($arr['gnetwork'] == "") {
857 $arr['gnetwork'] = $ret['network'];
859 if ($arr['gaddr'] == "") {
860 $arr['gaddr'] = $ret['addr'];