]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Feed.php
9ba2089c13af5a49114d02e84f534be015a2fb2d
[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["plink"] = DI::httpRequest()->finalUrl($item["plink"]);
355
356                         $item["parent-uri"] = $item["uri"];
357
358                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
359
360                         if (empty($item["title"])) {
361                                 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
362                         }
363                         if (empty($item["title"])) {
364                                 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
365                         }
366
367                         $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
368
369                         $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
370
371                         if (empty($published)) {
372                                 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
373                         }
374
375                         if (empty($published)) {
376                                 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
377                         }
378
379                         $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
380
381                         if (empty($updated) && !empty($published)) {
382                                 $updated = $published;
383                         }
384
385                         if (empty($published) && !empty($updated)) {
386                                 $published = $updated;
387                         }
388
389                         if ($published != "") {
390                                 $item["created"] = $published;
391                         }
392
393                         if ($updated != "") {
394                                 $item["edited"] = $updated;
395                         }
396
397                         if (!$dryRun) {
398                                 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
399                                         $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
400                                 $previous = Item::selectFirst(['id', 'created'], $condition);
401                                 if (DBA::isResult($previous)) {
402                                         // Use the creation date when the post had been stored. It can happen this date changes in the feed.
403                                         $creation_dates[] = $previous['created'];
404                                         Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
405                                         continue;
406                                 }
407                                 $creation_dates[] = DateTimeFormat::utc($item['created']);
408                         }
409
410                         $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
411
412                         if (empty($creator)) {
413                                 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
414                         }
415
416                         if (empty($creator)) {
417                                 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
418                         }
419
420                         if ($creator != "") {
421                                 $item["author-name"] = $creator;
422                         }
423
424                         $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
425
426                         if ($creator != "") {
427                                 $item["author-name"] = $creator;
428                         }
429
430                         /// @TODO ?
431                         // <category>Ausland</category>
432                         // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
433
434                         $attachments = [];
435
436                         $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
437                         foreach ($enclosures AS $enclosure) {
438                                 $href = "";
439                                 $length = "";
440                                 $type = "";
441
442                                 foreach ($enclosure->attributes AS $attribute) {
443                                         if (in_array($attribute->name, ["url", "href"])) {
444                                                 $href = $attribute->textContent;
445                                         } elseif ($attribute->name == "length") {
446                                                 $length = $attribute->textContent;
447                                         } elseif ($attribute->name == "type") {
448                                                 $type = $attribute->textContent;
449                                         }
450                                 }
451
452                                 if (!empty($item["attach"])) {
453                                         $item["attach"] .= ',';
454                                 } else {
455                                         $item["attach"] = '';
456                                 }
457
458                                 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
459
460                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '"[/attach]';
461                         }
462
463                         $taglist = [];
464                         $categories = $xpath->query("category", $entry);
465                         foreach ($categories AS $category) {
466                                 $taglist[] = $category->nodeValue;
467                         }
468
469                         $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
470
471                         if (empty($body)) {
472                                 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
473                         }
474
475                         $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
476
477                         if (empty($summary)) {
478                                 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
479                         }
480
481                         if (empty($body)) {
482                                 $body = $summary;
483                                 $summary = '';
484                         }
485
486                         if ($body == $summary) {
487                                 $summary = '';
488                         }
489
490                         // remove the content of the title if it is identically to the body
491                         // This helps with auto generated titles e.g. from tumblr
492                         if (self::titleIsBody($item["title"], $body)) {
493                                 $item["title"] = "";
494                         }
495                         $item["body"] = HTML::toBBCode($body, $basepath);
496
497                         if (($item["body"] == '') && ($item["title"] != '')) {
498                                 $item["body"] = $item["title"];
499                                 $item["title"] = '';
500                         }
501
502                         if ($dryRun) {
503                                 $items[] = $item;
504                                 break;
505                         } elseif (!Item::isValid($item)) {
506                                 Logger::info('Feed is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
507                                 continue;
508                         }
509
510                         $preview = '';
511                         if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
512                                 // Handle enclosures and treat them as preview picture
513                                 foreach ($attachments AS $attachment) {
514                                         if ($attachment["type"] == "image/jpeg") {
515                                                 $preview = $attachment["link"];
516                                         }
517                                 }
518
519                                 // Remove a possible link to the item itself
520                                 $item["body"] = str_replace($item["plink"], '', $item["body"]);
521                                 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
522
523                                 // Replace the content when the title is longer than the body
524                                 $replace = (strlen($item["title"]) > strlen($item["body"]));
525
526                                 // Replace it, when there is an image in the body
527                                 if (strstr($item["body"], '[/img]')) {
528                                         $replace = true;
529                                 }
530
531                                 // Replace it, when there is a link in the body
532                                 if (strstr($item["body"], '[/url]')) {
533                                         $replace = true;
534                                 }
535
536                                 if ($replace) {
537                                         $item["body"] = trim($item["title"]);
538                                 }
539
540                                 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
541                                 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
542                                         // When the fetched page info text is longer than the body, we do try to enhance the body
543                                         if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
544                                                 // The body is not part of the fetched page info title or page info text. So we add the text to the body
545                                                 $item['body'] .= "\n\n" . $data['text'];
546                                         } else {
547                                                 // Else we replace the body with the page info text
548                                                 $item['body'] = $data['text'];
549                                         }
550                                 }
551
552                                 // We always strip the title since it will be added in the page information
553                                 $item["title"] = "";
554                                 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
555                                 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
556                                 $item["object-type"] = Activity\ObjectType::BOOKMARK;
557                                 unset($item["attach"]);
558                         } else {
559                                 if (!empty($summary)) {
560                                         $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
561                                 }
562
563                                 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
564                                         if (empty($taglist)) {
565                                                 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
566                                         }
567                                         $item["body"] .= "\n" . self::tagToString($taglist);
568                                 } else {
569                                         $taglist = [];
570                                 }
571
572                                 // Add the link to the original feed entry if not present in feed
573                                 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
574                                         $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
575                                 }
576                         }
577
578                         Logger::info('Stored feed', ['item' => $item]);
579
580                         $notify = Item::isRemoteSelf($contact, $item);
581
582                         // Distributed items should have a well formatted URI.
583                         // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
584                         if ($notify) {
585                                 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
586                                 unset($item['uri']);
587                                 unset($item['parent-uri']);
588
589                                 // Set the delivery priority for "remote self" to "medium"
590                                 $notify = PRIORITY_MEDIUM;
591                         }
592
593                         $id = Item::insert($item, $notify);
594
595                         Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
596
597                         if (!empty($id) && !empty($taglist)) {
598                                 $feeditem = Item::selectFirst(['uri-id'], ['id' => $id]);
599                                 foreach ($taglist as $tag) {
600                                         Tag::store($feeditem['uri-id'], Tag::HASHTAG, $tag);
601                                 }
602                         }
603                 }
604
605                 if (!$dryRun) {
606                         self::adjustPollFrequency($contact, $creation_dates);
607                 }
608
609                 return ["header" => $author, "items" => $items];
610         }
611
612         /**
613          * Automatically adjust the poll frequency according to the post frequency
614          *
615          * @param array $contact
616          * @param array $creation_dates
617          * @return void
618          */
619         private static function adjustPollFrequency(array $contact, array $creation_dates)
620         {
621                 if (($contact['priority'] > 3) || ($contact['network'] != Protocol::FEED)) {
622                         Logger::info('Contact is no feed or has a low priority, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'priority' => $contact['priority'], 'network' => $contact['network']]);
623                         return;
624                 }
625
626                 if (!empty($creation_dates)) {
627                         // Count the post frequency and the earliest and latest post date
628                         $frequency = [];
629                         $oldest = time();
630                         $newest = 0;
631                         $oldest_date = $newest_date = '';
632
633                         foreach ($creation_dates as $date) {
634                                 $timestamp = strtotime($date);
635                                 $day = intdiv($timestamp, 86400);
636                                 $hour = $timestamp % 86400;
637
638                                 // Only have a look at values from the last seven days
639                                 if (((time() / 86400) - $day) < 7) {
640                                         if (empty($frequency[$day])) {
641                                                 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
642                                         } else {
643                                                 ++$frequency[$day]['count'];
644                                                 if ($frequency[$day]['low'] > $hour) {
645                                                         $frequency[$day]['low'] = $hour;
646                                                 }
647                                                 if ($frequency[$day]['high'] < $hour) {
648                                                         $frequency[$day]['high'] = $hour;
649                                                 }
650                                         }
651                                 }
652                                 if ($oldest > $day) {
653                                         $oldest = $day;
654                                         $oldest_date = $date;
655                                 }
656                         
657                                 if ($newest < $day) {
658                                         $newest = $day;
659                                         $newest_date = $date;
660                                 }
661                         }
662
663                         if (($newest == $oldest) && count($creation_dates) > 1) {
664                                 Logger::info('Feed has no different creation dates, quitting', ['date' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
665                                 return;                         
666                         }
667
668                         if (empty($frequency)) {
669                                 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']]);
670                                 $priority = 3; // Poll once a day
671                         }
672
673                         if (empty($priority) && (count($creation_dates) == 1)) {
674                                 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
675                                 $priority = 3; // Poll once a day
676                         }
677
678                         if (empty($priority) && (($newest - $oldest) > count($creation_dates))) {
679                                 Logger::info('Less than a post per day, switching to daily polling', ['posts' => count($creation_dates), 'oldest' => $oldest_date, 'newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
680                                 $priority = 3; // Poll once a day
681                         }
682
683                         if (empty($priority)) {
684                                 // Calculate the highest "posts per day" value
685                                 $max = 1;
686                                 foreach ($frequency as $entry) {
687                                         if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
688                                                 continue;
689                                         }
690
691                                         // We take the earliest and latest post day and interpolate the number of post per day
692                                         // that would had been created with this post frequency
693
694                                         // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
695                                         $duration = max($entry['high'] - $entry['low'], 14400);
696                                         $ppd = (86400 / $duration) * $entry['count'];
697                                         if ($ppd > $max) {
698                                                 $max = $ppd;
699                                         }
700                                 }
701
702                                 if ($max >= 24) {
703                                         $priority = 0; // Poll with the minimum poll intervall
704                                 } elseif ($max >= 12) {
705                                         $priority = 1; // Poll hourly
706                                 } elseif ($max > 1) {
707                                         $priority = 2; // Poll twice a day
708                                 } else {
709                                         /// @todo In the future we could calculate the days between the posts to set even lower priorities
710                                         $priority = 3; // Poll once a day
711                                 }
712                                 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
713                         }
714                 } else {
715                         Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
716                         $priority = 3; // Poll once a day
717                 }
718
719                 if ($contact['priority'] != $priority) {
720                         Logger::info('Adjusting priority', ['old' => $contact['priority'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
721                 }
722         }
723
724         /**
725          * Convert a tag array to a tag string
726          *
727          * @param array $tags
728          * @return string tag string
729          */
730         private static function tagToString(array $tags)
731         {
732                 $tagstr = '';
733
734                 foreach ($tags as $tag) {
735                         if ($tagstr != "") {
736                                 $tagstr .= ", ";
737                         }
738         
739                         $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
740                 }
741
742                 return $tagstr;
743         }
744
745         private static function titleIsBody($title, $body)
746         {
747                 $title = strip_tags($title);
748                 $title = trim($title);
749                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
750                 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
751
752                 $body = strip_tags($body);
753                 $body = trim($body);
754                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
755                 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
756
757                 if (strlen($title) < strlen($body)) {
758                         $body = substr($body, 0, strlen($title));
759                 }
760
761                 if (($title != $body) && (substr($title, -3) == "...")) {
762                         $pos = strrpos($title, "...");
763                         if ($pos > 0) {
764                                 $title = substr($title, 0, $pos);
765                                 $body = substr($body, 0, $pos);
766                         }
767                 }
768                 return ($title == $body);
769         }
770
771         /**
772          * Creates the Atom feed for a given nickname
773          *
774          * Supported filters:
775          * - activity (default): all the public posts
776          * - posts: all the public top-level posts
777          * - comments: all the public replies
778          *
779          * Updates the provided last_update parameter if the result comes from the
780          * cache or it is empty
781          *
782          * @param string  $owner_nick  Nickname of the feed owner
783          * @param string  $last_update Date of the last update
784          * @param integer $max_items   Number of maximum items to fetch
785          * @param string  $filter      Feed items filter (activity, posts or comments)
786          * @param boolean $nocache     Wether to bypass caching
787          *
788          * @return string Atom feed
789          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
790          * @throws \ImagickException
791          */
792         public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
793         {
794                 $stamp = microtime(true);
795
796                 $owner = User::getOwnerDataByNick($owner_nick);
797                 if (!$owner) {
798                         return;
799                 }
800
801                 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
802
803                 $previous_created = $last_update;
804
805                 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
806                 if ((time() - strtotime($owner['last-item'])) < 15*60) {
807                         $result = DI::cache()->get($cachekey);
808                         if (!$nocache && !is_null($result)) {
809                                 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
810                                 return $result['feed'];
811                         }
812                 }
813
814                 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
815                 $authorid = Contact::getIdForURL($owner["url"]);
816
817                 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
818                         AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
819                         $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
820                         Item::PRIVATE, Protocol::ACTIVITYPUB,
821                         Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
822
823                 if ($filter === 'comments') {
824                         $condition[0] .= " AND `object-type` = ? ";
825                         $condition[] = Activity\ObjectType::COMMENT;
826                 }
827
828                 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
829                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
830                         $condition[] = $owner["id"];
831                         $condition[] = $authorid;
832                 }
833
834                 $params = ['order' => ['received' => true], 'limit' => $max_items];
835
836                 if ($filter === 'posts') {
837                         $ret = Item::selectThread([], $condition, $params);
838                 } else {
839                         $ret = Item::select([], $condition, $params);
840                 }
841
842                 $items = Item::inArray($ret);
843
844                 $doc = new DOMDocument('1.0', 'utf-8');
845                 $doc->formatOutput = true;
846
847                 $root = self::addHeader($doc, $owner, $filter);
848
849                 foreach ($items as $item) {
850                         $entry = self::entry($doc, $item, $owner);
851                         $root->appendChild($entry);
852
853                         if ($last_update < $item['created']) {
854                                 $last_update = $item['created'];
855                         }
856                 }
857
858                 $feeddata = trim($doc->saveXML());
859
860                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
861                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
862
863                 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
864
865                 return $feeddata;
866         }
867
868         /**
869          * Adds the header elements to the XML document
870          *
871          * @param DOMDocument $doc       XML document
872          * @param array       $owner     Contact data of the poster
873          * @param string      $filter    The related feed filter (activity, posts or comments)
874          *
875          * @return object header root element
876          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
877          */
878         private static function addHeader(DOMDocument $doc, array $owner, $filter)
879         {
880                 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
881                 $doc->appendChild($root);
882
883                 $title = '';
884                 $selfUri = '/feed/' . $owner["nick"] . '/';
885                 switch ($filter) {
886                         case 'activity':
887                                 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
888                                 $selfUri .= $filter;
889                                 break;
890                         case 'posts':
891                                 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
892                                 break;
893                         case 'comments':
894                                 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
895                                 $selfUri .= $filter;
896                                 break;
897                 }
898
899                 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
900                 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
901                 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
902                 XML::addElement($doc, $root, "title", $title);
903                 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
904                 XML::addElement($doc, $root, "logo", $owner["photo"]);
905                 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
906
907                 $author = self::addAuthor($doc, $owner);
908                 $root->appendChild($author);
909
910                 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
911                 XML::addElement($doc, $root, "link", "", $attributes);
912
913                 OStatus::hublinks($doc, $root, $owner["nick"]);
914
915                 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
916                 XML::addElement($doc, $root, "link", "", $attributes);
917
918                 return $root;
919         }
920
921         /**
922          * Adds the author element to the XML document
923          *
924          * @param DOMDocument $doc          XML document
925          * @param array       $owner        Contact data of the poster
926          *
927          * @return \DOMElement author element
928          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
929          */
930         private static function addAuthor(DOMDocument $doc, array $owner)
931         {
932                 $author = $doc->createElement("author");
933                 XML::addElement($doc, $author, "uri", $owner["url"]);
934                 XML::addElement($doc, $author, "name", $owner["nick"]);
935                 XML::addElement($doc, $author, "email", $owner["addr"]);
936
937                 return $author;
938         }
939
940         /**
941          * Adds an entry element to the XML document
942          *
943          * @param DOMDocument $doc       XML document
944          * @param array       $item      Data of the item that is to be posted
945          * @param array       $owner     Contact data of the poster
946          * @param bool        $toplevel  optional default false
947          *
948          * @return \DOMElement Entry element
949          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
950          * @throws \ImagickException
951          */
952         private static function entry(DOMDocument $doc, array $item, array $owner)
953         {
954                 $xml = null;
955
956                 $repeated_guid = OStatus::getResharedGuid($item);
957                 if ($repeated_guid != "") {
958                         $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid);
959                 }
960
961                 if ($xml) {
962                         return $xml;
963                 }
964
965                 return self::noteEntry($doc, $item, $owner);
966         }
967
968                 /**
969          * Adds an entry element with reshared content
970          *
971          * @param DOMDocument $doc           XML document
972          * @param array       $item          Data of the item that is to be posted
973          * @param array       $owner         Contact data of the poster
974          * @param string      $repeated_guid guid
975          * @param bool        $toplevel      Is it for en entry element (false) or a feed entry (true)?
976          *
977          * @return bool Entry element
978          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
979          * @throws \ImagickException
980          */
981         private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid)
982         {
983                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
984                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
985                 }
986
987                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
988
989                 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
990                         'network' => Protocol::FEDERATED];
991                 $repeated_item = Item::selectFirst([], $condition);
992                 if (!DBA::isResult($repeated_item)) {
993                         return false;
994                 }
995
996                 self::entryContent($doc, $entry, $item, self::getTitle($repeated_item), Activity::SHARE, false);
997
998                 self::entryFooter($doc, $entry, $item, $owner);
999
1000                 return $entry;
1001         }
1002
1003         /**
1004          * Adds a regular entry element
1005          *
1006          * @param DOMDocument $doc       XML document
1007          * @param array       $item      Data of the item that is to be posted
1008          * @param array       $owner     Contact data of the poster
1009          * @param bool        $toplevel  Is it for en entry element (false) or a feed entry (true)?
1010          *
1011          * @return \DOMElement Entry element
1012          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1013          * @throws \ImagickException
1014          */
1015         private static function noteEntry(DOMDocument $doc, array $item, array $owner)
1016         {
1017                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1018                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1019                 }
1020
1021                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1022
1023                 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1024
1025                 self::entryFooter($doc, $entry, $item, $owner);
1026
1027                 return $entry;
1028         }
1029
1030         /**
1031          * Adds elements to the XML document
1032          *
1033          * @param DOMDocument $doc       XML document
1034          * @param \DOMElement $entry     Entry element where the content is added
1035          * @param array       $item      Data of the item that is to be posted
1036          * @param array       $owner     Contact data of the poster
1037          * @param string      $title     Title for the post
1038          * @param string      $verb      The activity verb
1039          * @param bool        $complete  Add the "status_net" element?
1040          * @param bool        $feed_mode Behave like a regular feed for users if true
1041          * @return void
1042          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1043          */
1044         private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
1045         {
1046                 if ($verb == "") {
1047                         $verb = OStatus::constructVerb($item);
1048                 }
1049
1050                 XML::addElement($doc, $entry, "id", $item["uri"]);
1051                 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1052
1053                 $body = OStatus::formatPicturePost($item['body']);
1054
1055                 $body = BBCode::convert($body, false, BBCode::OSTATUS);
1056
1057                 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1058
1059                 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1060                                                                 "href" => DI::baseUrl()."/display/".$item["guid"]]
1061                 );
1062
1063                 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1064                 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1065         }
1066
1067         /**
1068          * Adds the elements at the foot of an entry to the XML document
1069          *
1070          * @param DOMDocument $doc       XML document
1071          * @param object      $entry     The entry element where the elements are added
1072          * @param array       $item      Data of the item that is to be posted
1073          * @param array       $owner     Contact data of the poster
1074          * @param bool        $complete  default true
1075          * @return void
1076          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1077          */
1078         private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1079         {
1080                 $mentioned = [];
1081
1082                 if ($item['gravity'] != GRAVITY_PARENT) {
1083                         $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1084                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1085
1086                         $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
1087
1088                         if (DBA::isResult($thrparent)) {
1089                                 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1090                                 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1091                                 $parent_plink = $thrparent["plink"];
1092                         } else {
1093                                 $mentioned[$parent["author-link"]] = $parent["author-link"];
1094                                 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1095                                 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
1096                         }
1097
1098                         $attributes = [
1099                                         "ref" => $parent_item,
1100                                         "href" => $parent_plink];
1101                         XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1102
1103                         $attributes = [
1104                                         "rel" => "related",
1105                                         "href" => $parent_plink];
1106                         XML::addElement($doc, $entry, "link", "", $attributes);
1107                 }
1108
1109                 // uri-id isn't present for follow entry pseudo-items
1110                 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1111                 foreach ($tags as $tag) {
1112                         $mentioned[$tag['url']] = $tag['url'];
1113                 }
1114
1115                 foreach ($tags as $tag) {
1116                         if ($tag['type'] == Tag::HASHTAG) {
1117                                 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
1118                         }
1119                 }
1120
1121                 OStatus::getAttachment($doc, $entry, $item);
1122         }
1123
1124         /**
1125          * Fetch or create title for feed entry
1126          *
1127          * @param array $item
1128          * @return string title
1129          */
1130         private static function getTitle(array $item)
1131         {
1132                 if ($item['title'] != '') {
1133                         return BBCode::convert($item['title'], false, BBCode::OSTATUS);
1134                 }
1135
1136                 // Fetch information about the post
1137                 $siteinfo = BBCode::getAttachedData($item["body"]);
1138                 if (isset($siteinfo["title"])) {
1139                         return $siteinfo["title"];
1140                 }
1141
1142                 // If no bookmark is found then take the first line
1143                 // Remove the share element before fetching the first line
1144                 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1145
1146                 $title = HTML::toPlaintext(BBCode::convert($title, false), 0, true)."\n";
1147                 $pos = strpos($title, "\n");
1148                 $trailer = "";
1149                 if (($pos == 0) || ($pos > 100)) {
1150                         $pos = 100;
1151                         $trailer = "...";
1152                 }
1153
1154                 return substr($title, 0, $pos) . $trailer;
1155         }
1156 }