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\PageInfo;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Core\Logger;
27 use Friendica\Core\System;
28 use Friendica\Database\Database;
29 use Friendica\Database\DBA;
31 use Friendica\Model\Item;
32 use Friendica\Model\Post;
33 use Friendica\Util\Images;
34 use Friendica\Util\ParseUrl;
35 use Friendica\Util\Strings;
40 * This Model class handles media interactions.
41 * This tables stores medias (images, videos, audio files) related to posts.
50 const APPLICATION = 5;
58 * Insert a post-media record
63 public static function insert(array $media, bool $force = false)
65 if (empty($media['url']) || empty($media['uri-id']) || !isset($media['type'])) {
66 Logger::warning('Incomplete media data', ['media' => $media]);
70 // "document" has got the lowest priority. So when the same file is both attached as document
71 // and embedded as picture then we only store the picture or replace the document
72 $found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
73 if (!$force && !empty($found) && (($found['type'] != self::DOCUMENT) || ($media['type'] == self::DOCUMENT))) {
74 Logger::info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
78 $media = self::unsetEmptyFields($media);
80 // We are storing as fast as possible to avoid duplicated network requests
81 // when fetching additional information for pictures and other content.
82 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
83 Logger::info('Stored media', ['result' => $result, 'media' => $media, 'callstack' => System::callstack()]);
86 $media = self::fetchAdditionalData($media);
87 $media = self::unsetEmptyFields($media);
89 if (array_diff_assoc($media, $stored)) {
90 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
91 Logger::info('Updated media', ['result' => $result, 'media' => $media]);
93 Logger::info('Nothing to update', ['media' => $media]);
98 * Remove empty media fields
100 * @param array $media
101 * @return array cleaned media array
103 private static function unsetEmptyFields(array $media)
105 $fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'description'];
106 foreach ($fields as $field) {
107 if (empty($media[$field])) {
108 unset($media[$field]);
115 * Copy attachments from one uri-id to another
117 * @param integer $from_uri_id
118 * @param integer $to_uri_id
121 public static function copy(int $from_uri_id, int $to_uri_id)
123 $attachments = self::getByURIId($from_uri_id);
124 foreach ($attachments as $attachment) {
125 $attachment['uri-id'] = $to_uri_id;
126 self::insert($attachment);
131 * Creates the "[attach]" element from the given attributes
133 * @param string $href
134 * @param integer $length
135 * @param string $type
136 * @param string $title
137 * @return string "[attach]" element
139 public static function getAttachElement(string $href, int $length, string $type, string $title = '')
141 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
142 'size' => $length, 'mimetype' => $type, 'description' => $title]);
144 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
145 '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
149 * Fetch additional data for the provided media array
151 * @param array $media
152 * @return array media array with additional data
154 public static function fetchAdditionalData(array $media)
156 // Fetch the mimetype or size if missing.
157 if (empty($media['mimetype']) || empty($media['size'])) {
158 $timeout = DI::config()->get('system', 'xrd_timeout');
159 $curlResult = DI::httpRequest()->head($media['url'], ['timeout' => $timeout]);
160 if ($curlResult->isSuccess()) {
161 if (empty($media['mimetype'])) {
162 $media['mimetype'] = $curlResult->getHeader('Content-Type');
164 if (empty($media['size'])) {
165 $media['size'] = (int)$curlResult->getHeader('Content-Length');
168 Logger::notice('Could not fetch head', ['media' => $media]);
172 $filetype = !empty($media['mimetype']) ? strtolower(current(explode('/', $media['mimetype']))) : '';
174 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
175 $imagedata = Images::getInfoFromURLCached($media['url']);
176 if (!empty($imagedata)) {
177 $media['mimetype'] = $imagedata['mime'];
178 $media['size'] = $imagedata['size'];
179 $media['width'] = $imagedata[0];
180 $media['height'] = $imagedata[1];
182 Logger::notice('No image data', ['media' => $media]);
184 if (!empty($media['preview'])) {
185 $imagedata = Images::getInfoFromURLCached($media['preview']);
186 if (!empty($imagedata)) {
187 $media['preview-width'] = $imagedata[0];
188 $media['preview-height'] = $imagedata[1];
193 if ($media['type'] != self::DOCUMENT) {
194 $media = self::addType($media);
197 if ($media['type'] == self::HTML) {
198 $data = ParseUrl::getSiteinfoCached($media['url'], false);
199 $media['preview'] = $data['images'][0]['src'] ?? null;
200 $media['preview-height'] = $data['images'][0]['height'] ?? null;
201 $media['preview-width'] = $data['images'][0]['width'] ?? null;
202 $media['description'] = $data['text'] ?? null;
203 $media['name'] = $data['title'] ?? null;
204 $media['author-url'] = $data['author_url'] ?? null;
205 $media['author-name'] = $data['author_name'] ?? null;
206 $media['author-image'] = $data['author_img'] ?? null;
207 $media['publisher-url'] = $data['publisher_url'] ?? null;
208 $media['publisher-name'] = $data['publisher_name'] ?? null;
209 $media['publisher-image'] = $data['publisher_img'] ?? null;
215 * Add the detected type to the media array
218 * @return array data array with the detected type
220 public static function addType(array $data)
222 if (empty($data['mimetype'])) {
223 Logger::info('No MimeType provided', ['media' => $data]);
227 $type = explode('/', current(explode(';', $data['mimetype'])));
228 if (count($type) < 2) {
229 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $data]);
230 $data['type'] = self::UNKNOWN;
234 $filetype = strtolower($type[0]);
235 $subtype = strtolower($type[1]);
237 if ($filetype == 'image') {
238 $data['type'] = self::IMAGE;
239 } elseif ($filetype == 'video') {
240 $data['type'] = self::VIDEO;
241 } elseif ($filetype == 'audio') {
242 $data['type'] = self::AUDIO;
243 } elseif (($filetype == 'text') && ($subtype == 'html')) {
244 $data['type'] = self::HTML;
245 } elseif (($filetype == 'text') && ($subtype == 'xml')) {
246 $data['type'] = self::XML;
247 } elseif (($filetype == 'text') && ($subtype == 'plain')) {
248 $data['type'] = self::PLAIN;
249 } elseif ($filetype == 'text') {
250 $data['type'] = self::TEXT;
251 } elseif (($filetype == 'application') && ($subtype == 'x-bittorrent')) {
252 $data['type'] = self::TORRENT;
253 } elseif ($filetype == 'application') {
254 $data['type'] = self::APPLICATION;
256 $data['type'] = self::UNKNOWN;
257 Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
261 Logger::debug('Detected type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
266 * Tests for path patterns that are usef for picture links in Friendica
268 * @param string $page Link to the image page
269 * @param string $preview Preview picture
272 private static function isPictureLink(string $page, string $preview)
274 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
278 * Add media links and remove them from the body
280 * @param integer $uriid
281 * @param string $body
282 * @return string Body without media links
284 public static function insertFromBody(int $uriid, string $body)
286 // Simplify image codes
287 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
290 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
291 foreach ($pictures as $picture) {
292 if (!self::isPictureLink($picture[1], $picture[2])) {
295 $body = str_replace($picture[0], '', $body);
296 $image = str_replace('-1.', '-0.', $picture[2]);
297 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
298 'preview' => $picture[2], 'description' => $picture[3]];
302 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
303 foreach ($pictures as $picture) {
304 $body = str_replace($picture[0], '', $body);
305 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
309 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
310 foreach ($pictures as $picture) {
311 if (!self::isPictureLink($picture[1], $picture[2])) {
314 $body = str_replace($picture[0], '', $body);
315 $image = str_replace('-1.', '-0.', $picture[2]);
316 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
317 'preview' => $picture[2], 'description' => null];
321 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
322 foreach ($pictures as $picture) {
323 $body = str_replace($picture[0], '', $body);
324 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
328 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]/ism", $body, $audios, PREG_SET_ORDER)) {
329 foreach ($audios as $audio) {
330 $body = str_replace($audio[0], '', $body);
331 $attachments[$audio[1]] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
335 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]/ism", $body, $videos, PREG_SET_ORDER)) {
336 foreach ($videos as $video) {
337 $body = str_replace($video[0], '', $body);
338 $attachments[$video[1]] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
342 $url = PageInfo::getRelevantUrlFromBody($body);
344 Logger::debug('Got page url', ['url' => $url]);
345 $attachments[$url] = ['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url];
348 foreach ($attachments as $attachment) {
349 self::insert($attachment);
356 * Add media links from the attachment field
358 * @param integer $uriid
359 * @param string $body
361 public static function insertFromAttachmentData(int $uriid, string $body)
363 $data = BBCode::getAttachmentData($body);
368 Logger::info('Adding attachment data', ['data' => $data]);
371 'type' => self::HTML,
372 'url' => $data['url'],
373 'preview' => $data['preview'] ?? null,
374 'description' => $data['description'] ?? null,
375 'name' => $data['title'] ?? null,
376 'author-url' => $data['author_url'] ?? null,
377 'author-name' => $data['author_name'] ?? null,
378 'publisher-url' => $data['provider_url'] ?? null,
379 'publisher-name' => $data['provider_name'] ?? null,
381 if (!empty($data['image'])) {
382 $attachment['preview'] = $data['image'];
384 self::insert($attachment);
388 * Add media links from the attach field
390 * @param integer $uriid
391 * @param string $attach
394 public static function insertFromAttachment(int $uriid, string $attach)
396 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
400 foreach ($matches as $attachment) {
401 $media['type'] = self::DOCUMENT;
402 $media['uri-id'] = $uriid;
403 $media['url'] = $attachment[1];
404 $media['size'] = $attachment[2];
405 $media['mimetype'] = $attachment[3];
406 $media['description'] = $attachment[4] ?? '';
408 self::insert($media);
413 * Retrieves the media attachments associated with the provided item ID.
416 * @param array $types
420 public static function getByURIId(int $uri_id, array $types = [])
422 $condition = ['uri-id' => $uri_id];
424 if (!empty($types)) {
425 $condition = DBA::mergeConditions($condition, ['type' => $types]);
428 return DBA::selectToArray('post-media', [], $condition);
432 * Checks if media attachments are associated with the provided item ID.
435 * @param array $types
439 public static function existsByURIId(int $uri_id, array $types = [])
441 $condition = ['uri-id' => $uri_id];
443 if (!empty($types)) {
444 $condition = DBA::mergeConditions($condition, ['type' => $types]);
447 return DBA::exists('post-media', $condition);
451 * Split the attachment media in the three segments "visual", "link" and "additional"
454 * @param string $guid
455 * @param array $links ist of links that shouldn't be added
456 * @return array attachments
458 public static function splitAttachments(int $uri_id, string $guid = '', array $links = [])
460 $attachments = ['visual' => [], 'link' => [], 'additional' => []];
462 $media = self::getByURIId($uri_id);
470 foreach ($media as $medium) {
471 foreach ($links as $link) {
472 if (Strings::compareLink($link, $medium['url'])) {
477 $type = explode('/', current(explode(';', $medium['mimetype'])));
478 if (count($type) < 2) {
479 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $medium]);
483 $filetype = strtolower($type[0]);
484 $subtype = strtolower($type[1]);
487 $medium['filetype'] = $filetype;
488 $medium['subtype'] = $subtype;
490 if ($medium['type'] == self::HTML || (($filetype == 'text') && ($subtype == 'html'))) {
491 $attachments['link'][] = $medium;
495 if (in_array($medium['type'], [self::AUDIO, self::IMAGE]) ||
496 in_array($filetype, ['audio', 'image'])) {
497 $attachments['visual'][] = $medium;
498 } elseif (($medium['type'] == self::VIDEO) || ($filetype == 'video')) {
499 if (strpos($medium['url'], $guid) !== false) {
500 // Peertube videos are delivered in many different resolutions. We pick a moderate one.
501 // By checking against the GUID we also ensure to only work this way on Peertube posts.
502 // This wouldn't be executed when someone for example on Mastodon was sharing multiple videos in a single post.
503 if (empty($height) || ($height > $medium['height']) && ($medium['height'] >= 480)) {
504 $height = $medium['height'];
505 $selected = $medium['url'];
507 $video[$medium['url']] = $medium;
509 $attachments['visual'][] = $medium;
512 $attachments['additional'][] = $medium;
515 if (!empty($selected)) {
516 $attachments['visual'][] = $video[$selected];
517 unset($video[$selected]);
518 foreach ($video as $element) {
519 $attachments['additional'][] = $element;
526 * Add media attachments to the body
529 * @return string body
531 public static function addAttachmentsToBody(int $uriid)
533 $item = Post::selectFirst(['body'], ['uri-id' => $uriid]);
534 if (!DBA::isResult($item)) {
537 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $item['body']);
539 foreach (self::getByURIId($uriid, [self::IMAGE, self::AUDIO, self::VIDEO]) as $media) {
540 if (Item::containsLink($body, $media['url'])) {
544 if ($media['type'] == self::IMAGE) {
545 if (!empty($media['description'])) {
546 $body .= "\n[img=" . $media['url'] . ']' . $media['description'] .'[/img]';
548 $body .= "\n[img]" . $media['url'] .'[/img]';
550 } elseif ($media['type'] == self::AUDIO) {
551 $body .= "\n[audio]" . $media['url'] . "[/audio]\n";
552 } elseif ($media['type'] == self::VIDEO) {
553 $body .= "\n[video]" . $media['url'] . "[/video]\n";
557 if (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $item['body'], $match)) {
558 $body .= "\n" . $match[1];