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\L10n;
13 use Friendica\Core\PConfig;
14 use Friendica\Core\System;
15 use Friendica\Database\DBM;
16 use Friendica\Model\Contact;
17 use Friendica\Model\Profile;
18 use Friendica\Model\Item;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Temporal;
21 use Friendica\Util\XML;
24 require_once 'include/dba.php';
27 * @brief Methods for read and write notifications from/to database
28 * or for formatting notifications
30 class NotificationsManager extends BaseObject
33 * @brief set some extra note properties
35 * @param array $notes array of note arrays from db
36 * @return array Copy of input array with added properties
38 * Set some extra properties to note array from db:
39 * - timestamp as int in default TZ
40 * - date_rel : relative date string
41 * - msg_html: message as html string
42 * - msg_plain: message as plain text string
44 private function _set_extra($notes)
47 foreach ($notes as $n) {
48 $local_time = DateTimeFormat::local($n['date']);
49 $n['timestamp'] = strtotime($local_time);
50 $n['date_rel'] = Temporal::getRelativeDate($n['date']);
51 $n['msg_html'] = BBCode::convert($n['msg'], false);
52 $n['msg_plain'] = explode("\n", trim(HTML::toPlaintext($n['msg_html'], 0)))[0];
60 * @brief Get all notifications for local_user()
62 * @param array $filter optional Array "column name"=>value: filter query by columns values
63 * @param string $order optional Space separated list of column to sort by.
64 * Prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
65 * @param string $limit optional Query limits
67 * @return array of results or false on errors
69 public function getAll($filter = [], $order = "-date", $limit = "")
73 foreach ($filter as $column => $value) {
74 $filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
76 if (count($filter_str) > 0) {
77 $filter_sql = "AND " . implode(" AND ", $filter_str);
80 $aOrder = explode(" ", $order);
82 foreach ($aOrder as $o) {
92 $asOrder[] = "$o $dir";
94 $order_sql = implode(", ", $asOrder);
97 $limit = " LIMIT " . $limit;
100 "SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
104 if (DBM::is_result($r)) {
105 return $this->_set_extra($r);
112 * @brief Get one note for local_user() by $id value
114 * @param int $id identity
115 * @return array note values or null if not found
117 public function getByID($id)
120 "SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
124 if (DBM::is_result($r)) {
125 return $this->_set_extra($r)[0];
131 * @brief set seen state of $note of local_user()
133 * @param array $note note array
134 * @param bool $seen optional true or false, default true
135 * @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 dbesc($note['link']),
143 intval($note['parent']),
144 dbesc($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
155 public function setAllSeen($seen = true)
158 "UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
165 * @brief List of pages for the Notifications TabBar
167 * @return array with with notifications TabBar data
169 public function getTabs()
173 'label' => L10n::t('System'),
174 'url' => 'notifications/system',
175 'sel' => ((self::getApp()->argv[1] == 'system') ? 'active' : ''),
176 'id' => 'system-tab',
180 'label' => L10n::t('Network'),
181 'url' => 'notifications/network',
182 'sel' => ((self::getApp()->argv[1] == 'network') ? 'active' : ''),
183 'id' => 'network-tab',
187 'label' => L10n::t('Personal'),
188 'url' => 'notifications/personal',
189 'sel' => ((self::getApp()->argv[1] == 'personal') ? 'active' : ''),
190 'id' => 'personal-tab',
194 'label' => L10n::t('Home'),
195 'url' => 'notifications/home',
196 'sel' => ((self::getApp()->argv[1] == 'home') ? 'active' : ''),
201 'label' => L10n::t('Introductions'),
202 'url' => 'notifications/intros',
203 'sel' => ((self::getApp()->argv[1] == '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($notifs, $ident = "")
232 if (DBM::is_result($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'] == NETWORK_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 = proxy_url($it['photo'], false, PROXY_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 = proxy_url($it['author-avatar'], false, PROXY_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 = proxy_url($it['author-avatar'], false, PROXY_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' => proxy_url($it['author-avatar'], false, PROXY_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' => proxy_url($it['author-avatar'], false, PROXY_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' => proxy_url($it['author-avatar'], false, PROXY_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' => proxy_url($it['author-avatar'], false, PROXY_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' => proxy_url($it['author-avatar'], false, PROXY_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 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
349 $obj = XML::parseString($xmlhead . $it['object']);
350 $it['fname'] = $obj->title;
354 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
355 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
356 'url' => $it['author-link'],
357 'text' => L10n::t("%s is now friends with %s", $it['author-name'], $it['fname']),
358 'when' => $default_item_when,
359 'ago' => $default_item_ago,
360 'seen' => $it['seen']
366 'label' => $default_item_label,
367 'link' => $default_item_link,
368 'image' => $default_item_image,
369 'url' => $default_item_url,
370 'text' => $default_item_text,
371 'when' => $default_item_when,
372 'ago' => $default_item_ago,
373 'seen' => $it['seen']
385 * @brief Get network notifications
387 * @param int|string $seen If 0 only include notifications into the query
388 * which aren't marked as "seen"
389 * @param int $start Start the query at this point
390 * @param int $limit Maximum number of query results
393 * string 'ident' => Notification identifier
394 * array 'notifications' => Network notifications
396 public function networkNotifs($seen = 0, $start = 0, $limit = 80)
401 $condition = ['wall' => false, 'uid' => local_user()];
404 $condition['unseen'] = true;
407 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
408 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
409 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
410 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
412 if (DBM::is_result($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` FROM `notify`
448 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
449 intval(local_user()),
453 if (DBM::is_result($r)) {
454 $notifs = $this->formatNotifs($r, $ident);
458 'notifications' => $notifs,
466 * @brief Get personal notifications
468 * @param int|string $seen If 0 only include notifications into the query
469 * which aren't marked as "seen"
470 * @param int $start Start the query at this point
471 * @param int $limit Maximum number of query results
474 * string 'ident' => Notification identifier
475 * array 'notifications' => Personal notifications
477 public function personalNotifs($seen = 0, $start = 0, $limit = 80)
482 $myurl = str_replace('http://', '', self::getApp()->contact['nurl']);
483 $diasp_url = str_replace('/profile/', '/u/', $myurl);
485 $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)",
486 local_user(), public_contact(), $myurl . '\\]', $diasp_url . '\\]'];
489 $condition[0] .= " AND `unseen`";
492 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
493 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
494 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
495 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
497 if (DBM::is_result($items)) {
498 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
502 'notifications' => $notifs,
510 * @brief Get home notifications
512 * @param int|string $seen If 0 only include notifications into the query
513 * which aren't marked as "seen"
514 * @param int $start Start the query at this point
515 * @param int $limit Maximum number of query results
518 * string 'ident' => Notification identifier
519 * array 'notifications' => Home notifications
521 public function homeNotifs($seen = 0, $start = 0, $limit = 80)
526 $condition = ['wall' => true, 'uid' => local_user()];
529 $condition['unseen'] = true;
532 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
533 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
534 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
535 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
537 if (DBM::is_result($items)) {
538 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
542 'notifications' => $notifs,
550 * @brief Get introductions
552 * @param bool $all If false only include introductions into the query
553 * which aren't marked as ignored
554 * @param int $start Start the query at this point
555 * @param int $limit Maximum number of query results
558 * string 'ident' => Notification identifier
559 * array 'notifications' => Introductions
561 public function introNotifs($all = false, $start = 0, $limit = 80)
563 $ident = 'introductions';
568 $sql_extra = " AND `ignore` = 0 ";
571 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
573 "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
574 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`,
575 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
576 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
577 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
578 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
580 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
581 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
582 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
583 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
585 intval($_SESSION['uid']),
589 if (DBM::is_result($r)) {
590 $notifs = $this->formatIntros($r);
595 'notifications' => $notifs,
602 * @brief Format the notification query in an usable array
604 * @param array $intros The array from the db query
605 * @return array with the introductions
607 private function formatIntros($intros)
611 foreach ($intros as $it) {
612 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
613 // We have to distinguish between these two because they use different data.
614 // Contact suggestions
616 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->get_hostname() . ((self::getApp()->urlpath) ? '/' . self::getApp()->urlpath : ''));
619 'label' => 'friend_suggestion',
620 'notify_type' => L10n::t('Friend Suggestion'),
621 'intro_id' => $it['intro_id'],
622 'madeby' => $it['name'],
623 'madeby_url' => $it['url'],
624 'madeby_zrl' => Contact::magicLink($it['url']),
625 'madeby_addr' => $it['addr'],
626 'contact_id' => $it['contact-id'],
627 'photo' => ((x($it, 'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
628 'name' => $it['fname'],
629 'url' => $it['furl'],
630 'zrl' => Contact::magicLink($it['furl']),
631 'hidden' => $it['hidden'] == 1,
632 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
633 'knowyou' => $knowyou,
634 'note' => $it['note'],
635 'request' => $it['frequest'] . '?addr=' . $return_addr,
638 // Normal connection requests
640 $it = $this->getMissingIntroData($it);
642 // Don't show these data until you are connected. Diaspora is doing the same.
643 if ($it['gnetwork'] === NETWORK_DIASPORA) {
644 $it['glocation'] = "";
649 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
650 'notify_type' => (($it['network'] !== NETWORK_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' => ((x($it, 'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.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
686 private function getMissingIntroData($arr)
688 // If the network and the addr isn't available from the gcontact
689 // table entry, take the one of the contact table entry
690 if ($arr['gnetwork'] == "") {
691 $arr['gnetwork'] = $arr['network'];
693 if ($arr['gaddr'] == "") {
694 $arr['gaddr'] = $arr['addr'];
697 // If the network and addr is still not available
698 // get the missing data data from other sources
699 if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
700 $ret = Contact::getDetailsByURL($arr['url']);
702 if ($arr['gnetwork'] == "" && $ret['network'] != "") {
703 $arr['gnetwork'] = $ret['network'];
705 if ($arr['gaddr'] == "" && $ret['addr'] != "") {
706 $arr['gaddr'] = $ret['addr'];