]> git.mxchange.org Git - friendica.git/blob - src/Core/NotificationsManager.php
Use short form array syntax everywhere
[friendica.git] / src / Core / NotificationsManager.php
1 <?php
2
3 /**
4  * @file src/Core/NotificationsManager.php
5  * @brief Methods for read and write notifications from/to database
6  *  or for formatting notifications
7  */
8
9 namespace Friendica\Core;
10
11 use Friendica\BaseObject;
12 use Friendica\Core\PConfig;
13 use Friendica\Core\System;
14 use Friendica\Database\DBM;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Profile;
17
18 require_once 'include/dba.php';
19 require_once 'include/html2plain.php';
20 require_once 'include/datetime.php';
21 require_once 'include/bbcode.php';
22
23 /**
24  * @brief Methods for read and write notifications from/to database
25  *  or for formatting notifications
26  */
27 class NotificationsManager extends BaseObject
28 {
29         /**
30          * @brief set some extra note properties
31          *
32          * @param array $notes array of note arrays from db
33          * @return array Copy of input array with added properties
34          *
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
40          */
41         private function _set_extra($notes)
42         {
43                 $rets = [];
44                 foreach ($notes as $n) {
45                         $local_time = datetime_convert('UTC', date_default_timezone_get(), $n['date']);
46                         $n['timestamp'] = strtotime($local_time);
47                         $n['date_rel'] = relative_date($n['date']);
48                         $n['msg_html'] = bbcode($n['msg'], false, false, false, false);
49                         $n['msg_plain'] = explode("\n", trim(html2plain($n['msg_html'], 0)))[0];
50
51                         $rets[] = $n;
52                 }
53                 return $rets;
54         }
55
56         /**
57          * @brief Get all notifications for local_user()
58          *
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
63          *
64          * @return array of results or false on errors
65          */
66         public function getAll($filter = [], $order = "-date", $limit = "")
67         {
68                 $filter_str = [];
69                 $filter_sql = "";
70                 foreach ($filter as $column => $value) {
71                         $filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
72                 }
73                 if (count($filter_str) > 0) {
74                         $filter_sql = "AND " . implode(" AND ", $filter_str);
75                 }
76
77                 $aOrder = explode(" ", $order);
78                 $asOrder = [];
79                 foreach ($aOrder as $o) {
80                         $dir = "asc";
81                         if ($o[0] === "-") {
82                                 $dir = "desc";
83                                 $o = substr($o, 1);
84                         }
85                         if ($o[0] === "+") {
86                                 $dir = "asc";
87                                 $o = substr($o, 1);
88                         }
89                         $asOrder[] = "$o $dir";
90                 }
91                 $order_sql = implode(", ", $asOrder);
92
93                 if ($limit != "") {
94                         $limit = " LIMIT " . $limit;
95                 }
96                 $r = q(
97                         "SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
98                         intval(local_user())
99                 );
100
101                 if (DBM::is_result($r)) {
102                         return $this->_set_extra($r);
103                 }
104
105                 return false;
106         }
107
108         /**
109          * @brief Get one note for local_user() by $id value
110          *
111          * @param int $id identity
112          * @return array note values or null if not found
113          */
114         public function getByID($id)
115         {
116                 $r = q(
117                         "SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
118                         intval($id),
119                         intval(local_user())
120                 );
121                 if (DBM::is_result($r)) {
122                         return $this->_set_extra($r)[0];
123                 }
124                 return null;
125         }
126
127         /**
128          * @brief set seen state of $note of local_user()
129          *
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
133          */
134         public function setSeen($note, $seen = true)
135         {
136                 return q(
137                         "UPDATE `notify` SET `seen` = %d WHERE ( `link` = '%s' OR ( `parent` != 0 AND `parent` = %d AND `otype` = '%s' )) AND `uid` = %d",
138                         intval($seen),
139                         dbesc($note['link']),
140                         intval($note['parent']),
141                         dbesc($note['otype']),
142                         intval(local_user())
143                 );
144         }
145
146         /**
147          * @brief set seen state of all notifications of local_user()
148          *
149          * @param bool $seen optional true or false. default true
150          * @return bool true on success, false on error
151          */
152         public function setAllSeen($seen = true)
153         {
154                 return q(
155                         "UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
156                         intval($seen),
157                         intval(local_user())
158                 );
159         }
160
161         /**
162          * @brief List of pages for the Notifications TabBar
163          *
164          * @return array with with notifications TabBar data
165          */
166         public function getTabs()
167         {
168                 $tabs = [
169                         [
170                                 'label' => t('System'),
171                                 'url'   => 'notifications/system',
172                                 'sel'   => ((self::getApp()->argv[1] == 'system') ? 'active' : ''),
173                                 'id'    => 'system-tab',
174                                 'accesskey' => 'y',
175                         ],
176                         [
177                                 'label' => t('Network'),
178                                 'url'   => 'notifications/network',
179                                 'sel'   => ((self::getApp()->argv[1] == 'network') ? 'active' : ''),
180                                 'id'    => 'network-tab',
181                                 'accesskey' => 'w',
182                         ],
183                         [
184                                 'label' => t('Personal'),
185                                 'url'   => 'notifications/personal',
186                                 'sel'   => ((self::getApp()->argv[1] == 'personal') ? 'active' : ''),
187                                 'id'    => 'personal-tab',
188                                 'accesskey' => 'r',
189                         ],
190                         [
191                                 'label' => t('Home'),
192                                 'url'   => 'notifications/home',
193                                 'sel'   => ((self::getApp()->argv[1] == 'home') ? 'active' : ''),
194                                 'id'    => 'home-tab',
195                                 'accesskey' => 'h',
196                         ],
197                         [
198                                 'label' => t('Introductions'),
199                                 'url'   => 'notifications/intros',
200                                 'sel'   => ((self::getApp()->argv[1] == 'intros') ? 'active' : ''),
201                                 'id'    => 'intro-tab',
202                                 'accesskey' => 'i',
203                         ],
204                 ];
205
206                 return $tabs;
207         }
208
209         /**
210          * @brief Format the notification query in an usable array
211          *
212          * @param array  $notifs The array from the db query
213          * @param string $ident  The notifications identifier (e.g. network)
214          * @return array
215          *      string 'label' => The type of the notification
216          *      string 'link' => URL to the source
217          *      string 'image' => The avatar image
218          *      string 'url' => The profile url of the contact
219          *      string 'text' => The notification text
220          *      string 'when' => The date of the notification
221          *      string 'ago' => T relative date of the notification
222          *      bool 'seen' => Is the notification marked as "seen"
223          */
224         private function formatNotifs($notifs, $ident = "")
225         {
226                 $notif = [];
227                 $arr = [];
228
229                 if (DBM::is_result($notifs)) {
230                         foreach ($notifs as $it) {
231                                 // Because we use different db tables for the notification query
232                                 // we have sometimes $it['unseen'] and sometimes $it['seen].
233                                 // So we will have to transform $it['unseen']
234                                 if (array_key_exists('unseen', $it)) {
235                                         $it['seen'] = ($it['unseen'] > 0 ? false : true);
236                                 }
237
238                                 // Depending on the identifier of the notification we need to use different defaults
239                                 switch ($ident) {
240                                         case 'system':
241                                                 $default_item_label = 'notify';
242                                                 $default_item_link = System::baseUrl(true) . '/notify/view/' . $it['id'];
243                                                 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
244                                                 $default_item_url = $it['url'];
245                                                 $default_item_text = strip_tags(bbcode($it['msg']));
246                                                 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['date'], 'r');
247                                                 $default_item_ago = relative_date($it['date']);
248                                                 break;
249
250                                         case 'home':
251                                                 $default_item_label = 'comment';
252                                                 $default_item_link = System::baseUrl(true) . '/display/' . $it['pguid'];
253                                                 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
254                                                 $default_item_url = $it['author-link'];
255                                                 $default_item_text = sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']);
256                                                 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
257                                                 $default_item_ago = relative_date($it['created']);
258                                                 break;
259
260                                         default:
261                                                 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
262                                                 $default_item_link = System::baseUrl(true) . '/display/' . $it['pguid'];
263                                                 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
264                                                 $default_item_url = $it['author-link'];
265                                                 $default_item_text = (($it['id'] == $it['parent'])
266                                                                         ? sprintf(t("%s created a new post"), $it['author-name'])
267                                                                         : sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']));
268                                                 $default_item_when = datetime_convert('UTC', date_default_timezone_get(), $it['created'], 'r');
269                                                 $default_item_ago = relative_date($it['created']);
270                                 }
271
272                                 // Transform the different types of notification in an usable array
273                                 switch ($it['verb']) {
274                                         case ACTIVITY_LIKE:
275                                                 $notif = [
276                                                         'label' => 'like',
277                                                         'link' => System::baseUrl(true) . '/display/' . $it['pguid'],
278                                                         'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
279                                                         'url' => $it['author-link'],
280                                                         'text' => sprintf(t("%s liked %s's post"), $it['author-name'], $it['pname']),
281                                                         'when' => $default_item_when,
282                                                         'ago' => $default_item_ago,
283                                                         'seen' => $it['seen']
284                                                 ];
285                                                 break;
286
287                                         case ACTIVITY_DISLIKE:
288                                                 $notif = [
289                                                         'label' => 'dislike',
290                                                         'link' => System::baseUrl(true) . '/display/' . $it['pguid'],
291                                                         'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
292                                                         'url' => $it['author-link'],
293                                                         'text' => sprintf(t("%s disliked %s's post"), $it['author-name'], $it['pname']),
294                                                         'when' => $default_item_when,
295                                                         'ago' => $default_item_ago,
296                                                         'seen' => $it['seen']
297                                                 ];
298                                                 break;
299
300                                         case ACTIVITY_ATTEND:
301                                                 $notif = [
302                                                         'label' => 'attend',
303                                                         'link' => System::baseUrl(true) . '/display/' . $it['pguid'],
304                                                         'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
305                                                         'url' => $it['author-link'],
306                                                         'text' => sprintf(t("%s is attending %s's event"), $it['author-name'], $it['pname']),
307                                                         'when' => $default_item_when,
308                                                         'ago' => $default_item_ago,
309                                                         'seen' => $it['seen']
310                                                 ];
311                                                 break;
312
313                                         case ACTIVITY_ATTENDNO:
314                                                 $notif = [
315                                                         'label' => 'attendno',
316                                                         'link' => System::baseUrl(true) . '/display/' . $it['pguid'],
317                                                         'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
318                                                         'url' => $it['author-link'],
319                                                         'text' => sprintf(t("%s is not attending %s's event"), $it['author-name'], $it['pname']),
320                                                         'when' => $default_item_when,
321                                                         'ago' => $default_item_ago,
322                                                         'seen' => $it['seen']
323                                                 ];
324                                                 break;
325
326                                         case ACTIVITY_ATTENDMAYBE:
327                                                 $notif = [
328                                                         'label' => 'attendmaybe',
329                                                         'link' => System::baseUrl(true) . '/display/' . $it['pguid'],
330                                                         'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
331                                                         'url' => $it['author-link'],
332                                                         'text' => sprintf(t("%s may attend %s's event"), $it['author-name'], $it['pname']),
333                                                         'when' => $default_item_when,
334                                                         'ago' => $default_item_ago,
335                                                         'seen' => $it['seen']
336                                                 ];
337                                                 break;
338
339                                         case ACTIVITY_FRIEND:
340                                                 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
341                                                 $obj = parse_xml_string($xmlhead . $it['object']);
342                                                 $it['fname'] = $obj->title;
343
344                                                 $notif = [
345                                                         'label' => 'friend',
346                                                         'link' => System::baseUrl(true) . '/display/' . $it['pguid'],
347                                                         'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
348                                                         'url' => $it['author-link'],
349                                                         'text' => sprintf(t("%s is now friends with %s"), $it['author-name'], $it['fname']),
350                                                         'when' => $default_item_when,
351                                                         'ago' => $default_item_ago,
352                                                         'seen' => $it['seen']
353                                                 ];
354                                                 break;
355
356                                         default:
357                                                 $notif = [
358                                                         'label' => $default_item_label,
359                                                         'link' => $default_item_link,
360                                                         'image' => $default_item_image,
361                                                         'url' => $default_item_url,
362                                                         'text' => $default_item_text,
363                                                         'when' => $default_item_when,
364                                                         'ago' => $default_item_ago,
365                                                         'seen' => $it['seen']
366                                                 ];
367                                 }
368
369                                 $arr[] = $notif;
370                         }
371                 }
372
373                 return $arr;
374         }
375
376         /**
377          * @brief Total number of network notifications
378          * @param int|string $seen If 0 only include notifications into the query
379          *                             which aren't marked as "seen"
380          *
381          * @return int Number of network notifications
382          */
383         private function networkTotal($seen = 0)
384         {
385                 $sql_seen = "";
386
387                 if ($seen === 0) {
388                         $sql_seen = " AND `item`.`unseen` = 1 ";
389                 }
390
391                 $r = q(
392                         "SELECT COUNT(*) AS `total`
393                                 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
394                                 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
395                                  `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
396                                 $sql_seen",
397                         intval(local_user())
398                 );
399                 if (DBM::is_result($r)) {
400                         return $r[0]['total'];
401                 }
402
403                 return 0;
404         }
405
406         /**
407          * @brief Get network notifications
408          *
409          * @param int|string $seen  If 0 only include notifications into the query
410          *                              which aren't marked as "seen"
411          * @param int        $start Start the query at this point
412          * @param int        $limit Maximum number of query results
413          *
414          * @return array with
415          *      string 'ident' => Notification identifier
416          *      int 'total' => Total number of available network notifications
417          *      array 'notifications' => Network notifications
418          */
419         public function networkNotifs($seen = 0, $start = 0, $limit = 80)
420         {
421                 $ident = 'network';
422                 $total = $this->networkTotal($seen);
423                 $notifs = [];
424                 $sql_seen = "";
425
426                 if ($seen === 0) {
427                         $sql_seen = " AND `item`.`unseen` = 1 ";
428                 }
429
430                 $r = q(
431                         "SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
432                                 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
433                                 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
434                         FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
435                         WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
436                                  `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
437                                 $sql_seen
438                         ORDER BY `item`.`created` DESC LIMIT %d, %d ",
439                         intval(local_user()),
440                         intval($start),
441                         intval($limit)
442                 );
443                 if (DBM::is_result($r)) {
444                         $notifs = $this->formatNotifs($r, $ident);
445                 }
446
447                 $arr = [
448                         'notifications' => $notifs,
449                         'ident' => $ident,
450                         'total' => $total,
451                 ];
452
453                 return $arr;
454         }
455
456         /**
457          * @brief Total number of system notifications
458          * @param int|string $seen If 0 only include notifications into the query
459          *                             which aren't marked as "seen"
460          *
461          * @return int Number of system notifications
462          */
463         private function systemTotal($seen = 0)
464         {
465                 $sql_seen = "";
466
467                 if ($seen === 0) {
468                         $sql_seen = " AND `seen` = 0 ";
469                 }
470
471                 $r = q(
472                         "SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
473                         intval(local_user())
474                 );
475                 if (DBM::is_result($r)) {
476                         return $r[0]['total'];
477                 }
478
479                 return 0;
480         }
481
482         /**
483          * @brief Get system notifications
484          *
485          * @param int|string $seen  If 0 only include notifications into the query
486          *                              which aren't marked as "seen"
487          * @param int        $start Start the query at this point
488          * @param int        $limit Maximum number of query results
489          *
490          * @return array with
491          *      string 'ident' => Notification identifier
492          *      int 'total' => Total number of available system notifications
493          *      array 'notifications' => System notifications
494          */
495         public function systemNotifs($seen = 0, $start = 0, $limit = 80)
496         {
497                 $ident = 'system';
498                 $total = $this->systemTotal($seen);
499                 $notifs = [];
500                 $sql_seen = "";
501
502                 if ($seen === 0) {
503                         $sql_seen = " AND `seen` = 0 ";
504                 }
505
506                 $r = q(
507                         "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
508                                 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
509                         intval(local_user()),
510                         intval($start),
511                         intval($limit)
512                 );
513                 if (DBM::is_result($r)) {
514                         $notifs = $this->formatNotifs($r, $ident);
515                 }
516
517                 $arr = [
518                         'notifications' => $notifs,
519                         'ident' => $ident,
520                         'total' => $total,
521                 ];
522
523                 return $arr;
524         }
525
526         /**
527          * @brief Additional SQL query string for the personal notifications
528          *
529          * @return string The additional SQL query
530          */
531         private function personalSqlExtra()
532         {
533                 $myurl = System::baseUrl(true) . '/profile/' . self::getApp()->user['nickname'];
534                 $myurl = substr($myurl, strpos($myurl, '://') + 3);
535                 $myurl = str_replace(['www.', '.'], ['', '\\.'], $myurl);
536                 $diasp_url = str_replace('/profile/', '/u/', $myurl);
537                 $sql_extra = sprintf(
538                         " AND ( `item`.`author-link` regexp '%s' OR `item`.`tag` regexp '%s' OR `item`.`tag` regexp '%s' ) ",
539                         dbesc($myurl . '$'),
540                         dbesc($myurl . '\\]'),
541                         dbesc($diasp_url . '\\]')
542                 );
543
544                 return $sql_extra;
545         }
546
547         /**
548          * @brief Total number of personal notifications
549          * @param int|string $seen If 0 only include notifications into the query
550          *                             which aren't marked as "seen"
551          *
552          * @return int Number of personal notifications
553          */
554         private function personalTotal($seen = 0)
555         {
556                 $sql_seen = "";
557                 $sql_extra = $this->personalSqlExtra();
558
559                 if ($seen === 0) {
560                         $sql_seen = " AND `item`.`unseen` = 1 ";
561                 }
562
563                 $r = q(
564                         "SELECT COUNT(*) AS `total`
565                                 FROM `item` INNER JOIN `item` AS `pitem` ON  `pitem`.`id`=`item`.`parent`
566                                 WHERE `item`.`visible` = 1
567                                 $sql_extra
568                                 $sql_seen
569                                 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 ",
570                         intval(local_user())
571                 );
572                 if (DBM::is_result($r)) {
573                         return $r[0]['total'];
574                 }
575
576                 return 0;
577         }
578
579         /**
580          * @brief Get personal notifications
581          *
582          * @param int|string $seen  If 0 only include notifications into the query
583          *                              which aren't marked as "seen"
584          * @param int        $start Start the query at this point
585          * @param int        $limit Maximum number of query results
586          *
587          * @return array with
588          *      string 'ident' => Notification identifier
589          *      int 'total' => Total number of available personal notifications
590          *      array 'notifications' => Personal notifications
591          */
592         public function personalNotifs($seen = 0, $start = 0, $limit = 80)
593         {
594                 $ident = 'personal';
595                 $total = $this->personalTotal($seen);
596                 $sql_extra = $this->personalSqlExtra();
597                 $notifs = [];
598                 $sql_seen = "";
599
600                 if ($seen === 0) {
601                         $sql_seen = " AND `item`.`unseen` = 1 ";
602                 }
603
604                 $r = q(
605                         "SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
606                                 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
607                                 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
608                         FROM `item` INNER JOIN `item` AS `pitem` ON  `pitem`.`id`=`item`.`parent`
609                         WHERE `item`.`visible` = 1
610                                 $sql_extra
611                                 $sql_seen
612                                 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
613                         ORDER BY `item`.`created` DESC LIMIT %d, %d ",
614                         intval(local_user()),
615                         intval($start),
616                         intval($limit)
617                 );
618                 if (DBM::is_result($r)) {
619                         $notifs = $this->formatNotifs($r, $ident);
620                 }
621
622                 $arr = [
623                         'notifications' => $notifs,
624                         'ident' => $ident,
625                         'total' => $total,
626                 ];
627
628                 return $arr;
629         }
630
631         /**
632          * @brief Total number of home notifications
633          * @param int|string $seen If 0 only include notifications into the query
634          *                             which aren't marked as "seen"
635          *
636          * @return int Number of home notifications
637          */
638         private function homeTotal($seen = 0)
639         {
640                 $sql_seen = "";
641
642                 if ($seen === 0) {
643                         $sql_seen = " AND `item`.`unseen` = 1 ";
644                 }
645
646                 $r = q(
647                         "SELECT COUNT(*) AS `total` FROM `item`
648                                 WHERE `item`.`visible` = 1 AND
649                                  `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
650                                 $sql_seen",
651                         intval(local_user())
652                 );
653                 if (DBM::is_result($r)) {
654                         return $r[0]['total'];
655                 }
656
657                 return 0;
658         }
659
660         /**
661          * @brief Get home notifications
662          *
663          * @param int|string $seen  If 0 only include notifications into the query
664          *                              which aren't marked as "seen"
665          * @param int        $start Start the query at this point
666          * @param int        $limit Maximum number of query results
667          *
668          * @return array with
669          *      string 'ident' => Notification identifier
670          *      int 'total' => Total number of available home notifications
671          *      array 'notifications' => Home notifications
672          */
673         public function homeNotifs($seen = 0, $start = 0, $limit = 80)
674         {
675                 $ident = 'home';
676                 $total = $this->homeTotal($seen);
677                 $notifs = [];
678                 $sql_seen = "";
679
680                 if ($seen === 0) {
681                         $sql_seen = " AND `item`.`unseen` = 1 ";
682                 }
683
684                 $r = q(
685                         "SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
686                                 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
687                                 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
688                         FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
689                         WHERE `item`.`visible` = 1 AND
690                                  `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
691                                 $sql_seen
692                         ORDER BY `item`.`created` DESC LIMIT %d, %d ",
693                         intval(local_user()),
694                         intval($start),
695                         intval($limit)
696                 );
697                 if (DBM::is_result($r)) {
698                         $notifs = $this->formatNotifs($r, $ident);
699                 }
700
701                 $arr = [
702                         'notifications' => $notifs,
703                         'ident' => $ident,
704                         'total' => $total,
705                 ];
706
707                 return $arr;
708         }
709
710         /**
711          * @brief Total number of introductions
712          * @param bool $all If false only include introductions into the query
713          *                      which aren't marked as ignored
714          *
715          * @return int Number of introductions
716          */
717         private function introTotal($all = false)
718         {
719                 $sql_extra = "";
720
721                 if (!$all) {
722                         $sql_extra = " AND `ignore` = 0 ";
723                 }
724
725                 $r = q(
726                         "SELECT COUNT(*) AS `total` FROM `intro`
727                         WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
728                         intval($_SESSION['uid'])
729                 );
730
731                 if (DBM::is_result($r)) {
732                         return $r[0]['total'];
733                 }
734
735                 return 0;
736         }
737
738         /**
739          * @brief Get introductions
740          *
741          * @param bool $all   If false only include introductions into the query
742          *                        which aren't marked as ignored
743          * @param int  $start Start the query at this point
744          * @param int  $limit Maximum number of query results
745          *
746          * @return array with
747          *      string 'ident' => Notification identifier
748          *      int 'total' => Total number of available introductions
749          *      array 'notifications' => Introductions
750          */
751         public function introNotifs($all = false, $start = 0, $limit = 80)
752         {
753                 $ident = 'introductions';
754                 $total = $this->introTotal($all);
755                 $notifs = [];
756                 $sql_extra = "";
757
758                 if (!$all) {
759                         $sql_extra = " AND `ignore` = 0 ";
760                 }
761
762                 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
763                 $r = q(
764                         "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
765                                 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`,
766                                 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
767                                 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
768                                 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
769                                 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
770                         FROM `intro`
771                                 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
772                                 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
773                                 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
774                         WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
775                         LIMIT %d, %d",
776                         intval($_SESSION['uid']),
777                         intval($start),
778                         intval($limit)
779                 );
780                 if (DBM::is_result($r)) {
781                         $notifs = $this->formatIntros($r);
782                 }
783
784                 $arr = [
785                         'ident' => $ident,
786                         'total' => $total,
787                         'notifications' => $notifs,
788                 ];
789
790                 return $arr;
791         }
792
793         /**
794          * @brief Format the notification query in an usable array
795          *
796          * @param array $intros The array from the db query
797          * @return array with the introductions
798          */
799         private function formatIntros($intros)
800         {
801                 $knowyou = '';
802
803                 foreach ($intros as $it) {
804                         // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
805                         // We have to distinguish between these two because they use different data.
806                         // Contact suggestions
807                         if ($it['fid']) {
808                                 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->get_hostname() . ((self::getApp()->path) ? '/' . self::getApp()->path : ''));
809
810                                 $intro = [
811                                         'label' => 'friend_suggestion',
812                                         'notify_type' => t('Friend Suggestion'),
813                                         'intro_id' => $it['intro_id'],
814                                         'madeby' => $it['name'],
815                                         'contact_id' => $it['contact-id'],
816                                         'photo' => ((x($it, 'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
817                                         'name' => $it['fname'],
818                                         'url' => Profile::zrl($it['furl']),
819                                         'hidden' => $it['hidden'] == 1,
820                                         'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
821                                         'knowyou' => $knowyou,
822                                         'note' => $it['note'],
823                                         'request' => $it['frequest'] . '?addr=' . $return_addr,
824                                 ];
825
826                                 // Normal connection requests
827                         } else {
828                                 $it = $this->getMissingIntroData($it);
829
830                                 // Don't show these data until you are connected. Diaspora is doing the same.
831                                 if ($it['gnetwork'] === NETWORK_DIASPORA) {
832                                         $it['glocation'] = "";
833                                         $it['gabout'] = "";
834                                         $it['ggender'] = "";
835                                 }
836                                 $intro = [
837                                         'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
838                                         'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? t('Friend/Connect Request') : t('New Follower')),
839                                         'dfrn_id' => $it['issued-id'],
840                                         'uid' => $_SESSION['uid'],
841                                         'intro_id' => $it['intro_id'],
842                                         'contact_id' => $it['contact-id'],
843                                         'photo' => ((x($it, 'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
844                                         'name' => $it['name'],
845                                         'location' => bbcode($it['glocation'], false, false),
846                                         'about' => bbcode($it['gabout'], false, false),
847                                         'keywords' => $it['gkeywords'],
848                                         'gender' => $it['ggender'],
849                                         'hidden' => $it['hidden'] == 1,
850                                         'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
851                                         'url' => $it['url'],
852                                         'zrl' => Profile::zrl($it['url']),
853                                         'addr' => $it['gaddr'],
854                                         'network' => $it['gnetwork'],
855                                         'knowyou' => $it['knowyou'],
856                                         'note' => $it['note'],
857                                 ];
858                         }
859
860                         $arr[] = $intro;
861                 }
862
863                 return $arr;
864         }
865
866         /**
867          * @brief Check for missing contact data and try to fetch the data from
868          *     from other sources
869          *
870          * @param array $arr The input array with the intro data
871          *
872          * @return array The array with the intro data
873          */
874         private function getMissingIntroData($arr)
875         {
876                 // If the network and the addr isn't available from the gcontact
877                 // table entry, take the one of the contact table entry
878                 if ($arr['gnetwork'] == "") {
879                         $arr['gnetwork'] = $arr['network'];
880                 }
881                 if ($arr['gaddr'] == "") {
882                         $arr['gaddr'] = $arr['addr'];
883                 }
884
885                 // If the network and addr is still not available
886                 // get the missing data data from other sources
887                 if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
888                         $ret = Contact::getDetailsByURL($arr['url']);
889
890                         if ($arr['gnetwork'] == "" && $ret['network'] != "") {
891                                 $arr['gnetwork'] = $ret['network'];
892                         }
893                         if ($arr['gaddr'] == "" && $ret['addr'] != "") {
894                                 $arr['gaddr'] = $ret['addr'];
895                         }
896                 }
897
898                 return $arr;
899         }
900 }