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