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