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 * Creates the "[attach]" element from the given attributes
93 * @param integer $length
95 * @param string $title
96 * @return string "[attach]" element
98 public static function getAttachElement(string $href, int $length, string $type, string $title = '')
100 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
101 'size' => $length, 'mimetype' => $type, 'description' => $title]);
103 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
104 '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
108 * Fetch additional data for the provided media array
110 * @param array $media
111 * @return array media array with additional data
113 public static function fetchAdditionalData(array $media)
115 // Fetch the mimetype or size if missing.
116 // We don't do it for torrent links since they need special treatment.
117 // We don't do this for images, since we are fetching their details some lines later anyway.
118 if (!in_array($media['type'], [self::TORRENT, self::IMAGE]) && (empty($media['mimetype']) || empty($media['size']))) {
119 $timeout = DI::config()->get('system', 'xrd_timeout');
120 $curlResult = DI::httpRequest()->head($media['url'], ['timeout' => $timeout]);
121 if ($curlResult->isSuccess()) {
122 $header = $curlResult->getHeaderArray();
123 if (empty($media['mimetype']) && !empty($header['content-type'])) {
124 $media['mimetype'] = $header['content-type'];
126 if (empty($media['size']) && !empty($header['content-length'])) {
127 $media['size'] = $header['content-length'];
132 $filetype = !empty($media['mimetype']) ? strtolower(substr($media['mimetype'], 0, strpos($media['mimetype'], '/'))) : '';
134 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
135 $imagedata = Images::getInfoFromURLCached($media['url']);
136 if (!empty($imagedata)) {
137 $media['mimetype'] = $imagedata['mime'];
138 $media['size'] = $imagedata['size'];
139 $media['width'] = $imagedata[0];
140 $media['height'] = $imagedata[1];
142 if (!empty($media['preview'])) {
143 $imagedata = Images::getInfoFromURLCached($media['preview']);
144 if (!empty($imagedata)) {
145 $media['preview-width'] = $imagedata[0];
146 $media['preview-height'] = $imagedata[1];
154 * Tests for path patterns that are usef for picture links in Friendica
156 * @param string $page Link to the image page
157 * @param string $preview Preview picture
160 private static function isPictureLink(string $page, string $preview)
162 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
166 * Add media links and remove them from the body
168 * @param integer $uriid
169 * @param string $body
170 * @return string Body without media links
172 public static function insertFromBody(int $uriid, string $body)
174 // Simplify image codes
175 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
178 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
179 foreach ($pictures as $picture) {
180 if (!self::isPictureLink($picture[1], $picture[2])) {
183 $body = str_replace($picture[0], '', $body);
184 $image = str_replace('-1.', '-0.', $picture[2]);
185 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
186 'preview' => $picture[2], 'description' => $picture[3]];
190 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
191 foreach ($pictures as $picture) {
192 $body = str_replace($picture[0], '', $body);
193 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
197 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
198 foreach ($pictures as $picture) {
199 if (!self::isPictureLink($picture[1], $picture[2])) {
202 $body = str_replace($picture[0], '', $body);
203 $image = str_replace('-1.', '-0.', $picture[2]);
204 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
205 'preview' => $picture[2], 'description' => null];
209 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
210 foreach ($pictures as $picture) {
211 $body = str_replace($picture[0], '', $body);
212 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
216 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]/ism", $body, $audios, PREG_SET_ORDER)) {
217 foreach ($audios as $audio) {
218 $body = str_replace($audio[0], '', $body);
219 $attachments[] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
223 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]/ism", $body, $videos, PREG_SET_ORDER)) {
224 foreach ($videos as $video) {
225 $body = str_replace($video[0], '', $body);
226 $attachments[] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
230 foreach ($attachments as $attachment) {
231 self::insert($attachment);
238 * Add media links from the attach field
240 * @param integer $uriid
241 * @param string $attach
244 public static function insertFromAttachment(int $uriid, string $attach)
246 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
250 foreach ($matches as $attachment) {
251 $media['type'] = self::DOCUMENT;
252 $media['uri-id'] = $uriid;
253 $media['url'] = $attachment[1];
254 $media['size'] = $attachment[2];
255 $media['mimetype'] = $attachment[3];
256 $media['description'] = $attachment[4] ?? '';
258 self::insert($media);
263 * Retrieves the media attachments associated with the provided item ID.
269 public static function getByURIId(int $uri_id)
271 return DBA::selectToArray('post-media', [], ['uri-id' => $uri_id]);