]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Feed.php
Reworked "getIdForURL"
[friendica.git] / src / Protocol / Feed.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol;
23
24 use DOMDocument;
25 use DOMXPath;
26 use Friendica\Content\PageInfo;
27 use Friendica\Content\Text\BBCode;
28 use Friendica\Content\Text\HTML;
29 use Friendica\Core\Cache\Duration;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Item;
36 use Friendica\Model\Tag;
37 use Friendica\Model\User;
38 use Friendica\Network\HTTPRequest;
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
305                 // Limit the number of items that are about to be fetched
306                 $total_items = ($entries->length - 1);
307                 $max_items = DI::config()->get('system', 'max_feed_items');
308                 if (($max_items > 0) && ($total_items > $max_items)) {
309                         $total_items = $max_items;
310                 }
311
312                 // Importing older entries first
313                 for ($i = $total_items; $i >= 0; --$i) {
314                         $entry = $entries->item($i);
315
316                         $item = array_merge($header, $author);
317
318                         $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
319                         if (!is_object($alternate)) {
320                                 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
321                         }
322                         if (is_object($alternate)) {
323                                 foreach ($alternate AS $attribute) {
324                                         if ($attribute->name == "href") {
325                                                 $item["plink"] = $attribute->textContent;
326                                         }
327                                 }
328                         }
329
330                         if (empty($item["plink"])) {
331                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
332                         }
333
334                         if (empty($item["plink"])) {
335                                 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
336                         }
337
338                         $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
339
340                         if (empty($item["uri"])) {
341                                 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
342                         }
343
344                         if (empty($item["uri"])) {
345                                 $item["uri"] = $item["plink"];
346                         }
347
348                         // Add the base path if missing
349                         $item["uri"] = Network::addBasePath($item["uri"], $basepath);
350                         $item["plink"] = Network::addBasePath($item["plink"], $basepath);
351
352                         $orig_plink = $item["plink"];
353
354                         $item["plink"] = DI::httpRequest()->finalUrl($item["plink"]);
355
356                         $item["parent-uri"] = $item["uri"];
357
358                         if (!$dryRun) {
359                                 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
360                                         $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
361                                 $previous = Item::selectFirst(['id'], $condition);
362                                 if (DBA::isResult($previous)) {
363                                         Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
364                                         continue;
365                                 }
366                         }
367
368                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
369
370                         if (empty($item["title"])) {
371                                 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
372                         }
373                         if (empty($item["title"])) {
374                                 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
375                         }
376
377                         $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
378
379                         $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
380
381                         if (empty($published)) {
382                                 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
383                         }
384
385                         if (empty($published)) {
386                                 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
387                         }
388
389                         $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
390
391                         if (empty($updated) && !empty($published)) {
392                                 $updated = $published;
393                         }
394
395                         if (empty($published) && !empty($updated)) {
396                                 $published = $updated;
397                         }
398
399                         if ($published != "") {
400                                 $item["created"] = $published;
401                         }
402
403                         if ($updated != "") {
404                                 $item["edited"] = $updated;
405                         }
406
407                         $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
408
409                         if (empty($creator)) {
410                                 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
411                         }
412
413                         if (empty($creator)) {
414                                 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
415                         }
416
417                         if ($creator != "") {
418                                 $item["author-name"] = $creator;
419                         }
420
421                         $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
422
423                         if ($creator != "") {
424                                 $item["author-name"] = $creator;
425                         }
426
427                         /// @TODO ?
428                         // <category>Ausland</category>
429                         // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
430
431                         $attachments = [];
432
433                         $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
434                         foreach ($enclosures AS $enclosure) {
435                                 $href = "";
436                                 $length = "";
437                                 $type = "";
438
439                                 foreach ($enclosure->attributes AS $attribute) {
440                                         if (in_array($attribute->name, ["url", "href"])) {
441                                                 $href = $attribute->textContent;
442                                         } elseif ($attribute->name == "length") {
443                                                 $length = $attribute->textContent;
444                                         } elseif ($attribute->name == "type") {
445                                                 $type = $attribute->textContent;
446                                         }
447                                 }
448
449                                 if (!empty($item["attach"])) {
450                                         $item["attach"] .= ',';
451                                 } else {
452                                         $item["attach"] = '';
453                                 }
454
455                                 $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
456
457                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '"[/attach]';
458                         }
459
460                         $taglist = [];
461                         $categories = $xpath->query("category", $entry);
462                         foreach ($categories AS $category) {
463                                 $taglist[] = $category->nodeValue;
464                         }
465
466                         $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
467
468                         if (empty($body)) {
469                                 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
470                         }
471
472                         $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
473
474                         if (empty($summary)) {
475                                 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
476                         }
477
478                         if (empty($body)) {
479                                 $body = $summary;
480                                 $summary = '';
481                         }
482
483                         if ($body == $summary) {
484                                 $summary = '';
485                         }
486
487                         // remove the content of the title if it is identically to the body
488                         // This helps with auto generated titles e.g. from tumblr
489                         if (self::titleIsBody($item["title"], $body)) {
490                                 $item["title"] = "";
491                         }
492                         $item["body"] = HTML::toBBCode($body, $basepath);
493
494                         if (($item["body"] == '') && ($item["title"] != '')) {
495                                 $item["body"] = $item["title"];
496                                 $item["title"] = '';
497                         }
498
499                         $preview = '';
500                         if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
501                                 // Handle enclosures and treat them as preview picture
502                                 foreach ($attachments AS $attachment) {
503                                         if ($attachment["type"] == "image/jpeg") {
504                                                 $preview = $attachment["link"];
505                                         }
506                                 }
507
508                                 // Remove a possible link to the item itself
509                                 $item["body"] = str_replace($item["plink"], '', $item["body"]);
510                                 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
511
512                                 // Replace the content when the title is longer than the body
513                                 $replace = (strlen($item["title"]) > strlen($item["body"]));
514
515                                 // Replace it, when there is an image in the body
516                                 if (strstr($item["body"], '[/img]')) {
517                                         $replace = true;
518                                 }
519
520                                 // Replace it, when there is a link in the body
521                                 if (strstr($item["body"], '[/url]')) {
522                                         $replace = true;
523                                 }
524
525                                 if ($replace) {
526                                         $item["body"] = trim($item["title"]);
527                                 }
528
529                                 $data = ParseUrl::getSiteinfoCached($item['plink'], true);
530                                 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
531                                         // When the fetched page info text is longer than the body, we do try to enhance the body
532                                         if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
533                                                 // The body is not part of the fetched page info title or page info text. So we add the text to the body
534                                                 $item['body'] .= "\n\n" . $data['text'];
535                                         } else {
536                                                 // Else we replace the body with the page info text
537                                                 $item['body'] = $data['text'];
538                                         }
539                                 }
540
541                                 // We always strip the title since it will be added in the page information
542                                 $item["title"] = "";
543                                 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
544                                 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
545                                 $item["object-type"] = Activity\ObjectType::BOOKMARK;
546                                 unset($item["attach"]);
547                         } else {
548                                 if (!empty($summary)) {
549                                         $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
550                                 }
551
552                                 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
553                                         if (empty($taglist)) {
554                                                 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
555                                         }
556                                         $item["body"] .= "\n" . self::tagToString($taglist);
557                                 } else {
558                                         $taglist = [];
559                                 }
560
561                                 // Add the link to the original feed entry if not present in feed
562                                 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
563                                         $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
564                                 }
565                         }
566
567                         if ($dryRun) {
568                                 $items[] = $item;
569                                 break;
570                         } else {
571                                 Logger::info('Stored feed', ['item' => $item]);
572
573                                 $notify = Item::isRemoteSelf($contact, $item);
574
575                                 // Distributed items should have a well formatted URI.
576                                 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
577                                 if ($notify) {
578                                         $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
579                                         unset($item['uri']);
580                                         unset($item['parent-uri']);
581
582                                         // Set the delivery priority for "remote self" to "medium"
583                                         $notify = PRIORITY_MEDIUM;
584                                 }
585
586                                 $id = Item::insert($item, $notify);
587
588                                 Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
589
590                                 if (!empty($id) && !empty($taglist)) {
591                                         $feeditem = Item::selectFirst(['uri-id'], ['id' => $id]);
592                                         foreach ($taglist as $tag) {
593                                                 Tag::store($feeditem['uri-id'], Tag::HASHTAG, $tag);
594                                         }                                       
595                                 }
596                         }
597                 }
598
599                 return ["header" => $author, "items" => $items];
600         }
601
602         /**
603          * Convert a tag array to a tag string
604          *
605          * @param array $tags
606          * @return string tag string
607          */
608         private static function tagToString(array $tags)
609         {
610                 $tagstr = '';
611
612                 foreach ($tags as $tag) {
613                         if ($tagstr != "") {
614                                 $tagstr .= ", ";
615                         }
616         
617                         $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
618                 }
619
620                 return $tagstr;
621         }
622
623         private static function titleIsBody($title, $body)
624         {
625                 $title = strip_tags($title);
626                 $title = trim($title);
627                 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
628                 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
629
630                 $body = strip_tags($body);
631                 $body = trim($body);
632                 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
633                 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
634
635                 if (strlen($title) < strlen($body)) {
636                         $body = substr($body, 0, strlen($title));
637                 }
638
639                 if (($title != $body) && (substr($title, -3) == "...")) {
640                         $pos = strrpos($title, "...");
641                         if ($pos > 0) {
642                                 $title = substr($title, 0, $pos);
643                                 $body = substr($body, 0, $pos);
644                         }
645                 }
646                 return ($title == $body);
647         }
648
649         /**
650          * Creates the Atom feed for a given nickname
651          *
652          * Supported filters:
653          * - activity (default): all the public posts
654          * - posts: all the public top-level posts
655          * - comments: all the public replies
656          *
657          * Updates the provided last_update parameter if the result comes from the
658          * cache or it is empty
659          *
660          * @param string  $owner_nick  Nickname of the feed owner
661          * @param string  $last_update Date of the last update
662          * @param integer $max_items   Number of maximum items to fetch
663          * @param string  $filter      Feed items filter (activity, posts or comments)
664          * @param boolean $nocache     Wether to bypass caching
665          *
666          * @return string Atom feed
667          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
668          * @throws \ImagickException
669          */
670         public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
671         {
672                 $stamp = microtime(true);
673
674                 $owner = User::getOwnerDataByNick($owner_nick);
675                 if (!$owner) {
676                         return;
677                 }
678
679                 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
680
681                 $previous_created = $last_update;
682
683                 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
684                 if ((time() - strtotime($owner['last-item'])) < 15*60) {
685                         $result = DI::cache()->get($cachekey);
686                         if (!$nocache && !is_null($result)) {
687                                 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
688                                 return $result['feed'];
689                         }
690                 }
691
692                 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
693                 $authorid = Contact::getIdForURL($owner["url"]);
694
695                 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
696                         AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
697                         $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
698                         Item::PRIVATE, Protocol::ACTIVITYPUB,
699                         Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
700
701                 if ($filter === 'comments') {
702                         $condition[0] .= " AND `object-type` = ? ";
703                         $condition[] = Activity\ObjectType::COMMENT;
704                 }
705
706                 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
707                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
708                         $condition[] = $owner["id"];
709                         $condition[] = $authorid;
710                 }
711
712                 $params = ['order' => ['received' => true], 'limit' => $max_items];
713
714                 if ($filter === 'posts') {
715                         $ret = Item::selectThread([], $condition, $params);
716                 } else {
717                         $ret = Item::select([], $condition, $params);
718                 }
719
720                 $items = Item::inArray($ret);
721
722                 $doc = new DOMDocument('1.0', 'utf-8');
723                 $doc->formatOutput = true;
724
725                 $root = self::addHeader($doc, $owner, $filter);
726
727                 foreach ($items as $item) {
728                         $entry = self::entry($doc, $item, $owner);
729                         $root->appendChild($entry);
730
731                         if ($last_update < $item['created']) {
732                                 $last_update = $item['created'];
733                         }
734                 }
735
736                 $feeddata = trim($doc->saveXML());
737
738                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
739                 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
740
741                 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
742
743                 return $feeddata;
744         }
745
746         /**
747          * Adds the header elements to the XML document
748          *
749          * @param DOMDocument $doc       XML document
750          * @param array       $owner     Contact data of the poster
751          * @param string      $filter    The related feed filter (activity, posts or comments)
752          *
753          * @return object header root element
754          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
755          */
756         private static function addHeader(DOMDocument $doc, array $owner, $filter)
757         {
758                 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
759                 $doc->appendChild($root);
760
761                 $title = '';
762                 $selfUri = '/feed/' . $owner["nick"] . '/';
763                 switch ($filter) {
764                         case 'activity':
765                                 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
766                                 $selfUri .= $filter;
767                                 break;
768                         case 'posts':
769                                 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
770                                 break;
771                         case 'comments':
772                                 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
773                                 $selfUri .= $filter;
774                                 break;
775                 }
776
777                 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
778                 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
779                 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
780                 XML::addElement($doc, $root, "title", $title);
781                 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
782                 XML::addElement($doc, $root, "logo", $owner["photo"]);
783                 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
784
785                 $author = self::addAuthor($doc, $owner);
786                 $root->appendChild($author);
787
788                 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
789                 XML::addElement($doc, $root, "link", "", $attributes);
790
791                 OStatus::hublinks($doc, $root, $owner["nick"]);
792
793                 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
794                 XML::addElement($doc, $root, "link", "", $attributes);
795
796                 return $root;
797         }
798
799         /**
800          * Adds the author element to the XML document
801          *
802          * @param DOMDocument $doc          XML document
803          * @param array       $owner        Contact data of the poster
804          *
805          * @return \DOMElement author element
806          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
807          */
808         private static function addAuthor(DOMDocument $doc, array $owner)
809         {
810                 $author = $doc->createElement("author");
811                 XML::addElement($doc, $author, "uri", $owner["url"]);
812                 XML::addElement($doc, $author, "name", $owner["nick"]);
813                 XML::addElement($doc, $author, "email", $owner["addr"]);
814
815                 return $author;
816         }
817
818         /**
819          * Adds an entry element to the XML document
820          *
821          * @param DOMDocument $doc       XML document
822          * @param array       $item      Data of the item that is to be posted
823          * @param array       $owner     Contact data of the poster
824          * @param bool        $toplevel  optional default false
825          *
826          * @return \DOMElement Entry element
827          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
828          * @throws \ImagickException
829          */
830         private static function entry(DOMDocument $doc, array $item, array $owner)
831         {
832                 $xml = null;
833
834                 $repeated_guid = OStatus::getResharedGuid($item);
835                 if ($repeated_guid != "") {
836                         $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid);
837                 }
838
839                 if ($xml) {
840                         return $xml;
841                 }
842
843                 return self::noteEntry($doc, $item, $owner);
844         }
845
846                 /**
847          * Adds an entry element with reshared content
848          *
849          * @param DOMDocument $doc           XML document
850          * @param array       $item          Data of the item that is to be posted
851          * @param array       $owner         Contact data of the poster
852          * @param string      $repeated_guid guid
853          * @param bool        $toplevel      Is it for en entry element (false) or a feed entry (true)?
854          *
855          * @return bool Entry element
856          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
857          * @throws \ImagickException
858          */
859         private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid)
860         {
861                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
862                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
863                 }
864
865                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
866
867                 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
868                         'network' => Protocol::FEDERATED];
869                 $repeated_item = Item::selectFirst([], $condition);
870                 if (!DBA::isResult($repeated_item)) {
871                         return false;
872                 }
873
874                 self::entryContent($doc, $entry, $item, self::getTitle($repeated_item), Activity::SHARE, false);
875
876                 self::entryFooter($doc, $entry, $item, $owner);
877
878                 return $entry;
879         }
880
881         /**
882          * Adds a regular entry element
883          *
884          * @param DOMDocument $doc       XML document
885          * @param array       $item      Data of the item that is to be posted
886          * @param array       $owner     Contact data of the poster
887          * @param bool        $toplevel  Is it for en entry element (false) or a feed entry (true)?
888          *
889          * @return \DOMElement Entry element
890          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
891          * @throws \ImagickException
892          */
893         private static function noteEntry(DOMDocument $doc, array $item, array $owner)
894         {
895                 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
896                         Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
897                 }
898
899                 $entry = OStatus::entryHeader($doc, $owner, $item, false);
900
901                 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
902
903                 self::entryFooter($doc, $entry, $item, $owner);
904
905                 return $entry;
906         }
907
908         /**
909          * Adds elements to the XML document
910          *
911          * @param DOMDocument $doc       XML document
912          * @param \DOMElement $entry     Entry element where the content is added
913          * @param array       $item      Data of the item that is to be posted
914          * @param array       $owner     Contact data of the poster
915          * @param string      $title     Title for the post
916          * @param string      $verb      The activity verb
917          * @param bool        $complete  Add the "status_net" element?
918          * @param bool        $feed_mode Behave like a regular feed for users if true
919          * @return void
920          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
921          */
922         private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
923         {
924                 if ($verb == "") {
925                         $verb = OStatus::constructVerb($item);
926                 }
927
928                 XML::addElement($doc, $entry, "id", $item["uri"]);
929                 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
930
931                 $body = OStatus::formatPicturePost($item['body']);
932
933                 $body = BBCode::convert($body, false, BBCode::OSTATUS);
934
935                 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
936
937                 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
938                                                                 "href" => DI::baseUrl()."/display/".$item["guid"]]
939                 );
940
941                 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
942                 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
943         }
944
945         /**
946          * Adds the elements at the foot of an entry to the XML document
947          *
948          * @param DOMDocument $doc       XML document
949          * @param object      $entry     The entry element where the elements are added
950          * @param array       $item      Data of the item that is to be posted
951          * @param array       $owner     Contact data of the poster
952          * @param bool        $complete  default true
953          * @return void
954          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
955          */
956         private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
957         {
958                 $mentioned = [];
959
960                 if ($item['gravity'] != GRAVITY_PARENT) {
961                         $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
962                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
963
964                         $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
965
966                         if (DBA::isResult($thrparent)) {
967                                 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
968                                 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
969                                 $parent_plink = $thrparent["plink"];
970                         } else {
971                                 $mentioned[$parent["author-link"]] = $parent["author-link"];
972                                 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
973                                 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
974                         }
975
976                         $attributes = [
977                                         "ref" => $parent_item,
978                                         "href" => $parent_plink];
979                         XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
980
981                         $attributes = [
982                                         "rel" => "related",
983                                         "href" => $parent_plink];
984                         XML::addElement($doc, $entry, "link", "", $attributes);
985                 }
986
987                 // uri-id isn't present for follow entry pseudo-items
988                 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
989                 foreach ($tags as $tag) {
990                         $mentioned[$tag['url']] = $tag['url'];
991                 }
992
993                 foreach ($tags as $tag) {
994                         if ($tag['type'] == Tag::HASHTAG) {
995                                 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
996                         }
997                 }
998
999                 OStatus::getAttachment($doc, $entry, $item);
1000         }
1001
1002         /**
1003          * Fetch or create title for feed entry
1004          *
1005          * @param array $item
1006          * @return string title
1007          */
1008         private static function getTitle(array $item)
1009         {
1010                 if ($item['title'] != '') {
1011                         return BBCode::convert($item['title'], false, BBCode::OSTATUS);
1012                 }
1013
1014                 // Fetch information about the post
1015                 $siteinfo = BBCode::getAttachedData($item["body"]);
1016                 if (isset($siteinfo["title"])) {
1017                         return $siteinfo["title"];
1018                 }
1019
1020                 // If no bookmark is found then take the first line
1021                 // Remove the share element before fetching the first line
1022                 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1023
1024                 $title = HTML::toPlaintext(BBCode::convert($title, false), 0, true)."\n";
1025                 $pos = strpos($title, "\n");
1026                 $trailer = "";
1027                 if (($pos == 0) || ($pos > 100)) {
1028                         $pos = 100;
1029                         $trailer = "...";
1030                 }
1031
1032                 return substr($title, 0, $pos) . $trailer;
1033         }
1034 }