3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
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 "valid_posting" and interpret only the new protocol.
12 use Friendica\Core\System;
13 use Friendica\Core\Config;
14 use Friendica\Core\PConfig;
15 use Friendica\Network\Probe;
17 require_once 'include/items.php';
18 require_once 'include/bb2diaspora.php';
19 require_once 'include/probe.php';
20 require_once 'include/Contact.php';
21 require_once 'include/Photo.php';
22 require_once 'include/socgraph.php';
23 require_once 'include/group.php';
24 require_once 'include/xml.php';
25 require_once 'include/datetime.php';
26 require_once 'include/queue_fn.php';
27 require_once 'include/cache.php';
30 * @brief This class contain functions to create and send Diaspora XML files
36 * @brief Return a list of relay servers
38 * This is an experimental Diaspora feature.
40 * @return array of relay servers
42 public static function relay_list() {
44 $serverdata = get_config("system", "relay_server");
45 if ($serverdata == "")
50 $servers = explode(",", $serverdata);
52 foreach ($servers AS $server) {
53 $server = trim($server);
54 $addr = "relay@".str_replace("http://", "", normalise_link($server));
55 $batch = $server."/receive/public";
57 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
58 dbesc($batch), dbesc($addr), dbesc(normalise_link($server)));
61 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
62 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
67 dbesc(normalise_link($server)),
69 dbesc(NETWORK_DIASPORA),
70 intval(CONTACT_IS_FOLLOWER),
71 dbesc(datetime_convert()),
72 dbesc(datetime_convert()),
73 dbesc(datetime_convert())
76 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
78 $relay[] = $relais[0];
80 $relay[] = $relais[0];
87 * @brief repairs a signature that was double encoded
89 * The function is unused at the moment. It was copied from the old implementation.
91 * @param string $signature The signature
92 * @param string $handle The handle of the signature owner
93 * @param integer $level This value is only set inside this function to avoid endless loops
95 * @return string the repaired signature
97 private static function repair_signature($signature, $handle = "", $level = 1) {
102 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
103 $signature = base64_decode($signature);
104 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
106 // Do a recursive call to be able to fix even multiple levels
108 $signature = self::repair_signature($signature, $handle, ++$level);
115 * @brief verify the envelope and return the verified data
117 * @param string $envelope The magic envelope
119 * @return string verified data
121 private static function verify_magic_envelope($envelope) {
123 $basedom = parse_xml_string($envelope);
125 if (!is_object($basedom)) {
126 logger("Envelope is no XML file");
130 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
132 if (sizeof($children) == 0) {
133 logger("XML has no children");
139 $data = base64url_decode($children->data);
140 $type = $children->data->attributes()->type[0];
142 $encoding = $children->encoding;
144 $alg = $children->alg;
146 $sig = base64url_decode($children->sig);
147 $key_id = $children->sig->attributes()->key_id[0];
149 $handle = base64url_decode($key_id);
151 $b64url_data = base64url_encode($data);
152 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
154 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
156 $key = self::key($handle);
158 $verify = rsa_verify($signable_data, $sig, $key);
160 logger('Message did not verify. Discarding.');
168 * @brief encrypts data via AES
170 * @param string $key The AES key
171 * @param string $iv The IV (is used for CBC encoding)
172 * @param string $data The data that is to be encrypted
174 * @return string encrypted data
176 private static function aes_encrypt($key, $iv, $data) {
177 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
181 * @brief decrypts data via AES
183 * @param string $key The AES key
184 * @param string $iv The IV (is used for CBC encoding)
185 * @param string $encrypted The encrypted data
187 * @return string decrypted data
189 private static function aes_decrypt($key, $iv, $encrypted) {
190 return openssl_decrypt($encrypted,'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA,str_pad($iv, 16, "\0"));
194 * @brief: Decodes incoming Diaspora message in the new format
196 * @param array $importer Array of the importer user
197 * @param string $raw raw post message
200 * 'message' -> decoded Diaspora XML message
201 * 'author' -> author diaspora handle
202 * 'key' -> author public key (converted to pkcs#8)
204 public static function decode_raw($importer, $raw) {
205 $data = json_decode($raw);
207 // Is it a private post? Then decrypt the outer Salmon
208 if (is_object($data)) {
209 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
210 $ciphertext = base64_decode($data->encrypted_magic_envelope);
212 $outer_key_bundle = '';
213 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
214 $j_outer_key_bundle = json_decode($outer_key_bundle);
216 if (!is_object($j_outer_key_bundle)) {
217 logger('Outer Salmon did not verify. Discarding.');
218 http_status_exit(400);
221 $outer_iv = base64_decode($j_outer_key_bundle->iv);
222 $outer_key = base64_decode($j_outer_key_bundle->key);
224 $xml = diaspora::aes_decrypt($outer_key, $outer_iv, $ciphertext);
229 $basedom = parse_xml_string($xml);
231 if (!is_object($basedom)) {
232 logger('Received data does not seem to be an XML. Discarding. '.$xml);
233 http_status_exit(400);
236 $base = $basedom->children(NAMESPACE_SALMON_ME);
238 // Not sure if this cleaning is needed
239 $data = str_replace(array(" ", "\t", "\r", "\n"), array("", "", "", ""), $base->data);
241 // Build the signed data
242 $type = $base->data[0]->attributes()->type[0];
243 $encoding = $base->encoding;
245 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
247 // This is the signature
248 $signature = base64url_decode($base->sig);
250 // Get the senders' public key
251 $key_id = $base->sig[0]->attributes()->key_id[0];
252 $author_addr = base64_decode($key_id);
253 $key = diaspora::key($author_addr);
255 $verify = rsa_verify($signed_data, $signature, $key);
257 logger('Message did not verify. Discarding.');
258 http_status_exit(400);
261 return array('message' => (string)base64url_decode($base->data),
262 'author' => unxmlify($author_addr),
263 'key' => (string)$key);
267 * @brief: Decodes incoming Diaspora message in the deprecated format
269 * @param array $importer Array of the importer user
270 * @param string $xml urldecoded Diaspora salmon
273 * 'message' -> decoded Diaspora XML message
274 * 'author' -> author diaspora handle
275 * 'key' -> author public key (converted to pkcs#8)
277 public static function decode($importer, $xml) {
280 $basedom = parse_xml_string($xml);
282 if (!is_object($basedom)) {
283 logger("XML is not parseable.");
286 $children = $basedom->children('https://joindiaspora.com/protocol');
288 if ($children->header) {
290 $author_link = str_replace('acct:','',$children->header->author_id);
292 // This happens with posts from a relais
294 logger("This is no private post in the old format", LOGGER_DEBUG);
298 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
300 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
301 $ciphertext = base64_decode($encrypted_header->ciphertext);
303 $outer_key_bundle = '';
304 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
306 $j_outer_key_bundle = json_decode($outer_key_bundle);
308 $outer_iv = base64_decode($j_outer_key_bundle->iv);
309 $outer_key = base64_decode($j_outer_key_bundle->key);
311 $decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
313 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
314 $idom = parse_xml_string($decrypted);
316 $inner_iv = base64_decode($idom->iv);
317 $inner_aes_key = base64_decode($idom->aes_key);
319 $author_link = str_replace('acct:','',$idom->author_id);
322 $dom = $basedom->children(NAMESPACE_SALMON_ME);
324 // figure out where in the DOM tree our data is hiding
326 if ($dom->provenance->data)
327 $base = $dom->provenance;
328 elseif ($dom->env->data)
334 logger('unable to locate salmon data in xml');
335 http_status_exit(400);
339 // Stash the signature away for now. We have to find their key or it won't be good for anything.
340 $signature = base64url_decode($base->sig);
344 // strip whitespace so our data element will return to one big base64 blob
345 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
348 // stash away some other stuff for later
350 $type = $base->data[0]->attributes()->type[0];
351 $keyhash = $base->sig[0]->attributes()->keyhash[0];
352 $encoding = $base->encoding;
356 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
360 $data = base64url_decode($data);
364 $inner_decrypted = $data;
367 // Decode the encrypted blob
369 $inner_encrypted = base64_decode($data);
370 $inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
374 logger('Could not retrieve author URI.');
375 http_status_exit(400);
377 // Once we have the author URI, go to the web and try to find their public key
378 // (first this will look it up locally if it is in the fcontact cache)
379 // This will also convert diaspora public key from pkcs#1 to pkcs#8
381 logger('Fetching key for '.$author_link);
382 $key = self::key($author_link);
385 logger('Could not retrieve author key.');
386 http_status_exit(400);
389 $verify = rsa_verify($signed_data,$signature,$key);
392 logger('Message did not verify. Discarding.');
393 http_status_exit(400);
396 logger('Message verified.');
398 return array('message' => (string)$inner_decrypted,
399 'author' => unxmlify($author_link),
400 'key' => (string)$key);
405 * @brief Dispatches public messages and find the fitting receivers
407 * @param array $msg The post that will be dispatched
409 * @return int The message id of the generated message, "true" or "false" if there was an error
411 public static function dispatch_public($msg) {
413 $enabled = intval(get_config("system", "diaspora_enabled"));
415 logger("diaspora is disabled");
419 if (!($postdata = self::valid_posting($msg))) {
420 logger("Invalid posting");
424 $fields = $postdata['fields'];
426 // Is it a an action (comment, like, ...) for our own post?
427 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
428 $guid = notags(unxmlify($fields->parent_guid));
429 $importer = self::importer_for_guid($guid);
430 if (is_array($importer)) {
431 logger("delivering to origin: ".$importer["name"]);
432 $message_id = self::dispatch($importer, $msg, $fields);
437 // Process item retractions. This has to be done separated from the other stuff,
438 // since retractions for comments could come even from non followers.
439 if (!empty($fields) && in_array($fields->getName(), array('retraction'))) {
440 $target = notags(unxmlify($fields->target_type));
441 if (in_array($target, array("Comment", "Like", "Post", "Reshare", "StatusMessage"))) {
442 logger('processing retraction for '.$target, LOGGER_DEBUG);
443 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
444 $message_id = self::dispatch($importer, $msg, $fields);
449 // Now distribute it to the followers
450 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
451 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
452 AND NOT `account_expired` AND NOT `account_removed`",
453 dbesc(NETWORK_DIASPORA),
454 dbesc($msg["author"])
457 if (dbm::is_result($r)) {
458 foreach ($r as $rr) {
459 logger("delivering to: ".$rr["username"]);
460 self::dispatch($rr, $msg, $fields);
462 } elseif (!Config::get('system', 'relay_subscribe', false)) {
463 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
465 // Use a dummy importer to import the data for the public copy
466 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
467 $message_id = self::dispatch($importer, $msg, $fields);
474 * @brief Dispatches the different message types to the different functions
476 * @param array $importer Array of the importer user
477 * @param array $msg The post that will be dispatched
478 * @param object $fields SimpleXML object that contains the message
480 * @return int The message id of the generated message, "true" or "false" if there was an error
482 public static function dispatch($importer, $msg, $fields = null) {
484 // The sender is the handle of the contact that sent the message.
485 // This will often be different with relayed messages (for example "like" and "comment")
486 $sender = $msg["author"];
488 // This is only needed for private postings since this is already done for public ones before
489 if (is_null($fields)) {
490 if (!($postdata = self::valid_posting($msg))) {
491 logger("Invalid posting");
494 $fields = $postdata['fields'];
497 $type = $fields->getName();
499 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
502 case "account_migration":
503 return self::receiveAccountMigration($importer, $fields);
505 case "account_deletion":
506 return self::receive_account_deletion($importer, $fields);
509 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
512 return self::receive_contact_request($importer, $fields);
515 return self::receive_conversation($importer, $msg, $fields);
518 return self::receive_like($importer, $sender, $fields);
521 return self::receive_message($importer, $fields);
523 case "participation": // Not implemented
524 return self::receive_participation($importer, $fields);
526 case "photo": // Not implemented
527 return self::receive_photo($importer, $fields);
529 case "poll_participation": // Not implemented
530 return self::receive_poll_participation($importer, $fields);
533 return self::receive_profile($importer, $fields);
536 return self::receive_reshare($importer, $fields, $msg["message"]);
539 return self::receive_retraction($importer, $sender, $fields);
541 case "status_message":
542 return self::receive_status_message($importer, $fields, $msg["message"]);
545 logger("Unknown message type ".$type);
553 * @brief Checks if a posting is valid and fetches the data fields.
555 * This function does not only check the signature.
556 * It also does the conversion between the old and the new diaspora format.
558 * @param array $msg Array with the XML, the sender handle and the sender signature
560 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
562 private static function valid_posting($msg) {
564 $data = parse_xml_string($msg["message"]);
566 if (!is_object($data)) {
567 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
571 $first_child = $data->getName();
573 // Is this the new or the old version?
574 if ($data->getName() == "XML") {
576 foreach ($data->post->children() as $child)
583 $type = $element->getName();
586 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
588 // All retractions are handled identically from now on.
589 // In the new version there will only be "retraction".
590 if (in_array($type, array("signed_retraction", "relayable_retraction")))
591 $type = "retraction";
593 if ($type == "request")
596 $fields = new SimpleXMLElement("<".$type."/>");
600 foreach ($element->children() AS $fieldname => $entry) {
602 // Translation for the old XML structure
603 if ($fieldname == "diaspora_handle") {
604 $fieldname = "author";
606 if ($fieldname == "participant_handles") {
607 $fieldname = "participants";
609 if (in_array($type, array("like", "participation"))) {
610 if ($fieldname == "target_type") {
611 $fieldname = "parent_type";
614 if ($fieldname == "sender_handle") {
615 $fieldname = "author";
617 if ($fieldname == "recipient_handle") {
618 $fieldname = "recipient";
620 if ($fieldname == "root_diaspora_id") {
621 $fieldname = "root_author";
623 if ($type == "status_message") {
624 if ($fieldname == "raw_message") {
628 if ($type == "retraction") {
629 if ($fieldname == "post_guid") {
630 $fieldname = "target_guid";
632 if ($fieldname == "type") {
633 $fieldname = "target_type";
638 if (($fieldname == "author_signature") && ($entry != ""))
639 $author_signature = base64_decode($entry);
640 elseif (($fieldname == "parent_author_signature") && ($entry != ""))
641 $parent_author_signature = base64_decode($entry);
642 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
643 if ($signed_data != "") {
645 $signed_data_parent .= ";";
648 $signed_data .= $entry;
650 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) ||
651 ($orig_type == "relayable_retraction"))
652 xml::copy($entry, $fields, $fieldname);
655 // This is something that shouldn't happen at all.
656 if (in_array($type, array("status_message", "reshare", "profile")))
657 if ($msg["author"] != $fields->author) {
658 logger("Message handle is not the same as envelope sender. Quitting this message.");
662 // Only some message types have signatures. So we quit here for the other types.
663 if (!in_array($type, array("comment", "like"))) {
664 return array("fields" => $fields, "relayed" => false);
666 // No author_signature? This is a must, so we quit.
667 if (!isset($author_signature)) {
668 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
672 if (isset($parent_author_signature)) {
675 $key = self::key($msg["author"]);
677 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
678 logger("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, LOGGER_DEBUG);
685 $key = self::key($fields->author);
687 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
688 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
691 return array("fields" => $fields, "relayed" => $relayed);
696 * @brief Fetches the public key for a given handle
698 * @param string $handle The handle
700 * @return string The public key
702 private static function key($handle) {
703 $handle = strval($handle);
705 logger("Fetching diaspora key for: ".$handle);
707 $r = self::person_by_handle($handle);
715 * @brief Fetches data for a given handle
717 * @param string $handle The handle
719 * @return array the queried data
721 public static function person_by_handle($handle) {
723 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
724 dbesc(NETWORK_DIASPORA),
729 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
731 // update record occasionally so it doesn't get stale
732 $d = strtotime($person["updated"]." +00:00");
733 if ($d < strtotime("now - 14 days"))
736 if ($person["guid"] == "")
740 if (!$person || $update) {
741 logger("create or refresh", LOGGER_DEBUG);
742 $r = probe_url($handle, PROBE_DIASPORA);
744 // Note that Friendica contacts will return a "Diaspora person"
745 // if Diaspora connectivity is enabled on their server
746 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
747 self::add_fcontact($r, $update);
755 * @brief Updates the fcontact table
757 * @param array $arr The fcontact data
758 * @param bool $update Update or insert?
760 * @return string The id of the fcontact entry
762 private static function add_fcontact($arr, $update = false) {
765 $r = q("UPDATE `fcontact` SET
779 WHERE `url` = '%s' AND `network` = '%s'",
781 dbesc($arr["photo"]),
782 dbesc($arr["request"]),
784 dbesc(strtolower($arr["addr"])),
786 dbesc($arr["batch"]),
787 dbesc($arr["notify"]),
789 dbesc($arr["confirm"]),
790 dbesc($arr["alias"]),
791 dbesc($arr["pubkey"]),
792 dbesc(datetime_convert()),
794 dbesc($arr["network"])
797 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
798 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
799 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
802 dbesc($arr["photo"]),
803 dbesc($arr["request"]),
807 dbesc($arr["batch"]),
808 dbesc($arr["notify"]),
810 dbesc($arr["confirm"]),
811 dbesc($arr["network"]),
812 dbesc($arr["alias"]),
813 dbesc($arr["pubkey"]),
814 dbesc(datetime_convert())
822 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
824 * @param int $contact_id The id in the contact table
825 * @param int $gcontact_id The id in the gcontact table
827 * @return string the handle
829 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
832 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
834 if ($gcontact_id != 0) {
835 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
836 intval($gcontact_id));
838 if (dbm::is_result($r)) {
839 return strtolower($r[0]["addr"]);
843 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
844 intval($contact_id));
846 if (dbm::is_result($r)) {
849 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
851 if ($contact['addr'] != "") {
852 $handle = $contact['addr'];
854 $baseurl_start = strpos($contact['url'],'://') + 3;
855 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
856 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
857 $handle = $contact['nick'].'@'.$baseurl;
861 return strtolower($handle);
865 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
868 * @param mixed $fcontact_guid Hexadecimal string guid
870 * @return string the contact url or null
872 public static function url_from_contact_guid($fcontact_guid) {
873 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
875 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
876 dbesc(NETWORK_DIASPORA),
877 dbesc($fcontact_guid)
880 if (dbm::is_result($r)) {
888 * @brief Get a contact id for a given handle
890 * @param int $uid The user id
891 * @param string $handle The handle in the format user@domain.tld
893 * @return The contact id
895 private static function contact_by_handle($uid, $handle) {
897 // First do a direct search on the contact table
898 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
903 if (dbm::is_result($r)) {
907 * We haven't found it?
908 * We use another function for it that will possibly create a contact entry.
910 $cid = get_contact($handle, $uid);
913 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
914 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
916 if (dbm::is_result($r)) {
922 $handle_parts = explode("@", $handle);
923 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
924 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
929 if (dbm::is_result($r)) {
933 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
938 * @brief Check if posting is allowed for this contact
940 * @param array $importer Array of the importer user
941 * @param array $contact The contact that is checked
942 * @param bool $is_comment Is the check for a comment?
944 * @return bool is the contact allowed to post?
946 private static function post_allow($importer, $contact, $is_comment = false) {
949 * Perhaps we were already sharing with this person. Now they're sharing with us.
950 * That makes us friends.
951 * Normally this should have handled by getting a request - but this could get lost
953 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
954 dba::update('contact', array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
955 array('id' => $contact["id"], 'uid' => $contact["uid"]));
957 $contact["rel"] = CONTACT_IS_FRIEND;
958 logger("defining user ".$contact["nick"]." as friend");
961 // We don't seem to like that person
962 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
963 // Maybe blocked, don't accept.
965 // We are following this person?
966 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
967 // Yes, then it is fine.
969 // Is it a post to a community?
970 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
973 // Is the message a global user or a comment?
974 } elseif (($importer["uid"] == 0) || $is_comment) {
975 // Messages for the global users and comments are always accepted
983 * @brief Fetches the contact id for a handle and checks if posting is allowed
985 * @param array $importer Array of the importer user
986 * @param string $handle The checked handle in the format user@domain.tld
987 * @param bool $is_comment Is the check for a comment?
989 * @return array The contact data
991 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
992 $contact = self::contact_by_handle($importer["uid"], $handle);
994 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
995 // If a contact isn't found, we accept it anyway if it is a comment
1003 if (!self::post_allow($importer, $contact, $is_comment)) {
1004 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1011 * @brief Does the message already exists on the system?
1013 * @param int $uid The user id
1014 * @param string $guid The guid of the message
1016 * @return int|bool message id if the message already was stored into the system - or false.
1018 private static function message_exists($uid, $guid) {
1019 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1024 if (dbm::is_result($r)) {
1025 logger("message ".$guid." already exists for user ".$uid);
1033 * @brief Checks for links to posts in a message
1035 * @param array $item The item array
1037 private static function fetch_guid($item) {
1038 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1039 preg_replace_callback($expression,
1040 function ($match) use ($item) {
1041 return self::fetch_guid_sub($match, $item);
1044 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1045 function ($match) use ($item) {
1046 return self::fetch_guid_sub($match, $item);
1051 * @brief Checks for relative /people/* links in an item body to match local
1052 * contacts or prepends the remote host taken from the author link.
1054 * @param string $body The item body to replace links from
1055 * @param string $author_link The author link for missing local contact fallback
1057 * @return the replaced string
1059 public static function replace_people_guid($body, $author_link) {
1060 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1061 function ($match) use ($author_link) {
1063 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1064 // 1 => '0123456789abcdef'
1066 $handle = self::url_from_contact_guid($match[1]);
1069 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1071 // No local match, restoring absolute remote URL from author scheme and host
1072 $author_url = parse_url($author_link);
1073 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1083 * @brief sub function of "fetch_guid" which checks for links in messages
1085 * @param array $match array containing a link that has to be checked for a message link
1086 * @param array $item The item array
1088 private static function fetch_guid_sub($match, $item) {
1089 if (!self::store_by_guid($match[1], $item["author-link"]))
1090 self::store_by_guid($match[1], $item["owner-link"]);
1094 * @brief Fetches an item with a given guid from a given server
1096 * @param string $guid the message guid
1097 * @param string $server The server address
1098 * @param int $uid The user id of the user
1100 * @return int the message id of the stored message or false
1102 private static function store_by_guid($guid, $server, $uid = 0) {
1103 $serverparts = parse_url($server);
1104 $server = $serverparts["scheme"]."://".$serverparts["host"];
1106 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1108 $msg = self::message($guid, $server);
1113 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1115 // Now call the dispatcher
1116 return self::dispatch_public($msg);
1120 * @brief Fetches a message from a server
1122 * @param string $guid message guid
1123 * @param string $server The url of the server
1124 * @param int $level Endless loop prevention
1127 * 'message' => The message XML
1128 * 'author' => The author handle
1129 * 'key' => The public key of the author
1131 private static function message($guid, $server, $level = 0) {
1136 // This will work for new Diaspora servers and Friendica servers from 3.5
1137 $source_url = $server."/fetch/post/".$guid;
1138 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1140 $envelope = fetch_url($source_url);
1142 logger("Envelope was fetched.", LOGGER_DEBUG);
1143 $x = self::verify_magic_envelope($envelope);
1145 logger("Envelope could not be verified.", LOGGER_DEBUG);
1147 logger("Envelope was verified.", LOGGER_DEBUG);
1151 // This will work for older Diaspora and Friendica servers
1153 $source_url = $server."/p/".$guid.".xml";
1154 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1156 $x = fetch_url($source_url);
1161 $source_xml = parse_xml_string($x);
1163 if (!is_object($source_xml))
1166 if ($source_xml->post->reshare) {
1167 // Reshare of a reshare - old Diaspora version
1168 logger("Message is a reshare", LOGGER_DEBUG);
1169 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1170 } elseif ($source_xml->getName() == "reshare") {
1171 // Reshare of a reshare - new Diaspora version
1172 logger("Message is a new reshare", LOGGER_DEBUG);
1173 return self::message($source_xml->root_guid, $server, ++$level);
1178 // Fetch the author - for the old and the new Diaspora version
1179 if ($source_xml->post->status_message->diaspora_handle)
1180 $author = (string)$source_xml->post->status_message->diaspora_handle;
1181 elseif ($source_xml->author && ($source_xml->getName() == "status_message"))
1182 $author = (string)$source_xml->author;
1184 // If this isn't a "status_message" then quit
1186 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1190 $msg = array("message" => $x, "author" => $author);
1192 $msg["key"] = self::key($msg["author"]);
1198 * @brief Fetches the item record of a given guid
1200 * @param int $uid The user id
1201 * @param string $guid message guid
1202 * @param string $author The handle of the item
1203 * @param array $contact The contact of the item owner
1205 * @return array the item record
1207 private static function parent_item($uid, $guid, $author, $contact) {
1208 $r = q("SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1209 `author-name`, `author-link`, `author-avatar`,
1210 `owner-name`, `owner-link`, `owner-avatar`
1211 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1212 intval($uid), dbesc($guid));
1215 $result = self::store_by_guid($guid, $contact["url"], $uid);
1218 $person = self::person_by_handle($author);
1219 $result = self::store_by_guid($guid, $person["url"], $uid);
1223 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1225 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1226 `author-name`, `author-link`, `author-avatar`,
1227 `owner-name`, `owner-link`, `owner-avatar`
1228 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1229 intval($uid), dbesc($guid));
1234 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1237 logger("parent item found: parent: ".$guid." - user: ".$uid);
1243 * @brief returns contact details
1245 * @param array $contact The default contact if the person isn't found
1246 * @param array $person The record of the person
1247 * @param int $uid The user id
1250 * 'cid' => contact id
1251 * 'network' => network type
1253 private static function author_contact_by_url($contact, $person, $uid) {
1255 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1256 dbesc(normalise_link($person["url"])), intval($uid));
1259 $network = $r[0]["network"];
1261 // We are receiving content from a user that possibly is about to be terminated
1262 // This means the user is vital, so we remove a possible termination date.
1263 unmark_for_death($r[0]);
1265 $cid = $contact["id"];
1266 $network = NETWORK_DIASPORA;
1269 return array("cid" => $cid, "network" => $network);
1273 * @brief Is the profile a hubzilla profile?
1275 * @param string $url The profile link
1277 * @return bool is it a hubzilla server?
1279 public static function is_redmatrix($url) {
1280 return(strstr($url, "/channel/"));
1284 * @brief Generate a post link with a given handle and message guid
1286 * @param string $addr The user handle
1287 * @param string $guid message guid
1289 * @return string the post link
1291 private static function plink($addr, $guid, $parent_guid = '') {
1292 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1295 if (!dbm::is_result($r)) {
1296 if ($parent_guid != '') {
1297 return "https://".substr($addr,strpos($addr,"@") + 1)."/posts/".$parent_guid."#".$guid;
1299 return "https://".substr($addr,strpos($addr,"@") + 1)."/posts/".$guid;
1303 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1304 // So we try another way as well.
1305 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1306 if (dbm::is_result($s)) {
1307 $r[0]["network"] = $s[0]["network"];
1310 if ($r[0]["network"] == NETWORK_DFRN) {
1311 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1314 if (self::is_redmatrix($r[0]["url"])) {
1315 return $r[0]["url"]."/?f=&mid=".$guid;
1318 if ($parent_guid != '') {
1319 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$parent_guid."#".$guid;
1321 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1326 * @brief Receives account migration
1328 * @param array $importer Array of the importer user
1329 * @param object $data The message object
1331 * @return bool Success
1333 private static function receiveAccountMigration($importer, $data) {
1334 $old_handle = notags(unxmlify($data->author));
1335 $new_handle = notags(unxmlify($data->profile->author));
1336 $signature = notags(unxmlify($data->signature));
1338 $contact = self::contact_by_handle($importer["uid"], $old_handle);
1340 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1344 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1347 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1348 $key = self::key($old_handle);
1349 if (!rsa_verify($signed_text, $signature, $key, "sha256")) {
1350 logger('No valid signature for migration.');
1354 // Update the profile
1355 self::receive_profile($importer, $data->profile);
1357 // change the technical stuff in contact and gcontact
1358 $data = Probe::uri($new_handle);
1359 if ($data['network'] == NETWORK_PHANTOM) {
1360 logger('Account for '.$new_handle." couldn't be probed.");
1364 $fields = array('url' => $data['url'], 'nurl' => normalise_link($data['url']),
1365 'name' => $data['name'], 'nick' => $data['nick'],
1366 'addr' => $data['addr'], 'batch' => $data['batch'],
1367 'notify' => $data['notify'], 'poll' => $data['poll'],
1368 'network' => $data['network']);
1370 dba::update('contact', $fields, array('addr' => $old_handle));
1372 $fields = array('url' => $data['url'], 'nurl' => normalise_link($data['url']),
1373 'name' => $data['name'], 'nick' => $data['nick'],
1374 'addr' => $data['addr'], 'connect' => $data['addr'],
1375 'notify' => $data['notify'], 'photo' => $data['photo'],
1376 'server_url' => $data['baseurl'], 'network' => $data['network']);
1378 dba::update('gcontact', $fields, array('addr' => $old_handle));
1380 logger('Contacts are updated.');
1383 /// @todo This is an extreme performance killer
1385 'owner-link' => array($contact["url"], $data["url"]),
1386 'author-link' => array($contact["url"], $data["url"]),
1388 foreach ($fields as $n=>$f) {
1389 $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1391 intval($importer["uid"]));
1393 if (dbm::is_result($r)) {
1394 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1397 intval($importer["uid"]));
1405 logger('Items are updated.');
1411 * @brief Processes an account deletion
1413 * @param array $importer Array of the importer user
1414 * @param object $data The message object
1416 * @return bool Success
1418 private static function receive_account_deletion($importer, $data) {
1420 /// @todo Account deletion should remove the contact from the global contacts as well
1422 $author = notags(unxmlify($data->author));
1424 $contact = self::contact_by_handle($importer["uid"], $author);
1426 logger("cannot find contact for author: ".$author);
1430 // We now remove the contact
1431 contact_remove($contact["id"]);
1436 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1438 * @param string $author Author handle
1439 * @param string $guid Message guid
1440 * @param boolean $onlyfound Only return uri when found in the database
1442 * @return string The constructed uri or the one from our database
1444 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1446 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1447 if (dbm::is_result($r)) {
1448 return $r[0]["uri"];
1449 } elseif (!$onlyfound) {
1450 return $author.":".$guid;
1457 * @brief Fetch the guid from our database with a given uri
1459 * @param string $author Author handle
1460 * @param string $uri Message uri
1462 * @return string The post guid
1464 private static function get_guid_from_uri($uri, $uid) {
1466 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1467 if (dbm::is_result($r)) {
1468 return $r[0]["guid"];
1475 * @brief Find the best importer for a comment, like, ...
1477 * @param string $guid The guid of the item
1479 * @return array|boolean the origin owner of that post - or false
1481 private static function importer_for_guid($guid) {
1482 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1484 if (dbm::is_result($item)) {
1485 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1486 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1487 if (dbm::is_result($contact)) {
1495 * @brief Processes an incoming comment
1497 * @param array $importer Array of the importer user
1498 * @param string $sender The sender of the message
1499 * @param object $data The message object
1500 * @param string $xml The original XML of the message
1502 * @return int The message id of the generated comment or "false" if there was an error
1504 private static function receive_comment($importer, $sender, $data, $xml) {
1505 $author = notags(unxmlify($data->author));
1506 $guid = notags(unxmlify($data->guid));
1507 $parent_guid = notags(unxmlify($data->parent_guid));
1508 $text = unxmlify($data->text);
1510 if (isset($data->created_at)) {
1511 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1513 $created_at = datetime_convert();
1516 if (isset($data->thread_parent_guid)) {
1517 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1518 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1523 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1528 $message_id = self::message_exists($importer["uid"], $guid);
1533 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1534 if (!$parent_item) {
1538 $person = self::person_by_handle($author);
1539 if (!is_array($person)) {
1540 logger("unable to find author details");
1544 // Fetch the contact id - if we know this contact
1545 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1547 $datarray = array();
1549 $datarray["uid"] = $importer["uid"];
1550 $datarray["contact-id"] = $author_contact["cid"];
1551 $datarray["network"] = $author_contact["network"];
1553 $datarray["author-name"] = $person["name"];
1554 $datarray["author-link"] = $person["url"];
1555 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1557 $datarray["owner-name"] = $contact["name"];
1558 $datarray["owner-link"] = $contact["url"];
1559 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1561 $datarray["guid"] = $guid;
1562 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1564 $datarray["type"] = "remote-comment";
1565 $datarray["verb"] = ACTIVITY_POST;
1566 $datarray["gravity"] = GRAVITY_COMMENT;
1568 if ($thr_uri != "") {
1569 $datarray["parent-uri"] = $thr_uri;
1571 $datarray["parent-uri"] = $parent_item["uri"];
1574 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1576 $datarray["protocol"] = PROTOCOL_DIASPORA;
1577 $datarray["source"] = $xml;
1579 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1581 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1583 $body = diaspora2bb($text);
1585 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1587 self::fetch_guid($datarray);
1589 $message_id = item_store($datarray);
1591 if ($message_id <= 0) {
1596 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1599 // If we are the origin of the parent we store the original data and notify our followers
1600 if ($message_id && $parent_item["origin"]) {
1602 // Formerly we stored the signed text, the signature and the author in different fields.
1603 // We now store the raw data so that we are more flexible.
1604 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
1607 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1614 * @brief processes and stores private messages
1616 * @param array $importer Array of the importer user
1617 * @param array $contact The contact of the message
1618 * @param object $data The message object
1619 * @param array $msg Array of the processed message, author handle and key
1620 * @param object $mesg The private message
1621 * @param array $conversation The conversation record to which this message belongs
1623 * @return bool "true" if it was successful
1625 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1626 $author = notags(unxmlify($data->author));
1627 $guid = notags(unxmlify($data->guid));
1628 $subject = notags(unxmlify($data->subject));
1630 // "diaspora_handle" is the element name from the old version
1631 // "author" is the element name from the new version
1632 if ($mesg->author) {
1633 $msg_author = notags(unxmlify($mesg->author));
1634 } elseif ($mesg->diaspora_handle) {
1635 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1640 $msg_guid = notags(unxmlify($mesg->guid));
1641 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1642 $msg_text = unxmlify($mesg->text);
1643 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1645 if ($msg_conversation_guid != $guid) {
1646 logger("message conversation guid does not belong to the current conversation.");
1650 $body = diaspora2bb($msg_text);
1651 $message_uri = $msg_author.":".$msg_guid;
1653 $person = self::person_by_handle($msg_author);
1657 $r = q("SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1659 intval($importer["uid"])
1661 if (dbm::is_result($r)) {
1662 logger("duplicate message already delivered.", LOGGER_DEBUG);
1666 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1667 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1668 intval($importer["uid"]),
1670 intval($conversation["id"]),
1671 dbesc($person["name"]),
1672 dbesc($person["photo"]),
1673 dbesc($person["url"]),
1674 intval($contact["id"]),
1679 dbesc($message_uri),
1680 dbesc($author.":".$guid),
1681 dbesc($msg_created_at)
1686 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
1689 "type" => NOTIFY_MAIL,
1690 "notify_flags" => $importer["notify-flags"],
1691 "language" => $importer["language"],
1692 "to_name" => $importer["username"],
1693 "to_email" => $importer["email"],
1694 "uid" =>$importer["uid"],
1695 "item" => array("subject" => $subject, "body" => $body),
1696 "source_name" => $person["name"],
1697 "source_link" => $person["url"],
1698 "source_photo" => $person["thumb"],
1699 "verb" => ACTIVITY_POST,
1706 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1708 * @param array $importer Array of the importer user
1709 * @param array $msg Array of the processed message, author handle and key
1710 * @param object $data The message object
1712 * @return bool Success
1714 private static function receive_conversation($importer, $msg, $data) {
1715 $author = notags(unxmlify($data->author));
1716 $guid = notags(unxmlify($data->guid));
1717 $subject = notags(unxmlify($data->subject));
1718 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1719 $participants = notags(unxmlify($data->participants));
1721 $messages = $data->message;
1723 if (!count($messages)) {
1724 logger("empty conversation");
1728 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1732 $conversation = null;
1734 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1735 intval($importer["uid"]),
1739 $conversation = $c[0];
1741 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1742 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1743 intval($importer["uid"]),
1747 dbesc(datetime_convert()),
1749 dbesc($participants)
1752 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1753 intval($importer["uid"]),
1758 $conversation = $c[0];
1760 if (!$conversation) {
1761 logger("unable to create conversation.");
1765 foreach ($messages as $mesg)
1766 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1772 * @brief Creates the body for a "like" message
1774 * @param array $contact The contact that send us the "like"
1775 * @param array $parent_item The item array of the parent item
1776 * @param string $guid message guid
1778 * @return string the body
1780 private static function construct_like_body($contact, $parent_item, $guid) {
1781 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1783 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1784 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1785 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1787 return sprintf($bodyverb, $ulink, $alink, $plink);
1791 * @brief Creates a XML object for a "like"
1793 * @param array $importer Array of the importer user
1794 * @param array $parent_item The item array of the parent item
1796 * @return string The XML
1798 private static function construct_like_object($importer, $parent_item) {
1799 $objtype = ACTIVITY_OBJ_NOTE;
1800 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1801 $parent_body = $parent_item["body"];
1803 $xmldata = array("object" => array("type" => $objtype,
1805 "id" => $parent_item["uri"],
1808 "content" => $parent_body));
1810 return xml::from_array($xmldata, $xml, true);
1814 * @brief Processes "like" messages
1816 * @param array $importer Array of the importer user
1817 * @param string $sender The sender of the message
1818 * @param object $data The message object
1820 * @return int The message id of the generated like or "false" if there was an error
1822 private static function receive_like($importer, $sender, $data) {
1823 $author = notags(unxmlify($data->author));
1824 $guid = notags(unxmlify($data->guid));
1825 $parent_guid = notags(unxmlify($data->parent_guid));
1826 $parent_type = notags(unxmlify($data->parent_type));
1827 $positive = notags(unxmlify($data->positive));
1829 // likes on comments aren't supported by Diaspora - only on posts
1830 // But maybe this will be supported in the future, so we will accept it.
1831 if (!in_array($parent_type, array("Post", "Comment")))
1834 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1838 $message_id = self::message_exists($importer["uid"], $guid);
1842 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1846 $person = self::person_by_handle($author);
1847 if (!is_array($person)) {
1848 logger("unable to find author details");
1852 // Fetch the contact id - if we know this contact
1853 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1855 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1856 // We would accept this anyhow.
1857 if ($positive == "true")
1858 $verb = ACTIVITY_LIKE;
1860 $verb = ACTIVITY_DISLIKE;
1862 $datarray = array();
1864 $datarray["protocol"] = PROTOCOL_DIASPORA;
1866 $datarray["uid"] = $importer["uid"];
1867 $datarray["contact-id"] = $author_contact["cid"];
1868 $datarray["network"] = $author_contact["network"];
1870 $datarray["author-name"] = $person["name"];
1871 $datarray["author-link"] = $person["url"];
1872 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1874 $datarray["owner-name"] = $contact["name"];
1875 $datarray["owner-link"] = $contact["url"];
1876 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1878 $datarray["guid"] = $guid;
1879 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1881 $datarray["type"] = "activity";
1882 $datarray["verb"] = $verb;
1883 $datarray["gravity"] = GRAVITY_LIKE;
1884 $datarray["parent-uri"] = $parent_item["uri"];
1886 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1887 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1889 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1891 $message_id = item_store($datarray);
1893 if ($message_id <= 0) {
1898 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1901 // like on comments have the comment as parent. So we need to fetch the toplevel parent
1902 if ($parent_item["id"] != $parent_item["parent"]) {
1903 $toplevel = dba::select('item', array('origin'), array('id' => $parent_item["parent"]), array('limit' => 1));
1904 $origin = $toplevel["origin"];
1906 $origin = $parent_item["origin"];
1909 // If we are the origin of the parent we store the original data and notify our followers
1910 if ($message_id && $origin) {
1912 // Formerly we stored the signed text, the signature and the author in different fields.
1913 // We now store the raw data so that we are more flexible.
1914 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($data)));
1917 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1924 * @brief Processes private messages
1926 * @param array $importer Array of the importer user
1927 * @param object $data The message object
1929 * @return bool Success?
1931 private static function receive_message($importer, $data) {
1932 $author = notags(unxmlify($data->author));
1933 $guid = notags(unxmlify($data->guid));
1934 $conversation_guid = notags(unxmlify($data->conversation_guid));
1935 $text = unxmlify($data->text);
1936 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1938 $contact = self::allowed_contact_by_handle($importer, $author, true);
1943 $conversation = null;
1945 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1946 intval($importer["uid"]),
1947 dbesc($conversation_guid)
1950 $conversation = $c[0];
1952 logger("conversation not available.");
1956 $message_uri = $author.":".$guid;
1958 $person = self::person_by_handle($author);
1960 logger("unable to find author details");
1964 $body = diaspora2bb($text);
1966 $body = self::replace_people_guid($body, $person["url"]);
1970 $r = q("SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1972 intval($importer["uid"])
1974 if (dbm::is_result($r)) {
1975 logger("duplicate message already delivered.", LOGGER_DEBUG);
1979 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1980 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1981 intval($importer["uid"]),
1983 intval($conversation["id"]),
1984 dbesc($person["name"]),
1985 dbesc($person["photo"]),
1986 dbesc($person["url"]),
1987 intval($contact["id"]),
1988 dbesc($conversation["subject"]),
1992 dbesc($message_uri),
1993 dbesc($author.":".$conversation["guid"]),
1999 dba::update('conv', array('updated' => datetime_convert()), array('id' => $conversation["id"]));
2004 * @brief Processes participations - unsupported by now
2006 * @param array $importer Array of the importer user
2007 * @param object $data The message object
2009 * @return bool always true
2011 private static function receive_participation($importer, $data) {
2012 // I'm not sure if we can fully support this message type
2017 * @brief Processes photos - unneeded
2019 * @param array $importer Array of the importer user
2020 * @param object $data The message object
2022 * @return bool always true
2024 private static function receive_photo($importer, $data) {
2025 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
2030 * @brief Processes poll participations - unssupported
2032 * @param array $importer Array of the importer user
2033 * @param object $data The message object
2035 * @return bool always true
2037 private static function receive_poll_participation($importer, $data) {
2038 // We don't support polls by now
2043 * @brief Processes incoming profile updates
2045 * @param array $importer Array of the importer user
2046 * @param object $data The message object
2048 * @return bool Success
2050 private static function receive_profile($importer, $data) {
2051 $author = strtolower(notags(unxmlify($data->author)));
2053 $contact = self::contact_by_handle($importer["uid"], $author);
2057 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2058 $image_url = unxmlify($data->image_url);
2059 $birthday = unxmlify($data->birthday);
2060 $gender = unxmlify($data->gender);
2061 $about = diaspora2bb(unxmlify($data->bio));
2062 $location = diaspora2bb(unxmlify($data->location));
2063 $searchable = (unxmlify($data->searchable) == "true");
2064 $nsfw = (unxmlify($data->nsfw) == "true");
2065 $tags = unxmlify($data->tag_string);
2067 $tags = explode("#", $tags);
2069 $keywords = array();
2070 foreach ($tags as $tag) {
2071 $tag = trim(strtolower($tag));
2076 $keywords = implode(", ", $keywords);
2078 $handle_parts = explode("@", $author);
2079 $nick = $handle_parts[0];
2082 $name = $handle_parts[0];
2084 if ( preg_match("|^https?://|", $image_url) === 0)
2085 $image_url = "http://".$handle_parts[1].$image_url;
2087 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
2089 // Generic birthday. We don't know the timezone. The year is irrelevant.
2091 $birthday = str_replace("1000", "1901", $birthday);
2093 if ($birthday != "")
2094 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
2096 // this is to prevent multiple birthday notifications in a single year
2097 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2099 if (substr($birthday,5) === substr($contact["bd"],5))
2100 $birthday = $contact["bd"];
2102 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2103 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2107 dbesc(datetime_convert()),
2113 intval($contact["id"]),
2114 intval($importer["uid"])
2117 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2118 "photo" => $image_url, "name" => $name, "location" => $location,
2119 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2120 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2121 "hide" => !$searchable, "nsfw" => $nsfw);
2123 $gcid = update_gcontact($gcontact);
2125 link_gcontact($gcid, $importer["uid"], $contact["id"]);
2127 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2133 * @brief Processes incoming friend requests
2135 * @param array $importer Array of the importer user
2136 * @param array $contact The contact that send the request
2138 private static function receive_request_make_friend($importer, $contact) {
2142 if ($contact["rel"] == CONTACT_IS_SHARING) {
2143 dba::update('contact', array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
2144 array('id' => $contact["id"], 'uid' => $importer["uid"]));
2146 // send notification
2148 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2149 intval($importer["uid"])
2152 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
2154 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2155 intval($importer["uid"])
2158 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2160 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2163 $arr["protocol"] = PROTOCOL_DIASPORA;
2164 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2165 $arr["uid"] = $importer["uid"];
2166 $arr["contact-id"] = $self[0]["id"];
2168 $arr["type"] = 'wall';
2169 $arr["gravity"] = 0;
2171 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2172 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2173 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2174 $arr["verb"] = ACTIVITY_FRIEND;
2175 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2177 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2178 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2179 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2180 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
2182 $arr["object"] = self::construct_new_friend_object($contact);
2184 $arr["last-child"] = 1;
2186 $arr["allow_cid"] = $user[0]["allow_cid"];
2187 $arr["allow_gid"] = $user[0]["allow_gid"];
2188 $arr["deny_cid"] = $user[0]["deny_cid"];
2189 $arr["deny_gid"] = $user[0]["deny_gid"];
2191 $i = item_store($arr);
2193 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
2199 * @brief Creates a XML object for a "new friend" message
2201 * @param array $contact Array of the contact
2203 * @return string The XML
2205 private static function construct_new_friend_object($contact) {
2206 $objtype = ACTIVITY_OBJ_PERSON;
2207 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2208 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2210 $xmldata = array("object" => array("type" => $objtype,
2211 "title" => $contact["name"],
2212 "id" => $contact["url"]."/".$contact["name"],
2215 return xml::from_array($xmldata, $xml, true);
2219 * @brief Processes incoming sharing notification
2221 * @param array $importer Array of the importer user
2222 * @param object $data The message object
2224 * @return bool Success
2226 private static function receive_contact_request($importer, $data) {
2227 $author = unxmlify($data->author);
2228 $recipient = unxmlify($data->recipient);
2230 if (!$author || !$recipient) {
2234 // the current protocol version doesn't know these fields
2235 // That means that we will assume their existance
2236 if (isset($data->following)) {
2237 $following = (unxmlify($data->following) == "true");
2242 if (isset($data->sharing)) {
2243 $sharing = (unxmlify($data->sharing) == "true");
2248 $contact = self::contact_by_handle($importer["uid"],$author);
2250 // perhaps we were already sharing with this person. Now they're sharing with us.
2251 // That makes us friends.
2254 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2255 self::receive_request_make_friend($importer, $contact);
2257 // refetch the contact array
2258 $contact = self::contact_by_handle($importer["uid"],$author);
2260 // If we are now friends, we are sending a share message.
2261 // Normally we needn't to do so, but the first message could have been vanished.
2262 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND))) {
2263 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2265 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2266 $ret = self::send_share($u[0], $contact);
2271 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2272 lose_follower($importer, $contact);
2277 if (!$following && $sharing && in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2278 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2280 } elseif (!$following && !$sharing) {
2281 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2283 } elseif (!$following && $sharing) {
2284 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2285 } elseif ($following && $sharing) {
2286 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2287 } elseif ($following && !$sharing) {
2288 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2291 $ret = self::person_by_handle($author);
2293 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2294 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2298 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2300 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2301 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2302 intval($importer["uid"]),
2303 dbesc($ret["network"]),
2304 dbesc($ret["addr"]),
2307 dbesc(normalise_link($ret["url"])),
2309 dbesc($ret["name"]),
2310 dbesc($ret["nick"]),
2311 dbesc($ret["photo"]),
2312 dbesc($ret["pubkey"]),
2313 dbesc($ret["notify"]),
2314 dbesc($ret["poll"]),
2319 // find the contact record we just created
2321 $contact_record = self::contact_by_handle($importer["uid"],$author);
2323 if (!$contact_record) {
2324 logger("unable to locate newly created contact record.");
2328 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2330 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2332 if (intval($def_gid))
2333 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2335 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2337 if ($importer["page-flags"] == PAGE_NORMAL) {
2339 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2341 $hash = random_string().(string)time(); // Generate a confirm_key
2343 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2344 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2345 intval($importer["uid"]),
2346 intval($contact_record["id"]),
2349 dbesc(t("Sharing notification from Diaspora network")),
2351 dbesc(datetime_convert())
2355 // automatic friend approval
2357 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2359 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2361 // technically they are sharing with us (CONTACT_IS_SHARING),
2362 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2363 // we are going to change the relationship and make them a follower.
2365 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following)
2366 $new_relation = CONTACT_IS_FRIEND;
2367 elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing)
2368 $new_relation = CONTACT_IS_SHARING;
2370 $new_relation = CONTACT_IS_FOLLOWER;
2372 $r = q("UPDATE `contact` SET `rel` = %d,
2380 intval($new_relation),
2381 dbesc(datetime_convert()),
2382 dbesc(datetime_convert()),
2383 intval($contact_record["id"])
2386 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2388 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2389 $ret = self::send_share($u[0], $contact_record);
2391 // Send the profile data, maybe it weren't transmitted before
2392 self::send_profile($importer["uid"], array($contact_record));
2400 * @brief Fetches a message with a given guid
2402 * @param string $guid message guid
2403 * @param string $orig_author handle of the original post
2404 * @param string $author handle of the sharer
2406 * @return array The fetched item
2408 private static function original_item($guid, $orig_author, $author) {
2410 // Do we already have this item?
2411 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2412 `author-name`, `author-link`, `author-avatar`
2413 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2416 if (dbm::is_result($r)) {
2417 logger("reshared message ".$guid." already exists on system.");
2419 // Maybe it is already a reshared item?
2420 // Then refetch the content, if it is a reshare from a reshare.
2421 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2422 if (self::is_reshare($r[0]["body"], true)) {
2424 } elseif (self::is_reshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2425 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2427 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2429 // Add OEmbed and other information to the body
2430 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2438 if (!dbm::is_result($r)) {
2439 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2440 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2441 $item_id = self::store_by_guid($guid, $server);
2444 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2445 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2446 $item_id = self::store_by_guid($guid, $server);
2450 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2451 `author-name`, `author-link`, `author-avatar`
2452 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2455 if (dbm::is_result($r)) {
2456 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2457 if (self::is_reshare($r[0]["body"], false)) {
2458 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2459 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2471 * @brief Processes a reshare message
2473 * @param array $importer Array of the importer user
2474 * @param object $data The message object
2475 * @param string $xml The original XML of the message
2477 * @return int the message id
2479 private static function receive_reshare($importer, $data, $xml) {
2480 $author = notags(unxmlify($data->author));
2481 $guid = notags(unxmlify($data->guid));
2482 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2483 $root_author = notags(unxmlify($data->root_author));
2484 $root_guid = notags(unxmlify($data->root_guid));
2485 /// @todo handle unprocessed property "provider_display_name"
2486 $public = notags(unxmlify($data->public));
2488 $contact = self::allowed_contact_by_handle($importer, $author, false);
2493 $message_id = self::message_exists($importer["uid"], $guid);
2498 $original_item = self::original_item($root_guid, $root_author, $author);
2499 if (!$original_item) {
2503 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2505 $datarray = array();
2507 $datarray["uid"] = $importer["uid"];
2508 $datarray["contact-id"] = $contact["id"];
2509 $datarray["network"] = NETWORK_DIASPORA;
2511 $datarray["author-name"] = $contact["name"];
2512 $datarray["author-link"] = $contact["url"];
2513 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2515 $datarray["owner-name"] = $datarray["author-name"];
2516 $datarray["owner-link"] = $datarray["author-link"];
2517 $datarray["owner-avatar"] = $datarray["author-avatar"];
2519 $datarray["guid"] = $guid;
2520 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2522 $datarray["verb"] = ACTIVITY_POST;
2523 $datarray["gravity"] = GRAVITY_PARENT;
2525 $datarray["protocol"] = PROTOCOL_DIASPORA;
2526 $datarray["source"] = $xml;
2528 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2529 $original_item["guid"], $original_item["created"], $orig_url);
2530 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2532 $datarray["tag"] = $original_item["tag"];
2533 $datarray["app"] = $original_item["app"];
2535 $datarray["plink"] = self::plink($author, $guid);
2536 $datarray["private"] = (($public == "false") ? 1 : 0);
2537 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2539 $datarray["object-type"] = $original_item["object-type"];
2541 self::fetch_guid($datarray);
2542 $message_id = item_store($datarray);
2545 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2553 * @brief Processes retractions
2555 * @param array $importer Array of the importer user
2556 * @param array $contact The contact of the item owner
2557 * @param object $data The message object
2559 * @return bool success
2561 private static function item_retraction($importer, $contact, $data) {
2562 $author = notags(unxmlify($data->author));
2563 $target_guid = notags(unxmlify($data->target_guid));
2564 $target_type = notags(unxmlify($data->target_type));
2566 $person = self::person_by_handle($author);
2567 if (!is_array($person)) {
2568 logger("unable to find author detail for ".$author);
2572 if (empty($contact["url"])) {
2573 $contact["url"] = $person["url"];
2576 // Fetch items that are about to be deleted
2577 $fields = array('uid', 'id', 'parent', 'parent-uri', 'author-link');
2579 // When we receive a public retraction, we delete every item that we find.
2580 if ($importer['uid'] == 0) {
2581 $condition = array("`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid);
2583 $condition = array("`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']);
2585 $r = dba::select('item', $fields, $condition);
2586 if (!dbm::is_result($r)) {
2587 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2591 while ($item = dba::fetch($r)) {
2592 // Fetch the parent item
2593 $parent = dba::select('item', array('author-link', 'origin'), array('id' => $item["parent"]), array('limit' => 1));
2595 // Only delete it if the parent author really fits
2596 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2597 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2601 // Currently we don't have a central deletion function that we could use in this case. The function "item_drop" doesn't work for that case
2602 dba::update('item', array('deleted' => true, 'title' => '', 'body' => '',
2603 'edited' => datetime_convert(), 'changed' => datetime_convert()),
2604 array('id' => $item["id"]));
2606 // Delete the thread - if it is a starting post and not a comment
2607 if ($target_type != 'Comment') {
2608 delete_thread($item["id"], $item["parent-uri"]);
2611 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2613 // Now check if the retraction needs to be relayed by us
2614 if ($parent["origin"]) {
2616 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $item["id"]);
2624 * @brief Receives retraction messages
2626 * @param array $importer Array of the importer user
2627 * @param string $sender The sender of the message
2628 * @param object $data The message object
2630 * @return bool Success
2632 private static function receive_retraction($importer, $sender, $data) {
2633 $target_type = notags(unxmlify($data->target_type));
2635 $contact = self::contact_by_handle($importer["uid"], $sender);
2636 if (!$contact && (in_array($target_type, array("Contact", "Person")))) {
2637 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2641 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2643 switch ($target_type) {
2648 case "StatusMessage":
2649 return self::item_retraction($importer, $contact, $data);
2653 /// @todo What should we do with an "unshare"?
2654 // Removing the contact isn't correct since we still can read the public items
2655 contact_remove($contact["id"]);
2659 logger("Unknown target type ".$target_type);
2666 * @brief Receives status messages
2668 * @param array $importer Array of the importer user
2669 * @param object $data The message object
2670 * @param string $xml The original XML of the message
2672 * @return int The message id of the newly created item
2674 private static function receive_status_message($importer, $data, $xml) {
2675 $author = notags(unxmlify($data->author));
2676 $guid = notags(unxmlify($data->guid));
2677 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2678 $public = notags(unxmlify($data->public));
2679 $text = unxmlify($data->text);
2680 $provider_display_name = notags(unxmlify($data->provider_display_name));
2682 $contact = self::allowed_contact_by_handle($importer, $author, false);
2687 $message_id = self::message_exists($importer["uid"], $guid);
2693 if ($data->location) {
2694 foreach ($data->location->children() AS $fieldname => $data) {
2695 $address[$fieldname] = notags(unxmlify($data));
2699 $body = diaspora2bb($text);
2701 $datarray = array();
2703 // Attach embedded pictures to the body
2705 foreach ($data->photo AS $photo) {
2706 $body = "[img]".unxmlify($photo->remote_photo_path).
2707 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2710 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2712 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2714 // Add OEmbed and other information to the body
2715 if (!self::is_redmatrix($contact["url"])) {
2716 $body = add_page_info_to_body($body, false, true);
2720 /// @todo enable support for polls
2721 //if ($data->poll) {
2722 // foreach ($data->poll AS $poll)
2727 /// @todo enable support for events
2729 $datarray["uid"] = $importer["uid"];
2730 $datarray["contact-id"] = $contact["id"];
2731 $datarray["network"] = NETWORK_DIASPORA;
2733 $datarray["author-name"] = $contact["name"];
2734 $datarray["author-link"] = $contact["url"];
2735 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2737 $datarray["owner-name"] = $datarray["author-name"];
2738 $datarray["owner-link"] = $datarray["author-link"];
2739 $datarray["owner-avatar"] = $datarray["author-avatar"];
2741 $datarray["guid"] = $guid;
2742 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2744 $datarray["verb"] = ACTIVITY_POST;
2745 $datarray["gravity"] = GRAVITY_PARENT;
2747 $datarray["protocol"] = PROTOCOL_DIASPORA;
2748 $datarray["source"] = $xml;
2750 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2752 if ($provider_display_name != "") {
2753 $datarray["app"] = $provider_display_name;
2756 $datarray["plink"] = self::plink($author, $guid);
2757 $datarray["private"] = (($public == "false") ? 1 : 0);
2758 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2760 if (isset($address["address"])) {
2761 $datarray["location"] = $address["address"];
2764 if (isset($address["lat"]) && isset($address["lng"])) {
2765 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2768 self::fetch_guid($datarray);
2769 $message_id = item_store($datarray);
2772 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2779 /* ************************************************************************************** *
2780 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2781 * ************************************************************************************** */
2784 * @brief returnes the handle of a contact
2786 * @param array $me contact array
2788 * @return string the handle in the format user@domain.tld
2790 private static function my_handle($contact) {
2791 if ($contact["addr"] != "") {
2792 return $contact["addr"];
2795 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2796 // So - just in case - we build the the address here.
2797 if ($contact["nickname"] != "") {
2798 $nick = $contact["nickname"];
2800 $nick = $contact["nick"];
2803 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(),"://") + 3);
2808 * @brief Creates the data for a private message in the new format
2810 * @param string $msg The message that is to be transmitted
2811 * @param array $user The record of the sender
2812 * @param array $contact Target of the communication
2813 * @param string $prvkey The private key of the sender
2814 * @param string $pubkey The public key of the receiver
2816 * @return string The encrypted data
2818 public static function encode_private_data($msg, $user, $contact, $prvkey, $pubkey) {
2820 logger("Message: ".$msg, LOGGER_DATA);
2822 // without a public key nothing will work
2824 logger("pubkey missing: contact id: ".$contact["id"]);
2828 $aes_key = openssl_random_pseudo_bytes(32);
2829 $b_aes_key = base64_encode($aes_key);
2830 $iv = openssl_random_pseudo_bytes(16);
2831 $b_iv = base64_encode($iv);
2833 $ciphertext = self::aes_encrypt($aes_key, $iv, $msg);
2835 $json = json_encode(array("iv" => $b_iv, "key" => $b_aes_key));
2837 $encrypted_key_bundle = "";
2838 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
2840 $json_object = json_encode(array("aes_key" => base64_encode($encrypted_key_bundle),
2841 "encrypted_magic_envelope" => base64_encode($ciphertext)));
2843 return $json_object;
2847 * @brief Creates the envelope for the "fetch" endpoint and for the new format
2849 * @param string $msg The message that is to be transmitted
2850 * @param array $user The record of the sender
2852 * @return string The envelope
2854 public static function build_magic_envelope($msg, $user) {
2856 $b64url_data = base64url_encode($msg);
2857 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2859 $key_id = base64url_encode(self::my_handle($user));
2860 $type = "application/xml";
2861 $encoding = "base64url";
2862 $alg = "RSA-SHA256";
2863 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2865 // Fallback if the private key wasn't transmitted in the expected field
2866 if ($user['uprvkey'] == "")
2867 $user['uprvkey'] = $user['prvkey'];
2869 $signature = rsa_sign($signable_data, $user["uprvkey"]);
2870 $sig = base64url_encode($signature);
2872 $xmldata = array("me:env" => array("me:data" => $data,
2873 "@attributes" => array("type" => $type),
2874 "me:encoding" => $encoding,
2877 "@attributes2" => array("key_id" => $key_id)));
2879 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2881 return xml::from_array($xmldata, $xml, false, $namespaces);
2885 * @brief Create the envelope for a message
2887 * @param string $msg The message that is to be transmitted
2888 * @param array $user The record of the sender
2889 * @param array $contact Target of the communication
2890 * @param string $prvkey The private key of the sender
2891 * @param string $pubkey The public key of the receiver
2892 * @param bool $public Is the message public?
2894 * @return string The message that will be transmitted to other servers
2896 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2898 // The message is put into an envelope with the sender's signature
2899 $envelope = self::build_magic_envelope($msg, $user);
2901 // Private messages are put into a second envelope, encrypted with the receivers public key
2903 $envelope = self::encode_private_data($envelope, $user, $contact, $prvkey, $pubkey);
2910 * @brief Creates a signature for a message
2912 * @param array $owner the array of the owner of the message
2913 * @param array $message The message that is to be signed
2915 * @return string The signature
2917 private static function signature($owner, $message) {
2919 unset($sigmsg["author_signature"]);
2920 unset($sigmsg["parent_author_signature"]);
2922 $signed_text = implode(";", $sigmsg);
2924 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2928 * @brief Transmit a message to a target server
2930 * @param array $owner the array of the item owner
2931 * @param array $contact Target of the communication
2932 * @param string $envelope The message that is to be transmitted
2933 * @param bool $public_batch Is it a public post?
2934 * @param bool $queue_run Is the transmission called from the queue?
2935 * @param string $guid message guid
2937 * @return int Result of the transmission
2939 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run=false, $guid = "") {
2943 $enabled = intval(get_config("system", "diaspora_enabled"));
2947 $logid = random_string(4);
2948 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2950 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2954 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2956 if (!$queue_run && was_recently_delayed($contact["id"])) {
2959 if (!intval(get_config("system", "diaspora_test"))) {
2960 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
2962 post_url($dest_url."/", $envelope, array("Content-Type: ".$content_type));
2963 $return_code = $a->get_curl_code();
2965 logger("test_mode");
2970 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2972 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2973 logger("queue message");
2975 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2976 intval($contact["id"]),
2977 dbesc(NETWORK_DIASPORA),
2979 intval($public_batch)
2982 logger("add_to_queue ignored - identical item already in queue");
2984 // queue message for redelivery
2985 add_to_queue($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch);
2987 // The message could not be delivered. We mark the contact as "dead"
2988 mark_for_death($contact);
2990 } elseif (($return_code >= 200) && ($return_code <= 299)) {
2991 // We successfully delivered a message, the contact is alive
2992 unmark_for_death($contact);
2995 return(($return_code) ? $return_code : (-1));
3000 * @brief Build the post xml
3002 * @param string $type The message type
3003 * @param array $message The message data
3005 * @return string The post XML
3007 public static function build_post_xml($type, $message) {
3009 $data = array($type => $message);
3011 return xml::from_array($data, $xml);
3015 * @brief Builds and transmit messages
3017 * @param array $owner the array of the item owner
3018 * @param array $contact Target of the communication
3019 * @param string $type The message type
3020 * @param array $message The message data
3021 * @param bool $public_batch Is it a public post?
3022 * @param string $guid message guid
3023 * @param bool $spool Should the transmission be spooled or transmitted?
3025 * @return int Result of the transmission
3027 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
3029 $msg = self::build_post_xml($type, $message);
3031 logger('message: '.$msg, LOGGER_DATA);
3032 logger('send guid '.$guid, LOGGER_DEBUG);
3034 // Fallback if the private key wasn't transmitted in the expected field
3035 if ($owner['uprvkey'] == "")
3036 $owner['uprvkey'] = $owner['prvkey'];
3038 $envelope = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3041 add_to_queue($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch);
3044 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3046 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
3048 return $return_code;
3052 * @brief sends an account migration
3054 * @param array $owner the array of the item owner
3055 * @param array $contact Target of the communication
3056 * @param int $uid User ID
3058 * @return int The result of the transmission
3060 public static function sendAccountMigration($owner, $contact, $uid) {
3062 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3063 $profile = self::createProfileData($uid);
3065 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3066 $signature = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3068 $message = array("author" => $old_handle,
3069 "profile" => $profile,
3070 "signature" => $signature);
3072 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3074 return self::build_and_transmit($owner, $contact, "account_migration", $message);
3078 * @brief Sends a "share" message
3080 * @param array $owner the array of the item owner
3081 * @param array $contact Target of the communication
3083 * @return int The result of the transmission
3085 public static function send_share($owner, $contact) {
3088 * @todo support the different possible combinations of "following" and "sharing"
3089 * Currently, Diaspora only interprets the "sharing" field
3091 * Before switching this code productive, we have to check all "send_share" calls if "rel" is set correctly
3095 switch ($contact["rel"]) {
3096 case CONTACT_IS_FRIEND:
3099 case CONTACT_IS_SHARING:
3102 case CONTACT_IS_FOLLOWER:
3108 $message = array("author" => self::my_handle($owner),
3109 "recipient" => $contact["addr"],
3110 "following" => "true",
3111 "sharing" => "true");
3113 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3115 return self::build_and_transmit($owner, $contact, "contact", $message);
3119 * @brief sends an "unshare"
3121 * @param array $owner the array of the item owner
3122 * @param array $contact Target of the communication
3124 * @return int The result of the transmission
3126 public static function send_unshare($owner, $contact) {
3128 $message = array("author" => self::my_handle($owner),
3129 "recipient" => $contact["addr"],
3130 "following" => "false",
3131 "sharing" => "false");
3133 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3135 return self::build_and_transmit($owner, $contact, "contact", $message);
3139 * @brief Checks a message body if it is a reshare
3141 * @param string $body The message body that is to be check
3142 * @param bool $complete Should it be a complete check or a simple check?
3144 * @return array|bool Reshare details or "false" if no reshare
3146 public static function is_reshare($body, $complete = true) {
3147 $body = trim($body);
3149 // Skip if it isn't a pure repeated messages
3150 // Does it start with a share?
3151 if ((strpos($body, "[share") > 0) && $complete)
3154 // Does it end with a share?
3155 if (strlen($body) > (strrpos($body, "[/share]") + 8))
3158 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
3159 // Skip if there is no shared message in there
3160 if ($body == $attributes)
3163 // If we don't do the complete check we quit here
3168 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3169 if ($matches[1] != "")
3170 $guid = $matches[1];
3172 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3173 if ($matches[1] != "")
3174 $guid = $matches[1];
3177 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3178 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
3181 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
3182 $ret["root_guid"] = $guid;
3188 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3189 if ($matches[1] != "")
3190 $profile = $matches[1];
3192 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3193 if ($matches[1] != "")
3194 $profile = $matches[1];
3198 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3199 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == ""))
3203 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3204 if ($matches[1] != "")
3205 $link = $matches[1];
3207 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3208 if ($matches[1] != "")
3209 $link = $matches[1];
3211 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3212 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == ""))
3219 * @brief Create an event array
3221 * @param integer $event_id The id of the event
3223 * @return array with event data
3225 private static function build_event($event_id) {
3227 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3228 if (!dbm::is_result($r)) {
3234 $eventdata = array();
3236 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3237 if (!dbm::is_result($r)) {
3243 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3244 if (!dbm::is_result($r)) {
3250 $eventdata['author'] = self::my_handle($owner);
3252 if ($event['guid']) {
3253 $eventdata['guid'] = $event['guid'];
3256 $mask = 'Y-m-d\TH:i:s\Z';
3258 /// @todo - establish "all day" events in Friendica
3259 $eventdata["all_day"] = "false";
3261 if (!$event['adjust']) {
3262 $eventdata['timezone'] = $user['timezone'];
3264 if ($eventdata['timezone'] == "") {
3265 $eventdata['timezone'] = 'UTC';
3269 if ($event['start']) {
3270 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3272 if ($event['finish'] && !$event['nofinish']) {
3273 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3275 if ($event['summary']) {
3276 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3278 if ($event['desc']) {
3279 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3281 if ($event['location']) {
3282 $location = array();
3283 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3284 $location["lat"] = 0;
3285 $location["lng"] = 0;
3286 $eventdata['location'] = $location;
3293 * @brief Create a post (status message or reshare)
3295 * @param array $item The item that will be exported
3296 * @param array $owner the array of the item owner
3299 * 'type' -> Message type ("status_message" or "reshare")
3300 * 'message' -> Array of XML elements of the status
3302 public static function build_status($item, $owner) {
3304 $cachekey = "diaspora:build_status:".$item['guid'];
3306 $result = Cache::get($cachekey);
3307 if (!is_null($result)) {
3311 $myaddr = self::my_handle($owner);
3313 $public = (($item["private"]) ? "false" : "true");
3315 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3317 // Detect a share element and do a reshare
3318 if (!$item['private'] && ($ret = self::is_reshare($item["body"]))) {
3319 $message = array("author" => $myaddr,
3320 "guid" => $item["guid"],
3321 "created_at" => $created,
3322 "root_author" => $ret["root_handle"],
3323 "root_guid" => $ret["root_guid"],
3324 "provider_display_name" => $item["app"],
3325 "public" => $public);
3329 $title = $item["title"];
3330 $body = $item["body"];
3332 // convert to markdown
3333 $body = html_entity_decode(bb2diaspora($body));
3337 $body = "## ".html_entity_decode($title)."\n\n".$body;
3339 if ($item["attach"]) {
3340 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3342 $body .= "\n".t("Attachments:")."\n";
3343 foreach ($matches as $mtch)
3344 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3348 $location = array();
3350 if ($item["location"] != "")
3351 $location["address"] = $item["location"];
3353 if ($item["coord"] != "") {
3354 $coord = explode(" ", $item["coord"]);
3355 $location["lat"] = $coord[0];
3356 $location["lng"] = $coord[1];
3359 $message = array("author" => $myaddr,
3360 "guid" => $item["guid"],
3361 "created_at" => $created,
3362 "public" => $public,
3364 "provider_display_name" => $item["app"],
3365 "location" => $location);
3367 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3368 if (!isset($location["lat"]) || !isset($location["lng"])) {
3369 unset($message["location"]);
3372 if ($item['event-id'] > 0) {
3373 $event = self::build_event($item['event-id']);
3374 if (count($event)) {
3375 $message['event'] = $event;
3377 /// @todo Once Diaspora supports it, we will remove the body
3378 // $message['text'] = '';
3382 $type = "status_message";
3385 $msg = array("type" => $type, "message" => $message);
3387 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3393 * @brief Sends a post
3395 * @param array $item The item that will be exported
3396 * @param array $owner the array of the item owner
3397 * @param array $contact Target of the communication
3398 * @param bool $public_batch Is it a public post?
3400 * @return int The result of the transmission
3402 public static function send_status($item, $owner, $contact, $public_batch = false) {
3404 $status = self::build_status($item, $owner);
3406 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3410 * @brief Creates a "like" object
3412 * @param array $item The item that will be exported
3413 * @param array $owner the array of the item owner
3415 * @return array The data for a "like"
3417 private static function construct_like($item, $owner) {
3419 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3420 dbesc($item["thr-parent"]));
3421 if (!dbm::is_result($p))
3426 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3427 if ($item['verb'] === ACTIVITY_LIKE) {
3429 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3430 $positive = "false";
3433 return(array("author" => self::my_handle($owner),
3434 "guid" => $item["guid"],
3435 "parent_guid" => $parent["guid"],
3436 "parent_type" => $target_type,
3437 "positive" => $positive,
3438 "author_signature" => ""));
3442 * @brief Creates an "EventParticipation" object
3444 * @param array $item The item that will be exported
3445 * @param array $owner the array of the item owner
3447 * @return array The data for an "EventParticipation"
3449 private static function construct_attend($item, $owner) {
3451 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3452 dbesc($item["thr-parent"]));
3453 if (!dbm::is_result($p))
3458 switch ($item['verb']) {
3459 case ACTIVITY_ATTEND:
3460 $attend_answer = 'accepted';
3462 case ACTIVITY_ATTENDNO:
3463 $attend_answer = 'declined';
3465 case ACTIVITY_ATTENDMAYBE:
3466 $attend_answer = 'tentative';
3469 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3473 return(array("author" => self::my_handle($owner),
3474 "guid" => $item["guid"],
3475 "parent_guid" => $parent["guid"],
3476 "status" => $attend_answer,
3477 "author_signature" => ""));
3481 * @brief Creates the object for a comment
3483 * @param array $item The item that will be exported
3484 * @param array $owner the array of the item owner
3486 * @return array The data for a comment
3488 private static function construct_comment($item, $owner) {
3490 $cachekey = "diaspora:construct_comment:".$item['guid'];
3492 $result = Cache::get($cachekey);
3493 if (!is_null($result)) {
3497 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3498 intval($item["parent"]),
3499 intval($item["parent"])
3502 if (!dbm::is_result($p))
3507 $text = html_entity_decode(bb2diaspora($item["body"]));
3508 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3510 $comment = array("author" => self::my_handle($owner),
3511 "guid" => $item["guid"],
3512 "created_at" => $created,
3513 "parent_guid" => $parent["guid"],
3515 "author_signature" => "");
3517 // Send the thread parent guid only if it is a threaded comment
3518 if ($item['thr-parent'] != $item['parent-uri']) {
3519 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3522 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3528 * @brief Send a like or a comment
3530 * @param array $item The item that will be exported
3531 * @param array $owner the array of the item owner
3532 * @param array $contact Target of the communication
3533 * @param bool $public_batch Is it a public post?
3535 * @return int The result of the transmission
3537 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3539 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3540 $message = self::construct_attend($item, $owner);
3541 $type = "event_participation";
3542 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3543 $message = self::construct_like($item, $owner);
3546 $message = self::construct_comment($item, $owner);
3553 $message["author_signature"] = self::signature($owner, $message);
3555 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3559 * @brief Creates a message from a signature record entry
3561 * @param array $item The item that will be exported
3562 * @param array $signature The entry of the "sign" record
3564 * @return string The message
3566 private static function message_from_signature($item, $signature) {
3568 // Split the signed text
3569 $signed_parts = explode(";", $signature['signed_text']);
3571 if ($item["deleted"])
3572 $message = array("author" => $signature['signer'],
3573 "target_guid" => $signed_parts[0],
3574 "target_type" => $signed_parts[1]);
3575 elseif ($item['verb'] === ACTIVITY_LIKE)
3576 $message = array("author" => $signed_parts[4],
3577 "guid" => $signed_parts[1],
3578 "parent_guid" => $signed_parts[3],
3579 "parent_type" => $signed_parts[2],
3580 "positive" => $signed_parts[0],
3581 "author_signature" => $signature['signature'],
3582 "parent_author_signature" => "");
3584 // Remove the comment guid
3585 $guid = array_shift($signed_parts);
3587 // Remove the parent guid
3588 $parent_guid = array_shift($signed_parts);
3590 // Remove the handle
3591 $handle = array_pop($signed_parts);
3593 // Glue the parts together
3594 $text = implode(";", $signed_parts);
3596 $message = array("author" => $handle,
3598 "parent_guid" => $parent_guid,
3599 "text" => implode(";", $signed_parts),
3600 "author_signature" => $signature['signature'],
3601 "parent_author_signature" => "");
3607 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3609 * @param array $item The item that will be exported
3610 * @param array $owner the array of the item owner
3611 * @param array $contact Target of the communication
3612 * @param bool $public_batch Is it a public post?
3614 * @return int The result of the transmission
3616 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3618 if ($item["deleted"])
3619 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3620 elseif ($item['verb'] === ACTIVITY_LIKE)
3625 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3627 // fetch the original signature
3629 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3630 intval($item["id"]));
3633 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3639 // Old way - is used by the internal Friendica functions
3640 /// @todo Change all signatur storing functions to the new format
3641 if ($signature['signed_text'] && $signature['signature'] && $signature['signer'])
3642 $message = self::message_from_signature($item, $signature);
3644 $msg = json_decode($signature['signed_text'], true);
3647 if (is_array($msg)) {
3648 foreach ($msg AS $field => $data) {
3649 if (!$item["deleted"]) {
3650 if ($field == "diaspora_handle") {
3653 if ($field == "target_type") {
3654 $field = "parent_type";
3658 $message[$field] = $data;
3661 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3664 $message["parent_author_signature"] = self::signature($owner, $message);
3666 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3668 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3672 * @brief Sends a retraction (deletion) of a message, like or comment
3674 * @param array $item The item that will be exported
3675 * @param array $owner the array of the item owner
3676 * @param array $contact Target of the communication
3677 * @param bool $public_batch Is it a public post?
3678 * @param bool $relay Is the retraction transmitted from a relay?
3680 * @return int The result of the transmission
3682 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3684 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3686 $msg_type = "retraction";
3688 if ($item['id'] == $item['parent']) {
3689 $target_type = "Post";
3690 } elseif ($item["verb"] == ACTIVITY_LIKE) {
3691 $target_type = "Like";
3693 $target_type = "Comment";
3696 $message = array("author" => $itemaddr,
3697 "target_guid" => $item['guid'],
3698 "target_type" => $target_type);
3700 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3702 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3706 * @brief Sends a mail
3708 * @param array $item The item that will be exported
3709 * @param array $owner The owner
3710 * @param array $contact Target of the communication
3712 * @return int The result of the transmission
3714 public static function send_mail($item, $owner, $contact) {
3716 $myaddr = self::my_handle($owner);
3718 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3719 intval($item["convid"]),
3720 intval($item["uid"])
3723 if (!dbm::is_result($r)) {
3724 logger("conversation not found.");
3730 "author" => $cnv["creator"],
3731 "guid" => $cnv["guid"],
3732 "subject" => $cnv["subject"],
3733 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3734 "participants" => $cnv["recips"]
3737 $body = bb2diaspora($item["body"]);
3738 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3741 "author" => $myaddr,
3742 "guid" => $item["guid"],
3743 "conversation_guid" => $cnv["guid"],
3745 "created_at" => $created,
3748 if ($item["reply"]) {
3753 "author" => $cnv["creator"],
3754 "guid" => $cnv["guid"],
3755 "subject" => $cnv["subject"],
3756 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3757 "participants" => $cnv["recips"],
3760 $type = "conversation";
3763 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3767 * @brief Create profile data
3769 * @param int $uid The user id
3771 * @return array The profile data
3773 private static function createProfileData($uid) {
3774 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3776 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3777 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3778 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3788 $handle = $profile["addr"];
3789 $first = ((strpos($profile['name'],' ')
3790 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3791 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3792 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3793 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3794 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3795 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3797 if ($searchable === 'true') {
3798 $dob = '1000-00-00';
3800 if (($profile['dob']) && ($profile['dob'] > '0001-01-01'))
3801 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3803 $about = $profile['about'];
3804 $about = strip_tags(bbcode($about));
3806 $location = formatted_location($profile);
3808 if ($profile['pub_keywords']) {
3809 $kw = str_replace(',',' ',$profile['pub_keywords']);
3810 $kw = str_replace(' ',' ',$kw);
3811 $arr = explode(' ',$profile['pub_keywords']);
3813 for ($x = 0; $x < 5; $x ++) {
3815 $tags .= '#'. trim($arr[$x]) .' ';
3819 $tags = trim($tags);
3822 return array("author" => $handle,
3823 "first_name" => $first,
3824 "last_name" => $last,
3825 "image_url" => $large,
3826 "image_url_medium" => $medium,
3827 "image_url_small" => $small,
3829 "gender" => $profile['gender'],
3831 "location" => $location,
3832 "searchable" => $searchable,
3834 "tag_string" => $tags);
3838 * @brief Sends profile data
3840 * @param int $uid The user id
3842 public static function send_profile($uid, $recips = false) {
3848 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3849 AND `uid` = %d AND `rel` != %d",
3850 dbesc(NETWORK_DIASPORA),
3852 intval(CONTACT_IS_SHARING)
3857 $message = self::createProfileData($uid);
3859 foreach ($recips as $recip) {
3860 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3861 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3866 * @brief Stores the signature for likes that are created on our system
3868 * @param array $contact The contact array of the "like"
3869 * @param int $post_id The post id of the "like"
3871 * @return bool Success
3873 public static function store_like_signature($contact, $post_id) {
3875 // Is the contact the owner? Then fetch the private key
3876 if (!$contact['self'] || ($contact['uid'] == 0)) {
3877 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3881 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3882 if (!dbm::is_result($r)) {
3886 $contact["uprvkey"] = $r[0]['prvkey'];
3888 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3889 if (!dbm::is_result($r)) {
3893 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3897 $message = self::construct_like($r[0], $contact);
3898 $message["author_signature"] = self::signature($contact, $message);
3901 * Now store the signature more flexible to dynamically support new fields.
3902 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
3904 dba::insert('sign', array('iid' => $post_id, 'signed_text' => json_encode($message)));
3906 logger('Stored diaspora like signature');
3911 * @brief Stores the signature for comments that are created on our system
3913 * @param array $item The item array of the comment
3914 * @param array $contact The contact array of the item owner
3915 * @param string $uprvkey The private key of the sender
3916 * @param int $message_id The message id of the comment
3918 * @return bool Success
3920 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3922 if ($uprvkey == "") {
3923 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3927 $contact["uprvkey"] = $uprvkey;
3929 $message = self::construct_comment($item, $contact);
3930 $message["author_signature"] = self::signature($contact, $message);
3933 * Now store the signature more flexible to dynamically support new fields.
3934 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
3936 dba::insert('sign', array('iid' => $message_id, 'signed_text' => json_encode($message)));
3938 logger('Stored diaspora comment signature');