3 * @file include/diaspora.php
4 * @brief The implementation of the diaspora protocol
6 * The new protocol is described here: http://diaspora.github.io/diaspora_federation/index.html
7 * Currently this implementation here interprets the old and the new protocol and sends the old one.
8 * This will change in the future.
11 require_once("include/items.php");
12 require_once("include/bb2diaspora.php");
13 require_once("include/Scrape.php");
14 require_once("include/Contact.php");
15 require_once("include/Photo.php");
16 require_once("include/socgraph.php");
17 require_once("include/group.php");
18 require_once("include/xml.php");
19 require_once("include/datetime.php");
20 require_once("include/queue_fn.php");
21 require_once("include/cache.php");
24 * @brief This class contain functions to create and send Diaspora XML files
30 * @brief Return a list of relay servers
32 * This is an experimental Diaspora feature.
34 * @return array of relay servers
36 public static function relay_list() {
38 $serverdata = get_config("system", "relay_server");
39 if ($serverdata == "")
44 $servers = explode(",", $serverdata);
46 foreach($servers AS $server) {
47 $server = trim($server);
48 $batch = $server."/receive/public";
50 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
53 $addr = "relay@".str_replace("http://", "", normalise_link($server));
55 $r = q("INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
56 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
61 dbesc(normalise_link($server)),
63 dbesc(NETWORK_DIASPORA),
64 intval(CONTACT_IS_FOLLOWER),
65 dbesc(datetime_convert()),
66 dbesc(datetime_convert()),
67 dbesc(datetime_convert())
70 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
72 $relay[] = $relais[0];
74 $relay[] = $relais[0];
81 * @brief repairs a signature that was double encoded
83 * The function is unused at the moment. It was copied from the old implementation.
85 * @param string $signature The signature
86 * @param string $handle The handle of the signature owner
87 * @param integer $level This value is only set inside this function to avoid endless loops
89 * @return string the repaired signature
91 private static function repair_signature($signature, $handle = "", $level = 1) {
96 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
97 $signature = base64_decode($signature);
98 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
100 // Do a recursive call to be able to fix even multiple levels
102 $signature = self::repair_signature($signature, $handle, ++$level);
109 * @brief verify the envelope and return the verified data
111 * @param string $envelope The magic envelope
113 * @return string verified data
115 private static function verify_magic_envelope($envelope) {
117 $basedom = parse_xml_string($envelope, false);
119 if (!is_object($basedom)) {
120 logger("Envelope is no XML file");
124 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
126 if (sizeof($children) == 0) {
127 logger("XML has no children");
133 $data = base64url_decode($children->data);
134 $type = $children->data->attributes()->type[0];
136 $encoding = $children->encoding;
138 $alg = $children->alg;
140 $sig = base64url_decode($children->sig);
141 $key_id = $children->sig->attributes()->key_id[0];
143 $handle = base64url_decode($key_id);
145 $b64url_data = base64url_encode($data);
146 $msg = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
148 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
150 $key = self::key($handle);
152 $verify = rsa_verify($signable_data, $sig, $key);
154 logger('Message did not verify. Discarding.');
162 * @brief: Decodes incoming Diaspora message
164 * @param array $importer Array of the importer user
165 * @param string $xml urldecoded Diaspora salmon
168 * 'message' -> decoded Diaspora XML message
169 * 'author' -> author diaspora handle
170 * 'key' -> author public key (converted to pkcs#8)
172 public static function decode($importer, $xml) {
175 $basedom = parse_xml_string($xml);
177 if (!is_object($basedom))
180 $children = $basedom->children('https://joindiaspora.com/protocol');
182 if($children->header) {
184 $author_link = str_replace('acct:','',$children->header->author_id);
187 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
189 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
190 $ciphertext = base64_decode($encrypted_header->ciphertext);
192 $outer_key_bundle = '';
193 openssl_private_decrypt($encrypted_aes_key_bundle,$outer_key_bundle,$importer['prvkey']);
195 $j_outer_key_bundle = json_decode($outer_key_bundle);
197 $outer_iv = base64_decode($j_outer_key_bundle->iv);
198 $outer_key = base64_decode($j_outer_key_bundle->key);
200 $decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $outer_key, $ciphertext, MCRYPT_MODE_CBC, $outer_iv);
203 $decrypted = pkcs5_unpad($decrypted);
205 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
206 $idom = parse_xml_string($decrypted,false);
208 $inner_iv = base64_decode($idom->iv);
209 $inner_aes_key = base64_decode($idom->aes_key);
211 $author_link = str_replace('acct:','',$idom->author_id);
214 $dom = $basedom->children(NAMESPACE_SALMON_ME);
216 // figure out where in the DOM tree our data is hiding
218 if($dom->provenance->data)
219 $base = $dom->provenance;
220 elseif($dom->env->data)
226 logger('unable to locate salmon data in xml');
227 http_status_exit(400);
231 // Stash the signature away for now. We have to find their key or it won't be good for anything.
232 $signature = base64url_decode($base->sig);
236 // strip whitespace so our data element will return to one big base64 blob
237 $data = str_replace(array(" ","\t","\r","\n"),array("","","",""),$base->data);
240 // stash away some other stuff for later
242 $type = $base->data[0]->attributes()->type[0];
243 $keyhash = $base->sig[0]->attributes()->keyhash[0];
244 $encoding = $base->encoding;
248 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
252 $data = base64url_decode($data);
256 $inner_decrypted = $data;
259 // Decode the encrypted blob
261 $inner_encrypted = base64_decode($data);
262 $inner_decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $inner_encrypted, MCRYPT_MODE_CBC, $inner_iv);
263 $inner_decrypted = pkcs5_unpad($inner_decrypted);
267 logger('Could not retrieve author URI.');
268 http_status_exit(400);
270 // Once we have the author URI, go to the web and try to find their public key
271 // (first this will look it up locally if it is in the fcontact cache)
272 // This will also convert diaspora public key from pkcs#1 to pkcs#8
274 logger('Fetching key for '.$author_link);
275 $key = self::key($author_link);
278 logger('Could not retrieve author key.');
279 http_status_exit(400);
282 $verify = rsa_verify($signed_data,$signature,$key);
285 logger('Message did not verify. Discarding.');
286 http_status_exit(400);
289 logger('Message verified.');
291 return array('message' => (string)$inner_decrypted,
292 'author' => unxmlify($author_link),
293 'key' => (string)$key);
298 * @brief Dispatches public messages and find the fitting receivers
300 * @param array $msg The post that will be dispatched
302 * @return int The message id of the generated message, "true" or "false" if there was an error
304 public static function dispatch_public($msg) {
306 $enabled = intval(get_config("system", "diaspora_enabled"));
308 logger("diaspora is disabled");
312 // Use a dummy importer to import the data for the public copy
313 $importer = array("uid" => 0, "page-flags" => PAGE_FREELOVE);
314 $message_id = self::dispatch($importer,$msg);
316 // Now distribute it to the followers
317 $r = q("SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
318 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
319 AND NOT `account_expired` AND NOT `account_removed`",
320 dbesc(NETWORK_DIASPORA),
321 dbesc($msg["author"])
324 foreach ($r as $rr) {
325 logger("delivering to: ".$rr["username"]);
326 self::dispatch($rr,$msg);
329 logger("No subscribers for ".$msg["author"]." ".print_r($msg, true));
335 * @brief Dispatches the different message types to the different functions
337 * @param array $importer Array of the importer user
338 * @param array $msg The post that will be dispatched
340 * @return int The message id of the generated message, "true" or "false" if there was an error
342 public static function dispatch($importer, $msg) {
344 // The sender is the handle of the contact that sent the message.
345 // This will often be different with relayed messages (for example "like" and "comment")
346 $sender = $msg["author"];
348 if (!self::valid_posting($msg, $fields)) {
349 logger("Invalid posting");
353 $type = $fields->getName();
355 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
358 case "account_deletion":
359 return self::receive_account_deletion($importer, $fields);
362 return self::receive_comment($importer, $sender, $fields, $msg["message"]);
365 return self::receive_contact_request($importer, $fields);
368 return self::receive_conversation($importer, $msg, $fields);
371 return self::receive_like($importer, $sender, $fields);
374 return self::receive_message($importer, $fields);
376 case "participation": // Not implemented
377 return self::receive_participation($importer, $fields);
379 case "photo": // Not implemented
380 return self::receive_photo($importer, $fields);
382 case "poll_participation": // Not implemented
383 return self::receive_poll_participation($importer, $fields);
386 return self::receive_profile($importer, $fields);
389 return self::receive_reshare($importer, $fields, $msg["message"]);
392 return self::receive_retraction($importer, $sender, $fields);
394 case "status_message":
395 return self::receive_status_message($importer, $fields, $msg["message"]);
398 logger("Unknown message type ".$type);
406 * @brief Checks if a posting is valid and fetches the data fields.
408 * This function does not only check the signature.
409 * It also does the conversion between the old and the new diaspora format.
411 * @param array $msg Array with the XML, the sender handle and the sender signature
412 * @param object $fields SimpleXML object that contains the posting when it is valid
414 * @return bool Is the posting valid?
416 private static function valid_posting($msg, &$fields) {
418 $data = parse_xml_string($msg["message"], false);
420 if (!is_object($data)) {
421 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
425 $first_child = $data->getName();
427 // Is this the new or the old version?
428 if ($data->getName() == "XML") {
430 foreach ($data->post->children() as $child)
437 $type = $element->getName();
440 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
442 // All retractions are handled identically from now on.
443 // In the new version there will only be "retraction".
444 if (in_array($type, array("signed_retraction", "relayable_retraction")))
445 $type = "retraction";
447 if ($type == "request")
450 $fields = new SimpleXMLElement("<".$type."/>");
454 foreach ($element->children() AS $fieldname => $entry) {
456 // Translation for the old XML structure
457 if ($fieldname == "diaspora_handle")
458 $fieldname = "author";
460 if ($fieldname == "participant_handles")
461 $fieldname = "participants";
463 if (in_array($type, array("like", "participation"))) {
464 if ($fieldname == "target_type")
465 $fieldname = "parent_type";
468 if ($fieldname == "sender_handle")
469 $fieldname = "author";
471 if ($fieldname == "recipient_handle")
472 $fieldname = "recipient";
474 if ($fieldname == "root_diaspora_id")
475 $fieldname = "root_author";
477 if ($type == "retraction") {
478 if ($fieldname == "post_guid")
479 $fieldname = "target_guid";
481 if ($fieldname == "type")
482 $fieldname = "target_type";
486 if (($fieldname == "author_signature") AND ($entry != ""))
487 $author_signature = base64_decode($entry);
488 elseif (($fieldname == "parent_author_signature") AND ($entry != ""))
489 $parent_author_signature = base64_decode($entry);
490 elseif (!in_array($fieldname, array("author_signature", "parent_author_signature", "target_author_signature"))) {
491 if ($signed_data != "") {
493 $signed_data_parent .= ";";
496 $signed_data .= $entry;
498 if (!in_array($fieldname, array("parent_author_signature", "target_author_signature")) OR
499 ($orig_type == "relayable_retraction"))
500 xml::copy($entry, $fields, $fieldname);
503 // This is something that shouldn't happen at all.
504 if (in_array($type, array("status_message", "reshare", "profile")))
505 if ($msg["author"] != $fields->author) {
506 logger("Message handle is not the same as envelope sender. Quitting this message.");
510 // Only some message types have signatures. So we quit here for the other types.
511 if (!in_array($type, array("comment", "message", "like")))
514 // No author_signature? This is a must, so we quit.
515 if (!isset($author_signature)) {
516 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
520 if (isset($parent_author_signature)) {
521 $key = self::key($msg["author"]);
523 if (!rsa_verify($signed_data, $parent_author_signature, $key, "sha256")) {
524 logger("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, LOGGER_DEBUG);
529 $key = self::key($fields->author);
531 if (!rsa_verify($signed_data, $author_signature, $key, "sha256")) {
532 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
539 * @brief Fetches the public key for a given handle
541 * @param string $handle The handle
543 * @return string The public key
545 private static function key($handle) {
546 $handle = strval($handle);
548 logger("Fetching diaspora key for: ".$handle);
550 $r = self::person_by_handle($handle);
558 * @brief Fetches data for a given handle
560 * @param string $handle The handle
562 * @return array the queried data
564 private static function person_by_handle($handle) {
566 $r = q("SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
567 dbesc(NETWORK_DIASPORA),
572 logger("In cache ".print_r($r,true), LOGGER_DEBUG);
574 // update record occasionally so it doesn't get stale
575 $d = strtotime($person["updated"]." +00:00");
576 if ($d < strtotime("now - 14 days"))
579 if ($person["guid"] == "")
583 if (!$person OR $update) {
584 logger("create or refresh", LOGGER_DEBUG);
585 $r = probe_url($handle, PROBE_DIASPORA);
587 // Note that Friendica contacts will return a "Diaspora person"
588 // if Diaspora connectivity is enabled on their server
589 if ($r AND ($r["network"] === NETWORK_DIASPORA)) {
590 self::add_fcontact($r, $update);
598 * @brief Updates the fcontact table
600 * @param array $arr The fcontact data
601 * @param bool $update Update or insert?
603 * @return string The id of the fcontact entry
605 private static function add_fcontact($arr, $update = false) {
608 $r = q("UPDATE `fcontact` SET
622 WHERE `url` = '%s' AND `network` = '%s'",
624 dbesc($arr["photo"]),
625 dbesc($arr["request"]),
627 dbesc(strtolower($arr["addr"])),
629 dbesc($arr["batch"]),
630 dbesc($arr["notify"]),
632 dbesc($arr["confirm"]),
633 dbesc($arr["alias"]),
634 dbesc($arr["pubkey"]),
635 dbesc(datetime_convert()),
637 dbesc($arr["network"])
640 $r = q("INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
641 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
642 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
645 dbesc($arr["photo"]),
646 dbesc($arr["request"]),
650 dbesc($arr["batch"]),
651 dbesc($arr["notify"]),
653 dbesc($arr["confirm"]),
654 dbesc($arr["network"]),
655 dbesc($arr["alias"]),
656 dbesc($arr["pubkey"]),
657 dbesc(datetime_convert())
665 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
667 * @param int $contact_id The id in the contact table
668 * @param int $gcontact_id The id in the gcontact table
670 * @return string the handle
672 public static function handle_from_contact($contact_id, $gcontact_id = 0) {
675 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
677 if ($gcontact_id != 0) {
678 $r = q("SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
679 intval($gcontact_id));
681 if (dbm::is_result($r)) {
682 return strtolower($r[0]["addr"]);
686 $r = q("SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
687 intval($contact_id));
689 if (dbm::is_result($r)) {
692 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
694 if ($contact['addr'] != "") {
695 $handle = $contact['addr'];
697 $baseurl_start = strpos($contact['url'],'://') + 3;
698 $baseurl_length = strpos($contact['url'],'/profile') - $baseurl_start; // allows installations in a subdirectory--not sure how Diaspora will handle
699 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
700 $handle = $contact['nick'].'@'.$baseurl;
704 return strtolower($handle);
708 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
711 * @param mixed $fcontact_guid Hexadecimal string guid
713 * @return string the contact url or null
715 public static function url_from_contact_guid($fcontact_guid) {
716 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
718 $r = q("SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
719 dbesc(NETWORK_DIASPORA),
720 dbesc($fcontact_guid)
723 if (dbm::is_result($r)) {
731 * @brief Get a contact id for a given handle
733 * @param int $uid The user id
734 * @param string $handle The handle in the format user@domain.tld
736 * @return The contact id
738 private static function contact_by_handle($uid, $handle) {
740 // First do a direct search on the contact table
741 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
746 if (dbm::is_result($r)) {
749 // We haven't found it?
750 // We use another function for it that will possibly create a contact entry
751 $cid = get_contact($handle, $uid);
754 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
756 if (dbm::is_result($r)) {
762 $handle_parts = explode("@", $handle);
763 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
764 $r = q("SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
769 if(dbm::is_result($r)) {
773 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
778 * @brief Check if posting is allowed for this contact
780 * @param array $importer Array of the importer user
781 * @param array $contact The contact that is checked
782 * @param bool $is_comment Is the check for a comment?
784 * @return bool is the contact allowed to post?
786 private static function post_allow($importer, $contact, $is_comment = false) {
788 // perhaps we were already sharing with this person. Now they're sharing with us.
789 // That makes us friends.
790 // Normally this should have handled by getting a request - but this could get lost
791 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
792 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
793 intval(CONTACT_IS_FRIEND),
794 intval($contact["id"]),
795 intval($importer["uid"])
797 $contact["rel"] = CONTACT_IS_FRIEND;
798 logger("defining user ".$contact["nick"]." as friend");
801 if(($contact["blocked"]) || ($contact["readonly"]) || ($contact["archive"]))
803 if($contact["rel"] == CONTACT_IS_SHARING || $contact["rel"] == CONTACT_IS_FRIEND)
805 if($contact["rel"] == CONTACT_IS_FOLLOWER)
806 if(($importer["page-flags"] == PAGE_COMMUNITY) OR $is_comment)
809 // Messages for the global users are always accepted
810 if ($importer["uid"] == 0)
817 * @brief Fetches the contact id for a handle and checks if posting is allowed
819 * @param array $importer Array of the importer user
820 * @param string $handle The checked handle in the format user@domain.tld
821 * @param bool $is_comment Is the check for a comment?
823 * @return array The contact data
825 private static function allowed_contact_by_handle($importer, $handle, $is_comment = false) {
826 $contact = self::contact_by_handle($importer["uid"], $handle);
828 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
832 if (!self::post_allow($importer, $contact, $is_comment)) {
833 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
840 * @brief Does the message already exists on the system?
842 * @param int $uid The user id
843 * @param string $guid The guid of the message
845 * @return int|bool message id if the message already was stored into the system - or false.
847 private static function message_exists($uid, $guid) {
848 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
853 if (dbm::is_result($r)) {
854 logger("message ".$guid." already exists for user ".$uid);
862 * @brief Checks for links to posts in a message
864 * @param array $item The item array
866 private static function fetch_guid($item) {
867 preg_replace_callback("&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
868 function ($match) use ($item){
869 return(self::fetch_guid_sub($match, $item));
874 * @brief Checks for relative /people/* links in an item body to match local
875 * contacts or prepends the remote host taken from the author link.
877 * @param string $body The item body to replace links from
878 * @param string $author_link The author link for missing local contact fallback
880 * @return the replaced string
882 public function replace_people_guid($body, $author_link) {
883 $return = preg_replace_callback("&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
884 function ($match) use ($author_link) {
886 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
887 // 1 => '0123456789abcdef'
889 $handle = self::url_from_contact_guid($match[1]);
892 $return = '@[url='.$handle.']'.$match[2].'[/url]';
894 // No local match, restoring absolute remote URL from author scheme and host
895 $author_url = parse_url($author_link);
896 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
906 * @brief sub function of "fetch_guid" which checks for links in messages
908 * @param array $match array containing a link that has to be checked for a message link
909 * @param array $item The item array
911 private static function fetch_guid_sub($match, $item) {
912 if (!self::store_by_guid($match[1], $item["author-link"]))
913 self::store_by_guid($match[1], $item["owner-link"]);
917 * @brief Fetches an item with a given guid from a given server
919 * @param string $guid the message guid
920 * @param string $server The server address
921 * @param int $uid The user id of the user
923 * @return int the message id of the stored message or false
925 private static function store_by_guid($guid, $server, $uid = 0) {
926 $serverparts = parse_url($server);
927 $server = $serverparts["scheme"]."://".$serverparts["host"];
929 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
931 $msg = self::message($guid, $server);
936 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
938 // Now call the dispatcher
939 return self::dispatch_public($msg);
943 * @brief Fetches a message from a server
945 * @param string $guid message guid
946 * @param string $server The url of the server
947 * @param int $level Endless loop prevention
950 * 'message' => The message XML
951 * 'author' => The author handle
952 * 'key' => The public key of the author
954 private static function message($guid, $server, $level = 0) {
959 // This will work for new Diaspora servers and Friendica servers from 3.5
960 $source_url = $server."/fetch/post/".$guid;
961 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
963 $envelope = fetch_url($source_url);
965 logger("Envelope was fetched.", LOGGER_DEBUG);
966 $x = self::verify_magic_envelope($envelope);
968 logger("Envelope could not be verified.", LOGGER_DEBUG);
970 logger("Envelope was verified.", LOGGER_DEBUG);
974 // This will work for older Diaspora and Friendica servers
976 $source_url = $server."/p/".$guid.".xml";
977 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
979 $x = fetch_url($source_url);
984 $source_xml = parse_xml_string($x, false);
986 if (!is_object($source_xml))
989 if ($source_xml->post->reshare) {
990 // Reshare of a reshare - old Diaspora version
991 logger("Message is a reshare", LOGGER_DEBUG);
992 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
993 } elseif ($source_xml->getName() == "reshare") {
994 // Reshare of a reshare - new Diaspora version
995 logger("Message is a new reshare", LOGGER_DEBUG);
996 return self::message($source_xml->root_guid, $server, ++$level);
1001 // Fetch the author - for the old and the new Diaspora version
1002 if ($source_xml->post->status_message->diaspora_handle)
1003 $author = (string)$source_xml->post->status_message->diaspora_handle;
1004 elseif ($source_xml->author AND ($source_xml->getName() == "status_message"))
1005 $author = (string)$source_xml->author;
1007 // If this isn't a "status_message" then quit
1009 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1013 $msg = array("message" => $x, "author" => $author);
1015 $msg["key"] = self::key($msg["author"]);
1021 * @brief Fetches the item record of a given guid
1023 * @param int $uid The user id
1024 * @param string $guid message guid
1025 * @param string $author The handle of the item
1026 * @param array $contact The contact of the item owner
1028 * @return array the item record
1030 private static function parent_item($uid, $guid, $author, $contact) {
1031 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1032 `author-name`, `author-link`, `author-avatar`,
1033 `owner-name`, `owner-link`, `owner-avatar`
1034 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1035 intval($uid), dbesc($guid));
1038 $result = self::store_by_guid($guid, $contact["url"], $uid);
1041 $person = self::person_by_handle($author);
1042 $result = self::store_by_guid($guid, $person["url"], $uid);
1046 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1048 $r = q("SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1049 `author-name`, `author-link`, `author-avatar`,
1050 `owner-name`, `owner-link`, `owner-avatar`
1051 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1052 intval($uid), dbesc($guid));
1057 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1060 logger("parent item found: parent: ".$guid." - user: ".$uid);
1066 * @brief returns contact details
1068 * @param array $contact The default contact if the person isn't found
1069 * @param array $person The record of the person
1070 * @param int $uid The user id
1073 * 'cid' => contact id
1074 * 'network' => network type
1076 private static function author_contact_by_url($contact, $person, $uid) {
1078 $r = q("SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1079 dbesc(normalise_link($person["url"])), intval($uid));
1082 $network = $r[0]["network"];
1084 // We are receiving content from a user that is about to be terminated
1085 // This means the user is vital, so we remove a possible termination date.
1086 unmark_for_death($contact);
1088 $cid = $contact["id"];
1089 $network = NETWORK_DIASPORA;
1092 return array("cid" => $cid, "network" => $network);
1096 * @brief Is the profile a hubzilla profile?
1098 * @param string $url The profile link
1100 * @return bool is it a hubzilla server?
1102 public static function is_redmatrix($url) {
1103 return(strstr($url, "/channel/"));
1107 * @brief Generate a post link with a given handle and message guid
1109 * @param string $addr The user handle
1110 * @param string $guid message guid
1112 * @return string the post link
1114 private static function plink($addr, $guid) {
1115 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1119 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1121 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1122 // So we try another way as well.
1123 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1125 $r[0]["network"] = $s[0]["network"];
1127 if ($r[0]["network"] == NETWORK_DFRN)
1128 return(str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/"));
1130 if (self::is_redmatrix($r[0]["url"]))
1131 return $r[0]["url"]."/?f=&mid=".$guid;
1133 return "https://".substr($addr,strpos($addr,"@")+1)."/posts/".$guid;
1137 * @brief Processes an account deletion
1139 * @param array $importer Array of the importer user
1140 * @param object $data The message object
1142 * @return bool Success
1144 private static function receive_account_deletion($importer, $data) {
1146 /// @todo Account deletion should remove the contact from the global contacts as well
1148 $author = notags(unxmlify($data->author));
1150 $contact = self::contact_by_handle($importer["uid"], $author);
1152 logger("cannot find contact for author: ".$author);
1156 // We now remove the contact
1157 contact_remove($contact["id"]);
1162 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1164 * @param string $author Author handle
1165 * @param string $guid Message guid
1166 * @param boolean $onlyfound Only return uri when found in the database
1168 * @return string The constructed uri or the one from our database
1170 private static function get_uri_from_guid($author, $guid, $onlyfound = false) {
1172 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1173 if (dbm::is_result($r)) {
1174 return $r[0]["uri"];
1175 } elseif (!$onlyfound) {
1176 return $author.":".$guid;
1183 * @brief Fetch the guid from our database with a given uri
1185 * @param string $author Author handle
1186 * @param string $uri Message uri
1188 * @return string The post guid
1190 private static function get_guid_from_uri($uri, $uid) {
1192 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1193 if (dbm::is_result($r)) {
1194 return $r[0]["guid"];
1201 * @brief Processes an incoming comment
1203 * @param array $importer Array of the importer user
1204 * @param string $sender The sender of the message
1205 * @param object $data The message object
1206 * @param string $xml The original XML of the message
1208 * @return int The message id of the generated comment or "false" if there was an error
1210 private static function receive_comment($importer, $sender, $data, $xml) {
1211 $guid = notags(unxmlify($data->guid));
1212 $parent_guid = notags(unxmlify($data->parent_guid));
1213 $text = unxmlify($data->text);
1214 $author = notags(unxmlify($data->author));
1216 if (isset($data->created_at)) {
1217 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1219 $created_at = datetime_convert();
1222 if (isset($data->thread_parent_guid)) {
1223 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1224 $thr_uri = self::get_uri_from_guid("", $thread_parent_guid, true);
1229 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1234 $message_id = self::message_exists($importer["uid"], $guid);
1239 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1240 if (!$parent_item) {
1244 $person = self::person_by_handle($author);
1245 if (!is_array($person)) {
1246 logger("unable to find author details");
1250 // Fetch the contact id - if we know this contact
1251 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1253 $datarray = array();
1255 $datarray["uid"] = $importer["uid"];
1256 $datarray["contact-id"] = $author_contact["cid"];
1257 $datarray["network"] = $author_contact["network"];
1259 $datarray["author-name"] = $person["name"];
1260 $datarray["author-link"] = $person["url"];
1261 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1263 $datarray["owner-name"] = $contact["name"];
1264 $datarray["owner-link"] = $contact["url"];
1265 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1267 $datarray["guid"] = $guid;
1268 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1270 $datarray["type"] = "remote-comment";
1271 $datarray["verb"] = ACTIVITY_POST;
1272 $datarray["gravity"] = GRAVITY_COMMENT;
1274 if ($thr_uri != "") {
1275 $datarray["parent-uri"] = $thr_uri;
1277 $datarray["parent-uri"] = $parent_item["uri"];
1280 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1281 $datarray["object"] = $xml;
1283 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1285 $body = diaspora2bb($text);
1287 $datarray["body"] = self::replace_people_guid($body, $person["url"]);
1289 self::fetch_guid($datarray);
1291 $message_id = item_store($datarray);
1294 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1297 // If we are the origin of the parent we store the original data and notify our followers
1298 if($message_id AND $parent_item["origin"]) {
1300 // Formerly we stored the signed text, the signature and the author in different fields.
1301 // We now store the raw data so that we are more flexible.
1302 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1303 intval($message_id),
1304 dbesc(json_encode($data))
1308 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1315 * @brief processes and stores private messages
1317 * @param array $importer Array of the importer user
1318 * @param array $contact The contact of the message
1319 * @param object $data The message object
1320 * @param array $msg Array of the processed message, author handle and key
1321 * @param object $mesg The private message
1322 * @param array $conversation The conversation record to which this message belongs
1324 * @return bool "true" if it was successful
1326 private static function receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation) {
1327 $guid = notags(unxmlify($data->guid));
1328 $subject = notags(unxmlify($data->subject));
1329 $author = notags(unxmlify($data->author));
1331 $msg_guid = notags(unxmlify($mesg->guid));
1332 $msg_parent_guid = notags(unxmlify($mesg->parent_guid));
1333 $msg_parent_author_signature = notags(unxmlify($mesg->parent_author_signature));
1334 $msg_author_signature = notags(unxmlify($mesg->author_signature));
1335 $msg_text = unxmlify($mesg->text);
1336 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1338 // "diaspora_handle" is the element name from the old version
1339 // "author" is the element name from the new version
1340 if ($mesg->author) {
1341 $msg_author = notags(unxmlify($mesg->author));
1342 } elseif ($mesg->diaspora_handle) {
1343 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1348 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1350 if ($msg_conversation_guid != $guid) {
1351 logger("message conversation guid does not belong to the current conversation.");
1355 $body = diaspora2bb($msg_text);
1356 $message_uri = $msg_author.":".$msg_guid;
1358 $author_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1360 $author_signature = base64_decode($msg_author_signature);
1362 if (strcasecmp($msg_author,$msg["author"]) == 0) {
1366 $person = self::person_by_handle($msg_author);
1368 if (is_array($person) && x($person, "pubkey")) {
1369 $key = $person["pubkey"];
1371 logger("unable to find author details");
1376 if (!rsa_verify($author_signed_data, $author_signature, $key, "sha256")) {
1377 logger("verification failed.");
1381 if ($msg_parent_author_signature) {
1382 $owner_signed_data = $msg_guid.";".$msg_parent_guid.";".$msg_text.";".unxmlify($mesg->created_at).";".$msg_author.";".$msg_conversation_guid;
1384 $parent_author_signature = base64_decode($msg_parent_author_signature);
1388 if (!rsa_verify($owner_signed_data, $parent_author_signature, $key, "sha256")) {
1389 logger("owner verification failed.");
1394 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' LIMIT 1",
1397 if (dbm::is_result($r)) {
1398 logger("duplicate message already delivered.", LOGGER_DEBUG);
1402 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1403 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1404 intval($importer["uid"]),
1406 intval($conversation["id"]),
1407 dbesc($person["name"]),
1408 dbesc($person["photo"]),
1409 dbesc($person["url"]),
1410 intval($contact["id"]),
1415 dbesc($message_uri),
1416 dbesc($author.":".$guid),
1417 dbesc($msg_created_at)
1420 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1421 dbesc(datetime_convert()),
1422 intval($conversation["id"])
1426 "type" => NOTIFY_MAIL,
1427 "notify_flags" => $importer["notify-flags"],
1428 "language" => $importer["language"],
1429 "to_name" => $importer["username"],
1430 "to_email" => $importer["email"],
1431 "uid" =>$importer["uid"],
1432 "item" => array("subject" => $subject, "body" => $body),
1433 "source_name" => $person["name"],
1434 "source_link" => $person["url"],
1435 "source_photo" => $person["thumb"],
1436 "verb" => ACTIVITY_POST,
1443 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1445 * @param array $importer Array of the importer user
1446 * @param array $msg Array of the processed message, author handle and key
1447 * @param object $data The message object
1449 * @return bool Success
1451 private static function receive_conversation($importer, $msg, $data) {
1452 $guid = notags(unxmlify($data->guid));
1453 $subject = notags(unxmlify($data->subject));
1454 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1455 $author = notags(unxmlify($data->author));
1456 $participants = notags(unxmlify($data->participants));
1458 $messages = $data->message;
1460 if (!count($messages)) {
1461 logger("empty conversation");
1465 $contact = self::allowed_contact_by_handle($importer, $msg["author"], true);
1469 $conversation = null;
1471 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1472 intval($importer["uid"]),
1476 $conversation = $c[0];
1478 $r = q("INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1479 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1480 intval($importer["uid"]),
1484 dbesc(datetime_convert()),
1486 dbesc($participants)
1489 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1490 intval($importer["uid"]),
1495 $conversation = $c[0];
1497 if (!$conversation) {
1498 logger("unable to create conversation.");
1502 foreach($messages as $mesg)
1503 self::receive_conversation_message($importer, $contact, $data, $msg, $mesg, $conversation);
1509 * @brief Creates the body for a "like" message
1511 * @param array $contact The contact that send us the "like"
1512 * @param array $parent_item The item array of the parent item
1513 * @param string $guid message guid
1515 * @return string the body
1517 private static function construct_like_body($contact, $parent_item, $guid) {
1518 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1520 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1521 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1522 $plink = "[url=".App::get_baseurl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1524 return sprintf($bodyverb, $ulink, $alink, $plink);
1528 * @brief Creates a XML object for a "like"
1530 * @param array $importer Array of the importer user
1531 * @param array $parent_item The item array of the parent item
1533 * @return string The XML
1535 private static function construct_like_object($importer, $parent_item) {
1536 $objtype = ACTIVITY_OBJ_NOTE;
1537 $link = '<link rel="alternate" type="text/html" href="'.App::get_baseurl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1538 $parent_body = $parent_item["body"];
1540 $xmldata = array("object" => array("type" => $objtype,
1542 "id" => $parent_item["uri"],
1545 "content" => $parent_body));
1547 return xml::from_array($xmldata, $xml, true);
1551 * @brief Processes "like" messages
1553 * @param array $importer Array of the importer user
1554 * @param string $sender The sender of the message
1555 * @param object $data The message object
1557 * @return int The message id of the generated like or "false" if there was an error
1559 private static function receive_like($importer, $sender, $data) {
1560 $positive = notags(unxmlify($data->positive));
1561 $guid = notags(unxmlify($data->guid));
1562 $parent_type = notags(unxmlify($data->parent_type));
1563 $parent_guid = notags(unxmlify($data->parent_guid));
1564 $author = notags(unxmlify($data->author));
1566 // likes on comments aren't supported by Diaspora - only on posts
1567 // But maybe this will be supported in the future, so we will accept it.
1568 if (!in_array($parent_type, array("Post", "Comment")))
1571 $contact = self::allowed_contact_by_handle($importer, $sender, true);
1575 $message_id = self::message_exists($importer["uid"], $guid);
1579 $parent_item = self::parent_item($importer["uid"], $parent_guid, $author, $contact);
1583 $person = self::person_by_handle($author);
1584 if (!is_array($person)) {
1585 logger("unable to find author details");
1589 // Fetch the contact id - if we know this contact
1590 $author_contact = self::author_contact_by_url($contact, $person, $importer["uid"]);
1592 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
1593 // We would accept this anyhow.
1594 if ($positive == "true")
1595 $verb = ACTIVITY_LIKE;
1597 $verb = ACTIVITY_DISLIKE;
1599 $datarray = array();
1601 $datarray["uid"] = $importer["uid"];
1602 $datarray["contact-id"] = $author_contact["cid"];
1603 $datarray["network"] = $author_contact["network"];
1605 $datarray["author-name"] = $person["name"];
1606 $datarray["author-link"] = $person["url"];
1607 $datarray["author-avatar"] = ((x($person,"thumb")) ? $person["thumb"] : $person["photo"]);
1609 $datarray["owner-name"] = $contact["name"];
1610 $datarray["owner-link"] = $contact["url"];
1611 $datarray["owner-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
1613 $datarray["guid"] = $guid;
1614 $datarray["uri"] = self::get_uri_from_guid($author, $guid);
1616 $datarray["type"] = "activity";
1617 $datarray["verb"] = $verb;
1618 $datarray["gravity"] = GRAVITY_LIKE;
1619 $datarray["parent-uri"] = $parent_item["uri"];
1621 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
1622 $datarray["object"] = self::construct_like_object($importer, $parent_item);
1624 $datarray["body"] = self::construct_like_body($contact, $parent_item, $guid);
1626 $message_id = item_store($datarray);
1629 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1631 // If we are the origin of the parent we store the original data and notify our followers
1632 if($message_id AND $parent_item["origin"]) {
1634 // Formerly we stored the signed text, the signature and the author in different fields.
1635 // We now store the raw data so that we are more flexible.
1636 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
1637 intval($message_id),
1638 dbesc(json_encode($data))
1642 proc_run(PRIORITY_HIGH, "include/notifier.php", "comment-import", $message_id);
1649 * @brief Processes private messages
1651 * @param array $importer Array of the importer user
1652 * @param object $data The message object
1654 * @return bool Success?
1656 private static function receive_message($importer, $data) {
1657 $guid = notags(unxmlify($data->guid));
1658 $parent_guid = notags(unxmlify($data->parent_guid));
1659 $text = unxmlify($data->text);
1660 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1661 $author = notags(unxmlify($data->author));
1662 $conversation_guid = notags(unxmlify($data->conversation_guid));
1664 $contact = self::allowed_contact_by_handle($importer, $author, true);
1669 $conversation = null;
1671 $c = q("SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1672 intval($importer["uid"]),
1673 dbesc($conversation_guid)
1676 $conversation = $c[0];
1678 logger("conversation not available.");
1682 $message_uri = $author.":".$guid;
1684 $person = self::person_by_handle($author);
1686 logger("unable to find author details");
1690 $r = q("SELECT `id` FROM `mail` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1691 dbesc($message_uri),
1692 intval($importer["uid"])
1694 if (dbm::is_result($r)) {
1695 logger("duplicate message already delivered.", LOGGER_DEBUG);
1699 $body = diaspora2bb($text);
1701 $body = self::replace_people_guid($body, $person["url"]);
1703 q("INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1704 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1705 intval($importer["uid"]),
1707 intval($conversation["id"]),
1708 dbesc($person["name"]),
1709 dbesc($person["photo"]),
1710 dbesc($person["url"]),
1711 intval($contact["id"]),
1712 dbesc($conversation["subject"]),
1716 dbesc($message_uri),
1717 dbesc($author.":".$parent_guid),
1721 q("UPDATE `conv` SET `updated` = '%s' WHERE `id` = %d",
1722 dbesc(datetime_convert()),
1723 intval($conversation["id"])
1730 * @brief Processes participations - unsupported by now
1732 * @param array $importer Array of the importer user
1733 * @param object $data The message object
1735 * @return bool always true
1737 private static function receive_participation($importer, $data) {
1738 // I'm not sure if we can fully support this message type
1743 * @brief Processes photos - unneeded
1745 * @param array $importer Array of the importer user
1746 * @param object $data The message object
1748 * @return bool always true
1750 private static function receive_photo($importer, $data) {
1751 // There doesn't seem to be a reason for this function, since the photo data is transmitted in the status message as well
1756 * @brief Processes poll participations - unssupported
1758 * @param array $importer Array of the importer user
1759 * @param object $data The message object
1761 * @return bool always true
1763 private static function receive_poll_participation($importer, $data) {
1764 // We don't support polls by now
1769 * @brief Processes incoming profile updates
1771 * @param array $importer Array of the importer user
1772 * @param object $data The message object
1774 * @return bool Success
1776 private static function receive_profile($importer, $data) {
1777 $author = strtolower(notags(unxmlify($data->author)));
1779 $contact = self::contact_by_handle($importer["uid"], $author);
1783 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
1784 $image_url = unxmlify($data->image_url);
1785 $birthday = unxmlify($data->birthday);
1786 $location = diaspora2bb(unxmlify($data->location));
1787 $about = diaspora2bb(unxmlify($data->bio));
1788 $gender = unxmlify($data->gender);
1789 $searchable = (unxmlify($data->searchable) == "true");
1790 $nsfw = (unxmlify($data->nsfw) == "true");
1791 $tags = unxmlify($data->tag_string);
1793 $tags = explode("#", $tags);
1795 $keywords = array();
1796 foreach ($tags as $tag) {
1797 $tag = trim(strtolower($tag));
1802 $keywords = implode(", ", $keywords);
1804 $handle_parts = explode("@", $author);
1805 $nick = $handle_parts[0];
1808 $name = $handle_parts[0];
1810 if( preg_match("|^https?://|", $image_url) === 0)
1811 $image_url = "http://".$handle_parts[1].$image_url;
1813 update_contact_avatar($image_url, $importer["uid"], $contact["id"]);
1815 // Generic birthday. We don't know the timezone. The year is irrelevant.
1817 $birthday = str_replace("1000", "1901", $birthday);
1819 if ($birthday != "")
1820 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
1822 // this is to prevent multiple birthday notifications in a single year
1823 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
1825 if(substr($birthday,5) === substr($contact["bd"],5))
1826 $birthday = $contact["bd"];
1828 $r = q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
1829 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
1833 dbesc(datetime_convert()),
1839 intval($contact["id"]),
1840 intval($importer["uid"])
1844 poco_check($contact["url"], $name, NETWORK_DIASPORA, $image_url, $about, $location, $gender, $keywords, "",
1845 datetime_convert(), 2, $contact["id"], $importer["uid"]);
1848 $gcontact = array("url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
1849 "photo" => $image_url, "name" => $name, "location" => $location,
1850 "about" => $about, "birthday" => $birthday, "gender" => $gender,
1851 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
1852 "hide" => !$searchable, "nsfw" => $nsfw);
1854 update_gcontact($gcontact);
1856 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
1862 * @brief Processes incoming friend requests
1864 * @param array $importer Array of the importer user
1865 * @param array $contact The contact that send the request
1867 private static function receive_request_make_friend($importer, $contact) {
1871 if($contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1872 q("UPDATE `contact` SET `rel` = %d, `writable` = 1 WHERE `id` = %d AND `uid` = %d",
1873 intval(CONTACT_IS_FRIEND),
1874 intval($contact["id"]),
1875 intval($importer["uid"])
1878 // send notification
1880 $r = q("SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
1881 intval($importer["uid"])
1884 if($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(get_pconfig($importer["uid"], "system", "post_newfriend"))) {
1886 $self = q("SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
1887 intval($importer["uid"])
1890 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
1892 if($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
1895 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
1896 $arr["uid"] = $importer["uid"];
1897 $arr["contact-id"] = $self[0]["id"];
1899 $arr["type"] = 'wall';
1900 $arr["gravity"] = 0;
1902 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
1903 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
1904 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
1905 $arr["verb"] = ACTIVITY_FRIEND;
1906 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
1908 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
1909 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1910 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
1911 $arr["body"] = sprintf(t("%1$s is now friends with %2$s"), $A, $B)."\n\n\n".$Bphoto;
1913 $arr["object"] = self::construct_new_friend_object($contact);
1915 $arr["last-child"] = 1;
1917 $arr["allow_cid"] = $user[0]["allow_cid"];
1918 $arr["allow_gid"] = $user[0]["allow_gid"];
1919 $arr["deny_cid"] = $user[0]["deny_cid"];
1920 $arr["deny_gid"] = $user[0]["deny_gid"];
1922 $i = item_store($arr);
1924 proc_run(PRIORITY_HIGH, "include/notifier.php", "activity", $i);
1930 * @brief Creates a XML object for a "new friend" message
1932 * @param array $contact Array of the contact
1934 * @return string The XML
1936 private static function construct_new_friend_object($contact) {
1937 $objtype = ACTIVITY_OBJ_PERSON;
1938 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
1939 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
1941 $xmldata = array("object" => array("type" => $objtype,
1942 "title" => $contact["name"],
1943 "id" => $contact["url"]."/".$contact["name"],
1946 return xml::from_array($xmldata, $xml, true);
1950 * @brief Processes incoming sharing notification
1952 * @param array $importer Array of the importer user
1953 * @param object $data The message object
1955 * @return bool Success
1957 private static function receive_contact_request($importer, $data) {
1958 $author = unxmlify($data->author);
1959 $recipient = unxmlify($data->recipient);
1961 if (!$author || !$recipient) {
1965 // the current protocol version doesn't know these fields
1966 // That means that we will assume their existance
1967 if (isset($data->following)) {
1968 $following = (unxmlify($data->following) == "true");
1973 if (isset($data->sharing)) {
1974 $sharing = (unxmlify($data->sharing) == "true");
1979 $contact = self::contact_by_handle($importer["uid"],$author);
1981 // perhaps we were already sharing with this person. Now they're sharing with us.
1982 // That makes us friends.
1984 if ($following AND $sharing) {
1985 logger("Author ".$author." (Contact ".$contact["id"].") wants to have a bidirectional conection.", LOGGER_DEBUG);
1986 self::receive_request_make_friend($importer, $contact);
1988 // refetch the contact array
1989 $contact = self::contact_by_handle($importer["uid"],$author);
1991 // If we are now friends, we are sending a share message.
1992 // Normally we needn't to do so, but the first message could have been vanished.
1993 if (in_array($contact["rel"], array(CONTACT_IS_FRIEND, CONTACT_IS_FOLLOWER))) {
1994 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
1996 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
1997 $ret = self::send_share($u[0], $contact);
2001 } else { /// @todo Handle all possible variations of adding and retracting of permissions
2002 logger("Author ".$author." (Contact ".$contact["id"].") wants to change the relationship: Following: ".$following." - sharing: ".$sharing. "(By now unsupported)", LOGGER_DEBUG);
2007 if (!$following AND $sharing AND in_array($importer["page-flags"], array(PAGE_SOAPBOX, PAGE_NORMAL))) {
2008 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2010 } elseif (!$following AND !$sharing) {
2011 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2013 } elseif (!$following AND $sharing) {
2014 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2015 } elseif ($following AND $sharing) {
2016 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2017 } elseif ($following AND !$sharing) {
2018 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2021 $ret = self::person_by_handle($author);
2023 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2024 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2028 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2030 $r = q("INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2031 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2032 intval($importer["uid"]),
2033 dbesc($ret["network"]),
2034 dbesc($ret["addr"]),
2037 dbesc(normalise_link($ret["url"])),
2039 dbesc($ret["name"]),
2040 dbesc($ret["nick"]),
2041 dbesc($ret["photo"]),
2042 dbesc($ret["pubkey"]),
2043 dbesc($ret["notify"]),
2044 dbesc($ret["poll"]),
2049 // find the contact record we just created
2051 $contact_record = self::contact_by_handle($importer["uid"],$author);
2053 if (!$contact_record) {
2054 logger("unable to locate newly created contact record.");
2058 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2060 $def_gid = get_default_group($importer['uid'], $ret["network"]);
2062 if(intval($def_gid))
2063 group_add_member($importer["uid"], "", $contact_record["id"], $def_gid);
2065 update_contact_avatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2067 if($importer["page-flags"] == PAGE_NORMAL) {
2069 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2071 $hash = random_string().(string)time(); // Generate a confirm_key
2073 $ret = q("INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2074 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2075 intval($importer["uid"]),
2076 intval($contact_record["id"]),
2079 dbesc(t("Sharing notification from Diaspora network")),
2081 dbesc(datetime_convert())
2085 // automatic friend approval
2087 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2089 update_contact_avatar($contact_record["photo"],$importer["uid"],$contact_record["id"]);
2091 // technically they are sharing with us (CONTACT_IS_SHARING),
2092 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2093 // we are going to change the relationship and make them a follower.
2095 if (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing AND $following)
2096 $new_relation = CONTACT_IS_FRIEND;
2097 elseif (($importer["page-flags"] == PAGE_FREELOVE) AND $sharing)
2098 $new_relation = CONTACT_IS_SHARING;
2100 $new_relation = CONTACT_IS_FOLLOWER;
2102 $r = q("UPDATE `contact` SET `rel` = %d,
2110 intval($new_relation),
2111 dbesc(datetime_convert()),
2112 dbesc(datetime_convert()),
2113 intval($contact_record["id"])
2116 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2118 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2119 $ret = self::send_share($u[0], $contact_record);
2121 // Send the profile data, maybe it weren't transmitted before
2122 self::send_profile($importer["uid"], array($contact_record));
2130 * @brief Fetches a message with a given guid
2132 * @param string $guid message guid
2133 * @param string $orig_author handle of the original post
2134 * @param string $author handle of the sharer
2136 * @return array The fetched item
2138 private static function original_item($guid, $orig_author, $author) {
2140 // Do we already have this item?
2141 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2142 `author-name`, `author-link`, `author-avatar`
2143 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2146 if (dbm::is_result($r)) {
2147 logger("reshared message ".$guid." already exists on system.");
2149 // Maybe it is already a reshared item?
2150 // Then refetch the content, if it is a reshare from a reshare.
2151 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2152 if (self::is_reshare($r[0]["body"], true)) {
2154 } elseif (self::is_reshare($r[0]["body"], false)) {
2155 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2157 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2159 // Add OEmbed and other information to the body
2160 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2168 if (!dbm::is_result($r)) {
2169 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2170 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2171 $item_id = self::store_by_guid($guid, $server);
2174 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2175 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2176 $item_id = self::store_by_guid($guid, $server);
2180 $r = q("SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2181 `author-name`, `author-link`, `author-avatar`
2182 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2185 if (dbm::is_result($r)) {
2186 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2187 if (self::is_reshare($r[0]["body"], false)) {
2188 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2189 $r[0]["body"] = self::replace_people_guid($r[0]["body"], $r[0]["author-link"]);
2201 * @brief Processes a reshare message
2203 * @param array $importer Array of the importer user
2204 * @param object $data The message object
2205 * @param string $xml The original XML of the message
2207 * @return int the message id
2209 private static function receive_reshare($importer, $data, $xml) {
2210 $root_author = notags(unxmlify($data->root_author));
2211 $root_guid = notags(unxmlify($data->root_guid));
2212 $guid = notags(unxmlify($data->guid));
2213 $author = notags(unxmlify($data->author));
2214 $public = notags(unxmlify($data->public));
2215 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2217 $contact = self::allowed_contact_by_handle($importer, $author, false);
2222 $message_id = self::message_exists($importer["uid"], $guid);
2227 $original_item = self::original_item($root_guid, $root_author, $author);
2228 if (!$original_item) {
2232 $orig_url = App::get_baseurl()."/display/".$original_item["guid"];
2234 $datarray = array();
2236 $datarray["uid"] = $importer["uid"];
2237 $datarray["contact-id"] = $contact["id"];
2238 $datarray["network"] = NETWORK_DIASPORA;
2240 $datarray["author-name"] = $contact["name"];
2241 $datarray["author-link"] = $contact["url"];
2242 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2244 $datarray["owner-name"] = $datarray["author-name"];
2245 $datarray["owner-link"] = $datarray["author-link"];
2246 $datarray["owner-avatar"] = $datarray["author-avatar"];
2248 $datarray["guid"] = $guid;
2249 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2251 $datarray["verb"] = ACTIVITY_POST;
2252 $datarray["gravity"] = GRAVITY_PARENT;
2254 $datarray["object"] = $xml;
2256 $prefix = share_header($original_item["author-name"], $original_item["author-link"], $original_item["author-avatar"],
2257 $original_item["guid"], $original_item["created"], $orig_url);
2258 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2260 $datarray["tag"] = $original_item["tag"];
2261 $datarray["app"] = $original_item["app"];
2263 $datarray["plink"] = self::plink($author, $guid);
2264 $datarray["private"] = (($public == "false") ? 1 : 0);
2265 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2267 $datarray["object-type"] = $original_item["object-type"];
2269 self::fetch_guid($datarray);
2270 $message_id = item_store($datarray);
2273 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2280 * @brief Processes retractions
2282 * @param array $importer Array of the importer user
2283 * @param array $contact The contact of the item owner
2284 * @param object $data The message object
2286 * @return bool success
2288 private static function item_retraction($importer, $contact, $data) {
2289 $target_type = notags(unxmlify($data->target_type));
2290 $target_guid = notags(unxmlify($data->target_guid));
2291 $author = notags(unxmlify($data->author));
2293 $person = self::person_by_handle($author);
2294 if (!is_array($person)) {
2295 logger("unable to find author detail for ".$author);
2299 $r = q("SELECT `id`, `parent`, `parent-uri`, `author-link` FROM `item` WHERE `guid` = '%s' AND `uid` = %d AND NOT `file` LIKE '%%[%%' LIMIT 1",
2300 dbesc($target_guid),
2301 intval($importer["uid"])
2306 // Check if the sender is the thread owner
2307 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2308 intval($r[0]["parent"]));
2310 // Only delete it if the parent author really fits
2311 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2312 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2316 // 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
2317 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2318 dbesc(datetime_convert()),
2319 dbesc(datetime_convert()),
2322 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2324 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2326 // Now check if the retraction needs to be relayed by us
2327 if($p[0]["origin"]) {
2329 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2336 * @brief Receives retraction messages
2338 * @param array $importer Array of the importer user
2339 * @param string $sender The sender of the message
2340 * @param object $data The message object
2342 * @return bool Success
2344 private static function receive_retraction($importer, $sender, $data) {
2345 $target_type = notags(unxmlify($data->target_type));
2347 $contact = self::contact_by_handle($importer["uid"], $sender);
2349 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2353 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2355 switch ($target_type) {
2358 case "Post": // "Post" will be supported in a future version
2360 case "StatusMessage":
2361 return self::item_retraction($importer, $contact, $data);;
2365 /// @todo What should we do with an "unshare"?
2366 // Removing the contact isn't correct since we still can read the public items
2367 contact_remove($contact["id"]);
2371 logger("Unknown target type ".$target_type);
2378 * @brief Receives status messages
2380 * @param array $importer Array of the importer user
2381 * @param object $data The message object
2382 * @param string $xml The original XML of the message
2384 * @return int The message id of the newly created item
2386 private static function receive_status_message($importer, $data, $xml) {
2387 $raw_message = unxmlify($data->raw_message);
2388 $guid = notags(unxmlify($data->guid));
2389 $author = notags(unxmlify($data->author));
2390 $public = notags(unxmlify($data->public));
2391 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2392 $provider_display_name = notags(unxmlify($data->provider_display_name));
2394 /// @todo enable support for polls
2395 //if ($data->poll) {
2396 // foreach ($data->poll AS $poll)
2400 $contact = self::allowed_contact_by_handle($importer, $author, false);
2405 $message_id = self::message_exists($importer["uid"], $guid);
2411 if ($data->location) {
2412 foreach ($data->location->children() AS $fieldname => $data) {
2413 $address[$fieldname] = notags(unxmlify($data));
2417 $body = diaspora2bb($raw_message);
2419 $datarray = array();
2421 // Attach embedded pictures to the body
2423 foreach ($data->photo AS $photo) {
2424 $body = "[img]".unxmlify($photo->remote_photo_path).
2425 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2428 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2430 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2432 // Add OEmbed and other information to the body
2433 if (!self::is_redmatrix($contact["url"])) {
2434 $body = add_page_info_to_body($body, false, true);
2438 $datarray["uid"] = $importer["uid"];
2439 $datarray["contact-id"] = $contact["id"];
2440 $datarray["network"] = NETWORK_DIASPORA;
2442 $datarray["author-name"] = $contact["name"];
2443 $datarray["author-link"] = $contact["url"];
2444 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2446 $datarray["owner-name"] = $datarray["author-name"];
2447 $datarray["owner-link"] = $datarray["author-link"];
2448 $datarray["owner-avatar"] = $datarray["author-avatar"];
2450 $datarray["guid"] = $guid;
2451 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2453 $datarray["verb"] = ACTIVITY_POST;
2454 $datarray["gravity"] = GRAVITY_PARENT;
2456 $datarray["object"] = $xml;
2458 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2460 if ($provider_display_name != "") {
2461 $datarray["app"] = $provider_display_name;
2464 $datarray["plink"] = self::plink($author, $guid);
2465 $datarray["private"] = (($public == "false") ? 1 : 0);
2466 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2468 if (isset($address["address"])) {
2469 $datarray["location"] = $address["address"];
2472 if (isset($address["lat"]) AND isset($address["lng"])) {
2473 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2476 self::fetch_guid($datarray);
2477 $message_id = item_store($datarray);
2480 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2486 /* ************************************************************************************** *
2487 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2488 * ************************************************************************************** */
2491 * @brief returnes the handle of a contact
2493 * @param array $me contact array
2495 * @return string the handle in the format user@domain.tld
2497 private static function my_handle($contact) {
2498 if ($contact["addr"] != "")
2499 return $contact["addr"];
2501 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2502 // So - just in case - we build the the address here.
2503 if ($contact["nickname"] != "")
2504 $nick = $contact["nickname"];
2506 $nick = $contact["nick"];
2508 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2512 * @brief Creates the envelope for the "fetch" endpoint
2514 * @param string $msg The message that is to be transmitted
2515 * @param array $user The record of the sender
2517 * @return string The envelope
2520 public static function build_magic_envelope($msg, $user) {
2522 $b64url_data = base64url_encode($msg);
2523 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2525 $key_id = base64url_encode(self::my_handle($user));
2526 $type = "application/xml";
2527 $encoding = "base64url";
2528 $alg = "RSA-SHA256";
2529 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2530 $signature = rsa_sign($signable_data, $user["prvkey"]);
2531 $sig = base64url_encode($signature);
2533 $xmldata = array("me:env" => array("me:data" => $data,
2534 "@attributes" => array("type" => $type),
2535 "me:encoding" => $encoding,
2538 "@attributes2" => array("key_id" => $key_id)));
2540 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2542 return xml::from_array($xmldata, $xml, false, $namespaces);
2546 * @brief Creates the envelope for a public message
2548 * @param string $msg The message that is to be transmitted
2549 * @param array $user The record of the sender
2550 * @param array $contact Target of the communication
2551 * @param string $prvkey The private key of the sender
2552 * @param string $pubkey The public key of the receiver
2554 * @return string The envelope
2556 private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2558 logger("Message: ".$msg, LOGGER_DATA);
2560 $handle = self::my_handle($user);
2562 $b64url_data = base64url_encode($msg);
2564 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2566 $type = "application/xml";
2567 $encoding = "base64url";
2568 $alg = "RSA-SHA256";
2570 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2572 $signature = rsa_sign($signable_data,$prvkey);
2573 $sig = base64url_encode($signature);
2575 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2576 "me:env" => array("me:encoding" => $encoding,
2579 "@attributes" => array("type" => $type),
2580 "me:sig" => $sig)));
2582 $namespaces = array("" => "https://joindiaspora.com/protocol",
2583 "me" => "http://salmon-protocol.org/ns/magic-env");
2585 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2587 logger("magic_env: ".$magic_env, LOGGER_DATA);
2592 * @brief Creates the envelope for a private message
2594 * @param string $msg The message that is to be transmitted
2595 * @param array $user The record of the sender
2596 * @param array $contact Target of the communication
2597 * @param string $prvkey The private key of the sender
2598 * @param string $pubkey The public key of the receiver
2600 * @return string The envelope
2602 private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2604 logger("Message: ".$msg, LOGGER_DATA);
2606 // without a public key nothing will work
2609 logger("pubkey missing: contact id: ".$contact["id"]);
2613 $inner_aes_key = random_string(32);
2614 $b_inner_aes_key = base64_encode($inner_aes_key);
2615 $inner_iv = random_string(16);
2616 $b_inner_iv = base64_encode($inner_iv);
2618 $outer_aes_key = random_string(32);
2619 $b_outer_aes_key = base64_encode($outer_aes_key);
2620 $outer_iv = random_string(16);
2621 $b_outer_iv = base64_encode($outer_iv);
2623 $handle = self::my_handle($user);
2625 $padded_data = pkcs5_pad($msg,16);
2626 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2628 $b64_data = base64_encode($inner_encrypted);
2631 $b64url_data = base64url_encode($b64_data);
2632 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2634 $type = "application/xml";
2635 $encoding = "base64url";
2636 $alg = "RSA-SHA256";
2638 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2640 $signature = rsa_sign($signable_data,$prvkey);
2641 $sig = base64url_encode($signature);
2643 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2644 "aes_key" => $b_inner_aes_key,
2645 "author_id" => $handle));
2647 $decrypted_header = xml::from_array($xmldata, $xml, true);
2648 $decrypted_header = pkcs5_pad($decrypted_header,16);
2650 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2652 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2654 $encrypted_outer_key_bundle = "";
2655 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2657 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2659 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2661 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2662 "ciphertext" => base64_encode($ciphertext)));
2663 $cipher_json = base64_encode($encrypted_header_json_object);
2665 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2666 "me:env" => array("me:encoding" => $encoding,
2669 "@attributes" => array("type" => $type),
2670 "me:sig" => $sig)));
2672 $namespaces = array("" => "https://joindiaspora.com/protocol",
2673 "me" => "http://salmon-protocol.org/ns/magic-env");
2675 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2677 logger("magic_env: ".$magic_env, LOGGER_DATA);
2682 * @brief Create the envelope for a message
2684 * @param string $msg The message that is to be transmitted
2685 * @param array $user The record of the sender
2686 * @param array $contact Target of the communication
2687 * @param string $prvkey The private key of the sender
2688 * @param string $pubkey The public key of the receiver
2689 * @param bool $public Is the message public?
2691 * @return string The message that will be transmitted to other servers
2693 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2696 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2698 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2700 // The data that will be transmitted is double encoded via "urlencode", strange ...
2701 $slap = "xml=".urlencode(urlencode($magic_env));
2706 * @brief Creates a signature for a message
2708 * @param array $owner the array of the owner of the message
2709 * @param array $message The message that is to be signed
2711 * @return string The signature
2713 private static function signature($owner, $message) {
2715 unset($sigmsg["author_signature"]);
2716 unset($sigmsg["parent_author_signature"]);
2718 $signed_text = implode(";", $sigmsg);
2720 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2724 * @brief Transmit a message to a target server
2726 * @param array $owner the array of the item owner
2727 * @param array $contact Target of the communication
2728 * @param string $slap The message that is to be transmitted
2729 * @param bool $public_batch Is it a public post?
2730 * @param bool $queue_run Is the transmission called from the queue?
2731 * @param string $guid message guid
2733 * @return int Result of the transmission
2735 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2739 $enabled = intval(get_config("system", "diaspora_enabled"));
2743 $logid = random_string(4);
2744 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2746 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2750 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2752 if (!$queue_run && was_recently_delayed($contact["id"])) {
2755 if (!intval(get_config("system", "diaspora_test"))) {
2756 post_url($dest_url."/", $slap);
2757 $return_code = $a->get_curl_code();
2759 logger("test_mode");
2764 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2766 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2767 logger("queue message");
2769 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2770 intval($contact["id"]),
2771 dbesc(NETWORK_DIASPORA),
2773 intval($public_batch)
2776 logger("add_to_queue ignored - identical item already in queue");
2778 // queue message for redelivery
2779 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2781 // The message could not be delivered. We mark the contact as "dead"
2782 mark_for_death($contact);
2784 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2785 // We successfully delivered a message, the contact is alive
2786 unmark_for_death($contact);
2789 return(($return_code) ? $return_code : (-1));
2794 * @brief Build the post xml
2796 * @param string $type The message type
2797 * @param array $message The message data
2799 * @return string The post XML
2801 public static function build_post_xml($type, $message) {
2803 $data = array("XML" => array("post" => array($type => $message)));
2804 return xml::from_array($data, $xml);
2808 * @brief Builds and transmit messages
2810 * @param array $owner the array of the item owner
2811 * @param array $contact Target of the communication
2812 * @param string $type The message type
2813 * @param array $message The message data
2814 * @param bool $public_batch Is it a public post?
2815 * @param string $guid message guid
2816 * @param bool $spool Should the transmission be spooled or transmitted?
2818 * @return int Result of the transmission
2820 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2822 $msg = self::build_post_xml($type, $message);
2824 logger('message: '.$msg, LOGGER_DATA);
2825 logger('send guid '.$guid, LOGGER_DEBUG);
2827 // Fallback if the private key wasn't transmitted in the expected field
2828 if ($owner['uprvkey'] == "")
2829 $owner['uprvkey'] = $owner['prvkey'];
2831 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2834 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2837 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2839 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2841 return $return_code;
2845 * @brief Sends a "share" message
2847 * @param array $owner the array of the item owner
2848 * @param array $contact Target of the communication
2850 * @return int The result of the transmission
2852 public static function send_share($owner,$contact) {
2854 $message = array("sender_handle" => self::my_handle($owner),
2855 "recipient_handle" => $contact["addr"]);
2857 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2859 return self::build_and_transmit($owner, $contact, "request", $message);
2863 * @brief sends an "unshare"
2865 * @param array $owner the array of the item owner
2866 * @param array $contact Target of the communication
2868 * @return int The result of the transmission
2870 public static function send_unshare($owner,$contact) {
2872 $message = array("post_guid" => $owner["guid"],
2873 "diaspora_handle" => self::my_handle($owner),
2874 "type" => "Person");
2876 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2878 return self::build_and_transmit($owner, $contact, "retraction", $message);
2882 * @brief Checks a message body if it is a reshare
2884 * @param string $body The message body that is to be check
2885 * @param bool $complete Should it be a complete check or a simple check?
2887 * @return array|bool Reshare details or "false" if no reshare
2889 public static function is_reshare($body, $complete = true) {
2890 $body = trim($body);
2892 // Skip if it isn't a pure repeated messages
2893 // Does it start with a share?
2894 if ((strpos($body, "[share") > 0) AND $complete)
2897 // Does it end with a share?
2898 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2901 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2902 // Skip if there is no shared message in there
2903 if ($body == $attributes)
2906 // If we don't do the complete check we quit here
2911 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2912 if ($matches[1] != "")
2913 $guid = $matches[1];
2915 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2916 if ($matches[1] != "")
2917 $guid = $matches[1];
2920 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2921 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2924 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2925 $ret["root_guid"] = $guid;
2931 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2932 if ($matches[1] != "")
2933 $profile = $matches[1];
2935 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2936 if ($matches[1] != "")
2937 $profile = $matches[1];
2941 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2942 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2946 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2947 if ($matches[1] != "")
2948 $link = $matches[1];
2950 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2951 if ($matches[1] != "")
2952 $link = $matches[1];
2954 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2955 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2962 * @brief Create an event array
2964 * @param integer $event_id The id of the event
2966 * @return array with event data
2968 private static function build_event($event_id) {
2970 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
2971 if (!dbm::is_result($r)) {
2977 $eventdata = array();
2979 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
2980 if (!dbm::is_result($r)) {
2986 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
2987 if (!dbm::is_result($r)) {
2993 $eventdata['author'] = self::my_handle($owner);
2995 if ($event['guid']) {
2996 $eventdata['guid'] = $event['guid'];
2999 $mask = 'Y-m-d\TH:i:s\Z';
3001 /// @todo - establish "all day" events in Friendica
3002 $eventdata["all_day"] = "false";
3004 if (!$event['adjust']) {
3005 $eventdata['timezone'] = $user['timezone'];
3007 if ($eventdata['timezone'] == "") {
3008 $eventdata['timezone'] = 'UTC';
3012 if ($event['start']) {
3013 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3015 if ($event['finish'] AND !$event['nofinish']) {
3016 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3018 if ($event['summary']) {
3019 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3021 if ($event['desc']) {
3022 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3024 if ($event['location']) {
3025 $location = array();
3026 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3027 $location["lat"] = 0;
3028 $location["lng"] = 0;
3029 $eventdata['location'] = $location;
3036 * @brief Create a post (status message or reshare)
3038 * @param array $item The item that will be exported
3039 * @param array $owner the array of the item owner
3042 * 'type' -> Message type ("status_message" or "reshare")
3043 * 'message' -> Array of XML elements of the status
3045 public static function build_status($item, $owner) {
3047 $cachekey = "diaspora:build_status:".$item['guid'];
3049 $result = Cache::get($cachekey);
3050 if (!is_null($result)) {
3054 $myaddr = self::my_handle($owner);
3056 $public = (($item["private"]) ? "false" : "true");
3058 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3060 // Detect a share element and do a reshare
3061 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3062 $message = array("root_diaspora_id" => $ret["root_handle"],
3063 "root_guid" => $ret["root_guid"],
3064 "guid" => $item["guid"],
3065 "diaspora_handle" => $myaddr,
3066 "public" => $public,
3067 "created_at" => $created,
3068 "provider_display_name" => $item["app"]);
3072 $title = $item["title"];
3073 $body = $item["body"];
3075 // convert to markdown
3076 $body = html_entity_decode(bb2diaspora($body));
3080 $body = "## ".html_entity_decode($title)."\n\n".$body;
3082 if ($item["attach"]) {
3083 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3085 $body .= "\n".t("Attachments:")."\n";
3086 foreach($matches as $mtch)
3087 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3091 $location = array();
3093 if ($item["location"] != "")
3094 $location["address"] = $item["location"];
3096 if ($item["coord"] != "") {
3097 $coord = explode(" ", $item["coord"]);
3098 $location["lat"] = $coord[0];
3099 $location["lng"] = $coord[1];
3102 $message = array("raw_message" => $body,
3103 "location" => $location,
3104 "guid" => $item["guid"],
3105 "diaspora_handle" => $myaddr,
3106 "public" => $public,
3107 "created_at" => $created,
3108 "provider_display_name" => $item["app"]);
3110 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3111 if (!isset($location["lat"]) OR !isset($location["lng"])) {
3112 unset($message["location"]);
3115 if ($item['event-id'] > 0) {
3116 $event = self::build_event($item['event-id']);
3117 if (count($event)) {
3118 $message['event'] = $event;
3120 /// @todo Once Diaspora supports it, we will remove the body
3121 // $message['raw_message'] = '';
3125 $type = "status_message";
3128 $msg = array("type" => $type, "message" => $message);
3130 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3136 * @brief Sends a post
3138 * @param array $item The item that will be exported
3139 * @param array $owner the array of the item owner
3140 * @param array $contact Target of the communication
3141 * @param bool $public_batch Is it a public post?
3143 * @return int The result of the transmission
3145 public static function send_status($item, $owner, $contact, $public_batch = false) {
3147 $status = self::build_status($item, $owner);
3149 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3153 * @brief Creates a "like" object
3155 * @param array $item The item that will be exported
3156 * @param array $owner the array of the item owner
3158 * @return array The data for a "like"
3160 private static function construct_like($item, $owner) {
3162 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3163 dbesc($item["thr-parent"]));
3164 if (!dbm::is_result($p))
3169 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3170 if ($item['verb'] === ACTIVITY_LIKE) {
3172 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3173 $positive = "false";
3176 return(array("positive" => $positive,
3177 "guid" => $item["guid"],
3178 "target_type" => $target_type,
3179 "parent_guid" => $parent["guid"],
3180 "author_signature" => "",
3181 "diaspora_handle" => self::my_handle($owner)));
3185 * @brief Creates an "EventParticipation" object
3187 * @param array $item The item that will be exported
3188 * @param array $owner the array of the item owner
3190 * @return array The data for an "EventParticipation"
3192 private static function construct_attend($item, $owner) {
3194 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3195 dbesc($item["thr-parent"]));
3196 if (!dbm::is_result($p))
3201 switch ($item['verb']) {
3202 case ACTIVITY_ATTEND:
3203 $attend_answer = 'accepted';
3205 case ACTIVITY_ATTENDNO:
3206 $attend_answer = 'declined';
3208 case ACTIVITY_ATTENDMAYBE:
3209 $attend_answer = 'tentative';
3212 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3216 return(array("author" => self::my_handle($owner),
3217 "guid" => $item["guid"],
3218 "parent_guid" => $parent["guid"],
3219 "status" => $attend_answer,
3220 "author_signature" => ""));
3224 * @brief Creates the object for a comment
3226 * @param array $item The item that will be exported
3227 * @param array $owner the array of the item owner
3229 * @return array The data for a comment
3231 private static function construct_comment($item, $owner) {
3233 $cachekey = "diaspora:construct_comment:".$item['guid'];
3235 $result = Cache::get($cachekey);
3236 if (!is_null($result)) {
3240 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3241 intval($item["parent"]),
3242 intval($item["parent"])
3245 if (!dbm::is_result($p))
3250 $text = html_entity_decode(bb2diaspora($item["body"]));
3251 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3253 $comment = array("guid" => $item["guid"],
3254 "parent_guid" => $parent["guid"],
3255 "author_signature" => "",
3257 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3258 "diaspora_handle" => self::my_handle($owner));
3260 // Send the thread parent guid only if it is a threaded comment
3261 if ($item['thr-parent'] != $item['parent-uri']) {
3262 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3265 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3271 * @brief Send a like or a comment
3273 * @param array $item The item that will be exported
3274 * @param array $owner the array of the item owner
3275 * @param array $contact Target of the communication
3276 * @param bool $public_batch Is it a public post?
3278 * @return int The result of the transmission
3280 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3282 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3283 $message = self::construct_attend($item, $owner);
3284 $type = "event_participation";
3285 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3286 $message = self::construct_like($item, $owner);
3289 $message = self::construct_comment($item, $owner);
3296 $message["author_signature"] = self::signature($owner, $message);
3298 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3302 * @brief Creates a message from a signature record entry
3304 * @param array $item The item that will be exported
3305 * @param array $signature The entry of the "sign" record
3307 * @return string The message
3309 private static function message_from_signature($item, $signature) {
3311 // Split the signed text
3312 $signed_parts = explode(";", $signature['signed_text']);
3314 if ($item["deleted"])
3315 $message = array("parent_author_signature" => "",
3316 "target_guid" => $signed_parts[0],
3317 "target_type" => $signed_parts[1],
3318 "sender_handle" => $signature['signer'],
3319 "target_author_signature" => $signature['signature']);
3320 elseif ($item['verb'] === ACTIVITY_LIKE)
3321 $message = array("positive" => $signed_parts[0],
3322 "guid" => $signed_parts[1],
3323 "target_type" => $signed_parts[2],
3324 "parent_guid" => $signed_parts[3],
3325 "parent_author_signature" => "",
3326 "author_signature" => $signature['signature'],
3327 "diaspora_handle" => $signed_parts[4]);
3329 // Remove the comment guid
3330 $guid = array_shift($signed_parts);
3332 // Remove the parent guid
3333 $parent_guid = array_shift($signed_parts);
3335 // Remove the handle
3336 $handle = array_pop($signed_parts);
3338 // Glue the parts together
3339 $text = implode(";", $signed_parts);
3341 $message = array("guid" => $guid,
3342 "parent_guid" => $parent_guid,
3343 "parent_author_signature" => "",
3344 "author_signature" => $signature['signature'],
3345 "text" => implode(";", $signed_parts),
3346 "diaspora_handle" => $handle);
3352 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3354 * @param array $item The item that will be exported
3355 * @param array $owner the array of the item owner
3356 * @param array $contact Target of the communication
3357 * @param bool $public_batch Is it a public post?
3359 * @return int The result of the transmission
3361 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3363 if ($item["deleted"])
3364 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3365 elseif ($item['verb'] === ACTIVITY_LIKE)
3370 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3372 // fetch the original signature
3374 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3375 intval($item["id"]));
3378 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3384 // Old way - is used by the internal Friendica functions
3385 /// @todo Change all signatur storing functions to the new format
3386 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3387 $message = self::message_from_signature($item, $signature);
3389 $msg = json_decode($signature['signed_text'], true);
3392 if (is_array($msg)) {
3393 foreach ($msg AS $field => $data) {
3394 if (!$item["deleted"]) {
3395 if ($field == "author")
3396 $field = "diaspora_handle";
3397 if ($field == "parent_type")
3398 $field = "target_type";
3401 $message[$field] = $data;
3404 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3407 $message["parent_author_signature"] = self::signature($owner, $message);
3409 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3411 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3415 * @brief Sends a retraction (deletion) of a message, like or comment
3417 * @param array $item The item that will be exported
3418 * @param array $owner the array of the item owner
3419 * @param array $contact Target of the communication
3420 * @param bool $public_batch Is it a public post?
3421 * @param bool $relay Is the retraction transmitted from a relay?
3423 * @return int The result of the transmission
3425 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3427 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3429 // Check whether the retraction is for a top-level post or whether it's a relayable
3430 if ($item["uri"] !== $item["parent-uri"]) {
3431 $msg_type = "relayable_retraction";
3432 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3434 $msg_type = "signed_retraction";
3435 $target_type = "StatusMessage";
3438 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3439 $signature = "parent_author_signature";
3441 $signature = "target_author_signature";
3443 $signed_text = $item["guid"].";".$target_type;
3445 $message = array("target_guid" => $item['guid'],
3446 "target_type" => $target_type,
3447 "sender_handle" => $itemaddr,
3448 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3450 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3452 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3456 * @brief Sends a mail
3458 * @param array $item The item that will be exported
3459 * @param array $owner The owner
3460 * @param array $contact Target of the communication
3462 * @return int The result of the transmission
3464 public static function send_mail($item, $owner, $contact) {
3466 $myaddr = self::my_handle($owner);
3468 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3469 intval($item["convid"]),
3470 intval($item["uid"])
3473 if (!dbm::is_result($r)) {
3474 logger("conversation not found.");
3480 "guid" => $cnv["guid"],
3481 "subject" => $cnv["subject"],
3482 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3483 "diaspora_handle" => $cnv["creator"],
3484 "participant_handles" => $cnv["recips"]
3487 $body = bb2diaspora($item["body"]);
3488 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3490 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3491 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3494 "guid" => $item["guid"],
3495 "parent_guid" => $cnv["guid"],
3496 "parent_author_signature" => $sig,
3497 "author_signature" => $sig,
3499 "created_at" => $created,
3500 "diaspora_handle" => $myaddr,
3501 "conversation_guid" => $cnv["guid"]
3504 if ($item["reply"]) {
3508 $message = array("guid" => $cnv["guid"],
3509 "subject" => $cnv["subject"],
3510 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3512 "diaspora_handle" => $cnv["creator"],
3513 "participant_handles" => $cnv["recips"]);
3515 $type = "conversation";
3518 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3522 * @brief Sends profile data
3524 * @param int $uid The user id
3526 public static function send_profile($uid, $recips = false) {
3532 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3533 AND `uid` = %d AND `rel` != %d",
3534 dbesc(NETWORK_DIASPORA),
3536 intval(CONTACT_IS_SHARING)
3541 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3543 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3544 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3545 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3554 $handle = $profile["addr"];
3555 $first = ((strpos($profile['name'],' ')
3556 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3557 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3558 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3559 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3560 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3561 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3563 if ($searchable === 'true') {
3564 $dob = '1000-00-00';
3566 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3567 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3569 $about = $profile['about'];
3570 $about = strip_tags(bbcode($about));
3572 $location = formatted_location($profile);
3574 if ($profile['pub_keywords']) {
3575 $kw = str_replace(',',' ',$profile['pub_keywords']);
3576 $kw = str_replace(' ',' ',$kw);
3577 $arr = explode(' ',$profile['pub_keywords']);
3579 for($x = 0; $x < 5; $x ++) {
3581 $tags .= '#'. trim($arr[$x]) .' ';
3585 $tags = trim($tags);
3588 $message = array("diaspora_handle" => $handle,
3589 "first_name" => $first,
3590 "last_name" => $last,
3591 "image_url" => $large,
3592 "image_url_medium" => $medium,
3593 "image_url_small" => $small,
3595 "gender" => $profile['gender'],
3597 "location" => $location,
3598 "searchable" => $searchable,
3599 "tag_string" => $tags);
3601 foreach($recips as $recip) {
3602 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3603 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3608 * @brief Stores the signature for likes that are created on our system
3610 * @param array $contact The contact array of the "like"
3611 * @param int $post_id The post id of the "like"
3613 * @return bool Success
3615 public static function store_like_signature($contact, $post_id) {
3617 // Is the contact the owner? Then fetch the private key
3618 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3619 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3623 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3627 $contact["uprvkey"] = $r[0]['prvkey'];
3629 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3633 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3636 $message = self::construct_like($r[0], $contact);
3637 $message["author_signature"] = self::signature($contact, $message);
3639 // We now store the signature more flexible to dynamically support new fields.
3640 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3641 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3642 intval($message_id),
3643 dbesc(json_encode($message))
3646 logger('Stored diaspora like signature');
3651 * @brief Stores the signature for comments that are created on our system
3653 * @param array $item The item array of the comment
3654 * @param array $contact The contact array of the item owner
3655 * @param string $uprvkey The private key of the sender
3656 * @param int $message_id The message id of the comment
3658 * @return bool Success
3660 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3662 if ($uprvkey == "") {
3663 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3667 $contact["uprvkey"] = $uprvkey;
3669 $message = self::construct_comment($item, $contact);
3670 $message["author_signature"] = self::signature($contact, $message);
3672 // We now store the signature more flexible to dynamically support new fields.
3673 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3674 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3675 intval($message_id),
3676 dbesc(json_encode($message))
3679 logger('Stored diaspora comment signature');