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\DBA;
28 use Friendica\Util\Images;
33 * This Model class handles media interactions.
34 * This tables stores medias (images, videos, audio files) related to posts.
46 * Insert a post-media record
51 public static function insert(array $media, bool $force = false)
53 if (empty($media['url']) || empty($media['uri-id']) || empty($media['type'])) {
54 Logger::warning('Incomplete media data', ['media' => $media]);
58 // "document" has got the lowest priority. So when the same file is both attached as document
59 // and embedded as picture then we only store the picture or replace the document
60 $found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
61 if (!$force && !empty($found) && (($found['type'] != self::DOCUMENT) || ($media['type'] == self::DOCUMENT))) {
62 Logger::info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
66 $fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'description'];
67 foreach ($fields as $field) {
68 if (empty($media[$field])) {
69 unset($media[$field]);
73 // We are storing as fast as possible to avoid duplicated network requests
74 // when fetching additional information for pictures and other content.
75 $result = DBA::insert('post-media', $media, true);
76 Logger::info('Stored media', ['result' => $result, 'media' => $media, 'callstack' => System::callstack()]);
79 $media = self::fetchAdditionalData($media);
81 if (array_diff_assoc($media, $stored)) {
82 $result = DBA::insert('post-media', $media, true);
83 Logger::info('Updated media', ['result' => $result, 'media' => $media]);
85 Logger::info('Nothing to update', ['media' => $media]);
90 * Copy attachments from one uri-id to another
92 * @param integer $from_uri_id
93 * @param integer $to_uri_id
96 public static function copy(int $from_uri_id, int $to_uri_id)
98 $attachments = self::getByURIId($from_uri_id);
99 foreach ($attachments as $attachment) {
100 $attachment['uri-id'] = $to_uri_id;
101 self::insert($attachment);
106 * Creates the "[attach]" element from the given attributes
108 * @param string $href
109 * @param integer $length
110 * @param string $type
111 * @param string $title
112 * @return string "[attach]" element
114 public static function getAttachElement(string $href, int $length, string $type, string $title = '')
116 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
117 'size' => $length, 'mimetype' => $type, 'description' => $title]);
119 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
120 '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
124 * Fetch additional data for the provided media array
126 * @param array $media
127 * @return array media array with additional data
129 public static function fetchAdditionalData(array $media)
131 // Fetch the mimetype or size if missing.
132 // We don't do it for torrent links since they need special treatment.
133 // We don't do this for images, since we are fetching their details some lines later anyway.
134 if (!in_array($media['type'], [self::TORRENT, self::IMAGE]) && (empty($media['mimetype']) || empty($media['size']))) {
135 $timeout = DI::config()->get('system', 'xrd_timeout');
136 $curlResult = DI::httpRequest()->head($media['url'], ['timeout' => $timeout]);
137 if ($curlResult->isSuccess()) {
138 $header = $curlResult->getHeaderArray();
139 if (empty($media['mimetype']) && !empty($header['content-type'])) {
140 $media['mimetype'] = $header['content-type'];
142 if (empty($media['size']) && !empty($header['content-length'])) {
143 $media['size'] = $header['content-length'];
148 $filetype = !empty($media['mimetype']) ? strtolower(substr($media['mimetype'], 0, strpos($media['mimetype'], '/'))) : '';
150 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
151 $imagedata = Images::getInfoFromURLCached($media['url']);
152 if (!empty($imagedata)) {
153 $media['mimetype'] = $imagedata['mime'];
154 $media['size'] = $imagedata['size'];
155 $media['width'] = $imagedata[0];
156 $media['height'] = $imagedata[1];
158 if (!empty($media['preview'])) {
159 $imagedata = Images::getInfoFromURLCached($media['preview']);
160 if (!empty($imagedata)) {
161 $media['preview-width'] = $imagedata[0];
162 $media['preview-height'] = $imagedata[1];
170 * Tests for path patterns that are usef for picture links in Friendica
172 * @param string $page Link to the image page
173 * @param string $preview Preview picture
176 private static function isPictureLink(string $page, string $preview)
178 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
182 * Add media links and remove them from the body
184 * @param integer $uriid
185 * @param string $body
186 * @return string Body without media links
188 public static function insertFromBody(int $uriid, string $body)
190 // Simplify image codes
191 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
194 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
195 foreach ($pictures as $picture) {
196 if (!self::isPictureLink($picture[1], $picture[2])) {
199 $body = str_replace($picture[0], '', $body);
200 $image = str_replace('-1.', '-0.', $picture[2]);
201 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
202 'preview' => $picture[2], 'description' => $picture[3]];
206 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
207 foreach ($pictures as $picture) {
208 $body = str_replace($picture[0], '', $body);
209 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
213 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
214 foreach ($pictures as $picture) {
215 if (!self::isPictureLink($picture[1], $picture[2])) {
218 $body = str_replace($picture[0], '', $body);
219 $image = str_replace('-1.', '-0.', $picture[2]);
220 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
221 'preview' => $picture[2], 'description' => null];
225 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
226 foreach ($pictures as $picture) {
227 $body = str_replace($picture[0], '', $body);
228 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
232 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]/ism", $body, $audios, PREG_SET_ORDER)) {
233 foreach ($audios as $audio) {
234 $body = str_replace($audio[0], '', $body);
235 $attachments[] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
239 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]/ism", $body, $videos, PREG_SET_ORDER)) {
240 foreach ($videos as $video) {
241 $body = str_replace($video[0], '', $body);
242 $attachments[] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
246 foreach ($attachments as $attachment) {
247 self::insert($attachment);
254 * Add media links from the attach field
256 * @param integer $uriid
257 * @param string $attach
260 public static function insertFromAttachment(int $uriid, string $attach)
262 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
266 foreach ($matches as $attachment) {
267 $media['type'] = self::DOCUMENT;
268 $media['uri-id'] = $uriid;
269 $media['url'] = $attachment[1];
270 $media['size'] = $attachment[2];
271 $media['mimetype'] = $attachment[3];
272 $media['description'] = $attachment[4] ?? '';
274 self::insert($media);
279 * Retrieves the media attachments associated with the provided item ID.
282 * @param array $types
286 public static function getByURIId(int $uri_id, array $types = [])
288 $condition = ['uri-id' => $uri_id];
290 if (!empty($types)) {
291 $condition = DBA::mergeConditions($condition, ['type' => $types]);
294 return DBA::selectToArray('post-media', [], $condition);