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\Util\Images;
32 use Friendica\Util\ParseUrl;
37 * This Model class handles media interactions.
38 * This tables stores medias (images, videos, audio files) related to posts.
47 const APPLICATION = 5;
55 * Insert a post-media record
60 public static function insert(array $media, bool $force = false)
62 if (empty($media['url']) || empty($media['uri-id']) || !isset($media['type'])) {
63 Logger::warning('Incomplete media data', ['media' => $media]);
67 // "document" has got the lowest priority. So when the same file is both attached as document
68 // and embedded as picture then we only store the picture or replace the document
69 $found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
70 if (!$force && !empty($found) && (($found['type'] != self::DOCUMENT) || ($media['type'] == self::DOCUMENT))) {
71 Logger::info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
75 $media = self::unsetEmptyFields($media);
77 // We are storing as fast as possible to avoid duplicated network requests
78 // when fetching additional information for pictures and other content.
79 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
80 Logger::info('Stored media', ['result' => $result, 'media' => $media, 'callstack' => System::callstack()]);
83 $media = self::fetchAdditionalData($media);
84 $media = self::unsetEmptyFields($media);
86 if (array_diff_assoc($media, $stored)) {
87 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
88 Logger::info('Updated media', ['result' => $result, 'media' => $media]);
90 Logger::info('Nothing to update', ['media' => $media]);
95 * Remove empty media fields
98 * @return array cleaned media array
100 private static function unsetEmptyFields(array $media)
102 $fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'description'];
103 foreach ($fields as $field) {
104 if (empty($media[$field])) {
105 unset($media[$field]);
112 * Copy attachments from one uri-id to another
114 * @param integer $from_uri_id
115 * @param integer $to_uri_id
118 public static function copy(int $from_uri_id, int $to_uri_id)
120 $attachments = self::getByURIId($from_uri_id);
121 foreach ($attachments as $attachment) {
122 $attachment['uri-id'] = $to_uri_id;
123 self::insert($attachment);
128 * Creates the "[attach]" element from the given attributes
130 * @param string $href
131 * @param integer $length
132 * @param string $type
133 * @param string $title
134 * @return string "[attach]" element
136 public static function getAttachElement(string $href, int $length, string $type, string $title = '')
138 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
139 'size' => $length, 'mimetype' => $type, 'description' => $title]);
141 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
142 '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
146 * Fetch additional data for the provided media array
148 * @param array $media
149 * @return array media array with additional data
151 public static function fetchAdditionalData(array $media)
153 // Fetch the mimetype or size if missing.
154 if (empty($media['mimetype']) || empty($media['size'])) {
155 $timeout = DI::config()->get('system', 'xrd_timeout');
156 $curlResult = DI::httpRequest()->head($media['url'], ['timeout' => $timeout]);
157 if ($curlResult->isSuccess()) {
158 if (empty($media['mimetype'])) {
159 $media['mimetype'] = $curlResult->getHeader('Content-Type');
161 if (empty($media['size'])) {
162 $media['size'] = (int)$curlResult->getHeader('Content-Length');
165 Logger::notice('Could not fetch head', ['media' => $media]);
169 $filetype = !empty($media['mimetype']) ? strtolower(current(explode('/', $media['mimetype']))) : '';
171 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
172 $imagedata = Images::getInfoFromURLCached($media['url']);
173 if (!empty($imagedata)) {
174 $media['mimetype'] = $imagedata['mime'];
175 $media['size'] = $imagedata['size'];
176 $media['width'] = $imagedata[0];
177 $media['height'] = $imagedata[1];
179 Logger::notice('No image data', ['media' => $media]);
181 if (!empty($media['preview'])) {
182 $imagedata = Images::getInfoFromURLCached($media['preview']);
183 if (!empty($imagedata)) {
184 $media['preview-width'] = $imagedata[0];
185 $media['preview-height'] = $imagedata[1];
190 if ($media['type'] != self::DOCUMENT) {
191 $media = self::addType($media);
194 if ($media['type'] == self::HTML) {
195 $data = ParseUrl::getSiteinfoCached($media['url'], false);
196 $media['preview'] = $data['images'][0]['src'] ?? null;
197 $media['preview-height'] = $data['images'][0]['height'] ?? null;
198 $media['preview-width'] = $data['images'][0]['width'] ?? null;
199 $media['description'] = $data['text'] ?? null;
200 $media['name'] = $data['title'] ?? null;
201 $media['author-url'] = $data['author_url'] ?? null;
202 $media['author-name'] = $data['author_name'] ?? null;
203 $media['author-image'] = $data['author_img'] ?? null;
204 $media['publisher-url'] = $data['publisher_url'] ?? null;
205 $media['publisher-name'] = $data['publisher_name'] ?? null;
206 $media['publisher-image'] = $data['publisher_img'] ?? null;
212 * Add the detected type to the media array
215 * @return array data array with the detected type
217 public static function addType(array $data)
219 if (empty($data['mimetype'])) {
220 Logger::info('No MimeType provided', ['media' => $data]);
224 $type = explode('/', current(explode(';', $data['mimetype'])));
225 if (count($type) < 2) {
226 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $data]);
227 $data['type'] = self::UNKNOWN;
231 $filetype = strtolower($type[0]);
232 $subtype = strtolower($type[1]);
234 if ($filetype == 'image') {
235 $data['type'] = self::IMAGE;
236 } elseif ($filetype == 'video') {
237 $data['type'] = self::VIDEO;
238 } elseif ($filetype == 'audio') {
239 $data['type'] = self::AUDIO;
240 } elseif (($filetype == 'text') && ($subtype == 'html')) {
241 $data['type'] = self::HTML;
242 } elseif (($filetype == 'text') && ($subtype == 'xml')) {
243 $data['type'] = self::XML;
244 } elseif (($filetype == 'text') && ($subtype == 'plain')) {
245 $data['type'] = self::PLAIN;
246 } elseif ($filetype == 'text') {
247 $data['type'] = self::TEXT;
248 } elseif (($filetype == 'application') && ($subtype == 'x-bittorrent')) {
249 $data['type'] = self::TORRENT;
250 } elseif ($filetype == 'application') {
251 $data['type'] = self::APPLICATION;
253 $data['type'] = self::UNKNOWN;
254 Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
258 Logger::debug('Detected type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
263 * Tests for path patterns that are usef for picture links in Friendica
265 * @param string $page Link to the image page
266 * @param string $preview Preview picture
269 private static function isPictureLink(string $page, string $preview)
271 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
275 * Add media links and remove them from the body
277 * @param integer $uriid
278 * @param string $body
279 * @return string Body without media links
281 public static function insertFromBody(int $uriid, string $body)
283 // Simplify image codes
284 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
287 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
288 foreach ($pictures as $picture) {
289 if (!self::isPictureLink($picture[1], $picture[2])) {
292 $body = str_replace($picture[0], '', $body);
293 $image = str_replace('-1.', '-0.', $picture[2]);
294 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
295 'preview' => $picture[2], 'description' => $picture[3]];
299 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
300 foreach ($pictures as $picture) {
301 $body = str_replace($picture[0], '', $body);
302 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
306 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
307 foreach ($pictures as $picture) {
308 if (!self::isPictureLink($picture[1], $picture[2])) {
311 $body = str_replace($picture[0], '', $body);
312 $image = str_replace('-1.', '-0.', $picture[2]);
313 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
314 'preview' => $picture[2], 'description' => null];
318 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
319 foreach ($pictures as $picture) {
320 $body = str_replace($picture[0], '', $body);
321 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
325 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]/ism", $body, $audios, PREG_SET_ORDER)) {
326 foreach ($audios as $audio) {
327 $body = str_replace($audio[0], '', $body);
328 $attachments[$audio[1]] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
332 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]/ism", $body, $videos, PREG_SET_ORDER)) {
333 foreach ($videos as $video) {
334 $body = str_replace($video[0], '', $body);
335 $attachments[$video[1]] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
339 $url = PageInfo::getRelevantUrlFromBody($body);
341 Logger::debug('Got page url', ['url' => $url]);
342 $attachments[$url] = ['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url];
345 foreach ($attachments as $attachment) {
346 self::insert($attachment);
353 * Add media links from the attachment field
355 * @param integer $uriid
356 * @param string $body
358 public static function insertFromAttachmentData(int $uriid, string $body)
360 $data = BBCode::getAttachmentData($body);
365 Logger::info('Adding attachment data', ['data' => $data]);
368 'type' => self::HTML,
369 'url' => $data['url'],
370 'preview' => $data['preview'] ?? null,
371 'description' => $data['description'] ?? null,
372 'name' => $data['title'] ?? null,
373 'author-url' => $data['author_url'] ?? null,
374 'author-name' => $data['author_name'] ?? null,
375 'publisher-url' => $data['provider_url'] ?? null,
376 'publisher-name' => $data['provider_name'] ?? null,
378 if (!empty($data['image'])) {
379 $attachment['preview'] = $data['image'];
381 self::insert($attachment);
385 * Add media links from the attach field
387 * @param integer $uriid
388 * @param string $attach
391 public static function insertFromAttachment(int $uriid, string $attach)
393 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
397 foreach ($matches as $attachment) {
398 $media['type'] = self::DOCUMENT;
399 $media['uri-id'] = $uriid;
400 $media['url'] = $attachment[1];
401 $media['size'] = $attachment[2];
402 $media['mimetype'] = $attachment[3];
403 $media['description'] = $attachment[4] ?? '';
405 self::insert($media);
410 * Retrieves the media attachments associated with the provided item ID.
413 * @param array $types
417 public static function getByURIId(int $uri_id, array $types = [])
419 $condition = ['uri-id' => $uri_id];
421 if (!empty($types)) {
422 $condition = DBA::mergeConditions($condition, ['type' => $types]);
425 return DBA::selectToArray('post-media', [], $condition);
429 * Checks if media attachments are associated with the provided item ID.
432 * @param array $types
436 public static function existsByURIId(int $uri_id, array $types = [])
438 $condition = ['uri-id' => $uri_id];
440 if (!empty($types)) {
441 $condition = DBA::mergeConditions($condition, ['type' => $types]);
444 return DBA::exists('post-media', $condition);
448 * Split the attachment media in the three segments "visual", "link" and "additional"
451 * @param string $guid
452 * @param array $links ist of links that shouldn't be added
453 * @return array attachments
455 public static function splitAttachments(int $uri_id, string $guid = '', array $links = [])
457 $attachments = ['visual' => [], 'link' => [], 'additional' => []];
459 $media = self::getByURIId($uri_id);
467 foreach ($media as $medium) {
468 $medium['url'] = strtolower($medium['url']);
469 if (in_array($medium['url'], $links)) {
473 $type = explode('/', current(explode(';', $medium['mimetype'])));
474 if (count($type) < 2) {
475 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $medium]);
479 $filetype = strtolower($type[0]);
480 $subtype = strtolower($type[1]);
483 $medium['filetype'] = $filetype;
484 $medium['subtype'] = $subtype;
486 if ($medium['type'] == self::HTML || (($filetype == 'text') && ($subtype == 'html'))) {
487 $attachments['link'][] = $medium;
491 if (in_array($medium['type'], [self::AUDIO, self::IMAGE]) ||
492 in_array($filetype, ['audio', 'image'])) {
493 $attachments['visual'][] = $medium;
494 } elseif (($medium['type'] == self::VIDEO) || ($filetype == 'video')) {
495 if (strpos($medium['url'], $guid) !== false) {
496 // Peertube videos are delivered in many different resolutions. We pick a moderate one.
497 // By checking against the GUID we also ensure to only work this way on Peertube posts.
498 // This wouldn't be executed when someone for example on Mastodon was sharing multiple videos in a single post.
499 if (empty($height) || ($height > $medium['height']) && ($medium['height'] >= 480)) {
500 $height = $medium['height'];
501 $selected = $medium['url'];
503 $video[$medium['url']] = $medium;
505 $attachments['visual'][] = $medium;
508 $attachments['additional'][] = $medium;
511 if (!empty($selected)) {
512 $attachments['visual'][] = $video[$selected];
513 unset($video[$selected]);
514 foreach ($video as $element) {
515 $attachments['additional'][] = $element;