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;
205 // Look for a charset, first in headers
206 // Expected form: Content-Type: text/html; charset=ISO-8859-4
207 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $header, $matches)) {
208 $charset = trim(trim(trim(array_pop($matches)), ';,'));
211 // Then in body that gets precedence
213 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
214 // - <meta charset="utf-8">
215 // - <meta charset=utf-8>
216 // - <meta charSet="utf-8">
217 // We escape <style> and <script> tags since they can contain irrelevant charset information
218 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
219 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
220 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
221 $charset = trim(trim(trim(array_pop($matches)), ';,'));
225 $siteinfo['charset'] = $charset;
227 if ($charset && strtoupper($charset) != 'UTF-8') {
228 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
229 $charset = str_ireplace('latin-1', 'latin1', $charset);
231 Logger::log('detected charset ' . $charset, Logger::DEBUG);
232 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
235 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
237 $doc = new DOMDocument();
238 @$doc->loadHTML($body);
240 XML::deleteNode($doc, 'style');
241 XML::deleteNode($doc, 'script');
242 XML::deleteNode($doc, 'option');
243 XML::deleteNode($doc, 'h1');
244 XML::deleteNode($doc, 'h2');
245 XML::deleteNode($doc, 'h3');
246 XML::deleteNode($doc, 'h4');
247 XML::deleteNode($doc, 'h5');
248 XML::deleteNode($doc, 'h6');
249 XML::deleteNode($doc, 'ol');
250 XML::deleteNode($doc, 'ul');
252 $xpath = new DOMXPath($doc);
254 $list = $xpath->query('//meta[@content]');
255 foreach ($list as $node) {
257 if ($node->attributes->length) {
258 foreach ($node->attributes as $attribute) {
259 $meta_tag[$attribute->name] = $attribute->value;
263 if (@$meta_tag['http-equiv'] == 'refresh') {
264 $path = $meta_tag['content'];
265 $pathinfo = explode(';', $path);
267 foreach ($pathinfo as $value) {
268 if (substr(strtolower($value), 0, 4) == 'url=') {
269 $content = substr($value, 4);
272 if ($content != '') {
273 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
279 $list = $xpath->query('//title');
280 if ($list->length > 0) {
281 $siteinfo['title'] = trim($list->item(0)->nodeValue);
284 $list = $xpath->query('//meta[@name]');
285 foreach ($list as $node) {
287 if ($node->attributes->length) {
288 foreach ($node->attributes as $attribute) {
289 $meta_tag[$attribute->name] = $attribute->value;
293 if (empty($meta_tag['content'])) {
297 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
299 switch (strtolower($meta_tag['name'])) {
301 $siteinfo['title'] = trim($meta_tag['content']);
304 $siteinfo['text'] = trim($meta_tag['content']);
307 $siteinfo['image'] = $meta_tag['content'];
309 case 'twitter:image':
310 $siteinfo['image'] = $meta_tag['content'];
312 case 'twitter:image:src':
313 $siteinfo['image'] = $meta_tag['content'];
316 // Detect photo pages
317 if ($meta_tag['content'] == 'summary_large_image') {
318 $siteinfo['type'] = 'photo';
321 case 'twitter:description':
322 $siteinfo['text'] = trim($meta_tag['content']);
324 case 'twitter:title':
325 $siteinfo['title'] = trim($meta_tag['content']);
328 $siteinfo['title'] = trim($meta_tag['content']);
330 case 'dc.description':
331 $siteinfo['text'] = trim($meta_tag['content']);
334 $keywords = explode(',', $meta_tag['content']);
336 case 'news_keywords':
337 $keywords = explode(',', $meta_tag['content']);
342 if (isset($keywords)) {
343 $siteinfo['keywords'] = [];
344 foreach ($keywords as $keyword) {
345 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
346 $siteinfo['keywords'][] = trim($keyword);
351 $list = $xpath->query('//meta[@property]');
352 foreach ($list as $node) {
354 if ($node->attributes->length) {
355 foreach ($node->attributes as $attribute) {
356 $meta_tag[$attribute->name] = $attribute->value;
360 if (!empty($meta_tag['content'])) {
361 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
363 switch (strtolower($meta_tag['property'])) {
365 $siteinfo['image'] = $meta_tag['content'];
368 $siteinfo['title'] = trim($meta_tag['content']);
370 case 'og:description':
371 $siteinfo['text'] = trim($meta_tag['content']);
377 // Prevent to have a photo type without an image
378 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
379 $siteinfo['type'] = 'link';
382 if (!empty($siteinfo['image'])) {
383 $src = self::completeUrl($siteinfo['image'], $url);
385 unset($siteinfo['image']);
387 $photodata = Images::getInfoFromURLCached($src);
389 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
390 $siteinfo['images'][] = ['src' => $src,
391 'width' => $photodata[0],
392 'height' => $photodata[1]];
396 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
397 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
398 $pos = mb_strrpos($siteinfo['text'], '.');
399 if ($pos > self::MIN_DESC_COUNT) {
400 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
404 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
406 Hook::callAll('getsiteinfo', $siteinfo);
412 * Convert tags from CSV to an array
414 * @param string $string Tags
415 * @return array with formatted Hashtags
417 public static function convertTagsToArray($string)
419 $arr_tags = str_getcsv($string);
420 if (count($arr_tags)) {
421 // add the # sign to every tag
422 array_walk($arr_tags, ["self", "arrAddHashes"]);
429 * Add a hasht sign to a string
431 * This method is used as callback function
433 * @param string $tag The pure tag name
434 * @param int $k Counter for internal use
437 private static function arrAddHashes(&$tag, $k)
443 * Add a scheme to an url
445 * The src attribute of some html elements (e.g. images)
446 * can miss the scheme so we need to add the correct
449 * @param string $url The url which possibly does have
450 * a missing scheme (a link to an image)
451 * @param string $scheme The url with a correct scheme
452 * (e.g. the url from the webpage which does contain the image)
454 * @return string The url with a scheme
456 private static function completeUrl($url, $scheme)
458 $urlarr = parse_url($url);
460 // If the url does allready have an scheme
461 // we can stop the process here
462 if (isset($urlarr["scheme"])) {
466 $schemearr = parse_url($scheme);
468 $complete = $schemearr["scheme"]."://".$schemearr["host"];
470 if (!empty($schemearr["port"])) {
471 $complete .= ":".$schemearr["port"];
474 if (!empty($urlarr["path"])) {
475 if (strpos($urlarr["path"], "/") !== 0) {
479 $complete .= $urlarr["path"];
482 if (!empty($urlarr["query"])) {
483 $complete .= "?".$urlarr["query"];
486 if (!empty($urlarr["fragment"])) {
487 $complete .= "#".$urlarr["fragment"];