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