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