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