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.
 
 
 
 
 
 

2295 lines
76 KiB

  1. <?php
  2. /**
  3. * @file src/Protocol/OStatus.php
  4. */
  5. namespace Friendica\Protocol;
  6. use DOMDocument;
  7. use DOMXPath;
  8. use Friendica\Content\Text\BBCode;
  9. use Friendica\Content\Text\HTML;
  10. use Friendica\Core\Cache\Cache;
  11. use Friendica\Core\Config;
  12. use Friendica\Core\L10n;
  13. use Friendica\Core\Logger;
  14. use Friendica\Core\Protocol;
  15. use Friendica\Database\DBA;
  16. use Friendica\DI;
  17. use Friendica\Model\APContact;
  18. use Friendica\Model\Contact;
  19. use Friendica\Model\Conversation;
  20. use Friendica\Model\GContact;
  21. use Friendica\Model\Item;
  22. use Friendica\Model\User;
  23. use Friendica\Network\Probe;
  24. use Friendica\Util\DateTimeFormat;
  25. use Friendica\Util\Images;
  26. use Friendica\Util\Network;
  27. use Friendica\Util\Proxy as ProxyUtils;
  28. use Friendica\Util\Strings;
  29. use Friendica\Util\XML;
  30. require_once 'mod/share.php';
  31. require_once 'include/api.php';
  32. /**
  33. * @brief This class contain functions for the OStatus protocol
  34. */
  35. class OStatus
  36. {
  37. private static $itemlist;
  38. private static $conv_list = [];
  39. /**
  40. * @brief Fetches author data
  41. *
  42. * @param DOMXPath $xpath The xpath object
  43. * @param object $context The xml context of the author details
  44. * @param array $importer user record of the importing user
  45. * @param array $contact Called by reference, will contain the fetched contact
  46. * @param bool $onlyfetch Only fetch the header without updating the contact entries
  47. *
  48. * @return array Array of author related entries for the item
  49. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  50. * @throws \ImagickException
  51. */
  52. private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
  53. {
  54. $author = [];
  55. $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
  56. $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
  57. $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
  58. $aliaslink = $author["author-link"];
  59. $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
  60. if (is_object($alternate_item)) {
  61. foreach ($alternate_item->attributes as $attributes) {
  62. if (($attributes->name == "href") && ($attributes->textContent != "")) {
  63. $author["author-link"] = $attributes->textContent;
  64. }
  65. }
  66. }
  67. $author["author-id"] = Contact::getIdForURL($author["author-link"]);
  68. $author['contact-id'] = ($contact['id'] ?? 0) ?: $author['author-id'];
  69. $contact = [];
  70. /*
  71. This here would be better, but we would get problems with contacts from the statusnet addon
  72. This is kept here as a reminder for the future
  73. $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
  74. if ($cid) {
  75. $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
  76. }
  77. */
  78. if ($aliaslink != '') {
  79. $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
  80. $importer["uid"], $aliaslink, Protocol::STATUSNET,
  81. Contact::SHARING, Contact::FRIEND];
  82. $contact = DBA::selectFirst('contact', [], $condition);
  83. }
  84. if (!DBA::isResult($contact) && $author["author-link"] != '') {
  85. if ($aliaslink == "") {
  86. $aliaslink = $author["author-link"];
  87. }
  88. $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
  89. $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
  90. Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
  91. $contact = DBA::selectFirst('contact', [], $condition);
  92. }
  93. if (!DBA::isResult($contact) && ($addr != '')) {
  94. $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
  95. $importer["uid"], $addr, Protocol::STATUSNET,
  96. Contact::SHARING, Contact::FRIEND];
  97. $contact = DBA::selectFirst('contact', [], $condition);
  98. }
  99. if (DBA::isResult($contact)) {
  100. if ($contact['blocked']) {
  101. $contact['id'] = -1;
  102. } elseif (!empty(APContact::getByURL($contact['url'], false))) {
  103. ActivityPub\Receiver::switchContact($contact['id'], $importer['uid'], $contact['url']);
  104. }
  105. $author["contact-id"] = $contact["id"];
  106. }
  107. $avatarlist = [];
  108. $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
  109. foreach ($avatars as $avatar) {
  110. $href = "";
  111. $width = 0;
  112. foreach ($avatar->attributes as $attributes) {
  113. if ($attributes->name == "href") {
  114. $href = $attributes->textContent;
  115. }
  116. if ($attributes->name == "width") {
  117. $width = $attributes->textContent;
  118. }
  119. }
  120. if ($href != "") {
  121. $avatarlist[$width] = $href;
  122. }
  123. }
  124. if (count($avatarlist) > 0) {
  125. krsort($avatarlist);
  126. $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
  127. }
  128. $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
  129. if ($displayname != "") {
  130. $author["author-name"] = $displayname;
  131. }
  132. $author["owner-id"] = $author["author-id"];
  133. // Only update the contacts if it is an OStatus contact
  134. if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
  135. // Update contact data
  136. $current = $contact;
  137. unset($current['name-date']);
  138. // This query doesn't seem to work
  139. // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
  140. // if ($value != "")
  141. // $contact["notify"] = $value;
  142. // This query doesn't seem to work as well - I hate these queries
  143. // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
  144. // if ($value != "")
  145. // $contact["poll"] = $value;
  146. $contact['url'] = $author["author-link"];
  147. $contact['nurl'] = Strings::normaliseLink($contact['url']);
  148. $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
  149. if ($value != "") {
  150. $contact["alias"] = $value;
  151. }
  152. $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
  153. if ($value != "") {
  154. $contact["name"] = $value;
  155. }
  156. $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
  157. if ($value != "") {
  158. $contact["nick"] = $value;
  159. }
  160. $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
  161. if ($value != "") {
  162. $contact["about"] = HTML::toBBCode($value);
  163. }
  164. $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
  165. if ($value != "") {
  166. $contact["location"] = $value;
  167. }
  168. $contact['name-date'] = DateTimeFormat::utcNow();
  169. DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
  170. if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
  171. Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
  172. Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
  173. }
  174. // Ensure that we are having this contact (with uid=0)
  175. $cid = Contact::getIdForURL($aliaslink, 0, true);
  176. if ($cid) {
  177. $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
  178. $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
  179. // Update it with the current values
  180. $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
  181. 'nurl' => Strings::normaliseLink($author["author-link"]),
  182. 'nick' => $contact["nick"], 'alias' => $contact["alias"],
  183. 'about' => $contact["about"], 'location' => $contact["location"],
  184. 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
  185. DBA::update('contact', $fields, ['id' => $cid], $old_contact);
  186. // Update the avatar
  187. if (!empty($author["author-avatar"])) {
  188. Contact::updateAvatar($author["author-avatar"], 0, $cid);
  189. }
  190. }
  191. $contact["generation"] = 2;
  192. $contact["hide"] = false; // OStatus contacts are never hidden
  193. if (!empty($author["author-avatar"])) {
  194. $contact["photo"] = $author["author-avatar"];
  195. }
  196. $gcid = GContact::update($contact);
  197. GContact::link($gcid, $contact["uid"], $contact["id"]);
  198. } elseif ($contact["network"] != Protocol::DFRN) {
  199. $contact = [];
  200. }
  201. return $author;
  202. }
  203. /**
  204. * @brief Fetches author data from a given XML string
  205. *
  206. * @param string $xml The XML
  207. * @param array $importer user record of the importing user
  208. *
  209. * @return array Array of author related entries for the item
  210. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  211. * @throws \ImagickException
  212. */
  213. public static function salmonAuthor($xml, array $importer)
  214. {
  215. if ($xml == "") {
  216. return;
  217. }
  218. $doc = new DOMDocument();
  219. @$doc->loadXML($xml);
  220. $xpath = new DOMXPath($doc);
  221. $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
  222. $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
  223. $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
  224. $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
  225. $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
  226. $xpath->registerNamespace('poco', ActivityNamespace::POCO);
  227. $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
  228. $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
  229. $contact = ["id" => 0];
  230. // Fetch the first author
  231. $authordata = $xpath->query('//author')->item(0);
  232. $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
  233. return $author;
  234. }
  235. /**
  236. * @brief Read attributes from element
  237. *
  238. * @param object $element Element object
  239. *
  240. * @return array attributes
  241. */
  242. private static function readAttributes($element)
  243. {
  244. $attribute = [];
  245. foreach ($element->attributes as $attributes) {
  246. $attribute[$attributes->name] = $attributes->textContent;
  247. }
  248. return $attribute;
  249. }
  250. /**
  251. * @brief Imports an XML string containing OStatus elements
  252. *
  253. * @param string $xml The XML
  254. * @param array $importer user record of the importing user
  255. * @param array $contact contact
  256. * @param string $hub Called by reference, returns the fetched hub data
  257. * @return void
  258. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  259. * @throws \ImagickException
  260. */
  261. public static function import($xml, array $importer, array &$contact, &$hub)
  262. {
  263. self::process($xml, $importer, $contact, $hub);
  264. }
  265. /**
  266. * @brief Internal feed processing
  267. *
  268. * @param string $xml The XML
  269. * @param array $importer user record of the importing user
  270. * @param array $contact contact
  271. * @param string $hub Called by reference, returns the fetched hub data
  272. * @param boolean $stored Is the post fresh imported or from the database?
  273. * @param boolean $initialize Is it the leading post so that data has to be initialized?
  274. *
  275. * @return boolean Could the XML be processed?
  276. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  277. * @throws \ImagickException
  278. */
  279. private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
  280. {
  281. if ($initialize) {
  282. self::$itemlist = [];
  283. self::$conv_list = [];
  284. }
  285. Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
  286. if ($xml == "") {
  287. return false;
  288. }
  289. $doc = new DOMDocument();
  290. @$doc->loadXML($xml);
  291. $xpath = new DOMXPath($doc);
  292. $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
  293. $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
  294. $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
  295. $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
  296. $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
  297. $xpath->registerNamespace('poco', ActivityNamespace::POCO);
  298. $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
  299. $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
  300. $hub = "";
  301. $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
  302. if (is_object($hub_items)) {
  303. $hub_attributes = $hub_items->attributes;
  304. if (is_object($hub_attributes)) {
  305. foreach ($hub_attributes as $hub_attribute) {
  306. if ($hub_attribute->name == "href") {
  307. $hub = $hub_attribute->textContent;
  308. Logger::log("Found hub ".$hub, Logger::DEBUG);
  309. }
  310. }
  311. }
  312. }
  313. $header = [];
  314. $header["uid"] = $importer["uid"];
  315. $header["network"] = Protocol::OSTATUS;
  316. $header["wall"] = 0;
  317. $header["origin"] = 0;
  318. $header["gravity"] = GRAVITY_COMMENT;
  319. if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
  320. return false;
  321. }
  322. $first_child = $doc->firstChild->tagName;
  323. if ($first_child == "feed") {
  324. $entries = $xpath->query('/atom:feed/atom:entry');
  325. } else {
  326. $entries = $xpath->query('/atom:entry');
  327. }
  328. if ($entries->length == 1) {
  329. // We reformat the XML to make it better readable
  330. $doc2 = new DOMDocument();
  331. $doc2->loadXML($xml);
  332. $doc2->preserveWhiteSpace = false;
  333. $doc2->formatOutput = true;
  334. $xml2 = $doc2->saveXML();
  335. $header["protocol"] = Conversation::PARCEL_SALMON;
  336. $header["source"] = $xml2;
  337. } elseif (!$initialize) {
  338. return false;
  339. }
  340. // Fetch the first author
  341. $authordata = $xpath->query('//author')->item(0);
  342. $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
  343. // Reverse the order of the entries
  344. $entrylist = [];
  345. foreach ($entries as $entry) {
  346. $entrylist[] = $entry;
  347. }
  348. foreach (array_reverse($entrylist) as $entry) {
  349. // fetch the author
  350. $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
  351. if ($authorelement->length == 0) {
  352. $authorelement = $xpath->query('atom:author', $entry);
  353. }
  354. if ($authorelement->length > 0) {
  355. $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
  356. }
  357. $item = array_merge($header, $author);
  358. $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
  359. $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
  360. // Delete a message
  361. if (in_array($item["verb"], ['qvitter-delete-notice', Activity::DELETE, 'delete'])) {
  362. self::deleteNotice($item);
  363. continue;
  364. }
  365. if (in_array($item["verb"], [Activity::O_UNFAVOURITE, Activity::UNFAVORITE])) {
  366. // Ignore "Unfavorite" message
  367. Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
  368. continue;
  369. }
  370. // Deletions come with the same uri, so we check for duplicates after processing deletions
  371. if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
  372. Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
  373. continue;
  374. } else {
  375. Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
  376. }
  377. if ($item["verb"] == Activity::JOIN) {
  378. // ignore "Join" messages
  379. Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
  380. continue;
  381. }
  382. if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
  383. // ignore mastodon "block" messages
  384. Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
  385. continue;
  386. }
  387. if ($item["verb"] == Activity::FOLLOW) {
  388. Contact::addRelationship($importer, $contact, $item);
  389. continue;
  390. }
  391. if ($item["verb"] == Activity::O_UNFOLLOW) {
  392. $dummy = null;
  393. Contact::removeFollower($importer, $contact, $item, $dummy);
  394. continue;
  395. }
  396. if ($item["verb"] == Activity::FAVORITE) {
  397. $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
  398. Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
  399. $item["verb"] = Activity::LIKE;
  400. $item["parent-uri"] = $orig_uri;
  401. $item["gravity"] = GRAVITY_ACTIVITY;
  402. $item["object-type"] = Activity\ObjectType::NOTE;
  403. }
  404. // http://activitystrea.ms/schema/1.0/rsvp-yes
  405. if (!in_array($item["verb"], [Activity::POST, Activity::LIKE, Activity::SHARE])) {
  406. Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
  407. }
  408. self::processPost($xpath, $entry, $item, $importer);
  409. if ($initialize && (count(self::$itemlist) > 0)) {
  410. if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
  411. // We will import it everytime, when it is started by our contacts
  412. $valid = Contact::isSharingByURL(self::$itemlist[0]['author-link'], self::$itemlist[0]['uid']);
  413. if (!$valid) {
  414. // If not, then it depends on this setting
  415. $valid = ((self::$itemlist[0]['uid'] == 0) || !DI::pConfig()->get(self::$itemlist[0]['uid'], 'system', 'accept_only_sharer', false));
  416. if ($valid) {
  417. Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
  418. }
  419. } else {
  420. Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
  421. }
  422. if ($valid) {
  423. // Never post a thread when the only interaction by our contact was a like
  424. $valid = false;
  425. $verbs = [Activity::POST, Activity::SHARE];
  426. foreach (self::$itemlist as $item) {
  427. if (in_array($item['verb'], $verbs) && Contact::isSharingByURL($item['author-link'], $item['uid'])) {
  428. $valid = true;
  429. }
  430. }
  431. if ($valid) {
  432. Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
  433. }
  434. }
  435. } else {
  436. // But we will only import complete threads
  437. $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
  438. if ($valid) {
  439. Logger::log("Item with uri ".self::$itemlist[0]["uri"]." belongs to parent ".self::$itemlist[0]['parent-uri']." of user ".$importer["uid"].". It will be imported.", Logger::DEBUG);
  440. }
  441. }
  442. if ($valid) {
  443. $default_contact = 0;
  444. for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
  445. if (empty(self::$itemlist[$key]['contact-id'])) {
  446. self::$itemlist[$key]['contact-id'] = $default_contact;
  447. } else {
  448. $default_contact = $item['contact-id'];
  449. }
  450. }
  451. foreach (self::$itemlist as $item) {
  452. $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
  453. if ($found) {
  454. Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
  455. } elseif ($item['contact-id'] < 0) {
  456. Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
  457. } else {
  458. // We are having duplicated entries. Hopefully this solves it.
  459. if (DI::lock()->acquire('ostatus_process_item_insert')) {
  460. $ret = Item::insert($item);
  461. DI::lock()->release('ostatus_process_item_insert');
  462. Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
  463. } else {
  464. $ret = Item::insert($item);
  465. Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
  466. }
  467. }
  468. }
  469. }
  470. self::$itemlist = [];
  471. }
  472. Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
  473. }
  474. return true;
  475. }
  476. /**
  477. * Removes notice item from database
  478. *
  479. * @param array $item item
  480. * @return void
  481. * @throws \Exception
  482. */
  483. private static function deleteNotice(array $item)
  484. {
  485. $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
  486. if (!Item::exists($condition)) {
  487. Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
  488. return;
  489. }
  490. Item::delete($condition);
  491. Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
  492. }
  493. /**
  494. * @brief Processes the XML for a post
  495. *
  496. * @param DOMXPath $xpath The xpath object
  497. * @param object $entry The xml entry that is processed
  498. * @param array $item The item array
  499. * @param array $importer user record of the importing user
  500. * @return void
  501. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  502. * @throws \ImagickException
  503. */
  504. private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
  505. {
  506. $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
  507. $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
  508. if (($item["object-type"] == Activity\ObjectType::BOOKMARK) || ($item["object-type"] == Activity\ObjectType::EVENT)) {
  509. $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
  510. $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
  511. } elseif ($item["object-type"] == Activity\ObjectType::QUESTION) {
  512. $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
  513. }
  514. $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
  515. $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
  516. $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
  517. $conv = $xpath->query('ostatus:conversation', $entry);
  518. if (is_object($conv->item(0))) {
  519. foreach ($conv->item(0)->attributes as $attributes) {
  520. if ($attributes->name == "ref") {
  521. $item['conversation-uri'] = $attributes->textContent;
  522. }
  523. if ($attributes->name == "href") {
  524. $item['conversation-href'] = $attributes->textContent;
  525. }
  526. }
  527. }
  528. $related = "";
  529. $inreplyto = $xpath->query('thr:in-reply-to', $entry);
  530. if (is_object($inreplyto->item(0))) {
  531. foreach ($inreplyto->item(0)->attributes as $attributes) {
  532. if ($attributes->name == "ref") {
  533. $item["parent-uri"] = $attributes->textContent;
  534. }
  535. if ($attributes->name == "href") {
  536. $related = $attributes->textContent;
  537. }
  538. }
  539. }
  540. $georsspoint = $xpath->query('georss:point', $entry);
  541. if (!empty($georsspoint) && ($georsspoint->length > 0)) {
  542. $item["coord"] = $georsspoint->item(0)->nodeValue;
  543. }
  544. $categories = $xpath->query('atom:category', $entry);
  545. if ($categories) {
  546. foreach ($categories as $category) {
  547. foreach ($category->attributes as $attributes) {
  548. if ($attributes->name == 'term') {
  549. $term = $attributes->textContent;
  550. if (!empty($item['tag'])) {
  551. $item['tag'] .= ',';
  552. } else {
  553. $item['tag'] = '';
  554. }
  555. $item['tag'] .= '#[url=' . DI::baseUrl() . '/search?tag=' . $term . ']' . $term . '[/url]';
  556. }
  557. }
  558. }
  559. }
  560. $self = '';
  561. $add_body = '';
  562. $links = $xpath->query('atom:link', $entry);
  563. if ($links) {
  564. $link_data = self::processLinks($links, $item);
  565. $self = $link_data['self'];
  566. $add_body = $link_data['add_body'];
  567. }
  568. $repeat_of = "";
  569. $notice_info = $xpath->query('statusnet:notice_info', $entry);
  570. if ($notice_info && ($notice_info->length > 0)) {
  571. foreach ($notice_info->item(0)->attributes as $attributes) {
  572. if ($attributes->name == "source") {
  573. $item["app"] = strip_tags($attributes->textContent);
  574. }
  575. if ($attributes->name == "repeat_of") {
  576. $repeat_of = $attributes->textContent;
  577. }
  578. }
  579. }
  580. // Is it a repeated post?
  581. if (($repeat_of != "") || ($item["verb"] == Activity::SHARE)) {
  582. $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
  583. if (!empty($link_data['add_body'])) {
  584. $add_body .= $link_data['add_body'];
  585. }
  586. }
  587. $item["body"] .= $add_body;
  588. // Only add additional data when there is no picture in the post
  589. if (!strstr($item["body"], '[/img]')) {
  590. $item["body"] = add_page_info_to_body($item["body"]);
  591. }
  592. // Mastodon Content Warning
  593. if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
  594. $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
  595. if (!empty($clear_text)) {
  596. $item['content-warning'] = HTML::toBBCode($clear_text);
  597. }
  598. }
  599. if (($self != '') && empty($item['protocol'])) {
  600. self::fetchSelf($self, $item);
  601. }
  602. if (!empty($item["conversation-href"])) {
  603. self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
  604. }
  605. if (isset($item["parent-uri"])) {
  606. if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
  607. if ($related != '') {
  608. self::fetchRelated($related, $item["parent-uri"], $importer);
  609. }
  610. } else {
  611. Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
  612. }
  613. } else {
  614. $item["parent-uri"] = $item["uri"];
  615. $item["gravity"] = GRAVITY_PARENT;
  616. }
  617. if (($item['author-link'] != '') && !empty($item['protocol'])) {
  618. $item = Conversation::insert($item);
  619. }
  620. self::$itemlist[] = $item;
  621. }
  622. /**
  623. * @brief Fetch the conversation for posts
  624. *
  625. * @param string $conversation The link to the conversation
  626. * @param string $conversation_uri The conversation in "uri" format
  627. * @return void
  628. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  629. */
  630. private static function fetchConversation($conversation, $conversation_uri)
  631. {
  632. // Ensure that we only store a conversation once in a process
  633. if (isset(self::$conv_list[$conversation])) {
  634. return;
  635. }
  636. self::$conv_list[$conversation] = true;
  637. $curlResult = Network::curl($conversation, false, ['accept_content' => 'application/atom+xml, text/html']);
  638. if (!$curlResult->isSuccess()) {
  639. return;
  640. }
  641. $xml = '';
  642. if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
  643. $xml = $curlResult->getBody();
  644. }
  645. if ($xml == '') {
  646. $doc = new DOMDocument();
  647. if (!@$doc->loadHTML($curlResult->getBody())) {
  648. return;
  649. }
  650. $xpath = new DOMXPath($doc);
  651. $links = $xpath->query('//link');
  652. if ($links) {
  653. $file = '';
  654. foreach ($links as $link) {
  655. $attribute = self::readAttributes($link);
  656. if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
  657. $file = $attribute['href'];
  658. }
  659. }
  660. if ($file != '') {
  661. $conversation_atom = Network::curl($attribute['href']);
  662. if ($conversation_atom->isSuccess()) {
  663. $xml = $conversation_atom->getBody();
  664. }
  665. }
  666. }
  667. }
  668. if ($xml == '') {
  669. return;
  670. }
  671. self::storeConversation($xml, $conversation, $conversation_uri);
  672. }
  673. /**
  674. * @brief Store a feed in several conversation entries
  675. *
  676. * @param string $xml The feed
  677. * @param string $conversation conversation
  678. * @param string $conversation_uri conversation uri
  679. * @return void
  680. * @throws \Exception
  681. */
  682. private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
  683. {
  684. $doc = new DOMDocument();
  685. @$doc->loadXML($xml);
  686. $xpath = new DOMXPath($doc);
  687. $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
  688. $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
  689. $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
  690. $entries = $xpath->query('/atom:feed/atom:entry');
  691. // Now store the entries
  692. foreach ($entries as $entry) {
  693. $doc2 = new DOMDocument();
  694. $doc2->preserveWhiteSpace = false;
  695. $doc2->formatOutput = true;
  696. $conv_data = [];
  697. $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
  698. $conv_data['network'] = Protocol::OSTATUS;
  699. $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
  700. $inreplyto = $xpath->query('thr:in-reply-to', $entry);
  701. if (is_object($inreplyto->item(0))) {
  702. foreach ($inreplyto->item(0)->attributes as $attributes) {
  703. if ($attributes->name == "ref") {
  704. $conv_data['reply-to-uri'] = $attributes->textContent;
  705. }
  706. }
  707. }
  708. $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
  709. $conv = $xpath->query('ostatus:conversation', $entry);
  710. if (is_object($conv->item(0))) {
  711. foreach ($conv->item(0)->attributes as $attributes) {
  712. if ($attributes->name == "ref") {
  713. $conv_data['conversation-uri'] = $attributes->textContent;
  714. }
  715. if ($attributes->name == "href") {
  716. $conv_data['conversation-href'] = $attributes->textContent;
  717. }
  718. }
  719. }
  720. if ($conversation != '') {
  721. $conv_data['conversation-uri'] = $conversation;
  722. }
  723. if ($conversation_uri != '') {
  724. $conv_data['conversation-uri'] = $conversation_uri;
  725. }
  726. $entry = $doc2->importNode($entry, true);
  727. $doc2->appendChild($entry);
  728. $conv_data['source'] = $doc2->saveXML();
  729. $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
  730. if (DBA::exists('conversation', $condition)) {
  731. Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
  732. DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
  733. }
  734. Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
  735. Conversation::insert($conv_data);
  736. }
  737. }
  738. /**
  739. * @brief Fetch the own post so that it can be stored later
  740. *
  741. * We want to store the original data for later processing.
  742. * This function is meant for cases where we process a feed with multiple entries.
  743. * In that case we need to fetch the single posts here.
  744. *
  745. * @param string $self The link to the self item
  746. * @param array $item The item array
  747. * @return void
  748. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  749. */
  750. private static function fetchSelf($self, array &$item)
  751. {
  752. $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
  753. if (DBA::exists('conversation', $condition)) {
  754. Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
  755. return;
  756. }
  757. $curlResult = Network::curl($self);
  758. if (!$curlResult->isSuccess()) {
  759. return;
  760. }
  761. // We reformat the XML to make it better readable
  762. $doc = new DOMDocument();
  763. $doc->loadXML($curlResult->getBody());
  764. $doc->preserveWhiteSpace = false;
  765. $doc->formatOutput = true;
  766. $xml = $doc->saveXML();
  767. $item["protocol"] = Conversation::PARCEL_SALMON;
  768. $item["source"] = $xml;
  769. Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
  770. }
  771. /**
  772. * @brief Fetch related posts and processes them
  773. *
  774. * @param string $related The link to the related item
  775. * @param string $related_uri The related item in "uri" format
  776. * @param array $importer user record of the importing user
  777. * @return void
  778. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  779. * @throws \ImagickException
  780. */
  781. private static function fetchRelated($related, $related_uri, $importer)
  782. {
  783. $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
  784. $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
  785. if (DBA::isResult($conversation)) {
  786. $stored = true;
  787. $xml = $conversation['source'];
  788. if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
  789. Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
  790. return;
  791. }
  792. if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
  793. Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
  794. DBA::delete('conversation', ['item-uri' => $related_uri]);
  795. }
  796. }
  797. $stored = false;
  798. $curlResult = Network::curl($related, false, ['accept_content' => 'application/atom+xml, text/html']);
  799. if (!$curlResult->isSuccess()) {
  800. return;
  801. }
  802. $xml = '';
  803. if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
  804. Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
  805. $xml = $curlResult->getBody();
  806. }
  807. if ($xml == '') {
  808. $doc = new DOMDocument();
  809. if (!@$doc->loadHTML($curlResult->getBody())) {
  810. return;
  811. }
  812. $xpath = new DOMXPath($doc);
  813. $atom_file = '';
  814. $links = $xpath->query('//link');
  815. if ($links) {
  816. foreach ($links as $link) {
  817. $attribute = self::readAttributes($link);
  818. if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
  819. $atom_file = $attribute['href'];
  820. }
  821. }
  822. if ($atom_file != '') {
  823. $curlResult = Network::curl($atom_file);
  824. if ($curlResult->isSuccess()) {
  825. Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
  826. $xml = $curlResult->getBody();
  827. }
  828. }
  829. }
  830. }
  831. // Workaround for older GNU Social servers
  832. if (($xml == '') && strstr($related, '/notice/')) {
  833. $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
  834. if ($curlResult->isSuccess()) {
  835. Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
  836. $xml = $curlResult->getBody();
  837. }
  838. }
  839. // Even more worse workaround for GNU Social ;-)
  840. if ($xml == '') {
  841. $related_guess = OStatus::convertHref($related_uri);
  842. $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
  843. if ($curlResult->isSuccess()) {
  844. Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
  845. $xml = $curlResult->getBody();
  846. }
  847. }
  848. // Finally we take the data that we fetched from "ostatus:conversation"
  849. if ($xml == '') {
  850. $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
  851. $conversation = DBA::selectFirst('conversation', ['source'], $condition);
  852. if (DBA::isResult($conversation)) {
  853. $stored = true;
  854. Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
  855. $xml = $conversation['source'];
  856. }
  857. }
  858. if ($xml != '') {
  859. self::process($xml, $importer, $contact, $hub, $stored, false);
  860. } else {
  861. Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
  862. }
  863. return;
  864. }
  865. /**
  866. * @brief Processes the XML for a repeated post
  867. *
  868. * @param DOMXPath $xpath The xpath object
  869. * @param object $entry The xml entry that is processed
  870. * @param array $item The item array
  871. * @param array $importer user record of the importing user
  872. *
  873. * @return array with data from links
  874. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  875. * @throws \ImagickException
  876. */
  877. private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
  878. {
  879. $activityobject = $xpath->query('activity:object', $entry)->item(0);
  880. if (!is_object($activityobject)) {
  881. return [];
  882. }
  883. $link_data = [];
  884. $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
  885. $links = $xpath->query("atom:link", $activityobject);
  886. if ($links) {
  887. $link_data = self::processLinks($links, $item);
  888. }
  889. $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
  890. $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
  891. $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
  892. $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
  893. $item["author-name"] = $orig_author["author-name"];
  894. $item["author-link"] = $orig_author["author-link"];
  895. $item["author-id"] = $orig_author["author-id"];
  896. $item["body"] = HTML::toBBCode($orig_body);
  897. $item["created"] = $orig_created;
  898. $item["edited"] = $orig_edited;
  899. $item["uri"] = $orig_uri;
  900. $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
  901. $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
  902. // Mastodon Content Warning
  903. if (($item["verb"] == Activity::POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
  904. $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
  905. if (!empty($clear_text)) {
  906. $item['content-warning'] = HTML::toBBCode($clear_text);
  907. }
  908. }
  909. $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
  910. if (is_object($inreplyto->item(0))) {
  911. foreach ($inreplyto->item(0)->attributes as $attributes) {
  912. if ($attributes->name == "ref") {
  913. $item["parent-uri"] = $attributes->textContent;
  914. }
  915. }
  916. }
  917. return $link_data;
  918. }
  919. /**
  920. * @brief Processes links in the XML
  921. *
  922. * @param object $links The xml data that contain links
  923. * @param array $item The item array
  924. *
  925. * @return array with data from the links
  926. */
  927. private static function processLinks($links, array &$item)
  928. {
  929. $link_data = ['add_body' => '', 'self' => ''];
  930. foreach ($links as $link) {
  931. $attribute = self::readAttributes($link);
  932. if (!empty($attribute['rel']) && !empty($attribute['href'])) {
  933. switch ($attribute['rel']) {
  934. case "alternate":
  935. $item["plink"] = $attribute['href'];
  936. if (($item["object-type"] == Activity\ObjectType::QUESTION)
  937. || ($item["object-type"] == Activity\ObjectType::EVENT)
  938. ) {
  939. $item["body"] .= add_page_info($attribute['href']);
  940. }
  941. break;
  942. case "ostatus:conversation":
  943. $link_data['conversation'] = $attribute['href'];
  944. $item['conversation-href'] = $link_data['conversation'];
  945. if (!isset($item['conversation-uri'])) {
  946. $item['conversation-uri'] = $item['conversation-href'];
  947. }
  948. break;
  949. case "enclosure":
  950. $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
  951. if ($filetype == 'image') {
  952. $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
  953. } else {
  954. if (!empty($item["attach"])) {
  955. $item["attach"] .= ',';
  956. } else {
  957. $item["attach"] = '';
  958. }
  959. if (!isset($attribute['length'])) {
  960. $attribute['length'] = "0";
  961. }
  962. $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.($attribute['title'] ?? '') .'"[/attach]';
  963. }
  964. break;
  965. case "related":
  966. if ($item["object-type"] != Activity\ObjectType::BOOKMARK) {
  967. if (!isset($item["parent-uri"])) {
  968. $item["parent-uri"] = $attribute['href'];
  969. }
  970. $link_data['related'] = $attribute['href'];
  971. } else {
  972. $item["body"] .= add_page_info($attribute['href']);
  973. }
  974. break;
  975. case "self":
  976. if (empty($item["plink"])) {
  977. $item["plink"] = $attribute['href'];
  978. }
  979. $link_data['self'] = $attribute['href'];
  980. break;
  981. }
  982. }
  983. }
  984. return $link_data;
  985. }
  986. /**
  987. * @brief Create an url out of an uri
  988. *
  989. * @param string $href URI in the format "parameter1:parameter1:..."
  990. *
  991. * @return string URL in the format http(s)://....
  992. */
  993. public static function convertHref($href)
  994. {
  995. $elements = explode(":", $href);
  996. if ((count($elements) <= 2) || ($elements[0] != "tag")) {
  997. return $href;
  998. }
  999. $server = explode(",", $elements[1]);
  1000. $conversation = explode("=", $elements[2]);
  1001. if ((count($elements) == 4) && ($elements[2] == "post")) {
  1002. return "http://".$server[0]."/notice/".$elements[3];
  1003. }
  1004. if ((count($conversation) != 2) || ($conversation[1] =="")) {
  1005. return $href;
  1006. }
  1007. if ($elements[3] == "objectType=thread") {
  1008. return "http://".$server[0]."/conversation/".$conversation[1];
  1009. } else {
  1010. return "http://".$server[0]."/notice/".$conversation[1];
  1011. }
  1012. }
  1013. /**
  1014. * @brief Checks if the current post is a reshare
  1015. *
  1016. * @param array $item The item array of thw post
  1017. *
  1018. * @return string The guid if the post is a reshare
  1019. */
  1020. private static function getResharedGuid(array $item)
  1021. {
  1022. $reshared = Item::getShareArray($item);
  1023. if (empty($reshared['guid']) || !empty($reshared['comment'])) {
  1024. return '';
  1025. }
  1026. return $reshared['guid'];
  1027. }
  1028. /**
  1029. * @brief Cleans the body of a post if it contains picture links
  1030. *
  1031. * @param string $body The body
  1032. *
  1033. * @return string The cleaned body
  1034. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1035. */
  1036. private static function formatPicturePost($body)
  1037. {
  1038. $siteinfo = BBCode::getAttachedData($body);
  1039. if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
  1040. if (isset($siteinfo["preview"])) {
  1041. $preview = $siteinfo["preview"];
  1042. } else {
  1043. $preview = $siteinfo["image"];
  1044. }
  1045. // Is it a remote picture? Then make a smaller preview here
  1046. $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
  1047. // Is it a local picture? Then make it smaller here
  1048. $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
  1049. $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
  1050. if (isset($siteinfo["url"])) {
  1051. $url = $siteinfo["url"];
  1052. } else {
  1053. $url = $siteinfo["image"];
  1054. }
  1055. $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
  1056. }
  1057. return $body;
  1058. }
  1059. /**
  1060. * @brief Adds the header elements to the XML document
  1061. *
  1062. * @param DOMDocument $doc XML document
  1063. * @param array $owner Contact data of the poster
  1064. * @param string $filter The related feed filter (activity, posts or comments)
  1065. * @param bool $feed_mode Behave like a regular feed for users if true
  1066. *
  1067. * @return object header root element
  1068. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1069. */
  1070. private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false)
  1071. {
  1072. $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
  1073. $doc->appendChild($root);
  1074. $root->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
  1075. $root->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
  1076. $root->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
  1077. $root->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
  1078. $root->setAttribute("xmlns:poco", ActivityNamespace::POCO);
  1079. $root->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
  1080. $root->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
  1081. $root->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
  1082. $title = '';
  1083. $selfUri = '/feed/' . $owner["nick"] . '/';
  1084. switch ($filter) {
  1085. case 'activity':
  1086. $title = L10n::t('%s\'s timeline', $owner['name']);
  1087. $selfUri .= $filter;
  1088. break;
  1089. case 'posts':
  1090. $title = L10n::t('%s\'s posts', $owner['name']);
  1091. break;
  1092. case 'comments':
  1093. $title = L10n::t('%s\'s comments', $owner['name']);
  1094. $selfUri .= $filter;
  1095. break;
  1096. }
  1097. if (!$feed_mode) {
  1098. $selfUri = "/dfrn_poll/" . $owner["nick"];
  1099. }
  1100. $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
  1101. XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
  1102. XML::addElement($doc, $root, "id", DI::baseUrl() . "/profile/" . $owner["nick"]);
  1103. XML::addElement($doc, $root, "title", $title);
  1104. XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], Config::get('config', 'sitename')));
  1105. XML::addElement($doc, $root, "logo", $owner["photo"]);
  1106. XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
  1107. $author = self::addAuthor($doc, $owner);
  1108. $root->appendChild($author);
  1109. $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
  1110. XML::addElement($doc, $root, "link", "", $attributes);
  1111. /// @TODO We have to find out what this is
  1112. /// $attributes = array("href" => DI::baseUrl()."/sup",
  1113. /// "rel" => "http://api.friendfeed.com/2008/03#sup",
  1114. /// "type" => "application/json");
  1115. /// XML::addElement($doc, $root, "link", "", $attributes);
  1116. self::hublinks($doc, $root, $owner["nick"]);
  1117. $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
  1118. XML::addElement($doc, $root, "link", "", $attributes);
  1119. $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
  1120. XML::addElement($doc, $root, "link", "", $attributes);
  1121. $attributes = ["href" => DI::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
  1122. XML::addElement($doc, $root, "link", "", $attributes);
  1123. $attributes = ["href" => DI::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
  1124. XML::addElement($doc, $root, "link", "", $attributes);
  1125. if ($owner['account-type'] == Contact::TYPE_COMMUNITY) {
  1126. $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
  1127. 'archive' => false, 'hidden' => false, 'blocked' => false];
  1128. $members = DBA::count('contact', $condition);
  1129. XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
  1130. }
  1131. return $root;
  1132. }
  1133. /**
  1134. * @brief Add the link to the push hubs to the XML document
  1135. *
  1136. * @param DOMDocument $doc XML document
  1137. * @param object $root XML root element where the hub links are added
  1138. * @param object $nick nick
  1139. * @return void
  1140. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1141. */
  1142. public static function hublinks(DOMDocument $doc, $root, $nick)
  1143. {
  1144. $h = DI::baseUrl() . '/pubsubhubbub/'.$nick;
  1145. XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
  1146. }
  1147. /**
  1148. * @brief Adds attachment data to the XML document
  1149. *
  1150. * @param DOMDocument $doc XML document
  1151. * @param object $root XML root element where the hub links are added
  1152. * @param array $item Data of the item that is to be posted
  1153. * @return void
  1154. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1155. */
  1156. private static function getAttachment(DOMDocument $doc, $root, $item)
  1157. {
  1158. $siteinfo = BBCode::getAttachedData($item["body"]);
  1159. switch ($siteinfo["type"]) {
  1160. case 'photo':
  1161. if (!empty($siteinfo["image"])) {
  1162. $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
  1163. if ($imgdata) {
  1164. $attributes = ["rel" => "enclosure",
  1165. "href" => $siteinfo["image"],
  1166. "type" => $imgdata["mime"],
  1167. "length" => intval($imgdata["size"])];
  1168. XML::addElement($doc, $root, "link", "", $attributes);
  1169. }
  1170. }
  1171. break;
  1172. case 'video':
  1173. $attributes = ["rel" => "enclosure",
  1174. "href" => $siteinfo["url"],
  1175. "type" => "text/html; charset=UTF-8",
  1176. "length" => "",
  1177. "title" => ($siteinfo["title"] ?? '') ?: $siteinfo["url"],
  1178. ];
  1179. XML::addElement($doc, $root, "link", "", $attributes);
  1180. break;
  1181. default:
  1182. break;
  1183. }
  1184. if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
  1185. $imgdata = Images::getInfoFromURLCached($siteinfo["image"]);
  1186. if ($imgdata) {
  1187. $attributes = ["rel" => "enclosure",
  1188. "href" => $siteinfo["image"],
  1189. "type" => $imgdata["mime"],
  1190. "length" => intval($imgdata["size"])];
  1191. XML::addElement($doc, $root, "link", "", $attributes);
  1192. }
  1193. }
  1194. $arr = explode('[/attach],', $item['attach']);
  1195. if (count($arr)) {
  1196. foreach ($arr as $r) {
  1197. $matches = false;
  1198. $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
  1199. if ($cnt) {
  1200. $attributes = ["rel" => "enclosure",
  1201. "href" => $matches[1],
  1202. "type" => $matches[3]];
  1203. if (intval($matches[2])) {
  1204. $attributes["length"] = intval($matches[2]);
  1205. }
  1206. if (trim($matches[4]) != "") {
  1207. $attributes["title"] = trim($matches[4]);
  1208. }
  1209. XML::addElement($doc, $root, "link", "", $attributes);
  1210. }
  1211. }
  1212. }
  1213. }
  1214. /**
  1215. * @brief Adds the author element to the XML document
  1216. *
  1217. * @param DOMDocument $doc XML document
  1218. * @param array $owner Contact data of the poster
  1219. * @param bool $show_profile Whether to show profile
  1220. *
  1221. * @return \DOMElement author element
  1222. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1223. */
  1224. private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
  1225. {
  1226. $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
  1227. $author = $doc->createElement("author");
  1228. XML::addElement($doc, $author, "id", $owner["url"]);
  1229. if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
  1230. XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::GROUP);
  1231. } else {
  1232. XML::addElement($doc, $author, "activity:object-type", Activity\ObjectType::PERSON);
  1233. }
  1234. XML::addElement($doc, $author, "uri", $owner["url"]);
  1235. XML::addElement($doc, $author, "name", $owner["nick"]);
  1236. XML::addElement($doc, $author, "email", $owner["addr"]);
  1237. if ($show_profile) {
  1238. XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
  1239. }
  1240. $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
  1241. XML::addElement($doc, $author, "link", "", $attributes);
  1242. $attributes = [
  1243. "rel" => "avatar",
  1244. "type" => "image/jpeg", // To-Do?
  1245. "media:width" => 300,
  1246. "media:height" => 300,
  1247. "href" => $owner["photo"]];
  1248. XML::addElement($doc, $author, "link", "", $attributes);
  1249. if (isset($owner["thumb"])) {
  1250. $attributes = [
  1251. "rel" => "avatar",
  1252. "type" => "image/jpeg", // To-Do?
  1253. "media:width" => 80,
  1254. "media:height" => 80,
  1255. "href" => $owner["thumb"]];
  1256. XML::addElement($doc, $author, "link", "", $attributes);
  1257. }
  1258. XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
  1259. XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
  1260. if ($show_profile) {
  1261. XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
  1262. if (trim($owner["location"]) != "") {
  1263. $element = $doc->createElement("poco:address");
  1264. XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
  1265. $author->appendChild($element);
  1266. }
  1267. }
  1268. if (DBA::isResult($profile) && !$show_profile) {
  1269. if (trim($profile["homepage"]) != "") {
  1270. $urls = $doc->createElement("poco:urls");
  1271. XML::addElement($doc, $urls, "poco:type", "homepage");
  1272. XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
  1273. XML::addElement($doc, $urls, "poco:primary", "true");
  1274. $author->appendChild($urls);
  1275. }
  1276. XML::addElement($doc, $author, "followers", "", ["url" => DI::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
  1277. XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
  1278. if ($profile["publish"]) {
  1279. XML::addElement($doc, $author, "mastodon:scope", "public");
  1280. }
  1281. }
  1282. return $author;
  1283. }
  1284. /**
  1285. * @TODO Picture attachments should look like this:
  1286. * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
  1287. * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
  1288. */
  1289. /**
  1290. * @brief Returns the given activity if present - otherwise returns the "post" activity
  1291. *
  1292. * @param array $item Data of the item that is to be posted
  1293. *
  1294. * @return string activity
  1295. */
  1296. private static function constructVerb(array $item)
  1297. {
  1298. if (!empty($item['verb'])) {
  1299. return $item['verb'];
  1300. }
  1301. return Activity::POST;
  1302. }
  1303. /**
  1304. * @brief Returns the given object type if present - otherwise returns the "note" object type
  1305. *
  1306. * @param array $item Data of the item that is to be posted
  1307. *
  1308. * @return string Object type
  1309. */
  1310. private static function constructObjecttype(array $item)
  1311. {
  1312. if (!empty($item['object-type']) && in_array($item['object-type'], [Activity\ObjectType::NOTE, Activity\ObjectType::COMMENT])) {
  1313. return $item['object-type'];
  1314. }
  1315. return Activity\ObjectType::NOTE;
  1316. }
  1317. /**
  1318. * @brief Adds an entry element to the XML document
  1319. *
  1320. * @param DOMDocument $doc XML document
  1321. * @param array $item Data of the item that is to be posted
  1322. * @param array $owner Contact data of the poster
  1323. * @param bool $toplevel optional default false
  1324. * @param bool $feed_mode Behave like a regular feed for users if true
  1325. *
  1326. * @return \DOMElement Entry element
  1327. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1328. * @throws \ImagickException
  1329. */
  1330. private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false, $feed_mode = false)
  1331. {
  1332. $xml = null;
  1333. $repeated_guid = self::getResharedGuid($item);
  1334. if ($repeated_guid != "") {
  1335. $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
  1336. }
  1337. if ($xml) {
  1338. return $xml;
  1339. }
  1340. if ($item["verb"] == Activity::LIKE) {
  1341. return self::likeEntry($doc, $item, $owner, $toplevel);
  1342. } elseif (in_array($item["verb"], [Activity::FOLLOW, Activity::O_UNFOLLOW])) {
  1343. return self::followEntry($doc, $item, $owner, $toplevel);
  1344. } else {
  1345. return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode);
  1346. }
  1347. }
  1348. /**
  1349. * @brief Adds a source entry to the XML document
  1350. *
  1351. * @param DOMDocument $doc XML document
  1352. * @param array $contact Array of the contact that is added
  1353. *
  1354. * @return \DOMElement Source element
  1355. * @throws \Exception
  1356. */
  1357. private static function sourceEntry(DOMDocument $doc, array $contact)
  1358. {
  1359. $source = $doc->createElement("source");
  1360. XML::addElement($doc, $source, "id", $contact["poll"]);
  1361. XML::addElement($doc, $source, "title", $contact["name"]);
  1362. XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
  1363. XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
  1364. XML::addElement($doc, $source, "icon", $contact["photo"]);
  1365. XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
  1366. return $source;
  1367. }
  1368. /**
  1369. * @brief Fetches contact data from the contact or the gcontact table
  1370. *
  1371. * @param string $url URL of the contact
  1372. * @param array $owner Contact data of the poster
  1373. *
  1374. * @return array Contact array
  1375. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1376. * @throws \ImagickException
  1377. */
  1378. private static function contactEntry($url, array $owner)
  1379. {
  1380. $r = q(
  1381. "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
  1382. DBA::escape(Strings::normaliseLink($url)),
  1383. intval($owner["uid"])
  1384. );
  1385. if (DBA::isResult($r)) {
  1386. $contact = $r[0];
  1387. $contact["uid"] = -1;
  1388. }
  1389. if (!DBA::isResult($r)) {
  1390. $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => Strings::normaliseLink($url)]);
  1391. if (DBA::isResult($r)) {
  1392. $contact = $gcontact;
  1393. $contact["uid"] = -1;
  1394. $contact["success_update"] = $contact["updated"];
  1395. }
  1396. }
  1397. if (!DBA::isResult($r)) {
  1398. $contact = $owner;
  1399. }
  1400. if (!isset($contact["poll"])) {
  1401. $data = Probe::uri($url);
  1402. $contact["poll"] = $data["poll"];
  1403. if (!$contact["alias"]) {
  1404. $contact["alias"] = $data["alias"];
  1405. }
  1406. }
  1407. if (!isset($contact["alias"])) {
  1408. $contact["alias"] = $contact["url"];
  1409. }
  1410. $contact['account-type'] = $owner['account-type'];
  1411. return $contact;
  1412. }
  1413. /**
  1414. * @brief Adds an entry element with reshared content
  1415. *
  1416. * @param DOMDocument $doc XML document
  1417. * @param array $item Data of the item that is to be posted
  1418. * @param array $owner Contact data of the poster
  1419. * @param string $repeated_guid guid
  1420. * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
  1421. *
  1422. * @return bool Entry element
  1423. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1424. * @throws \ImagickException
  1425. */
  1426. private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
  1427. {
  1428. if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
  1429. Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
  1430. }
  1431. $entry = self::entryHeader($doc, $owner, $item, $toplevel);
  1432. $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
  1433. 'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
  1434. $repeated_item = Item::selectFirst([], $condition);
  1435. if (!DBA::isResult($repeated_item)) {
  1436. return false;
  1437. }
  1438. $contact = self::contactEntry($repeated_item['author-link'], $owner);
  1439. $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
  1440. self::entryContent($doc, $entry, $item, $owner, $title, Activity::SHARE, false);
  1441. $as_object = $doc->createElement("activity:object");
  1442. XML::addElement($doc, $as_object, "activity:object-type", ActivityNamespace::ACTIVITY_SCHEMA . "activity");
  1443. self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
  1444. $author = self::addAuthor($doc, $contact, false);
  1445. $as_object->appendChild($author);
  1446. $as_object2 = $doc->createElement("activity:object");
  1447. XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
  1448. $title = sprintf("New comment by %s", $contact["nick"]);
  1449. self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
  1450. $as_object->appendChild($as_object2);
  1451. self::entryFooter($doc, $as_object, $item, $owner, false);
  1452. $source = self::sourceEntry($doc, $contact);
  1453. $as_object->appendChild($source);
  1454. $entry->appendChild($as_object);
  1455. self::entryFooter($doc, $entry, $item, $owner);
  1456. return $entry;
  1457. }
  1458. /**
  1459. * @brief Adds an entry element with a "like"
  1460. *
  1461. * @param DOMDocument $doc XML document
  1462. * @param array $item Data of the item that is to be posted
  1463. * @param array $owner Contact data of the poster
  1464. * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
  1465. *
  1466. * @return \DOMElement Entry element with "like"
  1467. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1468. * @throws \ImagickException
  1469. */
  1470. private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
  1471. {
  1472. if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
  1473. Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
  1474. }
  1475. $entry = self::entryHeader($doc, $owner, $item, $toplevel);
  1476. $verb = ActivityNamespace::ACTIVITY_SCHEMA . "favorite";
  1477. self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
  1478. $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
  1479. if (DBA::isResult($parent)) {
  1480. $as_object = $doc->createElement("activity:object");
  1481. XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
  1482. self::entryContent($doc, $as_object, $parent, $owner, "New entry");
  1483. $entry->appendChild($as_object);
  1484. }
  1485. self::entryFooter($doc, $entry, $item, $owner);
  1486. return $entry;
  1487. }
  1488. /**
  1489. * @brief Adds the person object element to the XML document
  1490. *
  1491. * @param DOMDocument $doc XML document
  1492. * @param array $owner Contact data of the poster
  1493. * @param array $contact Contact data of the target
  1494. *
  1495. * @return object author element
  1496. */
  1497. private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
  1498. {
  1499. $object = $doc->createElement("activity:object");
  1500. XML::addElement($doc, $object, "activity:object-type", Activity\ObjectType::PERSON);
  1501. if ($contact['network'] == Protocol::PHANTOM) {
  1502. XML::addElement($doc, $object, "id", $contact['url']);
  1503. return $object;
  1504. }
  1505. XML::addElement($doc, $object, "id", $contact["alias"]);
  1506. XML::addElement($doc, $object, "title", $contact["nick"]);
  1507. $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
  1508. XML::addElement($doc, $object, "link", "", $attributes);
  1509. $attributes = [
  1510. "rel" => "avatar",
  1511. "type" => "image/jpeg", // To-Do?
  1512. "media:width" => 300,
  1513. "media:height" => 300,
  1514. "href" => $contact["photo"]];
  1515. XML::addElement($doc, $object, "link", "", $attributes);
  1516. XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
  1517. XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
  1518. if (trim($contact["location"]) != "") {
  1519. $element = $doc->createElement("poco:address");
  1520. XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
  1521. $object->appendChild($element);
  1522. }
  1523. return $object;
  1524. }
  1525. /**
  1526. * @brief Adds a follow/unfollow entry element
  1527. *
  1528. * @param DOMDocument $doc XML document
  1529. * @param array $item Data of the follow/unfollow message
  1530. * @param array $owner Contact data of the poster
  1531. * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
  1532. *
  1533. * @return \DOMElement Entry element
  1534. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1535. * @throws \ImagickException
  1536. */
  1537. private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
  1538. {
  1539. $item["id"] = $item["parent"] = 0;
  1540. $item["created"] = $item["edited"] = date("c");
  1541. $item["private"] = true;
  1542. $contact = Probe::uri($item['follow']);
  1543. if ($contact['alias'] == '') {
  1544. $contact['alias'] = $contact["url"];
  1545. } else {
  1546. $item['follow'] = $contact['alias'];
  1547. }
  1548. $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
  1549. $user_contact = DBA::selectFirst('contact', ['id'], $condition);
  1550. if (DBA::isResult($user_contact)) {
  1551. $connect_id = $user_contact['id'];
  1552. } else {
  1553. $connect_id = 0;
  1554. }
  1555. if ($item['verb'] == Activity::FOLLOW) {
  1556. $message = L10n::t('%s is now following %s.');
  1557. $title = L10n::t('following');
  1558. $action = "subscription";
  1559. } else {
  1560. $message = L10n::t('%s stopped following %s.');
  1561. $title = L10n::t('stopped following');
  1562. $action = "unfollow";
  1563. }
  1564. $item["uri"] = $item['parent-uri'] = $item['thr-parent']
  1565. = 'tag:' . DI::baseUrl()->getHostname().
  1566. ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
  1567. ':person:'.$connect_id.':'.$item['created'];
  1568. $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
  1569. $entry = self::entryHeader($doc, $owner, $item, $toplevel);
  1570. self::entryContent($doc, $entry, $item, $owner, $title);
  1571. $object = self::addPersonObject($doc, $owner, $contact);
  1572. $entry->appendChild($object);
  1573. self::entryFooter($doc, $entry, $item, $owner);
  1574. return $entry;
  1575. }
  1576. /**
  1577. * @brief Adds a regular entry element
  1578. *
  1579. * @param DOMDocument $doc XML document
  1580. * @param array $item Data of the item that is to be posted
  1581. * @param array $owner Contact data of the poster
  1582. * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
  1583. * @param bool $feed_mode Behave like a regular feed for users if true
  1584. *
  1585. * @return \DOMElement Entry element
  1586. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1587. * @throws \ImagickException
  1588. */
  1589. private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel, $feed_mode)
  1590. {
  1591. if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
  1592. Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
  1593. }
  1594. if (!$toplevel) {
  1595. if (!empty($item['title'])) {
  1596. $title = BBCode::convert($item['title'], false, 7);
  1597. } else {
  1598. $title = sprintf("New note by %s", $owner["nick"]);
  1599. }
  1600. } else {
  1601. $title = sprintf("New comment by %s", $owner["nick"]);
  1602. }
  1603. $entry = self::entryHeader($doc, $owner, $item, $toplevel);
  1604. XML::addElement($doc, $entry, "activity:object-type", Activity\ObjectType::NOTE);
  1605. self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode);
  1606. self::entryFooter($doc, $entry, $item, $owner, !$feed_mode, $feed_mode);
  1607. return $entry;
  1608. }
  1609. /**
  1610. * @brief Adds a header element to the XML document
  1611. *
  1612. * @param DOMDocument $doc XML document
  1613. * @param array $owner Contact data of the poster
  1614. * @param array $item
  1615. * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
  1616. *
  1617. * @return \DOMElement The entry element where the elements are added
  1618. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1619. * @throws \ImagickException
  1620. */
  1621. private static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
  1622. {
  1623. if (!$toplevel) {
  1624. $entry = $doc->createElement("entry");
  1625. if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
  1626. $contact = self::contactEntry($item['author-link'], $owner);
  1627. $author = self::addAuthor($doc, $contact, false);
  1628. $entry->appendChild($author);
  1629. }
  1630. } else {
  1631. $entry = $doc->createElementNS(ActivityNamespace::ATOM1, "entry");
  1632. $entry->setAttribute("xmlns:thr", ActivityNamespace::THREAD);
  1633. $entry->setAttribute("xmlns:georss", ActivityNamespace::GEORSS);
  1634. $entry->setAttribute("xmlns:activity", ActivityNamespace::ACTIVITY);
  1635. $entry->setAttribute("xmlns:media", ActivityNamespace::MEDIA);
  1636. $entry->setAttribute("xmlns:poco", ActivityNamespace::POCO);
  1637. $entry->setAttribute("xmlns:ostatus", ActivityNamespace::OSTATUS);
  1638. $entry->setAttribute("xmlns:statusnet", ActivityNamespace::STATUSNET);
  1639. $entry->setAttribute("xmlns:mastodon", ActivityNamespace::MASTODON);
  1640. $author = self::addAuthor($doc, $owner);
  1641. $entry->appendChild($author);
  1642. }
  1643. return $entry;
  1644. }
  1645. /**
  1646. * @brief Adds elements to the XML document
  1647. *
  1648. * @param DOMDocument $doc XML document
  1649. * @param \DOMElement $entry Entry element where the content is added
  1650. * @param array $item Data of the item that is to be posted
  1651. * @param array $owner Contact data of the poster
  1652. * @param string $title Title for the post
  1653. * @param string $verb The activity verb
  1654. * @param bool $complete Add the "status_net" element?
  1655. * @param bool $feed_mode Behave like a regular feed for users if true
  1656. * @return void
  1657. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1658. */
  1659. private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true, $feed_mode = false)
  1660. {
  1661. if ($verb == "") {
  1662. $verb = self::constructVerb($item);
  1663. }
  1664. XML::addElement($doc, $entry, "id", $item["uri"]);
  1665. XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
  1666. $body = self::formatPicturePost($item['body']);
  1667. if (!empty($item['title']) && !$feed_mode) {
  1668. $body = "[b]".$item['title']."[/b]\n\n".$body;
  1669. }
  1670. $body = BBCode::convert($body, false, 7);
  1671. XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
  1672. XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
  1673. "href" => DI::baseUrl()."/display/".$item["guid"]]
  1674. );
  1675. if (!$feed_mode && $complete && ($item["id"] > 0)) {
  1676. XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
  1677. }
  1678. if (!$feed_mode) {
  1679. XML::addElement($doc, $entry, "activity:verb", $verb);
  1680. }
  1681. XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
  1682. XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
  1683. }
  1684. /**
  1685. * @brief Adds the elements at the foot of an entry to the XML document
  1686. *
  1687. * @param DOMDocument $doc XML document
  1688. * @param object $entry The entry element where the elements are added
  1689. * @param array $item Data of the item that is to be posted
  1690. * @param array $owner Contact data of the poster
  1691. * @param bool $complete default true
  1692. * @param bool $feed_mode Behave like a regular feed for users if true
  1693. * @return void
  1694. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1695. */
  1696. private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true, $feed_mode = false)
  1697. {
  1698. $mentioned = [];
  1699. if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
  1700. $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
  1701. $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
  1702. $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
  1703. if (DBA::isResult($thrparent)) {
  1704. $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
  1705. $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
  1706. $parent_plink = $thrparent["plink"];
  1707. } else {
  1708. $mentioned[$parent["author-link"]] = $parent["author-link"];
  1709. $mentioned[$parent["owner-link"]] = $parent["owner-link"];
  1710. $parent_plink = DI::baseUrl()."/display/".$parent["guid"];
  1711. }
  1712. $attributes = [
  1713. "ref" => $parent_item,
  1714. "href" => $parent_plink];
  1715. XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
  1716. $attributes = [
  1717. "rel" => "related",
  1718. "href" => $parent_plink];
  1719. XML::addElement($doc, $entry, "link", "", $attributes);
  1720. }
  1721. if (!$feed_mode && (intval($item["parent"]) > 0)) {
  1722. $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
  1723. if (isset($parent_item)) {
  1724. $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
  1725. if (DBA::isResult($conversation)) {
  1726. if ($conversation['conversation-uri'] != '') {
  1727. $conversation_uri = $conversation['conversation-uri'];
  1728. }
  1729. if ($conversation['conversation-href'] != '') {
  1730. $conversation_href = $conversation['conversation-href'];
  1731. }
  1732. }
  1733. }
  1734. XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
  1735. $attributes = [
  1736. "href" => $conversation_href,
  1737. "local_id" => $item["parent"],
  1738. "ref" => $conversation_uri];
  1739. XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
  1740. }
  1741. $tags = item::getFeedTags($item);
  1742. if (count($tags)) {
  1743. foreach ($tags as $t) {
  1744. if ($t[0] == "@") {
  1745. $mentioned[$t[1]] = $t[1];
  1746. }
  1747. }
  1748. }
  1749. // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
  1750. $newmentions = [];
  1751. foreach ($mentioned as $mention) {
  1752. $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
  1753. $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
  1754. }
  1755. $mentioned = $newmentions;
  1756. foreach ($mentioned as $mention) {
  1757. $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)];
  1758. $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
  1759. if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == Contact::TYPE_COMMUNITY) ||
  1760. ($contact['self'] && ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY))) {
  1761. XML::addElement($doc, $entry, "link", "",
  1762. [
  1763. "rel" => "mentioned",
  1764. "ostatus:object-type" => Activity\ObjectType::GROUP,
  1765. "href" => $mention]
  1766. );
  1767. } else {
  1768. XML::addElement($doc, $entry, "link", "",
  1769. [
  1770. "rel" => "mentioned",
  1771. "ostatus:object-type" => Activity\ObjectType::PERSON,
  1772. "href" => $mention]
  1773. );
  1774. }
  1775. }
  1776. if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
  1777. XML::addElement($doc, $entry, "link", "", [
  1778. "rel" => "mentioned",
  1779. "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
  1780. "href" => $owner['url']
  1781. ]);
  1782. }
  1783. if (!$item["private"] && !$feed_mode) {
  1784. XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
  1785. "href" => "http://activityschema.org/collection/public"]);
  1786. XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
  1787. "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
  1788. "href" => "http://activityschema.org/collection/public"]);
  1789. XML::addElement($doc, $entry, "mastodon:scope", "public");
  1790. }
  1791. if (count($tags)) {
  1792. foreach ($tags as $t) {
  1793. if ($t[0] != "@") {
  1794. XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
  1795. }
  1796. }
  1797. }
  1798. self::getAttachment($doc, $entry, $item);
  1799. if ($complete && ($item["id"] > 0)) {
  1800. $app = $item["app"];
  1801. if ($app == "") {
  1802. $app = "web";
  1803. }
  1804. $attributes = ["local_id" => $item["id"], "source" => $app];
  1805. if (isset($parent["id"])) {
  1806. $attributes["repeat_of"] = $parent["id"];
  1807. }
  1808. if ($item["coord"] != "") {
  1809. XML::addElement($doc, $entry, "georss:point", $item["coord"]);
  1810. }
  1811. XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
  1812. }
  1813. }
  1814. /**
  1815. * Creates the XML feed for a given nickname
  1816. *
  1817. * Supported filters:
  1818. * - activity (default): all the public posts
  1819. * - posts: all the public top-level posts
  1820. * - comments: all the public replies
  1821. *
  1822. * Updates the provided last_update parameter if the result comes from the
  1823. * cache or it is empty
  1824. *
  1825. * @brief Creates the XML feed for a given nickname
  1826. *
  1827. * @param string $owner_nick Nickname of the feed owner
  1828. * @param string $last_update Date of the last update
  1829. * @param integer $max_items Number of maximum items to fetch
  1830. * @param string $filter Feed items filter (activity, posts or comments)
  1831. * @param boolean $nocache Wether to bypass caching
  1832. * @param boolean $feed_mode Behave like a regular feed for users if true
  1833. *
  1834. * @return string XML feed
  1835. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1836. * @throws \ImagickException
  1837. */
  1838. public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false, $feed_mode = false)
  1839. {
  1840. $stamp = microtime(true);
  1841. $owner = User::getOwnerDataByNick($owner_nick);
  1842. if (!$owner) {
  1843. return;
  1844. }
  1845. $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
  1846. $previous_created = $last_update;
  1847. // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
  1848. if ((time() - strtotime($owner['last-item'])) < 15*60) {
  1849. $result = DI::cache()->get($cachekey);
  1850. if (!$nocache && !is_null($result)) {
  1851. Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
  1852. $last_update = $result['last_update'];
  1853. return $result['feed'];
  1854. }
  1855. }
  1856. if (!strlen($last_update)) {
  1857. $last_update = 'now -30 days';
  1858. }
  1859. $check_date = DateTimeFormat::utc($last_update);
  1860. $authorid = Contact::getIdForURL($owner["url"], 0, true);
  1861. $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
  1862. AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
  1863. $owner["uid"], $check_date, Protocol::OSTATUS, Protocol::DFRN];
  1864. if ($filter === 'comments') {
  1865. $condition[0] .= " AND `object-type` = ? ";
  1866. $condition[] = Activity\ObjectType::COMMENT;
  1867. }
  1868. if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
  1869. $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
  1870. $condition[] = $owner["id"];
  1871. $condition[] = $authorid;
  1872. }
  1873. $params = ['order' => ['received' => true], 'limit' => $max_items];
  1874. if ($filter === 'posts') {
  1875. $ret = Item::selectThread([], $condition, $params);
  1876. } else {
  1877. $ret = Item::select([], $condition, $params);
  1878. }
  1879. $items = Item::inArray($ret);
  1880. $doc = new DOMDocument('1.0', 'utf-8');
  1881. $doc->formatOutput = true;
  1882. $root = self::addHeader($doc, $owner, $filter, $feed_mode);
  1883. foreach ($items as $item) {
  1884. if (Config::get('system', 'ostatus_debug')) {
  1885. $item['body'] .= '🍼';
  1886. }
  1887. $entry = self::entry($doc, $item, $owner, false, $feed_mode);
  1888. $root->appendChild($entry);
  1889. if ($last_update < $item['created']) {
  1890. $last_update = $item['created'];
  1891. }
  1892. }
  1893. $feeddata = trim($doc->saveXML());
  1894. $msg = ['feed' => $feeddata, 'last_update' => $last_update];
  1895. DI::cache()->set($cachekey, $msg, Cache::QUARTER_HOUR);
  1896. Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
  1897. return $feeddata;
  1898. }
  1899. /**
  1900. * @brief Creates the XML for a salmon message
  1901. *
  1902. * @param array $item Data of the item that is to be posted
  1903. * @param array $owner Contact data of the poster
  1904. *
  1905. * @return string XML for the salmon
  1906. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1907. * @throws \ImagickException
  1908. */
  1909. public static function salmon(array $item, array $owner)
  1910. {
  1911. $doc = new DOMDocument('1.0', 'utf-8');
  1912. $doc->formatOutput = true;
  1913. if (Config::get('system', 'ostatus_debug')) {
  1914. $item['body'] .= '🐟';
  1915. }
  1916. $entry = self::entry($doc, $item, $owner, true);
  1917. $doc->appendChild($entry);
  1918. return trim($doc->saveXML());
  1919. }
  1920. /**
  1921. * Checks if the given contact url does support OStatus
  1922. *
  1923. * @param string $url profile url
  1924. * @param boolean $update Update the profile
  1925. * @return boolean
  1926. * @throws \Friendica\Network\HTTPException\InternalServerErrorException
  1927. * @throws \ImagickException
  1928. */
  1929. public static function isSupportedByContactUrl($url, $update = false)
  1930. {
  1931. $probe = Probe::uri($url, Protocol::OSTATUS, 0, !$update);
  1932. return $probe['network'] == Protocol::OSTATUS;
  1933. }
  1934. }