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