3 * @file include/NotificationsManager.php
4 * @brief Methods for read and write notifications from/to database
5 * or for formatting notifications
8 require_once 'include/html2plain.php';
9 require_once 'include/probe.php';
10 require_once 'include/datetime.php';
11 require_once 'include/bbcode.php';
12 require_once 'include/Contact.php';
15 * @brief Methods for read and write notifications from/to database
16 * or for formatting notifications
18 class NotificationsManager {
21 public function __construct() {
26 * @brief set some extra note properties
28 * @param array $notes array of note arrays from db
29 * @return array Copy of input array with added properties
31 * Set some extra properties to note array from db:
32 * - timestamp as int in default TZ
33 * - date_rel : relative date string
34 * - msg_html: message as html string
35 * - msg_plain: message as plain text string
37 private function _set_extra($notes) {
39 foreach($notes as $n) {
40 $local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']);
41 $n['timestamp'] = strtotime($local_time);
42 $n['date_rel'] = relative_date($n['date']);
43 $n['msg_html'] = bbcode($n['msg'], false, false, false, false);
44 $n['msg_plain'] = explode("\n",trim(html2plain($n['msg_html'], 0)))[0];
53 * @brief Get all notifications for local_user()
55 * @param array $filter optional Array "column name"=>value: filter query by columns values
56 * @param string $order optional Space separated list of column to sort by. prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
57 * @param string $limit optional Query limits
59 * @return array of results or false on errors
61 public function getAll($filter = array(), $order="-date", $limit="") {
62 $filter_str = array();
64 foreach($filter as $column => $value) {
65 $filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
67 if (count($filter_str)>0) {
68 $filter_sql = "AND ".implode(" AND ", $filter_str);
71 $aOrder = explode(" ", $order);
73 foreach($aOrder as $o) {
83 $asOrder[] = "$o $dir";
85 $order_sql = implode(", ", $asOrder);
88 $limit = " LIMIT ".$limit;
90 $r = q("SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
94 if (dbm::is_result($r))
95 return $this->_set_extra($r);
101 * @brief Get one note for local_user() by $id value
104 * @return array note values or null if not found
106 public function getByID($id) {
107 $r = q("SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
111 if (dbm::is_result($r)) {
112 return $this->_set_extra($r)[0];
118 * @brief set seen state of $note of local_user()
121 * @param bool $seen optional true or false, default true
122 * @return bool true on success, false on errors
124 public function setSeen($note, $seen = true) {
125 return q("UPDATE `notify` SET `seen` = %d WHERE ( `link` = '%s' OR ( `parent` != 0 AND `parent` = %d AND `otype` = '%s' )) AND `uid` = %d",
127 dbesc($note['link']),
128 intval($note['parent']),
129 dbesc($note['otype']),
135 * @brief set seen state of all notifications of local_user()
137 * @param bool $seen optional true or false. default true
138 * @return bool true on success, false on error
140 public function setAllSeen($seen = true) {
141 return q("UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
148 * @brief List of pages for the Notifications TabBar
150 * @return array with with notifications TabBar data
152 public function getTabs() {
155 'label' => t('System'),
156 'url'=>'notifications/system',
157 'sel'=> (($this->a->argv[1] == 'system') ? 'active' : ''),
158 'id' => 'system-tab',
162 'label' => t('Network'),
163 'url'=>'notifications/network',
164 'sel'=> (($this->a->argv[1] == 'network') ? 'active' : ''),
165 'id' => 'network-tab',
169 'label' => t('Personal'),
170 'url'=>'notifications/personal',
171 'sel'=> (($this->a->argv[1] == 'personal') ? 'active' : ''),
172 'id' => 'personal-tab',
176 'label' => t('Home'),
177 'url' => 'notifications/home',
178 'sel'=> (($this->a->argv[1] == 'home') ? 'active' : ''),
183 'label' => t('Introductions'),
184 'url' => 'notifications/intros',
185 'sel'=> (($this->a->argv[1] == 'intros') ? 'active' : ''),
195 * @brief Format the notification query in an usable array
197 * @param array $notifs The array from the db query
198 * @param string $ident The notifications identifier (e.g. network)
200 * string 'label' => The type of the notification
201 * string 'link' => URL to the source
202 * string 'image' => The avatar image
203 * string 'url' => The profile url of the contact
204 * string 'text' => The notification text
205 * string 'when' => The date of the notification
206 * string 'ago' => T relative date of the notification
207 * bool 'seen' => Is the notification marked as "seen"
209 private function formatNotifs($notifs, $ident = "") {
214 if (dbm::is_result($notifs)) {
216 foreach ($notifs as $it) {
217 // Because we use different db tables for the notification query
218 // we have sometimes $it['unseen'] and sometimes $it['seen].
219 // So we will have to transform $it['unseen']
220 if (array_key_exists('unseen', $it)) {
221 $it['seen'] = ($it['unseen'] > 0 ? false : true);
224 // Depending on the identifier of the notification we need to use different defaults
227 $default_item_label = 'notify';
228 $default_item_link = $this->a->get_baseurl(true).'/notify/view/'. $it['id'];
229 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
230 $default_item_url = $it['url'];
231 $default_item_text = strip_tags(bbcode($it['msg']));
232 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['date'], 'r');
233 $default_item_ago = relative_date($it['date']);
237 $default_item_label = 'comment';
238 $default_item_link = $this->a->get_baseurl(true).'/display/'.$it['pguid'];
239 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
240 $default_item_url = $it['author-link'];
241 $default_item_text = sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']);
242 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
243 $default_item_ago = relative_date($it['created']);
247 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
248 $default_item_link = $this->a->get_baseurl(true).'/display/'.$it['pguid'];
249 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
250 $default_item_url = $it['author-link'];
251 $default_item_text = (($it['id'] == $it['parent'])
252 ? sprintf(t("%s created a new post"), $it['author-name'])
253 : sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']));
254 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
255 $default_item_ago = relative_date($it['created']);
259 // Transform the different types of notification in an usable array
260 switch ($it['verb']){
264 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
265 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
266 'url' => $it['author-link'],
267 'text' => sprintf(t("%s liked %s's post"), $it['author-name'], $it['pname']),
268 'when' => $default_item_when,
269 'ago' => $default_item_ago,
270 'seen' => $it['seen']
274 case ACTIVITY_DISLIKE:
276 'label' => 'dislike',
277 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
278 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
279 'url' => $it['author-link'],
280 'text' => sprintf(t("%s disliked %s's post"), $it['author-name'], $it['pname']),
281 'when' => $default_item_when,
282 'ago' => $default_item_ago,
283 'seen' => $it['seen']
287 case ACTIVITY_ATTEND:
290 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
291 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
292 'url' => $it['author-link'],
293 'text' => sprintf(t("%s is attending %s's event"), $it['author-name'], $it['pname']),
294 'when' => $default_item_when,
295 'ago' => $default_item_ago,
296 'seen' => $it['seen']
300 case ACTIVITY_ATTENDNO:
302 'label' => 'attendno',
303 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
304 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
305 'url' => $it['author-link'],
306 'text' => sprintf( t("%s is not attending %s's event"), $it['author-name'], $it['pname']),
307 'when' => $default_item_when,
308 'ago' => $default_item_ago,
309 'seen' => $it['seen']
313 case ACTIVITY_ATTENDMAYBE:
315 'label' => 'attendmaybe',
316 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
317 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
318 'url' => $it['author-link'],
319 'text' => sprintf(t("%s may attend %s's event"), $it['author-name'], $it['pname']),
320 'when' => $default_item_when,
321 'ago' => $default_item_ago,
322 'seen' => $it['seen']
326 case ACTIVITY_FRIEND:
327 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
328 $obj = parse_xml_string($xmlhead.$it['object']);
329 $it['fname'] = $obj->title;
333 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
334 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
335 'url' => $it['author-link'],
336 'text' => sprintf(t("%s is now friends with %s"), $it['author-name'], $it['fname']),
337 'when' => $default_item_when,
338 'ago' => $default_item_ago,
339 'seen' => $it['seen']
345 'label' => $default_item_label,
346 'link' => $default_item_link,
347 'image' => $default_item_image,
348 'url' => $default_item_url,
349 'text' => $default_item_text,
350 'when' => $default_item_when,
351 'ago' => $default_item_ago,
352 'seen' => $it['seen']
365 * @brief Total number of network notifications
366 * @param int|string $seen
367 * If 0 only include notifications into the query
368 * which aren't marked as "seen"
369 * @return int Number of network notifications
371 private function networkTotal($seen = 0) {
375 $sql_seen = " AND `item`.`unseen` = 1 ";
377 $r = q("SELECT COUNT(*) AS `total`
378 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
379 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
380 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
385 if (dbm::is_result($r))
386 return $r[0]['total'];
392 * @brief Get network notifications
394 * @param int|string $seen
395 * If 0 only include notifications into the query
396 * which aren't marked as "seen"
397 * @param int $start Start the query at this point
398 * @param int $limit Maximum number of query results
401 * string 'ident' => Notification identifier
402 * int 'total' => Total number of available network notifications
403 * array 'notifications' => Network notifications
405 public function networkNotifs($seen = 0, $start = 0, $limit = 80) {
407 $total = $this->networkTotal($seen);
412 $sql_seen = " AND `item`.`unseen` = 1 ";
415 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
416 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
417 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
418 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
419 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
420 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
422 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
423 intval(local_user()),
428 if (dbm::is_result($r))
429 $notifs = $this->formatNotifs($r, $ident);
432 'notifications' => $notifs,
441 * @brief Total number of system notifications
442 * @param int|string $seen
443 * If 0 only include notifications into the query
444 * which aren't marked as "seen"
445 * @return int Number of system notifications
447 private function systemTotal($seen = 0) {
451 $sql_seen = " AND `seen` = 0 ";
453 $r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
457 if (dbm::is_result($r))
458 return $r[0]['total'];
464 * @brief Get system notifications
466 * @param int|string $seen
467 * If 0 only include notifications into the query
468 * which aren't marked as "seen"
469 * @param int $start Start the query at this point
470 * @param int $limit Maximum number of query results
473 * string 'ident' => Notification identifier
474 * int 'total' => Total number of available system notifications
475 * array 'notifications' => System notifications
477 public function systemNotifs($seen = 0, $start = 0, $limit = 80) {
479 $total = $this->systemTotal($seen);
484 $sql_seen = " AND `seen` = 0 ";
486 $r = q("SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
487 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
488 intval(local_user()),
493 if (dbm::is_result($r))
494 $notifs = $this->formatNotifs($r, $ident);
497 'notifications' => $notifs,
506 * @brief Addional SQL query string for the personal notifications
508 * @return string The additional sql query
510 private function _personal_sql_extra() {
511 $myurl = $this->a->get_baseurl(true) . '/profile/'. $this->a->user['nickname'];
512 $myurl = substr($myurl,strpos($myurl,'://')+3);
513 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
514 $diasp_url = str_replace('/profile/','/u/',$myurl);
515 $sql_extra = sprintf(" AND ( `item`.`author-link` regexp '%s' or `item`.`tag` regexp '%s' or `item`.`tag` regexp '%s' ) ",
517 dbesc($myurl . '\\]'),
518 dbesc($diasp_url . '\\]')
525 * @brief Total number of personal notifications
526 * @param int|string $seen
527 * If 0 only include notifications into the query
528 * which aren't marked as "seen"
529 * @return int Number of personal notifications
531 private function personalTotal($seen = 0) {
533 $sql_extra = $this->_personal_sql_extra();
536 $sql_seen = " AND `item`.`unseen` = 1 ";
538 $r = q("SELECT COUNT(*) AS `total`
539 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
540 WHERE `item`.`visible` = 1
543 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 " ,
547 if (dbm::is_result($r))
548 return $r[0]['total'];
554 * @brief Get personal notifications
556 * @param int|string $seen
557 * If 0 only include notifications into the query
558 * which aren't marked as "seen"
559 * @param int $start Start the query at this point
560 * @param int $limit Maximum number of query results
563 * string 'ident' => Notification identifier
564 * int 'total' => Total number of available personal notifications
565 * array 'notifications' => Personal notifications
567 public function personalNotifs($seen = 0, $start = 0, $limit = 80) {
569 $total = $this->personalTotal($seen);
570 $sql_extra = $this->_personal_sql_extra();
575 $sql_seen = " AND `item`.`unseen` = 1 ";
577 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
578 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
579 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
580 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
581 WHERE `item`.`visible` = 1
584 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
585 ORDER BY `item`.`created` DESC LIMIT %d, %d " ,
586 intval(local_user()),
591 if (dbm::is_result($r))
592 $notifs = $this->formatNotifs($r, $ident);
595 'notifications' => $notifs,
604 * @brief Total number of home notifications
605 * @param int|string $seen
606 * If 0 only include notifications into the query
607 * which aren't marked as "seen"
608 * @return int Number of home notifications
610 private function homeTotal($seen = 0) {
614 $sql_seen = " AND `item`.`unseen` = 1 ";
616 $r = q("SELECT COUNT(*) AS `total` FROM `item`
617 WHERE `item`.`visible` = 1 AND
618 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
623 if (dbm::is_result($r))
624 return $r[0]['total'];
630 * @brief Get home notifications
632 * @param int|string $seen
633 * If 0 only include notifications into the query
634 * which aren't marked as "seen"
635 * @param int $start Start the query at this point
636 * @param int $limit Maximum number of query results
639 * string 'ident' => Notification identifier
640 * int 'total' => Total number of available home notifications
641 * array 'notifications' => Home notifications
643 public function homeNotifs($seen = 0, $start = 0, $limit = 80) {
645 $total = $this->homeTotal($seen);
650 $sql_seen = " AND `item`.`unseen` = 1 ";
652 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
653 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
654 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
655 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
656 WHERE `item`.`visible` = 1 AND
657 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
659 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
660 intval(local_user()),
665 if (dbm::is_result($r))
666 $notifs = $this->formatNotifs($r, $ident);
669 'notifications' => $notifs,
678 * @brief Total number of introductions
680 * If false only include introductions into the query
681 * which aren't marked as ignored
682 * @return int Number of introductions
684 private function introTotal($all = false) {
688 $sql_extra = " AND `ignore` = 0 ";
690 $r = q("SELECT COUNT(*) AS `total` FROM `intro`
691 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
692 intval($_SESSION['uid'])
695 if (dbm::is_result($r))
696 return $r[0]['total'];
702 * @brief Get introductions
705 * If false only include introductions into the query
706 * which aren't marked as ignored
707 * @param int $start Start the query at this point
708 * @param int $limit Maximum number of query results
711 * string 'ident' => Notification identifier
712 * int 'total' => Total number of available introductions
713 * array 'notifications' => Introductions
715 public function introNotifs($all = false, $start = 0, $limit = 80) {
716 $ident = 'introductions';
717 $total = $this->introTotal($seen);
722 $sql_extra = " AND `ignore` = 0 ";
724 /// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact
725 $r = q("SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
726 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`,
727 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
728 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
729 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
730 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
732 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
733 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
734 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
735 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
737 intval($_SESSION['uid']),
742 if (dbm::is_result($r))
743 $notifs = $this->formatIntros($r);
748 'notifications' => $notifs,
755 * @brief Format the notification query in an usable array
757 * @param array $intros The array from the db query
758 * @return array with the introductions
760 private function formatIntros($intros) {
763 foreach($intros as $it) {
764 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
765 // We have to distinguish between these two because they use different data.
767 // Contact suggestions
770 $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
773 'label' => 'friend_suggestion',
774 'notify_type' => t('Friend Suggestion'),
775 'intro_id' => $it['intro_id'],
776 'madeby' => $it['name'],
777 'contact_id' => $it['contact-id'],
778 'photo' => ((x($it,'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
779 'name' => $it['fname'],
780 'url' => zrl($it['furl']),
781 'hidden' => $it['hidden'] == 1,
782 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
784 'knowyou' => $knowyou,
785 'note' => $it['note'],
786 'request' => $it['frequest'] . '?addr=' . $return_addr,
790 // Normal connection requests
793 $it = $this->getMissingIntroData($it);
795 // Don't show these data until you are connected. Diaspora is doing the same.
796 if($it['gnetwork'] === NETWORK_DIASPORA) {
797 $it['glocation'] = "";
802 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
803 'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? t('Friend/Connect Request') : t('New Follower')),
804 'dfrn_id' => $it['issued-id'],
805 'uid' => $_SESSION['uid'],
806 'intro_id' => $it['intro_id'],
807 'contact_id' => $it['contact-id'],
808 'photo' => ((x($it,'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
809 'name' => $it['name'],
810 'location' => bbcode($it['glocation'], false, false),
811 'about' => bbcode($it['gabout'], false, false),
812 'keywords' => $it['gkeywords'],
813 'gender' => $it['ggender'],
814 'hidden' => $it['hidden'] == 1,
815 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
817 'zrl' => zrl($it['url']),
818 'addr' => $it['gaddr'],
819 'network' => $it['gnetwork'],
820 'knowyou' => $it['knowyou'],
821 'note' => $it['note'],
832 * @brief Check for missing contact data and try to fetch the data from
835 * @param array $arr The input array with the intro data
837 * @return array The array with the intro data
839 private function getMissingIntroData($arr) {
840 // If the network and the addr isn't available from the gcontact
841 // table entry, take the one of the contact table entry
842 if ($arr['gnetwork'] == "") {
843 $arr['gnetwork'] = $arr['network'];
845 if ($arr['gaddr'] == "") {
846 $arr['gaddr'] = $arr['addr'];
849 // If the network and addr is still not available
850 // get the missing data data from other sources
851 if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
852 $ret = get_contact_details_by_url($arr['url']);
854 if ($arr['gnetwork'] == "" && $ret['network'] != "") {
855 $arr['gnetwork'] = $ret['network'];
857 if ($arr['gaddr'] == "" && $ret['addr'] != "") {
858 $arr['gaddr'] = $ret['addr'];