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\Protocol;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Proxy as ProxyUtils;
18 use Friendica\Util\Temporal;
19 use Friendica\Util\XML;
21 require_once 'include/dba.php';
24 * @brief Methods for read and write notifications from/to database
25 * or for formatting notifications
27 class NotificationsManager extends BaseObject
30 * @brief set some extra note properties
32 * @param array $notes array of note arrays from db
33 * @return array Copy of input array with added properties
35 * Set some extra properties to note array from db:
36 * - timestamp as int in default TZ
37 * - date_rel : relative date string
38 * - msg_html: message as html string
39 * - msg_plain: message as plain text string
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
66 public function getAll($filter = [], $order = "-date", $limit = "")
70 foreach ($filter as $column => $value) {
71 $filter_str[] = sprintf("`%s` = '%s'", $column, DBA::escape($value));
73 if (count($filter_str) > 0) {
74 $filter_sql = "AND " . implode(" AND ", $filter_str);
77 $aOrder = explode(" ", $order);
79 foreach ($aOrder as $o) {
89 $asOrder[] = "$o $dir";
91 $order_sql = implode(", ", $asOrder);
94 $limit = " LIMIT " . $limit;
97 "SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
101 if (DBA::isResult($r)) {
102 return $this->_set_extra($r);
109 * @brief Get one note for local_user() by $id value
111 * @param int $id identity
112 * @return array note values or null if not found
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
134 public function setSeen($note, $seen = true)
137 "UPDATE `notify` SET `seen` = %d WHERE (`link` = '%s' OR (`parent` != 0 AND `parent` = %d AND `otype` = '%s')) AND `uid` = %d",
139 DBA::escape($note['link']),
140 intval($note['parent']),
141 DBA::escape($note['otype']),
147 * @brief set seen state of all notifications of local_user()
149 * @param bool $seen optional true or false. default true
150 * @return bool true on success, false on error
152 public function setAllSeen($seen = true)
155 "UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
162 * @brief List of pages for the Notifications TabBar
164 * @return array with with notifications TabBar data
166 public function getTabs()
168 $selected = defaults(self::getApp()->argv, 1, '');
172 'label' => L10n::t('System'),
173 'url' => 'notifications/system',
174 'sel' => (($selected == 'system') ? 'active' : ''),
175 'id' => 'system-tab',
179 'label' => L10n::t('Network'),
180 'url' => 'notifications/network',
181 'sel' => (($selected == 'network') ? 'active' : ''),
182 'id' => 'network-tab',
186 'label' => L10n::t('Personal'),
187 'url' => 'notifications/personal',
188 'sel' => (($selected == 'personal') ? 'active' : ''),
189 'id' => 'personal-tab',
193 'label' => L10n::t('Home'),
194 'url' => 'notifications/home',
195 'sel' => (($selected == 'home') ? 'active' : ''),
200 'label' => L10n::t('Introductions'),
201 'url' => 'notifications/intros',
202 'sel' => (($selected == 'intros') ? 'active' : ''),
212 * @brief Format the notification query in an usable array
214 * @param array $notifs The array from the db query
215 * @param string $ident The notifications identifier (e.g. network)
217 * string 'label' => The type of the notification
218 * string 'link' => URL to the source
219 * string 'image' => The avatar image
220 * string 'url' => The profile url of the contact
221 * string 'text' => The notification text
222 * string 'when' => The date of the notification
223 * string 'ago' => T relative date of the notification
224 * bool 'seen' => Is the notification marked as "seen"
226 private function formatNotifs(array $notifs, $ident = "")
231 if (DBA::isResult($notifs)) {
232 foreach ($notifs as $it) {
233 // Because we use different db tables for the notification query
234 // we have sometimes $it['unseen'] and sometimes $it['seen].
235 // So we will have to transform $it['unseen']
236 if (array_key_exists('unseen', $it)) {
237 $it['seen'] = ($it['unseen'] > 0 ? false : true);
240 // For feed items we use the user's contact, since the avatar is mostly self choosen.
241 if (!empty($it['network']) && $it['network'] == Protocol::FEED) {
242 $it['author-avatar'] = $it['contact-avatar'];
245 // Depending on the identifier of the notification we need to use different defaults
248 $default_item_label = 'notify';
249 $default_item_link = System::baseUrl(true) . '/notify/view/' . $it['id'];
250 $default_item_image = ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_MICRO);
251 $default_item_url = $it['url'];
252 $default_item_text = strip_tags(BBCode::convert($it['msg']));
253 $default_item_when = DateTimeFormat::local($it['date'], 'r');
254 $default_item_ago = Temporal::getRelativeDate($it['date']);
258 $default_item_label = 'comment';
259 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
260 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
261 $default_item_url = $it['author-link'];
262 $default_item_text = L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']);
263 $default_item_when = DateTimeFormat::local($it['created'], 'r');
264 $default_item_ago = Temporal::getRelativeDate($it['created']);
268 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
269 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
270 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
271 $default_item_url = $it['author-link'];
272 $default_item_text = (($it['id'] == $it['parent'])
273 ? L10n::t("%s created a new post", $it['author-name'])
274 : L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']));
275 $default_item_when = DateTimeFormat::local($it['created'], 'r');
276 $default_item_ago = Temporal::getRelativeDate($it['created']);
279 // Transform the different types of notification in an usable array
280 switch ($it['verb']) {
284 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
285 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
286 'url' => $it['author-link'],
287 'text' => L10n::t("%s liked %s's post", $it['author-name'], $it['parent-author-name']),
288 'when' => $default_item_when,
289 'ago' => $default_item_ago,
290 'seen' => $it['seen']
294 case ACTIVITY_DISLIKE:
296 'label' => 'dislike',
297 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
298 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
299 'url' => $it['author-link'],
300 'text' => L10n::t("%s disliked %s's post", $it['author-name'], $it['parent-author-name']),
301 'when' => $default_item_when,
302 'ago' => $default_item_ago,
303 'seen' => $it['seen']
307 case ACTIVITY_ATTEND:
310 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
311 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
312 'url' => $it['author-link'],
313 'text' => L10n::t("%s is attending %s's event", $it['author-name'], $it['parent-author-name']),
314 'when' => $default_item_when,
315 'ago' => $default_item_ago,
316 'seen' => $it['seen']
320 case ACTIVITY_ATTENDNO:
322 'label' => 'attendno',
323 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
324 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
325 'url' => $it['author-link'],
326 'text' => L10n::t("%s is not attending %s's event", $it['author-name'], $it['parent-author-name']),
327 'when' => $default_item_when,
328 'ago' => $default_item_ago,
329 'seen' => $it['seen']
333 case ACTIVITY_ATTENDMAYBE:
335 'label' => 'attendmaybe',
336 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
337 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
338 'url' => $it['author-link'],
339 'text' => L10n::t("%s may attend %s's event", $it['author-name'], $it['parent-author-name']),
340 'when' => $default_item_when,
341 'ago' => $default_item_ago,
342 'seen' => $it['seen']
346 case ACTIVITY_FRIEND:
347 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
348 $obj = XML::parseString($xmlhead . $it['object']);
349 $it['fname'] = $obj->title;
353 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
354 'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
355 'url' => $it['author-link'],
356 'text' => L10n::t("%s is now friends with %s", $it['author-name'], $it['fname']),
357 'when' => $default_item_when,
358 'ago' => $default_item_ago,
359 'seen' => $it['seen']
365 'label' => $default_item_label,
366 'link' => $default_item_link,
367 'image' => $default_item_image,
368 'url' => $default_item_url,
369 'text' => $default_item_text,
370 'when' => $default_item_when,
371 'ago' => $default_item_ago,
372 'seen' => $it['seen']
384 * @brief Get network notifications
386 * @param int|string $seen If 0 only include notifications into the query
387 * which aren't marked as "seen"
388 * @param int $start Start the query at this point
389 * @param int $limit Maximum number of query results
392 * string 'ident' => Notification identifier
393 * array 'notifications' => Network notifications
395 public function networkNotifs($seen = 0, $start = 0, $limit = 80)
400 $condition = ['wall' => false, 'uid' => local_user()];
403 $condition['unseen'] = true;
406 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
407 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
408 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
410 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
412 if (DBA::isResult($items)) {
413 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
417 'notifications' => $notifs,
425 * @brief Get system notifications
427 * @param int|string $seen If 0 only include notifications into the query
428 * which aren't marked as "seen"
429 * @param int $start Start the query at this point
430 * @param int $limit Maximum number of query results
433 * string 'ident' => Notification identifier
434 * array 'notifications' => System notifications
436 public function systemNotifs($seen = 0, $start = 0, $limit = 80)
443 $sql_seen = " AND NOT `seen` ";
447 "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen`, `verb` FROM `notify`
448 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
449 intval(local_user()),
454 if (DBA::isResult($r)) {
455 $notifs = $this->formatNotifs($r, $ident);
459 'notifications' => $notifs,
467 * @brief Get personal notifications
469 * @param int|string $seen If 0 only include notifications into the query
470 * which aren't marked as "seen"
471 * @param int $start Start the query at this point
472 * @param int $limit Maximum number of query results
475 * string 'ident' => Notification identifier
476 * array 'notifications' => Personal notifications
478 public function personalNotifs($seen = 0, $start = 0, $limit = 80)
483 $myurl = str_replace('http://', '', self::getApp()->contact['nurl']);
484 $diasp_url = str_replace('/profile/', '/u/', $myurl);
486 $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)",
487 local_user(), public_contact(), $myurl . '\\]', $diasp_url . '\\]'];
490 $condition[0] .= " AND `unseen`";
493 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
494 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
495 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
497 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
499 if (DBA::isResult($items)) {
500 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
504 'notifications' => $notifs,
512 * @brief Get home notifications
514 * @param int|string $seen If 0 only include notifications into the query
515 * which aren't marked as "seen"
516 * @param int $start Start the query at this point
517 * @param int $limit Maximum number of query results
520 * string 'ident' => Notification identifier
521 * array 'notifications' => Home notifications
523 public function homeNotifs($seen = 0, $start = 0, $limit = 80)
528 $condition = ['wall' => true, 'uid' => local_user()];
531 $condition['unseen'] = true;
534 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
535 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
536 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
537 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
539 if (DBA::isResult($items)) {
540 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
544 'notifications' => $notifs,
552 * @brief Get introductions
554 * @param bool $all If false only include introductions into the query
555 * which aren't marked as ignored
556 * @param int $start Start the query at this point
557 * @param int $limit Maximum number of query results
560 * string 'ident' => Notification identifier
561 * array 'notifications' => Introductions
563 public function introNotifs($all = false, $start = 0, $limit = 80)
565 $ident = 'introductions';
570 $sql_extra = " AND `ignore` = 0 ";
573 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
575 "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
576 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`,
577 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
578 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
579 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
580 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
582 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
583 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
584 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
585 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
587 intval($_SESSION['uid']),
591 if (DBA::isResult($r)) {
592 $notifs = $this->formatIntros($r);
597 'notifications' => $notifs,
604 * @brief Format the notification query in an usable array
606 * @param array $intros The array from the db query
607 * @return array with the introductions
609 private function formatIntros($intros)
613 foreach ($intros as $it) {
614 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
615 // We have to distinguish between these two because they use different data.
616 // Contact suggestions
618 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->get_hostname() . ((self::getApp()->urlpath) ? '/' . self::getApp()->urlpath : ''));
621 'label' => 'friend_suggestion',
622 'notify_type' => L10n::t('Friend Suggestion'),
623 'intro_id' => $it['intro_id'],
624 'madeby' => $it['name'],
625 'madeby_url' => $it['url'],
626 'madeby_zrl' => Contact::magicLink($it['url']),
627 'madeby_addr' => $it['addr'],
628 'contact_id' => $it['contact-id'],
629 'photo' => ((x($it, 'fphoto')) ? ProxyUtils::proxifyUrl($it['fphoto'], false, ProxyUtils::SIZE_SMALL) : "images/person-175.jpg"),
630 'name' => $it['fname'],
631 'url' => $it['furl'],
632 'zrl' => Contact::magicLink($it['furl']),
633 'hidden' => $it['hidden'] == 1,
634 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
635 'knowyou' => $knowyou,
636 'note' => $it['note'],
637 'request' => $it['frequest'] . '?addr=' . $return_addr,
640 // Normal connection requests
642 $it = $this->getMissingIntroData($it);
644 // Don't show these data until you are connected. Diaspora is doing the same.
645 if ($it['gnetwork'] === Protocol::DIASPORA) {
646 $it['glocation'] = "";
651 'label' => (($it['network'] !== Protocol::OSTATUS) ? 'friend_request' : 'follower'),
652 'notify_type' => (($it['network'] !== Protocol::OSTATUS) ? L10n::t('Friend/Connect Request') : L10n::t('New Follower')),
653 'dfrn_id' => $it['issued-id'],
654 'uid' => $_SESSION['uid'],
655 'intro_id' => $it['intro_id'],
656 'contact_id' => $it['contact-id'],
657 'photo' => ((x($it, 'photo')) ? ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_SMALL) : "images/person-175.jpg"),
658 'name' => $it['name'],
659 'location' => BBCode::convert($it['glocation'], false),
660 'about' => BBCode::convert($it['gabout'], false),
661 'keywords' => $it['gkeywords'],
662 'gender' => $it['ggender'],
663 'hidden' => $it['hidden'] == 1,
664 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
666 'zrl' => Contact::magicLink($it['url']),
667 'addr' => $it['gaddr'],
668 'network' => $it['gnetwork'],
669 'knowyou' => $it['knowyou'],
670 'note' => $it['note'],
681 * @brief Check for missing contact data and try to fetch the data from
684 * @param array $arr The input array with the intro data
686 * @return array The array with the intro data
688 private function getMissingIntroData($arr)
690 // If the network and the addr isn't available from the gcontact
691 // table entry, take the one of the contact table entry
692 if ($arr['gnetwork'] == "") {
693 $arr['gnetwork'] = $arr['network'];
695 if ($arr['gaddr'] == "") {
696 $arr['gaddr'] = $arr['addr'];
699 // If the network and addr is still not available
700 // get the missing data data from other sources
701 if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
702 $ret = Contact::getDetailsByURL($arr['url']);
704 if ($arr['gnetwork'] == "" && $ret['network'] != "") {
705 $arr['gnetwork'] = $ret['network'];
707 if ($arr['gaddr'] == "" && $ret['addr'] != "") {
708 $arr['gaddr'] = $ret['addr'];