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