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;
22 require_once 'include/dba.php';
25 * @brief Methods for read and write notifications from/to database
26 * or for formatting notifications
28 class NotificationsManager extends BaseObject
31 * @brief set some extra note properties
33 * @param array $notes array of note arrays from db
34 * @return array Copy of input array with added properties
36 * Set some extra properties to note array from db:
37 * - timestamp as int in default TZ
38 * - date_rel : relative date string
39 * - msg_html: message as html string
40 * - msg_plain: message as plain text string
42 private function _set_extra($notes)
45 foreach ($notes as $n) {
46 $local_time = DateTimeFormat::local($n['date']);
47 $n['timestamp'] = strtotime($local_time);
48 $n['date_rel'] = Temporal::getRelativeDate($n['date']);
49 $n['msg_html'] = BBCode::convert($n['msg'], false);
50 $n['msg_plain'] = explode("\n", trim(HTML::toPlaintext($n['msg_html'], 0)))[0];
58 * @brief Get all notifications for local_user()
60 * @param array $filter optional Array "column name"=>value: filter query by columns values
61 * @param string $order optional Space separated list of column to sort by.
62 * Prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
63 * @param string $limit optional Query limits
65 * @return array of results or false on errors
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
115 public function getByID($id)
118 "SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
122 if (DBA::isResult($r)) {
123 return $this->_set_extra($r)[0];
129 * @brief set seen state of $note of local_user()
131 * @param array $note note array
132 * @param bool $seen optional true or false, default true
133 * @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
153 public function setAllSeen($seen = true)
156 "UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
163 * @brief List of pages for the Notifications TabBar
165 * @return array with with notifications TabBar data
167 public function getTabs()
169 $selected = defaults(self::getApp()->argv, 1, '');
173 'label' => L10n::t('System'),
174 'url' => 'notifications/system',
175 'sel' => (($selected == 'system') ? 'active' : ''),
176 'id' => 'system-tab',
180 'label' => L10n::t('Network'),
181 'url' => 'notifications/network',
182 'sel' => (($selected == 'network') ? 'active' : ''),
183 'id' => 'network-tab',
187 'label' => L10n::t('Personal'),
188 'url' => 'notifications/personal',
189 'sel' => (($selected == 'personal') ? 'active' : ''),
190 'id' => 'personal-tab',
194 'label' => L10n::t('Home'),
195 'url' => 'notifications/home',
196 'sel' => (($selected == 'home') ? 'active' : ''),
201 'label' => L10n::t('Introductions'),
202 'url' => 'notifications/intros',
203 'sel' => (($selected == 'intros') ? 'active' : ''),
213 * @brief Format the notification query in an usable array
215 * @param array $notifs The array from the db query
216 * @param string $ident The notifications identifier (e.g. network)
218 * string 'label' => The type of the notification
219 * string 'link' => URL to the source
220 * string 'image' => The avatar image
221 * string 'url' => The profile url of the contact
222 * string 'text' => The notification text
223 * string 'when' => The date of the notification
224 * string 'ago' => T relative date of the notification
225 * bool 'seen' => Is the notification marked as "seen"
227 private function formatNotifs(array $notifs, $ident = "")
232 if (DBA::isResult($notifs)) {
233 foreach ($notifs as $it) {
234 // Because we use different db tables for the notification query
235 // we have sometimes $it['unseen'] and sometimes $it['seen].
236 // So we will have to transform $it['unseen']
237 if (array_key_exists('unseen', $it)) {
238 $it['seen'] = ($it['unseen'] > 0 ? false : true);
241 // For feed items we use the user's contact, since the avatar is mostly self choosen.
242 if (!empty($it['network']) && $it['network'] == Protocol::FEED) {
243 $it['author-avatar'] = $it['contact-avatar'];
246 // Depending on the identifier of the notification we need to use different defaults
249 $default_item_label = 'notify';
250 $default_item_link = System::baseUrl(true) . '/notify/view/' . $it['id'];
251 $default_item_image = ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_MICRO);
252 $default_item_url = $it['url'];
253 $default_item_text = strip_tags(BBCode::convert($it['msg']));
254 $default_item_when = DateTimeFormat::local($it['date'], 'r');
255 $default_item_ago = Temporal::getRelativeDate($it['date']);
259 $default_item_label = 'comment';
260 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
261 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
262 $default_item_url = $it['author-link'];
263 $default_item_text = L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']);
264 $default_item_when = DateTimeFormat::local($it['created'], 'r');
265 $default_item_ago = Temporal::getRelativeDate($it['created']);
269 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
270 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
271 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
272 $default_item_url = $it['author-link'];
273 $default_item_text = (($it['id'] == $it['parent'])
274 ? L10n::t("%s created a new post", $it['author-name'])
275 : L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']));
276 $default_item_when = DateTimeFormat::local($it['created'], 'r');
277 $default_item_ago = Temporal::getRelativeDate($it['created']);
280 // Transform the different types of notification in an usable array
281 switch ($it['verb']) {
285 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
286 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
287 'url' => $it['author-link'],
288 'text' => L10n::t("%s liked %s's post", $it['author-name'], $it['parent-author-name']),
289 'when' => $default_item_when,
290 'ago' => $default_item_ago,
291 'seen' => $it['seen']
295 case ACTIVITY_DISLIKE:
297 'label' => 'dislike',
298 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
299 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
300 'url' => $it['author-link'],
301 'text' => L10n::t("%s disliked %s's post", $it['author-name'], $it['parent-author-name']),
302 'when' => $default_item_when,
303 'ago' => $default_item_ago,
304 'seen' => $it['seen']
308 case ACTIVITY_ATTEND:
311 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
312 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
313 'url' => $it['author-link'],
314 'text' => L10n::t("%s is attending %s's event", $it['author-name'], $it['parent-author-name']),
315 'when' => $default_item_when,
316 'ago' => $default_item_ago,
317 'seen' => $it['seen']
321 case ACTIVITY_ATTENDNO:
323 'label' => 'attendno',
324 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
325 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
326 'url' => $it['author-link'],
327 'text' => L10n::t("%s is not attending %s's event", $it['author-name'], $it['parent-author-name']),
328 'when' => $default_item_when,
329 'ago' => $default_item_ago,
330 'seen' => $it['seen']
334 case ACTIVITY_ATTENDMAYBE:
336 'label' => 'attendmaybe',
337 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
338 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
339 'url' => $it['author-link'],
340 'text' => L10n::t("%s may attend %s's event", $it['author-name'], $it['parent-author-name']),
341 'when' => $default_item_when,
342 'ago' => $default_item_ago,
343 'seen' => $it['seen']
347 case ACTIVITY_FRIEND:
348 if (!isset($it['object'])) {
351 'link' => $default_item_link,
352 'image' => $default_item_image,
353 'url' => $default_item_url,
354 'text' => $default_item_text,
355 'when' => $default_item_when,
356 'ago' => $default_item_ago,
357 'seen' => $it['seen']
361 /// @todo Check if this part here is used at all
362 Logger::log('Complete data: ' . json_encode($it) . ' - ' . System::callstack(20), Logger::DEBUG);
364 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
365 $obj = XML::parseString($xmlhead . $it['object']);
366 $it['fname'] = $obj->title;
370 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
371 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
372 'url' => $it['author-link'],
373 'text' => L10n::t("%s is now friends with %s", $it['author-name'], $it['fname']),
374 'when' => $default_item_when,
375 'ago' => $default_item_ago,
376 'seen' => $it['seen']
382 'label' => $default_item_label,
383 'link' => $default_item_link,
384 'image' => $default_item_image,
385 'url' => $default_item_url,
386 'text' => $default_item_text,
387 'when' => $default_item_when,
388 'ago' => $default_item_ago,
389 'seen' => $it['seen']
401 * @brief Get network notifications
403 * @param int|string $seen If 0 only include notifications into the query
404 * which aren't marked as "seen"
405 * @param int $start Start the query at this point
406 * @param int $limit Maximum number of query results
409 * string 'ident' => Notification identifier
410 * array 'notifications' => Network notifications
412 public function networkNotifs($seen = 0, $start = 0, $limit = 80)
417 $condition = ['wall' => false, 'uid' => local_user()];
420 $condition['unseen'] = true;
423 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
424 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
425 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
427 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
429 if (DBA::isResult($items)) {
430 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
434 'notifications' => $notifs,
442 * @brief Get system notifications
444 * @param int|string $seen If 0 only include notifications into the query
445 * which aren't marked as "seen"
446 * @param int $start Start the query at this point
447 * @param int $limit Maximum number of query results
450 * string 'ident' => Notification identifier
451 * array 'notifications' => System notifications
453 public function systemNotifs($seen = 0, $start = 0, $limit = 80)
460 $sql_seen = " AND NOT `seen` ";
464 "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen`, `verb` FROM `notify`
465 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
466 intval(local_user()),
471 if (DBA::isResult($r)) {
472 $notifs = $this->formatNotifs($r, $ident);
476 'notifications' => $notifs,
484 * @brief Get personal notifications
486 * @param int|string $seen If 0 only include notifications into the query
487 * which aren't marked as "seen"
488 * @param int $start Start the query at this point
489 * @param int $limit Maximum number of query results
492 * string 'ident' => Notification identifier
493 * array 'notifications' => Personal notifications
495 public function personalNotifs($seen = 0, $start = 0, $limit = 80)
500 $myurl = str_replace('http://', '', self::getApp()->contact['nurl']);
501 $diasp_url = str_replace('/profile/', '/u/', $myurl);
503 $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)",
504 local_user(), public_contact(), $myurl . '\\]', $diasp_url . '\\]'];
507 $condition[0] .= " AND `unseen`";
510 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
511 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
512 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
514 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
516 if (DBA::isResult($items)) {
517 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
521 'notifications' => $notifs,
529 * @brief Get home notifications
531 * @param int|string $seen If 0 only include notifications into the query
532 * which aren't marked as "seen"
533 * @param int $start Start the query at this point
534 * @param int $limit Maximum number of query results
537 * string 'ident' => Notification identifier
538 * array 'notifications' => Home notifications
540 public function homeNotifs($seen = 0, $start = 0, $limit = 80)
545 $condition = ['wall' => true, 'uid' => local_user()];
548 $condition['unseen'] = true;
551 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
552 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
553 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
554 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
556 if (DBA::isResult($items)) {
557 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
561 'notifications' => $notifs,
569 * @brief Get introductions
571 * @param bool $all If false only include introductions into the query
572 * which aren't marked as ignored
573 * @param int $start Start the query at this point
574 * @param int $limit Maximum number of query results
577 * string 'ident' => Notification identifier
578 * array 'notifications' => Introductions
580 public function introNotifs($all = false, $start = 0, $limit = 80)
582 $ident = 'introductions';
587 $sql_extra = " AND `ignore` = 0 ";
590 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
592 "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
593 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`,
594 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
595 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
596 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
597 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
599 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
600 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
601 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
602 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
604 intval($_SESSION['uid']),
608 if (DBA::isResult($r)) {
609 $notifs = $this->formatIntros($r);
614 'notifications' => $notifs,
621 * @brief Format the notification query in an usable array
623 * @param array $intros The array from the db query
624 * @return array with the introductions
626 private function formatIntros($intros)
630 foreach ($intros as $it) {
631 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
632 // We have to distinguish between these two because they use different data.
633 // Contact suggestions
635 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->getHostName() . ((self::getApp()->getURLPath()) ? '/' . self::getApp()->getURLPath() : ''));
638 'label' => 'friend_suggestion',
639 'notify_type' => L10n::t('Friend Suggestion'),
640 'intro_id' => $it['intro_id'],
641 'madeby' => $it['name'],
642 'madeby_url' => $it['url'],
643 'madeby_zrl' => Contact::magicLink($it['url']),
644 'madeby_addr' => $it['addr'],
645 'contact_id' => $it['contact-id'],
646 'photo' => ((x($it, 'fphoto')) ? ProxyUtils::proxifyUrl($it['fphoto'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"),
647 'name' => $it['fname'],
648 'url' => $it['furl'],
649 'zrl' => Contact::magicLink($it['furl']),
650 'hidden' => $it['hidden'] == 1,
651 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
652 'knowyou' => $knowyou,
653 'note' => $it['note'],
654 'request' => $it['frequest'] . '?addr=' . $return_addr,
657 // Normal connection requests
659 $it = $this->getMissingIntroData($it);
661 if (empty($it['url'])) {
665 // Don't show these data until you are connected. Diaspora is doing the same.
666 if ($it['gnetwork'] === Protocol::DIASPORA) {
667 $it['glocation'] = "";
672 'label' => (($it['network'] !== Protocol::OSTATUS) ? 'friend_request' : 'follower'),
673 'notify_type' => (($it['network'] !== Protocol::OSTATUS) ? L10n::t('Friend/Connect Request') : L10n::t('New Follower')),
674 'dfrn_id' => $it['issued-id'],
675 'uid' => $_SESSION['uid'],
676 'intro_id' => $it['intro_id'],
677 'contact_id' => $it['contact-id'],
678 'photo' => ((x($it, 'photo')) ? ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_SMALL) : "images/person-300.jpg"),
679 'name' => $it['name'],
680 'location' => BBCode::convert($it['glocation'], false),
681 'about' => BBCode::convert($it['gabout'], false),
682 'keywords' => $it['gkeywords'],
683 'gender' => $it['ggender'],
684 'hidden' => $it['hidden'] == 1,
685 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
687 'zrl' => Contact::magicLink($it['url']),
688 'addr' => $it['gaddr'],
689 'network' => $it['gnetwork'],
690 'knowyou' => $it['knowyou'],
691 'note' => $it['note'],
702 * @brief Check for missing contact data and try to fetch the data from
705 * @param array $arr The input array with the intro data
707 * @return array The array with the intro data
709 private function getMissingIntroData($arr)
711 // If the network and the addr isn't available from the gcontact
712 // table entry, take the one of the contact table entry
713 if (empty($arr['gnetwork']) && !empty($arr['network'])) {
714 $arr['gnetwork'] = $arr['network'];
716 if (empty($arr['gaddr']) && !empty($arr['addr'])) {
717 $arr['gaddr'] = $arr['addr'];
720 // If the network and addr is still not available
721 // get the missing data data from other sources
722 if (empty($arr['gnetwork']) || empty($arr['gaddr'])) {
723 $ret = Contact::getDetailsByURL($arr['url']);
725 if (empty($arr['gnetwork']) && !empty($ret['network'])) {
726 $arr['gnetwork'] = $ret['network'];
728 if (empty($arr['gaddr']) && !empty($ret['addr'])) {
729 $arr['gaddr'] = $ret['addr'];