4 * @file include/ParseUrl.php
5 * @brief Get informations about a given URL
10 use Friendica\Core\Config;
18 require_once("include/network.php");
19 require_once("include/Photo.php");
20 require_once("include/oembed.php");
21 require_once("include/xml.php");
24 * @brief Class with methods for extracting certain content from an url
29 * @brief Search for chached embeddable data of an url otherwise fetch it
31 * @param type $url The url of the page which should be scraped
32 * @param type $no_guessing If true the parse doens't search for
34 * @param type $do_oembed The false option is used by the function fetch_oembed()
35 * to avoid endless loops
37 * @return array which contains needed data for embedding
38 * string 'url' => The url of the parsed page
39 * string 'type' => Content type
40 * string 'title' => The title of the content
41 * string 'text' => The description for the content
42 * string 'image' => A preview image of the content (only available
43 * if $no_geuessing = false
44 * array'images' = Array of preview pictures
45 * string 'keywords' => The tags which belong to the content
47 * @see ParseUrl::getSiteinfo() for more information about scraping
50 public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true) {
56 $r = q("SELECT * FROM `parsed_url` WHERE `url` = '%s' AND `guessing` = %d AND `oembed` = %d",
57 dbesc(normalise_link($url)), intval(!$no_guessing), intval($do_oembed));
60 $data = $r[0]["content"];
63 if (!is_null($data)) {
64 $data = unserialize($data);
68 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
70 dba::insert('parsed_url', array('url' => normalise_link($url), 'guessing' => !$no_guessing,
71 'oembed' => $do_oembed, 'content' => serialize($data),
72 'created' => datetime_convert()), true);
77 * @brief Parse a page for embeddable content information
79 * This method parses to url for meta data which can be used to embed
80 * the content. If available it prioritizes Open Graph meta tags.
81 * If this is not available it uses the twitter cards meta tags.
82 * As fallback it uses standard html elements with meta informations
83 * like \<title\>Awesome Title\</title\> or
84 * \<meta name="description" content="An awesome description"\>
86 * @param type $url The url of the page which should be scraped
87 * @param type $no_guessing If true the parse doens't search for
89 * @param type $do_oembed The false option is used by the function fetch_oembed()
90 * to avoid endless loops
91 * @param type $count Internal counter to avoid endless loops
93 * @return array which contains needed data for embedding
94 * string 'url' => The url of the parsed page
95 * string 'type' => Content type
96 * string 'title' => The title of the content
97 * string 'text' => The description for the content
98 * string 'image' => A preview image of the content (only available
99 * if $no_geuessing = false
100 * array'images' = Array of preview pictures
101 * string 'keywords' => The tags which belong to the content
103 * @todo https://developers.google.com/+/plugins/snippet/
105 * <meta itemprop="name" content="Awesome title">
106 * <meta itemprop="description" content="An awesome description">
107 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
109 * <body itemscope itemtype="http://schema.org/Product">
110 * <h1 itemprop="name">Shiny Trinket</h1>
111 * <img itemprop="image" src="{image-url}" />
112 * <p itemprop="description">Shiny trinkets are shiny.</p>
116 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1) {
122 // Check if the URL does contain a scheme
123 $scheme = parse_url($url, PHP_URL_SCHEME);
126 $url = "http://".trim($url, "/");
130 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
134 $url = trim($url, "'");
135 $url = trim($url, '"');
137 $url = strip_tracking_query_params($url);
139 $siteinfo["url"] = $url;
140 $siteinfo["type"] = "link";
142 $data = z_fetch_url($url);
143 if (!$data['success']) {
147 // If the file is too large then exit
148 if ($data["info"]["download_content_length"] > 1000000) {
152 // If it isn't a HTML file then exit
153 if (($data["info"]["content_type"] != "") && !strstr(strtolower($data["info"]["content_type"]), "html")) {
157 $header = $data["header"];
158 $body = $data["body"];
162 $oembed_data = oembed_fetch_url($url);
164 if (!in_array($oembed_data->type, array("error", "rich"))) {
165 $siteinfo["type"] = $oembed_data->type;
168 if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
169 if (isset($oembed_data->title)) {
170 $siteinfo["title"] = $oembed_data->title;
172 if (isset($oembed_data->description)) {
173 $siteinfo["text"] = trim($oembed_data->description);
175 if (isset($oembed_data->thumbnail_url)) {
176 $siteinfo["image"] = $oembed_data->thumbnail_url;
181 // Fetch the first mentioned charset. Can be in body or header
183 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches)) {
184 $charset = trim(trim(trim(array_pop($matches)), ';,'));
187 if ($charset == "") {
191 if (($charset != "") && (strtoupper($charset) != "UTF-8")) {
192 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
193 //$body = mb_convert_encoding($body, "UTF-8", $charset);
194 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
197 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
199 $doc = new DOMDocument();
200 @$doc->loadHTML($body);
202 xml::deleteNode($doc, "style");
203 xml::deleteNode($doc, "script");
204 xml::deleteNode($doc, "option");
205 xml::deleteNode($doc, "h1");
206 xml::deleteNode($doc, "h2");
207 xml::deleteNode($doc, "h3");
208 xml::deleteNode($doc, "h4");
209 xml::deleteNode($doc, "h5");
210 xml::deleteNode($doc, "h6");
211 xml::deleteNode($doc, "ol");
212 xml::deleteNode($doc, "ul");
214 $xpath = new DomXPath($doc);
216 $list = $xpath->query("//meta[@content]");
217 foreach ($list as $node) {
219 if ($node->attributes->length) {
220 foreach ($node->attributes as $attribute) {
221 $attr[$attribute->name] = $attribute->value;
225 if (@$attr["http-equiv"] == "refresh") {
226 $path = $attr["content"];
227 $pathinfo = explode(";", $path);
229 foreach ($pathinfo as $value) {
230 if (substr(strtolower($value), 0, 4) == "url=") {
231 $content = substr($value, 4);
234 if ($content != "") {
235 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
241 $list = $xpath->query("//title");
242 if ($list->length > 0) {
243 $siteinfo["title"] = $list->item(0)->nodeValue;
246 //$list = $xpath->query("head/meta[@name]");
247 $list = $xpath->query("//meta[@name]");
248 foreach ($list as $node) {
250 if ($node->attributes->length) {
251 foreach ($node->attributes as $attribute) {
252 $attr[$attribute->name] = $attribute->value;
256 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
258 if ($attr["content"] != "") {
259 switch (strtolower($attr["name"])) {
261 $siteinfo["title"] = $attr["content"];
264 $siteinfo["text"] = $attr["content"];
267 $siteinfo["image"] = $attr["content"];
269 case "twitter:image":
270 $siteinfo["image"] = $attr["content"];
272 case "twitter:image:src":
273 $siteinfo["image"] = $attr["content"];
276 if (($siteinfo["type"] == "") || ($attr["content"] == "photo")) {
277 $siteinfo["type"] = $attr["content"];
280 case "twitter:description":
281 $siteinfo["text"] = $attr["content"];
283 case "twitter:title":
284 $siteinfo["title"] = $attr["content"];
287 $siteinfo["title"] = $attr["content"];
289 case "dc.description":
290 $siteinfo["text"] = $attr["content"];
293 $keywords = explode(",", $attr["content"]);
295 case "news_keywords":
296 $keywords = explode(",", $attr["content"]);
300 if ($siteinfo["type"] == "summary") {
301 $siteinfo["type"] = "link";
305 if (isset($keywords)) {
306 $siteinfo["keywords"] = array();
307 foreach ($keywords as $keyword) {
308 if (!in_array(trim($keyword), $siteinfo["keywords"])) {
309 $siteinfo["keywords"][] = trim($keyword);
314 //$list = $xpath->query("head/meta[@property]");
315 $list = $xpath->query("//meta[@property]");
316 foreach ($list as $node) {
318 if ($node->attributes->length) {
319 foreach ($node->attributes as $attribute) {
320 $attr[$attribute->name] = $attribute->value;
324 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
326 if ($attr["content"] != "") {
327 switch (strtolower($attr["property"])) {
329 $siteinfo["image"] = $attr["content"];
332 $siteinfo["title"] = $attr["content"];
334 case "og:description":
335 $siteinfo["text"] = $attr["content"];
341 if ((@$siteinfo["image"] == "") && !$no_guessing) {
342 $list = $xpath->query("//img[@src]");
343 foreach ($list as $node) {
345 if ($node->attributes->length) {
346 foreach ($node->attributes as $attribute) {
347 $attr[$attribute->name] = $attribute->value;
351 $src = self::completeUrl($attr["src"], $url);
352 $photodata = get_photo_info($src);
354 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
355 if ($photodata[0] > 300) {
356 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
359 if ($photodata[1] > 300) {
360 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
363 $siteinfo["images"][] = array("src" => $src,
364 "width" => $photodata[0],
365 "height" => $photodata[1]);
369 } elseif ($siteinfo["image"] != "") {
370 $src = self::completeUrl($siteinfo["image"], $url);
372 unset($siteinfo["image"]);
374 $photodata = get_photo_info($src);
376 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
377 $siteinfo["images"][] = array("src" => $src,
378 "width" => $photodata[0],
379 "height" => $photodata[1]);
383 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
386 $list = $xpath->query("//div[@class='article']");
387 foreach ($list as $node) {
388 if (strlen($node->nodeValue) > 40) {
389 $text .= " ".trim($node->nodeValue);
394 $list = $xpath->query("//div[@class='content']");
395 foreach ($list as $node) {
396 if (strlen($node->nodeValue) > 40) {
397 $text .= " ".trim($node->nodeValue);
402 // If none text was found then take the paragraph content
404 $list = $xpath->query("//p");
405 foreach ($list as $node) {
406 if (strlen($node->nodeValue) > 40) {
407 $text .= " ".trim($node->nodeValue);
413 $text = trim(str_replace(array("\n", "\r"), array(" ", " "), $text));
415 while (strpos($text, " ")) {
416 $text = trim(str_replace(" ", " ", $text));
419 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
423 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
425 call_hooks("getsiteinfo", $siteinfo);
431 * @brief Convert tags from CSV to an array
433 * @param string $string Tags
434 * @return array with formatted Hashtags
436 public static function convertTagsToArray($string) {
437 $arr_tags = str_getcsv($string);
438 if (count($arr_tags)) {
439 // add the # sign to every tag
440 array_walk($arr_tags, array("self", "arrAddHashes"));
447 * @brief Add a hasht sign to a string
449 * This method is used as callback function
451 * @param string $tag The pure tag name
452 * @param int $k Counter for internal use
454 private static function arrAddHashes(&$tag, $k) {
459 * @brief Add a scheme to an url
461 * The src attribute of some html elements (e.g. images)
462 * can miss the scheme so we need to add the correct
465 * @param string $url The url which possibly does have
466 * a missing scheme (a link to an image)
467 * @param string $scheme The url with a correct scheme
468 * (e.g. the url from the webpage which does contain the image)
470 * @return string The url with a scheme
472 private static function completeUrl($url, $scheme) {
473 $urlarr = parse_url($url);
475 // If the url does allready have an scheme
476 // we can stop the process here
477 if (isset($urlarr["scheme"])) {
481 $schemearr = parse_url($scheme);
483 $complete = $schemearr["scheme"]."://".$schemearr["host"];
485 if (@$schemearr["port"] != "") {
486 $complete .= ":".$schemearr["port"];
489 if (strpos($urlarr["path"],"/") !== 0) {
493 $complete .= $urlarr["path"];
495 if (@$urlarr["query"] != "") {
496 $complete .= "?".$urlarr["query"];
499 if (@$urlarr["fragment"] != "") {
500 $complete .= "#".$urlarr["fragment"];