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