]> git.mxchange.org Git - friendica.git/blob - src/Model/Post/Media.php
Merge pull request #9553 from annando/insert-mode
[friendica.git] / src / Model / Post / Media.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
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 TORRENT  = 16;
44         const DOCUMENT = 128;
45
46         /**
47          * Insert a post-media record
48          *
49          * @param array $media
50          * @return void
51          */
52         public static function insert(array $media, bool $force = false)
53         {
54                 if (empty($media['url']) || empty($media['uri-id']) || empty($media['type'])) {
55                         Logger::warning('Incomplete media data', ['media' => $media]);
56                         return;
57                 }
58
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()]);
64                         return;
65                 }
66
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]);
71                         }
72                 }
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
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]);
85                 } else {
86                         Logger::info('Nothing to update', ['media' => $media]);
87                 }
88         }
89
90         /**
91          * Copy attachments from one uri-id to another
92          *
93          * @param integer $from_uri_id
94          * @param integer $to_uri_id
95          * @return void
96          */
97         public static function copy(int $from_uri_id, int $to_uri_id)
98         {
99                 $attachments = self::getByURIId($from_uri_id);
100                 foreach ($attachments as $attachment) {
101                         $attachment['uri-id'] = $to_uri_id;
102                         self::insert($attachment);
103                 }
104         }
105
106         /**
107          * Creates the "[attach]" element from the given attributes
108          *
109          * @param string $href
110          * @param integer $length
111          * @param string $type
112          * @param string $title
113          * @return string "[attach]" element
114          */
115         public static function getAttachElement(string $href, int $length, string $type, string $title = '')
116         {
117                 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
118                         'size' => $length, 'mimetype' => $type, 'description' => $title]);
119
120                 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
121                         '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
122         }
123
124         /**
125          * Fetch additional data for the provided media array
126          *
127          * @param array $media
128          * @return array media array with additional data
129          */
130         public static function fetchAdditionalData(array $media)
131         {
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'];
142                                 }
143                                 if (empty($media['size']) && !empty($header['content-length'])) {
144                                         $media['size'] = $header['content-length'];
145                                 }
146                         }
147                 }
148
149                 $filetype = !empty($media['mimetype']) ? strtolower(substr($media['mimetype'], 0, strpos($media['mimetype'], '/'))) : '';
150
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];
158                         }
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];
164                                 }
165                         }
166                 }
167                 return $media;
168         }
169
170         /**
171          * Tests for path patterns that are usef for picture links in Friendica
172          *
173          * @param string $page    Link to the image page
174          * @param string $preview Preview picture
175          * @return boolean
176          */
177         private static function isPictureLink(string $page, string $preview)
178         {
179                 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
180         }
181
182         /**
183          * Add media links and remove them from the body
184          *
185          * @param integer $uriid
186          * @param string $body
187          * @return string Body without media links
188          */
189         public static function insertFromBody(int $uriid, string $body)
190         {
191                 // Simplify image codes
192                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
193
194                 $attachments = [];
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])) {
198                                         continue;
199                                 }
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]];
204                         }
205                 }
206
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]];
211                         }
212                 }
213
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])) {
217                                         continue;
218                                 }
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];
223                         }
224                 }
225
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]];
230                         }
231                 }
232
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]];
237                         }
238                 }
239
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]];
244                         }
245                 }
246
247                 foreach ($attachments as $attachment) {
248                         self::insert($attachment);
249                 }
250
251                 return trim($body);
252         }
253
254         /**
255          * Add media links from the attach field
256          *
257          * @param integer $uriid
258          * @param string $attach
259          * @return void
260          */
261         public static function insertFromAttachment(int $uriid, string $attach)
262         {
263                 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
264                         return;
265                 }
266
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] ?? '';
274
275                         self::insert($media);
276                 }
277         }
278
279         /**
280          * Retrieves the media attachments associated with the provided item ID.
281          *
282          * @param int $uri_id
283          * @param array $types
284          * @return array
285          * @throws \Exception
286          */
287         public static function getByURIId(int $uri_id, array $types = [])
288         {
289                 $condition = ['uri-id' => $uri_id];
290
291                 if (!empty($types)) {
292                         $condition = DBA::mergeConditions($condition, ['type' => $types]);
293                 }
294
295                 return DBA::selectToArray('post-media', [], $condition);
296         }
297 }