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
147 * @return array with with notifications TabBar data
149 public function getTabs() {
152 'label' => t('System'),
153 'url'=>'notifications/system',
154 'sel'=> (($this->a->argv[1] == 'system') ? 'active' : ''),
155 'id' => 'system-tab',
159 'label' => t('Network'),
160 'url'=>'notifications/network',
161 'sel'=> (($this->a->argv[1] == 'network') ? 'active' : ''),
162 'id' => 'network-tab',
166 'label' => t('Personal'),
167 'url'=>'notifications/personal',
168 'sel'=> (($this->a->argv[1] == 'personal') ? 'active' : ''),
169 'id' => 'personal-tab',
173 'label' => t('Home'),
174 'url' => 'notifications/home',
175 'sel'=> (($this->a->argv[1] == 'home') ? 'active' : ''),
180 'label' => t('Introductions'),
181 'url' => 'notifications/intros',
182 'sel'=> (($this->a->argv[1] == 'intros') ? 'active' : ''),
192 * @brief Format the notification query in an usable array
194 * @param array $notifs The array from the db query
195 * @param string $ident The notifications identifier (e.g. network)
197 * string 'label' => The type of the notification
198 * string 'link' => URL to the source
199 * string 'image' => The avatar image
200 * string 'url' => The profile url of the contact
201 * string 'text' => The notification text
202 * string 'when' => The date of the notification
203 * string 'ago' => T 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 = datetime_convert('UTC', date_default_timezone_get(), $it['date'], 'r');
230 $default_item_ago = relative_date($it['date']);
234 $default_item_label = 'comment';
235 $default_item_link = $this->a->get_baseurl(true).'/display/'.$it['pguid'];
236 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
237 $default_item_url = $it['author-link'];
238 $default_item_text = sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']);
239 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
240 $default_item_ago = relative_date($it['created']);
244 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
245 $default_item_link = $this->a->get_baseurl(true).'/display/'.$it['pguid'];
246 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
247 $default_item_url = $it['author-link'];
248 $default_item_text = (($it['id'] == $it['parent'])
249 ? sprintf(t("%s created a new post"), $it['author-name'])
250 : sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']));
251 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
252 $default_item_ago = relative_date($it['created']);
256 // Transform the different types of notification in an usable array
257 switch ($it['verb']){
261 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
262 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
263 'url' => $it['author-link'],
264 'text' => sprintf(t("%s liked %s's post"), $it['author-name'], $it['pname']),
265 'when' => $default_item_when,
266 'ago' => $default_item_ago,
267 'seen' => $it['seen']
271 case ACTIVITY_DISLIKE:
273 'label' => 'dislike',
274 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
275 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
276 'url' => $it['author-link'],
277 'text' => sprintf(t("%s disliked %s's post"), $it['author-name'], $it['pname']),
278 'when' => $default_item_when,
279 'ago' => $default_item_ago,
280 'seen' => $it['seen']
284 case ACTIVITY_ATTEND:
287 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
288 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
289 'url' => $it['author-link'],
290 'text' => sprintf(t("%s is attending %s's event"), $it['author-name'], $it['pname']),
291 'when' => $default_item_when,
292 'ago' => $default_item_ago,
293 'seen' => $it['seen']
297 case ACTIVITY_ATTENDNO:
299 'label' => 'attendno',
300 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
301 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
302 'url' => $it['author-link'],
303 'text' => sprintf( t("%s is not attending %s's event"), $it['author-name'], $it['pname']),
304 'when' => $default_item_when,
305 'ago' => $default_item_ago,
306 'seen' => $it['seen']
310 case ACTIVITY_ATTENDMAYBE:
312 'label' => 'attendmaybe',
313 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
314 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
315 'url' => $it['author-link'],
316 'text' => sprintf(t("%s may attend %s's event"), $it['author-name'], $it['pname']),
317 'when' => $default_item_when,
318 'ago' => $default_item_ago,
319 'seen' => $it['seen']
323 case ACTIVITY_FRIEND:
324 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
325 $obj = parse_xml_string($xmlhead.$it['object']);
326 $it['fname'] = $obj->title;
330 'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
331 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
332 'url' => $it['author-link'],
333 'text' => sprintf(t("%s is now friends with %s"), $it['author-name'], $it['fname']),
334 'when' => $default_item_when,
335 'ago' => $default_item_ago,
336 'seen' => $it['seen']
342 'label' => $default_item_label,
343 'link' => $default_item_link,
344 'image' => $default_item_image,
345 'url' => $default_item_url,
346 'text' => $default_item_text,
347 'when' => $default_item_when,
348 'ago' => $default_item_ago,
349 'seen' => $it['seen']
362 * @brief Total number of network notifications
363 * @param int|string $seen
364 * If 0 only include notifications into the query
365 * which aren't marked as "seen"
366 * @return int Number of network notifications
368 private function networkTotal($seen = 0) {
372 $sql_seen = " AND `item`.`unseen` = 1 ";
374 $r = q("SELECT COUNT(*) AS `total`
375 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
376 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
377 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
382 if (dbm::is_result($r))
383 return $r[0]['total'];
389 * @brief Get network notifications
391 * @param int|string $seen
392 * If 0 only include notifications into the query
393 * which aren't marked as "seen"
394 * @param int $start Start the query at this point
395 * @param int $limit Maximum number of query results
398 * string 'ident' => Notification identifier
399 * int 'total' => Total number of available network notifications
400 * array 'notifications' => Network notifications
402 public function networkNotifs($seen = 0, $start = 0, $limit = 80) {
404 $total = $this->networkTotal($seen);
409 $sql_seen = " AND `item`.`unseen` = 1 ";
412 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
413 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
414 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
415 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
416 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
417 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
419 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
420 intval(local_user()),
425 if (dbm::is_result($r))
426 $notifs = $this->formatNotifs($r, $ident);
429 'notifications' => $notifs,
438 * @brief Total number of system notifications
439 * @param int|string $seen
440 * If 0 only include notifications into the query
441 * which aren't marked as "seen"
442 * @return int Number of system notifications
444 private function systemTotal($seen = 0) {
448 $sql_seen = " AND `seen` = 0 ";
450 $r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
454 if (dbm::is_result($r))
455 return $r[0]['total'];
461 * @brief Get system notifications
463 * @param int|string $seen
464 * If 0 only include notifications into the query
465 * which aren't marked as "seen"
466 * @param int $start Start the query at this point
467 * @param int $limit Maximum number of query results
470 * string 'ident' => Notification identifier
471 * int 'total' => Total number of available system notifications
472 * array 'notifications' => System notifications
474 public function systemNotifs($seen = 0, $start = 0, $limit = 80) {
476 $total = $this->systemTotal($seen);
481 $sql_seen = " AND `seen` = 0 ";
483 $r = q("SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
484 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
485 intval(local_user()),
490 if (dbm::is_result($r))
491 $notifs = $this->formatNotifs($r, $ident);
494 'notifications' => $notifs,
503 * @brief Addional SQL query string for the personal notifications
505 * @return string The additional sql query
507 private function _personal_sql_extra() {
508 $myurl = $this->a->get_baseurl(true) . '/profile/'. $this->a->user['nickname'];
509 $myurl = substr($myurl,strpos($myurl,'://')+3);
510 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
511 $diasp_url = str_replace('/profile/','/u/',$myurl);
512 $sql_extra = sprintf(" AND ( `item`.`author-link` regexp '%s' or `item`.`tag` regexp '%s' or `item`.`tag` regexp '%s' ) ",
514 dbesc($myurl . '\\]'),
515 dbesc($diasp_url . '\\]')
522 * @brief Total number of personal notifications
523 * @param int|string $seen
524 * If 0 only include notifications into the query
525 * which aren't marked as "seen"
526 * @return int Number of personal notifications
528 private function personalTotal($seen = 0) {
530 $sql_extra = $this->_personal_sql_extra();
533 $sql_seen = " AND `item`.`unseen` = 1 ";
535 $r = q("SELECT COUNT(*) AS `total`
536 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
537 WHERE `item`.`visible` = 1
540 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 " ,
544 if (dbm::is_result($r))
545 return $r[0]['total'];
551 * @brief Get personal notifications
553 * @param int|string $seen
554 * If 0 only include notifications into the query
555 * which aren't marked as "seen"
556 * @param int $start Start the query at this point
557 * @param int $limit Maximum number of query results
560 * string 'ident' => Notification identifier
561 * int 'total' => Total number of available personal notifications
562 * array 'notifications' => Personal notifications
564 public function personalNotifs($seen = 0, $start = 0, $limit = 80) {
566 $total = $this->personalTotal($seen);
567 $sql_extra = $this->_personal_sql_extra();
572 $sql_seen = " AND `item`.`unseen` = 1 ";
574 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
575 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
576 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
577 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
578 WHERE `item`.`visible` = 1
581 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
582 ORDER BY `item`.`created` DESC LIMIT %d, %d " ,
583 intval(local_user()),
588 if (dbm::is_result($r))
589 $notifs = $this->formatNotifs($r, $ident);
592 'notifications' => $notifs,
601 * @brief Total number of home notifications
602 * @param int|string $seen
603 * If 0 only include notifications into the query
604 * which aren't marked as "seen"
605 * @return int Number of home notifications
607 private function homeTotal($seen = 0) {
611 $sql_seen = " AND `item`.`unseen` = 1 ";
613 $r = q("SELECT COUNT(*) AS `total` FROM `item`
614 WHERE `item`.`visible` = 1 AND
615 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
620 if (dbm::is_result($r))
621 return $r[0]['total'];
627 * @brief Get home notifications
629 * @param int|string $seen
630 * If 0 only include notifications into the query
631 * which aren't marked as "seen"
632 * @param int $start Start the query at this point
633 * @param int $limit Maximum number of query results
636 * string 'ident' => Notification identifier
637 * int 'total' => Total number of available home notifications
638 * array 'notifications' => Home notifications
640 public function homeNotifs($seen = 0, $start = 0, $limit = 80) {
642 $total = $this->homeTotal($seen);
647 $sql_seen = " AND `item`.`unseen` = 1 ";
649 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
650 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
651 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
652 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
653 WHERE `item`.`visible` = 1 AND
654 `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
656 ORDER BY `item`.`created` DESC LIMIT %d, %d ",
657 intval(local_user()),
662 if (dbm::is_result($r))
663 $notifs = $this->formatNotifs($r, $ident);
666 'notifications' => $notifs,
675 * @brief Total number of introductions
677 * If false only include introductions into the query
678 * which aren't marked as ignored
679 * @return int Number of introductions
681 private function introTotal($all = false) {
685 $sql_extra = " AND `ignore` = 0 ";
687 $r = q("SELECT COUNT(*) AS `total` FROM `intro`
688 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
689 intval($_SESSION['uid'])
692 if (dbm::is_result($r))
693 return $r[0]['total'];
699 * @brief Get introductions
702 * If false only include introductions into the query
703 * which aren't marked as ignored
704 * @param int $start Start the query at this point
705 * @param int $limit Maximum number of query results
708 * string 'ident' => Notification identifier
709 * int 'total' => Total number of available introductions
710 * array 'notifications' => Introductions
712 public function introNotifs($all = false, $start = 0, $limit = 80) {
713 $ident = 'introductions';
714 $total = $this->introTotal($seen);
719 $sql_extra = " AND `ignore` = 0 ";
721 /// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact
722 $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`,
723 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
724 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
725 `gcontact`.`network` AS `gnetwork`
727 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
728 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
729 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
730 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
732 intval($_SESSION['uid']),
737 if (dbm::is_result($r))
738 $notifs = $this->formatIntros($r);
743 'notifications' => $notifs,
750 * @brief Format the notification query in an usable array
752 * @param array $intros The array from the db query
753 * @return array with the introductions
755 private function formatIntros($intros) {
758 foreach($intros as $it) {
759 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
760 // We have to distinguish between these two because they use different data.
762 // Contact suggestions
765 $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
768 'label' => 'friend_suggestion',
769 'notify_type' => t('Friend Suggestion'),
770 'intro_id' => $it['intro_id'],
771 'madeby' => $it['name'],
772 'contact_id' => $it['contact-id'],
773 'photo' => ((x($it,'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
774 'name' => $it['fname'],
775 'url' => zrl($it['furl']),
776 'hidden' => $it['hidden'] == 1,
777 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
779 'knowyou' => $knowyou,
780 'note' => $it['note'],
781 'request' => $it['frequest'] . '?addr=' . $return_addr,
785 // Normal connection requests
788 // Probe the contact url to get missing data
789 $ret = probe_url($it["url"]);
791 if ($it['gnetwork'] == "")
792 $it['gnetwork'] = $ret["network"];
794 // Don't show these data until you are connected. Diaspora is doing the same.
795 if($it['gnetwork'] === NETWORK_DIASPORA) {
796 $it['glocation'] = "";
801 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
802 'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? t('Friend/Connect Request') : t('New Follower')),
803 'dfrn_id' => $it['issued-id'],
804 'uid' => $_SESSION['uid'],
805 'intro_id' => $it['intro_id'],
806 'contact_id' => $it['contact-id'],
807 'photo' => ((x($it,'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
808 'name' => $it['name'],
809 'location' => bbcode($it['glocation'], false, false),
810 'about' => bbcode($it['gabout'], false, false),
811 'keywords' => $it['gkeywords'],
812 'gender' => $it['ggender'],
813 'hidden' => $it['hidden'] == 1,
814 'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
816 'zrl' => zrl($it['url']),
817 'addr' => $ret['addr'],
818 'network' => $it['gnetwork'],
819 'knowyou' => $it['knowyou'],
820 'note' => $it['note'],