Friendica Communications Platform (please note that this is a clone of the repository at github, issues are handled there) https://friendi.ca
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

3694 lines
111 KiB

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