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