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 * Currently this implementation here interprets the old and the new protocol and sends the old one.
8 * This will change in the future.
11 use \Friendica\Core\Config;
13 require_once("include/items.php");
14 require_once("include/bb2diaspora.php");
15 require_once("include/Scrape.php");
16 require_once("include/Contact.php");
17 require_once("include/Photo.php");
18 require_once("include/socgraph.php");
19 require_once("include/group.php");
20 require_once("include/xml.php");
21 require_once("include/datetime.php");
22 require_once("include/queue_fn.php");
23 require_once("include/cache.php");
26 * @brief This class contain functions to create and send Diaspora XML files
32 * @brief Return a list of relay servers
34 * This is an experimental Diaspora feature.
36 * @return array of relay servers
38 public static function relay_list() {
40 $serverdata = get_config("system", "relay_server");
41 if ($serverdata == "")
46 $servers = explode(",", $serverdata);
48 foreach($servers AS $server) {
49 $server = trim($server);
50 $addr = "relay@".str_replace("http://", "", normalise_link($server));
51 $batch = $server."/receive/public";
53 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
54 dbesc($batch), dbesc($addr), dbesc(normalise_link($server)));
57 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
58 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
63 dbesc(normalise_link($server)),
65 dbesc(NETWORK_DIASPORA),
66 intval(CONTACT_IS_FOLLOWER),
67 dbesc(datetime_convert()),
68 dbesc(datetime_convert()),
69 dbesc(datetime_convert())
72 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
74 $relay[] = $relais[0];
76 $relay[] = $relais[0];
83 * @brief repairs a signature that was double encoded
85 * The function is unused at the moment. It was copied from the old implementation.
87 * @param string $signature The signature
88 * @param string $handle The handle of the signature owner
89 * @param integer $level This value is only set inside this function to avoid endless loops
91 * @return string the repaired signature
93 private static function repair_signature($signature, $handle = "", $level = 1) {
98 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
99 $signature = base64_decode($signature);
100 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
102 // Do a recursive call to be able to fix even multiple levels
104 $signature = self::repair_signature($signature, $handle, ++$level);
111 * @brief verify the envelope and return the verified data
113 * @param string $envelope The magic envelope
115 * @return string verified data
117 private static function verify_magic_envelope($envelope) {
119 $basedom = parse_xml_string($envelope, false);
121 if (!is_object($basedom)) {
122 logger("Envelope is no XML file");
126 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
128 if (sizeof($children) == 0) {
129 logger("XML has no children");
135 $data = base64url_decode($children->data);
136 $type = $children->data->attributes()->type[0];
138 $encoding = $children->encoding;
140 $alg = $children->alg;
142 $sig = base64url_decode($children->sig);
143 $key_id = $children->sig->attributes()->key_id[0];
145 $handle = base64url_decode($key_id);
147 $b64url_data = base64url_encode($data);
148 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
150 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
152 $key = self::key($handle);
154 $verify = rsa_verify($signable_data, $sig, $key);
156 logger('Message did not verify. Discarding.');
164 * @brief: Decodes incoming Diaspora message
166 * @param array $importer Array of the importer user
167 * @param string $xml urldecoded Diaspora salmon
170 * 'message' -> decoded Diaspora XML message
171 * 'author' -> author diaspora handle
172 * 'key' -> author public key (converted to pkcs#8)
174 public static function decode($importer, $xml) {
177 $basedom = parse_xml_string($xml);
179 if (!is_object($basedom))
182 $children = $basedom->children('https://joindiaspora.com/protocol');
184 if($children->header) {
186 $author_link = str_replace('acct:','',$children->header->author_id);
189 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
191 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
192 $ciphertext = base64_decode($encrypted_header->ciphertext);
194 $outer_key_bundle = '';
195 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
197 $j_outer_key_bundle = json_decode($outer_key_bundle);
199 $outer_iv = base64_decode($j_outer_key_bundle->iv);
200 $outer_key = base64_decode($j_outer_key_bundle->key);
202 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
205 $decrypted = pkcs5_unpad($decrypted);
207 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
208 $idom = parse_xml_string($decrypted,false);
210 $inner_iv = base64_decode($idom->iv);
211 $inner_aes_key = base64_decode($idom->aes_key);
213 $author_link = str_replace('acct:','',$idom->author_id);
216 $dom = $basedom->children(NAMESPACE_SALMON_ME);
218 // figure out where in the DOM tree our data is hiding
220 if($dom->provenance->data)
221 $base = $dom->provenance;
222 elseif($dom->env->data)
228 logger('unable to locate salmon data in xml');
229 http_status_exit(400);
233 // Stash the signature away for now. We have to find their key or it won't be good for anything.
234 $signature = base64url_decode($base->sig);
238 // strip whitespace so our data element will return to one big base64 blob
239 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
242 // stash away some other stuff for later
244 $type = $base->data[0]->attributes()->type[0];
245 $keyhash = $base->sig[0]->attributes()->keyhash[0];
246 $encoding = $base->encoding;
250 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
254 $data = base64url_decode($data);
258 $inner_decrypted = $data;
261 // Decode the encrypted blob
263 $inner_encrypted = base64_decode($data);
264 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
265 $inner_decrypted = pkcs5_unpad($inner_decrypted);
269 logger('Could not retrieve author URI.');
270 http_status_exit(400);
272 // Once we have the author URI, go to the web and try to find their public key
273 // (first this will look it up locally if it is in the fcontact cache)
274 // This will also convert diaspora public key from pkcs#1 to pkcs#8
276 logger('Fetching key for '.$author_link);
277 $key = self::key($author_link);
280 logger('Could not retrieve author key.');
281 http_status_exit(400);
284 $verify = rsa_verify($signed_data,$signature,$key);
287 logger('Message did not verify. Discarding.');
288 http_status_exit(400);
291 logger('Message verified.');
293 return array('message' => (string)$inner_decrypted,
294 'author' => unxmlify($author_link),
295 'key' => (string)$key);
300 * @brief Dispatches public messages and find the fitting receivers
302 * @param array $msg The post that will be dispatched
304 * @return int The message id of the generated message, "true" or "false" if there was an error
306 public static function dispatch_public($msg) {
308 $enabled = intval(get_config("system", "diaspora_enabled"));
310 logger("diaspora is disabled");
314 // Now distribute it to the followers
315 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
316 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
317 AND NOT `account_expired` AND NOT `account_removed`",
318 dbesc(NETWORK_DIASPORA),
319 dbesc($msg["author"])
322 if (dbm::is_result($r)) {
323 foreach ($r as $rr) {
324 logger("delivering to: ".$rr["username"]);
325 self::dispatch($rr,$msg);
328 $social_relay = (bool)Config::get('system', 'relay_subscribe', false);
330 // Use a dummy importer to import the data for the public copy
332 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
333 $message_id = self::dispatch($importer,$msg);
335 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
343 * @brief Dispatches the different message types to the different functions
345 * @param array $importer Array of the importer user
346 * @param array $msg The post that will be dispatched
348 * @return int The message id of the generated message, "true" or "false" if there was an error
350 public static function dispatch($importer, $msg) {
352 // The sender is the handle of the contact that sent the message.
353 // This will often be different with relayed messages (for example "like" and "comment")
354 $sender = $msg["author"];
356 if (!self::valid_posting($msg, $fields)) {
357 logger("Invalid posting");
361 $type = $fields->getName();
363 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
366 case "account_deletion":
367 return self::receive_account_deletion($importer, $fields);
370 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
373 return self::receive_contact_request($importer, $fields);
376 return self::receive_conversation($importer, $msg, $fields);
379 return self::receive_like($importer, $sender, $fields);
382 return self::receive_message($importer, $fields);
384 case "participation": // Not implemented
385 return self::receive_participation($importer, $fields);
387 case "photo": // Not implemented
388 return self::receive_photo($importer, $fields);
390 case "poll_participation": // Not implemented
391 return self::receive_poll_participation($importer, $fields);
394 return self::receive_profile($importer, $fields);
397 return self::receive_reshare($importer, $fields, $msg["message"]);
400 return self::receive_retraction($importer, $sender, $fields);
402 case "status_message":
403 return self::receive_status_message($importer, $fields, $msg["message"]);
406 logger("Unknown message type ".$type);
414 * @brief Checks if a posting is valid and fetches the data fields.
416 * This function does not only check the signature.
417 * It also does the conversion between the old and the new diaspora format.
419 * @param array $msg Array with the XML, the sender handle and the sender signature
420 * @param object $fields SimpleXML object that contains the posting when it is valid
422 * @return bool Is the posting valid?
424 private static function valid_posting($msg, &$fields) {
426 $data = parse_xml_string($msg["message"], false);
428 if (!is_object($data)) {
429 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
433 $first_child = $data->getName();
435 // Is this the new or the old version?
436 if ($data->getName() == "XML") {
438 foreach ($data->post->children() as $child)
445 $type = $element->getName();
448 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
450 // All retractions are handled identically from now on.
451 // In the new version there will only be "retraction".
452 if (in_array($type, array("signed_retraction", "relayable_retraction")))
453 $type = "retraction";
455 if ($type == "request")
458 $fields = new SimpleXMLElement("<".$type."/>");
462 foreach ($element->children() AS $fieldname => $entry) {
464 // Translation for the old XML structure
465 if ($fieldname == "diaspora_handle")
466 $fieldname = "author";
468 if ($fieldname == "participant_handles")
469 $fieldname = "participants";
471 if (in_array($type, array("like", "participation"))) {
472 if ($fieldname == "target_type")
473 $fieldname = "parent_type";
476 if ($fieldname == "sender_handle")
477 $fieldname = "author";
479 if ($fieldname == "recipient_handle")
480 $fieldname = "recipient";
482 if ($fieldname == "root_diaspora_id")
483 $fieldname = "root_author";
485 if ($type == "retraction") {
486 if ($fieldname == "post_guid")
487 $fieldname = "target_guid";
489 if ($fieldname == "type")
490 $fieldname = "target_type";
494 if (($fieldname == "author_signature") AND ($entry != ""))
495 $author_signature = base64_decode($entry);
496 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
497 $parent_author_signature = base64_decode($entry);
498 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
499 if ($signed_data != "") {
501 $signed_data_parent .= ";";
504 $signed_data .= $entry;
506 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
507 ($orig_type == "relayable_retraction"))
508 xml::copy($entry, $fields, $fieldname);
511 // This is something that shouldn't happen at all.
512 if (in_array($type, array("status_message", "reshare", "profile")))
513 if ($msg["author"] != $fields->author) {
514 logger("Message handle is not the same as envelope sender. Quitting this message.");
518 // Only some message types have signatures. So we quit here for the other types.
519 if (!in_array($type, array("comment", "message", "like")))
522 // No author_signature? This is a must, so we quit.
523 if (!isset($author_signature)) {
524 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
528 if (isset($parent_author_signature)) {
529 $key = self::key($msg["author"]);
531 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
532 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);
537 $key = self::key($fields->author);
539 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
540 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
547 * @brief Fetches the public key for a given handle
549 * @param string $handle The handle
551 * @return string The public key
553 private static function key($handle) {
554 $handle = strval($handle);
556 logger("Fetching diaspora key for: ".$handle);
558 $r = self::person_by_handle($handle);
566 * @brief Fetches data for a given handle
568 * @param string $handle The handle
570 * @return array the queried data
572 private static function person_by_handle($handle) {
574 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
575 dbesc(NETWORK_DIASPORA),
580 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
582 // update record occasionally so it doesn't get stale
583 $d = strtotime($person["updated"]." +00:00");
584 if ($d < strtotime("now - 14 days"))
587 if ($person["guid"] == "")
591 if (!$person OR $update) {
592 logger("create or refresh", LOGGER_DEBUG);
593 $r = probe_url($handle, PROBE_DIASPORA);
595 // Note that Friendica contacts will return a "Diaspora person"
596 // if Diaspora connectivity is enabled on their server
597 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
598 self::add_fcontact($r, $update);
606 * @brief Updates the fcontact table
608 * @param array $arr The fcontact data
609 * @param bool $update Update or insert?
611 * @return string The id of the fcontact entry
613 private static function add_fcontact($arr, $update = false) {
616 $r = q("UPDATE `fcontact` SET
630 WHERE `url` = '%s' AND `network` = '%s'",
632 dbesc($arr["photo"]),
633 dbesc($arr["request"]),
635 dbesc(strtolower($arr["addr"])),
637 dbesc($arr["batch"]),
638 dbesc($arr["notify"]),
640 dbesc($arr["confirm"]),
641 dbesc($arr["alias"]),
642 dbesc($arr["pubkey"]),
643 dbesc(datetime_convert()),
645 dbesc($arr["network"])
648 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
649 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
650 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
653 dbesc($arr["photo"]),
654 dbesc($arr["request"]),
658 dbesc($arr["batch"]),
659 dbesc($arr["notify"]),
661 dbesc($arr["confirm"]),
662 dbesc($arr["network"]),
663 dbesc($arr["alias"]),
664 dbesc($arr["pubkey"]),
665 dbesc(datetime_convert())
673 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
675 * @param int $contact_id The id in the contact table
676 * @param int $gcontact_id The id in the gcontact table
678 * @return string the handle
680 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
683 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
685 if ($gcontact_id != 0) {
686 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
687 intval($gcontact_id));
689 if (dbm::is_result($r)) {
690 return strtolower($r[0]["addr"]);
694 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
695 intval($contact_id));
697 if (dbm::is_result($r)) {
700 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
702 if ($contact['addr'] != "") {
703 $handle = $contact['addr'];
705 $baseurl_start = strpos($contact['url'],'://') + 3;
706 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
707 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
708 $handle = $contact['nick'].'@'.$baseurl;
712 return strtolower($handle);
716 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
719 * @param mixed $fcontact_guid Hexadecimal string guid
721 * @return string the contact url or null
723 public static function url_from_contact_guid($fcontact_guid) {
724 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
726 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
727 dbesc(NETWORK_DIASPORA),
728 dbesc($fcontact_guid)
731 if (dbm::is_result($r)) {
739 * @brief Get a contact id for a given handle
741 * @param int $uid The user id
742 * @param string $handle The handle in the format user@domain.tld
744 * @return The contact id
746 private static function contact_by_handle($uid, $handle) {
748 // First do a direct search on the contact table
749 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
754 if (dbm::is_result($r)) {
757 // We haven't found it?
758 // We use another function for it that will possibly create a contact entry
759 $cid = get_contact($handle, $uid);
762 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
764 if (dbm::is_result($r)) {
770 $handle_parts = explode("@", $handle);
771 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
772 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
777 if (dbm::is_result($r)) {
781 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
786 * @brief Check if posting is allowed for this contact
788 * @param array $importer Array of the importer user
789 * @param array $contact The contact that is checked
790 * @param bool $is_comment Is the check for a comment?
792 * @return bool is the contact allowed to post?
794 private static function post_allow($importer, $contact, $is_comment = false) {
796 // perhaps we were already sharing with this person. Now they're sharing with us.
797 // That makes us friends.
798 // Normally this should have handled by getting a request - but this could get lost
799 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
800 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
801 intval(CONTACT_IS_FRIEND),
802 intval($contact["id"]),
803 intval($importer["uid"])
805 $contact["rel"] = CONTACT_IS_FRIEND;
806 logger("defining user ".$contact["nick"]." as friend");
809 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
811 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
813 if($contact["rel"] == CONTACT_IS_FOLLOWER)
814 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
817 // Messages for the global users are always accepted
818 if ($importer["uid"] == 0)
825 * @brief Fetches the contact id for a handle and checks if posting is allowed
827 * @param array $importer Array of the importer user
828 * @param string $handle The checked handle in the format user@domain.tld
829 * @param bool $is_comment Is the check for a comment?
831 * @return array The contact data
833 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
834 $contact = self::contact_by_handle($importer["uid"], $handle);
836 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
840 if (!self::post_allow($importer, $contact, $is_comment)) {
841 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
848 * @brief Does the message already exists on the system?
850 * @param int $uid The user id
851 * @param string $guid The guid of the message
853 * @return int|bool message id if the message already was stored into the system - or false.
855 private static function message_exists($uid, $guid) {
856 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
861 if (dbm::is_result($r)) {
862 logger("message ".$guid." already exists for user ".$uid);
870 * @brief Checks for links to posts in a message
872 * @param array $item The item array
874 private static function fetch_guid($item) {
875 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
876 function ($match) use ($item){
877 return(self::fetch_guid_sub($match, $item));
882 * @brief Checks for relative /people/* links in an item body to match local
883 * contacts or prepends the remote host taken from the author link.
885 * @param string $body The item body to replace links from
886 * @param string $author_link The author link for missing local contact fallback
888 * @return the replaced string
890 public function replace_people_guid($body, $author_link) {
891 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
892 function ($match) use ($author_link) {
894 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
895 // 1 => '0123456789abcdef'
897 $handle = self::url_from_contact_guid($match[1]);
900 $return = '@[url='.$handle.']'.$match[2].'[/url]';
902 // No local match, restoring absolute remote URL from author scheme and host
903 $author_url = parse_url($author_link);
904 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
914 * @brief sub function of "fetch_guid" which checks for links in messages
916 * @param array $match array containing a link that has to be checked for a message link
917 * @param array $item The item array
919 private static function fetch_guid_sub($match, $item) {
920 if (!self::store_by_guid($match[1], $item["author-link"]))
921 self::store_by_guid($match[1], $item["owner-link"]);
925 * @brief Fetches an item with a given guid from a given server
927 * @param string $guid the message guid
928 * @param string $server The server address
929 * @param int $uid The user id of the user
931 * @return int the message id of the stored message or false
933 private static function store_by_guid($guid, $server, $uid = 0) {
934 $serverparts = parse_url($server);
935 $server = $serverparts["scheme"]."://".$serverparts["host"];
937 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
939 $msg = self::message($guid, $server);
944 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
946 // Now call the dispatcher
947 return self::dispatch_public($msg);
951 * @brief Fetches a message from a server
953 * @param string $guid message guid
954 * @param string $server The url of the server
955 * @param int $level Endless loop prevention
958 * 'message' => The message XML
959 * 'author' => The author handle
960 * 'key' => The public key of the author
962 private static function message($guid, $server, $level = 0) {
967 // This will work for new Diaspora servers and Friendica servers from 3.5
968 $source_url = $server."/fetch/post/".$guid;
969 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
971 $envelope = fetch_url($source_url);
973 logger("Envelope was fetched.", LOGGER_DEBUG);
974 $x = self::verify_magic_envelope($envelope);
976 logger("Envelope could not be verified.", LOGGER_DEBUG);
978 logger("Envelope was verified.", LOGGER_DEBUG);
982 // This will work for older Diaspora and Friendica servers
984 $source_url = $server."/p/".$guid.".xml";
985 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
987 $x = fetch_url($source_url);
992 $source_xml = parse_xml_string($x, false);
994 if (!is_object($source_xml))
997 if ($source_xml->post->reshare) {
998 // Reshare of a reshare - old Diaspora version
999 logger("Message is a reshare", LOGGER_DEBUG);
1000 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1001 } elseif ($source_xml->getName() == "reshare") {
1002 // Reshare of a reshare - new Diaspora version
1003 logger("Message is a new reshare", LOGGER_DEBUG);
1004 return self::message($source_xml->root_guid, $server, ++$level);
1009 // Fetch the author - for the old and the new Diaspora version
1010 if ($source_xml->post->status_message->diaspora_handle)
1011 $author = (string)$source_xml->post->status_message->diaspora_handle;
1012 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
1013 $author = (string)$source_xml->author;
1015 // If this isn't a "status_message" then quit
1017 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1021 $msg = array("message" => $x, "author" => $author);
1023 $msg["key"] = self::key($msg["author"]);
1029 * @brief Fetches the item record of a given guid
1031 * @param int $uid The user id
1032 * @param string $guid message guid
1033 * @param string $author The handle of the item
1034 * @param array $contact The contact of the item owner
1036 * @return array the item record
1038 private static function parent_item($uid, $guid, $author, $contact) {
1039 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1040 `author-name`, `author-link`, `author-avatar`,
1041 `owner-name`, `owner-link`, `owner-avatar`
1042 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1043 intval($uid), dbesc($guid));
1046 $result = self::store_by_guid($guid, $contact["url"], $uid);
1049 $person = self::person_by_handle($author);
1050 $result = self::store_by_guid($guid, $person["url"], $uid);
1054 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1056 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1057 `author-name`, `author-link`, `author-avatar`,
1058 `owner-name`, `owner-link`, `owner-avatar`
1059 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1060 intval($uid), dbesc($guid));
1065 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1068 logger("parent item found: parent: ".$guid." - user: ".$uid);
1074 * @brief returns contact details
1076 * @param array $contact The default contact if the person isn't found
1077 * @param array $person The record of the person
1078 * @param int $uid The user id
1081 * 'cid' => contact id
1082 * 'network' => network type
1084 private static function author_contact_by_url($contact, $person, $uid) {
1086 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1087 dbesc(normalise_link($person["url"])), intval($uid));
1090 $network = $r[0]["network"];
1092 // We are receiving content from a user that is about to be terminated
1093 // This means the user is vital, so we remove a possible termination date.
1094 unmark_for_death($contact);
1096 $cid = $contact["id"];
1097 $network = NETWORK_DIASPORA;
1100 return array("cid" => $cid, "network" => $network);
1104 * @brief Is the profile a hubzilla profile?
1106 * @param string $url The profile link
1108 * @return bool is it a hubzilla server?
1110 public static function is_redmatrix($url) {
1111 return(strstr($url, "/channel/"));
1115 * @brief Generate a post link with a given handle and message guid
1117 * @param string $addr The user handle
1118 * @param string $guid message guid
1120 * @return string the post link
1122 private static function plink($addr, $guid) {
1123 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1127 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1129 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1130 // So we try another way as well.
1131 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1133 $r[0]["network"] = $s[0]["network"];
1135 if ($r[0]["network"] == NETWORK_DFRN)
1136 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1138 if (self::is_redmatrix($r[0]["url"]))
1139 return $r[0]["url"]."/?f=&mid=".$guid;
1141 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1145 * @brief Processes an account deletion
1147 * @param array $importer Array of the importer user
1148 * @param object $data The message object
1150 * @return bool Success
1152 private static function receive_account_deletion($importer, $data) {
1154 /// @todo Account deletion should remove the contact from the global contacts as well
1156 $author = notags(unxmlify($data->author));
1158 $contact = self::contact_by_handle($importer["uid"], $author);
1160 logger("cannot find contact for author: ".$author);
1164 // We now remove the contact
1165 contact_remove($contact["id"]);
1170 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1172 * @param string $author Author handle
1173 * @param string $guid Message guid
1174 * @param boolean $onlyfound Only return uri when found in the database
1176 * @return string The constructed uri or the one from our database
1178 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1180 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1181 if (dbm::is_result($r)) {
1182 return $r[0]["uri"];
1183 } elseif (!$onlyfound) {
1184 return $author.":".$guid;
1191 * @brief Fetch the guid from our database with a given uri
1193 * @param string $author Author handle
1194 * @param string $uri Message uri
1196 * @return string The post guid
1198 private static function get_guid_from_uri($uri, $uid) {
1200 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1201 if (dbm::is_result($r)) {
1202 return $r[0]["guid"];
1209 * @brief Processes an incoming comment
1211 * @param array $importer Array of the importer user
1212 * @param string $sender The sender of the message
1213 * @param object $data The message object
1214 * @param string $xml The original XML of the message
1216 * @return int The message id of the generated comment or "false" if there was an error
1218 private static function receive_comment($importer, $sender, $data, $xml) {
1219 $guid = notags(unxmlify($data->guid));
1220 $parent_guid = notags(unxmlify($data->parent_guid));
1221 $text = unxmlify($data->text);
1222 $author = notags(unxmlify($data->author));
1224 if (isset($data->created_at)) {
1225 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1227 $created_at = datetime_convert();
1230 if (isset($data->thread_parent_guid)) {
1231 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1232 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1237 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1242 $message_id = self::message_exists($importer["uid"], $guid);
1247 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1248 if (!$parent_item) {
1252 $person = self::person_by_handle($author);
1253 if (!is_array($person)) {
1254 logger("unable to find author details");
1258 // Fetch the contact id - if we know this contact
1259 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1261 $datarray = array();
1263 $datarray["uid"] = $importer["uid"];
1264 $datarray["contact-id"] = $author_contact["cid"];
1265 $datarray["network"] = $author_contact["network"];
1267 $datarray["author-name"] = $person["name"];
1268 $datarray["author-link"] = $person["url"];
1269 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1271 $datarray["owner-name"] = $contact["name"];
1272 $datarray["owner-link"] = $contact["url"];
1273 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1275 $datarray["guid"] = $guid;
1276 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1278 $datarray["type"] = "remote-comment";
1279 $datarray["verb"] = ACTIVITY_POST;
1280 $datarray["gravity"] = GRAVITY_COMMENT;
1282 if ($thr_uri != "") {
1283 $datarray["parent-uri"] = $thr_uri;
1285 $datarray["parent-uri"] = $parent_item["uri"];
1288 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1289 $datarray["object"] = $xml;
1291 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1293 $body = diaspora2bb($text);
1295 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1297 self::fetch_guid($datarray);
1299 $message_id = item_store($datarray);
1302 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1305 // If we are the origin of the parent we store the original data and notify our followers
1306 if($message_id AND $parent_item["origin"]) {
1308 // Formerly we stored the signed text, the signature and the author in different fields.
1309 // We now store the raw data so that we are more flexible.
1310 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1311 intval($message_id),
1312 dbesc(json_encode($data))
1316 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1323 * @brief processes and stores private messages
1325 * @param array $importer Array of the importer user
1326 * @param array $contact The contact of the message
1327 * @param object $data The message object
1328 * @param array $msg Array of the processed message, author handle and key
1329 * @param object $mesg The private message
1330 * @param array $conversation The conversation record to which this message belongs
1332 * @return bool "true" if it was successful
1334 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1335 $guid = notags(unxmlify($data->guid));
1336 $subject = notags(unxmlify($data->subject));
1337 $author = notags(unxmlify($data->author));
1339 $msg_guid = notags(unxmlify($mesg->guid));
1340 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1341 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1342 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1343 $msg_text = unxmlify($mesg->text);
1344 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1346 // "diaspora_handle" is the element name from the old version
1347 // "author" is the element name from the new version
1348 if ($mesg->author) {
1349 $msg_author = notags(unxmlify($mesg->author));
1350 } elseif ($mesg->diaspora_handle) {
1351 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1356 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1358 if ($msg_conversation_guid != $guid) {
1359 logger("message conversation guid does not belong to the current conversation.");
1363 $body = diaspora2bb($msg_text);
1364 $message_uri = $msg_author.":".$msg_guid;
1366 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1368 $author_signature = base64_decode($msg_author_signature);
1370 if (strcasecmp($msg_author,$msg["author"]) == 0) {
1374 $person = self::person_by_handle($msg_author);
1376 if (is_array($person) && x($person, "pubkey")) {
1377 $key = $person["pubkey"];
1379 logger("unable to find author details");
1384 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1385 logger("verification failed.");
1389 if ($msg_parent_author_signature) {
1390 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1392 $parent_author_signature = base64_decode($msg_parent_author_signature);
1396 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1397 logger("owner verification failed.");
1402 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1405 if (dbm::is_result($r)) {
1406 logger("duplicate message already delivered.", LOGGER_DEBUG);
1410 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1411 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1412 intval($importer["uid"]),
1414 intval($conversation["id"]),
1415 dbesc($person["name"]),
1416 dbesc($person["photo"]),
1417 dbesc($person["url"]),
1418 intval($contact["id"]),
1423 dbesc($message_uri),
1424 dbesc($author.":".$guid),
1425 dbesc($msg_created_at)
1428 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1429 dbesc(datetime_convert()),
1430 intval($conversation["id"])
1434 "type" => NOTIFY_MAIL,
1435 "notify_flags" => $importer["notify-flags"],
1436 "language" => $importer["language"],
1437 "to_name" => $importer["username"],
1438 "to_email" => $importer["email"],
1439 "uid" =>$importer["uid"],
1440 "item" => array("subject" => $subject, "body" => $body),
1441 "source_name" => $person["name"],
1442 "source_link" => $person["url"],
1443 "source_photo" => $person["thumb"],
1444 "verb" => ACTIVITY_POST,
1451 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1453 * @param array $importer Array of the importer user
1454 * @param array $msg Array of the processed message, author handle and key
1455 * @param object $data The message object
1457 * @return bool Success
1459 private static function receive_conversation($importer, $msg, $data) {
1460 $guid = notags(unxmlify($data->guid));
1461 $subject = notags(unxmlify($data->subject));
1462 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1463 $author = notags(unxmlify($data->author));
1464 $participants = notags(unxmlify($data->participants));
1466 $messages = $data->message;
1468 if (!count($messages)) {
1469 logger("empty conversation");
1473 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1477 $conversation = null;
1479 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1480 intval($importer["uid"]),
1484 $conversation = $c[0];
1486 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1487 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1488 intval($importer["uid"]),
1492 dbesc(datetime_convert()),
1494 dbesc($participants)
1497 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1498 intval($importer["uid"]),
1503 $conversation = $c[0];
1505 if (!$conversation) {
1506 logger("unable to create conversation.");
1510 foreach($messages as $mesg)
1511 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1517 * @brief Creates the body for a "like" message
1519 * @param array $contact The contact that send us the "like"
1520 * @param array $parent_item The item array of the parent item
1521 * @param string $guid message guid
1523 * @return string the body
1525 private static function construct_like_body($contact, $parent_item, $guid) {
1526 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1528 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1529 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1530 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1532 return sprintf($bodyverb, $ulink, $alink, $plink);
1536 * @brief Creates a XML object for a "like"
1538 * @param array $importer Array of the importer user
1539 * @param array $parent_item The item array of the parent item
1541 * @return string The XML
1543 private static function construct_like_object($importer, $parent_item) {
1544 $objtype = ACTIVITY_OBJ_NOTE;
1545 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1546 $parent_body = $parent_item["body"];
1548 $xmldata = array("object" => array("type" => $objtype,
1550 "id" => $parent_item["uri"],
1553 "content" => $parent_body));
1555 return xml::from_array($xmldata, $xml, true);
1559 * @brief Processes "like" messages
1561 * @param array $importer Array of the importer user
1562 * @param string $sender The sender of the message
1563 * @param object $data The message object
1565 * @return int The message id of the generated like or "false" if there was an error
1567 private static function receive_like($importer, $sender, $data) {
1568 $positive = notags(unxmlify($data->positive));
1569 $guid = notags(unxmlify($data->guid));
1570 $parent_type = notags(unxmlify($data->parent_type));
1571 $parent_guid = notags(unxmlify($data->parent_guid));
1572 $author = notags(unxmlify($data->author));
1574 // likes on comments aren't supported by Diaspora - only on posts
1575 // But maybe this will be supported in the future, so we will accept it.
1576 if (!in_array($parent_type, array("Post", "Comment")))
1579 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1583 $message_id = self::message_exists($importer["uid"], $guid);
1587 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1591 $person = self::person_by_handle($author);
1592 if (!is_array($person)) {
1593 logger("unable to find author details");
1597 // Fetch the contact id - if we know this contact
1598 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1600 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1601 // We would accept this anyhow.
1602 if ($positive == "true")
1603 $verb = ACTIVITY_LIKE;
1605 $verb = ACTIVITY_DISLIKE;
1607 $datarray = array();
1609 $datarray["uid"] = $importer["uid"];
1610 $datarray["contact-id"] = $author_contact["cid"];
1611 $datarray["network"] = $author_contact["network"];
1613 $datarray["author-name"] = $person["name"];
1614 $datarray["author-link"] = $person["url"];
1615 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1617 $datarray["owner-name"] = $contact["name"];
1618 $datarray["owner-link"] = $contact["url"];
1619 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1621 $datarray["guid"] = $guid;
1622 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1624 $datarray["type"] = "activity";
1625 $datarray["verb"] = $verb;
1626 $datarray["gravity"] = GRAVITY_LIKE;
1627 $datarray["parent-uri"] = $parent_item["uri"];
1629 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1630 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1632 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1634 $message_id = item_store($datarray);
1637 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1639 // If we are the origin of the parent we store the original data and notify our followers
1640 if($message_id AND $parent_item["origin"]) {
1642 // Formerly we stored the signed text, the signature and the author in different fields.
1643 // We now store the raw data so that we are more flexible.
1644 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1645 intval($message_id),
1646 dbesc(json_encode($data))
1650 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1657 * @brief Processes private messages
1659 * @param array $importer Array of the importer user
1660 * @param object $data The message object
1662 * @return bool Success?
1664 private static function receive_message($importer, $data) {
1665 $guid = notags(unxmlify($data->guid));
1666 $parent_guid = notags(unxmlify($data->parent_guid));
1667 $text = unxmlify($data->text);
1668 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1669 $author = notags(unxmlify($data->author));
1670 $conversation_guid = notags(unxmlify($data->conversation_guid));
1672 $contact = self::allowed_contact_by_handle($importer, $author, true);
1677 $conversation = null;
1679 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1680 intval($importer["uid"]),
1681 dbesc($conversation_guid)
1684 $conversation = $c[0];
1686 logger("conversation not available.");
1690 $message_uri = $author.":".$guid;
1692 $person = self::person_by_handle($author);
1694 logger("unable to find author details");
1698 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1699 dbesc($message_uri),
1700 intval($importer["uid"])
1702 if (dbm::is_result($r)) {
1703 logger("duplicate message already delivered.", LOGGER_DEBUG);
1707 $body = diaspora2bb($text);
1709 $body = self::replace_people_guid($body, $person["url"]);
1711 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1712 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1713 intval($importer["uid"]),
1715 intval($conversation["id"]),
1716 dbesc($person["name"]),
1717 dbesc($person["photo"]),
1718 dbesc($person["url"]),
1719 intval($contact["id"]),
1720 dbesc($conversation["subject"]),
1724 dbesc($message_uri),
1725 dbesc($author.":".$parent_guid),
1729 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1730 dbesc(datetime_convert()),
1731 intval($conversation["id"])
1738 * @brief Processes participations - unsupported by now
1740 * @param array $importer Array of the importer user
1741 * @param object $data The message object
1743 * @return bool always true
1745 private static function receive_participation($importer, $data) {
1746 // I'm not sure if we can fully support this message type
1751 * @brief Processes photos - unneeded
1753 * @param array $importer Array of the importer user
1754 * @param object $data The message object
1756 * @return bool always true
1758 private static function receive_photo($importer, $data) {
1759 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1764 * @brief Processes poll participations - unssupported
1766 * @param array $importer Array of the importer user
1767 * @param object $data The message object
1769 * @return bool always true
1771 private static function receive_poll_participation($importer, $data) {
1772 // We don't support polls by now
1777 * @brief Processes incoming profile updates
1779 * @param array $importer Array of the importer user
1780 * @param object $data The message object
1782 * @return bool Success
1784 private static function receive_profile($importer, $data) {
1785 $author = strtolower(notags(unxmlify($data->author)));
1787 $contact = self::contact_by_handle($importer["uid"], $author);
1791 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1792 $image_url = unxmlify($data->image_url);
1793 $birthday = unxmlify($data->birthday);
1794 $location = diaspora2bb(unxmlify($data->location));
1795 $about = diaspora2bb(unxmlify($data->bio));
1796 $gender = unxmlify($data->gender);
1797 $searchable = (unxmlify($data->searchable) == "true");
1798 $nsfw = (unxmlify($data->nsfw) == "true");
1799 $tags = unxmlify($data->tag_string);
1801 $tags = explode("#", $tags);
1803 $keywords = array();
1804 foreach ($tags as $tag) {
1805 $tag = trim(strtolower($tag));
1810 $keywords = implode(", ", $keywords);
1812 $handle_parts = explode("@", $author);
1813 $nick = $handle_parts[0];
1816 $name = $handle_parts[0];
1818 if( preg_match("|^https?://|", $image_url) === 0)
1819 $image_url = "http://".$handle_parts[1].$image_url;
1821 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1823 // Generic birthday. We don't know the timezone. The year is irrelevant.
1825 $birthday = str_replace("1000", "1901", $birthday);
1827 if ($birthday != "")
1828 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1830 // this is to prevent multiple birthday notifications in a single year
1831 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1833 if(substr($birthday,5) === substr($contact["bd"],5))
1834 $birthday = $contact["bd"];
1836 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1837 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1841 dbesc(datetime_convert()),
1847 intval($contact["id"]),
1848 intval($importer["uid"])
1851 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1852 "photo" => $image_url, "name" => $name, "location" => $location,
1853 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1854 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1855 "hide" => !$searchable, "nsfw" => $nsfw);
1857 $gcid = update_gcontact($gcontact);
1859 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1861 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1867 * @brief Processes incoming friend requests
1869 * @param array $importer Array of the importer user
1870 * @param array $contact The contact that send the request
1872 private static function receive_request_make_friend($importer, $contact) {
1876 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1877 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1878 intval(CONTACT_IS_FRIEND),
1879 intval($contact["id"]),
1880 intval($importer["uid"])
1883 // send notification
1885 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1886 intval($importer["uid"])
1889 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1891 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1892 intval($importer["uid"])
1895 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1897 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1900 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1901 $arr["uid"] = $importer["uid"];
1902 $arr["contact-id"] = $self[0]["id"];
1904 $arr["type"] = 'wall';
1905 $arr["gravity"] = 0;
1907 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1908 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1909 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1910 $arr["verb"] = ACTIVITY_FRIEND;
1911 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1913 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1914 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1915 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1916 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1918 $arr["object"] = self::construct_new_friend_object($contact);
1920 $arr["last-child"] = 1;
1922 $arr["allow_cid"] = $user[0]["allow_cid"];
1923 $arr["allow_gid"] = $user[0]["allow_gid"];
1924 $arr["deny_cid"] = $user[0]["deny_cid"];
1925 $arr["deny_gid"] = $user[0]["deny_gid"];
1927 $i = item_store($arr);
1929 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
1935 * @brief Creates a XML object for a "new friend" message
1937 * @param array $contact Array of the contact
1939 * @return string The XML
1941 private static function construct_new_friend_object($contact) {
1942 $objtype = ACTIVITY_OBJ_PERSON;
1943 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1944 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1946 $xmldata = array("object" => array("type" => $objtype,
1947 "title" => $contact["name"],
1948 "id" => $contact["url"]."/".$contact["name"],
1951 return xml::from_array($xmldata, $xml, true);
1955 * @brief Processes incoming sharing notification
1957 * @param array $importer Array of the importer user
1958 * @param object $data The message object
1960 * @return bool Success
1962 private static function receive_contact_request($importer, $data) {
1963 $author = unxmlify($data->author);
1964 $recipient = unxmlify($data->recipient);
1966 if (!$author || !$recipient) {
1970 // the current protocol version doesn't know these fields
1971 // That means that we will assume their existance
1972 if (isset($data->following)) {
1973 $following = (unxmlify($data->following) == "true");
1978 if (isset($data->sharing)) {
1979 $sharing = (unxmlify($data->sharing) == "true");
1984 $contact = self::contact_by_handle($importer["uid"],$author);
1986 // perhaps we were already sharing with this person. Now they're sharing with us.
1987 // That makes us friends.
1989 if ($following AND $sharing) {
1990 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
1991 self::receive_request_make_friend($importer, $contact);
1993 // refetch the contact array
1994 $contact = self::contact_by_handle($importer["uid"],$author);
1996 // If we are now friends, we are sending a share message.
1997 // Normally we needn't to do so, but the first message could have been vanished.
1998 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
1999 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2001 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2002 $ret = self::send_share($u[0], $contact);
2006 } else { /// @todo Handle all possible variations of adding and retracting of permissions
2007 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
2012 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2013 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2015 } elseif (!$following AND !$sharing) {
2016 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2018 } elseif (!$following AND $sharing) {
2019 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2020 } elseif ($following AND $sharing) {
2021 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2022 } elseif ($following AND !$sharing) {
2023 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2026 $ret = self::person_by_handle($author);
2028 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2029 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2033 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2035 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2036 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2037 intval($importer["uid"]),
2038 dbesc($ret["network"]),
2039 dbesc($ret["addr"]),
2042 dbesc(normalise_link($ret["url"])),
2044 dbesc($ret["name"]),
2045 dbesc($ret["nick"]),
2046 dbesc($ret["photo"]),
2047 dbesc($ret["pubkey"]),
2048 dbesc($ret["notify"]),
2049 dbesc($ret["poll"]),
2054 // find the contact record we just created
2056 $contact_record = self::contact_by_handle($importer["uid"],$author);
2058 if (!$contact_record) {
2059 logger("unable to locate newly created contact record.");
2063 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2065 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2067 if(intval($def_gid))
2068 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2070 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2072 if($importer["page-flags"] == PAGE_NORMAL) {
2074 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2076 $hash = random_string().(string)time(); // Generate a confirm_key
2078 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2079 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2080 intval($importer["uid"]),
2081 intval($contact_record["id"]),
2084 dbesc(t("Sharing notification from Diaspora network")),
2086 dbesc(datetime_convert())
2090 // automatic friend approval
2092 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2094 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2096 // technically they are sharing with us (CONTACT_IS_SHARING),
2097 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2098 // we are going to change the relationship and make them a follower.
2100 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2101 $new_relation = CONTACT_IS_FRIEND;
2102 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2103 $new_relation = CONTACT_IS_SHARING;
2105 $new_relation = CONTACT_IS_FOLLOWER;
2107 $r = q("UPDATE `contact` SET `rel` = %d,
2115 intval($new_relation),
2116 dbesc(datetime_convert()),
2117 dbesc(datetime_convert()),
2118 intval($contact_record["id"])
2121 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2123 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2124 $ret = self::send_share($u[0], $contact_record);
2126 // Send the profile data, maybe it weren't transmitted before
2127 self::send_profile($importer["uid"], array($contact_record));
2135 * @brief Fetches a message with a given guid
2137 * @param string $guid message guid
2138 * @param string $orig_author handle of the original post
2139 * @param string $author handle of the sharer
2141 * @return array The fetched item
2143 private static function original_item($guid, $orig_author, $author) {
2145 // Do we already have this item?
2146 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2147 `author-name`, `author-link`, `author-avatar`
2148 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2151 if (dbm::is_result($r)) {
2152 logger("reshared message ".$guid." already exists on system.");
2154 // Maybe it is already a reshared item?
2155 // Then refetch the content, if it is a reshare from a reshare.
2156 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2157 if (self::is_reshare($r[0]["body"], true)) {
2159 } elseif (self::is_reshare($r[0]["body"], false)) {
2160 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2162 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2164 // Add OEmbed and other information to the body
2165 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2173 if (!dbm::is_result($r)) {
2174 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2175 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2176 $item_id = self::store_by_guid($guid, $server);
2179 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2180 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2181 $item_id = self::store_by_guid($guid, $server);
2185 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2186 `author-name`, `author-link`, `author-avatar`
2187 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2190 if (dbm::is_result($r)) {
2191 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2192 if (self::is_reshare($r[0]["body"], false)) {
2193 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2194 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2206 * @brief Processes a reshare message
2208 * @param array $importer Array of the importer user
2209 * @param object $data The message object
2210 * @param string $xml The original XML of the message
2212 * @return int the message id
2214 private static function receive_reshare($importer, $data, $xml) {
2215 $root_author = notags(unxmlify($data->root_author));
2216 $root_guid = notags(unxmlify($data->root_guid));
2217 $guid = notags(unxmlify($data->guid));
2218 $author = notags(unxmlify($data->author));
2219 $public = notags(unxmlify($data->public));
2220 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2222 $contact = self::allowed_contact_by_handle($importer, $author, false);
2227 $message_id = self::message_exists($importer["uid"], $guid);
2232 $original_item = self::original_item($root_guid, $root_author, $author);
2233 if (!$original_item) {
2237 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2239 $datarray = array();
2241 $datarray["uid"] = $importer["uid"];
2242 $datarray["contact-id"] = $contact["id"];
2243 $datarray["network"] = NETWORK_DIASPORA;
2245 $datarray["author-name"] = $contact["name"];
2246 $datarray["author-link"] = $contact["url"];
2247 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2249 $datarray["owner-name"] = $datarray["author-name"];
2250 $datarray["owner-link"] = $datarray["author-link"];
2251 $datarray["owner-avatar"] = $datarray["author-avatar"];
2253 $datarray["guid"] = $guid;
2254 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2256 $datarray["verb"] = ACTIVITY_POST;
2257 $datarray["gravity"] = GRAVITY_PARENT;
2259 $datarray["object"] = $xml;
2261 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2262 $original_item["guid"], $original_item["created"], $orig_url);
2263 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2265 $datarray["tag"] = $original_item["tag"];
2266 $datarray["app"] = $original_item["app"];
2268 $datarray["plink"] = self::plink($author, $guid);
2269 $datarray["private"] = (($public == "false") ? 1 : 0);
2270 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2272 $datarray["object-type"] = $original_item["object-type"];
2274 self::fetch_guid($datarray);
2275 $message_id = item_store($datarray);
2278 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2285 * @brief Processes retractions
2287 * @param array $importer Array of the importer user
2288 * @param array $contact The contact of the item owner
2289 * @param object $data The message object
2291 * @return bool success
2293 private static function item_retraction($importer, $contact, $data) {
2294 $target_type = notags(unxmlify($data->target_type));
2295 $target_guid = notags(unxmlify($data->target_guid));
2296 $author = notags(unxmlify($data->author));
2298 $person = self::person_by_handle($author);
2299 if (!is_array($person)) {
2300 logger("unable to find author detail for ".$author);
2304 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2305 dbesc($target_guid),
2306 intval($importer["uid"])
2312 // Check if the sender is the thread owner
2313 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2314 intval($r[0]["parent"]));
2316 // Only delete it if the parent author really fits
2317 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2318 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2322 // 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
2323 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2324 dbesc(datetime_convert()),
2325 dbesc(datetime_convert()),
2328 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2330 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2332 // Now check if the retraction needs to be relayed by us
2333 if ($p[0]["origin"]) {
2335 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2342 * @brief Receives retraction messages
2344 * @param array $importer Array of the importer user
2345 * @param string $sender The sender of the message
2346 * @param object $data The message object
2348 * @return bool Success
2350 private static function receive_retraction($importer, $sender, $data) {
2351 $target_type = notags(unxmlify($data->target_type));
2353 $contact = self::contact_by_handle($importer["uid"], $sender);
2355 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2359 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2361 switch ($target_type) {
2364 case "Post": // "Post" will be supported in a future version
2366 case "StatusMessage":
2367 return self::item_retraction($importer, $contact, $data);;
2371 /// @todo What should we do with an "unshare"?
2372 // Removing the contact isn't correct since we still can read the public items
2373 contact_remove($contact["id"]);
2377 logger("Unknown target type ".$target_type);
2384 * @brief Receives status messages
2386 * @param array $importer Array of the importer user
2387 * @param object $data The message object
2388 * @param string $xml The original XML of the message
2390 * @return int The message id of the newly created item
2392 private static function receive_status_message($importer, $data, $xml) {
2393 $raw_message = unxmlify($data->raw_message);
2394 $guid = notags(unxmlify($data->guid));
2395 $author = notags(unxmlify($data->author));
2396 $public = notags(unxmlify($data->public));
2397 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2398 $provider_display_name = notags(unxmlify($data->provider_display_name));
2400 /// @todo enable support for polls
2401 //if ($data->poll) {
2402 // foreach ($data->poll AS $poll)
2406 $contact = self::allowed_contact_by_handle($importer, $author, false);
2411 $message_id = self::message_exists($importer["uid"], $guid);
2417 if ($data->location) {
2418 foreach ($data->location->children() AS $fieldname => $data) {
2419 $address[$fieldname] = notags(unxmlify($data));
2423 $body = diaspora2bb($raw_message);
2425 $datarray = array();
2427 // Attach embedded pictures to the body
2429 foreach ($data->photo AS $photo) {
2430 $body = "[img]".unxmlify($photo->remote_photo_path).
2431 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2434 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2436 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2438 // Add OEmbed and other information to the body
2439 if (!self::is_redmatrix($contact["url"])) {
2440 $body = add_page_info_to_body($body, false, true);
2444 $datarray["uid"] = $importer["uid"];
2445 $datarray["contact-id"] = $contact["id"];
2446 $datarray["network"] = NETWORK_DIASPORA;
2448 $datarray["author-name"] = $contact["name"];
2449 $datarray["author-link"] = $contact["url"];
2450 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2452 $datarray["owner-name"] = $datarray["author-name"];
2453 $datarray["owner-link"] = $datarray["author-link"];
2454 $datarray["owner-avatar"] = $datarray["author-avatar"];
2456 $datarray["guid"] = $guid;
2457 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2459 $datarray["verb"] = ACTIVITY_POST;
2460 $datarray["gravity"] = GRAVITY_PARENT;
2462 $datarray["object"] = $xml;
2464 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2466 if ($provider_display_name != "") {
2467 $datarray["app"] = $provider_display_name;
2470 $datarray["plink"] = self::plink($author, $guid);
2471 $datarray["private"] = (($public == "false") ? 1 : 0);
2472 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2474 if (isset($address["address"])) {
2475 $datarray["location"] = $address["address"];
2478 if (isset($address["lat"]) AND isset($address["lng"])) {
2479 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2482 self::fetch_guid($datarray);
2483 $message_id = item_store($datarray);
2486 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2492 /* ************************************************************************************** *
2493 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2494 * ************************************************************************************** */
2497 * @brief returnes the handle of a contact
2499 * @param array $me contact array
2501 * @return string the handle in the format user@domain.tld
2503 private static function my_handle($contact) {
2504 if ($contact["addr"] != "") {
2505 return $contact["addr"];
2508 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2509 // So - just in case - we build the the address here.
2510 if ($contact["nickname"] != "") {
2511 $nick = $contact["nickname"];
2513 $nick = $contact["nick"];
2516 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2520 * @brief Creates the envelope for the "fetch" endpoint
2522 * @param string $msg The message that is to be transmitted
2523 * @param array $user The record of the sender
2525 * @return string The envelope
2528 public static function build_magic_envelope($msg, $user) {
2530 $b64url_data = base64url_encode($msg);
2531 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2533 $key_id = base64url_encode(self::my_handle($user));
2534 $type = "application/xml";
2535 $encoding = "base64url";
2536 $alg = "RSA-SHA256";
2537 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2538 $signature = rsa_sign($signable_data, $user["prvkey"]);
2539 $sig = base64url_encode($signature);
2541 $xmldata = array("me:env" => array("me:data" => $data,
2542 "@attributes" => array("type" => $type),
2543 "me:encoding" => $encoding,
2546 "@attributes2" => array("key_id" => $key_id)));
2548 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2550 return xml::from_array($xmldata, $xml, false, $namespaces);
2554 * @brief Creates the envelope for a public message
2556 * @param string $msg The message that is to be transmitted
2557 * @param array $user The record of the sender
2558 * @param array $contact Target of the communication
2559 * @param string $prvkey The private key of the sender
2560 * @param string $pubkey The public key of the receiver
2562 * @return string The envelope
2564 private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2566 logger("Message: ".$msg, LOGGER_DATA);
2568 $handle = self::my_handle($user);
2570 $b64url_data = base64url_encode($msg);
2572 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2574 $type = "application/xml";
2575 $encoding = "base64url";
2576 $alg = "RSA-SHA256";
2578 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2580 $signature = rsa_sign($signable_data,$prvkey);
2581 $sig = base64url_encode($signature);
2583 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2584 "me:env" => array("me:encoding" => $encoding,
2587 "@attributes" => array("type" => $type),
2588 "me:sig" => $sig)));
2590 $namespaces = array("" => "https://joindiaspora.com/protocol",
2591 "me" => "http://salmon-protocol.org/ns/magic-env");
2593 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2595 logger("magic_env: ".$magic_env, LOGGER_DATA);
2600 * @brief Creates the envelope for a private message
2602 * @param string $msg The message that is to be transmitted
2603 * @param array $user The record of the sender
2604 * @param array $contact Target of the communication
2605 * @param string $prvkey The private key of the sender
2606 * @param string $pubkey The public key of the receiver
2608 * @return string The envelope
2610 private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2612 logger("Message: ".$msg, LOGGER_DATA);
2614 // without a public key nothing will work
2617 logger("pubkey missing: contact id: ".$contact["id"]);
2621 $inner_aes_key = random_string(32);
2622 $b_inner_aes_key = base64_encode($inner_aes_key);
2623 $inner_iv = random_string(16);
2624 $b_inner_iv = base64_encode($inner_iv);
2626 $outer_aes_key = random_string(32);
2627 $b_outer_aes_key = base64_encode($outer_aes_key);
2628 $outer_iv = random_string(16);
2629 $b_outer_iv = base64_encode($outer_iv);
2631 $handle = self::my_handle($user);
2633 $padded_data = pkcs5_pad($msg,16);
2634 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2636 $b64_data = base64_encode($inner_encrypted);
2639 $b64url_data = base64url_encode($b64_data);
2640 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2642 $type = "application/xml";
2643 $encoding = "base64url";
2644 $alg = "RSA-SHA256";
2646 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2648 $signature = rsa_sign($signable_data,$prvkey);
2649 $sig = base64url_encode($signature);
2651 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2652 "aes_key" => $b_inner_aes_key,
2653 "author_id" => $handle));
2655 $decrypted_header = xml::from_array($xmldata, $xml, true);
2656 $decrypted_header = pkcs5_pad($decrypted_header,16);
2658 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2660 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2662 $encrypted_outer_key_bundle = "";
2663 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2665 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2667 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2669 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2670 "ciphertext" => base64_encode($ciphertext)));
2671 $cipher_json = base64_encode($encrypted_header_json_object);
2673 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2674 "me:env" => array("me:encoding" => $encoding,
2677 "@attributes" => array("type" => $type),
2678 "me:sig" => $sig)));
2680 $namespaces = array("" => "https://joindiaspora.com/protocol",
2681 "me" => "http://salmon-protocol.org/ns/magic-env");
2683 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2685 logger("magic_env: ".$magic_env, LOGGER_DATA);
2690 * @brief Create the envelope for a message
2692 * @param string $msg The message that is to be transmitted
2693 * @param array $user The record of the sender
2694 * @param array $contact Target of the communication
2695 * @param string $prvkey The private key of the sender
2696 * @param string $pubkey The public key of the receiver
2697 * @param bool $public Is the message public?
2699 * @return string The message that will be transmitted to other servers
2701 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2704 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2706 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2708 // The data that will be transmitted is double encoded via "urlencode", strange ...
2709 $slap = "xml=".urlencode(urlencode($magic_env));
2714 * @brief Creates a signature for a message
2716 * @param array $owner the array of the owner of the message
2717 * @param array $message The message that is to be signed
2719 * @return string The signature
2721 private static function signature($owner, $message) {
2723 unset($sigmsg["author_signature"]);
2724 unset($sigmsg["parent_author_signature"]);
2726 $signed_text = implode(";", $sigmsg);
2728 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2732 * @brief Transmit a message to a target server
2734 * @param array $owner the array of the item owner
2735 * @param array $contact Target of the communication
2736 * @param string $slap The message that is to be transmitted
2737 * @param bool $public_batch Is it a public post?
2738 * @param bool $queue_run Is the transmission called from the queue?
2739 * @param string $guid message guid
2741 * @return int Result of the transmission
2743 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2747 $enabled = intval(get_config("system", "diaspora_enabled"));
2751 $logid = random_string(4);
2752 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2754 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2758 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2760 if (!$queue_run && was_recently_delayed($contact["id"])) {
2763 if (!intval(get_config("system", "diaspora_test"))) {
2764 post_url($dest_url."/", $slap);
2765 $return_code = $a->get_curl_code();
2767 logger("test_mode");
2772 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2774 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2775 logger("queue message");
2777 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2778 intval($contact["id"]),
2779 dbesc(NETWORK_DIASPORA),
2781 intval($public_batch)
2784 logger("add_to_queue ignored - identical item already in queue");
2786 // queue message for redelivery
2787 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2789 // The message could not be delivered. We mark the contact as "dead"
2790 mark_for_death($contact);
2792 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2793 // We successfully delivered a message, the contact is alive
2794 unmark_for_death($contact);
2797 return(($return_code) ? $return_code : (-1));
2802 * @brief Build the post xml
2804 * @param string $type The message type
2805 * @param array $message The message data
2807 * @return string The post XML
2809 public static function build_post_xml($type, $message) {
2811 $data = array("XML" => array("post" => array($type => $message)));
2812 return xml::from_array($data, $xml);
2816 * @brief Builds and transmit messages
2818 * @param array $owner the array of the item owner
2819 * @param array $contact Target of the communication
2820 * @param string $type The message type
2821 * @param array $message The message data
2822 * @param bool $public_batch Is it a public post?
2823 * @param string $guid message guid
2824 * @param bool $spool Should the transmission be spooled or transmitted?
2826 * @return int Result of the transmission
2828 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2830 $msg = self::build_post_xml($type, $message);
2832 logger('message: '.$msg, LOGGER_DATA);
2833 logger('send guid '.$guid, LOGGER_DEBUG);
2835 // Fallback if the private key wasn't transmitted in the expected field
2836 if ($owner['uprvkey'] == "")
2837 $owner['uprvkey'] = $owner['prvkey'];
2839 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2842 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2845 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2847 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2849 return $return_code;
2853 * @brief Sends a "share" message
2855 * @param array $owner the array of the item owner
2856 * @param array $contact Target of the communication
2858 * @return int The result of the transmission
2860 public static function send_share($owner,$contact) {
2862 $message = array("sender_handle" => self::my_handle($owner),
2863 "recipient_handle" => $contact["addr"]);
2865 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2867 return self::build_and_transmit($owner, $contact, "request", $message);
2871 * @brief sends an "unshare"
2873 * @param array $owner the array of the item owner
2874 * @param array $contact Target of the communication
2876 * @return int The result of the transmission
2878 public static function send_unshare($owner,$contact) {
2880 $message = array("post_guid" => $owner["guid"],
2881 "diaspora_handle" => self::my_handle($owner),
2882 "type" => "Person");
2884 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2886 return self::build_and_transmit($owner, $contact, "retraction", $message);
2890 * @brief Checks a message body if it is a reshare
2892 * @param string $body The message body that is to be check
2893 * @param bool $complete Should it be a complete check or a simple check?
2895 * @return array|bool Reshare details or "false" if no reshare
2897 public static function is_reshare($body, $complete = true) {
2898 $body = trim($body);
2900 // Skip if it isn't a pure repeated messages
2901 // Does it start with a share?
2902 if ((strpos($body, "[share") > 0) AND $complete)
2905 // Does it end with a share?
2906 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2909 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2910 // Skip if there is no shared message in there
2911 if ($body == $attributes)
2914 // If we don't do the complete check we quit here
2919 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2920 if ($matches[1] != "")
2921 $guid = $matches[1];
2923 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2924 if ($matches[1] != "")
2925 $guid = $matches[1];
2928 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2929 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2932 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2933 $ret["root_guid"] = $guid;
2939 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2940 if ($matches[1] != "")
2941 $profile = $matches[1];
2943 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2944 if ($matches[1] != "")
2945 $profile = $matches[1];
2949 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2950 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2954 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2955 if ($matches[1] != "")
2956 $link = $matches[1];
2958 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2959 if ($matches[1] != "")
2960 $link = $matches[1];
2962 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2963 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2970 * @brief Create an event array
2972 * @param integer $event_id The id of the event
2974 * @return array with event data
2976 private static function build_event($event_id) {
2978 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
2979 if (!dbm::is_result($r)) {
2985 $eventdata = array();
2987 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
2988 if (!dbm::is_result($r)) {
2994 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
2995 if (!dbm::is_result($r)) {
3001 $eventdata['author'] = self::my_handle($owner);
3003 if ($event['guid']) {
3004 $eventdata['guid'] = $event['guid'];
3007 $mask = 'Y-m-d\TH:i:s\Z';
3009 /// @todo - establish "all day" events in Friendica
3010 $eventdata["all_day"] = "false";
3012 if (!$event['adjust']) {
3013 $eventdata['timezone'] = $user['timezone'];
3015 if ($eventdata['timezone'] == "") {
3016 $eventdata['timezone'] = 'UTC';
3020 if ($event['start']) {
3021 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3023 if ($event['finish'] AND !$event['nofinish']) {
3024 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3026 if ($event['summary']) {
3027 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3029 if ($event['desc']) {
3030 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3032 if ($event['location']) {
3033 $location = array();
3034 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3035 $location["lat"] = 0;
3036 $location["lng"] = 0;
3037 $eventdata['location'] = $location;
3044 * @brief Create a post (status message or reshare)
3046 * @param array $item The item that will be exported
3047 * @param array $owner the array of the item owner
3050 * 'type' -> Message type ("status_message" or "reshare")
3051 * 'message' -> Array of XML elements of the status
3053 public static function build_status($item, $owner) {
3055 $cachekey = "diaspora:build_status:".$item['guid'];
3057 $result = Cache::get($cachekey);
3058 if (!is_null($result)) {
3062 $myaddr = self::my_handle($owner);
3064 $public = (($item["private"]) ? "false" : "true");
3066 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3068 // Detect a share element and do a reshare
3069 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3070 $message = array("root_diaspora_id" => $ret["root_handle"],
3071 "root_guid" => $ret["root_guid"],
3072 "guid" => $item["guid"],
3073 "diaspora_handle" => $myaddr,
3074 "public" => $public,
3075 "created_at" => $created,
3076 "provider_display_name" => $item["app"]);
3080 $title = $item["title"];
3081 $body = $item["body"];
3083 // convert to markdown
3084 $body = html_entity_decode(bb2diaspora($body));
3088 $body = "## ".html_entity_decode($title)."\n\n".$body;
3090 if ($item["attach"]) {
3091 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3093 $body .= "\n".t("Attachments:")."\n";
3094 foreach($matches as $mtch)
3095 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3099 $location = array();
3101 if ($item["location"] != "")
3102 $location["address"] = $item["location"];
3104 if ($item["coord"] != "") {
3105 $coord = explode(" ", $item["coord"]);
3106 $location["lat"] = $coord[0];
3107 $location["lng"] = $coord[1];
3110 $message = array("raw_message" => $body,
3111 "location" => $location,
3112 "guid" => $item["guid"],
3113 "diaspora_handle" => $myaddr,
3114 "public" => $public,
3115 "created_at" => $created,
3116 "provider_display_name" => $item["app"]);
3118 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3119 if (!isset($location["lat"]) OR !isset($location["lng"])) {
3120 unset($message["location"]);
3123 if ($item['event-id'] > 0) {
3124 $event = self::build_event($item['event-id']);
3125 if (count($event)) {
3126 $message['event'] = $event;
3128 /// @todo Once Diaspora supports it, we will remove the body
3129 // $message['raw_message'] = '';
3133 $type = "status_message";
3136 $msg = array("type" => $type, "message" => $message);
3138 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3144 * @brief Sends a post
3146 * @param array $item The item that will be exported
3147 * @param array $owner the array of the item owner
3148 * @param array $contact Target of the communication
3149 * @param bool $public_batch Is it a public post?
3151 * @return int The result of the transmission
3153 public static function send_status($item, $owner, $contact, $public_batch = false) {
3155 $status = self::build_status($item, $owner);
3157 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3161 * @brief Creates a "like" object
3163 * @param array $item The item that will be exported
3164 * @param array $owner the array of the item owner
3166 * @return array The data for a "like"
3168 private static function construct_like($item, $owner) {
3170 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3171 dbesc($item["thr-parent"]));
3172 if (!dbm::is_result($p))
3177 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3178 if ($item['verb'] === ACTIVITY_LIKE) {
3180 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3181 $positive = "false";
3184 return(array("positive" => $positive,
3185 "guid" => $item["guid"],
3186 "target_type" => $target_type,
3187 "parent_guid" => $parent["guid"],
3188 "author_signature" => "",
3189 "diaspora_handle" => self::my_handle($owner)));
3193 * @brief Creates an "EventParticipation" object
3195 * @param array $item The item that will be exported
3196 * @param array $owner the array of the item owner
3198 * @return array The data for an "EventParticipation"
3200 private static function construct_attend($item, $owner) {
3202 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3203 dbesc($item["thr-parent"]));
3204 if (!dbm::is_result($p))
3209 switch ($item['verb']) {
3210 case ACTIVITY_ATTEND:
3211 $attend_answer = 'accepted';
3213 case ACTIVITY_ATTENDNO:
3214 $attend_answer = 'declined';
3216 case ACTIVITY_ATTENDMAYBE:
3217 $attend_answer = 'tentative';
3220 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3224 return(array("author" => self::my_handle($owner),
3225 "guid" => $item["guid"],
3226 "parent_guid" => $parent["guid"],
3227 "status" => $attend_answer,
3228 "author_signature" => ""));
3232 * @brief Creates the object for a comment
3234 * @param array $item The item that will be exported
3235 * @param array $owner the array of the item owner
3237 * @return array The data for a comment
3239 private static function construct_comment($item, $owner) {
3241 $cachekey = "diaspora:construct_comment:".$item['guid'];
3243 $result = Cache::get($cachekey);
3244 if (!is_null($result)) {
3248 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3249 intval($item["parent"]),
3250 intval($item["parent"])
3253 if (!dbm::is_result($p))
3258 $text = html_entity_decode(bb2diaspora($item["body"]));
3259 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3261 $comment = array("guid" => $item["guid"],
3262 "parent_guid" => $parent["guid"],
3263 "author_signature" => "",
3265 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3266 "diaspora_handle" => self::my_handle($owner));
3268 // Send the thread parent guid only if it is a threaded comment
3269 if ($item['thr-parent'] != $item['parent-uri']) {
3270 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3273 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3279 * @brief Send a like or a comment
3281 * @param array $item The item that will be exported
3282 * @param array $owner the array of the item owner
3283 * @param array $contact Target of the communication
3284 * @param bool $public_batch Is it a public post?
3286 * @return int The result of the transmission
3288 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3290 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3291 $message = self::construct_attend($item, $owner);
3292 $type = "event_participation";
3293 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3294 $message = self::construct_like($item, $owner);
3297 $message = self::construct_comment($item, $owner);
3304 $message["author_signature"] = self::signature($owner, $message);
3306 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3310 * @brief Creates a message from a signature record entry
3312 * @param array $item The item that will be exported
3313 * @param array $signature The entry of the "sign" record
3315 * @return string The message
3317 private static function message_from_signature($item, $signature) {
3319 // Split the signed text
3320 $signed_parts = explode(";", $signature['signed_text']);
3322 if ($item["deleted"])
3323 $message = array("parent_author_signature" => "",
3324 "target_guid" => $signed_parts[0],
3325 "target_type" => $signed_parts[1],
3326 "sender_handle" => $signature['signer'],
3327 "target_author_signature" => $signature['signature']);
3328 elseif ($item['verb'] === ACTIVITY_LIKE)
3329 $message = array("positive" => $signed_parts[0],
3330 "guid" => $signed_parts[1],
3331 "target_type" => $signed_parts[2],
3332 "parent_guid" => $signed_parts[3],
3333 "parent_author_signature" => "",
3334 "author_signature" => $signature['signature'],
3335 "diaspora_handle" => $signed_parts[4]);
3337 // Remove the comment guid
3338 $guid = array_shift($signed_parts);
3340 // Remove the parent guid
3341 $parent_guid = array_shift($signed_parts);
3343 // Remove the handle
3344 $handle = array_pop($signed_parts);
3346 // Glue the parts together
3347 $text = implode(";", $signed_parts);
3349 $message = array("guid" => $guid,
3350 "parent_guid" => $parent_guid,
3351 "parent_author_signature" => "",
3352 "author_signature" => $signature['signature'],
3353 "text" => implode(";", $signed_parts),
3354 "diaspora_handle" => $handle);
3360 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3362 * @param array $item The item that will be exported
3363 * @param array $owner the array of the item owner
3364 * @param array $contact Target of the communication
3365 * @param bool $public_batch Is it a public post?
3367 * @return int The result of the transmission
3369 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3371 if ($item["deleted"])
3372 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3373 elseif ($item['verb'] === ACTIVITY_LIKE)
3378 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3380 // fetch the original signature
3382 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3383 intval($item["id"]));
3386 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3392 // Old way - is used by the internal Friendica functions
3393 /// @todo Change all signatur storing functions to the new format
3394 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3395 $message = self::message_from_signature($item, $signature);
3397 $msg = json_decode($signature['signed_text'], true);
3400 if (is_array($msg)) {
3401 foreach ($msg AS $field => $data) {
3402 if (!$item["deleted"]) {
3403 if ($field == "author")
3404 $field = "diaspora_handle";
3405 if ($field == "parent_type")
3406 $field = "target_type";
3409 $message[$field] = $data;
3412 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3415 $message["parent_author_signature"] = self::signature($owner, $message);
3417 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3419 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3423 * @brief Sends a retraction (deletion) of a message, like or comment
3425 * @param array $item The item that will be exported
3426 * @param array $owner the array of the item owner
3427 * @param array $contact Target of the communication
3428 * @param bool $public_batch Is it a public post?
3429 * @param bool $relay Is the retraction transmitted from a relay?
3431 * @return int The result of the transmission
3433 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3435 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3437 // Check whether the retraction is for a top-level post or whether it's a relayable
3438 if ($item["uri"] !== $item["parent-uri"]) {
3439 $msg_type = "relayable_retraction";
3440 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3442 $msg_type = "signed_retraction";
3443 $target_type = "StatusMessage";
3446 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3447 $signature = "parent_author_signature";
3449 $signature = "target_author_signature";
3451 $signed_text = $item["guid"].";".$target_type;
3453 $message = array("target_guid" => $item['guid'],
3454 "target_type" => $target_type,
3455 "sender_handle" => $itemaddr,
3456 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3458 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3460 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3464 * @brief Sends a mail
3466 * @param array $item The item that will be exported
3467 * @param array $owner The owner
3468 * @param array $contact Target of the communication
3470 * @return int The result of the transmission
3472 public static function send_mail($item, $owner, $contact) {
3474 $myaddr = self::my_handle($owner);
3476 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3477 intval($item["convid"]),
3478 intval($item["uid"])
3481 if (!dbm::is_result($r)) {
3482 logger("conversation not found.");
3488 "guid" => $cnv["guid"],
3489 "subject" => $cnv["subject"],
3490 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3491 "diaspora_handle" => $cnv["creator"],
3492 "participant_handles" => $cnv["recips"]
3495 $body = bb2diaspora($item["body"]);
3496 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3498 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3499 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3502 "guid" => $item["guid"],
3503 "parent_guid" => $cnv["guid"],
3504 "parent_author_signature" => $sig,
3505 "author_signature" => $sig,
3507 "created_at" => $created,
3508 "diaspora_handle" => $myaddr,
3509 "conversation_guid" => $cnv["guid"]
3512 if ($item["reply"]) {
3516 $message = array("guid" => $cnv["guid"],
3517 "subject" => $cnv["subject"],
3518 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3520 "diaspora_handle" => $cnv["creator"],
3521 "participant_handles" => $cnv["recips"]);
3523 $type = "conversation";
3526 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3530 * @brief Sends profile data
3532 * @param int $uid The user id
3534 public static function send_profile($uid, $recips = false) {
3540 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3541 AND `uid` = %d AND `rel` != %d",
3542 dbesc(NETWORK_DIASPORA),
3544 intval(CONTACT_IS_SHARING)
3549 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3551 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3552 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3553 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3562 $handle = $profile["addr"];
3563 $first = ((strpos($profile['name'],' ')
3564 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3565 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3566 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3567 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3568 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3569 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3571 if ($searchable === 'true') {
3572 $dob = '1000-00-00';
3574 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3575 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3577 $about = $profile['about'];
3578 $about = strip_tags(bbcode($about));
3580 $location = formatted_location($profile);
3582 if ($profile['pub_keywords']) {
3583 $kw = str_replace(',',' ',$profile['pub_keywords']);
3584 $kw = str_replace(' ',' ',$kw);
3585 $arr = explode(' ',$profile['pub_keywords']);
3587 for($x = 0; $x < 5; $x ++) {
3589 $tags .= '#'. trim($arr[$x]) .' ';
3593 $tags = trim($tags);
3596 $message = array("diaspora_handle" => $handle,
3597 "first_name" => $first,
3598 "last_name" => $last,
3599 "image_url" => $large,
3600 "image_url_medium" => $medium,
3601 "image_url_small" => $small,
3603 "gender" => $profile['gender'],
3605 "location" => $location,
3606 "searchable" => $searchable,
3607 "tag_string" => $tags);
3609 foreach($recips as $recip) {
3610 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3611 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3616 * @brief Stores the signature for likes that are created on our system
3618 * @param array $contact The contact array of the "like"
3619 * @param int $post_id The post id of the "like"
3621 * @return bool Success
3623 public static function store_like_signature($contact, $post_id) {
3625 // Is the contact the owner? Then fetch the private key
3626 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3627 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3631 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3635 $contact["uprvkey"] = $r[0]['prvkey'];
3637 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3641 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3644 $message = self::construct_like($r[0], $contact);
3645 $message["author_signature"] = self::signature($contact, $message);
3647 // We now store the signature more flexible to dynamically support new fields.
3648 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3649 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3650 intval($message_id),
3651 dbesc(json_encode($message))
3654 logger('Stored diaspora like signature');
3659 * @brief Stores the signature for comments that are created on our system
3661 * @param array $item The item array of the comment
3662 * @param array $contact The contact array of the item owner
3663 * @param string $uprvkey The private key of the sender
3664 * @param int $message_id The message id of the comment
3666 * @return bool Success
3668 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3670 if ($uprvkey == "") {
3671 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3675 $contact["uprvkey"] = $uprvkey;
3677 $message = self::construct_comment($item, $contact);
3678 $message["author_signature"] = self::signature($contact, $message);
3680 // We now store the signature more flexible to dynamically support new fields.
3681 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3682 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3683 intval($message_id),
3684 dbesc(json_encode($message))
3687 logger('Stored diaspora comment signature');