]> git.mxchange.org Git - friendica.git/blob - src/Model/Post/Media.php
441fd52767d06d5a01fb1ed6a76350c7316e0b30
[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\DBA;
27 use Friendica\DI;
28 use Friendica\Util\Images;
29
30 /**
31  * Class Media
32  *
33  * This Model class handles media interactions.
34  * This tables stores medias (images, videos, audio files) related to posts.
35  */
36 class Media
37 {
38         const UNKNOWN  = 0;
39         const IMAGE    = 1;
40         const VIDEO    = 2;
41         const AUDIO    = 3;
42         const TORRENT  = 16;
43         const DOCUMENT = 128;
44
45         /**
46          * Insert a post-media record
47          *
48          * @param array $media
49          * @return void
50          */
51         public static function insert(array $media, bool $force = false)
52         {
53                 if (empty($media['url']) || empty($media['uri-id']) || empty($media['type'])) {
54                         Logger::warning('Incomplete media data', ['media' => $media]);
55                         return;
56                 }
57
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()]);
63                         return;
64                 }
65
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]);
70                         }
71                 }
72
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()]);
77                 $stored = $media;
78
79                 $media = self::fetchAdditionalData($media);
80
81                 if (array_diff_assoc($media, $stored)) {
82                         $result = DBA::insert('post-media', $media, true);
83                         Logger::info('Updated media', ['result' => $result, 'media' => $media]);
84                 } else {
85                         Logger::info('Nothing to update', ['media' => $media]);
86                 }
87         }
88
89         /**
90          * Copy attachments from one uri-id to another
91          *
92          * @param integer $from_uri_id
93          * @param integer $to_uri_id
94          * @return void
95          */
96         public static function copy(int $from_uri_id, int $to_uri_id)
97         {
98                 $attachments = self::getByURIId($from_uri_id);
99                 foreach ($attachments as $attachment) {
100                         $attachment['uri-id'] = $to_uri_id;
101                         self::insert($attachment);
102                 }
103         }
104
105         /**
106          * Creates the "[attach]" element from the given attributes
107          *
108          * @param string $href
109          * @param integer $length
110          * @param string $type
111          * @param string $title
112          * @return string "[attach]" element
113          */
114         public static function getAttachElement(string $href, int $length, string $type, string $title = '')
115         {
116                 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
117                         'size' => $length, 'mimetype' => $type, 'description' => $title]);
118
119                 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
120                         '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
121         }
122
123         /**
124          * Fetch additional data for the provided media array
125          *
126          * @param array $media
127          * @return array media array with additional data
128          */
129         public static function fetchAdditionalData(array $media)
130         {
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'];
141                                 }
142                                 if (empty($media['size']) && !empty($header['content-length'])) {
143                                         $media['size'] = $header['content-length'];
144                                 }
145                         }
146                 }
147
148                 $filetype = !empty($media['mimetype']) ? strtolower(substr($media['mimetype'], 0, strpos($media['mimetype'], '/'))) : '';
149
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];
157                         }
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];
163                                 }
164                         }
165                 }
166                 return $media;
167         }
168
169         /**
170          * Tests for path patterns that are usef for picture links in Friendica
171          *
172          * @param string $page    Link to the image page
173          * @param string $preview Preview picture
174          * @return boolean
175          */
176         private static function isPictureLink(string $page, string $preview)
177         {
178                 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
179         }
180
181         /**
182          * Add media links and remove them from the body
183          *
184          * @param integer $uriid
185          * @param string $body
186          * @return string Body without media links
187          */
188         public static function insertFromBody(int $uriid, string $body)
189         {
190                 // Simplify image codes
191                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
192
193                 $attachments = [];
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])) {
197                                         continue;
198                                 }
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]];
203                         }
204                 }
205
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]];
210                         }
211                 }
212
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])) {
216                                         continue;
217                                 }
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];
222                         }
223                 }
224
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]];
229                         }
230                 }
231
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]];
236                         }
237                 }
238
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]];
243                         }
244                 }
245
246                 foreach ($attachments as $attachment) {
247                         self::insert($attachment);
248                 }
249
250                 return trim($body);
251         }
252
253         /**
254          * Add media links from the attach field
255          *
256          * @param integer $uriid
257          * @param string $attach
258          * @return void
259          */
260         public static function insertFromAttachment(int $uriid, string $attach)
261         {
262                 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
263                         return;
264                 }
265
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] ?? '';
273
274                         self::insert($media);
275                 }
276         }
277
278         /**
279          * Retrieves the media attachments associated with the provided item ID.
280          *
281          * @param int $uri_id
282          * @param array $types
283          * @return array
284          * @throws \Exception
285          */
286         public static function getByURIId(int $uri_id, array $types = [])
287         {
288                 $condition = ['uri-id' => $uri_id];
289
290                 if (!empty($types)) {
291                         $condition = DBA::mergeConditions($condition, ['type' => $types]);
292                 }
293
294                 return DBA::selectToArray('post-media', [], $condition);
295         }
296 }