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;
21 * @brief Methods for read and write notifications from/to database
22 * or for formatting notifications
24 class NotificationsManager extends BaseObject
27 * @brief set some extra note properties
29 * @param array $notes array of note arrays from db
30 * @return array Copy of input array with added properties
32 * Set some extra properties to note array from db:
33 * - timestamp as int in default TZ
34 * - date_rel : relative date string
35 * - msg_html: message as html string
36 * - msg_plain: message as plain text string
37 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
39 private function _set_extra($notes)
42 foreach ($notes as $n) {
43 $local_time = DateTimeFormat::local($n['date']);
44 $n['timestamp'] = strtotime($local_time);
45 $n['date_rel'] = Temporal::getRelativeDate($n['date']);
46 $n['msg_html'] = BBCode::convert($n['msg'], false);
47 $n['msg_plain'] = explode("\n", trim(HTML::toPlaintext($n['msg_html'], 0)))[0];
55 * @brief Get all notifications for local_user()
57 * @param array $filter optional Array "column name"=>value: filter query by columns values
58 * @param string $order optional Space separated list of column to sort by.
59 * Prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
60 * @param string $limit optional Query limits
62 * @return array of results or false on errors
63 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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
112 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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
135 public function setSeen($note, $seen = true)
138 "UPDATE `notify` SET `seen` = %d WHERE (`link` = '%s' OR (`parent` != 0 AND `parent` = %d AND `otype` = '%s')) AND `uid` = %d",
140 DBA::escape($note['link']),
141 intval($note['parent']),
142 DBA::escape($note['otype']),
148 * @brief set seen state of all notifications of local_user()
150 * @param bool $seen optional true or false. default true
151 * @return bool true on success, false on error
154 public function setAllSeen($seen = true)
157 "UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
164 * @brief List of pages for the Notifications TabBar
166 * @return array with with notifications TabBar data
169 public function getTabs()
171 $selected = defaults(self::getApp()->argv, 1, '');
175 'label' => L10n::t('System'),
176 'url' => 'notifications/system',
177 'sel' => (($selected == 'system') ? 'active' : ''),
178 'id' => 'system-tab',
182 'label' => L10n::t('Network'),
183 'url' => 'notifications/network',
184 'sel' => (($selected == 'network') ? 'active' : ''),
185 'id' => 'network-tab',
189 'label' => L10n::t('Personal'),
190 'url' => 'notifications/personal',
191 'sel' => (($selected == 'personal') ? 'active' : ''),
192 'id' => 'personal-tab',
196 'label' => L10n::t('Home'),
197 'url' => 'notifications/home',
198 'sel' => (($selected == 'home') ? 'active' : ''),
203 'label' => L10n::t('Introductions'),
204 'url' => 'notifications/intros',
205 'sel' => (($selected == 'intros') ? 'active' : ''),
215 * @brief Format the notification query in an usable array
217 * @param array $notifs The array from the db query
218 * @param string $ident The notifications identifier (e.g. network)
220 * string 'label' => The type of the notification
221 * string 'link' => URL to the source
222 * string 'image' => The avatar image
223 * string 'url' => The profile url of the contact
224 * string 'text' => The notification text
225 * string 'when' => The date of the notification
226 * string 'ago' => T relative date of the notification
227 * bool 'seen' => Is the notification marked as "seen"
228 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
230 private function formatNotifs(array $notifs, $ident = "")
234 if (DBA::isResult($notifs)) {
235 foreach ($notifs as $it) {
236 // Because we use different db tables for the notification query
237 // we have sometimes $it['unseen'] and sometimes $it['seen].
238 // So we will have to transform $it['unseen']
239 if (array_key_exists('unseen', $it)) {
240 $it['seen'] = ($it['unseen'] > 0 ? false : true);
243 // For feed items we use the user's contact, since the avatar is mostly self choosen.
244 if (!empty($it['network']) && $it['network'] == Protocol::FEED) {
245 $it['author-avatar'] = $it['contact-avatar'];
248 // Depending on the identifier of the notification we need to use different defaults
251 $default_item_label = 'notify';
252 $default_item_link = System::baseUrl(true) . '/notify/view/' . $it['id'];
253 $default_item_image = ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_MICRO);
254 $default_item_url = $it['url'];
255 $default_item_text = strip_tags(BBCode::convert($it['msg']));
256 $default_item_when = DateTimeFormat::local($it['date'], 'r');
257 $default_item_ago = Temporal::getRelativeDate($it['date']);
261 $default_item_label = 'comment';
262 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
263 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
264 $default_item_url = $it['author-link'];
265 $default_item_text = L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']);
266 $default_item_when = DateTimeFormat::local($it['created'], 'r');
267 $default_item_ago = Temporal::getRelativeDate($it['created']);
271 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
272 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
273 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
274 $default_item_url = $it['author-link'];
275 $default_item_text = (($it['id'] == $it['parent'])
276 ? L10n::t("%s created a new post", $it['author-name'])
277 : L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']));
278 $default_item_when = DateTimeFormat::local($it['created'], 'r');
279 $default_item_ago = Temporal::getRelativeDate($it['created']);
282 // Transform the different types of notification in an usable array
283 switch ($it['verb']) {
287 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
288 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
289 'url' => $it['author-link'],
290 'text' => L10n::t("%s liked %s's post", $it['author-name'], $it['parent-author-name']),
291 'when' => $default_item_when,
292 'ago' => $default_item_ago,
293 'seen' => $it['seen']
297 case ACTIVITY_DISLIKE:
299 'label' => 'dislike',
300 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
301 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
302 'url' => $it['author-link'],
303 'text' => L10n::t("%s disliked %s's post", $it['author-name'], $it['parent-author-name']),
304 'when' => $default_item_when,
305 'ago' => $default_item_ago,
306 'seen' => $it['seen']
310 case ACTIVITY_ATTEND:
313 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
314 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
315 'url' => $it['author-link'],
316 'text' => L10n::t("%s is attending %s's event", $it['author-name'], $it['parent-author-name']),
317 'when' => $default_item_when,
318 'ago' => $default_item_ago,
319 'seen' => $it['seen']
323 case ACTIVITY_ATTENDNO:
325 'label' => 'attendno',
326 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
327 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
328 'url' => $it['author-link'],
329 'text' => L10n::t("%s is not attending %s's event", $it['author-name'], $it['parent-author-name']),
330 'when' => $default_item_when,
331 'ago' => $default_item_ago,
332 'seen' => $it['seen']
336 case ACTIVITY_ATTENDMAYBE:
338 'label' => 'attendmaybe',
339 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
340 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
341 'url' => $it['author-link'],
342 'text' => L10n::t("%s may attend %s's event", $it['author-name'], $it['parent-author-name']),
343 'when' => $default_item_when,
344 'ago' => $default_item_ago,
345 'seen' => $it['seen']
349 case ACTIVITY_FRIEND:
350 if (!isset($it['object'])) {
353 'link' => $default_item_link,
354 'image' => $default_item_image,
355 'url' => $default_item_url,
356 'text' => $default_item_text,
357 'when' => $default_item_when,
358 'ago' => $default_item_ago,
359 'seen' => $it['seen']
363 /// @todo Check if this part here is used at all
364 Logger::log('Complete data: ' . json_encode($it) . ' - ' . System::callstack(20), Logger::DEBUG);
366 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
367 $obj = XML::parseString($xmlhead . $it['object']);
368 $it['fname'] = $obj->title;
372 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
373 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
374 'url' => $it['author-link'],
375 'text' => L10n::t("%s is now friends with %s", $it['author-name'], $it['fname']),
376 'when' => $default_item_when,
377 'ago' => $default_item_ago,
378 'seen' => $it['seen']
384 'label' => $default_item_label,
385 'link' => $default_item_link,
386 'image' => $default_item_image,
387 'url' => $default_item_url,
388 'text' => $default_item_text,
389 'when' => $default_item_when,
390 'ago' => $default_item_ago,
391 'seen' => $it['seen']
403 * @brief Get network notifications
405 * @param int|string $seen If 0 only include notifications into the query
406 * which aren't marked as "seen"
407 * @param int $start Start the query at this point
408 * @param int $limit Maximum number of query results
411 * string 'ident' => Notification identifier
412 * array 'notifications' => Network notifications
413 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
415 public function networkNotifs($seen = 0, $start = 0, $limit = 80)
420 $condition = ['wall' => false, 'uid' => local_user()];
423 $condition['unseen'] = true;
426 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
427 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
428 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
430 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
432 if (DBA::isResult($items)) {
433 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
437 'notifications' => $notifs,
445 * @brief Get system notifications
447 * @param int|string $seen If 0 only include notifications into the query
448 * which aren't marked as "seen"
449 * @param int $start Start the query at this point
450 * @param int $limit Maximum number of query results
453 * string 'ident' => Notification identifier
454 * array 'notifications' => System notifications
455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
457 public function systemNotifs($seen = 0, $start = 0, $limit = 80)
464 $sql_seen = " AND NOT `seen` ";
468 "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen`, `verb` FROM `notify`
469 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
470 intval(local_user()),
475 if (DBA::isResult($r)) {
476 $notifs = $this->formatNotifs($r, $ident);
480 'notifications' => $notifs,
488 * @brief Get personal notifications
490 * @param int|string $seen If 0 only include notifications into the query
491 * which aren't marked as "seen"
492 * @param int $start Start the query at this point
493 * @param int $limit Maximum number of query results
496 * string 'ident' => Notification identifier
497 * array 'notifications' => Personal notifications
500 public function personalNotifs($seen = 0, $start = 0, $limit = 80)
505 $myurl = str_replace('http://', '', self::getApp()->contact['nurl']);
506 $diasp_url = str_replace('/profile/', '/u/', $myurl);
508 $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)",
509 local_user(), public_contact(), $myurl . '\\]', $diasp_url . '\\]'];
512 $condition[0] .= " AND `unseen`";
515 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
516 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
517 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
519 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
521 if (DBA::isResult($items)) {
522 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
526 'notifications' => $notifs,
534 * @brief Get home notifications
536 * @param int|string $seen If 0 only include notifications into the query
537 * which aren't marked as "seen"
538 * @param int $start Start the query at this point
539 * @param int $limit Maximum number of query results
542 * string 'ident' => Notification identifier
543 * array 'notifications' => Home notifications
544 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
546 public function homeNotifs($seen = 0, $start = 0, $limit = 80)
551 $condition = ['wall' => true, 'uid' => local_user()];
554 $condition['unseen'] = true;
557 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
558 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
559 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
560 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
562 if (DBA::isResult($items)) {
563 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
567 'notifications' => $notifs,
575 * @brief Get introductions
577 * @param bool $all If false only include introductions into the query
578 * which aren't marked as ignored
579 * @param int $start Start the query at this point
580 * @param int $limit Maximum number of query results
583 * string 'ident' => Notification identifier
584 * array 'notifications' => Introductions
585 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
586 * @throws \ImagickException
588 public function introNotifs($all = false, $start = 0, $limit = 80)
590 $ident = 'introductions';
595 $sql_extra = " AND `ignore` = 0 ";
598 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
600 "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
601 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`,
602 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
603 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
604 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
605 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
607 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
608 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
609 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
610 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
612 intval($_SESSION['uid']),
616 if (DBA::isResult($r)) {
617 $notifs = $this->formatIntros($r);
622 'notifications' => $notifs,
629 * @brief Format the notification query in an usable array
631 * @param array $intros The array from the db query
632 * @return array with the introductions
633 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
634 * @throws \ImagickException
636 private function formatIntros($intros)
642 foreach ($intros as $it) {
643 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
644 // We have to distinguish between these two because they use different data.
645 // Contact suggestions
647 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->getHostName() . ((self::getApp()->getURLPath()) ? '/' . self::getApp()->getURLPath() : ''));
650 'label' => 'friend_suggestion',
651 'notify_type' => L10n::t('Friend Suggestion'),
652 'intro_id' => $it['intro_id'],
653 'madeby' => $it['name'],
654 'madeby_url' => $it['url'],
655 'madeby_zrl' => Contact::magicLink($it['url']),
656 'madeby_addr' => $it['addr'],
657 'contact_id' => $it['contact-id'],
658 'photo' => (!empty($it['fphoto']) ? ProxyUtils::proxifyUrl($it['fphoto'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"),
659 'name' => $it['fname'],
660 'url' => $it['furl'],
661 'zrl' => Contact::magicLink($it['furl']),
662 'hidden' => $it['hidden'] == 1,
663 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
664 'knowyou' => $knowyou,
665 'note' => $it['note'],
666 'request' => $it['frequest'] . '?addr=' . $return_addr,
669 // Normal connection requests
671 $it = $this->getMissingIntroData($it);
673 if (empty($it['url'])) {
677 // Don't show these data until you are connected. Diaspora is doing the same.
678 if ($it['gnetwork'] === Protocol::DIASPORA) {
679 $it['glocation'] = "";
684 'label' => (($it['network'] !== Protocol::OSTATUS) ? 'friend_request' : 'follower'),
685 'notify_type' => (($it['network'] !== Protocol::OSTATUS) ? L10n::t('Friend/Connect Request') : L10n::t('New Follower')),
686 'dfrn_id' => $it['issued-id'],
687 'uid' => $_SESSION['uid'],
688 'intro_id' => $it['intro_id'],
689 'contact_id' => $it['contact-id'],
690 'photo' => (!empty($it['photo']) ? ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"),
691 'name' => $it['name'],
692 'location' => BBCode::convert($it['glocation'], false),
693 'about' => BBCode::convert($it['gabout'], false),
694 'keywords' => $it['gkeywords'],
695 'gender' => $it['ggender'],
696 'hidden' => $it['hidden'] == 1,
697 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
699 'zrl' => Contact::magicLink($it['url']),
700 'addr' => $it['gaddr'],
701 'network' => $it['gnetwork'],
702 'knowyou' => $it['knowyou'],
703 'note' => $it['note'],
714 * @brief Check for missing contact data and try to fetch the data from
717 * @param array $arr The input array with the intro data
719 * @return array The array with the intro data
720 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
722 private function getMissingIntroData($arr)
724 // If the network and the addr isn't available from the gcontact
725 // table entry, take the one of the contact table entry
726 if (empty($arr['gnetwork']) && !empty($arr['network'])) {
727 $arr['gnetwork'] = $arr['network'];
729 if (empty($arr['gaddr']) && !empty($arr['addr'])) {
730 $arr['gaddr'] = $arr['addr'];
733 // If the network and addr is still not available
734 // get the missing data data from other sources
735 if (empty($arr['gnetwork']) || empty($arr['gaddr'])) {
736 $ret = Contact::getDetailsByURL($arr['url']);
738 if (empty($arr['gnetwork']) && !empty($ret['network'])) {
739 $arr['gnetwork'] = $ret['network'];
741 if (empty($arr['gaddr']) && !empty($ret['addr'])) {
742 $arr['gaddr'] = $ret['addr'];