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.

3102 lines
98KB

  1. <?php
  2. /**
  3. * @file include/dfrn.php
  4. * @brief The implementation of the dfrn protocol
  5. *
  6. * @see https://github.com/friendica/friendica/wiki/Protocol and
  7. * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
  8. */
  9. namespace Friendica\Protocol;
  10. use Friendica\App;
  11. use Friendica\Content\OEmbed;
  12. use Friendica\Content\Text\BBCode;
  13. use Friendica\Content\Text\HTML;
  14. use Friendica\Core\Addon;
  15. use Friendica\Core\Config;
  16. use Friendica\Core\L10n;
  17. use Friendica\Core\System;
  18. use Friendica\Core\Worker;
  19. use Friendica\Database\DBM;
  20. use Friendica\Model\Contact;
  21. use Friendica\Model\Event;
  22. use Friendica\Model\GContact;
  23. use Friendica\Model\Group;
  24. use Friendica\Model\Item;
  25. use Friendica\Model\Profile;
  26. use Friendica\Model\User;
  27. use Friendica\Object\Image;
  28. use Friendica\Protocol\OStatus;
  29. use Friendica\Util\Crypto;
  30. use Friendica\Util\DateTimeFormat;
  31. use Friendica\Util\Network;
  32. use Friendica\Util\XML;
  33. use Friendica\Protocol\Diaspora;
  34. use dba;
  35. use DOMDocument;
  36. use DOMXPath;
  37. use HTMLPurifier;
  38. use HTMLPurifier_Config;
  39. require_once 'boot.php';
  40. require_once 'include/dba.php';
  41. require_once "include/enotify.php";
  42. require_once "include/items.php";
  43. require_once "include/text.php";
  44. /**
  45. * @brief This class contain functions to create and send DFRN XML files
  46. */
  47. class DFRN
  48. {
  49. const TOP_LEVEL = 0; // Top level posting
  50. const REPLY = 1; // Regular reply that is stored locally
  51. const REPLY_RC = 2; // Reply that will be relayed
  52. /**
  53. * @brief Generates the atom entries for delivery.php
  54. *
  55. * This function is used whenever content is transmitted via DFRN.
  56. *
  57. * @param array $items Item elements
  58. * @param array $owner Owner record
  59. *
  60. * @return string DFRN entries
  61. * @todo Find proper type-hints
  62. */
  63. public static function entries($items, $owner)
  64. {
  65. $doc = new DOMDocument('1.0', 'utf-8');
  66. $doc->formatOutput = true;
  67. $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
  68. if (! count($items)) {
  69. return trim($doc->saveXML());
  70. }
  71. foreach ($items as $item) {
  72. $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
  73. $root->appendChild($entry);
  74. }
  75. return trim($doc->saveXML());
  76. }
  77. /**
  78. * @brief Generate an atom feed for the given user
  79. *
  80. * This function is called when another server is pulling data from the user feed.
  81. *
  82. * @param string $dfrn_id DFRN ID from the requesting party
  83. * @param string $owner_nick Owner nick name
  84. * @param string $last_update Date of the last update
  85. * @param int $direction Can be -1, 0 or 1.
  86. * @param boolean $onlyheader Output only the header without content? (Default is "no")
  87. *
  88. * @return string DFRN feed entries
  89. */
  90. public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
  91. {
  92. $a = get_app();
  93. $sitefeed = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
  94. $public_feed = (($dfrn_id) ? false : true);
  95. $starred = false; // not yet implemented, possible security issues
  96. $converse = false;
  97. if ($public_feed && $a->argc > 2) {
  98. for ($x = 2; $x < $a->argc; $x++) {
  99. if ($a->argv[$x] == 'converse') {
  100. $converse = true;
  101. }
  102. if ($a->argv[$x] == 'starred') {
  103. $starred = true;
  104. }
  105. if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
  106. $category = $a->argv[$x+1];
  107. }
  108. }
  109. }
  110. // default permissions - anonymous user
  111. $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = '' ";
  112. $r = q(
  113. "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
  114. FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
  115. WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
  116. dbesc($owner_nick)
  117. );
  118. if (! DBM::is_result($r)) {
  119. logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
  120. killme();
  121. }
  122. $owner = $r[0];
  123. $owner_id = $owner['uid'];
  124. $owner_nick = $owner['nickname'];
  125. $sql_post_table = "";
  126. if (! $public_feed) {
  127. $sql_extra = '';
  128. switch ($direction) {
  129. case (-1):
  130. $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
  131. $my_id = $dfrn_id;
  132. break;
  133. case 0:
  134. $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
  135. $my_id = '1:' . $dfrn_id;
  136. break;
  137. case 1:
  138. $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
  139. $my_id = '0:' . $dfrn_id;
  140. break;
  141. default:
  142. return false;
  143. break; // NOTREACHED
  144. }
  145. $r = q(
  146. "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
  147. intval($owner_id)
  148. );
  149. if (! DBM::is_result($r)) {
  150. logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
  151. killme();
  152. }
  153. $contact = $r[0];
  154. include_once 'include/security.php';
  155. $groups = Group::getIdsByContactId($contact['id']);
  156. if (count($groups)) {
  157. for ($x = 0; $x < count($groups); $x ++) {
  158. $groups[$x] = '<' . intval($groups[$x]) . '>' ;
  159. }
  160. $gs = implode('|', $groups);
  161. } else {
  162. $gs = '<<>>' ; // Impossible to match
  163. }
  164. $sql_extra = sprintf(
  165. "
  166. AND ( `allow_cid` = '' OR `allow_cid` REGEXP '<%d>' )
  167. AND ( `deny_cid` = '' OR NOT `deny_cid` REGEXP '<%d>' )
  168. AND ( `allow_gid` = '' OR `allow_gid` REGEXP '%s' )
  169. AND ( `deny_gid` = '' OR NOT `deny_gid` REGEXP '%s')
  170. ",
  171. intval($contact['id']),
  172. intval($contact['id']),
  173. dbesc($gs),
  174. dbesc($gs)
  175. );
  176. }
  177. if ($public_feed) {
  178. $sort = 'DESC';
  179. } else {
  180. $sort = 'ASC';
  181. }
  182. if (! strlen($last_update)) {
  183. $last_update = 'now -30 days';
  184. }
  185. if (isset($category)) {
  186. $sql_post_table = sprintf(
  187. "INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
  188. dbesc(protect_sprintf($category)),
  189. intval(TERM_OBJ_POST),
  190. intval(TERM_CATEGORY),
  191. intval($owner_id)
  192. );
  193. //$sql_extra .= file_tag_file_query('item',$category,'category');
  194. }
  195. if ($public_feed && ! $converse) {
  196. $sql_extra .= " AND `contact`.`self` = 1 ";
  197. }
  198. $check_date = DateTimeFormat::utc($last_update);
  199. $r = q(
  200. "SELECT `item`.`id`
  201. FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
  202. STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
  203. WHERE `item`.`uid` = %d AND `item`.`wall` AND `item`.`changed` > '%s'
  204. $sql_extra
  205. ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
  206. intval($owner_id),
  207. dbesc($check_date),
  208. dbesc($sort)
  209. );
  210. $ids = [];
  211. foreach ($r as $item) {
  212. $ids[] = $item['id'];
  213. }
  214. if (!empty($ids)) {
  215. $ret = Item::select(Item::DELIVER_FIELDLIST, ['id' => $ids]);
  216. $items = dba::inArray($ret);
  217. } else {
  218. $items = [];
  219. }
  220. /*
  221. * Will check further below if this actually returned results.
  222. * We will provide an empty feed if that is the case.
  223. */
  224. $doc = new DOMDocument('1.0', 'utf-8');
  225. $doc->formatOutput = true;
  226. $alternatelink = $owner['url'];
  227. if (isset($category)) {
  228. $alternatelink .= "/category/".$category;
  229. }
  230. if ($public_feed) {
  231. $author = "dfrn:owner";
  232. } else {
  233. $author = "author";
  234. }
  235. $root = self::addHeader($doc, $owner, $author, $alternatelink, true);
  236. /// @TODO This hook can't work anymore
  237. // Addon::callHooks('atom_feed', $atom);
  238. if (!DBM::is_result($items) || $onlyheader) {
  239. $atom = trim($doc->saveXML());
  240. Addon::callHooks('atom_feed_end', $atom);
  241. return $atom;
  242. }
  243. foreach ($items as $item) {
  244. // prevent private email from leaking.
  245. if ($item['network'] == NETWORK_MAIL) {
  246. continue;
  247. }
  248. // public feeds get html, our own nodes use bbcode
  249. if ($public_feed) {
  250. $type = 'html';
  251. // catch any email that's in a public conversation and make sure it doesn't leak
  252. if ($item['private']) {
  253. continue;
  254. }
  255. } else {
  256. $type = 'text';
  257. }
  258. $entry = self::entry($doc, $type, $item, $owner, true);
  259. $root->appendChild($entry);
  260. }
  261. $atom = trim($doc->saveXML());
  262. Addon::callHooks('atom_feed_end', $atom);
  263. return $atom;
  264. }
  265. /**
  266. * @brief Generate an atom entry for a given item id
  267. *
  268. * @param int $item_id The item id
  269. * @param boolean $conversation Show the conversation. If false show the single post.
  270. *
  271. * @return string DFRN feed entry
  272. */
  273. public static function itemFeed($item_id, $conversation = false)
  274. {
  275. if ($conversation) {
  276. $condition = ['parent' => $item_id];
  277. } else {
  278. $condition = ['id' => $item_id];
  279. }
  280. $ret = Item::select(Item::DELIVER_FIELDLIST, $condition);
  281. $items = dba::inArray($ret);
  282. if (!DBM::is_result($items)) {
  283. killme();
  284. }
  285. $item = $items[0];
  286. if ($item['uid'] != 0) {
  287. $owner = User::getOwnerDataById($item['uid']);
  288. if (!$owner) {
  289. killme();
  290. }
  291. } else {
  292. $owner = ['uid' => 0, 'nick' => 'feed-item'];
  293. }
  294. $doc = new DOMDocument('1.0', 'utf-8');
  295. $doc->formatOutput = true;
  296. $type = 'html';
  297. if ($conversation) {
  298. $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
  299. $doc->appendChild($root);
  300. $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
  301. $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
  302. $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
  303. $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
  304. $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
  305. $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
  306. $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
  307. $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
  308. $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
  309. //$root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
  310. foreach ($items as $item) {
  311. $entry = self::entry($doc, $type, $item, $owner, true, 0);
  312. $root->appendChild($entry);
  313. }
  314. } else {
  315. $root = self::entry($doc, $type, $item, $owner, true, 0, true);
  316. }
  317. $atom = trim($doc->saveXML());
  318. return $atom;
  319. }
  320. /**
  321. * @brief Create XML text for DFRN mails
  322. *
  323. * @param array $item message elements
  324. * @param array $owner Owner record
  325. *
  326. * @return string DFRN mail
  327. * @todo Find proper type-hints
  328. */
  329. public static function mail($item, $owner)
  330. {
  331. $doc = new DOMDocument('1.0', 'utf-8');
  332. $doc->formatOutput = true;
  333. $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
  334. $mail = $doc->createElement("dfrn:mail");
  335. $sender = $doc->createElement("dfrn:sender");
  336. XML::addElement($doc, $sender, "dfrn:name", $owner['name']);
  337. XML::addElement($doc, $sender, "dfrn:uri", $owner['url']);
  338. XML::addElement($doc, $sender, "dfrn:avatar", $owner['thumb']);
  339. $mail->appendChild($sender);
  340. XML::addElement($doc, $mail, "dfrn:id", $item['uri']);
  341. XML::addElement($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
  342. XML::addElement($doc, $mail, "dfrn:sentdate", DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
  343. XML::addElement($doc, $mail, "dfrn:subject", $item['title']);
  344. XML::addElement($doc, $mail, "dfrn:content", $item['body']);
  345. $root->appendChild($mail);
  346. return trim($doc->saveXML());
  347. }
  348. /**
  349. * @brief Create XML text for DFRN friend suggestions
  350. *
  351. * @param array $item suggestion elements
  352. * @param array $owner Owner record
  353. *
  354. * @return string DFRN suggestions
  355. * @todo Find proper type-hints
  356. */
  357. public static function fsuggest($item, $owner)
  358. {
  359. $doc = new DOMDocument('1.0', 'utf-8');
  360. $doc->formatOutput = true;
  361. $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
  362. $suggest = $doc->createElement("dfrn:suggest");
  363. XML::addElement($doc, $suggest, "dfrn:url", $item['url']);
  364. XML::addElement($doc, $suggest, "dfrn:name", $item['name']);
  365. XML::addElement($doc, $suggest, "dfrn:photo", $item['photo']);
  366. XML::addElement($doc, $suggest, "dfrn:request", $item['request']);
  367. XML::addElement($doc, $suggest, "dfrn:note", $item['note']);
  368. $root->appendChild($suggest);
  369. return trim($doc->saveXML());
  370. }
  371. /**
  372. * @brief Create XML text for DFRN relocations
  373. *
  374. * @param array $owner Owner record
  375. * @param int $uid User ID
  376. *
  377. * @return string DFRN relocations
  378. * @todo Find proper type-hints
  379. */
  380. public static function relocate($owner, $uid)
  381. {
  382. /* get site pubkey. this could be a new installation with no site keys*/
  383. $pubkey = Config::get('system', 'site_pubkey');
  384. if (! $pubkey) {
  385. $res = Crypto::newKeypair(1024);
  386. Config::set('system', 'site_prvkey', $res['prvkey']);
  387. Config::set('system', 'site_pubkey', $res['pubkey']);
  388. }
  389. $rp = q(
  390. "SELECT `resource-id` , `scale`, type FROM `photo`
  391. WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;",
  392. $uid
  393. );
  394. $photos = [];
  395. $ext = Image::supportedTypes();
  396. foreach ($rp as $p) {
  397. $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
  398. }
  399. $doc = new DOMDocument('1.0', 'utf-8');
  400. $doc->formatOutput = true;
  401. $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
  402. $relocate = $doc->createElement("dfrn:relocate");
  403. XML::addElement($doc, $relocate, "dfrn:url", $owner['url']);
  404. XML::addElement($doc, $relocate, "dfrn:name", $owner['name']);
  405. XML::addElement($doc, $relocate, "dfrn:addr", $owner['addr']);
  406. XML::addElement($doc, $relocate, "dfrn:avatar", $owner['avatar']);
  407. XML::addElement($doc, $relocate, "dfrn:photo", $photos[4]);
  408. XML::addElement($doc, $relocate, "dfrn:thumb", $photos[5]);
  409. XML::addElement($doc, $relocate, "dfrn:micro", $photos[6]);
  410. XML::addElement($doc, $relocate, "dfrn:request", $owner['request']);
  411. XML::addElement($doc, $relocate, "dfrn:confirm", $owner['confirm']);
  412. XML::addElement($doc, $relocate, "dfrn:notify", $owner['notify']);
  413. XML::addElement($doc, $relocate, "dfrn:poll", $owner['poll']);
  414. XML::addElement($doc, $relocate, "dfrn:sitepubkey", Config::get('system', 'site_pubkey'));
  415. $root->appendChild($relocate);
  416. return trim($doc->saveXML());
  417. }
  418. /**
  419. * @brief Adds the header elements for the DFRN protocol
  420. *
  421. * @param object $doc XML document
  422. * @param array $owner Owner record
  423. * @param string $authorelement Element name for the author
  424. * @param string $alternatelink link to profile or category
  425. * @param bool $public Is it a header for public posts?
  426. *
  427. * @return object XML root object
  428. * @todo Find proper type-hints
  429. */
  430. private static function addHeader($doc, $owner, $authorelement, $alternatelink = "", $public = false)
  431. {
  432. if ($alternatelink == "") {
  433. $alternatelink = $owner['url'];
  434. }
  435. $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
  436. $doc->appendChild($root);
  437. $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
  438. $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
  439. $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
  440. $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
  441. $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
  442. $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
  443. $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
  444. $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
  445. $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
  446. XML::addElement($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
  447. XML::addElement($doc, $root, "title", $owner["name"]);
  448. $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION];
  449. XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
  450. $attributes = ["rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/"];
  451. XML::addElement($doc, $root, "link", "", $attributes);
  452. $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $alternatelink];
  453. XML::addElement($doc, $root, "link", "", $attributes);
  454. if ($public) {
  455. // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
  456. OStatus::hublinks($doc, $root, $owner["nick"]);
  457. $attributes = ["rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
  458. XML::addElement($doc, $root, "link", "", $attributes);
  459. $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
  460. XML::addElement($doc, $root, "link", "", $attributes);
  461. $attributes = ["rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]];
  462. XML::addElement($doc, $root, "link", "", $attributes);
  463. }
  464. // For backward compatibility we keep this element
  465. if ($owner['page-flags'] == PAGE_COMMUNITY) {
  466. XML::addElement($doc, $root, "dfrn:community", 1);
  467. }
  468. // The former element is replaced by this one
  469. XML::addElement($doc, $root, "dfrn:account_type", $owner["account-type"]);
  470. /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
  471. XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
  472. $author = self::addAuthor($doc, $owner, $authorelement, $public);
  473. $root->appendChild($author);
  474. return $root;
  475. }
  476. /**
  477. * @brief Adds the author element in the header for the DFRN protocol
  478. *
  479. * @param object $doc XML document
  480. * @param array $owner Owner record
  481. * @param string $authorelement Element name for the author
  482. * @param boolean $public boolean
  483. *
  484. * @return object XML author object
  485. * @todo Find proper type-hints
  486. */
  487. private static function addAuthor($doc, $owner, $authorelement, $public)
  488. {
  489. // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
  490. $r = q(
  491. "SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
  492. WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
  493. intval($owner['uid'])
  494. );
  495. if (DBM::is_result($r)) {
  496. $hidewall = true;
  497. } else {
  498. $hidewall = false;
  499. }
  500. $author = $doc->createElement($authorelement);
  501. $namdate = DateTimeFormat::utc($owner['name-date'].'+00:00', DateTimeFormat::ATOM);
  502. $uridate = DateTimeFormat::utc($owner['uri-date'].'+00:00', DateTimeFormat::ATOM);
  503. $picdate = DateTimeFormat::utc($owner['avatar-date'].'+00:00', DateTimeFormat::ATOM);
  504. $attributes = [];
  505. if (!$public || !$hidewall) {
  506. $attributes = ["dfrn:updated" => $namdate];
  507. }
  508. XML::addElement($doc, $author, "name", $owner["name"], $attributes);
  509. XML::addElement($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
  510. XML::addElement($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
  511. $attributes = ["rel" => "photo", "type" => "image/jpeg",
  512. "media:width" => 175, "media:height" => 175, "href" => $owner['photo']];
  513. if (!$public || !$hidewall) {
  514. $attributes["dfrn:updated"] = $picdate;
  515. }
  516. XML::addElement($doc, $author, "link", "", $attributes);
  517. $attributes["rel"] = "avatar";
  518. XML::addElement($doc, $author, "link", "", $attributes);
  519. if ($hidewall) {
  520. XML::addElement($doc, $author, "dfrn:hide", "true");
  521. }
  522. // The following fields will only be generated if the data isn't meant for a public feed
  523. if ($public) {
  524. return $author;
  525. }
  526. $birthday = feed_birthday($owner['uid'], $owner['timezone']);
  527. if ($birthday) {
  528. XML::addElement($doc, $author, "dfrn:birthday", $birthday);
  529. }
  530. // Only show contact details when we are allowed to
  531. $r = q(
  532. "SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
  533. `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
  534. `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
  535. FROM `profile`
  536. INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
  537. WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
  538. intval($owner['uid'])
  539. );
  540. if (DBM::is_result($r)) {
  541. $profile = $r[0];
  542. XML::addElement($doc, $author, "poco:displayName", $profile["name"]);
  543. XML::addElement($doc, $author, "poco:updated", $namdate);
  544. if (trim($profile["dob"]) > '0001-01-01') {
  545. XML::addElement($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
  546. }
  547. XML::addElement($doc, $author, "poco:note", $profile["about"]);
  548. XML::addElement($doc, $author, "poco:preferredUsername", $profile["nickname"]);
  549. $savetz = date_default_timezone_get();
  550. date_default_timezone_set($profile["timezone"]);
  551. XML::addElement($doc, $author, "poco:utcOffset", date("P"));
  552. date_default_timezone_set($savetz);
  553. if (trim($profile["homepage"]) != "") {
  554. $urls = $doc->createElement("poco:urls");
  555. XML::addElement($doc, $urls, "poco:type", "homepage");
  556. XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
  557. XML::addElement($doc, $urls, "poco:primary", "true");
  558. $author->appendChild($urls);
  559. }
  560. if (trim($profile["pub_keywords"]) != "") {
  561. $keywords = explode(",", $profile["pub_keywords"]);
  562. foreach ($keywords as $keyword) {
  563. XML::addElement($doc, $author, "poco:tags", trim($keyword));
  564. }
  565. }
  566. if (trim($profile["xmpp"]) != "") {
  567. $ims = $doc->createElement("poco:ims");
  568. XML::addElement($doc, $ims, "poco:type", "xmpp");
  569. XML::addElement($doc, $ims, "poco:value", $profile["xmpp"]);
  570. XML::addElement($doc, $ims, "poco:primary", "true");
  571. $author->appendChild($ims);
  572. }
  573. if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
  574. $element = $doc->createElement("poco:address");
  575. XML::addElement($doc, $element, "poco:formatted", Profile::formatLocation($profile));
  576. if (trim($profile["locality"]) != "") {
  577. XML::addElement($doc, $element, "poco:locality", $profile["locality"]);
  578. }
  579. if (trim($profile["region"]) != "") {
  580. XML::addElement($doc, $element, "poco:region", $profile["region"]);
  581. }
  582. if (trim($profile["country-name"]) != "") {
  583. XML::addElement($doc, $element, "poco:country", $profile["country-name"]);
  584. }
  585. $author->appendChild($element);
  586. }
  587. }
  588. return $author;
  589. }
  590. /**
  591. * @brief Adds the author elements in the "entry" elements of the DFRN protocol
  592. *
  593. * @param object $doc XML document
  594. * @param string $element Element name for the author
  595. * @param string $contact_url Link of the contact
  596. * @param array $item Item elements
  597. *
  598. * @return object XML author object
  599. * @todo Find proper type-hints
  600. */
  601. private static function addEntryAuthor($doc, $element, $contact_url, $item)
  602. {
  603. $contact = Contact::getDetailsByURL($contact_url, $item["uid"]);
  604. $author = $doc->createElement($element);
  605. XML::addElement($doc, $author, "name", $contact["name"]);
  606. XML::addElement($doc, $author, "uri", $contact["url"]);
  607. XML::addElement($doc, $author, "dfrn:handle", $contact["addr"]);
  608. /// @Todo
  609. /// - Check real image type and image size
  610. /// - Check which of these boths elements we should use
  611. $attributes = [
  612. "rel" => "photo",
  613. "type" => "image/jpeg",
  614. "media:width" => 80,
  615. "media:height" => 80,
  616. "href" => $contact["photo"]];
  617. XML::addElement($doc, $author, "link", "", $attributes);
  618. $attributes = [
  619. "rel" => "avatar",
  620. "type" => "image/jpeg",
  621. "media:width" => 80,
  622. "media:height" => 80,
  623. "href" => $contact["photo"]];
  624. XML::addElement($doc, $author, "link", "", $attributes);
  625. return $author;
  626. }
  627. /**
  628. * @brief Adds the activity elements
  629. *
  630. * @param object $doc XML document
  631. * @param string $element Element name for the activity
  632. * @param string $activity activity value
  633. *
  634. * @return object XML activity object
  635. * @todo Find proper type-hints
  636. */
  637. private static function createActivity($doc, $element, $activity)
  638. {
  639. if ($activity) {
  640. $entry = $doc->createElement($element);
  641. $r = XML::parseString($activity, false);
  642. if (!$r) {
  643. return false;
  644. }
  645. if ($r->type) {
  646. XML::addElement($doc, $entry, "activity:object-type", $r->type);
  647. }
  648. if ($r->id) {
  649. XML::addElement($doc, $entry, "id", $r->id);
  650. }
  651. if ($r->title) {
  652. XML::addElement($doc, $entry, "title", $r->title);
  653. }
  654. if ($r->link) {
  655. if (substr($r->link, 0, 1) == '<') {
  656. if (strstr($r->link, '&') && (! strstr($r->link, '&amp;'))) {
  657. $r->link = str_replace('&', '&amp;', $r->link);
  658. }
  659. $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
  660. // XML does need a single element as root element so we add a dummy element here
  661. $data = XML::parseString("<dummy>" . $r->link . "</dummy>", false);
  662. if (is_object($data)) {
  663. foreach ($data->link as $link) {
  664. $attributes = [];
  665. foreach ($link->attributes() as $parameter => $value) {
  666. $attributes[$parameter] = $value;
  667. }
  668. XML::addElement($doc, $entry, "link", "", $attributes);
  669. }
  670. }
  671. } else {
  672. $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $r->link];
  673. XML::addElement($doc, $entry, "link", "", $attributes);
  674. }
  675. }
  676. if ($r->content) {
  677. XML::addElement($doc, $entry, "content", BBCode::convert($r->content), ["type" => "html"]);
  678. }
  679. return $entry;
  680. }
  681. return false;
  682. }
  683. /**
  684. * @brief Adds the elements for attachments
  685. *
  686. * @param object $doc XML document
  687. * @param object $root XML root
  688. * @param array $item Item element
  689. *
  690. * @return object XML attachment object
  691. * @todo Find proper type-hints
  692. */
  693. private static function getAttachment($doc, $root, $item)
  694. {
  695. $arr = explode('[/attach],', $item['attach']);
  696. if (count($arr)) {
  697. foreach ($arr as $r) {
  698. $matches = false;
  699. $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
  700. if ($cnt) {
  701. $attributes = ["rel" => "enclosure",
  702. "href" => $matches[1],
  703. "type" => $matches[3]];
  704. if (intval($matches[2])) {
  705. $attributes["length"] = intval($matches[2]);
  706. }
  707. if (trim($matches[4]) != "") {
  708. $attributes["title"] = trim($matches[4]);
  709. }
  710. XML::addElement($doc, $root, "link", "", $attributes);
  711. }
  712. }
  713. }
  714. }
  715. /**
  716. * @brief Adds the "entry" elements for the DFRN protocol
  717. *
  718. * @param object $doc XML document
  719. * @param string $type "text" or "html"
  720. * @param array $item Item element
  721. * @param array $owner Owner record
  722. * @param bool $comment Trigger the sending of the "comment" element
  723. * @param int $cid Contact ID of the recipient
  724. * @param bool $single If set, the entry is created as an XML document with a single "entry" element
  725. *
  726. * @return object XML entry object
  727. * @todo Find proper type-hints
  728. */
  729. private static function entry($doc, $type, array $item, array $owner, $comment = false, $cid = 0, $single = false)
  730. {
  731. $mentioned = [];
  732. if (!$item['parent']) {
  733. return;
  734. }
  735. if ($item['deleted']) {
  736. $attributes = ["ref" => $item['uri'], "when" => DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM)];
  737. return XML::createElement($doc, "at:deleted-entry", "", $attributes);
  738. }
  739. if (!$single) {
  740. $entry = $doc->createElement("entry");
  741. } else {
  742. $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
  743. $doc->appendChild($entry);
  744. $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
  745. $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
  746. $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
  747. $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
  748. $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
  749. $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
  750. $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
  751. $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
  752. $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
  753. }
  754. if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
  755. $body = Item::fixPrivatePhotos($item['body'], $owner['uid'], $item, $cid);
  756. } else {
  757. $body = $item['body'];
  758. }
  759. // Remove the abstract element. It is only locally important.
  760. $body = BBCode::stripAbstract($body);
  761. $htmlbody = '';
  762. if ($type == 'html') {
  763. $htmlbody = $body;
  764. if ($item['title'] != "") {
  765. $htmlbody = "[b]" . $item['title'] . "[/b]\n\n" . $htmlbody;
  766. }
  767. $htmlbody = BBCode::convert($htmlbody, false, 7);
  768. }
  769. $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
  770. $entry->appendChild($author);
  771. $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
  772. $entry->appendChild($dfrnowner);
  773. if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
  774. $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
  775. $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
  776. $attributes = ["ref" => $parent_item, "type" => "text/html",
  777. "href" => $parent[0]['plink'],
  778. "dfrn:diaspora_guid" => $parent[0]['guid']];
  779. XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
  780. }
  781. // Add conversation data. This is used for OStatus
  782. $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
  783. $conversation_uri = $conversation_href;
  784. if (isset($parent_item)) {
  785. $conversation = dba::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $item['parent-uri']]);
  786. if (DBM::is_result($conversation)) {
  787. if ($r['conversation-uri'] != '') {
  788. $conversation_uri = $conversation['conversation-uri'];
  789. }
  790. if ($r['conversation-href'] != '') {
  791. $conversation_href = $conversation['conversation-href'];
  792. }
  793. }
  794. }
  795. $attributes = [
  796. "href" => $conversation_href,
  797. "ref" => $conversation_uri];
  798. XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
  799. XML::addElement($doc, $entry, "id", $item["uri"]);
  800. XML::addElement($doc, $entry, "title", $item["title"]);
  801. XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"] . "+00:00", DateTimeFormat::ATOM));
  802. XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"] . "+00:00", DateTimeFormat::ATOM));
  803. // "dfrn:env" is used to read the content
  804. XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
  805. // The "content" field is not read by the receiver. We could remove it when the type is "text"
  806. // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
  807. XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
  808. // We save this value in "plink". Maybe we should read it from there as well?
  809. XML::addElement(
  810. $doc,
  811. $entry,
  812. "link",
  813. "",
  814. ["rel" => "alternate", "type" => "text/html",
  815. "href" => System::baseUrl() . "/display/" . $item["guid"]]
  816. );
  817. // "comment-allow" is some old fashioned stuff for old Friendica versions.
  818. // It is included in the rewritten code for completeness
  819. if ($comment) {
  820. XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
  821. }
  822. if ($item['location']) {
  823. XML::addElement($doc, $entry, "dfrn:location", $item['location']);
  824. }
  825. if ($item['coord']) {
  826. XML::addElement($doc, $entry, "georss:point", $item['coord']);
  827. }
  828. if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
  829. XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
  830. }
  831. if ($item['extid']) {
  832. XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
  833. }
  834. if ($item['bookmark']) {
  835. XML::addElement($doc, $entry, "dfrn:bookmark", "true");
  836. }
  837. if ($item['app']) {
  838. XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
  839. }
  840. XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
  841. // The signed text contains the content in Markdown, the sender handle and the signatur for the content
  842. // It is needed for relayed comments to Diaspora.
  843. if ($item['signed_text']) {
  844. $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
  845. XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
  846. }
  847. XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
  848. if ($item['object-type'] != "") {
  849. XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
  850. } elseif ($item['id'] == $item['parent']) {
  851. XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
  852. } else {
  853. XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
  854. }
  855. $actobj = self::createActivity($doc, "activity:object", $item['object']);
  856. if ($actobj) {
  857. $entry->appendChild($actobj);
  858. }
  859. $actarg = self::createActivity($doc, "activity:target", $item['target']);
  860. if ($actarg) {
  861. $entry->appendChild($actarg);
  862. }
  863. $tags = Item::getFeedTags($item);
  864. /// @TODO Combine this with similar below if() block?
  865. if (count($tags)) {
  866. foreach ($tags as $t) {
  867. if (($type != 'html') || ($t[0] != "@")) {
  868. XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
  869. }
  870. }
  871. }
  872. if (count($tags)) {
  873. foreach ($tags as $t) {
  874. if ($t[0] == "@") {
  875. $mentioned[$t[1]] = $t[1];
  876. }
  877. }
  878. }
  879. foreach ($mentioned as $mention) {
  880. $r = q(
  881. "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
  882. intval($owner["uid"]),
  883. dbesc(normalise_link($mention))
  884. );
  885. if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
  886. XML::addElement(
  887. $doc,
  888. $entry,
  889. "link",
  890. "",
  891. ["rel" => "mentioned",
  892. "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
  893. "href" => $mention]
  894. );
  895. } else {
  896. XML::addElement(
  897. $doc,
  898. $entry,
  899. "link",
  900. "",
  901. ["rel" => "mentioned",
  902. "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
  903. "href" => $mention]
  904. );
  905. }
  906. }
  907. self::getAttachment($doc, $entry, $item);
  908. return $entry;
  909. }
  910. /**
  911. * @brief encrypts data via AES
  912. *
  913. * @param string $data The data that is to be encrypted
  914. * @param string $key The AES key
  915. *
  916. * @return string encrypted data
  917. */
  918. private static function aesEncrypt($data, $key)
  919. {
  920. return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
  921. }
  922. /**
  923. * @brief decrypts data via AES
  924. *
  925. * @param string $encrypted The encrypted data
  926. * @param string $key The AES key
  927. *
  928. * @return string decrypted data
  929. */
  930. public static function aesDecrypt($encrypted, $key)
  931. {
  932. return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
  933. }
  934. /**
  935. * @brief Delivers the atom content to the contacts
  936. *
  937. * @param array $owner Owner record
  938. * @param array $contact Contact record of the receiver
  939. * @param string $atom Content that will be transmitted
  940. * @param bool $dissolve (to be documented)
  941. *
  942. * @return int Deliver status. Negative values mean an error.
  943. * @todo Add array type-hint for $owner, $contact
  944. */
  945. public static function deliver($owner, $contact, $atom, $dissolve = false)
  946. {
  947. $a = get_app();
  948. // At first try the Diaspora transport layer
  949. $ret = self::transmit($owner, $contact, $atom);
  950. if ($ret >= 200) {
  951. logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
  952. return $ret;
  953. }
  954. $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
  955. if ($contact['duplex'] && $contact['dfrn-id']) {
  956. $idtosend = '0:' . $orig_id;
  957. }
  958. if ($contact['duplex'] && $contact['issued-id']) {
  959. $idtosend = '1:' . $orig_id;
  960. }
  961. $rino = Config::get('system', 'rino_encrypt');
  962. $rino = intval($rino);
  963. logger("Local rino version: ". $rino, LOGGER_DEBUG);
  964. $ssl_val = intval(Config::get('system', 'ssl_policy'));
  965. $ssl_policy = '';
  966. switch ($ssl_val) {
  967. case SSL_POLICY_FULL:
  968. $ssl_policy = 'full';
  969. break;
  970. case SSL_POLICY_SELFSIGN:
  971. $ssl_policy = 'self';
  972. break;
  973. case SSL_POLICY_NONE:
  974. default:
  975. $ssl_policy = 'none';
  976. break;
  977. }
  978. $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
  979. logger('dfrn_deliver: ' . $url);
  980. $ret = Network::curl($url);
  981. if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
  982. Contact::markForArchival($contact);
  983. return -2; // timed out
  984. }
  985. $xml = $ret['body'];
  986. $curl_stat = $a->get_curl_code();
  987. if (empty($curl_stat)) {
  988. Contact::markForArchival($contact);
  989. return -3; // timed out
  990. }
  991. logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
  992. if (empty($xml)) {
  993. Contact::markForArchival($contact);
  994. return 3;
  995. }
  996. if (strpos($xml, '<?xml') === false) {
  997. logger('dfrn_deliver: no valid XML returned');
  998. logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
  999. Contact::markForArchival($contact);
  1000. return 3;
  1001. }
  1002. $res = XML::parseString($xml);
  1003. if ((intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
  1004. Contact::markForArchival($contact);
  1005. return ($res->status ? $res->status : 3);
  1006. }
  1007. $postvars = [];
  1008. $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
  1009. $challenge = hex2bin((string) $res->challenge);
  1010. $perm = (($res->perm) ? $res->perm : null);
  1011. $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
  1012. $rino_remote_version = intval($res->rino);
  1013. $page = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
  1014. logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
  1015. if ($owner['page-flags'] == PAGE_PRVGROUP) {
  1016. $page = 2;
  1017. }
  1018. $final_dfrn_id = '';
  1019. if ($perm) {
  1020. if ((($perm == 'rw') && (! intval($contact['writable'])))
  1021. || (($perm == 'r') && (intval($contact['writable'])))
  1022. ) {
  1023. q(
  1024. "update contact set writable = %d where id = %d",
  1025. intval(($perm == 'rw') ? 1 : 0),
  1026. intval($contact['id'])
  1027. );
  1028. $contact['writable'] = (string) 1 - intval($contact['writable']);
  1029. }
  1030. }
  1031. if (($contact['duplex'] && strlen($contact['pubkey']))
  1032. || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
  1033. || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
  1034. ) {
  1035. openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
  1036. openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
  1037. } else {
  1038. openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
  1039. openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
  1040. }
  1041. $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
  1042. if (strpos($final_dfrn_id, ':') == 1) {
  1043. $final_dfrn_id = substr($final_dfrn_id, 2);
  1044. }
  1045. if ($final_dfrn_id != $orig_id) {
  1046. logger('dfrn_deliver: wrong dfrn_id.');
  1047. // did not decode properly - cannot trust this site
  1048. Contact::markForArchival($contact);
  1049. return 3;
  1050. }
  1051. $postvars['dfrn_id'] = $idtosend;
  1052. $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
  1053. if ($dissolve) {
  1054. $postvars['dissolve'] = '1';
  1055. }
  1056. if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
  1057. $postvars['data'] = $atom;
  1058. $postvars['perm'] = 'rw';
  1059. } else {
  1060. $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
  1061. $postvars['perm'] = 'r';
  1062. }
  1063. $postvars['ssl_policy'] = $ssl_policy;
  1064. if ($page) {
  1065. $postvars['page'] = $page;
  1066. }
  1067. if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
  1068. logger('rino version: '. $rino_remote_version);
  1069. switch ($rino_remote_version) {
  1070. case 1:
  1071. $key = openssl_random_pseudo_bytes(16);
  1072. $data = self::aesEncrypt($postvars['data'], $key);
  1073. break;
  1074. default:
  1075. logger("rino: invalid requested version '$rino_remote_version'");
  1076. Contact::markForArchival($contact);
  1077. return -8;
  1078. }
  1079. $postvars['rino'] = $rino_remote_version;
  1080. $postvars['data'] = bin2hex($data);
  1081. if ($dfrn_version >= 2.1) {
  1082. if (($contact['duplex'] && strlen($contact['pubkey']))
  1083. || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
  1084. || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
  1085. ) {
  1086. openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
  1087. } else {
  1088. openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
  1089. }
  1090. } else {
  1091. if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
  1092. openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
  1093. } else {
  1094. openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
  1095. }
  1096. }
  1097. logger('md5 rawkey ' . md5($postvars['key']));
  1098. $postvars['key'] = bin2hex($postvars['key']);
  1099. }
  1100. logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
  1101. $xml = Network::post($contact['notify'], $postvars);
  1102. logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
  1103. $curl_stat = $a->get_curl_code();
  1104. if (empty($curl_stat) || empty($xml)) {
  1105. Contact::markForArchival($contact);
  1106. return -9; // timed out
  1107. }
  1108. if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
  1109. Contact::markForArchival($contact);
  1110. return -10;
  1111. }
  1112. if (strpos($xml, '<?xml') === false) {
  1113. logger('dfrn_deliver: phase 2: no valid XML returned');
  1114. logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
  1115. Contact::markForArchival($contact);
  1116. return 3;
  1117. }
  1118. $res = XML::parseString($xml);
  1119. if (!isset($res->status)) {
  1120. Contact::markForArchival($contact);
  1121. return -11;
  1122. }
  1123. // Possibly old servers had returned an empty value when everything was okay
  1124. if (empty($res->status)) {
  1125. $res->status = 200;
  1126. }
  1127. if (!empty($res->message)) {
  1128. logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
  1129. }
  1130. if (($res->status >= 200) && ($res->status <= 299)) {
  1131. Contact::unmarkForArchival($contact);
  1132. }
  1133. return intval($res->status);
  1134. }
  1135. /**
  1136. * @brief Transmits atom content to the contacts via the Diaspora transport layer
  1137. *
  1138. * @param array $owner Owner record
  1139. * @param array $contact Contact record of the receiver
  1140. * @param string $atom Content that will be transmitted
  1141. *
  1142. * @return int Deliver status. Negative values mean an error.
  1143. */
  1144. public static function transmit($owner, $contact, $atom, $public_batch = false)
  1145. {
  1146. $a = get_app();
  1147. if (!$public_batch) {
  1148. if (empty($contact['addr'])) {
  1149. logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
  1150. if (Contact::updateFromProbe($contact['id'])) {
  1151. $new_contact = dba::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
  1152. $contact['addr'] = $new_contact['addr'];
  1153. }
  1154. if (empty($contact['addr'])) {
  1155. logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
  1156. Contact::markForArchival($contact);
  1157. return -21;
  1158. }
  1159. }
  1160. $fcontact = Diaspora::personByHandle($contact['addr']);
  1161. if (empty($fcontact)) {
  1162. logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
  1163. Contact::markForArchival($contact);
  1164. return -22;
  1165. }
  1166. $pubkey = $fcontact['pubkey'];
  1167. } else {
  1168. $pubkey = '';
  1169. }
  1170. $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
  1171. // Create the endpoint for public posts. This is some WIP and should later be added to the probing
  1172. if ($public_batch && empty($contact["batch"])) {
  1173. $parts = parse_url($contact["notify"]);
  1174. $path_parts = explode('/', $parts['path']);
  1175. array_pop($path_parts);
  1176. $parts['path'] = implode('/', $path_parts);
  1177. $contact["batch"] = Network::unparseURL($parts);
  1178. }
  1179. $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
  1180. $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
  1181. $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
  1182. $curl_stat = $a->get_curl_code();
  1183. if (empty($curl_stat) || empty($xml)) {
  1184. logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
  1185. Contact::markForArchival($contact);
  1186. return -9; // timed out
  1187. }
  1188. if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
  1189. Contact::markForArchival($contact);
  1190. return -10;
  1191. }
  1192. if (strpos($xml, '<?xml') === false) {
  1193. logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
  1194. logger('Returned XML: ' . $xml, LOGGER_DATA);
  1195. Contact::markForArchival($contact);
  1196. return 3;
  1197. }
  1198. $res = XML::parseString($xml);
  1199. if (empty($res->status)) {
  1200. Contact::markForArchival($contact);
  1201. return -23;
  1202. }
  1203. if (!empty($res->message)) {
  1204. logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
  1205. }
  1206. if (($res->status >= 200) && ($res->status <= 299)) {
  1207. Contact::unmarkForArchival($contact);
  1208. }
  1209. return intval($res->status);
  1210. }
  1211. /**
  1212. * @brief Add new birthday event for this person
  1213. *
  1214. * @param array $contact Contact record
  1215. * @param string $birthday Birthday of the contact
  1216. * @return void
  1217. * @todo Add array type-hint for $contact
  1218. */
  1219. private static function birthdayEvent($contact, $birthday)
  1220. {
  1221. // Check for duplicates
  1222. $r = q(
  1223. "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
  1224. intval($contact['uid']),
  1225. intval($contact['id']),
  1226. dbesc(DateTimeFormat::utc($birthday)),
  1227. dbesc('birthday')
  1228. );
  1229. if (DBM::is_result($r)) {
  1230. return;
  1231. }
  1232. logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
  1233. $bdtext = L10n::t('%s\'s birthday', $contact['name']);
  1234. $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
  1235. $r = q(
  1236. "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
  1237. VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
  1238. intval($contact['uid']),
  1239. intval($contact['id']),
  1240. dbesc(DateTimeFormat::utcNow()),
  1241. dbesc(DateTimeFormat::utcNow()),
  1242. dbesc(DateTimeFormat::utc($birthday)),
  1243. dbesc(DateTimeFormat::utc($birthday . ' + 1 day ')),
  1244. dbesc($bdtext),
  1245. dbesc($bdtext2),
  1246. dbesc('birthday')
  1247. );
  1248. }
  1249. /**
  1250. * @brief Fetch the author data from head or entry items
  1251. *
  1252. * @param object $xpath XPath object
  1253. * @param object $context In which context should the data be searched
  1254. * @param array $importer Record of the importer user mixed with contact of the content
  1255. * @param string $element Element name from which the data is fetched
  1256. * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
  1257. * @param string $xml optional, default empty
  1258. *
  1259. * @return array Relevant data of the author
  1260. * @todo Find good type-hints for all parameter
  1261. */
  1262. private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
  1263. {
  1264. $author = [];
  1265. $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
  1266. $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
  1267. $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
  1268. 'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
  1269. $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
  1270. $importer["importer_uid"], normalise_link($author["link"]), NETWORK_STATUSNET];
  1271. $contact_old = dba::selectFirst('contact', $fields, $condition);
  1272. if (DBM::is_result($contact_old)) {
  1273. $author["contact-id"] = $contact_old["id"];
  1274. $author["network"] = $contact_old["network"];
  1275. } else {
  1276. if (!$onlyfetch) {
  1277. logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
  1278. }
  1279. $author["contact-id"] = $importer["id"];
  1280. $author["network"] = $importer["network"];
  1281. $onlyfetch = true;
  1282. }
  1283. // Until now we aren't serving different sizes - but maybe later
  1284. $avatarlist = [];
  1285. /// @todo check if "avatar" or "photo" would be the best field in the specification
  1286. $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
  1287. foreach ($avatars as $avatar) {
  1288. $href = "";
  1289. $width = 0;
  1290. foreach ($avatar->attributes as $attributes) {
  1291. /// @TODO Rewrite these similar if() to one switch
  1292. if ($attributes->name == "href") {
  1293. $href = $attributes->textContent;
  1294. }
  1295. if ($attributes->name == "width") {
  1296. $width = $attributes->textContent;
  1297. }
  1298. if ($attributes->name == "updated") {
  1299. $author["avatar-date"] = $attributes->textContent;
  1300. }
  1301. }
  1302. if (($width > 0) && ($href != "")) {
  1303. $avatarlist[$width] = $href;
  1304. }
  1305. }
  1306. if (count($avatarlist) > 0) {
  1307. krsort($avatarlist);
  1308. $author["avatar"] = current($avatarlist);
  1309. }
  1310. if (DBM::is_result($contact_old) && !$onlyfetch) {
  1311. logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
  1312. $poco = ["url" => $contact_old["url"]];
  1313. // When was the last change to name or uri?
  1314. $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
  1315. foreach ($name_element->attributes as $attributes) {
  1316. if ($attributes->name == "updated") {
  1317. $poco["name-date"] = $attributes->textContent;
  1318. }
  1319. }
  1320. $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
  1321. foreach ($link_element->attributes as $attributes) {
  1322. if ($attributes->name == "updated") {
  1323. $poco["uri-date"] = $attributes->textContent;
  1324. }
  1325. }
  1326. // Update contact data
  1327. $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
  1328. if ($value != "") {
  1329. $poco["addr"] = $value;
  1330. }
  1331. $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
  1332. if ($value != "") {
  1333. $poco["name"] = $value;
  1334. }
  1335. $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
  1336. if ($value != "") {
  1337. $poco["nick"] = $value;
  1338. }
  1339. $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
  1340. if ($value != "") {
  1341. $poco["about"] = $value;
  1342. }
  1343. $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
  1344. if ($value != "") {
  1345. $poco["location"] = $value;
  1346. }
  1347. /// @todo Only search for elements with "poco:type" = "xmpp"
  1348. $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
  1349. if ($value != "") {
  1350. $poco["xmpp"] = $value;
  1351. }
  1352. /// @todo Add support for the following fields that we don't support by now in the contact table:
  1353. /// - poco:utcOffset
  1354. /// - poco:urls
  1355. /// - poco:locality
  1356. /// - poco:region
  1357. /// - poco:country
  1358. // If the "hide" element is present then the profile isn't searchable.
  1359. $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
  1360. logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
  1361. // If the contact isn't searchable then set the contact to "hidden".
  1362. // Problem: This can be manually overridden by the user.
  1363. if ($hide) {
  1364. $contact_old["hidden"] = true;
  1365. }
  1366. // Save the keywords into the contact table
  1367. $tags = [];
  1368. $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
  1369. foreach ($tagelements as $tag) {
  1370. $tags[$tag->nodeValue] = $tag->nodeValue;
  1371. }
  1372. if (count($tags)) {
  1373. $poco["keywords"] = implode(", ", $tags);
  1374. }
  1375. // "dfrn:birthday" contains the birthday converted to UTC
  1376. $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
  1377. if (strtotime($birthday) > time()) {
  1378. $bd_timestamp = strtotime($birthday);
  1379. $poco["bdyear"] = date("Y", $bd_timestamp);
  1380. }
  1381. // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
  1382. $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
  1383. if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
  1384. $bdyear = date("Y");
  1385. $value = str_replace("0000", $bdyear, $value);
  1386. if (strtotime($value) < time()) {
  1387. $value = str_replace($bdyear, $bdyear + 1, $value);
  1388. $bdyear = $bdyear + 1;
  1389. }
  1390. $poco["bd"] = $value;
  1391. }
  1392. $contact = array_merge($contact_old, $poco);
  1393. if ($contact_old["bdyear"] != $contact["bdyear"]) {
  1394. self::birthdayEvent($contact, $birthday);
  1395. }
  1396. // Get all field names
  1397. $fields = [];
  1398. foreach ($contact_old as $field => $data) {
  1399. $fields[$field] = $data;
  1400. }
  1401. unset($fields["id"]);
  1402. unset($fields["uid"]);
  1403. unset($fields["url"]);
  1404. unset($fields["avatar-date"]);
  1405. unset($fields["avatar"]);
  1406. unset($fields["name-date"]);
  1407. unset($fields["uri-date"]);
  1408. $update = false;
  1409. // Update check for this field has to be done differently
  1410. $datefields = ["name-date", "uri-date"];
  1411. foreach ($datefields as $field) {
  1412. if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
  1413. logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
  1414. $update = true;
  1415. }
  1416. }
  1417. foreach ($fields as $field => $data) {
  1418. if ($contact[$field] != $contact_old[$field]) {
  1419. logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
  1420. $update = true;
  1421. }
  1422. }
  1423. if ($update) {
  1424. logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
  1425. q(
  1426. "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
  1427. `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
  1428. `xmpp` = '%s', `name-date` = '%s', `uri-date` = '%s'
  1429. WHERE `id` = %d AND `network` = '%s'",
  1430. dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
  1431. dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
  1432. dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
  1433. dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
  1434. intval($contact["id"]), dbesc($contact["network"])
  1435. );
  1436. }
  1437. Contact::updateAvatar(
  1438. $author['avatar'],
  1439. $importer['importer_uid'],
  1440. $contact['id'],
  1441. (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
  1442. );
  1443. /*
  1444. * The generation is a sign for the reliability of the provided data.
  1445. * It is used in the socgraph.php to prevent that old contact data
  1446. * that was relayed over several servers can overwrite contact
  1447. * data that we received directly.
  1448. */
  1449. $poco["generation"] = 2;
  1450. $poco["photo"] = $author["avatar"];
  1451. $poco["hide"] = $hide;
  1452. $poco["contact-type"] = $contact["contact-type"];
  1453. $gcid = GContact::update($poco);
  1454. GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
  1455. }
  1456. return $author;
  1457. }
  1458. /**
  1459. * @brief Transforms activity objects into an XML string
  1460. *
  1461. * @param object $xpath XPath object
  1462. * @param object $activity Activity object
  1463. * @param string $element element name
  1464. *
  1465. * @return string XML string
  1466. * @todo Find good type-hints for all parameter
  1467. */
  1468. private static function transformActivity($xpath, $activity, $element)
  1469. {
  1470. if (!is_object($activity)) {
  1471. return "";
  1472. }
  1473. $obj_doc = new DOMDocument("1.0", "utf-8");
  1474. $obj_doc->formatOutput = true;
  1475. $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
  1476. $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
  1477. XML::addElement($obj_doc, $obj_element, "type", $activity_type);
  1478. $id = $xpath->query("atom:id", $activity)->item(0);
  1479. if (is_object($id)) {
  1480. $obj_element->appendChild($obj_doc->importNode($id, true));
  1481. }
  1482. $title = $xpath->query("atom:title", $activity)->item(0);
  1483. if (is_object($title)) {
  1484. $obj_element->appendChild($obj_doc->importNode($title, true));
  1485. }
  1486. $links = $xpath->query("atom:link", $activity);
  1487. if (is_object($links)) {
  1488. foreach ($links as $link) {
  1489. $obj_element->appendChild($obj_doc->importNode($link, true));
  1490. }
  1491. }
  1492. $content = $xpath->query("atom:content", $activity)->item(0);
  1493. if (is_object($content)) {
  1494. $obj_element->appendChild($obj_doc->importNode($content, true));
  1495. }
  1496. $obj_doc->appendChild($obj_element);
  1497. $objxml = $obj_doc->saveXML($obj_element);
  1498. /// @todo This isn't totally clean. We should find a way to transform the namespaces
  1499. $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
  1500. return($objxml);
  1501. }
  1502. /**
  1503. * @brief Processes the mail elements
  1504. *
  1505. * @param object $xpath XPath object
  1506. * @param object $mail mail elements
  1507. * @param array $importer Record of the importer user mixed with contact of the content
  1508. * @return void
  1509. * @todo Find good type-hints for all parameter
  1510. */
  1511. private static function processMail($xpath, $mail, $importer)
  1512. {
  1513. logger("Processing mails");
  1514. /// @TODO Rewrite this to one statement
  1515. $msg = [];
  1516. $msg["uid"] = $importer["importer_uid"];
  1517. $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
  1518. $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
  1519. $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
  1520. $msg["contact-id"] = $importer["id"];
  1521. $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
  1522. $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
  1523. $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
  1524. $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
  1525. $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
  1526. $msg["seen"] = 0;
  1527. $msg["replied"] = 0;
  1528. dba::insert('mail', $msg);
  1529. // send notifications.
  1530. /// @TODO Arange this mess
  1531. $notif_params = [
  1532. "type" => NOTIFY_MAIL,
  1533. "notify_flags" => $importer["notify-flags"],
  1534. "language" => $importer["language"],
  1535. "to_name" => $importer["username"],
  1536. "to_email" => $importer["email"],
  1537. "uid" => $importer["importer_uid"],
  1538. "item" => $msg,
  1539. "source_name" => $msg["from-name"],
  1540. "source_link" => $importer["url"],
  1541. "source_photo" => $importer["thumb"],
  1542. "verb" => ACTIVITY_POST,
  1543. "otype" => "mail"
  1544. ];
  1545. notification($notif_params);
  1546. logger("Mail is processed, notification was sent.");
  1547. }
  1548. /**
  1549. * @brief Processes the suggestion elements
  1550. *
  1551. * @param object $xpath XPath object
  1552. * @param object $suggestion suggestion elements
  1553. * @param array $importer Record of the importer user mixed with contact of the content
  1554. * @return boolean
  1555. * @todo Find good type-hints for all parameter
  1556. */
  1557. private static function processSuggestion($xpath, $suggestion, $importer)
  1558. {
  1559. $a = get_app();
  1560. logger("Processing suggestions");
  1561. /// @TODO Rewrite this to one statement
  1562. $suggest = [];
  1563. $suggest["uid"] = $importer["importer_uid"];
  1564. $suggest["cid"] = $importer["id"];
  1565. $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
  1566. $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
  1567. $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
  1568. $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
  1569. $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
  1570. // Does our member already have a friend matching this description?
  1571. $r = q(
  1572. "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
  1573. dbesc($suggest["name"]),
  1574. dbesc(normalise_link($suggest["url"])),
  1575. intval($suggest["uid"])
  1576. );
  1577. /*
  1578. * The valid result means the friend we're about to send a friend
  1579. * suggestion already has them in their contact, which means no further
  1580. * action is required.
  1581. *
  1582. * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
  1583. */
  1584. if (DBM::is_result($r)) {
  1585. return false;
  1586. }
  1587. // Do we already have an fcontact record for this person?
  1588. $fid = 0;
  1589. $r = q(
  1590. "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
  1591. dbesc($suggest["url"]),
  1592. dbesc($suggest["name"]),
  1593. dbesc($suggest["request"])
  1594. );
  1595. if (DBM::is_result($r)) {
  1596. $fid = $r[0]["id"];
  1597. // OK, we do. Do we already have an introduction for this person ?
  1598. $r = q(
  1599. "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
  1600. intval($suggest["uid"]),
  1601. intval($fid)
  1602. );
  1603. /*
  1604. * The valid result means the friend we're about to send a friend
  1605. * suggestion already has them in their contact, which means no further
  1606. * action is required.
  1607. *
  1608. * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
  1609. */
  1610. if (DBM::is_result($r)) {
  1611. return false;
  1612. }
  1613. }
  1614. if (!$fid) {
  1615. $r = q(
  1616. "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
  1617. dbesc($suggest["name"]),
  1618. dbesc($suggest["url"]),
  1619. dbesc($suggest["photo"]),
  1620. dbesc($suggest["request"])
  1621. );
  1622. }
  1623. $r = q(
  1624. "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
  1625. dbesc($suggest["url"]),
  1626. dbesc($suggest["name"]),
  1627. dbesc($suggest["request"])
  1628. );
  1629. /*
  1630. * If no record in fcontact is found, below INSERT statement will not
  1631. * link an introduction to it.
  1632. */
  1633. if (!DBM::is_result($r)) {
  1634. // database record did not get created. Quietly give up.
  1635. killme();
  1636. }
  1637. $fid = $r[0]["id"];
  1638. $hash = random_string();
  1639. $r = q(
  1640. "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
  1641. VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
  1642. intval($suggest["uid"]),
  1643. intval($fid),
  1644. intval($suggest["cid"]),
  1645. dbesc($suggest["body"]),
  1646. dbesc($hash),
  1647. dbesc(DateTimeFormat::utcNow()),
  1648. intval(0)
  1649. );
  1650. notification(
  1651. [
  1652. "type" => NOTIFY_SUGGEST,
  1653. "notify_flags" => $importer["notify-flags"],
  1654. "language" => $importer["language"],
  1655. "to_name" => $importer["username"],
  1656. "to_email" => $importer["email"],
  1657. "uid" => $importer["importer_uid"],
  1658. "item" => $suggest,
  1659. "link" => System::baseUrl()."/notifications/intros",
  1660. "source_name" => $importer["name"],
  1661. "source_link" => $importer["url"],
  1662. "source_photo" => $importer["photo"],
  1663. "verb" => ACTIVITY_REQ_FRIEND,
  1664. "otype" => "intro"]
  1665. );
  1666. return true;
  1667. }
  1668. /**
  1669. * @brief Processes the relocation elements
  1670. *
  1671. * @param object $xpath XPath object
  1672. * @param object $relocation relocation elements
  1673. * @param array $importer Record of the importer user mixed with contact of the content
  1674. * @return boolean
  1675. * @todo Find good type-hints for all parameter
  1676. */
  1677. private static function processRelocation($xpath, $relocation, $importer)
  1678. {
  1679. logger("Processing relocations");
  1680. /// @TODO Rewrite this to one statement
  1681. $relocate = [];
  1682. $relocate["uid"] = $importer["importer_uid"];
  1683. $relocate["cid"] = $importer["id"];
  1684. $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
  1685. $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
  1686. $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
  1687. $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
  1688. $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
  1689. $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
  1690. $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
  1691. $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
  1692. $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
  1693. $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
  1694. $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
  1695. $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
  1696. if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
  1697. $relocate["avatar"] = $relocate["photo"];
  1698. }
  1699. if ($relocate["addr"] == "") {
  1700. $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
  1701. }
  1702. // update contact
  1703. $r = q(
  1704. "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
  1705. intval($importer["id"]),
  1706. intval($importer["importer_uid"])
  1707. );
  1708. if (!DBM::is_result($r)) {
  1709. logger("Query failed to execute, no result returned in " . __FUNCTION__);
  1710. return false;
  1711. }
  1712. $old = $r[0];
  1713. // Update the gcontact entry
  1714. $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
  1715. $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
  1716. 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
  1717. 'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
  1718. 'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
  1719. dba::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
  1720. // Update the contact table. We try to find every entry.
  1721. $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
  1722. 'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
  1723. 'addr' => $relocate["addr"], 'request' => $relocate["request"],
  1724. 'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
  1725. 'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
  1726. $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
  1727. dba::update('contact', $fields, $condition);
  1728. Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
  1729. logger('Contacts are updated.');
  1730. // update items
  1731. // This is an extreme performance killer
  1732. Item::update(['owner-link' => $relocate["url"]], ['owner-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
  1733. Item::update(['author-link' => $relocate["url"]], ['author-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
  1734. logger('Items are updated.');
  1735. /// @TODO
  1736. /// merge with current record, current contents have priority
  1737. /// update record, set url-updated
  1738. /// update profile photos
  1739. /// schedule a scan?
  1740. return true;
  1741. }
  1742. /**
  1743. * @brief Updates an item
  1744. *
  1745. * @param array $current the current item record
  1746. * @param array $item the new item record
  1747. * @param array $importer Record of the importer user mixed with contact of the content
  1748. * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
  1749. * @return mixed
  1750. * @todo set proper type-hints (array?)
  1751. */
  1752. private static function updateContent($current, $item, $importer, $entrytype)
  1753. {
  1754. $changed = false;
  1755. if (self::isEditedTimestampNewer($current, $item)) {
  1756. // do not accept (ignore) an earlier edit than one we currently have.
  1757. if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
  1758. return false;
  1759. }
  1760. $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
  1761. 'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
  1762. 'edited' => DateTimeFormat::utc($item["edited"])];
  1763. $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
  1764. Item::update($fields, $condition);
  1765. $changed = true;
  1766. }
  1767. return $changed;
  1768. }
  1769. /**
  1770. * @brief Detects the entry type of the item
  1771. *
  1772. * @param array $importer Record of the importer user mixed with contact of the content
  1773. * @param array $item the new item record
  1774. *
  1775. * @return int Is it a toplevel entry, a comment or a relayed comment?
  1776. * @todo set proper type-hints (array?)
  1777. */
  1778. private static function getEntryType($importer, $item)
  1779. {
  1780. if ($item["parent-uri"] != $item["uri"]) {
  1781. $community = false;
  1782. if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
  1783. $sql_extra = "";
  1784. $community = true;
  1785. logger("possible community action");
  1786. } else {
  1787. $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
  1788. }
  1789. // was the top-level post for this action written by somebody on this site?
  1790. // Specifically, the recipient?
  1791. $is_a_remote_action = false;
  1792. $r = q(
  1793. "SELECT `item`.`parent-uri` FROM `item`
  1794. WHERE `item`.`uri` = '%s'
  1795. LIMIT 1",
  1796. dbesc($item["parent-uri"])
  1797. );
  1798. if (DBM::is_result($r)) {
  1799. $r = q(
  1800. "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
  1801. INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
  1802. WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
  1803. AND `item`.`uid` = %d
  1804. $sql_extra
  1805. LIMIT 1",
  1806. dbesc($r[0]["parent-uri"]),
  1807. dbesc($r[0]["parent-uri"]),
  1808. dbesc($r[0]["parent-uri"]),
  1809. intval($importer["importer_uid"])
  1810. );
  1811. if (DBM::is_result($r)) {
  1812. $is_a_remote_action = true;
  1813. }
  1814. }
  1815. /*
  1816. * Does this have the characteristics of a community or private group action?
  1817. * If it's an action to a wall post on a community/prvgroup page it's a
  1818. * valid community action. Also forum_mode makes it valid for sure.
  1819. * If neither, it's not.
  1820. */
  1821. if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
  1822. $is_a_remote_action = false;
  1823. logger("not a community action");
  1824. }
  1825. if ($is_a_remote_action) {
  1826. return DFRN::REPLY_RC;
  1827. } else {
  1828. return DFRN::REPLY;
  1829. }
  1830. } else {
  1831. return DFRN::TOP_LEVEL;
  1832. }
  1833. }
  1834. /**
  1835. * @brief Send a "poke"
  1836. *
  1837. * @param array $item the new item record
  1838. * @param array $importer Record of the importer user mixed with contact of the content
  1839. * @param int $posted_id The record number of item record that was just posted
  1840. * @return void
  1841. * @todo set proper type-hints (array?)
  1842. */
  1843. private static function doPoke($item, $importer, $posted_id)
  1844. {
  1845. $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
  1846. if (!$verb) {
  1847. return;
  1848. }
  1849. $xo = XML::parseString($item["object"], false);
  1850. if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
  1851. // somebody was poked/prodded. Was it me?
  1852. foreach ($xo->link as $l) {
  1853. $atts = $l->attributes();
  1854. switch ($atts["rel"]) {
  1855. case "alternate":
  1856. $Blink = $atts["href"];
  1857. break;
  1858. default:
  1859. break;
  1860. }
  1861. }
  1862. if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
  1863. $author = dba::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
  1864. // send a notification
  1865. notification(
  1866. [
  1867. "type" => NOTIFY_POKE,
  1868. "notify_flags" => $importer["notify-flags"],
  1869. "language" => $importer["language"],
  1870. "to_name" => $importer["username"],
  1871. "to_email" => $importer["email"],
  1872. "uid" => $importer["importer_uid"],
  1873. "item" => $item,
  1874. "link" => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
  1875. "source_name" => $author["name"],
  1876. "source_link" => $author["url"],
  1877. "source_photo" => $author["thumb"],
  1878. "verb" => $item["verb"],
  1879. "otype" => "person",
  1880. "activity" => $verb,
  1881. "parent" => $item["parent"]]
  1882. );
  1883. }
  1884. }
  1885. }
  1886. /**
  1887. * @brief Processes several actions, depending on the verb
  1888. *
  1889. * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
  1890. * @param array $importer Record of the importer user mixed with contact of the content
  1891. * @param array $item the new item record
  1892. * @param bool $is_like Is the verb a "like"?
  1893. *
  1894. * @return bool Should the processing of the entries be continued?
  1895. * @todo set proper type-hints (array?)
  1896. */
  1897. private static function processVerbs($entrytype, $importer, &$item, &$is_like)
  1898. {
  1899. logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
  1900. if (($entrytype == DFRN::TOP_LEVEL)) {
  1901. // The filling of the the "contact" variable is done for legcy reasons
  1902. // The functions below are partly used by ostatus.php as well - where we have this variable
  1903. $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
  1904. $contact = $r[0];
  1905. $nickname = $contact["nick"];
  1906. // Big question: Do we need these functions? They were part of the "consume_feed" function.
  1907. // This function once was responsible for DFRN and OStatus.
  1908. if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
  1909. logger("New follower");
  1910. Contact::addRelationship($importer, $contact, $item, $nickname);
  1911. return false;
  1912. }
  1913. if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
  1914. logger("Lost follower");
  1915. Contact::removeFollower($importer, $contact, $item);
  1916. return false;
  1917. }
  1918. if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
  1919. logger("New friend request");
  1920. Contact::addRelationship($importer, $contact, $item, $nickname, true);
  1921. return false;
  1922. }
  1923. if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
  1924. logger("Lost sharer");
  1925. Contact::removeSharer($importer, $contact, $item);
  1926. return false;
  1927. }
  1928. } else {
  1929. if (($item["verb"] == ACTIVITY_LIKE)
  1930. || ($item["verb"] == ACTIVITY_DISLIKE)
  1931. || ($item["verb"] == ACTIVITY_ATTEND)
  1932. || ($item["verb"] == ACTIVITY_ATTENDNO)
  1933. || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
  1934. ) {
  1935. $is_like = true;
  1936. $item["type"] = "activity";
  1937. $item["gravity"] = GRAVITY_LIKE;
  1938. // only one like or dislike per person
  1939. // splitted into two queries for performance issues
  1940. $r = q(
  1941. "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-id` = %d AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
  1942. intval($item["uid"]),
  1943. intval($item["author-id"]),
  1944. dbesc($item["verb"]),
  1945. dbesc($item["parent-uri"])
  1946. );
  1947. if (DBM::is_result($r)) {
  1948. return false;
  1949. }
  1950. $r = q(
  1951. "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-id` = %d AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
  1952. intval($item["uid"]),
  1953. intval($item["author-id"]),
  1954. dbesc($item["verb"]),
  1955. dbesc($item["parent-uri"])
  1956. );
  1957. if (DBM::is_result($r)) {
  1958. return false;
  1959. }
  1960. } else {
  1961. $is_like = false;
  1962. }
  1963. if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
  1964. $xo = XML::parseString($item["object"], false);
  1965. $xt = XML::parseString($item["target"], false);
  1966. if ($xt->type == ACTIVITY_OBJ_NOTE) {
  1967. $r = q(
  1968. "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  1969. dbesc($xt->id),
  1970. intval($importer["importer_uid"])
  1971. );
  1972. if (!DBM::is_result($r)) {
  1973. logger("Query failed to execute, no result returned in " . __FUNCTION__);
  1974. return false;
  1975. }
  1976. // extract tag, if not duplicate, add to parent item
  1977. if ($xo->content) {
  1978. if (!stristr($r[0]["tag"], trim($xo->content))) {
  1979. $tag = $r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
  1980. Item::update(['tag' => $tag], ['id' => $r[0]["id"]]);
  1981. }
  1982. }
  1983. }
  1984. }
  1985. }
  1986. return true;
  1987. }
  1988. /**
  1989. * @brief Processes the link elements
  1990. *
  1991. * @param object $links link elements
  1992. * @param array $item the item record
  1993. * @return void
  1994. * @todo set proper type-hints
  1995. */
  1996. private static function parseLinks($links, &$item)
  1997. {
  1998. $rel = "";
  1999. $href = "";
  2000. $type = "";
  2001. $length = "0";
  2002. $title = "";
  2003. foreach ($links as $link) {
  2004. foreach ($link->attributes as $attributes) {
  2005. switch ($attributes->name) {
  2006. case "href" : $href = $attributes->textContent; break;
  2007. case "rel" : $rel = $attributes->textContent; break;
  2008. case "type" : $type = $attributes->textContent; break;
  2009. case "length": $length = $attributes->textContent; break;
  2010. case "title" : $title = $attributes->textContent; break;
  2011. }
  2012. }
  2013. if (($rel != "") && ($href != "")) {
  2014. switch ($rel) {
  2015. case "alternate":
  2016. $item["plink"] = $href;
  2017. break;
  2018. case "enclosure":
  2019. $enclosure = $href;
  2020. if (strlen($item["attach"])) {
  2021. $item["attach"] .= ",";
  2022. }
  2023. $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
  2024. break;
  2025. }
  2026. }
  2027. }
  2028. }
  2029. /**
  2030. * @brief Processes the entry elements which contain the items and comments
  2031. *
  2032. * @param array $header Array of the header elements that always stay the same
  2033. * @param object $xpath XPath object
  2034. * @param object $entry entry elements
  2035. * @param array $importer Record of the importer user mixed with contact of the content
  2036. * @param object $xml xml
  2037. * @return void
  2038. * @todo Add type-hints
  2039. */
  2040. private static function processEntry($header, $xpath, $entry, $importer, $xml)
  2041. {
  2042. logger("Processing entries");
  2043. $item = $header;
  2044. $item["protocol"] = PROTOCOL_DFRN;
  2045. $item["source"] = $xml;
  2046. // Get the uri
  2047. $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
  2048. $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
  2049. $current = dba::selectFirst('item',
  2050. ['id', 'uid', 'edited', 'body'],
  2051. ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
  2052. );
  2053. // Is there an existing item?
  2054. if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
  2055. logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
  2056. return;
  2057. }
  2058. // Fetch the owner
  2059. $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
  2060. $item["owner-link"] = $owner["link"];
  2061. $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
  2062. // fetch the author
  2063. $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
  2064. $item["author-link"] = $author["link"];
  2065. $item["author-id"] = Contact::getIdForURL($author["link"], 0);
  2066. $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
  2067. $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
  2068. $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
  2069. $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
  2070. // make sure nobody is trying to sneak some html tags by us
  2071. $item["body"] = notags(base64url_decode($item["body"]));
  2072. $item["body"] = BBCode::limitBodySize($item["body"]);
  2073. /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
  2074. if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
  2075. $base_url = get_app()->get_baseurl();
  2076. $item['body'] = reltoabs($item['body'], $base_url);
  2077. $item['body'] = html2bb_video($item['body']);
  2078. $item['body'] = OEmbed::HTML2BBCode($item['body']);
  2079. $config = HTMLPurifier_Config::createDefault();
  2080. $config->set('Cache.DefinitionImpl', null);
  2081. // we shouldn't need a whitelist, because the bbcode converter
  2082. // will strip out any unsupported tags.
  2083. $purifier = new HTMLPurifier($config);
  2084. $item['body'] = $purifier->purify($item['body']);
  2085. $item['body'] = @HTML::toBBCode($item['body']);
  2086. }
  2087. /// @todo We should check for a repeated post and if we know the repeated author.
  2088. // We don't need the content element since "dfrn:env" is always present
  2089. //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
  2090. $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
  2091. $georsspoint = $xpath->query("georss:point", $entry);
  2092. if ($georsspoint) {
  2093. $item["coord"] = $georsspoint->item(0)->nodeValue;
  2094. }
  2095. $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
  2096. $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
  2097. if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
  2098. $item["bookmark"] = true;
  2099. }
  2100. $notice_info = $xpath->query("statusnet:notice_info", $entry);
  2101. if ($notice_info && ($notice_info->length > 0)) {
  2102. foreach ($notice_info->item(0)->attributes as $attributes) {
  2103. if ($attributes->name == "source") {
  2104. $item["app"] = strip_tags($attributes->textContent);
  2105. }
  2106. }
  2107. }
  2108. $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
  2109. // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
  2110. $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
  2111. if ($dsprsig != "") {
  2112. $item["dsprsig"] = $dsprsig;
  2113. }
  2114. $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
  2115. if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
  2116. $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
  2117. }
  2118. $object = $xpath->query("activity:object", $entry)->item(0);
  2119. $item["object"] = self::transformActivity($xpath, $object, "object");
  2120. if (trim($item["object"]) != "") {
  2121. $r = XML::parseString($item["object"], false);
  2122. if (isset($r->type)) {
  2123. $item["object-type"] = $r->type;
  2124. }
  2125. }
  2126. $target = $xpath->query("activity:target", $entry)->item(0);
  2127. $item["target"] = self::transformActivity($xpath, $target, "target");
  2128. $categories = $xpath->query("atom:category", $entry);
  2129. if ($categories) {
  2130. foreach ($categories as $category) {
  2131. $term = "";
  2132. $scheme = "";
  2133. foreach ($category->attributes as $attributes) {
  2134. if ($attributes->name == "term") {
  2135. $term = $attributes->textContent;
  2136. }
  2137. if ($attributes->name == "scheme") {
  2138. $scheme = $attributes->textContent;
  2139. }
  2140. }
  2141. if (($term != "") && ($scheme != "")) {
  2142. $parts = explode(":", $scheme);
  2143. if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
  2144. $termhash = array_shift($parts);
  2145. $termurl = implode(":", $parts);
  2146. if (strlen($item["tag"])) {
  2147. $item["tag"] .= ",";
  2148. }
  2149. $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
  2150. }
  2151. }
  2152. }
  2153. }
  2154. $enclosure = "";
  2155. $links = $xpath->query("atom:link", $entry);
  2156. if ($links) {
  2157. self::parseLinks($links, $item);
  2158. }
  2159. $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
  2160. $conv = $xpath->query('ostatus:conversation', $entry);
  2161. if (is_object($conv->item(0))) {
  2162. foreach ($conv->item(0)->attributes as $attributes) {
  2163. if ($attributes->name == "ref") {
  2164. $item['conversation-uri'] = $attributes->textContent;
  2165. }
  2166. if ($attributes->name == "href") {
  2167. $item['conversation-href'] = $attributes->textContent;
  2168. }
  2169. }
  2170. }
  2171. // Is it a reply or a top level posting?
  2172. $item["parent-uri"] = $item["uri"];
  2173. $inreplyto = $xpath->query("thr:in-reply-to", $entry);
  2174. if (is_object($inreplyto->item(0))) {
  2175. foreach ($inreplyto->item(0)->attributes as $attributes) {
  2176. if ($attributes->name == "ref") {
  2177. $item["parent-uri"] = $attributes->textContent;
  2178. }
  2179. }
  2180. }
  2181. // Get the type of the item (Top level post, reply or remote reply)
  2182. $entrytype = self::getEntryType($importer, $item);
  2183. // Now assign the rest of the values that depend on the type of the message
  2184. if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
  2185. if (!isset($item["object-type"])) {
  2186. $item["object-type"] = ACTIVITY_OBJ_COMMENT;
  2187. }
  2188. if ($item["contact-id"] != $owner["contact-id"]) {
  2189. $item["contact-id"] = $owner["contact-id"];
  2190. }
  2191. if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
  2192. $item["network"] = $owner["network"];
  2193. }
  2194. if ($item["contact-id"] != $author["contact-id"]) {
  2195. $item["contact-id"] = $author["contact-id"];
  2196. }
  2197. if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
  2198. $item["network"] = $author["network"];
  2199. }
  2200. }
  2201. if ($entrytype == DFRN::REPLY_RC) {
  2202. $item["type"] = "remote-comment";
  2203. $item["wall"] = 1;
  2204. } elseif ($entrytype == DFRN::TOP_LEVEL) {
  2205. if (!isset($item["object-type"])) {
  2206. $item["object-type"] = ACTIVITY_OBJ_NOTE;
  2207. }
  2208. // Is it an event?
  2209. if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
  2210. logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
  2211. $ev = Event::fromBBCode($item["body"]);
  2212. if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
  2213. logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
  2214. $ev["cid"] = $importer["id"];
  2215. $ev["uid"] = $importer["importer_uid"];
  2216. $ev["uri"] = $item["uri"];
  2217. $ev["edited"] = $item["edited"];
  2218. $ev["private"] = $item["private"];
  2219. $ev["guid"] = $item["guid"];
  2220. $r = q(
  2221. "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
  2222. dbesc($item["uri"]),
  2223. intval($importer["importer_uid"])
  2224. );
  2225. if (DBM::is_result($r)) {
  2226. $ev["id"] = $r[0]["id"];
  2227. }
  2228. $event_id = Event::store($ev);
  2229. logger("Event ".$event_id." was stored", LOGGER_DEBUG);
  2230. return;
  2231. }
  2232. }
  2233. }
  2234. if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
  2235. logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
  2236. return;
  2237. }
  2238. // Update content if 'updated' changes
  2239. if (DBM::is_result($current)) {
  2240. if (self::updateContent($current, $item, $importer, $entrytype)) {
  2241. logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
  2242. } else {
  2243. logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
  2244. }
  2245. return;
  2246. }
  2247. if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
  2248. $posted_id = Item::insert($item);
  2249. $parent = 0;
  2250. if ($posted_id) {
  2251. logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
  2252. if ($item['uid'] == 0) {
  2253. Item::distribute($posted_id);
  2254. }
  2255. return true;
  2256. }
  2257. } else { // $entrytype == DFRN::TOP_LEVEL
  2258. if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
  2259. logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
  2260. return;
  2261. }
  2262. if (!link_compare($item["owner-link"], $importer["url"])) {
  2263. /*
  2264. * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
  2265. * but otherwise there's a possible data mixup on the sender's system.
  2266. * the tgroup delivery code called from Item::insert will correct it if it's a forum,
  2267. * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
  2268. */
  2269. logger('Correcting item owner.', LOGGER_DEBUG);
  2270. $item["owner-link"] = $importer["url"];
  2271. $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
  2272. }
  2273. if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
  2274. logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
  2275. return;
  2276. }
  2277. // This is my contact on another system, but it's really me.
  2278. // Turn this into a wall post.
  2279. $notify = Item::isRemoteSelf($importer, $item);
  2280. $posted_id = Item::insert($item, false, $notify);
  2281. if ($notify) {
  2282. $posted_id = $notify;
  2283. }
  2284. logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
  2285. if ($item['uid'] == 0) {
  2286. Item::distribute($posted_id);
  2287. }
  2288. if (stristr($item["verb"], ACTIVITY_POKE)) {
  2289. self::doPoke($item, $importer, $posted_id);
  2290. }
  2291. }
  2292. }
  2293. /**
  2294. * @brief Deletes items
  2295. *
  2296. * @param object $xpath XPath object
  2297. * @param object $deletion deletion elements
  2298. * @param array $importer Record of the importer user mixed with contact of the content
  2299. * @return void
  2300. * @todo set proper type-hints
  2301. */
  2302. private static function processDeletion($xpath, $deletion, $importer)
  2303. {
  2304. logger("Processing deletions");
  2305. $uri = null;
  2306. foreach ($deletion->attributes as $attributes) {
  2307. if ($attributes->name == "ref") {
  2308. $uri = $attributes->textContent;
  2309. }
  2310. }
  2311. if (!$uri || !$importer["id"]) {
  2312. return false;
  2313. }
  2314. $condition = ["`uri` = ? AND `uid` = ? AND NOT `file` LIKE '%[%'", $uri, $importer["importer_uid"]];
  2315. $item = dba::selectFirst('item', ['id', 'parent', 'contact-id'], $condition);
  2316. if (!DBM::is_result($item)) {
  2317. logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
  2318. return;
  2319. }
  2320. // When it is a starting post it has to belong to the person that wants to delete it
  2321. if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
  2322. logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
  2323. return;
  2324. }
  2325. // Comments can be deleted by the thread owner or comment owner
  2326. if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
  2327. $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
  2328. if (!dba::exists('item', $condition)) {
  2329. logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
  2330. return;
  2331. }
  2332. }
  2333. if ($item["deleted"]) {
  2334. return;
  2335. }
  2336. logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
  2337. Item::delete(['id' => $item['id']]);
  2338. }
  2339. /**
  2340. * @brief Imports a DFRN message
  2341. *
  2342. * @param string $xml The DFRN message
  2343. * @param array $importer Record of the importer user mixed with contact of the content
  2344. * @param bool $sort_by_date Is used when feeds are polled
  2345. * @return integer Import status
  2346. * @todo set proper type-hints
  2347. */
  2348. public static function import($xml, $importer, $sort_by_date = false)
  2349. {
  2350. if ($xml == "") {
  2351. return 400;
  2352. }
  2353. $doc = new DOMDocument();
  2354. @$doc->loadXML($xml);
  2355. $xpath = new DOMXPath($doc);
  2356. $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
  2357. $xpath->registerNamespace("thr", NAMESPACE_THREAD);
  2358. $xpath->registerNamespace("at", NAMESPACE_TOMB);
  2359. $xpath->registerNamespace("media", NAMESPACE_MEDIA);
  2360. $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
  2361. $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
  2362. $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
  2363. $xpath->registerNamespace("poco", NAMESPACE_POCO);
  2364. $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
  2365. $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
  2366. $header = [];
  2367. $header["uid"] = $importer["importer_uid"];
  2368. $header["network"] = NETWORK_DFRN;
  2369. $header["type"] = "remote";
  2370. $header["wall"] = 0;
  2371. $header["origin"] = 0;
  2372. $header["contact-id"] = $importer["id"];
  2373. // Update the contact table if the data has changed
  2374. // The "atom:author" is only present in feeds
  2375. if ($xpath->query("/atom:feed/atom:author")->length > 0) {
  2376. self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
  2377. }
  2378. // Only the "dfrn:owner" in the head section contains all data
  2379. if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
  2380. self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
  2381. }
  2382. logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
  2383. // is it a public forum? Private forums aren't exposed with this method
  2384. $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
  2385. // The account type is new since 3.5.1
  2386. if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
  2387. $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
  2388. if ($accounttype != $importer["contact-type"]) {
  2389. dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
  2390. }
  2391. // A forum contact can either have set "forum" or "prv" - but not both
  2392. if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
  2393. $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
  2394. dba::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
  2395. }
  2396. } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
  2397. $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
  2398. dba::update('contact', ['forum' => $forum], $condition);
  2399. }
  2400. // We are processing relocations even if we are ignoring a contact
  2401. $relocations = $xpath->query("/atom:feed/dfrn:relocate");
  2402. foreach ($relocations as $relocation) {
  2403. self::processRelocation($xpath, $relocation, $importer);
  2404. }
  2405. if (($importer["uid"] != 0) && !$importer["readonly"]) {
  2406. $mails = $xpath->query("/atom:feed/dfrn:mail");
  2407. foreach ($mails as $mail) {
  2408. self::processMail($xpath, $mail, $importer);
  2409. }
  2410. $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
  2411. foreach ($suggestions as $suggestion) {
  2412. self::processSuggestion($xpath, $suggestion, $importer);
  2413. }
  2414. }
  2415. $deletions = $xpath->query("/atom:feed/at:deleted-entry");
  2416. foreach ($deletions as $deletion) {
  2417. self::processDeletion($xpath, $deletion, $importer);
  2418. }
  2419. if (!$sort_by_date) {
  2420. $entries = $xpath->query("/atom:feed/atom:entry");
  2421. foreach ($entries as $entry) {
  2422. self::processEntry($header, $xpath, $entry, $importer, $xml);
  2423. }
  2424. } else {
  2425. $newentries = [];
  2426. $entries = $xpath->query("/atom:feed/atom:entry");
  2427. foreach ($entries as $entry) {
  2428. $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
  2429. $newentries[strtotime($created)] = $entry;
  2430. }
  2431. // Now sort after the publishing date
  2432. ksort($newentries);
  2433. foreach ($newentries as $entry) {
  2434. self::processEntry($header, $xpath, $entry, $importer, $xml);
  2435. }
  2436. }
  2437. logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
  2438. return 200;
  2439. }
  2440. /**
  2441. * @param App $a App
  2442. * @param string $contact_nick contact nickname
  2443. */
  2444. public static function autoRedir(App $a, $contact_nick)
  2445. {
  2446. // prevent looping
  2447. if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
  2448. return;
  2449. }
  2450. if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
  2451. return;
  2452. }
  2453. if (local_user()) {
  2454. // We need to find out if $contact_nick is a user on this hub, and if so, if I
  2455. // am a contact of that user. However, that user may have other contacts with the
  2456. // same nickname as me on other hubs or other networks. Exclude these by requiring
  2457. // that the contact have a local URL. I will be the only person with my nickname at
  2458. // this URL, so if a result is found, then I am a contact of the $contact_nick user.
  2459. //
  2460. // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
  2461. $baseurl = System::baseUrl();
  2462. $domain_st = strpos($baseurl, "://");
  2463. if ($domain_st === false) {
  2464. return;
  2465. }
  2466. $baseurl = substr($baseurl, $domain_st + 3);
  2467. $nurl = normalise_link($baseurl);
  2468. /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
  2469. $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
  2470. AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
  2471. dbesc($contact_nick),
  2472. dbesc($a->user['nickname']),
  2473. dbesc($baseurl),
  2474. dbesc($nurl)
  2475. );
  2476. if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
  2477. return;
  2478. }
  2479. $r = q("SELECT * FROM contact WHERE nick = '%s'
  2480. AND network = '%s' AND uid = %d AND url LIKE '%%%s%%' LIMIT 1",
  2481. dbesc($contact_nick),
  2482. dbesc(NETWORK_DFRN),
  2483. intval(local_user()),
  2484. dbesc($baseurl)
  2485. );
  2486. if (! DBM::is_result($r)) {
  2487. return;
  2488. }
  2489. $cid = $r[0]['id'];
  2490. $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
  2491. if ($r[0]['duplex'] && $r[0]['issued-id']) {
  2492. $orig_id = $r[0]['issued-id'];
  2493. $dfrn_id = '1:' . $orig_id;
  2494. }
  2495. if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
  2496. $orig_id = $r[0]['dfrn-id'];
  2497. $dfrn_id = '0:' . $orig_id;
  2498. }
  2499. // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
  2500. // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
  2501. if (strlen($dfrn_id) < 3) {
  2502. return;
  2503. }
  2504. $sec = random_string();
  2505. dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
  2506. $url = curPageURL();
  2507. logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
  2508. $dest = (($url) ? '&destination_url=' . $url : '');
  2509. goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
  2510. . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
  2511. }
  2512. return;
  2513. }
  2514. /**
  2515. * @brief Returns the activity verb
  2516. *
  2517. * @param array $item Item array
  2518. *
  2519. * @return string activity verb
  2520. */
  2521. private static function constructVerb(array $item)
  2522. {
  2523. if ($item['verb']) {
  2524. return $item['verb'];
  2525. }
  2526. return ACTIVITY_POST;
  2527. }
  2528. private static function tgroupCheck($uid, $item)
  2529. {
  2530. $mention = false;
  2531. // check that the message originated elsewhere and is a top-level post
  2532. if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
  2533. return false;
  2534. }
  2535. $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
  2536. intval($uid)
  2537. );
  2538. if (!DBM::is_result($u)) {
  2539. return false;
  2540. }
  2541. $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
  2542. $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
  2543. $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
  2544. /*
  2545. * Diaspora uses their own hardwired link URL in @-tags
  2546. * instead of the one we supply with webfinger
  2547. */
  2548. $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
  2549. $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
  2550. if ($cnt) {
  2551. foreach ($matches as $mtch) {
  2552. if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
  2553. $mention = true;
  2554. logger('mention found: ' . $mtch[2]);
  2555. }
  2556. }
  2557. }
  2558. if (!$mention) {
  2559. return false;
  2560. }
  2561. return $community_page || $prvgroup;
  2562. }
  2563. /**
  2564. * This function returns true if $update has an edited timestamp newer
  2565. * than $existing, i.e. $update contains new data which should override
  2566. * what's already there. If there is no timestamp yet, the update is
  2567. * assumed to be newer. If the update has no timestamp, the existing
  2568. * item is assumed to be up-to-date. If the timestamps are equal it
  2569. * assumes the update has been seen before and should be ignored.
  2570. *
  2571. */
  2572. private static function isEditedTimestampNewer($existing, $update)
  2573. {
  2574. if (!x($existing, 'edited') || !$existing['edited']) {
  2575. return true;
  2576. }
  2577. if (!x($update, 'edited') || !$update['edited']) {
  2578. return false;
  2579. }
  2580. $existing_edited = DateTimeFormat::utc($existing['edited']);
  2581. $update_edited = DateTimeFormat::utc($update['edited']);
  2582. return (strcmp($existing_edited, $update_edited) < 0);
  2583. }
  2584. }