]> git.mxchange.org Git - friendica.git/blob - src/Content/Item.php
Merge pull request #12076 from annando/quote
[friendica.git] / src / Content / Item.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Content;
23
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Core\Hook;
27 use Friendica\Core\L10n;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\Session\Capability\IHandleUserSessions;
31 use Friendica\Core\System;
32 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Group;
35 use Friendica\Model\Item as ItemModel;
36 use Friendica\Model\Photo;
37 use Friendica\Model\Tag;
38 use Friendica\Model\Post;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\Diaspora;
41 use Friendica\Util\Profiler;
42 use Friendica\Util\Proxy;
43 use Friendica\Util\XML;
44
45 /**
46  * A content helper class for displaying items
47  */
48 class Item
49 {
50         /** @var Activity */
51         private $activity;
52         /** @var L10n */
53         private $l10n;
54         /** @var Profiler */
55         private $profiler;
56         /** @var IHandleUserSessions */
57         private $userSession;
58
59         public function __construct(Profiler $profiler, Activity $activity, L10n $l10n, IHandleUserSessions $userSession)
60         {
61                 $this->profiler    = $profiler;
62                 $this->activity    = $activity;
63                 $this->l10n        = $l10n;
64                 $this->userSession = $userSession;
65         }
66
67         /**
68          * Return array with details for categories and folders for an item
69          *
70          * @param array $item
71          * @param int   $uid
72          * @return [array, array]
73          *
74          * [
75          *      [ // categories array
76          *          {
77          *               'name': 'category name',
78          *               'removeurl': 'url to remove this category',
79          *               'first': 'is the first in this array? true/false',
80          *               'last': 'is the last in this array? true/false',
81          *           } ,
82          *           ....
83          *       ],
84          *       [ //folders array
85          *                      {
86          *               'name': 'folder name',
87          *               'removeurl': 'url to remove this folder',
88          *               'first': 'is the first in this array? true/false',
89          *               'last': 'is the last in this array? true/false',
90          *           } ,
91          *           ....
92          *       ]
93          *  ]
94          */
95         public function determineCategoriesTerms(array $item, int $uid = 0): array
96         {
97                 $categories = [];
98                 $folders = [];
99                 $first = true;
100
101                 $uid = $item['uid'] ?: $uid;
102
103                 if (empty($item['has-categories'])) {
104                         return [$categories, $folders];
105                 }
106
107                 foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::CATEGORY) as $savedFolderName) {
108                         if (!empty($item['author-link'])) {
109                                 $url = $item['author-link'] . "?category=" . rawurlencode($savedFolderName);
110                         } else {
111                                 $url = '#';
112                         }
113                         $categories[] = [
114                                 'name' => $savedFolderName,
115                                 'url' => $url,
116                                 'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?cat=' . rawurlencode($savedFolderName) : '',
117                                 'first' => $first,
118                                 'last' => false
119                         ];
120                         $first = false;
121                 }
122
123                 if (count($categories)) {
124                         $categories[count($categories) - 1]['last'] = true;
125                 }
126
127                 if ($this->userSession->getLocalUserId() == $uid) {
128                         foreach (Post\Category::getArrayByURIId($item['uri-id'], $uid, Post\Category::FILE) as $savedFolderName) {
129                                 $folders[] = [
130                                         'name' => $savedFolderName,
131                                         'url' => "#",
132                                         'removeurl' => $this->userSession->getLocalUserId() == $uid ? 'filerm/' . $item['id'] . '?term=' . rawurlencode($savedFolderName) : '',
133                                         'first' => $first,
134                                         'last' => false
135                                 ];
136                                 $first = false;
137                         }
138                 }
139
140                 if (count($folders)) {
141                         $folders[count($folders) - 1]['last'] = true;
142                 }
143
144                 return [$categories, $folders];
145         }
146
147         /**
148          * This function removes the tag $tag from the text $body and replaces it with
149          * the appropriate link.
150          *
151          * @param string $body        the text to replace the tag in
152          * @param int    $profile_uid the user id to replace the tag for (0 = anyone)
153          * @param string $tag         the tag to replace
154          * @param string $network     The network of the post
155          *
156          * @return array|bool ['replaced' => $replaced, 'contact' => $contact] or "false" on if already replaced
157          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
158          * @throws \ImagickException
159          */
160         public static function replaceTag(string &$body, int $profile_uid, string $tag, string $network = '')
161         {
162                 $replaced = false;
163
164                 //is it a person tag?
165                 if (Tag::isType($tag, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION)) {
166                         $tag_type = substr($tag, 0, 1);
167                         //is it already replaced?
168                         if (strpos($tag, '[url=')) {
169                                 return $replaced;
170                         }
171
172                         //get the person's name
173                         $name = substr($tag, 1);
174
175                         // Sometimes the tag detection doesn't seem to work right
176                         // This is some workaround
177                         $nameparts = explode(' ', $name);
178                         $name = $nameparts[0];
179
180                         // Try to detect the contact in various ways
181                         if (strpos($name, 'http://') || strpos($name, '@')) {
182                                 $contact = Contact::getByURLForUser($name, $profile_uid);
183                         } else {
184                                 $contact = false;
185                                 $fields = ['id', 'url', 'nick', 'name', 'alias', 'network', 'forum', 'prv'];
186
187                                 if (strrpos($name, '+')) {
188                                         // Is it in format @nick+number?
189                                         $tagcid = intval(substr($name, strrpos($name, '+') + 1));
190                                         $contact = DBA::selectFirst('contact', $fields, ['id' => $tagcid, 'uid' => $profile_uid]);
191                                 }
192
193                                 // select someone by nick in the current network
194                                 if (!DBA::isResult($contact) && ($network != '')) {
195                                         $condition = ["`nick` = ? AND `network` = ? AND `uid` = ?",
196                                                 $name, $network, $profile_uid];
197                                         $contact = DBA::selectFirst('contact', $fields, $condition);
198                                 }
199
200                                 // select someone by attag in the current network
201                                 if (!DBA::isResult($contact) && ($network != '')) {
202                                         $condition = ["`attag` = ? AND `network` = ? AND `uid` = ?",
203                                                 $name, $network, $profile_uid];
204                                         $contact = DBA::selectFirst('contact', $fields, $condition);
205                                 }
206
207                                 //select someone by name in the current network
208                                 if (!DBA::isResult($contact) && ($network != '')) {
209                                         $condition = ['name' => $name, 'network' => $network, 'uid' => $profile_uid];
210                                         $contact = DBA::selectFirst('contact', $fields, $condition);
211                                 }
212
213                                 // select someone by nick in any network
214                                 if (!DBA::isResult($contact)) {
215                                         $condition = ["`nick` = ? AND `uid` = ?", $name, $profile_uid];
216                                         $contact = DBA::selectFirst('contact', $fields, $condition);
217                                 }
218
219                                 // select someone by attag in any network
220                                 if (!DBA::isResult($contact)) {
221                                         $condition = ["`attag` = ? AND `uid` = ?", $name, $profile_uid];
222                                         $contact = DBA::selectFirst('contact', $fields, $condition);
223                                 }
224
225                                 // select someone by name in any network
226                                 if (!DBA::isResult($contact)) {
227                                         $condition = ['name' => $name, 'uid' => $profile_uid];
228                                         $contact = DBA::selectFirst('contact', $fields, $condition);
229                                 }
230                         }
231
232                         // Check if $contact has been successfully loaded
233                         if (DBA::isResult($contact)) {
234                                 $profile = $contact['url'];
235                                 $newname = ($contact['name'] ?? '') ?: $contact['nick'];
236                         }
237
238                         //if there is an url for this persons profile
239                         if (isset($profile) && ($newname != '')) {
240                                 $replaced = true;
241                                 // create profile link
242                                 $profile = str_replace(',', '%2c', $profile);
243                                 $newtag = $tag_type.'[url=' . $profile . ']' . $newname . '[/url]';
244                                 $body = str_replace($tag_type . $name, $newtag, $body);
245                         }
246                 }
247
248                 return ['replaced' => $replaced, 'contact' => $contact];
249         }
250
251         /**
252          * Render actions localized
253          *
254          * @param array $item
255          * @return void
256          * @throws ImagickException
257          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
258          */
259         public function localize(array &$item)
260         {
261                 $this->profiler->startRecording('rendering');
262                 /// @todo The following functionality needs to be cleaned up.
263                 if (!empty($item['verb'])) {
264                         $xmlhead = '<?xml version="1.0" encoding="UTF-8" ?>';
265
266                         if ($this->activity->match($item['verb'], Activity::TAG)) {
267                                 $fields = ['author-id', 'author-link', 'author-name', 'author-network',
268                                         'verb', 'object-type', 'resource-id', 'body', 'plink'];
269                                 $obj = Post::selectFirst($fields, ['uri' => $item['parent-uri']]);
270                                 if (!DBA::isResult($obj)) {
271                                         $this->profiler->stopRecording();
272                                         return;
273                                 }
274
275                                 $author_arr = [
276                                         'uid' => 0,
277                                         'id' => $item['author-id'],
278                                         'network' => $item['author-network'],
279                                         'url' => $item['author-link'],
280                                 ];
281                                 $author  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $item['author-name'] . '[/url]';
282
283                                 $author_arr = [
284                                         'uid' => 0,
285                                         'id' => $obj['author-id'],
286                                         'network' => $obj['author-network'],
287                                         'url' => $obj['author-link'],
288                                 ];
289                                 $objauthor  = '[url=' . Contact::magicLinkByContact($author_arr) . ']' . $obj['author-name'] . '[/url]';
290
291                                 switch ($obj['verb']) {
292                                         case Activity::POST:
293                                                 switch ($obj['object-type']) {
294                                                         case Activity\ObjectType::EVENT:
295                                                                 $post_type = $this->l10n->t('event');
296                                                                 break;
297                                                         default:
298                                                                 $post_type = $this->l10n->t('status');
299                                                 }
300                                                 break;
301
302                                         default:
303                                                 if ($obj['resource-id']) {
304                                                         $post_type = $this->l10n->t('photo');
305                                                         $m=[]; preg_match("/\[url=([^]]*)\]/", $obj['body'], $m);
306                                                         $rr['plink'] = $m[1];
307                                                 } else {
308                                                         $post_type = $this->l10n->t('status');
309                                                 }
310                                                 // Let's break everthing ... ;-)
311                                                 break;
312                                 }
313                                 $plink = '[url=' . $obj['plink'] . ']' . $post_type . '[/url]';
314
315                                 $parsedobj = XML::parseString($xmlhead . $item['object']);
316
317                                 $tag = sprintf('#[url=%s]%s[/url]', $parsedobj->id, $parsedobj->content);
318                                 $item['body'] = $this->l10n->t('%1$s tagged %2$s\'s %3$s with %4$s', $author, $objauthor, $plink, $tag);
319                         }
320                 }
321
322                 $this->profiler->stopRecording();
323         }
324
325         /**
326          * Renders photo menu based on item
327          *
328          * @param array $item
329          * @param string $formSecurityToken
330          * @return string
331          */
332         public function photoMenu(array $item, string $formSecurityToken): string
333         {
334                 $this->profiler->startRecording('rendering');
335                 $sub_link = $contact_url = $pm_url = $status_link = '';
336                 $photos_link = $posts_link = $block_link = $ignore_link = '';
337
338                 if ($this->userSession->getLocalUserId() && $this->userSession->getLocalUserId() == $item['uid'] && $item['gravity'] == ItemModel::GRAVITY_PARENT && !$item['self'] && !$item['mention']) {
339                         $sub_link = 'javascript:doFollowThread(' . $item['id'] . '); return false;';
340                 }
341
342                 $author = [
343                         'uid' => 0,
344                         'id' => $item['author-id'],
345                         'network' => $item['author-network'],
346                         'url' => $item['author-link'],
347                 ];
348                 $profile_link = Contact::magicLinkByContact($author, $item['author-link']);
349                 $sparkle = (strpos($profile_link, 'redir/') === 0);
350
351                 $cid = 0;
352                 $pcid = $item['author-id'];
353                 $network = '';
354                 $rel = 0;
355                 $condition = ['uid' => $this->userSession->getLocalUserId(), 'uri-id' => $item['author-uri-id']];
356                 $contact = DBA::selectFirst('contact', ['id', 'network', 'rel'], $condition);
357                 if (DBA::isResult($contact)) {
358                         $cid = $contact['id'];
359                         $network = $contact['network'];
360                         $rel = $contact['rel'];
361                 }
362
363                 if ($sparkle) {
364                         $status_link = $profile_link . '/status';
365                         $photos_link = str_replace('/profile/', '/photos/', $profile_link);
366                         $profile_link = $profile_link . '/profile';
367                 }
368
369                 if (!empty($pcid)) {
370                         $contact_url = 'contact/' . $pcid;
371                         $posts_link  = $contact_url . '/posts';
372                         $block_link  = $item['self'] ? '' : $contact_url . '/block?t=' . $formSecurityToken;
373                         $ignore_link = $item['self'] ? '' : $contact_url . '/ignore?t=' . $formSecurityToken;
374                 }
375
376                 if ($cid && !$item['self']) {
377                         $contact_url = 'contact/' . $cid;
378                         $posts_link  = $contact_url . '/posts';
379
380                         if (in_array($network, [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA])) {
381                                 $pm_url = 'message/new/' . $cid;
382                         }
383                 }
384
385                 if ($this->userSession->getLocalUserId()) {
386                         $menu = [
387                                 $this->l10n->t('Follow Thread') => $sub_link,
388                                 $this->l10n->t('View Status') => $status_link,
389                                 $this->l10n->t('View Profile') => $profile_link,
390                                 $this->l10n->t('View Photos') => $photos_link,
391                                 $this->l10n->t('Network Posts') => $posts_link,
392                                 $this->l10n->t('View Contact') => $contact_url,
393                                 $this->l10n->t('Send PM') => $pm_url,
394                                 $this->l10n->t('Block') => $block_link,
395                                 $this->l10n->t('Ignore') => $ignore_link
396                         ];
397
398                         if (!empty($item['language'])) {
399                                 $menu[$this->l10n->t('Languages')] = 'javascript:alert(\'' . ItemModel::getLanguageMessage($item) . '\');';
400                         }
401
402                         if ((($cid == 0) || ($rel == Contact::FOLLOWER)) &&
403                                 in_array($item['network'], Protocol::FEDERATED)) {
404                                 $menu[$this->l10n->t('Connect/Follow')] = 'follow?url=' . urlencode($item['author-link']) . '&auto=1';
405                         }
406                 } else {
407                         $menu = [$this->l10n->t('View Profile') => $item['author-link']];
408                 }
409
410                 $args = ['item' => $item, 'menu' => $menu];
411
412                 Hook::callAll('item_photo_menu', $args);
413
414                 $menu = $args['menu'];
415
416                 $o = '';
417                 foreach ($menu as $k => $v) {
418                         if (strpos($v, 'javascript:') === 0) {
419                                 $v = substr($v, 11);
420                                 $o .= '<li role="menuitem"><a onclick="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
421                         } elseif ($v) {
422                                 $o .= '<li role="menuitem"><a href="' . $v . '">' . $k . '</a></li>' . PHP_EOL;
423                         }
424                 }
425                 $this->profiler->stopRecording();
426                 return $o;
427         }
428
429         /**
430          * Checks if the activity is visible to current user
431          *
432          * @param array $item Activity item
433          * @return bool Whether the item is visible to the user
434          */
435         public function isVisibleActivity(array $item): bool
436         {
437                 // Empty verb or hidden?
438                 if (empty($item['verb']) || $this->activity->isHidden($item['verb'])) {
439                         return false;
440                 }
441
442                 // Check conditions
443                 return (!($this->activity->match($item['verb'], Activity::FOLLOW) &&
444                         $item['object-type'] === Activity\ObjectType::NOTE &&
445                         empty($item['self']) &&
446                         $item['uid'] == $this->userSession->getLocalUserId())
447                 );
448         }
449
450         public function expandTags(array $item, bool $setPermissions = false): array
451         {
452                 // Look for any tags and linkify them
453                 $item['inform'] = '';
454                 $private_forum  = false;
455                 $private_id     = null;
456                 $only_to_forum  = false;
457                 $forum_contact  = [];
458                 $receivers      = [];
459
460                 // Convert mentions in the body to a unified format
461                 $item['body'] = BBCode::setMentions($item['body'], $item['uid'], $item['network']);
462
463                 // Search for forum mentions
464                 foreach (Tag::getFromBody($item['body'], Tag::TAG_CHARACTER[Tag::MENTION] . Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]) as $tag) {
465                         $contact = Contact::getByURLForUser($tag[2], $item['uid']);
466                         if (empty($contact)) {
467                                 continue;
468                         }
469
470                         $receivers[] = $contact['id'];
471
472                         if (!empty($item['inform'])) {
473                                 $item['inform'] .= ',';
474                         }
475                         $item['inform'] .= 'cid:' . $contact['id'];
476
477                         if (($item['gravity'] == ItemModel::GRAVITY_COMMENT) || empty($contact['cid']) || ($contact['contact-type'] != Contact::TYPE_COMMUNITY)) {
478                                 continue;
479                         }
480
481                         if (!empty($contact['prv']) || ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION])) {
482                                 $private_forum = $contact['prv'];
483                                 $only_to_forum = ($tag[1] == Tag::TAG_CHARACTER[Tag::EXCLUSIVE_MENTION]);
484                                 $private_id = $contact['id'];
485                                 $forum_contact = $contact;
486                                 Logger::info('Private forum or exclusive mention', ['url' => $tag[2], 'mention' => $tag[1]]);
487                         } elseif ($item['allow_cid'] == '<' . $contact['id'] . '>') {
488                                 $private_forum = false;
489                                 $only_to_forum = true;
490                                 $private_id = $contact['id'];
491                                 $forum_contact = $contact;
492                                 Logger::info('Public forum', ['url' => $tag[2], 'mention' => $tag[1]]);
493                         } else {
494                                 Logger::info('Post with forum mention will not be converted to a forum post', ['url' => $tag[2], 'mention' => $tag[1]]);
495                         }
496                 }
497                 Logger::info('Got inform', ['inform' => $item['inform']]);
498
499                 if (($item['gravity'] == ItemModel::GRAVITY_PARENT) && !empty($forum_contact) && ($private_forum || $only_to_forum)) {
500                         // we tagged a forum in a top level post. Now we change the post
501                         $item['private'] = $private_forum ? ItemModel::PRIVATE : ItemModel::UNLISTED;
502
503                         if ($only_to_forum) {
504                                 $item['postopts'] = '';
505                         }
506
507                         $item['deny_cid'] = '';
508                         $item['deny_gid'] = '';
509
510                         if ($private_forum) {
511                                 $item['allow_cid'] = '<' . $private_id . '>';
512                                 $item['allow_gid'] = '<' . Group::getIdForForum($forum_contact['id']) . '>';
513                         } else {
514                                 $item['allow_cid'] = '';
515                                 $item['allow_gid'] = '';
516                         }
517                 } elseif ($setPermissions && ($item['gravity'] == ItemModel::GRAVITY_PARENT)) {
518                         if (empty($receivers)) {
519                                 // For security reasons direct posts without any receiver will be posts to yourself
520                                 $self = Contact::selectFirst(['id'], ['uid' => $item['uid'], 'self' => true]);
521                                 $receivers[] = $self['id'];
522                         }
523
524                         $item['private']   = ItemModel::PRIVATE;
525                         $item['allow_cid'] = '';
526                         $item['allow_gid'] = '';
527                         $item['deny_cid']  = '';
528                         $item['deny_gid']  = '';
529
530                         foreach ($receivers as $receiver) {
531                                 $item['allow_cid'] .= '<' . $receiver . '>';
532                         }
533                 }
534                 return $item;
535         }
536
537         public function getAuthorAvatar(array $item): string
538         {
539                 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
540                         $author_avatar  = $item['contact-id'];
541                         $author_updated = '';
542                         $author_thumb   = $item['contact-avatar'];
543                 } else {
544                         $author_avatar  = $item['author-id'];
545                         $author_updated = $item['author-updated'];
546                         $author_thumb   = $item['author-avatar'];
547                 }
548
549
550                 if (empty($author_thumb) || Photo::isPhotoURI($author_thumb)) {
551                         $author_thumb = Contact::getAvatarUrlForId($author_avatar, Proxy::SIZE_THUMB, $author_updated);
552                 }
553
554                 return $author_thumb;
555         }
556
557         public function getOwnerAvatar(array $item): string
558         {
559                 if (in_array($item['network'], [Protocol::FEED, Protocol::MAIL])) {
560                         $owner_avatar  = $item['contact-id'];
561                         $owner_updated = '';
562                         $owner_thumb   = $item['contact-avatar'];
563                 } else {
564                         $owner_avatar   = $item['owner-id'];
565                         $owner_updated  = $item['owner-updated'];
566                         $owner_thumb    = $item['owner-avatar'];
567                 }
568
569                 if (empty($owner_thumb) || Photo::isPhotoURI($owner_thumb)) {
570                         $owner_thumb = Contact::getAvatarUrlForId($owner_avatar, Proxy::SIZE_THUMB, $owner_updated);
571                 }
572
573                 return $owner_thumb;
574         }
575
576         /**
577          * Add a share block for the given uri-id
578          *
579          * @param array  $item
580          * @param string $body
581          * @return string
582          */
583         public function addSharedPost(array $item, string $body = ''): string
584         {
585                 if (empty($body)) {
586                         $body = $item['body'];
587                 }
588
589                 if (empty($item['quote-uri-id'])) {
590                         return $body;
591                 }
592
593                 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'];
594                 $shared_item = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [$item['uid'], 0], 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
595                 if (!DBA::isResult($shared_item)) {
596                         Logger::notice('Post does not exist.', ['uri-id' => $item['quote-uri-id'], 'uid' => $item['uid']]);
597                         return $body;
598                 }
599
600                 return $body . "\n" . $this->createSharedBlockByArray($shared_item, true);
601         }
602
603         /**
604          * Add a share block for the given guid
605          *
606          * @param string $guid
607          * @param integer $uid
608          * @param bool $add_media
609          * @return string
610          */
611         private function createSharedPostByGuid(string $guid, bool $add_media): string
612         {
613                 $fields = ['uri-id', 'uri', 'body', 'title', 'author-name', 'author-link', 'author-avatar', 'guid', 'created', 'plink', 'network'];
614                 $shared_item = Post::selectFirst($fields, ['guid' => $guid, 'uid' => 0, 'private' => [ItemModel::PUBLIC, ItemModel::UNLISTED]]);
615
616                 if (!DBA::isResult($shared_item)) {
617                         Logger::notice('Post does not exist.', ['guid' => $guid]);
618                         return '';
619                 }
620
621                 return $this->createSharedBlockByArray($shared_item, $add_media);
622         }
623
624         /**
625          * Add a share block for the given item array
626          *
627          * @param array $item
628          * @param bool $add_media
629          * @return string
630          */
631         public function createSharedBlockByArray(array $item, bool $add_media = false): string
632         {
633                 if ($item['network'] == Protocol::FEED) {
634                         return PageInfo::getFooterFromUrl($item['plink']);
635                 } elseif (!in_array($item['network'] ?? '', Protocol::FEDERATED)) {
636                         $item['guid'] = '';
637                         $item['uri']  = '';
638                 }
639
640                 if ($add_media) {
641                         $item['body'] = Post\Media::addAttachmentsToBody($item['uri-id'], $item['body']);
642                 }
643
644                 $shared_content = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'], $item['plink'], $item['created'], $item['guid'], $item['uri']);
645
646                 if (!empty($item['title'])) {
647                         $shared_content .= '[h3]' . $item['title'] . "[/h3]\n";
648                 }
649
650                 $shared = $this->getShareArray($item);
651
652                 // If it is a reshared post then reformat it to avoid display problems with two share elements
653                 if (!empty($shared)) {
654                         if (!empty($shared['guid']) && ($encaspulated_share = $this->createSharedPostByGuid($shared['guid'], $add_media))) {
655                                 $item['body'] = preg_replace("/\[share.*?\](.*)\[\/share\]/ism", $encaspulated_share, $item['body']);
656                         }
657
658                         $item['body'] = HTML::toBBCode(BBCode::convertForUriId($item['uri-id'], $item['body'], BBCode::ACTIVITYPUB));
659                 }
660
661                 $shared_content .= $item['body'] . '[/share]';
662
663                 return $shared_content;
664         }
665
666         /**
667          * Return the shared post from an item array (if the item is shared item)
668          *
669          * @param array $item
670          * @param array $fields
671          *
672          * @return array with the shared post
673          */
674         public function getSharedPost(array $item, array $fields = []): array
675         {
676                 if (!empty($item['quote-uri-id'])) {
677                         $shared = Post::selectFirst($fields, ['uri-id' => $item['quote-uri-id'], 'uid' => [0, $item['uid'] ?? 0]]);
678                         if (is_array($shared)) {
679                                 return [
680                                         'comment' => BBCode::removeSharedData($item['body'] ?? ''),
681                                         'post'    => $shared
682                                 ];
683                         }
684                 }
685
686                 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
687                 if (!empty($attributes)) {
688                         $shared = Post::selectFirst($fields, ['guid' => $attributes['guid'], 'uid' => [0, $item['uid'] ?? 0]]);
689                         if (is_array($shared)) {
690                                 return [
691                                         'comment' => $attributes['comment'],
692                                         'post'    => $shared
693                                 ];
694                         }
695                 }
696
697                 return [];
698         }
699
700         /**
701          * Return share data from an item array (if the item is shared item)
702          * We are providing the complete Item array, because at some time in the future
703          * we hopefully will define these values not in the body anymore but in some item fields.
704          * This function is meant to replace all similar functions in the system.
705          *
706          * @param array $item
707          *
708          * @return array with share information
709          */
710         private function getShareArray(array $item): array
711         {
712                 $attributes = BBCode::fetchShareAttributes($item['body'] ?? '');
713                 if (!empty($attributes)) {
714                         return $attributes;
715                 }
716
717                 if (!empty($item['quote-uri-id'])) {
718                         $shared = Post::selectFirst(['author-name', 'author-link', 'author-avatar', 'plink', 'created', 'guid', 'uri', 'body'], ['uri-id' => $item['quote-uri-id']]);
719                         if (!empty($shared)) {
720                                 return [
721                                         'author'     => $shared['author-name'],
722                                         'profile'    => $shared['author-link'],
723                                         'avatar'     => $shared['author-avatar'],
724                                         'link'       => $shared['plink'],
725                                         'posted'     => $shared['created'],
726                                         'guid'       => $shared['guid'],
727                                         'message_id' => $shared['uri'],
728                                         'comment'    => $item['body'],
729                                         'shared'     => $shared['body'],
730                                 ];                              
731                         }
732                 }
733
734                 return [];
735         }
736
737         /**
738          * Add a link to a shared post at the end of the post 
739          *
740          * @param string  $body
741          * @param integer $quote_uri_id
742          * @return string
743          */
744         public function addShareLink(string $body, int $quote_uri_id): string
745         {
746                 $post = Post::selectFirstPost(['uri', 'plink'], ['uri-id' => $quote_uri_id]);
747                 if (empty($post)) {
748                         return $body;
749                 }
750
751                 $body .= "\n♲ " . ($post['plink'] ?: $post['uri']);
752
753                 return $body;
754         }
755 }