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\System;
10 require_once 'include/html2plain.php';
11 require_once 'include/probe.php';
12 require_once 'include/datetime.php';
13 require_once 'include/bbcode.php';
14 require_once 'include/Contact.php';
17 * @brief Methods for read and write notifications from/to database
18 * or for formatting notifications
20 class NotificationsManager {
23 public function __construct() {
28 * @brief set some extra note properties
30 * @param array $notes array of note arrays from db
31 * @return array Copy of input array with added properties
33 * Set some extra properties to note array from db:
34 * - timestamp as int in default TZ
35 * - date_rel : relative date string
36 * - msg_html: message as html string
37 * - msg_plain: message as plain text string
39 private function _set_extra($notes) {
41 foreach($notes as $n) {
42 $local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']);
43 $n['timestamp'] = strtotime($local_time);
44 $n['date_rel'] = relative_date($n['date']);
45 $n['msg_html'] = bbcode($n['msg'], false, false, false, false);
46 $n['msg_plain'] = explode("\n",trim(html2plain($n['msg_html'], 0)))[0];
55 * @brief Get all notifications for local_user()
57 * @param array $filter optional Array "column name"=>value: filter query by columns values
58 * @param string $order optional Space separated list of column to sort by. prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
59 * @param string $limit optional Query limits
61 * @return array of results or false on errors
63 public function getAll($filter = array(), $order="-date", $limit="") {
64 $filter_str = array();
66 foreach($filter as $column => $value) {
67 $filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
69 if (count($filter_str)>0) {
70 $filter_sql = "AND ".implode(" AND ", $filter_str);
73 $aOrder = explode(" ", $order);
75 foreach($aOrder as $o) {
85 $asOrder[] = "$o $dir";
87 $order_sql = implode(", ", $asOrder);
90 $limit = " LIMIT ".$limit;
92 $r = q("SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
96 if (dbm::is_result($r))
97 return $this->_set_extra($r);
103 * @brief Get one note for local_user() by $id value
106 * @return array note values or null if not found
108 public function getByID($id) {
109 $r = q("SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
113 if (dbm::is_result($r)) {
114 return $this->_set_extra($r)[0];
120 * @brief set seen state of $note of local_user()
123 * @param bool $seen optional true or false, default true
124 * @return bool true on success, false on errors
126 public function setSeen($note, $seen = true) {
127 return q("UPDATE `notify` SET `seen` = %d WHERE ( `link` = '%s' OR ( `parent` != 0 AND `parent` = %d AND `otype` = '%s' )) AND `uid` = %d",
129 dbesc($note['link']),
130 intval($note['parent']),
131 dbesc($note['otype']),
137 * @brief set seen state of all notifications of local_user()
139 * @param bool $seen optional true or false. default true
140 * @return bool true on success, false on error
142 public function setAllSeen($seen = true) {
143 return q("UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
150 * @brief List of pages for the Notifications TabBar
152 * @return array with with notifications TabBar data
154 public function getTabs() {
157 'label' => t('System'),
158 'url'=>'notifications/system',
159 'sel'=> (($this->a->argv[1] == 'system') ? 'active' : ''),
160 'id' => 'system-tab',
164 'label' => t('Network'),
165 'url'=>'notifications/network',
166 'sel'=> (($this->a->argv[1] == 'network') ? 'active' : ''),
167 'id' => 'network-tab',
171 'label' => t('Personal'),
172 'url'=>'notifications/personal',
173 'sel'=> (($this->a->argv[1] == 'personal') ? 'active' : ''),
174 'id' => 'personal-tab',
178 'label' => t('Home'),
179 'url' => 'notifications/home',
180 'sel'=> (($this->a->argv[1] == 'home') ? 'active' : ''),
185 'label' => t('Introductions'),
186 'url' => 'notifications/intros',
187 'sel'=> (($this->a->argv[1] == 'intros') ? 'active' : ''),
197 * @brief Format the notification query in an usable array
199 * @param array $notifs The array from the db query
200 * @param string $ident The notifications identifier (e.g. network)
202 * string 'label' => The type of the notification
203 * string 'link' => URL to the source
204 * string 'image' => The avatar image
205 * string 'url' => The profile url of the contact
206 * string 'text' => The notification text
207 * string 'when' => The date of the notification
208 * string 'ago' => T relative date of the notification
209 * bool 'seen' => Is the notification marked as "seen"
211 private function formatNotifs($notifs, $ident = "") {
216 if (dbm::is_result($notifs)) {
218 foreach ($notifs as $it) {
219 // Because we use different db tables for the notification query
220 // we have sometimes $it['unseen'] and sometimes $it['seen].
221 // So we will have to transform $it['unseen']
222 if (array_key_exists('unseen', $it)) {
223 $it['seen'] = ($it['unseen'] > 0 ? false : true);
226 // Depending on the identifier of the notification we need to use different defaults
229 $default_item_label = 'notify';
230 $default_item_link = System::baseUrl(true).'/notify/view/'. $it['id'];
231 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
232 $default_item_url = $it['url'];
233 $default_item_text = strip_tags(bbcode($it['msg']));
234 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['date'], 'r');
235 $default_item_ago = relative_date($it['date']);
239 $default_item_label = 'comment';
240 $default_item_link = System::baseUrl(true).'/display/'.$it['pguid'];
241 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
242 $default_item_url = $it['author-link'];
243 $default_item_text = sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']);
244 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
245 $default_item_ago = relative_date($it['created']);
249 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
250 $default_item_link = System::baseUrl(true).'/display/'.$it['pguid'];
251 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
252 $default_item_url = $it['author-link'];
253 $default_item_text = (($it['id'] == $it['parent'])
254 ? sprintf(t("%s created a new post"), $it['author-name'])
255 : sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']));
256 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
257 $default_item_ago = relative_date($it['created']);
261 // Transform the different types of notification in an usable array
262 switch ($it['verb']){
266 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
267 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
268 'url' => $it['author-link'],
269 'text' => sprintf(t("%s liked %s's post"), $it['author-name'], $it['pname']),
270 'when' => $default_item_when,
271 'ago' => $default_item_ago,
272 'seen' => $it['seen']
276 case ACTIVITY_DISLIKE:
278 'label' => 'dislike',
279 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
280 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
281 'url' => $it['author-link'],
282 'text' => sprintf(t("%s disliked %s's post"), $it['author-name'], $it['pname']),
283 'when' => $default_item_when,
284 'ago' => $default_item_ago,
285 'seen' => $it['seen']
289 case ACTIVITY_ATTEND:
292 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
293 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
294 'url' => $it['author-link'],
295 'text' => sprintf(t("%s is attending %s's event"), $it['author-name'], $it['pname']),
296 'when' => $default_item_when,
297 'ago' => $default_item_ago,
298 'seen' => $it['seen']
302 case ACTIVITY_ATTENDNO:
304 'label' => 'attendno',
305 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
306 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
307 'url' => $it['author-link'],
308 'text' => sprintf( t("%s is not attending %s's event"), $it['author-name'], $it['pname']),
309 'when' => $default_item_when,
310 'ago' => $default_item_ago,
311 'seen' => $it['seen']
315 case ACTIVITY_ATTENDMAYBE:
317 'label' => 'attendmaybe',
318 'link' => System::baseUrl(true).'/display/'.$it['pguid'],
319 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
320 'url' => $it['author-link'],
321 'text' => sprintf(t("%s may attend %s's event"), $it['author-name'], $it['pname']),
322 'when' => $default_item_when,
323 'ago' => $default_item_ago,
324 'seen' => $it['seen']
328 case ACTIVITY_FRIEND:
329 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
330 $obj = parse_xml_string($xmlhead.$it['object']);
331 $it['fname'] = $obj->title;
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 is now friends with %s"), $it['author-name'], $it['fname']),
339 'when' => $default_item_when,
340 'ago' => $default_item_ago,
341 'seen' => $it['seen']
347 'label' => $default_item_label,
348 'link' => $default_item_link,
349 'image' => $default_item_image,
350 'url' => $default_item_url,
351 'text' => $default_item_text,
352 'when' => $default_item_when,
353 'ago' => $default_item_ago,
354 'seen' => $it['seen']
367 * @brief Total number of network notifications
368 * @param int|string $seen
369 * If 0 only include notifications into the query
370 * which aren't marked as "seen"
371 * @return int Number of network notifications
373 private function networkTotal($seen = 0) {
377 $sql_seen = " AND `item`.`unseen` = 1 ";
379 $r = q("SELECT COUNT(*) AS `total`
380 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
381 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
382 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
387 if (dbm::is_result($r))
388 return $r[0]['total'];
394 * @brief Get network notifications
396 * @param int|string $seen
397 * If 0 only include notifications into the query
398 * which aren't marked as "seen"
399 * @param int $start Start the query at this point
400 * @param int $limit Maximum number of query results
403 * string 'ident' => Notification identifier
404 * int 'total' => Total number of available network notifications
405 * array 'notifications' => Network notifications
407 public function networkNotifs($seen = 0, $start = 0, $limit = 80) {
409 $total = $this->networkTotal($seen);
414 $sql_seen = " AND `item`.`unseen` = 1 ";
417 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
418 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
419 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
420 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
421 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
422 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
424 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
425 intval(local_user()),
430 if (dbm::is_result($r))
431 $notifs = $this->formatNotifs($r, $ident);
434 'notifications' => $notifs,
443 * @brief Total number of system notifications
444 * @param int|string $seen
445 * If 0 only include notifications into the query
446 * which aren't marked as "seen"
447 * @return int Number of system notifications
449 private function systemTotal($seen = 0) {
453 $sql_seen = " AND `seen` = 0 ";
455 $r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
459 if (dbm::is_result($r))
460 return $r[0]['total'];
466 * @brief Get system notifications
468 * @param int|string $seen
469 * If 0 only include notifications into the query
470 * which aren't marked as "seen"
471 * @param int $start Start the query at this point
472 * @param int $limit Maximum number of query results
475 * string 'ident' => Notification identifier
476 * int 'total' => Total number of available system notifications
477 * array 'notifications' => System notifications
479 public function systemNotifs($seen = 0, $start = 0, $limit = 80) {
481 $total = $this->systemTotal($seen);
486 $sql_seen = " AND `seen` = 0 ";
488 $r = q("SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
489 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
490 intval(local_user()),
495 if (dbm::is_result($r))
496 $notifs = $this->formatNotifs($r, $ident);
499 'notifications' => $notifs,
508 * @brief Addional SQL query string for the personal notifications
510 * @return string The additional sql query
512 private function _personal_sql_extra() {
513 $myurl = System::baseUrl(true) . '/profile/'. $this->a->user['nickname'];
514 $myurl = substr($myurl,strpos($myurl,'://')+3);
515 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
516 $diasp_url = str_replace('/profile/','/u/',$myurl);
517 $sql_extra = sprintf(" AND ( `item`.`author-link` regexp '%s' OR `item`.`tag` regexp '%s' OR `item`.`tag` regexp '%s' ) ",
519 dbesc($myurl . '\\]'),
520 dbesc($diasp_url . '\\]')
527 * @brief Total number of personal notifications
528 * @param int|string $seen
529 * If 0 only include notifications into the query
530 * which aren't marked as "seen"
531 * @return int Number of personal notifications
533 private function personalTotal($seen = 0) {
535 $sql_extra = $this->_personal_sql_extra();
538 $sql_seen = " AND `item`.`unseen` = 1 ";
540 $r = q("SELECT COUNT(*) AS `total`
541 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
542 WHERE `item`.`visible` = 1
545 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 " ,
549 if (dbm::is_result($r))
550 return $r[0]['total'];
556 * @brief Get personal notifications
558 * @param int|string $seen
559 * If 0 only include notifications into the query
560 * which aren't marked as "seen"
561 * @param int $start Start the query at this point
562 * @param int $limit Maximum number of query results
565 * string 'ident' => Notification identifier
566 * int 'total' => Total number of available personal notifications
567 * array 'notifications' => Personal notifications
569 public function personalNotifs($seen = 0, $start = 0, $limit = 80) {
571 $total = $this->personalTotal($seen);
572 $sql_extra = $this->_personal_sql_extra();
577 $sql_seen = " AND `item`.`unseen` = 1 ";
579 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
580 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
581 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
582 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
583 WHERE `item`.`visible` = 1
586 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
587 ORDER BY `item`.`created` DESC LIMIT %d, %d " ,
588 intval(local_user()),
593 if (dbm::is_result($r))
594 $notifs = $this->formatNotifs($r, $ident);
597 'notifications' => $notifs,
606 * @brief Total number of home notifications
607 * @param int|string $seen
608 * If 0 only include notifications into the query
609 * which aren't marked as "seen"
610 * @return int Number of home notifications
612 private function homeTotal($seen = 0) {
616 $sql_seen = " AND `item`.`unseen` = 1 ";
618 $r = q("SELECT COUNT(*) AS `total` FROM `item`
619 WHERE `item`.`visible` = 1 AND
620 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
625 if (dbm::is_result($r))
626 return $r[0]['total'];
632 * @brief Get home notifications
634 * @param int|string $seen
635 * If 0 only include notifications into the query
636 * which aren't marked as "seen"
637 * @param int $start Start the query at this point
638 * @param int $limit Maximum number of query results
641 * string 'ident' => Notification identifier
642 * int 'total' => Total number of available home notifications
643 * array 'notifications' => Home notifications
645 public function homeNotifs($seen = 0, $start = 0, $limit = 80) {
647 $total = $this->homeTotal($seen);
652 $sql_seen = " AND `item`.`unseen` = 1 ";
654 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
655 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
656 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
657 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
658 WHERE `item`.`visible` = 1 AND
659 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
661 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
662 intval(local_user()),
667 if (dbm::is_result($r))
668 $notifs = $this->formatNotifs($r, $ident);
671 'notifications' => $notifs,
680 * @brief Total number of introductions
682 * If false only include introductions into the query
683 * which aren't marked as ignored
684 * @return int Number of introductions
686 private function introTotal($all = false) {
690 $sql_extra = " AND `ignore` = 0 ";
692 $r = q("SELECT COUNT(*) AS `total` FROM `intro`
693 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
694 intval($_SESSION['uid'])
697 if (dbm::is_result($r))
698 return $r[0]['total'];
704 * @brief Get introductions
707 * If false only include introductions into the query
708 * which aren't marked as ignored
709 * @param int $start Start the query at this point
710 * @param int $limit Maximum number of query results
713 * string 'ident' => Notification identifier
714 * int 'total' => Total number of available introductions
715 * array 'notifications' => Introductions
717 public function introNotifs($all = false, $start = 0, $limit = 80) {
718 $ident = 'introductions';
719 $total = $this->introTotal($seen);
724 $sql_extra = " AND `ignore` = 0 ";
726 /// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact
727 $r = q("SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
728 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`,
729 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
730 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
731 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
732 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
734 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
735 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
736 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
737 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
739 intval($_SESSION['uid']),
744 if (dbm::is_result($r))
745 $notifs = $this->formatIntros($r);
750 'notifications' => $notifs,
757 * @brief Format the notification query in an usable array
759 * @param array $intros The array from the db query
760 * @return array with the introductions
762 private function formatIntros($intros) {
765 foreach($intros as $it) {
766 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
767 // We have to distinguish between these two because they use different data.
769 // Contact suggestions
772 $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
775 'label' => 'friend_suggestion',
776 'notify_type' => t('Friend Suggestion'),
777 'intro_id' => $it['intro_id'],
778 'madeby' => $it['name'],
779 'contact_id' => $it['contact-id'],
780 'photo' => ((x($it,'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
781 'name' => $it['fname'],
782 'url' => zrl($it['furl']),
783 'hidden' => $it['hidden'] == 1,
784 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
786 'knowyou' => $knowyou,
787 'note' => $it['note'],
788 'request' => $it['frequest'] . '?addr=' . $return_addr,
792 // Normal connection requests
795 $it = $this->getMissingIntroData($it);
797 // Don't show these data until you are connected. Diaspora is doing the same.
798 if($it['gnetwork'] === NETWORK_DIASPORA) {
799 $it['glocation'] = "";
804 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
805 'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? t('Friend/Connect Request') : t('New Follower')),
806 'dfrn_id' => $it['issued-id'],
807 'uid' => $_SESSION['uid'],
808 'intro_id' => $it['intro_id'],
809 'contact_id' => $it['contact-id'],
810 'photo' => ((x($it,'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
811 'name' => $it['name'],
812 'location' => bbcode($it['glocation'], false, false),
813 'about' => bbcode($it['gabout'], false, false),
814 'keywords' => $it['gkeywords'],
815 'gender' => $it['ggender'],
816 'hidden' => $it['hidden'] == 1,
817 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
819 'zrl' => zrl($it['url']),
820 'addr' => $it['gaddr'],
821 'network' => $it['gnetwork'],
822 'knowyou' => $it['knowyou'],
823 'note' => $it['note'],
834 * @brief Check for missing contact data and try to fetch the data from
837 * @param array $arr The input array with the intro data
839 * @return array The array with the intro data
841 private function getMissingIntroData($arr) {
842 // If the network and the addr isn't available from the gcontact
843 // table entry, take the one of the contact table entry
844 if ($arr['gnetwork'] == "") {
845 $arr['gnetwork'] = $arr['network'];
847 if ($arr['gaddr'] == "") {
848 $arr['gaddr'] = $arr['addr'];
851 // If the network and addr is still not available
852 // get the missing data data from other sources
853 if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
854 $ret = get_contact_details_by_url($arr['url']);
856 if ($arr['gnetwork'] == "" && $ret['network'] != "") {
857 $arr['gnetwork'] = $ret['network'];
859 if ($arr['gaddr'] == "" && $ret['addr'] != "") {
860 $arr['gaddr'] = $ret['addr'];