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