5396bc1bbe96d4d17a3eb55e6d40bf0918b62b76
[friendica.git/.git] / src / Content / PageInfo.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\Content;
23
24 use Friendica\Core\Hook;
25 use Friendica\Core\Logger;
26 use Friendica\DI;
27 use Friendica\Network\HTTPException;
28 use Friendica\Util\ParseUrl;
29 use Friendica\Util\Strings;
30
31 /**
32  * Extracts trailing URLs from post bodies to transform them in enriched attachment tags through Site Info query
33  */
34 class PageInfo
35 {
36         /**
37          * @param string $body
38          * @param bool   $searchNakedUrls
39          * @param bool   $no_photos
40          * @return string
41          * @throws HTTPException\InternalServerErrorException
42          */
43         public static function searchAndAppendToBody(string $body, bool $searchNakedUrls = false, bool $no_photos = false)
44         {
45                 Logger::info('add_page_info_to_body: fetch page info for body', ['body' => $body]);
46
47                 $url = self::getRelevantUrlFromBody($body, $searchNakedUrls);
48                 if (!$url) {
49                         return $body;
50                 }
51
52                 $data = self::queryUrl($url);
53                 if (!$data) {
54                         return $body;
55                 }
56
57                 return self::appendDataToBody($body, $data, $no_photos);
58         }
59
60         /**
61          * @param string $body
62          * @param array  $data
63          * @param bool   $no_photos
64          * @return string
65          * @throws HTTPException\InternalServerErrorException
66          */
67         public static function appendDataToBody(string $body, array $data, bool $no_photos = false)
68         {
69                 // Only one [attachment] tag per body is allowed
70                 $existingAttachmentPos = strpos($body, '[attachment');
71                 if ($existingAttachmentPos !== false) {
72                         $linkTitle = $data['title'] ?: $data['url'];
73                         // Additional link attachments are prepended before the existing [attachment] tag
74                         $body = substr_replace($body, "\n[bookmark=" . $data['url'] . ']' . $linkTitle . "[/bookmark]\n", $existingAttachmentPos, 0);
75                 } else {
76                         $footer = PageInfo::getFooterFromData($data, $no_photos);
77                         $body = self::stripTrailingUrlFromBody($body, $data['url']);
78                         $body .= "\n" . $footer;
79                 }
80
81                 return $body;
82         }
83
84         /**
85          * @param string $url
86          * @param bool $no_photos
87          * @param string $photo
88          * @param bool $keywords
89          * @param string $keyword_denylist
90          * @return string
91          * @throws HTTPException\InternalServerErrorException
92          */
93         public static function getFooterFromUrl(string $url, bool $no_photos = false, string $photo = '', bool $keywords = false, string $keyword_denylist = '')
94         {
95                 $data = self::queryUrl($url, $photo, $keywords, $keyword_denylist);
96
97                 return self::getFooterFromData($data, $no_photos);
98         }
99
100         /**
101          * @param array $data
102          * @param bool  $no_photos
103          * @return string
104          * @throws HTTPException\InternalServerErrorException
105          */
106         public static function getFooterFromData(array $data, bool $no_photos = false)
107         {
108                 Hook::callAll('page_info_data', $data);
109
110                 if (empty($data['type'])) {
111                         return '';
112                 }
113
114                 // It maybe is a rich content, but if it does have everything that a link has,
115                 // then treat it that way
116                 if (($data['type'] == 'rich') && is_string($data['title']) &&
117                         is_string($data['text']) && !empty($data['images'])) {
118                         $data['type'] = 'link';
119                 }
120
121                 $data['title'] = $data['title'] ?? '';
122
123                 if ((($data['type'] != 'link') && ($data['type'] != 'video') && ($data['type'] != 'photo')) || ($data['title'] == $data['url'])) {
124                         return '';
125                 }
126
127                 if ($no_photos && ($data['type'] == 'photo')) {
128                         return '';
129                 }
130
131                 // Escape some bad characters
132                 $data['url'] = str_replace(['[', ']'], ['&#91;', '&#93;'], htmlentities($data['url'], ENT_QUOTES, 'UTF-8', false));
133                 $data['title'] = str_replace(['[', ']'], ['&#91;', '&#93;'], htmlentities($data['title'], ENT_QUOTES, 'UTF-8', false));
134
135                 $text = "[attachment type='" . $data['type'] . "'";
136
137                 if (!empty($data['url'])) {
138                         $text .= " url='" . $data['url'] . "'";
139                 }
140
141                 if (!empty($data['title'])) {
142                         $text .= " title='" . $data['title'] . "'";
143                 }
144
145                 if (empty($data['text'])) {
146                         $data['text'] = '';
147                 }
148
149                 // Only embedd a picture link when it seems to be a valid picture ("width" is set)
150                 if (!empty($data['images']) && !empty($data['images'][0]['width'])) {
151                         $preview = str_replace(['[', ']'], ['&#91;', '&#93;'], htmlentities($data['images'][0]['src'], ENT_QUOTES, 'UTF-8', false));
152                         // if the preview picture is larger than 500 pixels then show it in a larger mode
153                         // But only, if the picture isn't higher than large (To prevent huge posts)
154                         if (!DI::config()->get('system', 'always_show_preview') && ($data['images'][0]['width'] >= 500)
155                                 && ($data['images'][0]['width'] >= $data['images'][0]['height'])) {
156                                 $text .= " image='" . $preview . "'";
157                         } else {
158                                 $text .= " preview='" . $preview . "'";
159
160                                 if (empty($data['text'])) {
161                                         $data['text'] = $data['title'];
162                                 }
163                 
164                                 if (empty($data['text'])) {
165                                         $data['text'] = $data['url'];
166                                 }
167                         }
168                 }
169
170                 $text .= ']' . $data['text'] . '[/attachment]';
171
172                 $hashtags = '';
173                 if (!empty($data['keywords'])) {
174                         $hashtags = "\n";
175                         foreach ($data['keywords'] as $keyword) {
176                                 /// @TODO make a positive list of allowed characters
177                                 $hashtag = str_replace([' ', '+', '/', '.', '#', '@', "'", '"', '’', '`', '(', ')', '„', '“'], '', $keyword);
178                                 $hashtags .= '#[url=' . DI::baseUrl() . '/search?tag=' . $hashtag . ']' . $hashtag . '[/url] ';
179                         }
180                 }
181
182                 return $text . $hashtags;
183         }
184
185         /**
186          * @param string  $url
187          * @param string $photo
188          * @param bool $keywords
189          * @param string $keyword_denylist
190          * @return array|bool
191          * @throws HTTPException\InternalServerErrorException
192          */
193         public static function queryUrl(string $url, string $photo = '', bool $keywords = false, string $keyword_denylist = '')
194         {
195                 $data = ParseUrl::getSiteinfoCached($url, true);
196
197                 if ($photo != '') {
198                         $data['images'][0]['src'] = $photo;
199                 }
200
201                 if (!$keywords) {
202                         unset($data['keywords']);
203                 } elseif ($keyword_denylist && !empty($data['keywords'])) {
204                         $list = explode(', ', $keyword_denylist);
205
206                         foreach ($list as $keyword) {
207                                 $keyword = trim($keyword);
208
209                                 $index = array_search($keyword, $data['keywords']);
210                                 if ($index !== false) {
211                                         unset($data['keywords'][$index]);
212                                 }
213                         }
214                 }
215
216                 Logger::info('fetch page info for URL', ['url' => $url, 'data' => $data]);
217
218                 return $data;
219         }
220
221         /**
222          * @param string $url
223          * @param string $photo
224          * @param string $keyword_denylist
225          * @return array
226          * @throws HTTPException\InternalServerErrorException
227          */
228         public static function getTagsFromUrl(string $url, string $photo = '', string $keyword_denylist = '')
229         {
230                 $data = self::queryUrl($url, $photo, true, $keyword_denylist);
231
232                 if (empty($data['keywords'])) {
233                         return [];
234                 }
235
236                 $taglist = [];
237                 foreach ($data['keywords'] as $keyword) {
238                         $hashtag = str_replace([' ', '+', '/', '.', '#', "'"],
239                                 ['', '', '', '', '', ''], $keyword);
240
241                         $taglist[] = $hashtag;
242                 }
243
244                 return $taglist;
245         }
246
247         /**
248          * Picks a non-hashtag, non-mention, schemeful URL at the end of the provided body string to be converted into Page Info.
249          *
250          * @param string $body
251          * @param bool   $searchNakedUrls Whether we should pick a naked URL (outside of BBCode tags) as a last resort
252          * @return string|null
253          */
254         protected static function getRelevantUrlFromBody(string $body, bool $searchNakedUrls = false)
255         {
256                 $URLSearchString = 'https?://[^\[\]]*';
257
258                 // Fix for Mastodon where the mentions are in a different format
259                 $body = preg_replace("~\[url=($URLSearchString)]([#!@])(.*?)\[/url]~is", '$2[url=$1]$3[/url]', $body);
260
261                 preg_match("~(?<![!#@])\[url]($URLSearchString)\[/url]$~is", $body, $matches);
262
263                 if (!$matches) {
264                         preg_match("~(?<![!#@])\[url=($URLSearchString)].*\[/url]$~is", $body, $matches);
265                 }
266
267                 if (!$matches && $searchNakedUrls) {
268                         preg_match(Strings::autoLinkRegEx(), $body, $matches);
269                         if ($matches && !Strings::endsWith($body, $matches[1])) {
270                                 unset($matches);
271                         }
272                 }
273
274                 return $matches[1] ?? null;
275         }
276
277         /**
278          * Remove the provided URL from the body if it is at the end of it.
279          * Keep the link label if it isn't the full URL or a shortened version of it.
280          *
281          * @param string $body
282          * @param string $url
283          * @return string
284          */
285         protected static function stripTrailingUrlFromBody(string $body, string $url)
286         {
287                 $quotedUrl = preg_quote($url, '#');
288                 $body = preg_replace_callback("#(?:
289                         \[url]$quotedUrl\[/url]|
290                         \[url=$quotedUrl]$quotedUrl\[/url]|
291                         \[url=$quotedUrl]([^[]*?)\[/url]|
292                         $quotedUrl
293                 )$#isx", function ($match) use ($url) {
294                         // Stripping URLs with no label
295                         if (empty($match[1])) {
296                                 return '';
297                         }
298
299                         // Stripping link labels that include a shortened version of the URL
300                         if (strpos($url, trim($match[1], '.…')) !== false) {
301                                 return '';
302                         }
303
304                         // Keep all other labels
305                         return $match[1];
306                 }, $body);
307
308                 return rtrim($body);
309         }
310 }