]> git.mxchange.org Git - friendica.git/blobdiff - src/Protocol/Feed.php
Reducing parameter list
[friendica.git] / src / Protocol / Feed.php
index 9aab4f52c6b92aa864d86f8c07a2aae590f88f47..821de8c33580556f3d8675531a65ee5f6782a5b5 100644 (file)
@@ -29,13 +29,15 @@ use Friendica\Content\Text\HTML;
 use Friendica\Core\Cache\Duration;
 use Friendica\Core\Logger;
 use Friendica\Core\Protocol;
+use Friendica\Core\Worker;
 use Friendica\Database\DBA;
 use Friendica\DI;
 use Friendica\Model\Contact;
+use Friendica\Model\Conversation;
 use Friendica\Model\Item;
+use Friendica\Model\Post;
 use Friendica\Model\Tag;
 use Friendica\Model\User;
-use Friendica\Network\HTTPRequest;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Network;
 use Friendica\Util\ParseUrl;
@@ -100,7 +102,7 @@ class Feed
                        $dfrn_importer = DFRN::getImporter($contact['id'], $importer['uid']);
                        if (!empty($dfrn_importer)) {
                                Logger::info('Now import the DFRN feed');
-                               DFRN::import($xml, $dfrn_importer, true);
+                               DFRN::import($xml, $dfrn_importer, true, Conversation::PARCEL_LEGACY_DFRN);
                                return;
                        }
                }
@@ -301,6 +303,7 @@ class Feed
                }
 
                $items = [];
+               $creation_dates = [];
 
                // Limit the number of items that are about to be fetched
                $total_items = ($entries->length - 1);
@@ -309,6 +312,8 @@ class Feed
                        $total_items = $max_items;
                }
 
