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\Temporal;
17 use Friendica\Util\XML;
19 require_once 'include/dba.php';
22 * @brief Methods for read and write notifications from/to database
23 * or for formatting notifications
25 class NotificationsManager extends BaseObject
28 * @brief set some extra note properties
30 * @param array $notes array of note arrays from db
31 * @return array Copy of input array with added properties
33 * Set some extra properties to note array from db:
34 * - timestamp as int in default TZ
35 * - date_rel : relative date string
36 * - msg_html: message as html string
37 * - msg_plain: message as plain text string
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 string $order optional Space separated list of column to sort by.
59 * Prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
60 * @param string $limit optional Query limits
62 * @return array of results or false on errors
64 public function getAll($filter = [], $order = "-date", $limit = "")
68 foreach ($filter as $column => $value) {
69 $filter_str[] = sprintf("`%s` = '%s'", $column, DBA::escape($value));
71 if (count($filter_str) > 0) {
72 $filter_sql = "AND " . implode(" AND ", $filter_str);
75 $aOrder = explode(" ", $order);
77 foreach ($aOrder as $o) {
87 $asOrder[] = "$o $dir";
89 $order_sql = implode(", ", $asOrder);
92 $limit = " LIMIT " . $limit;
95 "SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
99 if (DBA::isResult($r)) {
100 return $this->_set_extra($r);
107 * @brief Get one note for local_user() by $id value
109 * @param int $id identity
110 * @return array note values or null if not found
112 public function getByID($id)
115 "SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
119 if (DBA::isResult($r)) {
120 return $this->_set_extra($r)[0];
126 * @brief set seen state of $note of local_user()
128 * @param array $note note array
129 * @param bool $seen optional true or false, default true
130 * @return bool true on success, false on errors
132 public function setSeen($note, $seen = true)
135 "UPDATE `notify` SET `seen` = %d WHERE (`link` = '%s' OR (`parent` != 0 AND `parent` = %d AND `otype` = '%s')) AND `uid` = %d",
137 DBA::escape($note['link']),
138 intval($note['parent']),
139 DBA::escape($note['otype']),
145 * @brief set seen state of all notifications of local_user()
147 * @param bool $seen optional true or false. default true
148 * @return bool true on success, false on error
150 public function setAllSeen($seen = true)
153 "UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
160 * @brief List of pages for the Notifications TabBar
162 * @return array with with notifications TabBar data
164 public function getTabs()
168 'label' => L10n::t('System'),
169 'url' => 'notifications/system',
170 'sel' => ((self::getApp()->argv[1] == 'system') ? 'active' : ''),
171 'id' => 'system-tab',
175 'label' => L10n::t('Network'),
176 'url' => 'notifications/network',
177 'sel' => ((self::getApp()->argv[1] == 'network') ? 'active' : ''),
178 'id' => 'network-tab',
182 'label' => L10n::t('Personal'),
183 'url' => 'notifications/personal',
184 'sel' => ((self::getApp()->argv[1] == 'personal') ? 'active' : ''),
185 'id' => 'personal-tab',
189 'label' => L10n::t('Home'),
190 'url' => 'notifications/home',
191 'sel' => ((self::getApp()->argv[1] == 'home') ? 'active' : ''),
196 'label' => L10n::t('Introductions'),
197 'url' => 'notifications/intros',
198 'sel' => ((self::getApp()->argv[1] == 'intros') ? 'active' : ''),
208 * @brief Format the notification query in an usable array
210 * @param array $notifs The array from the db query
211 * @param string $ident The notifications identifier (e.g. network)
213 * string 'label' => The type of the notification
214 * string 'link' => URL to the source
215 * string 'image' => The avatar image
216 * string 'url' => The profile url of the contact
217 * string 'text' => The notification text
218 * string 'when' => The date of the notification
219 * string 'ago' => T relative date of the notification
220 * bool 'seen' => Is the notification marked as "seen"
222 private function formatNotifs(array $notifs, $ident = "")
227 if (DBA::isResult($notifs)) {
228 foreach ($notifs as $it) {
229 // Because we use different db tables for the notification query
230 // we have sometimes $it['unseen'] and sometimes $it['seen].
231 // So we will have to transform $it['unseen']
232 if (array_key_exists('unseen', $it)) {
233 $it['seen'] = ($it['unseen'] > 0 ? false : true);
236 // For feed items we use the user's contact, since the avatar is mostly self choosen.
237 if (!empty($it['network']) && $it['network'] == NETWORK_FEED) {
238 $it['author-avatar'] = $it['contact-avatar'];
241 // Depending on the identifier of the notification we need to use different defaults
244 $default_item_label = 'notify';
245 $default_item_link = System::baseUrl(true) . '/notify/view/' . $it['id'];
246 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
247 $default_item_url = $it['url'];
248 $default_item_text = strip_tags(BBCode::convert($it['msg']));
249 $default_item_when = DateTimeFormat::local($it['date'], 'r');
250 $default_item_ago = Temporal::getRelativeDate($it['date']);
254 $default_item_label = 'comment';
255 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
256 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
257 $default_item_url = $it['author-link'];
258 $default_item_text = L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']);
259 $default_item_when = DateTimeFormat::local($it['created'], 'r');
260 $default_item_ago = Temporal::getRelativeDate($it['created']);
264 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
265 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
266 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
267 $default_item_url = $it['author-link'];
268 $default_item_text = (($it['id'] == $it['parent'])
269 ? L10n::t("%s created a new post", $it['author-name'])
270 : L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']));
271 $default_item_when = DateTimeFormat::local($it['created'], 'r');
272 $default_item_ago = Temporal::getRelativeDate($it['created']);
275 // Transform the different types of notification in an usable array
276 switch ($it['verb']) {
280 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
281 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
282 'url' => $it['author-link'],
283 'text' => L10n::t("%s liked %s's post", $it['author-name'], $it['parent-author-name']),
284 'when' => $default_item_when,
285 'ago' => $default_item_ago,
286 'seen' => $it['seen']
290 case ACTIVITY_DISLIKE:
292 'label' => 'dislike',
293 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
294 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
295 'url' => $it['author-link'],
296 'text' => L10n::t("%s disliked %s's post", $it['author-name'], $it['parent-author-name']),
297 'when' => $default_item_when,
298 'ago' => $default_item_ago,
299 'seen' => $it['seen']
303 case ACTIVITY_ATTEND:
306 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
307 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
308 'url' => $it['author-link'],
309 'text' => L10n::t("%s is attending %s's event", $it['author-name'], $it['parent-author-name']),
310 'when' => $default_item_when,
311 'ago' => $default_item_ago,
312 'seen' => $it['seen']
316 case ACTIVITY_ATTENDNO:
318 'label' => 'attendno',
319 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
320 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
321 'url' => $it['author-link'],
322 'text' => L10n::t("%s is not attending %s's event", $it['author-name'], $it['parent-author-name']),
323 'when' => $default_item_when,
324 'ago' => $default_item_ago,
325 'seen' => $it['seen']
329 case ACTIVITY_ATTENDMAYBE:
331 'label' => 'attendmaybe',
332 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
333 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
334 'url' => $it['author-link'],
335 'text' => L10n::t("%s may attend %s's event", $it['author-name'], $it['parent-author-name']),
336 'when' => $default_item_when,
337 'ago' => $default_item_ago,
338 'seen' => $it['seen']
342 case ACTIVITY_FRIEND:
343 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
344 $obj = XML::parseString($xmlhead . $it['object']);
345 $it['fname'] = $obj->title;
349 'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
350 'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
351 'url' => $it['author-link'],
352 'text' => L10n::t("%s is now friends with %s", $it['author-name'], $it['fname']),
353 'when' => $default_item_when,
354 'ago' => $default_item_ago,
355 'seen' => $it['seen']
361 'label' => $default_item_label,
362 'link' => $default_item_link,
363 'image' => $default_item_image,
364 'url' => $default_item_url,
365 'text' => $default_item_text,
366 'when' => $default_item_when,
367 'ago' => $default_item_ago,
368 'seen' => $it['seen']
380 * @brief Get network notifications
382 * @param int|string $seen If 0 only include notifications into the query
383 * which aren't marked as "seen"
384 * @param int $start Start the query at this point
385 * @param int $limit Maximum number of query results
388 * string 'ident' => Notification identifier
389 * array 'notifications' => Network notifications
391 public function networkNotifs($seen = 0, $start = 0, $limit = 80)
396 $condition = ['wall' => false, 'uid' => local_user()];
399 $condition['unseen'] = true;
402 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
403 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
404 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
406 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
408 if (DBA::isResult($items)) {
409 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
413 'notifications' => $notifs,
421 * @brief Get system notifications
423 * @param int|string $seen If 0 only include notifications into the query
424 * which aren't marked as "seen"
425 * @param int $start Start the query at this point
426 * @param int $limit Maximum number of query results
429 * string 'ident' => Notification identifier
430 * array 'notifications' => System notifications
432 public function systemNotifs($seen = 0, $start = 0, $limit = 80)
439 $sql_seen = " AND NOT `seen` ";
443 "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen`, `verb` FROM `notify`
444 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
445 intval(local_user()),
450 if (DBA::isResult($r)) {
451 $notifs = $this->formatNotifs($r, $ident);
455 'notifications' => $notifs,
463 * @brief Get personal notifications
465 * @param int|string $seen If 0 only include notifications into the query
466 * which aren't marked as "seen"
467 * @param int $start Start the query at this point
468 * @param int $limit Maximum number of query results
471 * string 'ident' => Notification identifier
472 * array 'notifications' => Personal notifications
474 public function personalNotifs($seen = 0, $start = 0, $limit = 80)
479 $myurl = str_replace('http://', '', self::getApp()->contact['nurl']);
480 $diasp_url = str_replace('/profile/', '/u/', $myurl);
482 $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)",
483 local_user(), public_contact(), $myurl . '\\]', $diasp_url . '\\]'];
486 $condition[0] .= " AND `unseen`";
489 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
490 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
491 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
493 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
495 if (DBA::isResult($items)) {
496 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
500 'notifications' => $notifs,
508 * @brief Get home notifications
510 * @param int|string $seen If 0 only include notifications into the query
511 * which aren't marked as "seen"
512 * @param int $start Start the query at this point
513 * @param int $limit Maximum number of query results
516 * string 'ident' => Notification identifier
517 * array 'notifications' => Home notifications
519 public function homeNotifs($seen = 0, $start = 0, $limit = 80)
524 $condition = ['wall' => true, 'uid' => local_user()];
527 $condition['unseen'] = true;
530 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
531 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
532 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
533 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
535 if (DBA::isResult($items)) {
536 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
540 'notifications' => $notifs,
548 * @brief Get introductions
550 * @param bool $all If false only include introductions into the query
551 * which aren't marked as ignored
552 * @param int $start Start the query at this point
553 * @param int $limit Maximum number of query results
556 * string 'ident' => Notification identifier
557 * array 'notifications' => Introductions
559 public function introNotifs($all = false, $start = 0, $limit = 80)
561 $ident = 'introductions';
566 $sql_extra = " AND `ignore` = 0 ";
569 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
571 "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
572 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`,
573 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
574 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
575 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
576 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
578 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
579 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
580 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
581 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
583 intval($_SESSION['uid']),
587 if (DBA::isResult($r)) {
588 $notifs = $this->formatIntros($r);
593 'notifications' => $notifs,
600 * @brief Format the notification query in an usable array
602 * @param array $intros The array from the db query
603 * @return array with the introductions
605 private function formatIntros($intros)
609 foreach ($intros as $it) {
610 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
611 // We have to distinguish between these two because they use different data.
612 // Contact suggestions
614 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->get_hostname() . ((self::getApp()->urlpath) ? '/' . self::getApp()->urlpath : ''));
617 'label' => 'friend_suggestion',
618 'notify_type' => L10n::t('Friend Suggestion'),
619 'intro_id' => $it['intro_id'],
620 'madeby' => $it['name'],
621 'madeby_url' => $it['url'],
622 'madeby_zrl' => Contact::magicLink($it['url']),
623 'madeby_addr' => $it['addr'],
624 'contact_id' => $it['contact-id'],
625 'photo' => ((x($it, 'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
626 'name' => $it['fname'],
627 'url' => $it['furl'],
628 'zrl' => Contact::magicLink($it['furl']),
629 'hidden' => $it['hidden'] == 1,
630 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
631 'knowyou' => $knowyou,
632 'note' => $it['note'],
633 'request' => $it['frequest'] . '?addr=' . $return_addr,
636 // Normal connection requests
638 $it = $this->getMissingIntroData($it);
640 // Don't show these data until you are connected. Diaspora is doing the same.
641 if ($it['gnetwork'] === NETWORK_DIASPORA) {
642 $it['glocation'] = "";
647 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
648 'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? L10n::t('Friend/Connect Request') : L10n::t('New Follower')),
649 'dfrn_id' => $it['issued-id'],
650 'uid' => $_SESSION['uid'],
651 'intro_id' => $it['intro_id'],
652 'contact_id' => $it['contact-id'],
653 'photo' => ((x($it, 'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
654 'name' => $it['name'],
655 'location' => BBCode::convert($it['glocation'], false),
656 'about' => BBCode::convert($it['gabout'], false),
657 'keywords' => $it['gkeywords'],
658 'gender' => $it['ggender'],
659 'hidden' => $it['hidden'] == 1,
660 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
662 'zrl' => Contact::magicLink($it['url']),
663 'addr' => $it['gaddr'],
664 'network' => $it['gnetwork'],
665 'knowyou' => $it['knowyou'],
666 'note' => $it['note'],
677 * @brief Check for missing contact data and try to fetch the data from
680 * @param array $arr The input array with the intro data
682 * @return array The array with the intro data
684 private function getMissingIntroData($arr)
686 // If the network and the addr isn't available from the gcontact
687 // table entry, take the one of the contact table entry
688 if ($arr['gnetwork'] == "") {
689 $arr['gnetwork'] = $arr['network'];
691 if ($arr['gaddr'] == "") {
692 $arr['gaddr'] = $arr['addr'];
695 // If the network and addr is still not available
696 // get the missing data data from other sources
697 if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
698 $ret = Contact::getDetailsByURL($arr['url']);
700 if ($arr['gnetwork'] == "" && $ret['network'] != "") {
701 $arr['gnetwork'] = $ret['network'];
703 if ($arr['gaddr'] == "" && $ret['addr'] != "") {
704 $arr['gaddr'] = $ret['addr'];