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