]> git.mxchange.org Git - friendica.git/blob - include/NotificationsManager.php
Merge remote-tracking branch 'upstream/develop' into 1607-performance
[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 (array_key_exists('unseen', $it)) {
217                                         $it['seen'] = ($it['unseen'] > 0 ? false : true);
218                                 }
219
220                                 // Depending on the identifier of the notification we need to use different defaults
221                                 switch ($ident) {
222                                         case 'system':
223                                                 $default_item_label = 'notify';
224                                                 $default_item_link = $this->a->get_baseurl(true).'/notify/view/'. $it['id'];
225                                                 $default_item_image = proxy_url($it['photo'], false, PROXY_SIZE_MICRO);
226                                                 $default_item_text = strip_tags(bbcode($it['msg']));
227                                                 $default_item_when = relative_date($it['date']);
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                                                 break;
237
238                                         default:
239                                                 $default_item_label = (($it['id'] == $it['parent']) ? 'post' : 'comment');
240                                                 $default_item_link = $this->a->get_baseurl(true).'/display/'.$it['pguid'];
241                                                 $default_item_image = proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO);
242                                                 $default_item_text = (($it['id'] == $it['parent'])
243                                                                         ? sprintf(t("%s created a new post"), $it['author-name'])
244                                                                         : sprintf(t("%s commented on %s's post"), $it['author-name'], $it['pname']));
245                                                 $default_item_when = relative_date($it['created']);
246
247                                 }
248
249                                 // Transform the different types of notification in an usable array
250                                 switch ($it['verb']){
251                                         case ACTIVITY_LIKE:
252                                                 $notif = array(
253                                                         'label' => 'like',
254                                                         'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
255                                                         '$image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
256                                                         'text' => sprintf(t("%s liked %s's post"), $it['author-name'], $it['pname']),
257                                                         'when' => relative_date($it['created']),
258                                                         'seen' => $it['seen']
259                                                 );
260                                                 break;
261
262                                         case ACTIVITY_DISLIKE:
263                                                 $notif = array(
264                                                         'label' => 'dislike',
265                                                         'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
266                                                         'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
267                                                         'text' => sprintf(t("%s disliked %s's post"), $it['author-name'], $it['pname']),
268                                                         'when' => relative_date($it['created']),
269                                                         'seen' => $it['seen']
270                                                 );
271                                                 break;
272
273                                         case ACTIVITY_ATTEND:
274                                                 $notif = array(
275                                                         'label' => 'attend',
276                                                         'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
277                                                         'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
278                                                         'text' => sprintf(t("%s is attending %s's event"), $it['author-name'], $it['pname']),
279                                                         'when' => relative_date($it['created']),
280                                                         'seen' => $it['seen']
281                                                 );
282                                                 break;
283
284                                         case ACTIVITY_ATTENDNO:
285                                                 $notif = array(
286                                                         'label' => 'attendno',
287                                                         'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
288                                                         'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
289                                                         'text' => sprintf( t("%s is not attending %s's event"), $it['author-name'], $it['pname']),
290                                                         'when' => relative_date($it['created']),
291                                                         'seen' => $it['seen']
292                                                 );
293                                                 break;
294
295                                         case ACTIVITY_ATTENDMAYBE:
296                                                 $notif = array(
297                                                         'label' => 'attendmaybe',
298                                                         'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
299                                                         'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
300                                                         'text' => sprintf(t("%s may attend %s's event"), $it['author-name'], $it['pname']),
301                                                         'when' => relative_date($it['created']),
302                                                         'seen' => $it['seen']
303                                                 );
304                                                 break;
305
306                                         case ACTIVITY_FRIEND:
307                                                 $xmlhead="<"."?xml version='1.0' encoding='UTF-8' ?".">";
308                                                 $obj = parse_xml_string($xmlhead.$it['object']);
309                                                 $it['fname'] = $obj->title;
310
311                                                 $notif = array(
312                                                         'label' => 'friend',
313                                                         'link' => $this->a->get_baseurl(true).'/display/'.$it['pguid'],
314                                                         'image' => proxy_url($it['author-avatar'], false, PROXY_SIZE_MICRO),
315                                                         'text' => sprintf(t("%s is now friends with %s"), $it['author-name'], $it['fname']),
316                                                         'when' => relative_date($it['created']),
317                                                         'seen' => $it['seen']
318                                                 );
319                                                 break;
320
321                                         default:
322                                                 $notif = array(
323                                                         'label' => $default_item_label,
324                                                         'link' => $default_item_link,
325                                                         'image' => $default_item_image,
326                                                         'text' => $default_item_text,
327                                                         'when' => $default_item_when,
328                                                         'seen' => $it['seen']
329                                                 );
330                                 }
331
332                                 $arr[] = $notif;
333                         }
334                 }
335
336                 return $arr;
337
338         }
339
340         /**
341          * @brief Total number of network notifications 
342          * @param int|string $seen
343          *      If 0 only include notifications into the query
344          *      which aren't marked as "seen"
345          * @return int Number of network notifications
346          */
347         private function networkTotal($seen = 0) {
348                 $sql_seen = "";
349
350                 if($seen === 0)
351                         $sql_seen = " AND `item`.`unseen` = 1 ";
352
353                 $r = q("SELECT COUNT(*) AS `total`
354                                 FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
355                                 WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
356                                  `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
357                                 $sql_seen",
358                         intval(local_user())
359                 );
360
361                 if(dbm::is_result($r))
362                         return $r[0]['total'];
363
364                 return 0;
365         }
366
367         /**
368          * @brief Get network notifications
369          * 
370          * @param int|string $seen
371          *      If 0 only include notifications into the query
372          *      which aren't marked as "seen"
373          * @param int $start Start the query at this point
374          * @param int $limit Maximum number of query results
375          * 
376          * @return array with
377          *      string 'ident' => Notification identifier
378          *      int 'total' => Total number of available network notifications
379          *      array 'notifications' => Network notifications
380          */
381         public function networkNotifs($seen = 0, $start = 0, $limit = 80) {
382                 $ident = 'network';
383                 $total = $this->networkTotal($seen);
384                 $notifs = array();
385                 $sql_seen = "";
386
387                 if($seen === 0)
388                         $sql_seen = " AND `item`.`unseen` = 1 ";
389
390
391                 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
392                                 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`,
393                                 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid`
394                         FROM `item` INNER JOIN `item` AS `pitem` ON `pitem`.`id`=`item`.`parent`
395                         WHERE `item`.`visible` = 1 AND `pitem`.`parent` != 0 AND
396                                  `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0
397                                 $sql_seen
398                         ORDER BY `item`.`created` DESC LIMIT %d, %d ",
399                                 intval(local_user()),
400                                 intval($start),
401                                 intval($limit)
402                 );
403
404                 if(dbm::is_result($r))
405                         $notifs = $this->formatNotifs($r, $ident);
406
407                 $arr = array (
408                         'notifications' => $notifs,
409                         'ident' => $ident,
410                         'total' => $total,
411                 );
412
413                 return $arr;
414         }
415
416         /**
417          * @brief Total number of system notifications 
418          * @param int|string $seen
419          *      If 0 only include notifications into the query
420          *      which aren't marked as "seen"
421          * @return int Number of system notifications
422          */
423         private function systemTotal($seen = 0) {
424                 $sql_seen = "";
425
426                 if($seen === 0)
427                         $sql_seen = " AND `seen` = 0 ";
428
429                 $r = q("SELECT COUNT(*) AS `total` FROM `notify` WHERE `uid` = %d $sql_seen",
430                         intval(local_user())
431                 );
432
433                 if(dbm::is_result($r))
434                         return $r[0]['total'];
435
436                 return 0;
437         }
438
439         /**
440          * @brief Get system notifications
441          * 
442          * @param int|string $seen
443          *      If 0 only include notifications into the query
444          *      which aren't marked as "seen"
445          * @param int $start Start the query at this point
446          * @param int $limit Maximum number of query results
447          * 
448          * @return array with
449          *      string 'ident' => Notification identifier
450          *      int 'total' => Total number of available system notifications
451          *      array 'notifications' => System notifications
452          */
453         public function systemNotifs($seen = 0, $start = 0, $limit = 80) {
454                 $ident = 'system';
455                 $total = $this->systemTotal($seen);
456                 $notifs = array();
457                 $sql_seen = "";
458
459                 if($seen === 0)
460                         $sql_seen = " AND `seen` = 0 ";
461
462                 $r = q("SELECT `id`, `photo`, `msg`, `date`, `seen` FROM `notify`
463                                 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
464                         intval(local_user()),
465                         intval($start),
466                         intval($limit)
467                 );
468
469                 if(dbm::is_result($r))
470                         $notifs = $this->formatNotifs($r, $ident);
471
472                 $arr = array (
473                         'notifications' => $notifs,
474                         'ident' => $ident,
475                         'total' => $total,
476                 );
477
478                 return $arr;
479         }
480
481         /**
482          * @brief Addional SQL query string for the personal notifications
483          * 
484          * @return string The additional sql query
485          */
486         private function _personal_sql_extra() {
487                 $myurl = $this->a->get_baseurl(true) . '/profile/'. $this->a->user['nickname'];
488                 $myurl = substr($myurl,strpos($myurl,'://')+3);
489                 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
490                 $diasp_url = str_replace('/profile/','/u/',$myurl);
491                 $sql_extra = sprintf(" AND ( `item`.`author-link` regexp '%s' or `item`.`tag` regexp '%s' or `item`.`tag` regexp '%s' ) ",
492                         dbesc($myurl . '$'),
493                         dbesc($myurl . '\\]'),
494                         dbesc($diasp_url . '\\]')
495                 );
496
497                 return $sql_extra;
498         }
499
500         /**
501          * @brief Total number of personal notifications 
502          * @param int|string $seen
503          *      If 0 only include notifications into the query
504          *      which aren't marked as "seen"
505          * @return int Number of personal notifications
506          */
507         private function personalTotal($seen = 0) {
508                 $sql_seen = "";
509                 $sql_extra = $this->_personal_sql_extra();
510
511                 if($seen === 0)
512                         $sql_seen = " AND `item`.`unseen` = 1 ";
513
514                 $r = q("SELECT COUNT(*) AS `total`
515                                 FROM `item` INNER JOIN `item` AS `pitem` ON  `pitem`.`id`=`item`.`parent`
516                                 WHERE `item`.`visible` = 1
517                                 $sql_extra
518                                 $sql_seen
519                                 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 " ,
520                         intval(local_user())
521                 );
522
523                 if(dbm::is_result($r))
524                         return $r[0]['total'];
525
526                 return 0;
527         }
528
529         /**
530          * @brief Get personal notifications
531          * 
532          * @param int|string $seen
533          *      If 0 only include notifications into the query
534          *      which aren't marked as "seen"
535          * @param int $start Start the query at this point
536          * @param int $limit Maximum number of query results
537          * 
538          * @return array with
539          *      string 'ident' => Notification identifier
540          *      int 'total' => Total number of available personal notifications
541          *      array 'notifications' => Personal notifications
542          */
543         public function personalNotifs($seen = 0, $start = 0, $limit = 80) {
544                 $ident = 'personal';
545                 $total = $this->personalTotal($seen);
546                 $sql_extra = $this->_personal_sql_extra();
547                 $notifs = array();
548                 $sql_seen = "";
549
550                 if($seen === 0)
551                         $sql_seen = " AND `item`.`unseen` = 1 ";
552
553                 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
554                                 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` AS `object`, 
555                                 `pitem`.`author-name` AS `pname`, `pitem`.`author-link` AS `plink`, `pitem`.`guid` AS `pguid` 
556                         FROM `item` INNER JOIN `item` AS `pitem` ON  `pitem`.`id`=`item`.`parent`
557                         WHERE `item`.`visible` = 1
558                                 $sql_extra
559                                 $sql_seen
560                                 AND `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 0 
561                         ORDER BY `item`.`created` DESC LIMIT %d, %d " ,
562                                 intval(local_user()),
563                                 intval($start),
564                                 intval($limit)
565                 );
566
567                 if(dbm::is_result($r))
568                         $notifs = $this->formatNotifs($r, $ident);
569                 
570                 $arr = array (
571                         'notifications' => $notifs,
572                         'ident' => $ident,
573                         'total' => $total,
574                 );
575
576                 return $arr;
577         }
578
579         /**
580          * @brief Total number of home notifications 
581          * @param int|string $seen
582          *      If 0 only include notifications into the query
583          *      which aren't marked as "seen"
584          * @return int Number of home notifications
585          */
586         private function homeTotal($seen = 0) {
587                 $sql_seen = "";
588
589                 if($seen === 0)
590                         $sql_seen = " AND `item`.`unseen` = 1 ";
591
592                 $r = q("SELECT COUNT(*) AS `total` FROM `item`
593                                 WHERE `item`.`visible` = 1 AND
594                                  `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
595                                 $sql_seen",
596                         intval(local_user())
597                 );
598
599                 if(dbm::is_result($r))
600                         return $r[0]['total'];
601
602                 return 0;
603         }
604
605         /**
606          * @brief Get home notifications
607          * 
608          * @param int|string $seen
609          *      If 0 only include notifications into the query
610          *      which aren't marked as "seen"
611          * @param int $start Start the query at this point
612          * @param int $limit Maximum number of query results
613          * 
614          * @return array with
615          *      string 'ident' => Notification identifier
616          *      int 'total' => Total number of available home notifications
617          *      array 'notifications' => Home notifications
618          */
619         public function homeNotifs($seen = 0, $start = 0, $limit = 80) {
620                 $ident = 'home';
621                 $total = $this->homeTotal($seen);
622                 $notifs = array();
623                 $sql_seen = "";
624
625                 if($seen === 0)
626                         $sql_seen = " AND `item`.`unseen` = 1 ";
627
628                 $r = q("SELECT `item`.`id`,`item`.`parent`, `item`.`verb`, `item`.`author-name`, `item`.`unseen`,
629                                 `item`.`author-link`, `item`.`author-avatar`, `item`.`created`, `item`.`object` as `object`,
630                                 `pitem`.`author-name` as `pname`, `pitem`.`author-link` as `plink`, `pitem`.`guid` as `pguid`
631                         FROM `item` INNER JOIN `item` as `pitem` ON `pitem`.`id`=`item`.`parent`
632                         WHERE `item`.`visible` = 1 AND
633                                  `item`.`deleted` = 0 AND `item`.`uid` = %d AND `item`.`wall` = 1
634                                 $sql_seen
635                         ORDER BY `item`.`created` DESC LIMIT %d, %d ",
636                                 intval(local_user()),
637                                 intval($start),
638                                 intval($limit)
639                 );
640
641                 if(dbm::is_result($r))
642                         $notifs = $this->formatNotifs($r, $ident);
643
644                 $arr = array (
645                         'notifications' => $notifs,
646                         'ident' => $ident,
647                         'total' => $total,
648                 );
649
650                 return $arr;
651         }
652
653         /**
654          * @brief Total number of introductions 
655          * @param bool $all
656          *      If false only include introductions into the query
657          *      which aren't marked as ignored
658          * @return int Number of introductions
659          */
660         private function introTotal($all = false) {
661                 $sql_extra = "";
662
663                 if(!$all)
664                         $sql_extra = " AND `ignore` = 0 ";
665
666                 $r = q("SELECT COUNT(*) AS `total` FROM `intro`
667                         WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0 ",
668                                 intval($_SESSION['uid'])
669                 );
670
671                 if(dbm::is_result($r))
672                         return $r[0]['total'];
673
674                 return 0;
675         }
676
677         /**
678          * @brief Get introductions
679          * 
680          * @param bool $all
681          *      If false only include introductions into the query
682          *      which aren't marked as ignored
683          * @param int $start Start the query at this point
684          * @param int $limit Maximum number of query results
685          * 
686          * @return array with
687          *      string 'ident' => Notification identifier
688          *      int 'total' => Total number of available introductions
689          *      array 'notifications' => Introductions
690          */
691         public function introNotifs($all = false, $start = 0, $limit = 80) {
692                 $ident = 'introductions';
693                 $total = $this->introTotal($seen);
694                 $notifs = array();
695                 $sql_extra = "";
696
697                 if(!$all)
698                         $sql_extra = " AND `ignore` = 0 ";
699
700                 /// @todo Fetch contact details by "get_contact_details_by_url" instead of queries to contact, fcontact and gcontact
701                 $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`,
702                                 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
703                                 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
704                                 `gcontact`.`network` AS `gnetwork`
705                         FROM `intro`
706                                 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
707                                 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
708                                 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
709                         WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
710                         LIMIT %d, %d",
711                                 intval($_SESSION['uid']),
712                                 intval($start),
713                                 intval($limit)
714                 );
715
716                 if(dbm::is_result($r))
717                         $notifs = $this->formatIntros($r);
718
719                 $arr = array (
720                         'ident' => $ident,
721                         'total' => $total,
722                         'notifications' => $notifs,
723                 );
724
725                 return $arr;
726         }
727
728         /**
729          * @brief Format the notification query in an usable array
730          * 
731          * @param array $intros The array from the db query
732          * @return array with the introductions
733          */
734         private function formatIntros($intros) {
735                 $knowyou = '';
736
737                 foreach($intros as $it) {
738                         // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
739                         // We have to distinguish between these two because they use different data.
740
741                         // Contact suggestions
742                         if($it['fid']) {
743
744                                 $return_addr = bin2hex($this->a->user['nickname'] . '@' . $this->a->get_hostname() . (($this->a->path) ? '/' . $this->a->path : ''));
745
746                                 $intro = array(
747                                         'label' => 'friend_suggestion',
748                                         'notify_type' => t('Friend Suggestion'),
749                                         'intro_id' => $it['intro_id'],
750                                         'madeby' => $it['name'],
751                                         'contact_id' => $it['contact-id'],
752                                         'photo' => ((x($it,'fphoto')) ? proxy_url($it['fphoto'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
753                                         'name' => $it['fname'],
754                                         'url' => zrl($it['furl']),
755                                         'hidden' => $it['hidden'] == 1,
756                                         'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
757
758                                         'knowyou' => $knowyou,
759                                         'note' => $it['note'],
760                                         'request' => $it['frequest'] . '?addr=' . $return_addr,
761
762                                 );
763
764                         // Normal connection requests
765                         } else {
766
767                                 // Probe the contact url to get missing data
768                                 $ret = probe_url($it["url"]);
769
770                                 if ($it['gnetwork'] == "")
771                                         $it['gnetwork'] = $ret["network"];
772
773                                 // Don't show these data until you are connected. Diaspora is doing the same.
774                                 if($it['gnetwork'] === NETWORK_DIASPORA) {
775                                         $it['glocation'] = "";
776                                         $it['gabout'] = "";
777                                         $it['ggender'] = "";
778                                 }
779                                 $intro = array(
780                                         'label' => (($it['network'] !== NETWORK_OSTATUS) ? 'friend_request' : 'follower'),
781                                         'notify_type' => (($it['network'] !== NETWORK_OSTATUS) ? t('Friend/Connect Request') : t('New Follower')),
782                                         'dfrn_id' => $it['issued-id'],
783                                         'uid' => $_SESSION['uid'],
784                                         'intro_id' => $it['intro_id'],
785                                         'contact_id' => $it['contact-id'],
786                                         'photo' => ((x($it,'photo')) ? proxy_url($it['photo'], false, PROXY_SIZE_SMALL) : "images/person-175.jpg"),
787                                         'name' => $it['name'],
788                                         'location' => bbcode($it['glocation'], false, false),
789                                         'about' => bbcode($it['gabout'], false, false),
790                                         'keywords' => $it['gkeywords'],
791                                         'gender' => $it['ggender'],
792                                         'hidden' => $it['hidden'] == 1,
793                                         'post_newfriend' => (intval(get_pconfig(local_user(),'system','post_newfriend')) ? '1' : 0),
794                                         'url' => $it['url'],
795                                         'zrl' => zrl($it['url']),
796                                         'addr' => $ret['addr'],
797                                         'network' => $it['gnetwork'],
798                                         'knowyou' => $it['knowyou'],
799                                         'note' => $it['note'],
800                                 );
801                         }
802
803                         $arr[] = $intro;
804                 }
805
806                 return $arr;
807         }
808 }