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;
34 * Get information about a given URL
36 * Class with methods for extracting certain content from an url
41 * Maximum number of characters for the description
43 const MAX_DESC_COUNT = 250;
46 * Minimum number of characters for the description
48 const MIN_DESC_COUNT = 100;
51 * Search for chached embeddable data of an url otherwise fetch it
53 * @param string $url The url of the page which should be scraped
54 * @param bool $no_guessing If true the parse doens't search for
56 * @param bool $do_oembed The false option is used by the function fetch_oembed()
57 * to avoid endless loops
59 * @return array which contains needed data for embedding
60 * string 'url' => The url of the parsed page
61 * string 'type' => Content type
62 * string 'title' => (optional) The title of the content
63 * string 'text' => (optional) The description for the content
64 * string 'image' => (optional) A preview image of the content (only available if $no_geuessing = false)
65 * array 'images' => (optional) Array of preview pictures
66 * string 'keywords' => (optional) The tags which belong to the content
68 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
69 * @see ParseUrl::getSiteinfo() for more information about scraping
72 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true)
78 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
79 ['url' => Strings::normaliseLink($url), 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
81 if (!empty($parsed_url['content'])) {
82 $data = unserialize($parsed_url['content']);
86 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
91 'url' => substr(Strings::normaliseLink($url), 0, 255), 'guessing' => !$no_guessing,
92 'oembed' => $do_oembed, 'content' => serialize($data),
93 'created' => DateTimeFormat::utcNow()
95 Database::INSERT_UPDATE
102 * Parse a page for embeddable content information
104 * This method parses to url for meta data which can be used to embed
105 * the content. If available it prioritizes Open Graph meta tags.
106 * If this is not available it uses the twitter cards meta tags.
107 * As fallback it uses standard html elements with meta informations
108 * like \<title\>Awesome Title\</title\> or
109 * \<meta name="description" content="An awesome description"\>
111 * @param string $url The url of the page which should be scraped
112 * @param bool $no_guessing If true the parse doens't search for
114 * @param bool $do_oembed The false option is used by the function fetch_oembed()
115 * to avoid endless loops
116 * @param int $count Internal counter to avoid endless loops
118 * @return array which contains needed data for embedding
119 * string 'url' => The url of the parsed page
120 * string 'type' => Content type
121 * string 'title' => (optional) The title of the content
122 * string 'text' => (optional) The description for the content
123 * string 'image' => (optional) A preview image of the content (only available if $no_guessing = false)
124 * array 'images' => (optional) Array of preview pictures
125 * string 'keywords' => (optional) The tags which belong to the content
127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
128 * @todo https://developers.google.com/+/plugins/snippet/
130 * <meta itemprop="name" content="Awesome title">
131 * <meta itemprop="description" content="An awesome description">
132 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
134 * <body itemscope itemtype="http://schema.org/Product">
135 * <h1 itemprop="name">Shiny Trinket</h1>
136 * <img itemprop="image" src="{image-url}" />
137 * <p itemprop="description">Shiny trinkets are shiny.</p>
141 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
143 // Check if the URL does contain a scheme
144 $scheme = parse_url($url, PHP_URL_SCHEME);
147 $url = 'http://' . ltrim($url, '/');
150 $url = trim($url, "'\"");
152 $url = Network::stripTrackingQueryParams($url);
160 Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
164 $curlResult = DI::httpRequest()->get($url);
165 if (!$curlResult->isSuccess()) {
169 // If the file is too large then exit
170 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
174 // If it isn't a HTML file then exit
175 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
179 $header = $curlResult->getHeader();
180 $body = $curlResult->getBody();
183 $oembed_data = OEmbed::fetchURL($url);
185 if (!empty($oembed_data->type)) {
186 if (!in_array($oembed_data->type, ['error', 'rich', ''])) {
187 $siteinfo['type'] = $oembed_data->type;
190 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
191 if ($siteinfo['type'] != 'photo') {
192 if (isset($oembed_data->title)) {
193 $siteinfo['title'] = trim($oembed_data->title);
195 if (isset($oembed_data->description)) {
196 $siteinfo['text'] = trim($oembed_data->description);
198 if (isset($oembed_data->thumbnail_url)) {
199 $siteinfo['image'] = $oembed_data->thumbnail_url;
206 // Look for a charset, first in headers
207 // Expected form: Content-Type: text/html; charset=ISO-8859-4
208 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $header, $matches)) {
209 $charset = trim(trim(trim(array_pop($matches)), ';,'));
212 // Then in body that gets precedence
214 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
215 // - <meta charset="utf-8">
216 // - <meta charset=utf-8>
217 // - <meta charSet="utf-8">
218 // We escape <style> and <script> tags since they can contain irrelevant charset information
219 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
220 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
221 if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
222 $charset = trim(trim(trim(array_pop($matches)), ';,'));
226 $siteinfo['charset'] = $charset;
228 if ($charset && strtoupper($charset) != 'UTF-8') {
229 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
230 $charset = str_ireplace('latin-1', 'latin1', $charset);
232 Logger::log('detected charset ' . $charset, Logger::DEBUG);
233 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
236 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
238 $doc = new DOMDocument();
239 @$doc->loadHTML($body);
241 XML::deleteNode($doc, 'style');
242 XML::deleteNode($doc, 'script');
243 XML::deleteNode($doc, 'option');
244 XML::deleteNode($doc, 'h1');
245 XML::deleteNode($doc, 'h2');
246 XML::deleteNode($doc, 'h3');
247 XML::deleteNode($doc, 'h4');
248 XML::deleteNode($doc, 'h5');
249 XML::deleteNode($doc, 'h6');
250 XML::deleteNode($doc, 'ol');
251 XML::deleteNode($doc, 'ul');
253 $xpath = new DOMXPath($doc);
255 $list = $xpath->query('//meta[@content]');
256 foreach ($list as $node) {
258 if ($node->attributes->length) {
259 foreach ($node->attributes as $attribute) {
260 $meta_tag[$attribute->name] = $attribute->value;
264 if (@$meta_tag['http-equiv'] == 'refresh') {
265 $path = $meta_tag['content'];
266 $pathinfo = explode(';', $path);
268 foreach ($pathinfo as $value) {
269 if (substr(strtolower($value), 0, 4) == 'url=') {
270 $content = substr($value, 4);
273 if ($content != '') {
274 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
280 $list = $xpath->query('//title');
281 if ($list->length > 0) {
282 $siteinfo['title'] = trim($list->item(0)->nodeValue);
285 $list = $xpath->query('//meta[@name]');
286 foreach ($list as $node) {
288 if ($node->attributes->length) {
289 foreach ($node->attributes as $attribute) {
290 $meta_tag[$attribute->name] = $attribute->value;
294 if (empty($meta_tag['content'])) {
298 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
300 switch (strtolower($meta_tag['name'])) {
302 $siteinfo['title'] = trim($meta_tag['content']);
305 $siteinfo['text'] = trim($meta_tag['content']);
308 $siteinfo['image'] = $meta_tag['content'];
310 case 'twitter:image':
311 $siteinfo['image'] = $meta_tag['content'];
313 case 'twitter:image:src':
314 $siteinfo['image'] = $meta_tag['content'];
317 // Detect photo pages
318 if ($meta_tag['content'] == 'summary_large_image') {
319 $siteinfo['type'] = 'photo';
322 case 'twitter:description':
323 $siteinfo['text'] = trim($meta_tag['content']);
325 case 'twitter:title':
326 $siteinfo['title'] = trim($meta_tag['content']);
329 $siteinfo['title'] = trim($meta_tag['content']);
331 case 'dc.description':
332 $siteinfo['text'] = trim($meta_tag['content']);
335 $keywords = explode(',', $meta_tag['content']);
337 case 'news_keywords':
338 $keywords = explode(',', $meta_tag['content']);
343 if (isset($keywords)) {
344 $siteinfo['keywords'] = [];
345 foreach ($keywords as $keyword) {
346 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
347 $siteinfo['keywords'][] = trim($keyword);
352 $list = $xpath->query('//meta[@property]');
353 foreach ($list as $node) {
355 if ($node->attributes->length) {
356 foreach ($node->attributes as $attribute) {
357 $meta_tag[$attribute->name] = $attribute->value;
361 if (!empty($meta_tag['content'])) {
362 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
364 switch (strtolower($meta_tag['property'])) {
366 $siteinfo['image'] = $meta_tag['content'];
369 $siteinfo['title'] = trim($meta_tag['content']);
371 case 'og:description':
372 $siteinfo['text'] = trim($meta_tag['content']);
378 // Prevent to have a photo type without an image
379 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
380 $siteinfo['type'] = 'link';
383 if (!empty($siteinfo['image'])) {
384 $src = self::completeUrl($siteinfo['image'], $url);
386 unset($siteinfo['image']);
388 $photodata = Images::getInfoFromURLCached($src);
390 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
391 $siteinfo['images'][] = ['src' => $src,
392 'width' => $photodata[0],
393 'height' => $photodata[1]];
397 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
398 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
399 $pos = mb_strrpos($siteinfo['text'], '.');
400 if ($pos > self::MIN_DESC_COUNT) {
401 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
405 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
407 Hook::callAll('getsiteinfo', $siteinfo);
413 * Convert tags from CSV to an array
415 * @param string $string Tags
416 * @return array with formatted Hashtags
418 public static function convertTagsToArray($string)
420 $arr_tags = str_getcsv($string);
421 if (count($arr_tags)) {
422 // add the # sign to every tag
423 array_walk($arr_tags, ["self", "arrAddHashes"]);
430 * Add a hasht sign to a string
432 * This method is used as callback function
434 * @param string $tag The pure tag name
435 * @param int $k Counter for internal use
438 private static function arrAddHashes(&$tag, $k)
444 * Add a scheme to an url
446 * The src attribute of some html elements (e.g. images)
447 * can miss the scheme so we need to add the correct
450 * @param string $url The url which possibly does have
451 * a missing scheme (a link to an image)
452 * @param string $scheme The url with a correct scheme
453 * (e.g. the url from the webpage which does contain the image)
455 * @return string The url with a scheme
457 private static function completeUrl($url, $scheme)
459 $urlarr = parse_url($url);
461 // If the url does allready have an scheme
462 // we can stop the process here
463 if (isset($urlarr["scheme"])) {
467 $schemearr = parse_url($scheme);
469 $complete = $schemearr["scheme"]."://".$schemearr["host"];
471 if (!empty($schemearr["port"])) {
472 $complete .= ":".$schemearr["port"];
475 if (!empty($urlarr["path"])) {
476 if (strpos($urlarr["path"], "/") !== 0) {
480 $complete .= $urlarr["path"];
483 if (!empty($urlarr["query"])) {
484 $complete .= "?".$urlarr["query"];
487 if (!empty($urlarr["fragment"])) {
488 $complete .= "#".$urlarr["fragment"];