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