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\HttpClientAccept;
34 use Friendica\Network\HTTPClient\Client\HttpClientOptions;
35 use Friendica\Util\Images;
36 use Friendica\Util\Network;
37 use Friendica\Util\ParseUrl;
38 use Friendica\Util\Proxy;
39 use Friendica\Util\Strings;
44 * This Model class handles media interactions.
45 * This tables stores medias (images, videos, audio files) related to posts.
54 const APPLICATION = 5;
62 * Insert a post-media record
67 public static function insert(array $media, bool $force = false)
69 if (empty($media['url']) || empty($media['uri-id']) || !isset($media['type'])) {
70 Logger::warning('Incomplete media data', ['media' => $media]);
74 if (DBA::exists('post-media', ['uri-id' => $media['uri-id'], 'preview' => $media['url']])) {
75 Logger::info('Media already exists as preview', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
79 // "document" has got the lowest priority. So when the same file is both attached as document
80 // and embedded as picture then we only store the picture or replace the document
81 $found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
82 if (!$force && !empty($found) && (($found['type'] != self::DOCUMENT) || ($media['type'] == self::DOCUMENT))) {
83 Logger::info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
87 $media = self::unsetEmptyFields($media);
89 // We are storing as fast as possible to avoid duplicated network requests
90 // when fetching additional information for pictures and other content.
91 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
92 Logger::info('Stored media', ['result' => $result, 'media' => $media, 'callstack' => System::callstack()]);
95 $media = self::fetchAdditionalData($media);
96 $media = self::unsetEmptyFields($media);
98 if (array_diff_assoc($media, $stored)) {
99 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
100 Logger::info('Updated media', ['result' => $result, 'media' => $media]);
102 Logger::info('Nothing to update', ['media' => $media]);
107 * Remove empty media fields
109 * @param array $media
110 * @return array cleaned media array
112 private static function unsetEmptyFields(array $media): array
114 $fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'description'];
115 foreach ($fields as $field) {
116 if (empty($media[$field])) {
117 unset($media[$field]);
124 * Copy attachments from one uri-id to another
126 * @param integer $from_uri_id
127 * @param integer $to_uri_id
130 public static function copy(int $from_uri_id, int $to_uri_id)
132 $attachments = self::getByURIId($from_uri_id);
133 foreach ($attachments as $attachment) {
134 $attachment['uri-id'] = $to_uri_id;
135 self::insert($attachment);
140 * Creates the "[attach]" element from the given attributes
142 * @param string $href
143 * @param integer $length
144 * @param string $type
145 * @param string $title
146 * @return string "[attach]" element
148 public static function getAttachElement(string $href, int $length, string $type, string $title = ''): string
150 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
151 'size' => $length, 'mimetype' => $type, 'description' => $title]);
153 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
154 '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
158 * Fetch additional data for the provided media array
160 * @param array $media
161 * @return array media array with additional data
163 public static function fetchAdditionalData(array $media): array
165 if (Network::isLocalLink($media['url'])) {
166 $media = self::fetchLocalData($media);
169 // Fetch the mimetype or size if missing.
170 if (empty($media['mimetype']) || empty($media['size'])) {
171 $timeout = DI::config()->get('system', 'xrd_timeout');
172 $curlResult = DI::httpClient()->head($media['url'], [HttpClientOptions::TIMEOUT => $timeout]);
174 // Workaround for systems that can't handle a HEAD request
175 if (!$curlResult->isSuccess() && ($curlResult->getReturnCode() == 405)) {
176 $curlResult = DI::httpClient()->get($media['url'], HttpClientAccept::DEFAULT, [HttpClientOptions::TIMEOUT => $timeout]);
179 if ($curlResult->isSuccess()) {
180 if (empty($media['mimetype'])) {
181 $media['mimetype'] = $curlResult->getHeader('Content-Type')[0] ?? '';
183 if (empty($media['size'])) {
184 $media['size'] = (int)($curlResult->getHeader('Content-Length')[0] ?? 0);
187 Logger::notice('Could not fetch head', ['media' => $media]);
191 $filetype = !empty($media['mimetype']) ? strtolower(current(explode('/', $media['mimetype']))) : '';
193 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
194 $imagedata = Images::getInfoFromURLCached($media['url']);
196 $media['mimetype'] = $imagedata['mime'];
197 $media['size'] = $imagedata['size'];
198 $media['width'] = $imagedata[0];
199 $media['height'] = $imagedata[1];
201 Logger::notice('No image data', ['media' => $media]);
203 if (!empty($media['preview'])) {
204 $imagedata = Images::getInfoFromURLCached($media['preview']);
206 $media['preview-width'] = $imagedata[0];
207 $media['preview-height'] = $imagedata[1];
212 if ($media['type'] != self::DOCUMENT) {
213 $media = self::addType($media);
216 if ($media['type'] == self::HTML) {
217 $data = ParseUrl::getSiteinfoCached($media['url'], false);
218 $media['preview'] = $data['images'][0]['src'] ?? null;
219 $media['preview-height'] = $data['images'][0]['height'] ?? null;
220 $media['preview-width'] = $data['images'][0]['width'] ?? null;
221 $media['description'] = $data['text'] ?? null;
222 $media['name'] = $data['title'] ?? null;
223 $media['author-url'] = $data['author_url'] ?? null;
224 $media['author-name'] = $data['author_name'] ?? null;
225 $media['author-image'] = $data['author_img'] ?? null;
226 $media['publisher-url'] = $data['publisher_url'] ?? null;
227 $media['publisher-name'] = $data['publisher_name'] ?? null;
228 $media['publisher-image'] = $data['publisher_img'] ?? null;
234 * Fetch media data from local resources
235 * @param array $media
236 * @return array media with added data
238 private static function fetchLocalData(array $media): array
240 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'] ?? '', $matches)) {
243 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
244 if (!empty($photo)) {
245 $media['mimetype'] = $photo['type'];
246 $media['size'] = $photo['datasize'];
247 $media['width'] = $photo['width'];
248 $media['height'] = $photo['height'];
251 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['preview'] ?? '', $matches)) {
254 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
255 if (!empty($photo)) {
256 $media['preview-width'] = $photo['width'];
257 $media['preview-height'] = $photo['height'];
264 * Add the detected type to the media array
267 * @return array data array with the detected type
269 public static function addType(array $data): array
271 if (empty($data['mimetype'])) {
272 Logger::info('No MimeType provided', ['media' => $data]);
276 $type = explode('/', current(explode(';', $data['mimetype'])));
277 if (count($type) < 2) {
278 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $data]);
279 $data['type'] = self::UNKNOWN;
283 $filetype = strtolower($type[0]);
284 $subtype = strtolower($type[1]);
286 if ($filetype == 'image') {
287 $data['type'] = self::IMAGE;
288 } elseif ($filetype == 'video') {
289 $data['type'] = self::VIDEO;
290 } elseif ($filetype == 'audio') {
291 $data['type'] = self::AUDIO;
292 } elseif (($filetype == 'text') && ($subtype == 'html')) {
293 $data['type'] = self::HTML;
294 } elseif (($filetype == 'text') && ($subtype == 'xml')) {
295 $data['type'] = self::XML;
296 } elseif (($filetype == 'text') && ($subtype == 'plain')) {
297 $data['type'] = self::PLAIN;
298 } elseif ($filetype == 'text') {
299 $data['type'] = self::TEXT;
300 } elseif (($filetype == 'application') && ($subtype == 'x-bittorrent')) {
301 $data['type'] = self::TORRENT;
302 } elseif ($filetype == 'application') {
303 $data['type'] = self::APPLICATION;
305 $data['type'] = self::UNKNOWN;
306 Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
310 Logger::debug('Detected type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
315 * Tests for path patterns that are usef for picture links in Friendica
317 * @param string $page Link to the image page
318 * @param string $preview Preview picture
321 private static function isPictureLink(string $page, string $preview): bool
323 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
327 * Add media links and remove them from the body
329 * @param integer $uriid
330 * @param string $body
331 * @return string Body without media links
333 public static function insertFromBody(int $uriid, string $body): string
335 // Simplify image codes
336 $unshared_body = $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
338 // Only remove the shared data from "real" reshares
339 $shared = BBCode::fetchShareAttributes($body);
340 if (!empty($shared['guid'])) {
341 $unshared_body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
345 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
346 foreach ($pictures as $picture) {
347 if (!self::isPictureLink($picture[1], $picture[2])) {
350 $body = str_replace($picture[0], '', $body);
351 $image = str_replace('-1.', '-0.', $picture[2]);
352 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
353 'preview' => $picture[2], 'description' => $picture[3]];
357 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
358 foreach ($pictures as $picture) {
359 $body = str_replace($picture[0], '', $body);
360 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
364 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
365 foreach ($pictures as $picture) {
366 if (!self::isPictureLink($picture[1], $picture[2])) {
369 $body = str_replace($picture[0], '', $body);
370 $image = str_replace('-1.', '-0.', $picture[2]);
371 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
372 'preview' => $picture[2], 'description' => null];
376 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
377 foreach ($pictures as $picture) {
378 $body = str_replace($picture[0], '', $body);
379 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
383 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]/ism", $body, $audios, PREG_SET_ORDER)) {
384 foreach ($audios as $audio) {
385 $body = str_replace($audio[0], '', $body);
386 $attachments[$audio[1]] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
390 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]/ism", $body, $videos, PREG_SET_ORDER)) {
391 foreach ($videos as $video) {
392 $body = str_replace($video[0], '', $body);
393 $attachments[$video[1]] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
397 foreach ($attachments as $attachment) {
398 if (Post\Link::exists($uriid, $attachment['preview'] ?? $attachment['url'])) {
402 // Only store attachments that are part of the unshared body
403 if (Item::containsLink($unshared_body, $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
404 self::insert($attachment);
412 * Add media links from a relevant url in the body
414 * @param integer $uriid
415 * @param string $body
418 public static function insertFromRelevantUrl(int $uriid, string $body)
420 // Only remove the shared data from "real" reshares
421 $shared = BBCode::fetchShareAttributes($body);
422 if (!empty($shared['guid'])) {
423 // Don't look at the shared content
424 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
427 // Remove all hashtags and mentions
428 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '', $body);
430 // Search for pure links
431 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) {
432 foreach ($matches[1] as $url) {
433 Logger::info('Got page url (link without description)', ['uri-id' => $uriid, 'url' => $url]);
434 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
438 // Search for links with descriptions
439 if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) {
440 foreach ($matches[1] as $url) {
441 Logger::info('Got page url (link with description)', ['uri-id' => $uriid, 'url' => $url]);
442 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
448 * Add media links from the attachment field
450 * @param integer $uriid
451 * @param string $body
454 public static function insertFromAttachmentData(int $uriid, string $body)
456 // Don't look at the shared content
457 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
459 $data = BBCode::getAttachmentData($body);
464 Logger::info('Adding attachment data', ['data' => $data]);
467 'type' => self::HTML,
468 'url' => $data['url'],
469 'preview' => $data['preview'] ?? null,
470 'description' => $data['description'] ?? null,
471 'name' => $data['title'] ?? null,
472 'author-url' => $data['author_url'] ?? null,
473 'author-name' => $data['author_name'] ?? null,
474 'publisher-url' => $data['provider_url'] ?? null,
475 'publisher-name' => $data['provider_name'] ?? null,
477 if (!empty($data['image'])) {
478 $attachment['preview'] = $data['image'];
480 self::insert($attachment);
484 * Add media links from the attach field
486 * @param integer $uriid
487 * @param string $attach
490 public static function insertFromAttachment(int $uriid, string $attach)
492 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
496 foreach ($matches as $attachment) {
497 $media['type'] = self::DOCUMENT;
498 $media['uri-id'] = $uriid;
499 $media['url'] = $attachment[1];
500 $media['size'] = $attachment[2];
501 $media['mimetype'] = $attachment[3];
502 $media['description'] = $attachment[4] ?? '';
504 self::insert($media);
509 * Retrieves the media attachments associated with the provided item ID.
511 * @param int $uri_id URI id
512 * @param array $types Media types
513 * @return array|bool Array on success, false on error
516 public static function getByURIId(int $uri_id, array $types = [])
518 $condition = ['uri-id' => $uri_id];
520 if (!empty($types)) {
521 $condition = DBA::mergeConditions($condition, ['type' => $types]);
524 return DBA::selectToArray('post-media', [], $condition, ['order' => ['id']]);
528 * Checks if media attachments are associated with the provided item ID.
530 * @param int $uri_id URI id
531 * @param array $types Media types
532 * @return bool Whether media attachment exists
535 public static function existsByURIId(int $uri_id, array $types = []): bool
537 $condition = ['uri-id' => $uri_id];
539 if (!empty($types)) {
540 $condition = DBA::mergeConditions($condition, ['type' => $types]);
543 return DBA::exists('post-media', $condition);
547 * Split the attachment media in the three segments "visual", "link" and "additional"
549 * @param int $uri_id URI id
550 * @param string $guid GUID
551 * @param array $links list of links that shouldn't be added
552 * @param bool $has_media
553 * @return array attachments
555 public static function splitAttachments(int $uri_id, string $guid = '', array $links = [], bool $has_media = true): array
557 $attachments = ['visual' => [], 'link' => [], 'additional' => []];
563 $media = self::getByURIId($uri_id);
572 foreach ($media as $medium) {
573 foreach ($links as $link) {
574 if (Strings::compareLink($link, $medium['url'])) {
579 // Avoid adding separate media entries for previews
580 foreach ($previews as $preview) {
581 if (Strings::compareLink($preview, $medium['url'])) {
586 if (!empty($medium['preview'])) {
587 $previews[] = $medium['preview'];
590 $type = explode('/', current(explode(';', $medium['mimetype'])));
591 if (count($type) < 2) {
592 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $medium]);
596 $filetype = strtolower($type[0]);
597 $subtype = strtolower($type[1]);
600 $medium['filetype'] = $filetype;
601 $medium['subtype'] = $subtype;
603 if ($medium['type'] == self::HTML || (($filetype == 'text') && ($subtype == 'html'))) {
604 $attachments['link'][] = $medium;
608 if (in_array($medium['type'], [self::AUDIO, self::IMAGE]) ||
609 in_array($filetype, ['audio', 'image'])) {
610 $attachments['visual'][] = $medium;
611 } elseif (($medium['type'] == self::VIDEO) || ($filetype == 'video')) {
612 if (!empty($medium['height'])) {
613 // Peertube videos are delivered in many different resolutions. We pick a moderate one.
614 // Since only Peertube provides a "height" parameter, this wouldn't be executed
615 // when someone for example on Mastodon was sharing multiple videos in a single post.
616 $heights[$medium['height']] = $medium['url'];
617 $video[$medium['url']] = $medium;
619 $attachments['visual'][] = $medium;
622 $attachments['additional'][] = $medium;
626 if (!empty($heights)) {
628 foreach ($heights as $height => $url) {
629 if (empty($selected) || $height <= 480) {
634 if (!empty($selected)) {
635 $attachments['visual'][] = $video[$selected];
636 unset($video[$selected]);
637 foreach ($video as $element) {
638 $attachments['additional'][] = $element;
647 * Add media attachments to the body
650 * @param string $body
651 * @return string body
653 public static function addAttachmentsToBody(int $uriid, string $body = ''): string
656 $item = Post::selectFirst(['body'], ['uri-id' => $uriid]);
657 if (!DBA::isResult($item)) {
660 $body = $item['body'];
662 $original_body = $body;
664 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
666 foreach (self::getByURIId($uriid, [self::IMAGE, self::AUDIO, self::VIDEO]) as $media) {
667 if (Item::containsLink($body, $media['preview'] ?? $media['url'], $media['type'])) {
671 if ($media['type'] == self::IMAGE) {
672 if (!empty($media['preview'])) {
673 if (!empty($media['description'])) {
674 $body .= "\n[url=" . $media['url'] . "][img=" . $media['preview'] . ']' . $media['description'] .'[/img][/url]';
676 $body .= "\n[url=" . $media['url'] . "][img]" . $media['preview'] .'[/img][/url]';
679 if (!empty($media['description'])) {
680 $body .= "\n[img=" . $media['url'] . ']' . $media['description'] .'[/img]';
682 $body .= "\n[img]" . $media['url'] .'[/img]';
685 } elseif ($media['type'] == self::AUDIO) {
686 $body .= "\n[audio]" . $media['url'] . "[/audio]\n";
687 } elseif ($media['type'] == self::VIDEO) {
688 $body .= "\n[video]" . $media['url'] . "[/video]\n";
692 if (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $original_body, $match)) {
693 $body .= "\n" . $match[1];
700 * Get preview link for given media id
702 * @param integer $id media id
703 * @param string $size One of the Proxy::SIZE_* constants
704 * @return string preview link
706 public static function getPreviewUrlForId(int $id, string $size = ''): string
708 $url = DI::baseUrl() . '/photo/preview/';
710 case Proxy::SIZE_MICRO:
711 $url .= Proxy::PIXEL_MICRO . '/';
713 case Proxy::SIZE_THUMB:
714 $url .= Proxy::PIXEL_THUMB . '/';
716 case Proxy::SIZE_SMALL:
717 $url .= Proxy::PIXEL_SMALL . '/';
719 case Proxy::SIZE_MEDIUM:
720 $url .= Proxy::PIXEL_MEDIUM . '/';
722 case Proxy::SIZE_LARGE:
723 $url .= Proxy::PIXEL_LARGE . '/';
730 * Get media link for given media id
732 * @param integer $id media id
733 * @param string $size One of the Proxy::SIZE_* constants
734 * @return string media link
736 public static function getUrlForId(int $id, string $size = ''): string
738 $url = DI::baseUrl() . '/photo/media/';
740 case Proxy::SIZE_MICRO:
741 $url .= Proxy::PIXEL_MICRO . '/';
743 case Proxy::SIZE_THUMB:
744 $url .= Proxy::PIXEL_THUMB . '/';
746 case Proxy::SIZE_SMALL:
747 $url .= Proxy::PIXEL_SMALL . '/';
749 case Proxy::SIZE_MEDIUM:
750 $url .= Proxy::PIXEL_MEDIUM . '/';
752 case Proxy::SIZE_LARGE:
753 $url .= Proxy::PIXEL_LARGE . '/';