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' => The title of the content
61 * string 'text' => The description for the content
62 * string 'image' => A preview image of the content (only available
63 * if $no_geuessing = false
64 * array'images' = Array of preview pictures
65 * string 'keywords' => 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' => Strings::normaliseLink($url), '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' => The title of the content
121 * string 'text' => The description for the content
122 * string 'image' => A preview image of the content (only available
123 * if $no_geuessing = false
124 * array'images' = Array of preview pictures
125 * string 'keywords' => 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)
145 // Check if the URL does contain a scheme
146 $scheme = parse_url($url, PHP_URL_SCHEME);
149 $url = 'http://' . trim($url, '/');
153 Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
157 $url = trim($url, "'");
158 $url = trim($url, '"');
160 $url = Network::stripTrackingQueryParams($url);
162 $siteinfo['url'] = $url;
163 $siteinfo['type'] = 'link';
165 $curlResult = Network::curl($url);
166 if (!$curlResult->isSuccess()) {
170 // If the file is too large then exit
171 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
175 // If it isn't a HTML file then exit
176 if (($curlResult->getContentType() != '') && !strstr(strtolower($curlResult->getContentType()), 'html')) {
180 $header = $curlResult->getHeader();
181 $body = $curlResult->getBody();
184 $oembed_data = OEmbed::fetchURL($url);
186 if (!empty($oembed_data->type)) {
187 if (!in_array($oembed_data->type, ['error', 'rich', ''])) {
188 $siteinfo['type'] = $oembed_data->type;
191 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
192 if ($siteinfo['type'] != 'photo') {
193 if (isset($oembed_data->title)) {
194 $siteinfo['title'] = trim($oembed_data->title);
196 if (isset($oembed_data->description)) {
197 $siteinfo['text'] = trim($oembed_data->description);
199 if (isset($oembed_data->thumbnail_url)) {
200 $siteinfo['image'] = $oembed_data->thumbnail_url;
206 // Fetch the first mentioned charset. Can be in body or header
208 if (preg_match('/charset=(.*?)[\'"\s\n]/', $header, $matches)) {
209 $charset = trim(trim(trim(array_pop($matches)), ';,'));
212 if ($charset && strtoupper($charset) != 'UTF-8') {
213 // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
214 $charset = str_ireplace('latin-1', 'latin1', $charset);
216 Logger::log('detected charset ' . $charset, Logger::DEBUG);
217 $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
220 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
222 $doc = new DOMDocument();
223 @$doc->loadHTML($body);
225 XML::deleteNode($doc, 'style');
226 XML::deleteNode($doc, 'script');
227 XML::deleteNode($doc, 'option');
228 XML::deleteNode($doc, 'h1');
229 XML::deleteNode($doc, 'h2');
230 XML::deleteNode($doc, 'h3');
231 XML::deleteNode($doc, 'h4');
232 XML::deleteNode($doc, 'h5');
233 XML::deleteNode($doc, 'h6');
234 XML::deleteNode($doc, 'ol');
235 XML::deleteNode($doc, 'ul');
237 $xpath = new DOMXPath($doc);
239 $list = $xpath->query('//meta[@content]');
240 foreach ($list as $node) {
242 if ($node->attributes->length) {
243 foreach ($node->attributes as $attribute) {
244 $meta_tag[$attribute->name] = $attribute->value;
248 if (@$meta_tag['http-equiv'] == 'refresh') {
249 $path = $meta_tag['content'];
250 $pathinfo = explode(';', $path);
252 foreach ($pathinfo as $value) {
253 if (substr(strtolower($value), 0, 4) == 'url=') {
254 $content = substr($value, 4);
257 if ($content != '') {
258 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
264 $list = $xpath->query('//title');
265 if ($list->length > 0) {
266 $siteinfo['title'] = trim($list->item(0)->nodeValue);
269 $list = $xpath->query('//meta[@name]');
270 foreach ($list as $node) {
272 if ($node->attributes->length) {
273 foreach ($node->attributes as $attribute) {
274 $meta_tag[$attribute->name] = $attribute->value;
278 if (empty($meta_tag['content'])) {
282 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
284 switch (strtolower($meta_tag['name'])) {
286 $siteinfo['title'] = trim($meta_tag['content']);
289 $siteinfo['text'] = trim($meta_tag['content']);
292 $siteinfo['image'] = $meta_tag['content'];
294 case 'twitter:image':
295 $siteinfo['image'] = $meta_tag['content'];
297 case 'twitter:image:src':
298 $siteinfo['image'] = $meta_tag['content'];
301 // Detect photo pages
302 if ($meta_tag['content'] == 'summary_large_image') {
303 $siteinfo['type'] = 'photo';
306 case 'twitter:description':
307 $siteinfo['text'] = trim($meta_tag['content']);
309 case 'twitter:title':
310 $siteinfo['title'] = trim($meta_tag['content']);
313 $siteinfo['title'] = trim($meta_tag['content']);
315 case 'dc.description':
316 $siteinfo['text'] = trim($meta_tag['content']);
319 $keywords = explode(',', $meta_tag['content']);
321 case 'news_keywords':
322 $keywords = explode(',', $meta_tag['content']);
327 if (isset($keywords)) {
328 $siteinfo['keywords'] = [];
329 foreach ($keywords as $keyword) {
330 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
331 $siteinfo['keywords'][] = trim($keyword);
336 $list = $xpath->query('//meta[@property]');
337 foreach ($list as $node) {
339 if ($node->attributes->length) {
340 foreach ($node->attributes as $attribute) {
341 $meta_tag[$attribute->name] = $attribute->value;
345 if (!empty($meta_tag['content'])) {
346 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
348 switch (strtolower($meta_tag['property'])) {
350 $siteinfo['image'] = $meta_tag['content'];
353 $siteinfo['title'] = trim($meta_tag['content']);
355 case 'og:description':
356 $siteinfo['text'] = trim($meta_tag['content']);
362 // Prevent to have a photo type without an image
363 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
364 $siteinfo['type'] = 'link';
367 if (!empty($siteinfo['image'])) {
368 $src = self::completeUrl($siteinfo['image'], $url);
370 unset($siteinfo['image']);
372 $photodata = Images::getInfoFromURLCached($src);
374 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
375 $siteinfo['images'][] = ['src' => $src,
376 'width' => $photodata[0],
377 'height' => $photodata[1]];
381 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
382 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
383 $pos = mb_strrpos($siteinfo['text'], '.');
384 if ($pos > self::MIN_DESC_COUNT) {
385 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
389 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
391 Hook::callAll('getsiteinfo', $siteinfo);
397 * Convert tags from CSV to an array
399 * @param string $string Tags
400 * @return array with formatted Hashtags
402 public static function convertTagsToArray($string)
404 $arr_tags = str_getcsv($string);
405 if (count($arr_tags)) {
406 // add the # sign to every tag
407 array_walk($arr_tags, ["self", "arrAddHashes"]);
414 * Add a hasht sign to a string
416 * This method is used as callback function
418 * @param string $tag The pure tag name
419 * @param int $k Counter for internal use
422 private static function arrAddHashes(&$tag, $k)
428 * Add a scheme to an url
430 * The src attribute of some html elements (e.g. images)
431 * can miss the scheme so we need to add the correct
434 * @param string $url The url which possibly does have
435 * a missing scheme (a link to an image)
436 * @param string $scheme The url with a correct scheme
437 * (e.g. the url from the webpage which does contain the image)
439 * @return string The url with a scheme
441 private static function completeUrl($url, $scheme)
443 $urlarr = parse_url($url);
445 // If the url does allready have an scheme
446 // we can stop the process here
447 if (isset($urlarr["scheme"])) {
451 $schemearr = parse_url($scheme);
453 $complete = $schemearr["scheme"]."://".$schemearr["host"];
455 if (!empty($schemearr["port"])) {
456 $complete .= ":".$schemearr["port"];
459 if (!empty($urlarr["path"])) {
460 if (strpos($urlarr["path"], "/") !== 0) {
464 $complete .= $urlarr["path"];
467 if (!empty($urlarr["query"])) {
468 $complete .= "?".$urlarr["query"];
471 if (!empty($urlarr["fragment"])) {
472 $complete .= "#".$urlarr["fragment"];