3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Protocol;
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;
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\Proxy;
43 use Friendica\Util\Strings;
44 use Friendica\Util\XML;
45 use GuzzleHttp\Exception\TransferException;
48 * This class contain functions to import feeds (RSS/RDF/Atom)
53 * Read a RSS/RDF/Atom feed and create an item entry for it
55 * @param string $xml The feed data
56 * @param array $importer The user record of the importer
57 * @param array $contact The contact record of the feed
59 * @return array Returns the header and the first item in dry run mode
60 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
62 public static function import($xml, array $importer = [], array $contact = [])
64 $dryRun = empty($importer) && empty($contact);
67 Logger::info("Test Atom/RSS feed");
69 Logger::info("Import Atom/RSS feed '" . $contact["name"] . "' (Contact " . $contact["id"] . ") for user " . $importer["uid"]);
73 Logger::info('XML is empty.');
77 if (!empty($contact['poll'])) {
78 $basepath = $contact['poll'];
79 } elseif (!empty($contact['url'])) {
80 $basepath = $contact['url'];
85 $doc = new DOMDocument();
86 @$doc->loadXML(trim($xml));
87 $xpath = new DOMXPath($doc);
88 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
89 $xpath->registerNamespace('dc', "http://purl.org/dc/elements/1.1/");
90 $xpath->registerNamespace('content', "http://purl.org/rss/1.0/modules/content/");
91 $xpath->registerNamespace('rdf', "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
92 $xpath->registerNamespace('rss', "http://purl.org/rss/1.0/");
93 $xpath->registerNamespace('media', "http://search.yahoo.com/mrss/");
94 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
100 if ($xpath->query('/rdf:RDF/rss:channel')->length > 0) {
101 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:link/text()');
102 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:title/text()');
104 if (empty($author["author-name"])) {
105 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rdf:RDF/rss:channel/rss:description/text()');
107 $entries = $xpath->query('/rdf:RDF/rss:item');
111 if ($xpath->query('/atom:feed')->length > 0) {
112 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']");
113 if (is_object($alternate)) {
114 foreach ($alternate AS $attribute) {
115 if ($attribute->name == "href") {
116 $author["author-link"] = $attribute->textContent;
121 if (empty($author["author-link"])) {
122 $self = XML::getFirstAttributes($xpath, "atom:link[@rel='self']");
123 if (is_object($self)) {
124 foreach ($self AS $attribute) {
125 if ($attribute->name == "href") {
126 $author["author-link"] = $attribute->textContent;
132 if (empty($author["author-link"])) {
133 $author["author-link"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:id/text()');
135 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:logo/text()');
137 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:title/text()');
139 if (empty($author["author-name"])) {
140 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:subtitle/text()');
143 if (empty($author["author-name"])) {
144 $author["author-name"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:name/text()');
147 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()');
149 $author["author-name"] = $value;
153 $author["author-id"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:author/atom:id/text()');
155 // See https://tools.ietf.org/html/rfc4287#section-3.2.2
156 $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()');
158 $author["author-link"] = $value;
161 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()');
163 $author["author-nick"] = $value;
166 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()');
168 $author["author-location"] = $value;
171 $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()');
173 $author["author-about"] = $value;
176 $avatar = XML::getFirstAttributes($xpath, "atom:author/atom:link[@rel='avatar']");
177 if (is_object($avatar)) {
178 foreach ($avatar AS $attribute) {
179 if ($attribute->name == "href") {
180 $author["author-avatar"] = $attribute->textContent;
186 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:updated/text()');
188 $author["app"] = XML::getFirstNodeValue($xpath, '/atom:feed/atom:generator/text()');
190 $entries = $xpath->query('/atom:feed/atom:entry');
194 if ($xpath->query('/rss/channel')->length > 0) {
195 $author["author-link"] = XML::getFirstNodeValue($xpath, '/rss/channel/link/text()');
197 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/title/text()');
198 $author["author-avatar"] = XML::getFirstNodeValue($xpath, '/rss/channel/image/url/text()');
200 if (empty($author["author-name"])) {
201 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/copyright/text()');
204 if (empty($author["author-name"])) {
205 $author["author-name"] = XML::getFirstNodeValue($xpath, '/rss/channel/description/text()');
208 $author["edited"] = $author["created"] = XML::getFirstNodeValue($xpath, '/rss/channel/pubDate/text()');
210 $author["app"] = XML::getFirstNodeValue($xpath, '/rss/channel/generator/text()');
212 $entries = $xpath->query('/rss/channel/item');
216 $author["author-link"] = $contact["url"];
218 if (empty($author["author-name"])) {
219 $author["author-name"] = $contact["name"];
222 $author["author-avatar"] = $contact["thumb"];
224 $author["owner-link"] = $contact["url"];
225 $author["owner-name"] = $contact["name"];
226 $author["owner-avatar"] = $contact["thumb"];
230 $header["uid"] = $importer["uid"] ?? 0;
231 $header["network"] = Protocol::FEED;
233 $header["origin"] = 0;
234 $header["gravity"] = GRAVITY_PARENT;
235 $header["private"] = Item::PUBLIC;
236 $header["verb"] = Activity::POST;
237 $header["object-type"] = Activity\ObjectType::NOTE;
238 $header["post-type"] = Item::PT_ARTICLE;
240 $header["contact-id"] = $contact["id"] ?? 0;
242 if (!is_object($entries)) {
243 Logger::info("There are no entries in this feed.");
248 $creation_dates = [];
250 // Limit the number of items that are about to be fetched
251 $total_items = ($entries->length - 1);
252 $max_items = DI::config()->get('system', 'max_feed_items');
253 if (($max_items > 0) && ($total_items > $max_items)) {
254 $total_items = $max_items;
259 // Importing older entries first
260 for ($i = $total_items; $i >= 0; --$i) {
261 $entry = $entries->item($i);
263 $item = array_merge($header, $author);
265 $alternate = XML::getFirstAttributes($xpath, "atom:link[@rel='alternate']", $entry);
266 if (!is_object($alternate)) {
267 $alternate = XML::getFirstAttributes($xpath, "atom:link", $entry);
269 if (is_object($alternate)) {
270 foreach ($alternate AS $attribute) {
271 if ($attribute->name == "href") {
272 $item["plink"] = $attribute->textContent;
277 if (empty($item["plink"])) {
278 $item["plink"] = XML::getFirstNodeValue($xpath, 'link/text()', $entry);
281 if (empty($item["plink"])) {
282 $item["plink"] = XML::getFirstNodeValue($xpath, 'rss:link/text()', $entry);
285 $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
287 if (empty($item["uri"])) {
288 $item["uri"] = XML::getFirstNodeValue($xpath, 'guid/text()', $entry);
291 if (empty($item["uri"])) {
292 $item["uri"] = $item["plink"];
295 // Add the base path if missing
296 $item["uri"] = Network::addBasePath($item["uri"], $basepath);
297 $item["plink"] = Network::addBasePath($item["plink"], $basepath);
299 $orig_plink = $item["plink"];
302 $item["plink"] = DI::httpClient()->finalUrl($item["plink"]);
303 } catch (TransferException $exception) {
304 Logger::notice('Item URL couldn\'t get expanded', ['url' => $item["plink"], 'exception' => $exception]);
307 $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
309 if (empty($item["title"])) {
310 $item["title"] = XML::getFirstNodeValue($xpath, 'title/text()', $entry);
312 if (empty($item["title"])) {
313 $item["title"] = XML::getFirstNodeValue($xpath, 'rss:title/text()', $entry);
316 $item["title"] = html_entity_decode($item["title"], ENT_QUOTES, 'UTF-8');
318 $published = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
320 if (empty($published)) {
321 $published = XML::getFirstNodeValue($xpath, 'pubDate/text()', $entry);
324 if (empty($published)) {
325 $published = XML::getFirstNodeValue($xpath, 'dc:date/text()', $entry);
328 $updated = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
330 if (empty($updated) && !empty($published)) {
331 $updated = $published;
334 if (empty($published) && !empty($updated)) {
335 $published = $updated;
338 if ($published != "") {
339 $item["created"] = $published;
342 if ($updated != "") {
343 $item["edited"] = $updated;
347 $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
348 $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
349 $previous = Post::selectFirst(['id', 'created'], $condition);
350 if (DBA::isResult($previous)) {
351 // Use the creation date when the post had been stored. It can happen this date changes in the feed.
352 $creation_dates[] = $previous['created'];
353 Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
356 $creation_dates[] = DateTimeFormat::utc($item['created']);
359 $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
361 if (empty($creator)) {
362 $creator = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $entry);
365 if (empty($creator)) {
366 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
369 if ($creator != "") {
370 $item["author-name"] = $creator;
373 $creator = XML::getFirstNodeValue($xpath, 'dc:creator/text()', $entry);
375 if ($creator != "") {
376 $item["author-name"] = $creator;
380 // <category>Ausland</category>
381 // <media:thumbnail width="152" height="76" url="http://www.taz.de/picture/667875/192/14388767.jpg"/>
385 $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
386 foreach ($enclosures AS $enclosure) {
391 foreach ($enclosure->attributes AS $attribute) {
392 if (in_array($attribute->name, ["url", "href"])) {
393 $href = $attribute->textContent;
394 } elseif ($attribute->name == "length") {
395 $length = (int)$attribute->textContent;
396 } elseif ($attribute->name == "type") {
397 $type = $attribute->textContent;
402 $attachments[] = ['type' => Post\Media::DOCUMENT, 'url' => $href, 'mimetype' => $type, 'size' => $length];
407 $categories = $xpath->query("category", $entry);
408 foreach ($categories AS $category) {
409 $taglist[] = $category->nodeValue;
412 $body = trim(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
415 $body = trim(XML::getFirstNodeValue($xpath, 'content:encoded/text()', $entry));
418 $summary = trim(XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry));
420 if (empty($summary)) {
421 $summary = trim(XML::getFirstNodeValue($xpath, 'description/text()', $entry));
429 if ($body == $summary) {
433 // remove the content of the title if it is identically to the body
434 // This helps with auto generated titles e.g. from tumblr
435 if (self::titleIsBody($item["title"], $body)) {
438 $item["body"] = HTML::toBBCode($body, $basepath);
440 // Remove tracking pixels
441 $item["body"] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item["body"]);
443 if (($item["body"] == '') && ($item["title"] != '')) {
444 $item["body"] = $item["title"];
451 } elseif (!Item::isValid($item)) {
452 Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
454 } elseif (Item::isTooOld($item)) {
455 Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
460 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
461 // Handle enclosures and treat them as preview picture
462 foreach ($attachments AS $attachment) {
463 if ($attachment["mimetype"] == "image/jpeg") {
464 $preview = $attachment["url"];
468 // Remove a possible link to the item itself
469 $item["body"] = str_replace($item["plink"], '', $item["body"]);
470 $item["body"] = trim(preg_replace('/\[url\=\](\w+.*?)\[\/url\]/i', '', $item["body"]));
472 // Replace the content when the title is longer than the body
473 $replace = (strlen($item["title"]) > strlen($item["body"]));
475 // Replace it, when there is an image in the body
476 if (strstr($item["body"], '[/img]')) {
480 // Replace it, when there is a link in the body
481 if (strstr($item["body"], '[/url]')) {
485 $saved_body = $item["body"];
486 $saved_title = $item["title"];
489 $item["body"] = trim($item["title"]);
492 $data = ParseUrl::getSiteinfoCached($item['plink']);
493 if (!empty($data['text']) && !empty($data['title']) && (mb_strlen($item['body']) < mb_strlen($data['text']))) {
494 // When the fetched page info text is longer than the body, we do try to enhance the body
495 if (!empty($item['body']) && (strpos($data['title'], $item['body']) === false) && (strpos($data['text'], $item['body']) === false)) {
496 // The body is not part of the fetched page info title or page info text. So we add the text to the body
497 $item['body'] .= "\n\n" . $data['text'];
499 // Else we replace the body with the page info text
500 $item['body'] = $data['text'];
504 $data = PageInfo::queryUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
507 // Take the data that was provided by the feed if the query is empty
508 if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
509 $data['title'] = $saved_title;
510 $item["body"] = $saved_body;
513 $data_text = strip_tags(trim($data['text'] ?? ''));
514 $item_body = strip_tags(trim($item['body'] ?? ''));
516 if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
520 // We always strip the title since it will be added in the page information
522 $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromData($data, false);
523 $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
524 $item["object-type"] = Activity\ObjectType::BOOKMARK;
528 if (!empty($summary)) {
529 $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
532 if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] == 3)) {
533 if (empty($taglist)) {
534 $taglist = PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '');
536 $item["body"] .= "\n" . self::tagToString($taglist);
541 // Add the link to the original feed entry if not present in feed
542 if (($item['plink'] != '') && !strstr($item["body"], $item['plink'])) {
543 $item["body"] .= "[hr][url]" . $item['plink'] . "[/url]";
547 if (empty($item['title'])) {
548 $item['post-type'] = Item::PT_NOTE;
551 Logger::info('Stored feed', ['item' => $item]);
553 $notify = Item::isRemoteSelf($contact, $item);
555 // Distributed items should have a well formatted URI.
556 // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
558 $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
559 $item['uri'] = Item::newURI($item['uid'], $item['guid']);
560 unset($item['thr-parent']);
561 unset($item['parent-uri']);
563 // Set the delivery priority for "remote self" to "medium"
564 $notify = PRIORITY_MEDIUM;
567 $condition = ['uid' => $item['uid'], 'uri' => $item['uri']];
568 if (!Post::exists($condition) && !Post\Delayed::exists($item["uri"], $item['uid'])) {
570 Post\Delayed::publish($item, $notify, $taglist, $attachments);
572 $postings[] = ['item' => $item, 'notify' => $notify,
573 'taglist' => $taglist, 'attachments' => $attachments];
576 Logger::info('Post already created or exists in the delayed posts queue', ['uid' => $item['uid'], 'uri' => $item["uri"]]);
580 if (!empty($postings)) {
581 $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
582 $total = count($postings);
584 // Posts shouldn't be delayed more than a day
585 $interval = min(1440, self::getPollInterval($contact));
586 $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
587 Logger::info('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
594 foreach ($postings as $posting) {
596 $publish_time = time() + $post_delay;
597 $post_delay += $delay;
599 $publish_time = time();
602 $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
603 $next_publish = max($last_publish + (60 * $min_posting), time());
604 if ($publish_time < $next_publish) {
605 $publish_time = $next_publish;
607 $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
609 if (Post\Delayed::add($posting['item']['uri'], $posting['item'], $posting['notify'], Post\Delayed::PREPARED, $publish_at, $posting['taglist'], $posting['attachments'])) {
610 DI::pConfig()->set($item['uid'], 'system', 'last_publish', $publish_time);
615 if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
616 self::adjustPollFrequency($contact, $creation_dates);
619 return ["header" => $author, "items" => $items];
623 * Automatically adjust the poll frequency according to the post frequency
625 * @param array $contact
626 * @param array $creation_dates
629 private static function adjustPollFrequency(array $contact, array $creation_dates)
631 if ($contact['network'] != Protocol::FEED) {
632 Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
636 if (!empty($creation_dates)) {
637 // Count the post frequency and the earliest and latest post date
641 $oldest_date = $newest_date = '';
643 foreach ($creation_dates as $date) {
644 $timestamp = strtotime($date);
645 $day = intdiv($timestamp, 86400);
646 $hour = $timestamp % 86400;
648 // Only have a look at values from the last seven days
649 if (((time() / 86400) - $day) < 7) {
650 if (empty($frequency[$day])) {
651 $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
653 ++$frequency[$day]['count'];
654 if ($frequency[$day]['low'] > $hour) {
655 $frequency[$day]['low'] = $hour;
657 if ($frequency[$day]['high'] < $hour) {
658 $frequency[$day]['high'] = $hour;
662 if ($oldest > $day) {
664 $oldest_date = $date;
667 if ($newest < $day) {
669 $newest_date = $date;
673 if (count($creation_dates) == 1) {
674 Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
675 $priority = 8; // Poll once a day
678 if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
679 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']]);
680 $priority = 10; // Poll every month
683 if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
684 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']]);
685 $priority = 9; // Poll every week
688 if (empty($priority) && empty($frequency)) {
689 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']]);
690 $priority = 8; // Poll once a day
693 if (empty($priority)) {
694 // Calculate the highest "posts per day" value
696 foreach ($frequency as $entry) {
697 if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
701 // We take the earliest and latest post day and interpolate the number of post per day
702 // that would had been created with this post frequency
704 // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
705 $duration = max($entry['high'] - $entry['low'], 14400);
706 $ppd = (86400 / $duration) * $entry['count'];
712 $priority = 1; // Poll every quarter hour
713 } elseif ($max > 24) {
714 $priority = 2; // Poll half an hour
715 } elseif ($max > 12) {
716 $priority = 3; // Poll hourly
717 } elseif ($max > 8) {
718 $priority = 4; // Poll every two hours
719 } elseif ($max > 4) {
720 $priority = 5; // Poll every three hours
721 } elseif ($max > 2) {
722 $priority = 6; // Poll every six hours
724 $priority = 7; // Poll twice a day
726 Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
729 Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
730 $priority = 8; // Poll once a day
733 if ($contact['rating'] != $priority) {
734 Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
735 Contact::update(['rating' => $priority], ['id' => $contact['id']]);
740 * Get the poll interval for the given contact array
742 * @param array $contact
743 * @return int Poll interval in minutes
745 public static function getPollInterval(array $contact)
747 if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
748 $ratings = [0, 3, 7, 8, 9, 10];
749 if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
750 $rating = $contact['rating'];
751 } elseif (array_key_exists($contact['priority'], $ratings)) {
752 $rating = $ratings[$contact['priority']];
757 // Check once a week per default for all other networks
761 // Friendica and OStatus are checked once a day
762 if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
766 // Check archived contacts or contacts with unsupported protocols once a month
767 if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
775 * Based on $contact['priority'], should we poll this site now? Or later?
778 $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
780 $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
782 //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
783 // '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
785 return $poll_intervals[$rating];
789 * Convert a tag array to a tag string
792 * @return string tag string
794 private static function tagToString(array $tags)
798 foreach ($tags as $tag) {
803 $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
809 private static function titleIsBody($title, $body)
811 $title = strip_tags($title);
812 $title = trim($title);
813 $title = html_entity_decode($title, ENT_QUOTES, 'UTF-8');
814 $title = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $title);
816 $body = strip_tags($body);
818 $body = html_entity_decode($body, ENT_QUOTES, 'UTF-8');
819 $body = str_replace(["\n", "\r", "\t", " "], ["", "", "", ""], $body);
821 if (strlen($title) < strlen($body)) {
822 $body = substr($body, 0, strlen($title));
825 if (($title != $body) && (substr($title, -3) == "...")) {
826 $pos = strrpos($title, "...");
828 $title = substr($title, 0, $pos);
829 $body = substr($body, 0, $pos);
832 return ($title == $body);
836 * Creates the Atom feed for a given nickname
839 * - activity (default): all the public posts
840 * - posts: all the public top-level posts
841 * - comments: all the public replies
843 * Updates the provided last_update parameter if the result comes from the
844 * cache or it is empty
846 * @param string $owner_nick Nickname of the feed owner
847 * @param string $last_update Date of the last update
848 * @param integer $max_items Number of maximum items to fetch
849 * @param string $filter Feed items filter (activity, posts or comments)
850 * @param boolean $nocache Wether to bypass caching
852 * @return string Atom feed
853 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
854 * @throws \ImagickException
856 public static function atom($owner_nick, $last_update, $max_items = 300, $filter = 'activity', $nocache = false)
858 $stamp = microtime(true);
860 $owner = User::getOwnerDataByNick($owner_nick);
865 $cachekey = "feed:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
867 $previous_created = $last_update;
869 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
870 if ((time() - strtotime($owner['last-item'])) < 15*60) {
871 $result = DI::cache()->get($cachekey);
872 if (!$nocache && !is_null($result)) {
873 Logger::info('Cached feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
874 return $result['feed'];
878 $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
879 $authorid = Contact::getIdForURL($owner["url"]);
881 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
882 AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
883 $owner["uid"], $check_date, GRAVITY_PARENT, GRAVITY_COMMENT,
884 Item::PRIVATE, Protocol::ACTIVITYPUB,
885 Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA];
887 if ($filter === 'comments') {
888 $condition[0] .= " AND `gravity` = ? ";
889 $condition[] = GRAVITY_COMMENT;
892 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
893 $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
894 $condition[] = $owner["id"];
895 $condition[] = $authorid;
898 $params = ['order' => ['received' => true], 'limit' => $max_items];
900 if ($filter === 'posts') {
901 $ret = Post::selectThread(Item::DELIVER_FIELDLIST, $condition, $params);
903 $ret = Post::select(Item::DELIVER_FIELDLIST, $condition, $params);
906 $items = Post::toArray($ret);
908 $doc = new DOMDocument('1.0', 'utf-8');
909 $doc->formatOutput = true;
911 $root = self::addHeader($doc, $owner, $filter);
913 foreach ($items as $item) {
914 $entry = self::entry($doc, $item, $owner);
915 $root->appendChild($entry);
917 if ($last_update < $item['created']) {
918 $last_update = $item['created'];
922 $feeddata = trim($doc->saveXML());
924 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
925 DI::cache()->set($cachekey, $msg, Duration::QUARTER_HOUR);
927 Logger::info('Feed duration', ['seconds' => number_format(microtime(true) - $stamp, 3), 'nick' => $owner_nick, 'filter' => $filter, 'created' => $previous_created]);
933 * Adds the header elements to the XML document
935 * @param DOMDocument $doc XML document
936 * @param array $owner Contact data of the poster
937 * @param string $filter The related feed filter (activity, posts or comments)
939 * @return object header root element
940 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
942 private static function addHeader(DOMDocument $doc, array $owner, $filter)
944 $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
945 $doc->appendChild($root);
948 $selfUri = '/feed/' . $owner["nick"] . '/';
951 $title = DI::l10n()->t('%s\'s timeline', $owner['name']);
955 $title = DI::l10n()->t('%s\'s posts', $owner['name']);
958 $title = DI::l10n()->t('%s\'s comments', $owner['name']);
963 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
964 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
965 XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
966 XML::addElement($doc, $root, "title", $title);
967 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], DI::config()->get('config', 'sitename')));
968 XML::addElement($doc, $root, "logo", Contact::getAvatarUrlForId($owner['id'], Proxy::SIZE_SMALL, $owner['updated']));
969 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
971 $author = self::addAuthor($doc, $owner);
972 $root->appendChild($author);
974 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
975 XML::addElement($doc, $root, "link", "", $attributes);
977 OStatus::hublinks($doc, $root, $owner["nick"]);
979 $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
980 XML::addElement($doc, $root, "link", "", $attributes);
986 * Adds the author element to the XML document
988 * @param DOMDocument $doc XML document
989 * @param array $owner Contact data of the poster
991 * @return \DOMElement author element
992 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
994 private static function addAuthor(DOMDocument $doc, array $owner)
996 $author = $doc->createElement("author");
997 XML::addElement($doc, $author, "uri", $owner["url"]);
998 XML::addElement($doc, $author, "name", $owner["nick"]);
999 XML::addElement($doc, $author, "email", $owner["addr"]);
1005 * Adds an entry element to the XML document
1007 * @param DOMDocument $doc XML document
1008 * @param array $item Data of the item that is to be posted
1009 * @param array $owner Contact data of the poster
1010 * @param bool $toplevel optional default false
1012 * @return \DOMElement Entry element
1013 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1014 * @throws \ImagickException
1016 private static function entry(DOMDocument $doc, array $item, array $owner)
1020 $repeated_guid = OStatus::getResharedGuid($item);
1021 if ($repeated_guid != "") {
1022 $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid);
1029 return self::noteEntry($doc, $item, $owner);
1033 * Adds an entry element with reshared content
1035 * @param DOMDocument $doc XML document
1036 * @param array $item Data of the item that is to be posted
1037 * @param array $owner Contact data of the poster
1038 * @param string $repeated_guid guid
1039 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1041 * @return bool Entry element
1042 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1043 * @throws \ImagickException
1045 private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid)
1047 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1048 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1051 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1053 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => [Item::PUBLIC, Item::UNLISTED],
1054 'network' => Protocol::FEDERATED];
1055 $repeated_item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition);
1056 if (!DBA::isResult($repeated_item)) {
1060 self::entryContent($doc, $entry, $item, self::getTitle($repeated_item), Activity::SHARE, false);
1062 self::entryFooter($doc, $entry, $item, $owner);
1068 * Adds a regular entry element
1070 * @param DOMDocument $doc XML document
1071 * @param array $item Data of the item that is to be posted
1072 * @param array $owner Contact data of the poster
1073 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1075 * @return \DOMElement Entry element
1076 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1077 * @throws \ImagickException
1079 private static function noteEntry(DOMDocument $doc, array $item, array $owner)
1081 if (($item['gravity'] != GRAVITY_PARENT) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1082 Logger::info('Feed entry author does not match feed owner', ['owner' => $owner["url"], 'author' => $item["author-link"]]);
1085 $entry = OStatus::entryHeader($doc, $owner, $item, false);
1087 self::entryContent($doc, $entry, $item, self::getTitle($item), '', true);
1089 self::entryFooter($doc, $entry, $item, $owner);
1095 * Adds elements to the XML document
1097 * @param DOMDocument $doc XML document
1098 * @param \DOMElement $entry Entry element where the content is added
1099 * @param array $item Data of the item that is to be posted
1100 * @param array $owner Contact data of the poster
1101 * @param string $title Title for the post
1102 * @param string $verb The activity verb
1103 * @param bool $complete Add the "status_net" element?
1104 * @param bool $feed_mode Behave like a regular feed for users if true
1106 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1108 private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, $title, $verb = "", $complete = true)
1111 $verb = OStatus::constructVerb($item);
1114 XML::addElement($doc, $entry, "id", $item["uri"]);
1115 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1117 $body = OStatus::formatPicturePost($item['body'], $item['uri-id']);
1119 $body = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1121 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1123 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1124 "href" => DI::baseUrl()."/display/".$item["guid"]]
1127 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1128 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1132 * Adds the elements at the foot of an entry to the XML document
1134 * @param DOMDocument $doc XML document
1135 * @param object $entry The entry element where the elements are added
1136 * @param array $item Data of the item that is to be posted
1137 * @param array $owner Contact data of the poster
1138 * @param bool $complete default true
1140 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1142 private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner)
1146 if ($item['gravity'] != GRAVITY_PARENT) {
1147 $parent = Post::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
1149 $thrparent = Post::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $item['thr-parent']]);
1151 if (DBA::isResult($thrparent)) {
1152 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1153 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1154 $parent_plink = $thrparent["plink"];
1156 $mentioned[$parent["author-link"]] = $parent["author-link"];
1157 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1158 $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
1162 "ref" => $item['thr-parent'],
1163 "href" => $parent_plink];
1164 XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1168 "href" => $parent_plink];
1169 XML::addElement($doc, $entry, "link", "", $attributes);
1172 // uri-id isn't present for follow entry pseudo-items
1173 $tags = Tag::getByURIId($item['uri-id'] ?? 0);
1174 foreach ($tags as $tag) {
1175 $mentioned[$tag['url']] = $tag['url'];
1178 foreach ($tags as $tag) {
1179 if ($tag['type'] == Tag::HASHTAG) {
1180 XML::addElement($doc, $entry, "category", "", ["term" => $tag['name']]);
1184 OStatus::getAttachment($doc, $entry, $item);
1188 * Fetch or create title for feed entry
1190 * @param array $item
1191 * @return string title
1193 private static function getTitle(array $item)
1195 if ($item['title'] != '') {
1196 return BBCode::convertForUriId($item['uri-id'], $item['title'], BBCode::ACTIVITYPUB);
1199 // Fetch information about the post
1200 $siteinfo = BBCode::getAttachedData($item["body"]);
1201 if (isset($siteinfo["title"])) {
1202 return $siteinfo["title"];
1205 // If no bookmark is found then take the first line
1206 // Remove the share element before fetching the first line
1207 $title = trim(preg_replace("/\[share.*?\](.*?)\[\/share\]/ism","\n$1\n",$item['body']));
1209 $title = BBCode::toPlaintext($title)."\n";
1210 $pos = strpos($title, "\n");
1212 if (($pos == 0) || ($pos > 100)) {
1217 return substr($title, 0, $pos) . $trailer;