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' => The date of the notification
204 * string 'ago' => T relative date of the notification
205 * bool 'seen' => Is the notification marked as "seen"
207 private function formatNotifs($notifs, $ident = "") {
212 if (dbm::is_result($notifs)) {
214 foreach ($notifs as $it) {
215 // Because we use different db tables for the notification query
216 // we have sometimes $it['unseen'] and sometimes $it['seen].
217 // So we will have to transform $it['unseen']
218 if (array_key_exists('unseen', $it)) {
219 $it['seen'] = ($it['unseen'] > 0 ? false : true);
222 // Depending on the identifier of the notification we need to use different defaults
225 $default_item_label = 'notify';
226 $default_item_link = $this->a->get_baseurl(true).'/notify/view/'. $it['id'];
227 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
228 $default_item_url = $it['url'];
229 $default_item_text = strip_tags(bbcode($it['msg']));
230 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['date'], 'r');
231 $default_item_ago = relative_date($it['date']);
235 $default_item_label = 'comment';
236 $default_item_link = $this->a->get_baseurl(true).'/display/'.$it['pguid'];
237 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
238 $default_item_url = $it['author-link'];
239 $default_item_text = sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']);
240 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
241 $default_item_ago = relative_date($it['created']);
245 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
246 $default_item_link = $this->a->get_baseurl(true).'/display/'.$it['pguid'];
247 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
248 $default_item_url = $it['author-link'];
249 $default_item_text = (($it['id'] == $it['parent'])
250 ? sprintf(t("%s created a new post"), $it['author-name'])
251 : sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']));
252 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
253 $default_item_ago = relative_date($it['created']);
257 // Transform the different types of notification in an usable array
258 switch ($it['verb']){
262 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
263 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
264 'url' => $it['author-link'],
265 'text' => sprintf(t("%s liked %s's post"), $it['author-name'], $it['pname']),
266 'when' => $default_item_when,
267 'ago' => $default_item_ago,
268 'seen' => $it['seen']
272 case ACTIVITY_DISLIKE:
274 'label' => 'dislike',
275 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
276 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
277 'url' => $it['author-link'],
278 'text' => sprintf(t("%s disliked %s's post"), $it['author-name'], $it['pname']),
279 'when' => $default_item_when,
280 'ago' => $default_item_ago,
281 'seen' => $it['seen']
285 case ACTIVITY_ATTEND:
288 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
289 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
290 'url' => $it['author-link'],
291 'text' => sprintf(t("%s is attending %s's event"), $it['author-name'], $it['pname']),
292 'when' => $default_item_when,
293 'ago' => $default_item_ago,
294 'seen' => $it['seen']
298 case ACTIVITY_ATTENDNO:
300 'label' => 'attendno',
301 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
302 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
303 'url' => $it['author-link'],
304 'text' => sprintf( t("%s is not attending %s's event"), $it['author-name'], $it['pname']),
305 'when' => $default_item_when,
306 'ago' => $default_item_ago,
307 'seen' => $it['seen']
311 case ACTIVITY_ATTENDMAYBE:
313 'label' => 'attendmaybe',
314 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
315 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
316 'url' => $it['author-link'],
317 'text' => sprintf(t("%s may attend %s's event"), $it['author-name'], $it['pname']),
318 'when' => $default_item_when,
319 'ago' => $default_item_ago,
320 'seen' => $it['seen']
324 case ACTIVITY_FRIEND:
325 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
326 $obj = parse_xml_string($xmlhead.$it['object']);
327 $it['fname'] = $obj->title;
331 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
332 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
333 'url' => $it['author-link'],
334 'text' => sprintf(t("%s is now friends with %s"), $it['author-name'], $it['fname']),
335 'when' => $default_item_when,
336 'ago' => $default_item_ago,
337 'seen' => $it['seen']
343 'label' => $default_item_label,
344 'link' => $default_item_link,
345 'image' => $default_item_image,
346 'url' => $default_item_url,
347 'text' => $default_item_text,
348 'when' => $default_item_when,
349 'ago' => $default_item_ago,
350 'seen' => $it['seen']
363 * @brief Total number of network notifications
364 * @param int|string $seen
365 * If 0 only include notifications into the query
366 * which aren't marked as "seen"
367 * @return int Number of network notifications
369 private function networkTotal($seen = 0) {
373 $sql_seen = " AND `item`.`unseen` = 1 ";
375 $r = q("SELECT COUNT(*) AS `total`
376 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
377 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
378 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
383 if (dbm::is_result($r))
384 return $r[0]['total'];
390 * @brief Get network notifications
392 * @param int|string $seen
393 * If 0 only include notifications into the query
394 * which aren't marked as "seen"
395 * @param int $start Start the query at this point
396 * @param int $limit Maximum number of query results
399 * string 'ident' => Notification identifier
400 * int 'total' => Total number of available network notifications
401 * array 'notifications' => Network notifications
403 public function networkNotifs($seen = 0, $start = 0, $limit = 80) {
405 $total = $this->networkTotal($seen);
410 $sql_seen = " AND `item`.`unseen` = 1 ";
413 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
414 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
415 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
416 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
417 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
418 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
420 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
421 intval(local_user()),
426 if (dbm::is_result($r))
427 $notifs = $this->formatNotifs($r, $ident);
430 'notifications' => $notifs,
439 * @brief Total number of system notifications
440 * @param int|string $seen
441 * If 0 only include notifications into the query
442 * which aren't marked as "seen"
443 * @return int Number of system notifications
445 private function systemTotal($seen = 0) {
449 $sql_seen = " AND `seen` = 0 ";
451 $r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
455 if (dbm::is_result($r))
456 return $r[0]['total'];
462 * @brief Get system notifications
464 * @param int|string $seen
465 * If 0 only include notifications into the query
466 * which aren't marked as "seen"
467 * @param int $start Start the query at this point
468 * @param int $limit Maximum number of query results
471 * string 'ident' => Notification identifier
472 * int 'total' => Total number of available system notifications
473 * array 'notifications' => System notifications
475 public function systemNotifs($seen = 0, $start = 0, $limit = 80) {
477 $total = $this->systemTotal($seen);
482 $sql_seen = " AND `seen` = 0 ";
484 $r = q("SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
485 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
486 intval(local_user()),
491 if (dbm::is_result($r))
492 $notifs = $this->formatNotifs($r, $ident);
495 'notifications' => $notifs,
504 * @brief Addional SQL query string for the personal notifications
506 * @return string The additional sql query
508 private function _personal_sql_extra() {
509 $myurl = $this->a->get_baseurl(true) . '/profile/'. $this->a->user['nickname'];
510 $myurl = substr($myurl,strpos($myurl,'://')+3);
511 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
512 $diasp_url = str_replace('/profile/','/u/',$myurl);
513 $sql_extra = sprintf(" AND ( `item`.`author-link` regexp '%s' or `item`.`tag` regexp '%s' or `item`.`tag` regexp '%s' ) ",
515 dbesc($myurl . '\\]'),
516 dbesc($diasp_url . '\\]')
523 * @brief Total number of personal notifications
524 * @param int|string $seen
525 * If 0 only include notifications into the query
526 * which aren't marked as "seen"
527 * @return int Number of personal notifications
529 private function personalTotal($seen = 0) {
531 $sql_extra = $this->_personal_sql_extra();
534 $sql_seen = " AND `item`.`unseen` = 1 ";
536 $r = q("SELECT COUNT(*) AS `total`
537 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
538 WHERE `item`.`visible` = 1
541 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 " ,
545 if (dbm::is_result($r))
546 return $r[0]['total'];
552 * @brief Get personal notifications
554 * @param int|string $seen
555 * If 0 only include notifications into the query
556 * which aren't marked as "seen"
557 * @param int $start Start the query at this point
558 * @param int $limit Maximum number of query results
561 * string 'ident' => Notification identifier
562 * int 'total' => Total number of available personal notifications
563 * array 'notifications' => Personal notifications
565 public function personalNotifs($seen = 0, $start = 0, $limit = 80) {
567 $total = $this->personalTotal($seen);
568 $sql_extra = $this->_personal_sql_extra();
573 $sql_seen = " AND `item`.`unseen` = 1 ";
575 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
576 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
577 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
578 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
579 WHERE `item`.`visible` = 1
582 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
583 ORDER BY `item`.`created` DESC LIMIT %d, %d " ,
584 intval(local_user()),
589 if (dbm::is_result($r))
590 $notifs = $this->formatNotifs($r, $ident);
593 'notifications' => $notifs,
602 * @brief Total number of home notifications
603 * @param int|string $seen
604 * If 0 only include notifications into the query
605 * which aren't marked as "seen"
606 * @return int Number of home notifications
608 private function homeTotal($seen = 0) {
612 $sql_seen = " AND `item`.`unseen` = 1 ";
614 $r = q("SELECT COUNT(*) AS `total` FROM `item`
615 WHERE `item`.`visible` = 1 AND
616 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
621 if (dbm::is_result($r))
622 return $r[0]['total'];
628 * @brief Get home notifications
630 * @param int|string $seen
631 * If 0 only include notifications into the query
632 * which aren't marked as "seen"
633 * @param int $start Start the query at this point
634 * @param int $limit Maximum number of query results
637 * string 'ident' => Notification identifier
638 * int 'total' => Total number of available home notifications
639 * array 'notifications' => Home notifications
641 public function homeNotifs($seen = 0, $start = 0, $limit = 80) {
643 $total = $this->homeTotal($seen);
648 $sql_seen = " AND `item`.`unseen` = 1 ";
650 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
651 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
652 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
653 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
654 WHERE `item`.`visible` = 1 AND
655 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
657 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
658 intval(local_user()),
663 if (dbm::is_result($r))
664 $notifs = $this->formatNotifs($r, $ident);
667 'notifications' => $notifs,
676 * @brief Total number of introductions
678 * If false only include introductions into the query
679 * which aren't marked as ignored
680 * @return int Number of introductions
682 private function introTotal($all = false) {
686 $sql_extra = " AND `ignore` = 0 ";
688 $r = q("SELECT COUNT(*) AS `total` FROM `intro`
689 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
690 intval($_SESSION['uid'])
693 if (dbm::is_result($r))
694 return $r[0]['total'];
700 * @brief Get introductions
703 * If false only include introductions into the query
704 * which aren't marked as ignored
705 * @param int $start Start the query at this point
706 * @param int $limit Maximum number of query results
709 * string 'ident' => Notification identifier
710 * int 'total' => Total number of available introductions
711 * array 'notifications' => Introductions
713 public function introNotifs($all = false, $start = 0, $limit = 80) {
714 $ident = 'introductions';
715 $total = $this->introTotal($seen);
720 $sql_extra = " AND `ignore` = 0 ";
722 /// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact
723 $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`,
724 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
725 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
726 `gcontact`.`network` AS `gnetwork`
728 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
729 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
730 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
731 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
733 intval($_SESSION['uid']),
738 if (dbm::is_result($r))
739 $notifs = $this->formatIntros($r);
744 'notifications' => $notifs,
751 * @brief Format the notification query in an usable array
753 * @param array $intros The array from the db query
754 * @return array with the introductions
756 private function formatIntros($intros) {
759 foreach($intros as $it) {
760 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
761 // We have to distinguish between these two because they use different data.
763 // Contact suggestions
766 $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
769 'label' => 'friend_suggestion',
770 'notify_type' => t('Friend Suggestion'),
771 'intro_id' => $it['intro_id'],
772 'madeby' => $it['name'],
773 'contact_id' => $it['contact-id'],
774 'photo' => ((x($it,'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
775 'name' => $it['fname'],
776 'url' => zrl($it['furl']),
777 'hidden' => $it['hidden'] == 1,
778 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
780 'knowyou' => $knowyou,
781 'note' => $it['note'],
782 'request' => $it['frequest'] . '?addr=' . $return_addr,
786 // Normal connection requests
789 // Probe the contact url to get missing data
790 $ret = probe_url($it["url"]);
792 if ($it['gnetwork'] == "")
793 $it['gnetwork'] = $ret["network"];
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' => $ret['addr'],
819 'network' => $it['gnetwork'],
820 'knowyou' => $it['knowyou'],
821 'note' => $it['note'],