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 'url' => The profile url of the contact
202 * string 'text' => The notification text
203 * string 'when' => Relative date of the notification
204 * bool 'seen' => Is the notification marked as "seen"
206 private function formatNotifs($notifs, $ident = "") {
211 if (dbm::is_result($notifs)) {
213 foreach ($notifs as $it) {
214 // Because we use different db tables for the notification query
215 // we have sometimes $it['unseen'] and sometimes $it['seen].
216 // So we will have to transform $it['unseen']
217 if (array_key_exists('unseen', $it)) {
218 $it['seen'] = ($it['unseen'] > 0 ? false : true);
221 // Depending on the identifier of the notification we need to use different defaults
224 $default_item_label = 'notify';
225 $default_item_link = $this->a->get_baseurl(true).'/notify/view/'. $it['id'];
226 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
227 $default_item_url = $it['url'];
228 $default_item_text = strip_tags(bbcode($it['msg']));
229 $default_item_when = relative_date($it['date']);
233 $default_item_label = 'comment';
234 $default_item_link = $this->a->get_baseurl(true).'/display/'.$it['pguid'];
235 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
236 $default_item_url = $it['author-link'];
237 $default_item_text = sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']);
238 $default_item_when = relative_date($it['created']);
242 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
243 $default_item_link = $this->a->get_baseurl(true).'/display/'.$it['pguid'];
244 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
245 $default_item_url = $it['author-link'];
246 $default_item_text = (($it['id'] == $it['parent'])
247 ? sprintf(t("%s created a new post"), $it['author-name'])
248 : sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']));
249 $default_item_when = relative_date($it['created']);
253 // Transform the different types of notification in an usable array
254 switch ($it['verb']){
258 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
259 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
260 'url' => $it['author-link'],
261 'text' => sprintf(t("%s liked %s's post"), $it['author-name'], $it['pname']),
262 'when' => relative_date($it['created']),
263 'seen' => $it['seen']
267 case ACTIVITY_DISLIKE:
269 'label' => 'dislike',
270 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
271 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
272 'url' => $it['author-link'],
273 'text' => sprintf(t("%s disliked %s's post"), $it['author-name'], $it['pname']),
274 'when' => relative_date($it['created']),
275 'seen' => $it['seen']
279 case ACTIVITY_ATTEND:
282 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
283 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
284 'url' => $it['author-link'],
285 'text' => sprintf(t("%s is attending %s's event"), $it['author-name'], $it['pname']),
286 'when' => relative_date($it['created']),
287 'seen' => $it['seen']
291 case ACTIVITY_ATTENDNO:
293 'label' => 'attendno',
294 'link' => $this->a->get_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 not attending %s's event"), $it['author-name'], $it['pname']),
298 'when' => relative_date($it['created']),
299 'seen' => $it['seen']
303 case ACTIVITY_ATTENDMAYBE:
305 'label' => 'attendmaybe',
306 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
307 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
308 'url' => $it['author-link'],
309 'text' => sprintf(t("%s may attend %s's event"), $it['author-name'], $it['pname']),
310 'when' => relative_date($it['created']),
311 'seen' => $it['seen']
315 case ACTIVITY_FRIEND:
316 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
317 $obj = parse_xml_string($xmlhead.$it['object']);
318 $it['fname'] = $obj->title;
322 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
323 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
324 'url' => $it['author-link'],
325 'text' => sprintf(t("%s is now friends with %s"), $it['author-name'], $it['fname']),
326 'when' => relative_date($it['created']),
327 'seen' => $it['seen']
333 'label' => $default_item_label,
334 'link' => $default_item_link,
335 'image' => $default_item_image,
336 'url' => $default_item_url,
337 'text' => $default_item_text,
338 'when' => $default_item_when,
339 'seen' => $it['seen']
352 * @brief Total number of network notifications
353 * @param int|string $seen
354 * If 0 only include notifications into the query
355 * which aren't marked as "seen"
356 * @return int Number of network notifications
358 private function networkTotal($seen = 0) {
362 $sql_seen = " AND `item`.`unseen` = 1 ";
364 $r = q("SELECT COUNT(*) AS `total`
365 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
366 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
367 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
372 if (dbm::is_result($r))
373 return $r[0]['total'];
379 * @brief Get network notifications
381 * @param int|string $seen
382 * If 0 only include notifications into the query
383 * which aren't marked as "seen"
384 * @param int $start Start the query at this point
385 * @param int $limit Maximum number of query results
388 * string 'ident' => Notification identifier
389 * int 'total' => Total number of available network notifications
390 * array 'notifications' => Network notifications
392 public function networkNotifs($seen = 0, $start = 0, $limit = 80) {
394 $total = $this->networkTotal($seen);
399 $sql_seen = " AND `item`.`unseen` = 1 ";
402 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
403 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
404 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
405 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
406 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
407 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
409 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
410 intval(local_user()),
415 if (dbm::is_result($r))
416 $notifs = $this->formatNotifs($r, $ident);
419 'notifications' => $notifs,
428 * @brief Total number of system notifications
429 * @param int|string $seen
430 * If 0 only include notifications into the query
431 * which aren't marked as "seen"
432 * @return int Number of system notifications
434 private function systemTotal($seen = 0) {
438 $sql_seen = " AND `seen` = 0 ";
440 $r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
444 if (dbm::is_result($r))
445 return $r[0]['total'];
451 * @brief Get system notifications
453 * @param int|string $seen
454 * If 0 only include notifications into the query
455 * which aren't marked as "seen"
456 * @param int $start Start the query at this point
457 * @param int $limit Maximum number of query results
460 * string 'ident' => Notification identifier
461 * int 'total' => Total number of available system notifications
462 * array 'notifications' => System notifications
464 public function systemNotifs($seen = 0, $start = 0, $limit = 80) {
466 $total = $this->systemTotal($seen);
471 $sql_seen = " AND `seen` = 0 ";
473 $r = q("SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
474 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
475 intval(local_user()),
480 if (dbm::is_result($r))
481 $notifs = $this->formatNotifs($r, $ident);
484 'notifications' => $notifs,
493 * @brief Addional SQL query string for the personal notifications
495 * @return string The additional sql query
497 private function _personal_sql_extra() {
498 $myurl = $this->a->get_baseurl(true) . '/profile/'. $this->a->user['nickname'];
499 $myurl = substr($myurl,strpos($myurl,'://')+3);
500 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
501 $diasp_url = str_replace('/profile/','/u/',$myurl);
502 $sql_extra = sprintf(" AND ( `item`.`author-link` regexp '%s' or `item`.`tag` regexp '%s' or `item`.`tag` regexp '%s' ) ",
504 dbesc($myurl . '\\]'),
505 dbesc($diasp_url . '\\]')
512 * @brief Total number of personal notifications
513 * @param int|string $seen
514 * If 0 only include notifications into the query
515 * which aren't marked as "seen"
516 * @return int Number of personal notifications
518 private function personalTotal($seen = 0) {
520 $sql_extra = $this->_personal_sql_extra();
523 $sql_seen = " AND `item`.`unseen` = 1 ";
525 $r = q("SELECT COUNT(*) AS `total`
526 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
527 WHERE `item`.`visible` = 1
530 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 " ,
534 if (dbm::is_result($r))
535 return $r[0]['total'];
541 * @brief Get personal notifications
543 * @param int|string $seen
544 * If 0 only include notifications into the query
545 * which aren't marked as "seen"
546 * @param int $start Start the query at this point
547 * @param int $limit Maximum number of query results
550 * string 'ident' => Notification identifier
551 * int 'total' => Total number of available personal notifications
552 * array 'notifications' => Personal notifications
554 public function personalNotifs($seen = 0, $start = 0, $limit = 80) {
556 $total = $this->personalTotal($seen);
557 $sql_extra = $this->_personal_sql_extra();
562 $sql_seen = " AND `item`.`unseen` = 1 ";
564 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
565 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
566 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
567 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
568 WHERE `item`.`visible` = 1
571 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
572 ORDER BY `item`.`created` DESC LIMIT %d, %d " ,
573 intval(local_user()),
578 if (dbm::is_result($r))
579 $notifs = $this->formatNotifs($r, $ident);
582 'notifications' => $notifs,
591 * @brief Total number of home notifications
592 * @param int|string $seen
593 * If 0 only include notifications into the query
594 * which aren't marked as "seen"
595 * @return int Number of home notifications
597 private function homeTotal($seen = 0) {
601 $sql_seen = " AND `item`.`unseen` = 1 ";
603 $r = q("SELECT COUNT(*) AS `total` FROM `item`
604 WHERE `item`.`visible` = 1 AND
605 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
610 if (dbm::is_result($r))
611 return $r[0]['total'];
617 * @brief Get home notifications
619 * @param int|string $seen
620 * If 0 only include notifications into the query
621 * which aren't marked as "seen"
622 * @param int $start Start the query at this point
623 * @param int $limit Maximum number of query results
626 * string 'ident' => Notification identifier
627 * int 'total' => Total number of available home notifications
628 * array 'notifications' => Home notifications
630 public function homeNotifs($seen = 0, $start = 0, $limit = 80) {
632 $total = $this->homeTotal($seen);
637 $sql_seen = " AND `item`.`unseen` = 1 ";
639 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
640 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
641 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
642 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
643 WHERE `item`.`visible` = 1 AND
644 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
646 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
647 intval(local_user()),
652 if (dbm::is_result($r))
653 $notifs = $this->formatNotifs($r, $ident);
656 'notifications' => $notifs,
665 * @brief Total number of introductions
667 * If false only include introductions into the query
668 * which aren't marked as ignored
669 * @return int Number of introductions
671 private function introTotal($all = false) {
675 $sql_extra = " AND `ignore` = 0 ";
677 $r = q("SELECT COUNT(*) AS `total` FROM `intro`
678 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
679 intval($_SESSION['uid'])
682 if (dbm::is_result($r))
683 return $r[0]['total'];
689 * @brief Get introductions
692 * If false only include introductions into the query
693 * which aren't marked as ignored
694 * @param int $start Start the query at this point
695 * @param int $limit Maximum number of query results
698 * string 'ident' => Notification identifier
699 * int 'total' => Total number of available introductions
700 * array 'notifications' => Introductions
702 public function introNotifs($all = false, $start = 0, $limit = 80) {
703 $ident = 'introductions';
704 $total = $this->introTotal($seen);
709 $sql_extra = " AND `ignore` = 0 ";
711 /// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact
712 $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`,
713 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
714 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
715 `gcontact`.`network` AS `gnetwork`
717 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
718 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
719 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
720 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
722 intval($_SESSION['uid']),
727 if (dbm::is_result($r))
728 $notifs = $this->formatIntros($r);
733 'notifications' => $notifs,
740 * @brief Format the notification query in an usable array
742 * @param array $intros The array from the db query
743 * @return array with the introductions
745 private function formatIntros($intros) {
748 foreach($intros as $it) {
749 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
750 // We have to distinguish between these two because they use different data.
752 // Contact suggestions
755 $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
758 'label' => 'friend_suggestion',
759 'notify_type' => t('Friend Suggestion'),
760 'intro_id' => $it['intro_id'],
761 'madeby' => $it['name'],
762 'contact_id' => $it['contact-id'],
763 'photo' => ((x($it,'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
764 'name' => $it['fname'],
765 'url' => zrl($it['furl']),
766 'hidden' => $it['hidden'] == 1,
767 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
769 'knowyou' => $knowyou,
770 'note' => $it['note'],
771 'request' => $it['frequest'] . '?addr=' . $return_addr,
775 // Normal connection requests
778 // Probe the contact url to get missing data
779 $ret = probe_url($it["url"]);
781 if ($it['gnetwork'] == "")
782 $it['gnetwork'] = $ret["network"];
784 // Don't show these data until you are connected. Diaspora is doing the same.
785 if($it['gnetwork'] === NETWORK_DIASPORA) {
786 $it['glocation'] = "";
791 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
792 'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? t('Friend/Connect Request') : t('New Follower')),
793 'dfrn_id' => $it['issued-id'],
794 'uid' => $_SESSION['uid'],
795 'intro_id' => $it['intro_id'],
796 'contact_id' => $it['contact-id'],
797 'photo' => ((x($it,'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
798 'name' => $it['name'],
799 'location' => bbcode($it['glocation'], false, false),
800 'about' => bbcode($it['gabout'], false, false),
801 'keywords' => $it['gkeywords'],
802 'gender' => $it['ggender'],
803 'hidden' => $it['hidden'] == 1,
804 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
806 'zrl' => zrl($it['url']),
807 'addr' => $ret['addr'],
808 'network' => $it['gnetwork'],
809 'knowyou' => $it['knowyou'],
810 'note' => $it['note'],