3 * @copyright Copyright (C) 2010-2022, 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\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;
46 * This Model class handles media interactions.
47 * This tables stores medias (images, videos, audio files) related to posts.
56 const APPLICATION = 5;
66 * Insert a post-media record
71 public static function insert(array $media, bool $force = false)
73 if (empty($media['url']) || empty($media['uri-id']) || !isset($media['type'])) {
74 Logger::warning('Incomplete media data', ['media' => $media]);
78 if (DBA::exists('post-media', ['uri-id' => $media['uri-id'], 'preview' => $media['url']])) {
79 Logger::info('Media already exists as preview', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
83 // "document" has got the lowest priority. So when the same file is both attached as document
84 // and embedded as picture then we only store the picture or replace the document
85 $found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
86 if (!$force && !empty($found) && (($found['type'] != self::DOCUMENT) || ($media['type'] == self::DOCUMENT))) {
87 Logger::info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
91 $media = self::unsetEmptyFields($media);
92 $media = DI::dbaDefinition()->truncateFieldsForTable('post-media', $media);
94 // We are storing as fast as possible to avoid duplicated network requests
95 // when fetching additional information for pictures and other content.
96 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
97 Logger::info('Stored media', ['result' => $result, 'media' => $media, 'callstack' => System::callstack()]);
100 $media = self::fetchAdditionalData($media);
101 $media = self::unsetEmptyFields($media);
102 $media = DI::dbaDefinition()->truncateFieldsForTable('post-media', $media);
104 if (array_diff_assoc($media, $stored)) {
105 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
106 Logger::info('Updated media', ['result' => $result, 'media' => $media]);
108 Logger::info('Nothing to update', ['media' => $media]);
113 * Remove empty media fields
115 * @param array $media
116 * @return array cleaned media array
118 private static function unsetEmptyFields(array $media): array
120 $fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'blurhash', 'description'];
121 foreach ($fields as $field) {
122 if (empty($media[$field])) {
123 unset($media[$field]);
130 * Copy attachments from one uri-id to another
132 * @param integer $from_uri_id
133 * @param integer $to_uri_id
136 public static function copy(int $from_uri_id, int $to_uri_id)
138 $attachments = self::getByURIId($from_uri_id);
139 foreach ($attachments as $attachment) {
140 $attachment['uri-id'] = $to_uri_id;
141 self::insert($attachment);
146 * Creates the "[attach]" element from the given attributes
148 * @param string $href
149 * @param integer $length
150 * @param string $type
151 * @param string $title
152 * @return string "[attach]" element
154 public static function getAttachElement(string $href, int $length, string $type, string $title = ''): string
156 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
157 'size' => $length, 'mimetype' => $type, 'description' => $title]);
159 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
160 '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
164 * Fetch additional data for the provided media array
166 * @param array $media
167 * @return array media array with additional data
169 public static function fetchAdditionalData(array $media): array
171 if (Network::isLocalLink($media['url'])) {
172 $media = self::fetchLocalData($media);
175 // Fetch the mimetype or size if missing.
176 if (empty($media['mimetype']) || empty($media['size'])) {
177 $timeout = DI::config()->get('system', 'xrd_timeout');
178 $curlResult = DI::httpClient()->head($media['url'], [HttpClientOptions::TIMEOUT => $timeout]);
180 // Workaround for systems that can't handle a HEAD request
181 if (!$curlResult->isSuccess() && ($curlResult->getReturnCode() == 405)) {
182 $curlResult = DI::httpClient()->get($media['url'], HttpClientAccept::DEFAULT, [HttpClientOptions::TIMEOUT => $timeout]);
185 if ($curlResult->isSuccess()) {
186 if (empty($media['mimetype'])) {
187 $media['mimetype'] = $curlResult->getHeader('Content-Type')[0] ?? '';
189 if (empty($media['size'])) {
190 $media['size'] = (int)($curlResult->getHeader('Content-Length')[0] ?? 0);
193 Logger::notice('Could not fetch head', ['media' => $media]);
197 $filetype = !empty($media['mimetype']) ? strtolower(current(explode('/', $media['mimetype']))) : '';
199 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
200 $imagedata = Images::getInfoFromURLCached($media['url']);
202 $media['mimetype'] = $imagedata['mime'];
203 $media['size'] = $imagedata['size'];
204 $media['width'] = $imagedata[0];
205 $media['height'] = $imagedata[1];
206 $media['blurhash'] = $imagedata['blurhash'] ?? null;
208 Logger::notice('No image data', ['media' => $media]);
210 if (!empty($media['preview'])) {
211 $imagedata = Images::getInfoFromURLCached($media['preview']);
213 $media['preview-width'] = $imagedata[0];
214 $media['preview-height'] = $imagedata[1];
219 if ($media['type'] != self::DOCUMENT) {
220 $media = self::addType($media);
223 if (in_array($media['type'], [self::TEXT, self::APPLICATION, self::HTML, self::XML, self::PLAIN])) {
224 $media = self::addActivity($media);
227 if (in_array($media['type'], [self::TEXT, self::APPLICATION, self::HTML, self::XML, self::PLAIN])) {
228 $media = self::addAccount($media);
231 if ($media['type'] == self::HTML) {
232 $data = ParseUrl::getSiteinfoCached($media['url'], false);
233 $media['preview'] = $data['images'][0]['src'] ?? null;
234 $media['preview-height'] = $data['images'][0]['height'] ?? null;
235 $media['preview-width'] = $data['images'][0]['width'] ?? null;
236 $media['blurhash'] = $data['images'][0]['blurhash'] ?? null;
237 $media['description'] = $data['text'] ?? null;
238 $media['name'] = $data['title'] ?? null;
239 $media['author-url'] = $data['author_url'] ?? null;
240 $media['author-name'] = $data['author_name'] ?? null;
241 $media['author-image'] = $data['author_img'] ?? null;
242 $media['publisher-url'] = $data['publisher_url'] ?? null;
243 $media['publisher-name'] = $data['publisher_name'] ?? null;
244 $media['publisher-image'] = $data['publisher_img'] ?? null;
250 * Adds the activity type if the media entry is linked to an activity
252 * @param array $media
255 private static function addActivity(array $media): array
257 $id = Item::fetchByLink($media['url']);
262 $item = Post::selectFirst([], ['id' => $id, 'network' => Protocol::FEDERATED]);
263 if (empty($item['id'])) {
264 Logger::debug('Not a federated activity', ['id' => $id, 'uri-id' => $media['uri-id'], 'url' => $media['url']]);
268 if (!empty($item['plink']) && Strings::compareLink($item['plink'], $media['url']) &&
269 parse_url($item['plink'], PHP_URL_HOST) != parse_url($item['uri'], PHP_URL_HOST)) {
270 Logger::debug('Not a link to an activity', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'plink' => $item['plink'], 'uri' => $item['uri']]);
274 if (in_array($item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
275 $media['mimetype'] = 'application/activity+json';
276 } elseif ($item['network'] == Protocol::DIASPORA) {
277 $media['mimetype'] = 'application/xml';
280 $contact = Contact::getById($item['author-id'], ['avatar', 'gsid']);
281 if (!empty($contact['gsid'])) {
282 $gserver = DBA::selectFirst('gserver', ['url', 'site_name'], ['id' => $contact['gsid']]);
285 $media['type'] = self::ACTIVITY;
286 $media['media-uri-id'] = $item['uri-id'];
287 $media['height'] = null;
288 $media['width'] = null;
289 $media['preview'] = null;
290 $media['preview-height'] = null;
291 $media['preview-width'] = null;
292 $media['blurhash'] = null;
293 $media['description'] = $item['body'];
294 $media['name'] = $item['title'];
295 $media['author-url'] = $item['author-link'];
296 $media['author-name'] = $item['author-name'];
297 $media['author-image'] = $contact['avatar'] ?? $item['author-avatar'];
298 $media['publisher-url'] = $gserver['url'] ?? null;
299 $media['publisher-name'] = $gserver['site_name'] ?? null;
300 $media['publisher-image'] = null;
302 Logger::debug('Activity detected', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'plink' => $item['plink'], 'uri' => $item['uri']]);
307 * Adds the account type if the media entry is linked to an account
309 * @param array $media
312 private static function addAccount(array $media): array
314 $contact = Contact::getByURL($media['url'], false);
315 if (empty($contact) || ($contact['network'] == Protocol::PHANTOM)) {
319 if (in_array($contact['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
320 $media['mimetype'] = 'application/activity+json';
323 if (!empty($contact['gsid'])) {
324 $gserver = DBA::selectFirst('gserver', ['url', 'site_name'], ['id' => $contact['gsid']]);
327 $media['type'] = self::ACCOUNT;
328 $media['media-uri-id'] = $contact['uri-id'];
329 $media['height'] = null;
330 $media['width'] = null;
331 $media['preview'] = null;
332 $media['preview-height'] = null;
333 $media['preview-width'] = null;
334 $media['blurhash'] = null;
335 $media['description'] = $contact['about'];
336 $media['name'] = $contact['name'];
337 $media['author-url'] = $contact['url'];
338 $media['author-name'] = $contact['name'];
339 $media['author-image'] = $contact['avatar'];
340 $media['publisher-url'] = $gserver['url'] ?? null;
341 $media['publisher-name'] = $gserver['site_name'] ?? null;
342 $media['publisher-image'] = null;
344 Logger::debug('Account detected', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'uri' => $contact['url']]);
349 * Fetch media data from local resources
350 * @param array $media
351 * @return array media with added data
353 private static function fetchLocalData(array $media): array
355 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'] ?? '', $matches)) {
358 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
359 if (!empty($photo)) {
360 $media['mimetype'] = $photo['type'];
361 $media['size'] = $photo['datasize'];
362 $media['width'] = $photo['width'];
363 $media['height'] = $photo['height'];
364 $media['blurhash'] = $photo['blurhash'];
367 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['preview'] ?? '', $matches)) {
370 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
371 if (!empty($photo)) {
372 $media['preview-width'] = $photo['width'];
373 $media['preview-height'] = $photo['height'];
380 * Add the detected type to the media array
383 * @return array data array with the detected type
385 public static function addType(array $data): array
387 if (empty($data['mimetype'])) {
388 Logger::info('No MimeType provided', ['media' => $data]);
392 $type = explode('/', current(explode(';', $data['mimetype'])));
393 if (count($type) < 2) {
394 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $data]);
395 $data['type'] = self::UNKNOWN;
399 $filetype = strtolower($type[0]);
400 $subtype = strtolower($type[1]);
402 if ($filetype == 'image') {
403 $data['type'] = self::IMAGE;
404 } elseif ($filetype == 'video') {
405 $data['type'] = self::VIDEO;
406 } elseif ($filetype == 'audio') {
407 $data['type'] = self::AUDIO;
408 } elseif (($filetype == 'text') && ($subtype == 'html')) {
409 $data['type'] = self::HTML;
410 } elseif (($filetype == 'text') && ($subtype == 'xml')) {
411 $data['type'] = self::XML;
412 } elseif (($filetype == 'text') && ($subtype == 'plain')) {
413 $data['type'] = self::PLAIN;
414 } elseif ($filetype == 'text') {
415 $data['type'] = self::TEXT;
416 } elseif (($filetype == 'application') && ($subtype == 'x-bittorrent')) {
417 $data['type'] = self::TORRENT;
418 } elseif ($filetype == 'application') {
419 $data['type'] = self::APPLICATION;
421 $data['type'] = self::UNKNOWN;
422 Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
426 Logger::debug('Detected type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
431 * Tests for path patterns that are usef for picture links in Friendica
433 * @param string $page Link to the image page
434 * @param string $preview Preview picture
437 private static function isPictureLink(string $page, string $preview): bool
439 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
443 * Add media links and remove them from the body
445 * @param integer $uriid
446 * @param string $body
447 * @return string Body without media links
449 public static function insertFromBody(int $uriid, string $body, bool $endmatch = false): string
451 $endmatchpattern = $endmatch ? '\z' : '';
452 // Simplify image codes
453 $unshared_body = $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]$endmatchpattern/ism", '[img]$3[/img]', $body);
456 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]$endmatchpattern#ism", $body, $pictures, PREG_SET_ORDER)) {
457 foreach ($pictures as $picture) {
458 if (!self::isPictureLink($picture[1], $picture[2])) {
461 $body = str_replace($picture[0], '', $body);
462 $image = str_replace('-1.', '-0.', $picture[2]);
463 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
464 'preview' => $picture[2], 'description' => $picture[3]];
468 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]$endmatchpattern/Usi", $body, $pictures, PREG_SET_ORDER)) {
469 foreach ($pictures as $picture) {
470 $body = str_replace($picture[0], '', $body);
471 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
475 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]$endmatchpattern#ism", $body, $pictures, PREG_SET_ORDER)) {
476 foreach ($pictures as $picture) {
477 if (!self::isPictureLink($picture[1], $picture[2])) {
480 $body = str_replace($picture[0], '', $body);
481 $image = str_replace('-1.', '-0.', $picture[2]);
482 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
483 'preview' => $picture[2], 'description' => null];
487 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]$endmatchpattern/ism", $body, $pictures, PREG_SET_ORDER)) {
488 foreach ($pictures as $picture) {
489 $body = str_replace($picture[0], '', $body);
490 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
494 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]$endmatchpattern/ism", $body, $audios, PREG_SET_ORDER)) {
495 foreach ($audios as $audio) {
496 $body = str_replace($audio[0], '', $body);
497 $attachments[$audio[1]] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
501 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]$endmatchpattern/ism", $body, $videos, PREG_SET_ORDER)) {
502 foreach ($videos as $video) {
503 $body = str_replace($video[0], '', $body);
504 $attachments[$video[1]] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
509 foreach ($attachments as $attachment) {
510 if (Post\Link::exists($uriid, $attachment['preview'] ?? $attachment['url'])) {
514 // Only store attachments that are part of the unshared body
515 if (Item::containsLink($unshared_body, $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
516 self::insert($attachment);
525 * Remove media that is at the end of the body
527 * @param string $body
530 public static function removeFromEndOfBody(string $body): string
534 $body = self::insertFromBody(0, $body, true);
535 } while ($prebody != $body);
540 * Add media links from a relevant url in the body
542 * @param integer $uriid
543 * @param string $body
546 public static function insertFromRelevantUrl(int $uriid, string $body)
548 // Remove all hashtags and mentions
549 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '', $body);
551 // Search for pure links
552 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) {
553 foreach ($matches[1] as $url) {
554 Logger::info('Got page url (link without description)', ['uri-id' => $uriid, 'url' => $url]);
555 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
559 // Search for links with descriptions
560 if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) {
561 foreach ($matches[1] as $url) {
562 Logger::info('Got page url (link with description)', ['uri-id' => $uriid, 'url' => $url]);
563 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
569 * Add media links from the attachment field
571 * @param integer $uriid
572 * @param string $body
575 public static function insertFromAttachmentData(int $uriid, string $body)
577 $data = BBCode::getAttachmentData($body);
582 Logger::info('Adding attachment data', ['data' => $data]);
585 'type' => self::HTML,
586 'url' => $data['url'],
587 'preview' => $data['preview'] ?? null,
588 'description' => $data['description'] ?? null,
589 'name' => $data['title'] ?? null,
590 'author-url' => $data['author_url'] ?? null,
591 'author-name' => $data['author_name'] ?? null,
592 'publisher-url' => $data['provider_url'] ?? null,
593 'publisher-name' => $data['provider_name'] ?? null,
595 if (!empty($data['image'])) {
596 $attachment['preview'] = $data['image'];
598 self::insert($attachment);
602 * Add media links from the attach field
604 * @param integer $uriid
605 * @param string $attach
608 public static function insertFromAttachment(int $uriid, string $attach)
610 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
614 foreach ($matches as $attachment) {
615 $media['type'] = self::DOCUMENT;
616 $media['uri-id'] = $uriid;
617 $media['url'] = $attachment[1];
618 $media['size'] = $attachment[2];
619 $media['mimetype'] = $attachment[3];
620 $media['description'] = $attachment[4] ?? '';
622 self::insert($media);
627 * Retrieves the media attachments associated with the provided item ID.
629 * @param int $uri_id URI id
630 * @param array $types Media types
631 * @return array|bool Array on success, false on error
634 public static function getByURIId(int $uri_id, array $types = [])
636 $condition = ['uri-id' => $uri_id];
638 if (!empty($types)) {
639 $condition = DBA::mergeConditions($condition, ['type' => $types]);
642 return DBA::selectToArray('post-media', [], $condition, ['order' => ['id']]);
646 * Checks if media attachments are associated with the provided item ID.
648 * @param int $uri_id URI id
649 * @param array $types Media types
650 * @return bool Whether media attachment exists
653 public static function existsByURIId(int $uri_id, array $types = []): bool
655 $condition = ['uri-id' => $uri_id];
657 if (!empty($types)) {
658 $condition = DBA::mergeConditions($condition, ['type' => $types]);
661 return DBA::exists('post-media', $condition);
665 * Split the attachment media in the three segments "visual", "link" and "additional"
667 * @param int $uri_id URI id
668 * @param array $links list of links that shouldn't be added
669 * @param bool $has_media
670 * @return array attachments
672 public static function splitAttachments(int $uri_id, array $links = [], bool $has_media = true): array
674 $attachments = ['visual' => [], 'link' => [], 'additional' => []];
680 $media = self::getByURIId($uri_id);
689 foreach ($media as $medium) {
690 foreach ($links as $link) {
691 if (Strings::compareLink($link, $medium['url'])) {
696 // Avoid adding separate media entries for previews
697 foreach ($previews as $preview) {
698 if (Strings::compareLink($preview, $medium['url'])) {
703 // Currently these two types are ignored here.
704 // Posts are added differently and contacts are not displayed as attachments.
705 if (in_array($medium['type'], [self::ACCOUNT, self::ACTIVITY])) {
709 if (!empty($medium['preview'])) {
710 $previews[] = $medium['preview'];
713 $type = explode('/', explode(';', $medium['mimetype'] ?? '')[0]);
714 if (count($type) < 2) {
715 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $medium]);
719 $filetype = strtolower($type[0]);
720 $subtype = strtolower($type[1]);
723 $medium['filetype'] = $filetype;
724 $medium['subtype'] = $subtype;
726 if ($medium['type'] == self::HTML || (($filetype == 'text') && ($subtype == 'html'))) {
727 $attachments['link'][] = $medium;
731 if (in_array($medium['type'], [self::AUDIO, self::IMAGE]) ||
732 in_array($filetype, ['audio', 'image'])) {
733 $attachments['visual'][] = $medium;
734 } elseif (($medium['type'] == self::VIDEO) || ($filetype == 'video')) {
735 if (!empty($medium['height'])) {
736 // Peertube videos are delivered in many different resolutions. We pick a moderate one.
737 // Since only Peertube provides a "height" parameter, this wouldn't be executed
738 // when someone for example on Mastodon was sharing multiple videos in a single post.
739 $heights[$medium['height']] = $medium['url'];
740 $video[$medium['url']] = $medium;
742 $attachments['visual'][] = $medium;
745 $attachments['additional'][] = $medium;
749 if (!empty($heights)) {
751 foreach ($heights as $height => $url) {
752 if (empty($selected) || $height <= 480) {
757 if (!empty($selected)) {
758 $attachments['visual'][] = $video[$selected];
759 unset($video[$selected]);
760 foreach ($video as $element) {
761 $attachments['additional'][] = $element;
770 * Add media attachments to the body
773 * @param string $body
774 * @param array $types
776 * @return string body
778 public static function addAttachmentsToBody(int $uriid, string $body = '', array $types = [self::IMAGE, self::AUDIO, self::VIDEO]): string
781 $item = Post::selectFirst(['body'], ['uri-id' => $uriid]);
782 if (!DBA::isResult($item)) {
785 $body = $item['body'];
787 $original_body = $body;
789 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
791 foreach (self::getByURIId($uriid, $types) as $media) {
792 if (Item::containsLink($body, $media['preview'] ?? $media['url'], $media['type'])) {
796 if ($media['type'] == self::IMAGE) {
797 if (!empty($media['preview'])) {
798 if (!empty($media['description'])) {
799 $body .= "\n[url=" . $media['url'] . "][img=" . $media['preview'] . ']' . $media['description'] .'[/img][/url]';
801 $body .= "\n[url=" . $media['url'] . "][img]" . $media['preview'] .'[/img][/url]';
804 if (!empty($media['description'])) {
805 $body .= "\n[img=" . $media['url'] . ']' . $media['description'] .'[/img]';
807 $body .= "\n[img]" . $media['url'] .'[/img]';
810 } elseif ($media['type'] == self::AUDIO) {
811 $body .= "\n[audio]" . $media['url'] . "[/audio]\n";
812 } elseif ($media['type'] == self::VIDEO) {
813 $body .= "\n[video]" . $media['url'] . "[/video]\n";
817 if (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $original_body, $match)) {
818 $body .= "\n" . $match[1];
825 * Get preview link for given media id
827 * @param integer $id media id
828 * @param string $size One of the Proxy::SIZE_* constants
829 * @return string preview link
831 public static function getPreviewUrlForId(int $id, string $size = ''): string
833 $url = DI::baseUrl() . '/photo/preview/';
835 case Proxy::SIZE_MICRO:
836 $url .= Proxy::PIXEL_MICRO . '/';
838 case Proxy::SIZE_THUMB:
839 $url .= Proxy::PIXEL_THUMB . '/';
841 case Proxy::SIZE_SMALL:
842 $url .= Proxy::PIXEL_SMALL . '/';
844 case Proxy::SIZE_MEDIUM:
845 $url .= Proxy::PIXEL_MEDIUM . '/';
847 case Proxy::SIZE_LARGE:
848 $url .= Proxy::PIXEL_LARGE . '/';
855 * Get media link for given media id
857 * @param integer $id media id
858 * @param string $size One of the Proxy::SIZE_* constants
859 * @return string media link
861 public static function getUrlForId(int $id, string $size = ''): string
863 $url = DI::baseUrl() . '/photo/media/';
865 case Proxy::SIZE_MICRO:
866 $url .= Proxy::PIXEL_MICRO . '/';
868 case Proxy::SIZE_THUMB:
869 $url .= Proxy::PIXEL_THUMB . '/';
871 case Proxy::SIZE_SMALL:
872 $url .= Proxy::PIXEL_SMALL . '/';
874 case Proxy::SIZE_MEDIUM:
875 $url .= Proxy::PIXEL_MEDIUM . '/';
877 case Proxy::SIZE_LARGE:
878 $url .= Proxy::PIXEL_LARGE . '/';