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\DBM;
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, dbesc($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 (DBM::is_result($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 (DBM::is_result($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 dbesc($note['link']),
138 intval($note['parent']),
139 dbesc($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 (DBM::is_result($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]];
405 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
407 if (DBM::is_result($items)) {
408 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
412 'notifications' => $notifs,
420 * @brief Get system notifications
422 * @param int|string $seen If 0 only include notifications into the query
423 * which aren't marked as "seen"
424 * @param int $start Start the query at this point
425 * @param int $limit Maximum number of query results
428 * string 'ident' => Notification identifier
429 * array 'notifications' => System notifications
431 public function systemNotifs($seen = 0, $start = 0, $limit = 80)
438 $sql_seen = " AND NOT `seen` ";
442 "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
443 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
444 intval(local_user()),
448 if (DBM::is_result($r)) {
449 $notifs = $this->formatNotifs($r, $ident);
453 'notifications' => $notifs,
461 * @brief Get personal notifications
463 * @param int|string $seen If 0 only include notifications into the query
464 * which aren't marked as "seen"
465 * @param int $start Start the query at this point
466 * @param int $limit Maximum number of query results
469 * string 'ident' => Notification identifier
470 * array 'notifications' => Personal notifications
472 public function personalNotifs($seen = 0, $start = 0, $limit = 80)
477 $myurl = str_replace('http://', '', self::getApp()->contact['nurl']);
478 $diasp_url = str_replace('/profile/', '/u/', $myurl);
480 $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)",
481 local_user(), public_contact(), $myurl . '\\]', $diasp_url . '\\]'];
484 $condition[0] .= " AND `unseen`";
487 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
488 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
489 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
490 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
492 if (DBM::is_result($items)) {
493 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
497 'notifications' => $notifs,
505 * @brief Get home notifications
507 * @param int|string $seen If 0 only include notifications into the query
508 * which aren't marked as "seen"
509 * @param int $start Start the query at this point
510 * @param int $limit Maximum number of query results
513 * string 'ident' => Notification identifier
514 * array 'notifications' => Home notifications
516 public function homeNotifs($seen = 0, $start = 0, $limit = 80)
521 $condition = ['wall' => true, 'uid' => local_user()];
524 $condition['unseen'] = true;
527 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
528 'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
529 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
530 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
532 if (DBM::is_result($items)) {
533 $notifs = $this->formatNotifs(Item::inArray($items), $ident);
537 'notifications' => $notifs,
545 * @brief Get introductions
547 * @param bool $all If false only include introductions into the query
548 * which aren't marked as ignored
549 * @param int $start Start the query at this point
550 * @param int $limit Maximum number of query results
553 * string 'ident' => Notification identifier
554 * array 'notifications' => Introductions
556 public function introNotifs($all = false, $start = 0, $limit = 80)
558 $ident = 'introductions';
563 $sql_extra = " AND `ignore` = 0 ";
566 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
568 "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
569 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`,
570 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
571 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
572 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
573 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
575 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
576 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
577 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
578 WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
580 intval($_SESSION['uid']),
584 if (DBM::is_result($r)) {
585 $notifs = $this->formatIntros($r);
590 'notifications' => $notifs,
597 * @brief Format the notification query in an usable array
599 * @param array $intros The array from the db query
600 * @return array with the introductions
602 private function formatIntros($intros)
606 foreach ($intros as $it) {
607 // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
608 // We have to distinguish between these two because they use different data.
609 // Contact suggestions
611 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->get_hostname() . ((self::getApp()->urlpath) ? '/' . self::getApp()->urlpath : ''));
614 'label' => 'friend_suggestion',
615 'notify_type' => L10n::t('Friend Suggestion'),
616 'intro_id' => $it['intro_id'],
617 'madeby' => $it['name'],
618 'madeby_url' => $it['url'],
619 'madeby_zrl' => Contact::magicLink($it['url']),
620 'madeby_addr' => $it['addr'],
621 'contact_id' => $it['contact-id'],
622 'photo' => ((x($it, 'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
623 'name' => $it['fname'],
624 'url' => $it['furl'],
625 'zrl' => Contact::magicLink($it['furl']),
626 'hidden' => $it['hidden'] == 1,
627 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
628 'knowyou' => $knowyou,
629 'note' => $it['note'],
630 'request' => $it['frequest'] . '?addr=' . $return_addr,
633 // Normal connection requests
635 $it = $this->getMissingIntroData($it);
637 // Don't show these data until you are connected. Diaspora is doing the same.
638 if ($it['gnetwork'] === NETWORK_DIASPORA) {
639 $it['glocation'] = "";
644 'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
645 'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? L10n::t('Friend/Connect Request') : L10n::t('New Follower')),
646 'dfrn_id' => $it['issued-id'],
647 'uid' => $_SESSION['uid'],
648 'intro_id' => $it['intro_id'],
649 'contact_id' => $it['contact-id'],
650 'photo' => ((x($it, 'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
651 'name' => $it['name'],
652 'location' => BBCode::convert($it['glocation'], false),
653 'about' => BBCode::convert($it['gabout'], false),
654 'keywords' => $it['gkeywords'],
655 'gender' => $it['ggender'],
656 'hidden' => $it['hidden'] == 1,
657 'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
659 'zrl' => Contact::magicLink($it['url']),
660 'addr' => $it['gaddr'],
661 'network' => $it['gnetwork'],
662 'knowyou' => $it['knowyou'],
663 'note' => $it['note'],
674 * @brief Check for missing contact data and try to fetch the data from
677 * @param array $arr The input array with the intro data
679 * @return array The array with the intro data
681 private function getMissingIntroData($arr)
683 // If the network and the addr isn't available from the gcontact
684 // table entry, take the one of the contact table entry
685 if ($arr['gnetwork'] == "") {
686 $arr['gnetwork'] = $arr['network'];
688 if ($arr['gaddr'] == "") {
689 $arr['gaddr'] = $arr['addr'];
692 // If the network and addr is still not available
693 // get the missing data data from other sources
694 if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
695 $ret = Contact::getDetailsByURL($arr['url']);
697 if ($arr['gnetwork'] == "" && $ret['network'] != "") {
698 $arr['gnetwork'] = $ret['network'];
700 if ($arr['gaddr'] == "" && $ret['addr'] != "") {
701 $arr['gaddr'] = $ret['addr'];