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