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