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\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Database\DBA;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Item;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Proxy as ProxyUtils;
19 use Friendica\Util\Temporal;
20 use Friendica\Util\XML;
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()
167 $selected = defaults(self::getApp()->argv, 1, '');
171 'label' => L10n::t('System'),
172 'url' => 'notifications/system',
173 'sel' => (($selected == 'system') ? 'active' : ''),
174 'id' => 'system-tab',
178 'label' => L10n::t('Network'),
179 'url' => 'notifications/network',
180 'sel' => (($selected == 'network') ? 'active' : ''),
181 'id' => 'network-tab',
185 'label' => L10n::t('Personal'),
186 'url' => 'notifications/personal',
187 'sel' => (($selected == 'personal') ? 'active' : ''),
188 'id' => 'personal-tab',
192 'label' => L10n::t('Home'),
193 'url' => 'notifications/home',
194 'sel' => (($selected == 'home') ? 'active' : ''),
199 'label' => L10n::t('Introductions'),
200 'url' => 'notifications/intros',
201 'sel' => (($selected == 'intros') ? 'active' : ''),
211 * @brief Format the notification query in an usable array
213 * @param array $notifs The array from the db query
214 * @param string $ident The notifications identifier (e.g. network)
216 * string 'label' => The type of the notification
217 * string 'link' => URL to the source
218 * string 'image' => The avatar image
219 * string 'url' => The profile url of the contact
220 * string 'text' => The notification text
221 * string 'when' => The date of the notification
222 * string 'ago' => T relative date of the notification
223 * bool 'seen' => Is the notification marked as "seen"
225 private function formatNotifs(array $notifs, $ident = "")
230 if (DBA::isResult($notifs)) {
231 foreach ($notifs as $it) {
232 // Because we use different db tables for the notification query
233 // we have sometimes $it['unseen'] and sometimes $it['seen].
234 // So we will have to transform $it['unseen']
235 if (array_key_exists('unseen', $it)) {
236 $it['seen'] = ($it['unseen'] > 0 ? false : true);
239 // For feed items we use the user's contact, since the avatar is mostly self choosen.
240 if (!empty($it['network']) && $it['network'] == Protocol::FEED) {
241 $it['author-avatar'] = $it['contact-avatar'];
244 // Depending on the identifier of the notification we need to use different defaults
247 $default_item_label = 'notify';
248 $default_item_link = System::baseUrl(true) . '/notify/view/' . $it['id'];
249 $default_item_image = ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_MICRO);
250 $default_item_url = $it['url'];
251 $default_item_text = strip_tags(BBCode::convert($it['msg']));
252 $default_item_when = DateTimeFormat::local($it['date'], 'r');
253 $default_item_ago = Temporal::getRelativeDate($it['date']);
257 $default_item_label = 'comment';
258 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
259 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
260 $default_item_url = $it['author-link'];
261 $default_item_text = L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']);
262 $default_item_when = DateTimeFormat::local($it['created'], 'r');
263 $default_item_ago = Temporal::getRelativeDate($it['created']);
267 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
268 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
269 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
270 $default_item_url = $it['author-link'];
271 $default_item_text = (($it['id'] == $it['parent'])
272 ? L10n::t("%s created a new post", $it['author-name'])
273 : L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']));
274 $default_item_when = DateTimeFormat::local($it['created'], 'r');
275 $default_item_ago = Temporal::getRelativeDate($it['created']);
278 // Transform the different types of notification in an usable array
279 switch ($it['verb']) {
283 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
284 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
285 'url' => $it['author-link'],
286 'text' => L10n::t("%s liked %s's post", $it['author-name'], $it['parent-author-name']),
287 'when' => $default_item_when,
288 'ago' => $default_item_ago,
289 'seen' => $it['seen']
293 case ACTIVITY_DISLIKE:
295 'label' => 'dislike',
296 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
297 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
298 'url' => $it['author-link'],
299 'text' => L10n::t("%s disliked %s's post", $it['author-name'], $it['parent-author-name']),
300 'when' => $default_item_when,
301 'ago' => $default_item_ago,
302 'seen' => $it['seen']
306 case ACTIVITY_ATTEND:
309 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
310 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
311 'url' => $it['author-link'],
312 'text' => L10n::t("%s is attending %s's event", $it['author-name'], $it['parent-author-name']),
313 'when' => $default_item_when,
314 'ago' => $default_item_ago,
315 'seen' => $it['seen']
319 case ACTIVITY_ATTENDNO:
321 'label' => 'attendno',
322 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
323 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
324 'url' => $it['author-link'],
325 'text' => L10n::t("%s is not attending %s's event", $it['author-name'], $it['parent-author-name']),
326 'when' => $default_item_when,
327 'ago' => $default_item_ago,
328 'seen' => $it['seen']
332 case ACTIVITY_ATTENDMAYBE:
334 'label' => 'attendmaybe',
335 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
336 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
337 'url' => $it['author-link'],
338 'text' => L10n::t("%s may attend %s's event", $it['author-name'], $it['parent-author-name']),
339 'when' => $default_item_when,
340 'ago' => $default_item_ago,
341 'seen' => $it['seen']
345 case ACTIVITY_FRIEND:
346 if (!isset($it['object'])) {
349 'link' => $default_item_link,
350 'image' => $default_item_image,
351 'url' => $default_item_url,
352 'text' => $default_item_text,
353 'when' => $default_item_when,
354 'ago' => $default_item_ago,
355 'seen' => $it['seen']
359 /// @todo Check if this part here is used at all
360 Logger::log('Complete data: ' . json_encode($it) . ' - ' . System::callstack(20), Logger::DEBUG);
362 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
363 $obj = XML::parseString($xmlhead . $it['object']);
364 $it['fname'] = $obj->title;
368 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
369 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
370 'url' => $it['author-link'],
371 'text' => L10n::t("%s is now friends with %s", $it['author-name'], $it['fname']),
372 'when' => $default_item_when,
373 'ago' => $default_item_ago,
374 'seen' => $it['seen']
380 'label' => $default_item_label,
381 'link' => $default_item_link,
382 'image' => $default_item_image,
383 'url' => $default_item_url,
384 'text' => $default_item_text,
385 'when' => $default_item_when,
386 'ago' => $default_item_ago,
387 'seen' => $it['seen']
399 * @brief Get network notifications
401 * @param int|string $seen If 0 only include notifications into the query
402 * which aren't marked as "seen"
403 * @param int $start Start the query at this point
404 * @param int $limit Maximum number of query results
407 * string 'ident' => Notification identifier
408 * array 'notifications' => Network notifications
410 public function networkNotifs($seen = 0, $start = 0, $limit = 80)
415 $condition = ['wall' => false, 'uid' => local_user()];
418 $condition['unseen'] = true;
421 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
422 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
423 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
425 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
427 if (DBA::isResult($items)) {
428 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
432 'notifications' => $notifs,
440 * @brief Get system notifications
442 * @param int|string $seen If 0 only include notifications into the query
443 * which aren't marked as "seen"
444 * @param int $start Start the query at this point
445 * @param int $limit Maximum number of query results
448 * string 'ident' => Notification identifier
449 * array 'notifications' => System notifications
451 public function systemNotifs($seen = 0, $start = 0, $limit = 80)
458 $sql_seen = " AND NOT `seen` ";
462 "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen`, `verb` FROM `notify`
463 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
464 intval(local_user()),
469 if (DBA::isResult($r)) {
470 $notifs = $this->formatNotifs($r, $ident);
474 'notifications' => $notifs,
482 * @brief Get personal notifications
484 * @param int|string $seen If 0 only include notifications into the query
485 * which aren't marked as "seen"
486 * @param int $start Start the query at this point
487 * @param int $limit Maximum number of query results
490 * string 'ident' => Notification identifier
491 * array 'notifications' => Personal notifications
493 public function personalNotifs($seen = 0, $start = 0, $limit = 80)
498 $myurl = str_replace('http://', '', self::getApp()->contact['nurl']);
499 $diasp_url = str_replace('/profile/', '/u/', $myurl);
501 $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)",
502 local_user(), public_contact(), $myurl . '\\]', $diasp_url . '\\]'];
505 $condition[0] .= " AND `unseen`";
508 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
509 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
510 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
512 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
514 if (DBA::isResult($items)) {
515 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
519 'notifications' => $notifs,
527 * @brief Get home notifications
529 * @param int|string $seen If 0 only include notifications into the query
530 * which aren't marked as "seen"
531 * @param int $start Start the query at this point
532 * @param int $limit Maximum number of query results
535 * string 'ident' => Notification identifier
536 * array 'notifications' => Home notifications
538 public function homeNotifs($seen = 0, $start = 0, $limit = 80)
543 $condition = ['wall' => true, 'uid' => local_user()];
546 $condition['unseen'] = true;
549 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
550 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
551 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
552 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
554 if (DBA::isResult($items)) {
555 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
559 'notifications' => $notifs,
567 * @brief Get introductions
569 * @param bool $all If false only include introductions into the query
570 * which aren't marked as ignored
571 * @param int $start Start the query at this point
572 * @param int $limit Maximum number of query results
575 * string 'ident' => Notification identifier
576 * array 'notifications' => Introductions
578 public function introNotifs($all = false, $start = 0, $limit = 80)
580 $ident = 'introductions';
585 $sql_extra = " AND `ignore` = 0 ";
588 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
590 "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
591 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`,
592 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
593 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
594 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
595 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
597 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
598 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
599 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
600 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
602 intval($_SESSION['uid']),
606 if (DBA::isResult($r)) {
607 $notifs = $this->formatIntros($r);
612 'notifications' => $notifs,
619 * @brief Format the notification query in an usable array
621 * @param array $intros The array from the db query
622 * @return array with the introductions
624 private function formatIntros($intros)
628 foreach ($intros as $it) {
629 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
630 // We have to distinguish between these two because they use different data.
631 // Contact suggestions
633 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->getHostName() . ((self::getApp()->getURLPath()) ? '/' . self::getApp()->getURLPath() : ''));
636 'label' => 'friend_suggestion',
637 'notify_type' => L10n::t('Friend Suggestion'),
638 'intro_id' => $it['intro_id'],
639 'madeby' => $it['name'],
640 'madeby_url' => $it['url'],
641 'madeby_zrl' => Contact::magicLink($it['url']),
642 'madeby_addr' => $it['addr'],
643 'contact_id' => $it['contact-id'],
644 'photo' => (!empty($it['fphoto']) ? ProxyUtils::proxifyUrl($it['fphoto'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"),
645 'name' => $it['fname'],
646 'url' => $it['furl'],
647 'zrl' => Contact::magicLink($it['furl']),
648 'hidden' => $it['hidden'] == 1,
649 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
650 'knowyou' => $knowyou,
651 'note' => $it['note'],
652 'request' => $it['frequest'] . '?addr=' . $return_addr,
655 // Normal connection requests
657 $it = $this->getMissingIntroData($it);
659 if (empty($it['url'])) {
663 // Don't show these data until you are connected. Diaspora is doing the same.
664 if ($it['gnetwork'] === Protocol::DIASPORA) {
665 $it['glocation'] = "";
670 'label' => (($it['network'] !== Protocol::OSTATUS) ? 'friend_request' : 'follower'),
671 'notify_type' => (($it['network'] !== Protocol::OSTATUS) ? L10n::t('Friend/Connect Request') : L10n::t('New Follower')),
672 'dfrn_id' => $it['issued-id'],
673 'uid' => $_SESSION['uid'],
674 'intro_id' => $it['intro_id'],
675 'contact_id' => $it['contact-id'],
676 'photo' => (!empty($it['photo']) ? ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"),
677 'name' => $it['name'],
678 'location' => BBCode::convert($it['glocation'], false),
679 'about' => BBCode::convert($it['gabout'], false),
680 'keywords' => $it['gkeywords'],
681 'gender' => $it['ggender'],
682 'hidden' => $it['hidden'] == 1,
683 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
685 'zrl' => Contact::magicLink($it['url']),
686 'addr' => $it['gaddr'],
687 'network' => $it['gnetwork'],
688 'knowyou' => $it['knowyou'],
689 'note' => $it['note'],
700 * @brief Check for missing contact data and try to fetch the data from
703 * @param array $arr The input array with the intro data
705 * @return array The array with the intro data
707 private function getMissingIntroData($arr)
709 // If the network and the addr isn't available from the gcontact
710 // table entry, take the one of the contact table entry
711 if (empty($arr['gnetwork']) && !empty($arr['network'])) {
712 $arr['gnetwork'] = $arr['network'];
714 if (empty($arr['gaddr']) && !empty($arr['addr'])) {
715 $arr['gaddr'] = $arr['addr'];
718 // If the network and addr is still not available
719 // get the missing data data from other sources
720 if (empty($arr['gnetwork']) || empty($arr['gaddr'])) {
721 $ret = Contact::getDetailsByURL($arr['url']);
723 if (empty($arr['gnetwork']) && !empty($ret['network'])) {
724 $arr['gnetwork'] = $ret['network'];
726 if (empty($arr['gaddr']) && !empty($ret['addr'])) {
727 $arr['gaddr'] = $ret['addr'];