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']
217 $it['seen'] = ($it['unseen'] > 0 ? false : true);
219 // Depending on the identifier of the notification we need to use different defaults
222 $default_item_label = 'notify';
223 $default_item_link = $this->a->get_baseurl(true).'/notify/view/'. $it['id'];
224 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
225 $default_item_text = strip_tags(bbcode($it['msg']));
226 $default_item_when = relative_date($it['date']);
227 $default_tpl = $tpl_notify;
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']);
236 $default_tpl = $tpl_item_comments;
240 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
241 $default_item_link = $this->a->get_baseurl(true).'/display/'.$it['pguid'];
242 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
243 $default_item_text = (($it['id'] == $it['parent'])
244 ? sprintf( t("%s created a new post"), $it['author-name'])
245 : sprintf( t("%s commented on %s's post"), $it['author-name'], $it['pname']));
246 $default_item_when = relative_date($it['created']);
247 $default_tpl = (($it['id'] == $it['parent']) ? $tpl_item_posts : $tpl_item_comments);
251 // Transform the different types of notification in an usable array
256 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
257 '$image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
258 'text' => sprintf( t("%s liked %s's post"), $it['author-name'], $it['pname']),
259 'when' => relative_date($it['created']),
260 'seen' => $it['seen']
264 case ACTIVITY_DISLIKE:
266 'label' => 'dislike',
267 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
268 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
269 'text' => sprintf( t("%s disliked %s's post"), $it['author-name'], $it['pname']),
270 'when' => relative_date($it['created']),
271 'seen' => $it['seen']
275 case ACTIVITY_ATTEND:
278 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
279 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
280 'text' => sprintf( t("%s is attending %s's event"), $it['author-name'], $it['pname']),
281 'when' => relative_date($it['created']),
282 'seen' => $it['seen']
286 case ACTIVITY_ATTENDNO:
288 'label' => 'attendno',
289 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
290 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
291 'text' => sprintf( t("%s is not attending %s's event"), $it['author-name'], $it['pname']),
292 'when' => relative_date($it['created']),
293 'seen' => $it['seen']
297 case ACTIVITY_ATTENDMAYBE:
299 'label' => 'attendmaybe',
300 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
301 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
302 'text' => sprintf( t("%s may attend %s's event"), $it['author-name'], $it['pname']),
303 'when' => relative_date($it['created']),
304 'seen' => $it['seen']
308 case ACTIVITY_FRIEND:
309 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
310 $obj = parse_xml_string($xmlhead.$it['object']);
311 $it['fname'] = $obj->title;
315 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
316 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
317 'text' => sprintf( t("%s is now friends with %s"), $it['author-name'], $it['fname']),
318 'when' => relative_date($it['created']),
319 'seen' => $it['seen']
325 'label' => $default_item_label,
326 'link' => $default_item_link,
327 'image' => $default_item_image,
328 'text' => $default_item_text,
329 'when' => $default_item_when,
330 'seen' => $it['seen']
343 * @brief Total number of network notifications
344 * @param int|string $seen
345 * If 0 only include notifications into the query
346 * which aren't marked as "seen"
347 * @return int Number of network notifications
349 private function networkTotal($seen = 0) {
353 $sql_seen = " AND `item`.`unseen` = 1 ";
355 $r = q("SELECT COUNT(*) AS `total`
356 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
357 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
358 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
363 if(dbm::is_result($r))
364 return $r[0]['total'];
370 * @brief Get network notifications
372 * @param int|string $seen
373 * If 0 only include notifications into the query
374 * which aren't marked as "seen"
375 * @param int $start Start the query at this point
376 * @param int $limit Maximum number of query results
379 * string 'ident' => Notification identifier
380 * int 'total' => Total number of available network notifications
381 * array 'notifications' => Network notifications
383 public function networkNotifs($seen = 0, $start = 0, $limit = 80) {
385 $total = $this->networkTotal($seen);
390 $sql_seen = " AND `item`.`unseen` = 1 ";
393 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
394 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
395 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
396 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
397 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
398 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
400 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
401 intval(local_user()),
406 if(dbm::is_result($r))
407 $notifs = $this->formatNotifs($r, $ident);
410 'notifications' => $notifs,
419 * @brief Total number of system notifications
420 * @param int|string $seen
421 * If 0 only include notifications into the query
422 * which aren't marked as "seen"
423 * @return int Number of system notifications
425 private function systemTotal($seen = 0) {
429 $sql_seen = " AND `seen` = 0 ";
431 $r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
435 if(dbm::is_result($r))
436 return $r[0]['total'];
442 * @brief Get system notifications
444 * @param int|string $seen
445 * If 0 only include notifications into the query
446 * which aren't marked as "seen"
447 * @param int $start Start the query at this point
448 * @param int $limit Maximum number of query results
451 * string 'ident' => Notification identifier
452 * int 'total' => Total number of available system notifications
453 * array 'notifications' => System notifications
455 public function systemNotifs($seen = 0, $start = 0, $limit = 80) {
457 $total = $this->systemTotal($seen);
462 $sql_seen = " AND `seen` = 0 ";
464 $r = q("SELECT `id`, `photo`, `msg`, `date`, `seen` FROM `notify`
465 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
466 intval(local_user()),
471 if(dbm::is_result($r))
472 $notifs = $this->formatNotifs($r, $ident);
475 'notifications' => $notifs,
484 * @brief Addional SQL query string for the personal notifications
486 * @return string The additional sql query
488 private function _personal_sql_extra() {
489 $myurl = $this->a->get_baseurl(true) . '/profile/'. $this->a->user['nickname'];
490 $myurl = substr($myurl,strpos($myurl,'://')+3);
491 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
492 $diasp_url = str_replace('/profile/','/u/',$myurl);
493 $sql_extra = sprintf(" AND ( `item`.`author-link` regexp '%s' or `item`.`tag` regexp '%s' or `item`.`tag` regexp '%s' ) ",
495 dbesc($myurl . '\\]'),
496 dbesc($diasp_url . '\\]')
503 * @brief Total number of personal notifications
504 * @param int|string $seen
505 * If 0 only include notifications into the query
506 * which aren't marked as "seen"
507 * @return int Number of personal notifications
509 private function personalTotal($seen = 0) {
511 $sql_extra = $this->_personal_sql_extra();
514 $sql_seen = " AND `item`.`unseen` = 1 ";
516 $r = q("SELECT COUNT(*) AS `total`
517 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
518 WHERE `item`.`visible` = 1
521 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 " ,
525 if(dbm::is_result($r))
526 return $r[0]['total'];
532 * @brief Get personal notifications
534 * @param int|string $seen
535 * If 0 only include notifications into the query
536 * which aren't marked as "seen"
537 * @param int $start Start the query at this point
538 * @param int $limit Maximum number of query results
541 * string 'ident' => Notification identifier
542 * int 'total' => Total number of available personal notifications
543 * array 'notifications' => Personal notifications
545 public function personalNotifs($seen = 0, $start = 0, $limit = 80) {
547 $total = $this->personalTotal($seen);
548 $sql_extra = $this->_personal_sql_extra();
553 $sql_seen = " AND `item`.`unseen` = 1 ";
555 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
556 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
557 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`,
558 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
559 WHERE `item`.`visible` = 1
562 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
563 ORDER BY `item`.`created` DESC LIMIT %d, %d " ,
564 intval(local_user()),
569 if(dbm::is_result($r))
570 $notifs = $this->formatNotifs($r, $ident);
573 'notifications' => $notifs,
582 * @brief Total number of home notifications
583 * @param int|string $seen
584 * If 0 only include notifications into the query
585 * which aren't marked as "seen"
586 * @return int Number of home notifications
588 private function homeTotal($seen = 0) {
592 $sql_seen = " AND `item`.`unseen` = 1 ";
594 $r = q("SELECT COUNT(*) AS `total` FROM `item`
595 WHERE `item`.`visible` = 1 AND
596 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
601 if(dbm::is_result($r))
602 return $r[0]['total'];
608 * @brief Get home notifications
610 * @param int|string $seen
611 * If 0 only include notifications into the query
612 * which aren't marked as "seen"
613 * @param int $start Start the query at this point
614 * @param int $limit Maximum number of query results
617 * string 'ident' => Notification identifier
618 * int 'total' => Total number of available home notifications
619 * array 'notifications' => Home notifications
621 public function homeNotifs($seen = 0, $start = 0, $limit = 80) {
623 $total = $this->homeTotal($seen);
628 $sql_seen = " AND `item`.`unseen` = 1 ";
630 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
631 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` as `object`,
632 `pitem`.`author-name` as `pname`, `pitem`.`author-link` as `plink`, `pitem`.`guid` as `pguid`
633 FROM `item` INNER JOIN `item` as `pitem` ON `pitem`.`id`=`item`.`parent`
634 WHERE `item`.`visible` = 1 AND
635 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
637 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
638 intval(local_user()),
643 if(dbm::is_result($r))
644 $notifs = $this->formatNotifs($r, $ident);
647 'notifications' => $notifs,
656 * @brief Total number of introductions
658 * If false only include introductions into the query
659 * which aren't marked as ignored
660 * @return int Number of introductions
662 private function introTotal($all = false) {
666 $sql_extra = " AND `ignore` = 0 ";
668 $r = q("SELECT COUNT(*) AS `total` FROM `intro`
669 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
670 intval($_SESSION['uid'])
673 if(dbm::is_result($r))
674 return $r[0]['total'];
680 * @brief Get introductions
683 * If false only include introductions into the query
684 * which aren't marked as ignored
685 * @param int $start Start the query at this point
686 * @param int $limit Maximum number of query results
689 * string 'ident' => Notification identifier
690 * int 'total' => Total number of available introductions
691 * array 'notifications' => Introductions
693 public function introNotifs($all = false, $start = 0, $limit = 80) {
694 $ident = 'introductions';
695 $total = $this->introTotal($seen);
700 $sql_extra = " AND `ignore` = 0 ";
702 /// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact
703 $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`,
704 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
705 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
706 `gcontact`.`network` AS `gnetwork`
708 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
709 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
710 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
711 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
713 intval($_SESSION['uid']),
718 if(dbm::is_result($r))
719 $notifs = $this->formatIntros($r);
724 'notifications' => $notifs,
731 * @brief Format the notification query in an usable array
733 * @param array $intros The array from the db query
734 * @return array with the introductions
736 private function formatIntros($intros) {
739 foreach($intros as $it) {
740 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
741 // We have to distinguish between these two because they use different data.
743 // Contact suggestions
746 $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
749 'label' => 'friend_suggestion',
750 'notify_type' => t('Friend Suggestion'),
751 'intro_id' => $it['intro_id'],
752 'madeby' => $it['name'],
753 'contact_id' => $it['contact-id'],
754 'photo' => ((x($it,'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
755 'name' => $it['fname'],
756 'url' => zrl($it['furl']),
757 'hidden' => $it['hidden'] == 1,
758 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
760 'knowyou' => $knowyou,
761 'note' => $it['note'],
762 'request' => $it['frequest'] . '?addr=' . $return_addr,
766 // Normal connection requests
769 // Probe the contact url to get missing data
770 $ret = probe_url($it["url"]);
772 if ($it['gnetwork'] == "")
773 $it['gnetwork'] = $ret["network"];
775 // Don't show these data until you are connected. Diaspora is doing the same.
776 if($it['gnetwork'] === NETWORK_DIASPORA) {
777 $it['glocation'] = "";
782 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
783 'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? t('Friend/Connect Request') : t('New Follower')),
784 'dfrn_id' => $it['issued-id'],
785 'uid' => $_SESSION['uid'],
786 'intro_id' => $it['intro_id'],
787 'contact_id' => $it['contact-id'],
788 'photo' => ((x($it,'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
789 'name' => $it['name'],
790 'location' => bbcode($it['glocation'], false, false),
791 'about' => bbcode($it['gabout'], false, false),
792 'keywords' => $it['gkeywords'],
793 'gender' => $it['ggender'],
794 'hidden' => $it['hidden'] == 1,
795 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
797 'zrl' => zrl($it['url']),
798 'addr' => $ret['addr'],
799 'network' => $it['gnetwork'],
800 'knowyou' => $it['knowyou'],
801 'note' => $it['note'],