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)
53 $parsed_url = dba::selectFirst('parsed_url', ['content'],
54 ['url' => normalise_link($url), 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
56 if (!empty($parsed_url['content'])) {
57 $data = unserialize($parsed_url['content']);
61 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
66 'url' => normalise_link($url), 'guessing' => !$no_guessing,
67 'oembed' => $do_oembed, 'content' => serialize($data),
68 'created' => DateTimeFormat::utcNow()
76 * @brief Parse a page for embeddable content information
78 * This method parses to url for meta data which can be used to embed
79 * the content. If available it prioritizes Open Graph meta tags.
80 * If this is not available it uses the twitter cards meta tags.
81 * As fallback it uses standard html elements with meta informations
82 * like \<title\>Awesome Title\</title\> or
83 * \<meta name="description" content="An awesome description"\>
85 * @param string $url The url of the page which should be scraped
86 * @param bool $no_guessing If true the parse doens't search for
88 * @param bool $do_oembed The false option is used by the function fetch_oembed()
89 * to avoid endless loops
90 * @param int $count Internal counter to avoid endless loops
92 * @return array which contains needed data for embedding
93 * string 'url' => The url of the parsed page
94 * string 'type' => Content type
95 * string 'title' => The title of the content
96 * string 'text' => The description for the content
97 * string 'image' => A preview image of the content (only available
98 * if $no_geuessing = false
99 * array'images' = Array of preview pictures
100 * string 'keywords' => The tags which belong to the content
102 * @todo https://developers.google.com/+/plugins/snippet/
104 * <meta itemprop="name" content="Awesome title">
105 * <meta itemprop="description" content="An awesome description">
106 * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
108 * <body itemscope itemtype="http://schema.org/Product">
109 * <h1 itemprop="name">Shiny Trinket</h1>
110 * <img itemprop="image" src="{image-url}" />
111 * <p itemprop="description">Shiny trinkets are shiny.</p>
115 public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
121 // Check if the URL does contain a scheme
122 $scheme = parse_url($url, PHP_URL_SCHEME);
125 $url = "http://".trim($url, "/");
129 logger("parseurl_getsiteinfo: Endless loop detected for ".$url, LOGGER_DEBUG);
133 $url = trim($url, "'");
134 $url = trim($url, '"');
136 $url = Network::stripTrackingQueryParams($url);
138 $siteinfo["url"] = $url;
139 $siteinfo["type"] = "link";
141 $data = Network::curl($url);
142 if (!$data['success']) {
146 // If the file is too large then exit
147 if ($data["info"]["download_content_length"] > 1000000) {
151 // If it isn't a HTML file then exit
152 if (($data["info"]["content_type"] != "") && !strstr(strtolower($data["info"]["content_type"]), "html")) {
156 $header = $data["header"];
157 $body = $data["body"];
160 $oembed_data = OEmbed::fetchURL($url);
162 if (!in_array($oembed_data->type, ["error", "rich", ""])) {
163 $siteinfo["type"] = $oembed_data->type;
166 if (($oembed_data->type == "link") && ($siteinfo["type"] != "photo")) {
167 if (isset($oembed_data->title)) {
168 $siteinfo["title"] = trim($oembed_data->title);
170 if (isset($oembed_data->description)) {
171 $siteinfo["text"] = trim($oembed_data->description);
173 if (isset($oembed_data->thumbnail_url)) {
174 $siteinfo["image"] = $oembed_data->thumbnail_url;
179 // Fetch the first mentioned charset. Can be in body or header
181 if (preg_match('/charset=(.*?)['."'".'"\s\n]/', $header, $matches)) {
182 $charset = trim(trim(trim(array_pop($matches)), ';,'));
185 if ($charset == "") {
189 if (($charset != "") && (strtoupper($charset) != "UTF-8")) {
190 logger("parseurl_getsiteinfo: detected charset ".$charset, LOGGER_DEBUG);
191 //$body = mb_convert_encoding($body, "UTF-8", $charset);
192 $body = iconv($charset, "UTF-8//TRANSLIT", $body);
195 $body = mb_convert_encoding($body, 'HTML-ENTITIES', "UTF-8");
197 $doc = new DOMDocument();
198 @$doc->loadHTML($body);
200 XML::deleteNode($doc, "style");
201 XML::deleteNode($doc, "script");
202 XML::deleteNode($doc, "option");
203 XML::deleteNode($doc, "h1");
204 XML::deleteNode($doc, "h2");
205 XML::deleteNode($doc, "h3");
206 XML::deleteNode($doc, "h4");
207 XML::deleteNode($doc, "h5");
208 XML::deleteNode($doc, "h6");
209 XML::deleteNode($doc, "ol");
210 XML::deleteNode($doc, "ul");
212 $xpath = new DOMXPath($doc);
214 $list = $xpath->query("//meta[@content]");
215 foreach ($list as $node) {
217 if ($node->attributes->length) {
218 foreach ($node->attributes as $attribute) {
219 $attr[$attribute->name] = $attribute->value;
223 if (@$attr["http-equiv"] == "refresh") {
224 $path = $attr["content"];
225 $pathinfo = explode(";", $path);
227 foreach ($pathinfo as $value) {
228 if (substr(strtolower($value), 0, 4) == "url=") {
229 $content = substr($value, 4);
232 if ($content != "") {
233 $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
239 $list = $xpath->query("//title");
240 if ($list->length > 0) {
241 $siteinfo["title"] = trim($list->item(0)->nodeValue);
244 //$list = $xpath->query("head/meta[@name]");
245 $list = $xpath->query("//meta[@name]");
246 foreach ($list as $node) {
248 if ($node->attributes->length) {
249 foreach ($node->attributes as $attribute) {
250 $attr[$attribute->name] = $attribute->value;
254 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
256 if ($attr["content"] != "") {
257 switch (strtolower($attr["name"])) {
259 $siteinfo["title"] = trim($attr["content"]);
262 $siteinfo["text"] = trim($attr["content"]);
265 $siteinfo["image"] = $attr["content"];
267 case "twitter:image":
268 $siteinfo["image"] = $attr["content"];
270 case "twitter:image:src":
271 $siteinfo["image"] = $attr["content"];
274 if (($siteinfo["type"] == "") || ($attr["content"] == "photo")) {
275 $siteinfo["type"] = $attr["content"];
278 case "twitter:description":
279 $siteinfo["text"] = trim($attr["content"]);
281 case "twitter:title":
282 $siteinfo["title"] = trim($attr["content"]);
285 $siteinfo["title"] = trim($attr["content"]);
287 case "dc.description":
288 $siteinfo["text"] = trim($attr["content"]);
291 $keywords = explode(",", $attr["content"]);
293 case "news_keywords":
294 $keywords = explode(",", $attr["content"]);
298 if ($siteinfo["type"] == "summary") {
299 $siteinfo["type"] = "link";
303 if (isset($keywords)) {
304 $siteinfo["keywords"] = [];
305 foreach ($keywords as $keyword) {
306 if (!in_array(trim($keyword), $siteinfo["keywords"])) {
307 $siteinfo["keywords"][] = trim($keyword);
312 //$list = $xpath->query("head/meta[@property]");
313 $list = $xpath->query("//meta[@property]");
314 foreach ($list as $node) {
316 if ($node->attributes->length) {
317 foreach ($node->attributes as $attribute) {
318 $attr[$attribute->name] = $attribute->value;
322 $attr["content"] = trim(html_entity_decode($attr["content"], ENT_QUOTES, "UTF-8"));
324 if ($attr["content"] != "") {
325 switch (strtolower($attr["property"])) {
327 $siteinfo["image"] = $attr["content"];
330 $siteinfo["title"] = trim($attr["content"]);
332 case "og:description":
333 $siteinfo["text"] = trim($attr["content"]);
339 if ((@$siteinfo["image"] == "") && !$no_guessing) {
340 $list = $xpath->query("//img[@src]");
341 foreach ($list as $node) {
343 if ($node->attributes->length) {
344 foreach ($node->attributes as $attribute) {
345 $attr[$attribute->name] = $attribute->value;
349 $src = self::completeUrl($attr["src"], $url);
350 $photodata = Image::getInfoFromURL($src);
352 if (($photodata) && ($photodata[0] > 150) && ($photodata[1] > 150)) {
353 if ($photodata[0] > 300) {
354 $photodata[1] = round($photodata[1] * (300 / $photodata[0]));
357 if ($photodata[1] > 300) {
358 $photodata[0] = round($photodata[0] * (300 / $photodata[1]));
361 $siteinfo["images"][] = ["src" => $src,
362 "width" => $photodata[0],
363 "height" => $photodata[1]];
366 } elseif ($siteinfo["image"] != "") {
367 $src = self::completeUrl($siteinfo["image"], $url);
369 unset($siteinfo["image"]);
371 $photodata = Image::getInfoFromURL($src);
373 if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
374 $siteinfo["images"][] = ["src" => $src,
375 "width" => $photodata[0],
376 "height" => $photodata[1]];
380 if ((@$siteinfo["text"] == "") && (@$siteinfo["title"] != "") && !$no_guessing) {
383 $list = $xpath->query("//div[@class='article']");
384 foreach ($list as $node) {
385 if (strlen($node->nodeValue) > 40) {
386 $text .= " ".trim($node->nodeValue);
391 $list = $xpath->query("//div[@class='content']");
392 foreach ($list as $node) {
393 if (strlen($node->nodeValue) > 40) {
394 $text .= " ".trim($node->nodeValue);
399 // If none text was found then take the paragraph content
401 $list = $xpath->query("//p");
402 foreach ($list as $node) {
403 if (strlen($node->nodeValue) > 40) {
404 $text .= " ".trim($node->nodeValue);
410 $text = trim(str_replace(["\n", "\r"], [" ", " "], $text));
412 while (strpos($text, " ")) {
413 $text = trim(str_replace(" ", " ", $text));
416 $siteinfo["text"] = trim(html_entity_decode(substr($text, 0, 350), ENT_QUOTES, "UTF-8").'...');
420 logger("parseurl_getsiteinfo: Siteinfo for ".$url." ".print_r($siteinfo, true), LOGGER_DEBUG);
422 Addon::callHooks("getsiteinfo", $siteinfo);
428 * @brief Convert tags from CSV to an array
430 * @param string $string Tags
431 * @return array with formatted Hashtags
433 public static function convertTagsToArray($string)
435 $arr_tags = str_getcsv($string);
436 if (count($arr_tags)) {
437 // add the # sign to every tag
438 array_walk($arr_tags, ["self", "arrAddHashes"]);
445 * @brief Add a hasht sign to a string
447 * This method is used as callback function
449 * @param string $tag The pure tag name
450 * @param int $k Counter for internal use
453 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)
474 $urlarr = parse_url($url);
476 // If the url does allready have an scheme
477 // we can stop the process here
478 if (isset($urlarr["scheme"])) {
482 $schemearr = parse_url($scheme);
484 $complete = $schemearr["scheme"]."://".$schemearr["host"];
486 if (@$schemearr["port"] != "") {
487 $complete .= ":".$schemearr["port"];
490 if (strpos($urlarr["path"], "/") !== 0) {
494 $complete .= $urlarr["path"];
496 if (@$urlarr["query"] != "") {
497 $complete .= "?".$urlarr["query"];
500 if (@$urlarr["fragment"] != "") {
501 $complete .= "#".$urlarr["fragment"];