]> git.mxchange.org Git - friendica.git/blob - include/NotificationsManager.php
Merge pull request #3373 from strk/expire-login-later
[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/datetime.php");
9 require_once("include/bbcode.php");
10
11 /**
12  * @brief Methods for read and write notifications from/to database
13  *  or for formatting notifications
14  */
15 class NotificationsManager {
16         private $a;
17
18         public function __construct() {
19                 $this->a = get_app();
20         }
21
22         /**
23          * @brief set some extra note properties
24          *
25          * @param array $notes array of note arrays from db
26          * @return array Copy of input array with added properties
27          * 
28          * Set some extra properties to note array from db:
29          *  - timestamp as int in default TZ
30          *  - date_rel : relative date string
31          *  - msg_html: message as html string
32          *  - msg_plain: message as plain text string
33          */
34         private function _set_extra($notes) {
35                 $rets = array();
36                 foreach($notes as $n) {
37                         $local_time = datetime_convert('UTC',date_default_timezone_get(),$n['date']);
38                         $n['timestamp'] = strtotime($local_time);
39                         $n['date_rel'] = relative_date($n['date']);
40                                 $n['msg_html'] = bbcode($n['msg'], false, false, false, false);
41                                 $n['msg_plain'] = explode("\n",trim(html2plain($n['msg_html'], 0)))[0];
42
43                         $rets[] = $n;
44                 }
45                 return $rets;
46         }
47
48
49         /**
50          * @brief Get all notifications for local_user()
51          *
52          * @param array $filter optional Array "column name"=>value: filter query by columns values
53          * @param string $order optional Space separated list of column to sort by. prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
54          * @param string $limit optional Query limits
55          *
56          * @return array of results or false on errors
57          */
58         public function getAll($filter = array(), $order="-date", $limit="") {
59                 $filter_str = array();
60                 $filter_sql = "";
61                 foreach($filter as $column => $value) {
62                         $filter_str[] = sprintf("`%s` = '%s'", $column, dbesc($value));
63                 }
64                 if (count($filter_str)>0) {
65                         $filter_sql = "AND ".implode(" AND ", $filter_str);
66                 }
67
68                 $aOrder = explode(" ", $order);
69                 $asOrder = array();
70                 foreach($aOrder as $o) {
71                         $dir = "asc";
72                         if ($o[0]==="-") {
73                                 $dir = "desc";
74                                 $o = substr($o,1);
75                         }
76                         if ($o[0]==="+") {
77                                 $dir = "asc";
78                                 $o = substr($o,1);
79                         }
80                         $asOrder[] = "$o $dir";
81                 }
82                 $order_sql = implode(", ", $asOrder);
83
84                 if($limit!="")
85                         $limit = " LIMIT ".$limit;
86
87                         $r = q("SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
88                                 intval(local_user())
89                         );
90
91                 if (dbm::is_result($r))
92                         return $this->_set_extra($r);
93
94                 return false;
95         }
96
97         /**
98          * @brief Get one note for local_user() by $id value
99          *
100          * @param int $id
101          * @return array note values or null if not found
102          */
103         public function getByID($id) {
104                 $r = q("SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
105                         intval($id),
106                         intval(local_user())
107                 );
108                 if (dbm::is_result($r)) {
109                         return $this->_set_extra($r)[0];
110                 }
111                 return null;
112         }
113
114         /**
115          * @brief set seen state of $note of local_user()
116          *
117          * @param array $note
118          * @param bool $seen optional true or false, default true
119          * @return bool true on success, false on errors
120          */
121         public function setSeen($note, $seen = true) {
122                 return q("UPDATE `notify` SET `seen` = %d WHERE ( `link` = '%s' OR ( `parent` != 0 AND `parent` = %d AND `otype` = '%s' )) AND `uid` = %d",
123                         intval($seen),
124                         dbesc($note['link']),
125                         intval($note['parent']),
126                         dbesc($note['otype']),
127                         intval(local_user())
128                 );
129         }
130
131         /**
132          * @brief set seen state of all notifications of local_user()
133          *
134          * @param bool $seen optional true or false. default true
135          * @return bool true on success, false on error
136          */
137         public function setAllSeen($seen = true) {
138                 return q("UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
139                         intval($seen),
140                         intval(local_user())
141                 );
142         }
143
144         /**
145          * @brief List of pages for the Notifications TabBar
146          * 
147          * @param app $a The 
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`.*, `fcontact`.`name` AS `fname`,`fcontact`.`url` AS `furl`,`fcontact`.`photo` AS `fphoto`,`fcontact`.`request` AS `frequest`,
724                                 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
725                                 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
726                                 `gcontact`.`network` AS `gnetwork`
727                         FROM `intro`
728                                 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
729                                 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
730                                 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
731                         WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
732                         LIMIT %d, %d",
733                                 intval($_SESSION['uid']),
734                                 intval($start),
735                                 intval($limit)
736                 );
737
738                 if (dbm::is_result($r))
739                         $notifs = $this->formatIntros($r);
740
741                 $arr = array (
742                         'ident' => $ident,
743                         'total' => $total,
744                         'notifications' => $notifs,
745                 );
746
747                 return $arr;
748         }
749
750         /**
751          * @brief Format the notification query in an usable array
752          * 
753          * @param array $intros The array from the db query
754          * @return array with the introductions
755          */
756         private function formatIntros($intros) {
757                 $knowyou = '';
758
759                 foreach($intros as $it) {
760                         // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
761                         // We have to distinguish between these two because they use different data.
762
763                         // Contact suggestions
764                         if($it['fid']) {
765
766                                 $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
767
768                                 $intro = array(
769                                         'label' => 'friend_suggestion',
770                                         'notify_type' => t('Friend Suggestion'),
771                                         'intro_id' => $it['intro_id'],
772                                         'madeby' => $it['name'],
773                                         'contact_id' => $it['contact-id'],
774                                         'photo' => ((x($it,'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
775                                         'name' => $it['fname'],
776                                         'url' => zrl($it['furl']),
777                                         'hidden' => $it['hidden'] == 1,
778                                         'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
779
780                                         'knowyou' => $knowyou,
781                                         'note' => $it['note'],
782                                         'request' => $it['frequest'] . '?addr=' . $return_addr,
783
784                                 );
785
786                         // Normal connection requests
787                         } else {
788
789                                 // Probe the contact url to get missing data
790                                 $ret = probe_url($it["url"]);
791
792                                 if ($it['gnetwork'] == "")
793                                         $it['gnetwork'] = $ret["network"];
794
795                                 // Don't show these data until you are connected. Diaspora is doing the same.
796                                 if($it['gnetwork'] === NETWORK_DIASPORA) {
797                                         $it['glocation'] = "";
798                                         $it['gabout'] = "";
799                                         $it['ggender'] = "";
800                                 }
801                                 $intro = array(
802                                         'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
803                                         'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? t('Friend/Connect Request') : t('New Follower')),
804                                         'dfrn_id' => $it['issued-id'],
805                                         'uid' => $_SESSION['uid'],
806                                         'intro_id' => $it['intro_id'],
807                                         'contact_id' => $it['contact-id'],
808                                         'photo' => ((x($it,'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
809                                         'name' => $it['name'],
810                                         'location' => bbcode($it['glocation'], false, false),
811                                         'about' => bbcode($it['gabout'], false, false),
812                                         'keywords' => $it['gkeywords'],
813                                         'gender' => $it['ggender'],
814                                         'hidden' => $it['hidden'] == 1,
815                                         'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
816                                         'url' => $it['url'],
817                                         'zrl' => zrl($it['url']),
818                                         'addr' => $ret['addr'],
819                                         'network' => $it['gnetwork'],
820                                         'knowyou' => $it['knowyou'],
821                                         'note' => $it['note'],
822                                 );
823                         }
824
825                         $arr[] = $intro;
826                 }
827
828                 return $arr;
829         }
830 }