3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * Currently this implementation here interprets the old and the new protocol and sends the old one.
8 * This will change in the future.
11 use \Friendica\Core\Config;
13 require_once 'include/items.php';
14 require_once 'include/bb2diaspora.php';
15 require_once 'include/Scrape.php';
16 require_once 'include/Contact.php';
17 require_once 'include/Photo.php';
18 require_once 'include/socgraph.php';
19 require_once 'include/group.php';
20 require_once 'include/xml.php';
21 require_once 'include/datetime.php';
22 require_once 'include/queue_fn.php';
23 require_once 'include/cache.php';
26 * @brief This class contain functions to create and send Diaspora XML files
32 * @brief Return a list of relay servers
34 * This is an experimental Diaspora feature.
36 * @return array of relay servers
38 public static function relay_list() {
40 $serverdata = get_config("system", "relay_server");
41 if ($serverdata == "")
46 $servers = explode(",", $serverdata);
48 foreach ($servers AS $server) {
49 $server = trim($server);
50 $addr = "relay@".str_replace("http://", "", normalise_link($server));
51 $batch = $server."/receive/public";
53 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
54 dbesc($batch), dbesc($addr), dbesc(normalise_link($server)));
57 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
58 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
63 dbesc(normalise_link($server)),
65 dbesc(NETWORK_DIASPORA),
66 intval(CONTACT_IS_FOLLOWER),
67 dbesc(datetime_convert()),
68 dbesc(datetime_convert()),
69 dbesc(datetime_convert())
72 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
74 $relay[] = $relais[0];
76 $relay[] = $relais[0];
83 * @brief repairs a signature that was double encoded
85 * The function is unused at the moment. It was copied from the old implementation.
87 * @param string $signature The signature
88 * @param string $handle The handle of the signature owner
89 * @param integer $level This value is only set inside this function to avoid endless loops
91 * @return string the repaired signature
93 private static function repair_signature($signature, $handle = "", $level = 1) {
98 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
99 $signature = base64_decode($signature);
100 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
102 // Do a recursive call to be able to fix even multiple levels
104 $signature = self::repair_signature($signature, $handle, ++$level);
111 * @brief verify the envelope and return the verified data
113 * @param string $envelope The magic envelope
115 * @return string verified data
117 private static function verify_magic_envelope($envelope) {
119 $basedom = parse_xml_string($envelope, false);
121 if (!is_object($basedom)) {
122 logger("Envelope is no XML file");
126 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
128 if (sizeof($children) == 0) {
129 logger("XML has no children");
135 $data = base64url_decode($children->data);
136 $type = $children->data->attributes()->type[0];
138 $encoding = $children->encoding;
140 $alg = $children->alg;
142 $sig = base64url_decode($children->sig);
143 $key_id = $children->sig->attributes()->key_id[0];
145 $handle = base64url_decode($key_id);
147 $b64url_data = base64url_encode($data);
148 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
150 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
152 $key = self::key($handle);
154 $verify = rsa_verify($signable_data, $sig, $key);
156 logger('Message did not verify. Discarding.');
164 * @brief encrypts data via AES
166 * @param string $key The AES key
167 * @param string $iv The IV (is used for CBC encoding)
168 * @param string $data The data that is to be encrypted
170 * @return string encrypted data
172 private static function aes_encrypt($key, $iv, $data) {
173 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
177 * @brief decrypts data via AES
179 * @param string $key The AES key
180 * @param string $iv The IV (is used for CBC encoding)
181 * @param string $encrypted The encrypted data
183 * @return string decrypted data
185 private static function aes_decrypt($key, $iv, $encrypted) {
186 return openssl_decrypt($encrypted,'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA,str_pad($iv, 16, "\0"));
190 * @brief: Decodes incoming Diaspora message
192 * @param array $importer Array of the importer user
193 * @param string $xml urldecoded Diaspora salmon
196 * 'message' -> decoded Diaspora XML message
197 * 'author' -> author diaspora handle
198 * 'key' -> author public key (converted to pkcs#8)
200 public static function decode($importer, $xml) {
203 $basedom = parse_xml_string($xml);
205 if (!is_object($basedom))
208 $children = $basedom->children('https://joindiaspora.com/protocol');
210 if ($children->header) {
212 $author_link = str_replace('acct:','',$children->header->author_id);
215 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
217 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
218 $ciphertext = base64_decode($encrypted_header->ciphertext);
220 $outer_key_bundle = '';
221 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
223 $j_outer_key_bundle = json_decode($outer_key_bundle);
225 $outer_iv = base64_decode($j_outer_key_bundle->iv);
226 $outer_key = base64_decode($j_outer_key_bundle->key);
228 $decrypted = self::aes_decrypt($outer_key, $outer_iv, $ciphertext);
230 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
231 $idom = parse_xml_string($decrypted,false);
233 $inner_iv = base64_decode($idom->iv);
234 $inner_aes_key = base64_decode($idom->aes_key);
236 $author_link = str_replace('acct:','',$idom->author_id);
239 $dom = $basedom->children(NAMESPACE_SALMON_ME);
241 // figure out where in the DOM tree our data is hiding
243 if ($dom->provenance->data)
244 $base = $dom->provenance;
245 elseif ($dom->env->data)
251 logger('unable to locate salmon data in xml');
252 http_status_exit(400);
256 // Stash the signature away for now. We have to find their key or it won't be good for anything.
257 $signature = base64url_decode($base->sig);
261 // strip whitespace so our data element will return to one big base64 blob
262 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
265 // stash away some other stuff for later
267 $type = $base->data[0]->attributes()->type[0];
268 $keyhash = $base->sig[0]->attributes()->keyhash[0];
269 $encoding = $base->encoding;
273 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
277 $data = base64url_decode($data);
281 $inner_decrypted = $data;
284 // Decode the encrypted blob
286 $inner_encrypted = base64_decode($data);
287 $inner_decrypted = self::aes_decrypt($inner_aes_key, $inner_iv, $inner_encrypted);
291 logger('Could not retrieve author URI.');
292 http_status_exit(400);
294 // Once we have the author URI, go to the web and try to find their public key
295 // (first this will look it up locally if it is in the fcontact cache)
296 // This will also convert diaspora public key from pkcs#1 to pkcs#8
298 logger('Fetching key for '.$author_link);
299 $key = self::key($author_link);
302 logger('Could not retrieve author key.');
303 http_status_exit(400);
306 $verify = rsa_verify($signed_data,$signature,$key);
309 logger('Message did not verify. Discarding.');
310 http_status_exit(400);
313 logger('Message verified.');
315 return array('message' => (string)$inner_decrypted,
316 'author' => unxmlify($author_link),
317 'key' => (string)$key);
322 * @brief Dispatches public messages and find the fitting receivers
324 * @param array $msg The post that will be dispatched
326 * @return int The message id of the generated message, "true" or "false" if there was an error
328 public static function dispatch_public($msg) {
330 $enabled = intval(get_config("system", "diaspora_enabled"));
332 logger("diaspora is disabled");
336 // Now distribute it to the followers
337 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
338 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
339 AND NOT `account_expired` AND NOT `account_removed`",
340 dbesc(NETWORK_DIASPORA),
341 dbesc($msg["author"])
344 if (dbm::is_result($r)) {
345 foreach ($r as $rr) {
346 logger("delivering to: ".$rr["username"]);
347 self::dispatch($rr,$msg);
350 $social_relay = (bool)Config::get('system', 'relay_subscribe', false);
352 // Use a dummy importer to import the data for the public copy
354 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
355 $message_id = self::dispatch($importer,$msg);
357 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
365 * @brief Dispatches the different message types to the different functions
367 * @param array $importer Array of the importer user
368 * @param array $msg The post that will be dispatched
370 * @return int The message id of the generated message, "true" or "false" if there was an error
372 public static function dispatch($importer, $msg) {
374 // The sender is the handle of the contact that sent the message.
375 // This will often be different with relayed messages (for example "like" and "comment")
376 $sender = $msg["author"];
378 if (!self::valid_posting($msg, $fields)) {
379 logger("Invalid posting");
383 $type = $fields->getName();
385 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
388 case "account_deletion":
389 return self::receive_account_deletion($importer, $fields);
392 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
395 return self::receive_contact_request($importer, $fields);
398 return self::receive_conversation($importer, $msg, $fields);
401 return self::receive_like($importer, $sender, $fields);
404 return self::receive_message($importer, $fields);
406 case "participation": // Not implemented
407 return self::receive_participation($importer, $fields);
409 case "photo": // Not implemented
410 return self::receive_photo($importer, $fields);
412 case "poll_participation": // Not implemented
413 return self::receive_poll_participation($importer, $fields);
416 return self::receive_profile($importer, $fields);
419 return self::receive_reshare($importer, $fields, $msg["message"]);
422 return self::receive_retraction($importer, $sender, $fields);
424 case "status_message":
425 return self::receive_status_message($importer, $fields, $msg["message"]);
428 logger("Unknown message type ".$type);
436 * @brief Checks if a posting is valid and fetches the data fields.
438 * This function does not only check the signature.
439 * It also does the conversion between the old and the new diaspora format.
441 * @param array $msg Array with the XML, the sender handle and the sender signature
442 * @param object $fields SimpleXML object that contains the posting when it is valid
444 * @return bool Is the posting valid?
446 private static function valid_posting($msg, &$fields) {
448 $data = parse_xml_string($msg["message"], false);
450 if (!is_object($data)) {
451 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
455 $first_child = $data->getName();
457 // Is this the new or the old version?
458 if ($data->getName() == "XML") {
460 foreach ($data->post->children() as $child)
467 $type = $element->getName();
470 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
472 // All retractions are handled identically from now on.
473 // In the new version there will only be "retraction".
474 if (in_array($type, array("signed_retraction", "relayable_retraction")))
475 $type = "retraction";
477 if ($type == "request")
480 $fields = new SimpleXMLElement("<".$type."/>");
484 foreach ($element->children() AS $fieldname => $entry) {
486 // Translation for the old XML structure
487 if ($fieldname == "diaspora_handle")
488 $fieldname = "author";
490 if ($fieldname == "participant_handles")
491 $fieldname = "participants";
493 if (in_array($type, array("like", "participation"))) {
494 if ($fieldname == "target_type")
495 $fieldname = "parent_type";
498 if ($fieldname == "sender_handle")
499 $fieldname = "author";
501 if ($fieldname == "recipient_handle")
502 $fieldname = "recipient";
504 if ($fieldname == "root_diaspora_id")
505 $fieldname = "root_author";
507 if ($type == "retraction") {
508 if ($fieldname == "post_guid")
509 $fieldname = "target_guid";
511 if ($fieldname == "type")
512 $fieldname = "target_type";
516 if (($fieldname == "author_signature") AND ($entry != ""))
517 $author_signature = base64_decode($entry);
518 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
519 $parent_author_signature = base64_decode($entry);
520 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
521 if ($signed_data != "") {
523 $signed_data_parent .= ";";
526 $signed_data .= $entry;
528 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
529 ($orig_type == "relayable_retraction"))
530 xml::copy($entry, $fields, $fieldname);
533 // This is something that shouldn't happen at all.
534 if (in_array($type, array("status_message", "reshare", "profile")))
535 if ($msg["author"] != $fields->author) {
536 logger("Message handle is not the same as envelope sender. Quitting this message.");
540 // Only some message types have signatures. So we quit here for the other types.
541 if (!in_array($type, array("comment", "message", "like")))
544 // No author_signature? This is a must, so we quit.
545 if (!isset($author_signature)) {
546 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
550 if (isset($parent_author_signature)) {
551 $key = self::key($msg["author"]);
553 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
554 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);
559 $key = self::key($fields->author);
561 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
562 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
569 * @brief Fetches the public key for a given handle
571 * @param string $handle The handle
573 * @return string The public key
575 private static function key($handle) {
576 $handle = strval($handle);
578 logger("Fetching diaspora key for: ".$handle);
580 $r = self::person_by_handle($handle);
588 * @brief Fetches data for a given handle
590 * @param string $handle The handle
592 * @return array the queried data
594 private static function person_by_handle($handle) {
596 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
597 dbesc(NETWORK_DIASPORA),
602 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
604 // update record occasionally so it doesn't get stale
605 $d = strtotime($person["updated"]." +00:00");
606 if ($d < strtotime("now - 14 days"))
609 if ($person["guid"] == "")
613 if (!$person OR $update) {
614 logger("create or refresh", LOGGER_DEBUG);
615 $r = probe_url($handle, PROBE_DIASPORA);
617 // Note that Friendica contacts will return a "Diaspora person"
618 // if Diaspora connectivity is enabled on their server
619 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
620 self::add_fcontact($r, $update);
628 * @brief Updates the fcontact table
630 * @param array $arr The fcontact data
631 * @param bool $update Update or insert?
633 * @return string The id of the fcontact entry
635 private static function add_fcontact($arr, $update = false) {
638 $r = q("UPDATE `fcontact` SET
652 WHERE `url` = '%s' AND `network` = '%s'",
654 dbesc($arr["photo"]),
655 dbesc($arr["request"]),
657 dbesc(strtolower($arr["addr"])),
659 dbesc($arr["batch"]),
660 dbesc($arr["notify"]),
662 dbesc($arr["confirm"]),
663 dbesc($arr["alias"]),
664 dbesc($arr["pubkey"]),
665 dbesc(datetime_convert()),
667 dbesc($arr["network"])
670 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
671 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
672 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
675 dbesc($arr["photo"]),
676 dbesc($arr["request"]),
680 dbesc($arr["batch"]),
681 dbesc($arr["notify"]),
683 dbesc($arr["confirm"]),
684 dbesc($arr["network"]),
685 dbesc($arr["alias"]),
686 dbesc($arr["pubkey"]),
687 dbesc(datetime_convert())
695 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
697 * @param int $contact_id The id in the contact table
698 * @param int $gcontact_id The id in the gcontact table
700 * @return string the handle
702 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
705 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
707 if ($gcontact_id != 0) {
708 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
709 intval($gcontact_id));
711 if (dbm::is_result($r)) {
712 return strtolower($r[0]["addr"]);
716 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
717 intval($contact_id));
719 if (dbm::is_result($r)) {
722 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
724 if ($contact['addr'] != "") {
725 $handle = $contact['addr'];
727 $baseurl_start = strpos($contact['url'],'://') + 3;
728 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
729 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
730 $handle = $contact['nick'].'@'.$baseurl;
734 return strtolower($handle);
738 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
741 * @param mixed $fcontact_guid Hexadecimal string guid
743 * @return string the contact url or null
745 public static function url_from_contact_guid($fcontact_guid) {
746 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
748 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
749 dbesc(NETWORK_DIASPORA),
750 dbesc($fcontact_guid)
753 if (dbm::is_result($r)) {
761 * @brief Get a contact id for a given handle
763 * @param int $uid The user id
764 * @param string $handle The handle in the format user@domain.tld
766 * @return The contact id
768 private static function contact_by_handle($uid, $handle) {
770 // First do a direct search on the contact table
771 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
776 if (dbm::is_result($r)) {
779 // We haven't found it?
780 // We use another function for it that will possibly create a contact entry
781 $cid = get_contact($handle, $uid);
784 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
786 if (dbm::is_result($r)) {
792 $handle_parts = explode("@", $handle);
793 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
794 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
799 if (dbm::is_result($r)) {
803 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
808 * @brief Check if posting is allowed for this contact
810 * @param array $importer Array of the importer user
811 * @param array $contact The contact that is checked
812 * @param bool $is_comment Is the check for a comment?
814 * @return bool is the contact allowed to post?
816 private static function post_allow($importer, $contact, $is_comment = false) {
818 // perhaps we were already sharing with this person. Now they're sharing with us.
819 // That makes us friends.
820 // Normally this should have handled by getting a request - but this could get lost
821 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
822 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
823 intval(CONTACT_IS_FRIEND),
824 intval($contact["id"]),
825 intval($importer["uid"])
827 $contact["rel"] = CONTACT_IS_FRIEND;
828 logger("defining user ".$contact["nick"]." as friend");
831 if (($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
833 if ($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
835 if ($contact["rel"] == CONTACT_IS_FOLLOWER)
836 if (($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
839 // Messages for the global users are always accepted
840 if ($importer["uid"] == 0)
847 * @brief Fetches the contact id for a handle and checks if posting is allowed
849 * @param array $importer Array of the importer user
850 * @param string $handle The checked handle in the format user@domain.tld
851 * @param bool $is_comment Is the check for a comment?
853 * @return array The contact data
855 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
856 $contact = self::contact_by_handle($importer["uid"], $handle);
858 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
862 if (!self::post_allow($importer, $contact, $is_comment)) {
863 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
870 * @brief Does the message already exists on the system?
872 * @param int $uid The user id
873 * @param string $guid The guid of the message
875 * @return int|bool message id if the message already was stored into the system - or false.
877 private static function message_exists($uid, $guid) {
878 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
883 if (dbm::is_result($r)) {
884 logger("message ".$guid." already exists for user ".$uid);
892 * @brief Checks for links to posts in a message
894 * @param array $item The item array
896 private static function fetch_guid($item) {
897 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
898 function ($match) use ($item){
899 return(self::fetch_guid_sub($match, $item));
904 * @brief Checks for relative /people/* links in an item body to match local
905 * contacts or prepends the remote host taken from the author link.
907 * @param string $body The item body to replace links from
908 * @param string $author_link The author link for missing local contact fallback
910 * @return the replaced string
912 public function replace_people_guid($body, $author_link) {
913 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
914 function ($match) use ($author_link) {
916 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
917 // 1 => '0123456789abcdef'
919 $handle = self::url_from_contact_guid($match[1]);
922 $return = '@[url='.$handle.']'.$match[2].'[/url]';
924 // No local match, restoring absolute remote URL from author scheme and host
925 $author_url = parse_url($author_link);
926 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
936 * @brief sub function of "fetch_guid" which checks for links in messages
938 * @param array $match array containing a link that has to be checked for a message link
939 * @param array $item The item array
941 private static function fetch_guid_sub($match, $item) {
942 if (!self::store_by_guid($match[1], $item["author-link"]))
943 self::store_by_guid($match[1], $item["owner-link"]);
947 * @brief Fetches an item with a given guid from a given server
949 * @param string $guid the message guid
950 * @param string $server The server address
951 * @param int $uid The user id of the user
953 * @return int the message id of the stored message or false
955 private static function store_by_guid($guid, $server, $uid = 0) {
956 $serverparts = parse_url($server);
957 $server = $serverparts["scheme"]."://".$serverparts["host"];
959 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
961 $msg = self::message($guid, $server);
966 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
968 // Now call the dispatcher
969 return self::dispatch_public($msg);
973 * @brief Fetches a message from a server
975 * @param string $guid message guid
976 * @param string $server The url of the server
977 * @param int $level Endless loop prevention
980 * 'message' => The message XML
981 * 'author' => The author handle
982 * 'key' => The public key of the author
984 private static function message($guid, $server, $level = 0) {
989 // This will work for new Diaspora servers and Friendica servers from 3.5
990 $source_url = $server."/fetch/post/".$guid;
991 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
993 $envelope = fetch_url($source_url);
995 logger("Envelope was fetched.", LOGGER_DEBUG);
996 $x = self::verify_magic_envelope($envelope);
998 logger("Envelope could not be verified.", LOGGER_DEBUG);
1000 logger("Envelope was verified.", LOGGER_DEBUG);
1004 // This will work for older Diaspora and Friendica servers
1006 $source_url = $server."/p/".$guid.".xml";
1007 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1009 $x = fetch_url($source_url);
1014 $source_xml = parse_xml_string($x, false);
1016 if (!is_object($source_xml))
1019 if ($source_xml->post->reshare) {
1020 // Reshare of a reshare - old Diaspora version
1021 logger("Message is a reshare", LOGGER_DEBUG);
1022 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1023 } elseif ($source_xml->getName() == "reshare") {
1024 // Reshare of a reshare - new Diaspora version
1025 logger("Message is a new reshare", LOGGER_DEBUG);
1026 return self::message($source_xml->root_guid, $server, ++$level);
1031 // Fetch the author - for the old and the new Diaspora version
1032 if ($source_xml->post->status_message->diaspora_handle)
1033 $author = (string)$source_xml->post->status_message->diaspora_handle;
1034 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
1035 $author = (string)$source_xml->author;
1037 // If this isn't a "status_message" then quit
1039 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1043 $msg = array("message" => $x, "author" => $author);
1045 $msg["key"] = self::key($msg["author"]);
1051 * @brief Fetches the item record of a given guid
1053 * @param int $uid The user id
1054 * @param string $guid message guid
1055 * @param string $author The handle of the item
1056 * @param array $contact The contact of the item owner
1058 * @return array the item record
1060 private static function parent_item($uid, $guid, $author, $contact) {
1061 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1062 `author-name`, `author-link`, `author-avatar`,
1063 `owner-name`, `owner-link`, `owner-avatar`
1064 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1065 intval($uid), dbesc($guid));
1068 $result = self::store_by_guid($guid, $contact["url"], $uid);
1071 $person = self::person_by_handle($author);
1072 $result = self::store_by_guid($guid, $person["url"], $uid);
1076 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1078 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1079 `author-name`, `author-link`, `author-avatar`,
1080 `owner-name`, `owner-link`, `owner-avatar`
1081 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1082 intval($uid), dbesc($guid));
1087 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1090 logger("parent item found: parent: ".$guid." - user: ".$uid);
1096 * @brief returns contact details
1098 * @param array $contact The default contact if the person isn't found
1099 * @param array $person The record of the person
1100 * @param int $uid The user id
1103 * 'cid' => contact id
1104 * 'network' => network type
1106 private static function author_contact_by_url($contact, $person, $uid) {
1108 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1109 dbesc(normalise_link($person["url"])), intval($uid));
1112 $network = $r[0]["network"];
1114 // We are receiving content from a user that is about to be terminated
1115 // This means the user is vital, so we remove a possible termination date.
1116 unmark_for_death($contact);
1118 $cid = $contact["id"];
1119 $network = NETWORK_DIASPORA;
1122 return array("cid" => $cid, "network" => $network);
1126 * @brief Is the profile a hubzilla profile?
1128 * @param string $url The profile link
1130 * @return bool is it a hubzilla server?
1132 public static function is_redmatrix($url) {
1133 return(strstr($url, "/channel/"));
1137 * @brief Generate a post link with a given handle and message guid
1139 * @param string $addr The user handle
1140 * @param string $guid message guid
1142 * @return string the post link
1144 private static function plink($addr, $guid) {
1145 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1149 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1151 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1152 // So we try another way as well.
1153 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1155 $r[0]["network"] = $s[0]["network"];
1157 if ($r[0]["network"] == NETWORK_DFRN)
1158 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1160 if (self::is_redmatrix($r[0]["url"]))
1161 return $r[0]["url"]."/?f=&mid=".$guid;
1163 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1167 * @brief Processes an account deletion
1169 * @param array $importer Array of the importer user
1170 * @param object $data The message object
1172 * @return bool Success
1174 private static function receive_account_deletion($importer, $data) {
1176 /// @todo Account deletion should remove the contact from the global contacts as well
1178 $author = notags(unxmlify($data->author));
1180 $contact = self::contact_by_handle($importer["uid"], $author);
1182 logger("cannot find contact for author: ".$author);
1186 // We now remove the contact
1187 contact_remove($contact["id"]);
1192 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1194 * @param string $author Author handle
1195 * @param string $guid Message guid
1196 * @param boolean $onlyfound Only return uri when found in the database
1198 * @return string The constructed uri or the one from our database
1200 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1202 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1203 if (dbm::is_result($r)) {
1204 return $r[0]["uri"];
1205 } elseif (!$onlyfound) {
1206 return $author.":".$guid;
1213 * @brief Fetch the guid from our database with a given uri
1215 * @param string $author Author handle
1216 * @param string $uri Message uri
1218 * @return string The post guid
1220 private static function get_guid_from_uri($uri, $uid) {
1222 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1223 if (dbm::is_result($r)) {
1224 return $r[0]["guid"];
1231 * @brief Processes an incoming comment
1233 * @param array $importer Array of the importer user
1234 * @param string $sender The sender of the message
1235 * @param object $data The message object
1236 * @param string $xml The original XML of the message
1238 * @return int The message id of the generated comment or "false" if there was an error
1240 private static function receive_comment($importer, $sender, $data, $xml) {
1241 $guid = notags(unxmlify($data->guid));
1242 $parent_guid = notags(unxmlify($data->parent_guid));
1243 $text = unxmlify($data->text);
1244 $author = notags(unxmlify($data->author));
1246 if (isset($data->created_at)) {
1247 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1249 $created_at = datetime_convert();
1252 if (isset($data->thread_parent_guid)) {
1253 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1254 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1259 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1264 $message_id = self::message_exists($importer["uid"], $guid);
1269 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1270 if (!$parent_item) {
1274 $person = self::person_by_handle($author);
1275 if (!is_array($person)) {
1276 logger("unable to find author details");
1280 // Fetch the contact id - if we know this contact
1281 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1283 $datarray = array();
1285 $datarray["uid"] = $importer["uid"];
1286 $datarray["contact-id"] = $author_contact["cid"];
1287 $datarray["network"] = $author_contact["network"];
1289 $datarray["author-name"] = $person["name"];
1290 $datarray["author-link"] = $person["url"];
1291 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1293 $datarray["owner-name"] = $contact["name"];
1294 $datarray["owner-link"] = $contact["url"];
1295 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1297 $datarray["guid"] = $guid;
1298 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1300 $datarray["type"] = "remote-comment";
1301 $datarray["verb"] = ACTIVITY_POST;
1302 $datarray["gravity"] = GRAVITY_COMMENT;
1304 if ($thr_uri != "") {
1305 $datarray["parent-uri"] = $thr_uri;
1307 $datarray["parent-uri"] = $parent_item["uri"];
1310 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1312 $datarray["protocol"] = PROTOCOL_DIASPORA;
1313 $datarray["source"] = $xml;
1315 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1317 $body = diaspora2bb($text);
1319 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1321 self::fetch_guid($datarray);
1323 $message_id = item_store($datarray);
1326 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1329 // If we are the origin of the parent we store the original data and notify our followers
1330 if ($message_id AND $parent_item["origin"]) {
1332 // Formerly we stored the signed text, the signature and the author in different fields.
1333 // We now store the raw data so that we are more flexible.
1334 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1335 intval($message_id),
1336 dbesc(json_encode($data))
1340 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1347 * @brief processes and stores private messages
1349 * @param array $importer Array of the importer user
1350 * @param array $contact The contact of the message
1351 * @param object $data The message object
1352 * @param array $msg Array of the processed message, author handle and key
1353 * @param object $mesg The private message
1354 * @param array $conversation The conversation record to which this message belongs
1356 * @return bool "true" if it was successful
1358 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1359 $guid = notags(unxmlify($data->guid));
1360 $subject = notags(unxmlify($data->subject));
1361 $author = notags(unxmlify($data->author));
1363 $msg_guid = notags(unxmlify($mesg->guid));
1364 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1365 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1366 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1367 $msg_text = unxmlify($mesg->text);
1368 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1370 // "diaspora_handle" is the element name from the old version
1371 // "author" is the element name from the new version
1372 if ($mesg->author) {
1373 $msg_author = notags(unxmlify($mesg->author));
1374 } elseif ($mesg->diaspora_handle) {
1375 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1380 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1382 if ($msg_conversation_guid != $guid) {
1383 logger("message conversation guid does not belong to the current conversation.");
1387 $body = diaspora2bb($msg_text);
1388 $message_uri = $msg_author.":".$msg_guid;
1390 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1392 $author_signature = base64_decode($msg_author_signature);
1394 if (strcasecmp($msg_author,$msg["author"]) == 0) {
1398 $person = self::person_by_handle($msg_author);
1400 if (is_array($person) && x($person, "pubkey")) {
1401 $key = $person["pubkey"];
1403 logger("unable to find author details");
1408 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1409 logger("verification failed.");
1413 if ($msg_parent_author_signature) {
1414 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1416 $parent_author_signature = base64_decode($msg_parent_author_signature);
1420 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1421 logger("owner verification failed.");
1426 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1429 if (dbm::is_result($r)) {
1430 logger("duplicate message already delivered.", LOGGER_DEBUG);
1434 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1435 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1436 intval($importer["uid"]),
1438 intval($conversation["id"]),
1439 dbesc($person["name"]),
1440 dbesc($person["photo"]),
1441 dbesc($person["url"]),
1442 intval($contact["id"]),
1447 dbesc($message_uri),
1448 dbesc($author.":".$guid),
1449 dbesc($msg_created_at)
1452 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1453 dbesc(datetime_convert()),
1454 intval($conversation["id"])
1458 "type" => NOTIFY_MAIL,
1459 "notify_flags" => $importer["notify-flags"],
1460 "language" => $importer["language"],
1461 "to_name" => $importer["username"],
1462 "to_email" => $importer["email"],
1463 "uid" =>$importer["uid"],
1464 "item" => array("subject" => $subject, "body" => $body),
1465 "source_name" => $person["name"],
1466 "source_link" => $person["url"],
1467 "source_photo" => $person["thumb"],
1468 "verb" => ACTIVITY_POST,
1475 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1477 * @param array $importer Array of the importer user
1478 * @param array $msg Array of the processed message, author handle and key
1479 * @param object $data The message object
1481 * @return bool Success
1483 private static function receive_conversation($importer, $msg, $data) {
1484 $guid = notags(unxmlify($data->guid));
1485 $subject = notags(unxmlify($data->subject));
1486 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1487 $author = notags(unxmlify($data->author));
1488 $participants = notags(unxmlify($data->participants));
1490 $messages = $data->message;
1492 if (!count($messages)) {
1493 logger("empty conversation");
1497 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1501 $conversation = null;
1503 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1504 intval($importer["uid"]),
1508 $conversation = $c[0];
1510 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1511 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1512 intval($importer["uid"]),
1516 dbesc(datetime_convert()),
1518 dbesc($participants)
1521 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1522 intval($importer["uid"]),
1527 $conversation = $c[0];
1529 if (!$conversation) {
1530 logger("unable to create conversation.");
1534 foreach ($messages as $mesg)
1535 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1541 * @brief Creates the body for a "like" message
1543 * @param array $contact The contact that send us the "like"
1544 * @param array $parent_item The item array of the parent item
1545 * @param string $guid message guid
1547 * @return string the body
1549 private static function construct_like_body($contact, $parent_item, $guid) {
1550 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1552 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1553 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1554 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1556 return sprintf($bodyverb, $ulink, $alink, $plink);
1560 * @brief Creates a XML object for a "like"
1562 * @param array $importer Array of the importer user
1563 * @param array $parent_item The item array of the parent item
1565 * @return string The XML
1567 private static function construct_like_object($importer, $parent_item) {
1568 $objtype = ACTIVITY_OBJ_NOTE;
1569 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1570 $parent_body = $parent_item["body"];
1572 $xmldata = array("object" => array("type" => $objtype,
1574 "id" => $parent_item["uri"],
1577 "content" => $parent_body));
1579 return xml::from_array($xmldata, $xml, true);
1583 * @brief Processes "like" messages
1585 * @param array $importer Array of the importer user
1586 * @param string $sender The sender of the message
1587 * @param object $data The message object
1589 * @return int The message id of the generated like or "false" if there was an error
1591 private static function receive_like($importer, $sender, $data) {
1592 $positive = notags(unxmlify($data->positive));
1593 $guid = notags(unxmlify($data->guid));
1594 $parent_type = notags(unxmlify($data->parent_type));
1595 $parent_guid = notags(unxmlify($data->parent_guid));
1596 $author = notags(unxmlify($data->author));
1598 // likes on comments aren't supported by Diaspora - only on posts
1599 // But maybe this will be supported in the future, so we will accept it.
1600 if (!in_array($parent_type, array("Post", "Comment")))
1603 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1607 $message_id = self::message_exists($importer["uid"], $guid);
1611 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1615 $person = self::person_by_handle($author);
1616 if (!is_array($person)) {
1617 logger("unable to find author details");
1621 // Fetch the contact id - if we know this contact
1622 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1624 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1625 // We would accept this anyhow.
1626 if ($positive == "true")
1627 $verb = ACTIVITY_LIKE;
1629 $verb = ACTIVITY_DISLIKE;
1631 $datarray = array();
1633 $datarray["protocol"] = PROTOCOL_DIASPORA;
1635 $datarray["uid"] = $importer["uid"];
1636 $datarray["contact-id"] = $author_contact["cid"];
1637 $datarray["network"] = $author_contact["network"];
1639 $datarray["author-name"] = $person["name"];
1640 $datarray["author-link"] = $person["url"];
1641 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1643 $datarray["owner-name"] = $contact["name"];
1644 $datarray["owner-link"] = $contact["url"];
1645 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1647 $datarray["guid"] = $guid;
1648 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1650 $datarray["type"] = "activity";
1651 $datarray["verb"] = $verb;
1652 $datarray["gravity"] = GRAVITY_LIKE;
1653 $datarray["parent-uri"] = $parent_item["uri"];
1655 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1656 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1658 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1660 $message_id = item_store($datarray);
1663 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1665 // If we are the origin of the parent we store the original data and notify our followers
1666 if ($message_id AND $parent_item["origin"]) {
1668 // Formerly we stored the signed text, the signature and the author in different fields.
1669 // We now store the raw data so that we are more flexible.
1670 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1671 intval($message_id),
1672 dbesc(json_encode($data))
1676 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1683 * @brief Processes private messages
1685 * @param array $importer Array of the importer user
1686 * @param object $data The message object
1688 * @return bool Success?
1690 private static function receive_message($importer, $data) {
1691 $guid = notags(unxmlify($data->guid));
1692 $parent_guid = notags(unxmlify($data->parent_guid));
1693 $text = unxmlify($data->text);
1694 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1695 $author = notags(unxmlify($data->author));
1696 $conversation_guid = notags(unxmlify($data->conversation_guid));
1698 $contact = self::allowed_contact_by_handle($importer, $author, true);
1703 $conversation = null;
1705 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1706 intval($importer["uid"]),
1707 dbesc($conversation_guid)
1710 $conversation = $c[0];
1712 logger("conversation not available.");
1716 $message_uri = $author.":".$guid;
1718 $person = self::person_by_handle($author);
1720 logger("unable to find author details");
1724 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1725 dbesc($message_uri),
1726 intval($importer["uid"])
1728 if (dbm::is_result($r)) {
1729 logger("duplicate message already delivered.", LOGGER_DEBUG);
1733 $body = diaspora2bb($text);
1735 $body = self::replace_people_guid($body, $person["url"]);
1737 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1738 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1739 intval($importer["uid"]),
1741 intval($conversation["id"]),
1742 dbesc($person["name"]),
1743 dbesc($person["photo"]),
1744 dbesc($person["url"]),
1745 intval($contact["id"]),
1746 dbesc($conversation["subject"]),
1750 dbesc($message_uri),
1751 dbesc($author.":".$parent_guid),
1755 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1756 dbesc(datetime_convert()),
1757 intval($conversation["id"])
1764 * @brief Processes participations - unsupported by now
1766 * @param array $importer Array of the importer user
1767 * @param object $data The message object
1769 * @return bool always true
1771 private static function receive_participation($importer, $data) {
1772 // I'm not sure if we can fully support this message type
1777 * @brief Processes photos - unneeded
1779 * @param array $importer Array of the importer user
1780 * @param object $data The message object
1782 * @return bool always true
1784 private static function receive_photo($importer, $data) {
1785 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1790 * @brief Processes poll participations - unssupported
1792 * @param array $importer Array of the importer user
1793 * @param object $data The message object
1795 * @return bool always true
1797 private static function receive_poll_participation($importer, $data) {
1798 // We don't support polls by now
1803 * @brief Processes incoming profile updates
1805 * @param array $importer Array of the importer user
1806 * @param object $data The message object
1808 * @return bool Success
1810 private static function receive_profile($importer, $data) {
1811 $author = strtolower(notags(unxmlify($data->author)));
1813 $contact = self::contact_by_handle($importer["uid"], $author);
1817 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1818 $image_url = unxmlify($data->image_url);
1819 $birthday = unxmlify($data->birthday);
1820 $location = diaspora2bb(unxmlify($data->location));
1821 $about = diaspora2bb(unxmlify($data->bio));
1822 $gender = unxmlify($data->gender);
1823 $searchable = (unxmlify($data->searchable) == "true");
1824 $nsfw = (unxmlify($data->nsfw) == "true");
1825 $tags = unxmlify($data->tag_string);
1827 $tags = explode("#", $tags);
1829 $keywords = array();
1830 foreach ($tags as $tag) {
1831 $tag = trim(strtolower($tag));
1836 $keywords = implode(", ", $keywords);
1838 $handle_parts = explode("@", $author);
1839 $nick = $handle_parts[0];
1842 $name = $handle_parts[0];
1844 if ( preg_match("|^https?://|", $image_url) === 0)
1845 $image_url = "http://".$handle_parts[1].$image_url;
1847 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1849 // Generic birthday. We don't know the timezone. The year is irrelevant.
1851 $birthday = str_replace("1000", "1901", $birthday);
1853 if ($birthday != "")
1854 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1856 // this is to prevent multiple birthday notifications in a single year
1857 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1859 if (substr($birthday,5) === substr($contact["bd"],5))
1860 $birthday = $contact["bd"];
1862 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1863 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1867 dbesc(datetime_convert()),
1873 intval($contact["id"]),
1874 intval($importer["uid"])
1877 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1878 "photo" => $image_url, "name" => $name, "location" => $location,
1879 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1880 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1881 "hide" => !$searchable, "nsfw" => $nsfw);
1883 $gcid = update_gcontact($gcontact);
1885 link_gcontact($gcid, $importer["uid"], $contact["id"]);
1887 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1893 * @brief Processes incoming friend requests
1895 * @param array $importer Array of the importer user
1896 * @param array $contact The contact that send the request
1898 private static function receive_request_make_friend($importer, $contact) {
1902 if ($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1903 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1904 intval(CONTACT_IS_FRIEND),
1905 intval($contact["id"]),
1906 intval($importer["uid"])
1909 // send notification
1911 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1912 intval($importer["uid"])
1915 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1917 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1918 intval($importer["uid"])
1921 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1923 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1926 $arr["protocol"] = PROTOCOL_DIASPORA;
1927 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1928 $arr["uid"] = $importer["uid"];
1929 $arr["contact-id"] = $self[0]["id"];
1931 $arr["type"] = 'wall';
1932 $arr["gravity"] = 0;
1934 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1935 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1936 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1937 $arr["verb"] = ACTIVITY_FRIEND;
1938 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1940 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1941 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1942 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1943 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1945 $arr["object"] = self::construct_new_friend_object($contact);
1947 $arr["last-child"] = 1;
1949 $arr["allow_cid"] = $user[0]["allow_cid"];
1950 $arr["allow_gid"] = $user[0]["allow_gid"];
1951 $arr["deny_cid"] = $user[0]["deny_cid"];
1952 $arr["deny_gid"] = $user[0]["deny_gid"];
1954 $i = item_store($arr);
1956 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
1962 * @brief Creates a XML object for a "new friend" message
1964 * @param array $contact Array of the contact
1966 * @return string The XML
1968 private static function construct_new_friend_object($contact) {
1969 $objtype = ACTIVITY_OBJ_PERSON;
1970 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1971 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1973 $xmldata = array("object" => array("type" => $objtype,
1974 "title" => $contact["name"],
1975 "id" => $contact["url"]."/".$contact["name"],
1978 return xml::from_array($xmldata, $xml, true);
1982 * @brief Processes incoming sharing notification
1984 * @param array $importer Array of the importer user
1985 * @param object $data The message object
1987 * @return bool Success
1989 private static function receive_contact_request($importer, $data) {
1990 $author = unxmlify($data->author);
1991 $recipient = unxmlify($data->recipient);
1993 if (!$author || !$recipient) {
1997 // the current protocol version doesn't know these fields
1998 // That means that we will assume their existance
1999 if (isset($data->following)) {
2000 $following = (unxmlify($data->following) == "true");
2005 if (isset($data->sharing)) {
2006 $sharing = (unxmlify($data->sharing) == "true");
2011 $contact = self::contact_by_handle($importer["uid"],$author);
2013 // perhaps we were already sharing with this person. Now they're sharing with us.
2014 // That makes us friends.
2016 if ($following AND $sharing) {
2017 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
2018 self::receive_request_make_friend($importer, $contact);
2020 // refetch the contact array
2021 $contact = self::contact_by_handle($importer["uid"],$author);
2023 // If we are now friends, we are sending a share message.
2024 // Normally we needn't to do so, but the first message could have been vanished.
2025 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
2026 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2028 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2029 $ret = self::send_share($u[0], $contact);
2033 } else { /// @todo Handle all possible variations of adding and retracting of permissions
2034 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
2039 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2040 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2042 } elseif (!$following AND !$sharing) {
2043 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2045 } elseif (!$following AND $sharing) {
2046 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2047 } elseif ($following AND $sharing) {
2048 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2049 } elseif ($following AND !$sharing) {
2050 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2053 $ret = self::person_by_handle($author);
2055 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2056 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2060 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2062 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2063 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2064 intval($importer["uid"]),
2065 dbesc($ret["network"]),
2066 dbesc($ret["addr"]),
2069 dbesc(normalise_link($ret["url"])),
2071 dbesc($ret["name"]),
2072 dbesc($ret["nick"]),
2073 dbesc($ret["photo"]),
2074 dbesc($ret["pubkey"]),
2075 dbesc($ret["notify"]),
2076 dbesc($ret["poll"]),
2081 // find the contact record we just created
2083 $contact_record = self::contact_by_handle($importer["uid"],$author);
2085 if (!$contact_record) {
2086 logger("unable to locate newly created contact record.");
2090 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2092 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2094 if (intval($def_gid))
2095 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2097 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2099 if ($importer["page-flags"] == PAGE_NORMAL) {
2101 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2103 $hash = random_string().(string)time(); // Generate a confirm_key
2105 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2106 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2107 intval($importer["uid"]),
2108 intval($contact_record["id"]),
2111 dbesc(t("Sharing notification from Diaspora network")),
2113 dbesc(datetime_convert())
2117 // automatic friend approval
2119 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2121 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2123 // technically they are sharing with us (CONTACT_IS_SHARING),
2124 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2125 // we are going to change the relationship and make them a follower.
2127 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2128 $new_relation = CONTACT_IS_FRIEND;
2129 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2130 $new_relation = CONTACT_IS_SHARING;
2132 $new_relation = CONTACT_IS_FOLLOWER;
2134 $r = q("UPDATE `contact` SET `rel` = %d,
2142 intval($new_relation),
2143 dbesc(datetime_convert()),
2144 dbesc(datetime_convert()),
2145 intval($contact_record["id"])
2148 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2150 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2151 $ret = self::send_share($u[0], $contact_record);
2153 // Send the profile data, maybe it weren't transmitted before
2154 self::send_profile($importer["uid"], array($contact_record));
2162 * @brief Fetches a message with a given guid
2164 * @param string $guid message guid
2165 * @param string $orig_author handle of the original post
2166 * @param string $author handle of the sharer
2168 * @return array The fetched item
2170 private static function original_item($guid, $orig_author, $author) {
2172 // Do we already have this item?
2173 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2174 `author-name`, `author-link`, `author-avatar`
2175 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2178 if (dbm::is_result($r)) {
2179 logger("reshared message ".$guid." already exists on system.");
2181 // Maybe it is already a reshared item?
2182 // Then refetch the content, if it is a reshare from a reshare.
2183 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2184 if (self::is_reshare($r[0]["body"], true)) {
2186 } elseif (self::is_reshare($r[0]["body"], false)) {
2187 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2189 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2191 // Add OEmbed and other information to the body
2192 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2200 if (!dbm::is_result($r)) {
2201 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2202 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2203 $item_id = self::store_by_guid($guid, $server);
2206 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2207 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2208 $item_id = self::store_by_guid($guid, $server);
2212 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2213 `author-name`, `author-link`, `author-avatar`
2214 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2217 if (dbm::is_result($r)) {
2218 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2219 if (self::is_reshare($r[0]["body"], false)) {
2220 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2221 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2233 * @brief Processes a reshare message
2235 * @param array $importer Array of the importer user
2236 * @param object $data The message object
2237 * @param string $xml The original XML of the message
2239 * @return int the message id
2241 private static function receive_reshare($importer, $data, $xml) {
2242 $root_author = notags(unxmlify($data->root_author));
2243 $root_guid = notags(unxmlify($data->root_guid));
2244 $guid = notags(unxmlify($data->guid));
2245 $author = notags(unxmlify($data->author));
2246 $public = notags(unxmlify($data->public));
2247 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2249 $contact = self::allowed_contact_by_handle($importer, $author, false);
2254 $message_id = self::message_exists($importer["uid"], $guid);
2259 $original_item = self::original_item($root_guid, $root_author, $author);
2260 if (!$original_item) {
2264 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2266 $datarray = array();
2268 $datarray["uid"] = $importer["uid"];
2269 $datarray["contact-id"] = $contact["id"];
2270 $datarray["network"] = NETWORK_DIASPORA;
2272 $datarray["author-name"] = $contact["name"];
2273 $datarray["author-link"] = $contact["url"];
2274 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2276 $datarray["owner-name"] = $datarray["author-name"];
2277 $datarray["owner-link"] = $datarray["author-link"];
2278 $datarray["owner-avatar"] = $datarray["author-avatar"];
2280 $datarray["guid"] = $guid;
2281 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2283 $datarray["verb"] = ACTIVITY_POST;
2284 $datarray["gravity"] = GRAVITY_PARENT;
2286 $datarray["protocol"] = PROTOCOL_DIASPORA;
2287 $datarray["source"] = $xml;
2289 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2290 $original_item["guid"], $original_item["created"], $orig_url);
2291 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2293 $datarray["tag"] = $original_item["tag"];
2294 $datarray["app"] = $original_item["app"];
2296 $datarray["plink"] = self::plink($author, $guid);
2297 $datarray["private"] = (($public == "false") ? 1 : 0);
2298 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2300 $datarray["object-type"] = $original_item["object-type"];
2302 self::fetch_guid($datarray);
2303 $message_id = item_store($datarray);
2306 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2313 * @brief Processes retractions
2315 * @param array $importer Array of the importer user
2316 * @param array $contact The contact of the item owner
2317 * @param object $data The message object
2319 * @return bool success
2321 private static function item_retraction($importer, $contact, $data) {
2322 $target_type = notags(unxmlify($data->target_type));
2323 $target_guid = notags(unxmlify($data->target_guid));
2324 $author = notags(unxmlify($data->author));
2326 $person = self::person_by_handle($author);
2327 if (!is_array($person)) {
2328 logger("unable to find author detail for ".$author);
2332 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2333 dbesc($target_guid),
2334 intval($importer["uid"])
2340 // Check if the sender is the thread owner
2341 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2342 intval($r[0]["parent"]));
2344 // Only delete it if the parent author really fits
2345 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2346 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2350 // 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
2351 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2352 dbesc(datetime_convert()),
2353 dbesc(datetime_convert()),
2356 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2358 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2360 // Now check if the retraction needs to be relayed by us
2361 if ($p[0]["origin"]) {
2363 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2370 * @brief Receives retraction messages
2372 * @param array $importer Array of the importer user
2373 * @param string $sender The sender of the message
2374 * @param object $data The message object
2376 * @return bool Success
2378 private static function receive_retraction($importer, $sender, $data) {
2379 $target_type = notags(unxmlify($data->target_type));
2381 $contact = self::contact_by_handle($importer["uid"], $sender);
2383 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2387 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2389 switch ($target_type) {
2392 case "Post": // "Post" will be supported in a future version
2394 case "StatusMessage":
2395 return self::item_retraction($importer, $contact, $data);;
2399 /// @todo What should we do with an "unshare"?
2400 // Removing the contact isn't correct since we still can read the public items
2401 contact_remove($contact["id"]);
2405 logger("Unknown target type ".$target_type);
2412 * @brief Receives status messages
2414 * @param array $importer Array of the importer user
2415 * @param object $data The message object
2416 * @param string $xml The original XML of the message
2418 * @return int The message id of the newly created item
2420 private static function receive_status_message($importer, $data, $xml) {
2421 $raw_message = unxmlify($data->raw_message);
2422 $guid = notags(unxmlify($data->guid));
2423 $author = notags(unxmlify($data->author));
2424 $public = notags(unxmlify($data->public));
2425 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2426 $provider_display_name = notags(unxmlify($data->provider_display_name));
2428 /// @todo enable support for polls
2429 //if ($data->poll) {
2430 // foreach ($data->poll AS $poll)
2434 $contact = self::allowed_contact_by_handle($importer, $author, false);
2439 $message_id = self::message_exists($importer["uid"], $guid);
2445 if ($data->location) {
2446 foreach ($data->location->children() AS $fieldname => $data) {
2447 $address[$fieldname] = notags(unxmlify($data));
2451 $body = diaspora2bb($raw_message);
2453 $datarray = array();
2455 // Attach embedded pictures to the body
2457 foreach ($data->photo AS $photo) {
2458 $body = "[img]".unxmlify($photo->remote_photo_path).
2459 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2462 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2464 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2466 // Add OEmbed and other information to the body
2467 if (!self::is_redmatrix($contact["url"])) {
2468 $body = add_page_info_to_body($body, false, true);
2472 $datarray["uid"] = $importer["uid"];
2473 $datarray["contact-id"] = $contact["id"];
2474 $datarray["network"] = NETWORK_DIASPORA;
2476 $datarray["author-name"] = $contact["name"];
2477 $datarray["author-link"] = $contact["url"];
2478 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2480 $datarray["owner-name"] = $datarray["author-name"];
2481 $datarray["owner-link"] = $datarray["author-link"];
2482 $datarray["owner-avatar"] = $datarray["author-avatar"];
2484 $datarray["guid"] = $guid;
2485 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2487 $datarray["verb"] = ACTIVITY_POST;
2488 $datarray["gravity"] = GRAVITY_PARENT;
2490 $datarray["protocol"] = PROTOCOL_DIASPORA;
2491 $datarray["source"] = $xml;
2493 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2495 if ($provider_display_name != "") {
2496 $datarray["app"] = $provider_display_name;
2499 $datarray["plink"] = self::plink($author, $guid);
2500 $datarray["private"] = (($public == "false") ? 1 : 0);
2501 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2503 if (isset($address["address"])) {
2504 $datarray["location"] = $address["address"];
2507 if (isset($address["lat"]) AND isset($address["lng"])) {
2508 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2511 self::fetch_guid($datarray);
2512 $message_id = item_store($datarray);
2515 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2521 /* ************************************************************************************** *
2522 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2523 * ************************************************************************************** */
2526 * @brief returnes the handle of a contact
2528 * @param array $me contact array
2530 * @return string the handle in the format user@domain.tld
2532 private static function my_handle($contact) {
2533 if ($contact["addr"] != "") {
2534 return $contact["addr"];
2537 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2538 // So - just in case - we build the the address here.
2539 if ($contact["nickname"] != "") {
2540 $nick = $contact["nickname"];
2542 $nick = $contact["nick"];
2545 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2549 * @brief Creates the envelope for the "fetch" endpoint
2551 * @param string $msg The message that is to be transmitted
2552 * @param array $user The record of the sender
2554 * @return string The envelope
2557 public static function build_magic_envelope($msg, $user) {
2559 $b64url_data = base64url_encode($msg);
2560 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2562 $key_id = base64url_encode(self::my_handle($user));
2563 $type = "application/xml";
2564 $encoding = "base64url";
2565 $alg = "RSA-SHA256";
2566 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2567 $signature = rsa_sign($signable_data, $user["prvkey"]);
2568 $sig = base64url_encode($signature);
2570 $xmldata = array("me:env" => array("me:data" => $data,
2571 "@attributes" => array("type" => $type),
2572 "me:encoding" => $encoding,
2575 "@attributes2" => array("key_id" => $key_id)));
2577 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2579 return xml::from_array($xmldata, $xml, false, $namespaces);
2583 * @brief Creates the envelope for a public message
2585 * @param string $msg The message that is to be transmitted
2586 * @param array $user The record of the sender
2587 * @param array $contact Target of the communication
2588 * @param string $prvkey The private key of the sender
2589 * @param string $pubkey The public key of the receiver
2591 * @return string The envelope
2593 private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2595 logger("Message: ".$msg, LOGGER_DATA);
2597 $handle = self::my_handle($user);
2599 $b64url_data = base64url_encode($msg);
2601 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2603 $type = "application/xml";
2604 $encoding = "base64url";
2605 $alg = "RSA-SHA256";
2607 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2609 $signature = rsa_sign($signable_data,$prvkey);
2610 $sig = base64url_encode($signature);
2612 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2613 "me:env" => array("me:encoding" => $encoding,
2616 "@attributes" => array("type" => $type),
2617 "me:sig" => $sig)));
2619 $namespaces = array("" => "https://joindiaspora.com/protocol",
2620 "me" => "http://salmon-protocol.org/ns/magic-env");
2622 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2624 logger("magic_env: ".$magic_env, LOGGER_DATA);
2629 * @brief Creates the envelope for a private message
2631 * @param string $msg The message that is to be transmitted
2632 * @param array $user The record of the sender
2633 * @param array $contact Target of the communication
2634 * @param string $prvkey The private key of the sender
2635 * @param string $pubkey The public key of the receiver
2637 * @return string The envelope
2639 private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2641 logger("Message: ".$msg, LOGGER_DATA);
2643 // without a public key nothing will work
2646 logger("pubkey missing: contact id: ".$contact["id"]);
2650 $inner_aes_key = openssl_random_pseudo_bytes(32);
2651 $b_inner_aes_key = base64_encode($inner_aes_key);
2652 $inner_iv = openssl_random_pseudo_bytes(16);
2653 $b_inner_iv = base64_encode($inner_iv);
2655 $outer_aes_key = openssl_random_pseudo_bytes(32);
2656 $b_outer_aes_key = base64_encode($outer_aes_key);
2657 $outer_iv = openssl_random_pseudo_bytes(16);
2658 $b_outer_iv = base64_encode($outer_iv);
2660 $handle = self::my_handle($user);
2662 $inner_encrypted = self::aes_encrypt($inner_aes_key, $inner_iv, $msg);
2664 $b64_data = base64_encode($inner_encrypted);
2667 $b64url_data = base64url_encode($b64_data);
2668 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2670 $type = "application/xml";
2671 $encoding = "base64url";
2672 $alg = "RSA-SHA256";
2674 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2676 $signature = rsa_sign($signable_data,$prvkey);
2677 $sig = base64url_encode($signature);
2679 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2680 "aes_key" => $b_inner_aes_key,
2681 "author_id" => $handle));
2683 $decrypted_header = xml::from_array($xmldata, $xml, true);
2685 $ciphertext = self::aes_encrypt($outer_aes_key, $outer_iv, $decrypted_header);
2687 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2689 $encrypted_outer_key_bundle = "";
2690 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2692 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2694 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2696 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2697 "ciphertext" => base64_encode($ciphertext)));
2698 $cipher_json = base64_encode($encrypted_header_json_object);
2700 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2701 "me:env" => array("me:encoding" => $encoding,
2704 "@attributes" => array("type" => $type),
2705 "me:sig" => $sig)));
2707 $namespaces = array("" => "https://joindiaspora.com/protocol",
2708 "me" => "http://salmon-protocol.org/ns/magic-env");
2710 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2712 logger("magic_env: ".$magic_env, LOGGER_DATA);
2717 * @brief Create the envelope for a message
2719 * @param string $msg The message that is to be transmitted
2720 * @param array $user The record of the sender
2721 * @param array $contact Target of the communication
2722 * @param string $prvkey The private key of the sender
2723 * @param string $pubkey The public key of the receiver
2724 * @param bool $public Is the message public?
2726 * @return string The message that will be transmitted to other servers
2728 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2731 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2733 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2735 // The data that will be transmitted is double encoded via "urlencode", strange ...
2736 $slap = "xml=".urlencode(urlencode($magic_env));
2741 * @brief Creates a signature for a message
2743 * @param array $owner the array of the owner of the message
2744 * @param array $message The message that is to be signed
2746 * @return string The signature
2748 private static function signature($owner, $message) {
2750 unset($sigmsg["author_signature"]);
2751 unset($sigmsg["parent_author_signature"]);
2753 $signed_text = implode(";", $sigmsg);
2755 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2759 * @brief Transmit a message to a target server
2761 * @param array $owner the array of the item owner
2762 * @param array $contact Target of the communication
2763 * @param string $slap The message that is to be transmitted
2764 * @param bool $public_batch Is it a public post?
2765 * @param bool $queue_run Is the transmission called from the queue?
2766 * @param string $guid message guid
2768 * @return int Result of the transmission
2770 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2774 $enabled = intval(get_config("system", "diaspora_enabled"));
2778 $logid = random_string(4);
2779 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2781 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2785 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2787 if (!$queue_run && was_recently_delayed($contact["id"])) {
2790 if (!intval(get_config("system", "diaspora_test"))) {
2791 post_url($dest_url."/", $slap);
2792 $return_code = $a->get_curl_code();
2794 logger("test_mode");
2799 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2801 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2802 logger("queue message");
2804 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2805 intval($contact["id"]),
2806 dbesc(NETWORK_DIASPORA),
2808 intval($public_batch)
2811 logger("add_to_queue ignored - identical item already in queue");
2813 // queue message for redelivery
2814 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2816 // The message could not be delivered. We mark the contact as "dead"
2817 mark_for_death($contact);
2819 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2820 // We successfully delivered a message, the contact is alive
2821 unmark_for_death($contact);
2824 return(($return_code) ? $return_code : (-1));
2829 * @brief Build the post xml
2831 * @param string $type The message type
2832 * @param array $message The message data
2834 * @return string The post XML
2836 public static function build_post_xml($type, $message) {
2838 $data = array("XML" => array("post" => array($type => $message)));
2839 return xml::from_array($data, $xml);
2843 * @brief Builds and transmit messages
2845 * @param array $owner the array of the item owner
2846 * @param array $contact Target of the communication
2847 * @param string $type The message type
2848 * @param array $message The message data
2849 * @param bool $public_batch Is it a public post?
2850 * @param string $guid message guid
2851 * @param bool $spool Should the transmission be spooled or transmitted?
2853 * @return int Result of the transmission
2855 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2857 $msg = self::build_post_xml($type, $message);
2859 logger('message: '.$msg, LOGGER_DATA);
2860 logger('send guid '.$guid, LOGGER_DEBUG);
2862 // Fallback if the private key wasn't transmitted in the expected field
2863 if ($owner['uprvkey'] == "")
2864 $owner['uprvkey'] = $owner['prvkey'];
2866 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2869 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2872 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2874 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2876 return $return_code;
2880 * @brief Sends a "share" message
2882 * @param array $owner the array of the item owner
2883 * @param array $contact Target of the communication
2885 * @return int The result of the transmission
2887 public static function send_share($owner,$contact) {
2889 $message = array("sender_handle" => self::my_handle($owner),
2890 "recipient_handle" => $contact["addr"]);
2892 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2894 return self::build_and_transmit($owner, $contact, "request", $message);
2898 * @brief sends an "unshare"
2900 * @param array $owner the array of the item owner
2901 * @param array $contact Target of the communication
2903 * @return int The result of the transmission
2905 public static function send_unshare($owner,$contact) {
2907 $message = array("post_guid" => $owner["guid"],
2908 "diaspora_handle" => self::my_handle($owner),
2909 "type" => "Person");
2911 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2913 return self::build_and_transmit($owner, $contact, "retraction", $message);
2917 * @brief Checks a message body if it is a reshare
2919 * @param string $body The message body that is to be check
2920 * @param bool $complete Should it be a complete check or a simple check?
2922 * @return array|bool Reshare details or "false" if no reshare
2924 public static function is_reshare($body, $complete = true) {
2925 $body = trim($body);
2927 // Skip if it isn't a pure repeated messages
2928 // Does it start with a share?
2929 if ((strpos($body, "[share") > 0) AND $complete)
2932 // Does it end with a share?
2933 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2936 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2937 // Skip if there is no shared message in there
2938 if ($body == $attributes)
2941 // If we don't do the complete check we quit here
2946 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2947 if ($matches[1] != "")
2948 $guid = $matches[1];
2950 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2951 if ($matches[1] != "")
2952 $guid = $matches[1];
2955 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2956 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2959 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2960 $ret["root_guid"] = $guid;
2966 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2967 if ($matches[1] != "")
2968 $profile = $matches[1];
2970 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2971 if ($matches[1] != "")
2972 $profile = $matches[1];
2976 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2977 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2981 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2982 if ($matches[1] != "")
2983 $link = $matches[1];
2985 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2986 if ($matches[1] != "")
2987 $link = $matches[1];
2989 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2990 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2997 * @brief Create an event array
2999 * @param integer $event_id The id of the event
3001 * @return array with event data
3003 private static function build_event($event_id) {
3005 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3006 if (!dbm::is_result($r)) {
3012 $eventdata = array();
3014 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3015 if (!dbm::is_result($r)) {
3021 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3022 if (!dbm::is_result($r)) {
3028 $eventdata['author'] = self::my_handle($owner);
3030 if ($event['guid']) {
3031 $eventdata['guid'] = $event['guid'];
3034 $mask = 'Y-m-d\TH:i:s\Z';
3036 /// @todo - establish "all day" events in Friendica
3037 $eventdata["all_day"] = "false";
3039 if (!$event['adjust']) {
3040 $eventdata['timezone'] = $user['timezone'];
3042 if ($eventdata['timezone'] == "") {
3043 $eventdata['timezone'] = 'UTC';
3047 if ($event['start']) {
3048 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3050 if ($event['finish'] AND !$event['nofinish']) {
3051 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3053 if ($event['summary']) {
3054 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3056 if ($event['desc']) {
3057 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3059 if ($event['location']) {
3060 $location = array();
3061 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3062 $location["lat"] = 0;
3063 $location["lng"] = 0;
3064 $eventdata['location'] = $location;
3071 * @brief Create a post (status message or reshare)
3073 * @param array $item The item that will be exported
3074 * @param array $owner the array of the item owner
3077 * 'type' -> Message type ("status_message" or "reshare")
3078 * 'message' -> Array of XML elements of the status
3080 public static function build_status($item, $owner) {
3082 $cachekey = "diaspora:build_status:".$item['guid'];
3084 $result = Cache::get($cachekey);
3085 if (!is_null($result)) {
3089 $myaddr = self::my_handle($owner);
3091 $public = (($item["private"]) ? "false" : "true");
3093 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3095 // Detect a share element and do a reshare
3096 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3097 $message = array("root_diaspora_id" => $ret["root_handle"],
3098 "root_guid" => $ret["root_guid"],
3099 "guid" => $item["guid"],
3100 "diaspora_handle" => $myaddr,
3101 "public" => $public,
3102 "created_at" => $created,
3103 "provider_display_name" => $item["app"]);
3107 $title = $item["title"];
3108 $body = $item["body"];
3110 // convert to markdown
3111 $body = html_entity_decode(bb2diaspora($body));
3115 $body = "## ".html_entity_decode($title)."\n\n".$body;
3117 if ($item["attach"]) {
3118 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3120 $body .= "\n".t("Attachments:")."\n";
3121 foreach ($matches as $mtch)
3122 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3126 $location = array();
3128 if ($item["location"] != "")
3129 $location["address"] = $item["location"];
3131 if ($item["coord"] != "") {
3132 $coord = explode(" ", $item["coord"]);
3133 $location["lat"] = $coord[0];
3134 $location["lng"] = $coord[1];
3137 $message = array("raw_message" => $body,
3138 "location" => $location,
3139 "guid" => $item["guid"],
3140 "diaspora_handle" => $myaddr,
3141 "public" => $public,
3142 "created_at" => $created,
3143 "provider_display_name" => $item["app"]);
3145 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3146 if (!isset($location["lat"]) OR !isset($location["lng"])) {
3147 unset($message["location"]);
3150 if ($item['event-id'] > 0) {
3151 $event = self::build_event($item['event-id']);
3152 if (count($event)) {
3153 $message['event'] = $event;
3155 /// @todo Once Diaspora supports it, we will remove the body
3156 // $message['raw_message'] = '';
3160 $type = "status_message";
3163 $msg = array("type" => $type, "message" => $message);
3165 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3171 * @brief Sends a post
3173 * @param array $item The item that will be exported
3174 * @param array $owner the array of the item owner
3175 * @param array $contact Target of the communication
3176 * @param bool $public_batch Is it a public post?
3178 * @return int The result of the transmission
3180 public static function send_status($item, $owner, $contact, $public_batch = false) {
3182 $status = self::build_status($item, $owner);
3184 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3188 * @brief Creates a "like" 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 a "like"
3195 private static function construct_like($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 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3205 if ($item['verb'] === ACTIVITY_LIKE) {
3207 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3208 $positive = "false";
3211 return(array("positive" => $positive,
3212 "guid" => $item["guid"],
3213 "target_type" => $target_type,
3214 "parent_guid" => $parent["guid"],
3215 "author_signature" => "",
3216 "diaspora_handle" => self::my_handle($owner)));
3220 * @brief Creates an "EventParticipation" object
3222 * @param array $item The item that will be exported
3223 * @param array $owner the array of the item owner
3225 * @return array The data for an "EventParticipation"
3227 private static function construct_attend($item, $owner) {
3229 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3230 dbesc($item["thr-parent"]));
3231 if (!dbm::is_result($p))
3236 switch ($item['verb']) {
3237 case ACTIVITY_ATTEND:
3238 $attend_answer = 'accepted';
3240 case ACTIVITY_ATTENDNO:
3241 $attend_answer = 'declined';
3243 case ACTIVITY_ATTENDMAYBE:
3244 $attend_answer = 'tentative';
3247 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3251 return(array("author" => self::my_handle($owner),
3252 "guid" => $item["guid"],
3253 "parent_guid" => $parent["guid"],
3254 "status" => $attend_answer,
3255 "author_signature" => ""));
3259 * @brief Creates the object for a comment
3261 * @param array $item The item that will be exported
3262 * @param array $owner the array of the item owner
3264 * @return array The data for a comment
3266 private static function construct_comment($item, $owner) {
3268 $cachekey = "diaspora:construct_comment:".$item['guid'];
3270 $result = Cache::get($cachekey);
3271 if (!is_null($result)) {
3275 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3276 intval($item["parent"]),
3277 intval($item["parent"])
3280 if (!dbm::is_result($p))
3285 $text = html_entity_decode(bb2diaspora($item["body"]));
3286 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3288 $comment = array("guid" => $item["guid"],
3289 "parent_guid" => $parent["guid"],
3290 "author_signature" => "",
3292 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3293 "diaspora_handle" => self::my_handle($owner));
3295 // Send the thread parent guid only if it is a threaded comment
3296 if ($item['thr-parent'] != $item['parent-uri']) {
3297 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3300 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3306 * @brief Send a like or a comment
3308 * @param array $item The item that will be exported
3309 * @param array $owner the array of the item owner
3310 * @param array $contact Target of the communication
3311 * @param bool $public_batch Is it a public post?
3313 * @return int The result of the transmission
3315 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3317 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3318 $message = self::construct_attend($item, $owner);
3319 $type = "event_participation";
3320 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3321 $message = self::construct_like($item, $owner);
3324 $message = self::construct_comment($item, $owner);
3331 $message["author_signature"] = self::signature($owner, $message);
3333 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3337 * @brief Creates a message from a signature record entry
3339 * @param array $item The item that will be exported
3340 * @param array $signature The entry of the "sign" record
3342 * @return string The message
3344 private static function message_from_signature($item, $signature) {
3346 // Split the signed text
3347 $signed_parts = explode(";", $signature['signed_text']);
3349 if ($item["deleted"])
3350 $message = array("parent_author_signature" => "",
3351 "target_guid" => $signed_parts[0],
3352 "target_type" => $signed_parts[1],
3353 "sender_handle" => $signature['signer'],
3354 "target_author_signature" => $signature['signature']);
3355 elseif ($item['verb'] === ACTIVITY_LIKE)
3356 $message = array("positive" => $signed_parts[0],
3357 "guid" => $signed_parts[1],
3358 "target_type" => $signed_parts[2],
3359 "parent_guid" => $signed_parts[3],
3360 "parent_author_signature" => "",
3361 "author_signature" => $signature['signature'],
3362 "diaspora_handle" => $signed_parts[4]);
3364 // Remove the comment guid
3365 $guid = array_shift($signed_parts);
3367 // Remove the parent guid
3368 $parent_guid = array_shift($signed_parts);
3370 // Remove the handle
3371 $handle = array_pop($signed_parts);
3373 // Glue the parts together
3374 $text = implode(";", $signed_parts);
3376 $message = array("guid" => $guid,
3377 "parent_guid" => $parent_guid,
3378 "parent_author_signature" => "",
3379 "author_signature" => $signature['signature'],
3380 "text" => implode(";", $signed_parts),
3381 "diaspora_handle" => $handle);
3387 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3389 * @param array $item The item that will be exported
3390 * @param array $owner the array of the item owner
3391 * @param array $contact Target of the communication
3392 * @param bool $public_batch Is it a public post?
3394 * @return int The result of the transmission
3396 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3398 if ($item["deleted"])
3399 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3400 elseif ($item['verb'] === ACTIVITY_LIKE)
3405 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3407 // fetch the original signature
3409 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3410 intval($item["id"]));
3413 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3419 // Old way - is used by the internal Friendica functions
3420 /// @todo Change all signatur storing functions to the new format
3421 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3422 $message = self::message_from_signature($item, $signature);
3424 $msg = json_decode($signature['signed_text'], true);
3427 if (is_array($msg)) {
3428 foreach ($msg AS $field => $data) {
3429 if (!$item["deleted"]) {
3430 if ($field == "author")
3431 $field = "diaspora_handle";
3432 if ($field == "parent_type")
3433 $field = "target_type";
3436 $message[$field] = $data;
3439 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3442 $message["parent_author_signature"] = self::signature($owner, $message);
3444 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3446 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3450 * @brief Sends a retraction (deletion) of a message, like or comment
3452 * @param array $item The item that will be exported
3453 * @param array $owner the array of the item owner
3454 * @param array $contact Target of the communication
3455 * @param bool $public_batch Is it a public post?
3456 * @param bool $relay Is the retraction transmitted from a relay?
3458 * @return int The result of the transmission
3460 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3462 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3464 // Check whether the retraction is for a top-level post or whether it's a relayable
3465 if ($item["uri"] !== $item["parent-uri"]) {
3466 $msg_type = "relayable_retraction";
3467 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3469 $msg_type = "signed_retraction";
3470 $target_type = "StatusMessage";
3473 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3474 $signature = "parent_author_signature";
3476 $signature = "target_author_signature";
3478 $signed_text = $item["guid"].";".$target_type;
3480 $message = array("target_guid" => $item['guid'],
3481 "target_type" => $target_type,
3482 "sender_handle" => $itemaddr,
3483 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3485 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3487 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3491 * @brief Sends a mail
3493 * @param array $item The item that will be exported
3494 * @param array $owner The owner
3495 * @param array $contact Target of the communication
3497 * @return int The result of the transmission
3499 public static function send_mail($item, $owner, $contact) {
3501 $myaddr = self::my_handle($owner);
3503 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3504 intval($item["convid"]),
3505 intval($item["uid"])
3508 if (!dbm::is_result($r)) {
3509 logger("conversation not found.");
3515 "guid" => $cnv["guid"],
3516 "subject" => $cnv["subject"],
3517 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3518 "diaspora_handle" => $cnv["creator"],
3519 "participant_handles" => $cnv["recips"]
3522 $body = bb2diaspora($item["body"]);
3523 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3525 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3526 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3529 "guid" => $item["guid"],
3530 "parent_guid" => $cnv["guid"],
3531 "parent_author_signature" => $sig,
3532 "author_signature" => $sig,
3534 "created_at" => $created,
3535 "diaspora_handle" => $myaddr,
3536 "conversation_guid" => $cnv["guid"]
3539 if ($item["reply"]) {
3543 $message = array("guid" => $cnv["guid"],
3544 "subject" => $cnv["subject"],
3545 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3547 "diaspora_handle" => $cnv["creator"],
3548 "participant_handles" => $cnv["recips"]);
3550 $type = "conversation";
3553 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3557 * @brief Sends profile data
3559 * @param int $uid The user id
3561 public static function send_profile($uid, $recips = false) {
3567 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3568 AND `uid` = %d AND `rel` != %d",
3569 dbesc(NETWORK_DIASPORA),
3571 intval(CONTACT_IS_SHARING)
3576 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3578 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3579 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3580 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3589 $handle = $profile["addr"];
3590 $first = ((strpos($profile['name'],' ')
3591 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3592 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3593 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3594 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3595 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3596 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3598 if ($searchable === 'true') {
3599 $dob = '1000-00-00';
3601 if (($profile['dob']) && ($profile['dob'] > '0001-01-01'))
3602 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3604 $about = $profile['about'];
3605 $about = strip_tags(bbcode($about));
3607 $location = formatted_location($profile);
3609 if ($profile['pub_keywords']) {
3610 $kw = str_replace(',',' ',$profile['pub_keywords']);
3611 $kw = str_replace(' ',' ',$kw);
3612 $arr = explode(' ',$profile['pub_keywords']);
3614 for ($x = 0; $x < 5; $x ++) {
3616 $tags .= '#'. trim($arr[$x]) .' ';
3620 $tags = trim($tags);
3623 $message = array("diaspora_handle" => $handle,
3624 "first_name" => $first,
3625 "last_name" => $last,
3626 "image_url" => $large,
3627 "image_url_medium" => $medium,
3628 "image_url_small" => $small,
3630 "gender" => $profile['gender'],
3632 "location" => $location,
3633 "searchable" => $searchable,
3634 "tag_string" => $tags);
3636 foreach ($recips as $recip) {
3637 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3638 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3643 * @brief Stores the signature for likes that are created on our system
3645 * @param array $contact The contact array of the "like"
3646 * @param int $post_id The post id of the "like"
3648 * @return bool Success
3650 public static function store_like_signature($contact, $post_id) {
3652 // Is the contact the owner? Then fetch the private key
3653 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3654 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3658 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3659 if (!dbm::is_result($r)) {
3663 $contact["uprvkey"] = $r[0]['prvkey'];
3665 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3666 if (!dbm::is_result($r)) {
3670 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3674 $message = self::construct_like($r[0], $contact);
3675 $message["author_signature"] = self::signature($contact, $message);
3677 // We now store the signature more flexible to dynamically support new fields.
3678 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3679 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3680 intval($message_id),
3681 dbesc(json_encode($message))
3684 logger('Stored diaspora like signature');
3689 * @brief Stores the signature for comments that are created on our system
3691 * @param array $item The item array of the comment
3692 * @param array $contact The contact array of the item owner
3693 * @param string $uprvkey The private key of the sender
3694 * @param int $message_id The message id of the comment
3696 * @return bool Success
3698 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3700 if ($uprvkey == "") {
3701 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3705 $contact["uprvkey"] = $uprvkey;
3707 $message = self::construct_comment($item, $contact);
3708 $message["author_signature"] = self::signature($contact, $message);
3710 // We now store the signature more flexible to dynamically support new fields.
3711 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3712 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3713 intval($message_id),
3714 dbesc(json_encode($message))
3717 logger('Stored diaspora comment signature');