3 * @copyright Copyright (C) 2020, Friendica
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\Core\Logger;
25 use Friendica\Core\System;
26 use Friendica\Database\Database;
27 use Friendica\Database\DBA;
29 use Friendica\Util\Images;
34 * This Model class handles media interactions.
35 * This tables stores medias (images, videos, audio files) related to posts.
47 * Insert a post-media record
52 public static function insert(array $media, bool $force = false)
54 if (empty($media['url']) || empty($media['uri-id']) || empty($media['type'])) {
55 Logger::warning('Incomplete media data', ['media' => $media]);
59 // "document" has got the lowest priority. So when the same file is both attached as document
60 // and embedded as picture then we only store the picture or replace the document
61 $found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
62 if (!$force && !empty($found) && (($found['type'] != self::DOCUMENT) || ($media['type'] == self::DOCUMENT))) {
63 Logger::info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
67 $fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'description'];
68 foreach ($fields as $field) {
69 if (empty($media[$field])) {
70 unset($media[$field]);
74 // We are storing as fast as possible to avoid duplicated network requests
75 // when fetching additional information for pictures and other content.
76 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
77 Logger::info('Stored media', ['result' => $result, 'media' => $media, 'callstack' => System::callstack()]);
80 $media = self::fetchAdditionalData($media);
82 if (array_diff_assoc($media, $stored)) {
83 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
84 Logger::info('Updated media', ['result' => $result, 'media' => $media]);
86 Logger::info('Nothing to update', ['media' => $media]);
91 * Copy attachments from one uri-id to another
93 * @param integer $from_uri_id
94 * @param integer $to_uri_id
97 public static function copy(int $from_uri_id, int $to_uri_id)
99 $attachments = self::getByURIId($from_uri_id);
100 foreach ($attachments as $attachment) {
101 $attachment['uri-id'] = $to_uri_id;
102 self::insert($attachment);
107 * Creates the "[attach]" element from the given attributes
109 * @param string $href
110 * @param integer $length
111 * @param string $type
112 * @param string $title
113 * @return string "[attach]" element
115 public static function getAttachElement(string $href, int $length, string $type, string $title = '')
117 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
118 'size' => $length, 'mimetype' => $type, 'description' => $title]);
120 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
121 '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
125 * Fetch additional data for the provided media array
127 * @param array $media
128 * @return array media array with additional data
130 public static function fetchAdditionalData(array $media)
132 // Fetch the mimetype or size if missing.
133 // We don't do it for torrent links since they need special treatment.
134 // We don't do this for images, since we are fetching their details some lines later anyway.
135 if (!in_array($media['type'], [self::TORRENT, self::IMAGE]) && (empty($media['mimetype']) || empty($media['size']))) {
136 $timeout = DI::config()->get('system', 'xrd_timeout');
137 $curlResult = DI::httpRequest()->head($media['url'], ['timeout' => $timeout]);
138 if ($curlResult->isSuccess()) {
139 $header = $curlResult->getHeaderArray();
140 if (empty($media['mimetype']) && !empty($header['content-type'])) {
141 $media['mimetype'] = $header['content-type'];
143 if (empty($media['size']) && !empty($header['content-length'])) {
144 $media['size'] = $header['content-length'];
149 $filetype = !empty($media['mimetype']) ? strtolower(substr($media['mimetype'], 0, strpos($media['mimetype'], '/'))) : '';
151 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
152 $imagedata = Images::getInfoFromURLCached($media['url']);
153 if (!empty($imagedata)) {
154 $media['mimetype'] = $imagedata['mime'];
155 $media['size'] = $imagedata['size'];
156 $media['width'] = $imagedata[0];
157 $media['height'] = $imagedata[1];
159 if (!empty($media['preview'])) {
160 $imagedata = Images::getInfoFromURLCached($media['preview']);
161 if (!empty($imagedata)) {
162 $media['preview-width'] = $imagedata[0];
163 $media['preview-height'] = $imagedata[1];
171 * Tests for path patterns that are usef for picture links in Friendica
173 * @param string $page Link to the image page
174 * @param string $preview Preview picture
177 private static function isPictureLink(string $page, string $preview)
179 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
183 * Add media links and remove them from the body
185 * @param integer $uriid
186 * @param string $body
187 * @return string Body without media links
189 public static function insertFromBody(int $uriid, string $body)
191 // Simplify image codes
192 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
195 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
196 foreach ($pictures as $picture) {
197 if (!self::isPictureLink($picture[1], $picture[2])) {
200 $body = str_replace($picture[0], '', $body);
201 $image = str_replace('-1.', '-0.', $picture[2]);
202 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
203 'preview' => $picture[2], 'description' => $picture[3]];
207 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
208 foreach ($pictures as $picture) {
209 $body = str_replace($picture[0], '', $body);
210 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
214 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
215 foreach ($pictures as $picture) {
216 if (!self::isPictureLink($picture[1], $picture[2])) {
219 $body = str_replace($picture[0], '', $body);
220 $image = str_replace('-1.', '-0.', $picture[2]);
221 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
222 'preview' => $picture[2], 'description' => null];
226 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
227 foreach ($pictures as $picture) {
228 $body = str_replace($picture[0], '', $body);
229 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
233 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]/ism", $body, $audios, PREG_SET_ORDER)) {
234 foreach ($audios as $audio) {
235 $body = str_replace($audio[0], '', $body);
236 $attachments[] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
240 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]/ism", $body, $videos, PREG_SET_ORDER)) {
241 foreach ($videos as $video) {
242 $body = str_replace($video[0], '', $body);
243 $attachments[] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
247 foreach ($attachments as $attachment) {
248 self::insert($attachment);
255 * Add media links from the attach field
257 * @param integer $uriid
258 * @param string $attach
261 public static function insertFromAttachment(int $uriid, string $attach)
263 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
267 foreach ($matches as $attachment) {
268 $media['type'] = self::DOCUMENT;
269 $media['uri-id'] = $uriid;
270 $media['url'] = $attachment[1];
271 $media['size'] = $attachment[2];
272 $media['mimetype'] = $attachment[3];
273 $media['description'] = $attachment[4] ?? '';
275 self::insert($media);
280 * Retrieves the media attachments associated with the provided item ID.
283 * @param array $types
287 public static function getByURIId(int $uri_id, array $types = [])
289 $condition = ['uri-id' => $uri_id];
291 if (!empty($types)) {
292 $condition = DBA::mergeConditions($condition, ['type' => $types]);
295 return DBA::selectToArray('post-media', [], $condition);