]> git.mxchange.org Git - friendica.git/blob - src/Model/Post/Media.php
Merge pull request #10807 from annando/emoji-media
[friendica.git] / src / Model / Post / Media.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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\Model\Post;
23
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Core\Logger;
26 use Friendica\Core\System;
27 use Friendica\Database\Database;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Model\Item;
31 use Friendica\Model\Photo;
32 use Friendica\Model\Post;
33 use Friendica\Network\HTTPClientOptions;
34 use Friendica\Util\Images;
35 use Friendica\Util\Network;
36 use Friendica\Util\ParseUrl;
37 use Friendica\Util\Proxy;
38 use Friendica\Util\Strings;
39
40 /**
41  * Class Media
42  *
43  * This Model class handles media interactions.
44  * This tables stores medias (images, videos, audio files) related to posts.
45  */
46 class Media
47 {
48         const UNKNOWN     = 0;
49         const IMAGE       = 1;
50         const VIDEO       = 2;
51         const AUDIO       = 3;
52         const TEXT        = 4;
53         const APPLICATION = 5;
54         const TORRENT     = 16;
55         const HTML        = 17;
56         const XML         = 18;
57         const PLAIN       = 19;
58         const DOCUMENT    = 128;
59
60         /**
61          * Insert a post-media record
62          *
63          * @param array $media
64          * @return void
65          */
66         public static function insert(array $media, bool $force = false)
67         {
68                 if (empty($media['url']) || empty($media['uri-id']) || !isset($media['type'])) {
69                         Logger::warning('Incomplete media data', ['media' => $media]);
70                         return;
71                 }
72
73                 if (DBA::exists('post-media', ['uri-id' => $media['uri-id'], 'preview' => $media['url']])) {
74                         Logger::info('Media already exists as preview', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
75                         return;
76                 }
77
78                 // "document" has got the lowest priority. So when the same file is both attached as document
79                 // and embedded as picture then we only store the picture or replace the document
80                 $found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
81                 if (!$force && !empty($found) && (($found['type'] != self::DOCUMENT) || ($media['type'] == self::DOCUMENT))) {
82                         Logger::info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
83                         return;
84                 }
85
86                 $media = self::unsetEmptyFields($media);
87
88                 // We are storing as fast as possible to avoid duplicated network requests
89                 // when fetching additional information for pictures and other content.
90                 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
91                 Logger::info('Stored media', ['result' => $result, 'media' => $media, 'callstack' => System::callstack()]);
92                 $stored = $media;
93
94                 $media = self::fetchAdditionalData($media);
95                 $media = self::unsetEmptyFields($media);
96
97                 if (array_diff_assoc($media, $stored)) {
98                         $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
99                         Logger::info('Updated media', ['result' => $result, 'media' => $media]);
100                 } else {
101                         Logger::info('Nothing to update', ['media' => $media]);
102                 }
103         }
104
105         /**
106          * Remove empty media fields
107          *
108          * @param array $media
109          * @return array cleaned media array
110          */
111         private static function unsetEmptyFields(array $media)
112         {
113                 $fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'description'];
114                 foreach ($fields as $field) {
115                         if (empty($media[$field])) {
116                                 unset($media[$field]);
117                         }
118                 }
119                 return $media;
120         }
121
122         /**
123          * Copy attachments from one uri-id to another
124          *
125          * @param integer $from_uri_id
126          * @param integer $to_uri_id
127          * @return void
128          */
129         public static function copy(int $from_uri_id, int $to_uri_id)
130         {
131                 $attachments = self::getByURIId($from_uri_id);
132                 foreach ($attachments as $attachment) {
133                         $attachment['uri-id'] = $to_uri_id;
134                         self::insert($attachment);
135                 }
136         }
137
138         /**
139          * Creates the "[attach]" element from the given attributes
140          *
141          * @param string $href
142          * @param integer $length
143          * @param string $type
144          * @param string $title
145          * @return string "[attach]" element
146          */
147         public static function getAttachElement(string $href, int $length, string $type, string $title = '')
148         {
149                 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
150                         'size' => $length, 'mimetype' => $type, 'description' => $title]);
151
152                 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
153                         '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
154         }
155
156         /**
157          * Fetch additional data for the provided media array
158          *
159          * @param array $media
160          * @return array media array with additional data
161          */
162         public static function fetchAdditionalData(array $media)
163         {
164                 if (Network::isLocalLink($media['url'])) {
165                         $media = self::fetchLocalData($media);
166                 }
167
168                 // Fetch the mimetype or size if missing.
169                 if (empty($media['mimetype']) || empty($media['size'])) {
170                         $timeout = DI::config()->get('system', 'xrd_timeout');
171                         $curlResult = DI::httpClient()->head($media['url'], [HTTPClientOptions::TIMEOUT => $timeout]);
172                         if ($curlResult->isSuccess()) {
173                                 if (empty($media['mimetype'])) {
174                                         $media['mimetype'] = $curlResult->getHeader('Content-Type')[0] ?? '';
175                                 }
176                                 if (empty($media['size'])) {
177                                         $media['size'] = (int)($curlResult->getHeader('Content-Length')[0] ?? 0);
178                                 }
179                         } else {
180                                 Logger::notice('Could not fetch head', ['media' => $media]);
181                         }
182                 }
183
184                 $filetype = !empty($media['mimetype']) ? strtolower(current(explode('/', $media['mimetype']))) : '';
185
186                 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
187                         $imagedata = Images::getInfoFromURLCached($media['url']);
188                         if (!empty($imagedata)) {
189                                 $media['mimetype'] = $imagedata['mime'];
190                                 $media['size'] = $imagedata['size'];
191                                 $media['width'] = $imagedata[0];
192                                 $media['height'] = $imagedata[1];
193                         } else {
194                                 Logger::notice('No image data', ['media' => $media]);
195                         }
196                         if (!empty($media['preview'])) {
197                                 $imagedata = Images::getInfoFromURLCached($media['preview']);
198                                 if (!empty($imagedata)) {
199                                         $media['preview-width'] = $imagedata[0];
200                                         $media['preview-height'] = $imagedata[1];
201                                 }
202                         }
203                 }
204
205                 if ($media['type'] != self::DOCUMENT) {
206                         $media = self::addType($media);
207                 }
208
209                 if ($media['type'] == self::HTML) {
210                         $data = ParseUrl::getSiteinfoCached($media['url'], false);
211                         $media['preview'] = $data['images'][0]['src'] ?? null;
212                         $media['preview-height'] = $data['images'][0]['height'] ?? null;
213                         $media['preview-width'] = $data['images'][0]['width'] ?? null;
214                         $media['description'] = $data['text'] ?? null;
215                         $media['name'] = $data['title'] ?? null;
216                         $media['author-url'] = $data['author_url'] ?? null;
217                         $media['author-name'] = $data['author_name'] ?? null;
218                         $media['author-image'] = $data['author_img'] ?? null;
219                         $media['publisher-url'] = $data['publisher_url'] ?? null;
220                         $media['publisher-name'] = $data['publisher_name'] ?? null;
221                         $media['publisher-image'] = $data['publisher_img'] ?? null;
222                 }
223                 return $media;
224         }
225
226         /**
227          * Fetch media data from local resources
228          * @param array $media
229          * @return array media with added data
230          */
231         private static function fetchLocalData(array $media)
232         {
233                 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'] ?? '', $matches)) {
234                         return $media;
235                 }
236                 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
237                 if (!empty($photo)) {
238                         $media['mimetype'] = $photo['type'];
239                         $media['size'] = $photo['datasize'];
240                         $media['width'] = $photo['width'];
241                         $media['height'] = $photo['height'];
242                 }
243
244                 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['preview'] ?? '', $matches)) {
245                         return $media;
246                 }
247                 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
248                 if (!empty($photo)) {
249                         $media['preview-width'] = $photo['width'];
250                         $media['preview-height'] = $photo['height'];
251                 }
252
253                 return $media;
254         }
255
256         /**
257          * Add the detected type to the media array
258          *
259          * @param array $data
260          * @return array data array with the detected type
261          */
262         public static function addType(array $data)
263         {
264                 if (empty($data['mimetype'])) {
265                         Logger::info('No MimeType provided', ['media' => $data]);
266                         return $data;
267                 }
268
269                 $type = explode('/', current(explode(';', $data['mimetype'])));
270                 if (count($type) < 2) {
271                         Logger::info('Unknown MimeType', ['type' => $type, 'media' => $data]);
272                         $data['type'] = self::UNKNOWN;
273                         return $data;
274                 }
275
276                 $filetype = strtolower($type[0]);
277                 $subtype = strtolower($type[1]);
278
279                 if ($filetype == 'image') {
280                         $data['type'] = self::IMAGE;
281                 } elseif ($filetype == 'video') {
282                         $data['type'] = self::VIDEO;
283                 } elseif ($filetype == 'audio') {
284                         $data['type'] = self::AUDIO;
285                 } elseif (($filetype == 'text') && ($subtype == 'html')) {
286                         $data['type'] = self::HTML;
287                 } elseif (($filetype == 'text') && ($subtype == 'xml')) {
288                         $data['type'] = self::XML;
289                 } elseif (($filetype == 'text') && ($subtype == 'plain')) {
290                         $data['type'] = self::PLAIN;
291                 } elseif ($filetype == 'text') {
292                         $data['type'] = self::TEXT;
293                 } elseif (($filetype == 'application') && ($subtype == 'x-bittorrent')) {
294                         $data['type'] = self::TORRENT;
295                 } elseif ($filetype == 'application') {
296                         $data['type'] = self::APPLICATION;
297                 } else {
298                         $data['type'] = self::UNKNOWN;
299                         Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
300                         return $data;
301                 }
302
303                 Logger::debug('Detected type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
304                 return $data;
305         }
306
307         /**
308          * Tests for path patterns that are usef for picture links in Friendica
309          *
310          * @param string $page    Link to the image page
311          * @param string $preview Preview picture
312          * @return boolean
313          */
314         private static function isPictureLink(string $page, string $preview)
315         {
316                 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
317         }
318
319         /**
320          * Add media links and remove them from the body
321          *
322          * @param integer $uriid
323          * @param string $body
324          * @return string Body without media links
325          */
326         public static function insertFromBody(int $uriid, string $body)
327         {
328                 // Simplify image codes
329                 $unshared_body = $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
330
331                 // Only remove the shared data from "real" reshares
332                 $shared = BBCode::fetchShareAttributes($body);
333                 if (!empty($shared['guid'])) {
334                         $unshared_body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
335                 }
336
337                 $attachments = [];
338                 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
339                         foreach ($pictures as $picture) {
340                                 if (!self::isPictureLink($picture[1], $picture[2])) {
341                                         continue;
342                                 }
343                                 $body = str_replace($picture[0], '', $body);
344                                 $image = str_replace('-1.', '-0.', $picture[2]);
345                                 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
346                                         'preview' => $picture[2], 'description' => $picture[3]];
347                         }
348                 }
349
350                 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
351                         foreach ($pictures as $picture) {
352                                 $body = str_replace($picture[0], '', $body);
353                                 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
354                         }
355                 }
356
357                 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
358                         foreach ($pictures as $picture) {
359                                 if (!self::isPictureLink($picture[1], $picture[2])) {
360                                         continue;
361                                 }
362                                 $body = str_replace($picture[0], '', $body);
363                                 $image = str_replace('-1.', '-0.', $picture[2]);
364                                 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
365                                         'preview' => $picture[2], 'description' => null];
366                         }
367                 }
368
369                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
370                         foreach ($pictures as $picture) {
371                                 $body = str_replace($picture[0], '', $body);
372                                 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
373                         }
374                 }
375
376                 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]/ism", $body, $audios, PREG_SET_ORDER)) {
377                         foreach ($audios as $audio) {
378                                 $body = str_replace($audio[0], '', $body);
379                                 $attachments[$audio[1]] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
380                         }
381                 }
382
383                 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]/ism", $body, $videos, PREG_SET_ORDER)) {
384                         foreach ($videos as $video) {
385                                 $body = str_replace($video[0], '', $body);
386                                 $attachments[$video[1]] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
387                         }
388                 }
389
390                 foreach ($attachments as $attachment) {
391                         if (Post\Link::exists($uriid, $attachment['preview'] ?? $attachment['url'])) {
392                                 continue;
393                         }
394
395                         // Only store attachments that are part of the unshared body
396                         if (Item::containsLink($unshared_body, $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
397                                 self::insert($attachment);
398                         }
399                 }
400
401                 return trim($body);
402         }
403
404         /**
405          * Add media links from a relevant url in the body
406          *
407          * @param integer $uriid
408          * @param string $body
409          */
410         public static function insertFromRelevantUrl(int $uriid, string $body)
411         {
412                 // Only remove the shared data from "real" reshares
413                 $shared = BBCode::fetchShareAttributes($body);
414                 if (!empty($shared['guid'])) {
415                         // Don't look at the shared content
416                         $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
417                 }
418
419                 // Remove all hashtags and mentions
420                 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '', $body);
421
422                 // Search for pure links
423                 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) {
424                         foreach ($matches[1] as $url) {
425                                 Logger::info('Got page url (link without description)', ['uri-id' => $uriid, 'url' => $url]);
426                                 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
427                         }
428                 }
429
430                 // Search for links with descriptions
431                 if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) {
432                         foreach ($matches[1] as $url) {
433                                 Logger::info('Got page url (link with description)', ['uri-id' => $uriid, 'url' => $url]);
434                                 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
435                         }
436                 }
437         }
438
439         /**
440          * Add media links from the attachment field
441          *
442          * @param integer $uriid
443          * @param string $body
444          */
445         public static function insertFromAttachmentData(int $uriid, string $body)
446         {
447                 // Don't look at the shared content
448                 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
449
450                 $data = BBCode::getAttachmentData($body);
451                 if (empty($data))  {
452                         return;
453                 }
454
455                 Logger::info('Adding attachment data', ['data' => $data]);
456                 $attachment = [
457                         'uri-id' => $uriid,
458                         'type' => self::HTML,
459                         'url' => $data['url'],
460                         'preview' => $data['preview'] ?? null,
461                         'description' => $data['description'] ?? null,
462                         'name' => $data['title'] ?? null,
463                         'author-url' => $data['author_url'] ?? null,
464                         'author-name' => $data['author_name'] ?? null,
465                         'publisher-url' => $data['provider_url'] ?? null,
466                         'publisher-name' => $data['provider_name'] ?? null,
467                 ];
468                 if (!empty($data['image'])) {
469                         $attachment['preview'] = $data['image'];
470                 }
471                 self::insert($attachment);
472         }
473
474         /**
475          * Add media links from the attach field
476          *
477          * @param integer $uriid
478          * @param string $attach
479          * @return void
480          */
481         public static function insertFromAttachment(int $uriid, string $attach)
482         {
483                 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
484                         return;
485                 }
486
487                 foreach ($matches as $attachment) {
488                         $media['type'] = self::DOCUMENT;
489                         $media['uri-id'] = $uriid;
490                         $media['url'] = $attachment[1];
491                         $media['size'] = $attachment[2];
492                         $media['mimetype'] = $attachment[3];
493                         $media['description'] = $attachment[4] ?? '';
494
495                         self::insert($media);
496                 }
497         }
498
499         /**
500          * Retrieves the media attachments associated with the provided item ID.
501          *
502          * @param int $uri_id
503          * @param array $types
504          * @return array
505          * @throws \Exception
506          */
507         public static function getByURIId(int $uri_id, array $types = [])
508         {
509                 $condition = ['uri-id' => $uri_id];
510
511                 if (!empty($types)) {
512                         $condition = DBA::mergeConditions($condition, ['type' => $types]);
513                 }
514
515                 return DBA::selectToArray('post-media', [], $condition);
516         }
517
518         /**
519          * Checks if media attachments are associated with the provided item ID.
520          *
521          * @param int $uri_id
522          * @param array $types
523          * @return array
524          * @throws \Exception
525          */
526         public static function existsByURIId(int $uri_id, array $types = [])
527         {
528                 $condition = ['uri-id' => $uri_id];
529
530                 if (!empty($types)) {
531                         $condition = DBA::mergeConditions($condition, ['type' => $types]);
532                 }
533
534                 return DBA::exists('post-media', $condition);
535         }
536
537         /**
538          * Split the attachment media in the three segments "visual", "link" and "additional"
539          *
540          * @param int    $uri_id
541          * @param string $guid
542          * @param array  $links list of links that shouldn't be added
543          * @return array attachments
544          */
545         public static function splitAttachments(int $uri_id, string $guid = '', array $links = [])
546         {
547                 $attachments = ['visual' => [], 'link' => [], 'additional' => []];
548
549                 $media = self::getByURIId($uri_id);
550                 if (empty($media)) {
551                         return $attachments;
552                 }
553
554                 $heights = [];
555                 $selected = '';
556                 $previews = [];
557
558                 foreach ($media as $medium) {
559                         foreach ($links as $link) {
560                                 if (Strings::compareLink($link, $medium['url'])) {
561                                         continue 2;
562                                 }
563                         }
564
565                         // Avoid adding separate media entries for previews
566                         foreach ($previews as $preview) {
567                                 if (Strings::compareLink($preview, $medium['url'])) {
568                                         continue 2;
569                                 }
570                         }
571
572                         if (!empty($medium['preview'])) {
573                                 $previews[] = $medium['preview'];
574                         }
575
576                         $type = explode('/', current(explode(';', $medium['mimetype'])));
577                         if (count($type) < 2) {
578                                 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $medium]);
579                                 $filetype = 'unkn';
580                                 $subtype = 'unkn';
581                         } else {
582                                 $filetype = strtolower($type[0]);
583                                 $subtype = strtolower($type[1]);
584                         }
585
586                         $medium['filetype'] = $filetype;
587                         $medium['subtype'] = $subtype;
588
589                         if ($medium['type'] == self::HTML || (($filetype == 'text') && ($subtype == 'html'))) {
590                                 $attachments['link'][] = $medium;
591                                 continue;
592                         }
593
594                         if (in_array($medium['type'], [self::AUDIO, self::IMAGE]) ||
595                                 in_array($filetype, ['audio', 'image'])) {
596                                 $attachments['visual'][] = $medium;
597                         } elseif (($medium['type'] == self::VIDEO) || ($filetype == 'video')) {
598                                 if (!empty($medium['height'])) {
599                                         // Peertube videos are delivered in many different resolutions. We pick a moderate one.
600                                         // Since only Peertube provides a "height" parameter, this wouldn't be executed
601                                         // when someone for example on Mastodon was sharing multiple videos in a single post.
602                                         $heights[$medium['height']] = $medium['url'];
603                                         $video[$medium['url']] = $medium;
604                                 } else {
605                                         $attachments['visual'][] = $medium;
606                                 }
607                         } else {
608                                 $attachments['additional'][] = $medium;
609                         }
610                 }
611
612                 if (!empty($heights)) {
613                         ksort($heights);
614                         foreach ($heights as $height => $url) {
615                                 if (empty($selected) || $height <= 480) {
616                                         $selected = $url;
617                                 }
618                         }
619
620                         if (!empty($selected)) {
621                                 $attachments['visual'][] = $video[$selected];
622                                 unset($video[$selected]);
623                                 foreach ($video as $element) {
624                                         $attachments['additional'][] = $element;
625                                 }
626                         }
627                 }
628
629                 return $attachments;
630         }
631
632         /**
633          * Add media attachments to the body
634          *
635          * @param int $uriid
636          * @param string $body
637          * @return string body
638          */
639         public static function addAttachmentsToBody(int $uriid, string $body = '')
640         {
641                 if (empty($body)) {
642                         $item = Post::selectFirst(['body'], ['uri-id' => $uriid]);
643                         if (!DBA::isResult($item)) {
644                                 return '';
645                         }
646                         $body = $item['body'];
647                 }
648                 $original_body = $body;
649
650                 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
651
652                 foreach (self::getByURIId($uriid, [self::IMAGE, self::AUDIO, self::VIDEO]) as $media) {
653                         if (Item::containsLink($body, $media['preview'] ?? $media['url'], $media['type'])) {
654                                 continue;
655                         }
656
657                         if ($media['type'] == self::IMAGE) {
658                                 if (!empty($media['preview'])) {
659                                         if (!empty($media['description'])) {
660                                                 $body .= "\n[url=" . $media['url'] . "][img=" . $media['preview'] . ']' . $media['description'] .'[/img][/url]';
661                                         } else {
662                                                 $body .= "\n[url=" . $media['url'] . "][img]" . $media['preview'] .'[/img][/url]';
663                                         }
664                                 } else {
665                                         if (!empty($media['description'])) {
666                                                 $body .= "\n[img=" . $media['url'] . ']' . $media['description'] .'[/img]';
667                                         } else {
668                                                 $body .= "\n[img]" . $media['url'] .'[/img]';
669                                         }
670                                 }
671                         } elseif ($media['type'] == self::AUDIO) {
672                                 $body .= "\n[audio]" . $media['url'] . "[/audio]\n";
673                         } elseif ($media['type'] == self::VIDEO) {
674                                 $body .= "\n[video]" . $media['url'] . "[/video]\n";
675                         }
676                 }
677
678                 if (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $original_body, $match)) {
679                         $body .= "\n" . $match[1];
680                 }
681
682                 return $body;
683         }
684
685         /**
686          * Get preview link for given media id
687          *
688          * @param integer $id   media id
689          * @param string  $size One of the ProxyUtils::SIZE_* constants
690          * @return string preview link
691          */
692         public static function getPreviewUrlForId(int $id, string $size = ''):string
693         {
694                 $url = DI::baseUrl() . '/photo/preview/';
695                 switch ($size) {
696                         case Proxy::SIZE_MICRO:
697                                 $url .= Proxy::PIXEL_MICRO . '/';
698                                 break;
699                         case Proxy::SIZE_THUMB:
700                                 $url .= Proxy::PIXEL_THUMB . '/';
701                                 break;
702                         case Proxy::SIZE_SMALL:
703                                 $url .= Proxy::PIXEL_SMALL . '/';
704                                 break;
705                         case Proxy::SIZE_MEDIUM:
706                                 $url .= Proxy::PIXEL_MEDIUM . '/';
707                                 break;
708                         case Proxy::SIZE_LARGE:
709                                 $url .= Proxy::PIXEL_LARGE . '/';
710                                 break;
711                 }
712                 return $url . $id;
713         }
714
715         /**
716          * Get media link for given media id
717          *
718          * @param integer $id   media id
719          * @param string  $size One of the ProxyUtils::SIZE_* constants
720          * @return string media link
721          */
722         public static function getUrlForId(int $id, string $size = ''):string
723         {
724                 $url = DI::baseUrl() . '/photo/media/';
725                 switch ($size) {
726                         case Proxy::SIZE_MICRO:
727                                 $url .= Proxy::PIXEL_MICRO . '/';
728                                 break;
729                         case Proxy::SIZE_THUMB:
730                                 $url .= Proxy::PIXEL_THUMB . '/';
731                                 break;
732                         case Proxy::SIZE_SMALL:
733                                 $url .= Proxy::PIXEL_SMALL . '/';
734                                 break;
735                         case Proxy::SIZE_MEDIUM:
736                                 $url .= Proxy::PIXEL_MEDIUM . '/';
737                                 break;
738                         case Proxy::SIZE_LARGE:
739                                 $url .= Proxy::PIXEL_LARGE . '/';
740                                 break;
741                 }
742                 return $url . $id;
743         }
744 }