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 * Fetch the content type of the given url
56 * @param string $url URL of the page
57 * @return string content type
59 public static function getContentType(string $url)
61 $curlResult = DI::httpRequest()->head($url);
62 if (!$curlResult->isSuccess()) {
66 $contenttype = $curlResult->getHeader('Content-Type');
67 if (empty($contenttype)) {
71 if (!preg_match('#(image|video|audio)/#i', $contenttype, $matches)) {
75 return array_pop($matches);
79 * Search for chached embeddable data of an url otherwise fetch it
81 * @param string $url The url of the page which should be scraped
82 * @param bool $no_guessing If true the parse doens't search for
84 * @param bool $do_oembed The false option is used by the function fetch_oembed()
85 * to avoid endless loops
87 * @return array which contains needed data for embedding
88 * string 'url' => The url of the parsed page
89 * string 'type' => Content type
90 * string 'title' => (optional) The title of the content
91 * string 'text' => (optional) The description for the content
92 * string 'image' => (optional) A preview image of the content (only available if $no_geuessing = false)
93 * array 'images' => (optional) Array of preview pictures
94 * string 'keywords' => (optional) The tags which belong to the content
96 * @throws HTTPException\InternalServerErrorException
97 * @see ParseUrl::getSiteinfo() for more information about scraping
100 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true): array
109 $urlHash = hash('sha256', $url);
111 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
112 ['url_hash' => $urlHash, 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
114 if (!empty($parsed_url['content'])) {
115 $data = unserialize($parsed_url['content']);
119 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
121 $expires = $data['expires'];
123 unset($data['expires']);
128 'url_hash' => $urlHash,
129 'guessing' => !$no_guessing,
130 'oembed' => $do_oembed,
132 'content' => serialize($data),
133 'created' => DateTimeFormat::utcNow(),
134 'expires' => $expires,
136 Database::INSERT_UPDATE
143 * Parse a page for embeddable content information
145 * This method parses to url for meta data which can be used to embed
146 * the content. If available it prioritizes Open Graph meta tags.
147 * If this is not available it uses the twitter cards meta tags.
148 * As fallback it uses standard html elements with meta informations
149 * like \<title\>Awesome Title\</title\> or
150 * \<meta name="description" content="An awesome description"\>
152 * @param string $url The url of the page which should be scraped
153 * @param bool $no_guessing If true the parse doens't search for
155 * @param bool $do_oembed The false option is used by the function fetch_oembed()
156 * to avoid endless loops
157 * @param int $count Internal counter to avoid endless loops
159 * @return array which contains needed data for embedding
160 * string 'url' => The url of the parsed page
161 * string 'type' => Content type (error, link, photo, image, audio, video)
162 * string 'title' => (optional) The title of the content
163 * string 'text' => (optional) The description for the content
164 * string 'image' => (optional) A preview image of the content (only available if $no_guessing = false)
165 * array 'images' => (optional) Array of preview pictures
166 * string 'keywords' => (optional) The tags which belong to the content
168 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
169 * @todo https://developers.google.com/+/plugins/snippet/
171 * <meta itemprop="name" content="Awesome title">
172 * <meta itemprop="description" content="An awesome description">
173 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
175 * <body itemscope itemtype="http://schema.org/Product">
176 * <h1 itemprop="name">Shiny Trinket</h1>
177 * <img itemprop="image" src="{image-url}" />
178 * <p itemprop="description">Shiny trinkets are shiny.</p>
182 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
191 // Check if the URL does contain a scheme
192 $scheme = parse_url($url, PHP_URL_SCHEME);
195 $url = 'http://' . ltrim($url, '/');
198 $url = trim($url, "'\"");
200 $url = Network::stripTrackingQueryParams($url);
205 'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE),
209 Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
213 $curlResult = DI::httpRequest()->get($url);
214 if (!$curlResult->isSuccess()) {
218 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
220 // If the file is too large then exit
221 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
225 // Native media type, no need for HTML parsing
226 $type = $curlResult->getHeader('Content-Type');
228 preg_match('#(image|video|audio)/#i', $type, $matches);
230 $siteinfo['type'] = array_pop($matches);
235 // If it isn't a HTML file then exit
236 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
240 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')) {
241 if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
242 $maxAge = max(86400, (int)array_pop($matches));
243 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
247 $header = $curlResult->getHeader();
248 $body = $curlResult->getBody();
251 $oembed_data = OEmbed::fetchURL($url);
253 if (!empty($oembed_data->type)) {
254 if (!in_array($oembed_data->type, ['error', 'rich', ''])) {
255 $siteinfo['type'] = $oembed_data->type;
258 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
259 if ($siteinfo['type'] != 'photo') {
260 if (isset($oembed_data->title)) {
261 $siteinfo['title'] = trim($oembed_data->title);
263 if (isset($oembed_data->description)) {
264 $siteinfo['text'] = trim($oembed_data->description);
266 if (isset($oembed_data->thumbnail_url)) {
267 $siteinfo['image'] = $oembed_data->thumbnail_url;
274 // Look for a charset, first in headers
275 // Expected form: Content-Type: text/html; charset=ISO-8859-4
276 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $header, $matches)) {
277 $charset = trim(trim(trim(array_pop($matches)), ';,'));
280 // Then in body that gets precedence
282 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
283 // - <meta charset="utf-8">
284 // - <meta charset=utf-8>
285 // - <meta charSet="utf-8">
286 // We escape <style> and <script> tags since they can contain irrelevant charset information
287 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
288 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
289 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
290 $charset = trim(trim(trim(array_pop($matches)), ';,'));
294 $siteinfo['charset'] = $charset;
296 if ($charset && strtoupper($charset) != 'UTF-8') {
297 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
298 $charset = str_ireplace('latin-1', 'latin1', $charset);
300 Logger::log('detected charset ' . $charset, Logger::DEBUG);
301 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
304 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
306 $doc = new DOMDocument();
307 @$doc->loadHTML($body);
309 XML::deleteNode($doc, 'style');
310 XML::deleteNode($doc, 'script');
311 XML::deleteNode($doc, 'option');
312 XML::deleteNode($doc, 'h1');
313 XML::deleteNode($doc, 'h2');
314 XML::deleteNode($doc, 'h3');
315 XML::deleteNode($doc, 'h4');
316 XML::deleteNode($doc, 'h5');
317 XML::deleteNode($doc, 'h6');
318 XML::deleteNode($doc, 'ol');
319 XML::deleteNode($doc, 'ul');
321 $xpath = new DOMXPath($doc);
323 $list = $xpath->query('//meta[@content]');
324 foreach ($list as $node) {
326 if ($node->attributes->length) {
327 foreach ($node->attributes as $attribute) {
328 $meta_tag[$attribute->name] = $attribute->value;
332 if (@$meta_tag['http-equiv'] == 'refresh') {
333 $path = $meta_tag['content'];
334 $pathinfo = explode(';', $path);
336 foreach ($pathinfo as $value) {
337 if (substr(strtolower($value), 0, 4) == 'url=') {
338 $content = substr($value, 4);
341 if ($content != '') {
342 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
348 $list = $xpath->query('//title');
349 if ($list->length > 0) {
350 $siteinfo['title'] = trim($list->item(0)->nodeValue);
353 $list = $xpath->query('//meta[@name]');
354 foreach ($list as $node) {
356 if ($node->attributes->length) {
357 foreach ($node->attributes as $attribute) {
358 $meta_tag[$attribute->name] = $attribute->value;
362 if (empty($meta_tag['content'])) {
366 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
368 switch (strtolower($meta_tag['name'])) {
370 $siteinfo['title'] = trim($meta_tag['content']);
373 $siteinfo['text'] = trim($meta_tag['content']);
376 $siteinfo['image'] = $meta_tag['content'];
378 case 'twitter:image':
379 $siteinfo['image'] = $meta_tag['content'];
381 case 'twitter:image:src':
382 $siteinfo['image'] = $meta_tag['content'];
385 // Detect photo pages
386 if ($meta_tag['content'] == 'summary_large_image') {
387 $siteinfo['type'] = 'photo';
390 case 'twitter:description':
391 $siteinfo['text'] = trim($meta_tag['content']);
393 case 'twitter:title':
394 $siteinfo['title'] = trim($meta_tag['content']);
397 $siteinfo['title'] = trim($meta_tag['content']);
399 case 'dc.description':
400 $siteinfo['text'] = trim($meta_tag['content']);
403 $keywords = explode(',', $meta_tag['content']);
405 case 'news_keywords':
406 $keywords = explode(',', $meta_tag['content']);
411 if (isset($keywords)) {
412 $siteinfo['keywords'] = [];
413 foreach ($keywords as $keyword) {
414 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
415 $siteinfo['keywords'][] = trim($keyword);
420 $list = $xpath->query('//meta[@property]');
421 foreach ($list as $node) {
423 if ($node->attributes->length) {
424 foreach ($node->attributes as $attribute) {
425 $meta_tag[$attribute->name] = $attribute->value;
429 if (!empty($meta_tag['content'])) {
430 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
432 switch (strtolower($meta_tag['property'])) {
434 $siteinfo['image'] = $meta_tag['content'];
437 $siteinfo['title'] = trim($meta_tag['content']);
439 case 'og:description':
440 $siteinfo['text'] = trim($meta_tag['content']);
446 // Prevent to have a photo type without an image
447 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
448 $siteinfo['type'] = 'link';
451 if (!empty($siteinfo['image'])) {
452 $src = self::completeUrl($siteinfo['image'], $url);
454 unset($siteinfo['image']);
456 $photodata = Images::getInfoFromURLCached($src);
458 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
459 $siteinfo['images'][] = ['src' => $src,
460 'width' => $photodata[0],
461 'height' => $photodata[1]];
465 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
466 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
467 $pos = mb_strrpos($siteinfo['text'], '.');
468 if ($pos > self::MIN_DESC_COUNT) {
469 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
473 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
475 Hook::callAll('getsiteinfo', $siteinfo);
481 * Convert tags from CSV to an array
483 * @param string $string Tags
484 * @return array with formatted Hashtags
486 public static function convertTagsToArray($string)
488 $arr_tags = str_getcsv($string);
489 if (count($arr_tags)) {
490 // add the # sign to every tag
491 array_walk($arr_tags, ["self", "arrAddHashes"]);
498 * Add a hasht sign to a string
500 * This method is used as callback function
502 * @param string $tag The pure tag name
503 * @param int $k Counter for internal use
506 private static function arrAddHashes(&$tag, $k)
512 * Add a scheme to an url
514 * The src attribute of some html elements (e.g. images)
515 * can miss the scheme so we need to add the correct
518 * @param string $url The url which possibly does have
519 * a missing scheme (a link to an image)
520 * @param string $scheme The url with a correct scheme
521 * (e.g. the url from the webpage which does contain the image)
523 * @return string The url with a scheme
525 private static function completeUrl($url, $scheme)
527 $urlarr = parse_url($url);
529 // If the url does allready have an scheme
530 // we can stop the process here
531 if (isset($urlarr["scheme"])) {
535 $schemearr = parse_url($scheme);
537 $complete = $schemearr["scheme"]."://".$schemearr["host"];
539 if (!empty($schemearr["port"])) {
540 $complete .= ":".$schemearr["port"];
543 if (!empty($urlarr["path"])) {
544 if (strpos($urlarr["path"], "/") !== 0) {
548 $complete .= $urlarr["path"];
551 if (!empty($urlarr["query"])) {
552 $complete .= "?".$urlarr["query"];
555 if (!empty($urlarr["fragment"])) {
556 $complete .= "#".$urlarr["fragment"];