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.
 
 
 
 
 
 

4277 regels
129 KiB

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