]> git.mxchange.org Git - friendica.git/blob - src/Model/Post/Media.php
6cee11e6c88659ac03736b074c01338c034aa62b
[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', '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                         } else {
207                                 Logger::notice('No image data', ['media' => $media]);
208                         }
209                         if (!empty($media['preview'])) {
210                                 $imagedata = Images::getInfoFromURLCached($media['preview']);
211                                 if ($imagedata) {
212                                         $media['preview-width'] = $imagedata[0];
213                                         $media['preview-height'] = $imagedata[1];
214                                 }
215                         }
216                 }
217
218                 if ($media['type'] != self::DOCUMENT) {
219                         $media = self::addType($media);
220                 }
221
222                 if (in_array($media['type'], [self::TEXT, self::APPLICATION, self::HTML, self::XML, self::PLAIN])) {
223                         $media = self::addActivity($media);
224                 }
225
226                 if (in_array($media['type'], [self::TEXT, self::APPLICATION, self::HTML, self::XML, self::PLAIN])) {
227                         $media = self::addAccount($media);
228                 }
229
230                 if ($media['type'] == self::HTML) {
231                         $data = ParseUrl::getSiteinfoCached($media['url'], false);
232                         $media['preview'] = $data['images'][0]['src'] ?? null;
233                         $media['preview-height'] = $data['images'][0]['height'] ?? null;
234                         $media['preview-width'] = $data['images'][0]['width'] ?? null;
235                         $media['description'] = $data['text'] ?? null;
236                         $media['name'] = $data['title'] ?? null;
237                         $media['author-url'] = $data['author_url'] ?? null;
238                         $media['author-name'] = $data['author_name'] ?? null;
239                         $media['author-image'] = $data['author_img'] ?? null;
240                         $media['publisher-url'] = $data['publisher_url'] ?? null;
241                         $media['publisher-name'] = $data['publisher_name'] ?? null;
242                         $media['publisher-image'] = $data['publisher_img'] ?? null;
243                 }
244                 return $media;
245         }
246
247         /**
248          * Adds the activity type if the media entry is linked to an activity
249          *
250          * @param array $media
251          * @return array
252          */
253         private static function addActivity(array $media): array
254         {
255                 $id = Item::fetchByLink($media['url']);
256                 if (empty($id)) {
257                         return $media;
258                 }
259
260                 $item = Post::selectFirst([], ['id' => $id, 'network' => Protocol::FEDERATED]);
261                 if (empty($item['id'])) {
262                         Logger::debug('Not a federated activity', ['id' => $id, 'uri-id' => $media['uri-id'], 'url' => $media['url']]);
263                         return $media;
264                 }
265
266                 if (!empty($item['plink']) && Strings::compareLink($item['plink'], $media['url']) &&
267                         parse_url($item['plink'], PHP_URL_HOST) != parse_url($item['uri'], PHP_URL_HOST)) {
268                         Logger::debug('Not a link to an activity', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'plink' => $item['plink'], 'uri' => $item['uri']]);
269                         return $media;
270                 }
271
272                 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
273                         $media['mimetype'] = 'application/activity+json';
274                 } elseif ($item['network'] == Protocol::DIASPORA) {
275                         $media['mimetype'] = 'application/xml';
276                 }
277
278                 $contact = Contact::getById($item['author-id'], ['avatar', 'gsid']);
279                 if (!empty($contact['gsid'])) {
280                         $gserver = DBA::selectFirst('gserver', ['url', 'site_name'], ['id' => $contact['gsid']]);
281                 }
282                 
283                 $media['type'] = self::ACTIVITY;
284                 $media['media-uri-id'] = $item['uri-id'];
285                 $media['height'] = null;
286                 $media['width'] = null;
287                 $media['preview'] = null;
288                 $media['preview-height'] = null;
289                 $media['preview-width'] = null;
290                 $media['description'] = $item['body'];
291                 $media['name'] = $item['title'];
292                 $media['author-url'] = $item['author-link'];
293                 $media['author-name'] = $item['author-name'];
294                 $media['author-image'] = $contact['avatar'] ?? $item['author-avatar'];
295                 $media['publisher-url'] = $gserver['url'] ?? null;
296                 $media['publisher-name'] = $gserver['site_name'] ?? null;
297                 $media['publisher-image'] = null;
298
299                 Logger::debug('Activity detected', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'plink' => $item['plink'], 'uri' => $item['uri']]);
300                 return $media;
301         }
302
303         /**
304          * Adds the account type if the media entry is linked to an account
305          *
306          * @param array $media
307          * @return array
308          */
309         private static function addAccount(array $media): array
310         {
311                 $contact = Contact::getByURL($media['url'], false);
312                 if (empty($contact) || ($contact['network'] == Protocol::PHANTOM)) {
313                         return $media;
314                 }
315
316                 if (in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
317                         $media['mimetype'] = 'application/activity+json';
318                 }
319
320                 if (!empty($contact['gsid'])) {
321                         $gserver = DBA::selectFirst('gserver', ['url', 'site_name'], ['id' => $contact['gsid']]);
322                 }
323
324                 $media['type'] = self::ACCOUNT;
325                 $media['media-uri-id'] = $contact['uri-id'];
326                 $media['height'] = null;
327                 $media['width'] = null;
328                 $media['preview'] = null;
329                 $media['preview-height'] = null;
330                 $media['preview-width'] = null;
331                 $media['description'] = $contact['about'];
332                 $media['name'] = $contact['name'];
333                 $media['author-url'] = $contact['url'];
334                 $media['author-name'] = $contact['name'];
335                 $media['author-image'] = $contact['avatar'];
336                 $media['publisher-url'] = $gserver['url'] ?? null;
337                 $media['publisher-name'] = $gserver['site_name'] ?? null;
338                 $media['publisher-image'] = null;
339
340                 Logger::debug('Account detected', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'uri' => $contact['url']]);
341                 return $media;
342         }
343
344         /**
345          * Fetch media data from local resources
346          * @param array $media
347          * @return array media with added data
348          */
349         private static function fetchLocalData(array $media): array
350         {
351                 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'] ?? '', $matches)) {
352                         return $media;
353                 }
354                 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
355                 if (!empty($photo)) {
356                         $media['mimetype'] = $photo['type'];
357                         $media['size'] = $photo['datasize'];
358                         $media['width'] = $photo['width'];
359                         $media['height'] = $photo['height'];
360                 }
361
362                 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['preview'] ?? '', $matches)) {
363                         return $media;
364                 }
365                 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
366                 if (!empty($photo)) {
367                         $media['preview-width'] = $photo['width'];
368                         $media['preview-height'] = $photo['height'];
369                 }
370
371                 return $media;
372         }
373
374         /**
375          * Add the detected type to the media array
376          *
377          * @param array $data
378          * @return array data array with the detected type
379          */
380         public static function addType(array $data): array
381         {
382                 if (empty($data['mimetype'])) {
383                         Logger::info('No MimeType provided', ['media' => $data]);
384                         return $data;
385                 }
386
387                 $type = explode('/', current(explode(';', $data['mimetype'])));
388                 if (count($type) < 2) {
389                         Logger::info('Unknown MimeType', ['type' => $type, 'media' => $data]);
390                         $data['type'] = self::UNKNOWN;
391                         return $data;
392                 }
393
394                 $filetype = strtolower($type[0]);
395                 $subtype = strtolower($type[1]);
396
397                 if ($filetype == 'image') {
398                         $data['type'] = self::IMAGE;
399                 } elseif ($filetype == 'video') {
400                         $data['type'] = self::VIDEO;
401                 } elseif ($filetype == 'audio') {
402                         $data['type'] = self::AUDIO;
403                 } elseif (($filetype == 'text') && ($subtype == 'html')) {
404                         $data['type'] = self::HTML;
405                 } elseif (($filetype == 'text') && ($subtype == 'xml')) {
406                         $data['type'] = self::XML;
407                 } elseif (($filetype == 'text') && ($subtype == 'plain')) {
408                         $data['type'] = self::PLAIN;
409                 } elseif ($filetype == 'text') {
410                         $data['type'] = self::TEXT;
411                 } elseif (($filetype == 'application') && ($subtype == 'x-bittorrent')) {
412                         $data['type'] = self::TORRENT;
413                 } elseif ($filetype == 'application') {
414                         $data['type'] = self::APPLICATION;
415                 } else {
416                         $data['type'] = self::UNKNOWN;
417                         Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
418                         return $data;
419                 }
420
421                 Logger::debug('Detected type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
422                 return $data;
423         }
424
425         /**
426          * Tests for path patterns that are usef for picture links in Friendica
427          *
428          * @param string $page    Link to the image page
429          * @param string $preview Preview picture
430          * @return boolean
431          */
432         private static function isPictureLink(string $page, string $preview): bool
433         {
434                 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
435         }
436
437         /**
438          * Add media links and remove them from the body
439          *
440          * @param integer $uriid
441          * @param string $body
442          * @return string Body without media links
443          */
444         public static function insertFromBody(int $uriid, string $body): string
445         {
446                 // Simplify image codes
447                 $unshared_body = $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
448
449                 $attachments = [];
450                 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
451                         foreach ($pictures as $picture) {
452                                 if (!self::isPictureLink($picture[1], $picture[2])) {
453                                         continue;
454                                 }
455                                 $body = str_replace($picture[0], '', $body);
456                                 $image = str_replace('-1.', '-0.', $picture[2]);
457                                 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
458                                         'preview' => $picture[2], 'description' => $picture[3]];
459                         }
460                 }
461
462                 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
463                         foreach ($pictures as $picture) {
464                                 $body = str_replace($picture[0], '', $body);
465                                 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
466                         }
467                 }
468
469                 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
470                         foreach ($pictures as $picture) {
471                                 if (!self::isPictureLink($picture[1], $picture[2])) {
472                                         continue;
473                                 }
474                                 $body = str_replace($picture[0], '', $body);
475                                 $image = str_replace('-1.', '-0.', $picture[2]);
476                                 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
477                                         'preview' => $picture[2], 'description' => null];
478                         }
479                 }
480
481                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
482                         foreach ($pictures as $picture) {
483                                 $body = str_replace($picture[0], '', $body);
484                                 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
485                         }
486                 }
487
488                 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]/ism", $body, $audios, PREG_SET_ORDER)) {
489                         foreach ($audios as $audio) {
490                                 $body = str_replace($audio[0], '', $body);
491                                 $attachments[$audio[1]] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
492                         }
493                 }
494
495                 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]/ism", $body, $videos, PREG_SET_ORDER)) {
496                         foreach ($videos as $video) {
497                                 $body = str_replace($video[0], '', $body);
498                                 $attachments[$video[1]] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
499                         }
500                 }
501
502                 foreach ($attachments as $attachment) {
503                         if (Post\Link::exists($uriid, $attachment['preview'] ?? $attachment['url'])) {
504                                 continue;
505                         }
506
507                         // Only store attachments that are part of the unshared body
508                         if (Item::containsLink($unshared_body, $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
509                                 self::insert($attachment);
510                         }
511                 }
512
513                 return trim($body);
514         }
515
516         /**
517          * Add media links from a relevant url in the body
518          *
519          * @param integer $uriid
520          * @param string $body
521          * @return void
522          */
523         public static function insertFromRelevantUrl(int $uriid, string $body)
524         {
525                 // Remove all hashtags and mentions
526                 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '', $body);
527
528                 // Search for pure links
529                 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) {
530                         foreach ($matches[1] as $url) {
531                                 Logger::info('Got page url (link without description)', ['uri-id' => $uriid, 'url' => $url]);
532                                 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
533                         }
534                 }
535
536                 // Search for links with descriptions
537                 if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) {
538                         foreach ($matches[1] as $url) {
539                                 Logger::info('Got page url (link with description)', ['uri-id' => $uriid, 'url' => $url]);
540                                 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
541                         }
542                 }
543         }
544
545         /**
546          * Add media links from the attachment field
547          *
548          * @param integer $uriid
549          * @param string $body
550          * @return void
551          */
552         public static function insertFromAttachmentData(int $uriid, string $body)
553         {
554                 $data = BBCode::getAttachmentData($body);
555                 if (empty($data))  {
556                         return;
557                 }
558
559                 Logger::info('Adding attachment data', ['data' => $data]);
560                 $attachment = [
561                         'uri-id' => $uriid,
562                         'type' => self::HTML,
563                         'url' => $data['url'],
564                         'preview' => $data['preview'] ?? null,
565                         'description' => $data['description'] ?? null,
566                         'name' => $data['title'] ?? null,
567                         'author-url' => $data['author_url'] ?? null,
568                         'author-name' => $data['author_name'] ?? null,
569                         'publisher-url' => $data['provider_url'] ?? null,
570                         'publisher-name' => $data['provider_name'] ?? null,
571                 ];
572                 if (!empty($data['image'])) {
573                         $attachment['preview'] = $data['image'];
574                 }
575                 self::insert($attachment);
576         }
577
578         /**
579          * Add media links from the attach field
580          *
581          * @param integer $uriid
582          * @param string $attach
583          * @return void
584          */
585         public static function insertFromAttachment(int $uriid, string $attach)
586         {
587                 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
588                         return;
589                 }
590
591                 foreach ($matches as $attachment) {
592                         $media['type'] = self::DOCUMENT;
593                         $media['uri-id'] = $uriid;
594                         $media['url'] = $attachment[1];
595                         $media['size'] = $attachment[2];
596                         $media['mimetype'] = $attachment[3];
597                         $media['description'] = $attachment[4] ?? '';
598
599                         self::insert($media);
600                 }
601         }
602
603         /**
604          * Retrieves the media attachments associated with the provided item ID.
605          *
606          * @param int $uri_id URI id
607          * @param array $types Media types
608          * @return array|bool Array on success, false on error
609          * @throws \Exception
610          */
611         public static function getByURIId(int $uri_id, array $types = [])
612         {
613                 $condition = ['uri-id' => $uri_id];
614
615                 if (!empty($types)) {
616                         $condition = DBA::mergeConditions($condition, ['type' => $types]);
617                 }
618
619                 return DBA::selectToArray('post-media', [], $condition, ['order' => ['id']]);
620         }
621
622         /**
623          * Checks if media attachments are associated with the provided item ID.
624          *
625          * @param int $uri_id URI id
626          * @param array $types Media types
627          * @return bool Whether media attachment exists
628          * @throws \Exception
629          */
630         public static function existsByURIId(int $uri_id, array $types = []): bool
631         {
632                 $condition = ['uri-id' => $uri_id];
633
634                 if (!empty($types)) {
635                         $condition = DBA::mergeConditions($condition, ['type' => $types]);
636                 }
637
638                 return DBA::exists('post-media', $condition);
639         }
640
641         /**
642          * Split the attachment media in the three segments "visual", "link" and "additional"
643          *
644          * @param int    $uri_id URI id
645          * @param array  $links list of links that shouldn't be added
646          * @param bool   $has_media
647          * @return array attachments
648          */
649         public static function splitAttachments(int $uri_id, array $links = [], bool $has_media = true): array
650         {
651                 $attachments = ['visual' => [], 'link' => [], 'additional' => []];
652
653                 if (!$has_media) {
654                         return $attachments;
655                 }
656
657                 $media = self::getByURIId($uri_id);
658                 if (empty($media)) {
659                         return $attachments;
660                 }
661
662                 $heights = [];
663                 $selected = '';
664                 $previews = [];
665
666                 foreach ($media as $medium) {
667                         foreach ($links as $link) {
668                                 if (Strings::compareLink($link, $medium['url'])) {
669                                         continue 2;
670                                 }
671                         }
672
673                         // Avoid adding separate media entries for previews
674                         foreach ($previews as $preview) {
675                                 if (Strings::compareLink($preview, $medium['url'])) {
676                                         continue 2;
677                                 }
678                         }
679
680                         // Currently these two types are ignored here.
681                         // Posts are added differently and contacts are not displayed as attachments.
682                         if (in_array($medium['type'], [self::ACCOUNT, self::ACTIVITY])) {
683                                 continue;
684                         }
685
686                         if (!empty($medium['preview'])) {
687                                 $previews[] = $medium['preview'];
688                         }
689
690                         $type = explode('/', current(explode(';', $medium['mimetype'])));
691                         if (count($type) < 2) {
692                                 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $medium]);
693                                 $filetype = 'unkn';
694                                 $subtype = 'unkn';
695                         } else {
696                                 $filetype = strtolower($type[0]);
697                                 $subtype = strtolower($type[1]);
698                         }
699
700                         $medium['filetype'] = $filetype;
701                         $medium['subtype'] = $subtype;
702
703                         if ($medium['type'] == self::HTML || (($filetype == 'text') && ($subtype == 'html'))) {
704                                 $attachments['link'][] = $medium;
705                                 continue;
706                         }
707
708                         if (in_array($medium['type'], [self::AUDIO, self::IMAGE]) ||
709                                 in_array($filetype, ['audio', 'image'])) {
710                                 $attachments['visual'][] = $medium;
711                         } elseif (($medium['type'] == self::VIDEO) || ($filetype == 'video')) {
712                                 if (!empty($medium['height'])) {
713                                         // Peertube videos are delivered in many different resolutions. We pick a moderate one.
714                                         // Since only Peertube provides a "height" parameter, this wouldn't be executed
715                                         // when someone for example on Mastodon was sharing multiple videos in a single post.
716                                         $heights[$medium['height']] = $medium['url'];
717                                         $video[$medium['url']] = $medium;
718                                 } else {
719                                         $attachments['visual'][] = $medium;
720                                 }
721                         } else {
722                                 $attachments['additional'][] = $medium;
723                         }
724                 }
725
726                 if (!empty($heights)) {
727                         ksort($heights);
728                         foreach ($heights as $height => $url) {
729                                 if (empty($selected) || $height <= 480) {
730                                         $selected = $url;
731                                 }
732                         }
733
734                         if (!empty($selected)) {
735                                 $attachments['visual'][] = $video[$selected];
736                                 unset($video[$selected]);
737                                 foreach ($video as $element) {
738                                         $attachments['additional'][] = $element;
739                                 }
740                         }
741                 }
742
743                 return $attachments;
744         }
745
746         /**
747          * Add media attachments to the body
748          *
749          * @param int    $uriid
750          * @param string $body
751          * @param array  $types
752          *
753          * @return string body
754          */
755         public static function addAttachmentsToBody(int $uriid, string $body = '', array $types = [self::IMAGE, self::AUDIO, self::VIDEO]): string
756         {
757                 if (empty($body)) {
758                         $item = Post::selectFirst(['body'], ['uri-id' => $uriid]);
759                         if (!DBA::isResult($item)) {
760                                 return '';
761                         }
762                         $body = $item['body'];
763                 }
764                 $original_body = $body;
765
766                 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
767
768                 foreach (self::getByURIId($uriid, $types) as $media) {
769                         if (Item::containsLink($body, $media['preview'] ?? $media['url'], $media['type'])) {
770                                 continue;
771                         }
772
773                         if ($media['type'] == self::IMAGE) {
774                                 if (!empty($media['preview'])) {
775                                         if (!empty($media['description'])) {
776                                                 $body .= "\n[url=" . $media['url'] . "][img=" . $media['preview'] . ']' . $media['description'] .'[/img][/url]';
777                                         } else {
778                                                 $body .= "\n[url=" . $media['url'] . "][img]" . $media['preview'] .'[/img][/url]';
779                                         }
780                                 } else {
781                                         if (!empty($media['description'])) {
782                                                 $body .= "\n[img=" . $media['url'] . ']' . $media['description'] .'[/img]';
783                                         } else {
784                                                 $body .= "\n[img]" . $media['url'] .'[/img]';
785                                         }
786                                 }
787                         } elseif ($media['type'] == self::AUDIO) {
788                                 $body .= "\n[audio]" . $media['url'] . "[/audio]\n";
789                         } elseif ($media['type'] == self::VIDEO) {
790                                 $body .= "\n[video]" . $media['url'] . "[/video]\n";
791                         }
792                 }
793
794                 if (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $original_body, $match)) {
795                         $body .= "\n" . $match[1];
796                 }
797
798                 return $body;
799         }
800
801         /**
802          * Get preview link for given media id
803          *
804          * @param integer $id   media id
805          * @param string  $size One of the Proxy::SIZE_* constants
806          * @return string preview link
807          */
808         public static function getPreviewUrlForId(int $id, string $size = ''): string
809         {
810                 $url = DI::baseUrl() . '/photo/preview/';
811                 switch ($size) {
812                         case Proxy::SIZE_MICRO:
813                                 $url .= Proxy::PIXEL_MICRO . '/';
814                                 break;
815                         case Proxy::SIZE_THUMB:
816                                 $url .= Proxy::PIXEL_THUMB . '/';
817                                 break;
818                         case Proxy::SIZE_SMALL:
819                                 $url .= Proxy::PIXEL_SMALL . '/';
820                                 break;
821                         case Proxy::SIZE_MEDIUM:
822                                 $url .= Proxy::PIXEL_MEDIUM . '/';
823                                 break;
824                         case Proxy::SIZE_LARGE:
825                                 $url .= Proxy::PIXEL_LARGE . '/';
826                                 break;
827                 }
828                 return $url . $id;
829         }
830
831         /**
832          * Get media link for given media id
833          *
834          * @param integer $id   media id
835          * @param string  $size One of the Proxy::SIZE_* constants
836          * @return string media link
837          */
838         public static function getUrlForId(int $id, string $size = ''): string
839         {
840                 $url = DI::baseUrl() . '/photo/media/';
841                 switch ($size) {
842                         case Proxy::SIZE_MICRO:
843                                 $url .= Proxy::PIXEL_MICRO . '/';
844                                 break;
845                         case Proxy::SIZE_THUMB:
846                                 $url .= Proxy::PIXEL_THUMB . '/';
847                                 break;
848                         case Proxy::SIZE_SMALL:
849                                 $url .= Proxy::PIXEL_SMALL . '/';
850                                 break;
851                         case Proxy::SIZE_MEDIUM:
852                                 $url .= Proxy::PIXEL_MEDIUM . '/';
853                                 break;
854                         case Proxy::SIZE_LARGE:
855                                 $url .= Proxy::PIXEL_LARGE . '/';
856                                 break;
857                 }
858                 return $url . $id;
859         }
860 }