]> git.mxchange.org Git - friendica.git/blob - src/Model/Post/Media.php
Merge pull request #10119 from tobiasd/2021.03-CHANGELOG
[friendica.git] / src / Model / Post / Media.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Model\Post;
23
24 use Friendica\Core\Logger;
25 use Friendica\Core\System;
26 use Friendica\Database\Database;
27 use Friendica\Database\DBA;
28 use Friendica\DI;
29 use Friendica\Util\Images;
30
31 /**
32  * Class Media
33  *
34  * This Model class handles media interactions.
35  * This tables stores medias (images, videos, audio files) related to posts.
36  */
37 class Media
38 {
39         const UNKNOWN     = 0;
40         const IMAGE       = 1;
41         const VIDEO       = 2;
42         const AUDIO       = 3;
43         const TEXT        = 4;
44         const APPLICATION = 5;
45         const TORRENT     = 16;
46         const HTML        = 17;
47         const XML         = 18;
48         const PLAIN       = 19;
49         const DOCUMENT    = 128;
50
51         /**
52          * Insert a post-media record
53          *
54          * @param array $media
55          * @return void
56          */
57         public static function insert(array $media, bool $force = false)
58         {
59                 if (empty($media['url']) || empty($media['uri-id']) || !isset($media['type'])) {
60                         Logger::warning('Incomplete media data', ['media' => $media]);
61                         return;
62                 }
63
64                 // "document" has got the lowest priority. So when the same file is both attached as document
65                 // and embedded as picture then we only store the picture or replace the document 
66                 $found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
67                 if (!$force && !empty($found) && (($found['type'] != self::DOCUMENT) || ($media['type'] == self::DOCUMENT))) {
68                         Logger::info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
69                         return;
70                 }
71
72                 $media = self::unsetEmptyFields($media);
73
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()]);
78                 $stored = $media;
79
80                 $media = self::fetchAdditionalData($media);
81                 $media = self::unsetEmptyFields($media);
82
83                 if (array_diff_assoc($media, $stored)) {
84                         $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
85                         Logger::info('Updated media', ['result' => $result, 'media' => $media]);
86                 } else {
87                         Logger::info('Nothing to update', ['media' => $media]);
88                 }
89         }
90
91         /**
92          * Remove empty media fields
93          *
94          * @param array $media
95          * @return array cleaned media array
96          */
97         private static function unsetEmptyFields(array $media)
98         {
99                 $fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'description'];
100                 foreach ($fields as $field) {
101                         if (empty($media[$field])) {
102                                 unset($media[$field]);
103                         }
104                 }
105                 return $media;
106         }
107
108         /**
109          * Copy attachments from one uri-id to another
110          *
111          * @param integer $from_uri_id
112          * @param integer $to_uri_id
113          * @return void
114          */
115         public static function copy(int $from_uri_id, int $to_uri_id)
116         {
117                 $attachments = self::getByURIId($from_uri_id);
118                 foreach ($attachments as $attachment) {
119                         $attachment['uri-id'] = $to_uri_id;
120                         self::insert($attachment);
121                 }
122         }
123
124         /**
125          * Creates the "[attach]" element from the given attributes
126          *
127          * @param string $href
128          * @param integer $length
129          * @param string $type
130          * @param string $title
131          * @return string "[attach]" element
132          */
133         public static function getAttachElement(string $href, int $length, string $type, string $title = '')
134         {
135                 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
136                         'size' => $length, 'mimetype' => $type, 'description' => $title]);
137
138                 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
139                         '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
140         }
141
142         /**
143          * Fetch additional data for the provided media array
144          *
145          * @param array $media
146          * @return array media array with additional data
147          */
148         public static function fetchAdditionalData(array $media)
149         {
150                 // Fetch the mimetype or size if missing.
151                 if (empty($media['mimetype']) || empty($media['size'])) {
152                         $timeout = DI::config()->get('system', 'xrd_timeout');
153                         $curlResult = DI::httpRequest()->head($media['url'], ['timeout' => $timeout]);
154                         if ($curlResult->isSuccess()) {
155                                 if (empty($media['mimetype'])) {
156                                         $media['mimetype'] = $curlResult->getHeader('Content-Type');
157                                 }
158                                 if (empty($media['size'])) {
159                                         $media['size'] = (int)$curlResult->getHeader('Content-Length');
160                                 }
161                         } else {
162                                 Logger::notice('Could not fetch head', ['media' => $media]);
163                         }
164                 }
165
166                 $filetype = !empty($media['mimetype']) ? strtolower(current(explode('/', $media['mimetype']))) : '';
167
168                 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
169                         $imagedata = Images::getInfoFromURLCached($media['url']);
170                         if (!empty($imagedata)) {
171                                 $media['mimetype'] = $imagedata['mime'];
172                                 $media['size'] = $imagedata['size'];
173                                 $media['width'] = $imagedata[0];
174                                 $media['height'] = $imagedata[1];
175                         } else {
176                                 Logger::notice('No image data', ['media' => $media]);
177                         }
178                         if (!empty($media['preview'])) {
179                                 $imagedata = Images::getInfoFromURLCached($media['preview']);
180                                 if (!empty($imagedata)) {
181                                         $media['preview-width'] = $imagedata[0];
182                                         $media['preview-height'] = $imagedata[1];
183                                 }
184                         }
185                 }
186
187                 if ($media['type'] != self::DOCUMENT) {
188                         $media = self::addType($media);
189                 }
190
191                 return $media;
192         }
193
194         /**
195          * Add the detected type to the media array
196          *
197          * @param array $data 
198          * @return array data array with the detected type
199          */
200         public static function addType(array $data)
201         {
202                 if (empty($data['mimetype'])) {
203                         Logger::info('No MimeType provided', ['media' => $data]);
204                         return $data;
205                 }
206
207                 $type = explode('/', current(explode(';', $data['mimetype'])));
208                 if (count($type) < 2) {
209                         Logger::info('Unknown MimeType', ['type' => $type, 'media' => $data]);
210                         $data['type'] = self::UNKNOWN;
211                         return $data;
212                 }
213
214                 $filetype = strtolower($type[0]);
215                 $subtype = strtolower($type[1]);
216
217                 if ($filetype == 'image') {
218                         $data['type'] = self::IMAGE;
219                 } elseif ($filetype == 'video') {
220                         $data['type'] = self::VIDEO;
221                 } elseif ($filetype == 'audio') {
222                         $data['type'] = self::AUDIO;
223                 } elseif (($filetype == 'text') && ($subtype == 'html')) {
224                         $data['type'] = self::HTML;
225                 } elseif (($filetype == 'text') && ($subtype == 'xml')) {
226                         $data['type'] = self::XML;
227                 } elseif (($filetype == 'text') && ($subtype == 'plain')) {
228                         $data['type'] = self::PLAIN;
229                 } elseif ($filetype == 'text') {
230                         $data['type'] = self::TEXT;
231                 } elseif (($filetype == 'application') && ($subtype == 'x-bittorrent')) {
232                         $data['type'] = self::TORRENT;
233                 } elseif ($filetype == 'application') {
234                         $data['type'] = self::APPLICATION;
235                 } else {
236                         $data['type'] = self::UNKNOWN;
237                         Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
238                         return $data;
239                 }
240
241                 Logger::debug('Detected type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
242                 return $data;
243         }
244
245         /**
246          * Tests for path patterns that are usef for picture links in Friendica
247          *
248          * @param string $page    Link to the image page
249          * @param string $preview Preview picture
250          * @return boolean
251          */
252         private static function isPictureLink(string $page, string $preview)
253         {
254                 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
255         }
256
257         /**
258          * Add media links and remove them from the body
259          *
260          * @param integer $uriid
261          * @param string $body
262          * @return string Body without media links
263          */
264         public static function insertFromBody(int $uriid, string $body)
265         {
266                 // Simplify image codes
267                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
268
269                 $attachments = [];
270                 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
271                         foreach ($pictures as $picture) {
272                                 if (!self::isPictureLink($picture[1], $picture[2])) {
273                                         continue;
274                                 }
275                                 $body = str_replace($picture[0], '', $body);
276                                 $image = str_replace('-1.', '-0.', $picture[2]);
277                                 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
278                                         'preview' => $picture[2], 'description' => $picture[3]];
279                         }
280                 }
281
282                 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
283                         foreach ($pictures as $picture) {
284                                 $body = str_replace($picture[0], '', $body);
285                                 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
286                         }
287                 }
288
289                 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
290                         foreach ($pictures as $picture) {
291                                 if (!self::isPictureLink($picture[1], $picture[2])) {
292                                         continue;
293                                 }
294                                 $body = str_replace($picture[0], '', $body);
295                                 $image = str_replace('-1.', '-0.', $picture[2]);
296                                 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
297                                         'preview' => $picture[2], 'description' => null];
298                         }
299                 }
300
301                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
302                         foreach ($pictures as $picture) {
303                                 $body = str_replace($picture[0], '', $body);
304                                 $attachments[] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
305                         }
306                 }
307
308                 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]/ism", $body, $audios, PREG_SET_ORDER)) {
309                         foreach ($audios as $audio) {
310                                 $body = str_replace($audio[0], '', $body);
311                                 $attachments[] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
312                         }
313                 }
314
315                 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]/ism", $body, $videos, PREG_SET_ORDER)) {
316                         foreach ($videos as $video) {
317                                 $body = str_replace($video[0], '', $body);
318                                 $attachments[] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
319                         }
320                 }
321
322                 foreach ($attachments as $attachment) {
323                         self::insert($attachment);
324                 }
325
326                 return trim($body);
327         }
328
329         /**
330          * Add media links from the attach field
331          *
332          * @param integer $uriid
333          * @param string $attach
334          * @return void
335          */
336         public static function insertFromAttachment(int $uriid, string $attach)
337         {
338                 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
339                         return;
340                 }
341
342                 foreach ($matches as $attachment) {
343                         $media['type'] = self::DOCUMENT;
344                         $media['uri-id'] = $uriid;
345                         $media['url'] = $attachment[1];
346                         $media['size'] = $attachment[2];
347                         $media['mimetype'] = $attachment[3];
348                         $media['description'] = $attachment[4] ?? '';
349
350                         self::insert($media);
351                 }
352         }
353
354         /**
355          * Retrieves the media attachments associated with the provided item ID.
356          *
357          * @param int $uri_id
358          * @param array $types
359          * @return array
360          * @throws \Exception
361          */
362         public static function getByURIId(int $uri_id, array $types = [])
363         {
364                 $condition = ['uri-id' => $uri_id];
365
366                 if (!empty($types)) {
367                         $condition = DBA::mergeConditions($condition, ['type' => $types]);
368                 }
369
370                 return DBA::selectToArray('post-media', [], $condition);
371         }
372 }