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\Network\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]);
172 if ($curlResult->isSuccess()) {
173 if (empty($media['mimetype'])) {
174 $media['mimetype'] = $curlResult->getHeader('Content-Type')[0] ?? '';
176 if (empty($media['size'])) {
177 $media['size'] = (int)($curlResult->getHeader('Content-Length')[0] ?? 0);
180 Logger::notice('Could not fetch head', ['media' => $media]);
184 $filetype = !empty($media['mimetype']) ? strtolower(current(explode('/', $media['mimetype']))) : '';
186 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
187 $imagedata = Images::getInfoFromURLCached($media['url']);
188 if (!empty($imagedata)) {
189 $media['mimetype'] = $imagedata['mime'];
190 $media['size'] = $imagedata['size'];
191 $media['width'] = $imagedata[0];
192 $media['height'] = $imagedata[1];
194 Logger::notice('No image data', ['media' => $media]);
196 if (!empty($media['preview'])) {
197 $imagedata = Images::getInfoFromURLCached($media['preview']);
198 if (!empty($imagedata)) {
199 $media['preview-width'] = $imagedata[0];
200 $media['preview-height'] = $imagedata[1];
205 if ($media['type'] != self::DOCUMENT) {
206 $media = self::addType($media);
209 if ($media['type'] == self::HTML) {
210 $data = ParseUrl::getSiteinfoCached($media['url'], false);
211 $media['preview'] = $data['images'][0]['src'] ?? null;
212 $media['preview-height'] = $data['images'][0]['height'] ?? null;
213 $media['preview-width'] = $data['images'][0]['width'] ?? null;
214 $media['description'] = $data['text'] ?? null;
215 $media['name'] = $data['title'] ?? null;
216 $media['author-url'] = $data['author_url'] ?? null;
217 $media['author-name'] = $data['author_name'] ?? null;
218 $media['author-image'] = $data['author_img'] ?? null;
219 $media['publisher-url'] = $data['publisher_url'] ?? null;
220 $media['publisher-name'] = $data['publisher_name'] ?? null;
221 $media['publisher-image'] = $data['publisher_img'] ?? null;
227 * Fetch media data from local resources
228 * @param array $media
229 * @return array media with added data
231 private static function fetchLocalData(array $media)
233 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['url'] ?? '', $matches)) {
236 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
237 if (!empty($photo)) {
238 $media['mimetype'] = $photo['type'];
239 $media['size'] = $photo['datasize'];
240 $media['width'] = $photo['width'];
241 $media['height'] = $photo['height'];
244 if (!preg_match('|.*?/photo/(.*[a-fA-F0-9])\-(.*[0-9])\..*[\w]|', $media['preview'] ?? '', $matches)) {
247 $photo = Photo::selectFirst([], ['resource-id' => $matches[1], 'scale' => $matches[2]]);
248 if (!empty($photo)) {
249 $media['preview-width'] = $photo['width'];
250 $media['preview-height'] = $photo['height'];
257 * Add the detected type to the media array
260 * @return array data array with the detected type
262 public static function addType(array $data)
264 if (empty($data['mimetype'])) {
265 Logger::info('No MimeType provided', ['media' => $data]);
269 $type = explode('/', current(explode(';', $data['mimetype'])));
270 if (count($type) < 2) {
271 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $data]);
272 $data['type'] = self::UNKNOWN;
276 $filetype = strtolower($type[0]);
277 $subtype = strtolower($type[1]);
279 if ($filetype == 'image') {
280 $data['type'] = self::IMAGE;
281 } elseif ($filetype == 'video') {
282 $data['type'] = self::VIDEO;
283 } elseif ($filetype == 'audio') {
284 $data['type'] = self::AUDIO;
285 } elseif (($filetype == 'text') && ($subtype == 'html')) {
286 $data['type'] = self::HTML;
287 } elseif (($filetype == 'text') && ($subtype == 'xml')) {
288 $data['type'] = self::XML;
289 } elseif (($filetype == 'text') && ($subtype == 'plain')) {
290 $data['type'] = self::PLAIN;
291 } elseif ($filetype == 'text') {
292 $data['type'] = self::TEXT;
293 } elseif (($filetype == 'application') && ($subtype == 'x-bittorrent')) {
294 $data['type'] = self::TORRENT;
295 } elseif ($filetype == 'application') {
296 $data['type'] = self::APPLICATION;
298 $data['type'] = self::UNKNOWN;
299 Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
303 Logger::debug('Detected type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
308 * Tests for path patterns that are usef for picture links in Friendica
310 * @param string $page Link to the image page
311 * @param string $preview Preview picture
314 private static function isPictureLink(string $page, string $preview)
316 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
320 * Add media links and remove them from the body
322 * @param integer $uriid
323 * @param string $body
324 * @return string Body without media links
326 public static function insertFromBody(int $uriid, string $body)
328 // Simplify image codes
329 $unshared_body = $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
331 // Only remove the shared data from "real" reshares
332 $shared = BBCode::fetchShareAttributes($body);
333 if (!empty($shared['guid'])) {
334 $unshared_body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
338 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
339 foreach ($pictures as $picture) {
340 if (!self::isPictureLink($picture[1], $picture[2])) {
343 $body = str_replace($picture[0], '', $body);
344 $image = str_replace('-1.', '-0.', $picture[2]);
345 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
346 'preview' => $picture[2], 'description' => $picture[3]];
350 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
351 foreach ($pictures as $picture) {
352 $body = str_replace($picture[0], '', $body);
353 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
357 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
358 foreach ($pictures as $picture) {
359 if (!self::isPictureLink($picture[1], $picture[2])) {
362 $body = str_replace($picture[0], '', $body);
363 $image = str_replace('-1.', '-0.', $picture[2]);
364 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
365 'preview' => $picture[2], 'description' => null];
369 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
370 foreach ($pictures as $picture) {
371 $body = str_replace($picture[0], '', $body);
372 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
376 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]/ism", $body, $audios, PREG_SET_ORDER)) {
377 foreach ($audios as $audio) {
378 $body = str_replace($audio[0], '', $body);
379 $attachments[$audio[1]] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
383 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]/ism", $body, $videos, PREG_SET_ORDER)) {
384 foreach ($videos as $video) {
385 $body = str_replace($video[0], '', $body);
386 $attachments[$video[1]] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
390 foreach ($attachments as $attachment) {
391 if (Post\Link::exists($uriid, $attachment['preview'] ?? $attachment['url'])) {
395 // Only store attachments that are part of the unshared body
396 if (Item::containsLink($unshared_body, $attachment['preview'] ?? $attachment['url'], $attachment['type'])) {
397 self::insert($attachment);
405 * Add media links from a relevant url in the body
407 * @param integer $uriid
408 * @param string $body
410 public static function insertFromRelevantUrl(int $uriid, string $body)
412 // Only remove the shared data from "real" reshares
413 $shared = BBCode::fetchShareAttributes($body);
414 if (!empty($shared['guid'])) {
415 // Don't look at the shared content
416 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
419 // Remove all hashtags and mentions
420 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '', $body);
422 // Search for pure links
423 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) {
424 foreach ($matches[1] as $url) {
425 Logger::info('Got page url (link without description)', ['uri-id' => $uriid, 'url' => $url]);
426 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
430 // Search for links with descriptions
431 if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) {
432 foreach ($matches[1] as $url) {
433 Logger::info('Got page url (link with description)', ['uri-id' => $uriid, 'url' => $url]);
434 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
440 * Add media links from the attachment field
442 * @param integer $uriid
443 * @param string $body
445 public static function insertFromAttachmentData(int $uriid, string $body)
447 // Don't look at the shared content
448 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
450 $data = BBCode::getAttachmentData($body);
455 Logger::info('Adding attachment data', ['data' => $data]);
458 'type' => self::HTML,
459 'url' => $data['url'],
460 'preview' => $data['preview'] ?? null,
461 'description' => $data['description'] ?? null,
462 'name' => $data['title'] ?? null,
463 'author-url' => $data['author_url'] ?? null,
464 'author-name' => $data['author_name'] ?? null,
465 'publisher-url' => $data['provider_url'] ?? null,
466 'publisher-name' => $data['provider_name'] ?? null,
468 if (!empty($data['image'])) {
469 $attachment['preview'] = $data['image'];
471 self::insert($attachment);
475 * Add media links from the attach field
477 * @param integer $uriid
478 * @param string $attach
481 public static function insertFromAttachment(int $uriid, string $attach)
483 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
487 foreach ($matches as $attachment) {
488 $media['type'] = self::DOCUMENT;
489 $media['uri-id'] = $uriid;
490 $media['url'] = $attachment[1];
491 $media['size'] = $attachment[2];
492 $media['mimetype'] = $attachment[3];
493 $media['description'] = $attachment[4] ?? '';
495 self::insert($media);
500 * Retrieves the media attachments associated with the provided item ID.
503 * @param array $types
507 public static function getByURIId(int $uri_id, array $types = [])
509 $condition = ['uri-id' => $uri_id];
511 if (!empty($types)) {
512 $condition = DBA::mergeConditions($condition, ['type' => $types]);
515 return DBA::selectToArray('post-media', [], $condition);
519 * Checks if media attachments are associated with the provided item ID.
522 * @param array $types
526 public static function existsByURIId(int $uri_id, array $types = [])
528 $condition = ['uri-id' => $uri_id];
530 if (!empty($types)) {
531 $condition = DBA::mergeConditions($condition, ['type' => $types]);
534 return DBA::exists('post-media', $condition);
538 * Split the attachment media in the three segments "visual", "link" and "additional"
541 * @param string $guid
542 * @param array $links list of links that shouldn't be added
543 * @return array attachments
545 public static function splitAttachments(int $uri_id, string $guid = '', array $links = [])
547 $attachments = ['visual' => [], 'link' => [], 'additional' => []];
549 $media = self::getByURIId($uri_id);
558 foreach ($media as $medium) {
559 foreach ($links as $link) {
560 if (Strings::compareLink($link, $medium['url'])) {
565 // Avoid adding separate media entries for previews
566 foreach ($previews as $preview) {
567 if (Strings::compareLink($preview, $medium['url'])) {
572 if (!empty($medium['preview'])) {
573 $previews[] = $medium['preview'];
576 $type = explode('/', current(explode(';', $medium['mimetype'])));
577 if (count($type) < 2) {
578 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $medium]);
582 $filetype = strtolower($type[0]);
583 $subtype = strtolower($type[1]);
586 $medium['filetype'] = $filetype;
587 $medium['subtype'] = $subtype;
589 if ($medium['type'] == self::HTML || (($filetype == 'text') && ($subtype == 'html'))) {
590 $attachments['link'][] = $medium;
594 if (in_array($medium['type'], [self::AUDIO, self::IMAGE]) ||
595 in_array($filetype, ['audio', 'image'])) {
596 $attachments['visual'][] = $medium;
597 } elseif (($medium['type'] == self::VIDEO) || ($filetype == 'video')) {
598 if (!empty($medium['height'])) {
599 // Peertube videos are delivered in many different resolutions. We pick a moderate one.
600 // Since only Peertube provides a "height" parameter, this wouldn't be executed
601 // when someone for example on Mastodon was sharing multiple videos in a single post.
602 $heights[$medium['height']] = $medium['url'];
603 $video[$medium['url']] = $medium;
605 $attachments['visual'][] = $medium;
608 $attachments['additional'][] = $medium;
612 if (!empty($heights)) {
614 foreach ($heights as $height => $url) {
615 if (empty($selected) || $height <= 480) {
620 if (!empty($selected)) {
621 $attachments['visual'][] = $video[$selected];
622 unset($video[$selected]);
623 foreach ($video as $element) {
624 $attachments['additional'][] = $element;
633 * Add media attachments to the body
636 * @param string $body
637 * @return string body
639 public static function addAttachmentsToBody(int $uriid, string $body = '')
642 $item = Post::selectFirst(['body'], ['uri-id' => $uriid]);
643 if (!DBA::isResult($item)) {
646 $body = $item['body'];
648 $original_body = $body;
650 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
652 foreach (self::getByURIId($uriid, [self::IMAGE, self::AUDIO, self::VIDEO]) as $media) {
653 if (Item::containsLink($body, $media['preview'] ?? $media['url'], $media['type'])) {
657 if ($media['type'] == self::IMAGE) {
658 if (!empty($media['preview'])) {
659 if (!empty($media['description'])) {
660 $body .= "\n[url=" . $media['url'] . "][img=" . $media['preview'] . ']' . $media['description'] .'[/img][/url]';
662 $body .= "\n[url=" . $media['url'] . "][img]" . $media['preview'] .'[/img][/url]';
665 if (!empty($media['description'])) {
666 $body .= "\n[img=" . $media['url'] . ']' . $media['description'] .'[/img]';
668 $body .= "\n[img]" . $media['url'] .'[/img]';
671 } elseif ($media['type'] == self::AUDIO) {
672 $body .= "\n[audio]" . $media['url'] . "[/audio]\n";
673 } elseif ($media['type'] == self::VIDEO) {
674 $body .= "\n[video]" . $media['url'] . "[/video]\n";
678 if (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $original_body, $match)) {
679 $body .= "\n" . $match[1];
686 * Get preview link for given media id
688 * @param integer $id media id
689 * @param string $size One of the Proxy::SIZE_* constants
690 * @return string preview link
692 public static function getPreviewUrlForId(int $id, string $size = ''):string
694 $url = DI::baseUrl() . '/photo/preview/';
696 case Proxy::SIZE_MICRO:
697 $url .= Proxy::PIXEL_MICRO . '/';
699 case Proxy::SIZE_THUMB:
700 $url .= Proxy::PIXEL_THUMB . '/';
702 case Proxy::SIZE_SMALL:
703 $url .= Proxy::PIXEL_SMALL . '/';
705 case Proxy::SIZE_MEDIUM:
706 $url .= Proxy::PIXEL_MEDIUM . '/';
708 case Proxy::SIZE_LARGE:
709 $url .= Proxy::PIXEL_LARGE . '/';
716 * Get media link for given media id
718 * @param integer $id media id
719 * @param string $size One of the Proxy::SIZE_* constants
720 * @return string media link
722 public static function getUrlForId(int $id, string $size = ''):string
724 $url = DI::baseUrl() . '/photo/media/';
726 case Proxy::SIZE_MICRO:
727 $url .= Proxy::PIXEL_MICRO . '/';
729 case Proxy::SIZE_THUMB:
730 $url .= Proxy::PIXEL_THUMB . '/';
732 case Proxy::SIZE_SMALL:
733 $url .= Proxy::PIXEL_SMALL . '/';
735 case Proxy::SIZE_MEDIUM:
736 $url .= Proxy::PIXEL_MEDIUM . '/';
738 case Proxy::SIZE_LARGE:
739 $url .= Proxy::PIXEL_LARGE . '/';