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\Database;
30 use Friendica\Database\DBA;
32 use Friendica\Network\HTTPException;
35 * Get information about a given URL
37 * Class with methods for extracting certain content from an url
41 const DEFAULT_EXPIRATION_FAILURE = 'now + 1 day';
42 const DEFAULT_EXPIRATION_SUCCESS = 'now + 3 months';
45 * Maximum number of characters for the description
47 const MAX_DESC_COUNT = 250;
50 * Minimum number of characters for the description
52 const MIN_DESC_COUNT = 100;
55 * Search for chached embeddable data of an url otherwise fetch it
57 * @param string $url The url of the page which should be scraped
58 * @param bool $no_guessing If true the parse doens't search for
60 * @param bool $do_oembed The false option is used by the function fetch_oembed()
61 * to avoid endless loops
63 * @return array which contains needed data for embedding
64 * string 'url' => The url of the parsed page
65 * string 'type' => Content type
66 * string 'title' => (optional) The title of the content
67 * string 'text' => (optional) The description for the content
68 * string 'image' => (optional) A preview image of the content (only available if $no_geuessing = false)
69 * array 'images' => (optional) Array of preview pictures
70 * string 'keywords' => (optional) The tags which belong to the content
72 * @throws HTTPException\InternalServerErrorException
73 * @see ParseUrl::getSiteinfo() for more information about scraping
76 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true): array
85 $urlHash = hash('sha256', $url);
87 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
88 ['url_hash' => $urlHash, 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
90 if (!empty($parsed_url['content'])) {
91 $data = unserialize($parsed_url['content']);
95 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
97 $expires = $data['expires'];
99 unset($data['expires']);
104 'url_hash' => $urlHash,
105 'guessing' => !$no_guessing,
106 'oembed' => $do_oembed,
108 'content' => serialize($data),
109 'created' => DateTimeFormat::utcNow(),
110 'expires' => $expires,
112 Database::INSERT_UPDATE
119 * Parse a page for embeddable content information
121 * This method parses to url for meta data which can be used to embed
122 * the content. If available it prioritizes Open Graph meta tags.
123 * If this is not available it uses the twitter cards meta tags.
124 * As fallback it uses standard html elements with meta informations
125 * like \<title\>Awesome Title\</title\> or
126 * \<meta name="description" content="An awesome description"\>
128 * @param string $url The url of the page which should be scraped
129 * @param bool $no_guessing If true the parse doens't search for
131 * @param bool $do_oembed The false option is used by the function fetch_oembed()
132 * to avoid endless loops
133 * @param int $count Internal counter to avoid endless loops
135 * @return array which contains needed data for embedding
136 * string 'url' => The url of the parsed page
137 * string 'type' => Content type (error, link, photo, image, audio, video)
138 * string 'title' => (optional) The title of the content
139 * string 'text' => (optional) The description for the content
140 * string 'image' => (optional) A preview image of the content (only available if $no_guessing = false)
141 * array 'images' => (optional) Array of preview pictures
142 * string 'keywords' => (optional) The tags which belong to the content
144 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
145 * @todo https://developers.google.com/+/plugins/snippet/
147 * <meta itemprop="name" content="Awesome title">
148 * <meta itemprop="description" content="An awesome description">
149 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
151 * <body itemscope itemtype="http://schema.org/Product">
152 * <h1 itemprop="name">Shiny Trinket</h1>
153 * <img itemprop="image" src="{image-url}" />
154 * <p itemprop="description">Shiny trinkets are shiny.</p>
158 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
167 // Check if the URL does contain a scheme
168 $scheme = parse_url($url, PHP_URL_SCHEME);
171 $url = 'http://' . ltrim($url, '/');
174 $url = trim($url, "'\"");
176 $url = Network::stripTrackingQueryParams($url);
181 'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE),
185 Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
189 $curlResult = DI::httpRequest()->get($url);
190 if (!$curlResult->isSuccess()) {
194 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
196 // If the file is too large then exit
197 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
201 // Native media type, no need for HTML parsing
202 $type = $curlResult->getHeader('Content-Type');
204 preg_match('#(image|video|audio)/#i', $type, $matches);
206 $siteinfo['type'] = array_pop($matches);
211 // If it isn't a HTML file then exit
212 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
216 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')) {
217 if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
218 $maxAge = max(86400, (int)array_pop($matches));
219 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
223 $header = $curlResult->getHeader();
224 $body = $curlResult->getBody();
227 $oembed_data = OEmbed::fetchURL($url);
229 if (!empty($oembed_data->type)) {
230 if (!in_array($oembed_data->type, ['error', 'rich', ''])) {
231 $siteinfo['type'] = $oembed_data->type;
234 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
235 if ($siteinfo['type'] != 'photo') {
236 if (isset($oembed_data->title)) {
237 $siteinfo['title'] = trim($oembed_data->title);
239 if (isset($oembed_data->description)) {
240 $siteinfo['text'] = trim($oembed_data->description);
242 if (isset($oembed_data->thumbnail_url)) {
243 $siteinfo['image'] = $oembed_data->thumbnail_url;
250 // Look for a charset, first in headers
251 // Expected form: Content-Type: text/html; charset=ISO-8859-4
252 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $header, $matches)) {
253 $charset = trim(trim(trim(array_pop($matches)), ';,'));
256 // Then in body that gets precedence
258 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
259 // - <meta charset="utf-8">
260 // - <meta charset=utf-8>
261 // - <meta charSet="utf-8">
262 // We escape <style> and <script> tags since they can contain irrelevant charset information
263 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
264 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
265 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
266 $charset = trim(trim(trim(array_pop($matches)), ';,'));
270 $siteinfo['charset'] = $charset;
272 if ($charset && strtoupper($charset) != 'UTF-8') {
273 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
274 $charset = str_ireplace('latin-1', 'latin1', $charset);
276 Logger::log('detected charset ' . $charset, Logger::DEBUG);
277 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
280 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
282 $doc = new DOMDocument();
283 @$doc->loadHTML($body);
285 XML::deleteNode($doc, 'style');
286 XML::deleteNode($doc, 'script');
287 XML::deleteNode($doc, 'option');
288 XML::deleteNode($doc, 'h1');
289 XML::deleteNode($doc, 'h2');
290 XML::deleteNode($doc, 'h3');
291 XML::deleteNode($doc, 'h4');
292 XML::deleteNode($doc, 'h5');
293 XML::deleteNode($doc, 'h6');
294 XML::deleteNode($doc, 'ol');
295 XML::deleteNode($doc, 'ul');
297 $xpath = new DOMXPath($doc);
299 $list = $xpath->query('//meta[@content]');
300 foreach ($list as $node) {
302 if ($node->attributes->length) {
303 foreach ($node->attributes as $attribute) {
304 $meta_tag[$attribute->name] = $attribute->value;
308 if (@$meta_tag['http-equiv'] == 'refresh') {
309 $path = $meta_tag['content'];
310 $pathinfo = explode(';', $path);
312 foreach ($pathinfo as $value) {
313 if (substr(strtolower($value), 0, 4) == 'url=') {
314 $content = substr($value, 4);
317 if ($content != '') {
318 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
324 $list = $xpath->query('//title');
325 if ($list->length > 0) {
326 $siteinfo['title'] = trim($list->item(0)->nodeValue);
329 $list = $xpath->query('//meta[@name]');
330 foreach ($list as $node) {
332 if ($node->attributes->length) {
333 foreach ($node->attributes as $attribute) {
334 $meta_tag[$attribute->name] = $attribute->value;
338 if (empty($meta_tag['content'])) {
342 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
344 switch (strtolower($meta_tag['name'])) {
346 $siteinfo['title'] = trim($meta_tag['content']);
349 $siteinfo['text'] = trim($meta_tag['content']);
352 $siteinfo['image'] = $meta_tag['content'];
354 case 'twitter:image':
355 $siteinfo['image'] = $meta_tag['content'];
357 case 'twitter:image:src':
358 $siteinfo['image'] = $meta_tag['content'];
361 // Detect photo pages
362 if ($meta_tag['content'] == 'summary_large_image') {
363 $siteinfo['type'] = 'photo';
366 case 'twitter:description':
367 $siteinfo['text'] = trim($meta_tag['content']);
369 case 'twitter:title':
370 $siteinfo['title'] = trim($meta_tag['content']);
373 $siteinfo['title'] = trim($meta_tag['content']);
375 case 'dc.description':
376 $siteinfo['text'] = trim($meta_tag['content']);
379 $keywords = explode(',', $meta_tag['content']);
381 case 'news_keywords':
382 $keywords = explode(',', $meta_tag['content']);
387 if (isset($keywords)) {
388 $siteinfo['keywords'] = [];
389 foreach ($keywords as $keyword) {
390 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
391 $siteinfo['keywords'][] = trim($keyword);
396 $list = $xpath->query('//meta[@property]');
397 foreach ($list as $node) {
399 if ($node->attributes->length) {
400 foreach ($node->attributes as $attribute) {
401 $meta_tag[$attribute->name] = $attribute->value;
405 if (!empty($meta_tag['content'])) {
406 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
408 switch (strtolower($meta_tag['property'])) {
410 $siteinfo['image'] = $meta_tag['content'];
413 $siteinfo['title'] = trim($meta_tag['content']);
415 case 'og:description':
416 $siteinfo['text'] = trim($meta_tag['content']);
422 // Prevent to have a photo type without an image
423 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
424 $siteinfo['type'] = 'link';
427 if (!empty($siteinfo['image'])) {
428 $src = self::completeUrl($siteinfo['image'], $url);
430 unset($siteinfo['image']);
432 $photodata = Images::getInfoFromURLCached($src);
434 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
435 $siteinfo['images'][] = ['src' => $src,
436 'width' => $photodata[0],
437 'height' => $photodata[1]];
441 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
442 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
443 $pos = mb_strrpos($siteinfo['text'], '.');
444 if ($pos > self::MIN_DESC_COUNT) {
445 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
449 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
451 Hook::callAll('getsiteinfo', $siteinfo);
457 * Convert tags from CSV to an array
459 * @param string $string Tags
460 * @return array with formatted Hashtags
462 public static function convertTagsToArray($string)
464 $arr_tags = str_getcsv($string);
465 if (count($arr_tags)) {
466 // add the # sign to every tag
467 array_walk($arr_tags, ["self", "arrAddHashes"]);
474 * Add a hasht sign to a string
476 * This method is used as callback function
478 * @param string $tag The pure tag name
479 * @param int $k Counter for internal use
482 private static function arrAddHashes(&$tag, $k)
488 * Add a scheme to an url
490 * The src attribute of some html elements (e.g. images)
491 * can miss the scheme so we need to add the correct
494 * @param string $url The url which possibly does have
495 * a missing scheme (a link to an image)
496 * @param string $scheme The url with a correct scheme
497 * (e.g. the url from the webpage which does contain the image)
499 * @return string The url with a scheme
501 private static function completeUrl($url, $scheme)
503 $urlarr = parse_url($url);
505 // If the url does allready have an scheme
506 // we can stop the process here
507 if (isset($urlarr["scheme"])) {
511 $schemearr = parse_url($scheme);
513 $complete = $schemearr["scheme"]."://".$schemearr["host"];
515 if (!empty($schemearr["port"])) {
516 $complete .= ":".$schemearr["port"];
519 if (!empty($urlarr["path"])) {
520 if (strpos($urlarr["path"], "/") !== 0) {
524 $complete .= $urlarr["path"];
527 if (!empty($urlarr["query"])) {
528 $complete .= "?".$urlarr["query"];
531 if (!empty($urlarr["fragment"])) {
532 $complete .= "#".$urlarr["fragment"];