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