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\Post;
32 use Friendica\Util\Images;
33 use Friendica\Util\ParseUrl;
34 use Friendica\Util\Strings;
39 * This Model class handles media interactions.
40 * This tables stores medias (images, videos, audio files) related to posts.
49 const APPLICATION = 5;
57 * Insert a post-media record
62 public static function insert(array $media, bool $force = false)
64 if (empty($media['url']) || empty($media['uri-id']) || !isset($media['type'])) {
65 Logger::warning('Incomplete media data', ['media' => $media]);
69 if (DBA::exists('post-media', ['uri-id' => $media['uri-id'], 'preview' => $media['url']])) {
70 Logger::info('Media already exists as preview', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
74 // "document" has got the lowest priority. So when the same file is both attached as document
75 // and embedded as picture then we only store the picture or replace the document
76 $found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
77 if (!$force && !empty($found) && (($found['type'] != self::DOCUMENT) || ($media['type'] == self::DOCUMENT))) {
78 Logger::info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
82 $media = self::unsetEmptyFields($media);
84 // We are storing as fast as possible to avoid duplicated network requests
85 // when fetching additional information for pictures and other content.
86 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
87 Logger::info('Stored media', ['result' => $result, 'media' => $media, 'callstack' => System::callstack()]);
90 $media = self::fetchAdditionalData($media);
91 $media = self::unsetEmptyFields($media);
93 if (array_diff_assoc($media, $stored)) {
94 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
95 Logger::info('Updated media', ['result' => $result, 'media' => $media]);
97 Logger::info('Nothing to update', ['media' => $media]);
102 * Remove empty media fields
104 * @param array $media
105 * @return array cleaned media array
107 private static function unsetEmptyFields(array $media)
109 $fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'description'];
110 foreach ($fields as $field) {
111 if (empty($media[$field])) {
112 unset($media[$field]);
119 * Copy attachments from one uri-id to another
121 * @param integer $from_uri_id
122 * @param integer $to_uri_id
125 public static function copy(int $from_uri_id, int $to_uri_id)
127 $attachments = self::getByURIId($from_uri_id);
128 foreach ($attachments as $attachment) {
129 $attachment['uri-id'] = $to_uri_id;
130 self::insert($attachment);
135 * Creates the "[attach]" element from the given attributes
137 * @param string $href
138 * @param integer $length
139 * @param string $type
140 * @param string $title
141 * @return string "[attach]" element
143 public static function getAttachElement(string $href, int $length, string $type, string $title = '')
145 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
146 'size' => $length, 'mimetype' => $type, 'description' => $title]);
148 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
149 '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
153 * Fetch additional data for the provided media array
155 * @param array $media
156 * @return array media array with additional data
158 public static function fetchAdditionalData(array $media)
160 // Fetch the mimetype or size if missing.
161 if (empty($media['mimetype']) || empty($media['size'])) {
162 $timeout = DI::config()->get('system', 'xrd_timeout');
163 $curlResult = DI::httpRequest()->head($media['url'], ['timeout' => $timeout]);
164 if ($curlResult->isSuccess()) {
165 if (empty($media['mimetype'])) {
166 $media['mimetype'] = $curlResult->getHeader('Content-Type');
168 if (empty($media['size'])) {
169 $media['size'] = (int)$curlResult->getHeader('Content-Length');
172 Logger::notice('Could not fetch head', ['media' => $media]);
176 $filetype = !empty($media['mimetype']) ? strtolower(current(explode('/', $media['mimetype']))) : '';
178 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
179 $imagedata = Images::getInfoFromURLCached($media['url']);
180 if (!empty($imagedata)) {
181 $media['mimetype'] = $imagedata['mime'];
182 $media['size'] = $imagedata['size'];
183 $media['width'] = $imagedata[0];
184 $media['height'] = $imagedata[1];
186 Logger::notice('No image data', ['media' => $media]);
188 if (!empty($media['preview'])) {
189 $imagedata = Images::getInfoFromURLCached($media['preview']);
190 if (!empty($imagedata)) {
191 $media['preview-width'] = $imagedata[0];
192 $media['preview-height'] = $imagedata[1];
197 if ($media['type'] != self::DOCUMENT) {
198 $media = self::addType($media);
201 if ($media['type'] == self::HTML) {
202 $data = ParseUrl::getSiteinfoCached($media['url'], false);
203 $media['preview'] = $data['images'][0]['src'] ?? null;
204 $media['preview-height'] = $data['images'][0]['height'] ?? null;
205 $media['preview-width'] = $data['images'][0]['width'] ?? null;
206 $media['description'] = $data['text'] ?? null;
207 $media['name'] = $data['title'] ?? null;
208 $media['author-url'] = $data['author_url'] ?? null;
209 $media['author-name'] = $data['author_name'] ?? null;
210 $media['author-image'] = $data['author_img'] ?? null;
211 $media['publisher-url'] = $data['publisher_url'] ?? null;
212 $media['publisher-name'] = $data['publisher_name'] ?? null;
213 $media['publisher-image'] = $data['publisher_img'] ?? null;
219 * Add the detected type to the media array
222 * @return array data array with the detected type
224 public static function addType(array $data)
226 if (empty($data['mimetype'])) {
227 Logger::info('No MimeType provided', ['media' => $data]);
231 $type = explode('/', current(explode(';', $data['mimetype'])));
232 if (count($type) < 2) {
233 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $data]);
234 $data['type'] = self::UNKNOWN;
238 $filetype = strtolower($type[0]);
239 $subtype = strtolower($type[1]);
241 if ($filetype == 'image') {
242 $data['type'] = self::IMAGE;
243 } elseif ($filetype == 'video') {
244 $data['type'] = self::VIDEO;
245 } elseif ($filetype == 'audio') {
246 $data['type'] = self::AUDIO;
247 } elseif (($filetype == 'text') && ($subtype == 'html')) {
248 $data['type'] = self::HTML;
249 } elseif (($filetype == 'text') && ($subtype == 'xml')) {
250 $data['type'] = self::XML;
251 } elseif (($filetype == 'text') && ($subtype == 'plain')) {
252 $data['type'] = self::PLAIN;
253 } elseif ($filetype == 'text') {
254 $data['type'] = self::TEXT;
255 } elseif (($filetype == 'application') && ($subtype == 'x-bittorrent')) {
256 $data['type'] = self::TORRENT;
257 } elseif ($filetype == 'application') {
258 $data['type'] = self::APPLICATION;
260 $data['type'] = self::UNKNOWN;
261 Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
265 Logger::debug('Detected type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
270 * Tests for path patterns that are usef for picture links in Friendica
272 * @param string $page Link to the image page
273 * @param string $preview Preview picture
276 private static function isPictureLink(string $page, string $preview)
278 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
282 * Add media links and remove them from the body
284 * @param integer $uriid
285 * @param string $body
286 * @return string Body without media links
288 public static function insertFromBody(int $uriid, string $body)
290 // Simplify image codes
291 $unshared_body = $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
293 // Only remove the shared data from "real" reshares
294 $shared = BBCode::fetchShareAttributes($body);
295 if (!empty($shared['guid'])) {
296 $unshared_body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
300 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
301 foreach ($pictures as $picture) {
302 if (!self::isPictureLink($picture[1], $picture[2])) {
305 $body = str_replace($picture[0], '', $body);
306 $image = str_replace('-1.', '-0.', $picture[2]);
307 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
308 'preview' => $picture[2], 'description' => $picture[3]];
312 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
313 foreach ($pictures as $picture) {
314 $body = str_replace($picture[0], '', $body);
315 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
319 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
320 foreach ($pictures as $picture) {
321 if (!self::isPictureLink($picture[1], $picture[2])) {
324 $body = str_replace($picture[0], '', $body);
325 $image = str_replace('-1.', '-0.', $picture[2]);
326 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
327 'preview' => $picture[2], 'description' => null];
331 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
332 foreach ($pictures as $picture) {
333 $body = str_replace($picture[0], '', $body);
334 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
338 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]/ism", $body, $audios, PREG_SET_ORDER)) {
339 foreach ($audios as $audio) {
340 $body = str_replace($audio[0], '', $body);
341 $attachments[$audio[1]] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
345 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]/ism", $body, $videos, PREG_SET_ORDER)) {
346 foreach ($videos as $video) {
347 $body = str_replace($video[0], '', $body);
348 $attachments[$video[1]] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
352 foreach ($attachments as $attachment) {
353 // Only store attachments that are part of the unshared body
354 if (Item::containsLink($unshared_body, $attachment['url'], $attachment['type'])) {
355 self::insert($attachment);
363 * Add media links from a relevant url in the body
365 * @param integer $uriid
366 * @param string $body
368 public static function insertFromRelevantUrl(int $uriid, string $body)
370 // Only remove the shared data from "real" reshares
371 $shared = BBCode::fetchShareAttributes($body);
372 if (!empty($shared['guid'])) {
373 // Don't look at the shared content
374 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
377 // Remove all hashtags and mentions
378 $body = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '', $body);
380 // Search for pure links
381 if (preg_match_all("/\[url\](https?:.*?)\[\/url\]/ism", $body, $matches)) {
382 foreach ($matches[1] as $url) {
383 Logger::info('Got page url (link without description)', ['uri-id' => $uriid, 'url' => $url]);
384 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
388 // Search for links with descriptions
389 if (preg_match_all("/\[url\=(https?:.*?)\].*?\[\/url\]/ism", $body, $matches)) {
390 foreach ($matches[1] as $url) {
391 Logger::info('Got page url (link with description)', ['uri-id' => $uriid, 'url' => $url]);
392 self::insert(['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url]);
398 * Add media links from the attachment field
400 * @param integer $uriid
401 * @param string $body
403 public static function insertFromAttachmentData(int $uriid, string $body)
405 // Don't look at the shared content
406 $body = preg_replace("/\s*\[share .*?\].*?\[\/share\]\s*/ism", '', $body);
408 $data = BBCode::getAttachmentData($body);
413 Logger::info('Adding attachment data', ['data' => $data]);
416 'type' => self::HTML,
417 'url' => $data['url'],
418 'preview' => $data['preview'] ?? null,
419 'description' => $data['description'] ?? null,
420 'name' => $data['title'] ?? null,
421 'author-url' => $data['author_url'] ?? null,
422 'author-name' => $data['author_name'] ?? null,
423 'publisher-url' => $data['provider_url'] ?? null,
424 'publisher-name' => $data['provider_name'] ?? null,
426 if (!empty($data['image'])) {
427 $attachment['preview'] = $data['image'];
429 self::insert($attachment);
433 * Add media links from the attach field
435 * @param integer $uriid
436 * @param string $attach
439 public static function insertFromAttachment(int $uriid, string $attach)
441 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
445 foreach ($matches as $attachment) {
446 $media['type'] = self::DOCUMENT;
447 $media['uri-id'] = $uriid;
448 $media['url'] = $attachment[1];
449 $media['size'] = $attachment[2];
450 $media['mimetype'] = $attachment[3];
451 $media['description'] = $attachment[4] ?? '';
453 self::insert($media);
458 * Retrieves the media attachments associated with the provided item ID.
461 * @param array $types
465 public static function getByURIId(int $uri_id, array $types = [])
467 $condition = ['uri-id' => $uri_id];
469 if (!empty($types)) {
470 $condition = DBA::mergeConditions($condition, ['type' => $types]);
473 return DBA::selectToArray('post-media', [], $condition);
477 * Checks if media attachments are associated with the provided item ID.
480 * @param array $types
484 public static function existsByURIId(int $uri_id, array $types = [])
486 $condition = ['uri-id' => $uri_id];
488 if (!empty($types)) {
489 $condition = DBA::mergeConditions($condition, ['type' => $types]);
492 return DBA::exists('post-media', $condition);
496 * Split the attachment media in the three segments "visual", "link" and "additional"
499 * @param string $guid
500 * @param array $links ist of links that shouldn't be added
501 * @return array attachments
503 public static function splitAttachments(int $uri_id, string $guid = '', array $links = [])
505 $attachments = ['visual' => [], 'link' => [], 'additional' => []];
507 $media = self::getByURIId($uri_id);
516 foreach ($media as $medium) {
517 foreach ($links as $link) {
518 if (Strings::compareLink($link, $medium['url'])) {
523 // Avoid adding separate media entries for previews
524 foreach ($previews as $preview) {
525 if (Strings::compareLink($preview, $medium['url'])) {
530 if (!empty($medium['preview'])) {
531 $previews[] = $medium['preview'];
534 $type = explode('/', current(explode(';', $medium['mimetype'])));
535 if (count($type) < 2) {
536 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $medium]);
540 $filetype = strtolower($type[0]);
541 $subtype = strtolower($type[1]);
544 $medium['filetype'] = $filetype;
545 $medium['subtype'] = $subtype;
547 if ($medium['type'] == self::HTML || (($filetype == 'text') && ($subtype == 'html'))) {
548 $attachments['link'][] = $medium;
552 if (in_array($medium['type'], [self::AUDIO, self::IMAGE]) ||
553 in_array($filetype, ['audio', 'image'])) {
554 $attachments['visual'][] = $medium;
555 } elseif (($medium['type'] == self::VIDEO) || ($filetype == 'video')) {
556 if (strpos($medium['url'], $guid) !== false) {
557 // Peertube videos are delivered in many different resolutions. We pick a moderate one.
558 // By checking against the GUID we also ensure to only work this way on Peertube posts.
559 // This wouldn't be executed when someone for example on Mastodon was sharing multiple videos in a single post.
560 if (empty($height) || ($height > $medium['height']) && ($medium['height'] >= 480)) {
561 $height = $medium['height'];
562 $selected = $medium['url'];
564 $video[$medium['url']] = $medium;
566 $attachments['visual'][] = $medium;
569 $attachments['additional'][] = $medium;
572 if (!empty($selected)) {
573 $attachments['visual'][] = $video[$selected];
574 unset($video[$selected]);
575 foreach ($video as $element) {
576 $attachments['additional'][] = $element;
583 * Add media attachments to the body
586 * @param string $body
587 * @return string body
589 public static function addAttachmentsToBody(int $uriid, string $body = '')
592 $item = Post::selectFirst(['body'], ['uri-id' => $uriid]);
593 if (!DBA::isResult($item)) {
596 $body = $item['body'];
598 $original_body = $body;
600 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
602 foreach (self::getByURIId($uriid, [self::IMAGE, self::AUDIO, self::VIDEO]) as $media) {
603 if (Item::containsLink($body, $media['url'], $media['type'])) {
607 if ($media['type'] == self::IMAGE) {
608 if (!empty($media['preview'])) {
609 if (!empty($media['description'])) {
610 $body .= "\n[url=" . $media['url'] . "][img=" . $media['preview'] . ']' . $media['description'] .'[/img][/url]';
612 $body .= "\n[url=" . $media['url'] . "][img]" . $media['preview'] .'[/img][/url]';
615 if (!empty($media['description'])) {
616 $body .= "\n[img=" . $media['url'] . ']' . $media['description'] .'[/img]';
618 $body .= "\n[img]" . $media['url'] .'[/img]';
621 } elseif ($media['type'] == self::AUDIO) {
622 $body .= "\n[audio]" . $media['url'] . "[/audio]\n";
623 } elseif ($media['type'] == self::VIDEO) {
624 $body .= "\n[video]" . $media['url'] . "[/video]\n";
628 if (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $original_body, $match)) {
629 $body .= "\n" . $match[1];