Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1211 lines
40 KiB

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