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 = "")
235 if (DBA::isResult($notifs)) {
236 foreach ($notifs as $it) {
237 // Because we use different db tables for the notification query
238 // we have sometimes $it['unseen'] and sometimes $it['seen].
239 // So we will have to transform $it['unseen']
240 if (array_key_exists('unseen', $it)) {
241 $it['seen'] = ($it['unseen'] > 0 ? false : true);
244 // For feed items we use the user's contact, since the avatar is mostly self choosen.
245 if (!empty($it['network']) && $it['network'] == Protocol::FEED) {
246 $it['author-avatar'] = $it['contact-avatar'];
249 // Depending on the identifier of the notification we need to use different defaults
252 $default_item_label = 'notify';
253 $default_item_link = System::baseUrl(true) . '/notify/view/' . $it['id'];
254 $default_item_image = ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_MICRO);
255 $default_item_url = $it['url'];
256 $default_item_text = strip_tags(BBCode::convert($it['msg']));
257 $default_item_when = DateTimeFormat::local($it['date'], 'r');
258 $default_item_ago = Temporal::getRelativeDate($it['date']);
262 $default_item_label = 'comment';
263 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
264 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
265 $default_item_url = $it['author-link'];
266 $default_item_text = L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']);
267 $default_item_when = DateTimeFormat::local($it['created'], 'r');
268 $default_item_ago = Temporal::getRelativeDate($it['created']);
272 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
273 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
274 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
275 $default_item_url = $it['author-link'];
276 $default_item_text = (($it['id'] == $it['parent'])
277 ? L10n::t("%s created a new post", $it['author-name'])
278 : L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']));
279 $default_item_when = DateTimeFormat::local($it['created'], 'r');
280 $default_item_ago = Temporal::getRelativeDate($it['created']);
283 // Transform the different types of notification in an usable array
284 switch ($it['verb']) {
288 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
289 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
290 'url' => $it['author-link'],
291 'text' => L10n::t("%s liked %s's post", $it['author-name'], $it['parent-author-name']),
292 'when' => $default_item_when,
293 'ago' => $default_item_ago,
294 'seen' => $it['seen']
298 case ACTIVITY_DISLIKE:
300 'label' => 'dislike',
301 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
302 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
303 'url' => $it['author-link'],
304 'text' => L10n::t("%s disliked %s's post", $it['author-name'], $it['parent-author-name']),
305 'when' => $default_item_when,
306 'ago' => $default_item_ago,
307 'seen' => $it['seen']
311 case ACTIVITY_ATTEND:
314 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
315 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
316 'url' => $it['author-link'],
317 'text' => L10n::t("%s is attending %s's event", $it['author-name'], $it['parent-author-name']),
318 'when' => $default_item_when,
319 'ago' => $default_item_ago,
320 'seen' => $it['seen']
324 case ACTIVITY_ATTENDNO:
326 'label' => 'attendno',
327 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
328 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
329 'url' => $it['author-link'],
330 'text' => L10n::t("%s is not attending %s's event", $it['author-name'], $it['parent-author-name']),
331 'when' => $default_item_when,
332 'ago' => $default_item_ago,
333 'seen' => $it['seen']
337 case ACTIVITY_ATTENDMAYBE:
339 'label' => 'attendmaybe',
340 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
341 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
342 'url' => $it['author-link'],
343 'text' => L10n::t("%s may attend %s's event", $it['author-name'], $it['parent-author-name']),
344 'when' => $default_item_when,
345 'ago' => $default_item_ago,
346 'seen' => $it['seen']
350 case ACTIVITY_FRIEND:
351 if (!isset($it['object'])) {
354 'link' => $default_item_link,
355 'image' => $default_item_image,
356 'url' => $default_item_url,
357 'text' => $default_item_text,
358 'when' => $default_item_when,
359 'ago' => $default_item_ago,
360 'seen' => $it['seen']
364 /// @todo Check if this part here is used at all
365 Logger::log('Complete data: ' . json_encode($it) . ' - ' . System::callstack(20), Logger::DEBUG);
367 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
368 $obj = XML::parseString($xmlhead . $it['object']);
369 $it['fname'] = $obj->title;
373 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
374 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
375 'url' => $it['author-link'],
376 'text' => L10n::t("%s is now friends with %s", $it['author-name'], $it['fname']),
377 'when' => $default_item_when,
378 'ago' => $default_item_ago,
379 'seen' => $it['seen']
385 'label' => $default_item_label,
386 'link' => $default_item_link,
387 'image' => $default_item_image,
388 'url' => $default_item_url,
389 'text' => $default_item_text,
390 'when' => $default_item_when,
391 'ago' => $default_item_ago,
392 'seen' => $it['seen']
404 * @brief Get network notifications
406 * @param int|string $seen If 0 only include notifications into the query
407 * which aren't marked as "seen"
408 * @param int $start Start the query at this point
409 * @param int $limit Maximum number of query results
412 * string 'ident' => Notification identifier
413 * array 'notifications' => Network notifications
414 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
416 public function networkNotifs($seen = 0, $start = 0, $limit = 80)
421 $condition = ['wall' => false, 'uid' => local_user()];
424 $condition['unseen'] = true;
427 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
428 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
429 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
431 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
433 if (DBA::isResult($items)) {
434 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
438 'notifications' => $notifs,
446 * @brief Get system notifications
448 * @param int|string $seen If 0 only include notifications into the query
449 * which aren't marked as "seen"
450 * @param int $start Start the query at this point
451 * @param int $limit Maximum number of query results
454 * string 'ident' => Notification identifier
455 * array 'notifications' => System notifications
456 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
458 public function systemNotifs($seen = 0, $start = 0, $limit = 80)
465 $sql_seen = " AND NOT `seen` ";
469 "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen`, `verb` FROM `notify`
470 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
471 intval(local_user()),
476 if (DBA::isResult($r)) {
477 $notifs = $this->formatNotifs($r, $ident);
481 'notifications' => $notifs,
489 * @brief Get personal notifications
491 * @param int|string $seen If 0 only include notifications into the query
492 * which aren't marked as "seen"
493 * @param int $start Start the query at this point
494 * @param int $limit Maximum number of query results
497 * string 'ident' => Notification identifier
498 * array 'notifications' => Personal notifications
501 public function personalNotifs($seen = 0, $start = 0, $limit = 80)
506 $myurl = str_replace('http://', '', self::getApp()->contact['nurl']);
507 $diasp_url = str_replace('/profile/', '/u/', $myurl);
509 $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)",
510 local_user(), public_contact(), $myurl . '\\]', $diasp_url . '\\]'];
513 $condition[0] .= " AND `unseen`";
516 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
517 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
518 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
520 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
522 if (DBA::isResult($items)) {
523 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
527 'notifications' => $notifs,
535 * @brief Get home notifications
537 * @param int|string $seen If 0 only include notifications into the query
538 * which aren't marked as "seen"
539 * @param int $start Start the query at this point
540 * @param int $limit Maximum number of query results
543 * string 'ident' => Notification identifier
544 * array 'notifications' => Home notifications
545 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
547 public function homeNotifs($seen = 0, $start = 0, $limit = 80)
552 $condition = ['wall' => true, 'uid' => local_user()];
555 $condition['unseen'] = true;
558 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
559 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
560 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
561 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
563 if (DBA::isResult($items)) {
564 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
568 'notifications' => $notifs,
576 * @brief Get introductions
578 * @param bool $all If false only include introductions into the query
579 * which aren't marked as ignored
580 * @param int $start Start the query at this point
581 * @param int $limit Maximum number of query results
584 * string 'ident' => Notification identifier
585 * array 'notifications' => Introductions
586 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
587 * @throws \ImagickException
589 public function introNotifs($all = false, $start = 0, $limit = 80)
591 $ident = 'introductions';
596 $sql_extra = " AND `ignore` = 0 ";
599 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
601 "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
602 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`,
603 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
604 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
605 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
606 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
608 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
609 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
610 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
611 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
613 intval($_SESSION['uid']),
617 if (DBA::isResult($r)) {
618 $notifs = $this->formatIntros($r);
623 'notifications' => $notifs,
630 * @brief Format the notification query in an usable array
632 * @param array $intros The array from the db query
633 * @return array with the introductions
634 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
635 * @throws \ImagickException
637 private function formatIntros($intros)
641 foreach ($intros as $it) {
642 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
643 // We have to distinguish between these two because they use different data.
644 // Contact suggestions
646 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->getHostName() . ((self::getApp()->getURLPath()) ? '/' . self::getApp()->getURLPath() : ''));
649 'label' => 'friend_suggestion',
650 'notify_type' => L10n::t('Friend Suggestion'),
651 'intro_id' => $it['intro_id'],
652 'madeby' => $it['name'],
653 'madeby_url' => $it['url'],
654 'madeby_zrl' => Contact::magicLink($it['url']),
655 'madeby_addr' => $it['addr'],
656 'contact_id' => $it['contact-id'],
657 'photo' => (!empty($it['fphoto']) ? ProxyUtils::proxifyUrl($it['fphoto'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"),
658 'name' => $it['fname'],
659 'url' => $it['furl'],
660 'zrl' => Contact::magicLink($it['furl']),
661 'hidden' => $it['hidden'] == 1,
662 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
663 'knowyou' => $knowyou,
664 'note' => $it['note'],
665 'request' => $it['frequest'] . '?addr=' . $return_addr,
668 // Normal connection requests
670 $it = $this->getMissingIntroData($it);
672 if (empty($it['url'])) {
676 // Don't show these data until you are connected. Diaspora is doing the same.
677 if ($it['gnetwork'] === Protocol::DIASPORA) {
678 $it['glocation'] = "";
683 'label' => (($it['network'] !== Protocol::OSTATUS) ? 'friend_request' : 'follower'),
684 'notify_type' => (($it['network'] !== Protocol::OSTATUS) ? L10n::t('Friend/Connect Request') : L10n::t('New Follower')),
685 'dfrn_id' => $it['issued-id'],
686 'uid' => $_SESSION['uid'],
687 'intro_id' => $it['intro_id'],
688 'contact_id' => $it['contact-id'],
689 'photo' => (!empty($it['photo']) ? ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"),
690 'name' => $it['name'],
691 'location' => BBCode::convert($it['glocation'], false),
692 'about' => BBCode::convert($it['gabout'], false),
693 'keywords' => $it['gkeywords'],
694 'gender' => $it['ggender'],
695 'hidden' => $it['hidden'] == 1,
696 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
698 'zrl' => Contact::magicLink($it['url']),
699 'addr' => $it['gaddr'],
700 'network' => $it['gnetwork'],
701 'knowyou' => $it['knowyou'],
702 'note' => $it['note'],
713 * @brief Check for missing contact data and try to fetch the data from
716 * @param array $arr The input array with the intro data
718 * @return array The array with the intro data
719 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
721 private function getMissingIntroData($arr)
723 // If the network and the addr isn't available from the gcontact
724 // table entry, take the one of the contact table entry
725 if (empty($arr['gnetwork']) && !empty($arr['network'])) {
726 $arr['gnetwork'] = $arr['network'];
728 if (empty($arr['gaddr']) && !empty($arr['addr'])) {
729 $arr['gaddr'] = $arr['addr'];
732 // If the network and addr is still not available
733 // get the missing data data from other sources
734 if (empty($arr['gnetwork']) || empty($arr['gaddr'])) {
735 $ret = Contact::getDetailsByURL($arr['url']);
737 if (empty($arr['gnetwork']) && !empty($ret['network'])) {
738 $arr['gnetwork'] = $ret['network'];
740 if (empty($arr['gaddr']) && !empty($ret['addr'])) {
741 $arr['gaddr'] = $ret['addr'];