]> git.mxchange.org Git - friendica.git/blob - src/Core/NotificationsManager.php
Fewer Defaults
[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\Content\Text\BBCode;
11 use Friendica\Core\L10n;
12 use Friendica\Core\PConfig;
13 use Friendica\Core\System;
14 use Friendica\Database\DBM;
15 use Friendica\Model\Contact;
16 use Friendica\Model\Profile;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Temporal;
19 use Friendica\Util\XML;
20
21 require_once 'include/dba.php';
22 require_once 'include/html2plain.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 = DateTimeFormat::local($n['date']);
47                         $n['timestamp'] = strtotime($local_time);
48                         $n['date_rel'] = Temporal::getRelativeDate($n['date']);
49                         $n['msg_html'] = BBCode::convert($n['msg'], 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::convert($it['msg']));
247                                                 $default_item_when = DateTimeFormat::local($it['date'], 'r');
248                                                 $default_item_ago = Temporal::getRelativeDate($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 = DateTimeFormat::local($it['created'], 'r');
258                                                 $default_item_ago = Temporal::getRelativeDate($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 = DateTimeFormat::local($it['created'], 'r');
270                                                 $default_item_ago = Temporal::getRelativeDate($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                 $index_hint = "";
388
389                 if ($seen === 0) {
390                         $sql_seen = " AND `item`.`unseen` ";
391                         $index_hint = "USE INDEX (`uid_unseen_contactid`)";
392                 }
393
394                 $r = q(
395                         "SELECT COUNT(*) AS `total`
396                                 FROM `item` $index_hint STRAIGHT_JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
397                                 WHERE `item`.`visible` AND `pitem`.`parent` != 0 AND
398                                 NOT `item`.`deleted` AND `item`.`uid` = %d AND NOT `item`.`wall`
399                                 $sql_seen",
400                         intval(local_user())
401                 );
402                 if (DBM::is_result($r)) {
403                         return $r[0]['total'];
404                 }
405
406                 return 0;
407         }
408
409         /**
410          * @brief Get network notifications
411          *
412          * @param int|string $seen  If 0 only include notifications into the query
413          *                              which aren't marked as "seen"
414          * @param int        $start Start the query at this point
415          * @param int        $limit Maximum number of query results
416          *
417          * @return array with
418          *      string 'ident' => Notification identifier
419          *      int 'total' => Total number of available network notifications
420          *      array 'notifications' => Network notifications
421          */
422         public function networkNotifs($seen = 0, $start = 0, $limit = 80)
423         {
424                 $ident = 'network';
425                 $total = $this->networkTotal($seen);
426                 $notifs = [];
427                 $sql_seen = "";
428                 $index_hint = "";
429
430                 if ($seen === 0) {
431                         $sql_seen = " AND `item`.`unseen` ";
432                         $index_hint = "USE INDEX (`uid_unseen_contactid`)";
433                 }
434
435                 $r = q(
436                         "SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
437                                 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
438                                 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
439                         FROM `item` $index_hint STRAIGHT_JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
440                         WHERE `item`.`visible` AND `pitem`.`parent` != 0 AND
441                                 NOT `item`.`deleted` AND `item`.`uid` = %d AND NOT `item`.`wall`
442                                 $sql_seen
443                         ORDER BY `item`.`created` DESC LIMIT %d, %d ",
444                         intval(local_user()),
445                         intval($start),
446                         intval($limit)
447                 );
448                 if (DBM::is_result($r)) {
449                         $notifs = $this->formatNotifs($r, $ident);
450                 }
451
452                 $arr = [
453                         'notifications' => $notifs,
454                         'ident' => $ident,
455                         'total' => $total,
456                 ];
457
458                 return $arr;
459         }
460
461         /**
462          * @brief Total number of system notifications
463          * @param int|string $seen If 0 only include notifications into the query
464          *                             which aren't marked as "seen"
465          *
466          * @return int Number of system notifications
467          */
468         private function systemTotal($seen = 0)
469         {
470                 $sql_seen = "";
471
472                 if ($seen === 0) {
473                         $sql_seen = " AND NOT `seen` ";
474                 }
475
476                 $r = q(
477                         "SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
478                         intval(local_user())
479                 );
480                 if (DBM::is_result($r)) {
481                         return $r[0]['total'];
482                 }
483
484                 return 0;
485         }
486
487         /**
488          * @brief Get system notifications
489          *
490          * @param int|string $seen  If 0 only include notifications into the query
491          *                              which aren't marked as "seen"
492          * @param int        $start Start the query at this point
493          * @param int        $limit Maximum number of query results
494          *
495          * @return array with
496          *      string 'ident' => Notification identifier
497          *      int 'total' => Total number of available system notifications
498          *      array 'notifications' => System notifications
499          */
500         public function systemNotifs($seen = 0, $start = 0, $limit = 80)
501         {
502                 $ident = 'system';
503                 $total = $this->systemTotal($seen);
504                 $notifs = [];
505                 $sql_seen = "";
506
507                 if ($seen === 0) {
508                         $sql_seen = " AND NOT `seen` ";
509                 }
510
511                 $r = q(
512                         "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen` FROM `notify`
513                                 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
514                         intval(local_user()),
515                         intval($start),
516                         intval($limit)
517                 );
518                 if (DBM::is_result($r)) {
519                         $notifs = $this->formatNotifs($r, $ident);
520                 }
521
522                 $arr = [
523                         'notifications' => $notifs,
524                         'ident' => $ident,
525                         'total' => $total,
526                 ];
527
528                 return $arr;
529         }
530
531         /**
532          * @brief Additional SQL query string for the personal notifications
533          *
534          * @return string The additional SQL query
535          */
536         private function personalSqlExtra()
537         {
538                 $myurl = System::baseUrl(true) . '/profile/' . self::getApp()->user['nickname'];
539                 $myurl = substr($myurl, strpos($myurl, '://') + 3);
540                 $myurl = str_replace(['www.', '.'], ['', '\\.'], $myurl);
541                 $diasp_url = str_replace('/profile/', '/u/', $myurl);
542                 $sql_extra = sprintf(
543                         " AND (`item`.`author-link` REGEXP '%s' OR `item`.`tag` REGEXP '%s' OR `item`.`tag` REGEXP '%s') ",
544                         dbesc($myurl . '$'),
545                         dbesc($myurl . '\\]'),
546                         dbesc($diasp_url . '\\]')
547                 );
548
549                 return $sql_extra;
550         }
551
552         /**
553          * @brief Total number of personal notifications
554          * @param int|string $seen If 0 only include notifications into the query
555          *                             which aren't marked as "seen"
556          *
557          * @return int Number of personal notifications
558          */
559         private function personalTotal($seen = 0)
560         {
561                 $sql_seen = "";
562                 $index_hint = "";
563                 $sql_extra = $this->personalSqlExtra();
564
565                 if ($seen === 0) {
566                         $sql_seen = " AND `item`.`unseen` ";
567                         $index_hint = "USE INDEX (`uid_unseen_contactid`)";
568                 }
569
570                 $r = q(
571                         "SELECT COUNT(*) AS `total`
572                                 FROM `item` $index_hint
573                                 WHERE `item`.`visible`
574                                 $sql_extra
575                                 $sql_seen
576                                 AND NOT `item`.`deleted` AND `item`.`uid` = %d AND NOT `item`.`wall`",
577                         intval(local_user())
578                 );
579                 if (DBM::is_result($r)) {
580                         return $r[0]['total'];
581                 }
582
583                 return 0;
584         }
585
586         /**
587          * @brief Get personal notifications
588          *
589          * @param int|string $seen  If 0 only include notifications into the query
590          *                              which aren't marked as "seen"
591          * @param int        $start Start the query at this point
592          * @param int        $limit Maximum number of query results
593          *
594          * @return array with
595          *      string 'ident' => Notification identifier
596          *      int 'total' => Total number of available personal notifications
597          *      array 'notifications' => Personal notifications
598          */
599         public function personalNotifs($seen = 0, $start = 0, $limit = 80)
600         {
601                 $ident = 'personal';
602                 $total = $this->personalTotal($seen);
603                 $sql_extra = $this->personalSqlExtra();
604                 $notifs = [];
605                 $sql_seen = "";
606                 $index_hint = "";
607
608                 if ($seen === 0) {
609                         $sql_seen = " AND `item`.`unseen` ";
610                         $index_hint = "USE INDEX (`uid_unseen_contactid`)";
611                 }
612
613                 $r = q(
614                         "SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
615                                 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
616                                 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
617                         FROM `item` $index_hint STRAIGHT_JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
618                         WHERE `item`.`visible`
619                                 $sql_extra
620                                 $sql_seen
621                                 AND NOT `item`.`deleted` AND `item`.`uid` = %d AND NOT `item`.`wall`
622                         ORDER BY `item`.`created` DESC LIMIT %d, %d ",
623                         intval(local_user()),
624                         intval($start),
625                         intval($limit)
626                 );
627                 if (DBM::is_result($r)) {
628                         $notifs = $this->formatNotifs($r, $ident);
629                 }
630
631                 $arr = [
632                         'notifications' => $notifs,
633                         'ident' => $ident,
634                         'total' => $total,
635                 ];
636
637                 return $arr;
638         }
639
640         /**
641          * @brief Total number of home notifications
642          * @param int|string $seen If 0 only include notifications into the query
643          *                             which aren't marked as "seen"
644          *
645          * @return int Number of home notifications
646          */
647         private function homeTotal($seen = 0)
648         {
649                 $sql_seen = "";
650                 $index_hint = "";
651
652                 if ($seen === 0) {
653                         $sql_seen = " AND `item`.`unseen` ";
654                         $index_hint = "USE INDEX (`uid_unseen_contactid`)";
655                 }
656
657                 $r = q(
658                         "SELECT COUNT(*) AS `total` FROM `item` $index_hint
659                                 WHERE `item`.`visible` = 1 AND
660                                  `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
661                                 $sql_seen",
662                         intval(local_user())
663                 );
664                 if (DBM::is_result($r)) {
665                         return $r[0]['total'];
666                 }
667
668                 return 0;
669         }
670
671         /**
672          * @brief Get home notifications
673          *
674          * @param int|string $seen  If 0 only include notifications into the query
675          *                              which aren't marked as "seen"
676          * @param int        $start Start the query at this point
677          * @param int        $limit Maximum number of query results
678          *
679          * @return array with
680          *      string 'ident' => Notification identifier
681          *      int 'total' => Total number of available home notifications
682          *      array 'notifications' => Home notifications
683          */
684         public function homeNotifs($seen = 0, $start = 0, $limit = 80)
685         {
686                 $ident = 'home';
687                 $total = $this->homeTotal($seen);
688                 $notifs = [];
689                 $sql_seen = "";
690                 $index_hint = "";
691
692                 if ($seen === 0) {
693                         $sql_seen = " AND `item`.`unseen` ";
694                         $index_hint = "USE INDEX (`uid_unseen_contactid`)";
695                 }
696
697                 $r = q(
698                         "SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
699                                 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
700                                 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
701                         FROM `item` $index_hint STRAIGHT_JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
702                         WHERE `item`.`visible` AND
703                                 NOT `item`.`deleted` AND `item`.`uid` = %d AND `item`.`wall`
704                                 $sql_seen
705                         ORDER BY `item`.`created` DESC LIMIT %d, %d ",
706                         intval(local_user()),
707                         intval($start),
708                         intval($limit)
709                 );
710                 if (DBM::is_result($r)) {
711                         $notifs = $this->formatNotifs($r, $ident);
712                 }
713
714                 $arr = [
715                         'notifications' => $notifs,
716                         'ident' => $ident,
717                         'total' => $total,
718                 ];
719
720                 return $arr;
721         }
722
723         /**
724          * @brief Total number of introductions
725          * @param bool $all If false only include introductions into the query
726          *                      which aren't marked as ignored
727          *
728          * @return int Number of introductions
729          */
730         private function introTotal($all = false)
731         {
732                 $sql_extra = "";
733
734                 if (!$all) {
735                         $sql_extra = " AND `ignore` = 0 ";
736                 }
737
738                 $r = q(
739                         "SELECT COUNT(*) AS `total` FROM `intro`
740                         WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
741                         intval($_SESSION['uid'])
742                 );
743
744                 if (DBM::is_result($r)) {
745                         return $r[0]['total'];
746                 }
747
748                 return 0;
749         }
750
751         /**
752          * @brief Get introductions
753          *
754          * @param bool $all   If false only include introductions into the query
755          *                        which aren't marked as ignored
756          * @param int  $start Start the query at this point
757          * @param int  $limit Maximum number of query results
758          *
759          * @return array with
760          *      string 'ident' => Notification identifier
761          *      int 'total' => Total number of available introductions
762          *      array 'notifications' => Introductions
763          */
764         public function introNotifs($all = false, $start = 0, $limit = 80)
765         {
766                 $ident = 'introductions';
767                 $total = $this->introTotal($all);
768                 $notifs = [];
769                 $sql_extra = "";
770
771                 if (!$all) {
772                         $sql_extra = " AND `ignore` = 0 ";
773                 }
774
775                 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
776                 $r = q(
777                         "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
778                                 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`,
779                                 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
780                                 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
781                                 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
782                                 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
783                         FROM `intro`
784                                 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
785                                 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
786                                 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
787                         WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
788                         LIMIT %d, %d",
789                         intval($_SESSION['uid']),
790                         intval($start),
791                         intval($limit)
792                 );
793                 if (DBM::is_result($r)) {
794                         $notifs = $this->formatIntros($r);
795                 }
796
797                 $arr = [
798                         'ident' => $ident,
799                         'total' => $total,
800                         'notifications' => $notifs,
801                 ];
802
803                 return $arr;
804         }
805
806         /**
807          * @brief Format the notification query in an usable array
808          *
809          * @param array $intros The array from the db query
810          * @return array with the introductions
811          */
812         private function formatIntros($intros)
813         {
814                 $knowyou = '';
815
816                 foreach ($intros as $it) {
817                         // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
818                         // We have to distinguish between these two because they use different data.
819                         // Contact suggestions
820                         if ($it['fid']) {
821                                 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->get_hostname() . ((self::getApp()->path) ? '/' . self::getApp()->path : ''));
822
823                                 $intro = [
824                                         'label' => 'friend_suggestion',
825                                         'notify_type' => L10n::t('Friend Suggestion'),
826                                         'intro_id' => $it['intro_id'],
827                                         'madeby' => $it['name'],
828                                         'contact_id' => $it['contact-id'],
829                                         'photo' => ((x($it, 'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
830                                         'name' => $it['fname'],
831                                         'url' => Profile::zrl($it['furl']),
832                                         'hidden' => $it['hidden'] == 1,
833                                         'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
834                                         'knowyou' => $knowyou,
835                                         'note' => $it['note'],
836                                         'request' => $it['frequest'] . '?addr=' . $return_addr,
837                                 ];
838
839                                 // Normal connection requests
840                         } else {
841                                 $it = $this->getMissingIntroData($it);
842
843                                 // Don't show these data until you are connected. Diaspora is doing the same.
844                                 if ($it['gnetwork'] === NETWORK_DIASPORA) {
845                                         $it['glocation'] = "";
846                                         $it['gabout'] = "";
847                                         $it['ggender'] = "";
848                                 }
849                                 $intro = [
850                                         'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
851                                         'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? L10n::t('Friend/Connect Request') : L10n::t('New Follower')),
852                                         'dfrn_id' => $it['issued-id'],
853                                         'uid' => $_SESSION['uid'],
854                                         'intro_id' => $it['intro_id'],
855                                         'contact_id' => $it['contact-id'],
856                                         'photo' => ((x($it, 'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
857                                         'name' => $it['name'],
858                                         'location' => BBCode::convert($it['glocation'], false),
859                                         'about' => BBCode::convert($it['gabout'], false),
860                                         'keywords' => $it['gkeywords'],
861                                         'gender' => $it['ggender'],
862                                         'hidden' => $it['hidden'] == 1,
863                                         'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
864                                         'url' => $it['url'],
865                                         'zrl' => Profile::zrl($it['url']),
866                                         'addr' => $it['gaddr'],
867                                         'network' => $it['gnetwork'],
868                                         'knowyou' => $it['knowyou'],
869                                         'note' => $it['note'],
870                                 ];
871                         }
872
873                         $arr[] = $intro;
874                 }
875
876                 return $arr;
877         }
878
879         /**
880          * @brief Check for missing contact data and try to fetch the data from
881          *     from other sources
882          *
883          * @param array $arr The input array with the intro data
884          *
885          * @return array The array with the intro data
886          */
887         private function getMissingIntroData($arr)
888         {
889                 // If the network and the addr isn't available from the gcontact
890                 // table entry, take the one of the contact table entry
891                 if ($arr['gnetwork'] == "") {
892                         $arr['gnetwork'] = $arr['network'];
893                 }
894                 if ($arr['gaddr'] == "") {
895                         $arr['gaddr'] = $arr['addr'];
896                 }
897
898                 // If the network and addr is still not available
899                 // get the missing data data from other sources
900                 if ($arr['gnetwork'] == "" || $arr['gaddr'] == "") {
901                         $ret = Contact::getDetailsByURL($arr['url']);
902
903                         if ($arr['gnetwork'] == "" && $ret['network'] != "") {
904                                 $arr['gnetwork'] = $ret['network'];
905                         }
906                         if ($arr['gaddr'] == "" && $ret['addr'] != "") {
907                                 $arr['gaddr'] = $ret['addr'];
908                         }
909                 }
910
911                 return $arr;
912         }
913 }