]> git.mxchange.org Git - friendica.git/blob - src/Util/ParseUrl.php
Avoid double fetches
[friendica.git] / src / Util / ParseUrl.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Util;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Friendica\Content\OEmbed;
27 use Friendica\Core\Hook;
28 use Friendica\Core\Logger;
29 use Friendica\Database\Database;
30 use Friendica\Database\DBA;
31 use Friendica\DI;
32 use Friendica\Network\HTTPException;
33
34 /**
35  * Get information about a given URL
36  *
37  * Class with methods for extracting certain content from an url
38  */
39 class ParseUrl
40 {
41         const DEFAULT_EXPIRATION_FAILURE = 'now + 1 day';
42         const DEFAULT_EXPIRATION_SUCCESS = 'now + 3 months';
43
44         /**
45          * Maximum number of characters for the description
46          */
47         const MAX_DESC_COUNT = 250;
48
49         /**
50          * Minimum number of characters for the description
51          */
52         const MIN_DESC_COUNT = 100;
53
54         /**
55          * Fetch the content type of the given url
56          * @param string $url URL of the page
57          * @return array content type 
58          */
59         public static function getContentType(string $url)
60         {
61                 $curlResult = DI::httpRequest()->head($url);
62                 if (!$curlResult->isSuccess()) {
63                         return [];
64                 }
65
66                 $contenttype =  $curlResult->getHeader('Content-Type');
67                 if (empty($contenttype)) {
68                         return [];
69                 }
70
71                 return explode('/', current(explode(';', $contenttype)));
72         }
73
74         /**
75          * Search for chached embeddable data of an url otherwise fetch it
76          *
77          * @param string $url         The url of the page which should be scraped
78          * @param bool   $no_guessing If true the parse doens't search for
79          *                            preview pictures
80          * @param bool   $do_oembed   The false option is used by the function fetch_oembed()
81          *                            to avoid endless loops
82          *
83          * @return array which contains needed data for embedding
84          *    string 'url'      => The url of the parsed page
85          *    string 'type'     => Content type
86          *    string 'title'    => (optional) The title of the content
87          *    string 'text'     => (optional) The description for the content
88          *    string 'image'    => (optional) A preview image of the content (only available if $no_geuessing = false)
89          *    array  'images'   => (optional) Array of preview pictures
90          *    string 'keywords' => (optional) The tags which belong to the content
91          *
92          * @throws HTTPException\InternalServerErrorException
93          * @see   ParseUrl::getSiteinfo() for more information about scraping
94          * embeddable content
95          */
96         public static function getSiteinfoCached($url, $no_guessing = false, $do_oembed = true): array
97         {
98                 if (empty($url)) {
99                         return [
100                                 'url' => '',
101                                 'type' => 'error',
102                         ];
103                 }
104
105                 $urlHash = hash('sha256', $url);
106
107                 $parsed_url = DBA::selectFirst('parsed_url', ['content'],
108                         ['url_hash' => $urlHash, 'guessing' => !$no_guessing, 'oembed' => $do_oembed]
109                 );
110                 if (!empty($parsed_url['content'])) {
111                         $data = unserialize($parsed_url['content']);
112                         return $data;
113                 }
114
115                 $data = self::getSiteinfo($url, $no_guessing, $do_oembed);
116
117                 $expires = $data['expires'];
118
119                 unset($data['expires']);
120
121                 DI::dba()->insert(
122                         'parsed_url',
123                         [
124                                 'url_hash' => $urlHash,
125                                 'guessing' => !$no_guessing,
126                                 'oembed'   => $do_oembed,
127                                 'url'      => $url,
128                                 'content'  => serialize($data),
129                                 'created'  => DateTimeFormat::utcNow(),
130                                 'expires'  => $expires,
131                         ],
132                         Database::INSERT_UPDATE
133                 );
134
135                 return $data;
136         }
137
138         /**
139          * Parse a page for embeddable content information
140          *
141          * This method parses to url for meta data which can be used to embed
142          * the content. If available it prioritizes Open Graph meta tags.
143          * If this is not available it uses the twitter cards meta tags.
144          * As fallback it uses standard html elements with meta informations
145          * like \<title\>Awesome Title\</title\> or
146          * \<meta name="description" content="An awesome description"\>
147          *
148          * @param string $url         The url of the page which should be scraped
149          * @param bool   $no_guessing If true the parse doens't search for
150          *                            preview pictures
151          * @param bool   $do_oembed   The false option is used by the function fetch_oembed()
152          *                            to avoid endless loops
153          * @param int    $count       Internal counter to avoid endless loops
154          *
155          * @return array which contains needed data for embedding
156          *    string 'url'      => The url of the parsed page
157          *    string 'type'     => Content type (error, link, photo, image, audio, video)
158          *    string 'title'    => (optional) The title of the content
159          *    string 'text'     => (optional) The description for the content
160          *    string 'image'    => (optional) A preview image of the content (only available if $no_guessing = false)
161          *    array  'images'   => (optional) Array of preview pictures
162          *    string 'keywords' => (optional) The tags which belong to the content
163          *
164          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
165          * @todo  https://developers.google.com/+/plugins/snippet/
166          * @verbatim
167          * <meta itemprop="name" content="Awesome title">
168          * <meta itemprop="description" content="An awesome description">
169          * <meta itemprop="image" content="http://maple.libertreeproject.org/images/tree-icon.png">
170          *
171          * <body itemscope itemtype="http://schema.org/Product">
172          *   <h1 itemprop="name">Shiny Trinket</h1>
173          *   <img itemprop="image" src="{image-url}" />
174          *   <p itemprop="description">Shiny trinkets are shiny.</p>
175          * </body>
176          * @endverbatim
177          */
178         public static function getSiteinfo($url, $no_guessing = false, $do_oembed = true, $count = 1)
179         {
180                 if (empty($url)) {
181                         return [
182                                 'url' => '',
183                                 'type' => 'error',
184                         ];
185                 }
186
187                 // Check if the URL does contain a scheme
188                 $scheme = parse_url($url, PHP_URL_SCHEME);
189
190                 if ($scheme == '') {
191                         $url = 'http://' . ltrim($url, '/');
192                 }
193
194                 $url = trim($url, "'\"");
195
196                 $url = Network::stripTrackingQueryParams($url);
197
198                 $siteinfo = [
199                         'url' => $url,
200                         'type' => 'link',
201                         'expires' => DateTimeFormat::utc(self::DEFAULT_EXPIRATION_FAILURE),
202                 ];
203
204                 if ($count > 10) {
205                         Logger::log('Endless loop detected for ' . $url, Logger::DEBUG);
206                         return $siteinfo;
207                 }
208
209                 $type = self::getContentType($url);
210                 Logger::info('Got content-type', ['content-type' => $type, 'url' => $url]);
211                 if (!empty($type) && in_array($type[0], ['image', 'video', 'audio'])) {
212                         $siteinfo['type'] = $type[0];
213                         return $siteinfo;
214                 }
215
216                 if ((count($type) >= 2) && (($type[0] != 'text') || ($type[1] != 'html'))) {
217                         Logger::info('Unparseable content-type, quitting here, ', ['content-type' => $type, 'url' => $url]);
218                         return $siteinfo;
219                 }
220
221                 $curlResult = DI::httpRequest()->get($url);
222                 if (!$curlResult->isSuccess()) {
223                         return $siteinfo;
224                 }
225
226                 $siteinfo['expires'] = DateTimeFormat::utc(self::DEFAULT_EXPIRATION_SUCCESS);
227
228                 // If the file is too large then exit
229                 if (($curlResult->getInfo()['download_content_length'] ?? 0) > 1000000) {
230                         return $siteinfo;
231                 }
232
233                 if ($cacheControlHeader = $curlResult->getHeader('Cache-Control')) {
234                         if (preg_match('/max-age=([0-9]+)/i', $cacheControlHeader, $matches)) {
235                                 $maxAge = max(86400, (int)array_pop($matches));
236                                 $siteinfo['expires'] = DateTimeFormat::utc("now + $maxAge seconds");
237                         }
238                 }
239
240                 $header = $curlResult->getHeader();
241                 $body = $curlResult->getBody();
242
243                 if ($do_oembed) {
244                         $oembed_data = OEmbed::fetchURL($url, false, false);
245
246                         if (!empty($oembed_data->type)) {
247                                 if (!in_array($oembed_data->type, ['error', 'rich', 'image', 'video', 'audio', ''])) {
248                                         $siteinfo['type'] = $oembed_data->type;
249                                 }
250
251                                 // See https://github.com/friendica/friendica/pull/5763#discussion_r217913178
252                                 if ($siteinfo['type'] != 'photo') {
253                                         if (!empty($oembed_data->title)) {
254                                                 $siteinfo['title'] = trim($oembed_data->title);
255                                         }
256                                         if (!empty($oembed_data->description)) {
257                                                 $siteinfo['text'] = trim($oembed_data->description);
258                                         }
259                                         if (!empty($oembed_data->author_name)) {
260                                                 $siteinfo['author_name'] = trim($oembed_data->author_name);
261                                         }
262                                         if (!empty($oembed_data->author_url)) {
263                                                 $siteinfo['author_url'] = trim($oembed_data->author_url);
264                                         }
265                                         if (!empty($oembed_data->provider_name)) {
266                                                 $siteinfo['publisher_name'] = trim($oembed_data->provider_name);
267                                         }
268                                         if (!empty($oembed_data->provider_url)) {
269                                                 $siteinfo['publisher_url'] = trim($oembed_data->provider_url);
270                                         }
271                                         if (!empty($oembed_data->thumbnail_url)) {
272                                                 $siteinfo['image'] = $oembed_data->thumbnail_url;
273                                         }
274                                 }
275                         }
276                 }
277
278                 $charset = '';
279                 // Look for a charset, first in headers
280                 // Expected form: Content-Type: text/html; charset=ISO-8859-4
281                 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $header, $matches)) {
282                         $charset = trim(trim(trim(array_pop($matches)), ';,'));
283                 }
284
285                 // Then in body that gets precedence
286                 // Expected forms:
287                 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
288                 // - <meta charset="utf-8">
289                 // - <meta charset=utf-8>
290                 // - <meta charSet="utf-8">
291                 // We escape <style> and <script> tags since they can contain irrelevant charset information
292                 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
293                 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
294                         if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
295                                 $charset = trim(trim(trim(array_pop($matches)), ';,'));
296                         }
297                 });
298
299                 $siteinfo['charset'] = $charset;
300
301                 if ($charset && strtoupper($charset) != 'UTF-8') {
302                         // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
303                         $charset = str_ireplace('latin-1', 'latin1', $charset);
304
305                         Logger::log('detected charset ' . $charset, Logger::DEBUG);
306                         $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
307                 }
308
309                 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
310
311                 $doc = new DOMDocument();
312                 @$doc->loadHTML($body);
313
314                 XML::deleteNode($doc, 'style');
315                 XML::deleteNode($doc, 'option');
316                 XML::deleteNode($doc, 'h1');
317                 XML::deleteNode($doc, 'h2');
318                 XML::deleteNode($doc, 'h3');
319                 XML::deleteNode($doc, 'h4');
320                 XML::deleteNode($doc, 'h5');
321                 XML::deleteNode($doc, 'h6');
322                 XML::deleteNode($doc, 'ol');
323                 XML::deleteNode($doc, 'ul');
324
325                 $xpath = new DOMXPath($doc);
326
327                 $list = $xpath->query('//meta[@content]');
328                 foreach ($list as $node) {
329                         $meta_tag = [];
330                         if ($node->attributes->length) {
331                                 foreach ($node->attributes as $attribute) {
332                                         $meta_tag[$attribute->name] = $attribute->value;
333                                 }
334                         }
335
336                         if (@$meta_tag['http-equiv'] == 'refresh') {
337                                 $path = $meta_tag['content'];
338                                 $pathinfo = explode(';', $path);
339                                 $content = '';
340                                 foreach ($pathinfo as $value) {
341                                         if (substr(strtolower($value), 0, 4) == 'url=') {
342                                                 $content = substr($value, 4);
343                                         }
344                                 }
345                                 if ($content != '') {
346                                         $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
347                                         return $siteinfo;
348                                 }
349                         }
350                 }
351
352                 $list = $xpath->query('//title');
353                 if ($list->length > 0) {
354                         $siteinfo['title'] = trim($list->item(0)->nodeValue);
355                 }
356
357                 $list = $xpath->query('//meta[@name]');
358                 foreach ($list as $node) {
359                         $meta_tag = [];
360                         if ($node->attributes->length) {
361                                 foreach ($node->attributes as $attribute) {
362                                         $meta_tag[$attribute->name] = $attribute->value;
363                                 }
364                         }
365
366                         if (empty($meta_tag['content'])) {
367                                 continue;
368                         }
369
370                         $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
371
372                         switch (strtolower($meta_tag['name'])) {
373                                 case 'fulltitle':
374                                         $siteinfo['title'] = trim($meta_tag['content']);
375                                         break;
376                                 case 'description':
377                                         $siteinfo['text'] = trim($meta_tag['content']);
378                                         break;
379                                 case 'thumbnail':
380                                         $siteinfo['image'] = $meta_tag['content'];
381                                         break;
382                                 case 'twitter:image':
383                                         $siteinfo['image'] = $meta_tag['content'];
384                                         break;
385                                 case 'twitter:image:src':
386                                         $siteinfo['image'] = $meta_tag['content'];
387                                         break;
388                                 case 'twitter:card':
389                                         // Detect photo pages
390                                         if ($meta_tag['content'] == 'summary_large_image') {
391                                                 $siteinfo['type'] = 'photo';
392                                         }
393                                         break;
394                                 case 'twitter:description':
395                                         $siteinfo['text'] = trim($meta_tag['content']);
396                                         break;
397                                 case 'twitter:title':
398                                         $siteinfo['title'] = trim($meta_tag['content']);
399                                         break;
400                                 case 'dc.title':
401                                         $siteinfo['title'] = trim($meta_tag['content']);
402                                         break;
403                                 case 'dc.description':
404                                         $siteinfo['text'] = trim($meta_tag['content']);
405                                         break;
406                                 case 'dc.creator':
407                                         $siteinfo['publisher_name'] = trim($meta_tag['content']);
408                                         break;
409                                 case 'keywords':
410                                         $keywords = explode(',', $meta_tag['content']);
411                                         break;
412                                 case 'news_keywords':
413                                         $keywords = explode(',', $meta_tag['content']);
414                                         break;
415                         }
416                 }
417
418                 if (isset($keywords)) {
419                         $siteinfo['keywords'] = [];
420                         foreach ($keywords as $keyword) {
421                                 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
422                                         $siteinfo['keywords'][] = trim($keyword);
423                                 }
424                         }
425                 }
426
427                 $list = $xpath->query('//meta[@property]');
428                 foreach ($list as $node) {
429                         $meta_tag = [];
430                         if ($node->attributes->length) {
431                                 foreach ($node->attributes as $attribute) {
432                                         $meta_tag[$attribute->name] = $attribute->value;
433                                 }
434                         }
435
436                         if (!empty($meta_tag['content'])) {
437                                 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
438
439                                 switch (strtolower($meta_tag['property'])) {
440                                         case 'og:image':
441                                                 $siteinfo['image'] = $meta_tag['content'];
442                                                 break;
443                                         case 'og:image:url':
444                                                 $siteinfo['image'] = $meta_tag['content'];
445                                                 break;
446                                         case 'og:image:secure_url':
447                                                 $siteinfo['image'] = $meta_tag['content'];
448                                                 break;
449                                         case 'og:title':
450                                                 $siteinfo['title'] = trim($meta_tag['content']);
451                                                 break;
452                                         case 'og:description':
453                                                 $siteinfo['text'] = trim($meta_tag['content']);
454                                                 break;
455                                         case 'og:site_name':
456                                                 $siteinfo['publisher_name'] = trim($meta_tag['content']);
457                                                 break;
458                                         case 'twitter:description':
459                                                 $siteinfo['text'] = trim($meta_tag['content']);
460                                                 break;
461                                         case 'twitter:title':
462                                                 $siteinfo['title'] = trim($meta_tag['content']);
463                                                 break;
464                                         case 'twitter:image':
465                                                 $siteinfo['image'] = $meta_tag['content'];
466                                                 break;
467                                 }
468                         }
469                 }
470
471                 $list = $xpath->query("//script[@type='application/ld+json']");
472                 foreach ($list as $node) {
473                         if (!empty($node->nodeValue)) {
474                                 $nodevalue = html_entity_decode($node->nodeValue, ENT_COMPAT, 'UTF-8');
475                                 if ($jsonld = json_decode($nodevalue, true)) {
476                                         if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
477                                                 foreach ($jsonld['@graph'] as $part) {
478                                                         $siteinfo = self::parseJsonLd($siteinfo, $part);
479                                                 }
480                                         } else {
481                                                 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
482                                         }
483                                 }
484                         }
485                 }
486
487                 // Prevent to have a photo type without an image
488                 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
489                         $siteinfo['type'] = 'link';
490                 }
491
492                 if (!empty($siteinfo['image'])) {
493                         $src = self::completeUrl($siteinfo['image'], $url);
494
495                         unset($siteinfo['image']);
496
497                         $photodata = Images::getInfoFromURLCached($src);
498
499                         if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
500                                 $siteinfo['images'][] = ['src' => $src,
501                                         'width' => $photodata[0],
502                                         'height' => $photodata[1]];
503                         }
504                 }
505
506                 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
507                         $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
508                         $pos = mb_strrpos($siteinfo['text'], '.');
509                         if ($pos > self::MIN_DESC_COUNT) {
510                                 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
511                         }
512                 }
513
514                 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
515
516                 Hook::callAll('getsiteinfo', $siteinfo);
517
518                 return $siteinfo;
519         }
520
521         /**
522          * Improve the siteinfo with information from the provided JSON-LD information
523          * @see https://jsonld.com/
524          *
525          * @param array $siteinfo
526          * @param array $jsonld
527          * @return array siteinfo
528          */
529         private static function parseJsonLd(array $siteinfo, array $jsonld)
530         {
531                 $type = JsonLD::fetchElement($jsonld, '@type');
532
533                 switch ($type) {
534                         case 'Article':
535                         case 'NewsArticle':
536                                 return self::parseJsonLdArticle($siteinfo, $jsonld);
537                         case 'WebPage':
538                                 return self::parseJsonLdWebPage($siteinfo, $jsonld);
539                         case 'WebSite':
540                                 return self::parseJsonLdWebSite($siteinfo, $jsonld);
541                         case 'Organization':
542                                 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
543                         case 'Person':
544                                 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
545                         case 'BreadcrumbList':
546                         case 'Audio': /// @todo Can contain direct media links to audio - can be interesting in the future
547                         case 'VideoObject':
548                         case 'ImageObject':
549                         case 'LiveBlogPosting':
550                         case 'SocialMediaPosting':
551                                         // quit silently
552                                 return $siteinfo;
553                         default:
554                                 Logger::info('Unsupported or unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
555                                 return $siteinfo;
556                 }
557         }
558
559         /**
560          * Improve the siteinfo with information from the provided JSON-LD information concerning authors and publishers
561          *
562          * @param array $siteinfo
563          * @param array $jsonld
564          * @return array siteinfo
565          */
566         private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
567         {
568                 $jsonldinfo = [];
569
570                 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
571                         $content = JsonLD::fetchElement($jsonld, 'publisher', 'name', '@type', 'Organization');
572                         if (!empty($content) && is_string($content)) {
573                                 $jsonldinfo['publisher_name'] = trim($content);
574                         }
575
576                         $content = JsonLD::fetchElement($jsonld, 'publisher', 'url', '@type', 'Organization');
577                         if (!empty($content) && is_string($content)) {
578                                 $jsonldinfo['publisher_url'] = trim($content);
579                         }
580
581                         $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
582                         if (!empty($brand)) {
583                                 $content = JsonLD::fetchElement($brand, 'name', '@type', 'brand');
584                                 if (!empty($content) && is_string($content)) {
585                                         $jsonldinfo['publisher_name'] = trim($content);
586                                 }
587                         }
588                 }
589
590                 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
591                         $content = JsonLD::fetchElement($jsonld, 'author', 'name', '@type', 'Organization');
592                         if (!empty($content) && is_string($content)) {
593                                 $jsonldinfo['publisher_name'] = trim($content);
594                         }
595
596                         $content = JsonLD::fetchElement($jsonld, 'author', 'url', '@type', 'Organization');
597                         if (!empty($content) && is_string($content)) {
598                                 $jsonldinfo['publisher_url'] = trim($content);
599                         }
600
601                         $content = JsonLD::fetchElement($jsonld, 'author', 'name', '@type', 'Person');
602                         if (!empty($content) && is_string($content)) {
603                                 $jsonldinfo['author_name'] = trim($content);
604                         }
605
606                         $content = JsonLD::fetchElement($jsonld, 'author', 'url', '@type', 'Person');
607                         if (!empty($content) && is_string($content)) {
608                                 $jsonldinfo['author_url'] = trim($content);
609                         }
610                 }
611
612                 Logger::info('Fetched author information', ['fetched' => $jsonldinfo]);
613
614                 return array_merge($siteinfo, $jsonldinfo);
615         }
616
617         /**
618          * Improve the siteinfo with information from the provided JSON-LD Article information
619          *
620          * @param array $siteinfo
621          * @param array $jsonld
622          * @return array siteinfo
623          */
624         private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
625         {
626                 $jsonldinfo = [];
627
628                 $content = JsonLD::fetchElement($jsonld, 'headline');
629                 if (!empty($content) && is_string($content)) {
630                         $jsonldinfo['title'] = trim($content);
631                 }
632
633                 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
634                 if (!empty($content) && is_string($content)) {
635                         $jsonldinfo['alternative_title'] = trim($content);
636                 }
637
638                 $content = JsonLD::fetchElement($jsonld, 'description');
639                 if (!empty($content) && is_string($content)) {
640                         $jsonldinfo['text'] = trim($content);
641                 }
642
643                 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
644                 if (!empty($content) && is_string($content)) {
645                         $jsonldinfo['image'] = trim($content);
646                 }
647
648 /// @todo Check for the correct separator, also check for dpublicates before adding
649 //              $content = JsonLD::fetchElement($jsonld, 'keywords');
650 //              if (!empty($content) && is_string($content)) {
651 //                      $jsonldinfo['keywords'] = trim($content);
652 //              }
653
654                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
655
656                 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
657
658                 return array_merge($siteinfo, $jsonldinfo);
659         }
660
661         /**
662          * Improve the siteinfo with information from the provided JSON-LD WebPage information
663          *
664          * @param array $siteinfo
665          * @param array $jsonld
666          * @return array siteinfo
667          */
668         private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
669         {
670                 $jsonldinfo = [];
671
672                 $content = JsonLD::fetchElement($jsonld, 'name');
673                 if (!empty($content)) {
674                         $jsonldinfo['title'] = trim($content);
675                 }
676
677                 $content = JsonLD::fetchElement($jsonld, 'description');
678                 if (!empty($content)) {
679                         $jsonldinfo['text'] = trim($content);
680                 }
681
682                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
683                 if (!empty($content)) {
684                         $jsonldinfo['image'] = trim($content);
685                 }
686
687                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
688
689                 Logger::info('Fetched webpage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
690
691                 return array_merge($siteinfo, $jsonldinfo);
692         }
693
694         /**
695          * Improve the siteinfo with information from the provided JSON-LD WebSite information
696          *
697          * @param array $siteinfo
698          * @param array $jsonld
699          * @return array siteinfo
700          */
701         private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
702         {
703                 $jsonldinfo = [];
704
705                 $content = JsonLD::fetchElement($jsonld, 'name');
706                 if (!empty($content)) {
707                         $jsonldinfo['publisher_name'] = trim($content);
708                 }
709
710                 $content = JsonLD::fetchElement($jsonld, 'description');
711                 if (!empty($content)) {
712                         $jsonldinfo['publisher_description'] = trim($content);
713                 }
714
715                 $content = JsonLD::fetchElement($jsonld, 'url');
716                 if (!empty($content)) {
717                         $jsonldinfo['publisher_url'] = trim($content);
718                 }
719
720                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
721                 if (!empty($content)) {
722                         $jsonldinfo['image'] = trim($content);
723                 }
724
725                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
726
727                 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
728                 return array_merge($siteinfo, $jsonldinfo);
729         }
730
731         /**
732          * Improve the siteinfo with information from the provided JSON-LD Organization information
733          *
734          * @param array $siteinfo
735          * @param array $jsonld
736          * @return array siteinfo
737          */
738         private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
739         {
740                 $jsonldinfo = [];
741
742                 $content = JsonLD::fetchElement($jsonld, 'name');
743                 if (!empty($content)) {
744                         $jsonldinfo['publisher_name'] = trim($content);
745                 }
746
747                 $content = JsonLD::fetchElement($jsonld, 'url');
748                 if (!empty($content)) {
749                         $jsonldinfo['publisher_url'] = trim($content);
750                 }
751
752                 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
753                 if (!empty($content)) {
754                         $jsonldinfo['publisher_img'] = trim($content);
755                 }
756
757                 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
758                 return array_merge($siteinfo, $jsonldinfo);
759         }
760
761         /**
762          * Improve the siteinfo with information from the provided JSON-LD Person information
763          *
764          * @param array $siteinfo
765          * @param array $jsonld
766          * @return array siteinfo
767          */
768         private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
769         {
770                 $jsonldinfo = [];
771
772                 $content = JsonLD::fetchElement($jsonld, 'name');
773                 if (!empty($content)) {
774                         $jsonldinfo['author_name'] = trim($content);
775                 }
776
777                 $content = JsonLD::fetchElement($jsonld, 'description');
778                 if (!empty($content)) {
779                         $jsonldinfo['author_description'] = trim($content);
780                 }
781
782                 $content = JsonLD::fetchElement($jsonld, 'url');
783                 if (!empty($content)) {
784                         $jsonldinfo['author_url'] = trim($content);
785                 }
786
787                 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
788                 if (!empty($content)) {
789                         $jsonldinfo['author_img'] = trim($content);
790                 }
791
792                 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
793                 return array_merge($siteinfo, $jsonldinfo);
794         }
795
796         /**
797          * Convert tags from CSV to an array
798          *
799          * @param string $string Tags
800          * @return array with formatted Hashtags
801          */
802         public static function convertTagsToArray($string)
803         {
804                 $arr_tags = str_getcsv($string);
805                 if (count($arr_tags)) {
806                         // add the # sign to every tag
807                         array_walk($arr_tags, ["self", "arrAddHashes"]);
808
809                         return $arr_tags;
810                 }
811         }
812
813         /**
814          * Add a hasht sign to a string
815          *
816          * This method is used as callback function
817          *
818          * @param string $tag The pure tag name
819          * @param int    $k   Counter for internal use
820          * @return void
821          */
822         private static function arrAddHashes(&$tag, $k)
823         {
824                 $tag = "#" . $tag;
825         }
826
827         /**
828          * Add a scheme to an url
829          *
830          * The src attribute of some html elements (e.g. images)
831          * can miss the scheme so we need to add the correct
832          * scheme
833          *
834          * @param string $url    The url which possibly does have
835          *                       a missing scheme (a link to an image)
836          * @param string $scheme The url with a correct scheme
837          *                       (e.g. the url from the webpage which does contain the image)
838          *
839          * @return string The url with a scheme
840          */
841         private static function completeUrl($url, $scheme)
842         {
843                 $urlarr = parse_url($url);
844
845                 // If the url does allready have an scheme
846                 // we can stop the process here
847                 if (isset($urlarr["scheme"])) {
848                         return($url);
849                 }
850
851                 $schemearr = parse_url($scheme);
852
853                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
854
855                 if (!empty($schemearr["port"])) {
856                         $complete .= ":".$schemearr["port"];
857                 }
858
859                 if (!empty($urlarr["path"])) {
860                         if (strpos($urlarr["path"], "/") !== 0) {
861                                 $complete .= "/";
862                         }
863
864                         $complete .= $urlarr["path"];
865                 }
866
867                 if (!empty($urlarr["query"])) {
868                         $complete .= "?".$urlarr["query"];
869                 }
870
871                 if (!empty($urlarr["fragment"])) {
872                         $complete .= "#".$urlarr["fragment"];
873                 }
874
875                 return($complete);
876         }
877 }