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.

4210 lines
122KB

  1. <?php
  2. /**
  3. * @file src/Protocol/diaspora.php
  4. * @brief The implementation of the diaspora protocol
  5. *
  6. * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
  7. * This implementation here interprets the old and the new protocol and sends the new one.
  8. * In the future we will remove most stuff from "validPosting" and interpret only the new protocol.
  9. */
  10. namespace Friendica\Protocol;
  11. use Friendica\Content\Text\BBCode;
  12. use Friendica\Content\Text\Markdown;
  13. use Friendica\Core\Cache;
  14. use Friendica\Core\Config;
  15. use Friendica\Core\L10n;
  16. use Friendica\Core\PConfig;
  17. use Friendica\Core\Protocol;
  18. use Friendica\Core\System;
  19. use Friendica\Core\Worker;
  20. use Friendica\Database\DBA;
  21. use Friendica\Model\Contact;
  22. use Friendica\Model\Conversation;
  23. use Friendica\Model\GContact;
  24. use Friendica\Model\Group;
  25. use Friendica\Model\Item;
  26. use Friendica\Model\Profile;
  27. use Friendica\Model\Queue;
  28. use Friendica\Model\User;
  29. use Friendica\Network\Probe;
  30. use Friendica\Util\Crypto;
  31. use Friendica\Util\DateTimeFormat;
  32. use Friendica\Util\Map;
  33. use Friendica\Util\Network;
  34. use Friendica\Util\XML;
  35. use SimpleXMLElement;
  36. require_once 'include/dba.php';
  37. require_once 'include/items.php';
  38. /**
  39. * @brief This class contain functions to create and send Diaspora XML files
  40. *
  41. */
  42. class Diaspora
  43. {
  44. /**
  45. * @brief Return a list of relay servers
  46. *
  47. * The list contains not only the official relays but also servers that we serve directly
  48. *
  49. * @param integer $item_id The id of the item that is sent
  50. * @param array $contacts The previously fetched contacts
  51. *
  52. * @return array of relay servers
  53. */
  54. public static function relayList($item_id, array $contacts = [])
  55. {
  56. $serverlist = [];
  57. // Fetching relay servers
  58. $serverdata = Config::get("system", "relay_server");
  59. if (!empty($serverdata)) {
  60. $servers = explode(",", $serverdata);
  61. foreach ($servers as $server) {
  62. $serverlist[$server] = trim($server);
  63. }
  64. }
  65. if (Config::get("system", "relay_directly", false)) {
  66. // We distribute our stuff based on the parent to ensure that the thread will be complete
  67. $parent = Item::selectFirst(['parent'], ['id' => $item_id]);
  68. if (!DBA::isResult($parent)) {
  69. return;
  70. }
  71. // Servers that want to get all content
  72. $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'all']);
  73. while ($server = DBA::fetch($servers)) {
  74. $serverlist[$server['url']] = $server['url'];
  75. }
  76. // All tags of the current post
  77. $condition = ['otype' => TERM_OBJ_POST, 'type' => TERM_HASHTAG, 'oid' => $parent['parent']];
  78. $tags = DBA::select('term', ['term'], $condition);
  79. $taglist = [];
  80. while ($tag = DBA::fetch($tags)) {
  81. $taglist[] = $tag['term'];
  82. }
  83. // All servers who wants content with this tag
  84. $tagserverlist = [];
  85. if (!empty($taglist)) {
  86. $tagserver = DBA::select('gserver-tag', ['gserver-id'], ['tag' => $taglist]);
  87. while ($server = DBA::fetch($tagserver)) {
  88. $tagserverlist[] = $server['gserver-id'];
  89. }
  90. }
  91. // All adresses with the given id
  92. if (!empty($tagserverlist)) {
  93. $servers = DBA::select('gserver', ['url'], ['relay-subscribe' => true, 'relay-scope' => 'tags', 'id' => $tagserverlist]);
  94. while ($server = DBA::fetch($servers)) {
  95. $serverlist[$server['url']] = $server['url'];
  96. }
  97. }
  98. }
  99. // Now we are collecting all relay contacts
  100. foreach ($serverlist as $server_url) {
  101. // We don't send messages to ourselves
  102. if (link_compare($server_url, System::baseUrl())) {
  103. continue;
  104. }
  105. $contact = self::getRelayContact($server_url);
  106. if (is_bool($contact)) {
  107. continue;
  108. }
  109. $exists = false;
  110. foreach ($contacts as $entry) {
  111. if ($entry['batch'] == $contact['batch']) {
  112. $exists = true;
  113. }
  114. }
  115. if (!$exists) {
  116. $contacts[] = $contact;
  117. }
  118. }
  119. return $contacts;
  120. }
  121. /**
  122. * @brief Return a contact for a given server address or creates a dummy entry
  123. *
  124. * @param string $server_url The url of the server
  125. * @return array with the contact
  126. */
  127. private static function getRelayContact($server_url)
  128. {
  129. $fields = ['batch', 'id', 'name', 'network', 'archive', 'blocked'];
  130. // Fetch the relay contact
  131. $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
  132. 'contact-type' => Contact::ACCOUNT_TYPE_RELAY];
  133. $contact = DBA::selectFirst('contact', $fields, $condition);
  134. if (DBA::isResult($contact)) {
  135. if ($contact['archive'] || $contact['blocked']) {
  136. return false;
  137. }
  138. return $contact;
  139. } else {
  140. self::setRelayContact($server_url);
  141. $contact = DBA::selectFirst('contact', $fields, $condition);
  142. if (DBA::isResult($contact)) {
  143. return $contact;
  144. }
  145. }
  146. // It should never happen that we arrive here
  147. return [];
  148. }
  149. /**
  150. * @brief Update or insert a relay contact
  151. *
  152. * @param string $server_url The url of the server
  153. * @param array $network_fields Optional network specific fields
  154. */
  155. public static function setRelayContact($server_url, array $network_fields = [])
  156. {
  157. $fields = ['created' => DateTimeFormat::utcNow(),
  158. 'name' => 'relay', 'nick' => 'relay',
  159. 'url' => $server_url, 'network' => Protocol::DIASPORA,
  160. 'batch' => $server_url . '/receive/public',
  161. 'rel' => Contact::FOLLOWER, 'blocked' => false,
  162. 'pending' => false, 'writable' => true];
  163. $fields = array_merge($fields, $network_fields);
  164. $condition = ['uid' => 0, 'nurl' => normalise_link($server_url),
  165. 'contact-type' => Contact::ACCOUNT_TYPE_RELAY];
  166. if (DBA::exists('contact', $condition)) {
  167. unset($fields['created']);
  168. }
  169. DBA::update('contact', $fields, $condition, true);
  170. }
  171. /**
  172. * @brief Return a list of participating contacts for a thread
  173. *
  174. * This is used for the participation feature.
  175. * One of the parameters is a contact array.
  176. * This is done to avoid duplicates.
  177. *
  178. * @param integer $thread The id of the thread
  179. * @param array $contacts The previously fetched contacts
  180. *
  181. * @return array of relay servers
  182. */
  183. public static function participantsForThread($thread, array $contacts)
  184. {
  185. $r = DBA::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
  186. `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
  187. INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
  188. INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
  189. WHERE `participation`.`iid` = ?", $thread);
  190. while ($contact = DBA::fetch($r)) {
  191. if (!empty($contact['fnetwork'])) {
  192. $contact['network'] = $contact['fnetwork'];
  193. }
  194. unset($contact['fnetwork']);
  195. if (empty($contact['batch']) && !empty($contact['fbatch'])) {
  196. $contact['batch'] = $contact['fbatch'];
  197. }
  198. unset($contact['fbatch']);
  199. $exists = false;
  200. foreach ($contacts as $entry) {
  201. if ($entry['batch'] == $contact['batch']) {
  202. $exists = true;
  203. }
  204. }
  205. if (!$exists) {
  206. $contacts[] = $contact;
  207. }
  208. }
  209. DBA::close($r);
  210. return $contacts;
  211. }
  212. /**
  213. * @brief repairs a signature that was double encoded
  214. *
  215. * The function is unused at the moment. It was copied from the old implementation.
  216. *
  217. * @param string $signature The signature
  218. * @param string $handle The handle of the signature owner
  219. * @param integer $level This value is only set inside this function to avoid endless loops
  220. *
  221. * @return string the repaired signature
  222. */
  223. private static function repairSignature($signature, $handle = "", $level = 1)
  224. {
  225. if ($signature == "") {
  226. return ($signature);
  227. }
  228. if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
  229. $signature = base64_decode($signature);
  230. logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
  231. // Do a recursive call to be able to fix even multiple levels
  232. if ($level < 10) {
  233. $signature = self::repairSignature($signature, $handle, ++$level);
  234. }
  235. }
  236. return($signature);
  237. }
  238. /**
  239. * @brief verify the envelope and return the verified data
  240. *
  241. * @param string $envelope The magic envelope
  242. *
  243. * @return string verified data
  244. */
  245. private static function verifyMagicEnvelope($envelope)
  246. {
  247. $basedom = XML::parseString($envelope);
  248. if (!is_object($basedom)) {
  249. logger("Envelope is no XML file");
  250. return false;
  251. }
  252. $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
  253. if (sizeof($children) == 0) {
  254. logger("XML has no children");
  255. return false;
  256. }
  257. $handle = "";
  258. $data = base64url_decode($children->data);
  259. $type = $children->data->attributes()->type[0];
  260. $encoding = $children->encoding;
  261. $alg = $children->alg;
  262. $sig = base64url_decode($children->sig);
  263. $key_id = $children->sig->attributes()->key_id[0];
  264. if ($key_id != "") {
  265. $handle = base64url_decode($key_id);
  266. }
  267. $b64url_data = base64url_encode($data);
  268. $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
  269. $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
  270. if ($handle == '') {
  271. logger('No author could be decoded. Discarding. Message: ' . $envelope);
  272. return false;
  273. }
  274. $key = self::key($handle);
  275. if ($key == '') {
  276. logger("Couldn't get a key for handle " . $handle . ". Discarding.");
  277. return false;
  278. }
  279. $verify = Crypto::rsaVerify($signable_data, $sig, $key);
  280. if (!$verify) {
  281. logger('Message from ' . $handle . ' did not verify. Discarding.');
  282. return false;
  283. }
  284. return $data;
  285. }
  286. /**
  287. * @brief encrypts data via AES
  288. *
  289. * @param string $key The AES key
  290. * @param string $iv The IV (is used for CBC encoding)
  291. * @param string $data The data that is to be encrypted
  292. *
  293. * @return string encrypted data
  294. */
  295. private static function aesEncrypt($key, $iv, $data)
  296. {
  297. return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
  298. }
  299. /**
  300. * @brief decrypts data via AES
  301. *
  302. * @param string $key The AES key
  303. * @param string $iv The IV (is used for CBC encoding)
  304. * @param string $encrypted The encrypted data
  305. *
  306. * @return string decrypted data
  307. */
  308. private static function aesDecrypt($key, $iv, $encrypted)
  309. {
  310. return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
  311. }
  312. /**
  313. * @brief: Decodes incoming Diaspora message in the new format
  314. *
  315. * @param array $importer Array of the importer user
  316. * @param string $raw raw post message
  317. * @param boolean $no_exit Don't do an http exit on error
  318. *
  319. * @return array
  320. * 'message' -> decoded Diaspora XML message
  321. * 'author' -> author diaspora handle
  322. * 'key' -> author public key (converted to pkcs#8)
  323. */
  324. public static function decodeRaw(array $importer, $raw, $no_exit = false)
  325. {
  326. $data = json_decode($raw);
  327. // Is it a private post? Then decrypt the outer Salmon
  328. if (is_object($data)) {
  329. $encrypted_aes_key_bundle = base64_decode($data->aes_key);
  330. $ciphertext = base64_decode($data->encrypted_magic_envelope);
  331. $outer_key_bundle = '';
  332. @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
  333. $j_outer_key_bundle = json_decode($outer_key_bundle);
  334. if (!is_object($j_outer_key_bundle)) {
  335. logger('Outer Salmon did not verify. Discarding.');
  336. if ($no_exit) {
  337. return false;
  338. } else {
  339. System::httpExit(400);
  340. }
  341. }
  342. $outer_iv = base64_decode($j_outer_key_bundle->iv);
  343. $outer_key = base64_decode($j_outer_key_bundle->key);
  344. $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
  345. } else {
  346. $xml = $raw;
  347. }
  348. $basedom = XML::parseString($xml);
  349. if (!is_object($basedom)) {
  350. logger('Received data does not seem to be an XML. Discarding. '.$xml);
  351. if ($no_exit) {
  352. return false;
  353. } else {
  354. System::httpExit(400);
  355. }
  356. }
  357. $base = $basedom->children(NAMESPACE_SALMON_ME);
  358. // Not sure if this cleaning is needed
  359. $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
  360. // Build the signed data
  361. $type = $base->data[0]->attributes()->type[0];
  362. $encoding = $base->encoding;
  363. $alg = $base->alg;
  364. $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
  365. // This is the signature
  366. $signature = base64url_decode($base->sig);
  367. // Get the senders' public key
  368. $key_id = $base->sig[0]->attributes()->key_id[0];
  369. $author_addr = base64_decode($key_id);
  370. if ($author_addr == '') {
  371. logger('No author could be decoded. Discarding. Message: ' . $xml);
  372. if ($no_exit) {
  373. return false;
  374. } else {
  375. System::httpExit(400);
  376. }
  377. }
  378. $key = self::key($author_addr);
  379. if ($key == '') {
  380. logger("Couldn't get a key for handle " . $author_addr . ". Discarding.");
  381. if ($no_exit) {
  382. return false;
  383. } else {
  384. System::httpExit(400);
  385. }
  386. }
  387. $verify = Crypto::rsaVerify($signed_data, $signature, $key);
  388. if (!$verify) {
  389. logger('Message did not verify. Discarding.');
  390. if ($no_exit) {
  391. return false;
  392. } else {
  393. System::httpExit(400);
  394. }
  395. }
  396. return ['message' => (string)base64url_decode($base->data),
  397. 'author' => unxmlify($author_addr),
  398. 'key' => (string)$key];
  399. }
  400. /**
  401. * @brief: Decodes incoming Diaspora message in the deprecated format
  402. *
  403. * @param array $importer Array of the importer user
  404. * @param string $xml urldecoded Diaspora salmon
  405. *
  406. * @return array
  407. * 'message' -> decoded Diaspora XML message
  408. * 'author' -> author diaspora handle
  409. * 'key' -> author public key (converted to pkcs#8)
  410. */
  411. public static function decode(array $importer, $xml)
  412. {
  413. $public = false;
  414. $basedom = XML::parseString($xml);
  415. if (!is_object($basedom)) {
  416. logger("XML is not parseable.");
  417. return false;
  418. }
  419. $children = $basedom->children('https://joindiaspora.com/protocol');
  420. $inner_aes_key = null;
  421. $inner_iv = null;
  422. if ($children->header) {
  423. $public = true;
  424. $author_link = str_replace('acct:', '', $children->header->author_id);
  425. } else {
  426. // This happens with posts from a relais
  427. if (!$importer) {
  428. logger("This is no private post in the old format", LOGGER_DEBUG);
  429. return false;
  430. }
  431. $encrypted_header = json_decode(base64_decode($children->encrypted_header));
  432. $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
  433. $ciphertext = base64_decode($encrypted_header->ciphertext);
  434. $outer_key_bundle = '';
  435. openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
  436. $j_outer_key_bundle = json_decode($outer_key_bundle);
  437. $outer_iv = base64_decode($j_outer_key_bundle->iv);
  438. $outer_key = base64_decode($j_outer_key_bundle->key);
  439. $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
  440. logger('decrypted: '.$decrypted, LOGGER_DEBUG);
  441. $idom = XML::parseString($decrypted);
  442. $inner_iv = base64_decode($idom->iv);
  443. $inner_aes_key = base64_decode($idom->aes_key);
  444. $author_link = str_replace('acct:', '', $idom->author_id);
  445. }
  446. $dom = $basedom->children(NAMESPACE_SALMON_ME);
  447. // figure out where in the DOM tree our data is hiding
  448. $base = null;
  449. if ($dom->provenance->data) {
  450. $base = $dom->provenance;
  451. } elseif ($dom->env->data) {
  452. $base = $dom->env;
  453. } elseif ($dom->data) {
  454. $base = $dom;
  455. }
  456. if (!$base) {
  457. logger('unable to locate salmon data in xml');
  458. System::httpExit(400);
  459. }
  460. // Stash the signature away for now. We have to find their key or it won't be good for anything.
  461. $signature = base64url_decode($base->sig);
  462. // unpack the data
  463. // strip whitespace so our data element will return to one big base64 blob
  464. $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
  465. // stash away some other stuff for later
  466. $type = $base->data[0]->attributes()->type[0];
  467. $keyhash = $base->sig[0]->attributes()->keyhash[0];
  468. $encoding = $base->encoding;
  469. $alg = $base->alg;
  470. $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
  471. // decode the data
  472. $data = base64url_decode($data);
  473. if ($public) {
  474. $inner_decrypted = $data;
  475. } else {
  476. // Decode the encrypted blob
  477. $inner_encrypted = base64_decode($data);
  478. $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
  479. }
  480. if (!$author_link) {
  481. logger('Could not retrieve author URI.');
  482. System::httpExit(400);
  483. }
  484. // Once we have the author URI, go to the web and try to find their public key
  485. // (first this will look it up locally if it is in the fcontact cache)
  486. // This will also convert diaspora public key from pkcs#1 to pkcs#8
  487. logger('Fetching key for '.$author_link);
  488. $key = self::key($author_link);
  489. if (!$key) {
  490. logger('Could not retrieve author key.');
  491. System::httpExit(400);
  492. }
  493. $verify = Crypto::rsaVerify($signed_data, $signature, $key);
  494. if (!$verify) {
  495. logger('Message did not verify. Discarding.');
  496. System::httpExit(400);
  497. }
  498. logger('Message verified.');
  499. return ['message' => (string)$inner_decrypted,
  500. 'author' => unxmlify($author_link),
  501. 'key' => (string)$key];
  502. }
  503. /**
  504. * @brief Dispatches public messages and find the fitting receivers
  505. *
  506. * @param array $msg The post that will be dispatched
  507. *
  508. * @return int The message id of the generated message, "true" or "false" if there was an error
  509. */
  510. public static function dispatchPublic($msg)
  511. {
  512. $enabled = intval(Config::get("system", "diaspora_enabled"));
  513. if (!$enabled) {
  514. logger("diaspora is disabled");
  515. return false;
  516. }
  517. if (!($fields = self::validPosting($msg))) {
  518. logger("Invalid posting");
  519. return false;
  520. }
  521. $importer = ["uid" => 0, "page-flags" => Contact::PAGE_FREELOVE];
  522. $success = self::dispatch($importer, $msg, $fields);
  523. return $success;
  524. }
  525. /**
  526. * @brief Dispatches the different message types to the different functions
  527. *
  528. * @param array $importer Array of the importer user
  529. * @param array $msg The post that will be dispatched
  530. * @param object $fields SimpleXML object that contains the message
  531. *
  532. * @return int The message id of the generated message, "true" or "false" if there was an error
  533. */
  534. public static function dispatch(array $importer, $msg, $fields = null)
  535. {
  536. // The sender is the handle of the contact that sent the message.
  537. // This will often be different with relayed messages (for example "like" and "comment")
  538. $sender = $msg["author"];
  539. // This is only needed for private postings since this is already done for public ones before
  540. if (is_null($fields)) {
  541. $private = true;
  542. if (!($fields = self::validPosting($msg))) {
  543. logger("Invalid posting");
  544. return false;
  545. }
  546. } else {
  547. $private = false;
  548. }
  549. $type = $fields->getName();
  550. logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
  551. switch ($type) {
  552. case "account_migration":
  553. if (!$private) {
  554. logger('Message with type ' . $type . ' is not private, quitting.');
  555. return false;
  556. }
  557. return self::receiveAccountMigration($importer, $fields);
  558. case "account_deletion":
  559. return self::receiveAccountDeletion($fields);
  560. case "comment":
  561. return self::receiveComment($importer, $sender, $fields, $msg["message"]);
  562. case "contact":
  563. if (!$private) {
  564. logger('Message with type ' . $type . ' is not private, quitting.');
  565. return false;
  566. }
  567. return self::receiveContactRequest($importer, $fields);
  568. case "conversation":
  569. if (!$private) {
  570. logger('Message with type ' . $type . ' is not private, quitting.');
  571. return false;
  572. }
  573. return self::receiveConversation($importer, $msg, $fields);
  574. case "like":
  575. return self::receiveLike($importer, $sender, $fields);
  576. case "message":
  577. if (!$private) {
  578. logger('Message with type ' . $type . ' is not private, quitting.');
  579. return false;
  580. }
  581. return self::receiveMessage($importer, $fields);
  582. case "participation":
  583. if (!$private) {
  584. logger('Message with type ' . $type . ' is not private, quitting.');
  585. return false;
  586. }
  587. return self::receiveParticipation($importer, $fields);
  588. case "photo": // Not implemented
  589. return self::receivePhoto($importer, $fields);
  590. case "poll_participation": // Not implemented
  591. return self::receivePollParticipation($importer, $fields);
  592. case "profile":
  593. if (!$private) {
  594. logger('Message with type ' . $type . ' is not private, quitting.');
  595. return false;
  596. }
  597. return self::receiveProfile($importer, $fields);
  598. case "reshare":
  599. return self::receiveReshare($importer, $fields, $msg["message"]);
  600. case "retraction":
  601. return self::receiveRetraction($importer, $sender, $fields);
  602. case "status_message":
  603. return self::receiveStatusMessage($importer, $fields, $msg["message"]);
  604. default:
  605. logger("Unknown message type ".$type);
  606. return false;
  607. }
  608. return true;
  609. }
  610. /**
  611. * @brief Checks if a posting is valid and fetches the data fields.
  612. *
  613. * This function does not only check the signature.
  614. * It also does the conversion between the old and the new diaspora format.
  615. *
  616. * @param array $msg Array with the XML, the sender handle and the sender signature
  617. *
  618. * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
  619. */
  620. private static function validPosting($msg)
  621. {
  622. $data = XML::parseString($msg["message"]);
  623. if (!is_object($data)) {
  624. logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
  625. return false;
  626. }
  627. // Is this the new or the old version?
  628. if ($data->getName() == "XML") {
  629. $oldXML = true;
  630. foreach ($data->post->children() as $child) {
  631. $element = $child;
  632. }
  633. } else {
  634. $oldXML = false;
  635. $element = $data;
  636. }
  637. $type = $element->getName();
  638. $orig_type = $type;
  639. logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
  640. // All retractions are handled identically from now on.
  641. // In the new version there will only be "retraction".
  642. if (in_array($type, ["signed_retraction", "relayable_retraction"]))
  643. $type = "retraction";
  644. if ($type == "request") {
  645. $type = "contact";
  646. }
  647. $fields = new SimpleXMLElement("<".$type."/>");
  648. $signed_data = "";
  649. $author_signature = null;
  650. $parent_author_signature = null;
  651. foreach ($element->children() as $fieldname => $entry) {
  652. if ($oldXML) {
  653. // Translation for the old XML structure
  654. if ($fieldname == "diaspora_handle") {
  655. $fieldname = "author";
  656. }
  657. if ($fieldname == "participant_handles") {
  658. $fieldname = "participants";
  659. }
  660. if (in_array($type, ["like", "participation"])) {
  661. if ($fieldname == "target_type") {
  662. $fieldname = "parent_type";
  663. }
  664. }
  665. if ($fieldname == "sender_handle") {
  666. $fieldname = "author";
  667. }
  668. if ($fieldname == "recipient_handle") {
  669. $fieldname = "recipient";
  670. }
  671. if ($fieldname == "root_diaspora_id") {
  672. $fieldname = "root_author";
  673. }
  674. if ($type == "status_message") {
  675. if ($fieldname == "raw_message") {
  676. $fieldname = "text";
  677. }
  678. }
  679. if ($type == "retraction") {
  680. if ($fieldname == "post_guid") {
  681. $fieldname = "target_guid";
  682. }
  683. if ($fieldname == "type") {
  684. $fieldname = "target_type";
  685. }
  686. }
  687. }
  688. if (($fieldname == "author_signature") && ($entry != "")) {
  689. $author_signature = base64_decode($entry);
  690. } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
  691. $parent_author_signature = base64_decode($entry);
  692. } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
  693. if ($signed_data != "") {
  694. $signed_data .= ";";
  695. }
  696. $signed_data .= $entry;
  697. }
  698. if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
  699. || ($orig_type == "relayable_retraction")
  700. ) {
  701. XML::copy($entry, $fields, $fieldname);
  702. }
  703. }
  704. // This is something that shouldn't happen at all.
  705. if (in_array($type, ["status_message", "reshare", "profile"])) {
  706. if ($msg["author"] != $fields->author) {
  707. logger("Message handle is not the same as envelope sender. Quitting this message.");
  708. return false;
  709. }
  710. }
  711. // Only some message types have signatures. So we quit here for the other types.
  712. if (!in_array($type, ["comment", "like"])) {
  713. return $fields;
  714. }
  715. // No author_signature? This is a must, so we quit.
  716. if (!isset($author_signature)) {
  717. logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
  718. return false;
  719. }
  720. if (isset($parent_author_signature)) {
  721. $key = self::key($msg["author"]);
  722. if (empty($key)) {
  723. logger("No key found for parent author ".$msg["author"], LOGGER_DEBUG);
  724. return false;
  725. }
  726. if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
  727. logger("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, LOGGER_DEBUG);
  728. return false;
  729. }
  730. }
  731. $key = self::key($fields->author);
  732. if (empty($key)) {
  733. logger("No key found for author ".$fields->author, LOGGER_DEBUG);
  734. return false;
  735. }
  736. if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
  737. logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
  738. return false;
  739. } else {
  740. return $fields;
  741. }
  742. }
  743. /**
  744. * @brief Fetches the public key for a given handle
  745. *
  746. * @param string $handle The handle
  747. *
  748. * @return string The public key
  749. */
  750. private static function key($handle)
  751. {
  752. $handle = strval($handle);
  753. logger("Fetching diaspora key for: ".$handle);
  754. $r = self::personByHandle($handle);
  755. if ($r) {
  756. return $r["pubkey"];
  757. }
  758. return "";
  759. }
  760. /**
  761. * @brief Fetches data for a given handle
  762. *
  763. * @param string $handle The handle
  764. *
  765. * @return array the queried data
  766. */
  767. public static function personByHandle($handle)
  768. {
  769. $update = false;
  770. $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
  771. if (DBA::isResult($person)) {
  772. logger("In cache " . print_r($person, true), LOGGER_DEBUG);
  773. // update record occasionally so it doesn't get stale
  774. $d = strtotime($person["updated"]." +00:00");
  775. if ($d < strtotime("now - 14 days")) {
  776. $update = true;
  777. }
  778. if ($person["guid"] == "") {
  779. $update = true;
  780. }
  781. }
  782. if (!DBA::isResult($person) || $update) {
  783. logger("create or refresh", LOGGER_DEBUG);
  784. $r = Probe::uri($handle, Protocol::DIASPORA);
  785. // Note that Friendica contacts will return a "Diaspora person"
  786. // if Diaspora connectivity is enabled on their server
  787. if ($r && ($r["network"] === Protocol::DIASPORA)) {
  788. self::updateFContact($r);
  789. // Fetch the updated or added contact
  790. $person = DBA::selectFirst('fcontact', [], ['network' => Protocol::DIASPORA, 'addr' => $handle]);
  791. if (!DBA::isResult($person)) {
  792. $person = $r;
  793. }
  794. }
  795. }
  796. return $person;
  797. }
  798. /**
  799. * @brief Updates the fcontact table
  800. *
  801. * @param array $arr The fcontact data
  802. */
  803. private static function updateFContact($arr)
  804. {
  805. $fields = ['name' => $arr["name"], 'photo' => $arr["photo"],
  806. 'request' => $arr["request"], 'nick' => $arr["nick"],
  807. 'addr' => strtolower($arr["addr"]), 'guid' => $arr["guid"],
  808. 'batch' => $arr["batch"], 'notify' => $arr["notify"],
  809. 'poll' => $arr["poll"], 'confirm' => $arr["confirm"],
  810. 'alias' => $arr["alias"], 'pubkey' => $arr["pubkey"],
  811. 'updated' => DateTimeFormat::utcNow()];
  812. $condition = ['url' => $arr["url"], 'network' => $arr["network"]];
  813. DBA::update('fcontact', $fields, $condition, true);
  814. }
  815. /**
  816. * @brief get a handle (user@domain.tld) from a given contact id
  817. *
  818. * @param int $contact_id The id in the contact table
  819. * @param int $pcontact_id The id in the contact table (Used for the public contact)
  820. *
  821. * @return string the handle
  822. */
  823. private static function handleFromContact($contact_id, $pcontact_id = 0)
  824. {
  825. $handle = false;
  826. logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
  827. if ($pcontact_id != 0) {
  828. $contact = DBA::selectFirst('contact', ['addr'], ['id' => $pcontact_id]);
  829. if (DBA::isResult($contact) && !empty($contact["addr"])) {
  830. return strtolower($contact["addr"]);
  831. }
  832. }
  833. $r = q(
  834. "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
  835. intval($contact_id)
  836. );
  837. if (DBA::isResult($r)) {
  838. $contact = $r[0];
  839. logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
  840. if ($contact['addr'] != "") {
  841. $handle = $contact['addr'];
  842. } else {
  843. $baseurl_start = strpos($contact['url'], '://') + 3;
  844. // allows installations in a subdirectory--not sure how Diaspora will handle
  845. $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
  846. $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
  847. $handle = $contact['nick'].'@'.$baseurl;
  848. }
  849. }
  850. return strtolower($handle);
  851. }
  852. /**
  853. * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
  854. * fcontact guid
  855. *
  856. * @param mixed $fcontact_guid Hexadecimal string guid
  857. *
  858. * @return string the contact url or null
  859. */
  860. public static function urlFromContactGuid($fcontact_guid)
  861. {
  862. logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
  863. $r = q(
  864. "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
  865. DBA::escape(Protocol::DIASPORA),
  866. DBA::escape($fcontact_guid)
  867. );
  868. if (DBA::isResult($r)) {
  869. return $r[0]['url'];
  870. }
  871. return null;
  872. }
  873. /**
  874. * @brief Get a contact id for a given handle
  875. *
  876. * @todo Move to Friendica\Model\Contact
  877. *
  878. * @param int $uid The user id
  879. * @param string $handle The handle in the format user@domain.tld
  880. *
  881. * @return int Contact id
  882. */
  883. private static function contactByHandle($uid, $handle)
  884. {
  885. $cid = Contact::getIdForURL($handle, $uid);
  886. if (!$cid) {
  887. $handle_parts = explode("@", $handle);
  888. $nurl_sql = "%%://" . $handle_parts[1] . "%%/profile/" . $handle_parts[0];
  889. $cid = Contact::getIdForURL($nurl_sql, $uid);
  890. }
  891. if (!$cid) {
  892. logger("Haven't found a contact for user " . $uid . " and handle " . $handle, LOGGER_DEBUG);
  893. return false;
  894. }
  895. $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
  896. if (!DBA::isResult($contact)) {
  897. // This here shouldn't happen at all
  898. logger("Haven't found a contact for user " . $uid . " and handle " . $handle, LOGGER_DEBUG);
  899. return false;
  900. }
  901. return $contact;
  902. }
  903. /**
  904. * @brief Check if posting is allowed for this contact
  905. *
  906. * @param array $importer Array of the importer user
  907. * @param array $contact The contact that is checked
  908. * @param bool $is_comment Is the check for a comment?
  909. *
  910. * @return bool is the contact allowed to post?
  911. */
  912. private static function postAllow(array $importer, array $contact, $is_comment = false)
  913. {
  914. /*
  915. * Perhaps we were already sharing with this person. Now they're sharing with us.
  916. * That makes us friends.
  917. * Normally this should have handled by getting a request - but this could get lost
  918. */
  919. // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
  920. // It is not removed by now. Possibly the code is needed?
  921. //if (!$is_comment && $contact["rel"] == Contact::FOLLOWER && in_array($importer["page-flags"], array(Contact::PAGE_FREELOVE))) {
  922. // DBA::update(
  923. // 'contact',
  924. // array('rel' => Contact::FRIEND, 'writable' => true),
  925. // array('id' => $contact["id"], 'uid' => $contact["uid"])
  926. // );
  927. //
  928. // $contact["rel"] = Contact::FRIEND;
  929. // logger("defining user ".$contact["nick"]." as friend");
  930. //}
  931. // We don't seem to like that person
  932. if ($contact["blocked"]) {
  933. // Maybe blocked, don't accept.
  934. return false;
  935. // We are following this person?
  936. } elseif (($contact["rel"] == Contact::SHARING) || ($contact["rel"] == Contact::FRIEND)) {
  937. // Yes, then it is fine.
  938. return true;
  939. // Is it a post to a community?
  940. } elseif (($contact["rel"] == Contact::FOLLOWER) && in_array($importer["page-flags"], [Contact::PAGE_COMMUNITY, Contact::PAGE_PRVGROUP])) {
  941. // That's good
  942. return true;
  943. // Is the message a global user or a comment?
  944. } elseif (($importer["uid"] == 0) || $is_comment) {
  945. // Messages for the global users and comments are always accepted
  946. return true;
  947. }
  948. return false;
  949. }
  950. /**
  951. * @brief Fetches the contact id for a handle and checks if posting is allowed
  952. *
  953. * @param array $importer Array of the importer user
  954. * @param string $handle The checked handle in the format user@domain.tld
  955. * @param bool $is_comment Is the check for a comment?
  956. *
  957. * @return array The contact data
  958. */
  959. private static function allowedContactByHandle(array $importer, $handle, $is_comment = false)
  960. {
  961. $contact = self::contactByHandle($importer["uid"], $handle);
  962. if (!$contact) {
  963. logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
  964. // If a contact isn't found, we accept it anyway if it is a comment
  965. if ($is_comment && ($importer["uid"] != 0)) {
  966. return self::contactByHandle(0, $handle);
  967. } elseif ($is_comment) {
  968. return $importer;
  969. } else {
  970. return false;
  971. }
  972. }
  973. if (!self::postAllow($importer, $contact, $is_comment)) {
  974. logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
  975. return false;
  976. }
  977. return $contact;
  978. }
  979. /**
  980. * @brief Does the message already exists on the system?
  981. *
  982. * @param int $uid The user id
  983. * @param string $guid The guid of the message
  984. *
  985. * @return int|bool message id if the message already was stored into the system - or false.
  986. */
  987. private static function messageExists($uid, $guid)
  988. {
  989. $item = Item::selectFirst(['id'], ['uid' => $uid, 'guid' => $guid]);
  990. if (DBA::isResult($item)) {
  991. logger("message ".$guid." already exists for user ".$uid);
  992. return $item["id"];
  993. }
  994. return false;
  995. }
  996. /**
  997. * @brief Checks for links to posts in a message
  998. *
  999. * @param array $item The item array
  1000. * @return void
  1001. */
  1002. private static function fetchGuid(array $item)
  1003. {
  1004. $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
  1005. preg_replace_callback(
  1006. $expression,
  1007. function ($match) use ($item) {
  1008. self::fetchGuidSub($match, $item);
  1009. },
  1010. $item["body"]
  1011. );
  1012. preg_replace_callback(
  1013. "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
  1014. function ($match) use ($item) {
  1015. self::fetchGuidSub($match, $item);
  1016. },
  1017. $item["body"]
  1018. );
  1019. }
  1020. /**
  1021. * @brief Checks for relative /people/* links in an item body to match local
  1022. * contacts or prepends the remote host taken from the author link.
  1023. *
  1024. * @param string $body The item body to replace links from
  1025. * @param string $author_link The author link for missing local contact fallback
  1026. *
  1027. * @return string the replaced string
  1028. */
  1029. public static function replacePeopleGuid($body, $author_link)
  1030. {
  1031. $return = preg_replace_callback(
  1032. "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
  1033. function ($match) use ($author_link) {
  1034. // $match
  1035. // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
  1036. // 1 => '0123456789abcdef'
  1037. // 2 => 'Foo Bar'
  1038. $handle = self::urlFromContactGuid($match[1]);
  1039. if ($handle) {
  1040. $return = '@[url='.$handle.']'.$match[2].'[/url]';
  1041. } else {
  1042. // No local match, restoring absolute remote URL from author scheme and host
  1043. $author_url = parse_url($author_link);
  1044. $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
  1045. }
  1046. return $return;
  1047. },
  1048. $body
  1049. );
  1050. return $return;
  1051. }
  1052. /**
  1053. * @brief sub function of "fetchGuid" which checks for links in messages
  1054. *
  1055. * @param array $match array containing a link that has to be checked for a message link
  1056. * @param array $item The item array
  1057. * @return void
  1058. */
  1059. private static function fetchGuidSub($match, $item)
  1060. {
  1061. if (!self::storeByGuid($match[1], $item["author-link"])) {
  1062. self::storeByGuid($match[1], $item["owner-link"]);
  1063. }
  1064. }
  1065. /**
  1066. * @brief Fetches an item with a given guid from a given server
  1067. *
  1068. * @param string $guid the message guid
  1069. * @param string $server The server address
  1070. * @param int $uid The user id of the user
  1071. *
  1072. * @return int the message id of the stored message or false
  1073. */
  1074. private static function storeByGuid($guid, $server, $uid = 0)
  1075. {
  1076. $serverparts = parse_url($server);
  1077. if (empty($serverparts["host"]) || empty($serverparts["scheme"])) {
  1078. return false;
  1079. }
  1080. $server = $serverparts["scheme"]."://".$serverparts["host"];
  1081. logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
  1082. $msg = self::message($guid, $server);
  1083. if (!$msg) {
  1084. return false;
  1085. }
  1086. logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
  1087. // Now call the dispatcher
  1088. return self::dispatchPublic($msg);
  1089. }
  1090. /**
  1091. * @brief Fetches a message from a server
  1092. *
  1093. * @param string $guid message guid
  1094. * @param string $server The url of the server
  1095. * @param int $level Endless loop prevention
  1096. *
  1097. * @return array
  1098. * 'message' => The message XML
  1099. * 'author' => The author handle
  1100. * 'key' => The public key of the author
  1101. */
  1102. private static function message($guid, $server, $level = 0)
  1103. {
  1104. if ($level > 5) {
  1105. return false;
  1106. }
  1107. // This will work for new Diaspora servers and Friendica servers from 3.5
  1108. $source_url = $server."/fetch/post/".urlencode($guid);
  1109. logger("Fetch post from ".$source_url, LOGGER_DEBUG);
  1110. $envelope = Network::fetchUrl($source_url);
  1111. if ($envelope) {
  1112. logger("Envelope was fetched.", LOGGER_DEBUG);
  1113. $x = self::verifyMagicEnvelope($envelope);
  1114. if (!$x) {
  1115. logger("Envelope could not be verified.", LOGGER_DEBUG);
  1116. } else {
  1117. logger("Envelope was verified.", LOGGER_DEBUG);
  1118. }
  1119. } else {
  1120. $x = false;
  1121. }
  1122. // This will work for older Diaspora and Friendica servers
  1123. if (!$x) {
  1124. $source_url = $server."/p/".urlencode($guid).".xml";
  1125. logger("Fetch post from ".$source_url, LOGGER_DEBUG);
  1126. $x = Network::fetchUrl($source_url);
  1127. if (!$x) {
  1128. return false;
  1129. }
  1130. }
  1131. $source_xml = XML::parseString($x);
  1132. if (!is_object($source_xml)) {
  1133. return false;
  1134. }
  1135. if ($source_xml->post->reshare) {
  1136. // Reshare of a reshare - old Diaspora version
  1137. logger("Message is a reshare", LOGGER_DEBUG);
  1138. return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
  1139. } elseif ($source_xml->getName() == "reshare") {
  1140. // Reshare of a reshare - new Diaspora version
  1141. logger("Message is a new reshare", LOGGER_DEBUG);
  1142. return self::message($source_xml->root_guid, $server, ++$level);
  1143. }
  1144. $author = "";
  1145. // Fetch the author - for the old and the new Diaspora version
  1146. if ($source_xml->post->status_message && $source_xml->post->status_message->diaspora_handle) {
  1147. $author = (string)$source_xml->post->status_message->diaspora_handle;
  1148. } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
  1149. $author = (string)$source_xml->author;
  1150. }
  1151. // If this isn't a "status_message" then quit
  1152. if (!$author) {
  1153. logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
  1154. return false;
  1155. }
  1156. $msg = ["message" => $x, "author" => $author];
  1157. $msg["key"] = self::key($msg["author"]);
  1158. return $msg;
  1159. }
  1160. /**
  1161. * @brief Fetches the item record of a given guid
  1162. *
  1163. * @param int $uid The user id
  1164. * @param string $guid message guid
  1165. * @param string $author The handle of the item
  1166. * @param array $contact The contact of the item owner
  1167. *
  1168. * @return array the item record
  1169. */
  1170. private static function parentItem($uid, $guid, $author, array $contact)
  1171. {
  1172. $fields = ['id', 'parent', 'body', 'wall', 'uri', 'guid', 'private', 'origin',
  1173. 'author-name', 'author-link', 'author-avatar',
  1174. 'owner-name', 'owner-link', 'owner-avatar'];
  1175. $condition = ['uid' => $uid, 'guid' => $guid];
  1176. $item = Item::selectFirst($fields, $condition);
  1177. if (!DBA::isResult($item)) {
  1178. $person = self::personByHandle($author);
  1179. $result = self::storeByGuid($guid, $person["url"], $uid);
  1180. // We don't have an url for items that arrived at the public dispatcher
  1181. if (!$result && !empty($contact["url"])) {
  1182. $result = self::storeByGuid($guid, $contact["url"], $uid);
  1183. }
  1184. if ($result) {
  1185. logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
  1186. $item = Item::selectFirst($fields, $condition);
  1187. }
  1188. }
  1189. if (!DBA::isResult($item)) {
  1190. logger("parent item not found: parent: ".$guid." - user: ".$uid);
  1191. return false;
  1192. } else {
  1193. logger("parent item found: parent: ".$guid." - user: ".$uid);
  1194. return $item;
  1195. }
  1196. }
  1197. /**
  1198. * @brief returns contact details
  1199. *
  1200. * @param array $def_contact The default contact if the person isn't found
  1201. * @param array $person The record of the person
  1202. * @param int $uid The user id
  1203. *
  1204. * @return array
  1205. * 'cid' => contact id
  1206. * 'network' => network type
  1207. */
  1208. private static function authorContactByUrl($def_contact, $person, $uid)
  1209. {
  1210. $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
  1211. $contact = DBA::selectFirst('contact', ['id', 'network'], $condition);
  1212. if (DBA::isResult($contact)) {
  1213. $cid = $contact["id"];
  1214. $network = $contact["network"];
  1215. } else {
  1216. $cid = $def_contact["id"];
  1217. $network = Protocol::DIASPORA;
  1218. }
  1219. return ["cid" => $cid, "network" => $network];
  1220. }
  1221. /**
  1222. * @brief Is the profile a hubzilla profile?
  1223. *
  1224. * @param string $url The profile link
  1225. *
  1226. * @return bool is it a hubzilla server?
  1227. */
  1228. public static function isRedmatrix($url)
  1229. {
  1230. return(strstr($url, "/channel/"));
  1231. }
  1232. /**
  1233. * @brief Generate a post link with a given handle and message guid
  1234. *
  1235. * @param string $addr The user handle
  1236. * @param string $guid message guid
  1237. * @param string $parent_guid optional parent guid
  1238. *
  1239. * @return string the post link
  1240. */
  1241. private static function plink($addr, $guid, $parent_guid = '')
  1242. {
  1243. $contact = Contact::getDetailsByAddr($addr);
  1244. // Fallback
  1245. if (!$contact) {
  1246. if ($parent_guid != '') {
  1247. return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
  1248. } else {
  1249. return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
  1250. }
  1251. }
  1252. if ($contact["network"] == Protocol::DFRN) {
  1253. return str_replace("/profile/" . $contact["nick"] . "/", "/display/" . $guid, $contact["url"] . "/");
  1254. }
  1255. if (self::isRedmatrix($contact["url"])) {
  1256. return $contact["url"] . "/?f=&mid=" . $guid;
  1257. }
  1258. if ($parent_guid != '') {
  1259. return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
  1260. } else {
  1261. return "https://" . substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
  1262. }
  1263. }
  1264. /**
  1265. * @brief Receives account migration
  1266. *
  1267. * @param array $importer Array of the importer user
  1268. * @param object $data The message object
  1269. *
  1270. * @return bool Success
  1271. */
  1272. private static function receiveAccountMigration(array $importer, $data)
  1273. {
  1274. $old_handle = notags(unxmlify($data->author));
  1275. $new_handle = notags(unxmlify($data->profile->author));
  1276. $signature = notags(unxmlify($data->signature));
  1277. $contact = self::contactByHandle($importer["uid"], $old_handle);
  1278. if (!$contact) {
  1279. logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
  1280. return false;
  1281. }
  1282. logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
  1283. // Check signature
  1284. $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
  1285. $key = self::key($old_handle);
  1286. if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
  1287. logger('No valid signature for migration.');
  1288. return false;
  1289. }
  1290. // Update the profile
  1291. self::receiveProfile($importer, $data->profile);
  1292. // change the technical stuff in contact and gcontact
  1293. $data = Probe::uri($new_handle);
  1294. if ($data['network'] == Protocol::PHANTOM) {
  1295. logger('Account for '.$new_handle." couldn't be probed.");
  1296. return false;
  1297. }
  1298. $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
  1299. 'name' => $data['name'], 'nick' => $data['nick'],
  1300. 'addr' => $data['addr'], 'batch' => $data['batch'],
  1301. 'notify' => $data['notify'], 'poll' => $data['poll'],
  1302. 'network' => $data['network']];
  1303. DBA::update('contact', $fields, ['addr' => $old_handle]);
  1304. $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
  1305. 'name' => $data['name'], 'nick' => $data['nick'],
  1306. 'addr' => $data['addr'], 'connect' => $data['addr'],
  1307. 'notify' => $data['notify'], 'photo' => $data['photo'],
  1308. 'server_url' => $data['baseurl'], 'network' => $data['network']];
  1309. DBA::update('gcontact', $fields, ['addr' => $old_handle]);
  1310. logger('Contacts are updated.');
  1311. return true;
  1312. }
  1313. /**
  1314. * @brief Processes an account deletion
  1315. *
  1316. * @param object $data The message object
  1317. *
  1318. * @return bool Success
  1319. */
  1320. private static function receiveAccountDeletion($data)
  1321. {
  1322. $author = notags(unxmlify($data->author));
  1323. $contacts = DBA::select('contact', ['id'], ['addr' => $author]);
  1324. while ($contact = DBA::fetch($contacts)) {
  1325. Contact::remove($contact["id"]);
  1326. }
  1327. DBA::delete('gcontact', ['addr' => $author]);
  1328. logger('Removed contacts for ' . $author);
  1329. return true;
  1330. }
  1331. /**
  1332. * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
  1333. *
  1334. * @param string $author Author handle
  1335. * @param string $guid Message guid
  1336. * @param boolean $onlyfound Only return uri when found in the database
  1337. *
  1338. * @return string The constructed uri or the one from our database
  1339. */
  1340. private static function getUriFromGuid($author, $guid, $onlyfound = false)
  1341. {
  1342. $item = Item::selectFirst(['uri'], ['guid' => $guid]);
  1343. if (DBA::isResult($item)) {
  1344. return $item["uri"];
  1345. } elseif (!$onlyfound) {
  1346. $person = self::personByHandle($author);
  1347. $parts = parse_url($person['url']);
  1348. unset($parts['path']);
  1349. $host_url = Network::unparseURL($parts);
  1350. return $host_url . '/objects/' . $guid;
  1351. }
  1352. return "";
  1353. }
  1354. /**
  1355. * @brief Fetch the guid from our database with a given uri
  1356. *
  1357. * @param string $uri Message uri
  1358. * @param string $uid Author handle
  1359. *
  1360. * @return string The post guid
  1361. */
  1362. private static function getGuidFromUri($uri, $uid)
  1363. {
  1364. $item = Item::selectFirst(['guid'], ['uri' => $uri, 'uid' => $uid]);
  1365. if (DBA::isResult($item)) {
  1366. return $item["guid"];
  1367. } else {
  1368. return false;
  1369. }
  1370. }
  1371. /**
  1372. * @brief Find the best importer for a comment, like, ...
  1373. *
  1374. * @param string $guid The guid of the item
  1375. *
  1376. * @return array|boolean the origin owner of that post - or false
  1377. */
  1378. private static function importerForGuid($guid)
  1379. {
  1380. $item = Item::selectFirst(['uid'], ['origin' => true, 'guid' => $guid]);
  1381. if (DBA::isResult($item)) {
  1382. logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
  1383. $contact = DBA::selectFirst('contact', [], ['self' => true, 'uid' => $item['uid']]);
  1384. if (DBA::isResult($contact)) {
  1385. return $contact;
  1386. }
  1387. }
  1388. return false;
  1389. }
  1390. /**
  1391. * @brief Processes an incoming comment
  1392. *
  1393. * @param array $importer Array of the importer user
  1394. * @param string $sender The sender of the message
  1395. * @param object $data The message object
  1396. * @param string $xml The original XML of the message
  1397. *
  1398. * @return int The message id of the generated comment or "false" if there was an error
  1399. */
  1400. private static function receiveComment(array $importer, $sender, $data, $xml)
  1401. {
  1402. $author = notags(unxmlify($data->author));
  1403. $guid = notags(unxmlify($data->guid));
  1404. $parent_guid = notags(unxmlify($data->parent_guid));
  1405. $text = unxmlify($data->text);
  1406. if (isset($data->created_at)) {
  1407. $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
  1408. } else {
  1409. $created_at = DateTimeFormat::utcNow();
  1410. }
  1411. if (isset($data->thread_parent_guid)) {
  1412. $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
  1413. $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
  1414. } else {
  1415. $thr_uri = "";
  1416. }
  1417. $contact = self::allowedContactByHandle($importer, $sender, true);
  1418. if (!$contact) {
  1419. return false;
  1420. }
  1421. $message_id = self::messageExists($importer["uid"], $guid);
  1422. if ($message_id) {
  1423. return true;
  1424. }
  1425. $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
  1426. if (!$parent_item) {
  1427. return false;
  1428. }
  1429. $person = self::personByHandle($author);
  1430. if (!is_array($person)) {
  1431. logger("unable to find author details");
  1432. return false;
  1433. }
  1434. // Fetch the contact id - if we know this contact
  1435. $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
  1436. $datarray = [];
  1437. $datarray["uid"] = $importer["uid"];
  1438. $datarray["contact-id"] = $author_contact["cid"];
  1439. $datarray["network"] = $author_contact["network"];
  1440. $datarray["author-link"] = $person["url"];
  1441. $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
  1442. $datarray["owner-link"] = $contact["url"];
  1443. $datarray["owner-id"] = Contact::getIdForURL($contact["url"], 0);
  1444. $datarray["guid"] = $guid;
  1445. $datarray["uri"] = self::getUriFromGuid($author, $guid);
  1446. $datarray["verb"] = ACTIVITY_POST;
  1447. $datarray["gravity"] = GRAVITY_COMMENT;
  1448. if ($thr_uri != "") {
  1449. $datarray["parent-uri"] = $thr_uri;
  1450. } else {
  1451. $datarray["parent-uri"] = $parent_item["uri"];
  1452. }
  1453. $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
  1454. $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
  1455. $datarray["source"] = $xml;
  1456. $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
  1457. $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
  1458. $body = Markdown::toBBCode($text);
  1459. $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
  1460. self::fetchGuid($datarray);
  1461. // If we are the origin of the parent we store the original data.
  1462. // We notify our followers during the item storage.
  1463. if ($parent_item["origin"]) {
  1464. $datarray['diaspora_signed_text'] = json_encode($data);
  1465. }
  1466. $message_id = Item::insert($datarray);
  1467. if ($message_id <= 0) {
  1468. return false;
  1469. }
  1470. if ($message_id) {
  1471. logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
  1472. if ($datarray['uid'] == 0) {
  1473. Item::distribute($message_id, json_encode($data));
  1474. }
  1475. }
  1476. return true;
  1477. }
  1478. /**
  1479. * @brief processes and stores private messages
  1480. *
  1481. * @param array $importer Array of the importer user
  1482. * @param array $contact The contact of the message
  1483. * @param object $data The message object
  1484. * @param array $msg Array of the processed message, author handle and key
  1485. * @param object $mesg The private message
  1486. * @param array $conversation The conversation record to which this message belongs
  1487. *
  1488. * @return bool "true" if it was successful
  1489. */
  1490. private static function receiveConversationMessage(array $importer, array $contact, $data, $msg, $mesg, $conversation)
  1491. {
  1492. $author = notags(unxmlify($data->author));
  1493. $guid = notags(unxmlify($data->guid));
  1494. $subject = notags(unxmlify($data->subject));
  1495. // "diaspora_handle" is the element name from the old version
  1496. // "author" is the element name from the new version
  1497. if ($mesg->author) {
  1498. $msg_author = notags(unxmlify($mesg->author));
  1499. } elseif ($mesg->diaspora_handle) {
  1500. $msg_author = notags(unxmlify($mesg->diaspora_handle));
  1501. } else {
  1502. return false;
  1503. }
  1504. $msg_guid = notags(unxmlify($mesg->guid));
  1505. $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
  1506. $msg_text = unxmlify($mesg->text);
  1507. $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
  1508. if ($msg_conversation_guid != $guid) {
  1509. logger("message conversation guid does not belong to the current conversation.");
  1510. return false;
  1511. }
  1512. $body = Markdown::toBBCode($msg_text);
  1513. $message_uri = $msg_author.":".$msg_guid;
  1514. $person = self::personByHandle($msg_author);
  1515. DBA::lock('mail');
  1516. if (DBA::exists('mail', ['guid' => $msg_guid, 'uid' => $importer["uid"]])) {
  1517. logger("duplicate message already delivered.", LOGGER_DEBUG);
  1518. return false;
  1519. }
  1520. q(
  1521. "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
  1522. VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
  1523. intval($importer["uid"]),
  1524. DBA::escape($msg_guid),
  1525. intval($conversation["id"]),
  1526. DBA::escape($person["name"]),
  1527. DBA::escape($person["photo"]),
  1528. DBA::escape($person["url"]),
  1529. intval($contact["id"]),
  1530. DBA::escape($subject),
  1531. DBA::escape($body),
  1532. 0,
  1533. 0,
  1534. DBA::escape($message_uri),
  1535. DBA::escape($author.":".$guid),
  1536. DBA::escape($msg_created_at)
  1537. );
  1538. DBA::unlock();
  1539. DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
  1540. notification(
  1541. [
  1542. "type" => NOTIFY_MAIL,
  1543. "notify_flags" => $importer["notify-flags"],
  1544. "language" => $importer["language"],
  1545. "to_name" => $importer["username"],
  1546. "to_email" => $importer["email"],
  1547. "uid" =>$importer["uid"],
  1548. "item" => ["id" => $conversation["id"], "title" => $subject, "subject" => $subject, "body" => $body],
  1549. "source_name" => $person["name"],
  1550. "source_link" => $person["url"],
  1551. "source_photo" => $person["photo"],
  1552. "verb" => ACTIVITY_POST,
  1553. "otype" => "mail"]
  1554. );
  1555. return true;
  1556. }
  1557. /**
  1558. * @brief Processes new private messages (answers to private messages are processed elsewhere)
  1559. *
  1560. * @param array $importer Array of the importer user
  1561. * @param array $msg Array of the processed message, author handle and key
  1562. * @param object $data The message object
  1563. *
  1564. * @return bool Success
  1565. */
  1566. private static function receiveConversation(array $importer, $msg, $data)
  1567. {
  1568. $author = notags(unxmlify($data->author));
  1569. $guid = notags(unxmlify($data->guid));
  1570. $subject = notags(unxmlify($data->subject));
  1571. $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
  1572. $participants = notags(unxmlify($data->participants));
  1573. $messages = $data->message;
  1574. if (!count($messages)) {
  1575. logger("empty conversation");
  1576. return false;
  1577. }
  1578. $contact = self::allowedContactByHandle($importer, $msg["author"], true);
  1579. if (!$contact) {
  1580. return false;
  1581. }
  1582. $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
  1583. if (!DBA::isResult($conversation)) {
  1584. $r = q(
  1585. "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
  1586. VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
  1587. intval($importer["uid"]),
  1588. DBA::escape($guid),
  1589. DBA::escape($author),
  1590. DBA::escape($created_at),
  1591. DBA::escape(DateTimeFormat::utcNow()),
  1592. DBA::escape($subject),
  1593. DBA::escape($participants)
  1594. );
  1595. if ($r) {
  1596. $conversation = DBA::selectFirst('conv', [], ['uid' => $importer["uid"], 'guid' => $guid]);
  1597. }
  1598. }
  1599. if (!$conversation) {
  1600. logger("unable to create conversation.");
  1601. return false;
  1602. }
  1603. foreach ($messages as $mesg) {
  1604. self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
  1605. }
  1606. return true;
  1607. }
  1608. /**
  1609. * @brief Processes "like" messages
  1610. *
  1611. * @param array $importer Array of the importer user
  1612. * @param string $sender The sender of the message
  1613. * @param object $data The message object
  1614. *
  1615. * @return int The message id of the generated like or "false" if there was an error
  1616. */
  1617. private static function receiveLike(array $importer, $sender, $data)
  1618. {
  1619. $author = notags(unxmlify($data->author));
  1620. $guid = notags(unxmlify($data->guid));
  1621. $parent_guid = notags(unxmlify($data->parent_guid));
  1622. $parent_type = notags(unxmlify($data->parent_type));
  1623. $positive = notags(unxmlify($data->positive));
  1624. // likes on comments aren't supported by Diaspora - only on posts
  1625. // But maybe this will be supported in the future, so we will accept it.
  1626. if (!in_array($parent_type, ["Post", "Comment"])) {
  1627. return false;
  1628. }
  1629. $contact = self::allowedContactByHandle($importer, $sender, true);
  1630. if (!$contact) {
  1631. return false;
  1632. }
  1633. $message_id = self::messageExists($importer["uid"], $guid);
  1634. if ($message_id) {
  1635. return true;
  1636. }
  1637. $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
  1638. if (!$parent_item) {
  1639. return false;
  1640. }
  1641. $person = self::personByHandle($author);
  1642. if (!is_array($person)) {
  1643. logger("unable to find author details");
  1644. return false;
  1645. }
  1646. // Fetch the contact id - if we know this contact
  1647. $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
  1648. // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
  1649. // We would accept this anyhow.
  1650. if ($positive == "true") {
  1651. $verb = ACTIVITY_LIKE;
  1652. } else {
  1653. $verb = ACTIVITY_DISLIKE;
  1654. }
  1655. $datarray = [];
  1656. $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
  1657. $datarray["uid"] = $importer["uid"];
  1658. $datarray["contact-id"] = $author_contact["cid"];
  1659. $datarray["network"] = $author_contact["network"];
  1660. $datarray["owner-link"] = $datarray["author-link"] = $person["url"];
  1661. $datarray["owner-id"] = $datarray["author-id"] = Contact::getIdForURL($person["url"], 0);
  1662. $datarray["guid"] = $guid;
  1663. $datarray["uri"] = self::getUriFromGuid($author, $guid);
  1664. $datarray["verb"] = $verb;
  1665. $datarray["gravity"] = GRAVITY_ACTIVITY;
  1666. $datarray["parent-uri"] = $parent_item["uri"];
  1667. $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
  1668. $datarray["body"] = $verb;
  1669. // Diaspora doesn't provide a date for likes
  1670. $datarray["changed"] = $datarray["created"] = $datarray["edited"] = DateTimeFormat::utcNow();
  1671. // like on comments have the comment as parent. So we need to fetch the toplevel parent
  1672. if ($parent_item["id"] != $parent_item["parent"]) {
  1673. $toplevel = Item::selectFirst(['origin'], ['id' => $parent_item["parent"]]);
  1674. $origin = $toplevel["origin"];
  1675. } else {
  1676. $origin = $parent_item["origin"];
  1677. }
  1678. // If we are the origin of the parent we store the original data.
  1679. // We notify our followers during the item storage.
  1680. if ($origin) {
  1681. $datarray['diaspora_signed_text'] = json_encode($data);
  1682. }
  1683. $message_id = Item::insert($datarray);
  1684. if ($message_id <= 0) {
  1685. return false;
  1686. }
  1687. if ($message_id) {
  1688. logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
  1689. if ($datarray['uid'] == 0) {
  1690. Item::distribute($message_id, json_encode($data));
  1691. }
  1692. }
  1693. return true;
  1694. }
  1695. /**
  1696. * @brief Processes private messages
  1697. *
  1698. * @param array $importer Array of the importer user
  1699. * @param object $data The message object
  1700. *
  1701. * @return bool Success?
  1702. */
  1703. private static function receiveMessage(array $importer, $data)
  1704. {
  1705. $author = notags(unxmlify($data->author));
  1706. $guid = notags(unxmlify($data->guid));
  1707. $conversation_guid = notags(unxmlify($data->conversation_guid));
  1708. $text = unxmlify($data->text);
  1709. $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
  1710. $contact = self::allowedContactByHandle($importer, $author, true);
  1711. if (!$contact) {
  1712. return false;
  1713. }
  1714. $conversation = null;
  1715. $condition = ['uid' => $importer["uid"], 'guid' => $conversation_guid];
  1716. $conversation = DBA::selectFirst('conv', [], $condition);
  1717. if (!DBA::isResult($conversation)) {
  1718. logger("conversation not available.");
  1719. return false;
  1720. }
  1721. $message_uri = $author.":".$guid;
  1722. $person = self::personByHandle($author);
  1723. if (!$person) {
  1724. logger("unable to find author details");
  1725. return false;
  1726. }
  1727. $body = Markdown::toBBCode($text);
  1728. $body = self::replacePeopleGuid($body, $person["url"]);
  1729. DBA::lock('mail');
  1730. if (DBA::exists('mail', ['guid' => $guid, 'uid' => $importer["uid"]])) {
  1731. logger("duplicate message already delivered.", LOGGER_DEBUG);
  1732. return false;
  1733. }
  1734. q(
  1735. "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
  1736. VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
  1737. intval($importer["uid"]),
  1738. DBA::escape($guid),
  1739. intval($conversation["id"]),
  1740. DBA::escape($person["name"]),
  1741. DBA::escape($person["photo"]),
  1742. DBA::escape($person["url"]),
  1743. intval($contact["id"]),
  1744. DBA::escape($conversation["subject"]),
  1745. DBA::escape($body),
  1746. 0,
  1747. 1,
  1748. DBA::escape($message_uri),
  1749. DBA::escape($author.":".$conversation["guid"]),
  1750. DBA::escape($created_at)
  1751. );
  1752. DBA::unlock();
  1753. DBA::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
  1754. return true;
  1755. }
  1756. /**
  1757. * @brief Processes participations - unsupported by now
  1758. *
  1759. * @param array $importer Array of the importer user
  1760. * @param object $data The message object
  1761. *
  1762. * @return bool always true
  1763. */
  1764. private static function receiveParticipation(array $importer, $data)
  1765. {
  1766. $author = strtolower(notags(unxmlify($data->author)));
  1767. $parent_guid = notags(unxmlify($data->parent_guid));
  1768. $contact_id = Contact::getIdForURL($author);
  1769. if (!$contact_id) {
  1770. logger('Contact not found: '.$author);
  1771. return false;
  1772. }
  1773. $person = self::personByHandle($author);
  1774. if (!is_array($person)) {
  1775. logger("Person not found: ".$author);
  1776. return false;
  1777. }
  1778. $item = Item::selectFirst(['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
  1779. if (!DBA::isResult($item)) {
  1780. logger('Item not found, no origin or private: '.$parent_guid);
  1781. return false;
  1782. }
  1783. $author_parts = explode('@', $author);
  1784. if (isset($author_parts[1])) {
  1785. $server = $author_parts[1];
  1786. } else {
  1787. // Should never happen
  1788. $server = $author;
  1789. }
  1790. logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
  1791. if (!DBA::exists('participation', ['iid' => $item['id'], 'server' => $server])) {
  1792. DBA::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
  1793. }
  1794. // Send all existing comments and likes to the requesting server
  1795. $comments = Item::select(['id', 'parent', 'verb', 'self'], ['parent' => $item['id']]);
  1796. while ($comment = Item::fetch($comments)) {
  1797. if ($comment['id'] == $comment['parent']) {
  1798. continue;
  1799. }
  1800. if ($comment['verb'] == ACTIVITY_POST) {
  1801. $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
  1802. } else {
  1803. $cmd = $comment['self'] ? 'like' : 'comment-import';
  1804. }
  1805. logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
  1806. Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
  1807. }
  1808. DBA::close($comments);
  1809. return true;
  1810. }
  1811. /**
  1812. * @brief Processes photos - unneeded
  1813. *
  1814. * @param array $importer Array of the importer user
  1815. * @param object $data The message object
  1816. *
  1817. * @return bool always true
  1818. */
  1819. private static function receivePhoto(array $importer, $data)
  1820. {
  1821. // There doesn't seem to be a reason for this function,
  1822. // since the photo data is transmitted in the status message as well
  1823. return true;
  1824. }
  1825. /**
  1826. * @brief Processes poll participations - unssupported
  1827. *
  1828. * @param array $importer Array of the importer user
  1829. * @param object $data The message object
  1830. *
  1831. * @return bool always true
  1832. */
  1833. private static function receivePollParticipation(array $importer, $data)
  1834. {
  1835. // We don't support polls by now
  1836. return true;
  1837. }
  1838. /**
  1839. * @brief Processes incoming profile updates
  1840. *
  1841. * @param array $importer Array of the importer user
  1842. * @param object $data The message object
  1843. *
  1844. * @return bool Success
  1845. */
  1846. private static function receiveProfile(array $importer, $data)
  1847. {
  1848. $author = strtolower(notags(unxmlify($data->author)));
  1849. $contact = self::contactByHandle($importer["uid"], $author);
  1850. if (!$contact) {
  1851. return false;
  1852. }
  1853. $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
  1854. $image_url = unxmlify($data->image_url);
  1855. $birthday = unxmlify($data->birthday);
  1856. $gender = unxmlify($data->gender);
  1857. $about = Markdown::toBBCode(unxmlify($data->bio));
  1858. $location = Markdown::toBBCode(unxmlify($data->location));
  1859. $searchable = (unxmlify($data->searchable) == "true");
  1860. $nsfw = (unxmlify($data->nsfw) == "true");
  1861. $tags = unxmlify($data->tag_string);
  1862. $tags = explode("#", $tags);
  1863. $keywords = [];
  1864. foreach ($tags as $tag) {
  1865. $tag = trim(strtolower($tag));
  1866. if ($tag != "") {
  1867. $keywords[] = $tag;
  1868. }
  1869. }
  1870. $keywords = implode(", ", $keywords);
  1871. $handle_parts = explode("@", $author);
  1872. $nick = $handle_parts[0];
  1873. if ($name === "") {
  1874. $name = $handle_parts[0];
  1875. }
  1876. if (preg_match("|^https?://|", $image_url) === 0) {
  1877. $image_url = "http://".$handle_parts[1].$image_url;
  1878. }
  1879. Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
  1880. // Generic birthday. We don't know the timezone. The year is irrelevant.
  1881. $birthday = str_replace("1000", "1901", $birthday);
  1882. if ($birthday != "") {
  1883. $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
  1884. }
  1885. // this is to prevent multiple birthday notifications in a single year
  1886. // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
  1887. if (substr($birthday, 5) === substr($contact["bd"], 5)) {
  1888. $birthday = $contact["bd"];
  1889. }
  1890. $fields = ['name' => $name, 'location' => $location,
  1891. 'name-date' => DateTimeFormat::utcNow(),
  1892. 'about' => $about, 'gender' => $gender,
  1893. 'addr' => $author, 'nick' => $nick,
  1894. 'keywords' => $keywords];
  1895. if (!empty($birthday)) {
  1896. $fields['bd'] = $birthday;
  1897. }
  1898. DBA::update('contact', $fields, ['id' => $contact['id']]);
  1899. $gcontact = ["url" => $contact["url"], "network" => Protocol::DIASPORA, "generation" => 2,
  1900. "photo" => $image_url, "name" => $name, "location" => $location,
  1901. "about" => $about, "birthday" => $birthday, "gender" => $gender,
  1902. "addr" => $author, "nick" => $nick, "keywords" => $keywords,
  1903. "hide" => !$searchable, "nsfw" => $nsfw];
  1904. $gcid = GContact::update($gcontact);
  1905. GContact::link($gcid, $importer["uid"], $contact["id"]);
  1906. logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
  1907. return true;
  1908. }
  1909. /**
  1910. * @brief Processes incoming friend requests
  1911. *
  1912. * @param array $importer Array of the importer user
  1913. * @param array $contact The contact that send the request
  1914. * @return void
  1915. */
  1916. private static function receiveRequestMakeFriend(array $importer, array $contact)
  1917. {
  1918. $a = get_app();
  1919. if ($contact["rel"] == Contact::SHARING) {
  1920. DBA::update(
  1921. 'contact',
  1922. ['rel' => Contact::FRIEND, 'writable' => true],
  1923. ['id' => $contact["id"], 'uid' => $importer["uid"]]
  1924. );
  1925. }
  1926. }
  1927. /**
  1928. * @brief Processes incoming sharing notification
  1929. *
  1930. * @param array $importer Array of the importer user
  1931. * @param object $data The message object
  1932. *
  1933. * @return bool Success
  1934. */
  1935. private static function receiveContactRequest(array $importer, $data)
  1936. {
  1937. $author = unxmlify($data->author);
  1938. $recipient = unxmlify($data->recipient);
  1939. if (!$author || !$recipient) {
  1940. return false;
  1941. }
  1942. // the current protocol version doesn't know these fields
  1943. // That means that we will assume their existance
  1944. if (isset($data->following)) {
  1945. $following = (unxmlify($data->following) == "true");
  1946. } else {
  1947. $following = true;
  1948. }
  1949. if (isset($data->sharing)) {
  1950. $sharing = (unxmlify($data->sharing) == "true");
  1951. } else {
  1952. $sharing = true;
  1953. }
  1954. $contact = self::contactByHandle($importer["uid"], $author);
  1955. // perhaps we were already sharing with this person. Now they're sharing with us.
  1956. // That makes us friends.
  1957. if ($contact) {
  1958. if ($following) {
  1959. logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
  1960. self::receiveRequestMakeFriend($importer, $contact);
  1961. // refetch the contact array
  1962. $contact = self::contactByHandle($importer["uid"], $author);
  1963. // If we are now friends, we are sending a share message.
  1964. // Normally we needn't to do so, but the first message could have been vanished.
  1965. if (in_array($contact["rel"], [Contact::FRIEND])) {
  1966. $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
  1967. if (DBA::isResult($user)) {
  1968. logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
  1969. $ret = self::sendShare($user, $contact);
  1970. }
  1971. }
  1972. return true;
  1973. } else {
  1974. logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
  1975. Contact::removeFollower($importer, $contact);
  1976. return true;
  1977. }
  1978. }
  1979. if (!$following && $sharing && in_array($importer["page-flags"], [Contact::PAGE_SOAPBOX, Contact::PAGE_NORMAL])) {
  1980. logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
  1981. return false;
  1982. } elseif (!$following && !$sharing) {
  1983. logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
  1984. return false;
  1985. } elseif (!$following && $sharing) {
  1986. logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
  1987. } elseif ($following && $sharing) {
  1988. logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
  1989. } elseif ($following && !$sharing) {
  1990. logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
  1991. }
  1992. $ret = self::personByHandle($author);
  1993. if (!$ret || ($ret["network"] != Protocol::DIASPORA)) {
  1994. logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
  1995. return false;
  1996. }
  1997. $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
  1998. $r = q(
  1999. "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
  2000. VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
  2001. intval($importer["uid"]),
  2002. DBA::escape($ret["network"]),
  2003. DBA::escape($ret["addr"]),
  2004. DateTimeFormat::utcNow(),
  2005. DBA::escape($ret["url"]),
  2006. DBA::escape(normalise_link($ret["url"])),
  2007. DBA::escape($batch),
  2008. DBA::escape($ret["name"]),
  2009. DBA::escape($ret["nick"]),
  2010. DBA::escape($ret["photo"]),
  2011. DBA::escape($ret["pubkey"]),
  2012. DBA::escape($ret["notify"]),
  2013. DBA::escape($ret["poll"]),
  2014. 1,
  2015. 2
  2016. );
  2017. // find the contact record we just created
  2018. $contact_record = self::contactByHandle($importer["uid"], $author);
  2019. if (!$contact_record) {
  2020. logger("unable to locate newly created contact record.");
  2021. return;
  2022. }
  2023. logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
  2024. Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
  2025. Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
  2026. if (in_array($importer["page-flags"], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP])) {
  2027. logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
  2028. $hash = random_string().(string)time(); // Generate a confirm_key
  2029. $ret = q(
  2030. "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
  2031. VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
  2032. intval($importer["uid"]),
  2033. intval($contact_record["id"]),
  2034. 0,
  2035. 0,
  2036. DBA::escape(L10n::t("Sharing notification from Diaspora network")),
  2037. DBA::escape($hash),
  2038. DBA::escape(DateTimeFormat::utcNow())
  2039. );
  2040. } else {
  2041. // automatic friend approval
  2042. logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
  2043. Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
  2044. /*
  2045. * technically they are sharing with us (Contact::SHARING),
  2046. * but if our page-type is Profile::PAGE_COMMUNITY or Profile::PAGE_SOAPBOX
  2047. * we are going to change the relationship and make them a follower.
  2048. */
  2049. if (($importer["page-flags"] == Contact::PAGE_FREELOVE) && $sharing && $following) {
  2050. $new_relation = Contact::FRIEND;
  2051. } elseif (($importer["page-flags"] == Contact::PAGE_FREELOVE) && $sharing) {
  2052. $new_relation = Contact::SHARING;
  2053. } else {
  2054. $new_relation = Contact::FOLLOWER;
  2055. }
  2056. $r = q(
  2057. "UPDATE `contact` SET `rel` = %d,
  2058. `name-date` = '%s',
  2059. `uri-date` = '%s',
  2060. `blocked` = 0,
  2061. `pending` = 0,
  2062. `writable` = 1
  2063. WHERE `id` = %d
  2064. ",
  2065. intval($new_relation),
  2066. DBA::escape(DateTimeFormat::utcNow()),
  2067. DBA::escape(DateTimeFormat::utcNow()),
  2068. intval($contact_record["id"])
  2069. );
  2070. $user = DBA::selectFirst('user', [], ['uid' => $importer["uid"]]);
  2071. if (DBA::isResult($user)) {
  2072. logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
  2073. $ret = self::sendShare($user, $contact_record);
  2074. // Send the profile data, maybe it weren't transmitted before
  2075. self::sendProfile($importer["uid"], [$contact_record]);
  2076. }
  2077. }
  2078. return true;
  2079. }
  2080. /**
  2081. * @brief Fetches a message with a given guid
  2082. *
  2083. * @param string $guid message guid
  2084. * @param string $orig_author handle of the original post
  2085. * @param string $author handle of the sharer
  2086. *
  2087. * @return array The fetched item
  2088. */
  2089. public static function originalItem($guid, $orig_author)
  2090. {
  2091. if (empty($guid)) {
  2092. logger('Empty guid. Quitting.');
  2093. return false;
  2094. }
  2095. // Do we already have this item?
  2096. $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
  2097. 'author-name', 'author-link', 'author-avatar'];
  2098. $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
  2099. $item = Item::selectFirst($fields, $condition);
  2100. if (DBA::isResult($item)) {
  2101. logger("reshared message ".$guid." already exists on system.");
  2102. // Maybe it is already a reshared item?
  2103. // Then refetch the content, if it is a reshare from a reshare.
  2104. // If it is a reshared post from another network then reformat to avoid display problems with two share elements
  2105. if (self::isReshare($item["body"], true)) {
  2106. $item = [];
  2107. } elseif (self::isReshare($item["body"], false) || strstr($item["body"], "[share")) {
  2108. $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
  2109. $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
  2110. // Add OEmbed and other information to the body
  2111. $item["body"] = add_page_info_to_body($item["body"], false, true);
  2112. return $item;
  2113. } else {
  2114. return $item;
  2115. }
  2116. }
  2117. if (!DBA::isResult($item)) {
  2118. if (empty($orig_author)) {
  2119. logger('Empty author for guid ' . $guid . '. Quitting.');
  2120. return false;
  2121. }
  2122. $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
  2123. logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
  2124. $stored = self::storeByGuid($guid, $server);
  2125. if (!$stored) {
  2126. $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
  2127. logger("2nd try: reshared message ".$guid." will be fetched without SSL from the server ".$server);
  2128. $stored = self::storeByGuid($guid, $server);
  2129. }
  2130. if ($stored) {
  2131. $fields = ['body', 'tag', 'app', 'created', 'object-type', 'uri', 'guid',
  2132. 'author-name', 'author-link', 'author-avatar'];
  2133. $condition = ['guid' => $guid, 'visible' => true, 'deleted' => false, 'private' => false];
  2134. $item = Item::selectFirst($fields, $condition);
  2135. if (DBA::isResult($item)) {
  2136. // If it is a reshared post from another network then reformat to avoid display problems with two share elements
  2137. if (self::isReshare($item["body"], false)) {
  2138. $item["body"] = Markdown::toBBCode(BBCode::toMarkdown($item["body"]));
  2139. $item["body"] = self::replacePeopleGuid($item["body"], $item["author-link"]);
  2140. }
  2141. return $item;
  2142. }
  2143. }
  2144. }
  2145. return false;
  2146. }
  2147. /**
  2148. * @brief Processes a reshare message
  2149. *
  2150. * @param array $importer Array of the importer user
  2151. * @param object $data The message object
  2152. * @param string $xml The original XML of the message
  2153. *
  2154. * @return int the message id
  2155. */
  2156. private static function receiveReshare(array $importer, $data, $xml)
  2157. {
  2158. $author = notags(unxmlify($data->author));
  2159. $guid = notags(unxmlify($data->guid));
  2160. $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
  2161. $root_author = notags(unxmlify($data->root_author));
  2162. $root_guid = notags(unxmlify($data->root_guid));
  2163. /// @todo handle unprocessed property "provider_display_name"
  2164. $public = notags(unxmlify($data->public));
  2165. $contact = self::allowedContactByHandle($importer, $author, false);
  2166. if (!$contact) {
  2167. return false;
  2168. }
  2169. $message_id = self::messageExists($importer["uid"], $guid);
  2170. if ($message_id) {
  2171. return true;
  2172. }
  2173. $original_item = self::originalItem($root_guid, $root_author);
  2174. if (!$original_item) {
  2175. return false;
  2176. }
  2177. $orig_url = System::baseUrl()."/display/".$original_item["guid"];
  2178. $datarray = [];
  2179. $datarray["uid"] = $importer["uid"];
  2180. $datarray["contact-id"] = $contact["id"];
  2181. $datarray["network"] = Protocol::DIASPORA;
  2182. $datarray["author-link"] = $contact["url"];
  2183. $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
  2184. $datarray["owner-link"] = $datarray["author-link"];
  2185. $datarray["owner-id"] = $datarray["author-id"];
  2186. $datarray["guid"] = $guid;
  2187. $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
  2188. $datarray["verb"] = ACTIVITY_POST;
  2189. $datarray["gravity"] = GRAVITY_PARENT;
  2190. $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
  2191. $datarray["source"] = $xml;
  2192. $prefix = share_header(
  2193. $original_item["author-name"],
  2194. $original_item["author-link"],
  2195. $original_item["author-avatar"],
  2196. $original_item["guid"],
  2197. $original_item["created"],
  2198. $orig_url
  2199. );
  2200. $datarray["body"] = $prefix.$original_item["body"]."[/share]";
  2201. $datarray["tag"] = $original_item["tag"];
  2202. $datarray["app"] = $original_item["app"];
  2203. $datarray["plink"] = self::plink($author, $guid);
  2204. $datarray["private"] = (($public == "false") ? 1 : 0);
  2205. $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
  2206. $datarray["object-type"] = $original_item["object-type"];
  2207. self::fetchGuid($datarray);
  2208. $message_id = Item::insert($datarray);
  2209. self::sendParticipation($contact, $datarray);
  2210. if ($message_id) {
  2211. logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
  2212. if ($datarray['uid'] == 0) {
  2213. Item::distribute($message_id);
  2214. }
  2215. return true;
  2216. } else {
  2217. return false;
  2218. }
  2219. }
  2220. /**
  2221. * @brief Processes retractions
  2222. *
  2223. * @param array $importer Array of the importer user
  2224. * @param array $contact The contact of the item owner
  2225. * @param object $data The message object
  2226. *
  2227. * @return bool success
  2228. */
  2229. private static function itemRetraction(array $importer, array $contact, $data)
  2230. {
  2231. $author = notags(unxmlify($data->author));
  2232. $target_guid = notags(unxmlify($data->target_guid));
  2233. $target_type = notags(unxmlify($data->target_type));
  2234. $person = self::personByHandle($author);
  2235. if (!is_array($person)) {
  2236. logger("unable to find author detail for ".$author);
  2237. return false;
  2238. }
  2239. if (empty($contact["url"])) {
  2240. $contact["url"] = $person["url"];
  2241. }
  2242. // Fetch items that are about to be deleted
  2243. $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link', 'file'];
  2244. // When we receive a public retraction, we delete every item that we find.
  2245. if ($importer['uid'] == 0) {
  2246. $condition = ['guid' => $target_guid, 'deleted' => false];
  2247. } else {
  2248. $condition = ['guid' => $target_guid, 'deleted' => false, 'uid' => $importer['uid']];
  2249. }
  2250. $r = Item::select($fields, $condition);
  2251. if (!DBA::isResult($r)) {
  2252. logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
  2253. return false;
  2254. }
  2255. while ($item = Item::fetch($r)) {
  2256. if (strstr($item['file'], '[')) {
  2257. logger("Target guid " . $target_guid . " for user " . $item['uid'] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
  2258. continue;
  2259. }
  2260. // Fetch the parent item
  2261. $parent = Item::selectFirst(['author-link'], ['id' => $item["parent"]]);
  2262. // Only delete it if the parent author really fits
  2263. if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
  2264. logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
  2265. continue;
  2266. }
  2267. Item::delete(['id' => $item['id']]);
  2268. logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
  2269. }
  2270. return true;
  2271. }
  2272. /**
  2273. * @brief Receives retraction messages
  2274. *
  2275. * @param array $importer Array of the importer user
  2276. * @param string $sender The sender of the message
  2277. * @param object $data The message object
  2278. *
  2279. * @return bool Success
  2280. */
  2281. private static function receiveRetraction(array $importer, $sender, $data)
  2282. {
  2283. $target_type = notags(unxmlify($data->target_type));
  2284. $contact = self::contactByHandle($importer["uid"], $sender);
  2285. if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
  2286. logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
  2287. return false;
  2288. }
  2289. if (!$contact) {
  2290. $contact = [];
  2291. }
  2292. logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
  2293. switch ($target_type) {
  2294. case "Comment":
  2295. case "Like":
  2296. case "Post":
  2297. case "Reshare":
  2298. case "StatusMessage":
  2299. return self::itemRetraction($importer, $contact, $data);
  2300. case "PollParticipation":
  2301. case "Photo":
  2302. // Currently unsupported
  2303. break;
  2304. default:
  2305. logger("Unknown target type ".$target_type);
  2306. return false;
  2307. }
  2308. return true;
  2309. }
  2310. /**
  2311. * @brief Receives status messages
  2312. *
  2313. * @param array $importer Array of the importer user
  2314. * @param object $data The message object
  2315. * @param string $xml The original XML of the message
  2316. *
  2317. * @return int The message id of the newly created item
  2318. */
  2319. private static function receiveStatusMessage(array $importer, SimpleXMLElement $data, $xml)
  2320. {
  2321. $author = notags(unxmlify($data->author));
  2322. $guid = notags(unxmlify($data->guid));
  2323. $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
  2324. $public = notags(unxmlify($data->public));
  2325. $text = unxmlify($data->text);
  2326. $provider_display_name = notags(unxmlify($data->provider_display_name));
  2327. $contact = self::allowedContactByHandle($importer, $author, false);
  2328. if (!$contact) {
  2329. return false;
  2330. }
  2331. $message_id = self::messageExists($importer["uid"], $guid);
  2332. if ($message_id) {
  2333. return true;
  2334. }
  2335. $address = [];
  2336. if ($data->location) {
  2337. foreach ($data->location->children() as $fieldname => $data) {
  2338. $address[$fieldname] = notags(unxmlify($data));
  2339. }
  2340. }
  2341. $body = Markdown::toBBCode($text);
  2342. $datarray = [];
  2343. // Attach embedded pictures to the body
  2344. if ($data->photo) {
  2345. foreach ($data->photo as $photo) {
  2346. $body = "[img]".unxmlify($photo->remote_photo_path).
  2347. unxmlify($photo->remote_photo_name)."[/img]\n".$body;
  2348. }
  2349. $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
  2350. } else {
  2351. $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
  2352. // Add OEmbed and other information to the body
  2353. if (!self::isRedmatrix($contact["url"])) {
  2354. $body = add_page_info_to_body($body, false, true);
  2355. }
  2356. }
  2357. /// @todo enable support for polls
  2358. //if ($data->poll) {
  2359. // foreach ($data->poll AS $poll)
  2360. // print_r($poll);
  2361. // die("poll!\n");
  2362. //}
  2363. /// @todo enable support for events
  2364. $datarray["uid"] = $importer["uid"];
  2365. $datarray["contact-id"] = $contact["id"];
  2366. $datarray["network"] = Protocol::DIASPORA;
  2367. $datarray["author-link"] = $contact["url"];
  2368. $datarray["author-id"] = Contact::getIdForURL($contact["url"], 0);
  2369. $datarray["owner-link"] = $datarray["author-link"];
  2370. $datarray["owner-id"] = $datarray["author-id"];
  2371. $datarray["guid"] = $guid;
  2372. $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
  2373. $datarray["verb"] = ACTIVITY_POST;
  2374. $datarray["gravity"] = GRAVITY_PARENT;
  2375. $datarray["protocol"] = Conversation::PARCEL_DIASPORA;
  2376. $datarray["source"] = $xml;
  2377. $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
  2378. if ($provider_display_name != "") {
  2379. $datarray["app"] = $provider_display_name;
  2380. }
  2381. $datarray["plink"] = self::plink($author, $guid);
  2382. $datarray["private"] = (($public == "false") ? 1 : 0);
  2383. $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
  2384. if (isset($address["address"])) {
  2385. $datarray["location"] = $address["address"];
  2386. }
  2387. if (isset($address["lat"]) && isset($address["lng"])) {
  2388. $datarray["coord"] = $address["lat"]." ".$address["lng"];
  2389. }
  2390. self::fetchGuid($datarray);
  2391. $message_id = Item::insert($datarray);
  2392. self::sendParticipation($contact, $datarray);
  2393. if ($message_id) {
  2394. logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
  2395. if ($datarray['uid'] == 0) {
  2396. Item::distribute($message_id);
  2397. }
  2398. return true;
  2399. } else {
  2400. return false;
  2401. }
  2402. }
  2403. /* ************************************************************************************** *
  2404. * Here are all the functions that are needed to transmit data with the Diaspora protocol *
  2405. * ************************************************************************************** */
  2406. /**
  2407. * @brief returnes the handle of a contact
  2408. *
  2409. * @param array $contact contact array
  2410. *
  2411. * @return string the handle in the format user@domain.tld
  2412. */
  2413. private static function myHandle(array $contact)
  2414. {
  2415. if (!empty($contact["addr"])) {
  2416. return $contact["addr"];
  2417. }
  2418. // Normally we should have a filled "addr" field - but in the past this wasn't the case
  2419. // So - just in case - we build the the address here.
  2420. if ($contact["nickname"] != "") {
  2421. $nick = $contact["nickname"];
  2422. } else {
  2423. $nick = $contact["nick"];
  2424. }
  2425. return $nick . "@" . substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
  2426. }
  2427. /**
  2428. * @brief Creates the data for a private message in the new format
  2429. *
  2430. * @param string $msg The message that is to be transmitted
  2431. * @param array $user The record of the sender
  2432. * @param array $contact Target of the communication
  2433. * @param string $prvkey The private key of the sender
  2434. * @param string $pubkey The public key of the receiver
  2435. *
  2436. * @return string The encrypted data
  2437. */
  2438. public static function encodePrivateData($msg, array $user, array $contact, $prvkey, $pubkey)
  2439. {
  2440. logger("Message: ".$msg, LOGGER_DATA);
  2441. // without a public key nothing will work
  2442. if (!$pubkey) {
  2443. logger("pubkey missing: contact id: ".$contact["id"]);
  2444. return false;
  2445. }
  2446. $aes_key = openssl_random_pseudo_bytes(32);
  2447. $b_aes_key = base64_encode($aes_key);
  2448. $iv = openssl_random_pseudo_bytes(16);
  2449. $b_iv = base64_encode($iv);
  2450. $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
  2451. $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
  2452. $encrypted_key_bundle = "";
  2453. openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
  2454. $json_object = json_encode(
  2455. ["aes_key" => base64_encode($encrypted_key_bundle),
  2456. "encrypted_magic_envelope" => base64_encode($ciphertext)]
  2457. );
  2458. return $json_object;
  2459. }
  2460. /**
  2461. * @brief Creates the envelope for the "fetch" endpoint and for the new format
  2462. *
  2463. * @param string $msg The message that is to be transmitted
  2464. * @param array $user The record of the sender
  2465. *
  2466. * @return string The envelope
  2467. */
  2468. public static function buildMagicEnvelope($msg, array $user)
  2469. {
  2470. $b64url_data = base64url_encode($msg);
  2471. $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
  2472. $key_id = base64url_encode(self::myHandle($user));
  2473. $type = "application/xml";
  2474. $encoding = "base64url";
  2475. $alg = "RSA-SHA256";
  2476. $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
  2477. // Fallback if the private key wasn't transmitted in the expected field
  2478. if ($user['uprvkey'] == "") {
  2479. $user['uprvkey'] = $user['prvkey'];
  2480. }
  2481. $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
  2482. $sig = base64url_encode($signature);
  2483. $xmldata = ["me:env" => ["me:data" => $data,
  2484. "@attributes" => ["type" => $type],
  2485. "me:encoding" => $encoding,
  2486. "me:alg" => $alg,
  2487. "me:sig" => $sig,
  2488. "@attributes2" => ["key_id" => $key_id]]];
  2489. $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
  2490. return XML::fromArray($xmldata, $xml, false, $namespaces);
  2491. }
  2492. /**
  2493. * @brief Create the envelope for a message
  2494. *
  2495. * @param string $msg The message that is to be transmitted
  2496. * @param array $user The record of the sender
  2497. * @param array $contact Target of the communication
  2498. * @param string $prvkey The private key of the sender
  2499. * @param string $pubkey The public key of the receiver
  2500. * @param bool $public Is the message public?
  2501. *
  2502. * @return string The message that will be transmitted to other servers
  2503. */
  2504. public static function buildMessage($msg, array $user, array $contact, $prvkey, $pubkey, $public = false)
  2505. {
  2506. // The message is put into an envelope with the sender's signature
  2507. $envelope = self::buildMagicEnvelope($msg, $user);
  2508. // Private messages are put into a second envelope, encrypted with the receivers public key
  2509. if (!$public) {
  2510. $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
  2511. }
  2512. return $envelope;
  2513. }
  2514. /**
  2515. * @brief Creates a signature for a message
  2516. *
  2517. * @param array $owner the array of the owner of the message
  2518. * @param array $message The message that is to be signed
  2519. *
  2520. * @return string The signature
  2521. */
  2522. private static function signature($owner, $message)
  2523. {
  2524. $sigmsg = $message;
  2525. unset($sigmsg["author_signature"]);
  2526. unset($sigmsg["parent_author_signature"]);
  2527. $signed_text = implode(";", $sigmsg);
  2528. return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
  2529. }
  2530. /**
  2531. * @brief Transmit a message to a target server
  2532. *
  2533. * @param array $owner the array of the item owner
  2534. * @param array $contact Target of the communication
  2535. * @param string $envelope The message that is to be transmitted
  2536. * @param bool $public_batch Is it a public post?
  2537. * @param bool $queue_run Is the transmission called from the queue?
  2538. * @param string $guid message guid
  2539. *
  2540. * @return int Result of the transmission
  2541. */
  2542. public static function transmit(array $owner, array $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
  2543. {
  2544. $a = get_app();
  2545. $enabled = intval(Config::get("system", "diaspora_enabled"));
  2546. if (!$enabled) {
  2547. return 200;
  2548. }
  2549. $logid = random_string(4);
  2550. $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
  2551. // We always try to use the data from the fcontact table.
  2552. // This is important for transmitting data to Friendica servers.
  2553. if (!empty($contact['addr'])) {
  2554. $fcontact = self::personByHandle($contact['addr']);
  2555. if (!empty($fcontact)) {
  2556. $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
  2557. }
  2558. }
  2559. if (!$dest_url) {
  2560. logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
  2561. return 0;
  2562. }
  2563. logger("transmit: ".$logid."-".$guid." ".$dest_url);
  2564. if (!$queue_run && Queue::wasDelayed($contact["id"])) {
  2565. $return_code = 0;
  2566. } else {
  2567. if (!intval(Config::get("system", "diaspora_test"))) {
  2568. $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
  2569. Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
  2570. $return_code = $a->get_curl_code();
  2571. } else {
  2572. logger("test_mode");
  2573. return 200;
  2574. }
  2575. }
  2576. logger("transmit: ".$logid."-".$guid." to ".$dest_url." returns: ".$return_code);
  2577. if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
  2578. if (!$no_queue && !empty($contact['contact-type']) && ($contact['contact-type'] != Contact::ACCOUNT_TYPE_RELAY)) {
  2579. logger("queue message");
  2580. // queue message for redelivery
  2581. Queue::add($contact["id"], Protocol::DIASPORA, $envelope, $public_batch, $guid);
  2582. }
  2583. // The message could not be delivered. We mark the contact as "dead"
  2584. Contact::markForArchival($contact);
  2585. } elseif (($return_code >= 200) && ($return_code <= 299)) {
  2586. // We successfully delivered a message, the contact is alive
  2587. Contact::unmarkForArchival($contact);
  2588. }
  2589. return $return_code ? $return_code : -1;
  2590. }
  2591. /**
  2592. * @brief Build the post xml
  2593. *
  2594. * @param string $type The message type
  2595. * @param array $message The message data
  2596. *
  2597. * @return string The post XML
  2598. */
  2599. public static function buildPostXml($type, $message)
  2600. {
  2601. $data = [$type => $message];
  2602. return XML::fromArray($data, $xml);
  2603. }
  2604. /**
  2605. * @brief Builds and transmit messages
  2606. *
  2607. * @param array $owner the array of the item owner
  2608. * @param array $contact Target of the communication
  2609. * @param string $type The message type
  2610. * @param array $message The message data
  2611. * @param bool $public_batch Is it a public post?
  2612. * @param string $guid message guid
  2613. * @param bool $spool Should the transmission be spooled or transmitted?
  2614. *
  2615. * @return int Result of the transmission
  2616. */
  2617. private static function buildAndTransmit(array $owner, array $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
  2618. {
  2619. $msg = self::buildPostXml($type, $message);
  2620. logger('message: '.$msg, LOGGER_DATA);
  2621. logger('send guid '.$guid, LOGGER_DEBUG);
  2622. // Fallback if the private key wasn't transmitted in the expected field
  2623. if (empty($owner['uprvkey'])) {
  2624. $owner['uprvkey'] = $owner['prvkey'];
  2625. }
  2626. $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
  2627. if ($spool) {
  2628. Queue::add($contact['id'], Protocol::DIASPORA, $envelope, $public_batch, $guid);
  2629. return true;
  2630. } else {
  2631. $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
  2632. }
  2633. logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
  2634. return $return_code;
  2635. }
  2636. /**
  2637. * @brief sends a participation (Used to get all further updates)
  2638. *
  2639. * @param array $contact Target of the communication
  2640. * @param array $item Item array
  2641. *
  2642. * @return int The result of the transmission
  2643. */
  2644. private static function sendParticipation(array $contact, array $item)
  2645. {
  2646. // Don't send notifications for private postings
  2647. if ($item['private']) {
  2648. return;
  2649. }
  2650. $cachekey = "diaspora:sendParticipation:".$item['guid'];
  2651. $result = Cache::get($cachekey);
  2652. if (!is_null($result)) {
  2653. return;
  2654. }
  2655. // Fetch some user id to have a valid handle to transmit the participation.
  2656. // In fact it doesn't matter which user sends this - but it is needed by the protocol.
  2657. // If the item belongs to a user, we take this user id.
  2658. if ($item['uid'] == 0) {
  2659. $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
  2660. $first_user = DBA::selectFirst('user', ['uid'], $condition);
  2661. $owner = User::getOwnerDataById($first_user['uid']);
  2662. } else {
  2663. $owner = User::getOwnerDataById($item['uid']);
  2664. }
  2665. $author = self::myHandle($owner);
  2666. $message = ["author" => $author,
  2667. "guid" => System::createUUID(),
  2668. "parent_type" => "Post",
  2669. "parent_guid" => $item["guid"]];
  2670. logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
  2671. // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
  2672. Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
  2673. return self::buildAndTransmit($owner, $contact, "participation", $message);
  2674. }
  2675. /**
  2676. * @brief sends an account migration
  2677. *
  2678. * @param array $owner the array of the item owner
  2679. * @param array $contact Target of the communication
  2680. * @param int $uid User ID
  2681. *
  2682. * @return int The result of the transmission
  2683. */
  2684. public static function sendAccountMigration(array $owner, array $contact, $uid)
  2685. {
  2686. $old_handle = PConfig::get($uid, 'system', 'previous_addr');
  2687. $profile = self::createProfileData($uid);
  2688. $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
  2689. $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
  2690. $message = ["author" => $old_handle,
  2691. "profile" => $profile,
  2692. "signature" => $signature];
  2693. logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
  2694. return self::buildAndTransmit($owner, $contact, "account_migration", $message);
  2695. }
  2696. /**
  2697. * @brief Sends a "share" message
  2698. *
  2699. * @param array $owner the array of the item owner
  2700. * @param array $contact Target of the communication
  2701. *
  2702. * @return int The result of the transmission
  2703. */
  2704. public static function sendShare(array $owner, array $contact)
  2705. {
  2706. /**
  2707. * @todo support the different possible combinations of "following" and "sharing"
  2708. * Currently, Diaspora only interprets the "sharing" field
  2709. *
  2710. * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
  2711. */
  2712. /*
  2713. switch ($contact["rel"]) {
  2714. case Contact::FRIEND:
  2715. $following = true;
  2716. $sharing = true;
  2717. case Contact::SHARING:
  2718. $following = false;
  2719. $sharing = true;
  2720. case Contact::FOLLOWER:
  2721. $following = true;
  2722. $sharing = false;
  2723. }
  2724. */
  2725. $message = ["author" => self::myHandle($owner),
  2726. "recipient" => $contact["addr"],
  2727. "following" => "true",
  2728. "sharing" => "true"];
  2729. logger("Send share ".print_r($message, true), LOGGER_DEBUG);
  2730. return self::buildAndTransmit($owner, $contact, "contact", $message);
  2731. }
  2732. /**
  2733. * @brief sends an "unshare"
  2734. *
  2735. * @param array $owner the array of the item owner
  2736. * @param array $contact Target of the communication
  2737. *
  2738. * @return int The result of the transmission
  2739. */
  2740. public static function sendUnshare(array $owner, array $contact)
  2741. {
  2742. $message = ["author" => self::myHandle($owner),
  2743. "recipient" => $contact["addr"],
  2744. "following" => "false",
  2745. "sharing" => "false"];
  2746. logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
  2747. return self::buildAndTransmit($owner, $contact, "contact", $message);
  2748. }
  2749. /**
  2750. * @brief Checks a message body if it is a reshare
  2751. *
  2752. * @param string $body The message body that is to be check
  2753. * @param bool $complete Should it be a complete check or a simple check?
  2754. *
  2755. * @return array|bool Reshare details or "false" if no reshare
  2756. */
  2757. public static function isReshare($body, $complete = true)
  2758. {
  2759. $body = trim($body);
  2760. // Skip if it isn't a pure repeated messages
  2761. // Does it start with a share?
  2762. if ((strpos($body, "[share") > 0) && $complete) {
  2763. return false;
  2764. }
  2765. // Does it end with a share?
  2766. if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
  2767. return false;
  2768. }
  2769. $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
  2770. // Skip if there is no shared message in there
  2771. if ($body == $attributes) {
  2772. return false;
  2773. }
  2774. // If we don't do the complete check we quit here
  2775. $guid = "";
  2776. preg_match("/guid='(.*?)'/ism", $attributes, $matches);
  2777. if (!empty($matches[1])) {
  2778. $guid = $matches[1];
  2779. }
  2780. preg_match('/guid="(.*?)"/ism', $attributes, $matches);
  2781. if (!empty($matches[1])) {
  2782. $guid = $matches[1];
  2783. }
  2784. if (($guid != "") && $complete) {
  2785. $condition = ['guid' => $guid, 'network' => [Protocol::DFRN, Protocol::DIASPORA]];
  2786. $item = Item::selectFirst(['contact-id'], $condition);
  2787. if (DBA::isResult($item)) {
  2788. $ret= [];
  2789. $ret["root_handle"] = self::handleFromContact($item["contact-id"]);
  2790. $ret["root_guid"] = $guid;
  2791. return $ret;
  2792. } elseif ($complete) {
  2793. // We are resharing something that isn't a DFRN or Diaspora post.
  2794. // So we have to return "false" on "$complete" to not trigger a reshare.
  2795. return false;
  2796. }
  2797. } elseif (($guid == "") && $complete) {
  2798. return false;
  2799. }
  2800. $ret["root_guid"] = $guid;
  2801. $profile = "";
  2802. preg_match("/profile='(.*?)'/ism", $attributes, $matches);
  2803. if (!empty($matches[1])) {
  2804. $profile = $matches[1];
  2805. }
  2806. preg_match('/profile="(.*?)"/ism', $attributes, $matches);
  2807. if (!empty($matches[1])) {
  2808. $profile = $matches[1];
  2809. }
  2810. $ret= [];
  2811. if ($profile != "") {
  2812. if (Contact::getIdForURL($profile)) {
  2813. $author = Contact::getDetailsByURL($profile);
  2814. $ret["root_handle"] = $author['addr'];
  2815. }
  2816. }
  2817. if (empty($ret) && !$complete) {
  2818. return true;
  2819. }
  2820. return $ret;
  2821. }
  2822. /**
  2823. * @brief Create an event array
  2824. *
  2825. * @param integer $event_id The id of the event
  2826. *
  2827. * @return array with event data
  2828. */
  2829. private static function buildEvent($event_id)
  2830. {
  2831. $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
  2832. if (!DBA::isResult($r)) {
  2833. return [];
  2834. }
  2835. $event = $r[0];
  2836. $eventdata = [];
  2837. $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
  2838. if (!DBA::isResult($r)) {
  2839. return [];
  2840. }
  2841. $user = $r[0];
  2842. $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
  2843. if (!DBA::isResult($r)) {
  2844. return [];
  2845. }
  2846. $owner = $r[0];
  2847. $eventdata['author'] = self::myHandle($owner);
  2848. if ($event['guid']) {
  2849. $eventdata['guid'] = $event['guid'];
  2850. }
  2851. $mask = DateTimeFormat::ATOM;
  2852. /// @todo - establish "all day" events in Friendica
  2853. $eventdata["all_day"] = "false";
  2854. if (!$event['adjust']) {
  2855. $eventdata['timezone'] = $user['timezone'];
  2856. if ($eventdata['timezone'] == "") {
  2857. $eventdata['timezone'] = 'UTC';
  2858. }
  2859. }
  2860. if ($event['start']) {
  2861. $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
  2862. }
  2863. if ($event['finish'] && !$event['nofinish']) {
  2864. $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
  2865. }
  2866. if ($event['summary']) {
  2867. $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
  2868. }
  2869. if ($event['desc']) {
  2870. $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
  2871. }
  2872. if ($event['location']) {
  2873. $event['location'] = preg_replace("/\[map\](.*?)\[\/map\]/ism", '$1', $event['location']);
  2874. $coord = Map::getCoordinates($event['location']);
  2875. $location = [];
  2876. $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
  2877. if (!empty($coord['lat']) && !empty($coord['lon'])) {
  2878. $location["lat"] = $coord['lat'];
  2879. $location["lng"] = $coord['lon'];
  2880. } else {
  2881. $location["lat"] = 0;
  2882. $location["lng"] = 0;
  2883. }
  2884. $eventdata['location'] = $location;
  2885. }
  2886. return $eventdata;
  2887. }
  2888. /**
  2889. * @brief Create a post (status message or reshare)
  2890. *
  2891. * @param array $item The item that will be exported
  2892. * @param array $owner the array of the item owner
  2893. *
  2894. * @return array
  2895. * 'type' -> Message type ("status_message" or "reshare")
  2896. * 'message' -> Array of XML elements of the status
  2897. */
  2898. public static function buildStatus(array $item, array $owner)
  2899. {
  2900. $cachekey = "diaspora:buildStatus:".$item['guid'];
  2901. $result = Cache::get($cachekey);
  2902. if (!is_null($result)) {
  2903. return $result;
  2904. }
  2905. $myaddr = self::myHandle($owner);
  2906. $public = ($item["private"] ? "false" : "true");
  2907. $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
  2908. // Detect a share element and do a reshare
  2909. if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
  2910. $message = ["author" => $myaddr,
  2911. "guid" => $item["guid"],
  2912. "created_at" => $created,
  2913. "root_author" => $ret["root_handle"],
  2914. "root_guid" => $ret["root_guid"],
  2915. "provider_display_name" => $item["app"],
  2916. "public" => $public];
  2917. $type = "reshare";
  2918. } else {
  2919. $title = $item["title"];
  2920. $body = $item["body"];
  2921. if ($item['author-link'] != $item['owner-link']) {
  2922. require_once 'mod/share.php';
  2923. $body = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
  2924. "", $item['created'], $item['plink']) . $body . '[/share]';
  2925. }
  2926. // convert to markdown
  2927. $body = html_entity_decode(BBCode::toMarkdown($body));
  2928. // Adding the title
  2929. if (strlen($title)) {
  2930. $body = "## ".html_entity_decode($title)."\n\n".$body;
  2931. }
  2932. if ($item["attach"]) {
  2933. $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
  2934. if ($cnt) {
  2935. $body .= "\n".L10n::t("Attachments:")."\n";
  2936. foreach ($matches as $mtch) {
  2937. $body .= "[".$mtch[3]."](".$mtch[1].")\n";
  2938. }
  2939. }
  2940. }
  2941. $location = [];
  2942. if ($item["location"] != "")
  2943. $location["address"] = $item["location"];
  2944. if ($item["coord"] != "") {
  2945. $coord = explode(" ", $item["coord"]);
  2946. $location["lat"] = $coord[0];
  2947. $location["lng"] = $coord[1];
  2948. }
  2949. $message = ["author" => $myaddr,
  2950. "guid" => $item["guid"],
  2951. "created_at" => $created,
  2952. "public" => $public,
  2953. "text" => $body,
  2954. "provider_display_name" => $item["app"],
  2955. "location" => $location];
  2956. // Diaspora rejects messages when they contain a location without "lat" or "lng"
  2957. if (!isset($location["lat"]) || !isset($location["lng"])) {
  2958. unset($message["location"]);
  2959. }
  2960. if ($item['event-id'] > 0) {
  2961. $event = self::buildEvent($item['event-id']);
  2962. if (count($event)) {
  2963. $message['event'] = $event;
  2964. if (!empty($event['location']['address']) &&
  2965. !empty($event['location']['lat']) &&
  2966. !empty($event['location']['lng'])) {
  2967. $message['location'] = $event['location'];
  2968. }
  2969. /// @todo Once Diaspora supports it, we will remove the body and the location hack above
  2970. // $message['text'] = '';
  2971. }
  2972. }
  2973. $type = "status_message";
  2974. }
  2975. $msg = ["type" => $type, "message" => $message];
  2976. Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
  2977. return $msg;
  2978. }
  2979. /**
  2980. * @brief Sends a post
  2981. *
  2982. * @param array $item The item that will be exported
  2983. * @param array $owner the array of the item owner
  2984. * @param array $contact Target of the communication
  2985. * @param bool $public_batch Is it a public post?
  2986. *
  2987. * @return int The result of the transmission
  2988. */
  2989. public static function sendStatus(array $item, array $owner, array $contact, $public_batch = false)
  2990. {
  2991. $status = self::buildStatus($item, $owner);
  2992. return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
  2993. }
  2994. /**
  2995. * @brief Creates a "like" object
  2996. *
  2997. * @param array $item The item that will be exported
  2998. * @param array $owner the array of the item owner
  2999. *
  3000. * @return array The data for a "like"
  3001. */
  3002. private static function constructLike(array $item, array $owner)
  3003. {
  3004. $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
  3005. if (!DBA::isResult($parent)) {
  3006. return false;
  3007. }
  3008. $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
  3009. $positive = null;
  3010. if ($item['verb'] === ACTIVITY_LIKE) {
  3011. $positive = "true";
  3012. } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
  3013. $positive = "false";
  3014. }
  3015. return(["author" => self::myHandle($owner),
  3016. "guid" => $item["guid"],
  3017. "parent_guid" => $parent["guid"],
  3018. "parent_type" => $target_type,
  3019. "positive" => $positive,
  3020. "author_signature" => ""]);
  3021. }
  3022. /**
  3023. * @brief Creates an "EventParticipation" object
  3024. *
  3025. * @param array $item The item that will be exported
  3026. * @param array $owner the array of the item owner
  3027. *
  3028. * @return array The data for an "EventParticipation"
  3029. */
  3030. private static function constructAttend(array $item, array $owner)
  3031. {
  3032. $parent = Item::selectFirst(['guid', 'uri', 'parent-uri'], ['uri' => $item["thr-parent"]]);
  3033. if (!DBA::isResult($parent)) {
  3034. return false;
  3035. }
  3036. switch ($item['verb']) {
  3037. case ACTIVITY_ATTEND:
  3038. $attend_answer = 'accepted';
  3039. break;
  3040. case ACTIVITY_ATTENDNO:
  3041. $attend_answer = 'declined';
  3042. break;
  3043. case ACTIVITY_ATTENDMAYBE:
  3044. $attend_answer = 'tentative';
  3045. break;
  3046. default:
  3047. logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
  3048. return false;
  3049. }
  3050. return(["author" => self::myHandle($owner),
  3051. "guid" => $item["guid"],
  3052. "parent_guid" => $parent["guid"],
  3053. "status" => $attend_answer,
  3054. "author_signature" => ""]);
  3055. }
  3056. /**
  3057. * @brief Creates the object for a comment
  3058. *
  3059. * @param array $item The item that will be exported
  3060. * @param array $owner the array of the item owner
  3061. *
  3062. * @return array The data for a comment
  3063. */
  3064. private static function constructComment(array $item, array $owner)
  3065. {
  3066. $cachekey = "diaspora:constructComment:".$item['guid'];
  3067. $result = Cache::get($cachekey);
  3068. if (!is_null($result)) {
  3069. return $result;
  3070. }
  3071. $parent = Item::selectFirst(['guid'], ['id' => $item["parent"], 'parent' => $item["parent"]]);
  3072. if (!DBA::isResult($parent)) {
  3073. return false;
  3074. }
  3075. $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
  3076. $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
  3077. $comment = ["author" => self::myHandle($owner),
  3078. "guid" => $item["guid"],
  3079. "created_at" => $created,
  3080. "parent_guid" => $parent["guid"],
  3081. "text" => $text,
  3082. "author_signature" => ""];
  3083. // Send the thread parent guid only if it is a threaded comment
  3084. if ($item['thr-parent'] != $item['parent-uri']) {
  3085. $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
  3086. }
  3087. Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
  3088. return($comment);
  3089. }
  3090. /**
  3091. * @brief Send a like or a comment
  3092. *
  3093. * @param array $item The item that will be exported
  3094. * @param array $owner the array of the item owner
  3095. * @param array $contact Target of the communication
  3096. * @param bool $public_batch Is it a public post?
  3097. *
  3098. * @return int The result of the transmission
  3099. */
  3100. public static function sendFollowup(array $item, array $owner, array $contact, $public_batch = false)
  3101. {
  3102. if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
  3103. $message = self::constructAttend($item, $owner);
  3104. $type = "event_participation";
  3105. } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
  3106. $message = self::constructLike($item, $owner);
  3107. $type = "like";
  3108. } else {
  3109. $message = self::constructComment($item, $owner);
  3110. $type = "comment";
  3111. }
  3112. if (!$message) {
  3113. return false;
  3114. }
  3115. $message["author_signature"] = self::signature($owner, $message);
  3116. return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
  3117. }
  3118. /**
  3119. * @brief Creates a message from a signature record entry
  3120. *
  3121. * @param array $item The item that will be exported
  3122. * @param array $signature The entry of the "sign" record
  3123. *
  3124. * @return string The message
  3125. */
  3126. private static function messageFromSignature(array $item, array $signature)
  3127. {
  3128. // Split the signed text
  3129. $signed_parts = explode(";", $signature['signed_text']);
  3130. if ($item["deleted"]) {
  3131. $message = ["author" => $signature['signer'],
  3132. "target_guid" => $signed_parts[0],
  3133. "target_type" => $signed_parts[1]];
  3134. } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
  3135. $message = ["author" => $signed_parts[4],
  3136. "guid" => $signed_parts[1],
  3137. "parent_guid" => $signed_parts[3],
  3138. "parent_type" => $signed_parts[2],
  3139. "positive" => $signed_parts[0],
  3140. "author_signature" => $signature['signature'],
  3141. "parent_author_signature" => ""];
  3142. } else {
  3143. // Remove the comment guid
  3144. $guid = array_shift($signed_parts);
  3145. // Remove the parent guid
  3146. $parent_guid = array_shift($signed_parts);
  3147. // Remove the handle
  3148. $handle = array_pop($signed_parts);
  3149. // Glue the parts together
  3150. $text = implode(";", $signed_parts);
  3151. $message = ["author" => $handle,
  3152. "guid" => $guid,
  3153. "parent_guid" => $parent_guid,
  3154. "text" => implode(";", $signed_parts),
  3155. "author_signature" => $signature['signature'],
  3156. "parent_author_signature" => ""];
  3157. }
  3158. return $message;
  3159. }
  3160. /**
  3161. * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
  3162. *
  3163. * @param array $item The item that will be exported
  3164. * @param array $owner the array of the item owner
  3165. * @param array $contact Target of the communication
  3166. * @param bool $public_batch Is it a public post?
  3167. *
  3168. * @return int The result of the transmission
  3169. */
  3170. public static function sendRelay(array $item, array $owner, array $contact, $public_batch = false)
  3171. {
  3172. if ($item["deleted"]) {
  3173. return self::sendRetraction($item, $owner, $contact, $public_batch, true);
  3174. } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
  3175. $type = "like";
  3176. } else {
  3177. $type = "comment";
  3178. }
  3179. logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
  3180. // fetch the original signature
  3181. $fields = ['signed_text', 'signature', 'signer'];
  3182. $signature = DBA::selectFirst('sign', $fields, ['iid' => $item["id"]]);
  3183. if (!DBA::isResult($signature)) {
  3184. logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
  3185. return false;
  3186. }
  3187. // Old way - is used by the internal Friendica functions
  3188. /// @todo Change all signatur storing functions to the new format
  3189. if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
  3190. $message = self::messageFromSignature($item, $signature);
  3191. } else {// New way
  3192. $msg = json_decode($signature['signed_text'], true);
  3193. $message = [];
  3194. if (is_array($msg)) {
  3195. foreach ($msg as $field => $data) {
  3196. if (!$item["deleted"]) {
  3197. if ($field == "diaspora_handle") {
  3198. $field = "author";
  3199. }
  3200. if ($field == "target_type") {
  3201. $field = "parent_type";
  3202. }
  3203. }
  3204. $message[$field] = $data;
  3205. }
  3206. } else {
  3207. logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
  3208. }
  3209. }
  3210. $message["parent_author_signature"] = self::signature($owner, $message);
  3211. logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
  3212. return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
  3213. }
  3214. /**
  3215. * @brief Sends a retraction (deletion) of a message, like or comment
  3216. *
  3217. * @param array $item The item that will be exported
  3218. * @param array $owner the array of the item owner
  3219. * @param array $contact Target of the communication
  3220. * @param bool $public_batch Is it a public post?
  3221. * @param bool $relay Is the retraction transmitted from a relay?
  3222. *
  3223. * @return int The result of the transmission
  3224. */
  3225. public static function sendRetraction(array $item, array $owner, array $contact, $public_batch = false, $relay = false)
  3226. {
  3227. $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
  3228. $msg_type = "retraction";
  3229. if ($item['id'] == $item['parent']) {
  3230. $target_type = "Post";
  3231. } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
  3232. $target_type = "Like";
  3233. } else {
  3234. $target_type = "Comment";
  3235. }
  3236. $message = ["author" => $itemaddr,
  3237. "target_guid" => $item['guid'],
  3238. "target_type" => $target_type];
  3239. logger("Got message ".print_r($message, true), LOGGER_DEBUG);
  3240. return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
  3241. }
  3242. /**
  3243. * @brief Sends a mail
  3244. *
  3245. * @param array $item The item that will be exported
  3246. * @param array $owner The owner
  3247. * @param array $contact Target of the communication
  3248. *
  3249. * @return int The result of the transmission
  3250. */
  3251. public static function sendMail(array $item, array $owner, array $contact)
  3252. {
  3253. $myaddr = self::myHandle($owner);
  3254. $cnv = DBA::selectFirst('conv', [], ['id' => $item["convid"], 'uid' => $item["uid"]]);
  3255. if (!DBA::isResult($cnv)) {
  3256. logger("conversation not found.");
  3257. return;
  3258. }
  3259. $conv = [
  3260. "author" => $cnv["creator"],
  3261. "guid" => $cnv["guid"],
  3262. "subject" => $cnv["subject"],
  3263. "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
  3264. "participants" => $cnv["recips"]
  3265. ];
  3266. $body = BBCode::toMarkdown($item["body"]);
  3267. $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
  3268. $msg = [
  3269. "author" => $myaddr,
  3270. "guid" => $item["guid"],
  3271. "conversation_guid" => $cnv["guid"],
  3272. "text" => $body,
  3273. "created_at" => $created,
  3274. ];
  3275. if ($item["reply"]) {
  3276. $message = $msg;
  3277. $type = "message";
  3278. } else {
  3279. $message = [
  3280. "author" => $cnv["creator"],
  3281. "guid" => $cnv["guid"],
  3282. "subject" => $cnv["subject"],
  3283. "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
  3284. "participants" => $cnv["recips"],
  3285. "message" => $msg];
  3286. $type = "conversation";
  3287. }
  3288. return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
  3289. }
  3290. /**
  3291. * @brief Split a name into first name and last name
  3292. *
  3293. * @param string $name The name
  3294. *
  3295. * @return array The array with "first" and "last"
  3296. */
  3297. public static function splitName($name) {
  3298. $name = trim($name);
  3299. // Is the name longer than 64 characters? Then cut the rest of it.
  3300. if (strlen($name) > 64) {
  3301. if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
  3302. $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
  3303. } else {
  3304. $name = substr($name, 0, 64);
  3305. }
  3306. }
  3307. // Take the first word as first name
  3308. $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
  3309. $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
  3310. if ((strlen($first) < 32) && (strlen($last) < 32)) {
  3311. return ['first' => $first, 'last' => $last];
  3312. }
  3313. // Take the last word as last name
  3314. $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
  3315. $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
  3316. if ((strlen($first) < 32) && (strlen($last) < 32)) {
  3317. return ['first' => $first, 'last' => $last];
  3318. }
  3319. // Take the first 32 characters if there is no space in the first 32 characters
  3320. if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
  3321. $first = substr($name, 0, 32);
  3322. $last = substr($name, 32);
  3323. return ['first' => $first, 'last' => $last];
  3324. }
  3325. $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
  3326. $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
  3327. // Check if the last name is longer than 32 characters
  3328. if (strlen($last) > 32) {
  3329. if (strpos($last, ' ') <= 32) {
  3330. $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
  3331. } else {
  3332. $last = substr($last, 0, 32);
  3333. }
  3334. }
  3335. return ['first' => $first, 'last' => $last];
  3336. }
  3337. /**
  3338. * @brief Create profile data
  3339. *
  3340. * @param int $uid The user id
  3341. *
  3342. * @return array The profile data
  3343. */
  3344. private static function createProfileData($uid)
  3345. {
  3346. $r = q(
  3347. "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
  3348. FROM `profile`
  3349. INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
  3350. INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
  3351. WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
  3352. intval($uid)
  3353. );
  3354. if (!$r) {
  3355. return [];
  3356. }
  3357. $profile = $r[0];
  3358. $handle = $profile["addr"];
  3359. $split_name = self::splitName($profile['name']);
  3360. $first = $split_name['first'];
  3361. $last = $split_name['last'];
  3362. $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
  3363. $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
  3364. $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
  3365. $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
  3366. $dob = null;
  3367. $about = null;
  3368. $location = null;
  3369. $tags = null;
  3370. if ($searchable === 'true') {
  3371. $dob = '';
  3372. if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
  3373. list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
  3374. if ($year < 1004) {
  3375. $year = 1004;
  3376. }
  3377. $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
  3378. }
  3379. $about = $profile['about'];
  3380. $about = strip_tags(BBCode::convert($about));
  3381. $location = Profile::formatLocation($profile);
  3382. $tags = '';
  3383. if ($profile['pub_keywords']) {
  3384. $kw = str_replace(',', ' ', $profile['pub_keywords']);
  3385. $kw = str_replace(' ', ' ', $kw);
  3386. $arr = explode(' ', $profile['pub_keywords']);
  3387. if (count($arr)) {
  3388. for ($x = 0; $x < 5; $x ++) {
  3389. if (!empty($arr[$x])) {
  3390. $tags .= '#'. trim($arr[$x]) .' ';
  3391. }
  3392. }
  3393. }
  3394. }
  3395. $tags = trim($tags);
  3396. }
  3397. return ["author" => $handle,
  3398. "first_name" => $first,
  3399. "last_name" => $last,
  3400. "image_url" => $large,
  3401. "image_url_medium" => $medium,
  3402. "image_url_small" => $small,
  3403. "birthday" => $dob,
  3404. "gender" => $profile['gender'],
  3405. "bio" => $about,
  3406. "location" => $location,
  3407. "searchable" => $searchable,
  3408. "nsfw" => "false",
  3409. "tag_string" => $tags];
  3410. }
  3411. /**
  3412. * @brief Sends profile data
  3413. *
  3414. * @param int $uid The user id
  3415. * @param bool $recips optional, default false
  3416. * @return void
  3417. */
  3418. public static function sendProfile($uid, $recips = false)
  3419. {
  3420. if (!$uid) {
  3421. return;
  3422. }
  3423. $owner = User::getOwnerDataById($uid);
  3424. if (!$owner) {
  3425. return;
  3426. }
  3427. if (!$recips) {
  3428. $recips = q(
  3429. "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
  3430. AND `uid` = %d AND `rel` != %d",
  3431. DBA::escape(Protocol::DIASPORA),
  3432. intval($uid),
  3433. intval(Contact::SHARING)
  3434. );
  3435. }
  3436. if (!$recips) {
  3437. return;
  3438. }
  3439. $message = self::createProfileData($uid);
  3440. foreach ($recips as $recip) {
  3441. logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
  3442. self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
  3443. }
  3444. }
  3445. /**
  3446. * @brief Stores the signature for likes that are created on our system
  3447. *
  3448. * @param array $contact The contact array of the "like"
  3449. * @param int $post_id The post id of the "like"
  3450. *
  3451. * @return bool Success
  3452. */
  3453. public static function storeLikeSignature(array $contact, $post_id)
  3454. {
  3455. // Is the contact the owner? Then fetch the private key
  3456. if (!$contact['self'] || ($contact['uid'] == 0)) {
  3457. logger("No owner post, so not storing signature", LOGGER_DEBUG);
  3458. return false;
  3459. }
  3460. $user = DBA::selectFirst('user', ['prvkey'], ['uid' => $contact["uid"]]);
  3461. if (!DBA::isResult($user)) {
  3462. return false;
  3463. }
  3464. $contact["uprvkey"] = $user['prvkey'];
  3465. $item = Item::selectFirst([], ['id' => $post_id]);
  3466. if (!DBA::isResult($item)) {
  3467. return false;
  3468. }
  3469. if (!in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
  3470. return false;
  3471. }
  3472. $message = self::constructLike($item, $contact);
  3473. if ($message === false) {
  3474. return false;
  3475. }
  3476. $message["author_signature"] = self::signature($contact, $message);
  3477. /*
  3478. * Now store the signature more flexible to dynamically support new fields.
  3479. * This will break Diaspora compatibility with Friendica versions prior to 3.5.
  3480. */
  3481. DBA::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
  3482. logger('Stored diaspora like signature');
  3483. return true;
  3484. }
  3485. /**
  3486. * @brief Stores the signature for comments that are created on our system
  3487. *
  3488. * @param array $item The item array of the comment
  3489. * @param array $contact The contact array of the item owner
  3490. * @param string $uprvkey The private key of the sender
  3491. * @param int $message_id The message id of the comment
  3492. *
  3493. * @return bool Success
  3494. */
  3495. public static function storeCommentSignature(array $item, array $contact, $uprvkey, $message_id)
  3496. {
  3497. if ($uprvkey == "") {
  3498. logger('No private key, so not storing comment signature', LOGGER_DEBUG);
  3499. return false;
  3500. }
  3501. $contact["uprvkey"] = $uprvkey;
  3502. $message = self::constructComment($item, $contact);
  3503. if ($message === false) {
  3504. return false;
  3505. }
  3506. $message["author_signature"] = self::signature($contact, $message);
  3507. /*
  3508. * Now store the signature more flexible to dynamically support new fields.
  3509. * This will break Diaspora compatibility with Friendica versions prior to 3.5.
  3510. */
  3511. DBA::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
  3512. logger('Stored diaspora comment signature');
  3513. return true;
  3514. }
  3515. }