3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
13 * - send status retraction
14 * - send comment retraction on own post
15 * - send like retraction on own post
16 * - send comment retraction on diaspora post
17 * - send like retraction on diaspora post
22 * - receive connect request
23 * - receive profile data
25 * - receive comment retraction
26 * - receive like retraction
29 * - relay comment retraction from diaspora
30 * - relay comment retraction from friendica
31 * - relay like retraction from diaspora
32 * - relay like retraction from friendica
36 * - receive account deletion
42 require_once("include/items.php");
43 require_once("include/bb2diaspora.php");
44 require_once("include/Scrape.php");
45 require_once("include/Contact.php");
46 require_once("include/Photo.php");
47 require_once("include/socgraph.php");
48 require_once("include/group.php");
49 require_once("include/xml.php");
50 require_once("include/datetime.php");
51 require_once("include/queue_fn.php");
54 * @brief This class contain functions to create and send Diaspora XML files
60 * @brief Return a list of relay servers
62 * This is an experimental Diaspora feature.
64 * @return array of relay servers
66 public static function relay_list() {
68 $serverdata = get_config("system", "relay_server");
69 if ($serverdata == "")
74 $servers = explode(",", $serverdata);
76 foreach($servers AS $server) {
77 $server = trim($server);
78 $batch = $server."/receive/public";
80 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
83 $addr = "relay@".str_replace("http://", "", normalise_link($server));
85 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
86 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
91 dbesc(normalise_link($server)),
93 dbesc(NETWORK_DIASPORA),
94 intval(CONTACT_IS_FOLLOWER),
95 dbesc(datetime_convert()),
96 dbesc(datetime_convert()),
97 dbesc(datetime_convert())
100 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
102 $relay[] = $relais[0];
104 $relay[] = $relais[0];
111 * @brief repairs a signature that was double encoded
113 * @param string $signature The signature
114 * @param string $handle The handle of the signature owner
115 * @param integer $level This value is only set inside this function to avoid endless loops
117 * @return the repaired signature
119 function repair_signature($signature, $handle = "", $level = 1) {
121 if ($signature == "")
124 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
125 $signature = base64_decode($signature);
126 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
128 // Do a recursive call to be able to fix even multiple levels
130 $signature = self::repair_signature($signature, $handle, ++$level);
137 * @brief: Decodes incoming Diaspora message
139 * @param array $importer Array of the importer user
140 * @param string $xml urldecoded Diaspora salmon
143 * 'message' -> decoded Diaspora XML message
144 * 'author' -> author diaspora handle
145 * 'key' -> author public key (converted to pkcs#8)
147 function decode($importer, $xml) {
150 $basedom = parse_xml_string($xml);
152 if (!is_object($basedom))
155 $children = $basedom->children('https://joindiaspora.com/protocol');
157 if($children->header) {
159 $author_link = str_replace('acct:','',$children->header->author_id);
162 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
164 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
165 $ciphertext = base64_decode($encrypted_header->ciphertext);
167 $outer_key_bundle = '';
168 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
170 $j_outer_key_bundle = json_decode($outer_key_bundle);
172 $outer_iv = base64_decode($j_outer_key_bundle->iv);
173 $outer_key = base64_decode($j_outer_key_bundle->key);
175 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
178 $decrypted = pkcs5_unpad($decrypted);
181 * $decrypted now contains something like
184 * <iv>8e+G2+ET8l5BPuW0sVTnQw==</iv>
185 * <aes_key>UvSMb4puPeB14STkcDWq+4QE302Edu15oaprAQSkLKU=</aes_key>
186 * <author_id>galaxor@diaspora.priateship.org</author_id>
187 * </decrypted_header>
190 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
191 $idom = parse_xml_string($decrypted,false);
193 $inner_iv = base64_decode($idom->iv);
194 $inner_aes_key = base64_decode($idom->aes_key);
196 $author_link = str_replace('acct:','',$idom->author_id);
199 $dom = $basedom->children(NAMESPACE_SALMON_ME);
201 // figure out where in the DOM tree our data is hiding
203 if($dom->provenance->data)
204 $base = $dom->provenance;
205 elseif($dom->env->data)
211 logger('unable to locate salmon data in xml');
212 http_status_exit(400);
216 // Stash the signature away for now. We have to find their key or it won't be good for anything.
217 $signature = base64url_decode($base->sig);
221 // strip whitespace so our data element will return to one big base64 blob
222 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
225 // stash away some other stuff for later
227 $type = $base->data[0]->attributes()->type[0];
228 $keyhash = $base->sig[0]->attributes()->keyhash[0];
229 $encoding = $base->encoding;
233 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
237 $data = base64url_decode($data);
241 $inner_decrypted = $data;
244 // Decode the encrypted blob
246 $inner_encrypted = base64_decode($data);
247 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
248 $inner_decrypted = pkcs5_unpad($inner_decrypted);
252 logger('Could not retrieve author URI.');
253 http_status_exit(400);
255 // Once we have the author URI, go to the web and try to find their public key
256 // (first this will look it up locally if it is in the fcontact cache)
257 // This will also convert diaspora public key from pkcs#1 to pkcs#8
259 logger('Fetching key for '.$author_link);
260 $key = self::key($author_link);
263 logger('Could not retrieve author key.');
264 http_status_exit(400);
267 $verify = rsa_verify($signed_data,$signature,$key);
270 logger('Message did not verify. Discarding.');
271 http_status_exit(400);
274 logger('Message verified.');
276 return array('message' => (string)$inner_decrypted,
277 'author' => unxmlify($author_link),
278 'key' => (string)$key);
284 * @brief Dispatches public messages and find the fitting receivers
286 * @param array $msg The post that will be dispatched
288 * @return bool Was the message accepted?
290 public static function dispatch_public($msg) {
292 $enabled = intval(get_config("system", "diaspora_enabled"));
294 logger("diaspora is disabled");
298 // Use a dummy importer to import the data for the public copy
299 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
300 $item_id = self::dispatch($importer,$msg);
302 // Now distribute it to the followers
303 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
304 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
305 AND NOT `account_expired` AND NOT `account_removed`",
306 dbesc(NETWORK_DIASPORA),
307 dbesc($msg["author"])
311 logger("delivering to: ".$rr["username"]);
312 self::dispatch($rr,$msg);
315 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
321 * @brief Dispatches the different message types to the different functions
323 * @param array $importer Array of the importer user
324 * @param array $msg The post that will be dispatched
326 * @return bool Was the message accepted?
328 public static function dispatch($importer, $msg) {
330 // The sender is the handle of the contact that sent the message.
331 // This will often be different with relayed messages (for example "like" and "comment")
332 $sender = $msg["author"];
334 if (!diaspora::valid_posting($msg, $fields)) {
335 logger("Invalid posting");
339 $type = $fields->getName();
341 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
344 case "account_deletion":
345 return self::receive_account_deletion($importer, $fields);
348 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
351 return self::receive_conversation($importer, $msg, $fields);
354 return self::receive_like($importer, $sender, $fields);
357 return self::receive_message($importer, $fields);
359 case "participation": // Not implemented
360 return self::receive_participation($importer, $fields);
362 case "photo": // Not implemented
363 return self::receive_photo($importer, $fields);
365 case "poll_participation": // Not implemented
366 return self::receive_poll_participation($importer, $fields);
369 return self::receive_profile($importer, $fields);
372 return self::receive_request($importer, $fields);
375 return self::receive_reshare($importer, $fields, $msg["message"]);
378 return self::receive_retraction($importer, $sender, $fields);
380 case "status_message":
381 return self::receive_status_message($importer, $fields, $msg["message"]);
384 logger("Unknown message type ".$type);
392 * @brief Checks if a posting is valid and fetches the data fields.
394 * This function does not only check the signature.
395 * It also does the conversion between the old and the new diaspora format.
397 * @param array $msg Array with the XML, the sender handle and the sender signature
398 * @param object $fields SimpleXML object that contains the posting when it is valid
400 * @return bool Is the posting valid?
402 private function valid_posting($msg, &$fields) {
404 $data = parse_xml_string($msg["message"], false);
406 if (!is_object($data))
409 $first_child = $data->getName();
411 // Is this the new or the old version?
412 if ($data->getName() == "XML") {
414 foreach ($data->post->children() as $child)
421 $type = $element->getName();
424 // All retractions are handled identically from now on.
425 // In the new version there will only be "retraction".
426 if (in_array($type, array("signed_retraction", "relayable_retraction")))
427 $type = "retraction";
429 $fields = new SimpleXMLElement("<".$type."/>");
433 foreach ($element->children() AS $fieldname => $entry) {
435 // Translation for the old XML structure
436 if ($fieldname == "diaspora_handle")
437 $fieldname = "author";
439 if ($fieldname == "participant_handles")
440 $fieldname = "participants";
442 if (in_array($type, array("like", "participation"))) {
443 if ($fieldname == "target_type")
444 $fieldname = "parent_type";
447 if ($fieldname == "sender_handle")
448 $fieldname = "author";
450 if ($fieldname == "recipient_handle")
451 $fieldname = "recipient";
453 if ($fieldname == "root_diaspora_id")
454 $fieldname = "root_author";
456 if ($type == "retraction") {
457 if ($fieldname == "post_guid")
458 $fieldname = "target_guid";
460 if ($fieldname == "type")
461 $fieldname = "target_type";
465 if ($fieldname == "author_signature")
466 $author_signature = base64_decode($entry);
467 elseif ($fieldname == "parent_author_signature")
468 $parent_author_signature = base64_decode($entry);
469 elseif ($fieldname != "target_author_signature") {
470 if ($signed_data != "") {
472 $signed_data_parent .= ";";
475 $signed_data .= $entry;
477 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
478 ($orig_type == "relayable_retraction"))
479 xml::copy($entry, $fields, $fieldname);
482 // This is something that shouldn't happen at all.
483 if (in_array($type, array("status_message", "reshare", "profile")))
484 if ($msg["author"] != $fields->author) {
485 logger("Message handle is not the same as envelope sender. Quitting this message.");
489 // Only some message types have signatures. So we quit here for the other types.
490 if (!in_array($type, array("comment", "message", "like")))
493 // No author_signature? This is a must, so we quit.
494 if (!isset($author_signature))
497 if (isset($parent_author_signature)) {
498 $key = self::key($msg["author"]);
500 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256"))
504 $key = self::key($fields->author);
506 return rsa_verify($signed_data, $author_signature, $key, "sha256");
510 * @brief Fetches the public key for a given handle
512 * @param string $handle The handle
514 * @return string The public key
516 private function key($handle) {
517 $handle = strval($handle);
519 logger("Fetching diaspora key for: ".$handle);
521 $r = self::person_by_handle($handle);
529 * @brief Fetches data for a given handle
531 * @param string $handle The handle
533 * @return array the queried data
535 private function person_by_handle($handle) {
537 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
538 dbesc(NETWORK_DIASPORA),
543 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
545 // update record occasionally so it doesn't get stale
546 $d = strtotime($person["updated"]." +00:00");
547 if ($d < strtotime("now - 14 days"))
551 if (!$person OR $update) {
552 logger("create or refresh", LOGGER_DEBUG);
553 $r = probe_url($handle, PROBE_DIASPORA);
555 // Note that Friendica contacts will return a "Diaspora person"
556 // if Diaspora connectivity is enabled on their server
557 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
558 self::add_fcontact($r, $update);
566 * @brief Updates the fcontact table
568 * @param array $arr The fcontact data
569 * @param bool $update Update or insert?
571 * @return string The id of the fcontact entry
573 private function add_fcontact($arr, $update = false) {
576 $r = q("UPDATE `fcontact` SET
589 WHERE `url` = '%s' AND `network` = '%s'",
591 dbesc($arr["photo"]),
592 dbesc($arr["request"]),
595 dbesc($arr["batch"]),
596 dbesc($arr["notify"]),
598 dbesc($arr["confirm"]),
599 dbesc($arr["alias"]),
600 dbesc($arr["pubkey"]),
601 dbesc(datetime_convert()),
603 dbesc($arr["network"])
606 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`,
607 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
608 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
611 dbesc($arr["photo"]),
612 dbesc($arr["request"]),
615 dbesc($arr["batch"]),
616 dbesc($arr["notify"]),
618 dbesc($arr["confirm"]),
619 dbesc($arr["network"]),
620 dbesc($arr["alias"]),
621 dbesc($arr["pubkey"]),
622 dbesc(datetime_convert())
630 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
632 * @param int $contact_id The id in the contact table
633 * @param int $gcontact_id The id in the gcontact table
635 * @return string the handle
637 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
640 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
642 if ($gcontact_id != 0) {
643 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
644 intval($gcontact_id));
646 return $r[0]["addr"];
649 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
650 intval($contact_id));
654 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
656 if($contact['addr'] != "")
657 $handle = $contact['addr'];
658 elseif(($contact['network'] === NETWORK_DFRN) || ($contact['self'] == 1)) {
659 $baseurl_start = strpos($contact['url'],'://') + 3;
660 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
661 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
662 $handle = $contact['nick'].'@'.$baseurl;
670 * @brief Get a contact id for a given handle
672 * @param int $uid The user id
673 * @param string $handle The handle in the format user@domain.tld
675 * @return The contact id
677 private function contact_by_handle($uid, $handle) {
678 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
686 $handle_parts = explode("@", $handle);
687 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
688 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
700 * @brief Check if posting is allowed for this contact
702 * @param array $importer Array of the importer user
703 * @param array $contact The contact that is checked
704 * @param bool $is_comment Is the check for a comment?
706 * @return bool is the contact allowed to post?
708 private function post_allow($importer, $contact, $is_comment = false) {
710 // perhaps we were already sharing with this person. Now they're sharing with us.
711 // That makes us friends.
712 // Normally this should have handled by getting a request - but this could get lost
713 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
714 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
715 intval(CONTACT_IS_FRIEND),
716 intval($contact["id"]),
717 intval($importer["uid"])
719 $contact["rel"] = CONTACT_IS_FRIEND;
720 logger("defining user ".$contact["nick"]." as friend");
723 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
725 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
727 if($contact["rel"] == CONTACT_IS_FOLLOWER)
728 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
731 // Messages for the global users are always accepted
732 if ($importer["uid"] == 0)
739 * @brief Fetches the contact id for a handle and checks if posting is allowed
741 * @param array $importer Array of the importer user
742 * @param string $handle The checked handle in the format user@domain.tld
743 * @param bool $is_comment Is the check for a comment?
745 * @return bool is posting allowed?
747 private function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
748 $contact = self::contact_by_handle($importer["uid"], $handle);
750 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
754 if (!self::post_allow($importer, $contact, $is_comment)) {
755 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
762 * @brief Does the message already exists on the system?
764 * @param int $uid The user id
765 * @param string $guid The guid of the message
767 * @return bool "true" if the message already was stored into the system
769 private function message_exists($uid, $guid) {
770 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
776 logger("message ".$guid." already exists for user ".$uid);
784 * @brief Checks for links to posts in a message
786 * @param array $item The item array
788 private function fetch_guid($item) {
789 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
790 function ($match) use ($item){
791 return(self::fetch_guid_sub($match, $item));
796 * @brief sub function of "fetch_guid"
798 * @param array $match array containing a link that has to be checked for a message link
799 * @param array $item The item array
801 private function fetch_guid_sub($match, $item) {
802 if (!self::store_by_guid($match[1], $item["author-link"]))
803 self::store_by_guid($match[1], $item["owner-link"]);
807 * @brief Fetches an item with a given guid from a given server
809 * @param string $guid the message guid
810 * @param string $server The server address
811 * @param int $uid The user id of the user
813 * @return int the message id of the stored message or false
815 private function store_by_guid($guid, $server, $uid = 0) {
816 $serverparts = parse_url($server);
817 $server = $serverparts["scheme"]."://".$serverparts["host"];
819 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
821 $msg = self::message($guid, $server);
826 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
828 // Now call the dispatcher
829 return self::dispatch_public($msg);
833 * @brief Fetches a message from a server
835 * @param string $guid message guid
836 * @param string $server The url of the server
837 * @param int $level Endless loop prevention
839 * @return array of message, author and public key
841 private function message($guid, $server, $level = 0) {
846 // This will work for Diaspora and newer Friendica servers
847 $source_url = $server."/p/".$guid.".xml";
848 $x = fetch_url($source_url);
852 $source_xml = parse_xml_string($x, false);
854 if (!is_object($source_xml))
857 if ($source_xml->post->reshare) {
858 // Reshare of a reshare - old Diaspora version
859 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
860 } elseif ($source_xml->getName() == "reshare") {
861 // Reshare of a reshare - new Diaspora version
862 return self::message($source_xml->root_guid, $server, ++$level);
867 // Fetch the author - for the old and the new Diaspora version
868 if ($source_xml->post->status_message->diaspora_handle)
869 $author = (string)$source_xml->post->status_message->diaspora_handle;
870 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
871 $author = (string)$source_xml->author;
873 // If this isn't a "status_message" then quit
877 $msg = array("message" => $x, "author" => $author);
879 $msg["key"] = self::key($msg["author"]);
885 * @brief Fetches the item record of a given guid
887 * @param int $uid The user id
888 * @param string $guid message guid
889 * @param string $author The handle of the item
890 * @param array $contact The contact that is checked
892 * @return array the item record
894 private function parent_item($uid, $guid, $author, $contact) {
895 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
896 `author-name`, `author-link`, `author-avatar`,
897 `owner-name`, `owner-link`, `owner-avatar`
898 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
899 intval($uid), dbesc($guid));
902 $result = self::store_by_guid($guid, $contact["url"], $uid);
905 $person = self::person_by_handle($author);
906 $result = self::store_by_guid($guid, $person["url"], $uid);
910 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
912 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
913 `author-name`, `author-link`, `author-avatar`,
914 `owner-name`, `owner-link`, `owner-avatar`
915 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
916 intval($uid), dbesc($guid));
921 logger("parent item not found: parent: ".$guid." - user: ".$uid);
924 logger("parent item found: parent: ".$guid." - user: ".$uid);
930 * @brief returns contact details
932 * @param array $contact The default contact if the person isn't found
933 * @param array $person The record of the person
934 * @param int $uid The user id
936 * @return array of contact id and network type
938 private function author_contact_by_url($contact, $person, $uid) {
940 $r = q("SELECT `id`, `network` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
941 dbesc(normalise_link($person["url"])), intval($uid));
944 $network = $r[0]["network"];
946 $cid = $contact["id"];
947 $network = NETWORK_DIASPORA;
950 return (array("cid" => $cid, "network" => $network));
954 * @brief Is the profile a hubzilla profile?
956 * @param string $url The profile link
958 * @return bool is it a hubzilla server?
960 public static function is_redmatrix($url) {
961 return(strstr($url, "/channel/"));
965 * @brief Generate a post link with a given handle and message guid
967 * @param string $addr The user handle
968 * @param string $guid message guid
970 * @return string the post link
972 private function plink($addr, $guid) {
973 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
977 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
979 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
980 // So we try another way as well.
981 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
983 $r[0]["network"] = $s[0]["network"];
985 if ($r[0]["network"] == NETWORK_DFRN)
986 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
988 if (self::is_redmatrix($r[0]["url"]))
989 return $r[0]["url"]."/?f=&mid=".$guid;
991 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
997 * @param array $importer Array of the importer user
998 * @param object $data The message object
1002 private function receive_account_deletion($importer, $data) {
1003 $author = notags(unxmlify($data->author));
1005 $contact = self::contact_by_handle($importer["uid"], $author);
1007 logger("cannot find contact for author: ".$author);
1011 // We now remove the contact
1012 contact_remove($contact["id"]);
1019 * @param array $importer Array of the importer user
1020 * @param string $sender The sender of the message
1021 * @param object $data The message object
1022 * @param string $xml The original XML of the message
1024 * @return int The message id of the generated comment or "false" if there was an error
1026 private function receive_comment($importer, $sender, $data, $xml) {
1027 $guid = notags(unxmlify($data->guid));
1028 $parent_guid = notags(unxmlify($data->parent_guid));
1029 $text = unxmlify($data->text);
1030 $author = notags(unxmlify($data->author));
1032 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1036 if (self::message_exists($importer["uid"], $guid))
1039 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1043 $person = self::person_by_handle($author);
1044 if (!is_array($person)) {
1045 logger("unable to find author details");
1049 // Fetch the contact id - if we know this contact
1050 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1052 $datarray = array();
1054 $datarray["uid"] = $importer["uid"];
1055 $datarray["contact-id"] = $author_contact["cid"];
1056 $datarray["network"] = $author_contact["network"];
1058 $datarray["author-name"] = $person["name"];
1059 $datarray["author-link"] = $person["url"];
1060 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1062 $datarray["owner-name"] = $contact["name"];
1063 $datarray["owner-link"] = $contact["url"];
1064 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1066 $datarray["guid"] = $guid;
1067 $datarray["uri"] = $author.":".$guid;
1069 $datarray["type"] = "remote-comment";
1070 $datarray["verb"] = ACTIVITY_POST;
1071 $datarray["gravity"] = GRAVITY_COMMENT;
1072 $datarray["parent-uri"] = $parent_item["uri"];
1074 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1075 $datarray["object"] = $xml;
1077 $datarray["body"] = diaspora2bb($text);
1079 self::fetch_guid($datarray);
1081 $message_id = item_store($datarray);
1084 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1086 // If we are the origin of the parent we store the original data and notify our followers
1087 if($message_id AND $parent_item["origin"]) {
1089 // Formerly we stored the signed text, the signature and the author in different fields.
1090 // We now store the raw data so that we are more flexible.
1091 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1092 intval($message_id),
1093 dbesc(json_encode($data))
1097 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1104 * @brief processes and stores private messages
1106 * @param array $importer Array of the importer user
1107 * @param array $contact The contact that is checked
1108 * @param object $data The message object
1109 * @param array $msg Array of the processed message, author handle and key
1110 * @param object $mesg The private message
1111 * @param array $conversation The conversation record to which this message belongs
1113 * @return bool "true" if it was successful
1115 private function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1116 $guid = notags(unxmlify($data->guid));
1117 $subject = notags(unxmlify($data->subject));
1118 $author = notags(unxmlify($data->author));
1122 $msg_guid = notags(unxmlify($mesg->guid));
1123 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1124 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1125 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1126 $msg_text = unxmlify($mesg->text);
1127 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1129 // "diaspora_handle" is the element name from the old version
1130 // "author" is the element name from the new version
1132 $msg_author = notags(unxmlify($mesg->author));
1133 elseif ($mesg->diaspora_handle)
1134 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1138 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1140 if($msg_conversation_guid != $guid) {
1141 logger("message conversation guid does not belong to the current conversation.");
1145 $body = diaspora2bb($msg_text);
1146 $message_uri = $msg_author.":".$msg_guid;
1148 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1150 $author_signature = base64_decode($msg_author_signature);
1152 if(strcasecmp($msg_author,$msg["author"]) == 0) {
1156 $person = self::person_by_handle($msg_author);
1158 if (is_array($person) && x($person, "pubkey"))
1159 $key = $person["pubkey"];
1161 logger("unable to find author details");
1166 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1167 logger("verification failed.");
1171 if($msg_parent_author_signature) {
1172 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1174 $parent_author_signature = base64_decode($msg_parent_author_signature);
1178 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1179 logger("owner verification failed.");
1184 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1188 logger("duplicate message already delivered.", LOGGER_DEBUG);
1192 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1193 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1194 intval($importer["uid"]),
1196 intval($conversation["id"]),
1197 dbesc($person["name"]),
1198 dbesc($person["photo"]),
1199 dbesc($person["url"]),
1200 intval($contact["id"]),
1205 dbesc($message_uri),
1206 dbesc($author.":".$guid),
1207 dbesc($msg_created_at)
1210 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1211 dbesc(datetime_convert()),
1212 intval($conversation["id"])
1216 "type" => NOTIFY_MAIL,
1217 "notify_flags" => $importer["notify-flags"],
1218 "language" => $importer["language"],
1219 "to_name" => $importer["username"],
1220 "to_email" => $importer["email"],
1221 "uid" =>$importer["uid"],
1222 "item" => array("subject" => $subject, "body" => $body),
1223 "source_name" => $person["name"],
1224 "source_link" => $person["url"],
1225 "source_photo" => $person["thumb"],
1226 "verb" => ACTIVITY_POST,
1235 * @param array $importer Array of the importer user
1236 * @param array $msg Array of the processed message, author handle and key
1237 * @param object $data The message object
1241 private function receive_conversation($importer, $msg, $data) {
1242 $guid = notags(unxmlify($data->guid));
1243 $subject = notags(unxmlify($data->subject));
1244 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1245 $author = notags(unxmlify($data->author));
1246 $participants = notags(unxmlify($data->participants));
1248 $messages = $data->message;
1250 if (!count($messages)) {
1251 logger("empty conversation");
1255 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1259 $conversation = null;
1261 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1262 intval($importer["uid"]),
1266 $conversation = $c[0];
1268 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1269 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1270 intval($importer["uid"]),
1273 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1274 dbesc(datetime_convert()),
1276 dbesc($participants)
1279 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1280 intval($importer["uid"]),
1285 $conversation = $c[0];
1287 if (!$conversation) {
1288 logger("unable to create conversation.");
1292 foreach($messages as $mesg)
1293 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1301 * @param array $contact The contact that is checked
1302 * @param $parent_item
1303 * @param string $guid message guid
1307 private function construct_like_body($contact, $parent_item, $guid) {
1308 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1310 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1311 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1312 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1314 return sprintf($bodyverb, $ulink, $alink, $plink);
1320 * @param array $importer Array of the importer user
1321 * @param $parent_item
1325 private function construct_like_object($importer, $parent_item) {
1326 $objtype = ACTIVITY_OBJ_NOTE;
1327 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1328 $parent_body = $parent_item["body"];
1330 $xmldata = array("object" => array("type" => $objtype,
1332 "id" => $parent_item["uri"],
1335 "content" => $parent_body));
1337 return xml::from_array($xmldata, $xml, true);
1343 * @param array $importer Array of the importer user
1344 * @param string $sender The sender of the message
1345 * @param object $data The message object
1347 * @return int The message id of the generated like or "false" if there was an error
1349 private function receive_like($importer, $sender, $data) {
1350 $positive = notags(unxmlify($data->positive));
1351 $guid = notags(unxmlify($data->guid));
1352 $parent_type = notags(unxmlify($data->parent_type));
1353 $parent_guid = notags(unxmlify($data->parent_guid));
1354 $author = notags(unxmlify($data->author));
1356 // likes on comments aren't supported by Diaspora - only on posts
1357 // But maybe this will be supported in the future, so we will accept it.
1358 if (!in_array($parent_type, array("Post", "Comment")))
1361 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1365 if (self::message_exists($importer["uid"], $guid))
1368 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1372 $person = self::person_by_handle($author);
1373 if (!is_array($person)) {
1374 logger("unable to find author details");
1378 // Fetch the contact id - if we know this contact
1379 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1381 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1382 // We would accept this anyhow.
1383 if ($positive === "true")
1384 $verb = ACTIVITY_LIKE;
1386 $verb = ACTIVITY_DISLIKE;
1388 $datarray = array();
1390 $datarray["uid"] = $importer["uid"];
1391 $datarray["contact-id"] = $author_contact["cid"];
1392 $datarray["network"] = $author_contact["network"];
1394 $datarray["author-name"] = $person["name"];
1395 $datarray["author-link"] = $person["url"];
1396 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1398 $datarray["owner-name"] = $contact["name"];
1399 $datarray["owner-link"] = $contact["url"];
1400 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1402 $datarray["guid"] = $guid;
1403 $datarray["uri"] = $author.":".$guid;
1405 $datarray["type"] = "activity";
1406 $datarray["verb"] = $verb;
1407 $datarray["gravity"] = GRAVITY_LIKE;
1408 $datarray["parent-uri"] = $parent_item["uri"];
1410 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1411 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1413 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1415 $message_id = item_store($datarray);
1418 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1420 // If we are the origin of the parent we store the original data and notify our followers
1421 if($message_id AND $parent_item["origin"]) {
1423 // Formerly we stored the signed text, the signature and the author in different fields.
1424 // We now store the raw data so that we are more flexible.
1425 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1426 intval($message_id),
1427 dbesc(json_encode($data))
1431 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1440 * @param array $importer Array of the importer user
1441 * @param object $data The message object
1445 private function receive_message($importer, $data) {
1446 $guid = notags(unxmlify($data->guid));
1447 $parent_guid = notags(unxmlify($data->parent_guid));
1448 $text = unxmlify($data->text);
1449 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1450 $author = notags(unxmlify($data->author));
1451 $conversation_guid = notags(unxmlify($data->conversation_guid));
1453 $contact = self::allowed_contact_by_handle($importer, $author, true);
1457 $conversation = null;
1459 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1460 intval($importer["uid"]),
1461 dbesc($conversation_guid)
1464 $conversation = $c[0];
1466 logger("conversation not available.");
1472 $body = diaspora2bb($text);
1473 $message_uri = $author.":".$guid;
1475 $person = self::person_by_handle($author);
1477 logger("unable to find author details");
1481 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1482 dbesc($message_uri),
1483 intval($importer["uid"])
1486 logger("duplicate message already delivered.", LOGGER_DEBUG);
1490 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1491 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1492 intval($importer["uid"]),
1494 intval($conversation["id"]),
1495 dbesc($person["name"]),
1496 dbesc($person["photo"]),
1497 dbesc($person["url"]),
1498 intval($contact["id"]),
1499 dbesc($conversation["subject"]),
1503 dbesc($message_uri),
1504 dbesc($author.":".$parent_guid),
1508 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1509 dbesc(datetime_convert()),
1510 intval($conversation["id"])
1519 * @param array $importer Array of the importer user
1520 * @param object $data The message object
1522 * @return bool always true
1524 private function receive_participation($importer, $data) {
1525 // I'm not sure if we can fully support this message type
1532 * @param array $importer Array of the importer user
1533 * @param object $data The message object
1537 private function receive_photo($importer, $data) {
1538 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1545 * @param array $importer Array of the importer user
1546 * @param object $data The message object
1550 private function receive_poll_participation($importer, $data) {
1551 // We don't support polls by now
1558 * @param array $importer Array of the importer user
1559 * @param object $data The message object
1563 private function receive_profile($importer, $data) {
1564 $author = notags(unxmlify($data->author));
1566 $contact = self::contact_by_handle($importer["uid"], $author);
1570 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1571 $image_url = unxmlify($data->image_url);
1572 $birthday = unxmlify($data->birthday);
1573 $location = diaspora2bb(unxmlify($data->location));
1574 $about = diaspora2bb(unxmlify($data->bio));
1575 $gender = unxmlify($data->gender);
1576 $searchable = (unxmlify($data->searchable) == "true");
1577 $nsfw = (unxmlify($data->nsfw) == "true");
1578 $tags = unxmlify($data->tag_string);
1580 $tags = explode("#", $tags);
1582 $keywords = array();
1583 foreach ($tags as $tag) {
1584 $tag = trim(strtolower($tag));
1589 $keywords = implode(", ", $keywords);
1591 $handle_parts = explode("@", $author);
1592 $nick = $handle_parts[0];
1595 $name = $handle_parts[0];
1597 if( preg_match("|^https?://|", $image_url) === 0)
1598 $image_url = "http://".$handle_parts[1].$image_url;
1600 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1602 // Generic birthday. We don't know the timezone. The year is irrelevant.
1604 $birthday = str_replace("1000", "1901", $birthday);
1606 if ($birthday != "")
1607 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1609 // this is to prevent multiple birthday notifications in a single year
1610 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1612 if(substr($birthday,5) === substr($contact["bd"],5))
1613 $birthday = $contact["bd"];
1615 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1616 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1620 dbesc(datetime_convert()),
1626 intval($contact["id"]),
1627 intval($importer["uid"])
1631 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1632 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1635 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1636 "photo" => $image_url, "name" => $name, "location" => $location,
1637 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1638 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1639 "hide" => !$searchable, "nsfw" => $nsfw);
1641 update_gcontact($gcontact);
1643 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1651 * @param array $importer Array of the importer user
1652 * @param array $contact The contact that is checked
1656 private function receive_request_make_friend($importer, $contact) {
1660 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1661 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1662 intval(CONTACT_IS_FRIEND),
1663 intval($contact["id"]),
1664 intval($importer["uid"])
1667 // send notification
1669 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1670 intval($importer["uid"])
1673 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1675 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1676 intval($importer["uid"])
1679 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1681 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1684 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1685 $arr["uid"] = $importer["uid"];
1686 $arr["contact-id"] = $self[0]["id"];
1688 $arr["type"] = 'wall';
1689 $arr["gravity"] = 0;
1691 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1692 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1693 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1694 $arr["verb"] = ACTIVITY_FRIEND;
1695 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1697 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1698 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1699 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1700 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1702 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1703 ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1704 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1705 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1706 $arr["object"] .= "</link></object>\n";
1707 $arr["last-child"] = 1;
1709 $arr["allow_cid"] = $user[0]["allow_cid"];
1710 $arr["allow_gid"] = $user[0]["allow_gid"];
1711 $arr["deny_cid"] = $user[0]["deny_cid"];
1712 $arr["deny_gid"] = $user[0]["deny_gid"];
1714 $i = item_store($arr);
1716 proc_run("php", "include/notifier.php", "activity", $i);
1726 * @param array $importer Array of the importer user
1727 * @param object $data The message object
1731 private function receive_request($importer, $data) {
1732 $author = unxmlify($data->author);
1733 $recipient = unxmlify($data->recipient);
1735 if (!$author || !$recipient)
1738 $contact = self::contact_by_handle($importer["uid"],$author);
1742 // perhaps we were already sharing with this person. Now they're sharing with us.
1743 // That makes us friends.
1745 self::receive_request_make_friend($importer, $contact);
1749 $ret = self::person_by_handle($author);
1751 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1752 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1756 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1758 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1759 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1760 intval($importer["uid"]),
1761 dbesc($ret["network"]),
1762 dbesc($ret["addr"]),
1765 dbesc(normalise_link($ret["url"])),
1767 dbesc($ret["name"]),
1768 dbesc($ret["nick"]),
1769 dbesc($ret["photo"]),
1770 dbesc($ret["pubkey"]),
1771 dbesc($ret["notify"]),
1772 dbesc($ret["poll"]),
1777 // find the contact record we just created
1779 $contact_record = self::contact_by_handle($importer["uid"],$author);
1781 if (!$contact_record) {
1782 logger("unable to locate newly created contact record.");
1786 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1787 intval($importer["uid"])
1790 if($g && intval($g[0]["def_gid"]))
1791 group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1793 if($importer["page-flags"] == PAGE_NORMAL) {
1795 $hash = random_string().(string)time(); // Generate a confirm_key
1797 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1798 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1799 intval($importer["uid"]),
1800 intval($contact_record["id"]),
1803 dbesc(t("Sharing notification from Diaspora network")),
1805 dbesc(datetime_convert())
1809 // automatic friend approval
1811 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1813 // technically they are sharing with us (CONTACT_IS_SHARING),
1814 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1815 // we are going to change the relationship and make them a follower.
1817 if($importer["page-flags"] == PAGE_FREELOVE)
1818 $new_relation = CONTACT_IS_FRIEND;
1820 $new_relation = CONTACT_IS_FOLLOWER;
1822 $r = q("UPDATE `contact` SET `rel` = %d,
1830 intval($new_relation),
1831 dbesc(datetime_convert()),
1832 dbesc(datetime_convert()),
1833 intval($contact_record["id"])
1836 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1838 $ret = self::send_share($u[0], $contact_record);
1847 * @param string $guid message guid
1848 * @param $orig_author
1853 private function original_item($guid, $orig_author, $author) {
1855 // Do we already have this item?
1856 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1857 `author-name`, `author-link`, `author-avatar`
1858 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1862 logger("reshared message ".$guid." already exists on system.");
1864 // Maybe it is already a reshared item?
1865 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1866 if (self::is_reshare($r[0]["body"], false))
1873 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1874 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1875 $item_id = self::store_by_guid($guid, $server);
1878 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1879 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1880 $item_id = self::store_by_guid($guid, $server);
1883 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1885 $server = "https://".substr($author, strpos($author, "@") + 1);
1886 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1887 $item_id = self::store_by_guid($guid, $server);
1890 $server = "http://".substr($author, strpos($author, "@") + 1);
1891 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1892 $item_id = self::store_by_guid($guid, $server);
1896 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1897 `author-name`, `author-link`, `author-avatar`
1898 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1912 * @param array $importer Array of the importer user
1913 * @param object $data The message object
1914 * @param string $xml The original XML of the message
1918 private function receive_reshare($importer, $data, $xml) {
1919 $root_author = notags(unxmlify($data->root_author));
1920 $root_guid = notags(unxmlify($data->root_guid));
1921 $guid = notags(unxmlify($data->guid));
1922 $author = notags(unxmlify($data->author));
1923 $public = notags(unxmlify($data->public));
1924 $created_at = notags(unxmlify($data->created_at));
1926 $contact = self::allowed_contact_by_handle($importer, $author, false);
1930 if (self::message_exists($importer["uid"], $guid))
1933 $original_item = self::original_item($root_guid, $root_author, $author);
1934 if (!$original_item)
1937 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1939 $datarray = array();
1941 $datarray["uid"] = $importer["uid"];
1942 $datarray["contact-id"] = $contact["id"];
1943 $datarray["network"] = NETWORK_DIASPORA;
1945 $datarray["author-name"] = $contact["name"];
1946 $datarray["author-link"] = $contact["url"];
1947 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1949 $datarray["owner-name"] = $datarray["author-name"];
1950 $datarray["owner-link"] = $datarray["author-link"];
1951 $datarray["owner-avatar"] = $datarray["author-avatar"];
1953 $datarray["guid"] = $guid;
1954 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1956 $datarray["verb"] = ACTIVITY_POST;
1957 $datarray["gravity"] = GRAVITY_PARENT;
1959 $datarray["object"] = $xml;
1961 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1962 $original_item["guid"], $original_item["created"], $orig_url);
1963 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1965 $datarray["tag"] = $original_item["tag"];
1966 $datarray["app"] = $original_item["app"];
1968 $datarray["plink"] = self::plink($author, $guid);
1969 $datarray["private"] = (($public == "false") ? 1 : 0);
1970 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1972 $datarray["object-type"] = $original_item["object-type"];
1974 self::fetch_guid($datarray);
1975 $message_id = item_store($datarray);
1978 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1986 * @param array $importer Array of the importer user
1987 * @param array $contact The contact that is checked
1988 * @param object $data The message object
1992 private function item_retraction($importer, $contact, $data) {
1993 $target_type = notags(unxmlify($data->target_type));
1994 $target_guid = notags(unxmlify($data->target_guid));
1995 $author = notags(unxmlify($data->author));
1997 $person = self::person_by_handle($author);
1998 if (!is_array($person)) {
1999 logger("unable to find author detail for ".$author);
2003 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2004 dbesc($target_guid),
2005 intval($importer["uid"])
2010 // Only delete it if the author really fits
2011 if (!link_compare($r[0]["author-link"], $person["url"])) {
2012 logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
2016 // Check if the sender is the thread owner
2017 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2018 intval($r[0]["parent"]));
2020 // Only delete it if the parent author really fits
2021 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2022 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2026 // 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
2027 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2028 dbesc(datetime_convert()),
2029 dbesc(datetime_convert()),
2032 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2034 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2036 // Now check if the retraction needs to be relayed by us
2037 if($p[0]["origin"]) {
2039 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
2046 * @param array $importer Array of the importer user
2047 * @param string $sender The sender of the message
2048 * @param object $data The message object
2052 private function receive_retraction($importer, $sender, $data) {
2053 $target_type = notags(unxmlify($data->target_type));
2055 $contact = self::contact_by_handle($importer["uid"], $sender);
2057 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2061 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2063 switch ($target_type) {
2066 case "Post": // "Post" will be supported in a future version
2068 case "StatusMessage":
2069 return self::item_retraction($importer, $contact, $data);;
2072 /// @todo What should we do with an "unshare"?
2073 // Removing the contact isn't correct since we still can read the public items
2074 //contact_remove($contact["id"]);
2078 logger("Unknown target type ".$target_type);
2087 * @param array $importer Array of the importer user
2088 * @param object $data The message object
2089 * @param string $xml The original XML of the message
2093 private function receive_status_message($importer, $data, $xml) {
2095 $raw_message = unxmlify($data->raw_message);
2096 $guid = notags(unxmlify($data->guid));
2097 $author = notags(unxmlify($data->author));
2098 $public = notags(unxmlify($data->public));
2099 $created_at = notags(unxmlify($data->created_at));
2100 $provider_display_name = notags(unxmlify($data->provider_display_name));
2102 /// @todo enable support for polls
2103 //if ($data->poll) {
2104 // foreach ($data->poll AS $poll)
2108 $contact = self::allowed_contact_by_handle($importer, $author, false);
2112 if (self::message_exists($importer["uid"], $guid))
2116 if ($data->location)
2117 foreach ($data->location->children() AS $fieldname => $data)
2118 $address[$fieldname] = notags(unxmlify($data));
2120 $body = diaspora2bb($raw_message);
2122 $datarray = array();
2125 foreach ($data->photo AS $photo)
2126 $body = "[img]".unxmlify($photo->remote_photo_path).
2127 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2129 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
2131 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2133 // Add OEmbed and other information to the body
2134 if (!self::is_redmatrix($contact["url"]))
2135 $body = add_page_info_to_body($body, false, true);
2138 $datarray["uid"] = $importer["uid"];
2139 $datarray["contact-id"] = $contact["id"];
2140 $datarray["network"] = NETWORK_DIASPORA;
2142 $datarray["author-name"] = $contact["name"];
2143 $datarray["author-link"] = $contact["url"];
2144 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2146 $datarray["owner-name"] = $datarray["author-name"];
2147 $datarray["owner-link"] = $datarray["author-link"];
2148 $datarray["owner-avatar"] = $datarray["author-avatar"];
2150 $datarray["guid"] = $guid;
2151 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
2153 $datarray["verb"] = ACTIVITY_POST;
2154 $datarray["gravity"] = GRAVITY_PARENT;
2156 $datarray["object"] = $xml;
2158 $datarray["body"] = $body;
2160 if ($provider_display_name != "")
2161 $datarray["app"] = $provider_display_name;
2163 $datarray["plink"] = self::plink($author, $guid);
2164 $datarray["private"] = (($public == "false") ? 1 : 0);
2165 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
2167 if (isset($address["address"]))
2168 $datarray["location"] = $address["address"];
2170 if (isset($address["lat"]) AND isset($address["lng"]))
2171 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2173 self::fetch_guid($datarray);
2174 $message_id = item_store($datarray);
2177 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2182 /******************************************************************************************
2183 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2184 ******************************************************************************************/
2187 * @brief returnes the handle of a contact
2189 * @param array $me contact array
2191 * @return string the handle in the format user@domain.tld
2193 private function my_handle($me) {
2194 if ($contact["addr"] != "")
2195 return $contact["addr"];
2197 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2198 // So - just in case - we build the the address here.
2199 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2203 * @brief Creates the envelope for a public message
2205 * @param string $msg The message that is to be transmitted
2206 * @param array $user The record of the sender
2207 * @param array $contact Target of the communication
2208 * @param string $prvkey The private key of the sender
2209 * @param string $pubkey The public key of the receiver
2211 * @return string The envelope
2213 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2215 logger("Message: ".$msg, LOGGER_DATA);
2217 $handle = self::my_handle($user);
2219 $b64url_data = base64url_encode($msg);
2221 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2223 $type = "application/xml";
2224 $encoding = "base64url";
2225 $alg = "RSA-SHA256";
2227 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2229 $signature = rsa_sign($signable_data,$prvkey);
2230 $sig = base64url_encode($signature);
2232 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2233 "me:env" => array("me:encoding" => "base64url",
2234 "me:alg" => "RSA-SHA256",
2236 "@attributes" => array("type" => "application/xml"),
2237 "me:sig" => $sig)));
2239 $namespaces = array("" => "https://joindiaspora.com/protocol",
2240 "me" => "http://salmon-protocol.org/ns/magic-env");
2242 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2244 logger("magic_env: ".$magic_env, LOGGER_DATA);
2249 * @brief Creates the envelope for a private message
2251 * @param string $msg The message that is to be transmitted
2252 * @param array $user The record of the sender
2253 * @param array $contact Target of the communication
2254 * @param string $prvkey The private key of the sender
2255 * @param string $pubkey The public key of the receiver
2257 * @return string The envelope
2259 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2261 logger("Message: ".$msg, LOGGER_DATA);
2263 // without a public key nothing will work
2266 logger("pubkey missing: contact id: ".$contact["id"]);
2270 $inner_aes_key = random_string(32);
2271 $b_inner_aes_key = base64_encode($inner_aes_key);
2272 $inner_iv = random_string(16);
2273 $b_inner_iv = base64_encode($inner_iv);
2275 $outer_aes_key = random_string(32);
2276 $b_outer_aes_key = base64_encode($outer_aes_key);
2277 $outer_iv = random_string(16);
2278 $b_outer_iv = base64_encode($outer_iv);
2280 $handle = self::my_handle($user);
2282 $padded_data = pkcs5_pad($msg,16);
2283 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2285 $b64_data = base64_encode($inner_encrypted);
2288 $b64url_data = base64url_encode($b64_data);
2289 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2291 $type = "application/xml";
2292 $encoding = "base64url";
2293 $alg = "RSA-SHA256";
2295 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2297 $signature = rsa_sign($signable_data,$prvkey);
2298 $sig = base64url_encode($signature);
2300 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2301 "aes_key" => $b_inner_aes_key,
2302 "author_id" => $handle));
2304 $decrypted_header = xml::from_array($xmldata, $xml, true);
2305 $decrypted_header = pkcs5_pad($decrypted_header,16);
2307 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2309 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2311 $encrypted_outer_key_bundle = "";
2312 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2314 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2316 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2318 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2319 "ciphertext" => base64_encode($ciphertext)));
2320 $cipher_json = base64_encode($encrypted_header_json_object);
2322 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2323 "me:env" => array("me:encoding" => "base64url",
2324 "me:alg" => "RSA-SHA256",
2326 "@attributes" => array("type" => "application/xml"),
2327 "me:sig" => $sig)));
2329 $namespaces = array("" => "https://joindiaspora.com/protocol",
2330 "me" => "http://salmon-protocol.org/ns/magic-env");
2332 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2334 logger("magic_env: ".$magic_env, LOGGER_DATA);
2339 * @brief Create the envelope for a message
2341 * @param string $msg The message that is to be transmitted
2342 * @param array $user The record of the sender
2343 * @param array $contact Target of the communication
2344 * @param string $prvkey The private key of the sender
2345 * @param string $pubkey The public key of the receiver
2346 * @param bool $public Is the message public?
2350 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2353 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2355 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2357 // The data that will be transmitted is double encoded via "urlencode", strange ...
2358 $slap = "xml=".urlencode(urlencode($magic_env));
2363 * @brief Creates a signature for a message
2365 * @param array $owner the array of the owner of the message
2366 * @param array $message The message that is to be signed
2368 * @return string The signature
2370 private function signature($owner, $message) {
2372 unset($sigmsg["author_signature"]);
2373 unset($sigmsg["parent_author_signature"]);
2375 $signed_text = implode(";", $sigmsg);
2377 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2381 * @brief Transmit a message to a target server
2383 * @param array $owner the array of the item owner
2384 * @param array $contact Target of the communication
2385 * @param string $slap The message that is to be transmitted
2386 * @param bool $public_batch Is it a public post?
2387 * @param bool $queue_run Is the transmission called from the queue?
2388 * @param string $guid message guid
2390 * @return int Result of the transmission
2392 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2396 $enabled = intval(get_config("system", "diaspora_enabled"));
2400 $logid = random_string(4);
2401 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2403 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2407 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2409 if (!$queue_run && was_recently_delayed($contact["id"])) {
2412 if (!intval(get_config("system", "diaspora_test"))) {
2413 post_url($dest_url."/", $slap);
2414 $return_code = $a->get_curl_code();
2416 logger("test_mode");
2421 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2423 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2424 logger("queue message");
2426 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2427 intval($contact["id"]),
2428 dbesc(NETWORK_DIASPORA),
2430 intval($public_batch)
2433 logger("add_to_queue ignored - identical item already in queue");
2435 // queue message for redelivery
2436 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2440 return(($return_code) ? $return_code : (-1));
2447 * @param array $owner the array of the item owner
2448 * @param array $contact Target of the communication
2449 * @param string $type The message type
2450 * @param array $message The message data
2451 * @param bool $public_batch Is it a public post?
2452 * @param string $guid message guid
2453 * @param bool $spool Should the transmission be spooled or transmitted?
2455 * @return int Result of the transmission
2457 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2459 $data = array("XML" => array("post" => array($type => $message)));
2461 $msg = xml::from_array($data, $xml);
2463 logger('message: '.$msg, LOGGER_DATA);
2464 logger('send guid '.$guid, LOGGER_DEBUG);
2466 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2469 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2472 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2474 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2476 return $return_code;
2482 * @param array $owner the array of the item owner
2483 * @param array $contact Target of the communication
2485 * @return int The result of the transmission
2487 public static function send_share($owner,$contact) {
2489 $message = array("sender_handle" => self::my_handle($owner),
2490 "recipient_handle" => $contact["addr"]);
2492 return self::build_and_transmit($owner, $contact, "request", $message);
2498 * @param array $owner the array of the item owner
2499 * @param array $contact Target of the communication
2501 * @return int The result of the transmission
2503 public static function send_unshare($owner,$contact) {
2505 $message = array("post_guid" => $owner["guid"],
2506 "diaspora_handle" => self::my_handle($owner),
2507 "type" => "Person");
2509 return self::build_and_transmit($owner, $contact, "retraction", $message);
2513 * @brief Checks a message body if it is a reshare
2515 * @param string $body The message body that is to be check
2516 * @param bool $complete Should it be a complete check or a simple check?
2518 * @return array|bool Reshare details or "false" if no reshare
2520 public static function is_reshare($body, $complete = true) {
2521 $body = trim($body);
2523 // Skip if it isn't a pure repeated messages
2524 // Does it start with a share?
2525 if (strpos($body, "[share") > 0)
2528 // Does it end with a share?
2529 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2532 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2533 // Skip if there is no shared message in there
2534 if ($body == $attributes)
2537 // If we don't do the complete check we quit here
2542 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2543 if ($matches[1] != "")
2544 $guid = $matches[1];
2546 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2547 if ($matches[1] != "")
2548 $guid = $matches[1];
2551 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2552 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2555 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2556 $ret["root_guid"] = $guid;
2562 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2563 if ($matches[1] != "")
2564 $profile = $matches[1];
2566 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2567 if ($matches[1] != "")
2568 $profile = $matches[1];
2572 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2573 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2577 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2578 if ($matches[1] != "")
2579 $link = $matches[1];
2581 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2582 if ($matches[1] != "")
2583 $link = $matches[1];
2585 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2586 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2594 * @param array $item The item that will be exported
2595 * @param array $owner the array of the item owner
2596 * @param array $contact Target of the communication
2597 * @param bool $public_batch Is it a public post?
2599 * @return int The result of the transmission
2601 public static function send_status($item, $owner, $contact, $public_batch = false) {
2603 $myaddr = self::my_handle($owner);
2605 $public = (($item["private"]) ? "false" : "true");
2607 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2609 // Detect a share element and do a reshare
2610 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2611 $message = array("root_diaspora_id" => $ret["root_handle"],
2612 "root_guid" => $ret["root_guid"],
2613 "guid" => $item["guid"],
2614 "diaspora_handle" => $myaddr,
2615 "public" => $public,
2616 "created_at" => $created,
2617 "provider_display_name" => $item["app"]);
2621 $title = $item["title"];
2622 $body = $item["body"];
2624 // convert to markdown
2625 $body = html_entity_decode(bb2diaspora($body));
2629 $body = "## ".html_entity_decode($title)."\n\n".$body;
2631 if ($item["attach"]) {
2632 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2634 $body .= "\n".t("Attachments:")."\n";
2635 foreach($matches as $mtch)
2636 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2640 $location = array();
2642 if ($item["location"] != "")
2643 $location["address"] = $item["location"];
2645 if ($item["coord"] != "") {
2646 $coord = explode(" ", $item["coord"]);
2647 $location["lat"] = $coord[0];
2648 $location["lng"] = $coord[1];
2651 $message = array("raw_message" => $body,
2652 "location" => $location,
2653 "guid" => $item["guid"],
2654 "diaspora_handle" => $myaddr,
2655 "public" => $public,
2656 "created_at" => $created,
2657 "provider_display_name" => $item["app"]);
2659 if (count($location) == 0)
2660 unset($message["location"]);
2662 $type = "status_message";
2665 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2671 * @param array $item The item that will be exported
2672 * @param array $owner the array of the item owner
2676 private function construct_like($item, $owner) {
2678 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2679 dbesc($item["thr-parent"]));
2685 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2688 return(array("positive" => $positive,
2689 "guid" => $item["guid"],
2690 "target_type" => $target_type,
2691 "parent_guid" => $parent["guid"],
2692 "author_signature" => $authorsig,
2693 "diaspora_handle" => self::my_handle($owner)));
2699 * @param array $item The item that will be exported
2700 * @param array $owner the array of the item owner
2704 private function construct_comment($item, $owner) {
2706 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2707 intval($item["parent"]),
2708 intval($item["parent"])
2716 $text = html_entity_decode(bb2diaspora($item["body"]));
2718 return(array("guid" => $item["guid"],
2719 "parent_guid" => $parent["guid"],
2720 "author_signature" => "",
2722 "diaspora_handle" => self::my_handle($owner)));
2726 * @brief Send a like or a comment
2728 * @param array $item The item that will be exported
2729 * @param array $owner the array of the item owner
2730 * @param array $contact Target of the communication
2731 * @param bool $public_batch Is it a public post?
2733 * @return int The result of the transmission
2735 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2737 if($item['verb'] === ACTIVITY_LIKE) {
2738 $message = self::construct_like($item, $owner);
2741 $message = self::construct_comment($item, $owner);
2748 $message["author_signature"] = self::signature($owner, $message);
2750 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2754 * @brief Creates a message from a signature record entry
2756 * @param array $item The item that will be exported
2757 * @param array $signature The entry of the "sign" record
2759 * @return string The message
2761 private function message_from_signature($item, $signature) {
2763 // Split the signed text
2764 $signed_parts = explode(";", $signature['signed_text']);
2766 if ($item["deleted"])
2767 $message = array("parent_author_signature" => "",
2768 "target_guid" => $signed_parts[0],
2769 "target_type" => $signed_parts[1],
2770 "sender_handle" => $signature['signer'],
2771 "target_author_signature" => $signature['signature']);
2772 elseif ($item['verb'] === ACTIVITY_LIKE)
2773 $message = array("positive" => $signed_parts[0],
2774 "guid" => $signed_parts[1],
2775 "target_type" => $signed_parts[2],
2776 "parent_guid" => $signed_parts[3],
2777 "parent_author_signature" => "",
2778 "author_signature" => $signature['signature'],
2779 "diaspora_handle" => $signed_parts[4]);
2781 // Remove the comment guid
2782 $guid = array_shift($signed_parts);
2784 // Remove the parent guid
2785 $parent_guid = array_shift($signed_parts);
2787 // Remove the handle
2788 $handle = array_pop($signed_parts);
2790 // Glue the parts together
2791 $text = implode(";", $signed_parts);
2793 $message = array("guid" => $guid,
2794 "parent_guid" => $parent_guid,
2795 "parent_author_signature" => "",
2796 "author_signature" => $signature['signature'],
2797 "text" => implode(";", $signed_parts),
2798 "diaspora_handle" => $handle);
2806 * @param array $item The item that will be exported
2807 * @param array $owner the array of the item owner
2808 * @param array $contact Target of the communication
2809 * @param bool $public_batch Is it a public post?
2811 * @return int The result of the transmission
2813 public static function send_relay($item, $owner, $contact, $public_batch = false) {
2815 if ($item["deleted"])
2816 return self::send_retraction($item, $owner, $contact, $public_batch, true);
2817 elseif ($item['verb'] === ACTIVITY_LIKE)
2822 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2824 // fetch the original signature
2826 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
2827 intval($item["id"]));
2830 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2836 // Old way - is used by the internal Friendica functions
2837 /// @todo Change all signatur storing functions to the new format
2838 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2839 $message = self::message_from_signature($item, $signature);
2841 $msg = json_decode($signature['signed_text'], true);
2844 if (is_array($msg)) {
2845 foreach ($msg AS $field => $data) {
2846 if (!$item["deleted"]) {
2847 if ($field == "author")
2848 $field = "diaspora_handle";
2849 if ($field == "parent_type")
2850 $field = "target_type";
2853 $message[$field] = $data;
2856 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
2859 $message["parent_author_signature"] = self::signature($owner, $message);
2861 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2863 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2867 * @brief Sends a retraction (deletion) of a message, like or comment
2869 * @param array $item The item that will be exported
2870 * @param array $owner the array of the item owner
2871 * @param array $contact Target of the communication
2872 * @param bool $public_batch Is it a public post?
2873 * @param bool $relay Is the retraction transmitted from a relay?
2875 * @return int The result of the transmission
2877 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
2879 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
2881 // Check whether the retraction is for a top-level post or whether it's a relayable
2882 if ($item["uri"] !== $item["parent-uri"]) {
2883 $msg_type = "relayable_retraction";
2884 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2886 $msg_type = "signed_retraction";
2887 $target_type = "StatusMessage";
2890 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
2891 $signature = "parent_author_signature";
2893 $signature = "target_author_signature";
2895 $signed_text = $item["guid"].";".$target_type;
2897 $message = array("target_guid" => $item['guid'],
2898 "target_type" => $target_type,
2899 "sender_handle" => $itemaddr,
2900 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2902 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
2904 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2910 * @param array $item The item that will be exported
2911 * @param array $owner The owner
2912 * @param array $contact Target of the communication
2914 * @return int The result of the transmission
2916 public static function send_mail($item, $owner, $contact) {
2918 $myaddr = self::my_handle($owner);
2920 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2921 intval($item["convid"]),
2922 intval($item["uid"])
2926 logger("conversation not found.");
2932 "guid" => $cnv["guid"],
2933 "subject" => $cnv["subject"],
2934 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2935 "diaspora_handle" => $cnv["creator"],
2936 "participant_handles" => $cnv["recips"]
2939 $body = bb2diaspora($item["body"]);
2940 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2942 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2943 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2946 "guid" => $item["guid"],
2947 "parent_guid" => $cnv["guid"],
2948 "parent_author_signature" => $sig,
2949 "author_signature" => $sig,
2951 "created_at" => $created,
2952 "diaspora_handle" => $myaddr,
2953 "conversation_guid" => $cnv["guid"]
2956 if ($item["reply"]) {
2960 $message = array("guid" => $cnv["guid"],
2961 "subject" => $cnv["subject"],
2962 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2964 "diaspora_handle" => $cnv["creator"],
2965 "participant_handles" => $cnv["recips"]);
2967 $type = "conversation";
2970 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
2976 * @param int $uid The user id
2978 * @return int The result of the transmission
2980 public static function send_profile($uid) {
2985 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
2986 AND `uid` = %d AND `rel` != %d",
2987 dbesc(NETWORK_DIASPORA),
2989 intval(CONTACT_IS_SHARING)
2994 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
2996 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
2997 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
2998 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3007 $handle = $profile["addr"];
3008 $first = ((strpos($profile['name'],' ')
3009 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3010 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3011 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3012 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3013 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3014 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3016 if ($searchable === 'true') {
3017 $dob = '1000-00-00';
3019 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3020 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3022 $about = $profile['about'];
3023 $about = strip_tags(bbcode($about));
3025 $location = formatted_location($profile);
3027 if ($profile['pub_keywords']) {
3028 $kw = str_replace(',',' ',$profile['pub_keywords']);
3029 $kw = str_replace(' ',' ',$kw);
3030 $arr = explode(' ',$profile['pub_keywords']);
3032 for($x = 0; $x < 5; $x ++) {
3034 $tags .= '#'. trim($arr[$x]) .' ';
3038 $tags = trim($tags);
3041 $message = array("diaspora_handle" => $handle,
3042 "first_name" => $first,
3043 "last_name" => $last,
3044 "image_url" => $large,
3045 "image_url_medium" => $medium,
3046 "image_url_small" => $small,
3048 "gender" => $profile['gender'],
3050 "location" => $location,
3051 "searchable" => $searchable,
3052 "tag_string" => $tags);
3054 foreach($recips as $recip)
3055 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);