Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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