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