+               $postings = [];
+
                // Importing older entries first
                for ($i = $total_items; $i >= 0; --$i) {
                        $entry = $entries->item($i);
@@ -353,18 +358,6 @@ class Feed
 
                        $item["plink"] = DI::httpRequest()->finalUrl($item["plink"]);
 
-                       $item["parent-uri"] = $item["uri"];
-
-                       if (!$dryRun) {
-                               $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
-                                       $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
-                               $previous = Item::selectFirst(['id'], $condition);
-                               if (DBA::isResult($previous)) {
-                                       Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
-                                       continue;
-                               }
-                       }
-
                        $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
 
                        if (empty($item["title"])) {
@@ -404,6 +397,19 @@ class Feed
                                $item["edited"] = $updated;
                        }
 
+                       if (!$dryRun) {
+                               $condition = ["`uid` = ? AND `uri` = ? AND `network` IN (?, ?)",
+                                       $importer["uid"], $item["uri"], Protocol::FEED, Protocol::DFRN];
+                               $previous = Item::selectFirst(['id', 'created'], $condition);
+                               if (DBA::isResult($previous)) {
+                                       // Use the creation date when the post had been stored. It can happen this date changes in the feed.
+                                       $creation_dates[] = $previous['created'];
+                                       Logger::info("Item with uri " . $item["uri"] . " for user " . $importer["uid"] . " already existed under id " . $previous["id"]);
+                                       continue;
+                               }
+                               $creation_dates[] = DateTimeFormat::utc($item['created']);
+                       }
+
                        $creator = XML::getFirstNodeValue($xpath, 'author/text()', $entry);
 
                        if (empty($creator)) {
@@ -433,28 +439,22 @@ class Feed
                        $enclosures = $xpath->query("enclosure|atom:link[@rel='enclosure']", $entry);
                        foreach ($enclosures AS $enclosure) {
                                $href = "";
-                               $length = "";
-                               $type = "";
+                               $length = null;
+                               $type = null;
 
                                foreach ($enclosure->attributes AS $attribute) {
                                        if (in_array($attribute->name, ["url", "href"])) {
                                                $href = $attribute->textContent;
                                        } elseif ($attribute->name == "length") {
-                                               $length = $attribute->textContent;
+                                               $length = (int)$attribute->textContent;
                                        } elseif ($attribute->name == "type") {
                                                $type = $attribute->textContent;
                                        }
                                }
 
-                               if (!empty($item["attach"])) {
-                                       $item["attach"] .= ',';
-                               } else {
-                                       $item["attach"] = '';
+                               if (!empty($href)) {
+                                       $attachments[] = ['type' => Post\Media::DOCUMENT, 'url' => $href, 'mimetype' => $type, 'size' => $length];
                                }
-
-                               $attachments[] = ["link" => $href, "type" => $type, "length" => $length];
-
-                               $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '"[/attach]';
                        }
 
                        $taglist = [];
@@ -491,17 +491,31 @@ class Feed
                        }
                        $item["body"] = HTML::toBBCode($body, $basepath);
 
+                       // Remove tracking pixels
+                       $item["body"] = preg_replace("/\[img=1x1\]([^\[\]]*)\[\/img\]/Usi", '', $item["body"]);
+
                        if (($item["body"] == '') && ($item["title"] != '')) {
                                $item["body"] = $item["title"];
                                $item["title"] = '';
                        }
 
+                       if ($dryRun) {
+                               $items[] = $item;
+                               break;
+                       } elseif (!Item::isValid($item)) {
+                               Logger::info('Feed item is invalid', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
+                               continue;
+                       } elseif (Item::isTooOld($item)) {
+                               Logger::info('Feed is too old', ['created' => $item['created'], 'uid' => $item['uid'], 'uri' => $item['uri']]);
+                               continue;
+                       }
+
                        $preview = '';
                        if (!empty($contact["fetch_further_information"]) && ($contact["fetch_further_information"] < 3)) {
                                // Handle enclosures and treat them as preview picture
                                foreach ($attachments AS $attachment) {
-                                       if ($attachment["type"] == "image/jpeg") {
-                                               $preview = $attachment["link"];
+                                       if ($attachment["mimetype"] == "image/jpeg") {
+                                               $preview = $attachment["url"];
                                        }
                                }
 
@@ -522,6 +536,9 @@ class Feed
                                        $replace = true;
                                }
 
+                               $saved_body = $item["body"];
+                               $saved_title = $item["title"];
+
                                if ($replace) {
                                        $item["body"] = trim($item["title"]);
                                }
@@ -538,12 +555,29 @@ class Feed
                                        }
                                }
 
-                               // We always strip the title since it will be added in the page information
-                               $item["title"] = "";
-                               $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
-                               $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
-                               $item["object-type"] = Activity\ObjectType::BOOKMARK;
-                               unset($item["attach"]);
+                               $data = PageInfo::queryUrl($item["plink"], false, $preview, ($contact["fetch_further_information"] == 2), $contact["ffi_keyword_denylist"] ?? '');
+
+                               if (!empty($data)) {
+                                       // Take the data that was provided by the feed if the query is empty
+                                       if (($data['type'] == 'link') && empty($data['title']) && empty($data['text'])) {
+                                               $data['title'] = $saved_title;
+                                               $item["body"] = $saved_body;
+                                       }
+
+                                       $data_text = strip_tags(trim($data['text'] ?? ''));
+                                       $item_body = strip_tags(trim($item['body'] ?? ''));
+
+                                       if (!empty($data_text) && (($data_text == $item_body) || strstr($item_body, $data_text))) {
+                                               $data['text'] = '';
+                                       }
+
+                                       // We always strip the title since it will be added in the page information
+                                       $item["title"] = "";
+                                       $item["body"] = $item["body"] . "\n" . PageInfo::getFooterFromData($data, false);
+                                       $taglist = $contact["fetch_further_information"] == 2 ? PageInfo::getTagsFromUrl($item["plink"], $preview, $contact["ffi_keyword_denylist"] ?? '') : [];
+                                       $item["object-type"] = Activity\ObjectType::BOOKMARK;
+                                       $attachments = [];
+                               }
                        } else {
                                if (!empty($summary)) {
                                        $item["body"] = '[abstract]' . HTML::toBBCode($summary, $basepath) . "[/abstract]\n" . $item["body"];
@@ -564,39 +598,240 @@ class Feed
                                }
                        }
 
-                       if ($dryRun) {
-                               $items[] = $item;
-                               break;
+                       Logger::info('Stored feed', ['item' => $item]);
+
+                       $notify = Item::isRemoteSelf($contact, $item);
+
+                       // Distributed items should have a well formatted URI.
+                       // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
+                       if ($notify) {
+                               $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
+                               $item['uri'] = Item::newURI($item['uid'], $item['guid']);
+                               unset($item['thr-parent']);
+                               unset($item['parent-uri']);
+
+                               // Set the delivery priority for "remote self" to "medium"
+                               $notify = PRIORITY_MEDIUM;
+                       }
+
+                       if (!Post\Delayed::exists($item["uri"])) {
+                               $postings[] = ['item' => $item, 'notify' => $notify,
+                                       'taglist' => $taglist, 'attachments' => $attachments];
                        } else {
-                               Logger::info('Stored feed', ['item' => $item]);
+                               Logger::info('Post already exists in the delayed posts queue', ['uri' => $item["uri"]]);
+                       }
+               }
 
-                               $notify = Item::isRemoteSelf($contact, $item);
+               if (!empty($postings)) {
+                       $min_posting = DI::config()->get('system', 'minimum_posting_interval', 0);
+                       $total = count($postings);
+                       if ($total > 1) {
+                               // Posts shouldn't be delayed more than a day
+                               $interval = min(1440, self::getPollInterval($contact));
+                               $delay = max(round(($interval * 60) / $total), 60 * $min_posting);
+                               Logger::notice('Got posting delay', ['delay' => $delay, 'interval' => $interval, 'items' => $total, 'cid' => $contact['id'], 'url' => $contact['url']]);
+                       } else {
+                               $delay = 0;
+                       }
+
+                       $post_delay = 0;
 
-                               // Distributed items should have a well formatted URI.
-                               // Additionally we have to avoid conflicts with identical URI between imported feeds and these items.
-                               if ($notify) {
-                                       $item['guid'] = Item::guidFromUri($orig_plink, DI::baseUrl()->getHostname());
-                                       unset($item['uri']);
-                                       unset($item['parent-uri']);
+                       foreach ($postings as $posting) {
+                               if ($delay > 0) {
+                                       $publish_time = time() + $post_delay;
+                                       Logger::notice('Got publishing date', ['delay' => $delay, 'cid' => $contact['id'], 'url' => $contact['url']]);
+                                       $post_delay += $delay;
+                               } else {
+                                       $publish_time = time();
+                               }
 
-                                       // Set the delivery priority for "remote self" to "medium"
-                                       $notify = PRIORITY_MEDIUM;
+                               $last_publish = DI::pConfig()->get($posting['item']['uid'], 'system', 'last_publish', 0, true);
+                               $next_publish = max($last_publish + (60 * $min_posting), time());
+                               if ($publish_time < $next_publish) {
+                                       Logger::notice('Adapting publish time',
+                                               ['last' => date(DateTimeFormat::MYSQL, $last_publish),
+                                               'next' => date(DateTimeFormat::MYSQL, $next_publish),
+                                               'publish' => date(DateTimeFormat::MYSQL, $publish_time)]);
+                                       $publish_time = $next_publish;
                                }
+                               $publish_at = date(DateTimeFormat::MYSQL, $publish_time);
 
-                               $id = Item::insert($item, $notify);
+                               Post\Delayed::add($publish_at, $posting['item'], $posting['notify'], $posting['taglist'], $posting['attachments']);
+                               DI::pConfig()->set($item['uid'], 'system', 'last_publish', $next_publish);
+                       }
+               }
 
-                               Logger::info("Feed for contact " . $contact["url"] . " stored under id " . $id);
+               if (!$dryRun && DI::config()->get('system', 'adjust_poll_frequency')) {
+                       self::adjustPollFrequency($contact, $creation_dates);
+               }
+
+               return ["header" => $author, "items" => $items];
+       }
 
-                               if (!empty($id) && !empty($taglist)) {
-                                       $feeditem = Item::selectFirst(['uri-id'], ['id' => $id]);
-                                       foreach ($taglist as $tag) {
-                                               Tag::store($feeditem['uri-id'], Tag::HASHTAG, $tag);
-                                       }                                       
+       /**
+        * Automatically adjust the poll frequency according to the post frequency
+        *
+        * @param array $contact
+        * @param array $creation_dates
+        * @return void
+        */
+       private static function adjustPollFrequency(array $contact, array $creation_dates)
+       {
+               if ($contact['network'] != Protocol::FEED) {
+                       Logger::info('Contact is no feed, skip.', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url'], 'network' => $contact['network']]);
+                       return;
+               }
+
+               if (!empty($creation_dates)) {
+                       // Count the post frequency and the earliest and latest post date
+                       $frequency = [];
+                       $oldest = time();
+                       $newest = 0;
+                       $oldest_date = $newest_date = '';
+
+                       foreach ($creation_dates as $date) {
+                               $timestamp = strtotime($date);
+                               $day = intdiv($timestamp, 86400);
+                               $hour = $timestamp % 86400;
+
+                               // Only have a look at values from the last seven days
+                               if (((time() / 86400) - $day) < 7) {
+                                       if (empty($frequency[$day])) {
+                                               $frequency[$day] = ['count' => 1, 'low' => $hour, 'high' => $hour];
+                                       } else {
+                                               ++$frequency[$day]['count'];
+                                               if ($frequency[$day]['low'] > $hour) {
+                                                       $frequency[$day]['low'] = $hour;
+                                               }
+                                               if ($frequency[$day]['high'] < $hour) {
+                                                       $frequency[$day]['high'] = $hour;
+                                               }
+                                       }
+                               }
+                               if ($oldest > $day) {
+                                       $oldest = $day;
+                                       $oldest_date = $date;
+                               }
+
+                               if ($newest < $day) {
+                                       $newest = $day;
+                                       $newest_date = $date;
+                               }
+                       }
+
+                       if (count($creation_dates) == 1) {
+                               Logger::info('Feed had posted a single time, switching to daily polling', ['newest' => $newest_date, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
+                               $priority = 8; // Poll once a day
+                       }
+
+                       if (empty($priority) && (((time() / 86400) - $newest) > 730)) {
+                               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']]);
+                               $priority = 10; // Poll every month
+                       }
+
+                       if (empty($priority) && (((time() / 86400) - $newest) > 365)) {
+                               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']]);
+                               $priority = 9; // Poll every week
+                       }
+
+                       if (empty($priority) && empty($frequency)) {
+                               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']]);
+                               $priority = 8; // Poll once a day
+                       }
+
+                       if (empty($priority)) {
+                               // Calculate the highest "posts per day" value
+                               $max = 0;
+                               foreach ($frequency as $entry) {
+                                       if (($entry['count'] == 1) || ($entry['high'] == $entry['low'])) {
+                                               continue;
+                                       }
+
+                                       // We take the earliest and latest post day and interpolate the number of post per day
+                                       // that would had been created with this post frequency
+
+                                       // Assume at least four hours between oldest and newest post per day - should be okay for news outlets
+                                       $duration = max($entry['high'] - $entry['low'], 14400);
+                                       $ppd = (86400 / $duration) * $entry['count'];
+                                       if ($ppd > $max) {
+                                               $max = $ppd;
+                                       }
+                               }
+                               if ($max > 48) {
+                                       $priority = 1; // Poll every quarter hour
+                               } elseif ($max > 24) {
+                                       $priority = 2; // Poll half an hour
+                               } elseif ($max > 12) {
+                                       $priority = 3; // Poll hourly
+                               } elseif ($max > 8) {
+                                       $priority = 4; // Poll every two hours
+                               } elseif ($max > 4) {
+                                       $priority = 5; // Poll every three hours
+                               } elseif ($max > 2) {
+                                       $priority = 6; // Poll every six hours
+                               } else {
+                                       $priority = 7; // Poll twice a day
                                }
+                               Logger::info('Calculated priority by the posts per day', ['priority' => $priority, 'max' => round($max, 2), 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
                        }
+               } else {
+                       Logger::info('No posts, switching to daily polling', ['id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
+                       $priority = 8; // Poll once a day
                }
 
-               return ["header" => $author, "items" => $items];
+               if ($contact['rating'] != $priority) {
+                       Logger::notice('Adjusting priority', ['old' => $contact['rating'], 'new' => $priority, 'id' => $contact['id'], 'uid' => $contact['uid'], 'url' => $contact['url']]);
+                       DBA::update('contact', ['rating' => $priority], ['id' => $contact['id']]);
+               }
+       }
+
+       /**
+        * Get the poll interval for the given contact array
+        *
+        * @param array $contact
+        * @return int Poll interval in minutes
+        */
+       public static function getPollInterval(array $contact)
+       {
+               if (in_array($contact['network'], [Protocol::MAIL, Protocol::FEED])) {
+                       $ratings = [0, 3, 7, 8, 9, 10];
+                       if (DI::config()->get('system', 'adjust_poll_frequency') && ($contact['network'] == Protocol::FEED)) {
+                               $rating = $contact['rating'];
+                       } elseif (array_key_exists($contact['priority'], $ratings)) {
+                               $rating = $ratings[$contact['priority']];
+                       } else {
+                               $rating = -1;
+                       }
+               } else {
+                       // Check once a week per default for all other networks
+                       $rating = 9;
+               }
+
+               // Friendica and OStatus are checked once a day
+               if (in_array($contact['network'], [Protocol::DFRN, Protocol::OSTATUS])) {
+                       $rating = 8;
+               }
+
+               // Check archived contacts or contacts with unsupported protocols once a month
+               if ($contact['archive'] || in_array($contact['network'], [Protocol::ZOT, Protocol::PHANTOM])) {
+                       $rating = 10;
+               }
+
+               if ($rating < 0) {
+                       return 0;
+               }
+               /*
+                * Based on $contact['priority'], should we poll this site now? Or later?
+                */
+
+               $min_poll_interval = max(1, DI::config()->get('system', 'min_poll_interval'));
+
+               $poll_intervals = [$min_poll_interval, 15, 30, 60, 120, 180, 360, 720 ,1440, 10080, 43200];
+
+               //$poll_intervals = [$min_poll_interval . ' minute', '15 minute', '30 minute',
+               //      '1 hour', '2 hour', '3 hour', '6 hour', '12 hour' ,'1 day', '1 week', '1 month'];
+
+               return $poll_intervals[$rating];
        }
 
        /**
@@ -613,7 +848,7 @@ class Feed
                        if ($tagstr != "") {
                                $tagstr .= ", ";
                        }
-       
+
                        $tagstr .= "#[url=" . DI::baseUrl() . "/search?tag=" . urlencode($tag) . "]" . $tag . "[/url]";
                }
 
@@ -690,7 +925,7 @@ class Feed
                }
 
                $check_date = empty($last_update) ? '' : DateTimeFormat::utc($last_update);
-               $authorid = Contact::getIdForURL($owner["url"], 0, false);
+               $authorid = Contact::getIdForURL($owner["url"]);
 
                $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted` AND `gravity` IN (?, ?)
                        AND `private` != ? AND `visible` AND `wall` AND `parent-network` IN (?, ?, ?, ?)",
@@ -959,9 +1194,8 @@ class Feed
 
                if ($item['gravity'] != GRAVITY_PARENT) {
                        $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item['parent']]);
-                       $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
 
-                       $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
+                       $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $item['thr-parent']]);
 
                        if (DBA::isResult($thrparent)) {
                                $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
@@ -974,7 +1208,7 @@ class Feed
                        }
 
                        $attributes = [
-                                       "ref" => $parent_item,
+                                       "ref" => $item['thr-parent'],
                                        "href" => $parent_plink];
                        XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);