3 * @file src/Core/NotificationsManager.php
4 * @brief Methods for read and write notifications from/to database
5 * or for formatting notifications
7 namespace Friendica\Core;
9 use Friendica\BaseObject;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Database\DBA;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Item;
15 use Friendica\Util\DateTimeFormat;
16 use Friendica\Util\Proxy as ProxyUtils;
17 use Friendica\Util\Temporal;
18 use Friendica\Util\XML;
20 require_once 'include/dba.php';
23 * @brief Methods for read and write notifications from/to database
24 * or for formatting notifications
26 class NotificationsManager extends BaseObject
29 * @brief set some extra note properties
31 * @param array $notes array of note arrays from db
32 * @return array Copy of input array with added properties
34 * Set some extra properties to note array from db:
35 * - timestamp as int in default TZ
36 * - date_rel : relative date string
37 * - msg_html: message as html string
38 * - msg_plain: message as plain text string
40 private function _set_extra($notes)
43 foreach ($notes as $n) {
44 $local_time = DateTimeFormat::local($n['date']);
45 $n['timestamp'] = strtotime($local_time);
46 $n['date_rel'] = Temporal::getRelativeDate($n['date']);
47 $n['msg_html'] = BBCode::convert($n['msg'], false);
48 $n['msg_plain'] = explode("\n", trim(HTML::toPlaintext($n['msg_html'], 0)))[0];
56 * @brief Get all notifications for local_user()
58 * @param array $filter optional Array "column name"=>value: filter query by columns values
59 * @param string $order optional Space separated list of column to sort by.
60 * Prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
61 * @param string $limit optional Query limits
63 * @return array of results or false on errors
65 public function getAll($filter = [], $order = "-date", $limit = "")
69 foreach ($filter as $column => $value) {
70 $filter_str[] = sprintf("`%s` = '%s'", $column, DBA::escape($value));
72 if (count($filter_str) > 0) {
73 $filter_sql = "AND " . implode(" AND ", $filter_str);
76 $aOrder = explode(" ", $order);
78 foreach ($aOrder as $o) {
88 $asOrder[] = "$o $dir";
90 $order_sql = implode(", ", $asOrder);
93 $limit = " LIMIT " . $limit;
96 "SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
100 if (DBA::isResult($r)) {
101 return $this->_set_extra($r);
108 * @brief Get one note for local_user() by $id value
110 * @param int $id identity
111 * @return array note values or null if not found
113 public function getByID($id)
116 "SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
120 if (DBA::isResult($r)) {
121 return $this->_set_extra($r)[0];
127 * @brief set seen state of $note of local_user()
129 * @param array $note note array
130 * @param bool $seen optional true or false, default true
131 * @return bool true on success, false on errors
133 public function setSeen($note, $seen = true)
136 "UPDATE `notify` SET `seen` = %d WHERE (`link` = '%s' OR (`parent` != 0 AND `parent` = %d AND `otype` = '%s')) AND `uid` = %d",
138 DBA::escape($note['link']),
139 intval($note['parent']),
140 DBA::escape($note['otype']),
146 * @brief set seen state of all notifications of local_user()
148 * @param bool $seen optional true or false. default true
149 * @return bool true on success, false on error
151 public function setAllSeen($seen = true)
154 "UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
161 * @brief List of pages for the Notifications TabBar
163 * @return array with with notifications TabBar data
165 public function getTabs()
169 'label' => L10n::t('System'),
170 'url' => 'notifications/system',
171 'sel' => ((self::getApp()->argv[1] == 'system') ? 'active' : ''),
172 'id' => 'system-tab',
176 'label' => L10n::t('Network'),
177 'url' => 'notifications/network',
178 'sel' => ((self::getApp()->argv[1] == 'network') ? 'active' : ''),
179 'id' => 'network-tab',
183 'label' => L10n::t('Personal'),
184 'url' => 'notifications/personal',
185 'sel' => ((self::getApp()->argv[1] == 'personal') ? 'active' : ''),
186 'id' => 'personal-tab',
190 'label' => L10n::t('Home'),
191 'url' => 'notifications/home',
192 'sel' => ((self::getApp()->argv[1] == 'home') ? 'active' : ''),
197 'label' => L10n::t('Introductions'),
198 'url' => 'notifications/intros',
199 'sel' => ((self::getApp()->argv[1] == 'intros') ? 'active' : ''),
209 * @brief Format the notification query in an usable array
211 * @param array $notifs The array from the db query
212 * @param string $ident The notifications identifier (e.g. network)
214 * string 'label' => The type of the notification
215 * string 'link' => URL to the source
216 * string 'image' => The avatar image
217 * string 'url' => The profile url of the contact
218 * string 'text' => The notification text
219 * string 'when' => The date of the notification
220 * string 'ago' => T relative date of the notification
221 * bool 'seen' => Is the notification marked as "seen"
223 private function formatNotifs(array $notifs, $ident = "")
228 if (DBA::isResult($notifs)) {
229 foreach ($notifs as $it) {
230 // Because we use different db tables for the notification query
231 // we have sometimes $it['unseen'] and sometimes $it['seen].
232 // So we will have to transform $it['unseen']
233 if (array_key_exists('unseen', $it)) {
234 $it['seen'] = ($it['unseen'] > 0 ? false : true);
237 // For feed items we use the user's contact, since the avatar is mostly self choosen.
238 if (!empty($it['network']) && $it['network'] == NETWORK_FEED) {
239 $it['author-avatar'] = $it['contact-avatar'];
242 // Depending on the identifier of the notification we need to use different defaults
245 $default_item_label = 'notify';
246 $default_item_link = System::baseUrl(true) . '/notify/view/' . $it['id'];
247 $default_item_image = ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_MICRO);
248 $default_item_url = $it['url'];
249 $default_item_text = strip_tags(BBCode::convert($it['msg']));
250 $default_item_when = DateTimeFormat::local($it['date'], 'r');
251 $default_item_ago = Temporal::getRelativeDate($it['date']);
255 $default_item_label = 'comment';
256 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
257 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
258 $default_item_url = $it['author-link'];
259 $default_item_text = L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']);
260 $default_item_when = DateTimeFormat::local($it['created'], 'r');
261 $default_item_ago = Temporal::getRelativeDate($it['created']);
265 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
266 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
267 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
268 $default_item_url = $it['author-link'];
269 $default_item_text = (($it['id'] == $it['parent'])
270 ? L10n::t("%s created a new post", $it['author-name'])
271 : L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']));
272 $default_item_when = DateTimeFormat::local($it['created'], 'r');
273 $default_item_ago = Temporal::getRelativeDate($it['created']);
276 // Transform the different types of notification in an usable array
277 switch ($it['verb']) {
281 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
282 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
283 'url' => $it['author-link'],
284 'text' => L10n::t("%s liked %s's post", $it['author-name'], $it['parent-author-name']),
285 'when' => $default_item_when,
286 'ago' => $default_item_ago,
287 'seen' => $it['seen']
291 case ACTIVITY_DISLIKE:
293 'label' => 'dislike',
294 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
295 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
296 'url' => $it['author-link'],
297 'text' => L10n::t("%s disliked %s's post", $it['author-name'], $it['parent-author-name']),
298 'when' => $default_item_when,
299 'ago' => $default_item_ago,
300 'seen' => $it['seen']
304 case ACTIVITY_ATTEND:
307 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
308 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
309 'url' => $it['author-link'],
310 'text' => L10n::t("%s is attending %s's event", $it['author-name'], $it['parent-author-name']),
311 'when' => $default_item_when,
312 'ago' => $default_item_ago,
313 'seen' => $it['seen']
317 case ACTIVITY_ATTENDNO:
319 'label' => 'attendno',
320 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
321 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
322 'url' => $it['author-link'],
323 'text' => L10n::t("%s is not attending %s's event", $it['author-name'], $it['parent-author-name']),
324 'when' => $default_item_when,
325 'ago' => $default_item_ago,
326 'seen' => $it['seen']
330 case ACTIVITY_ATTENDMAYBE:
332 'label' => 'attendmaybe',
333 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
334 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
335 'url' => $it['author-link'],
336 'text' => L10n::t("%s may attend %s's event", $it['author-name'], $it['parent-author-name']),
337 'when' => $default_item_when,
338 'ago' => $default_item_ago,
339 'seen' => $it['seen']
343 case ACTIVITY_FRIEND:
344 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
345 $obj = XML::parseString($xmlhead . $it['object']);
346 $it['fname'] = $obj->title;
350 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
351 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
352 'url' => $it['author-link'],
353 'text' => L10n::t("%s is now friends with %s", $it['author-name'], $it['fname']),
354 'when' => $default_item_when,
355 'ago' => $default_item_ago,
356 'seen' => $it['seen']
362 'label' => $default_item_label,
363 'link' => $default_item_link,
364 'image' => $default_item_image,
365 'url' => $default_item_url,
366 'text' => $default_item_text,
367 'when' => $default_item_when,
368 'ago' => $default_item_ago,
369 'seen' => $it['seen']
381 * @brief Get network notifications
383 * @param int|string $seen If 0 only include notifications into the query
384 * which aren't marked as "seen"
385 * @param int $start Start the query at this point
386 * @param int $limit Maximum number of query results
389 * string 'ident' => Notification identifier
390 * array 'notifications' => Network notifications
392 public function networkNotifs($seen = 0, $start = 0, $limit = 80)
397 $condition = ['wall' => false, 'uid' => local_user()];
400 $condition['unseen'] = true;
403 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
404 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
405 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
407 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
409 if (DBA::isResult($items)) {
410 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
414 'notifications' => $notifs,
422 * @brief Get system notifications
424 * @param int|string $seen If 0 only include notifications into the query
425 * which aren't marked as "seen"
426 * @param int $start Start the query at this point
427 * @param int $limit Maximum number of query results
430 * string 'ident' => Notification identifier
431 * array 'notifications' => System notifications
433 public function systemNotifs($seen = 0, $start = 0, $limit = 80)
440 $sql_seen = " AND NOT `seen` ";
444 "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen`, `verb` FROM `notify`
445 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
446 intval(local_user()),
451 if (DBA::isResult($r)) {
452 $notifs = $this->formatNotifs($r, $ident);
456 'notifications' => $notifs,
464 * @brief Get personal notifications
466 * @param int|string $seen If 0 only include notifications into the query
467 * which aren't marked as "seen"
468 * @param int $start Start the query at this point
469 * @param int $limit Maximum number of query results
472 * string 'ident' => Notification identifier
473 * array 'notifications' => Personal notifications
475 public function personalNotifs($seen = 0, $start = 0, $limit = 80)
480 $myurl = str_replace('http://', '', self::getApp()->contact['nurl']);
481 $diasp_url = str_replace('/profile/', '/u/', $myurl);
483 $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)",
484 local_user(), public_contact(), $myurl . '\\]', $diasp_url . '\\]'];
487 $condition[0] .= " AND `unseen`";
490 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
491 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
492 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
494 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
496 if (DBA::isResult($items)) {
497 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
501 'notifications' => $notifs,
509 * @brief Get home notifications
511 * @param int|string $seen If 0 only include notifications into the query
512 * which aren't marked as "seen"
513 * @param int $start Start the query at this point
514 * @param int $limit Maximum number of query results
517 * string 'ident' => Notification identifier
518 * array 'notifications' => Home notifications
520 public function homeNotifs($seen = 0, $start = 0, $limit = 80)
525 $condition = ['wall' => true, 'uid' => local_user()];
528 $condition['unseen'] = true;
531 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
532 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
533 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
534 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
536 if (DBA::isResult($items)) {
537 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
541 'notifications' => $notifs,
549 * @brief Get introductions
551 * @param bool $all If false only include introductions into the query
552 * which aren't marked as ignored
553 * @param int $start Start the query at this point
554 * @param int $limit Maximum number of query results
557 * string 'ident' => Notification identifier
558 * array 'notifications' => Introductions
560 public function introNotifs($all = false, $start = 0, $limit = 80)
562 $ident = 'introductions';
567 $sql_extra = " AND `ignore` = 0 ";
570 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
572 "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
573 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`,
574 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
575 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
576 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
577 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
579 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
580 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
581 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
582 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
584 intval($_SESSION['uid']),
588 if (DBA::isResult($r)) {
589 $notifs = $this->formatIntros($r);
594 'notifications' => $notifs,
601 * @brief Format the notification query in an usable array
603 * @param array $intros The array from the db query
604 * @return array with the introductions
606 private function formatIntros($intros)
610 foreach ($intros as $it) {
611 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
612 // We have to distinguish between these two because they use different data.
613 // Contact suggestions
615 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->get_hostname() . ((self::getApp()->urlpath) ? '/' . self::getApp()->urlpath : ''));
618 'label' => 'friend_suggestion',
619 'notify_type' => L10n::t('Friend Suggestion'),
620 'intro_id' => $it['intro_id'],
621 'madeby' => $it['name'],
622 'madeby_url' => $it['url'],
623 'madeby_zrl' => Contact::magicLink($it['url']),
624 'madeby_addr' => $it['addr'],
625 'contact_id' => $it['contact-id'],
626 'photo' => ((x($it, 'fphoto')) ? ProxyUtils::proxifyUrl($it['fphoto'], false, ProxyUtils::SIZE_SMALL) : "images/person-175.jpg"),
627 'name' => $it['fname'],
628 'url' => $it['furl'],
629 'zrl' => Contact::magicLink($it['furl']),
630 'hidden' => $it['hidden'] == 1,
631 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
632 'knowyou' => $knowyou,
633 'note' => $it['note'],
634 'request' => $it['frequest'] . '?addr=' . $return_addr,
637 // Normal connection requests
639 $it = $this->getMissingIntroData($it);
641 // Don't show these data until you are connected. Diaspora is doing the same.
642 if ($it['gnetwork'] === NETWORK_DIASPORA) {
643 $it['glocation'] = "";
648 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
649 'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? L10n::t('Friend/Connect Request') : L10n::t('New Follower')),
650 'dfrn_id' => $it['issued-id'],
651 'uid' => $_SESSION['uid'],
652 'intro_id' => $it['intro_id'],
653 'contact_id' => $it['contact-id'],
654 'photo' => ((x($it, 'photo')) ? ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_SMALL) : "images/person-175.jpg"),
655 'name' => $it['name'],
656 'location' => BBCode::convert($it['glocation'], false),
657 'about' => BBCode::convert($it['gabout'], false),
658 'keywords' => $it['gkeywords'],
659 'gender' => $it['ggender'],
660 'hidden' => $it['hidden'] == 1,
661 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
663 'zrl' => Contact::magicLink($it['url']),
664 'addr' => $it['gaddr'],
665 'network' => $it['gnetwork'],
666 'knowyou' => $it['knowyou'],
667 'note' => $it['note'],
678 * @brief Check for missing contact data and try to fetch the data from
681 * @param array $arr The input array with the intro data
683 * @return array The array with the intro data
685 private function getMissingIntroData($arr)
687 // If the network and the addr isn't available from the gcontact
688 // table entry, take the one of the contact table entry
689 if ($arr['gnetwork'] == "") {
690 $arr['gnetwork'] = $arr['network'];
692 if ($arr['gaddr'] == "") {
693 $arr['gaddr'] = $arr['addr'];
696 // If the network and addr is still not available
697 // get the missing data data from other sources
698 if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
699 $ret = Contact::getDetailsByURL($arr['url']);
701 if ($arr['gnetwork'] == "" && $ret['network'] != "") {
702 $arr['gnetwork'] = $ret['network'];
704 if ($arr['gaddr'] == "" && $ret['addr'] != "") {
705 $arr['gaddr'] = $ret['addr'];