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