3 * @file include/NotificationsManager.php
4 * @brief Methods for read and write notifications from/to database
5 * or for formatting notifications
7 require_once('include/html2plain.php');
8 require_once("include/datetime.php");
9 require_once("include/bbcode.php");
12 * @brief Methods for read and write notifications from/to database
13 * or for formatting notifications
15 class NotificationsManager {
18 public function __construct() {
23 * @brief set some extra note properties
25 * @param array $notes array of note arrays from db
26 * @return array Copy of input array with added properties
28 * Set some extra properties to note array from db:
29 * - timestamp as int in default TZ
30 * - date_rel : relative date string
31 * - msg_html: message as html string
32 * - msg_plain: message as plain text string
34 private function _set_extra($notes) {
36 foreach($notes as $n) {
37 $local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']);
38 $n['timestamp'] = strtotime($local_time);
39 $n['date_rel'] = relative_date($n['date']);
40 $n['msg_html'] = bbcode($n['msg'], false, false, false, false);
41 $n['msg_plain'] = explode("\n",trim(html2plain($n['msg_html'], 0)))[0];
50 * @brief Get all notifications for local_user()
52 * @param array $filter optional Array "column name"=>value: filter query by columns values
53 * @param string $order optional Space separated list of column to sort by. prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
54 * @param string $limit optional Query limits
56 * @return array of results or false on errors
58 public function getAll($filter = array(), $order="-date", $limit="") {
59 $filter_str = array();
61 foreach($filter as $column => $value) {
62 $filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
64 if (count($filter_str)>0) {
65 $filter_sql = "AND ".implode(" AND ", $filter_str);
68 $aOrder = explode(" ", $order);
70 foreach($aOrder as $o) {
80 $asOrder[] = "$o $dir";
82 $order_sql = implode(", ", $asOrder);
85 $limit = " LIMIT ".$limit;
87 $r = q("SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
91 if(dbm::is_result($r))
92 return $this->_set_extra($r);
98 * @brief Get one note for local_user() by $id value
101 * @return array note values or null if not found
103 public function getByID($id) {
104 $r = q("SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
108 if(dbm::is_result($r)) {
109 return $this->_set_extra($r)[0];
115 * @brief set seen state of $note of local_user()
118 * @param bool $seen optional true or false, default true
119 * @return bool true on success, false on errors
121 public function setSeen($note, $seen = true) {
122 return q("UPDATE `notify` SET `seen` = %d WHERE ( `link` = '%s' OR ( `parent` != 0 AND `parent` = %d AND `otype` = '%s' )) AND `uid` = %d",
124 dbesc($note['link']),
125 intval($note['parent']),
126 dbesc($note['otype']),
132 * @brief set seen state of all notifications of local_user()
134 * @param bool $seen optional true or false. default true
135 * @return bool true on success, false on error
137 public function setAllSeen($seen = true) {
138 return q("UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
145 * @brief List of pages for the Notifications TabBar
148 * @return array with with notifications TabBar data
150 public function getTabs() {
153 'label' => t('System'),
154 'url'=>'notifications/system',
155 'sel'=> (($this->a->argv[1] == 'system') ? 'active' : ''),
156 'id' => 'system-tab',
160 'label' => t('Network'),
161 'url'=>'notifications/network',
162 'sel'=> (($this->a->argv[1] == 'network') ? 'active' : ''),
163 'id' => 'network-tab',
167 'label' => t('Personal'),
168 'url'=>'notifications/personal',
169 'sel'=> (($this->a->argv[1] == 'personal') ? 'active' : ''),
170 'id' => 'personal-tab',
174 'label' => t('Home'),
175 'url' => 'notifications/home',
176 'sel'=> (($this->a->argv[1] == 'home') ? 'active' : ''),
181 'label' => t('Introductions'),
182 'url' => 'notifications/intros',
183 'sel'=> (($this->a->argv[1] == 'intros') ? 'active' : ''),
193 * @brief Format the notification query in an usable array
195 * @param array $notifs The array from the db query
196 * @param string $ident The notifications identifier (e.g. network)
198 * string 'label' => The type of the notification
199 * string 'link' => URL to the source
200 * string 'image' => The avatar image
201 * string 'text' => The notification text
202 * string 'when' => Relative date of the notification
203 * bool 'seen' => Is the notification marked as "seen"
205 private function formatNotifs($notifs, $ident = "") {
210 if (dbm::is_result($notifs)) {
212 foreach ($notifs as $it) {
213 // Because we use different db tables for the notification query
214 // we have sometimes $it['unseen'] and sometimes $it['seen].
215 // So we will have to transform $it['unseen']
216 if (array_key_exists('unseen', $it)) {
217 $it['seen'] = ($it['unseen'] > 0 ? false : true);
220 // Depending on the identifier of the notification we need to use different defaults
223 $default_item_label = 'notify';
224 $default_item_link = $this->a->get_baseurl(true).'/notify/view/'. $it['id'];
225 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
226 $default_item_text = strip_tags(bbcode($it['msg']));
227 $default_item_when = relative_date($it['date']);
231 $default_item_label = 'comment';
232 $default_item_link = $this->a->get_baseurl(true).'/display/'.$it['pguid'];
233 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
234 $default_item_text = sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']);
235 $default_item_when = relative_date($it['created']);
239 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
240 $default_item_link = $this->a->get_baseurl(true).'/display/'.$it['pguid'];
241 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
242 $default_item_text = (($it['id'] == $it['parent'])
243 ? sprintf(t("%s created a new post"), $it['author-name'])
244 : sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']));
245 $default_item_when = relative_date($it['created']);
249 // Transform the different types of notification in an usable array
250 switch ($it['verb']){
254 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
255 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
256 'text' => sprintf(t("%s liked %s's post"), $it['author-name'], $it['pname']),
257 'when' => relative_date($it['created']),
258 'seen' => $it['seen']
262 case ACTIVITY_DISLIKE:
264 'label' => 'dislike',
265 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
266 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
267 'text' => sprintf(t("%s disliked %s's post"), $it['author-name'], $it['pname']),
268 'when' => relative_date($it['created']),
269 'seen' => $it['seen']
273 case ACTIVITY_ATTEND:
276 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
277 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
278 'text' => sprintf(t("%s is attending %s's event"), $it['author-name'], $it['pname']),
279 'when' => relative_date($it['created']),
280 'seen' => $it['seen']
284 case ACTIVITY_ATTENDNO:
286 'label' => 'attendno',
287 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
288 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
289 'text' => sprintf( t("%s is not attending %s's event"), $it['author-name'], $it['pname']),
290 'when' => relative_date($it['created']),
291 'seen' => $it['seen']
295 case ACTIVITY_ATTENDMAYBE:
297 'label' => 'attendmaybe',
298 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
299 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
300 'text' => sprintf(t("%s may attend %s's event"), $it['author-name'], $it['pname']),
301 'when' => relative_date($it['created']),
302 'seen' => $it['seen']
306 case ACTIVITY_FRIEND:
307 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
308 $obj = parse_xml_string($xmlhead.$it['object']);
309 $it['fname'] = $obj->title;
313 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
314 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
315 'text' => sprintf(t("%s is now friends with %s"), $it['author-name'], $it['fname']),
316 'when' => relative_date($it['created']),
317 'seen' => $it['seen']
323 'label' => $default_item_label,
324 'link' => $default_item_link,
325 'image' => $default_item_image,
326 'text' => $default_item_text,
327 'when' => $default_item_when,
328 'seen' => $it['seen']
341 * @brief Total number of network notifications
342 * @param int|string $seen
343 * If 0 only include notifications into the query
344 * which aren't marked as "seen"
345 * @return int Number of network notifications
347 private function networkTotal($seen = 0) {
351 $sql_seen = " AND `item`.`unseen` = 1 ";
353 $r = q("SELECT COUNT(*) AS `total`
354 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
355 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
356 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
361 if(dbm::is_result($r))
362 return $r[0]['total'];
368 * @brief Get network notifications
370 * @param int|string $seen
371 * If 0 only include notifications into the query
372 * which aren't marked as "seen"
373 * @param int $start Start the query at this point
374 * @param int $limit Maximum number of query results
377 * string 'ident' => Notification identifier
378 * int 'total' => Total number of available network notifications
379 * array 'notifications' => Network notifications
381 public function networkNotifs($seen = 0, $start = 0, $limit = 80) {
383 $total = $this->networkTotal($seen);
388 $sql_seen = " AND `item`.`unseen` = 1 ";
391 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
392 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
393 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
394 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
395 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
396 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
398 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
399 intval(local_user()),
404 if(dbm::is_result($r))
405 $notifs = $this->formatNotifs($r, $ident);
408 'notifications' => $notifs,
417 * @brief Total number of system notifications
418 * @param int|string $seen
419 * If 0 only include notifications into the query
420 * which aren't marked as "seen"
421 * @return int Number of system notifications
423 private function systemTotal($seen = 0) {
427 $sql_seen = " AND `seen` = 0 ";
429 $r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
433 if(dbm::is_result($r))
434 return $r[0]['total'];
440 * @brief Get system notifications
442 * @param int|string $seen
443 * If 0 only include notifications into the query
444 * which aren't marked as "seen"
445 * @param int $start Start the query at this point
446 * @param int $limit Maximum number of query results
449 * string 'ident' => Notification identifier
450 * int 'total' => Total number of available system notifications
451 * array 'notifications' => System notifications
453 public function systemNotifs($seen = 0, $start = 0, $limit = 80) {
455 $total = $this->systemTotal($seen);
460 $sql_seen = " AND `seen` = 0 ";
462 $r = q("SELECT `id`, `photo`, `msg`, `date`, `seen` FROM `notify`
463 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
464 intval(local_user()),
469 if(dbm::is_result($r))
470 $notifs = $this->formatNotifs($r, $ident);
473 'notifications' => $notifs,
482 * @brief Addional SQL query string for the personal notifications
484 * @return string The additional sql query
486 private function _personal_sql_extra() {
487 $myurl = $this->a->get_baseurl(true) . '/profile/'. $this->a->user['nickname'];
488 $myurl = substr($myurl,strpos($myurl,'://')+3);
489 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
490 $diasp_url = str_replace('/profile/','/u/',$myurl);
491 $sql_extra = sprintf(" AND ( `item`.`author-link` regexp '%s' or `item`.`tag` regexp '%s' or `item`.`tag` regexp '%s' ) ",
493 dbesc($myurl . '\\]'),
494 dbesc($diasp_url . '\\]')
501 * @brief Total number of personal notifications
502 * @param int|string $seen
503 * If 0 only include notifications into the query
504 * which aren't marked as "seen"
505 * @return int Number of personal notifications
507 private function personalTotal($seen = 0) {
509 $sql_extra = $this->_personal_sql_extra();
512 $sql_seen = " AND `item`.`unseen` = 1 ";
514 $r = q("SELECT COUNT(*) AS `total`
515 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
516 WHERE `item`.`visible` = 1
519 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 " ,
523 if(dbm::is_result($r))
524 return $r[0]['total'];
530 * @brief Get personal notifications
532 * @param int|string $seen
533 * If 0 only include notifications into the query
534 * which aren't marked as "seen"
535 * @param int $start Start the query at this point
536 * @param int $limit Maximum number of query results
539 * string 'ident' => Notification identifier
540 * int 'total' => Total number of available personal notifications
541 * array 'notifications' => Personal notifications
543 public function personalNotifs($seen = 0, $start = 0, $limit = 80) {
545 $total = $this->personalTotal($seen);
546 $sql_extra = $this->_personal_sql_extra();
551 $sql_seen = " AND `item`.`unseen` = 1 ";
553 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
554 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
555 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
556 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
557 WHERE `item`.`visible` = 1
560 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
561 ORDER BY `item`.`created` DESC LIMIT %d, %d " ,
562 intval(local_user()),
567 if(dbm::is_result($r))
568 $notifs = $this->formatNotifs($r, $ident);
571 'notifications' => $notifs,
580 * @brief Total number of home notifications
581 * @param int|string $seen
582 * If 0 only include notifications into the query
583 * which aren't marked as "seen"
584 * @return int Number of home notifications
586 private function homeTotal($seen = 0) {
590 $sql_seen = " AND `item`.`unseen` = 1 ";
592 $r = q("SELECT COUNT(*) AS `total` FROM `item`
593 WHERE `item`.`visible` = 1 AND
594 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
599 if(dbm::is_result($r))
600 return $r[0]['total'];
606 * @brief Get home notifications
608 * @param int|string $seen
609 * If 0 only include notifications into the query
610 * which aren't marked as "seen"
611 * @param int $start Start the query at this point
612 * @param int $limit Maximum number of query results
615 * string 'ident' => Notification identifier
616 * int 'total' => Total number of available home notifications
617 * array 'notifications' => Home notifications
619 public function homeNotifs($seen = 0, $start = 0, $limit = 80) {
621 $total = $this->homeTotal($seen);
626 $sql_seen = " AND `item`.`unseen` = 1 ";
628 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
629 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` as `object`,
630 `pitem`.`author-name` as `pname`, `pitem`.`author-link` as `plink`, `pitem`.`guid` as `pguid`
631 FROM `item` INNER JOIN `item` as `pitem` ON `pitem`.`id`=`item`.`parent`
632 WHERE `item`.`visible` = 1 AND
633 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
635 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
636 intval(local_user()),
641 if(dbm::is_result($r))
642 $notifs = $this->formatNotifs($r, $ident);
645 'notifications' => $notifs,
654 * @brief Total number of introductions
656 * If false only include introductions into the query
657 * which aren't marked as ignored
658 * @return int Number of introductions
660 private function introTotal($all = false) {
664 $sql_extra = " AND `ignore` = 0 ";
666 $r = q("SELECT COUNT(*) AS `total` FROM `intro`
667 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
668 intval($_SESSION['uid'])
671 if(dbm::is_result($r))
672 return $r[0]['total'];
678 * @brief Get introductions
681 * If false only include introductions into the query
682 * which aren't marked as ignored
683 * @param int $start Start the query at this point
684 * @param int $limit Maximum number of query results
687 * string 'ident' => Notification identifier
688 * int 'total' => Total number of available introductions
689 * array 'notifications' => Introductions
691 public function introNotifs($all = false, $start = 0, $limit = 80) {
692 $ident = 'introductions';
693 $total = $this->introTotal($seen);
698 $sql_extra = " AND `ignore` = 0 ";
700 /// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact
701 $r = q("SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*, `fcontact`.`name` AS `fname`,`fcontact`.`url` AS `furl`,`fcontact`.`photo` AS `fphoto`,`fcontact`.`request` AS `frequest`,
702 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
703 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
704 `gcontact`.`network` AS `gnetwork`
706 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
707 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
708 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
709 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
711 intval($_SESSION['uid']),
716 if(dbm::is_result($r))
717 $notifs = $this->formatIntros($r);
722 'notifications' => $notifs,
729 * @brief Format the notification query in an usable array
731 * @param array $intros The array from the db query
732 * @return array with the introductions
734 private function formatIntros($intros) {
737 foreach($intros as $it) {
738 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
739 // We have to distinguish between these two because they use different data.
741 // Contact suggestions
744 $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
747 'label' => 'friend_suggestion',
748 'notify_type' => t('Friend Suggestion'),
749 'intro_id' => $it['intro_id'],
750 'madeby' => $it['name'],
751 'contact_id' => $it['contact-id'],
752 'photo' => ((x($it,'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
753 'name' => $it['fname'],
754 'url' => zrl($it['furl']),
755 'hidden' => $it['hidden'] == 1,
756 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
758 'knowyou' => $knowyou,
759 'note' => $it['note'],
760 'request' => $it['frequest'] . '?addr=' . $return_addr,
764 // Normal connection requests
767 // Probe the contact url to get missing data
768 $ret = probe_url($it["url"]);
770 if ($it['gnetwork'] == "")
771 $it['gnetwork'] = $ret["network"];
773 // Don't show these data until you are connected. Diaspora is doing the same.
774 if($it['gnetwork'] === NETWORK_DIASPORA) {
775 $it['glocation'] = "";
780 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
781 'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? t('Friend/Connect Request') : t('New Follower')),
782 'dfrn_id' => $it['issued-id'],
783 'uid' => $_SESSION['uid'],
784 'intro_id' => $it['intro_id'],
785 'contact_id' => $it['contact-id'],
786 'photo' => ((x($it,'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
787 'name' => $it['name'],
788 'location' => bbcode($it['glocation'], false, false),
789 'about' => bbcode($it['gabout'], false, false),
790 'keywords' => $it['gkeywords'],
791 'gender' => $it['ggender'],
792 'hidden' => $it['hidden'] == 1,
793 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
795 'zrl' => zrl($it['url']),
796 'addr' => $ret['addr'],
797 'network' => $it['gnetwork'],
798 'knowyou' => $it['knowyou'],
799 'note' => $it['note'],