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\System;
27 use Friendica\Database\Database;
28 use Friendica\Database\DBA;
30 use Friendica\Model\Item;
31 use Friendica\Model\Photo;
32 use Friendica\Model\Post;
33 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
34 use Friendica\Util\Images;
35 use Friendica\Util\Network;
36 use Friendica\Util\ParseUrl;
37 use Friendica\Util\Proxy;
38 use Friendica\Util\Strings;
43 * This Model class handles media interactions.
44 * This tables stores medias (images, videos, audio files) related to posts.
53 const APPLICATION = 5;
61 * Insert a post-media record
66 public static function insert(array $media, bool $force = false)
68 if (empty($media['url']) || empty($media['uri-id']) || !isset($media['type'])) {
69 Logger::warning('Incomplete media data', ['media' => $media]);
73 if (DBA::exists('post-media', ['uri-id' => $media['uri-id'], 'preview' => $media['url']])) {
74 Logger::info('Media already exists as preview', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
78 // "document" has got the lowest priority. So when the same file is both attached as document
79 // and embedded as picture then we only store the picture or replace the document
80 $found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
81 if (!$force && !empty($found) && (($found['type'] != self::DOCUMENT) || ($media['type'] == self::DOCUMENT))) {
82 Logger::info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
86 $media = self::unsetEmptyFields($media);
88 // We are storing as fast as possible to avoid duplicated network requests
89 // when fetching additional information for pictures and other content.
90 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
91 Logger::info('Stored media', ['result' => $result, 'media' => $media, 'callstack' => System::callstack()]);
94 $media = self::fetchAdditionalData($media);
95 $media = self::unsetEmptyFields($media);
97 if (array_diff_assoc($media, $stored)) {
98 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
99 Logger::info('Updated media', ['result' => $result, 'media' => $media]);
101 Logger::info('Nothing to update', ['media' => $media]);
106 * Remove empty media fields
108 * @param array $media
109 * @return array cleaned media array
111 private static function unsetEmptyFields(array $media)
113 $fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'description'];
114 foreach ($fields as $field) {
115 if (empty($media[$field])) {
116 unset($media[$field]);
123 * Copy attachments from one uri-id to another
125 * @param integer $from_uri_id
126 * @param integer $to_uri_id
129 public static function copy(int $from_uri_id, int $to_uri_id)
131 $attachments = self::getByURIId($from_uri_id);
132 foreach ($attachments as $attachment) {
133 $attachment['uri-id'] = $to_uri_id;
134 self::insert($attachment);
139 * Creates the "[attach]" element from the given attributes
141 * @param string $href
142 * @param integer $length
143 * @param string $type
144 * @param string $title
145 * @return string "[attach]" element
147 public static function getAttachElement(string $href, int $length, string $type, string $title = '')
149 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
150 'size' => $length, 'mimetype' => $type, 'description' => $title]);
152 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
153 '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
157 * Fetch additional data for the provided media array
159 * @param array $media
160 * @return array media array with additional data
162 public static function fetchAdditionalData(array $media)
164 if (Network::isLocalLink($media['url'])) {
165 $media = self::fetchLocalData($media);
168 // Fetch the mimetype or size if missing.
169 if (empty($media['mimetype']) || empty($media['size'])) {
170 $timeout = DI::config()->get('system', 'xrd_timeout');
171 $curlResult = DI::httpClient()->head($media['url'], [HttpClientOptions::TIMEOUT => $timeout]);
173 // Workaround for systems that can't handle a HEAD request
174 if (!$curlResult->isSuccess() && ($curlResult->getReturnCode() == 405)) {
175 $curlResult = DI::httpClient()->get($media['url'], [HttpClientOptions::TIMEOUT => $timeout]);
178 if ($curlResult->isSuccess()) {
179 if (empty($media['mimetype'])) {
180 $media['mimetype'] = $curlResult->getHeader('Content-Type')[0] ?? '';
182 if (empty($media['size'])) {
183 $media['size'] = (int)($curlResult->getHeader('Content-Length')[0] ?? 0);
186 Logger::notice('Could not fetch head', ['media' => $media]);
190 $filetype = !empty($media['mimetype']) ? strtolower(current(explode('/', $media['mimetype']))) : '';
192 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
193 $imagedata = Images::getInfoFromURLCached($media['url']);
194 if (!empty($imagedata)) {
195 $media['mimetype'] = $imagedata['mime'];
196 $media['size'] = $imagedata['size'];
197 $media['width'] = $imagedata[0];
198 $media['height'] = $imagedata[1];
200 Logger::notice('No image data', ['media' => $media]);
202 if (!empty($media['preview'])) {
203 $imagedata = Images::getInfoFromURLCached($media['preview']);
204 if (!empty($imagedata)) {
205 $media['preview-width'] = $imagedata[0];
206 $media['preview-height'] = $imagedata[1];
211 if ($media['type'] != self::DOCUMENT) {
212 $media = self::addType($media);
215 if ($media['type'] == self::HTML) {
216 $data = ParseUrl::getSiteinfoCached($media['url'], false);
217 $media['preview'] = $data['images'][0]['src'] ?? null;
218 $media['preview-height'] = $data['images'][0]['height'] ?? null;
219 $media['preview-width'] = $data['images'][0]['width'] ?? null;
220 $media['description'] = $data['text'] ?? null;
221 $media['name'] = $data['title'] ?? null;
222 $media['author-url'] = $data['author_url'] ?? null;
223 $media['author-name'] = $data['author_name'] ?? null;
224 $media['author-image'] = $data['author_img'] ?? null;
225 $media['publisher-url'] = $data['publisher_url'] ?? null;
226 $media['publisher-name'] = $data['publisher_name'] ?? null;
227 $media['publisher-image'] = $data['publisher_img'] ?? null;
233 * Fetch media data from local resources
234 * @param array $media
235 * @return array media with added data
237 private static function fetchLocalData(array $media)
239 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'] ?? '', $matches)) {
242 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
243 if (!empty($photo)) {
244 $media['mimetype'] = $photo['type'];
245 $media['size'] = $photo['datasize'];
246 $media['width'] = $photo['width'];
247 $media['height'] = $photo['height'];
250 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['preview'] ?? '', $matches)) {
253 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
254 if (!empty($photo)) {
255 $media['preview-width'] = $photo['width'];
256 $media['preview-height'] = $photo['height'];
263 * Add the detected type to the media array
266 * @return array data array with the detected type
268 public static function addType(array $data)
270 if (empty($data['mimetype'])) {
271 Logger::info('No MimeType provided', ['media' => $data]);
275 $type = explode('/', current(explode(';', $data['mimetype'])));
276 if (count($type) < 2) {
277 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $data]);
278 $data['type'] = self::UNKNOWN;
282 $filetype = strtolower($type[0]);
283 $subtype = strtolower($type[1]);
285 if ($filetype == 'image') {
286 $data['type'] = self::IMAGE;
287 } elseif ($filetype == 'video') {
288 $data['type'] = self::VIDEO;
289 } elseif ($filetype == 'audio') {
290 $data['type'] = self::AUDIO;
291 } elseif (($filetype == 'text') && ($subtype == 'html')) {
292 $data['type'] = self::HTML;
293 } elseif (($filetype == 'text') && ($subtype == 'xml')) {
294 $data['type'] = self::XML;
295 } elseif (($filetype == 'text') && ($subtype == 'plain')) {
296 $data['type'] = self::PLAIN;
297 } elseif ($filetype == 'text') {
298 $data['type'] = self::TEXT;
299 } elseif (($filetype == 'application') && ($subtype == 'x-bittorrent')) {
300 $data['type'] = self::TORRENT;
301 } elseif ($filetype == 'application') {
302 $data['type'] = self::APPLICATION;
304 $data['type'] = self::UNKNOWN;
305 Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
309 Logger::debug('Detected type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
314 * Tests for path patterns that are usef for picture links in Friendica
316 * @param string $page Link to the image page
317 * @param string $preview Preview picture
320 private static function isPictureLink(string $page, string $preview)
322 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
326 * Add media links and remove them from the body
328 * @param integer $uriid
329 * @param string $body
330 * @return string Body without media links
332 public static function insertFromBody(int $uriid, string $body)
334 // Simplify image codes
335 $unshared_body = $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
337 // Only remove the shared data from "real" reshares
338 $shared = BBCode::fetchShareAttributes($body);
339 if (!empty($shared['guid'])) {
340 $unshared_body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
344 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
345 foreach ($pictures as $picture) {
346 if (!self::isPictureLink($picture[1], $picture[2])) {
349 $body = str_replace($picture[0], '', $body);
350 $image = str_replace('-1.', '-0.', $picture[2]);
351 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
352 'preview' => $picture[2], 'description' => $picture[3]];
356 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
357 foreach ($pictures as $picture) {
358 $body = str_replace($picture[0], '', $body);
359 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
363 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
364 foreach ($pictures as $picture) {
365 if (!self::isPictureLink($picture[1], $picture[2])) {
368 $body = str_replace($picture[0], '', $body);
369 $image = str_replace('-1.', '-0.', $picture[2]);
370 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
371 'preview' => $picture[2], 'description' => null];
375 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
376 foreach ($pictures as $picture) {
377 $body = str_replace($picture[0], '', $body);
378 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
382 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]/ism", $body, $audios, PREG_SET_ORDER)) {
383 foreach ($audios as $audio) {
384 $body = str_replace($audio[0], '', $body);
385 $attachments[$audio[1]] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
389 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]/ism", $body, $videos, PREG_SET_ORDER)) {
390 foreach ($videos as $video) {
391 $body = str_replace($video[0], '', $body);
392 $attachments[$video[1]] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
396 foreach ($attachments as $attachment) {
397 if (Post\Link::exists($uriid, $attachment['preview'] ?? $attachment['url'])) {
401 // Only store attachments that are part of the unshared body
402 if (Item::containsLink($unshared_body, $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
403 self::insert($attachment);
411 * Add media links from a relevant url in the body
413 * @param integer $uriid
414 * @param string $body
416 public static function insertFromRelevantUrl(int $uriid, string $body)
418 // Only remove the shared data from "real" reshares
419 $shared = BBCode::fetchShareAttributes($body);
420 if (!empty($shared['guid'])) {
421 // Don't look at the shared content
422 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
425 // Remove all hashtags and mentions
426 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '', $body);
428 // Search for pure links
429 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) {
430 foreach ($matches[1] as $url) {
431 Logger::info('Got page url (link without description)', ['uri-id' => $uriid, 'url' => $url]);
432 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
436 // Search for links with descriptions
437 if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) {
438 foreach ($matches[1] as $url) {
439 Logger::info('Got page url (link with description)', ['uri-id' => $uriid, 'url' => $url]);
440 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
446 * Add media links from the attachment field
448 * @param integer $uriid
449 * @param string $body
451 public static function insertFromAttachmentData(int $uriid, string $body)
453 // Don't look at the shared content
454 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
456 $data = BBCode::getAttachmentData($body);
461 Logger::info('Adding attachment data', ['data' => $data]);
464 'type' => self::HTML,
465 'url' => $data['url'],
466 'preview' => $data['preview'] ?? null,
467 'description' => $data['description'] ?? null,
468 'name' => $data['title'] ?? null,
469 'author-url' => $data['author_url'] ?? null,
470 'author-name' => $data['author_name'] ?? null,
471 'publisher-url' => $data['provider_url'] ?? null,
472 'publisher-name' => $data['provider_name'] ?? null,
474 if (!empty($data['image'])) {
475 $attachment['preview'] = $data['image'];
477 self::insert($attachment);
481 * Add media links from the attach field
483 * @param integer $uriid
484 * @param string $attach
487 public static function insertFromAttachment(int $uriid, string $attach)
489 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
493 foreach ($matches as $attachment) {
494 $media['type'] = self::DOCUMENT;
495 $media['uri-id'] = $uriid;
496 $media['url'] = $attachment[1];
497 $media['size'] = $attachment[2];
498 $media['mimetype'] = $attachment[3];
499 $media['description'] = $attachment[4] ?? '';
501 self::insert($media);
506 * Retrieves the media attachments associated with the provided item ID.
509 * @param array $types
513 public static function getByURIId(int $uri_id, array $types = [])
515 $condition = ['uri-id' => $uri_id];
517 if (!empty($types)) {
518 $condition = DBA::mergeConditions($condition, ['type' => $types]);
521 return DBA::selectToArray('post-media', [], $condition, ['order' => ['id']]);
525 * Checks if media attachments are associated with the provided item ID.
528 * @param array $types
532 public static function existsByURIId(int $uri_id, array $types = [])
534 $condition = ['uri-id' => $uri_id];
536 if (!empty($types)) {
537 $condition = DBA::mergeConditions($condition, ['type' => $types]);
540 return DBA::exists('post-media', $condition);
544 * Split the attachment media in the three segments "visual", "link" and "additional"
547 * @param string $guid
548 * @param array $links list of links that shouldn't be added
549 * @return array attachments
551 public static function splitAttachments(int $uri_id, string $guid = '', array $links = [])
553 $attachments = ['visual' => [], 'link' => [], 'additional' => []];
555 $media = self::getByURIId($uri_id);
564 foreach ($media as $medium) {
565 foreach ($links as $link) {
566 if (Strings::compareLink($link, $medium['url'])) {
571 // Avoid adding separate media entries for previews
572 foreach ($previews as $preview) {
573 if (Strings::compareLink($preview, $medium['url'])) {
578 if (!empty($medium['preview'])) {
579 $previews[] = $medium['preview'];
582 $type = explode('/', current(explode(';', $medium['mimetype'])));
583 if (count($type) < 2) {
584 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $medium]);
588 $filetype = strtolower($type[0]);
589 $subtype = strtolower($type[1]);
592 $medium['filetype'] = $filetype;
593 $medium['subtype'] = $subtype;
595 if ($medium['type'] == self::HTML || (($filetype == 'text') && ($subtype == 'html'))) {
596 $attachments['link'][] = $medium;
600 if (in_array($medium['type'], [self::AUDIO, self::IMAGE]) ||
601 in_array($filetype, ['audio', 'image'])) {
602 $attachments['visual'][] = $medium;
603 } elseif (($medium['type'] == self::VIDEO) || ($filetype == 'video')) {
604 if (!empty($medium['height'])) {
605 // Peertube videos are delivered in many different resolutions. We pick a moderate one.
606 // Since only Peertube provides a "height" parameter, this wouldn't be executed
607 // when someone for example on Mastodon was sharing multiple videos in a single post.
608 $heights[$medium['height']] = $medium['url'];
609 $video[$medium['url']] = $medium;
611 $attachments['visual'][] = $medium;
614 $attachments['additional'][] = $medium;
618 if (!empty($heights)) {
620 foreach ($heights as $height => $url) {
621 if (empty($selected) || $height <= 480) {
626 if (!empty($selected)) {
627 $attachments['visual'][] = $video[$selected];
628 unset($video[$selected]);
629 foreach ($video as $element) {
630 $attachments['additional'][] = $element;
639 * Add media attachments to the body
642 * @param string $body
643 * @return string body
645 public static function addAttachmentsToBody(int $uriid, string $body = '')
648 $item = Post::selectFirst(['body'], ['uri-id' => $uriid]);
649 if (!DBA::isResult($item)) {
652 $body = $item['body'];
654 $original_body = $body;
656 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
658 foreach (self::getByURIId($uriid, [self::IMAGE, self::AUDIO, self::VIDEO]) as $media) {
659 if (Item::containsLink($body, $media['preview'] ?? $media['url'], $media['type'])) {
663 if ($media['type'] == self::IMAGE) {
664 if (!empty($media['preview'])) {
665 if (!empty($media['description'])) {
666 $body .= "\n[url=" . $media['url'] . "][img=" . $media['preview'] . ']' . $media['description'] .'[/img][/url]';
668 $body .= "\n[url=" . $media['url'] . "][img]" . $media['preview'] .'[/img][/url]';
671 if (!empty($media['description'])) {
672 $body .= "\n[img=" . $media['url'] . ']' . $media['description'] .'[/img]';
674 $body .= "\n[img]" . $media['url'] .'[/img]';
677 } elseif ($media['type'] == self::AUDIO) {
678 $body .= "\n[audio]" . $media['url'] . "[/audio]\n";
679 } elseif ($media['type'] == self::VIDEO) {
680 $body .= "\n[video]" . $media['url'] . "[/video]\n";
684 if (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $original_body, $match)) {
685 $body .= "\n" . $match[1];
692 * Get preview link for given media id
694 * @param integer $id media id
695 * @param string $size One of the Proxy::SIZE_* constants
696 * @return string preview link
698 public static function getPreviewUrlForId(int $id, string $size = ''):string
700 $url = DI::baseUrl() . '/photo/preview/';
702 case Proxy::SIZE_MICRO:
703 $url .= Proxy::PIXEL_MICRO . '/';
705 case Proxy::SIZE_THUMB:
706 $url .= Proxy::PIXEL_THUMB . '/';
708 case Proxy::SIZE_SMALL:
709 $url .= Proxy::PIXEL_SMALL . '/';
711 case Proxy::SIZE_MEDIUM:
712 $url .= Proxy::PIXEL_MEDIUM . '/';
714 case Proxy::SIZE_LARGE:
715 $url .= Proxy::PIXEL_LARGE . '/';
722 * Get media link for given media id
724 * @param integer $id media id
725 * @param string $size One of the Proxy::SIZE_* constants
726 * @return string media link
728 public static function getUrlForId(int $id, string $size = ''):string
730 $url = DI::baseUrl() . '/photo/media/';
732 case Proxy::SIZE_MICRO:
733 $url .= Proxy::PIXEL_MICRO . '/';
735 case Proxy::SIZE_THUMB:
736 $url .= Proxy::PIXEL_THUMB . '/';
738 case Proxy::SIZE_SMALL:
739 $url .= Proxy::PIXEL_SMALL . '/';
741 case Proxy::SIZE_MEDIUM:
742 $url .= Proxy::PIXEL_MEDIUM . '/';
744 case Proxy::SIZE_LARGE:
745 $url .= Proxy::PIXEL_LARGE . '/';