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