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