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.

3748 lines
113KB

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