]> git.mxchange.org Git - friendica.git/blob - src/Content/PageInfo.php
Add intermediate method PageInfo::appendDataToBody
[friendica.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['text'])) {
138                         $data['text'] = $data['title'];
139                 }
140
141                 if (empty($data['text'])) {
142                         $data['text'] = $data['url'];
143                 }
144
145                 if (!empty($data['url'])) {
146                         $text .= " url='" . $data['url'] . "'";
147                 }
148
149                 if (!empty($data['title'])) {
150                         $text .= " title='" . $data['title'] . "'";
151                 }
152
153                 // Only embedd a picture link when it seems to be a valid picture ("width" is set)
154                 if (!empty($data['images']) && !empty($data['images'][0]['width'])) {
155                         $preview = str_replace(['[', ']'], ['&#91;', '&#93;'], htmlentities($data['images'][0]['src'], ENT_QUOTES, 'UTF-8', false));
156                         // if the preview picture is larger than 500 pixels then show it in a larger mode
157                         // But only, if the picture isn't higher than large (To prevent huge posts)
158                         if (!DI::config()->get('system', 'always_show_preview') && ($data['images'][0]['width'] >= 500)
159                                 && ($data['images'][0]['width'] >= $data['images'][0]['height'])) {
160                                 $text .= " image='" . $preview . "'";
161                         } else {
162                                 $text .= " preview='" . $preview . "'";
163                         }
164                 }
165
166                 $text .= ']' . $data['text'] . '[/attachment]';
167
168                 $hashtags = '';
169                 if (!empty($data['keywords'])) {
170                         $hashtags = "\n";
171                         foreach ($data['keywords'] as $keyword) {
172                                 /// @TODO make a positive list of allowed characters
173                                 $hashtag = str_replace([' ', '+', '/', '.', '#', '@', "'", '"', '’', '`', '(', ')', '„', '“'], '', $keyword);
174                                 $hashtags .= '#[url=' . DI::baseUrl() . '/search?tag=' . $hashtag . ']' . $hashtag . '[/url] ';
175                         }
176                 }
177
178                 return $text . $hashtags;
179         }
180
181         /**
182          * @param string  $url
183          * @param string $photo
184          * @param bool $keywords
185          * @param string $keyword_denylist
186          * @return array|bool
187          * @throws HTTPException\InternalServerErrorException
188          */
189         public static function queryUrl(string $url, string $photo = '', bool $keywords = false, string $keyword_denylist = '')
190         {
191                 $data = ParseUrl::getSiteinfoCached($url, true);
192
193                 if ($photo != '') {
194                         $data['images'][0]['src'] = $photo;
195                 }
196
197                 if (!$keywords) {
198                         unset($data['keywords']);
199                 } elseif ($keyword_denylist && !empty($data['keywords'])) {
200                         $list = explode(', ', $keyword_denylist);
201
202                         foreach ($list as $keyword) {
203                                 $keyword = trim($keyword);
204
205                                 $index = array_search($keyword, $data['keywords']);
206                                 if ($index !== false) {
207                                         unset($data['keywords'][$index]);
208                                 }
209                         }
210                 }
211
212                 Logger::info('fetch page info for URL', ['url' => $url, 'data' => $data]);
213
214                 return $data;
215         }
216
217         /**
218          * @param string $url
219          * @param string $photo
220          * @param string $keyword_denylist
221          * @return array
222          * @throws HTTPException\InternalServerErrorException
223          */
224         public static function getTagsFromUrl(string $url, string $photo = '', string $keyword_denylist = '')
225         {
226                 $data = self::queryUrl($url, $photo, true, $keyword_denylist);
227
228                 if (empty($data['keywords'])) {
229                         return [];
230                 }
231
232                 $taglist = [];
233                 foreach ($data['keywords'] as $keyword) {
234                         $hashtag = str_replace([' ', '+', '/', '.', '#', "'"],
235                                 ['', '', '', '', '', ''], $keyword);
236
237                         $taglist[] = $hashtag;
238                 }
239
240                 return $taglist;
241         }
242
243         /**
244          * Picks a non-hashtag, non-mention, schemeful URL at the end of the provided body string to be converted into Page Info.
245          *
246          * @param string $body
247          * @param bool   $searchNakedUrls Whether we should pick a naked URL (outside of BBCode tags) as a last resort
248          * @return string|null
249          */
250         protected static function getRelevantUrlFromBody(string $body, bool $searchNakedUrls = false)
251         {
252                 $URLSearchString = 'https?://[^\[\]]*';
253
254                 // Fix for Mastodon where the mentions are in a different format
255                 $body = preg_replace("~\[url=($URLSearchString)]([#!@])(.*?)\[/url]~is", '$2[url=$1]$3[/url]', $body);
256
257                 preg_match("~(?<![!#@])\[url]($URLSearchString)\[/url]$~is", $body, $matches);
258
259                 if (!$matches) {
260                         preg_match("~(?<![!#@])\[url=($URLSearchString)].*\[/url]$~is", $body, $matches);
261                 }
262
263                 if (!$matches && $searchNakedUrls) {
264                         preg_match('~(?<=\W|^)(?<![=\]])(https?://.+)$~is', $body, $matches);
265                         if ($matches && !Strings::endsWith($body, $matches[1])) {
266                                 unset($matches);
267                         }
268                 }
269
270                 return $matches[1] ?? null;
271         }
272
273         /**
274          * Remove the provided URL from the body if it is at the end of it.
275          * Keep the link label if it isn't the full URL.
276          *
277          * @param string $body
278          * @param string $url
279          * @return string|string[]|null
280          */
281         protected static function stripTrailingUrlFromBody(string $body, string $url)
282         {
283                 $quotedUrl = preg_quote($url, '#');
284                 $body = preg_replace("#(?:
285                         \[url]$quotedUrl\[/url]|
286                         \[url=$quotedUrl]$quotedUrl\[/url]|
287                         \[url=$quotedUrl]([^[]*?)\[/url]|
288                         $quotedUrl
289                 )$#isx", '$1', $body);
290
291                 return $body;
292         }
293 }