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 array 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 return explode('/', current(explode(';', $contenttype)));
75 * Search for chached embeddable data of an url otherwise fetch it
77 * @param string $url The url of the page which should be scraped
78 * @param bool $no_guessing If true the parse doens't search for
80 * @param bool $do_oembed The false option is used by the function fetch_oembed()
81 * to avoid endless loops
83 * @return array which contains needed data for embedding
84 * string 'url' => The url of the parsed page
85 * string 'type' => Content type
86 * string 'title' => (optional) The title of the content
87 * string 'text' => (optional) The description for the content
88 * string 'image' => (optional) A preview image of the content (only available if $no_geuessing = false)
89 * array 'images' => (optional) Array of preview pictures
90 * string 'keywords' => (optional) The tags which belong to the content
92 * @throws HTTPException\InternalServerErrorException
93 * @see ParseUrl::getSiteinfo() for more information about scraping
96 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true): array
105 $urlHash = hash('sha256', $url);
107 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
108 ['url_hash' => $urlHash, 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
110 if (!empty($parsed_url['content'])) {
111 $data = unserialize($parsed_url['content']);
115 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
117 $expires = $data['expires'];
119 unset($data['expires']);
124 'url_hash' => $urlHash,
125 'guessing' => !$no_guessing,
126 'oembed' => $do_oembed,
128 'content' => serialize($data),
129 'created' => DateTimeFormat::utcNow(),
130 'expires' => $expires,
132 Database::INSERT_UPDATE
139 * Parse a page for embeddable content information
141 * This method parses to url for meta data which can be used to embed
142 * the content. If available it prioritizes Open Graph meta tags.
143 * If this is not available it uses the twitter cards meta tags.
144 * As fallback it uses standard html elements with meta informations
145 * like \<title\>Awesome Title\</title\> or
146 * \<meta name="description" content="An awesome description"\>
148 * @param string $url The url of the page which should be scraped
149 * @param bool $no_guessing If true the parse doens't search for
151 * @param bool $do_oembed The false option is used by the function fetch_oembed()
152 * to avoid endless loops
153 * @param int $count Internal counter to avoid endless loops
155 * @return array which contains needed data for embedding
156 * string 'url' => The url of the parsed page
157 * string 'type' => Content type (error, link, photo, image, audio, video)
158 * string 'title' => (optional) The title of the content
159 * string 'text' => (optional) The description for the content
160 * string 'image' => (optional) A preview image of the content (only available if $no_guessing = false)
161 * array 'images' => (optional) Array of preview pictures
162 * string 'keywords' => (optional) The tags which belong to the content
164 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
165 * @todo https://developers.google.com/+/plugins/snippet/
167 * <meta itemprop="name" content="Awesome title">
168 * <meta itemprop="description" content="An awesome description">
169 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
171 * <body itemscope itemtype="http://schema.org/Product">
172 * <h1 itemprop="name">Shiny Trinket</h1>
173 * <img itemprop="image" src="{image-url}" />
174 * <p itemprop="description">Shiny trinkets are shiny.</p>
178 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
187 // Check if the URL does contain a scheme
188 $scheme = parse_url($url, PHP_URL_SCHEME);
191 $url = 'http://' . ltrim($url, '/');
194 $url = trim($url, "'\"");
196 $url = Network::stripTrackingQueryParams($url);
201 'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE),
205 Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
209 $type = self::getContentType($url);
210 Logger::info('Got content-type', ['content-type' => $type, 'url' => $url]);
211 if (!empty($type) && in_array($type[0], ['image', 'video', 'audio'])) {
212 $siteinfo['type'] = $type[0];
216 if ((count($type) >= 2) && (($type[0] != 'text') || ($type[1] != 'html'))) {
217 Logger::info('Unparseable content-type, quitting here, ', ['content-type' => $type, 'url' => $url]);
221 $curlResult = DI::httpRequest()->get($url);
222 if (!$curlResult->isSuccess()) {
226 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
228 // If the file is too large then exit
229 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
233 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')) {
234 if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
235 $maxAge = max(86400, (int)array_pop($matches));
236 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
240 $header = $curlResult->getHeader();
241 $body = $curlResult->getBody();
244 $oembed_data = OEmbed::fetchURL($url);
246 if (!empty($oembed_data->type)) {
247 if (!in_array($oembed_data->type, ['error', 'rich', 'image', 'video', 'audio', ''])) {
248 $siteinfo['type'] = $oembed_data->type;
251 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
252 if ($siteinfo['type'] != 'photo') {
253 if (isset($oembed_data->title)) {
254 $siteinfo['title'] = trim($oembed_data->title);
256 if (isset($oembed_data->description)) {
257 $siteinfo['text'] = trim($oembed_data->description);
259 if (isset($oembed_data->thumbnail_url)) {
260 $siteinfo['image'] = $oembed_data->thumbnail_url;
267 // Look for a charset, first in headers
268 // Expected form: Content-Type: text/html; charset=ISO-8859-4
269 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $header, $matches)) {
270 $charset = trim(trim(trim(array_pop($matches)), ';,'));
273 // Then in body that gets precedence
275 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
276 // - <meta charset="utf-8">
277 // - <meta charset=utf-8>
278 // - <meta charSet="utf-8">
279 // We escape <style> and <script> tags since they can contain irrelevant charset information
280 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
281 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
282 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
283 $charset = trim(trim(trim(array_pop($matches)), ';,'));
287 $siteinfo['charset'] = $charset;
289 if ($charset && strtoupper($charset) != 'UTF-8') {
290 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
291 $charset = str_ireplace('latin-1', 'latin1', $charset);
293 Logger::log('detected charset ' . $charset, Logger::DEBUG);
294 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
297 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
299 $doc = new DOMDocument();
300 @$doc->loadHTML($body);
302 XML::deleteNode($doc, 'style');
303 XML::deleteNode($doc, 'script');
304 XML::deleteNode($doc, 'option');
305 XML::deleteNode($doc, 'h1');
306 XML::deleteNode($doc, 'h2');
307 XML::deleteNode($doc, 'h3');
308 XML::deleteNode($doc, 'h4');
309 XML::deleteNode($doc, 'h5');
310 XML::deleteNode($doc, 'h6');
311 XML::deleteNode($doc, 'ol');
312 XML::deleteNode($doc, 'ul');
314 $xpath = new DOMXPath($doc);
316 $list = $xpath->query('//meta[@content]');
317 foreach ($list as $node) {
319 if ($node->attributes->length) {
320 foreach ($node->attributes as $attribute) {
321 $meta_tag[$attribute->name] = $attribute->value;
325 if (@$meta_tag['http-equiv'] == 'refresh') {
326 $path = $meta_tag['content'];
327 $pathinfo = explode(';', $path);
329 foreach ($pathinfo as $value) {
330 if (substr(strtolower($value), 0, 4) == 'url=') {
331 $content = substr($value, 4);
334 if ($content != '') {
335 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
341 $list = $xpath->query('//title');
342 if ($list->length > 0) {
343 $siteinfo['title'] = trim($list->item(0)->nodeValue);
346 $list = $xpath->query('//meta[@name]');
347 foreach ($list as $node) {
349 if ($node->attributes->length) {
350 foreach ($node->attributes as $attribute) {
351 $meta_tag[$attribute->name] = $attribute->value;
355 if (empty($meta_tag['content'])) {
359 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
361 switch (strtolower($meta_tag['name'])) {
363 $siteinfo['title'] = trim($meta_tag['content']);
366 $siteinfo['text'] = trim($meta_tag['content']);
369 $siteinfo['image'] = $meta_tag['content'];
371 case 'twitter:image':
372 $siteinfo['image'] = $meta_tag['content'];
374 case 'twitter:image:src':
375 $siteinfo['image'] = $meta_tag['content'];
378 // Detect photo pages
379 if ($meta_tag['content'] == 'summary_large_image') {
380 $siteinfo['type'] = 'photo';
383 case 'twitter:description':
384 $siteinfo['text'] = trim($meta_tag['content']);
386 case 'twitter:title':
387 $siteinfo['title'] = trim($meta_tag['content']);
390 $siteinfo['title'] = trim($meta_tag['content']);
392 case 'dc.description':
393 $siteinfo['text'] = trim($meta_tag['content']);
396 $keywords = explode(',', $meta_tag['content']);
398 case 'news_keywords':
399 $keywords = explode(',', $meta_tag['content']);
404 if (isset($keywords)) {
405 $siteinfo['keywords'] = [];
406 foreach ($keywords as $keyword) {
407 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
408 $siteinfo['keywords'][] = trim($keyword);
413 $list = $xpath->query('//meta[@property]');
414 foreach ($list as $node) {
416 if ($node->attributes->length) {
417 foreach ($node->attributes as $attribute) {
418 $meta_tag[$attribute->name] = $attribute->value;
422 if (!empty($meta_tag['content'])) {
423 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
425 switch (strtolower($meta_tag['property'])) {
427 $siteinfo['image'] = $meta_tag['content'];
430 $siteinfo['title'] = trim($meta_tag['content']);
432 case 'og:description':
433 $siteinfo['text'] = trim($meta_tag['content']);
439 // Prevent to have a photo type without an image
440 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
441 $siteinfo['type'] = 'link';
444 if (!empty($siteinfo['image'])) {
445 $src = self::completeUrl($siteinfo['image'], $url);
447 unset($siteinfo['image']);
449 $photodata = Images::getInfoFromURLCached($src);
451 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
452 $siteinfo['images'][] = ['src' => $src,
453 'width' => $photodata[0],
454 'height' => $photodata[1]];
458 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
459 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
460 $pos = mb_strrpos($siteinfo['text'], '.');
461 if ($pos > self::MIN_DESC_COUNT) {
462 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
466 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
468 Hook::callAll('getsiteinfo', $siteinfo);
474 * Convert tags from CSV to an array
476 * @param string $string Tags
477 * @return array with formatted Hashtags
479 public static function convertTagsToArray($string)
481 $arr_tags = str_getcsv($string);
482 if (count($arr_tags)) {
483 // add the # sign to every tag
484 array_walk($arr_tags, ["self", "arrAddHashes"]);
491 * Add a hasht sign to a string
493 * This method is used as callback function
495 * @param string $tag The pure tag name
496 * @param int $k Counter for internal use
499 private static function arrAddHashes(&$tag, $k)
505 * Add a scheme to an url
507 * The src attribute of some html elements (e.g. images)
508 * can miss the scheme so we need to add the correct
511 * @param string $url The url which possibly does have
512 * a missing scheme (a link to an image)
513 * @param string $scheme The url with a correct scheme
514 * (e.g. the url from the webpage which does contain the image)
516 * @return string The url with a scheme
518 private static function completeUrl($url, $scheme)
520 $urlarr = parse_url($url);
522 // If the url does allready have an scheme
523 // we can stop the process here
524 if (isset($urlarr["scheme"])) {
528 $schemearr = parse_url($scheme);
530 $complete = $schemearr["scheme"]."://".$schemearr["host"];
532 if (!empty($schemearr["port"])) {
533 $complete .= ":".$schemearr["port"];
536 if (!empty($urlarr["path"])) {
537 if (strpos($urlarr["path"], "/") !== 0) {
541 $complete .= $urlarr["path"];
544 if (!empty($urlarr["query"])) {
545 $complete .= "?".$urlarr["query"];
548 if (!empty($urlarr["fragment"])) {
549 $complete .= "#".$urlarr["fragment"];