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
39 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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
65 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
67 public function getAll($filter = [], $order = "-date", $limit = "")
71 foreach ($filter as $column => $value) {
72 $filter_str[] = sprintf("`%s` = '%s'", $column, DBA::escape($value));
74 if (count($filter_str) > 0) {
75 $filter_sql = "AND " . implode(" AND ", $filter_str);
78 $aOrder = explode(" ", $order);
80 foreach ($aOrder as $o) {
90 $asOrder[] = "$o $dir";
92 $order_sql = implode(", ", $asOrder);
95 $limit = " LIMIT " . $limit;
98 "SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
102 if (DBA::isResult($r)) {
103 return $this->_set_extra($r);
110 * @brief Get one note for local_user() by $id value
112 * @param int $id identity
113 * @return array note values or null if not found
114 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
116 public function getByID($id)
119 "SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
123 if (DBA::isResult($r)) {
124 return $this->_set_extra($r)[0];
130 * @brief set seen state of $note of local_user()
132 * @param array $note note array
133 * @param bool $seen optional true or false, default true
134 * @return bool true on success, false on errors
137 public function setSeen($note, $seen = true)
140 "UPDATE `notify` SET `seen` = %d WHERE (`link` = '%s' OR (`parent` != 0 AND `parent` = %d AND `otype` = '%s')) AND `uid` = %d",
142 DBA::escape($note['link']),
143 intval($note['parent']),
144 DBA::escape($note['otype']),
150 * @brief set seen state of all notifications of local_user()
152 * @param bool $seen optional true or false. default true
153 * @return bool true on success, false on error
156 public function setAllSeen($seen = true)
159 "UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
166 * @brief List of pages for the Notifications TabBar
168 * @return array with with notifications TabBar data
171 public function getTabs()
173 $selected = defaults(self::getApp()->argv, 1, '');
177 'label' => L10n::t('System'),
178 'url' => 'notifications/system',
179 'sel' => (($selected == 'system') ? 'active' : ''),
180 'id' => 'system-tab',
184 'label' => L10n::t('Network'),
185 'url' => 'notifications/network',
186 'sel' => (($selected == 'network') ? 'active' : ''),
187 'id' => 'network-tab',
191 'label' => L10n::t('Personal'),
192 'url' => 'notifications/personal',
193 'sel' => (($selected == 'personal') ? 'active' : ''),
194 'id' => 'personal-tab',
198 'label' => L10n::t('Home'),
199 'url' => 'notifications/home',
200 'sel' => (($selected == 'home') ? 'active' : ''),
205 'label' => L10n::t('Introductions'),
206 'url' => 'notifications/intros',
207 'sel' => (($selected == 'intros') ? 'active' : ''),
217 * @brief Format the notification query in an usable array
219 * @param array $notifs The array from the db query
220 * @param string $ident The notifications identifier (e.g. network)
222 * string 'label' => The type of the notification
223 * string 'link' => URL to the source
224 * string 'image' => The avatar image
225 * string 'url' => The profile url of the contact
226 * string 'text' => The notification text
227 * string 'when' => The date of the notification
228 * string 'ago' => T relative date of the notification
229 * bool 'seen' => Is the notification marked as "seen"
230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
232 private function formatNotifs(array $notifs, $ident = "")
237 if (DBA::isResult($notifs)) {
238 foreach ($notifs as $it) {
239 // Because we use different db tables for the notification query
240 // we have sometimes $it['unseen'] and sometimes $it['seen].
241 // So we will have to transform $it['unseen']
242 if (array_key_exists('unseen', $it)) {
243 $it['seen'] = ($it['unseen'] > 0 ? false : true);
246 // For feed items we use the user's contact, since the avatar is mostly self choosen.
247 if (!empty($it['network']) && $it['network'] == Protocol::FEED) {
248 $it['author-avatar'] = $it['contact-avatar'];
251 // Depending on the identifier of the notification we need to use different defaults
254 $default_item_label = 'notify';
255 $default_item_link = System::baseUrl(true) . '/notify/view/' . $it['id'];
256 $default_item_image = ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_MICRO);
257 $default_item_url = $it['url'];
258 $default_item_text = strip_tags(BBCode::convert($it['msg']));
259 $default_item_when = DateTimeFormat::local($it['date'], 'r');
260 $default_item_ago = Temporal::getRelativeDate($it['date']);
264 $default_item_label = 'comment';
265 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
266 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
267 $default_item_url = $it['author-link'];
268 $default_item_text = L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']);
269 $default_item_when = DateTimeFormat::local($it['created'], 'r');
270 $default_item_ago = Temporal::getRelativeDate($it['created']);
274 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
275 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
276 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
277 $default_item_url = $it['author-link'];
278 $default_item_text = (($it['id'] == $it['parent'])
279 ? L10n::t("%s created a new post", $it['author-name'])
280 : L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']));
281 $default_item_when = DateTimeFormat::local($it['created'], 'r');
282 $default_item_ago = Temporal::getRelativeDate($it['created']);
285 // Transform the different types of notification in an usable array
286 switch ($it['verb']) {
290 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
291 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
292 'url' => $it['author-link'],
293 'text' => L10n::t("%s liked %s's post", $it['author-name'], $it['parent-author-name']),
294 'when' => $default_item_when,
295 'ago' => $default_item_ago,
296 'seen' => $it['seen']
300 case ACTIVITY_DISLIKE:
302 'label' => 'dislike',
303 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
304 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
305 'url' => $it['author-link'],
306 'text' => L10n::t("%s disliked %s's post", $it['author-name'], $it['parent-author-name']),
307 'when' => $default_item_when,
308 'ago' => $default_item_ago,
309 'seen' => $it['seen']
313 case ACTIVITY_ATTEND:
316 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
317 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
318 'url' => $it['author-link'],
319 'text' => L10n::t("%s is attending %s's event", $it['author-name'], $it['parent-author-name']),
320 'when' => $default_item_when,
321 'ago' => $default_item_ago,
322 'seen' => $it['seen']
326 case ACTIVITY_ATTENDNO:
328 'label' => 'attendno',
329 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
330 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
331 'url' => $it['author-link'],
332 'text' => L10n::t("%s is not attending %s's event", $it['author-name'], $it['parent-author-name']),
333 'when' => $default_item_when,
334 'ago' => $default_item_ago,
335 'seen' => $it['seen']
339 case ACTIVITY_ATTENDMAYBE:
341 'label' => 'attendmaybe',
342 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
343 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
344 'url' => $it['author-link'],
345 'text' => L10n::t("%s may attend %s's event", $it['author-name'], $it['parent-author-name']),
346 'when' => $default_item_when,
347 'ago' => $default_item_ago,
348 'seen' => $it['seen']
352 case ACTIVITY_FRIEND:
353 if (!isset($it['object'])) {
356 'link' => $default_item_link,
357 'image' => $default_item_image,
358 'url' => $default_item_url,
359 'text' => $default_item_text,
360 'when' => $default_item_when,
361 'ago' => $default_item_ago,
362 'seen' => $it['seen']
366 /// @todo Check if this part here is used at all
367 Logger::log('Complete data: ' . json_encode($it) . ' - ' . System::callstack(20), Logger::DEBUG);
369 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
370 $obj = XML::parseString($xmlhead . $it['object']);
371 $it['fname'] = $obj->title;
375 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
376 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
377 'url' => $it['author-link'],
378 'text' => L10n::t("%s is now friends with %s", $it['author-name'], $it['fname']),
379 'when' => $default_item_when,
380 'ago' => $default_item_ago,
381 'seen' => $it['seen']
387 'label' => $default_item_label,
388 'link' => $default_item_link,
389 'image' => $default_item_image,
390 'url' => $default_item_url,
391 'text' => $default_item_text,
392 'when' => $default_item_when,
393 'ago' => $default_item_ago,
394 'seen' => $it['seen']
406 * @brief Get network notifications
408 * @param int|string $seen If 0 only include notifications into the query
409 * which aren't marked as "seen"
410 * @param int $start Start the query at this point
411 * @param int $limit Maximum number of query results
414 * string 'ident' => Notification identifier
415 * array 'notifications' => Network notifications
416 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
418 public function networkNotifs($seen = 0, $start = 0, $limit = 80)
423 $condition = ['wall' => false, 'uid' => local_user()];
426 $condition['unseen'] = true;
429 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
430 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
431 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
433 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
435 if (DBA::isResult($items)) {
436 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
440 'notifications' => $notifs,
448 * @brief Get system notifications
450 * @param int|string $seen If 0 only include notifications into the query
451 * which aren't marked as "seen"
452 * @param int $start Start the query at this point
453 * @param int $limit Maximum number of query results
456 * string 'ident' => Notification identifier
457 * array 'notifications' => System notifications
458 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
460 public function systemNotifs($seen = 0, $start = 0, $limit = 80)
467 $sql_seen = " AND NOT `seen` ";
471 "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen`, `verb` FROM `notify`
472 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
473 intval(local_user()),
478 if (DBA::isResult($r)) {
479 $notifs = $this->formatNotifs($r, $ident);
483 'notifications' => $notifs,
491 * @brief Get personal notifications
493 * @param int|string $seen If 0 only include notifications into the query
494 * which aren't marked as "seen"
495 * @param int $start Start the query at this point
496 * @param int $limit Maximum number of query results
499 * string 'ident' => Notification identifier
500 * array 'notifications' => Personal notifications
503 public function personalNotifs($seen = 0, $start = 0, $limit = 80)
508 $myurl = str_replace('http://', '', self::getApp()->contact['nurl']);
509 $diasp_url = str_replace('/profile/', '/u/', $myurl);
511 $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)",
512 local_user(), public_contact(), $myurl . '\\]', $diasp_url . '\\]'];
515 $condition[0] .= " AND `unseen`";
518 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
519 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
520 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
522 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
524 if (DBA::isResult($items)) {
525 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
529 'notifications' => $notifs,
537 * @brief Get home notifications
539 * @param int|string $seen If 0 only include notifications into the query
540 * which aren't marked as "seen"
541 * @param int $start Start the query at this point
542 * @param int $limit Maximum number of query results
545 * string 'ident' => Notification identifier
546 * array 'notifications' => Home notifications
547 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
549 public function homeNotifs($seen = 0, $start = 0, $limit = 80)
554 $condition = ['wall' => true, 'uid' => local_user()];
557 $condition['unseen'] = true;
560 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
561 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
562 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
563 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
565 if (DBA::isResult($items)) {
566 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
570 'notifications' => $notifs,
578 * @brief Get introductions
580 * @param bool $all If false only include introductions into the query
581 * which aren't marked as ignored
582 * @param int $start Start the query at this point
583 * @param int $limit Maximum number of query results
586 * string 'ident' => Notification identifier
587 * array 'notifications' => Introductions
588 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
589 * @throws \ImagickException
591 public function introNotifs($all = false, $start = 0, $limit = 80)
593 $ident = 'introductions';
598 $sql_extra = " AND `ignore` = 0 ";
601 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
603 "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
604 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`,
605 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
606 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
607 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
608 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
610 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
611 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
612 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
613 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
615 intval($_SESSION['uid']),
619 if (DBA::isResult($r)) {
620 $notifs = $this->formatIntros($r);
625 'notifications' => $notifs,
632 * @brief Format the notification query in an usable array
634 * @param array $intros The array from the db query
635 * @return array with the introductions
636 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
637 * @throws \ImagickException
639 private function formatIntros($intros)
643 foreach ($intros as $it) {
644 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
645 // We have to distinguish between these two because they use different data.
646 // Contact suggestions
648 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->getHostName() . ((self::getApp()->getURLPath()) ? '/' . self::getApp()->getURLPath() : ''));
651 'label' => 'friend_suggestion',
652 'notify_type' => L10n::t('Friend Suggestion'),
653 'intro_id' => $it['intro_id'],
654 'madeby' => $it['name'],
655 'madeby_url' => $it['url'],
656 'madeby_zrl' => Contact::magicLink($it['url']),
657 'madeby_addr' => $it['addr'],
658 'contact_id' => $it['contact-id'],
659 'photo' => (!empty($it['fphoto']) ? ProxyUtils::proxifyUrl($it['fphoto'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"),
660 'name' => $it['fname'],
661 'url' => $it['furl'],
662 'zrl' => Contact::magicLink($it['furl']),
663 'hidden' => $it['hidden'] == 1,
664 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
665 'knowyou' => $knowyou,
666 'note' => $it['note'],
667 'request' => $it['frequest'] . '?addr=' . $return_addr,
670 // Normal connection requests
672 $it = $this->getMissingIntroData($it);
674 if (empty($it['url'])) {
678 // Don't show these data until you are connected. Diaspora is doing the same.
679 if ($it['gnetwork'] === Protocol::DIASPORA) {
680 $it['glocation'] = "";
685 'label' => (($it['network'] !== Protocol::OSTATUS) ? 'friend_request' : 'follower'),
686 'notify_type' => (($it['network'] !== Protocol::OSTATUS) ? L10n::t('Friend/Connect Request') : L10n::t('New Follower')),
687 'dfrn_id' => $it['issued-id'],
688 'uid' => $_SESSION['uid'],
689 'intro_id' => $it['intro_id'],
690 'contact_id' => $it['contact-id'],
691 'photo' => (!empty($it['photo']) ? ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"),
692 'name' => $it['name'],
693 'location' => BBCode::convert($it['glocation'], false),
694 'about' => BBCode::convert($it['gabout'], false),
695 'keywords' => $it['gkeywords'],
696 'gender' => $it['ggender'],
697 'hidden' => $it['hidden'] == 1,
698 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
700 'zrl' => Contact::magicLink($it['url']),
701 'addr' => $it['gaddr'],
702 'network' => $it['gnetwork'],
703 'knowyou' => $it['knowyou'],
704 'note' => $it['note'],
715 * @brief Check for missing contact data and try to fetch the data from
718 * @param array $arr The input array with the intro data
720 * @return array The array with the intro data
721 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
723 private function getMissingIntroData($arr)
725 // If the network and the addr isn't available from the gcontact
726 // table entry, take the one of the contact table entry
727 if (empty($arr['gnetwork']) && !empty($arr['network'])) {
728 $arr['gnetwork'] = $arr['network'];
730 if (empty($arr['gaddr']) && !empty($arr['addr'])) {
731 $arr['gaddr'] = $arr['addr'];
734 // If the network and addr is still not available
735 // get the missing data data from other sources
736 if (empty($arr['gnetwork']) || empty($arr['gaddr'])) {
737 $ret = Contact::getDetailsByURL($arr['url']);
739 if (empty($arr['gnetwork']) && !empty($ret['network'])) {
740 $arr['gnetwork'] = $ret['network'];
742 if (empty($arr['gaddr']) && !empty($ret['addr'])) {
743 $arr['gaddr'] = $ret['addr'];