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