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