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