3 * @file src/Util/ParseUrl.php
4 * @brief Get informations about a given URL
6 namespace Friendica\Util;
8 use Friendica\Content\OEmbed;
9 use Friendica\Core\Addon;
10 use Friendica\Object\Image;
11 use Friendica\Util\Network;
12 use Friendica\Util\XML;
18 require_once 'include/dba.php';
21 * @brief Class with methods for extracting certain content from an url
26 * @brief Search for chached embeddable data of an url otherwise fetch it
28 * @param string $url The url of the page which should be scraped
29 * @param bool $no_guessing If true the parse doens't search for
31 * @param bool $do_oembed The false option is used by the function fetch_oembed()
32 * to avoid endless loops
34 * @return array which contains needed data for embedding
35 * string 'url' => The url of the parsed page
36 * string 'type' => Content type
37 * string 'title' => The title of the content
38 * string 'text' => The description for the content
39 * string 'image' => A preview image of the content (only available
40 * if $no_geuessing = false
41 * array'images' = Array of preview pictures
42 * string 'keywords' => The tags which belong to the content
44 * @see ParseUrl::getSiteinfo() for more information about scraping
47 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true)
54 "SELECT * FROM `parsed_url` WHERE `url` = '%s' AND `guessing` = %d AND `oembed` = %d",
55 dbesc(normalise_link($url)),
56 intval(!$no_guessing),
61 $data = $r[0]["content"];
64 if (!is_null($data)) {
65 $data = unserialize($data);
69 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
74 'url' => normalise_link($url), 'guessing' => !$no_guessing,
75 'oembed' => $do_oembed, 'content' => serialize($data),
76 'created' => Temporal::convert()
84 * @brief Parse a page for embeddable content information
86 * This method parses to url for meta data which can be used to embed
87 * the content. If available it prioritizes Open Graph meta tags.
88 * If this is not available it uses the twitter cards meta tags.
89 * As fallback it uses standard html elements with meta informations
90 * like \<title\>Awesome Title\</title\> or
91 * \<meta name="description" content="An awesome description"\>
93 * @param string $url The url of the page which should be scraped
94 * @param bool $no_guessing If true the parse doens't search for
96 * @param bool $do_oembed The false option is used by the function fetch_oembed()
97 * to avoid endless loops
98 * @param int $count Internal counter to avoid endless loops
100 * @return array which contains needed data for embedding
101 * string 'url' => The url of the parsed page
102 * string 'type' => Content type
103 * string 'title' => The title of the content
104 * string 'text' => The description for the content
105 * string 'image' => A preview image of the content (only available
106 * if $no_geuessing = false
107 * array'images' = Array of preview pictures
108 * string 'keywords' => The tags which belong to the content
110 * @todo https://developers.google.com/+/plugins/snippet/
112 * <meta itemprop="name" content="Awesome title">
113 * <meta itemprop="description" content="An awesome description">
114 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
116 * <body itemscope itemtype="http://schema.org/Product">
117 * <h1 itemprop="name">Shiny Trinket</h1>
118 * <img itemprop="image" src="{image-url}" />
119 * <p itemprop="description">Shiny trinkets are shiny.</p>
123 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
129 // Check if the URL does contain a scheme
130 $scheme = parse_url($url, PHP_URL_SCHEME);
133 $url = "http://".trim($url, "/");
137 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
141 $url = trim($url, "'");
142 $url = trim($url, '"');
144 $url = Network::stripTrackingQueryParams($url);
146 $siteinfo["url"] = $url;
147 $siteinfo["type"] = "link";
149 $data = Network::curl($url);
150 if (!$data['success']) {
154 // If the file is too large then exit
155 if ($data["info"]["download_content_length"] > 1000000) {
159 // If it isn't a HTML file then exit
160 if (($data["info"]["content_type"] != "") && !strstr(strtolower($data["info"]["content_type"]), "html")) {
164 $header = $data["header"];
165 $body = $data["body"];
168 $oembed_data = OEmbed::fetchURL($url);
170 if (!in_array($oembed_data->type, ["error", "rich", ""])) {
171 $siteinfo["type"] = $oembed_data->type;
174 if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
175 if (isset($oembed_data->title)) {
176 $siteinfo["title"] = trim($oembed_data->title);
178 if (isset($oembed_data->description)) {
179 $siteinfo["text"] = trim($oembed_data->description);
181 if (isset($oembed_data->thumbnail_url)) {
182 $siteinfo["image"] = $oembed_data->thumbnail_url;
187 // Fetch the first mentioned charset. Can be in body or header
189 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches)) {
190 $charset = trim(trim(trim(array_pop($matches)), ';,'));
193 if ($charset == "") {
197 if (($charset != "") && (strtoupper($charset) != "UTF-8")) {
198 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
199 //$body = mb_convert_encoding($body, "UTF-8", $charset);
200 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
203 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
205 $doc = new DOMDocument();
206 @$doc->loadHTML($body);
208 XML::deleteNode($doc, "style");
209 XML::deleteNode($doc, "script");
210 XML::deleteNode($doc, "option");
211 XML::deleteNode($doc, "h1");
212 XML::deleteNode($doc, "h2");
213 XML::deleteNode($doc, "h3");
214 XML::deleteNode($doc, "h4");
215 XML::deleteNode($doc, "h5");
216 XML::deleteNode($doc, "h6");
217 XML::deleteNode($doc, "ol");
218 XML::deleteNode($doc, "ul");
220 $xpath = new DOMXPath($doc);
222 $list = $xpath->query("//meta[@content]");
223 foreach ($list as $node) {
225 if ($node->attributes->length) {
226 foreach ($node->attributes as $attribute) {
227 $attr[$attribute->name] = $attribute->value;
231 if (@$attr["http-equiv"] == "refresh") {
232 $path = $attr["content"];
233 $pathinfo = explode(";", $path);
235 foreach ($pathinfo as $value) {
236 if (substr(strtolower($value), 0, 4) == "url=") {
237 $content = substr($value, 4);
240 if ($content != "") {
241 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
247 $list = $xpath->query("//title");
248 if ($list->length > 0) {
249 $siteinfo["title"] = trim($list->item(0)->nodeValue);
252 //$list = $xpath->query("head/meta[@name]");
253 $list = $xpath->query("//meta[@name]");
254 foreach ($list as $node) {
256 if ($node->attributes->length) {
257 foreach ($node->attributes as $attribute) {
258 $attr[$attribute->name] = $attribute->value;
262 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
264 if ($attr["content"] != "") {
265 switch (strtolower($attr["name"])) {
267 $siteinfo["title"] = trim($attr["content"]);
270 $siteinfo["text"] = trim($attr["content"]);
273 $siteinfo["image"] = $attr["content"];
275 case "twitter:image":
276 $siteinfo["image"] = $attr["content"];
278 case "twitter:image:src":
279 $siteinfo["image"] = $attr["content"];
282 if (($siteinfo["type"] == "") || ($attr["content"] == "photo")) {
283 $siteinfo["type"] = $attr["content"];
286 case "twitter:description":
287 $siteinfo["text"] = trim($attr["content"]);
289 case "twitter:title":
290 $siteinfo["title"] = trim($attr["content"]);
293 $siteinfo["title"] = trim($attr["content"]);
295 case "dc.description":
296 $siteinfo["text"] = trim($attr["content"]);
299 $keywords = explode(",", $attr["content"]);
301 case "news_keywords":
302 $keywords = explode(",", $attr["content"]);
306 if ($siteinfo["type"] == "summary") {
307 $siteinfo["type"] = "link";
311 if (isset($keywords)) {
312 $siteinfo["keywords"] = [];
313 foreach ($keywords as $keyword) {
314 if (!in_array(trim($keyword), $siteinfo["keywords"])) {
315 $siteinfo["keywords"][] = trim($keyword);
320 //$list = $xpath->query("head/meta[@property]");
321 $list = $xpath->query("//meta[@property]");
322 foreach ($list as $node) {
324 if ($node->attributes->length) {
325 foreach ($node->attributes as $attribute) {
326 $attr[$attribute->name] = $attribute->value;
330 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
332 if ($attr["content"] != "") {
333 switch (strtolower($attr["property"])) {
335 $siteinfo["image"] = $attr["content"];
338 $siteinfo["title"] = trim($attr["content"]);
340 case "og:description":
341 $siteinfo["text"] = trim($attr["content"]);
347 if ((@$siteinfo["image"] == "") && !$no_guessing) {
348 $list = $xpath->query("//img[@src]");
349 foreach ($list as $node) {
351 if ($node->attributes->length) {
352 foreach ($node->attributes as $attribute) {
353 $attr[$attribute->name] = $attribute->value;
357 $src = self::completeUrl($attr["src"], $url);
358 $photodata = Image::getInfoFromURL($src);
360 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
361 if ($photodata[0] > 300) {
362 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
365 if ($photodata[1] > 300) {
366 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
369 $siteinfo["images"][] = ["src" => $src,
370 "width" => $photodata[0],
371 "height" => $photodata[1]];
374 } elseif ($siteinfo["image"] != "") {
375 $src = self::completeUrl($siteinfo["image"], $url);
377 unset($siteinfo["image"]);
379 $photodata = Image::getInfoFromURL($src);
381 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
382 $siteinfo["images"][] = ["src" => $src,
383 "width" => $photodata[0],
384 "height" => $photodata[1]];
388 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
391 $list = $xpath->query("//div[@class='article']");
392 foreach ($list as $node) {
393 if (strlen($node->nodeValue) > 40) {
394 $text .= " ".trim($node->nodeValue);
399 $list = $xpath->query("//div[@class='content']");
400 foreach ($list as $node) {
401 if (strlen($node->nodeValue) > 40) {
402 $text .= " ".trim($node->nodeValue);
407 // If none text was found then take the paragraph content
409 $list = $xpath->query("//p");
410 foreach ($list as $node) {
411 if (strlen($node->nodeValue) > 40) {
412 $text .= " ".trim($node->nodeValue);
418 $text = trim(str_replace(["\n", "\r"], [" ", " "], $text));
420 while (strpos($text, " ")) {
421 $text = trim(str_replace(" ", " ", $text));
424 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
428 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
430 Addon::callHooks("getsiteinfo", $siteinfo);
436 * @brief Convert tags from CSV to an array
438 * @param string $string Tags
439 * @return array with formatted Hashtags
441 public static function convertTagsToArray($string)
443 $arr_tags = str_getcsv($string);
444 if (count($arr_tags)) {
445 // add the # sign to every tag
446 array_walk($arr_tags, ["self", "arrAddHashes"]);
453 * @brief Add a hasht sign to a string
455 * This method is used as callback function
457 * @param string $tag The pure tag name
458 * @param int $k Counter for internal use
461 private static function arrAddHashes(&$tag, $k)
467 * @brief Add a scheme to an url
469 * The src attribute of some html elements (e.g. images)
470 * can miss the scheme so we need to add the correct
473 * @param string $url The url which possibly does have
474 * a missing scheme (a link to an image)
475 * @param string $scheme The url with a correct scheme
476 * (e.g. the url from the webpage which does contain the image)
478 * @return string The url with a scheme
480 private static function completeUrl($url, $scheme)
482 $urlarr = parse_url($url);
484 // If the url does allready have an scheme
485 // we can stop the process here
486 if (isset($urlarr["scheme"])) {
490 $schemearr = parse_url($scheme);
492 $complete = $schemearr["scheme"]."://".$schemearr["host"];
494 if (@$schemearr["port"] != "") {
495 $complete .= ":".$schemearr["port"];
498 if (strpos($urlarr["path"], "/") !== 0) {
502 $complete .= $urlarr["path"];
504 if (@$urlarr["query"] != "") {
505 $complete .= "?".$urlarr["query"];
508 if (@$urlarr["fragment"] != "") {
509 $complete .= "#".$urlarr["fragment"];