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