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): bool
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]);
121 * Remove empty media fields
123 * @param array $media
124 * @return array cleaned media array
126 private static function unsetEmptyFields(array $media): array
128 $fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'blurhash', 'description'];
129 foreach ($fields as $field) {
130 if (empty($media[$field])) {
131 unset($media[$field]);
138 * Copy attachments from one uri-id to another
140 * @param integer $from_uri_id
141 * @param integer $to_uri_id
144 public static function copy(int $from_uri_id, int $to_uri_id)
146 $attachments = self::getByURIId($from_uri_id);
147 foreach ($attachments as $attachment) {
148 $attachment['uri-id'] = $to_uri_id;
149 self::insert($attachment);
154 * Creates the "[attach]" element from the given attributes
156 * @param string $href
157 * @param integer $length
158 * @param string $type
159 * @param string $title
160 * @return string "[attach]" element
162 public static function getAttachElement(string $href, int $length, string $type, string $title = ''): string
164 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
165 'size' => $length, 'mimetype' => $type, 'description' => $title]);
167 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
168 '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
172 * Fetch additional data for the provided media array
174 * @param array $media
175 * @return array media array with additional data
177 public static function fetchAdditionalData(array $media): array
179 if (Network::isLocalLink($media['url'])) {
180 $media = self::fetchLocalData($media);
183 // Fetch the mimetype or size if missing.
184 if (Network::isValidHttpUrl($media['url']) && (empty($media['mimetype']) || empty($media['size']))) {
185 $timeout = DI::config()->get('system', 'xrd_timeout');
186 $curlResult = DI::httpClient()->head($media['url'], [HttpClientOptions::TIMEOUT => $timeout]);
188 // Workaround for systems that can't handle a HEAD request
189 if (!$curlResult->isSuccess() && ($curlResult->getReturnCode() == 405)) {
190 $curlResult = DI::httpClient()->get($media['url'], HttpClientAccept::DEFAULT, [HttpClientOptions::TIMEOUT => $timeout]);
193 if ($curlResult->isSuccess()) {
194 if (empty($media['mimetype'])) {
195 $media['mimetype'] = $curlResult->getHeader('Content-Type')[0] ?? '';
197 if (empty($media['size'])) {
198 $media['size'] = (int)($curlResult->getHeader('Content-Length')[0] ?? 0);
201 Logger::notice('Could not fetch head', ['media' => $media]);
205 $filetype = !empty($media['mimetype']) ? strtolower(current(explode('/', $media['mimetype']))) : '';
207 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
208 $imagedata = Images::getInfoFromURLCached($media['url']);
210 $media['mimetype'] = $imagedata['mime'];
211 $media['size'] = $imagedata['size'];
212 $media['width'] = $imagedata[0];
213 $media['height'] = $imagedata[1];
214 $media['blurhash'] = $imagedata['blurhash'] ?? null;
216 Logger::notice('No image data', ['media' => $media]);
218 if (!empty($media['preview'])) {
219 $imagedata = Images::getInfoFromURLCached($media['preview']);
221 $media['preview-width'] = $imagedata[0];
222 $media['preview-height'] = $imagedata[1];
227 if ($media['type'] != self::DOCUMENT) {
228 $media = self::addType($media);
231 if (in_array($media['type'], [self::TEXT, self::APPLICATION, self::HTML, self::XML, self::PLAIN])) {
232 $media = self::addActivity($media);
235 if (in_array($media['type'], [self::TEXT, self::APPLICATION, self::HTML, self::XML, self::PLAIN])) {
236 $media = self::addAccount($media);
239 if ($media['type'] == self::HTML) {
240 $media = self::addPage($media);
247 * Adds the activity type if the media entry is linked to an activity
249 * @param array $media
252 private static function addActivity(array $media): array
254 $id = Item::fetchByLink($media['url']);
259 $item = Post::selectFirst([], ['id' => $id, 'network' => Protocol::FEDERATED]);
260 if (empty($item['id'])) {
261 Logger::debug('Not a federated activity', ['id' => $id, 'uri-id' => $media['uri-id'], 'url' => $media['url']]);
265 if (!empty($item['plink']) && Strings::compareLink($item['plink'], $media['url']) &&
266 parse_url($item['plink'], PHP_URL_HOST) != parse_url($item['uri'], PHP_URL_HOST)) {
267 Logger::debug('Not a link to an activity', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'plink' => $item['plink'], 'uri' => $item['uri']]);
271 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
272 $media['mimetype'] = 'application/activity+json';
273 } elseif ($item['network'] == Protocol::DIASPORA) {
274 $media['mimetype'] = 'application/xml';
277 $contact = Contact::getById($item['author-id'], ['avatar', 'gsid']);
278 if (!empty($contact['gsid'])) {
279 $gserver = DBA::selectFirst('gserver', ['url', 'site_name'], ['id' => $contact['gsid']]);
282 $media['type'] = self::ACTIVITY;
283 $media['media-uri-id'] = $item['uri-id'];
284 $media['height'] = null;
285 $media['width'] = null;
286 $media['preview'] = null;
287 $media['preview-height'] = null;
288 $media['preview-width'] = null;
289 $media['blurhash'] = null;
290 $media['description'] = $item['body'];
291 $media['name'] = $item['title'];
292 $media['author-url'] = $item['author-link'];
293 $media['author-name'] = $item['author-name'];
294 $media['author-image'] = $contact['avatar'] ?? $item['author-avatar'];
295 $media['publisher-url'] = $gserver['url'] ?? null;
296 $media['publisher-name'] = $gserver['site_name'] ?? null;
297 $media['publisher-image'] = null;
299 Logger::debug('Activity detected', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'plink' => $item['plink'], 'uri' => $item['uri']]);
304 * Adds the account type if the media entry is linked to an account
306 * @param array $media
309 private static function addAccount(array $media): array
311 $contact = Contact::getByURL($media['url'], false);
312 if (empty($contact) || ($contact['network'] == Protocol::PHANTOM)) {
316 if (in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
317 $media['mimetype'] = 'application/activity+json';
320 if (!empty($contact['gsid'])) {
321 $gserver = DBA::selectFirst('gserver', ['url', 'site_name'], ['id' => $contact['gsid']]);
324 $media['type'] = self::ACCOUNT;
325 $media['media-uri-id'] = $contact['uri-id'];
326 $media['height'] = null;
327 $media['width'] = null;
328 $media['preview'] = null;
329 $media['preview-height'] = null;
330 $media['preview-width'] = null;
331 $media['blurhash'] = null;
332 $media['description'] = $contact['about'];
333 $media['name'] = $contact['name'];
334 $media['author-url'] = $contact['url'];
335 $media['author-name'] = $contact['name'];
336 $media['author-image'] = $contact['avatar'];
337 $media['publisher-url'] = $gserver['url'] ?? null;
338 $media['publisher-name'] = $gserver['site_name'] ?? null;
339 $media['publisher-image'] = null;
341 Logger::debug('Account detected', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'uri' => $contact['url']]);
346 * Add page infos for HTML entries
348 * @param array $media
351 private static function addPage(array $media): array
353 $data = ParseUrl::getSiteinfoCached($media['url'], false);
354 $media['preview'] = $data['images'][0]['src'] ?? null;
355 $media['preview-height'] = $data['images'][0]['height'] ?? null;
356 $media['preview-width'] = $data['images'][0]['width'] ?? null;
357 $media['blurhash'] = $data['images'][0]['blurhash'] ?? null;
358 $media['description'] = $data['text'] ?? null;
359 $media['name'] = $data['title'] ?? null;
360 $media['author-url'] = $data['author_url'] ?? null;
361 $media['author-name'] = $data['author_name'] ?? null;
362 $media['author-image'] = $data['author_img'] ?? null;
363 $media['publisher-url'] = $data['publisher_url'] ?? null;
364 $media['publisher-name'] = $data['publisher_name'] ?? null;
365 $media['publisher-image'] = $data['publisher_img'] ?? null;
371 * Fetch media data from local resources
372 * @param array $media
373 * @return array media with added data
375 private static function fetchLocalData(array $media): array
377 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'] ?? '', $matches)) {
380 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
381 if (!empty($photo)) {
382 $media['mimetype'] = $photo['type'];
383 $media['size'] = $photo['datasize'];
384 $media['width'] = $photo['width'];
385 $media['height'] = $photo['height'];
386 $media['blurhash'] = $photo['blurhash'];
389 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['preview'] ?? '', $matches)) {
392 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
393 if (!empty($photo)) {
394 $media['preview-width'] = $photo['width'];
395 $media['preview-height'] = $photo['height'];
402 * Add the detected type to the media array
405 * @return array data array with the detected type
407 public static function addType(array $data): array
409 if (empty($data['mimetype'])) {
410 Logger::info('No MimeType provided', ['media' => $data]);
414 $type = explode('/', current(explode(';', $data['mimetype'])));
415 if (count($type) < 2) {
416 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $data]);
417 $data['type'] = self::UNKNOWN;
421 $filetype = strtolower($type[0]);
422 $subtype = strtolower($type[1]);
424 if ($filetype == 'image') {
425 $data['type'] = self::IMAGE;
426 } elseif ($filetype == 'video') {
427 $data['type'] = self::VIDEO;
428 } elseif ($filetype == 'audio') {
429 $data['type'] = self::AUDIO;
430 } elseif (($filetype == 'text') && ($subtype == 'html')) {
431 $data['type'] = self::HTML;
432 } elseif (($filetype == 'text') && ($subtype == 'xml')) {
433 $data['type'] = self::XML;
434 } elseif (($filetype == 'text') && ($subtype == 'plain')) {
435 $data['type'] = self::PLAIN;
436 } elseif ($filetype == 'text') {
437 $data['type'] = self::TEXT;
438 } elseif (($filetype == 'application') && ($subtype == 'x-bittorrent')) {
439 $data['type'] = self::TORRENT;
440 } elseif ($filetype == 'application') {
441 $data['type'] = self::APPLICATION;
443 $data['type'] = self::UNKNOWN;
444 Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
448 Logger::debug('Detected type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
453 * Tests for path patterns that are usef for picture links in Friendica
455 * @param string $page Link to the image page
456 * @param string $preview Preview picture
459 private static function isPictureLink(string $page, string $preview): bool
461 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
465 * Add media links and remove them from the body
467 * @param integer $uriid
468 * @param string $body
469 * @return string Body without media links
471 public static function insertFromBody(int $uriid, string $body, bool $endmatch = false): string
473 $endmatchpattern = $endmatch ? '\z' : '';
474 // Simplify image codes
475 $unshared_body = $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]$endmatchpattern/ism", '[img]$3[/img]', $body);
478 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]$endmatchpattern#ism", $body, $pictures, PREG_SET_ORDER)) {
479 foreach ($pictures as $picture) {
480 if (!self::isPictureLink($picture[1], $picture[2])) {
483 $body = str_replace($picture[0], '', $body);
484 $image = str_replace('-1.', '-0.', $picture[2]);
485 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
486 'preview' => $picture[2], 'description' => $picture[3]];
490 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]$endmatchpattern/Usi", $body, $pictures, PREG_SET_ORDER)) {
491 foreach ($pictures as $picture) {
492 $body = str_replace($picture[0], '', $body);
493 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
497 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]$endmatchpattern#ism", $body, $pictures, PREG_SET_ORDER)) {
498 foreach ($pictures as $picture) {
499 if (!self::isPictureLink($picture[1], $picture[2])) {
502 $body = str_replace($picture[0], '', $body);
503 $image = str_replace('-1.', '-0.', $picture[2]);
504 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
505 'preview' => $picture[2], 'description' => null];
509 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]$endmatchpattern/ism", $body, $pictures, PREG_SET_ORDER)) {
510 foreach ($pictures as $picture) {
511 $body = str_replace($picture[0], '', $body);
512 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
516 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]$endmatchpattern/ism", $body, $audios, PREG_SET_ORDER)) {
517 foreach ($audios as $audio) {
518 $body = str_replace($audio[0], '', $body);
519 $attachments[$audio[1]] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
523 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]$endmatchpattern/ism", $body, $videos, PREG_SET_ORDER)) {
524 foreach ($videos as $video) {
525 $body = str_replace($video[0], '', $body);
526 $attachments[$video[1]] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
531 foreach ($attachments as $attachment) {
532 if (Post\Link::exists($uriid, $attachment['preview'] ?? $attachment['url'])) {
536 // Only store attachments that are part of the unshared body
537 if (Item::containsLink($unshared_body, $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
538 self::insert($attachment);
547 * Remove media that is at the end of the body
549 * @param string $body
552 public static function removeFromEndOfBody(string $body): string
556 $body = self::insertFromBody(0, $body, true);
557 } while ($prebody != $body);
562 * Add media links from a relevant url in the body
564 * @param integer $uriid
565 * @param string $body
568 public static function insertFromRelevantUrl(int $uriid, string $body, string $fullbody, string $network)
570 // Remove all hashtags and mentions
571 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '', $body);
573 // Search for pure links
574 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) {
575 foreach ($matches[1] as $url) {
576 Logger::info('Got page url (link without description)', ['uri-id' => $uriid, 'url' => $url]);
577 $result = self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url], false, $network);
578 if ($result && ($network == Protocol::DFRN)) {
579 self::revertHTMLType($uriid, $url, $fullbody);
580 Logger::debug('Revert HTML type', ['uri-id' => $uriid, 'url' => $url]);
582 Logger::debug('Media had been added', ['uri-id' => $uriid, 'url' => $url]);
584 Logger::debug('Media had not been added', ['uri-id' => $uriid, 'url' => $url]);
589 // Search for links with descriptions
590 if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) {
591 foreach ($matches[1] as $url) {
592 Logger::info('Got page url (link with description)', ['uri-id' => $uriid, 'url' => $url]);
593 $result = self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url], false, $network);
594 if ($result && ($network == Protocol::DFRN)) {
595 self::revertHTMLType($uriid, $url, $fullbody);
596 Logger::debug('Revert HTML type', ['uri-id' => $uriid, 'url' => $url]);
598 Logger::debug('Media had been added', ['uri-id' => $uriid, 'url' => $url]);
600 Logger::debug('Media had not been added', ['uri-id' => $uriid, 'url' => $url]);
607 * Revert the media type of links to UNKNOWN for DFRN posts when they aren't attached
609 * @param integer $uriid
611 * @param string $body
614 private static function revertHTMLType(int $uriid, string $url, string $body)
616 $attachment = BBCode::getAttachmentData($body);
617 if (!empty($attachment['url']) && Network::getUrlMatch($attachment['url'], $url)) {
620 DBA::update('post-media', ['type' => self::UNKNOWN], ['uri-id' => $uriid, 'type' => self::HTML, 'url' => $url]);
624 * Add media links from the attachment field
626 * @param integer $uriid
627 * @param string $body
630 public static function insertFromAttachmentData(int $uriid, string $body)
632 $data = BBCode::getAttachmentData($body);
637 Logger::info('Adding attachment data', ['data' => $data]);
640 'type' => self::HTML,
641 'url' => $data['url'],
642 'preview' => $data['preview'] ?? null,
643 'description' => $data['description'] ?? null,
644 'name' => $data['title'] ?? null,
645 'author-url' => $data['author_url'] ?? null,
646 'author-name' => $data['author_name'] ?? null,
647 'publisher-url' => $data['provider_url'] ?? null,
648 'publisher-name' => $data['provider_name'] ?? null,
650 if (!empty($data['image'])) {
651 $attachment['preview'] = $data['image'];
653 self::insert($attachment);
657 * Add media links from the attach field
659 * @param integer $uriid
660 * @param string $attach
663 public static function insertFromAttachment(int $uriid, string $attach)
665 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
669 foreach ($matches as $attachment) {
670 $media['type'] = self::DOCUMENT;
671 $media['uri-id'] = $uriid;
672 $media['url'] = $attachment[1];
673 $media['size'] = $attachment[2];
674 $media['mimetype'] = $attachment[3];
675 $media['description'] = $attachment[4] ?? '';
677 self::insert($media);
682 * Retrieves the media attachments associated with the provided item ID.
684 * @param int $uri_id URI id
685 * @param array $types Media types
686 * @return array|bool Array on success, false on error
689 public static function getByURIId(int $uri_id, array $types = [])
691 $condition = ["`uri-id` = ? AND `type` != ?", $uri_id, self::UNKNOWN];
693 if (!empty($types)) {
694 $condition = DBA::mergeConditions($condition, ['type' => $types]);
697 return DBA::selectToArray('post-media', [], $condition, ['order' => ['id']]);
701 * Checks if media attachments are associated with the provided item ID.
703 * @param int $uri_id URI id
704 * @param array $types Media types
705 * @return bool Whether media attachment exists
708 public static function existsByURIId(int $uri_id, array $types = []): bool
710 $condition = ["`uri-id` = ? AND `type` != ?", $uri_id, self::UNKNOWN];
712 if (!empty($types)) {
713 $condition = DBA::mergeConditions($condition, ['type' => $types]);
716 return DBA::exists('post-media', $condition);
720 * Delete media by uri-id and media type
722 * @param int $uri_id URI id
723 * @param array $types Media types
724 * @return bool Whether media attachment exists
727 public static function deleteByURIId(int $uri_id, array $types = []): bool
729 $condition = ['uri-id' => $uri_id];
731 if (!empty($types)) {
732 $condition = DBA::mergeConditions($condition, ['type' => $types]);
735 return DBA::delete('post-media', $condition);
739 * Split the attachment media in the three segments "visual", "link" and "additional"
741 * @param int $uri_id URI id
742 * @param array $links list of links that shouldn't be added
743 * @param bool $has_media
744 * @return array attachments
746 public static function splitAttachments(int $uri_id, array $links = [], bool $has_media = true): array
748 $attachments = ['visual' => [], 'link' => [], 'additional' => []];
754 $media = self::getByURIId($uri_id);
763 foreach ($media as $medium) {
764 foreach ($links as $link) {
765 if (Strings::compareLink($link, $medium['url'])) {
770 // Avoid adding separate media entries for previews
771 foreach ($previews as $preview) {
772 if (Strings::compareLink($preview, $medium['url'])) {
777 // Currently these two types are ignored here.
778 // Posts are added differently and contacts are not displayed as attachments.
779 if (in_array($medium['type'], [self::ACCOUNT, self::ACTIVITY])) {
783 if (!empty($medium['preview'])) {
784 $previews[] = $medium['preview'];
787 $type = explode('/', explode(';', $medium['mimetype'] ?? '')[0]);
788 if (count($type) < 2) {
789 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $medium]);
793 $filetype = strtolower($type[0]);
794 $subtype = strtolower($type[1]);
797 $medium['filetype'] = $filetype;
798 $medium['subtype'] = $subtype;
800 if ($medium['type'] == self::HTML || (($filetype == 'text') && ($subtype == 'html'))) {
801 $attachments['link'][] = $medium;
805 if (in_array($medium['type'], [self::AUDIO, self::IMAGE]) ||
806 in_array($filetype, ['audio', 'image'])) {
807 $attachments['visual'][] = $medium;
808 } elseif (($medium['type'] == self::VIDEO) || ($filetype == 'video')) {
809 if (!empty($medium['height'])) {
810 // Peertube videos are delivered in many different resolutions. We pick a moderate one.
811 // Since only Peertube provides a "height" parameter, this wouldn't be executed
812 // when someone for example on Mastodon was sharing multiple videos in a single post.
813 $heights[$medium['height']] = $medium['url'];
814 $video[$medium['url']] = $medium;
816 $attachments['visual'][] = $medium;
819 $attachments['additional'][] = $medium;
823 if (!empty($heights)) {
825 foreach ($heights as $height => $url) {
826 if (empty($selected) || $height <= 480) {
831 if (!empty($selected)) {
832 $attachments['visual'][] = $video[$selected];
833 unset($video[$selected]);
834 foreach ($video as $element) {
835 $attachments['additional'][] = $element;
844 * Add media attachments to the body
847 * @param string $body
848 * @param array $types
850 * @return string body
852 public static function addAttachmentsToBody(int $uriid, string $body = '', array $types = [self::IMAGE, self::AUDIO, self::VIDEO]): string
855 $item = Post::selectFirst(['body'], ['uri-id' => $uriid]);
856 if (!DBA::isResult($item)) {
859 $body = $item['body'];
861 $original_body = $body;
863 $body = BBCode::removeAttachment($body);
865 foreach (self::getByURIId($uriid, $types) as $media) {
866 if (Item::containsLink($body, $media['preview'] ?? $media['url'], $media['type'])) {
870 if ($media['type'] == self::IMAGE) {
871 if (!empty($media['preview'])) {
872 if (!empty($media['description'])) {
873 $body .= "\n[url=" . $media['url'] . "][img=" . $media['preview'] . ']' . $media['description'] .'[/img][/url]';
875 $body .= "\n[url=" . $media['url'] . "][img]" . $media['preview'] .'[/img][/url]';
878 if (!empty($media['description'])) {
879 $body .= "\n[img=" . $media['url'] . ']' . $media['description'] .'[/img]';
881 $body .= "\n[img]" . $media['url'] .'[/img]';
884 } elseif ($media['type'] == self::AUDIO) {
885 $body .= "\n[audio]" . $media['url'] . "[/audio]\n";
886 } elseif ($media['type'] == self::VIDEO) {
887 $body .= "\n[video]" . $media['url'] . "[/video]\n";
891 if (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $original_body, $match)) {
892 $body .= "\n" . $match[1];
899 * Get preview link for given media id
901 * @param integer $id media id
902 * @param string $size One of the Proxy::SIZE_* constants
903 * @return string preview link
905 public static function getPreviewUrlForId(int $id, string $size = ''): string
907 $url = DI::baseUrl() . '/photo/preview/';
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 . '/';
929 * Get media link for given media id
931 * @param integer $id media id
932 * @param string $size One of the Proxy::SIZE_* constants
933 * @return string media link
935 public static function getUrlForId(int $id, string $size = ''): string
937 $url = DI::baseUrl() . '/photo/media/';
939 case Proxy::SIZE_MICRO:
940 $url .= Proxy::PIXEL_MICRO . '/';
942 case Proxy::SIZE_THUMB:
943 $url .= Proxy::PIXEL_THUMB . '/';
945 case Proxy::SIZE_SMALL:
946 $url .= Proxy::PIXEL_SMALL . '/';
948 case Proxy::SIZE_MEDIUM:
949 $url .= Proxy::PIXEL_MEDIUM . '/';
951 case Proxy::SIZE_LARGE:
952 $url .= Proxy::PIXEL_LARGE . '/';