]> git.mxchange.org Git - friendica.git/blob - src/Model/Post/Media.php
Merge pull request #10787 from fabrixxm/issue/10767
[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                         // Only store attachments that are part of the unshared body
392                         if (Item::containsLink($unshared_body, $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
393                                 self::insert($attachment);
394                         }
395                 }
396
397                 return trim($body);
398         }
399
400         /**
401          * Add media links from a relevant url in the body
402          *
403          * @param integer $uriid
404          * @param string $body
405          */
406         public static function insertFromRelevantUrl(int $uriid, string $body)
407         {
408                 // Only remove the shared data from "real" reshares
409                 $shared = BBCode::fetchShareAttributes($body);
410                 if (!empty($shared['guid'])) {
411                         // Don't look at the shared content
412                         $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
413                 }
414
415                 // Remove all hashtags and mentions
416                 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '', $body);
417
418                 // Search for pure links
419                 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) {
420                         foreach ($matches[1] as $url) {
421                                 Logger::info('Got page url (link without description)', ['uri-id' => $uriid, 'url' => $url]);
422                                 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
423                         }
424                 }
425
426                 // Search for links with descriptions
427                 if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) {
428                         foreach ($matches[1] as $url) {
429                                 Logger::info('Got page url (link with description)', ['uri-id' => $uriid, 'url' => $url]);
430                                 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
431                         }
432                 }
433         }
434
435         /**
436          * Add media links from the attachment field
437          *
438          * @param integer $uriid
439          * @param string $body
440          */
441         public static function insertFromAttachmentData(int $uriid, string $body)
442         {
443                 // Don't look at the shared content
444                 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
445
446                 $data = BBCode::getAttachmentData($body);
447                 if (empty($data))  {
448                         return;
449                 }
450
451                 Logger::info('Adding attachment data', ['data' => $data]);
452                 $attachment = [
453                         'uri-id' => $uriid,
454                         'type' => self::HTML,
455                         'url' => $data['url'],
456                         'preview' => $data['preview'] ?? null,
457                         'description' => $data['description'] ?? null,
458                         'name' => $data['title'] ?? null,
459                         'author-url' => $data['author_url'] ?? null,
460                         'author-name' => $data['author_name'] ?? null,
461                         'publisher-url' => $data['provider_url'] ?? null,
462                         'publisher-name' => $data['provider_name'] ?? null,
463                 ];
464                 if (!empty($data['image'])) {
465                         $attachment['preview'] = $data['image'];
466                 }
467                 self::insert($attachment);
468         }
469
470         /**
471          * Add media links from the attach field
472          *
473          * @param integer $uriid
474          * @param string $attach
475          * @return void
476          */
477         public static function insertFromAttachment(int $uriid, string $attach)
478         {
479                 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
480                         return;
481                 }
482
483                 foreach ($matches as $attachment) {
484                         $media['type'] = self::DOCUMENT;
485                         $media['uri-id'] = $uriid;
486                         $media['url'] = $attachment[1];
487                         $media['size'] = $attachment[2];
488                         $media['mimetype'] = $attachment[3];
489                         $media['description'] = $attachment[4] ?? '';
490
491                         self::insert($media);
492                 }
493         }
494
495         /**
496          * Retrieves the media attachments associated with the provided item ID.
497          *
498          * @param int $uri_id
499          * @param array $types
500          * @return array
501          * @throws \Exception
502          */
503         public static function getByURIId(int $uri_id, array $types = [])
504         {
505                 $condition = ['uri-id' => $uri_id];
506
507                 if (!empty($types)) {
508                         $condition = DBA::mergeConditions($condition, ['type' => $types]);
509                 }
510
511                 return DBA::selectToArray('post-media', [], $condition);
512         }
513
514         /**
515          * Checks if media attachments are associated with the provided item ID.
516          *
517          * @param int $uri_id
518          * @param array $types
519          * @return array
520          * @throws \Exception
521          */
522         public static function existsByURIId(int $uri_id, array $types = [])
523         {
524                 $condition = ['uri-id' => $uri_id];
525
526                 if (!empty($types)) {
527                         $condition = DBA::mergeConditions($condition, ['type' => $types]);
528                 }
529
530                 return DBA::exists('post-media', $condition);
531         }
532
533         /**
534          * Split the attachment media in the three segments "visual", "link" and "additional"
535          *
536          * @param int    $uri_id
537          * @param string $guid
538          * @param array  $links list of links that shouldn't be added
539          * @return array attachments
540          */
541         public static function splitAttachments(int $uri_id, string $guid = '', array $links = [])
542         {
543                 $attachments = ['visual' => [], 'link' => [], 'additional' => []];
544
545                 $media = self::getByURIId($uri_id);
546                 if (empty($media)) {
547                         return $attachments;
548                 }
549
550                 $heights = [];
551                 $selected = '';
552                 $previews = [];
553
554                 foreach ($media as $medium) {
555                         foreach ($links as $link) {
556                                 if (Strings::compareLink($link, $medium['url'])) {
557                                         continue 2;
558                                 }
559                         }
560
561                         // Avoid adding separate media entries for previews
562                         foreach ($previews as $preview) {
563                                 if (Strings::compareLink($preview, $medium['url'])) {
564                                         continue 2;
565                                 }
566                         }
567
568                         if (!empty($medium['preview'])) {
569                                 $previews[] = $medium['preview'];
570                         }
571
572                         $type = explode('/', current(explode(';', $medium['mimetype'])));
573                         if (count($type) < 2) {
574                                 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $medium]);
575                                 $filetype = 'unkn';
576                                 $subtype = 'unkn';
577                         } else {
578                                 $filetype = strtolower($type[0]);
579                                 $subtype = strtolower($type[1]);
580                         }
581
582                         $medium['filetype'] = $filetype;
583                         $medium['subtype'] = $subtype;
584
585                         if ($medium['type'] == self::HTML || (($filetype == 'text') && ($subtype == 'html'))) {
586                                 $attachments['link'][] = $medium;
587                                 continue;
588                         }
589
590                         if (in_array($medium['type'], [self::AUDIO, self::IMAGE]) ||
591                                 in_array($filetype, ['audio', 'image'])) {
592                                 $attachments['visual'][] = $medium;
593                         } elseif (($medium['type'] == self::VIDEO) || ($filetype == 'video')) {
594                                 if (!empty($medium['height'])) {
595                                         // Peertube videos are delivered in many different resolutions. We pick a moderate one.
596                                         // Since only Peertube provides a "height" parameter, this wouldn't be executed
597                                         // when someone for example on Mastodon was sharing multiple videos in a single post.
598                                         $heights[$medium['height']] = $medium['url'];
599                                         $video[$medium['url']] = $medium;
600                                 } else {
601                                         $attachments['visual'][] = $medium;
602                                 }
603                         } else {
604                                 $attachments['additional'][] = $medium;
605                         }
606                 }
607
608                 if (!empty($heights)) {
609                         ksort($heights);
610                         foreach ($heights as $height => $url) {
611                                 if (empty($selected) || $height <= 480) {
612                                         $selected = $url;
613                                 }
614                         }
615
616                         if (!empty($selected)) {
617                                 $attachments['visual'][] = $video[$selected];
618                                 unset($video[$selected]);
619                                 foreach ($video as $element) {
620                                         $attachments['additional'][] = $element;
621                                 }
622                         }
623                 }
624
625                 return $attachments;
626         }
627
628         /**
629          * Add media attachments to the body
630          *
631          * @param int $uriid
632          * @param string $body
633          * @return string body
634          */
635         public static function addAttachmentsToBody(int $uriid, string $body = '')
636         {
637                 if (empty($body)) {
638                         $item = Post::selectFirst(['body'], ['uri-id' => $uriid]);
639                         if (!DBA::isResult($item)) {
640                                 return '';
641                         }
642                         $body = $item['body'];
643                 }
644                 $original_body = $body;
645
646                 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
647
648                 foreach (self::getByURIId($uriid, [self::IMAGE, self::AUDIO, self::VIDEO]) as $media) {
649                         if (Item::containsLink($body, $media['preview'] ?? $media['url'], $media['type'])) {
650                                 continue;
651                         }
652
653                         if ($media['type'] == self::IMAGE) {
654                                 if (!empty($media['preview'])) {
655                                         if (!empty($media['description'])) {
656                                                 $body .= "\n[url=" . $media['url'] . "][img=" . $media['preview'] . ']' . $media['description'] .'[/img][/url]';
657                                         } else {
658                                                 $body .= "\n[url=" . $media['url'] . "][img]" . $media['preview'] .'[/img][/url]';
659                                         }
660                                 } else {
661                                         if (!empty($media['description'])) {
662                                                 $body .= "\n[img=" . $media['url'] . ']' . $media['description'] .'[/img]';
663                                         } else {
664                                                 $body .= "\n[img]" . $media['url'] .'[/img]';
665                                         }
666                                 }
667                         } elseif ($media['type'] == self::AUDIO) {
668                                 $body .= "\n[audio]" . $media['url'] . "[/audio]\n";
669                         } elseif ($media['type'] == self::VIDEO) {
670                                 $body .= "\n[video]" . $media['url'] . "[/video]\n";
671                         }
672                 }
673
674                 if (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $original_body, $match)) {
675                         $body .= "\n" . $match[1];
676                 }
677
678                 return $body;
679         }
680
681         /**
682          * Get preview link for given media id
683          *
684          * @param integer $id   media id
685          * @param string  $size One of the ProxyUtils::SIZE_* constants
686          * @return string preview link
687          */
688         public static function getPreviewUrlForId(int $id, string $size = ''):string
689         {
690                 $url = DI::baseUrl() . '/photo/preview/';
691                 switch ($size) {
692                         case Proxy::SIZE_MICRO:
693                                 $url .= Proxy::PIXEL_MICRO . '/';
694                                 break;
695                         case Proxy::SIZE_THUMB:
696                                 $url .= Proxy::PIXEL_THUMB . '/';
697                                 break;
698                         case Proxy::SIZE_SMALL:
699                                 $url .= Proxy::PIXEL_SMALL . '/';
700                                 break;
701                         case Proxy::SIZE_MEDIUM:
702                                 $url .= Proxy::PIXEL_MEDIUM . '/';
703                                 break;
704                         case Proxy::SIZE_LARGE:
705                                 $url .= Proxy::PIXEL_LARGE . '/';
706                                 break;
707                 }
708                 return $url . $id;
709         }
710
711         /**
712          * Get media link for given media id
713          *
714          * @param integer $id   media id
715          * @param string  $size One of the ProxyUtils::SIZE_* constants
716          * @return string media link
717          */
718         public static function getUrlForId(int $id, string $size = ''):string
719         {
720                 $url = DI::baseUrl() . '/photo/media/';
721                 switch ($size) {
722                         case Proxy::SIZE_MICRO:
723                                 $url .= Proxy::PIXEL_MICRO . '/';
724                                 break;
725                         case Proxy::SIZE_THUMB:
726                                 $url .= Proxy::PIXEL_THUMB . '/';
727                                 break;
728                         case Proxy::SIZE_SMALL:
729                                 $url .= Proxy::PIXEL_SMALL . '/';
730                                 break;
731                         case Proxy::SIZE_MEDIUM:
732                                 $url .= Proxy::PIXEL_MEDIUM . '/';
733                                 break;
734                         case Proxy::SIZE_LARGE:
735                                 $url .= Proxy::PIXEL_LARGE . '/';
736                                 break;
737                 }
738                 return $url . $id;
739         }
740 }