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