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.

3087 lines
99KB

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