3 * @copyright Copyright (C) 2010-2023, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Model\Post;
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;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Item;
33 use Friendica\Model\ItemURI;
34 use Friendica\Model\Photo;
35 use Friendica\Model\Post;
36 use Friendica\Network\HTTPClient\Client\HttpClientAccept;
37 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
38 use Friendica\Util\Images;
39 use Friendica\Util\Network;
40 use Friendica\Util\ParseUrl;
41 use Friendica\Util\Proxy;
42 use Friendica\Util\Strings;
47 * This Model class handles media interactions.
48 * This tables stores medias (images, videos, audio files) related to posts.
57 const APPLICATION = 5;
67 * Insert a post-media record
73 public static function insert(array $media, bool $force = false)
75 if (empty($media['url']) || empty($media['uri-id']) || !isset($media['type'])) {
76 Logger::warning('Incomplete media data', ['media' => $media]);
80 if (DBA::exists('post-media', ['uri-id' => $media['uri-id'], 'preview' => $media['url']])) {
81 Logger::info('Media already exists as preview', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
85 // "document" has got the lowest priority. So when the same file is both attached as document
86 // and embedded as picture then we only store the picture or replace the document
87 $found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
88 if (!$force && !empty($found) && (($found['type'] != self::DOCUMENT) || ($media['type'] == self::DOCUMENT))) {
89 Logger::info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
93 if (!ItemURI::exists($media['uri-id'])) {
94 Logger::info('Media referenced URI ID not found', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
98 $media = self::unsetEmptyFields($media);
99 $media = DI::dbaDefinition()->truncateFieldsForTable('post-media', $media);
101 // We are storing as fast as possible to avoid duplicated network requests
102 // when fetching additional information for pictures and other content.
103 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
104 Logger::info('Stored media', ['result' => $result, 'media' => $media, 'callstack' => System::callstack()]);
107 $media = self::fetchAdditionalData($media);
108 $media = self::unsetEmptyFields($media);
109 $media = DI::dbaDefinition()->truncateFieldsForTable('post-media', $media);
111 if (array_diff_assoc($media, $stored)) {
112 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
113 Logger::info('Updated media', ['result' => $result, 'media' => $media]);
115 Logger::info('Nothing to update', ['media' => $media]);
120 * Remove empty media fields
122 * @param array $media
123 * @return array cleaned media array
125 private static function unsetEmptyFields(array $media): array
127 $fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'blurhash', 'description'];
128 foreach ($fields as $field) {
129 if (empty($media[$field])) {
130 unset($media[$field]);
137 * Copy attachments from one uri-id to another
139 * @param integer $from_uri_id
140 * @param integer $to_uri_id
143 public static function copy(int $from_uri_id, int $to_uri_id)
145 $attachments = self::getByURIId($from_uri_id);
146 foreach ($attachments as $attachment) {
147 $attachment['uri-id'] = $to_uri_id;
148 self::insert($attachment);
153 * Creates the "[attach]" element from the given attributes
155 * @param string $href
156 * @param integer $length
157 * @param string $type
158 * @param string $title
159 * @return string "[attach]" element
161 public static function getAttachElement(string $href, int $length, string $type, string $title = ''): string
163 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
164 'size' => $length, 'mimetype' => $type, 'description' => $title]);
166 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
167 '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
171 * Fetch additional data for the provided media array
173 * @param array $media
174 * @return array media array with additional data
176 public static function fetchAdditionalData(array $media): array
178 if (Network::isLocalLink($media['url'])) {
179 $media = self::fetchLocalData($media);
182 // Fetch the mimetype or size if missing.
183 if (empty($media['mimetype']) || empty($media['size'])) {
184 $timeout = DI::config()->get('system', 'xrd_timeout');
185 $curlResult = DI::httpClient()->head($media['url'], [HttpClientOptions::TIMEOUT => $timeout]);
187 // Workaround for systems that can't handle a HEAD request
188 if (!$curlResult->isSuccess() && ($curlResult->getReturnCode() == 405)) {
189 $curlResult = DI::httpClient()->get($media['url'], HttpClientAccept::DEFAULT, [HttpClientOptions::TIMEOUT => $timeout]);
192 if ($curlResult->isSuccess()) {
193 if (empty($media['mimetype'])) {
194 $media['mimetype'] = $curlResult->getHeader('Content-Type')[0] ?? '';
196 if (empty($media['size'])) {
197 $media['size'] = (int)($curlResult->getHeader('Content-Length')[0] ?? 0);
200 Logger::notice('Could not fetch head', ['media' => $media]);
204 $filetype = !empty($media['mimetype']) ? strtolower(current(explode('/', $media['mimetype']))) : '';
206 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
207 $imagedata = Images::getInfoFromURLCached($media['url']);
209 $media['mimetype'] = $imagedata['mime'];
210 $media['size'] = $imagedata['size'];
211 $media['width'] = $imagedata[0];
212 $media['height'] = $imagedata[1];
213 $media['blurhash'] = $imagedata['blurhash'] ?? null;
215 Logger::notice('No image data', ['media' => $media]);
217 if (!empty($media['preview'])) {
218 $imagedata = Images::getInfoFromURLCached($media['preview']);
220 $media['preview-width'] = $imagedata[0];
221 $media['preview-height'] = $imagedata[1];
226 if ($media['type'] != self::DOCUMENT) {
227 $media = self::addType($media);
230 if (in_array($media['type'], [self::TEXT, self::APPLICATION, self::HTML, self::XML, self::PLAIN])) {
231 $media = self::addActivity($media);
234 if (in_array($media['type'], [self::TEXT, self::APPLICATION, self::HTML, self::XML, self::PLAIN])) {
235 $media = self::addAccount($media);
238 if ($media['type'] == self::HTML) {
239 $media = self::addPage($media);
246 * Adds the activity type if the media entry is linked to an activity
248 * @param array $media
251 private static function addActivity(array $media): array
253 $id = Item::fetchByLink($media['url']);
258 $item = Post::selectFirst([], ['id' => $id, 'network' => Protocol::FEDERATED]);
259 if (empty($item['id'])) {
260 Logger::debug('Not a federated activity', ['id' => $id, 'uri-id' => $media['uri-id'], 'url' => $media['url']]);
264 if (!empty($item['plink']) && Strings::compareLink($item['plink'], $media['url']) &&
265 parse_url($item['plink'], PHP_URL_HOST) != parse_url($item['uri'], PHP_URL_HOST)) {
266 Logger::debug('Not a link to an activity', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'plink' => $item['plink'], 'uri' => $item['uri']]);
270 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
271 $media['mimetype'] = 'application/activity+json';
272 } elseif ($item['network'] == Protocol::DIASPORA) {
273 $media['mimetype'] = 'application/xml';
276 $contact = Contact::getById($item['author-id'], ['avatar', 'gsid']);
277 if (!empty($contact['gsid'])) {
278 $gserver = DBA::selectFirst('gserver', ['url', 'site_name'], ['id' => $contact['gsid']]);
281 $media['type'] = self::ACTIVITY;
282 $media['media-uri-id'] = $item['uri-id'];
283 $media['height'] = null;
284 $media['width'] = null;
285 $media['preview'] = null;
286 $media['preview-height'] = null;
287 $media['preview-width'] = null;
288 $media['blurhash'] = null;
289 $media['description'] = $item['body'];
290 $media['name'] = $item['title'];
291 $media['author-url'] = $item['author-link'];
292 $media['author-name'] = $item['author-name'];
293 $media['author-image'] = $contact['avatar'] ?? $item['author-avatar'];
294 $media['publisher-url'] = $gserver['url'] ?? null;
295 $media['publisher-name'] = $gserver['site_name'] ?? null;
296 $media['publisher-image'] = null;
298 Logger::debug('Activity detected', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'plink' => $item['plink'], 'uri' => $item['uri']]);
303 * Adds the account type if the media entry is linked to an account
305 * @param array $media
308 private static function addAccount(array $media): array
310 $contact = Contact::getByURL($media['url'], false);
311 if (empty($contact) || ($contact['network'] == Protocol::PHANTOM)) {
315 if (in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
316 $media['mimetype'] = 'application/activity+json';
319 if (!empty($contact['gsid'])) {
320 $gserver = DBA::selectFirst('gserver', ['url', 'site_name'], ['id' => $contact['gsid']]);
323 $media['type'] = self::ACCOUNT;
324 $media['media-uri-id'] = $contact['uri-id'];
325 $media['height'] = null;
326 $media['width'] = null;
327 $media['preview'] = null;
328 $media['preview-height'] = null;
329 $media['preview-width'] = null;
330 $media['blurhash'] = null;
331 $media['description'] = $contact['about'];
332 $media['name'] = $contact['name'];
333 $media['author-url'] = $contact['url'];
334 $media['author-name'] = $contact['name'];
335 $media['author-image'] = $contact['avatar'];
336 $media['publisher-url'] = $gserver['url'] ?? null;
337 $media['publisher-name'] = $gserver['site_name'] ?? null;
338 $media['publisher-image'] = null;
340 Logger::debug('Account detected', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'uri' => $contact['url']]);
345 * Add page infos for HTML entries
347 * @param array $media
350 private static function addPage(array $media): array
352 $data = ParseUrl::getSiteinfoCached($media['url'], false);
353 $media['preview'] = $data['images'][0]['src'] ?? null;
354 $media['preview-height'] = $data['images'][0]['height'] ?? null;
355 $media['preview-width'] = $data['images'][0]['width'] ?? null;
356 $media['blurhash'] = $data['images'][0]['blurhash'] ?? null;
357 $media['description'] = $data['text'] ?? null;
358 $media['name'] = $data['title'] ?? null;
359 $media['author-url'] = $data['author_url'] ?? null;
360 $media['author-name'] = $data['author_name'] ?? null;
361 $media['author-image'] = $data['author_img'] ?? null;
362 $media['publisher-url'] = $data['publisher_url'] ?? null;
363 $media['publisher-name'] = $data['publisher_name'] ?? null;
364 $media['publisher-image'] = $data['publisher_img'] ?? null;
370 * Fetch media data from local resources
371 * @param array $media
372 * @return array media with added data
374 private static function fetchLocalData(array $media): array
376 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'] ?? '', $matches)) {
379 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
380 if (!empty($photo)) {
381 $media['mimetype'] = $photo['type'];
382 $media['size'] = $photo['datasize'];
383 $media['width'] = $photo['width'];
384 $media['height'] = $photo['height'];
385 $media['blurhash'] = $photo['blurhash'];
388 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['preview'] ?? '', $matches)) {
391 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
392 if (!empty($photo)) {
393 $media['preview-width'] = $photo['width'];
394 $media['preview-height'] = $photo['height'];
401 * Add the detected type to the media array
404 * @return array data array with the detected type
406 public static function addType(array $data): array
408 if (empty($data['mimetype'])) {
409 Logger::info('No MimeType provided', ['media' => $data]);
413 $type = explode('/', current(explode(';', $data['mimetype'])));
414 if (count($type) < 2) {
415 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $data]);
416 $data['type'] = self::UNKNOWN;
420 $filetype = strtolower($type[0]);
421 $subtype = strtolower($type[1]);
423 if ($filetype == 'image') {
424 $data['type'] = self::IMAGE;
425 } elseif ($filetype == 'video') {
426 $data['type'] = self::VIDEO;
427 } elseif ($filetype == 'audio') {
428 $data['type'] = self::AUDIO;
429 } elseif (($filetype == 'text') && ($subtype == 'html')) {
430 $data['type'] = self::HTML;
431 } elseif (($filetype == 'text') && ($subtype == 'xml')) {
432 $data['type'] = self::XML;
433 } elseif (($filetype == 'text') && ($subtype == 'plain')) {
434 $data['type'] = self::PLAIN;
435 } elseif ($filetype == 'text') {
436 $data['type'] = self::TEXT;
437 } elseif (($filetype == 'application') && ($subtype == 'x-bittorrent')) {
438 $data['type'] = self::TORRENT;
439 } elseif ($filetype == 'application') {
440 $data['type'] = self::APPLICATION;
442 $data['type'] = self::UNKNOWN;
443 Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
447 Logger::debug('Detected type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
452 * Tests for path patterns that are usef for picture links in Friendica
454 * @param string $page Link to the image page
455 * @param string $preview Preview picture
458 private static function isPictureLink(string $page, string $preview): bool
460 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
464 * Add media links and remove them from the body
466 * @param integer $uriid
467 * @param string $body
468 * @return string Body without media links
470 public static function insertFromBody(int $uriid, string $body, bool $endmatch = false): string
472 $endmatchpattern = $endmatch ? '\z' : '';
473 // Simplify image codes
474 $unshared_body = $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]$endmatchpattern/ism", '[img]$3[/img]', $body);
477 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]$endmatchpattern#ism", $body, $pictures, PREG_SET_ORDER)) {
478 foreach ($pictures as $picture) {
479 if (!self::isPictureLink($picture[1], $picture[2])) {
482 $body = str_replace($picture[0], '', $body);
483 $image = str_replace('-1.', '-0.', $picture[2]);
484 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
485 'preview' => $picture[2], 'description' => $picture[3]];
489 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]$endmatchpattern/Usi", $body, $pictures, PREG_SET_ORDER)) {
490 foreach ($pictures as $picture) {
491 $body = str_replace($picture[0], '', $body);
492 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
496 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]$endmatchpattern#ism", $body, $pictures, PREG_SET_ORDER)) {
497 foreach ($pictures as $picture) {
498 if (!self::isPictureLink($picture[1], $picture[2])) {
501 $body = str_replace($picture[0], '', $body);
502 $image = str_replace('-1.', '-0.', $picture[2]);
503 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
504 'preview' => $picture[2], 'description' => null];
508 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]$endmatchpattern/ism", $body, $pictures, PREG_SET_ORDER)) {
509 foreach ($pictures as $picture) {
510 $body = str_replace($picture[0], '', $body);
511 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
515 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]$endmatchpattern/ism", $body, $audios, PREG_SET_ORDER)) {
516 foreach ($audios as $audio) {
517 $body = str_replace($audio[0], '', $body);
518 $attachments[$audio[1]] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
522 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]$endmatchpattern/ism", $body, $videos, PREG_SET_ORDER)) {
523 foreach ($videos as $video) {
524 $body = str_replace($video[0], '', $body);
525 $attachments[$video[1]] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
530 foreach ($attachments as $attachment) {
531 if (Post\Link::exists($uriid, $attachment['preview'] ?? $attachment['url'])) {
535 // Only store attachments that are part of the unshared body
536 if (Item::containsLink($unshared_body, $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
537 self::insert($attachment);
546 * Remove media that is at the end of the body
548 * @param string $body
551 public static function removeFromEndOfBody(string $body): string
555 $body = self::insertFromBody(0, $body, true);
556 } while ($prebody != $body);
561 * Add media links from a relevant url in the body
563 * @param integer $uriid
564 * @param string $body
567 public static function insertFromRelevantUrl(int $uriid, string $body, string $fullbody, string $network)
569 // Remove all hashtags and mentions
570 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '', $body);
572 // Search for pure links
573 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) {
574 foreach ($matches[1] as $url) {
575 Logger::info('Got page url (link without description)', ['uri-id' => $uriid, 'url' => $url]);
576 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url], false, $network);
577 if ($network == Protocol::DFRN) {
578 self::revertHTMLType($uriid, $url, $fullbody);
583 // Search for links with descriptions
584 if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) {
585 foreach ($matches[1] as $url) {
586 Logger::info('Got page url (link with description)', ['uri-id' => $uriid, 'url' => $url]);
587 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url], false, $network);
588 if ($network == Protocol::DFRN) {
589 self::revertHTMLType($uriid, $url, $fullbody);
596 * Revert the media type of links to UNKNOWN for DFRN posts when they aren't attached
598 * @param integer $uriid
600 * @param string $body
603 private static function revertHTMLType(int $uriid, string $url, string $body)
605 $attachment = BBCode::getAttachmentData($body);
606 if (!empty($attachment['url']) && Network::getUrlMatch($attachment['url'], $url)) {
609 DBA::update('post-media', ['type' => self::UNKNOWN], ['uri-id' => $uriid, 'type' => self::HTML, 'url' => $url]);
613 * Add media links from the attachment field
615 * @param integer $uriid
616 * @param string $body
619 public static function insertFromAttachmentData(int $uriid, string $body)
621 $data = BBCode::getAttachmentData($body);
626 Logger::info('Adding attachment data', ['data' => $data]);
629 'type' => self::HTML,
630 'url' => $data['url'],
631 'preview' => $data['preview'] ?? null,
632 'description' => $data['description'] ?? null,
633 'name' => $data['title'] ?? null,
634 'author-url' => $data['author_url'] ?? null,
635 'author-name' => $data['author_name'] ?? null,
636 'publisher-url' => $data['provider_url'] ?? null,
637 'publisher-name' => $data['provider_name'] ?? null,
639 if (!empty($data['image'])) {
640 $attachment['preview'] = $data['image'];
642 self::insert($attachment);
646 * Add media links from the attach field
648 * @param integer $uriid
649 * @param string $attach
652 public static function insertFromAttachment(int $uriid, string $attach)
654 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
658 foreach ($matches as $attachment) {
659 $media['type'] = self::DOCUMENT;
660 $media['uri-id'] = $uriid;
661 $media['url'] = $attachment[1];
662 $media['size'] = $attachment[2];
663 $media['mimetype'] = $attachment[3];
664 $media['description'] = $attachment[4] ?? '';
666 self::insert($media);
671 * Retrieves the media attachments associated with the provided item ID.
673 * @param int $uri_id URI id
674 * @param array $types Media types
675 * @return array|bool Array on success, false on error
678 public static function getByURIId(int $uri_id, array $types = [])
680 $condition = ["`uri-id` = ? AND `type` != ?", $uri_id, self::UNKNOWN];
682 if (!empty($types)) {
683 $condition = DBA::mergeConditions($condition, ['type' => $types]);
686 return DBA::selectToArray('post-media', [], $condition, ['order' => ['id']]);
690 * Checks if media attachments are associated with the provided item ID.
692 * @param int $uri_id URI id
693 * @param array $types Media types
694 * @return bool Whether media attachment exists
697 public static function existsByURIId(int $uri_id, array $types = []): bool
699 $condition = ["`uri-id` = ? AND `type` != ?", $uri_id, self::UNKNOWN];
701 if (!empty($types)) {
702 $condition = DBA::mergeConditions($condition, ['type' => $types]);
705 return DBA::exists('post-media', $condition);
709 * Split the attachment media in the three segments "visual", "link" and "additional"
711 * @param int $uri_id URI id
712 * @param array $links list of links that shouldn't be added
713 * @param bool $has_media
714 * @return array attachments
716 public static function splitAttachments(int $uri_id, array $links = [], bool $has_media = true): array
718 $attachments = ['visual' => [], 'link' => [], 'additional' => []];
724 $media = self::getByURIId($uri_id);
733 foreach ($media as $medium) {
734 foreach ($links as $link) {
735 if (Strings::compareLink($link, $medium['url'])) {
740 // Avoid adding separate media entries for previews
741 foreach ($previews as $preview) {
742 if (Strings::compareLink($preview, $medium['url'])) {
747 // Currently these two types are ignored here.
748 // Posts are added differently and contacts are not displayed as attachments.
749 if (in_array($medium['type'], [self::ACCOUNT, self::ACTIVITY])) {
753 if (!empty($medium['preview'])) {
754 $previews[] = $medium['preview'];
757 $type = explode('/', explode(';', $medium['mimetype'] ?? '')[0]);
758 if (count($type) < 2) {
759 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $medium]);
763 $filetype = strtolower($type[0]);
764 $subtype = strtolower($type[1]);
767 $medium['filetype'] = $filetype;
768 $medium['subtype'] = $subtype;
770 if ($medium['type'] == self::HTML || (($filetype == 'text') && ($subtype == 'html'))) {
771 $attachments['link'][] = $medium;
775 if (in_array($medium['type'], [self::AUDIO, self::IMAGE]) ||
776 in_array($filetype, ['audio', 'image'])) {
777 $attachments['visual'][] = $medium;
778 } elseif (($medium['type'] == self::VIDEO) || ($filetype == 'video')) {
779 if (!empty($medium['height'])) {
780 // Peertube videos are delivered in many different resolutions. We pick a moderate one.
781 // Since only Peertube provides a "height" parameter, this wouldn't be executed
782 // when someone for example on Mastodon was sharing multiple videos in a single post.
783 $heights[$medium['height']] = $medium['url'];
784 $video[$medium['url']] = $medium;
786 $attachments['visual'][] = $medium;
789 $attachments['additional'][] = $medium;
793 if (!empty($heights)) {
795 foreach ($heights as $height => $url) {
796 if (empty($selected) || $height <= 480) {
801 if (!empty($selected)) {
802 $attachments['visual'][] = $video[$selected];
803 unset($video[$selected]);
804 foreach ($video as $element) {
805 $attachments['additional'][] = $element;
814 * Add media attachments to the body
817 * @param string $body
818 * @param array $types
820 * @return string body
822 public static function addAttachmentsToBody(int $uriid, string $body = '', array $types = [self::IMAGE, self::AUDIO, self::VIDEO]): string
825 $item = Post::selectFirst(['body'], ['uri-id' => $uriid]);
826 if (!DBA::isResult($item)) {
829 $body = $item['body'];
831 $original_body = $body;
833 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
835 foreach (self::getByURIId($uriid, $types) as $media) {
836 if (Item::containsLink($body, $media['preview'] ?? $media['url'], $media['type'])) {
840 if ($media['type'] == self::IMAGE) {
841 if (!empty($media['preview'])) {
842 if (!empty($media['description'])) {
843 $body .= "\n[url=" . $media['url'] . "][img=" . $media['preview'] . ']' . $media['description'] .'[/img][/url]';
845 $body .= "\n[url=" . $media['url'] . "][img]" . $media['preview'] .'[/img][/url]';
848 if (!empty($media['description'])) {
849 $body .= "\n[img=" . $media['url'] . ']' . $media['description'] .'[/img]';
851 $body .= "\n[img]" . $media['url'] .'[/img]';
854 } elseif ($media['type'] == self::AUDIO) {
855 $body .= "\n[audio]" . $media['url'] . "[/audio]\n";
856 } elseif ($media['type'] == self::VIDEO) {
857 $body .= "\n[video]" . $media['url'] . "[/video]\n";
861 if (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $original_body, $match)) {
862 $body .= "\n" . $match[1];
869 * Get preview link for given media id
871 * @param integer $id media id
872 * @param string $size One of the Proxy::SIZE_* constants
873 * @return string preview link
875 public static function getPreviewUrlForId(int $id, string $size = ''): string
877 $url = DI::baseUrl() . '/photo/preview/';
879 case Proxy::SIZE_MICRO:
880 $url .= Proxy::PIXEL_MICRO . '/';
882 case Proxy::SIZE_THUMB:
883 $url .= Proxy::PIXEL_THUMB . '/';
885 case Proxy::SIZE_SMALL:
886 $url .= Proxy::PIXEL_SMALL . '/';
888 case Proxy::SIZE_MEDIUM:
889 $url .= Proxy::PIXEL_MEDIUM . '/';
891 case Proxy::SIZE_LARGE:
892 $url .= Proxy::PIXEL_LARGE . '/';
899 * Get media link for given media id
901 * @param integer $id media id
902 * @param string $size One of the Proxy::SIZE_* constants
903 * @return string media link
905 public static function getUrlForId(int $id, string $size = ''): string
907 $url = DI::baseUrl() . '/photo/media/';
909 case Proxy::SIZE_MICRO:
910 $url .= Proxy::PIXEL_MICRO . '/';
912 case Proxy::SIZE_THUMB:
913 $url .= Proxy::PIXEL_THUMB . '/';
915 case Proxy::SIZE_SMALL:
916 $url .= Proxy::PIXEL_SMALL . '/';
918 case Proxy::SIZE_MEDIUM:
919 $url .= Proxy::PIXEL_MEDIUM . '/';
921 case Proxy::SIZE_LARGE:
922 $url .= Proxy::PIXEL_LARGE . '/';