]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Feed.php
6b73e7af098020a85196e102176ebdc98533f9cd
[friendica.git] / src / Protocol / Feed.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\Protocol;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Friendica\Content\PageInfo;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Cache\Duration;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Item;
36 use Friendica\Model\Tag;
37 use Friendica\Model\User;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Network;
40 use Friendica\Util\ParseUrl;
41 use Friendica\Util\Strings;
42 use Friendica\Util\XML;
43
44 /**
45  * This class contain functions to import feeds (RSS/RDF/Atom)
46  */
47 class Feed
48 {
49         /**
50          * consume - process atom feed and update anything/everything we might need to update
51          *
52          * $xml = the (atom) feed to consume - RSS isn't as fully supported but may work for simple feeds.
53          *
54          * $importer = the contact_record (joined to user_record) of the local user who owns this relationship.
55          *             It is this person's stuff that is going to be updated.
56          * $contact =  the person who is sending us stuff. If not set, we MAY be processing a "follow" activity
57          *             from an external network and MAY create an appropriate contact record. Otherwise, we MUST
58          *             have a contact record.
59          * $hub = should we find a hub declation in the feed, pass it back to our calling process, who might (or
60          *        might not) try and subscribe to it.
61          * $datedir sorts in reverse order
62          * $pass - by default ($pass = 0) we cannot guarantee that a parent item has been
63          *      imported prior to its children being seen in the stream unless we are certain
64          *      of how the feed is arranged/ordered.
65          * With $pass = 1, we only pull parent items out of the stream.
66          * With $pass = 2, we only pull children (comments/likes).
67          *
68          * So running this twice, first with pass 1 and then with pass 2 will do the right
69          * thing regardless of feed ordering. This won't be adequate in a fully-threaded
70          * model where comments can have sub-threads. That would require some massive sorting
71          * to get all the feed items into a mostly linear ordering, and might still require
72          * recursion.
73          *
74          * @param       $xml
75          * @param array $importer
76          * @param array $contact
77          * @param       $hub
78          * @throws ImagickException
79          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
80          */
81         public static function consume($xml, array $importer, array $contact, &$hub)
82         {
83                 if ($contact['network'] === Protocol::OSTATUS) {
84                         Logger::info('Consume OStatus messages');
85                         OStatus::import($xml, $importer, $contact, $hub);
86
87                         return;
88                 }
89
90                 if ($contact['network'] === Protocol::FEED) {
91                         Logger::info('Consume feeds');
92                         self::import($xml, $importer, $contact);
93
94                         return;
95                 }
96
97                 if ($contact['network'] === Protocol::DFRN) {
98                         Logger::info('Consume DFRN messages');
99                         $dfrn_importer = DFRN::getImporter($contact['id'], $importer['uid']);
100                         if (!empty($dfrn_importer)) {
101                                 Logger::info('Now import the DFRN feed');
102                                 DFRN::import($xml, $dfrn_importer, true);
103                                 return;
104                         }
105                 }
106         }
107
108         /**
109          * Read a RSS/RDF/Atom feed and create an item entry for it
110          *
111          * @param string $xml      The feed data
112          * @param array  $importer The user record of the importer
113          * @param array  $contact  The contact record of the feed
114          *
115          * @return array Returns the header and the first item in dry run mode
116          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
117          */
118         public static function import($xml, array $importer = [], array $contact = [])
119         {
120                 $dryRun = empty($importer) && empty($contact);
121
122                 if ($dryRun) {
123                         Logger::info("Test Atom/RSS feed");
124                 } else {
125                         Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
126                 }
127
128                 if (empty($xml)) {
129                         Logger::info('XML is empty.');
130                         return [];
131                 }
132
133                 if (!empty($contact['poll'])) {
134                         $basepath = $contact['poll'];
135                 } elseif (!empty($contact['url'])) {
136                         $basepath = $contact['url'];
137                 } else {
138                         $basepath = '';
139                 }
140
141                 $doc = new DOMDocument();
142                 @$doc->loadXML(trim($xml));
143                 $xpath = new DOMXPath($doc);
144                 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
145                 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
146                 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
147                 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
148                 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
149                 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
150                 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
151
152                 $author = [];
153                 $entries = null;
154
155                 // Is it RDF?
156                 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
157                         $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
158                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
159
160                         if (empty($author["author-name"])) {
161                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
162                         }
163                         $entries = $xpath->query('/rdf:RDF/rss:item');
164                 }
165
166                 // Is it Atom?
167                 if ($xpath->query('/atom:feed')->length > 0) {
168                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
169                         if (is_object($alternate)) {
170                                 foreach ($alternate AS $attribute) {
171                                         if ($attribute->name == "href") {
172                                                 $author["author-link"] = $attribute->textContent;
173                                         }
174                                 }
175                         }
176
177                         if (empty($author["author-link"])) {
178                                 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
179                                 if (is_object($self)) {
180                                         foreach ($self AS $attribute) {
181                                                 if ($attribute->name == "href") {
182                                                         $author["author-link"] = $attribute->textContent;
183                                                 }
184                                         }
185                                 }
186                         }
187
188                         if (empty($author["author-link"])) {
189                                 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
190                         }
191                         $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
192
193                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
194
195                         if (empty($author["author-name"])) {
196                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
197                         }
198
199                         if (empty($author["author-name"])) {
200                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
201                         }
202
203                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
204                         if ($value != "") {
205                                 $author["author-name"] = $value;
206                         }
207
208                         if ($dryRun) {
209                                 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
210
211                                 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
212                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
213                                 if ($value != "") {
214                                         $author["author-link"] = $value;
215                                 }
216
217                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
218                                 if ($value != "") {
219                                         $author["author-nick"] = $value;
220                                 }
221
222                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
223                                 if ($value != "") {
224                                         $author["author-location"] = $value;
225                                 }
226
227                                 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
228                                 if ($value != "") {
229                                         $author["author-about"] = $value;
230                                 }
231
232                                 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
233                                 if (is_object($avatar)) {
234                                         foreach ($avatar AS $attribute) {
235                                                 if ($attribute->name == "href") {
236                                                         $author["author-avatar"] = $attribute->textContent;
237                                                 }
238                                         }
239                                 }
240                         }
241
242                         $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
243
244                         $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
245
246                         $entries = $xpath->query('/atom:feed/atom:entry');
247                 }
248
249                 // Is it RSS?
250                 if ($xpath->query('/rss/channel')->length > 0) {
251                         $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
252
253                         $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
254                         $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
255
256                         if (empty($author["author-name"])) {
257                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
258                         }
259
260                         if (empty($author["author-name"])) {
261                                 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
262                         }
263
264                         $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
265
266                         $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
267
268                         $entries = $xpath->query('/rss/channel/item');
269                 }
270
271                 if (!$dryRun) {
272                         $author["author-link"] = $contact["url"];
273
274                         if (empty($author["author-name"])) {
275                                 $author["author-name"] = $contact["name"];
276                         }
277
278                         $author["author-avatar"] = $contact["thumb"];
279
280                         $author["owner-link"] = $contact["url"];
281                         $author["owner-name"] = $contact["name"];
282                         $author["owner-avatar"] = $contact["thumb"];
283                 }
284
285                 $header = [];
286                 $header["uid"] = $importer["uid"] ?? 0;
287                 $header["network"] = Protocol::FEED;
288                 $header["wall"] = 0;
289                 $header["origin"] = 0;
290                 $header["gravity"] = GRAVITY_PARENT;
291                 $header["private"] = Item::PUBLIC;
292                 $header["verb"] = Activity::POST;
293                 $header["object-type"] = Activity\ObjectType::NOTE;
294
295                 $header["contact-id"] = $contact["id"] ?? 0;
296
297                 if (!is_object($entries)) {
298                         Logger::info("There are no entries in this feed.");
299                         return [];
300                 }
301
302                 $items = [];
303                 $creation_dates = [];
304
305                 // Limit the number of items that are about to be fetched
306                 $total_items = ($entries->length - 1);
307                 $max_items = DI::config()->get('system', 'max_feed_items');
308                 if (($max_items > 0) && ($total_items > $max_items)) {
309                         $total_items = $max_items;
310                 }
311
312                 // Importing older entries first
313                 for ($i = $total_items; $i >= 0; --$i) {
314                         $entry = $entries->item($i);
315
316                         $item = array_merge($header, $author);
317
318                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
319                         if (!is_object($alternate)) {
320                                 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
321                         }
322                         if (is_object($alternate)) {
323                                 foreach ($alternate AS $attribute) {
324                                         if ($attribute->name == "href") {
325                                                 $item["plink"] = $attribute->textContent;
326                                         }
327                                 }
328                         }
329
330                         if (empty($item["plink"])) {
331                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
332                         }
333
334                         if (empty($item["plink"])) {
335                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
336                         }
337
338                         $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
339
340                         if (empty($item["uri"])) {
341                                 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
342                         }
343
344                         if (empty($item["uri"])) {
345                                 $item["uri"] = $item["plink"];
346                         }
347
348                         // Add the base path if missing
349                         $item["uri"] = Network::addBasePath($item["uri"], $basepath);
350                         $item["plink"] = Network::addBasePath($item["plink"], $basepath);
351
352                         $orig_plink = $item["plink"];
353
354                         $item["parent-uri"] = $item["uri"];
355
356                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
357
358                         if (empty($item["title"])) {
359                                 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
360                         }
361                         if (empty($item["title"])) {
362                                 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
363                         }
364
365                         $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
366
367                         $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
368
369                         if (empty($published)) {
370                                 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
371                         }
372
373                         if (empty($published)) {
374                                 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
375                         }
376
377                         $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
378
379                         if (empty($updated) && !empty($published)) {
380                                 $updated = $published;
381                         }
382
383                         if (empty($published) && !empty($updated)) {
384                                 $published = $updated;
385                         }
386
387                         if ($published != "") {
388                                 $item["created"] = $published;
389                         }
390
391                         if ($updated != "") {
392                                 $item["edited"] = $updated;
393                         }
394
395                         if (!$dryRun) {
396                                 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
397                                         $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
398                                 $previous = Item::selectFirst(['id', 'created'], $condition);
399                                 if (DBA::isResult($previous)) {
400                                         // Use the creation date when the post had been stored. It can happen this date changes in the feed.
401                                         $creation_dates[] = $previous['created'];
402                                         Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
403                                         continue;
404                                 }
405                                 $creation_dates[] = DateTimeFormat::utc($item['created']);
406                         }
407
408                         $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
409
410                         if (empty($creator)) {
411                                 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
412                         }
413
414                         if (empty($creator)) {
415                                 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
416                         }
417
418                         if ($creator != "") {
419                                 $item["author-name"] = $creator;
420                         }
421
422                         $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
423
424                         if ($creator != "") {
425                                 $item["author-name"] = $creator;
426                         }
427
428                         /// @TODO ?
429                         // <category>Ausland</category>
430                         // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
431
432                         $attachments = [];
433
434                         $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
435                         foreach ($enclosures AS $enclosure) {
436                                 $href = "";
437                                 $length = "";
438                                 $type = "";
439
440                                 foreach ($enclosure->attributes AS $attribute) {
441                                         if (in_array($attribute->name, ["url", "href"])) {
442                                                 $href = $attribute->textContent;
443                                         } elseif ($attribute->name == "length") {
444                                                 $length = $attribute->textContent;
445                                         } elseif ($attribute->name == "type") {
446                                                 $type = $attribute->textContent;
447                                         }
448                                 }
449
450                                 if (!empty($item["attach"])) {
451                                         $item["attach"] .= ',';
452                                 } else {
453                                         $item["attach"] = '';
454                                 }
455
456                                 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
457
458                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '"[/attach]';
459                         }
460
461                         $taglist = [];
462                         $categories = $xpath->query("category", $entry);
463                         foreach ($categories AS $category) {
464                                 $taglist[] = $category->nodeValue;
465                         }
466
467                         $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
468
469                         if (empty($body)) {
470                                 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
471                         }
472
473                         $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
474
475                         if (empty($summary)) {
476                                 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
477                         }
478
479                         if (empty($body)) {
480                                 $body = $summary;
481                                 $summary = '';
482                         }
483
484                         if ($body == $summary) {
485                                 $summary = '';
486                         }
487
488                         // remove the content of the title if it is identically to the body
489                         // This helps with auto generated titles e.g. from tumblr
490                         if (self::titleIsBody($item["title"], $body)) {
491                                 $item["title"] = "";
492                         }
493                         $item["body"] = HTML::toBBCode($body, $basepath);
494
495                         if (($item["body"] == '') && ($item["title"] != '')) {
496                                 $item["body"] = $item["title"];
497                                 $item["title"] = '';
498                         }
499
500                         if ($dryRun) {
501                                 $items[] = $item;
502                                 break;
503                         } elseif (!Item::isValid($item)) {
504                                 Logger::info('Feed is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
505                                 continue;
506                         }
507
508                         $preview = '';
509                         if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
510                                 // Handle enclosures and treat them as preview picture
511                                 foreach ($attachments AS $attachment) {
512                                         if ($attachment["type"] == "image/jpeg") {
513                                                 $preview = $attachment["link"];
514                                         }
515                                 }
516
517                                 // Remove a possible link to the item itself
518                                 $item["body"] = str_replace($item["plink"], '', $item["body"]);
519                                 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
520
521                                 // Replace the content when the title is longer than the body
522                                 $replace = (strlen($item["title"]) > strlen($item["body"]));
523
524                                 // Replace it, when there is an image in the body
525                                 if (strstr($item["body"], '[/img]')) {
526                                         $replace = true;
527                                 }
528
529                                 // Replace it, when there is a link in the body
530                                 if (strstr($item["body"], '[/url]')) {
531                                         $replace = true;
532                                 }
533
534                                 if ($replace) {
535                                         $item["body"] = trim($item["title"]);
536                                 }
537
538                                 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
539                                 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
540                                         // When the fetched page info text is longer than the body, we do try to enhance the body
541                                         if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
542                                                 // The body is not part of the fetched page info title or page info text. So we add the text to the body
543                                                 $item['body'] .= "\n\n" . $data['text'];
544                                         } else {
545                                                 // Else we replace the body with the page info text
546                                                 $item['body'] = $data['text'];
547                                         }
548                                 }
549
550                                 // We always strip the title since it will be added in the page information
551                                 $item["title"] = "";
552                                 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
553                                 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
554                                 $item["object-type"] = Activity\ObjectType::BOOKMARK;
555                                 unset($item["attach"]);
556                         } else {
557                                 if (!empty($summary)) {
558                                         $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
559                                 }
560
561                                 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
562                                         if (empty($taglist)) {
563                                                 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
564                                         }
565                                         $item["body"] .= "\n" . self::tagToString($taglist);
566                                 } else {
567                                         $taglist = [];
568                                 }
569
570                                 // Add the link to the original feed entry if not present in feed
571                                 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
572                                         $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
573                                 }
574                         }
575
576                         Logger::info('Stored feed', ['item' => $item]);
577
578                         $notify = Item::isRemoteSelf($contact, $item);
579
580                         // Distributed items should have a well formatted URI.
581                         // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
582                         if ($notify) {
583                                 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
584                                 unset($item['uri']);
585                                 unset($item['parent-uri']);
586
587                                 // Set the delivery priority for "remote self" to "medium"
588                                 $notify = PRIORITY_MEDIUM;
589                         }
590
591                         $id = Item::insert($item, $notify);
592
593                         Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
594
595                         if (!empty($id) && !empty($taglist)) {
596                                 $feeditem = Item::selectFirst(['uri-id'], ['id' => $id]);
597                                 foreach ($taglist as $tag) {
598                                         Tag::store($feeditem['uri-id'], Tag::HASHTAG, $tag);
599                                 }
600                         }
601                 }
602
603                 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
604                         self::adjustPollFrequency($contact, $creation_dates);
605                 }
606
607                 return ["header" => $author, "items" => $items];
608         }
609
610         /**
611          * Automatically adjust the poll frequency according to the post frequency
612          *
613          * @param array $contact
614          * @param array $creation_dates
615          * @return void
616          */
617         private static function adjustPollFrequency(array $contact, array $creation_dates)
618         {
619                 if ($contact['network'] != Protocol::FEED) {
620                         Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
621                         return;
622                 }
623
624                 if (!empty($creation_dates)) {
625                         // Count the post frequency and the earliest and latest post date
626                         $frequency = [];
627                         $oldest = time();
628                         $newest = 0;
629                         $oldest_date = $newest_date = '';
630
631                         foreach ($creation_dates as $date) {
632                                 $timestamp = strtotime($date);
633                                 $day = intdiv($timestamp, 86400);
634                                 $hour = $timestamp % 86400;
635
636                                 // Only have a look at values from the last seven days
637                                 if (((time() / 86400) - $day) < 7) {
638                                         if (empty($frequency[$day])) {
639                                                 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
640                                         } else {
641                                                 ++$frequency[$day]['count'];
642                                                 if ($frequency[$day]['low'] > $hour) {
643                                                         $frequency[$day]['low'] = $hour;
644                                                 }
645                                                 if ($frequency[$day]['high'] < $hour) {
646                                                         $frequency[$day]['high'] = $hour;
647                                                 }
648                                         }
649                                 }
650                                 if ($oldest > $day) {
651                                         $oldest = $day;
652                                         $oldest_date = $date;
653                                 }
654                         
655                                 if ($newest < $day) {
656                                         $newest = $day;
657                                         $newest_date = $date;
658                                 }
659                         }
660
661                         if (count($creation_dates) == 1) {
662                                 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
663                                 $priority = 8; // Poll once a day
664                         }
665
666                         if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
667                                 Logger::info('Feed had not posted for two years, switching to monthly polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
668                                 $priority = 10; // Poll every month
669                         }
670
671                         if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
672                                 Logger::info('Feed had not posted for a year, switching to weekly polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
673                                 $priority = 9; // Poll every week
674                         }
675
676                         if (empty($priority) && empty($frequency)) {
677                                 Logger::info('Feed had not posted for at least a week, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
678                                 $priority = 8; // Poll once a day
679                         }
680
681                         if (empty($priority)) {
682                                 // Calculate the highest "posts per day" value
683                                 $max = 0;
684                                 foreach ($frequency as $entry) {
685                                         if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
686                                                 continue;
687                                         }
688
689                                         // We take the earliest and latest post day and interpolate the number of post per day
690                                         // that would had been created with this post frequency
691
692                                         // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
693                                         $duration = max($entry['high'] - $entry['low'], 14400);
694                                         $ppd = (86400 / $duration) * $entry['count'];
695                                         if ($ppd > $max) {
696                                                 $max = $ppd;
697                                         }
698                                 }
699                                 if ($max > 48) {
700                                         $priority = 1; // Poll every quarter hour
701                                 } elseif ($max > 24) {
702                                         $priority = 2; // Poll half an hour
703                                 } elseif ($max > 12) {
704                                         $priority = 3; // Poll hourly
705                                 } elseif ($max > 8) {
706                                         $priority = 4; // Poll every two hours
707                                 } elseif ($max > 4) {
708                                         $priority = 5; // Poll every three hours
709                                 } elseif ($max > 2) {
710                                         $priority = 6; // Poll every six hours
711                                 } else {
712                                         $priority = 7; // Poll twice a day
713                                 }
714                                 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
715                         }
716                 } else {
717                         Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
718                         $priority = 8; // Poll once a day
719                 }
720
721                 if ($contact['rating'] != $priority) {
722                         Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
723                         DBA::update('contact', ['rating' => $priority], ['id' => $contact['id']]);
724                 }
725         }
726
727         /**
728          * Convert a tag array to a tag string
729          *
730          * @param array $tags
731          * @return string tag string
732          */
733         private static function tagToString(array $tags)
734         {
735                 $tagstr = '';
736
737                 foreach ($tags as $tag) {
738                         if ($tagstr != "") {
739                                 $tagstr .= ", ";
740                         }
741         
742                         $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
743                 }
744
745                 return $tagstr;
746         }
747
748         private static function titleIsBody($title, $body)
749         {
750                 $title = strip_tags($title);
751                 $title = trim($title);
752                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
753                 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
754
755                 $body = strip_tags($body);
756                 $body = trim($body);
757                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
758                 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
759
760                 if (strlen($title) < strlen($body)) {
761                         $body = substr($body, 0, strlen($title));
762                 }
763
764                 if (($title != $body) && (substr($title, -3) == "...")) {
765                         $pos = strrpos($title, "...");
766                         if ($pos > 0) {
767                                 $title = substr($title, 0, $pos);
768                                 $body = substr($body, 0, $pos);
769                         }
770                 }
771                 return ($title == $body);
772         }
773
774         /**
775          * Creates the Atom feed for a given nickname
776          *
777          * Supported filters:
778          * - activity (default): all the public posts
779          * - posts: all the public top-level posts
780          * - comments: all the public replies
781          *
782          * Updates the provided last_update parameter if the result comes from the
783          * cache or it is empty
784          *
785          * @param string  $owner_nick  Nickname of the feed owner
786          * @param string  $last_update Date of the last update
787          * @param integer $max_items   Number of maximum items to fetch
788          * @param string  $filter      Feed items filter (activity, posts or comments)
789          * @param boolean $nocache     Wether to bypass caching
790          *
791          * @return string Atom feed
792          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
793          * @throws \ImagickException
794          */
795         public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
796         {
797                 $stamp = microtime(true);
798
799                 $owner = User::getOwnerDataByNick($owner_nick);
800                 if (!$owner) {
801                         return;
802                 }
803
804                 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
805
806                 $previous_created = $last_update;
807
808                 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
809                 if ((time() - strtotime($owner['last-item'])) < 15*60) {
810                         $result = DI::cache()->get($cachekey);
811                         if (!$nocache && !is_null($result)) {
812                                 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
813                                 return $result['feed'];
814                         }
815                 }
816
817                 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
818                 $authorid = Contact::getIdForURL($owner["url"]);
819
820                 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
821                         AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
822                         $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
823                         Item::PRIVATE, Protocol::ACTIVITYPUB,
824                         Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
825
826                 if ($filter === 'comments') {
827                         $condition[0] .= " AND `object-type` = ? ";
828                         $condition[] = Activity\ObjectType::COMMENT;
829                 }
830
831                 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
832                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
833                         $condition[] = $owner["id"];
834                         $condition[] = $authorid;
835                 }
836
837                 $params = ['order' => ['received' => true], 'limit' => $max_items];
838
839                 if ($filter === 'posts') {
840                         $ret = Item::selectThread([], $condition, $params);
841                 } else {
842                         $ret = Item::select([], $condition, $params);
843                 }
844
845                 $items = Item::inArray($ret);
846
847                 $doc = new DOMDocument('1.0', 'utf-8');
848                 $doc->formatOutput = true;
849
850                 $root = self::addHeader($doc, $owner, $filter);
851
852                 foreach ($items as $item) {
853                         $entry = self::entry($doc, $item, $owner);
854                         $root->appendChild($entry);
855
856                         if ($last_update < $item['created']) {
857                                 $last_update = $item['created'];
858                         }
859                 }
860
861                 $feeddata = trim($doc->saveXML());
862
863                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
864                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
865
866                 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
867
868                 return $feeddata;
869         }
870
871         /**
872          * Adds the header elements to the XML document
873          *
874          * @param DOMDocument $doc       XML document
875          * @param array       $owner     Contact data of the poster
876          * @param string      $filter    The related feed filter (activity, posts or comments)
877          *
878          * @return object header root element
879          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
880          */
881         private static function addHeader(DOMDocument $doc, array $owner, $filter)
882         {
883                 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
884                 $doc->appendChild($root);
885
886                 $title = '';
887                 $selfUri = '/feed/' . $owner["nick"] . '/';
888                 switch ($filter) {
889                         case 'activity':
890                                 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
891                                 $selfUri .= $filter;
892                                 break;
893                         case 'posts':
894                                 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
895                                 break;
896                         case 'comments':
897                                 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
898                                 $selfUri .= $filter;
899                                 break;
900                 }
901
902                 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
903                 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
904                 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
905                 XML::addElement($doc, $root, "title", $title);
906                 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
907                 XML::addElement($doc, $root, "logo", $owner["photo"]);
908                 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
909
910                 $author = self::addAuthor($doc, $owner);
911                 $root->appendChild($author);
912
913                 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
914                 XML::addElement($doc, $root, "link", "", $attributes);
915
916                 OStatus::hublinks($doc, $root, $owner["nick"]);
917
918                 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
919                 XML::addElement($doc, $root, "link", "", $attributes);
920
921                 return $root;
922         }
923
924         /**
925          * Adds the author element to the XML document
926          *
927          * @param DOMDocument $doc          XML document
928          * @param array       $owner        Contact data of the poster
929          *
930          * @return \DOMElement author element
931          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
932          */
933         private static function addAuthor(DOMDocument $doc, array $owner)
934         {
935                 $author = $doc->createElement("author");
936                 XML::addElement($doc, $author, "uri", $owner["url"]);
937                 XML::addElement($doc, $author, "name", $owner["nick"]);
938                 XML::addElement($doc, $author, "email", $owner["addr"]);
939
940                 return $author;
941         }
942
943         /**
944          * Adds an entry element to the XML document
945          *
946          * @param DOMDocument $doc       XML document
947          * @param array       $item      Data of the item that is to be posted
948          * @param array       $owner     Contact data of the poster
949          * @param bool        $toplevel  optional default false
950          *
951          * @return \DOMElement Entry element
952          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
953          * @throws \ImagickException
954          */
955         private static function entry(DOMDocument $doc, array $item, array $owner)
956         {
957                 $xml = null;
958
959                 $repeated_guid = OStatus::getResharedGuid($item);
960                 if ($repeated_guid != "") {
961                         $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid);
962                 }
963
964                 if ($xml) {
965                         return $xml;
966                 }
967
968                 return self::noteEntry($doc, $item, $owner);
969         }
970
971                 /**
972          * Adds an entry element with reshared content
973          *
974          * @param DOMDocument $doc           XML document
975          * @param array       $item          Data of the item that is to be posted
976          * @param array       $owner         Contact data of the poster
977          * @param string      $repeated_guid guid
978          * @param bool        $toplevel      Is it for en entry element (false) or a feed entry (true)?
979          *
980          * @return bool Entry element
981          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
982          * @throws \ImagickException
983          */
984         private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid)
985         {
986                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
987                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
988                 }
989
990                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
991
992                 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
993                         'network' => Protocol::FEDERATED];
994                 $repeated_item = Item::selectFirst([], $condition);
995                 if (!DBA::isResult($repeated_item)) {
996                         return false;
997                 }
998
999                 self::entryContent($doc, $entry, $item, self::getTitle($repeated_item), Activity::SHARE, false);
1000
1001                 self::entryFooter($doc, $entry, $item, $owner);
1002
1003                 return $entry;
1004         }
1005
1006         /**
1007          * Adds a regular entry element
1008          *
1009          * @param DOMDocument $doc       XML document
1010          * @param array       $item      Data of the item that is to be posted
1011          * @param array       $owner     Contact data of the poster
1012          * @param bool        $toplevel  Is it for en entry element (false) or a feed entry (true)?
1013          *
1014          * @return \DOMElement Entry element
1015          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1016          * @throws \ImagickException
1017          */
1018         private static function noteEntry(DOMDocument $doc, array $item, array $owner)
1019         {
1020                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1021                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1022                 }
1023
1024                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1025
1026                 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1027
1028                 self::entryFooter($doc, $entry, $item, $owner);
1029
1030                 return $entry;
1031         }
1032
1033         /**
1034          * Adds elements to the XML document
1035          *
1036          * @param DOMDocument $doc       XML document
1037          * @param \DOMElement $entry     Entry element where the content is added
1038          * @param array       $item      Data of the item that is to be posted
1039          * @param array       $owner     Contact data of the poster
1040          * @param string      $title     Title for the post
1041          * @param string      $verb      The activity verb
1042          * @param bool        $complete  Add the "status_net" element?
1043          * @param bool        $feed_mode Behave like a regular feed for users if true
1044          * @return void
1045          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1046          */
1047         private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
1048         {
1049                 if ($verb == "") {
1050                         $verb = OStatus::constructVerb($item);
1051                 }
1052
1053                 XML::addElement($doc, $entry, "id", $item["uri"]);
1054                 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1055
1056                 $body = OStatus::formatPicturePost($item['body']);
1057
1058                 $body = BBCode::convert($body, false, BBCode::OSTATUS);
1059
1060                 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1061
1062                 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1063                                                                 "href" => DI::baseUrl()."/display/".$item["guid"]]
1064                 );
1065
1066                 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1067                 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1068         }
1069
1070         /**
1071          * Adds the elements at the foot of an entry to the XML document
1072          *
1073          * @param DOMDocument $doc       XML document
1074          * @param object      $entry     The entry element where the elements are added
1075          * @param array       $item      Data of the item that is to be posted
1076          * @param array       $owner     Contact data of the poster
1077          * @param bool        $complete  default true
1078          * @return void
1079          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1080          */
1081         private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1082         {
1083                 $mentioned = [];
1084
1085                 if ($item['gravity'] != GRAVITY_PARENT) {
1086                         $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1087                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1088
1089                         $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
1090
1091                         if (DBA::isResult($thrparent)) {
1092                                 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1093                                 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1094                                 $parent_plink = $thrparent["plink"];
1095                         } else {
1096                                 $mentioned[$parent["author-link"]] = $parent["author-link"];
1097                                 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1098                                 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
1099                         }
1100
1101                         $attributes = [
1102                                         "ref" => $parent_item,
1103                                         "href" => $parent_plink];
1104                         XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1105
1106                         $attributes = [
1107                                         "rel" => "related",
1108                                         "href" => $parent_plink];
1109                         XML::addElement($doc, $entry, "link", "", $attributes);
1110                 }
1111
1112                 // uri-id isn't present for follow entry pseudo-items
1113                 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1114                 foreach ($tags as $tag) {
1115                         $mentioned[$tag['url']] = $tag['url'];
1116                 }
1117
1118                 foreach ($tags as $tag) {
1119                         if ($tag['type'] == Tag::HASHTAG) {
1120                                 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
1121                         }
1122                 }
1123
1124                 OStatus::getAttachment($doc, $entry, $item);
1125         }
1126
1127         /**
1128          * Fetch or create title for feed entry
1129          *
1130          * @param array $item
1131          * @return string title
1132          */
1133         private static function getTitle(array $item)
1134         {
1135                 if ($item['title'] != '') {
1136                         return BBCode::convert($item['title'], false, BBCode::OSTATUS);
1137                 }
1138
1139                 // Fetch information about the post
1140                 $siteinfo = BBCode::getAttachedData($item["body"]);
1141                 if (isset($siteinfo["title"])) {
1142                         return $siteinfo["title"];
1143                 }
1144
1145                 // If no bookmark is found then take the first line
1146                 // Remove the share element before fetching the first line
1147                 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1148
1149                 $title = HTML::toPlaintext(BBCode::convert($title, false), 0, true)."\n";
1150                 $pos = strpos($title, "\n");
1151                 $trailer = "";
1152                 if (($pos == 0) || ($pos > 100)) {
1153                         $pos = 100;
1154                         $trailer = "...";
1155                 }
1156
1157                 return substr($title, 0, $pos) . $trailer;
1158         }
1159 }