3 * @copyright Copyright (C) 2010-2021, 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\Util\Images;
34 use Friendica\Util\Network;
35 use Friendica\Util\ParseUrl;
36 use Friendica\Util\Proxy;
37 use Friendica\Util\Strings;
42 * This Model class handles media interactions.
43 * This tables stores medias (images, videos, audio files) related to posts.
52 const APPLICATION = 5;
60 * Insert a post-media record
65 public static function insert(array $media, bool $force = false)
67 if (empty($media['url']) || empty($media['uri-id']) || !isset($media['type'])) {
68 Logger::warning('Incomplete media data', ['media' => $media]);
72 if (DBA::exists('post-media', ['uri-id' => $media['uri-id'], 'preview' => $media['url']])) {
73 Logger::info('Media already exists as preview', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
77 // "document" has got the lowest priority. So when the same file is both attached as document
78 // and embedded as picture then we only store the picture or replace the document
79 $found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
80 if (!$force && !empty($found) && (($found['type'] != self::DOCUMENT) || ($media['type'] == self::DOCUMENT))) {
81 Logger::info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
85 $media = self::unsetEmptyFields($media);
87 // We are storing as fast as possible to avoid duplicated network requests
88 // when fetching additional information for pictures and other content.
89 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
90 Logger::info('Stored media', ['result' => $result, 'media' => $media, 'callstack' => System::callstack()]);
93 $media = self::fetchAdditionalData($media);
94 $media = self::unsetEmptyFields($media);
96 if (array_diff_assoc($media, $stored)) {
97 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
98 Logger::info('Updated media', ['result' => $result, 'media' => $media]);
100 Logger::info('Nothing to update', ['media' => $media]);
105 * Remove empty media fields
107 * @param array $media
108 * @return array cleaned media array
110 private static function unsetEmptyFields(array $media)
112 $fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'description'];
113 foreach ($fields as $field) {
114 if (empty($media[$field])) {
115 unset($media[$field]);
122 * Copy attachments from one uri-id to another
124 * @param integer $from_uri_id
125 * @param integer $to_uri_id
128 public static function copy(int $from_uri_id, int $to_uri_id)
130 $attachments = self::getByURIId($from_uri_id);
131 foreach ($attachments as $attachment) {
132 $attachment['uri-id'] = $to_uri_id;
133 self::insert($attachment);
138 * Creates the "[attach]" element from the given attributes
140 * @param string $href
141 * @param integer $length
142 * @param string $type
143 * @param string $title
144 * @return string "[attach]" element
146 public static function getAttachElement(string $href, int $length, string $type, string $title = '')
148 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
149 'size' => $length, 'mimetype' => $type, 'description' => $title]);
151 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
152 '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
156 * Fetch additional data for the provided media array
158 * @param array $media
159 * @return array media array with additional data
161 public static function fetchAdditionalData(array $media)
163 if (Network::isLocalLink($media['url'])) {
164 $media = self::fetchLocalData($media);
167 // Fetch the mimetype or size if missing.
168 if (empty($media['mimetype']) || empty($media['size'])) {
169 $timeout = DI::config()->get('system', 'xrd_timeout');
170 $curlResult = DI::httpRequest()->head($media['url'], ['timeout' => $timeout]);
171 if ($curlResult->isSuccess()) {
172 if (empty($media['mimetype'])) {
173 $media['mimetype'] = $curlResult->getHeader('Content-Type');
175 if (empty($media['size'])) {
176 $media['size'] = (int)$curlResult->getHeader('Content-Length');
179 Logger::notice('Could not fetch head', ['media' => $media]);
183 $filetype = !empty($media['mimetype']) ? strtolower(current(explode('/', $media['mimetype']))) : '';
185 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
186 $imagedata = Images::getInfoFromURLCached($media['url']);
187 if (!empty($imagedata)) {
188 $media['mimetype'] = $imagedata['mime'];
189 $media['size'] = $imagedata['size'];
190 $media['width'] = $imagedata[0];
191 $media['height'] = $imagedata[1];
193 Logger::notice('No image data', ['media' => $media]);
195 if (!empty($media['preview'])) {
196 $imagedata = Images::getInfoFromURLCached($media['preview']);
197 if (!empty($imagedata)) {
198 $media['preview-width'] = $imagedata[0];
199 $media['preview-height'] = $imagedata[1];
204 if ($media['type'] != self::DOCUMENT) {
205 $media = self::addType($media);
208 if ($media['type'] == self::HTML) {
209 $data = ParseUrl::getSiteinfoCached($media['url'], false);
210 $media['preview'] = $data['images'][0]['src'] ?? null;
211 $media['preview-height'] = $data['images'][0]['height'] ?? null;
212 $media['preview-width'] = $data['images'][0]['width'] ?? null;
213 $media['description'] = $data['text'] ?? null;
214 $media['name'] = $data['title'] ?? null;
215 $media['author-url'] = $data['author_url'] ?? null;
216 $media['author-name'] = $data['author_name'] ?? null;
217 $media['author-image'] = $data['author_img'] ?? null;
218 $media['publisher-url'] = $data['publisher_url'] ?? null;
219 $media['publisher-name'] = $data['publisher_name'] ?? null;
220 $media['publisher-image'] = $data['publisher_img'] ?? null;
226 * Fetch media data from local resources
227 * @param array $media
228 * @return array media with added data
230 private static function fetchLocalData(array $media)
232 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'] ?? '', $matches)) {
235 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
236 if (!empty($photo)) {
237 $media['mimetype'] = $photo['type'];
238 $media['size'] = $photo['datasize'];
239 $media['width'] = $photo['width'];
240 $media['height'] = $photo['height'];
243 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['preview'] ?? '', $matches)) {
246 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
247 if (!empty($photo)) {
248 $media['preview-width'] = $photo['width'];
249 $media['preview-height'] = $photo['height'];
256 * Add the detected type to the media array
259 * @return array data array with the detected type
261 public static function addType(array $data)
263 if (empty($data['mimetype'])) {
264 Logger::info('No MimeType provided', ['media' => $data]);
268 $type = explode('/', current(explode(';', $data['mimetype'])));
269 if (count($type) < 2) {
270 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $data]);
271 $data['type'] = self::UNKNOWN;
275 $filetype = strtolower($type[0]);
276 $subtype = strtolower($type[1]);
278 if ($filetype == 'image') {
279 $data['type'] = self::IMAGE;
280 } elseif ($filetype == 'video') {
281 $data['type'] = self::VIDEO;
282 } elseif ($filetype == 'audio') {
283 $data['type'] = self::AUDIO;
284 } elseif (($filetype == 'text') && ($subtype == 'html')) {
285 $data['type'] = self::HTML;
286 } elseif (($filetype == 'text') && ($subtype == 'xml')) {
287 $data['type'] = self::XML;
288 } elseif (($filetype == 'text') && ($subtype == 'plain')) {
289 $data['type'] = self::PLAIN;
290 } elseif ($filetype == 'text') {
291 $data['type'] = self::TEXT;
292 } elseif (($filetype == 'application') && ($subtype == 'x-bittorrent')) {
293 $data['type'] = self::TORRENT;
294 } elseif ($filetype == 'application') {
295 $data['type'] = self::APPLICATION;
297 $data['type'] = self::UNKNOWN;
298 Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
302 Logger::debug('Detected type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
307 * Tests for path patterns that are usef for picture links in Friendica
309 * @param string $page Link to the image page
310 * @param string $preview Preview picture
313 private static function isPictureLink(string $page, string $preview)
315 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
319 * Add media links and remove them from the body
321 * @param integer $uriid
322 * @param string $body
323 * @return string Body without media links
325 public static function insertFromBody(int $uriid, string $body)
327 // Simplify image codes
328 $unshared_body = $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
330 // Only remove the shared data from "real" reshares
331 $shared = BBCode::fetchShareAttributes($body);
332 if (!empty($shared['guid'])) {
333 $unshared_body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
337 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
338 foreach ($pictures as $picture) {
339 if (!self::isPictureLink($picture[1], $picture[2])) {
342 $body = str_replace($picture[0], '', $body);
343 $image = str_replace('-1.', '-0.', $picture[2]);
344 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
345 'preview' => $picture[2], 'description' => $picture[3]];
349 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
350 foreach ($pictures as $picture) {
351 $body = str_replace($picture[0], '', $body);
352 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
356 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
357 foreach ($pictures as $picture) {
358 if (!self::isPictureLink($picture[1], $picture[2])) {
361 $body = str_replace($picture[0], '', $body);
362 $image = str_replace('-1.', '-0.', $picture[2]);
363 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
364 'preview' => $picture[2], 'description' => null];
368 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
369 foreach ($pictures as $picture) {
370 $body = str_replace($picture[0], '', $body);
371 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
375 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]/ism", $body, $audios, PREG_SET_ORDER)) {
376 foreach ($audios as $audio) {
377 $body = str_replace($audio[0], '', $body);
378 $attachments[$audio[1]] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
382 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]/ism", $body, $videos, PREG_SET_ORDER)) {
383 foreach ($videos as $video) {
384 $body = str_replace($video[0], '', $body);
385 $attachments[$video[1]] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
389 foreach ($attachments as $attachment) {
390 // Only store attachments that are part of the unshared body
391 if (Item::containsLink($unshared_body, $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
392 self::insert($attachment);
400 * Add media links from a relevant url in the body
402 * @param integer $uriid
403 * @param string $body
405 public static function insertFromRelevantUrl(int $uriid, string $body)
407 // Only remove the shared data from "real" reshares
408 $shared = BBCode::fetchShareAttributes($body);
409 if (!empty($shared['guid'])) {
410 // Don't look at the shared content
411 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
414 // Remove all hashtags and mentions
415 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '', $body);
417 // Search for pure links
418 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) {
419 foreach ($matches[1] as $url) {
420 Logger::info('Got page url (link without description)', ['uri-id' => $uriid, 'url' => $url]);
421 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
425 // Search for links with descriptions
426 if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) {
427 foreach ($matches[1] as $url) {
428 Logger::info('Got page url (link with description)', ['uri-id' => $uriid, 'url' => $url]);
429 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
435 * Add media links from the attachment field
437 * @param integer $uriid
438 * @param string $body
440 public static function insertFromAttachmentData(int $uriid, string $body)
442 // Don't look at the shared content
443 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
445 $data = BBCode::getAttachmentData($body);
450 Logger::info('Adding attachment data', ['data' => $data]);
453 'type' => self::HTML,
454 'url' => $data['url'],
455 'preview' => $data['preview'] ?? null,
456 'description' => $data['description'] ?? null,
457 'name' => $data['title'] ?? null,
458 'author-url' => $data['author_url'] ?? null,
459 'author-name' => $data['author_name'] ?? null,
460 'publisher-url' => $data['provider_url'] ?? null,
461 'publisher-name' => $data['provider_name'] ?? null,
463 if (!empty($data['image'])) {
464 $attachment['preview'] = $data['image'];
466 self::insert($attachment);
470 * Add media links from the attach field
472 * @param integer $uriid
473 * @param string $attach
476 public static function insertFromAttachment(int $uriid, string $attach)
478 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
482 foreach ($matches as $attachment) {
483 $media['type'] = self::DOCUMENT;
484 $media['uri-id'] = $uriid;
485 $media['url'] = $attachment[1];
486 $media['size'] = $attachment[2];
487 $media['mimetype'] = $attachment[3];
488 $media['description'] = $attachment[4] ?? '';
490 self::insert($media);
495 * Retrieves the media attachments associated with the provided item ID.
498 * @param array $types
502 public static function getByURIId(int $uri_id, array $types = [])
504 $condition = ['uri-id' => $uri_id];
506 if (!empty($types)) {
507 $condition = DBA::mergeConditions($condition, ['type' => $types]);
510 return DBA::selectToArray('post-media', [], $condition);
514 * Checks if media attachments are associated with the provided item ID.
517 * @param array $types
521 public static function existsByURIId(int $uri_id, array $types = [])
523 $condition = ['uri-id' => $uri_id];
525 if (!empty($types)) {
526 $condition = DBA::mergeConditions($condition, ['type' => $types]);
529 return DBA::exists('post-media', $condition);
533 * Split the attachment media in the three segments "visual", "link" and "additional"
536 * @param string $guid
537 * @param array $links list of links that shouldn't be added
538 * @return array attachments
540 public static function splitAttachments(int $uri_id, string $guid = '', array $links = [])
542 $attachments = ['visual' => [], 'link' => [], 'additional' => []];
544 $media = self::getByURIId($uri_id);
553 foreach ($media as $medium) {
554 foreach ($links as $link) {
555 if (Strings::compareLink($link, $medium['url'])) {
560 // Avoid adding separate media entries for previews
561 foreach ($previews as $preview) {
562 if (Strings::compareLink($preview, $medium['url'])) {
567 if (!empty($medium['preview'])) {
568 $previews[] = $medium['preview'];
571 $type = explode('/', current(explode(';', $medium['mimetype'])));
572 if (count($type) < 2) {
573 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $medium]);
577 $filetype = strtolower($type[0]);
578 $subtype = strtolower($type[1]);
581 $medium['filetype'] = $filetype;
582 $medium['subtype'] = $subtype;
584 if ($medium['type'] == self::HTML || (($filetype == 'text') && ($subtype == 'html'))) {
585 $attachments['link'][] = $medium;
589 if (in_array($medium['type'], [self::AUDIO, self::IMAGE]) ||
590 in_array($filetype, ['audio', 'image'])) {
591 $attachments['visual'][] = $medium;
592 } elseif (($medium['type'] == self::VIDEO) || ($filetype == 'video')) {
593 if (strpos($medium['url'], $guid) !== false) {
594 // Peertube videos are delivered in many different resolutions. We pick a moderate one.
595 // By checking against the GUID we also ensure to only work this way on Peertube posts.
596 // This wouldn't be executed when someone for example on Mastodon was sharing multiple videos in a single post.
597 if (empty($height) || ($height > $medium['height']) && ($medium['height'] >= 480)) {
598 $height = $medium['height'];
599 $selected = $medium['url'];
601 $video[$medium['url']] = $medium;
603 $attachments['visual'][] = $medium;
606 $attachments['additional'][] = $medium;
609 if (!empty($selected)) {
610 $attachments['visual'][] = $video[$selected];
611 unset($video[$selected]);
612 foreach ($video as $element) {
613 $attachments['additional'][] = $element;
620 * Add media attachments to the body
623 * @param string $body
624 * @return string body
626 public static function addAttachmentsToBody(int $uriid, string $body = '')
629 $item = Post::selectFirst(['body'], ['uri-id' => $uriid]);
630 if (!DBA::isResult($item)) {
633 $body = $item['body'];
635 $original_body = $body;
637 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
639 foreach (self::getByURIId($uriid, [self::IMAGE, self::AUDIO, self::VIDEO]) as $media) {
640 if (Item::containsLink($body, $media['preview'] ?? $media['url'], $media['type'])) {
644 if ($media['type'] == self::IMAGE) {
645 if (!empty($media['preview'])) {
646 if (!empty($media['description'])) {
647 $body .= "\n[url=" . $media['url'] . "][img=" . $media['preview'] . ']' . $media['description'] .'[/img][/url]';
649 $body .= "\n[url=" . $media['url'] . "][img]" . $media['preview'] .'[/img][/url]';
652 if (!empty($media['description'])) {
653 $body .= "\n[img=" . $media['url'] . ']' . $media['description'] .'[/img]';
655 $body .= "\n[img]" . $media['url'] .'[/img]';
658 } elseif ($media['type'] == self::AUDIO) {
659 $body .= "\n[audio]" . $media['url'] . "[/audio]\n";
660 } elseif ($media['type'] == self::VIDEO) {
661 $body .= "\n[video]" . $media['url'] . "[/video]\n";
665 if (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $original_body, $match)) {
666 $body .= "\n" . $match[1];
673 * Get preview link for given media id
675 * @param integer $id media id
676 * @param string $size One of the ProxyUtils::SIZE_* constants
677 * @return string preview link
679 public static function getPreviewUrlForId(int $id, string $size = ''):string
681 $url = DI::baseUrl() . '/photo/preview/';
683 case Proxy::SIZE_MICRO:
684 $url .= Proxy::PIXEL_MICRO . '/';
686 case Proxy::SIZE_THUMB:
687 $url .= Proxy::PIXEL_THUMB . '/';
689 case Proxy::SIZE_SMALL:
690 $url .= Proxy::PIXEL_SMALL . '/';
692 case Proxy::SIZE_MEDIUM:
693 $url .= Proxy::PIXEL_MEDIUM . '/';
695 case Proxy::SIZE_LARGE:
696 $url .= Proxy::PIXEL_LARGE . '/';
703 * Get media link for given media id
705 * @param integer $id media id
706 * @param string $size One of the ProxyUtils::SIZE_* constants
707 * @return string media link
709 public static function getUrlForId(int $id, string $size = ''):string
711 $url = DI::baseUrl() . '/photo/media/';
713 case Proxy::SIZE_MICRO:
714 $url .= Proxy::PIXEL_MICRO . '/';
716 case Proxy::SIZE_THUMB:
717 $url .= Proxy::PIXEL_THUMB . '/';
719 case Proxy::SIZE_SMALL:
720 $url .= Proxy::PIXEL_SMALL . '/';
722 case Proxy::SIZE_MEDIUM:
723 $url .= Proxy::PIXEL_MEDIUM . '/';
725 case Proxy::SIZE_LARGE:
726 $url .= Proxy::PIXEL_LARGE . '/';