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);
835 * @param string $guid message guid
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"]);
887 * @param int $uid The user id
888 * @param string $guid message guid
890 * @param array $contact The contact that is checked
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);
932 * @param array $contact The contact that is checked
934 * @param int $uid The user id
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
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);
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
1111 * @param $conversation
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,
1234 * @param array $importer Array of the importer user
1236 * @param object $data The message object
1240 private function receive_conversation($importer, $msg, $data) {
1241 $guid = notags(unxmlify($data->guid));
1242 $subject = notags(unxmlify($data->subject));
1243 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1244 $author = notags(unxmlify($data->author));
1245 $participants = notags(unxmlify($data->participants));
1247 $messages = $data->message;
1249 if (!count($messages)) {
1250 logger("empty conversation");
1254 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1258 $conversation = null;
1260 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1261 intval($importer["uid"]),
1265 $conversation = $c[0];
1267 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1268 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1269 intval($importer["uid"]),
1272 dbesc(datetime_convert("UTC", "UTC", $created_at)),
1273 dbesc(datetime_convert()),
1275 dbesc($participants)
1278 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1279 intval($importer["uid"]),
1284 $conversation = $c[0];
1286 if (!$conversation) {
1287 logger("unable to create conversation.");
1291 foreach($messages as $mesg)
1292 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1300 * @param array $contact The contact that is checked
1301 * @param $parent_item
1302 * @param string $guid message guid
1306 private function construct_like_body($contact, $parent_item, $guid) {
1307 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1309 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1310 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1311 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1313 return sprintf($bodyverb, $ulink, $alink, $plink);
1319 * @param array $importer Array of the importer user
1320 * @param $parent_item
1324 private function construct_like_object($importer, $parent_item) {
1325 $objtype = ACTIVITY_OBJ_NOTE;
1326 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1327 $parent_body = $parent_item["body"];
1329 $xmldata = array("object" => array("type" => $objtype,
1331 "id" => $parent_item["uri"],
1334 "content" => $parent_body));
1336 return xml::from_array($xmldata, $xml, true);
1342 * @param array $importer Array of the importer user
1343 * @param string $sender The sender of the message
1344 * @param object $data The message object
1346 * @return int The message id of the generated like or "false" if there was an error
1348 private function receive_like($importer, $sender, $data) {
1349 $positive = notags(unxmlify($data->positive));
1350 $guid = notags(unxmlify($data->guid));
1351 $parent_type = notags(unxmlify($data->parent_type));
1352 $parent_guid = notags(unxmlify($data->parent_guid));
1353 $author = notags(unxmlify($data->author));
1355 // likes on comments aren't supported by Diaspora - only on posts
1356 // But maybe this will be supported in the future, so we will accept it.
1357 if (!in_array($parent_type, array("Post", "Comment")))
1360 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1364 if (self::message_exists($importer["uid"], $guid))
1367 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1371 $person = self::person_by_handle($author);
1372 if (!is_array($person)) {
1373 logger("unable to find author details");
1377 // Fetch the contact id - if we know this contact
1378 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1380 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1381 // We would accept this anyhow.
1382 if ($positive === "true")
1383 $verb = ACTIVITY_LIKE;
1385 $verb = ACTIVITY_DISLIKE;
1387 $datarray = array();
1389 $datarray["uid"] = $importer["uid"];
1390 $datarray["contact-id"] = $author_contact["cid"];
1391 $datarray["network"] = $author_contact["network"];
1393 $datarray["author-name"] = $person["name"];
1394 $datarray["author-link"] = $person["url"];
1395 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1397 $datarray["owner-name"] = $contact["name"];
1398 $datarray["owner-link"] = $contact["url"];
1399 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1401 $datarray["guid"] = $guid;
1402 $datarray["uri"] = $author.":".$guid;
1404 $datarray["type"] = "activity";
1405 $datarray["verb"] = $verb;
1406 $datarray["gravity"] = GRAVITY_LIKE;
1407 $datarray["parent-uri"] = $parent_item["uri"];
1409 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1410 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1412 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1414 $message_id = item_store($datarray);
1417 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1419 // If we are the origin of the parent we store the original data and notify our followers
1420 if($message_id AND $parent_item["origin"]) {
1422 // Formerly we stored the signed text, the signature and the author in different fields.
1423 // We now store the raw data so that we are more flexible.
1424 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1425 intval($message_id),
1426 dbesc(json_encode($data))
1430 proc_run("php", "include/notifier.php", "comment-import", $message_id);
1439 * @param array $importer Array of the importer user
1440 * @param object $data The message object
1444 private function receive_message($importer, $data) {
1445 $guid = notags(unxmlify($data->guid));
1446 $parent_guid = notags(unxmlify($data->parent_guid));
1447 $text = unxmlify($data->text);
1448 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1449 $author = notags(unxmlify($data->author));
1450 $conversation_guid = notags(unxmlify($data->conversation_guid));
1452 $contact = self::allowed_contact_by_handle($importer, $author, true);
1456 $conversation = null;
1458 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1459 intval($importer["uid"]),
1460 dbesc($conversation_guid)
1463 $conversation = $c[0];
1465 logger("conversation not available.");
1471 $body = diaspora2bb($text);
1472 $message_uri = $author.":".$guid;
1474 $person = self::person_by_handle($author);
1476 logger("unable to find author details");
1480 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1481 dbesc($message_uri),
1482 intval($importer["uid"])
1485 logger("duplicate message already delivered.", LOGGER_DEBUG);
1489 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1490 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1491 intval($importer["uid"]),
1493 intval($conversation["id"]),
1494 dbesc($person["name"]),
1495 dbesc($person["photo"]),
1496 dbesc($person["url"]),
1497 intval($contact["id"]),
1498 dbesc($conversation["subject"]),
1502 dbesc($message_uri),
1503 dbesc($author.":".$parent_guid),
1507 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1508 dbesc(datetime_convert()),
1509 intval($conversation["id"])
1518 * @param array $importer Array of the importer user
1519 * @param object $data The message object
1521 * @return bool always true
1523 private function receive_participation($importer, $data) {
1524 // I'm not sure if we can fully support this message type
1531 * @param array $importer Array of the importer user
1532 * @param object $data The message object
1536 private function receive_photo($importer, $data) {
1537 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1544 * @param array $importer Array of the importer user
1545 * @param object $data The message object
1549 private function receive_poll_participation($importer, $data) {
1550 // We don't support polls by now
1557 * @param array $importer Array of the importer user
1558 * @param object $data The message object
1562 private function receive_profile($importer, $data) {
1563 $author = notags(unxmlify($data->author));
1565 $contact = self::contact_by_handle($importer["uid"], $author);
1569 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1570 $image_url = unxmlify($data->image_url);
1571 $birthday = unxmlify($data->birthday);
1572 $location = diaspora2bb(unxmlify($data->location));
1573 $about = diaspora2bb(unxmlify($data->bio));
1574 $gender = unxmlify($data->gender);
1575 $searchable = (unxmlify($data->searchable) == "true");
1576 $nsfw = (unxmlify($data->nsfw) == "true");
1577 $tags = unxmlify($data->tag_string);
1579 $tags = explode("#", $tags);
1581 $keywords = array();
1582 foreach ($tags as $tag) {
1583 $tag = trim(strtolower($tag));
1588 $keywords = implode(", ", $keywords);
1590 $handle_parts = explode("@", $author);
1591 $nick = $handle_parts[0];
1594 $name = $handle_parts[0];
1596 if( preg_match("|^https?://|", $image_url) === 0)
1597 $image_url = "http://".$handle_parts[1].$image_url;
1599 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1601 // Generic birthday. We don't know the timezone. The year is irrelevant.
1603 $birthday = str_replace("1000", "1901", $birthday);
1605 if ($birthday != "")
1606 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1608 // this is to prevent multiple birthday notifications in a single year
1609 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1611 if(substr($birthday,5) === substr($contact["bd"],5))
1612 $birthday = $contact["bd"];
1614 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1615 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1619 dbesc(datetime_convert()),
1625 intval($contact["id"]),
1626 intval($importer["uid"])
1630 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1631 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1634 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1635 "photo" => $image_url, "name" => $name, "location" => $location,
1636 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1637 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1638 "hide" => !$searchable, "nsfw" => $nsfw);
1640 update_gcontact($gcontact);
1642 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1650 * @param array $importer Array of the importer user
1651 * @param array $contact The contact that is checked
1655 private function receive_request_make_friend($importer, $contact) {
1659 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1660 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1661 intval(CONTACT_IS_FRIEND),
1662 intval($contact["id"]),
1663 intval($importer["uid"])
1666 // send notification
1668 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1669 intval($importer["uid"])
1672 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1674 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1675 intval($importer["uid"])
1678 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1680 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1683 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1684 $arr["uid"] = $importer["uid"];
1685 $arr["contact-id"] = $self[0]["id"];
1687 $arr["type"] = 'wall';
1688 $arr["gravity"] = 0;
1690 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1691 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1692 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1693 $arr["verb"] = ACTIVITY_FRIEND;
1694 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1696 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1697 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1698 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1699 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1701 $arr["object"] = "<object><type>".ACTIVITY_OBJ_PERSON."</type><title>".$contact["name"]."</title>"
1702 ."<id>".$contact["url"]."/".$contact["name"]."</id>";
1703 $arr["object"] .= "<link>".xmlify('<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n");
1704 $arr["object"] .= xmlify('<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n");
1705 $arr["object"] .= "</link></object>\n";
1706 $arr["last-child"] = 1;
1708 $arr["allow_cid"] = $user[0]["allow_cid"];
1709 $arr["allow_gid"] = $user[0]["allow_gid"];
1710 $arr["deny_cid"] = $user[0]["deny_cid"];
1711 $arr["deny_gid"] = $user[0]["deny_gid"];
1713 $i = item_store($arr);
1715 proc_run("php", "include/notifier.php", "activity", $i);
1725 * @param array $importer Array of the importer user
1726 * @param object $data The message object
1730 private function receive_request($importer, $data) {
1731 $author = unxmlify($data->author);
1732 $recipient = unxmlify($data->recipient);
1734 if (!$author || !$recipient)
1737 $contact = self::contact_by_handle($importer["uid"],$author);
1741 // perhaps we were already sharing with this person. Now they're sharing with us.
1742 // That makes us friends.
1744 self::receive_request_make_friend($importer, $contact);
1748 $ret = self::person_by_handle($author);
1750 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
1751 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
1755 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
1757 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
1758 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
1759 intval($importer["uid"]),
1760 dbesc($ret["network"]),
1761 dbesc($ret["addr"]),
1764 dbesc(normalise_link($ret["url"])),
1766 dbesc($ret["name"]),
1767 dbesc($ret["nick"]),
1768 dbesc($ret["photo"]),
1769 dbesc($ret["pubkey"]),
1770 dbesc($ret["notify"]),
1771 dbesc($ret["poll"]),
1776 // find the contact record we just created
1778 $contact_record = self::contact_by_handle($importer["uid"],$author);
1780 if (!$contact_record) {
1781 logger("unable to locate newly created contact record.");
1785 $g = q("SELECT `def_gid` FROM `user` WHERE `uid` = %d LIMIT 1",
1786 intval($importer["uid"])
1789 if($g && intval($g[0]["def_gid"]))
1790 group_add_member($importer["uid"], "", $contact_record["id"], $g[0]["def_gid"]);
1792 if($importer["page-flags"] == PAGE_NORMAL) {
1794 $hash = random_string().(string)time(); // Generate a confirm_key
1796 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
1797 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
1798 intval($importer["uid"]),
1799 intval($contact_record["id"]),
1802 dbesc(t("Sharing notification from Diaspora network")),
1804 dbesc(datetime_convert())
1808 // automatic friend approval
1810 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
1812 // technically they are sharing with us (CONTACT_IS_SHARING),
1813 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
1814 // we are going to change the relationship and make them a follower.
1816 if($importer["page-flags"] == PAGE_FREELOVE)
1817 $new_relation = CONTACT_IS_FRIEND;
1819 $new_relation = CONTACT_IS_FOLLOWER;
1821 $r = q("UPDATE `contact` SET `rel` = %d,
1829 intval($new_relation),
1830 dbesc(datetime_convert()),
1831 dbesc(datetime_convert()),
1832 intval($contact_record["id"])
1835 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1837 $ret = self::send_share($u[0], $contact_record);
1846 * @param string $guid message guid
1847 * @param $orig_author
1852 private function original_item($guid, $orig_author, $author) {
1854 // Do we already have this item?
1855 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1856 `author-name`, `author-link`, `author-avatar`
1857 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1861 logger("reshared message ".$guid." already exists on system.");
1863 // Maybe it is already a reshared item?
1864 // Then refetch the content, since there can be many side effects with reshared posts from other networks or reshares from reshares
1865 if (self::is_reshare($r[0]["body"], false))
1872 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
1873 logger("1st try: reshared message ".$guid." will be fetched from original server: ".$server);
1874 $item_id = self::store_by_guid($guid, $server);
1877 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
1878 logger("2nd try: reshared message ".$guid." will be fetched from original server: ".$server);
1879 $item_id = self::store_by_guid($guid, $server);
1882 // Deactivated by now since there is a risk that someone could manipulate postings through this method
1884 $server = "https://".substr($author, strpos($author, "@") + 1);
1885 logger("3rd try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1886 $item_id = self::store_by_guid($guid, $server);
1889 $server = "http://".substr($author, strpos($author, "@") + 1);
1890 logger("4th try: reshared message ".$guid." will be fetched from sharer's server: ".$server);
1891 $item_id = self::store_by_guid($guid, $server);
1895 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
1896 `author-name`, `author-link`, `author-avatar`
1897 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
1911 * @param array $importer Array of the importer user
1912 * @param object $data The message object
1913 * @param string $xml The original XML of the message
1917 private function receive_reshare($importer, $data, $xml) {
1918 $root_author = notags(unxmlify($data->root_author));
1919 $root_guid = notags(unxmlify($data->root_guid));
1920 $guid = notags(unxmlify($data->guid));
1921 $author = notags(unxmlify($data->author));
1922 $public = notags(unxmlify($data->public));
1923 $created_at = notags(unxmlify($data->created_at));
1925 $contact = self::allowed_contact_by_handle($importer, $author, false);
1929 if (self::message_exists($importer["uid"], $guid))
1932 $original_item = self::original_item($root_guid, $root_author, $author);
1933 if (!$original_item)
1936 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
1938 $datarray = array();
1940 $datarray["uid"] = $importer["uid"];
1941 $datarray["contact-id"] = $contact["id"];
1942 $datarray["network"] = NETWORK_DIASPORA;
1944 $datarray["author-name"] = $contact["name"];
1945 $datarray["author-link"] = $contact["url"];
1946 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1948 $datarray["owner-name"] = $datarray["author-name"];
1949 $datarray["owner-link"] = $datarray["author-link"];
1950 $datarray["owner-avatar"] = $datarray["author-avatar"];
1952 $datarray["guid"] = $guid;
1953 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
1955 $datarray["verb"] = ACTIVITY_POST;
1956 $datarray["gravity"] = GRAVITY_PARENT;
1958 $datarray["object"] = $xml;
1960 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
1961 $original_item["guid"], $original_item["created"], $orig_url);
1962 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
1964 $datarray["tag"] = $original_item["tag"];
1965 $datarray["app"] = $original_item["app"];
1967 $datarray["plink"] = self::plink($author, $guid);
1968 $datarray["private"] = (($public == "false") ? 1 : 0);
1969 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
1971 $datarray["object-type"] = $original_item["object-type"];
1973 self::fetch_guid($datarray);
1974 $message_id = item_store($datarray);
1977 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1985 * @param array $importer Array of the importer user
1986 * @param array $contact The contact that is checked
1987 * @param object $data The message object
1991 private function item_retraction($importer, $contact, $data) {
1992 $target_type = notags(unxmlify($data->target_type));
1993 $target_guid = notags(unxmlify($data->target_guid));
1994 $author = notags(unxmlify($data->author));
1996 $person = self::person_by_handle($author);
1997 if (!is_array($person)) {
1998 logger("unable to find author detail for ".$author);
2002 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2003 dbesc($target_guid),
2004 intval($importer["uid"])
2009 // Only delete it if the author really fits
2010 if (!link_compare($r[0]["author-link"], $person["url"])) {
2011 logger("Item author ".$r[0]["author-link"]." doesn't fit to expected contact ".$person["url"], LOGGER_DEBUG);
2015 // Check if the sender is the thread owner
2016 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2017 intval($r[0]["parent"]));
2019 // Only delete it if the parent author really fits
2020 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2021 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2025 // 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
2026 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2027 dbesc(datetime_convert()),
2028 dbesc(datetime_convert()),
2031 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2033 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2035 // Now check if the retraction needs to be relayed by us
2036 if($p[0]["origin"]) {
2038 proc_run("php", "include/notifier.php", "drop", $r[0]["id"]);
2045 * @param array $importer Array of the importer user
2046 * @param string $sender The sender of the message
2047 * @param object $data The message object
2051 private function receive_retraction($importer, $sender, $data) {
2052 $target_type = notags(unxmlify($data->target_type));
2054 $contact = self::contact_by_handle($importer["uid"], $sender);
2056 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2060 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2062 switch ($target_type) {
2065 case "Post": // "Post" will be supported in a future version
2067 case "StatusMessage":
2068 return self::item_retraction($importer, $contact, $data);;
2071 /// @todo What should we do with an "unshare"?
2072 // Removing the contact isn't correct since we still can read the public items
2073 //contact_remove($contact["id"]);
2077 logger("Unknown target type ".$target_type);
2086 * @param array $importer Array of the importer user
2087 * @param object $data The message object
2088 * @param string $xml The original XML of the message
2092 private function receive_status_message($importer, $data, $xml) {
2094 $raw_message = unxmlify($data->raw_message);
2095 $guid = notags(unxmlify($data->guid));
2096 $author = notags(unxmlify($data->author));
2097 $public = notags(unxmlify($data->public));
2098 $created_at = notags(unxmlify($data->created_at));
2099 $provider_display_name = notags(unxmlify($data->provider_display_name));
2101 /// @todo enable support for polls
2102 //if ($data->poll) {
2103 // foreach ($data->poll AS $poll)
2107 $contact = self::allowed_contact_by_handle($importer, $author, false);
2111 if (self::message_exists($importer["uid"], $guid))
2115 if ($data->location)
2116 foreach ($data->location->children() AS $fieldname => $data)
2117 $address[$fieldname] = notags(unxmlify($data));
2119 $body = diaspora2bb($raw_message);
2121 $datarray = array();
2124 foreach ($data->photo AS $photo)
2125 $body = "[img]".unxmlify($photo->remote_photo_path).
2126 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2128 $datarray["object-type"] = ACTIVITY_OBJ_PHOTO;
2130 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2132 // Add OEmbed and other information to the body
2133 if (!self::is_redmatrix($contact["url"]))
2134 $body = add_page_info_to_body($body, false, true);
2137 $datarray["uid"] = $importer["uid"];
2138 $datarray["contact-id"] = $contact["id"];
2139 $datarray["network"] = NETWORK_DIASPORA;
2141 $datarray["author-name"] = $contact["name"];
2142 $datarray["author-link"] = $contact["url"];
2143 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2145 $datarray["owner-name"] = $datarray["author-name"];
2146 $datarray["owner-link"] = $datarray["author-link"];
2147 $datarray["owner-avatar"] = $datarray["author-avatar"];
2149 $datarray["guid"] = $guid;
2150 $datarray["uri"] = $datarray["parent-uri"] = $author.":".$guid;
2152 $datarray["verb"] = ACTIVITY_POST;
2153 $datarray["gravity"] = GRAVITY_PARENT;
2155 $datarray["object"] = $xml;
2157 $datarray["body"] = $body;
2159 if ($provider_display_name != "")
2160 $datarray["app"] = $provider_display_name;
2162 $datarray["plink"] = self::plink($author, $guid);
2163 $datarray["private"] = (($public == "false") ? 1 : 0);
2164 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = datetime_convert("UTC", "UTC", $created_at);
2166 if (isset($address["address"]))
2167 $datarray["location"] = $address["address"];
2169 if (isset($address["lat"]) AND isset($address["lng"]))
2170 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2172 self::fetch_guid($datarray);
2173 $message_id = item_store($datarray);
2176 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2181 /******************************************************************************************
2182 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2183 ******************************************************************************************/
2192 private function my_handle($me) {
2193 if ($contact["addr"] != "")
2194 return $contact["addr"];
2196 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2197 // So - just in case - we build the the address here.
2198 return $me["nickname"]."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2206 * @param array $contact The contact that is checked
2212 private function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2214 logger("Message: ".$msg, LOGGER_DATA);
2216 $handle = self::my_handle($user);
2218 $b64url_data = base64url_encode($msg);
2220 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2222 $type = "application/xml";
2223 $encoding = "base64url";
2224 $alg = "RSA-SHA256";
2226 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2228 $signature = rsa_sign($signable_data,$prvkey);
2229 $sig = base64url_encode($signature);
2231 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2232 "me:env" => array("me:encoding" => "base64url",
2233 "me:alg" => "RSA-SHA256",
2235 "@attributes" => array("type" => "application/xml"),
2236 "me:sig" => $sig)));
2238 $namespaces = array("" => "https://joindiaspora.com/protocol",
2239 "me" => "http://salmon-protocol.org/ns/magic-env");
2241 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2243 logger("magic_env: ".$magic_env, LOGGER_DATA);
2252 * @param array $contact The contact that is checked
2258 private function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2260 logger("Message: ".$msg, LOGGER_DATA);
2262 // without a public key nothing will work
2265 logger("pubkey missing: contact id: ".$contact["id"]);
2269 $inner_aes_key = random_string(32);
2270 $b_inner_aes_key = base64_encode($inner_aes_key);
2271 $inner_iv = random_string(16);
2272 $b_inner_iv = base64_encode($inner_iv);
2274 $outer_aes_key = random_string(32);
2275 $b_outer_aes_key = base64_encode($outer_aes_key);
2276 $outer_iv = random_string(16);
2277 $b_outer_iv = base64_encode($outer_iv);
2279 $handle = self::my_handle($user);
2281 $padded_data = pkcs5_pad($msg,16);
2282 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2284 $b64_data = base64_encode($inner_encrypted);
2287 $b64url_data = base64url_encode($b64_data);
2288 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2290 $type = "application/xml";
2291 $encoding = "base64url";
2292 $alg = "RSA-SHA256";
2294 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2296 $signature = rsa_sign($signable_data,$prvkey);
2297 $sig = base64url_encode($signature);
2299 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2300 "aes_key" => $b_inner_aes_key,
2301 "author_id" => $handle));
2303 $decrypted_header = xml::from_array($xmldata, $xml, true);
2304 $decrypted_header = pkcs5_pad($decrypted_header,16);
2306 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2308 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2310 $encrypted_outer_key_bundle = "";
2311 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2313 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2315 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2317 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2318 "ciphertext" => base64_encode($ciphertext)));
2319 $cipher_json = base64_encode($encrypted_header_json_object);
2321 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2322 "me:env" => array("me:encoding" => "base64url",
2323 "me:alg" => "RSA-SHA256",
2325 "@attributes" => array("type" => "application/xml"),
2326 "me:sig" => $sig)));
2328 $namespaces = array("" => "https://joindiaspora.com/protocol",
2329 "me" => "http://salmon-protocol.org/ns/magic-env");
2331 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2333 logger("magic_env: ".$magic_env, LOGGER_DATA);
2342 * @param array $contact The contact that is checked
2349 private function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2352 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2354 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2356 // The data that will be transmitted is double encoded via "urlencode", strange ...
2357 $slap = "xml=".urlencode(urlencode($magic_env));
2364 * @param array $owner the array of the item owner
2369 private function signature($owner, $message) {
2371 unset($sigmsg["author_signature"]);
2372 unset($sigmsg["parent_author_signature"]);
2374 $signed_text = implode(";", $sigmsg);
2376 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2382 * @param array $owner the array of the item owner
2383 * @param array $contact The contact that is checked
2385 * @param bool $public_batch Is it a public post?
2387 * @param string $guid message guid
2391 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2395 $enabled = intval(get_config("system", "diaspora_enabled"));
2399 $logid = random_string(4);
2400 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2402 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2406 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2408 if (!$queue_run && was_recently_delayed($contact["id"])) {
2411 if (!intval(get_config("system", "diaspora_test"))) {
2412 post_url($dest_url."/", $slap);
2413 $return_code = $a->get_curl_code();
2415 logger("test_mode");
2420 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2422 if(!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2423 logger("queue message");
2425 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2426 intval($contact["id"]),
2427 dbesc(NETWORK_DIASPORA),
2429 intval($public_batch)
2432 logger("add_to_queue ignored - identical item already in queue");
2434 // queue message for redelivery
2435 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2439 return(($return_code) ? $return_code : (-1));
2446 * @param array $owner the array of the item owner
2447 * @param array $contact The contact that is checked
2450 * @param bool $public_batch Is it a public post?
2451 * @param string $guid message guid
2456 private function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2458 $data = array("XML" => array("post" => array($type => $message)));
2460 $msg = xml::from_array($data, $xml);
2462 logger('message: '.$msg, LOGGER_DATA);
2463 logger('send guid '.$guid, LOGGER_DEBUG);
2465 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2468 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2471 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2473 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2475 return $return_code;
2481 * @param array $owner the array of the item owner
2482 * @param array $contact The contact that is checked
2484 * @return int The result of the transmission
2486 public static function send_share($owner,$contact) {
2488 $message = array("sender_handle" => self::my_handle($owner),
2489 "recipient_handle" => $contact["addr"]);
2491 return self::build_and_transmit($owner, $contact, "request", $message);
2497 * @param array $owner the array of the item owner
2498 * @param array $contact The contact that is checked
2500 * @return int The result of the transmission
2502 public static function send_unshare($owner,$contact) {
2504 $message = array("post_guid" => $owner["guid"],
2505 "diaspora_handle" => self::my_handle($owner),
2506 "type" => "Person");
2508 return self::build_and_transmit($owner, $contact, "retraction", $message);
2519 public static function is_reshare($body, $complete = true) {
2520 $body = trim($body);
2522 // Skip if it isn't a pure repeated messages
2523 // Does it start with a share?
2524 if (strpos($body, "[share") > 0)
2527 // Does it end with a share?
2528 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2531 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2532 // Skip if there is no shared message in there
2533 if ($body == $attributes)
2536 // If we don't do the complete check we quit here
2541 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2542 if ($matches[1] != "")
2543 $guid = $matches[1];
2545 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2546 if ($matches[1] != "")
2547 $guid = $matches[1];
2550 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2551 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2554 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2555 $ret["root_guid"] = $guid;
2561 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2562 if ($matches[1] != "")
2563 $profile = $matches[1];
2565 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2566 if ($matches[1] != "")
2567 $profile = $matches[1];
2571 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2572 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2576 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2577 if ($matches[1] != "")
2578 $link = $matches[1];
2580 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2581 if ($matches[1] != "")
2582 $link = $matches[1];
2584 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2585 if (($ret["root_guid"] == $link) OR ($ret["root_guid"] == ""))
2593 * @param array $item The item that will be exported
2594 * @param array $owner the array of the item owner
2595 * @param array $contact The contact that is checked
2596 * @param bool $public_batch Is it a public post?
2598 * @return int The result of the transmission
2600 public static function send_status($item, $owner, $contact, $public_batch = false) {
2602 $myaddr = self::my_handle($owner);
2604 $public = (($item["private"]) ? "false" : "true");
2606 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2608 // Detect a share element and do a reshare
2609 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
2610 $message = array("root_diaspora_id" => $ret["root_handle"],
2611 "root_guid" => $ret["root_guid"],
2612 "guid" => $item["guid"],
2613 "diaspora_handle" => $myaddr,
2614 "public" => $public,
2615 "created_at" => $created,
2616 "provider_display_name" => $item["app"]);
2620 $title = $item["title"];
2621 $body = $item["body"];
2623 // convert to markdown
2624 $body = html_entity_decode(bb2diaspora($body));
2628 $body = "## ".html_entity_decode($title)."\n\n".$body;
2630 if ($item["attach"]) {
2631 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
2633 $body .= "\n".t("Attachments:")."\n";
2634 foreach($matches as $mtch)
2635 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
2639 $location = array();
2641 if ($item["location"] != "")
2642 $location["address"] = $item["location"];
2644 if ($item["coord"] != "") {
2645 $coord = explode(" ", $item["coord"]);
2646 $location["lat"] = $coord[0];
2647 $location["lng"] = $coord[1];
2650 $message = array("raw_message" => $body,
2651 "location" => $location,
2652 "guid" => $item["guid"],
2653 "diaspora_handle" => $myaddr,
2654 "public" => $public,
2655 "created_at" => $created,
2656 "provider_display_name" => $item["app"]);
2658 if (count($location) == 0)
2659 unset($message["location"]);
2661 $type = "status_message";
2664 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2670 * @param array $item The item that will be exported
2671 * @param array $owner the array of the item owner
2675 private function construct_like($item, $owner) {
2677 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
2678 dbesc($item["thr-parent"]));
2684 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
2687 return(array("positive" => $positive,
2688 "guid" => $item["guid"],
2689 "target_type" => $target_type,
2690 "parent_guid" => $parent["guid"],
2691 "author_signature" => $authorsig,
2692 "diaspora_handle" => self::my_handle($owner)));
2698 * @param array $item The item that will be exported
2699 * @param array $owner the array of the item owner
2703 private function construct_comment($item, $owner) {
2705 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
2706 intval($item["parent"]),
2707 intval($item["parent"])
2715 $text = html_entity_decode(bb2diaspora($item["body"]));
2717 return(array("guid" => $item["guid"],
2718 "parent_guid" => $parent["guid"],
2719 "author_signature" => "",
2721 "diaspora_handle" => self::my_handle($owner)));
2725 * @brief Send a like or a comment
2727 * @param array $item The item that will be exported
2728 * @param array $owner the array of the item owner
2729 * @param array $contact The contact that is checked
2730 * @param bool $public_batch Is it a public post?
2732 * @return int The result of the transmission
2734 public static function send_followup($item,$owner,$contact,$public_batch = false) {
2736 if($item['verb'] === ACTIVITY_LIKE) {
2737 $message = self::construct_like($item, $owner);
2740 $message = self::construct_comment($item, $owner);
2747 $message["author_signature"] = self::signature($owner, $message);
2749 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2755 * @param array $item The item that will be exported
2758 * @return int The result of the transmission
2760 private function message_from_signatur($item, $signature) {
2762 // Split the signed text
2763 $signed_parts = explode(";", $signature['signed_text']);
2765 if ($item["deleted"])
2766 $message = array("parent_author_signature" => "",
2767 "target_guid" => $signed_parts[0],
2768 "target_type" => $signed_parts[1],
2769 "sender_handle" => $signature['signer'],
2770 "target_author_signature" => $signature['signature']);
2771 elseif ($item['verb'] === ACTIVITY_LIKE)
2772 $message = array("positive" => $signed_parts[0],
2773 "guid" => $signed_parts[1],
2774 "target_type" => $signed_parts[2],
2775 "parent_guid" => $signed_parts[3],
2776 "parent_author_signature" => "",
2777 "author_signature" => $signature['signature'],
2778 "diaspora_handle" => $signed_parts[4]);
2780 // Remove the comment guid
2781 $guid = array_shift($signed_parts);
2783 // Remove the parent guid
2784 $parent_guid = array_shift($signed_parts);
2786 // Remove the handle
2787 $handle = array_pop($signed_parts);
2789 // Glue the parts together
2790 $text = implode(";", $signed_parts);
2792 $message = array("guid" => $guid,
2793 "parent_guid" => $parent_guid,
2794 "parent_author_signature" => "",
2795 "author_signature" => $signature['signature'],
2796 "text" => implode(";", $signed_parts),
2797 "diaspora_handle" => $handle);
2805 * @param array $item The item that will be exported
2806 * @param array $owner the array of the item owner
2807 * @param array $contact The contact that is checked
2808 * @param bool $public_batch Is it a public post?
2810 * @return int The result of the transmission
2812 public static function send_relay($item, $owner, $contact, $public_batch = false) {
2814 if ($item["deleted"])
2815 return self::send_retraction($item, $owner, $contact, $public_batch, true);
2816 elseif ($item['verb'] === ACTIVITY_LIKE)
2821 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2823 // fetch the original signature
2825 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
2826 intval($item["id"]));
2829 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
2835 // Old way - is used by the internal Friendica functions
2836 /// @todo Change all signatur storing functions to the new format
2837 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
2838 $message = self::message_from_signatur($item, $signature);
2840 $msg = json_decode($signature['signed_text'], true);
2843 if (is_array($msg)) {
2844 foreach ($msg AS $field => $data) {
2845 if (!$item["deleted"]) {
2846 if ($field == "author")
2847 $field = "diaspora_handle";
2848 if ($field == "parent_type")
2849 $field = "target_type";
2852 $message[$field] = $data;
2855 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
2858 $message["parent_author_signature"] = self::signature($owner, $message);
2860 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
2862 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
2868 * @param array $item The item that will be exported
2869 * @param array $owner the array of the item owner
2870 * @param array $contact The contact that is checked
2871 * @param bool $public_batch Is it a public post?
2874 * @return int The result of the transmission
2876 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
2878 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
2880 // Check whether the retraction is for a top-level post or whether it's a relayable
2881 if ($item["uri"] !== $item["parent-uri"]) {
2882 $msg_type = "relayable_retraction";
2883 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
2885 $msg_type = "signed_retraction";
2886 $target_type = "StatusMessage";
2889 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
2890 $signature = "parent_author_signature";
2892 $signature = "target_author_signature";
2894 $signed_text = $item["guid"].";".$target_type;
2896 $message = array("target_guid" => $item['guid'],
2897 "target_type" => $target_type,
2898 "sender_handle" => $itemaddr,
2899 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
2901 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
2903 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
2909 * @param array $item The item that will be exported
2910 * @param array $owner The owner
2911 * @param array $contact The contact that is checked
2913 * @return int The result of the transmission
2915 public static function send_mail($item, $owner, $contact) {
2917 $myaddr = self::my_handle($owner);
2919 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2920 intval($item["convid"]),
2921 intval($item["uid"])
2925 logger("conversation not found.");
2931 "guid" => $cnv["guid"],
2932 "subject" => $cnv["subject"],
2933 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2934 "diaspora_handle" => $cnv["creator"],
2935 "participant_handles" => $cnv["recips"]
2938 $body = bb2diaspora($item["body"]);
2939 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d H:i:s \U\T\C');
2941 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
2942 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2945 "guid" => $item["guid"],
2946 "parent_guid" => $cnv["guid"],
2947 "parent_author_signature" => $sig,
2948 "author_signature" => $sig,
2950 "created_at" => $created,
2951 "diaspora_handle" => $myaddr,
2952 "conversation_guid" => $cnv["guid"]
2955 if ($item["reply"]) {
2959 $message = array("guid" => $cnv["guid"],
2960 "subject" => $cnv["subject"],
2961 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d H:i:s \U\T\C'),
2963 "diaspora_handle" => $cnv["creator"],
2964 "participant_handles" => $cnv["recips"]);
2966 $type = "conversation";
2969 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
2975 * @param int $uid The user id
2977 * @return int The result of the transmission
2979 public static function send_profile($uid) {
2984 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
2985 AND `uid` = %d AND `rel` != %d",
2986 dbesc(NETWORK_DIASPORA),
2988 intval(CONTACT_IS_SHARING)
2993 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
2995 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
2996 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
2997 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3006 $handle = $profile["addr"];
3007 $first = ((strpos($profile['name'],' ')
3008 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3009 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3010 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3011 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3012 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3013 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3015 if ($searchable === 'true') {
3016 $dob = '1000-00-00';
3018 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3019 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3021 $about = $profile['about'];
3022 $about = strip_tags(bbcode($about));
3024 $location = formatted_location($profile);
3026 if ($profile['pub_keywords']) {
3027 $kw = str_replace(',',' ',$profile['pub_keywords']);
3028 $kw = str_replace(' ',' ',$kw);
3029 $arr = explode(' ',$profile['pub_keywords']);
3031 for($x = 0; $x < 5; $x ++) {
3033 $tags .= '#'. trim($arr[$x]) .' ';
3037 $tags = trim($tags);
3040 $message = array("diaspora_handle" => $handle,
3041 "first_name" => $first,
3042 "last_name" => $last,
3043 "image_url" => $large,
3044 "image_url_medium" => $medium,
3045 "image_url_small" => $small,
3047 "gender" => $profile['gender'],
3049 "location" => $location,
3050 "searchable" => $searchable,
3051 "tag_string" => $tags);
3053 foreach($recips as $recip)
3054 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);