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