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