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 array $order optional Array to order by
59 * @param string $limit optional Query limits
61 * @return array|bool of results or false on errors
62 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
64 public function getAll($filter = [], $order = ['date' => 'DESC'], $limit = "")
68 $params['order'] = $order;
71 $params['limit'] = $limit;
74 $dbFilter = array_merge($filter, ['uid' => local_user()]);
76 $r = DBA::select('notify', [], $dbFilter, $order, $params);
78 if (DBA::isResult($r)) {
79 return $this->_set_extra($r);
86 * @brief Get one note for local_user() by $id value
88 * @param int $id identity
89 * @return array note values or null if not found
90 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
92 public function getByID($id)
94 $r = DBA::selectFirst('notify', ['id' => $id, 'uid' => local_user()]);
95 if (DBA::isResult($r)) {
96 return $this->_set_extra($r)[0];
102 * @brief set seen state of $note of local_user()
104 * @param array $note note array
105 * @param bool $seen optional true or false, default true
106 * @return bool true on success, false on errors
109 public function setSeen($note, $seen = true)
111 return DBA::update('notify', ['seen' => $seen], ['link' => $note['link'], 'parent' => $note['parent'], 'otype' => $note['otype'], 'uid' => local_user()]);
115 * @brief set seen state of all notifications of local_user()
117 * @param bool $seen optional true or false. default true
118 * @return bool true on success, false on error
121 public function setAllSeen($seen = true)
123 return DBA::update('notify', ['seen' => $seen], ['uid' => local_user()]);
127 * @brief List of pages for the Notifications TabBar
129 * @return array with with notifications TabBar data
132 public function getTabs()
134 $selected = defaults(self::getApp()->argv, 1, '');
138 'label' => L10n::t('System'),
139 'url' => 'notifications/system',
140 'sel' => (($selected == 'system') ? 'active' : ''),
141 'id' => 'system-tab',
145 'label' => L10n::t('Network'),
146 'url' => 'notifications/network',
147 'sel' => (($selected == 'network') ? 'active' : ''),
148 'id' => 'network-tab',
152 'label' => L10n::t('Personal'),
153 'url' => 'notifications/personal',
154 'sel' => (($selected == 'personal') ? 'active' : ''),
155 'id' => 'personal-tab',
159 'label' => L10n::t('Home'),
160 'url' => 'notifications/home',
161 'sel' => (($selected == 'home') ? 'active' : ''),
166 'label' => L10n::t('Introductions'),
167 'url' => 'notifications/intros',
168 'sel' => (($selected == 'intros') ? 'active' : ''),
178 * @brief Format the notification query in an usable array
180 * @param array $notifs The array from the db query
181 * @param string $ident The notifications identifier (e.g. network)
183 * string 'label' => The type of the notification
184 * string 'link' => URL to the source
185 * string 'image' => The avatar image
186 * string 'url' => The profile url of the contact
187 * string 'text' => The notification text
188 * string 'when' => The date of the notification
189 * string 'ago' => T relative date of the notification
190 * bool 'seen' => Is the notification marked as "seen"
191 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
193 private function formatNotifs(array $notifs, $ident = "")
197 if (DBA::isResult($notifs)) {
198 foreach ($notifs as $it) {
199 // Because we use different db tables for the notification query
200 // we have sometimes $it['unseen'] and sometimes $it['seen].
201 // So we will have to transform $it['unseen']
202 if (array_key_exists('unseen', $it)) {
203 $it['seen'] = ($it['unseen'] > 0 ? false : true);
206 // For feed items we use the user's contact, since the avatar is mostly self choosen.
207 if (!empty($it['network']) && $it['network'] == Protocol::FEED) {
208 $it['author-avatar'] = $it['contact-avatar'];
211 // Depending on the identifier of the notification we need to use different defaults
214 $default_item_label = 'notify';
215 $default_item_link = System::baseUrl(true) . '/notify/view/' . $it['id'];
216 $default_item_image = ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_MICRO);
217 $default_item_url = $it['url'];
218 $default_item_text = strip_tags(BBCode::convert($it['msg']));
219 $default_item_when = DateTimeFormat::local($it['date'], 'r');
220 $default_item_ago = Temporal::getRelativeDate($it['date']);
224 $default_item_label = 'comment';
225 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
226 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
227 $default_item_url = $it['author-link'];
228 $default_item_text = L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']);
229 $default_item_when = DateTimeFormat::local($it['created'], 'r');
230 $default_item_ago = Temporal::getRelativeDate($it['created']);
234 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
235 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
236 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
237 $default_item_url = $it['author-link'];
238 $default_item_text = (($it['id'] == $it['parent'])
239 ? L10n::t("%s created a new post", $it['author-name'])
240 : L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']));
241 $default_item_when = DateTimeFormat::local($it['created'], 'r');
242 $default_item_ago = Temporal::getRelativeDate($it['created']);
245 // Transform the different types of notification in an usable array
246 switch ($it['verb']) {
250 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
251 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
252 'url' => $it['author-link'],
253 'text' => L10n::t("%s liked %s's post", $it['author-name'], $it['parent-author-name']),
254 'when' => $default_item_when,
255 'ago' => $default_item_ago,
256 'seen' => $it['seen']
260 case ACTIVITY_DISLIKE:
262 'label' => 'dislike',
263 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
264 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
265 'url' => $it['author-link'],
266 'text' => L10n::t("%s disliked %s's post", $it['author-name'], $it['parent-author-name']),
267 'when' => $default_item_when,
268 'ago' => $default_item_ago,
269 'seen' => $it['seen']
273 case ACTIVITY_ATTEND:
276 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
277 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
278 'url' => $it['author-link'],
279 'text' => L10n::t("%s is attending %s's event", $it['author-name'], $it['parent-author-name']),
280 'when' => $default_item_when,
281 'ago' => $default_item_ago,
282 'seen' => $it['seen']
286 case ACTIVITY_ATTENDNO:
288 'label' => 'attendno',
289 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
290 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
291 'url' => $it['author-link'],
292 'text' => L10n::t("%s is not attending %s's event", $it['author-name'], $it['parent-author-name']),
293 'when' => $default_item_when,
294 'ago' => $default_item_ago,
295 'seen' => $it['seen']
299 case ACTIVITY_ATTENDMAYBE:
301 'label' => 'attendmaybe',
302 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
303 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
304 'url' => $it['author-link'],
305 'text' => L10n::t("%s may attend %s's event", $it['author-name'], $it['parent-author-name']),
306 'when' => $default_item_when,
307 'ago' => $default_item_ago,
308 'seen' => $it['seen']
312 case ACTIVITY_FRIEND:
313 if (!isset($it['object'])) {
316 'link' => $default_item_link,
317 'image' => $default_item_image,
318 'url' => $default_item_url,
319 'text' => $default_item_text,
320 'when' => $default_item_when,
321 'ago' => $default_item_ago,
322 'seen' => $it['seen']
326 /// @todo Check if this part here is used at all
327 Logger::log('Complete data: ' . json_encode($it) . ' - ' . System::callstack(20), Logger::DEBUG);
329 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
330 $obj = XML::parseString($xmlhead . $it['object']);
331 $it['fname'] = $obj->title;
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 is now friends with %s", $it['author-name'], $it['fname']),
339 'when' => $default_item_when,
340 'ago' => $default_item_ago,
341 'seen' => $it['seen']
347 'label' => $default_item_label,
348 'link' => $default_item_link,
349 'image' => $default_item_image,
350 'url' => $default_item_url,
351 'text' => $default_item_text,
352 'when' => $default_item_when,
353 'ago' => $default_item_ago,
354 'seen' => $it['seen']
366 * @brief Get network notifications
368 * @param int|string $seen If 0 only include notifications into the query
369 * which aren't marked as "seen"
370 * @param int $start Start the query at this point
371 * @param int $limit Maximum number of query results
374 * string 'ident' => Notification identifier
375 * array 'notifications' => Network notifications
376 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
378 public function networkNotifs($seen = 0, $start = 0, $limit = 80)
383 $condition = ['wall' => false, 'uid' => local_user()];
386 $condition['unseen'] = true;
389 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
390 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
391 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
393 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
395 if (DBA::isResult($items)) {
396 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
400 'notifications' => $notifs,
408 * @brief Get system notifications
410 * @param int|string $seen If 0 only include notifications into the query
411 * which aren't marked as "seen"
412 * @param int $start Start the query at this point
413 * @param int $limit Maximum number of query results
416 * string 'ident' => Notification identifier
417 * array 'notifications' => System notifications
418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
420 public function systemNotifs($seen = 0, $start = 0, $limit = 80)
427 $filter = ['`uid` = ? AND NOT `seen`', local_user()];
429 $filter = ['uid' => local_user()];
433 $params['limit'] = [$start, $limit];
435 $r = DBA::select('notify',
436 ['id', 'url', 'photo', 'msg', 'date', 'seen', 'verb'],
440 if (DBA::isResult($r)) {
441 $notifs = $this->formatNotifs(DBA::toArray($r), $ident);
445 'notifications' => $notifs,
453 * @brief Get personal notifications
455 * @param int|string $seen If 0 only include notifications into the query
456 * which aren't marked as "seen"
457 * @param int $start Start the query at this point
458 * @param int $limit Maximum number of query results
461 * string 'ident' => Notification identifier
462 * array 'notifications' => Personal notifications
465 public function personalNotifs($seen = 0, $start = 0, $limit = 80)
470 $myurl = str_replace('http://', '', self::getApp()->contact['nurl']);
471 $diasp_url = str_replace('/profile/', '/u/', $myurl);
473 $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)",
474 local_user(), public_contact(), $myurl . '\\]', $diasp_url . '\\]'];
477 $condition[0] .= " AND `unseen`";
480 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
481 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
482 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
484 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
486 if (DBA::isResult($items)) {
487 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
491 'notifications' => $notifs,
499 * @brief Get home notifications
501 * @param int|string $seen If 0 only include notifications into the query
502 * which aren't marked as "seen"
503 * @param int $start Start the query at this point
504 * @param int $limit Maximum number of query results
507 * string 'ident' => Notification identifier
508 * array 'notifications' => Home notifications
509 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
511 public function homeNotifs($seen = 0, $start = 0, $limit = 80)
516 $condition = ['wall' => true, 'uid' => local_user()];
519 $condition['unseen'] = true;
522 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
523 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
524 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
525 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
527 if (DBA::isResult($items)) {
528 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
532 'notifications' => $notifs,
540 * @brief Get introductions
542 * @param bool $all If false only include introductions into the query
543 * which aren't marked as ignored
544 * @param int $start Start the query at this point
545 * @param int $limit Maximum number of query results
548 * string 'ident' => Notification identifier
549 * array 'notifications' => Introductions
550 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
551 * @throws \ImagickException
553 public function introNotifs($all = false, $start = 0, $limit = 80)
555 $ident = 'introductions';
560 $sql_extra = " AND `ignore` = 0 ";
563 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
565 "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
566 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`,
567 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
568 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
569 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
570 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
572 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
573 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
574 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
575 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
577 intval($_SESSION['uid']),
581 if (DBA::isResult($r)) {
582 $notifs = $this->formatIntros(DBA::toArray($r));
587 'notifications' => $notifs,
594 * @brief Format the notification query in an usable array
596 * @param array $intros The array from the db query
597 * @return array with the introductions
598 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
599 * @throws \ImagickException
601 private function formatIntros($intros)
607 foreach ($intros as $it) {
608 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
609 // We have to distinguish between these two because they use different data.
610 // Contact suggestions
612 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->getHostName() . ((self::getApp()->getURLPath()) ? '/' . self::getApp()->getURLPath() : ''));
615 'label' => 'friend_suggestion',
616 'notify_type' => L10n::t('Friend Suggestion'),
617 'intro_id' => $it['intro_id'],
618 'madeby' => $it['name'],
619 'madeby_url' => $it['url'],
620 'madeby_zrl' => Contact::magicLink($it['url']),
621 'madeby_addr' => $it['addr'],
622 'contact_id' => $it['contact-id'],
623 'photo' => (!empty($it['fphoto']) ? ProxyUtils::proxifyUrl($it['fphoto'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"),
624 'name' => $it['fname'],
625 'url' => $it['furl'],
626 'zrl' => Contact::magicLink($it['furl']),
627 'hidden' => $it['hidden'] == 1,
628 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
629 'knowyou' => $knowyou,
630 'note' => $it['note'],
631 'request' => $it['frequest'] . '?addr=' . $return_addr,
634 // Normal connection requests
636 $it = $this->getMissingIntroData($it);
638 if (empty($it['url'])) {
642 // Don't show these data until you are connected. Diaspora is doing the same.
643 if ($it['gnetwork'] === Protocol::DIASPORA) {
644 $it['glocation'] = "";
649 'label' => (($it['network'] !== Protocol::OSTATUS) ? 'friend_request' : 'follower'),
650 'notify_type' => (($it['network'] !== Protocol::OSTATUS) ? L10n::t('Friend/Connect Request') : L10n::t('New Follower')),
651 'dfrn_id' => $it['issued-id'],
652 'uid' => $_SESSION['uid'],
653 'intro_id' => $it['intro_id'],
654 'contact_id' => $it['contact-id'],
655 'photo' => (!empty($it['photo']) ? ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"),
656 'name' => $it['name'],
657 'location' => BBCode::convert($it['glocation'], false),
658 'about' => BBCode::convert($it['gabout'], false),
659 'keywords' => $it['gkeywords'],
660 'gender' => $it['ggender'],
661 'hidden' => $it['hidden'] == 1,
662 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
664 'zrl' => Contact::magicLink($it['url']),
665 'addr' => $it['gaddr'],
666 'network' => $it['gnetwork'],
667 'knowyou' => $it['knowyou'],
668 'note' => $it['note'],
679 * @brief Check for missing contact data and try to fetch the data from
682 * @param array $arr The input array with the intro data
684 * @return array The array with the intro data
685 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
687 private function getMissingIntroData($arr)
689 // If the network and the addr isn't available from the gcontact
690 // table entry, take the one of the contact table entry
691 if (empty($arr['gnetwork']) && !empty($arr['network'])) {
692 $arr['gnetwork'] = $arr['network'];
694 if (empty($arr['gaddr']) && !empty($arr['addr'])) {
695 $arr['gaddr'] = $arr['addr'];
698 // If the network and addr is still not available
699 // get the missing data data from other sources
700 if (empty($arr['gnetwork']) || empty($arr['gaddr'])) {
701 $ret = Contact::getDetailsByURL($arr['url']);
703 if (empty($arr['gnetwork']) && !empty($ret['network'])) {
704 $arr['gnetwork'] = $ret['network'];
706 if (empty($arr['gaddr']) && !empty($ret['addr'])) {
707 $arr['gaddr'] = $ret['addr'];