]> git.mxchange.org Git - friendica.git/blob - src/Util/ParseUrl.php
Adjusted field names
[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);
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 (isset($oembed_data->title)) {
254                                                 $siteinfo['title'] = trim($oembed_data->title);
255                                         }
256                                         if (isset($oembed_data->description)) {
257                                                 $siteinfo['text'] = trim($oembed_data->description);
258                                         }
259                                         if (isset($oembed_data->thumbnail_url)) {
260                                                 $siteinfo['image'] = $oembed_data->thumbnail_url;
261                                         }
262                                 }
263                         }
264                 }
265
266                 $charset = '';
267                 // Look for a charset, first in headers
268                 // Expected form: Content-Type: text/html; charset=ISO-8859-4
269                 if (preg_match('/charset=([a-z0-9-_.\/]+)/i', $header, $matches)) {
270                         $charset = trim(trim(trim(array_pop($matches)), ';,'));
271                 }
272
273                 // Then in body that gets precedence
274                 // Expected forms:
275                 // - <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
276                 // - <meta charset="utf-8">
277                 // - <meta charset=utf-8>
278                 // - <meta charSet="utf-8">
279                 // We escape <style> and <script> tags since they can contain irrelevant charset information
280                 // (see https://github.com/friendica/friendica/issues/9251#issuecomment-698636806)
281                 Strings::performWithEscapedBlocks($body, '#<(?:style|script).*?</(?:style|script)>#ism', function ($body) use (&$charset) {
282                         if (preg_match('/charset=["\']?([a-z0-9-_.\/]+)/i', $body, $matches)) {
283                                 $charset = trim(trim(trim(array_pop($matches)), ';,'));
284                         }
285                 });
286
287                 $siteinfo['charset'] = $charset;
288
289                 if ($charset && strtoupper($charset) != 'UTF-8') {
290                         // See https://github.com/friendica/friendica/issues/5470#issuecomment-418351211
291                         $charset = str_ireplace('latin-1', 'latin1', $charset);
292
293                         Logger::log('detected charset ' . $charset, Logger::DEBUG);
294                         $body = iconv($charset, 'UTF-8//TRANSLIT', $body);
295                 }
296
297                 $body = mb_convert_encoding($body, 'HTML-ENTITIES', 'UTF-8');
298
299                 $doc = new DOMDocument();
300                 @$doc->loadHTML($body);
301
302                 XML::deleteNode($doc, 'style');
303                 XML::deleteNode($doc, 'option');
304                 XML::deleteNode($doc, 'h1');
305                 XML::deleteNode($doc, 'h2');
306                 XML::deleteNode($doc, 'h3');
307                 XML::deleteNode($doc, 'h4');
308                 XML::deleteNode($doc, 'h5');
309                 XML::deleteNode($doc, 'h6');
310                 XML::deleteNode($doc, 'ol');
311                 XML::deleteNode($doc, 'ul');
312
313                 $xpath = new DOMXPath($doc);
314
315                 $list = $xpath->query('//meta[@content]');
316                 foreach ($list as $node) {
317                         $meta_tag = [];
318                         if ($node->attributes->length) {
319                                 foreach ($node->attributes as $attribute) {
320                                         $meta_tag[$attribute->name] = $attribute->value;
321                                 }
322                         }
323
324                         if (@$meta_tag['http-equiv'] == 'refresh') {
325                                 $path = $meta_tag['content'];
326                                 $pathinfo = explode(';', $path);
327                                 $content = '';
328                                 foreach ($pathinfo as $value) {
329                                         if (substr(strtolower($value), 0, 4) == 'url=') {
330                                                 $content = substr($value, 4);
331                                         }
332                                 }
333                                 if ($content != '') {
334                                         $siteinfo = self::getSiteinfo($content, $no_guessing, $do_oembed, ++$count);
335                                         return $siteinfo;
336                                 }
337                         }
338                 }
339
340                 $list = $xpath->query('//title');
341                 if ($list->length > 0) {
342                         $siteinfo['title'] = trim($list->item(0)->nodeValue);
343                 }
344
345                 $list = $xpath->query('//meta[@name]');
346                 foreach ($list as $node) {
347                         $meta_tag = [];
348                         if ($node->attributes->length) {
349                                 foreach ($node->attributes as $attribute) {
350                                         $meta_tag[$attribute->name] = $attribute->value;
351                                 }
352                         }
353
354                         if (empty($meta_tag['content'])) {
355                                 continue;
356                         }
357
358                         $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
359
360                         switch (strtolower($meta_tag['name'])) {
361                                 case 'fulltitle':
362                                         $siteinfo['title'] = trim($meta_tag['content']);
363                                         break;
364                                 case 'description':
365                                         $siteinfo['text'] = trim($meta_tag['content']);
366                                         break;
367                                 case 'thumbnail':
368                                         $siteinfo['image'] = $meta_tag['content'];
369                                         break;
370                                 case 'twitter:image':
371                                         $siteinfo['image'] = $meta_tag['content'];
372                                         break;
373                                 case 'twitter:image:src':
374                                         $siteinfo['image'] = $meta_tag['content'];
375                                         break;
376                                 case 'twitter:card':
377                                         // Detect photo pages
378                                         if ($meta_tag['content'] == 'summary_large_image') {
379                                                 $siteinfo['type'] = 'photo';
380                                         }
381                                         break;
382                                 case 'twitter:description':
383                                         $siteinfo['text'] = trim($meta_tag['content']);
384                                         break;
385                                 case 'twitter:title':
386                                         $siteinfo['title'] = trim($meta_tag['content']);
387                                         break;
388                                 case 'dc.title':
389                                         $siteinfo['title'] = trim($meta_tag['content']);
390                                         break;
391                                 case 'dc.description':
392                                         $siteinfo['text'] = trim($meta_tag['content']);
393                                         break;
394                                 case 'dc.creator':
395                                         $siteinfo['publisher_name'] = trim($meta_tag['content']);
396                                         break;
397                                 case 'keywords':
398                                         $keywords = explode(',', $meta_tag['content']);
399                                         break;
400                                 case 'news_keywords':
401                                         $keywords = explode(',', $meta_tag['content']);
402                                         break;
403                         }
404                 }
405
406                 if (isset($keywords)) {
407                         $siteinfo['keywords'] = [];
408                         foreach ($keywords as $keyword) {
409                                 if (!in_array(trim($keyword), $siteinfo['keywords'])) {
410                                         $siteinfo['keywords'][] = trim($keyword);
411                                 }
412                         }
413                 }
414
415                 $list = $xpath->query('//meta[@property]');
416                 foreach ($list as $node) {
417                         $meta_tag = [];
418                         if ($node->attributes->length) {
419                                 foreach ($node->attributes as $attribute) {
420                                         $meta_tag[$attribute->name] = $attribute->value;
421                                 }
422                         }
423
424                         if (!empty($meta_tag['content'])) {
425                                 $meta_tag['content'] = trim(html_entity_decode($meta_tag['content'], ENT_QUOTES, 'UTF-8'));
426
427                                 switch (strtolower($meta_tag['property'])) {
428                                         case 'og:image':
429                                                 $siteinfo['image'] = $meta_tag['content'];
430                                                 break;
431                                         case 'og:image:url':
432                                                 $siteinfo['image'] = $meta_tag['content'];
433                                                 break;
434                                         case 'og:image:secure_url':
435                                                 $siteinfo['image'] = $meta_tag['content'];
436                                                 break;
437                                         case 'og:title':
438                                                 $siteinfo['title'] = trim($meta_tag['content']);
439                                                 break;
440                                         case 'og:description':
441                                                 $siteinfo['text'] = trim($meta_tag['content']);
442                                                 break;
443                                         case 'og:site_name':
444                                                 $siteinfo['publisher_name'] = trim($meta_tag['content']);
445                                                 break;
446                                         case 'twitter:description':
447                                                 $siteinfo['text'] = trim($meta_tag['content']);
448                                                 break;
449                                         case 'twitter:title':
450                                                 $siteinfo['title'] = trim($meta_tag['content']);
451                                                 break;
452                                         case 'twitter:image':
453                                                 $siteinfo['image'] = $meta_tag['content'];
454                                                 break;
455                                 }
456                         }
457                 }
458
459                 $list = $xpath->query("//script[@type='application/ld+json']");
460                 foreach ($list as $node) {
461                         if (!empty($node->nodeValue)) {
462                                 $nodevalue = html_entity_decode($node->nodeValue, ENT_COMPAT, 'UTF-8');
463                                 if ($jsonld = json_decode($nodevalue, true)) {
464                                         if (!empty($jsonld['@graph']) && is_array($jsonld['@graph'])) {
465                                                 foreach ($jsonld['@graph'] as $part) {
466                                                         $siteinfo = self::parseJsonLd($siteinfo, $part);
467                                                 }
468                                         } else {
469                                                 $siteinfo = self::parseJsonLd($siteinfo, $jsonld);
470                                         }
471                                 }
472                         }
473                 }
474
475                 // Prevent to have a photo type without an image
476                 if ((empty($siteinfo['image']) || !empty($siteinfo['text'])) && ($siteinfo['type'] == 'photo')) {
477                         $siteinfo['type'] = 'link';
478                 }
479
480                 if (!empty($siteinfo['image'])) {
481                         $src = self::completeUrl($siteinfo['image'], $url);
482
483                         unset($siteinfo['image']);
484
485                         $photodata = Images::getInfoFromURLCached($src);
486
487                         if (($photodata) && ($photodata[0] > 10) && ($photodata[1] > 10)) {
488                                 $siteinfo['images'][] = ['src' => $src,
489                                         'width' => $photodata[0],
490                                         'height' => $photodata[1]];
491                         }
492                 }
493
494                 if (!empty($siteinfo['text']) && mb_strlen($siteinfo['text']) > self::MAX_DESC_COUNT) {
495                         $siteinfo['text'] = mb_substr($siteinfo['text'], 0, self::MAX_DESC_COUNT) . '…';
496                         $pos = mb_strrpos($siteinfo['text'], '.');
497                         if ($pos > self::MIN_DESC_COUNT) {
498                                 $siteinfo['text'] = mb_substr($siteinfo['text'], 0, $pos + 1);
499                         }
500                 }
501
502                 Logger::info('Siteinfo fetched', ['url' => $url, 'siteinfo' => $siteinfo]);
503
504                 Hook::callAll('getsiteinfo', $siteinfo);
505
506                 return $siteinfo;
507         }
508
509         /**
510          * Improve the siteinfo with information from the provided JSON-LD information
511          * @see https://jsonld.com/
512          *
513          * @param array $siteinfo
514          * @param array $jsonld
515          * @return array siteinfo
516          */
517         private static function parseJsonLd(array $siteinfo, array $jsonld)
518         {
519                 $type = JsonLD::fetchElement($jsonld, '@type');
520
521                 switch ($type) {
522                         case 'Article':
523                         case 'NewsArticle':
524                                 return self::parseJsonLdArticle($siteinfo, $jsonld);
525                         case 'WebPage':
526                                 return self::parseJsonLdWebPage($siteinfo, $jsonld);
527                         case 'WebSite':
528                                 return self::parseJsonLdWebSite($siteinfo, $jsonld);
529                         case 'Organization':
530                                 return self::parseJsonLdWebOrganization($siteinfo, $jsonld);
531                         case 'Person':
532                                 return self::parseJsonLdWebPerson($siteinfo, $jsonld);
533                         case 'BreadcrumbList':
534                         case 'Audio': /// @todo Can contain direct media links to audio - can be interesting in the future
535                         case 'VideoObject':
536                         case 'ImageObject':
537                         case 'LiveBlogPosting':
538                         case 'SocialMediaPosting':
539                                         // quit silently
540                                 return $siteinfo;
541                         default:
542                                 Logger::info('Unsupported or unknown type', ['type' => $type, 'url' => $siteinfo['url']]);
543                                 return $siteinfo;
544                 }
545         }
546
547         /**
548          * Improve the siteinfo with information from the provided JSON-LD information concerning authors and publishers
549          *
550          * @param array $siteinfo
551          * @param array $jsonld
552          * @return array siteinfo
553          */
554         private static function parseJsonLdAuthor(array $siteinfo, array $jsonld)
555         {
556                 $jsonldinfo = [];
557
558                 if (!empty($jsonld['publisher']) && is_array($jsonld['publisher'])) {
559                         $content = JsonLD::fetchElement($jsonld, 'publisher', 'name', '@type', 'Organization');
560                         if (!empty($content) && is_string($content)) {
561                                 $jsonldinfo['publisher_name'] = trim($content);
562                         }
563
564                         $content = JsonLD::fetchElement($jsonld, 'publisher', 'url', '@type', 'Organization');
565                         if (!empty($content) && is_string($content)) {
566                                 $jsonldinfo['publisher_url'] = trim($content);
567                         }
568
569                         $brand = JsonLD::fetchElement($jsonld, 'publisher', 'brand', '@type', 'Organization');
570                         if (!empty($brand)) {
571                                 $content = JsonLD::fetchElement($brand, 'name', '@type', 'brand');
572                                 if (!empty($content) && is_string($content)) {
573                                         $jsonldinfo['publisher_name'] = trim($content);
574                                 }
575                         }
576                 }
577
578                 if (!empty($jsonld['author']) && is_array($jsonld['author'])) {
579                         $content = JsonLD::fetchElement($jsonld, 'author', 'name', '@type', 'Organization');
580                         if (!empty($content) && is_string($content)) {
581                                 $jsonldinfo['publisher_name'] = trim($content);
582                         }
583
584                         $content = JsonLD::fetchElement($jsonld, 'author', 'url', '@type', 'Organization');
585                         if (!empty($content) && is_string($content)) {
586                                 $jsonldinfo['publisher_url'] = trim($content);
587                         }
588
589                         $content = JsonLD::fetchElement($jsonld, 'author', 'name', '@type', 'Person');
590                         if (!empty($content) && is_string($content)) {
591                                 $jsonldinfo['author_name'] = trim($content);
592                         }
593
594                         $content = JsonLD::fetchElement($jsonld, 'author', 'url', '@type', 'Person');
595                         if (!empty($content) && is_string($content)) {
596                                 $jsonldinfo['author_url'] = trim($content);
597                         }
598                 }
599
600                 Logger::info('Fetched author information', ['fetched' => $jsonldinfo]);
601
602                 return array_merge($siteinfo, $jsonldinfo);
603         }
604
605         /**
606          * Improve the siteinfo with information from the provided JSON-LD Article information
607          *
608          * @param array $siteinfo
609          * @param array $jsonld
610          * @return array siteinfo
611          */
612         private static function parseJsonLdArticle(array $siteinfo, array $jsonld)
613         {
614                 $jsonldinfo = [];
615
616                 $content = JsonLD::fetchElement($jsonld, 'headline');
617                 if (!empty($content) && is_string($content)) {
618                         $jsonldinfo['title'] = trim($content);
619                 }
620
621                 $content = JsonLD::fetchElement($jsonld, 'alternativeHeadline');
622                 if (!empty($content) && is_string($content)) {
623                         $jsonldinfo['alternative_title'] = trim($content);
624                 }
625
626                 $content = JsonLD::fetchElement($jsonld, 'description');
627                 if (!empty($content) && is_string($content)) {
628                         $jsonldinfo['text'] = trim($content);
629                 }
630
631                 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
632                 if (!empty($content) && is_string($content)) {
633                         $jsonldinfo['image'] = trim($content);
634                 }
635
636 /// @todo Check for the correct separator, also check for dpublicates before adding
637 //              $content = JsonLD::fetchElement($jsonld, 'keywords');
638 //              if (!empty($content) && is_string($content)) {
639 //                      $jsonldinfo['keywords'] = trim($content);
640 //              }
641
642                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
643
644                 Logger::info('Fetched article information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
645
646                 return array_merge($siteinfo, $jsonldinfo);
647         }
648
649         /**
650          * Improve the siteinfo with information from the provided JSON-LD WebPage information
651          *
652          * @param array $siteinfo
653          * @param array $jsonld
654          * @return array siteinfo
655          */
656         private static function parseJsonLdWebPage(array $siteinfo, array $jsonld)
657         {
658                 $jsonldinfo = [];
659
660                 $content = JsonLD::fetchElement($jsonld, 'name');
661                 if (!empty($content)) {
662                         $jsonldinfo['title'] = trim($content);
663                 }
664
665                 $content = JsonLD::fetchElement($jsonld, 'description');
666                 if (!empty($content)) {
667                         $jsonldinfo['text'] = trim($content);
668                 }
669
670                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
671                 if (!empty($content)) {
672                         $jsonldinfo['image'] = trim($content);
673                 }
674
675                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
676
677                 Logger::info('Fetched webpage information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
678
679                 return array_merge($siteinfo, $jsonldinfo);
680         }
681
682         /**
683          * Improve the siteinfo with information from the provided JSON-LD WebSite information
684          *
685          * @param array $siteinfo
686          * @param array $jsonld
687          * @return array siteinfo
688          */
689         private static function parseJsonLdWebSite(array $siteinfo, array $jsonld)
690         {
691                 $jsonldinfo = [];
692
693                 $content = JsonLD::fetchElement($jsonld, 'name');
694                 if (!empty($content)) {
695                         $jsonldinfo['publisher_name'] = trim($content);
696                 }
697
698                 $content = JsonLD::fetchElement($jsonld, 'description');
699                 if (!empty($content)) {
700                         $jsonldinfo['publisher_description'] = trim($content);
701                 }
702
703                 $content = JsonLD::fetchElement($jsonld, 'url');
704                 if (!empty($content)) {
705                         $jsonldinfo['publisher_url'] = trim($content);
706                 }
707
708                 $content = JsonLD::fetchElement($jsonld, 'thumbnailUrl');
709                 if (!empty($content)) {
710                         $jsonldinfo['image'] = trim($content);
711                 }
712
713                 $jsonldinfo = self::parseJsonLdAuthor($jsonldinfo, $jsonld);
714
715                 Logger::info('Fetched WebSite information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
716                 return array_merge($siteinfo, $jsonldinfo);
717         }
718
719         /**
720          * Improve the siteinfo with information from the provided JSON-LD Organization information
721          *
722          * @param array $siteinfo
723          * @param array $jsonld
724          * @return array siteinfo
725          */
726         private static function parseJsonLdWebOrganization(array $siteinfo, array $jsonld)
727         {
728                 $jsonldinfo = [];
729
730                 $content = JsonLD::fetchElement($jsonld, 'name');
731                 if (!empty($content)) {
732                         $jsonldinfo['publisher_name'] = trim($content);
733                 }
734
735                 $content = JsonLD::fetchElement($jsonld, 'url');
736                 if (!empty($content)) {
737                         $jsonldinfo['publisher_url'] = trim($content);
738                 }
739
740                 $content = JsonLD::fetchElement($jsonld, 'logo', 'url', '@type', 'ImageObject');
741                 if (!empty($content)) {
742                         $jsonldinfo['publisher_img'] = trim($content);
743                 }
744
745                 Logger::info('Fetched Organization information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
746                 return array_merge($siteinfo, $jsonldinfo);
747         }
748
749         /**
750          * Improve the siteinfo with information from the provided JSON-LD Person information
751          *
752          * @param array $siteinfo
753          * @param array $jsonld
754          * @return array siteinfo
755          */
756         private static function parseJsonLdWebPerson(array $siteinfo, array $jsonld)
757         {
758                 $jsonldinfo = [];
759
760                 $content = JsonLD::fetchElement($jsonld, 'name');
761                 if (!empty($content)) {
762                         $jsonldinfo['author_name'] = trim($content);
763                 }
764
765                 $content = JsonLD::fetchElement($jsonld, 'description');
766                 if (!empty($content)) {
767                         $jsonldinfo['author_description'] = trim($content);
768                 }
769
770                 $content = JsonLD::fetchElement($jsonld, 'url');
771                 if (!empty($content)) {
772                         $jsonldinfo['author_url'] = trim($content);
773                 }
774
775                 $content = JsonLD::fetchElement($jsonld, 'image', 'url', '@type', 'ImageObject');
776                 if (!empty($content)) {
777                         $jsonldinfo['author_img'] = trim($content);
778                 }
779
780                 Logger::info('Fetched Person information', ['url' => $siteinfo['url'], 'fetched' => $jsonldinfo]);
781                 return array_merge($siteinfo, $jsonldinfo);
782         }
783
784         /**
785          * Convert tags from CSV to an array
786          *
787          * @param string $string Tags
788          * @return array with formatted Hashtags
789          */
790         public static function convertTagsToArray($string)
791         {
792                 $arr_tags = str_getcsv($string);
793                 if (count($arr_tags)) {
794                         // add the # sign to every tag
795                         array_walk($arr_tags, ["self", "arrAddHashes"]);
796
797                         return $arr_tags;
798                 }
799         }
800
801         /**
802          * Add a hasht sign to a string
803          *
804          * This method is used as callback function
805          *
806          * @param string $tag The pure tag name
807          * @param int    $k   Counter for internal use
808          * @return void
809          */
810         private static function arrAddHashes(&$tag, $k)
811         {
812                 $tag = "#" . $tag;
813         }
814
815         /**
816          * Add a scheme to an url
817          *
818          * The src attribute of some html elements (e.g. images)
819          * can miss the scheme so we need to add the correct
820          * scheme
821          *
822          * @param string $url    The url which possibly does have
823          *                       a missing scheme (a link to an image)
824          * @param string $scheme The url with a correct scheme
825          *                       (e.g. the url from the webpage which does contain the image)
826          *
827          * @return string The url with a scheme
828          */
829         private static function completeUrl($url, $scheme)
830         {
831                 $urlarr = parse_url($url);
832
833                 // If the url does allready have an scheme
834                 // we can stop the process here
835                 if (isset($urlarr["scheme"])) {
836                         return($url);
837                 }
838
839                 $schemearr = parse_url($scheme);
840
841                 $complete = $schemearr["scheme"]."://".$schemearr["host"];
842
843                 if (!empty($schemearr["port"])) {
844                         $complete .= ":".$schemearr["port"];
845                 }
846
847                 if (!empty($urlarr["path"])) {
848                         if (strpos($urlarr["path"], "/") !== 0) {
849                                 $complete .= "/";
850                         }
851
852                         $complete .= $urlarr["path"];
853                 }
854
855                 if (!empty($urlarr["query"])) {
856                         $complete .= "?".$urlarr["query"];
857                 }
858
859                 if (!empty($urlarr["fragment"])) {
860                         $complete .= "#".$urlarr["fragment"];
861                 }
862
863                 return($complete);
864         }
865 }