]> git.mxchange.org Git - friendica.git/blob - src/Model/Post/Media.php
Avoid empty posts on Diaspora
[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\Content\PageInfo;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Core\Logger;
27 use Friendica\Core\System;
28 use Friendica\Database\Database;
29 use Friendica\Database\DBA;
30 use Friendica\DI;
31 use Friendica\Model\Item;
32 use Friendica\Model\Post;
33 use Friendica\Util\Images;
34 use Friendica\Util\ParseUrl;
35 use Friendica\Util\Strings;
36
37 /**
38  * Class Media
39  *
40  * This Model class handles media interactions.
41  * This tables stores medias (images, videos, audio files) related to posts.
42  */
43 class Media
44 {
45         const UNKNOWN     = 0;
46         const IMAGE       = 1;
47         const VIDEO       = 2;
48         const AUDIO       = 3;
49         const TEXT        = 4;
50         const APPLICATION = 5;
51         const TORRENT     = 16;
52         const HTML        = 17;
53         const XML         = 18;
54         const PLAIN       = 19;
55         const DOCUMENT    = 128;
56
57         /**
58          * Insert a post-media record
59          *
60          * @param array $media
61          * @return void
62          */
63         public static function insert(array $media, bool $force = false)
64         {
65                 if (empty($media['url']) || empty($media['uri-id']) || !isset($media['type'])) {
66                         Logger::warning('Incomplete media data', ['media' => $media]);
67                         return;
68                 }
69
70                 // "document" has got the lowest priority. So when the same file is both attached as document
71                 // and embedded as picture then we only store the picture or replace the document
72                 $found = DBA::selectFirst('post-media', ['type'], ['uri-id' => $media['uri-id'], 'url' => $media['url']]);
73                 if (!$force && !empty($found) && (($found['type'] != self::DOCUMENT) || ($media['type'] == self::DOCUMENT))) {
74                         Logger::info('Media already exists', ['uri-id' => $media['uri-id'], 'url' => $media['url'], 'callstack' => System::callstack()]);
75                         return;
76                 }
77
78                 $media = self::unsetEmptyFields($media);
79
80                 // We are storing as fast as possible to avoid duplicated network requests
81                 // when fetching additional information for pictures and other content.
82                 $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
83                 Logger::info('Stored media', ['result' => $result, 'media' => $media, 'callstack' => System::callstack()]);
84                 $stored = $media;
85
86                 $media = self::fetchAdditionalData($media);
87                 $media = self::unsetEmptyFields($media);
88
89                 if (array_diff_assoc($media, $stored)) {
90                         $result = DBA::insert('post-media', $media, Database::INSERT_UPDATE);
91                         Logger::info('Updated media', ['result' => $result, 'media' => $media]);
92                 } else {
93                         Logger::info('Nothing to update', ['media' => $media]);
94                 }
95         }
96
97         /**
98          * Remove empty media fields
99          *
100          * @param array $media
101          * @return array cleaned media array
102          */
103         private static function unsetEmptyFields(array $media)
104         {
105                 $fields = ['mimetype', 'height', 'width', 'size', 'preview', 'preview-height', 'preview-width', 'description'];
106                 foreach ($fields as $field) {
107                         if (empty($media[$field])) {
108                                 unset($media[$field]);
109                         }
110                 }
111                 return $media;
112         }
113
114         /**
115          * Copy attachments from one uri-id to another
116          *
117          * @param integer $from_uri_id
118          * @param integer $to_uri_id
119          * @return void
120          */
121         public static function copy(int $from_uri_id, int $to_uri_id)
122         {
123                 $attachments = self::getByURIId($from_uri_id);
124                 foreach ($attachments as $attachment) {
125                         $attachment['uri-id'] = $to_uri_id;
126                         self::insert($attachment);
127                 }
128         }
129
130         /**
131          * Creates the "[attach]" element from the given attributes
132          *
133          * @param string $href
134          * @param integer $length
135          * @param string $type
136          * @param string $title
137          * @return string "[attach]" element
138          */
139         public static function getAttachElement(string $href, int $length, string $type, string $title = '')
140         {
141                 $media = self::fetchAdditionalData(['type' => self::DOCUMENT, 'url' => $href,
142                         'size' => $length, 'mimetype' => $type, 'description' => $title]);
143
144                 return '[attach]href="' . $media['url'] . '" length="' . $media['size'] .
145                         '" type="' . $media['mimetype'] . '" title="' . $media['description'] . '"[/attach]';
146         }
147
148         /**
149          * Fetch additional data for the provided media array
150          *
151          * @param array $media
152          * @return array media array with additional data
153          */
154         public static function fetchAdditionalData(array $media)
155         {
156                 // Fetch the mimetype or size if missing.
157                 if (empty($media['mimetype']) || empty($media['size'])) {
158                         $timeout = DI::config()->get('system', 'xrd_timeout');
159                         $curlResult = DI::httpRequest()->head($media['url'], ['timeout' => $timeout]);
160                         if ($curlResult->isSuccess()) {
161                                 if (empty($media['mimetype'])) {
162                                         $media['mimetype'] = $curlResult->getHeader('Content-Type');
163                                 }
164                                 if (empty($media['size'])) {
165                                         $media['size'] = (int)$curlResult->getHeader('Content-Length');
166                                 }
167                         } else {
168                                 Logger::notice('Could not fetch head', ['media' => $media]);
169                         }
170                 }
171
172                 $filetype = !empty($media['mimetype']) ? strtolower(current(explode('/', $media['mimetype']))) : '';
173
174                 if (($media['type'] == self::IMAGE) || ($filetype == 'image')) {
175                         $imagedata = Images::getInfoFromURLCached($media['url']);
176                         if (!empty($imagedata)) {
177                                 $media['mimetype'] = $imagedata['mime'];
178                                 $media['size'] = $imagedata['size'];
179                                 $media['width'] = $imagedata[0];
180                                 $media['height'] = $imagedata[1];
181                         } else {
182                                 Logger::notice('No image data', ['media' => $media]);
183                         }
184                         if (!empty($media['preview'])) {
185                                 $imagedata = Images::getInfoFromURLCached($media['preview']);
186                                 if (!empty($imagedata)) {
187                                         $media['preview-width'] = $imagedata[0];
188                                         $media['preview-height'] = $imagedata[1];
189                                 }
190                         }
191                 }
192
193                 if ($media['type'] != self::DOCUMENT) {
194                         $media = self::addType($media);
195                 }
196
197                 if ($media['type'] == self::HTML) {
198                         $data = ParseUrl::getSiteinfoCached($media['url'], false);
199                         $media['preview'] = $data['images'][0]['src'] ?? null;
200                         $media['preview-height'] = $data['images'][0]['height'] ?? null;
201                         $media['preview-width'] = $data['images'][0]['width'] ?? null;
202                         $media['description'] = $data['text'] ?? null;
203                         $media['name'] = $data['title'] ?? null;
204                         $media['author-url'] = $data['author_url'] ?? null;
205                         $media['author-name'] = $data['author_name'] ?? null;
206                         $media['author-image'] = $data['author_img'] ?? null;
207                         $media['publisher-url'] = $data['publisher_url'] ?? null;
208                         $media['publisher-name'] = $data['publisher_name'] ?? null;
209                         $media['publisher-image'] = $data['publisher_img'] ?? null;
210                 }
211                 return $media;
212         }
213
214         /**
215          * Add the detected type to the media array
216          *
217          * @param array $data
218          * @return array data array with the detected type
219          */
220         public static function addType(array $data)
221         {
222                 if (empty($data['mimetype'])) {
223                         Logger::info('No MimeType provided', ['media' => $data]);
224                         return $data;
225                 }
226
227                 $type = explode('/', current(explode(';', $data['mimetype'])));
228                 if (count($type) < 2) {
229                         Logger::info('Unknown MimeType', ['type' => $type, 'media' => $data]);
230                         $data['type'] = self::UNKNOWN;
231                         return $data;
232                 }
233
234                 $filetype = strtolower($type[0]);
235                 $subtype = strtolower($type[1]);
236
237                 if ($filetype == 'image') {
238                         $data['type'] = self::IMAGE;
239                 } elseif ($filetype == 'video') {
240                         $data['type'] = self::VIDEO;
241                 } elseif ($filetype == 'audio') {
242                         $data['type'] = self::AUDIO;
243                 } elseif (($filetype == 'text') && ($subtype == 'html')) {
244                         $data['type'] = self::HTML;
245                 } elseif (($filetype == 'text') && ($subtype == 'xml')) {
246                         $data['type'] = self::XML;
247                 } elseif (($filetype == 'text') && ($subtype == 'plain')) {
248                         $data['type'] = self::PLAIN;
249                 } elseif ($filetype == 'text') {
250                         $data['type'] = self::TEXT;
251                 } elseif (($filetype == 'application') && ($subtype == 'x-bittorrent')) {
252                         $data['type'] = self::TORRENT;
253                 } elseif ($filetype == 'application') {
254                         $data['type'] = self::APPLICATION;
255                 } else {
256                         $data['type'] = self::UNKNOWN;
257                         Logger::info('Unknown type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
258                         return $data;
259                 }
260
261                 Logger::debug('Detected type', ['filetype' => $filetype, 'subtype' => $subtype, 'media' => $data]);
262                 return $data;
263         }
264
265         /**
266          * Tests for path patterns that are usef for picture links in Friendica
267          *
268          * @param string $page    Link to the image page
269          * @param string $preview Preview picture
270          * @return boolean
271          */
272         private static function isPictureLink(string $page, string $preview)
273         {
274                 return preg_match('#/photos/.*/image/#ism', $page) && preg_match('#/photo/.*-1\.#ism', $preview);
275         }
276
277         /**
278          * Add media links and remove them from the body
279          *
280          * @param integer $uriid
281          * @param string $body
282          * @return string Body without media links
283          */
284         public static function insertFromBody(int $uriid, string $body)
285         {
286                 // Simplify image codes
287                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
288
289                 $attachments = [];
290                 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
291                         foreach ($pictures as $picture) {
292                                 if (!self::isPictureLink($picture[1], $picture[2])) {
293                                         continue;
294                                 }
295                                 $body = str_replace($picture[0], '', $body);
296                                 $image = str_replace('-1.', '-0.', $picture[2]);
297                                 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
298                                         'preview' => $picture[2], 'description' => $picture[3]];
299                         }
300                 }
301
302                 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
303                         foreach ($pictures as $picture) {
304                                 $body = str_replace($picture[0], '', $body);
305                                 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1], 'description' => $picture[2]];
306                         }
307                 }
308
309                 if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $body, $pictures, PREG_SET_ORDER)) {
310                         foreach ($pictures as $picture) {
311                                 if (!self::isPictureLink($picture[1], $picture[2])) {
312                                         continue;
313                                 }
314                                 $body = str_replace($picture[0], '', $body);
315                                 $image = str_replace('-1.', '-0.', $picture[2]);
316                                 $attachments[$image] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $image,
317                                         'preview' => $picture[2], 'description' => null];
318                         }
319                 }
320
321                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/ism", $body, $pictures, PREG_SET_ORDER)) {
322                         foreach ($pictures as $picture) {
323                                 $body = str_replace($picture[0], '', $body);
324                                 $attachments[$picture[1]] = ['uri-id' => $uriid, 'type' => self::IMAGE, 'url' => $picture[1]];
325                         }
326                 }
327
328                 if (preg_match_all("/\[audio\]([^\[\]]*)\[\/audio\]/ism", $body, $audios, PREG_SET_ORDER)) {
329                         foreach ($audios as $audio) {
330                                 $body = str_replace($audio[0], '', $body);
331                                 $attachments[$audio[1]] = ['uri-id' => $uriid, 'type' => self::AUDIO, 'url' => $audio[1]];
332                         }
333                 }
334
335                 if (preg_match_all("/\[video\]([^\[\]]*)\[\/video\]/ism", $body, $videos, PREG_SET_ORDER)) {
336                         foreach ($videos as $video) {
337                                 $body = str_replace($video[0], '', $body);
338                                 $attachments[$video[1]] = ['uri-id' => $uriid, 'type' => self::VIDEO, 'url' => $video[1]];
339                         }
340                 }
341
342                 $url = PageInfo::getRelevantUrlFromBody($body);
343                 if (!empty($url)) {
344                         Logger::debug('Got page url', ['url' => $url]);
345                         $attachments[$url] = ['uri-id' => $uriid, 'type' => self::UNKNOWN, 'url' => $url];
346                 }
347
348                 foreach ($attachments as $attachment) {
349                         self::insert($attachment);
350                 }
351
352                 return trim($body);
353         }
354
355         /**
356          * Add media links from the attachment field
357          *
358          * @param integer $uriid
359          * @param string $body
360          */
361         public static function insertFromAttachmentData(int $uriid, string $body)
362         {
363                 $data = BBCode::getAttachmentData($body);
364                 if (empty($data))  {
365                         return;
366                 }
367
368                 Logger::info('Adding attachment data', ['data' => $data]);
369                 $attachment = [
370                         'uri-id' => $uriid,
371                         'type' => self::HTML,
372                         'url' => $data['url'],
373                         'preview' => $data['preview'] ?? null,
374                         'description' => $data['description'] ?? null,
375                         'name' => $data['title'] ?? null,
376                         'author-url' => $data['author_url'] ?? null,
377                         'author-name' => $data['author_name'] ?? null,
378                         'publisher-url' => $data['provider_url'] ?? null,
379                         'publisher-name' => $data['provider_name'] ?? null,
380                 ];
381                 if (!empty($data['image'])) {
382                         $attachment['preview'] = $data['image'];
383                 }
384                 self::insert($attachment);
385         }
386
387         /**
388          * Add media links from the attach field
389          *
390          * @param integer $uriid
391          * @param string $attach
392          * @return void
393          */
394         public static function insertFromAttachment(int $uriid, string $attach)
395         {
396                 if (!preg_match_all('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\"(?: title=\"(.*?)\")?|', $attach, $matches, PREG_SET_ORDER)) {
397                         return;
398                 }
399
400                 foreach ($matches as $attachment) {
401                         $media['type'] = self::DOCUMENT;
402                         $media['uri-id'] = $uriid;
403                         $media['url'] = $attachment[1];
404                         $media['size'] = $attachment[2];
405                         $media['mimetype'] = $attachment[3];
406                         $media['description'] = $attachment[4] ?? '';
407
408                         self::insert($media);
409                 }
410         }
411
412         /**
413          * Retrieves the media attachments associated with the provided item ID.
414          *
415          * @param int $uri_id
416          * @param array $types
417          * @return array
418          * @throws \Exception
419          */
420         public static function getByURIId(int $uri_id, array $types = [])
421         {
422                 $condition = ['uri-id' => $uri_id];
423
424                 if (!empty($types)) {
425                         $condition = DBA::mergeConditions($condition, ['type' => $types]);
426                 }
427
428                 return DBA::selectToArray('post-media', [], $condition);
429         }
430
431         /**
432          * Checks if media attachments are associated with the provided item ID.
433          *
434          * @param int $uri_id
435          * @param array $types
436          * @return array
437          * @throws \Exception
438          */
439         public static function existsByURIId(int $uri_id, array $types = [])
440         {
441                 $condition = ['uri-id' => $uri_id];
442
443                 if (!empty($types)) {
444                         $condition = DBA::mergeConditions($condition, ['type' => $types]);
445                 }
446
447                 return DBA::exists('post-media', $condition);
448         }
449
450         /**
451          * Split the attachment media in the three segments "visual", "link" and "additional"
452          * 
453          * @param int    $uri_id 
454          * @param string $guid
455          * @param array  $links ist of links that shouldn't be added 
456          * @return array attachments
457          */
458         public static function splitAttachments(int $uri_id, string $guid = '', array $links = [])
459         {
460                 $attachments = ['visual' => [], 'link' => [], 'additional' => []];
461
462                 $media = self::getByURIId($uri_id);
463                 if (empty($media)) {
464                         return $attachments;
465                 }
466
467                 $height = 0;
468                 $selected = '';
469
470                 foreach ($media as $medium) {
471                         foreach ($links as $link) {
472                                 if (Strings::compareLink($link, $medium['url'])) {
473                                         continue 2;
474                                 }
475                         }
476
477                         $type = explode('/', current(explode(';', $medium['mimetype'])));
478                         if (count($type) < 2) {
479                                 Logger::info('Unknown MimeType', ['type' => $type, 'media' => $medium]);
480                                 $filetype = 'unkn';
481                                 $subtype = 'unkn';
482                         } else {
483                                 $filetype = strtolower($type[0]);
484                                 $subtype = strtolower($type[1]);
485                         }
486
487                         $medium['filetype'] = $filetype;
488                         $medium['subtype'] = $subtype;
489
490                         if ($medium['type'] == self::HTML || (($filetype == 'text') && ($subtype == 'html'))) {
491                                 $attachments['link'][] = $medium;
492                                 continue;
493                         }
494
495                         if (in_array($medium['type'], [self::AUDIO, self::IMAGE]) ||
496                                 in_array($filetype, ['audio', 'image'])) {
497                                 $attachments['visual'][] = $medium;
498                         } elseif (($medium['type'] == self::VIDEO) || ($filetype == 'video')) {
499                                 if (strpos($medium['url'], $guid) !== false) {
500                                         // Peertube videos are delivered in many different resolutions. We pick a moderate one.
501                                         // By checking against the GUID we also ensure to only work this way on Peertube posts.
502                                         // This wouldn't be executed when someone for example on Mastodon was sharing multiple videos in a single post.
503                                         if (empty($height) || ($height > $medium['height']) && ($medium['height'] >= 480)) {
504                                                 $height = $medium['height'];
505                                                 $selected = $medium['url'];
506                                         }
507                                         $video[$medium['url']] = $medium;
508                                 } else {
509                                         $attachments['visual'][] = $medium;
510                                 }
511                         } else {
512                                 $attachments['additional'][] = $medium;
513                         }
514                 }
515                 if (!empty($selected)) {
516                         $attachments['visual'][] = $video[$selected];
517                         unset($video[$selected]);
518                         foreach ($video as $element) {
519                                 $attachments['additional'][] = $element;
520                         }
521                 }
522                 return $attachments;
523         }
524
525         /**
526          * Add media attachments to the body
527          *
528          * @param int $uriid
529          * @param string $body
530          * @return string body
531          */
532         public static function addAttachmentsToBody(int $uriid, string $body = '')
533         {
534                 if (empty($body)) {
535                         $item = Post::selectFirst(['body'], ['uri-id' => $uriid]);
536                         if (!DBA::isResult($item)) {
537                                 return '';
538                         }
539                         $body = $item['body'];
540                 }
541                 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
542
543                 foreach (self::getByURIId($uriid, [self::IMAGE, self::AUDIO, self::VIDEO]) as $media) {
544                         if (Item::containsLink($body, $media['url'])) {
545                                 continue;
546                         }
547
548                         if ($media['type'] == self::IMAGE) {
549                                 if (!empty($media['description'])) {
550                                         $body .= "\n[img=" . $media['url'] . ']' . $media['description'] .'[/img]';
551                                 } else {
552                                         $body .= "\n[img]" . $media['url'] .'[/img]';
553                                 }
554                         } elseif ($media['type'] == self::AUDIO) {
555                                 $body .= "\n[audio]" . $media['url'] . "[/audio]\n";
556                         } elseif ($media['type'] == self::VIDEO) {
557                                 $body .= "\n[video]" . $media['url'] . "[/video]\n";
558                         }
559                 }
560
561                 if (preg_match("/.*(\[attachment.*?\].*?\[\/attachment\]).*/ism", $item['body'], $match)) {
562                         $body .= "\n" . $match[1];
563                 }
564
565                 return $body;
566         }
567 }