Merge branch '2018.08-rc'
[friendica.git/.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\BaseObject;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\Protocol;
13 use Friendica\Database\DBA;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Util\DateTimeFormat;
17 use Friendica\Util\Proxy as ProxyUtils;
18 use Friendica\Util\Temporal;
19 use Friendica\Util\XML;
20
21 require_once 'include/dba.php';
22
23 /**
24  * @brief Methods for read and write notifications from/to database
25  *  or for formatting notifications
26  */
27 class NotificationsManager extends BaseObject
28 {
29         /**
30          * @brief set some extra note properties
31          *
32          * @param array $notes array of note arrays from db
33          * @return array Copy of input array with added properties
34          *
35          * Set some extra properties to note array from db:
36          *  - timestamp as int in default TZ
37          *  - date_rel : relative date string
38          *  - msg_html: message as html string
39          *  - msg_plain: message as plain text string
40          */
41         private function _set_extra($notes)
42         {
43                 $rets = [];
44                 foreach ($notes as $n) {
45                         $local_time = DateTimeFormat::local($n['date']);
46                         $n['timestamp'] = strtotime($local_time);
47                         $n['date_rel'] = Temporal::getRelativeDate($n['date']);
48                         $n['msg_html'] = BBCode::convert($n['msg'], false);
49                         $n['msg_plain'] = explode("\n", trim(HTML::toPlaintext($n['msg_html'], 0)))[0];
50
51                         $rets[] = $n;
52                 }
53                 return $rets;
54         }
55
56         /**
57          * @brief Get all notifications for local_user()
58          *
59          * @param array  $filter optional Array "column name"=>value: filter query by columns values
60          * @param string $order  optional Space separated list of column to sort by.
61          *                       Prepend name with "+" to sort ASC, "-" to sort DESC. Default to "-date"
62          * @param string $limit  optional Query limits
63          *
64          * @return array of results or false on errors
65          */
66         public function getAll($filter = [], $order = "-date", $limit = "")
67         {
68                 $filter_str = [];
69                 $filter_sql = "";
70                 foreach ($filter as $column => $value) {
71                         $filter_str[] = sprintf("`%s` = '%s'", $column, DBA::escape($value));
72                 }
73                 if (count($filter_str) > 0) {
74                         $filter_sql = "AND " . implode(" AND ", $filter_str);
75                 }
76
77                 $aOrder = explode(" ", $order);
78                 $asOrder = [];
79                 foreach ($aOrder as $o) {
80                         $dir = "asc";
81                         if ($o[0] === "-") {
82                                 $dir = "desc";
83                                 $o = substr($o, 1);
84                         }
85                         if ($o[0] === "+") {
86                                 $dir = "asc";
87                                 $o = substr($o, 1);
88                         }
89                         $asOrder[] = "$o $dir";
90                 }
91                 $order_sql = implode(", ", $asOrder);
92
93                 if ($limit != "") {
94                         $limit = " LIMIT " . $limit;
95                 }
96                 $r = q(
97                         "SELECT * FROM `notify` WHERE `uid` = %d $filter_sql ORDER BY $order_sql $limit",
98                         intval(local_user())
99                 );
100
101                 if (DBA::isResult($r)) {
102                         return $this->_set_extra($r);
103                 }
104
105                 return false;
106         }
107
108         /**
109          * @brief Get one note for local_user() by $id value
110          *
111          * @param int $id identity
112          * @return array note values or null if not found
113          */
114         public function getByID($id)
115         {
116                 $r = q(
117                         "SELECT * FROM `notify` WHERE `id` = %d AND `uid` = %d LIMIT 1",
118                         intval($id),
119                         intval(local_user())
120                 );
121                 if (DBA::isResult($r)) {
122                         return $this->_set_extra($r)[0];
123                 }
124                 return null;
125         }
126
127         /**
128          * @brief set seen state of $note of local_user()
129          *
130          * @param array $note note array
131          * @param bool  $seen optional true or false, default true
132          * @return bool true on success, false on errors
133          */
134         public function setSeen($note, $seen = true)
135         {
136                 return q(
137                         "UPDATE `notify` SET `seen` = %d WHERE (`link` = '%s' OR (`parent` != 0 AND `parent` = %d AND `otype` = '%s')) AND `uid` = %d",
138                         intval($seen),
139                         DBA::escape($note['link']),
140                         intval($note['parent']),
141                         DBA::escape($note['otype']),
142                         intval(local_user())
143                 );
144         }
145
146         /**
147          * @brief set seen state of all notifications of local_user()
148          *
149          * @param bool $seen optional true or false. default true
150          * @return bool true on success, false on error
151          */
152         public function setAllSeen($seen = true)
153         {
154                 return q(
155                         "UPDATE `notify` SET `seen` = %d WHERE `uid` = %d",
156                         intval($seen),
157                         intval(local_user())
158                 );
159         }
160
161         /**
162          * @brief List of pages for the Notifications TabBar
163          *
164          * @return array with with notifications TabBar data
165          */
166         public function getTabs()
167         {
168                 $selected = defaults(self::getApp()->argv, 1, '');
169
170                 $tabs = [
171                         [
172                                 'label' => L10n::t('System'),
173                                 'url'   => 'notifications/system',
174                                 'sel'   => (($selected == 'system') ? 'active' : ''),
175                                 'id'    => 'system-tab',
176                                 'accesskey' => 'y',
177                         ],
178                         [
179                                 'label' => L10n::t('Network'),
180                                 'url'   => 'notifications/network',
181                                 'sel'   => (($selected == 'network') ? 'active' : ''),
182                                 'id'    => 'network-tab',
183                                 'accesskey' => 'w',
184                         ],
185                         [
186                                 'label' => L10n::t('Personal'),
187                                 'url'   => 'notifications/personal',
188                                 'sel'   => (($selected == 'personal') ? 'active' : ''),
189                                 'id'    => 'personal-tab',
190                                 'accesskey' => 'r',
191                         ],
192                         [
193                                 'label' => L10n::t('Home'),
194                                 'url'   => 'notifications/home',
195                                 'sel'   => (($selected == 'home') ? 'active' : ''),
196                                 'id'    => 'home-tab',
197                                 'accesskey' => 'h',
198                         ],
199                         [
200                                 'label' => L10n::t('Introductions'),
201                                 'url'   => 'notifications/intros',
202                                 'sel'   => (($selected == 'intros') ? 'active' : ''),
203                                 'id'    => 'intro-tab',
204                                 'accesskey' => 'i',
205                         ],
206                 ];
207
208                 return $tabs;
209         }
210
211         /**
212          * @brief Format the notification query in an usable array
213          *
214          * @param array  $notifs The array from the db query
215          * @param string $ident  The notifications identifier (e.g. network)
216          * @return array
217          *      string 'label' => The type of the notification
218          *      string 'link' => URL to the source
219          *      string 'image' => The avatar image
220          *      string 'url' => The profile url of the contact
221          *      string 'text' => The notification text
222          *      string 'when' => The date of the notification
223          *      string 'ago' => T relative date of the notification
224          *      bool 'seen' => Is the notification marked as "seen"
225          */
226         private function formatNotifs(array $notifs, $ident = "")
227         {
228                 $notif = [];
229                 $arr = [];
230
231                 if (DBA::isResult($notifs)) {
232                         foreach ($notifs as $it) {
233                                 // Because we use different db tables for the notification query
234                                 // we have sometimes $it['unseen'] and sometimes $it['seen].
235                                 // So we will have to transform $it['unseen']
236                                 if (array_key_exists('unseen', $it)) {
237                                         $it['seen'] = ($it['unseen'] > 0 ? false : true);
238                                 }
239
240                                 // For feed items we use the user's contact, since the avatar is mostly self choosen.
241                                 if (!empty($it['network']) && $it['network'] == Protocol::FEED) {
242                                         $it['author-avatar'] = $it['contact-avatar'];
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 = ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_MICRO);
251                                                 $default_item_url = $it['url'];
252                                                 $default_item_text = strip_tags(BBCode::convert($it['msg']));
253                                                 $default_item_when = DateTimeFormat::local($it['date'], 'r');
254                                                 $default_item_ago = Temporal::getRelativeDate($it['date']);
255                                                 break;
256
257                                         case 'home':
258                                                 $default_item_label = 'comment';
259                                                 $default_item_link = System::baseUrl(true) . '/display/' . $it['parent-guid'];
260                                                 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
261                                                 $default_item_url = $it['author-link'];
262                                                 $default_item_text = L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']);
263                                                 $default_item_when = DateTimeFormat::local($it['created'], 'r');
264                                                 $default_item_ago = Temporal::getRelativeDate($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['parent-guid'];
270                                                 $default_item_image = ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO);
271                                                 $default_item_url = $it['author-link'];
272                                                 $default_item_text = (($it['id'] == $it['parent'])
273                                                                         ? L10n::t("%s created a new post", $it['author-name'])
274                                                                         : L10n::t("%s commented on %s's post", $it['author-name'], $it['parent-author-name']));
275                                                 $default_item_when = DateTimeFormat::local($it['created'], 'r');
276                                                 $default_item_ago = Temporal::getRelativeDate($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 = [
283                                                         'label' => 'like',
284                                                         'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
285                                                         'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
286                                                         'url' => $it['author-link'],
287                                                         'text' => L10n::t("%s liked %s's post", $it['author-name'], $it['parent-author-name']),
288                                                         'when' => $default_item_when,
289                                                         'ago' => $default_item_ago,
290                                                         'seen' => $it['seen']
291                                                 ];
292                                                 break;
293
294                                         case ACTIVITY_DISLIKE:
295                                                 $notif = [
296                                                         'label' => 'dislike',
297                                                         'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
298                                                         'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
299                                                         'url' => $it['author-link'],
300                                                         'text' => L10n::t("%s disliked %s's post", $it['author-name'], $it['parent-author-name']),
301                                                         'when' => $default_item_when,
302                                                         'ago' => $default_item_ago,
303                                                         'seen' => $it['seen']
304                                                 ];
305                                                 break;
306
307                                         case ACTIVITY_ATTEND:
308                                                 $notif = [
309                                                         'label' => 'attend',
310                                                         'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
311                                                         'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
312                                                         'url' => $it['author-link'],
313                                                         'text' => L10n::t("%s is attending %s's event", $it['author-name'], $it['parent-author-name']),
314                                                         'when' => $default_item_when,
315                                                         'ago' => $default_item_ago,
316                                                         'seen' => $it['seen']
317                                                 ];
318                                                 break;
319
320                                         case ACTIVITY_ATTENDNO:
321                                                 $notif = [
322                                                         'label' => 'attendno',
323                                                         'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
324                                                         'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
325                                                         'url' => $it['author-link'],
326                                                         'text' => L10n::t("%s is not attending %s's event", $it['author-name'], $it['parent-author-name']),
327                                                         'when' => $default_item_when,
328                                                         'ago' => $default_item_ago,
329                                                         'seen' => $it['seen']
330                                                 ];
331                                                 break;
332
333                                         case ACTIVITY_ATTENDMAYBE:
334                                                 $notif = [
335                                                         'label' => 'attendmaybe',
336                                                         'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
337                                                         'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
338                                                         'url' => $it['author-link'],
339                                                         'text' => L10n::t("%s may attend %s's event", $it['author-name'], $it['parent-author-name']),
340                                                         'when' => $default_item_when,
341                                                         'ago' => $default_item_ago,
342                                                         'seen' => $it['seen']
343                                                 ];
344                                                 break;
345
346                                         case ACTIVITY_FRIEND:
347                                                 if (!isset($it['object'])) {
348                                                         $notif = [
349                                                                 'label' => 'friend',
350                                                                 'link' => $default_item_link,
351                                                                 'image' => $default_item_image,
352                                                                 'url' => $default_item_url,
353                                                                 'text' => $default_item_text,
354                                                                 'when' => $default_item_when,
355                                                                 'ago' => $default_item_ago,
356                                                                 'seen' => $it['seen']
357                                                         ];
358                                                         break;
359                                                 }
360                                                 /// @todo Check if this part here is used at all
361                                                 logger('Complete data: ' . json_encode($it) . ' - ' . System::callstack(20), LOGGER_DEBUG);
362
363                                                 $xmlhead = "<" . "?xml version='1.0' encoding='UTF-8' ?" . ">";
364                                                 $obj = XML::parseString($xmlhead . $it['object']);
365                                                 $it['fname'] = $obj->title;
366
367                                                 $notif = [
368                                                         'label' => 'friend',
369                                                         'link' => System::baseUrl(true) . '/display/' . $it['parent-guid'],
370                                                         'image' => ProxyUtils::proxifyUrl($it['author-avatar'], false, ProxyUtils::SIZE_MICRO),
371                                                         'url' => $it['author-link'],
372                                                         'text' => L10n::t("%s is now friends with %s", $it['author-name'], $it['fname']),
373                                                         'when' => $default_item_when,
374                                                         'ago' => $default_item_ago,
375                                                         'seen' => $it['seen']
376                                                 ];
377                                                 break;
378
379                                         default:
380                                                 $notif = [
381                                                         'label' => $default_item_label,
382                                                         'link' => $default_item_link,
383                                                         'image' => $default_item_image,
384                                                         'url' => $default_item_url,
385                                                         'text' => $default_item_text,
386                                                         'when' => $default_item_when,
387                                                         'ago' => $default_item_ago,
388                                                         'seen' => $it['seen']
389                                                 ];
390                                 }
391
392                                 $arr[] = $notif;
393                         }
394                 }
395
396                 return $arr;
397         }
398
399         /**
400          * @brief Get network notifications
401          *
402          * @param int|string $seen  If 0 only include notifications into the query
403          *                              which aren't marked as "seen"
404          * @param int        $start Start the query at this point
405          * @param int        $limit Maximum number of query results
406          *
407          * @return array with
408          *      string 'ident' => Notification identifier
409          *      array 'notifications' => Network notifications
410          */
411         public function networkNotifs($seen = 0, $start = 0, $limit = 80)
412         {
413                 $ident = 'network';
414                 $notifs = [];
415
416                 $condition = ['wall' => false, 'uid' => local_user()];
417
418                 if ($seen === 0) {
419                         $condition['unseen'] = true;
420                 }
421
422                 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
423                         'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
424                 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
425
426                 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
427
428                 if (DBA::isResult($items)) {
429                         $notifs = $this->formatNotifs(Item::inArray($items), $ident);
430                 }
431
432                 $arr = [
433                         'notifications' => $notifs,
434                         'ident' => $ident,
435                 ];
436
437                 return $arr;
438         }
439
440         /**
441          * @brief Get system notifications
442          *
443          * @param int|string $seen  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          *      array 'notifications' => System notifications
451          */
452         public function systemNotifs($seen = 0, $start = 0, $limit = 80)
453         {
454                 $ident = 'system';
455                 $notifs = [];
456                 $sql_seen = "";
457
458                 if ($seen === 0) {
459                         $sql_seen = " AND NOT `seen` ";
460                 }
461
462                 $r = q(
463                         "SELECT `id`, `url`, `photo`, `msg`, `date`, `seen`, `verb` FROM `notify`
464                                 WHERE `uid` = %d $sql_seen ORDER BY `date` DESC LIMIT %d, %d ",
465                         intval(local_user()),
466                         intval($start),
467                         intval($limit)
468                 );
469
470                 if (DBA::isResult($r)) {
471                         $notifs = $this->formatNotifs($r, $ident);
472                 }
473
474                 $arr = [
475                         'notifications' => $notifs,
476                         'ident' => $ident,
477                 ];
478
479                 return $arr;
480         }
481
482         /**
483          * @brief Get personal notifications
484          *
485          * @param int|string $seen  If 0 only include notifications into the query
486          *                              which aren't marked as "seen"
487          * @param int        $start Start the query at this point
488          * @param int        $limit Maximum number of query results
489          *
490          * @return array with
491          *      string 'ident' => Notification identifier
492          *      array 'notifications' => Personal notifications
493          */
494         public function personalNotifs($seen = 0, $start = 0, $limit = 80)
495         {
496                 $ident = 'personal';
497                 $notifs = [];
498
499                 $myurl = str_replace('http://', '', self::getApp()->contact['nurl']);
500                 $diasp_url = str_replace('/profile/', '/u/', $myurl);
501
502                 $condition = ["NOT `wall` AND `uid` = ? AND (`item`.`author-id` = ? OR `item`.`tag` REGEXP ? OR `item`.`tag` REGEXP ?)",
503                         local_user(), public_contact(), $myurl . '\\]', $diasp_url . '\\]'];
504
505                 if ($seen === 0) {
506                         $condition[0] .= " AND `unseen`";
507                 }
508
509                 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
510                         'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
511                 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
512
513                 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
514
515                 if (DBA::isResult($items)) {
516                         $notifs = $this->formatNotifs(Item::inArray($items), $ident);
517                 }
518
519                 $arr = [
520                         'notifications' => $notifs,
521                         'ident' => $ident,
522                 ];
523
524                 return $arr;
525         }
526
527         /**
528          * @brief Get home notifications
529          *
530          * @param int|string $seen  If 0 only include notifications into the query
531          *                              which aren't marked as "seen"
532          * @param int        $start Start the query at this point
533          * @param int        $limit Maximum number of query results
534          *
535          * @return array with
536          *      string 'ident' => Notification identifier
537          *      array 'notifications' => Home notifications
538          */
539         public function homeNotifs($seen = 0, $start = 0, $limit = 80)
540         {
541                 $ident = 'home';
542                 $notifs = [];
543
544                 $condition = ['wall' => true, 'uid' => local_user()];
545
546                 if ($seen === 0) {
547                         $condition['unseen'] = true;
548                 }
549
550                 $fields = ['id', 'parent', 'verb', 'author-name', 'unseen', 'author-link', 'author-avatar', 'contact-avatar',
551                         'network', 'created', 'object', 'parent-author-name', 'parent-author-link', 'parent-guid'];
552                 $params = ['order' => ['created' => true], 'limit' => [$start, $limit]];
553                 $items = Item::selectForUser(local_user(), $fields, $condition, $params);
554
555                 if (DBA::isResult($items)) {
556                         $notifs = $this->formatNotifs(Item::inArray($items), $ident);
557                 }
558
559                 $arr = [
560                         'notifications' => $notifs,
561                         'ident' => $ident,
562                 ];
563
564                 return $arr;
565         }
566
567         /**
568          * @brief Get introductions
569          *
570          * @param bool $all   If false only include introductions into the query
571          *                        which aren't marked as ignored
572          * @param int  $start Start the query at this point
573          * @param int  $limit Maximum number of query results
574          *
575          * @return array with
576          *      string 'ident' => Notification identifier
577          *      array 'notifications' => Introductions
578          */
579         public function introNotifs($all = false, $start = 0, $limit = 80)
580         {
581                 $ident = 'introductions';
582                 $notifs = [];
583                 $sql_extra = "";
584
585                 if (!$all) {
586                         $sql_extra = " AND `ignore` = 0 ";
587                 }
588
589                 /// @todo Fetch contact details by "Contact::getDetailsByUrl" instead of queries to contact, fcontact and gcontact
590                 $r = q(
591                         "SELECT `intro`.`id` AS `intro_id`, `intro`.*, `contact`.*,
592                                 `fcontact`.`name` AS `fname`, `fcontact`.`url` AS `furl`, `fcontact`.`addr` AS `faddr`,
593                                 `fcontact`.`photo` AS `fphoto`, `fcontact`.`request` AS `frequest`,
594                                 `gcontact`.`location` AS `glocation`, `gcontact`.`about` AS `gabout`,
595                                 `gcontact`.`keywords` AS `gkeywords`, `gcontact`.`gender` AS `ggender`,
596                                 `gcontact`.`network` AS `gnetwork`, `gcontact`.`addr` AS `gaddr`
597                         FROM `intro`
598                                 LEFT JOIN `contact` ON `contact`.`id` = `intro`.`contact-id`
599                                 LEFT JOIN `gcontact` ON `gcontact`.`nurl` = `contact`.`nurl`
600                                 LEFT JOIN `fcontact` ON `intro`.`fid` = `fcontact`.`id`
601                         WHERE `intro`.`uid` = %d $sql_extra AND `intro`.`blocked` = 0
602                         LIMIT %d, %d",
603                         intval($_SESSION['uid']),
604                         intval($start),
605                         intval($limit)
606                 );
607                 if (DBA::isResult($r)) {
608                         $notifs = $this->formatIntros($r);
609                 }
610
611                 $arr = [
612                         'ident' => $ident,
613                         'notifications' => $notifs,
614                 ];
615
616                 return $arr;
617         }
618
619         /**
620          * @brief Format the notification query in an usable array
621          *
622          * @param array $intros The array from the db query
623          * @return array with the introductions
624          */
625         private function formatIntros($intros)
626         {
627                 $knowyou = '';
628
629                 foreach ($intros as $it) {
630                         // There are two kind of introduction. Contacts suggested by other contacts and normal connection requests.
631                         // We have to distinguish between these two because they use different data.
632                         // Contact suggestions
633                         if ($it['fid']) {
634                                 $return_addr = bin2hex(self::getApp()->user['nickname'] . '@' . self::getApp()->get_hostname() . ((self::getApp()->urlpath) ? '/' . self::getApp()->urlpath : ''));
635
636                                 $intro = [
637                                         'label' => 'friend_suggestion',
638                                         'notify_type' => L10n::t('Friend Suggestion'),
639                                         'intro_id' => $it['intro_id'],
640                                         'madeby' => $it['name'],
641                                         'madeby_url' => $it['url'],
642                                         'madeby_zrl' => Contact::magicLink($it['url']),
643                                         'madeby_addr' => $it['addr'],
644                                         'contact_id' => $it['contact-id'],
645                                         'photo' => ((x($it, 'fphoto')) ? ProxyUtils::proxifyUrl($it['fphoto'], false, ProxyUtils::SIZE_SMALL) : "images/person-175.jpg"),
646                                         'name' => $it['fname'],
647                                         'url' => $it['furl'],
648                                         'zrl' => Contact::magicLink($it['furl']),
649                                         'hidden' => $it['hidden'] == 1,
650                                         'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
651                                         'knowyou' => $knowyou,
652                                         'note' => $it['note'],
653                                         'request' => $it['frequest'] . '?addr=' . $return_addr,
654                                 ];
655
656                                 // Normal connection requests
657                         } else {
658                                 $it = $this->getMissingIntroData($it);
659
660                                 if (empty($it['url'])) {
661                                         continue;
662                                 }
663
664                                 // Don't show these data until you are connected. Diaspora is doing the same.
665                                 if ($it['gnetwork'] === Protocol::DIASPORA) {
666                                         $it['glocation'] = "";
667                                         $it['gabout'] = "";
668                                         $it['ggender'] = "";
669                                 }
670                                 $intro = [
671                                         'label' => (($it['network'] !== Protocol::OSTATUS) ? 'friend_request' : 'follower'),
672                                         'notify_type' => (($it['network'] !== Protocol::OSTATUS) ? L10n::t('Friend/Connect Request') : L10n::t('New Follower')),
673                                         'dfrn_id' => $it['issued-id'],
674                                         'uid' => $_SESSION['uid'],
675                                         'intro_id' => $it['intro_id'],
676                                         'contact_id' => $it['contact-id'],
677                                         'photo' => ((x($it, 'photo')) ? ProxyUtils::proxifyUrl($it['photo'], false, ProxyUtils::SIZE_SMALL) : "images/person-175.jpg"),
678                                         'name' => $it['name'],
679                                         'location' => BBCode::convert($it['glocation'], false),
680                                         'about' => BBCode::convert($it['gabout'], false),
681                                         'keywords' => $it['gkeywords'],
682                                         'gender' => $it['ggender'],
683                                         'hidden' => $it['hidden'] == 1,
684                                         'post_newfriend' => (intval(PConfig::get(local_user(), 'system', 'post_newfriend')) ? '1' : 0),
685                                         'url' => $it['url'],
686                                         'zrl' => Contact::magicLink($it['url']),
687                                         'addr' => $it['gaddr'],
688                                         'network' => $it['gnetwork'],
689                                         'knowyou' => $it['knowyou'],
690                                         'note' => $it['note'],
691                                 ];
692                         }
693
694                         $arr[] = $intro;
695                 }
696
697                 return $arr;
698         }
699
700         /**
701          * @brief Check for missing contact data and try to fetch the data from
702          *     from other sources
703          *
704          * @param array $arr The input array with the intro data
705          *
706          * @return array The array with the intro data
707          */
708         private function getMissingIntroData($arr)
709         {
710                 // If the network and the addr isn't available from the gcontact
711                 // table entry, take the one of the contact table entry
712                 if (empty($arr['gnetwork']) && !empty($arr['network'])) {
713                         $arr['gnetwork'] = $arr['network'];
714                 }
715                 if (empty($arr['gaddr']) && !empty($arr['addr'])) {
716                         $arr['gaddr'] = $arr['addr'];
717                 }
718
719                 // If the network and addr is still not available
720                 // get the missing data data from other sources
721                 if (empty($arr['gnetwork']) || empty($arr['gaddr'])) {
722                         $ret = Contact::getDetailsByURL($arr['url']);
723
724                         if (empty($arr['gnetwork']) && !empty($ret['network'])) {
725                                 $arr['gnetwork'] = $ret['network'];
726                         }
727                         if (empty($arr['gaddr']) && !empty($ret['addr'])) {
728                                 $arr['gaddr'] = $ret['addr'];
729                         }
730                 }
731
732                 return $arr;
733         }
734 }