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 require_once("include/items.php");
12 require_once("include/bb2diaspora.php");
13 require_once("include/Scrape.php");
14 require_once("include/Contact.php");
15 require_once("include/Photo.php");
16 require_once("include/socgraph.php");
17 require_once("include/group.php");
18 require_once("include/xml.php");
19 require_once("include/datetime.php");
20 require_once("include/queue_fn.php");
21 require_once("include/cache.php");
24 * @brief This class contain functions to create and send Diaspora XML files
30 * @brief Return a list of relay servers
32 * This is an experimental Diaspora feature.
34 * @return array of relay servers
36 public static function relay_list() {
38 $serverdata = get_config("system", "relay_server");
39 if ($serverdata == "")
44 $servers = explode(",", $serverdata);
46 foreach($servers AS $server) {
47 $server = trim($server);
48 $batch = $server."/receive/public";
50 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
53 $addr = "relay@".str_replace("http://", "", normalise_link($server));
55 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
56 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
61 dbesc(normalise_link($server)),
63 dbesc(NETWORK_DIASPORA),
64 intval(CONTACT_IS_FOLLOWER),
65 dbesc(datetime_convert()),
66 dbesc(datetime_convert()),
67 dbesc(datetime_convert())
70 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
72 $relay[] = $relais[0];
74 $relay[] = $relais[0];
81 * @brief repairs a signature that was double encoded
83 * The function is unused at the moment. It was copied from the old implementation.
85 * @param string $signature The signature
86 * @param string $handle The handle of the signature owner
87 * @param integer $level This value is only set inside this function to avoid endless loops
89 * @return string the repaired signature
91 private static function repair_signature($signature, $handle = "", $level = 1) {
96 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
97 $signature = base64_decode($signature);
98 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
100 // Do a recursive call to be able to fix even multiple levels
102 $signature = self::repair_signature($signature, $handle, ++$level);
109 * @brief verify the envelope and return the verified data
111 * @param string $envelope The magic envelope
113 * @return string verified data
115 private static function verify_magic_envelope($envelope) {
117 $basedom = parse_xml_string($envelope, false);
119 if (!is_object($basedom)) {
120 logger("Envelope is no XML file");
124 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
126 if (sizeof($children) == 0) {
127 logger("XML has no children");
133 $data = base64url_decode($children->data);
134 $type = $children->data->attributes()->type[0];
136 $encoding = $children->encoding;
138 $alg = $children->alg;
140 $sig = base64url_decode($children->sig);
141 $key_id = $children->sig->attributes()->key_id[0];
143 $handle = base64url_decode($key_id);
145 $b64url_data = base64url_encode($data);
146 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
148 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
150 $key = self::key($handle);
152 $verify = rsa_verify($signable_data, $sig, $key);
154 logger('Message did not verify. Discarding.');
162 * @brief: Decodes incoming Diaspora message
164 * @param array $importer Array of the importer user
165 * @param string $xml urldecoded Diaspora salmon
168 * 'message' -> decoded Diaspora XML message
169 * 'author' -> author diaspora handle
170 * 'key' -> author public key (converted to pkcs#8)
172 public static function decode($importer, $xml) {
175 $basedom = parse_xml_string($xml);
177 if (!is_object($basedom))
180 $children = $basedom->children('https://joindiaspora.com/protocol');
182 if($children->header) {
184 $author_link = str_replace('acct:','',$children->header->author_id);
187 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
189 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
190 $ciphertext = base64_decode($encrypted_header->ciphertext);
192 $outer_key_bundle = '';
193 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
195 $j_outer_key_bundle = json_decode($outer_key_bundle);
197 $outer_iv = base64_decode($j_outer_key_bundle->iv);
198 $outer_key = base64_decode($j_outer_key_bundle->key);
200 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
203 $decrypted = pkcs5_unpad($decrypted);
205 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
206 $idom = parse_xml_string($decrypted,false);
208 $inner_iv = base64_decode($idom->iv);
209 $inner_aes_key = base64_decode($idom->aes_key);
211 $author_link = str_replace('acct:','',$idom->author_id);
214 $dom = $basedom->children(NAMESPACE_SALMON_ME);
216 // figure out where in the DOM tree our data is hiding
218 if($dom->provenance->data)
219 $base = $dom->provenance;
220 elseif($dom->env->data)
226 logger('unable to locate salmon data in xml');
227 http_status_exit(400);
231 // Stash the signature away for now. We have to find their key or it won't be good for anything.
232 $signature = base64url_decode($base->sig);
236 // strip whitespace so our data element will return to one big base64 blob
237 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
240 // stash away some other stuff for later
242 $type = $base->data[0]->attributes()->type[0];
243 $keyhash = $base->sig[0]->attributes()->keyhash[0];
244 $encoding = $base->encoding;
248 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
252 $data = base64url_decode($data);
256 $inner_decrypted = $data;
259 // Decode the encrypted blob
261 $inner_encrypted = base64_decode($data);
262 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
263 $inner_decrypted = pkcs5_unpad($inner_decrypted);
267 logger('Could not retrieve author URI.');
268 http_status_exit(400);
270 // Once we have the author URI, go to the web and try to find their public key
271 // (first this will look it up locally if it is in the fcontact cache)
272 // This will also convert diaspora public key from pkcs#1 to pkcs#8
274 logger('Fetching key for '.$author_link);
275 $key = self::key($author_link);
278 logger('Could not retrieve author key.');
279 http_status_exit(400);
282 $verify = rsa_verify($signed_data,$signature,$key);
285 logger('Message did not verify. Discarding.');
286 http_status_exit(400);
289 logger('Message verified.');
291 return array('message' => (string)$inner_decrypted,
292 'author' => unxmlify($author_link),
293 'key' => (string)$key);
298 * @brief Dispatches public messages and find the fitting receivers
300 * @param array $msg The post that will be dispatched
302 * @return int The message id of the generated message, "true" or "false" if there was an error
304 public static function dispatch_public($msg) {
306 $enabled = intval(get_config("system", "diaspora_enabled"));
308 logger("diaspora is disabled");
312 // Use a dummy importer to import the data for the public copy
313 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
314 $message_id = self::dispatch($importer,$msg);
316 // Now distribute it to the followers
317 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
318 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
319 AND NOT `account_expired` AND NOT `account_removed`",
320 dbesc(NETWORK_DIASPORA),
321 dbesc($msg["author"])
324 foreach ($r as $rr) {
325 logger("delivering to: ".$rr["username"]);
326 self::dispatch($rr,$msg);
329 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
335 * @brief Dispatches the different message types to the different functions
337 * @param array $importer Array of the importer user
338 * @param array $msg The post that will be dispatched
340 * @return int The message id of the generated message, "true" or "false" if there was an error
342 public static function dispatch($importer, $msg) {
344 // The sender is the handle of the contact that sent the message.
345 // This will often be different with relayed messages (for example "like" and "comment")
346 $sender = $msg["author"];
348 if (!self::valid_posting($msg, $fields)) {
349 logger("Invalid posting");
353 $type = $fields->getName();
355 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
358 case "account_deletion":
359 return self::receive_account_deletion($importer, $fields);
362 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
365 return self::receive_contact_request($importer, $fields);
368 return self::receive_conversation($importer, $msg, $fields);
371 return self::receive_like($importer, $sender, $fields);
374 return self::receive_message($importer, $fields);
376 case "participation": // Not implemented
377 return self::receive_participation($importer, $fields);
379 case "photo": // Not implemented
380 return self::receive_photo($importer, $fields);
382 case "poll_participation": // Not implemented
383 return self::receive_poll_participation($importer, $fields);
386 return self::receive_profile($importer, $fields);
389 return self::receive_reshare($importer, $fields, $msg["message"]);
392 return self::receive_retraction($importer, $sender, $fields);
394 case "status_message":
395 return self::receive_status_message($importer, $fields, $msg["message"]);
398 logger("Unknown message type ".$type);
406 * @brief Checks if a posting is valid and fetches the data fields.
408 * This function does not only check the signature.
409 * It also does the conversion between the old and the new diaspora format.
411 * @param array $msg Array with the XML, the sender handle and the sender signature
412 * @param object $fields SimpleXML object that contains the posting when it is valid
414 * @return bool Is the posting valid?
416 private static function valid_posting($msg, &$fields) {
418 $data = parse_xml_string($msg["message"], false);
420 if (!is_object($data)) {
421 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
425 $first_child = $data->getName();
427 // Is this the new or the old version?
428 if ($data->getName() == "XML") {
430 foreach ($data->post->children() as $child)
437 $type = $element->getName();
440 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
442 // All retractions are handled identically from now on.
443 // In the new version there will only be "retraction".
444 if (in_array($type, array("signed_retraction", "relayable_retraction")))
445 $type = "retraction";
447 if ($type == "request")
450 $fields = new SimpleXMLElement("<".$type."/>");
454 foreach ($element->children() AS $fieldname => $entry) {
456 // Translation for the old XML structure
457 if ($fieldname == "diaspora_handle")
458 $fieldname = "author";
460 if ($fieldname == "participant_handles")
461 $fieldname = "participants";
463 if (in_array($type, array("like", "participation"))) {
464 if ($fieldname == "target_type")
465 $fieldname = "parent_type";
468 if ($fieldname == "sender_handle")
469 $fieldname = "author";
471 if ($fieldname == "recipient_handle")
472 $fieldname = "recipient";
474 if ($fieldname == "root_diaspora_id")
475 $fieldname = "root_author";
477 if ($type == "retraction") {
478 if ($fieldname == "post_guid")
479 $fieldname = "target_guid";
481 if ($fieldname == "type")
482 $fieldname = "target_type";
486 if (($fieldname == "author_signature") AND ($entry != ""))
487 $author_signature = base64_decode($entry);
488 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
489 $parent_author_signature = base64_decode($entry);
490 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
491 if ($signed_data != "") {
493 $signed_data_parent .= ";";
496 $signed_data .= $entry;
498 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
499 ($orig_type == "relayable_retraction"))
500 xml::copy($entry, $fields, $fieldname);
503 // This is something that shouldn't happen at all.
504 if (in_array($type, array("status_message", "reshare", "profile")))
505 if ($msg["author"] != $fields->author) {
506 logger("Message handle is not the same as envelope sender. Quitting this message.");
510 // Only some message types have signatures. So we quit here for the other types.
511 if (!in_array($type, array("comment", "message", "like")))
514 // No author_signature? This is a must, so we quit.
515 if (!isset($author_signature)) {
516 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
520 if (isset($parent_author_signature)) {
521 $key = self::key($msg["author"]);
523 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
524 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);
529 $key = self::key($fields->author);
531 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
532 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
539 * @brief Fetches the public key for a given handle
541 * @param string $handle The handle
543 * @return string The public key
545 private static function key($handle) {
546 $handle = strval($handle);
548 logger("Fetching diaspora key for: ".$handle);
550 $r = self::person_by_handle($handle);
558 * @brief Fetches data for a given handle
560 * @param string $handle The handle
562 * @return array the queried data
564 private static function person_by_handle($handle) {
566 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
567 dbesc(NETWORK_DIASPORA),
572 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
574 // update record occasionally so it doesn't get stale
575 $d = strtotime($person["updated"]." +00:00");
576 if ($d < strtotime("now - 14 days"))
579 if ($person["guid"] == "")
583 if (!$person OR $update) {
584 logger("create or refresh", LOGGER_DEBUG);
585 $r = probe_url($handle, PROBE_DIASPORA);
587 // Note that Friendica contacts will return a "Diaspora person"
588 // if Diaspora connectivity is enabled on their server
589 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
590 self::add_fcontact($r, $update);
598 * @brief Updates the fcontact table
600 * @param array $arr The fcontact data
601 * @param bool $update Update or insert?
603 * @return string The id of the fcontact entry
605 private static function add_fcontact($arr, $update = false) {
608 $r = q("UPDATE `fcontact` SET
622 WHERE `url` = '%s' AND `network` = '%s'",
624 dbesc($arr["photo"]),
625 dbesc($arr["request"]),
627 dbesc(strtolower($arr["addr"])),
629 dbesc($arr["batch"]),
630 dbesc($arr["notify"]),
632 dbesc($arr["confirm"]),
633 dbesc($arr["alias"]),
634 dbesc($arr["pubkey"]),
635 dbesc(datetime_convert()),
637 dbesc($arr["network"])
640 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
641 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
642 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
645 dbesc($arr["photo"]),
646 dbesc($arr["request"]),
650 dbesc($arr["batch"]),
651 dbesc($arr["notify"]),
653 dbesc($arr["confirm"]),
654 dbesc($arr["network"]),
655 dbesc($arr["alias"]),
656 dbesc($arr["pubkey"]),
657 dbesc(datetime_convert())
665 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
667 * @param int $contact_id The id in the contact table
668 * @param int $gcontact_id The id in the gcontact table
670 * @return string the handle
672 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
675 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
677 if ($gcontact_id != 0) {
678 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
679 intval($gcontact_id));
681 if (dbm::is_result($r)) {
682 return strtolower($r[0]["addr"]);
686 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
687 intval($contact_id));
689 if (dbm::is_result($r)) {
692 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
694 if ($contact['addr'] != "") {
695 $handle = $contact['addr'];
697 $baseurl_start = strpos($contact['url'],'://') + 3;
698 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
699 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
700 $handle = $contact['nick'].'@'.$baseurl;
704 return strtolower($handle);
708 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
711 * @param mixed $fcontact_guid Hexadecimal string guid
713 * @return string the contact url or null
715 public static function url_from_contact_guid($fcontact_guid) {
716 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
718 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
719 dbesc(NETWORK_DIASPORA),
720 dbesc($fcontact_guid)
723 if (dbm::is_result($r)) {
731 * @brief Get a contact id for a given handle
733 * @param int $uid The user id
734 * @param string $handle The handle in the format user@domain.tld
736 * @return The contact id
738 private static function contact_by_handle($uid, $handle) {
740 // First do a direct search on the contact table
741 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
747 //logger("Found contact ".$r[0]['id']." for user ".$uid." and handle ".$handle." - first try", LOGGER_DEBUG);
750 // We haven't found it?
751 // We use another function for it that will possibly create a contact entry
752 $cid = get_contact($handle, $uid);
755 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
757 if (dbm::is_result($r)) {
758 logger("Found contact ".$r[0]['id']." for user ".$uid." and handle ".$handle." - second try", LOGGER_DEBUG);
764 $handle_parts = explode("@", $handle);
765 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
766 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
771 if(dbm::is_result($r)) {
772 logger("Found contact ".$r[0]['id']." for user ".$uid." and handle ".$handle." - third try", LOGGER_DEBUG);
776 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
781 * @brief Check if posting is allowed for this contact
783 * @param array $importer Array of the importer user
784 * @param array $contact The contact that is checked
785 * @param bool $is_comment Is the check for a comment?
787 * @return bool is the contact allowed to post?
789 private static function post_allow($importer, $contact, $is_comment = false) {
791 // perhaps we were already sharing with this person. Now they're sharing with us.
792 // That makes us friends.
793 // Normally this should have handled by getting a request - but this could get lost
794 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
795 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
796 intval(CONTACT_IS_FRIEND),
797 intval($contact["id"]),
798 intval($importer["uid"])
800 $contact["rel"] = CONTACT_IS_FRIEND;
801 logger("defining user ".$contact["nick"]." as friend");
804 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
806 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
808 if($contact["rel"] == CONTACT_IS_FOLLOWER)
809 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
812 // Messages for the global users are always accepted
813 if ($importer["uid"] == 0)
820 * @brief Fetches the contact id for a handle and checks if posting is allowed
822 * @param array $importer Array of the importer user
823 * @param string $handle The checked handle in the format user@domain.tld
824 * @param bool $is_comment Is the check for a comment?
826 * @return array The contact data
828 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
829 $contact = self::contact_by_handle($importer["uid"], $handle);
831 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
835 if (!self::post_allow($importer, $contact, $is_comment)) {
836 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
843 * @brief Does the message already exists on the system?
845 * @param int $uid The user id
846 * @param string $guid The guid of the message
848 * @return int|bool message id if the message already was stored into the system - or false.
850 private static function message_exists($uid, $guid) {
851 $r = q("SELECT `guid` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
857 logger("message ".$guid." already exists for user ".$uid);
865 * @brief Checks for links to posts in a message
867 * @param array $item The item array
869 private static function fetch_guid($item) {
870 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
871 function ($match) use ($item){
872 return(self::fetch_guid_sub($match, $item));
877 * @brief Checks for relative /people/* links in an item body to match local
878 * contacts or prepends the remote host taken from the author link.
880 * @param string $body The item body to replace links from
881 * @param string $author_link The author link for missing local contact fallback
883 * @return the replaced string
885 public function replace_people_guid($body, $author_link) {
886 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
887 function ($match) use ($author_link) {
889 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
890 // 1 => '0123456789abcdef'
892 $handle = self::url_from_contact_guid($match[1]);
895 $return = '@[url='.$handle.']'.$match[2].'[/url]';
897 // No local match, restoring absolute remote URL from author scheme and host
898 $author_url = parse_url($author_link);
899 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
909 * @brief sub function of "fetch_guid" which checks for links in messages
911 * @param array $match array containing a link that has to be checked for a message link
912 * @param array $item The item array
914 private static function fetch_guid_sub($match, $item) {
915 if (!self::store_by_guid($match[1], $item["author-link"]))
916 self::store_by_guid($match[1], $item["owner-link"]);
920 * @brief Fetches an item with a given guid from a given server
922 * @param string $guid the message guid
923 * @param string $server The server address
924 * @param int $uid The user id of the user
926 * @return int the message id of the stored message or false
928 private static function store_by_guid($guid, $server, $uid = 0) {
929 $serverparts = parse_url($server);
930 $server = $serverparts["scheme"]."://".$serverparts["host"];
932 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
934 $msg = self::message($guid, $server);
939 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
941 // Now call the dispatcher
942 return self::dispatch_public($msg);
946 * @brief Fetches a message from a server
948 * @param string $guid message guid
949 * @param string $server The url of the server
950 * @param int $level Endless loop prevention
953 * 'message' => The message XML
954 * 'author' => The author handle
955 * 'key' => The public key of the author
957 private static function message($guid, $server, $level = 0) {
962 // This will work for new Diaspora servers and Friendica servers from 3.5
963 $source_url = $server."/fetch/post/".$guid;
964 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
966 $envelope = fetch_url($source_url);
968 logger("Envelope was fetched.", LOGGER_DEBUG);
969 $x = self::verify_magic_envelope($envelope);
971 logger("Envelope could not be verified.", LOGGER_DEBUG);
973 logger("Envelope was verified.", LOGGER_DEBUG);
977 // This will work for older Diaspora and Friendica servers
979 $source_url = $server."/p/".$guid.".xml";
980 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
982 $x = fetch_url($source_url);
987 $source_xml = parse_xml_string($x, false);
989 if (!is_object($source_xml))
992 if ($source_xml->post->reshare) {
993 // Reshare of a reshare - old Diaspora version
994 logger("Message is a reshare", LOGGER_DEBUG);
995 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
996 } elseif ($source_xml->getName() == "reshare") {
997 // Reshare of a reshare - new Diaspora version
998 logger("Message is a new reshare", LOGGER_DEBUG);
999 return self::message($source_xml->root_guid, $server, ++$level);
1004 // Fetch the author - for the old and the new Diaspora version
1005 if ($source_xml->post->status_message->diaspora_handle)
1006 $author = (string)$source_xml->post->status_message->diaspora_handle;
1007 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
1008 $author = (string)$source_xml->author;
1010 // If this isn't a "status_message" then quit
1012 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1016 $msg = array("message" => $x, "author" => $author);
1018 $msg["key"] = self::key($msg["author"]);
1024 * @brief Fetches the item record of a given guid
1026 * @param int $uid The user id
1027 * @param string $guid message guid
1028 * @param string $author The handle of the item
1029 * @param array $contact The contact of the item owner
1031 * @return array the item record
1033 private static function parent_item($uid, $guid, $author, $contact) {
1034 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1035 `author-name`, `author-link`, `author-avatar`,
1036 `owner-name`, `owner-link`, `owner-avatar`
1037 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1038 intval($uid), dbesc($guid));
1041 $result = self::store_by_guid($guid, $contact["url"], $uid);
1044 $person = self::person_by_handle($author);
1045 $result = self::store_by_guid($guid, $person["url"], $uid);
1049 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1051 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1052 `author-name`, `author-link`, `author-avatar`,
1053 `owner-name`, `owner-link`, `owner-avatar`
1054 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1055 intval($uid), dbesc($guid));
1060 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1063 logger("parent item found: parent: ".$guid." - user: ".$uid);
1069 * @brief returns contact details
1071 * @param array $contact The default contact if the person isn't found
1072 * @param array $person The record of the person
1073 * @param int $uid The user id
1076 * 'cid' => contact id
1077 * 'network' => network type
1079 private static function author_contact_by_url($contact, $person, $uid) {
1081 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1082 dbesc(normalise_link($person["url"])), intval($uid));
1085 $network = $r[0]["network"];
1087 // We are receiving content from a user that is about to be terminated
1088 // This means the user is vital, so we remove a possible termination date.
1089 unmark_for_death($contact);
1091 $cid = $contact["id"];
1092 $network = NETWORK_DIASPORA;
1095 return array("cid" => $cid, "network" => $network);
1099 * @brief Is the profile a hubzilla profile?
1101 * @param string $url The profile link
1103 * @return bool is it a hubzilla server?
1105 public static function is_redmatrix($url) {
1106 return(strstr($url, "/channel/"));
1110 * @brief Generate a post link with a given handle and message guid
1112 * @param string $addr The user handle
1113 * @param string $guid message guid
1115 * @return string the post link
1117 private static function plink($addr, $guid) {
1118 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1122 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1124 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1125 // So we try another way as well.
1126 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1128 $r[0]["network"] = $s[0]["network"];
1130 if ($r[0]["network"] == NETWORK_DFRN)
1131 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1133 if (self::is_redmatrix($r[0]["url"]))
1134 return $r[0]["url"]."/?f=&mid=".$guid;
1136 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1140 * @brief Processes an account deletion
1142 * @param array $importer Array of the importer user
1143 * @param object $data The message object
1145 * @return bool Success
1147 private static function receive_account_deletion($importer, $data) {
1149 /// @todo Account deletion should remove the contact from the global contacts as well
1151 $author = notags(unxmlify($data->author));
1153 $contact = self::contact_by_handle($importer["uid"], $author);
1155 logger("cannot find contact for author: ".$author);
1159 // We now remove the contact
1160 contact_remove($contact["id"]);
1165 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1167 * @param string $author Author handle
1168 * @param string $guid Message guid
1169 * @param boolean $onlyfound Only return uri when found in the database
1171 * @return string The constructed uri or the one from our database
1173 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1175 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1176 if (dbm::is_result($r)) {
1177 return $r[0]["uri"];
1178 } elseif (!$onlyfound) {
1179 return $author.":".$guid;
1186 * @brief Fetch the guid from our database with a given uri
1188 * @param string $author Author handle
1189 * @param string $uri Message uri
1191 * @return string The post guid
1193 private static function get_guid_from_uri($uri, $uid) {
1195 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1196 if (dbm::is_result($r)) {
1197 return $r[0]["guid"];
1204 * @brief Processes an incoming comment
1206 * @param array $importer Array of the importer user
1207 * @param string $sender The sender of the message
1208 * @param object $data The message object
1209 * @param string $xml The original XML of the message
1211 * @return int The message id of the generated comment or "false" if there was an error
1213 private static function receive_comment($importer, $sender, $data, $xml) {
1214 $guid = notags(unxmlify($data->guid));
1215 $parent_guid = notags(unxmlify($data->parent_guid));
1216 $text = unxmlify($data->text);
1217 $author = notags(unxmlify($data->author));
1219 if (isset($data->created_at)) {
1220 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1222 $created_at = datetime_convert();
1225 if (isset($data->thread_parent_guid)) {
1226 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1227 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1232 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1237 $message_id = self::message_exists($importer["uid"], $guid);
1242 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1243 if (!$parent_item) {
1247 $person = self::person_by_handle($author);
1248 if (!is_array($person)) {
1249 logger("unable to find author details");
1253 // Fetch the contact id - if we know this contact
1254 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1256 $datarray = array();
1258 $datarray["uid"] = $importer["uid"];
1259 $datarray["contact-id"] = $author_contact["cid"];
1260 $datarray["network"] = $author_contact["network"];
1262 $datarray["author-name"] = $person["name"];
1263 $datarray["author-link"] = $person["url"];
1264 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1266 $datarray["owner-name"] = $contact["name"];
1267 $datarray["owner-link"] = $contact["url"];
1268 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1270 $datarray["guid"] = $guid;
1271 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1273 $datarray["type"] = "remote-comment";
1274 $datarray["verb"] = ACTIVITY_POST;
1275 $datarray["gravity"] = GRAVITY_COMMENT;
1277 if ($thr_uri != "") {
1278 $datarray["parent-uri"] = $thr_uri;
1280 $datarray["parent-uri"] = $parent_item["uri"];
1283 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1284 $datarray["object"] = $xml;
1286 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1288 $body = diaspora2bb($text);
1290 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1292 self::fetch_guid($datarray);
1294 $message_id = item_store($datarray);
1297 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1300 // If we are the origin of the parent we store the original data and notify our followers
1301 if($message_id AND $parent_item["origin"]) {
1303 // Formerly we stored the signed text, the signature and the author in different fields.
1304 // We now store the raw data so that we are more flexible.
1305 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1306 intval($message_id),
1307 dbesc(json_encode($data))
1311 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1318 * @brief processes and stores private messages
1320 * @param array $importer Array of the importer user
1321 * @param array $contact The contact of the message
1322 * @param object $data The message object
1323 * @param array $msg Array of the processed message, author handle and key
1324 * @param object $mesg The private message
1325 * @param array $conversation The conversation record to which this message belongs
1327 * @return bool "true" if it was successful
1329 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1330 $guid = notags(unxmlify($data->guid));
1331 $subject = notags(unxmlify($data->subject));
1332 $author = notags(unxmlify($data->author));
1334 $msg_guid = notags(unxmlify($mesg->guid));
1335 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1336 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1337 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1338 $msg_text = unxmlify($mesg->text);
1339 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1341 // "diaspora_handle" is the element name from the old version
1342 // "author" is the element name from the new version
1343 if ($mesg->author) {
1344 $msg_author = notags(unxmlify($mesg->author));
1345 } elseif ($mesg->diaspora_handle) {
1346 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1351 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1353 if ($msg_conversation_guid != $guid) {
1354 logger("message conversation guid does not belong to the current conversation.");
1358 $body = diaspora2bb($msg_text);
1359 $message_uri = $msg_author.":".$msg_guid;
1361 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1363 $author_signature = base64_decode($msg_author_signature);
1365 if (strcasecmp($msg_author,$msg["author"]) == 0) {
1369 $person = self::person_by_handle($msg_author);
1371 if (is_array($person) && x($person, "pubkey")) {
1372 $key = $person["pubkey"];
1374 logger("unable to find author details");
1379 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1380 logger("verification failed.");
1384 if ($msg_parent_author_signature) {
1385 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1387 $parent_author_signature = base64_decode($msg_parent_author_signature);
1391 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1392 logger("owner verification failed.");
1397 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1400 if (dbm::is_result($r)) {
1401 logger("duplicate message already delivered.", LOGGER_DEBUG);
1405 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1406 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1407 intval($importer["uid"]),
1409 intval($conversation["id"]),
1410 dbesc($person["name"]),
1411 dbesc($person["photo"]),
1412 dbesc($person["url"]),
1413 intval($contact["id"]),
1418 dbesc($message_uri),
1419 dbesc($author.":".$guid),
1420 dbesc($msg_created_at)
1423 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1424 dbesc(datetime_convert()),
1425 intval($conversation["id"])
1429 "type" => NOTIFY_MAIL,
1430 "notify_flags" => $importer["notify-flags"],
1431 "language" => $importer["language"],
1432 "to_name" => $importer["username"],
1433 "to_email" => $importer["email"],
1434 "uid" =>$importer["uid"],
1435 "item" => array("subject" => $subject, "body" => $body),
1436 "source_name" => $person["name"],
1437 "source_link" => $person["url"],
1438 "source_photo" => $person["thumb"],
1439 "verb" => ACTIVITY_POST,
1446 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1448 * @param array $importer Array of the importer user
1449 * @param array $msg Array of the processed message, author handle and key
1450 * @param object $data The message object
1452 * @return bool Success
1454 private static function receive_conversation($importer, $msg, $data) {
1455 $guid = notags(unxmlify($data->guid));
1456 $subject = notags(unxmlify($data->subject));
1457 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1458 $author = notags(unxmlify($data->author));
1459 $participants = notags(unxmlify($data->participants));
1461 $messages = $data->message;
1463 if (!count($messages)) {
1464 logger("empty conversation");
1468 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1472 $conversation = null;
1474 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1475 intval($importer["uid"]),
1479 $conversation = $c[0];
1481 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1482 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1483 intval($importer["uid"]),
1487 dbesc(datetime_convert()),
1489 dbesc($participants)
1492 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1493 intval($importer["uid"]),
1498 $conversation = $c[0];
1500 if (!$conversation) {
1501 logger("unable to create conversation.");
1505 foreach($messages as $mesg)
1506 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1512 * @brief Creates the body for a "like" message
1514 * @param array $contact The contact that send us the "like"
1515 * @param array $parent_item The item array of the parent item
1516 * @param string $guid message guid
1518 * @return string the body
1520 private static function construct_like_body($contact, $parent_item, $guid) {
1521 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1523 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1524 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1525 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1527 return sprintf($bodyverb, $ulink, $alink, $plink);
1531 * @brief Creates a XML object for a "like"
1533 * @param array $importer Array of the importer user
1534 * @param array $parent_item The item array of the parent item
1536 * @return string The XML
1538 private static function construct_like_object($importer, $parent_item) {
1539 $objtype = ACTIVITY_OBJ_NOTE;
1540 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1541 $parent_body = $parent_item["body"];
1543 $xmldata = array("object" => array("type" => $objtype,
1545 "id" => $parent_item["uri"],
1548 "content" => $parent_body));
1550 return xml::from_array($xmldata, $xml, true);
1554 * @brief Processes "like" messages
1556 * @param array $importer Array of the importer user
1557 * @param string $sender The sender of the message
1558 * @param object $data The message object
1560 * @return int The message id of the generated like or "false" if there was an error
1562 private static function receive_like($importer, $sender, $data) {
1563 $positive = notags(unxmlify($data->positive));
1564 $guid = notags(unxmlify($data->guid));
1565 $parent_type = notags(unxmlify($data->parent_type));
1566 $parent_guid = notags(unxmlify($data->parent_guid));
1567 $author = notags(unxmlify($data->author));
1569 // likes on comments aren't supported by Diaspora - only on posts
1570 // But maybe this will be supported in the future, so we will accept it.
1571 if (!in_array($parent_type, array("Post", "Comment")))
1574 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1578 $message_id = self::message_exists($importer["uid"], $guid);
1582 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1586 $person = self::person_by_handle($author);
1587 if (!is_array($person)) {
1588 logger("unable to find author details");
1592 // Fetch the contact id - if we know this contact
1593 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1595 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1596 // We would accept this anyhow.
1597 if ($positive == "true")
1598 $verb = ACTIVITY_LIKE;
1600 $verb = ACTIVITY_DISLIKE;
1602 $datarray = array();
1604 $datarray["uid"] = $importer["uid"];
1605 $datarray["contact-id"] = $author_contact["cid"];
1606 $datarray["network"] = $author_contact["network"];
1608 $datarray["author-name"] = $person["name"];
1609 $datarray["author-link"] = $person["url"];
1610 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1612 $datarray["owner-name"] = $contact["name"];
1613 $datarray["owner-link"] = $contact["url"];
1614 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1616 $datarray["guid"] = $guid;
1617 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1619 $datarray["type"] = "activity";
1620 $datarray["verb"] = $verb;
1621 $datarray["gravity"] = GRAVITY_LIKE;
1622 $datarray["parent-uri"] = $parent_item["uri"];
1624 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1625 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1627 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1629 $message_id = item_store($datarray);
1632 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1634 // If we are the origin of the parent we store the original data and notify our followers
1635 if($message_id AND $parent_item["origin"]) {
1637 // Formerly we stored the signed text, the signature and the author in different fields.
1638 // We now store the raw data so that we are more flexible.
1639 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1640 intval($message_id),
1641 dbesc(json_encode($data))
1645 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1652 * @brief Processes private messages
1654 * @param array $importer Array of the importer user
1655 * @param object $data The message object
1657 * @return bool Success?
1659 private static function receive_message($importer, $data) {
1660 $guid = notags(unxmlify($data->guid));
1661 $parent_guid = notags(unxmlify($data->parent_guid));
1662 $text = unxmlify($data->text);
1663 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1664 $author = notags(unxmlify($data->author));
1665 $conversation_guid = notags(unxmlify($data->conversation_guid));
1667 $contact = self::allowed_contact_by_handle($importer, $author, true);
1672 $conversation = null;
1674 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1675 intval($importer["uid"]),
1676 dbesc($conversation_guid)
1679 $conversation = $c[0];
1681 logger("conversation not available.");
1685 $message_uri = $author.":".$guid;
1687 $person = self::person_by_handle($author);
1689 logger("unable to find author details");
1693 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1694 dbesc($message_uri),
1695 intval($importer["uid"])
1697 if (dbm::is_result($r)) {
1698 logger("duplicate message already delivered.", LOGGER_DEBUG);
1702 $body = diaspora2bb($text);
1704 $body = self::replace_people_guid($body, $person["url"]);
1706 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1707 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1708 intval($importer["uid"]),
1710 intval($conversation["id"]),
1711 dbesc($person["name"]),
1712 dbesc($person["photo"]),
1713 dbesc($person["url"]),
1714 intval($contact["id"]),
1715 dbesc($conversation["subject"]),
1719 dbesc($message_uri),
1720 dbesc($author.":".$parent_guid),
1724 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1725 dbesc(datetime_convert()),
1726 intval($conversation["id"])
1733 * @brief Processes participations - unsupported by now
1735 * @param array $importer Array of the importer user
1736 * @param object $data The message object
1738 * @return bool always true
1740 private static function receive_participation($importer, $data) {
1741 // I'm not sure if we can fully support this message type
1746 * @brief Processes photos - unneeded
1748 * @param array $importer Array of the importer user
1749 * @param object $data The message object
1751 * @return bool always true
1753 private static function receive_photo($importer, $data) {
1754 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1759 * @brief Processes poll participations - unssupported
1761 * @param array $importer Array of the importer user
1762 * @param object $data The message object
1764 * @return bool always true
1766 private static function receive_poll_participation($importer, $data) {
1767 // We don't support polls by now
1772 * @brief Processes incoming profile updates
1774 * @param array $importer Array of the importer user
1775 * @param object $data The message object
1777 * @return bool Success
1779 private static function receive_profile($importer, $data) {
1780 $author = strtolower(notags(unxmlify($data->author)));
1782 $contact = self::contact_by_handle($importer["uid"], $author);
1786 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1787 $image_url = unxmlify($data->image_url);
1788 $birthday = unxmlify($data->birthday);
1789 $location = diaspora2bb(unxmlify($data->location));
1790 $about = diaspora2bb(unxmlify($data->bio));
1791 $gender = unxmlify($data->gender);
1792 $searchable = (unxmlify($data->searchable) == "true");
1793 $nsfw = (unxmlify($data->nsfw) == "true");
1794 $tags = unxmlify($data->tag_string);
1796 $tags = explode("#", $tags);
1798 $keywords = array();
1799 foreach ($tags as $tag) {
1800 $tag = trim(strtolower($tag));
1805 $keywords = implode(", ", $keywords);
1807 $handle_parts = explode("@", $author);
1808 $nick = $handle_parts[0];
1811 $name = $handle_parts[0];
1813 if( preg_match("|^https?://|", $image_url) === 0)
1814 $image_url = "http://".$handle_parts[1].$image_url;
1816 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1818 // Generic birthday. We don't know the timezone. The year is irrelevant.
1820 $birthday = str_replace("1000", "1901", $birthday);
1822 if ($birthday != "")
1823 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1825 // this is to prevent multiple birthday notifications in a single year
1826 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1828 if(substr($birthday,5) === substr($contact["bd"],5))
1829 $birthday = $contact["bd"];
1831 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1832 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1836 dbesc(datetime_convert()),
1842 intval($contact["id"]),
1843 intval($importer["uid"])
1847 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1848 datetime_convert(), 2, $contact["id"], $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 update_gcontact($gcontact);
1859 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1865 * @brief Processes incoming friend requests
1867 * @param array $importer Array of the importer user
1868 * @param array $contact The contact that send the request
1870 private static function receive_request_make_friend($importer, $contact) {
1874 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1875 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1876 intval(CONTACT_IS_FRIEND),
1877 intval($contact["id"]),
1878 intval($importer["uid"])
1881 // send notification
1883 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1884 intval($importer["uid"])
1887 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1889 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1890 intval($importer["uid"])
1893 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1895 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1898 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1899 $arr["uid"] = $importer["uid"];
1900 $arr["contact-id"] = $self[0]["id"];
1902 $arr["type"] = 'wall';
1903 $arr["gravity"] = 0;
1905 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1906 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1907 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1908 $arr["verb"] = ACTIVITY_FRIEND;
1909 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1911 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1912 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1913 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1914 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1916 $arr["object"] = self::construct_new_friend_object($contact);
1918 $arr["last-child"] = 1;
1920 $arr["allow_cid"] = $user[0]["allow_cid"];
1921 $arr["allow_gid"] = $user[0]["allow_gid"];
1922 $arr["deny_cid"] = $user[0]["deny_cid"];
1923 $arr["deny_gid"] = $user[0]["deny_gid"];
1925 $i = item_store($arr);
1927 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
1933 * @brief Creates a XML object for a "new friend" message
1935 * @param array $contact Array of the contact
1937 * @return string The XML
1939 private static function construct_new_friend_object($contact) {
1940 $objtype = ACTIVITY_OBJ_PERSON;
1941 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1942 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1944 $xmldata = array("object" => array("type" => $objtype,
1945 "title" => $contact["name"],
1946 "id" => $contact["url"]."/".$contact["name"],
1949 return xml::from_array($xmldata, $xml, true);
1953 * @brief Processes incoming sharing notification
1955 * @param array $importer Array of the importer user
1956 * @param object $data The message object
1958 * @return bool Success
1960 private static function receive_contact_request($importer, $data) {
1961 $author = unxmlify($data->author);
1962 $recipient = unxmlify($data->recipient);
1964 if (!$author || !$recipient) {
1968 // the current protocol version doesn't know these fields
1969 // That means that we will assume their existance
1970 if (isset($data->following)) {
1971 $following = (unxmlify($data->following) == "true");
1976 if (isset($data->sharing)) {
1977 $sharing = (unxmlify($data->sharing) == "true");
1982 $contact = self::contact_by_handle($importer["uid"],$author);
1984 // perhaps we were already sharing with this person. Now they're sharing with us.
1985 // That makes us friends.
1987 if ($following AND $sharing) {
1988 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
1989 self::receive_request_make_friend($importer, $contact);
1991 // refetch the contact array
1992 $contact = self::contact_by_handle($importer["uid"],$author);
1994 // If we are now friends, we are sending a share message.
1995 // Normally we needn't to do so, but the first message could have been vanished.
1996 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
1997 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1999 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2000 $ret = self::send_share($u[0], $contact);
2004 } else { /// @todo Handle all possible variations of adding and retracting of permissions
2005 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
2010 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2011 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2013 } elseif (!$following AND !$sharing) {
2014 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2016 } elseif (!$following AND $sharing) {
2017 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2018 } elseif ($following AND $sharing) {
2019 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2020 } elseif ($following AND !$sharing) {
2021 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2024 $ret = self::person_by_handle($author);
2026 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2027 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2031 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2033 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2034 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2035 intval($importer["uid"]),
2036 dbesc($ret["network"]),
2037 dbesc($ret["addr"]),
2040 dbesc(normalise_link($ret["url"])),
2042 dbesc($ret["name"]),
2043 dbesc($ret["nick"]),
2044 dbesc($ret["photo"]),
2045 dbesc($ret["pubkey"]),
2046 dbesc($ret["notify"]),
2047 dbesc($ret["poll"]),
2052 // find the contact record we just created
2054 $contact_record = self::contact_by_handle($importer["uid"],$author);
2056 if (!$contact_record) {
2057 logger("unable to locate newly created contact record.");
2061 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2063 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2065 if(intval($def_gid))
2066 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2068 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2070 if($importer["page-flags"] == PAGE_NORMAL) {
2072 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2074 $hash = random_string().(string)time(); // Generate a confirm_key
2076 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2077 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2078 intval($importer["uid"]),
2079 intval($contact_record["id"]),
2082 dbesc(t("Sharing notification from Diaspora network")),
2084 dbesc(datetime_convert())
2088 // automatic friend approval
2090 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2092 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2094 // technically they are sharing with us (CONTACT_IS_SHARING),
2095 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2096 // we are going to change the relationship and make them a follower.
2098 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2099 $new_relation = CONTACT_IS_FRIEND;
2100 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2101 $new_relation = CONTACT_IS_SHARING;
2103 $new_relation = CONTACT_IS_FOLLOWER;
2105 $r = q("UPDATE `contact` SET `rel` = %d,
2113 intval($new_relation),
2114 dbesc(datetime_convert()),
2115 dbesc(datetime_convert()),
2116 intval($contact_record["id"])
2119 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2121 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2122 $ret = self::send_share($u[0], $contact_record);
2124 // Send the profile data, maybe it weren't transmitted before
2125 self::send_profile($importer["uid"], array($contact_record));
2133 * @brief Fetches a message with a given guid
2135 * @param string $guid message guid
2136 * @param string $orig_author handle of the original post
2137 * @param string $author handle of the sharer
2139 * @return array The fetched item
2141 private static function original_item($guid, $orig_author, $author) {
2143 // Do we already have this item?
2144 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2145 `author-name`, `author-link`, `author-avatar`
2146 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2149 if (dbm::is_result($r)) {
2150 logger("reshared message ".$guid." already exists on system.");
2152 // Maybe it is already a reshared item?
2153 // Then refetch the content, if it is a reshare from a reshare.
2154 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2155 if (self::is_reshare($r[0]["body"], true)) {
2157 } elseif (self::is_reshare($r[0]["body"], false)) {
2158 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2160 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2162 // Add OEmbed and other information to the body
2163 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2171 if (!dbm::is_result($r)) {
2172 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2173 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2174 $item_id = self::store_by_guid($guid, $server);
2177 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2178 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2179 $item_id = self::store_by_guid($guid, $server);
2183 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2184 `author-name`, `author-link`, `author-avatar`
2185 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2188 if (dbm::is_result($r)) {
2189 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2190 if (self::is_reshare($r[0]["body"], false)) {
2191 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2192 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2204 * @brief Processes a reshare message
2206 * @param array $importer Array of the importer user
2207 * @param object $data The message object
2208 * @param string $xml The original XML of the message
2210 * @return int the message id
2212 private static function receive_reshare($importer, $data, $xml) {
2213 $root_author = notags(unxmlify($data->root_author));
2214 $root_guid = notags(unxmlify($data->root_guid));
2215 $guid = notags(unxmlify($data->guid));
2216 $author = notags(unxmlify($data->author));
2217 $public = notags(unxmlify($data->public));
2218 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2220 $contact = self::allowed_contact_by_handle($importer, $author, false);
2225 $message_id = self::message_exists($importer["uid"], $guid);
2230 $original_item = self::original_item($root_guid, $root_author, $author);
2231 if (!$original_item) {
2235 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2237 $datarray = array();
2239 $datarray["uid"] = $importer["uid"];
2240 $datarray["contact-id"] = $contact["id"];
2241 $datarray["network"] = NETWORK_DIASPORA;
2243 $datarray["author-name"] = $contact["name"];
2244 $datarray["author-link"] = $contact["url"];
2245 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2247 $datarray["owner-name"] = $datarray["author-name"];
2248 $datarray["owner-link"] = $datarray["author-link"];
2249 $datarray["owner-avatar"] = $datarray["author-avatar"];
2251 $datarray["guid"] = $guid;
2252 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2254 $datarray["verb"] = ACTIVITY_POST;
2255 $datarray["gravity"] = GRAVITY_PARENT;
2257 $datarray["object"] = $xml;
2259 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2260 $original_item["guid"], $original_item["created"], $orig_url);
2261 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2263 $datarray["tag"] = $original_item["tag"];
2264 $datarray["app"] = $original_item["app"];
2266 $datarray["plink"] = self::plink($author, $guid);
2267 $datarray["private"] = (($public == "false") ? 1 : 0);
2268 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2270 $datarray["object-type"] = $original_item["object-type"];
2272 self::fetch_guid($datarray);
2273 $message_id = item_store($datarray);
2276 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2283 * @brief Processes retractions
2285 * @param array $importer Array of the importer user
2286 * @param array $contact The contact of the item owner
2287 * @param object $data The message object
2289 * @return bool success
2291 private static function item_retraction($importer, $contact, $data) {
2292 $target_type = notags(unxmlify($data->target_type));
2293 $target_guid = notags(unxmlify($data->target_guid));
2294 $author = notags(unxmlify($data->author));
2296 $person = self::person_by_handle($author);
2297 if (!is_array($person)) {
2298 logger("unable to find author detail for ".$author);
2302 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2303 dbesc($target_guid),
2304 intval($importer["uid"])
2309 // Check if the sender is the thread owner
2310 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2311 intval($r[0]["parent"]));
2313 // Only delete it if the parent author really fits
2314 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2315 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2319 // 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
2320 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2321 dbesc(datetime_convert()),
2322 dbesc(datetime_convert()),
2325 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2327 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2329 // Now check if the retraction needs to be relayed by us
2330 if($p[0]["origin"]) {
2332 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2339 * @brief Receives retraction messages
2341 * @param array $importer Array of the importer user
2342 * @param string $sender The sender of the message
2343 * @param object $data The message object
2345 * @return bool Success
2347 private static function receive_retraction($importer, $sender, $data) {
2348 $target_type = notags(unxmlify($data->target_type));
2350 $contact = self::contact_by_handle($importer["uid"], $sender);
2352 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2356 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2358 switch ($target_type) {
2361 case "Post": // "Post" will be supported in a future version
2363 case "StatusMessage":
2364 return self::item_retraction($importer, $contact, $data);;
2368 /// @todo What should we do with an "unshare"?
2369 // Removing the contact isn't correct since we still can read the public items
2370 contact_remove($contact["id"]);
2374 logger("Unknown target type ".$target_type);
2381 * @brief Receives status messages
2383 * @param array $importer Array of the importer user
2384 * @param object $data The message object
2385 * @param string $xml The original XML of the message
2387 * @return int The message id of the newly created item
2389 private static function receive_status_message($importer, $data, $xml) {
2390 $raw_message = unxmlify($data->raw_message);
2391 $guid = notags(unxmlify($data->guid));
2392 $author = notags(unxmlify($data->author));
2393 $public = notags(unxmlify($data->public));
2394 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2395 $provider_display_name = notags(unxmlify($data->provider_display_name));
2397 /// @todo enable support for polls
2398 //if ($data->poll) {
2399 // foreach ($data->poll AS $poll)
2403 $contact = self::allowed_contact_by_handle($importer, $author, false);
2408 $message_id = self::message_exists($importer["uid"], $guid);
2414 if ($data->location) {
2415 foreach ($data->location->children() AS $fieldname => $data) {
2416 $address[$fieldname] = notags(unxmlify($data));
2420 $body = diaspora2bb($raw_message);
2422 $datarray = array();
2424 // Attach embedded pictures to the body
2426 foreach ($data->photo AS $photo) {
2427 $body = "[img]".unxmlify($photo->remote_photo_path).
2428 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2431 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2433 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2435 // Add OEmbed and other information to the body
2436 if (!self::is_redmatrix($contact["url"])) {
2437 $body = add_page_info_to_body($body, false, true);
2441 $datarray["uid"] = $importer["uid"];
2442 $datarray["contact-id"] = $contact["id"];
2443 $datarray["network"] = NETWORK_DIASPORA;
2445 $datarray["author-name"] = $contact["name"];
2446 $datarray["author-link"] = $contact["url"];
2447 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2449 $datarray["owner-name"] = $datarray["author-name"];
2450 $datarray["owner-link"] = $datarray["author-link"];
2451 $datarray["owner-avatar"] = $datarray["author-avatar"];
2453 $datarray["guid"] = $guid;
2454 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2456 $datarray["verb"] = ACTIVITY_POST;
2457 $datarray["gravity"] = GRAVITY_PARENT;
2459 $datarray["object"] = $xml;
2461 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2463 if ($provider_display_name != "") {
2464 $datarray["app"] = $provider_display_name;
2467 $datarray["plink"] = self::plink($author, $guid);
2468 $datarray["private"] = (($public == "false") ? 1 : 0);
2469 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2471 if (isset($address["address"])) {
2472 $datarray["location"] = $address["address"];
2475 if (isset($address["lat"]) AND isset($address["lng"])) {
2476 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2479 self::fetch_guid($datarray);
2480 $message_id = item_store($datarray);
2483 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2489 /* ************************************************************************************** *
2490 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2491 * ************************************************************************************** */
2494 * @brief returnes the handle of a contact
2496 * @param array $me contact array
2498 * @return string the handle in the format user@domain.tld
2500 private static function my_handle($contact) {
2501 if ($contact["addr"] != "")
2502 return $contact["addr"];
2504 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2505 // So - just in case - we build the the address here.
2506 if ($contact["nickname"] != "")
2507 $nick = $contact["nickname"];
2509 $nick = $contact["nick"];
2511 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2515 * @brief Creates the envelope for the "fetch" endpoint
2517 * @param string $msg The message that is to be transmitted
2518 * @param array $user The record of the sender
2520 * @return string The envelope
2523 public static function build_magic_envelope($msg, $user) {
2525 $b64url_data = base64url_encode($msg);
2526 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2528 $key_id = base64url_encode(self::my_handle($user));
2529 $type = "application/xml";
2530 $encoding = "base64url";
2531 $alg = "RSA-SHA256";
2532 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2533 $signature = rsa_sign($signable_data, $user["prvkey"]);
2534 $sig = base64url_encode($signature);
2536 $xmldata = array("me:env" => array("me:data" => $data,
2537 "@attributes" => array("type" => $type),
2538 "me:encoding" => $encoding,
2541 "@attributes2" => array("key_id" => $key_id)));
2543 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2545 return xml::from_array($xmldata, $xml, false, $namespaces);
2549 * @brief Creates the envelope for a public message
2551 * @param string $msg The message that is to be transmitted
2552 * @param array $user The record of the sender
2553 * @param array $contact Target of the communication
2554 * @param string $prvkey The private key of the sender
2555 * @param string $pubkey The public key of the receiver
2557 * @return string The envelope
2559 private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2561 logger("Message: ".$msg, LOGGER_DATA);
2563 $handle = self::my_handle($user);
2565 $b64url_data = base64url_encode($msg);
2567 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2569 $type = "application/xml";
2570 $encoding = "base64url";
2571 $alg = "RSA-SHA256";
2573 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2575 $signature = rsa_sign($signable_data,$prvkey);
2576 $sig = base64url_encode($signature);
2578 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2579 "me:env" => array("me:encoding" => $encoding,
2582 "@attributes" => array("type" => $type),
2583 "me:sig" => $sig)));
2585 $namespaces = array("" => "https://joindiaspora.com/protocol",
2586 "me" => "http://salmon-protocol.org/ns/magic-env");
2588 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2590 logger("magic_env: ".$magic_env, LOGGER_DATA);
2595 * @brief Creates the envelope for a private message
2597 * @param string $msg The message that is to be transmitted
2598 * @param array $user The record of the sender
2599 * @param array $contact Target of the communication
2600 * @param string $prvkey The private key of the sender
2601 * @param string $pubkey The public key of the receiver
2603 * @return string The envelope
2605 private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2607 logger("Message: ".$msg, LOGGER_DATA);
2609 // without a public key nothing will work
2612 logger("pubkey missing: contact id: ".$contact["id"]);
2616 $inner_aes_key = random_string(32);
2617 $b_inner_aes_key = base64_encode($inner_aes_key);
2618 $inner_iv = random_string(16);
2619 $b_inner_iv = base64_encode($inner_iv);
2621 $outer_aes_key = random_string(32);
2622 $b_outer_aes_key = base64_encode($outer_aes_key);
2623 $outer_iv = random_string(16);
2624 $b_outer_iv = base64_encode($outer_iv);
2626 $handle = self::my_handle($user);
2628 $padded_data = pkcs5_pad($msg,16);
2629 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2631 $b64_data = base64_encode($inner_encrypted);
2634 $b64url_data = base64url_encode($b64_data);
2635 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2637 $type = "application/xml";
2638 $encoding = "base64url";
2639 $alg = "RSA-SHA256";
2641 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2643 $signature = rsa_sign($signable_data,$prvkey);
2644 $sig = base64url_encode($signature);
2646 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2647 "aes_key" => $b_inner_aes_key,
2648 "author_id" => $handle));
2650 $decrypted_header = xml::from_array($xmldata, $xml, true);
2651 $decrypted_header = pkcs5_pad($decrypted_header,16);
2653 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2655 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2657 $encrypted_outer_key_bundle = "";
2658 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2660 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2662 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2664 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2665 "ciphertext" => base64_encode($ciphertext)));
2666 $cipher_json = base64_encode($encrypted_header_json_object);
2668 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2669 "me:env" => array("me:encoding" => $encoding,
2672 "@attributes" => array("type" => $type),
2673 "me:sig" => $sig)));
2675 $namespaces = array("" => "https://joindiaspora.com/protocol",
2676 "me" => "http://salmon-protocol.org/ns/magic-env");
2678 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2680 logger("magic_env: ".$magic_env, LOGGER_DATA);
2685 * @brief Create the envelope for a message
2687 * @param string $msg The message that is to be transmitted
2688 * @param array $user The record of the sender
2689 * @param array $contact Target of the communication
2690 * @param string $prvkey The private key of the sender
2691 * @param string $pubkey The public key of the receiver
2692 * @param bool $public Is the message public?
2694 * @return string The message that will be transmitted to other servers
2696 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2699 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2701 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2703 // The data that will be transmitted is double encoded via "urlencode", strange ...
2704 $slap = "xml=".urlencode(urlencode($magic_env));
2709 * @brief Creates a signature for a message
2711 * @param array $owner the array of the owner of the message
2712 * @param array $message The message that is to be signed
2714 * @return string The signature
2716 private static function signature($owner, $message) {
2718 unset($sigmsg["author_signature"]);
2719 unset($sigmsg["parent_author_signature"]);
2721 $signed_text = implode(";", $sigmsg);
2723 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2727 * @brief Transmit a message to a target server
2729 * @param array $owner the array of the item owner
2730 * @param array $contact Target of the communication
2731 * @param string $slap The message that is to be transmitted
2732 * @param bool $public_batch Is it a public post?
2733 * @param bool $queue_run Is the transmission called from the queue?
2734 * @param string $guid message guid
2736 * @return int Result of the transmission
2738 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2742 $enabled = intval(get_config("system", "diaspora_enabled"));
2746 $logid = random_string(4);
2747 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2749 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2753 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2755 if (!$queue_run && was_recently_delayed($contact["id"])) {
2758 if (!intval(get_config("system", "diaspora_test"))) {
2759 post_url($dest_url."/", $slap);
2760 $return_code = $a->get_curl_code();
2762 logger("test_mode");
2767 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2769 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2770 logger("queue message");
2772 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2773 intval($contact["id"]),
2774 dbesc(NETWORK_DIASPORA),
2776 intval($public_batch)
2779 logger("add_to_queue ignored - identical item already in queue");
2781 // queue message for redelivery
2782 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2784 // The message could not be delivered. We mark the contact as "dead"
2785 mark_for_death($contact);
2787 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2788 // We successfully delivered a message, the contact is alive
2789 unmark_for_death($contact);
2792 return(($return_code) ? $return_code : (-1));
2797 * @brief Build the post xml
2799 * @param string $type The message type
2800 * @param array $message The message data
2802 * @return string The post XML
2804 public static function build_post_xml($type, $message) {
2806 $data = array("XML" => array("post" => array($type => $message)));
2807 return xml::from_array($data, $xml);
2811 * @brief Builds and transmit messages
2813 * @param array $owner the array of the item owner
2814 * @param array $contact Target of the communication
2815 * @param string $type The message type
2816 * @param array $message The message data
2817 * @param bool $public_batch Is it a public post?
2818 * @param string $guid message guid
2819 * @param bool $spool Should the transmission be spooled or transmitted?
2821 * @return int Result of the transmission
2823 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2825 $msg = self::build_post_xml($type, $message);
2827 logger('message: '.$msg, LOGGER_DATA);
2828 logger('send guid '.$guid, LOGGER_DEBUG);
2830 // Fallback if the private key wasn't transmitted in the expected field
2831 if ($owner['uprvkey'] == "")
2832 $owner['uprvkey'] = $owner['prvkey'];
2834 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2837 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2840 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2842 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2844 return $return_code;
2848 * @brief Sends a "share" message
2850 * @param array $owner the array of the item owner
2851 * @param array $contact Target of the communication
2853 * @return int The result of the transmission
2855 public static function send_share($owner,$contact) {
2857 $message = array("sender_handle" => self::my_handle($owner),
2858 "recipient_handle" => $contact["addr"]);
2860 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2862 return self::build_and_transmit($owner, $contact, "request", $message);
2866 * @brief sends an "unshare"
2868 * @param array $owner the array of the item owner
2869 * @param array $contact Target of the communication
2871 * @return int The result of the transmission
2873 public static function send_unshare($owner,$contact) {
2875 $message = array("post_guid" => $owner["guid"],
2876 "diaspora_handle" => self::my_handle($owner),
2877 "type" => "Person");
2879 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2881 return self::build_and_transmit($owner, $contact, "retraction", $message);
2885 * @brief Checks a message body if it is a reshare
2887 * @param string $body The message body that is to be check
2888 * @param bool $complete Should it be a complete check or a simple check?
2890 * @return array|bool Reshare details or "false" if no reshare
2892 public static function is_reshare($body, $complete = true) {
2893 $body = trim($body);
2895 // Skip if it isn't a pure repeated messages
2896 // Does it start with a share?
2897 if ((strpos($body, "[share") > 0) AND $complete)
2900 // Does it end with a share?
2901 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2904 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2905 // Skip if there is no shared message in there
2906 if ($body == $attributes)
2909 // If we don't do the complete check we quit here
2914 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2915 if ($matches[1] != "")
2916 $guid = $matches[1];
2918 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2919 if ($matches[1] != "")
2920 $guid = $matches[1];
2923 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2924 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2927 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2928 $ret["root_guid"] = $guid;
2934 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2935 if ($matches[1] != "")
2936 $profile = $matches[1];
2938 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2939 if ($matches[1] != "")
2940 $profile = $matches[1];
2944 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2945 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2949 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2950 if ($matches[1] != "")
2951 $link = $matches[1];
2953 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2954 if ($matches[1] != "")
2955 $link = $matches[1];
2957 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2958 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2965 * @brief Create an event array
2967 * @param integer $event_id The id of the event
2969 * @return array with event data
2971 private static function build_event($event_id) {
2973 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
2974 if (!dbm::is_result($r)) {
2980 $eventdata = array();
2982 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
2983 if (!dbm::is_result($r)) {
2989 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
2990 if (!dbm::is_result($r)) {
2996 $eventdata['author'] = self::my_handle($owner);
2998 if ($event['guid']) {
2999 $eventdata['guid'] = $event['guid'];
3002 $mask = 'Y-m-d\TH:i:s\Z';
3004 /// @todo - establish "all day" events in Friendica
3005 $eventdata["all_day"] = "false";
3007 if (!$event['adjust']) {
3008 $eventdata['timezone'] = $user['timezone'];
3010 if ($eventdata['timezone'] == "") {
3011 $eventdata['timezone'] = 'UTC';
3015 if ($event['start']) {
3016 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3018 if ($event['finish'] AND !$event['nofinish']) {
3019 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3021 if ($event['summary']) {
3022 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3024 if ($event['desc']) {
3025 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3027 if ($event['location']) {
3028 $location = array();
3029 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3030 $location["lat"] = 0;
3031 $location["lng"] = 0;
3032 $eventdata['location'] = $location;
3039 * @brief Create a post (status message or reshare)
3041 * @param array $item The item that will be exported
3042 * @param array $owner the array of the item owner
3045 * 'type' -> Message type ("status_message" or "reshare")
3046 * 'message' -> Array of XML elements of the status
3048 public static function build_status($item, $owner) {
3050 $cachekey = "diaspora:build_status:".$item['guid'];
3052 $result = Cache::get($cachekey);
3053 if (!is_null($result)) {
3057 $myaddr = self::my_handle($owner);
3059 $public = (($item["private"]) ? "false" : "true");
3061 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3063 // Detect a share element and do a reshare
3064 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3065 $message = array("root_diaspora_id" => $ret["root_handle"],
3066 "root_guid" => $ret["root_guid"],
3067 "guid" => $item["guid"],
3068 "diaspora_handle" => $myaddr,
3069 "public" => $public,
3070 "created_at" => $created,
3071 "provider_display_name" => $item["app"]);
3075 $title = $item["title"];
3076 $body = $item["body"];
3078 // convert to markdown
3079 $body = html_entity_decode(bb2diaspora($body));
3083 $body = "## ".html_entity_decode($title)."\n\n".$body;
3085 if ($item["attach"]) {
3086 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3088 $body .= "\n".t("Attachments:")."\n";
3089 foreach($matches as $mtch)
3090 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3094 $location = array();
3096 if ($item["location"] != "")
3097 $location["address"] = $item["location"];
3099 if ($item["coord"] != "") {
3100 $coord = explode(" ", $item["coord"]);
3101 $location["lat"] = $coord[0];
3102 $location["lng"] = $coord[1];
3105 $message = array("raw_message" => $body,
3106 "location" => $location,
3107 "guid" => $item["guid"],
3108 "diaspora_handle" => $myaddr,
3109 "public" => $public,
3110 "created_at" => $created,
3111 "provider_display_name" => $item["app"]);
3113 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3114 if (!isset($location["lat"]) OR !isset($location["lng"])) {
3115 unset($message["location"]);
3118 if ($item['event-id'] > 0) {
3119 $event = self::build_event($item['event-id']);
3120 if (count($event)) {
3121 $message['event'] = $event;
3123 /// @todo Once Diaspora supports it, we will remove the body
3124 // $message['raw_message'] = '';
3128 $type = "status_message";
3131 $msg = array("type" => $type, "message" => $message);
3133 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3139 * @brief Sends a post
3141 * @param array $item The item that will be exported
3142 * @param array $owner the array of the item owner
3143 * @param array $contact Target of the communication
3144 * @param bool $public_batch Is it a public post?
3146 * @return int The result of the transmission
3148 public static function send_status($item, $owner, $contact, $public_batch = false) {
3150 $status = self::build_status($item, $owner);
3152 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3156 * @brief Creates a "like" object
3158 * @param array $item The item that will be exported
3159 * @param array $owner the array of the item owner
3161 * @return array The data for a "like"
3163 private static function construct_like($item, $owner) {
3165 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3166 dbesc($item["thr-parent"]));
3167 if (!dbm::is_result($p))
3172 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3173 if ($item['verb'] === ACTIVITY_LIKE) {
3175 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3176 $positive = "false";
3179 return(array("positive" => $positive,
3180 "guid" => $item["guid"],
3181 "target_type" => $target_type,
3182 "parent_guid" => $parent["guid"],
3183 "author_signature" => "",
3184 "diaspora_handle" => self::my_handle($owner)));
3188 * @brief Creates an "EventParticipation" object
3190 * @param array $item The item that will be exported
3191 * @param array $owner the array of the item owner
3193 * @return array The data for an "EventParticipation"
3195 private static function construct_attend($item, $owner) {
3197 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3198 dbesc($item["thr-parent"]));
3199 if (!dbm::is_result($p))
3204 switch ($item['verb']) {
3205 case ACTIVITY_ATTEND:
3206 $attend_answer = 'accepted';
3208 case ACTIVITY_ATTENDNO:
3209 $attend_answer = 'declined';
3211 case ACTIVITY_ATTENDMAYBE:
3212 $attend_answer = 'tentative';
3215 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3219 return(array("author" => self::my_handle($owner),
3220 "guid" => $item["guid"],
3221 "parent_guid" => $parent["guid"],
3222 "status" => $attend_answer,
3223 "author_signature" => ""));
3227 * @brief Creates the object for a comment
3229 * @param array $item The item that will be exported
3230 * @param array $owner the array of the item owner
3232 * @return array The data for a comment
3234 private static function construct_comment($item, $owner) {
3236 $cachekey = "diaspora:construct_comment:".$item['guid'];
3238 $result = Cache::get($cachekey);
3239 if (!is_null($result)) {
3243 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3244 intval($item["parent"]),
3245 intval($item["parent"])
3248 if (!dbm::is_result($p))
3253 $text = html_entity_decode(bb2diaspora($item["body"]));
3254 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3256 $comment = array("guid" => $item["guid"],
3257 "parent_guid" => $parent["guid"],
3258 "author_signature" => "",
3260 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3261 "diaspora_handle" => self::my_handle($owner));
3263 // Send the thread parent guid only if it is a threaded comment
3264 if ($item['thr-parent'] != $item['parent-uri']) {
3265 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3268 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3274 * @brief Send a like or a comment
3276 * @param array $item The item that will be exported
3277 * @param array $owner the array of the item owner
3278 * @param array $contact Target of the communication
3279 * @param bool $public_batch Is it a public post?
3281 * @return int The result of the transmission
3283 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3285 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3286 $message = self::construct_attend($item, $owner);
3287 $type = "event_participation";
3288 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3289 $message = self::construct_like($item, $owner);
3292 $message = self::construct_comment($item, $owner);
3299 $message["author_signature"] = self::signature($owner, $message);
3301 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3305 * @brief Creates a message from a signature record entry
3307 * @param array $item The item that will be exported
3308 * @param array $signature The entry of the "sign" record
3310 * @return string The message
3312 private static function message_from_signature($item, $signature) {
3314 // Split the signed text
3315 $signed_parts = explode(";", $signature['signed_text']);
3317 if ($item["deleted"])
3318 $message = array("parent_author_signature" => "",
3319 "target_guid" => $signed_parts[0],
3320 "target_type" => $signed_parts[1],
3321 "sender_handle" => $signature['signer'],
3322 "target_author_signature" => $signature['signature']);
3323 elseif ($item['verb'] === ACTIVITY_LIKE)
3324 $message = array("positive" => $signed_parts[0],
3325 "guid" => $signed_parts[1],
3326 "target_type" => $signed_parts[2],
3327 "parent_guid" => $signed_parts[3],
3328 "parent_author_signature" => "",
3329 "author_signature" => $signature['signature'],
3330 "diaspora_handle" => $signed_parts[4]);
3332 // Remove the comment guid
3333 $guid = array_shift($signed_parts);
3335 // Remove the parent guid
3336 $parent_guid = array_shift($signed_parts);
3338 // Remove the handle
3339 $handle = array_pop($signed_parts);
3341 // Glue the parts together
3342 $text = implode(";", $signed_parts);
3344 $message = array("guid" => $guid,
3345 "parent_guid" => $parent_guid,
3346 "parent_author_signature" => "",
3347 "author_signature" => $signature['signature'],
3348 "text" => implode(";", $signed_parts),
3349 "diaspora_handle" => $handle);
3355 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3357 * @param array $item The item that will be exported
3358 * @param array $owner the array of the item owner
3359 * @param array $contact Target of the communication
3360 * @param bool $public_batch Is it a public post?
3362 * @return int The result of the transmission
3364 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3366 if ($item["deleted"])
3367 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3368 elseif ($item['verb'] === ACTIVITY_LIKE)
3373 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3375 // fetch the original signature
3377 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3378 intval($item["id"]));
3381 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3387 // Old way - is used by the internal Friendica functions
3388 /// @todo Change all signatur storing functions to the new format
3389 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3390 $message = self::message_from_signature($item, $signature);
3392 $msg = json_decode($signature['signed_text'], true);
3395 if (is_array($msg)) {
3396 foreach ($msg AS $field => $data) {
3397 if (!$item["deleted"]) {
3398 if ($field == "author")
3399 $field = "diaspora_handle";
3400 if ($field == "parent_type")
3401 $field = "target_type";
3404 $message[$field] = $data;
3407 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3410 $message["parent_author_signature"] = self::signature($owner, $message);
3412 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3414 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3418 * @brief Sends a retraction (deletion) of a message, like or comment
3420 * @param array $item The item that will be exported
3421 * @param array $owner the array of the item owner
3422 * @param array $contact Target of the communication
3423 * @param bool $public_batch Is it a public post?
3424 * @param bool $relay Is the retraction transmitted from a relay?
3426 * @return int The result of the transmission
3428 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3430 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3432 // Check whether the retraction is for a top-level post or whether it's a relayable
3433 if ($item["uri"] !== $item["parent-uri"]) {
3434 $msg_type = "relayable_retraction";
3435 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3437 $msg_type = "signed_retraction";
3438 $target_type = "StatusMessage";
3441 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3442 $signature = "parent_author_signature";
3444 $signature = "target_author_signature";
3446 $signed_text = $item["guid"].";".$target_type;
3448 $message = array("target_guid" => $item['guid'],
3449 "target_type" => $target_type,
3450 "sender_handle" => $itemaddr,
3451 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3453 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3455 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3459 * @brief Sends a mail
3461 * @param array $item The item that will be exported
3462 * @param array $owner The owner
3463 * @param array $contact Target of the communication
3465 * @return int The result of the transmission
3467 public static function send_mail($item, $owner, $contact) {
3469 $myaddr = self::my_handle($owner);
3471 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3472 intval($item["convid"]),
3473 intval($item["uid"])
3476 if (!dbm::is_result($r)) {
3477 logger("conversation not found.");
3483 "guid" => $cnv["guid"],
3484 "subject" => $cnv["subject"],
3485 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3486 "diaspora_handle" => $cnv["creator"],
3487 "participant_handles" => $cnv["recips"]
3490 $body = bb2diaspora($item["body"]);
3491 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3493 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3494 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3497 "guid" => $item["guid"],
3498 "parent_guid" => $cnv["guid"],
3499 "parent_author_signature" => $sig,
3500 "author_signature" => $sig,
3502 "created_at" => $created,
3503 "diaspora_handle" => $myaddr,
3504 "conversation_guid" => $cnv["guid"]
3507 if ($item["reply"]) {
3511 $message = array("guid" => $cnv["guid"],
3512 "subject" => $cnv["subject"],
3513 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3515 "diaspora_handle" => $cnv["creator"],
3516 "participant_handles" => $cnv["recips"]);
3518 $type = "conversation";
3521 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3525 * @brief Sends profile data
3527 * @param int $uid The user id
3529 public static function send_profile($uid, $recips = false) {
3535 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3536 AND `uid` = %d AND `rel` != %d",
3537 dbesc(NETWORK_DIASPORA),
3539 intval(CONTACT_IS_SHARING)
3544 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3546 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3547 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3548 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3557 $handle = $profile["addr"];
3558 $first = ((strpos($profile['name'],' ')
3559 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3560 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3561 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3562 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3563 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3564 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3566 if ($searchable === 'true') {
3567 $dob = '1000-00-00';
3569 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3570 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3572 $about = $profile['about'];
3573 $about = strip_tags(bbcode($about));
3575 $location = formatted_location($profile);
3577 if ($profile['pub_keywords']) {
3578 $kw = str_replace(',',' ',$profile['pub_keywords']);
3579 $kw = str_replace(' ',' ',$kw);
3580 $arr = explode(' ',$profile['pub_keywords']);
3582 for($x = 0; $x < 5; $x ++) {
3584 $tags .= '#'. trim($arr[$x]) .' ';
3588 $tags = trim($tags);
3591 $message = array("diaspora_handle" => $handle,
3592 "first_name" => $first,
3593 "last_name" => $last,
3594 "image_url" => $large,
3595 "image_url_medium" => $medium,
3596 "image_url_small" => $small,
3598 "gender" => $profile['gender'],
3600 "location" => $location,
3601 "searchable" => $searchable,
3602 "tag_string" => $tags);
3604 foreach($recips as $recip) {
3605 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3606 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3611 * @brief Stores the signature for likes that are created on our system
3613 * @param array $contact The contact array of the "like"
3614 * @param int $post_id The post id of the "like"
3616 * @return bool Success
3618 public static function store_like_signature($contact, $post_id) {
3620 // Is the contact the owner? Then fetch the private key
3621 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3622 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3626 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3630 $contact["uprvkey"] = $r[0]['prvkey'];
3632 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3636 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3639 $message = self::construct_like($r[0], $contact);
3640 $message["author_signature"] = self::signature($contact, $message);
3642 // We now store the signature more flexible to dynamically support new fields.
3643 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3644 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3645 intval($message_id),
3646 dbesc(json_encode($message))
3649 logger('Stored diaspora like signature');
3654 * @brief Stores the signature for comments that are created on our system
3656 * @param array $item The item array of the comment
3657 * @param array $contact The contact array of the item owner
3658 * @param string $uprvkey The private key of the sender
3659 * @param int $message_id The message id of the comment
3661 * @return bool Success
3663 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3665 if ($uprvkey == "") {
3666 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3670 $contact["uprvkey"] = $uprvkey;
3672 $message = self::construct_comment($item, $contact);
3673 $message["author_signature"] = self::signature($contact, $message);
3675 // We now store the signature more flexible to dynamically support new fields.
3676 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3677 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3678 intval($message_id),
3679 dbesc(json_encode($message))
3682 logger('Stored diaspora comment signature');