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.

4180 lines
123KB

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