3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Util;
26 use Friendica\Content\OEmbed;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Database\DBA;
33 * Get information about a given URL
35 * Class with methods for extracting certain content from an url
40 * Maximum number of characters for the description
42 const MAX_DESC_COUNT = 250;
45 * Minimum number of characters for the description
47 const MIN_DESC_COUNT = 100;
50 * Search for chached embeddable data of an url otherwise fetch it
52 * @param string $url The url of the page which should be scraped
53 * @param bool $no_guessing If true the parse doens't search for
55 * @param bool $do_oembed The false option is used by the function fetch_oembed()
56 * to avoid endless loops
58 * @return array which contains needed data for embedding
59 * string 'url' => The url of the parsed page
60 * string 'type' => Content type
61 * string 'title' => (optional) The title of the content
62 * string 'text' => (optional) The description for the content
63 * string 'image' => (optional) A preview image of the content (only available if $no_geuessing = false)
64 * array 'images' => (optional) Array of preview pictures
65 * string 'keywords' => (optional) The tags which belong to the content
67 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
68 * @see ParseUrl::getSiteinfo() for more information about scraping
71 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true)
77 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
78 ['url' => Strings::normaliseLink($url), 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
80 if (!empty($parsed_url['content'])) {
81 $data = unserialize($parsed_url['content']);
85 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
90 'url' => substr(Strings::normaliseLink($url), 0, 255), 'guessing' => !$no_guessing,
91 'oembed' => $do_oembed, 'content' => serialize($data),
92 'created' => DateTimeFormat::utcNow()
101 * Parse a page for embeddable content information
103 * This method parses to url for meta data which can be used to embed
104 * the content. If available it prioritizes Open Graph meta tags.
105 * If this is not available it uses the twitter cards meta tags.
106 * As fallback it uses standard html elements with meta informations
107 * like \<title\>Awesome Title\</title\> or
108 * \<meta name="description" content="An awesome description"\>
110 * @param string $url The url of the page which should be scraped
111 * @param bool $no_guessing If true the parse doens't search for
113 * @param bool $do_oembed The false option is used by the function fetch_oembed()
114 * to avoid endless loops
115 * @param int $count Internal counter to avoid endless loops
117 * @return array which contains needed data for embedding
118 * string 'url' => The url of the parsed page
119 * string 'type' => Content type
120 * string 'title' => (optional) The title of the content
121 * string 'text' => (optional) The description for the content
122 * string 'image' => (optional) A preview image of the content (only available if $no_guessing = false)
123 * array 'images' => (optional) Array of preview pictures
124 * string 'keywords' => (optional) The tags which belong to the content
126 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
127 * @todo https://developers.google.com/+/plugins/snippet/
129 * <meta itemprop="name" content="Awesome title">
130 * <meta itemprop="description" content="An awesome description">
131 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
133 * <body itemscope itemtype="http://schema.org/Product">
134 * <h1 itemprop="name">Shiny Trinket</h1>
135 * <img itemprop="image" src="{image-url}" />
136 * <p itemprop="description">Shiny trinkets are shiny.</p>
140 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
142 // Check if the URL does contain a scheme
143 $scheme = parse_url($url, PHP_URL_SCHEME);
146 $url = 'http://' . ltrim($url, '/');
149 $url = trim($url, "'\"");
151 $url = Network::stripTrackingQueryParams($url);
159 Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
163 $curlResult = DI::httpRequest()->get($url);
164 if (!$curlResult->isSuccess()) {
168 // If the file is too large then exit
169 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
173 // If it isn't a HTML file then exit
174 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
178 $header = $curlResult->getHeader();
179 $body = $curlResult->getBody();
182 $oembed_data = OEmbed::fetchURL($url);
184 if (!empty($oembed_data->type)) {
185 if (!in_array($oembed_data->type, ['error', 'rich', ''])) {
186 $siteinfo['type'] = $oembed_data->type;
189 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
190 if ($siteinfo['type'] != 'photo') {
191 if (isset($oembed_data->title)) {
192 $siteinfo['title'] = trim($oembed_data->title);
194 if (isset($oembed_data->description)) {
195 $siteinfo['text'] = trim($oembed_data->description);
197 if (isset($oembed_data->thumbnail_url)) {
198 $siteinfo['image'] = $oembed_data->thumbnail_url;
204 // Fetch the first mentioned charset. Can be in body or header
206 if (preg_match('/charset=(.*?)[\'"\s\n]/', $header, $matches)) {
207 $charset = trim(trim(trim(array_pop($matches)), ';,'));
210 if ($charset && strtoupper($charset) != 'UTF-8') {
211 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
212 $charset = str_ireplace('latin-1', 'latin1', $charset);
214 Logger::log('detected charset ' . $charset, Logger::DEBUG);
215 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
218 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
220 $doc = new DOMDocument();
221 @$doc->loadHTML($body);
223 XML::deleteNode($doc, 'style');
224 XML::deleteNode($doc, 'script');
225 XML::deleteNode($doc, 'option');
226 XML::deleteNode($doc, 'h1');
227 XML::deleteNode($doc, 'h2');
228 XML::deleteNode($doc, 'h3');
229 XML::deleteNode($doc, 'h4');
230 XML::deleteNode($doc, 'h5');
231 XML::deleteNode($doc, 'h6');
232 XML::deleteNode($doc, 'ol');
233 XML::deleteNode($doc, 'ul');
235 $xpath = new DOMXPath($doc);
237 $list = $xpath->query('//meta[@content]');
238 foreach ($list as $node) {
240 if ($node->attributes->length) {
241 foreach ($node->attributes as $attribute) {
242 $meta_tag[$attribute->name] = $attribute->value;
246 if (@$meta_tag['http-equiv'] == 'refresh') {
247 $path = $meta_tag['content'];
248 $pathinfo = explode(';', $path);
250 foreach ($pathinfo as $value) {
251 if (substr(strtolower($value), 0, 4) == 'url=') {
252 $content = substr($value, 4);
255 if ($content != '') {
256 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
262 $list = $xpath->query('//title');
263 if ($list->length > 0) {
264 $siteinfo['title'] = trim($list->item(0)->nodeValue);
267 $list = $xpath->query('//meta[@name]');
268 foreach ($list as $node) {
270 if ($node->attributes->length) {
271 foreach ($node->attributes as $attribute) {
272 $meta_tag[$attribute->name] = $attribute->value;
276 if (empty($meta_tag['content'])) {
280 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
282 switch (strtolower($meta_tag['name'])) {
284 $siteinfo['title'] = trim($meta_tag['content']);
287 $siteinfo['text'] = trim($meta_tag['content']);
290 $siteinfo['image'] = $meta_tag['content'];
292 case 'twitter:image':
293 $siteinfo['image'] = $meta_tag['content'];
295 case 'twitter:image:src':
296 $siteinfo['image'] = $meta_tag['content'];
299 // Detect photo pages
300 if ($meta_tag['content'] == 'summary_large_image') {
301 $siteinfo['type'] = 'photo';
304 case 'twitter:description':
305 $siteinfo['text'] = trim($meta_tag['content']);
307 case 'twitter:title':
308 $siteinfo['title'] = trim($meta_tag['content']);
311 $siteinfo['title'] = trim($meta_tag['content']);
313 case 'dc.description':
314 $siteinfo['text'] = trim($meta_tag['content']);
317 $keywords = explode(',', $meta_tag['content']);
319 case 'news_keywords':
320 $keywords = explode(',', $meta_tag['content']);
325 if (isset($keywords)) {
326 $siteinfo['keywords'] = [];
327 foreach ($keywords as $keyword) {
328 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
329 $siteinfo['keywords'][] = trim($keyword);
334 $list = $xpath->query('//meta[@property]');
335 foreach ($list as $node) {
337 if ($node->attributes->length) {
338 foreach ($node->attributes as $attribute) {
339 $meta_tag[$attribute->name] = $attribute->value;
343 if (!empty($meta_tag['content'])) {
344 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
346 switch (strtolower($meta_tag['property'])) {
348 $siteinfo['image'] = $meta_tag['content'];
351 $siteinfo['title'] = trim($meta_tag['content']);
353 case 'og:description':
354 $siteinfo['text'] = trim($meta_tag['content']);
360 // Prevent to have a photo type without an image
361 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
362 $siteinfo['type'] = 'link';
365 if (!empty($siteinfo['image'])) {
366 $src = self::completeUrl($siteinfo['image'], $url);
368 unset($siteinfo['image']);
370 $photodata = Images::getInfoFromURLCached($src);
372 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
373 $siteinfo['images'][] = ['src' => $src,
374 'width' => $photodata[0],
375 'height' => $photodata[1]];
379 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
380 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
381 $pos = mb_strrpos($siteinfo['text'], '.');
382 if ($pos > self::MIN_DESC_COUNT) {
383 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
387 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
389 Hook::callAll('getsiteinfo', $siteinfo);
395 * Convert tags from CSV to an array
397 * @param string $string Tags
398 * @return array with formatted Hashtags
400 public static function convertTagsToArray($string)
402 $arr_tags = str_getcsv($string);
403 if (count($arr_tags)) {
404 // add the # sign to every tag
405 array_walk($arr_tags, ["self", "arrAddHashes"]);
412 * Add a hasht sign to a string
414 * This method is used as callback function
416 * @param string $tag The pure tag name
417 * @param int $k Counter for internal use
420 private static function arrAddHashes(&$tag, $k)
426 * Add a scheme to an url
428 * The src attribute of some html elements (e.g. images)
429 * can miss the scheme so we need to add the correct
432 * @param string $url The url which possibly does have
433 * a missing scheme (a link to an image)
434 * @param string $scheme The url with a correct scheme
435 * (e.g. the url from the webpage which does contain the image)
437 * @return string The url with a scheme
439 private static function completeUrl($url, $scheme)
441 $urlarr = parse_url($url);
443 // If the url does allready have an scheme
444 // we can stop the process here
445 if (isset($urlarr["scheme"])) {
449 $schemearr = parse_url($scheme);
451 $complete = $schemearr["scheme"]."://".$schemearr["host"];
453 if (!empty($schemearr["port"])) {
454 $complete .= ":".$schemearr["port"];
457 if (!empty($urlarr["path"])) {
458 if (strpos($urlarr["path"], "/") !== 0) {
462 $complete .= $urlarr["path"];
465 if (!empty($urlarr["query"])) {
466 $complete .= "?".$urlarr["query"];
469 if (!empty($urlarr["fragment"])) {
470 $complete .= "#".$urlarr["fragment"];