]> git.mxchange.org Git - friendica.git/blob - src/Model/Post/Media.php
554cc6c4cc54d5bf64492dc45acf8035a8f144d4
[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('Norhing to update', ['media' => $media]);
86                 }
87         }
88
89         /**
90          * Creates the "[attach]" element from the given attributes
91          *
92          * @param string $href
93          * @param integer $length
94          * @param string $type
95          * @param string $title
96          * @return string "[attach]" element
97          */
98         public static function getAttachElement(string $href, int $length, string $type, string $title = '')
99         {
100                 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
101                         'size' => $length, 'mimetype' => $type, 'description' => $title]);
102
103                 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
104                         '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
105         }
106
107         /**
108          * Fetch additional data for the provided media array
109          *
110          * @param array $media
111          * @return array media array with additional data
112          */
113         public static function fetchAdditionalData(array $media)
114         {
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'];
125                                 }
126                                 if (empty($media['size']) && !empty($header['content-length'])) {
127                                         $media['size'] = $header['content-length'];
128                                 }
129                         }
130                 }
131
132                 $filetype = !empty($media['mimetype']) ? strtolower(substr($media['mimetype'], 0, strpos($media['mimetype'], '/'))) : '';
133
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];
141                         }
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];
147                                 }
148                         }
149                 }
150                 return $media;
151         }
152
153         /**
154          * Tests for path patterns that are usef for picture links in Friendica
155          *
156          * @param string $page    Link to the image page
157          * @param string $preview Preview picture
158          * @return boolean
159          */
160         private static function isPictureLink(string $page, string $preview)
161         {
162                 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
163         }
164
165         /**
166          * Add media links and remove them from the body
167          *
168          * @param integer $uriid
169          * @param string $body
170          * @return string Body without media links
171          */
172         public static function insertFromBody(int $uriid, string $body)
173         {
174                 // Simplify image codes
175                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
176
177                 $attachments = [];
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])) {
181                                         continue;
182                                 }
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]];
187                         }
188                 }
189
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]];
194                         }
195                 }
196
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])) {
200                                         continue;
201                                 }
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];
206                         }
207                 }
208
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]];
213                         }
214                 }
215
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]];
220                         }
221                 }
222
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]];
227                         }
228                 }
229
230                 foreach ($attachments as $attachment) {
231                         self::insert($attachment);
232                 }
233
234                 return trim($body);
235         }
236
237         /**
238          * Add media links from the attach field
239          *
240          * @param integer $uriid
241          * @param string $attach
242          * @return void
243          */
244         public static function insertFromAttachment(int $uriid, string $attach)
245         {
246                 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
247                         return;
248                 }
249
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] ?? '';
257
258                         self::insert($media);
259                 }
260         }
261 }