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