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