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