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;
32 * Get information about a given URL
34 * Class with methods for extracting certain content from an url
39 * Maximum number of characters for the description
41 const MAX_DESC_COUNT = 250;
44 * Minimum number of characters for the description
46 const MIN_DESC_COUNT = 100;
49 * Search for chached embeddable data of an url otherwise fetch it
51 * @param string $url The url of the page which should be scraped
52 * @param bool $no_guessing If true the parse doens't search for
54 * @param bool $do_oembed The false option is used by the function fetch_oembed()
55 * to avoid endless loops
57 * @return array which contains needed data for embedding
58 * string 'url' => The url of the parsed page
59 * string 'type' => Content type
60 * string 'title' => (optional) The title of the content
61 * string 'text' => (optional) The description for the content
62 * string 'image' => (optional) A preview image of the content (only available if $no_geuessing = false)
63 * array 'images' => (optional) Array of preview pictures
64 * string 'keywords' => (optional) The tags which belong to the content
66 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
67 * @see ParseUrl::getSiteinfo() for more information about scraping
70 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true)
76 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
77 ['url' => Strings::normaliseLink($url), 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
79 if (!empty($parsed_url['content'])) {
80 $data = unserialize($parsed_url['content']);
84 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
89 'url' => substr(Strings::normaliseLink($url), 0, 255), 'guessing' => !$no_guessing,
90 'oembed' => $do_oembed, 'content' => serialize($data),
91 'created' => DateTimeFormat::utcNow()
100 * Parse a page for embeddable content information
102 * This method parses to url for meta data which can be used to embed
103 * the content. If available it prioritizes Open Graph meta tags.
104 * If this is not available it uses the twitter cards meta tags.
105 * As fallback it uses standard html elements with meta informations
106 * like \<title\>Awesome Title\</title\> or
107 * \<meta name="description" content="An awesome description"\>
109 * @param string $url The url of the page which should be scraped
110 * @param bool $no_guessing If true the parse doens't search for
112 * @param bool $do_oembed The false option is used by the function fetch_oembed()
113 * to avoid endless loops
114 * @param int $count Internal counter to avoid endless loops
116 * @return array which contains needed data for embedding
117 * string 'url' => The url of the parsed page
118 * string 'type' => Content type
119 * string 'title' => (optional) The title of the content
120 * string 'text' => (optional) The description for the content
121 * string 'image' => (optional) A preview image of the content (only available if $no_guessing = false)
122 * array 'images' => (optional) Array of preview pictures
123 * string 'keywords' => (optional) The tags which belong to the content
125 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
126 * @todo https://developers.google.com/+/plugins/snippet/
128 * <meta itemprop="name" content="Awesome title">
129 * <meta itemprop="description" content="An awesome description">
130 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
132 * <body itemscope itemtype="http://schema.org/Product">
133 * <h1 itemprop="name">Shiny Trinket</h1>
134 * <img itemprop="image" src="{image-url}" />
135 * <p itemprop="description">Shiny trinkets are shiny.</p>
139 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
141 // Check if the URL does contain a scheme
142 $scheme = parse_url($url, PHP_URL_SCHEME);
145 $url = 'http://' . ltrim($url, '/');
148 $url = trim($url, "'\"");
150 $url = Network::stripTrackingQueryParams($url);
158 Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
162 $curlResult = Network::curl($url);
163 if (!$curlResult->isSuccess()) {
167 // If the file is too large then exit
168 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
172 // If it isn't a HTML file then exit
173 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
177 $header = $curlResult->getHeader();
178 $body = $curlResult->getBody();
181 $oembed_data = OEmbed::fetchURL($url);
183 if (!empty($oembed_data->type)) {
184 if (!in_array($oembed_data->type, ['error', 'rich', ''])) {
185 $siteinfo['type'] = $oembed_data->type;
188 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
189 if ($siteinfo['type'] != 'photo') {
190 if (isset($oembed_data->title)) {
191 $siteinfo['title'] = trim($oembed_data->title);
193 if (isset($oembed_data->description)) {
194 $siteinfo['text'] = trim($oembed_data->description);
196 if (isset($oembed_data->thumbnail_url)) {
197 $siteinfo['image'] = $oembed_data->thumbnail_url;
203 // Fetch the first mentioned charset. Can be in body or header
205 if (preg_match('/charset=(.*?)[\'"\s\n]/', $header, $matches)) {
206 $charset = trim(trim(trim(array_pop($matches)), ';,'));
209 if ($charset && strtoupper($charset) != 'UTF-8') {
210 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
211 $charset = str_ireplace('latin-1', 'latin1', $charset);
213 Logger::log('detected charset ' . $charset, Logger::DEBUG);
214 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
217 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
219 $doc = new DOMDocument();
220 @$doc->loadHTML($body);
222 XML::deleteNode($doc, 'style');
223 XML::deleteNode($doc, 'script');
224 XML::deleteNode($doc, 'option');
225 XML::deleteNode($doc, 'h1');
226 XML::deleteNode($doc, 'h2');
227 XML::deleteNode($doc, 'h3');
228 XML::deleteNode($doc, 'h4');
229 XML::deleteNode($doc, 'h5');
230 XML::deleteNode($doc, 'h6');
231 XML::deleteNode($doc, 'ol');
232 XML::deleteNode($doc, 'ul');
234 $xpath = new DOMXPath($doc);
236 $list = $xpath->query('//meta[@content]');
237 foreach ($list as $node) {
239 if ($node->attributes->length) {
240 foreach ($node->attributes as $attribute) {
241 $meta_tag[$attribute->name] = $attribute->value;
245 if (@$meta_tag['http-equiv'] == 'refresh') {
246 $path = $meta_tag['content'];
247 $pathinfo = explode(';', $path);
249 foreach ($pathinfo as $value) {
250 if (substr(strtolower($value), 0, 4) == 'url=') {
251 $content = substr($value, 4);
254 if ($content != '') {
255 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
261 $list = $xpath->query('//title');
262 if ($list->length > 0) {
263 $siteinfo['title'] = trim($list->item(0)->nodeValue);
266 $list = $xpath->query('//meta[@name]');
267 foreach ($list as $node) {
269 if ($node->attributes->length) {
270 foreach ($node->attributes as $attribute) {
271 $meta_tag[$attribute->name] = $attribute->value;
275 if (empty($meta_tag['content'])) {
279 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
281 switch (strtolower($meta_tag['name'])) {
283 $siteinfo['title'] = trim($meta_tag['content']);
286 $siteinfo['text'] = trim($meta_tag['content']);
289 $siteinfo['image'] = $meta_tag['content'];
291 case 'twitter:image':
292 $siteinfo['image'] = $meta_tag['content'];
294 case 'twitter:image:src':
295 $siteinfo['image'] = $meta_tag['content'];
298 // Detect photo pages
299 if ($meta_tag['content'] == 'summary_large_image') {
300 $siteinfo['type'] = 'photo';
303 case 'twitter:description':
304 $siteinfo['text'] = trim($meta_tag['content']);
306 case 'twitter:title':
307 $siteinfo['title'] = trim($meta_tag['content']);
310 $siteinfo['title'] = trim($meta_tag['content']);
312 case 'dc.description':
313 $siteinfo['text'] = trim($meta_tag['content']);
316 $keywords = explode(',', $meta_tag['content']);
318 case 'news_keywords':
319 $keywords = explode(',', $meta_tag['content']);
324 if (isset($keywords)) {
325 $siteinfo['keywords'] = [];
326 foreach ($keywords as $keyword) {
327 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
328 $siteinfo['keywords'][] = trim($keyword);
333 $list = $xpath->query('//meta[@property]');
334 foreach ($list as $node) {
336 if ($node->attributes->length) {
337 foreach ($node->attributes as $attribute) {
338 $meta_tag[$attribute->name] = $attribute->value;
342 if (!empty($meta_tag['content'])) {
343 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
345 switch (strtolower($meta_tag['property'])) {
347 $siteinfo['image'] = $meta_tag['content'];
350 $siteinfo['title'] = trim($meta_tag['content']);
352 case 'og:description':
353 $siteinfo['text'] = trim($meta_tag['content']);
359 // Prevent to have a photo type without an image
360 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
361 $siteinfo['type'] = 'link';
364 if (!empty($siteinfo['image'])) {
365 $src = self::completeUrl($siteinfo['image'], $url);
367 unset($siteinfo['image']);
369 $photodata = Images::getInfoFromURLCached($src);
371 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
372 $siteinfo['images'][] = ['src' => $src,
373 'width' => $photodata[0],
374 'height' => $photodata[1]];
378 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
379 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
380 $pos = mb_strrpos($siteinfo['text'], '.');
381 if ($pos > self::MIN_DESC_COUNT) {
382 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
386 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
388 Hook::callAll('getsiteinfo', $siteinfo);
394 * Convert tags from CSV to an array
396 * @param string $string Tags
397 * @return array with formatted Hashtags
399 public static function convertTagsToArray($string)
401 $arr_tags = str_getcsv($string);
402 if (count($arr_tags)) {
403 // add the # sign to every tag
404 array_walk($arr_tags, ["self", "arrAddHashes"]);
411 * Add a hasht sign to a string
413 * This method is used as callback function
415 * @param string $tag The pure tag name
416 * @param int $k Counter for internal use
419 private static function arrAddHashes(&$tag, $k)
425 * Add a scheme to an url
427 * The src attribute of some html elements (e.g. images)
428 * can miss the scheme so we need to add the correct
431 * @param string $url The url which possibly does have
432 * a missing scheme (a link to an image)
433 * @param string $scheme The url with a correct scheme
434 * (e.g. the url from the webpage which does contain the image)
436 * @return string The url with a scheme
438 private static function completeUrl($url, $scheme)
440 $urlarr = parse_url($url);
442 // If the url does allready have an scheme
443 // we can stop the process here
444 if (isset($urlarr["scheme"])) {
448 $schemearr = parse_url($scheme);
450 $complete = $schemearr["scheme"]."://".$schemearr["host"];
452 if (!empty($schemearr["port"])) {
453 $complete .= ":".$schemearr["port"];
456 if (!empty($urlarr["path"])) {
457 if (strpos($urlarr["path"], "/") !== 0) {
461 $complete .= $urlarr["path"];
464 if (!empty($urlarr["query"])) {
465 $complete .= "?".$urlarr["query"];
468 if (!empty($urlarr["fragment"])) {
469 $complete .= "#".$urlarr["fragment"];