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\Protocol;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Proxy as ProxyUtils;
18 use Friendica\Util\Temporal;
19 use Friendica\Util\XML;
21 require_once 'include/dba.php';
24 * @brief Methods for read and write notifications from/to database
25 * or for formatting notifications
27 class NotificationsManager extends BaseObject
30 * @brief set some extra note properties
32 * @param array $notes array of note arrays from db
33 * @return array Copy of input array with added properties
35 * Set some extra properties to note array from db:
36 * - timestamp as int in default TZ
37 * - date_rel : relative date string
38 * - msg_html: message as html string
39 * - msg_plain: message as plain text string
41 private function _set_extra($notes)
44 foreach ($notes as $n) {
45 $local_time = DateTimeFormat::local($n['date']);
46 $n['timestamp'] = strtotime($local_time);
47 $n['date_rel'] = Temporal::getRelativeDate($n['date']);
48 $n['msg_html'] = BBCode::convert($n['msg'], false);
49 $n['msg_plain'] = explode("\n", trim(HTML::toPlaintext($n['msg_html'], 0)))[0];
57 * @brief Get all notifications for local_user()
59 * @param array $filter optional Array "column name"=>value: filter query by columns values
60 * @param string $order optional Space separated list of column to sort by.
61 * Prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
62 * @param string $limit optional Query limits
64 * @return array of results or false on errors
66 public function getAll($filter = [], $order = "-date", $limit = "")
70 foreach ($filter as $column => $value) {
71 $filter_str[] = sprintf("`%s` = '%s'", $column, DBA::escape($value));
73 if (count($filter_str) > 0) {
74 $filter_sql = "AND " . implode(" AND ", $filter_str);
77 $aOrder = explode(" ", $order);
79 foreach ($aOrder as $o) {
89 $asOrder[] = "$o $dir";
91 $order_sql = implode(", ", $asOrder);
94 $limit = " LIMIT " . $limit;
97 "SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
101 if (DBA::isResult($r)) {
102 return $this->_set_extra($r);
109 * @brief Get one note for local_user() by $id value
111 * @param int $id identity
112 * @return array note values or null if not found
114 public function getByID($id)
117 "SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
121 if (DBA::isResult($r)) {
122 return $this->_set_extra($r)[0];
128 * @brief set seen state of $note of local_user()
130 * @param array $note note array
131 * @param bool $seen optional true or false, default true
132 * @return bool true on success, false on errors
134 public function setSeen($note, $seen = true)
137 "UPDATE `notify` SET `seen` = %d WHERE (`link` = '%s' OR (`parent` != 0 AND `parent` = %d AND `otype` = '%s')) AND `uid` = %d",
139 DBA::escape($note['link']),
140 intval($note['parent']),
141 DBA::escape($note['otype']),
147 * @brief set seen state of all notifications of local_user()
149 * @param bool $seen optional true or false. default true
150 * @return bool true on success, false on error
152 public function setAllSeen($seen = true)
155 "UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
162 * @brief List of pages for the Notifications TabBar
164 * @return array with with notifications TabBar data
166 public function getTabs()
168 $selected = defaults(self::getApp()->argv, 1, '');
172 'label' => L10n::t('System'),
173 'url' => 'notifications/system',
174 'sel' => (($selected == 'system') ? 'active' : ''),
175 'id' => 'system-tab',
179 'label' => L10n::t('Network'),
180 'url' => 'notifications/network',
181 'sel' => (($selected == 'network') ? 'active' : ''),
182 'id' => 'network-tab',
186 'label' => L10n::t('Personal'),
187 'url' => 'notifications/personal',
188 'sel' => (($selected == 'personal') ? 'active' : ''),
189 'id' => 'personal-tab',
193 'label' => L10n::t('Home'),
194 'url' => 'notifications/home',
195 'sel' => (($selected == 'home') ? 'active' : ''),
200 'label' => L10n::t('Introductions'),
201 'url' => 'notifications/intros',
202 'sel' => (($selected == 'intros') ? 'active' : ''),
212 * @brief Format the notification query in an usable array
214 * @param array $notifs The array from the db query
215 * @param string $ident The notifications identifier (e.g. network)
217 * string 'label' => The type of the notification
218 * string 'link' => URL to the source
219 * string 'image' => The avatar image
220 * string 'url' => The profile url of the contact
221 * string 'text' => The notification text
222 * string 'when' => The date of the notification
223 * string 'ago' => T relative date of the notification
224 * bool 'seen' => Is the notification marked as "seen"
226 private function formatNotifs(array $notifs, $ident = "")
231 if (DBA::isResult($notifs)) {
232 foreach ($notifs as $it) {
233 // Because we use different db tables for the notification query
234 // we have sometimes $it['unseen'] and sometimes $it['seen].
235 // So we will have to transform $it['unseen']
236 if (array_key_exists('unseen', $it)) {
237 $it['seen'] = ($it['unseen'] > 0 ? false : true);
240 // For feed items we use the user's contact, since the avatar is mostly self choosen.
241 if (!empty($it['network']) && $it['network'] == Protocol::FEED) {
242 $it['author-avatar'] = $it['contact-avatar'];
245 // Depending on the identifier of the notification we need to use different defaults
248 $default_item_label = 'notify';
249 $default_item_link = System::baseUrl(true) . '/notify/view/' . $it['id'];
250 $default_item_image = ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_MICRO);
251 $default_item_url = $it['url'];
252 $default_item_text = strip_tags(BBCode::convert($it['msg']));
253 $default_item_when = DateTimeFormat::local($it['date'], 'r');
254 $default_item_ago = Temporal::getRelativeDate($it['date']);
258 $default_item_label = 'comment';
259 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
260 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
261 $default_item_url = $it['author-link'];
262 $default_item_text = L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']);
263 $default_item_when = DateTimeFormat::local($it['created'], 'r');
264 $default_item_ago = Temporal::getRelativeDate($it['created']);
268 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
269 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
270 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
271 $default_item_url = $it['author-link'];
272 $default_item_text = (($it['id'] == $it['parent'])
273 ? L10n::t("%s created a new post", $it['author-name'])
274 : L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']));
275 $default_item_when = DateTimeFormat::local($it['created'], 'r');
276 $default_item_ago = Temporal::getRelativeDate($it['created']);
279 // Transform the different types of notification in an usable array
280 switch ($it['verb']) {
284 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
285 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
286 'url' => $it['author-link'],
287 'text' => L10n::t("%s liked %s's post", $it['author-name'], $it['parent-author-name']),
288 'when' => $default_item_when,
289 'ago' => $default_item_ago,
290 'seen' => $it['seen']
294 case ACTIVITY_DISLIKE:
296 'label' => 'dislike',
297 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
298 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
299 'url' => $it['author-link'],
300 'text' => L10n::t("%s disliked %s's post", $it['author-name'], $it['parent-author-name']),
301 'when' => $default_item_when,
302 'ago' => $default_item_ago,
303 'seen' => $it['seen']
307 case ACTIVITY_ATTEND:
310 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
311 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
312 'url' => $it['author-link'],
313 'text' => L10n::t("%s is attending %s's event", $it['author-name'], $it['parent-author-name']),
314 'when' => $default_item_when,
315 'ago' => $default_item_ago,
316 'seen' => $it['seen']
320 case ACTIVITY_ATTENDNO:
322 'label' => 'attendno',
323 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
324 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
325 'url' => $it['author-link'],
326 'text' => L10n::t("%s is not attending %s's event", $it['author-name'], $it['parent-author-name']),
327 'when' => $default_item_when,
328 'ago' => $default_item_ago,
329 'seen' => $it['seen']
333 case ACTIVITY_ATTENDMAYBE:
335 'label' => 'attendmaybe',
336 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
337 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
338 'url' => $it['author-link'],
339 'text' => L10n::t("%s may attend %s's event", $it['author-name'], $it['parent-author-name']),
340 'when' => $default_item_when,
341 'ago' => $default_item_ago,
342 'seen' => $it['seen']
346 case ACTIVITY_FRIEND:
347 if (!isset($it['object'])) {
350 'link' => $default_item_link,
351 'image' => $default_item_image,
352 'url' => $default_item_url,
353 'text' => $default_item_text,
354 'when' => $default_item_when,
355 'ago' => $default_item_ago,
356 'seen' => $it['seen']
360 /// @todo Check if this part here is used at all
361 logger('Complete data: ' . json_encode($it) . ' - ' . System::callstack(20), LOGGER_DEBUG);
363 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
364 $obj = XML::parseString($xmlhead . $it['object']);
365 $it['fname'] = $obj->title;
369 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
370 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
371 'url' => $it['author-link'],
372 'text' => L10n::t("%s is now friends with %s", $it['author-name'], $it['fname']),
373 'when' => $default_item_when,
374 'ago' => $default_item_ago,
375 'seen' => $it['seen']
381 'label' => $default_item_label,
382 'link' => $default_item_link,
383 'image' => $default_item_image,
384 'url' => $default_item_url,
385 'text' => $default_item_text,
386 'when' => $default_item_when,
387 'ago' => $default_item_ago,
388 'seen' => $it['seen']
400 * @brief Get network notifications
402 * @param int|string $seen If 0 only include notifications into the query
403 * which aren't marked as "seen"
404 * @param int $start Start the query at this point
405 * @param int $limit Maximum number of query results
408 * string 'ident' => Notification identifier
409 * array 'notifications' => Network notifications
411 public function networkNotifs($seen = 0, $start = 0, $limit = 80)
416 $condition = ['wall' => false, 'uid' => local_user()];
419 $condition['unseen'] = true;
422 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
423 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
424 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
426 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
428 if (DBA::isResult($items)) {
429 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
433 'notifications' => $notifs,
441 * @brief Get system notifications
443 * @param int|string $seen If 0 only include notifications into the query
444 * which aren't marked as "seen"
445 * @param int $start Start the query at this point
446 * @param int $limit Maximum number of query results
449 * string 'ident' => Notification identifier
450 * array 'notifications' => System notifications
452 public function systemNotifs($seen = 0, $start = 0, $limit = 80)
459 $sql_seen = " AND NOT `seen` ";
463 "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen`, `verb` FROM `notify`
464 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
465 intval(local_user()),
470 if (DBA::isResult($r)) {
471 $notifs = $this->formatNotifs($r, $ident);
475 'notifications' => $notifs,
483 * @brief Get personal notifications
485 * @param int|string $seen If 0 only include notifications into the query
486 * which aren't marked as "seen"
487 * @param int $start Start the query at this point
488 * @param int $limit Maximum number of query results
491 * string 'ident' => Notification identifier
492 * array 'notifications' => Personal notifications
494 public function personalNotifs($seen = 0, $start = 0, $limit = 80)
499 $myurl = str_replace('http://', '', self::getApp()->contact['nurl']);
500 $diasp_url = str_replace('/profile/', '/u/', $myurl);
502 $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)",
503 local_user(), public_contact(), $myurl . '\\]', $diasp_url . '\\]'];
506 $condition[0] .= " AND `unseen`";
509 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
510 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
511 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
513 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
515 if (DBA::isResult($items)) {
516 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
520 'notifications' => $notifs,
528 * @brief Get home notifications
530 * @param int|string $seen If 0 only include notifications into the query
531 * which aren't marked as "seen"
532 * @param int $start Start the query at this point
533 * @param int $limit Maximum number of query results
536 * string 'ident' => Notification identifier
537 * array 'notifications' => Home notifications
539 public function homeNotifs($seen = 0, $start = 0, $limit = 80)
544 $condition = ['wall' => true, 'uid' => local_user()];
547 $condition['unseen'] = true;
550 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
551 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
552 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
553 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
555 if (DBA::isResult($items)) {
556 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
560 'notifications' => $notifs,
568 * @brief Get introductions
570 * @param bool $all If false only include introductions into the query
571 * which aren't marked as ignored
572 * @param int $start Start the query at this point
573 * @param int $limit Maximum number of query results
576 * string 'ident' => Notification identifier
577 * array 'notifications' => Introductions
579 public function introNotifs($all = false, $start = 0, $limit = 80)
581 $ident = 'introductions';
586 $sql_extra = " AND `ignore` = 0 ";
589 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
591 "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
592 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`,
593 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
594 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
595 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
596 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
598 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
599 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
600 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
601 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
603 intval($_SESSION['uid']),
607 if (DBA::isResult($r)) {
608 $notifs = $this->formatIntros($r);
613 'notifications' => $notifs,
620 * @brief Format the notification query in an usable array
622 * @param array $intros The array from the db query
623 * @return array with the introductions
625 private function formatIntros($intros)
629 foreach ($intros as $it) {
630 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
631 // We have to distinguish between these two because they use different data.
632 // Contact suggestions
634 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->get_hostname() . ((self::getApp()->urlpath) ? '/' . self::getApp()->urlpath : ''));
637 'label' => 'friend_suggestion',
638 'notify_type' => L10n::t('Friend Suggestion'),
639 'intro_id' => $it['intro_id'],
640 'madeby' => $it['name'],
641 'madeby_url' => $it['url'],
642 'madeby_zrl' => Contact::magicLink($it['url']),
643 'madeby_addr' => $it['addr'],
644 'contact_id' => $it['contact-id'],
645 'photo' => ((x($it, 'fphoto')) ? ProxyUtils::proxifyUrl($it['fphoto'], false, ProxyUtils::SIZE_SMALL) : "images/person-175.jpg"),
646 'name' => $it['fname'],
647 'url' => $it['furl'],
648 'zrl' => Contact::magicLink($it['furl']),
649 'hidden' => $it['hidden'] == 1,
650 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
651 'knowyou' => $knowyou,
652 'note' => $it['note'],
653 'request' => $it['frequest'] . '?addr=' . $return_addr,
656 // Normal connection requests
658 $it = $this->getMissingIntroData($it);
660 if (empty($it['url'])) {
664 // Don't show these data until you are connected. Diaspora is doing the same.
665 if ($it['gnetwork'] === Protocol::DIASPORA) {
666 $it['glocation'] = "";
671 'label' => (($it['network'] !== Protocol::OSTATUS) ? 'friend_request' : 'follower'),
672 'notify_type' => (($it['network'] !== Protocol::OSTATUS) ? L10n::t('Friend/Connect Request') : L10n::t('New Follower')),
673 'dfrn_id' => $it['issued-id'],
674 'uid' => $_SESSION['uid'],
675 'intro_id' => $it['intro_id'],
676 'contact_id' => $it['contact-id'],
677 'photo' => ((x($it, 'photo')) ? ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_SMALL) : "images/person-175.jpg"),
678 'name' => $it['name'],
679 'location' => BBCode::convert($it['glocation'], false),
680 'about' => BBCode::convert($it['gabout'], false),
681 'keywords' => $it['gkeywords'],
682 'gender' => $it['ggender'],
683 'hidden' => $it['hidden'] == 1,
684 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
686 'zrl' => Contact::magicLink($it['url']),
687 'addr' => $it['gaddr'],
688 'network' => $it['gnetwork'],
689 'knowyou' => $it['knowyou'],
690 'note' => $it['note'],
701 * @brief Check for missing contact data and try to fetch the data from
704 * @param array $arr The input array with the intro data
706 * @return array The array with the intro data
708 private function getMissingIntroData($arr)
710 // If the network and the addr isn't available from the gcontact
711 // table entry, take the one of the contact table entry
712 if (empty($arr['gnetwork']) && !empty($arr['network'])) {
713 $arr['gnetwork'] = $arr['network'];
715 if (empty($arr['gaddr']) && !empty($arr['addr'])) {
716 $arr['gaddr'] = $arr['addr'];
719 // If the network and addr is still not available
720 // get the missing data data from other sources
721 if (empty($arr['gnetwork']) || empty($arr['gaddr'])) {
722 $ret = Contact::getDetailsByURL($arr['url']);
724 if (empty($arr['gnetwork']) && !empty($ret['network'])) {
725 $arr['gnetwork'] = $ret['network'];
727 if (empty($arr['gaddr']) && !empty($ret['addr'])) {
728 $arr['gaddr'] = $ret['addr'];