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"])
2307 // Check if the sender is the thread owner
2308 $p = q("SELECT `id`, `author-link`, `origin` FROM `item` WHERE `id` = %d",
2309 intval($r[0]["parent"]));
2311 // Only delete it if the parent author really fits
2312 if (!link_compare($p[0]["author-link"], $contact["url"]) AND !link_compare($r[0]["author-link"], $contact["url"])) {
2313 logger("Thread author ".$p[0]["author-link"]." and item author ".$r[0]["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2317 // 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
2318 q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s', `body` = '' , `title` = '' WHERE `id` = %d",
2319 dbesc(datetime_convert()),
2320 dbesc(datetime_convert()),
2323 delete_thread($r[0]["id"], $r[0]["parent-uri"]);
2325 logger("Deleted target ".$target_guid." (".$r[0]["id"].") from user ".$importer["uid"]." parent: ".$p[0]["id"], LOGGER_DEBUG);
2327 // Now check if the retraction needs to be relayed by us
2328 if ($p[0]["origin"]) {
2330 proc_run(PRIORITY_HIGH, "include/notifier.php", "drop", $r[0]["id"]);
2337 * @brief Receives retraction messages
2339 * @param array $importer Array of the importer user
2340 * @param string $sender The sender of the message
2341 * @param object $data The message object
2343 * @return bool Success
2345 private static function receive_retraction($importer, $sender, $data) {
2346 $target_type = notags(unxmlify($data->target_type));
2348 $contact = self::contact_by_handle($importer["uid"], $sender);
2350 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2354 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2356 switch ($target_type) {
2359 case "Post": // "Post" will be supported in a future version
2361 case "StatusMessage":
2362 return self::item_retraction($importer, $contact, $data);;
2366 /// @todo What should we do with an "unshare"?
2367 // Removing the contact isn't correct since we still can read the public items
2368 contact_remove($contact["id"]);
2372 logger("Unknown target type ".$target_type);
2379 * @brief Receives status messages
2381 * @param array $importer Array of the importer user
2382 * @param object $data The message object
2383 * @param string $xml The original XML of the message
2385 * @return int The message id of the newly created item
2387 private static function receive_status_message($importer, $data, $xml) {
2388 $raw_message = unxmlify($data->raw_message);
2389 $guid = notags(unxmlify($data->guid));
2390 $author = notags(unxmlify($data->author));
2391 $public = notags(unxmlify($data->public));
2392 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2393 $provider_display_name = notags(unxmlify($data->provider_display_name));
2395 /// @todo enable support for polls
2396 //if ($data->poll) {
2397 // foreach ($data->poll AS $poll)
2401 $contact = self::allowed_contact_by_handle($importer, $author, false);
2406 $message_id = self::message_exists($importer["uid"], $guid);
2412 if ($data->location) {
2413 foreach ($data->location->children() AS $fieldname => $data) {
2414 $address[$fieldname] = notags(unxmlify($data));
2418 $body = diaspora2bb($raw_message);
2420 $datarray = array();
2422 // Attach embedded pictures to the body
2424 foreach ($data->photo AS $photo) {
2425 $body = "[img]".unxmlify($photo->remote_photo_path).
2426 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2429 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2431 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2433 // Add OEmbed and other information to the body
2434 if (!self::is_redmatrix($contact["url"])) {
2435 $body = add_page_info_to_body($body, false, true);
2439 $datarray["uid"] = $importer["uid"];
2440 $datarray["contact-id"] = $contact["id"];
2441 $datarray["network"] = NETWORK_DIASPORA;
2443 $datarray["author-name"] = $contact["name"];
2444 $datarray["author-link"] = $contact["url"];
2445 $datarray["author-avatar"] = ((x($contact,"thumb")) ? $contact["thumb"] : $contact["photo"]);
2447 $datarray["owner-name"] = $datarray["author-name"];
2448 $datarray["owner-link"] = $datarray["author-link"];
2449 $datarray["owner-avatar"] = $datarray["author-avatar"];
2451 $datarray["guid"] = $guid;
2452 $datarray["uri"] = $datarray["parent-uri"] = self::get_uri_from_guid($author, $guid);
2454 $datarray["verb"] = ACTIVITY_POST;
2455 $datarray["gravity"] = GRAVITY_PARENT;
2457 $datarray["object"] = $xml;
2459 $datarray["body"] = self::replace_people_guid($body, $contact["url"]);
2461 if ($provider_display_name != "") {
2462 $datarray["app"] = $provider_display_name;
2465 $datarray["plink"] = self::plink($author, $guid);
2466 $datarray["private"] = (($public == "false") ? 1 : 0);
2467 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2469 if (isset($address["address"])) {
2470 $datarray["location"] = $address["address"];
2473 if (isset($address["lat"]) AND isset($address["lng"])) {
2474 $datarray["coord"] = $address["lat"]." ".$address["lng"];
2477 self::fetch_guid($datarray);
2478 $message_id = item_store($datarray);
2481 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2487 /* ************************************************************************************** *
2488 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
2489 * ************************************************************************************** */
2492 * @brief returnes the handle of a contact
2494 * @param array $me contact array
2496 * @return string the handle in the format user@domain.tld
2498 private static function my_handle($contact) {
2499 if ($contact["addr"] != "") {
2500 return $contact["addr"];
2503 // Normally we should have a filled "addr" field - but in the past this wasn't the case
2504 // So - just in case - we build the the address here.
2505 if ($contact["nickname"] != "") {
2506 $nick = $contact["nickname"];
2508 $nick = $contact["nick"];
2511 return $nick."@".substr(App::get_baseurl(), strpos(App::get_baseurl(),"://") + 3);
2515 * @brief Creates the envelope for the "fetch" endpoint
2517 * @param string $msg The message that is to be transmitted
2518 * @param array $user The record of the sender
2520 * @return string The envelope
2523 public static function build_magic_envelope($msg, $user) {
2525 $b64url_data = base64url_encode($msg);
2526 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2528 $key_id = base64url_encode(self::my_handle($user));
2529 $type = "application/xml";
2530 $encoding = "base64url";
2531 $alg = "RSA-SHA256";
2532 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2533 $signature = rsa_sign($signable_data, $user["prvkey"]);
2534 $sig = base64url_encode($signature);
2536 $xmldata = array("me:env" => array("me:data" => $data,
2537 "@attributes" => array("type" => $type),
2538 "me:encoding" => $encoding,
2541 "@attributes2" => array("key_id" => $key_id)));
2543 $namespaces = array("me" => "http://salmon-protocol.org/ns/magic-env");
2545 return xml::from_array($xmldata, $xml, false, $namespaces);
2549 * @brief Creates the envelope for a public message
2551 * @param string $msg The message that is to be transmitted
2552 * @param array $user The record of the sender
2553 * @param array $contact Target of the communication
2554 * @param string $prvkey The private key of the sender
2555 * @param string $pubkey The public key of the receiver
2557 * @return string The envelope
2559 private static function build_public_message($msg, $user, $contact, $prvkey, $pubkey) {
2561 logger("Message: ".$msg, LOGGER_DATA);
2563 $handle = self::my_handle($user);
2565 $b64url_data = base64url_encode($msg);
2567 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2569 $type = "application/xml";
2570 $encoding = "base64url";
2571 $alg = "RSA-SHA256";
2573 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2575 $signature = rsa_sign($signable_data,$prvkey);
2576 $sig = base64url_encode($signature);
2578 $xmldata = array("diaspora" => array("header" => array("author_id" => $handle),
2579 "me:env" => array("me:encoding" => $encoding,
2582 "@attributes" => array("type" => $type),
2583 "me:sig" => $sig)));
2585 $namespaces = array("" => "https://joindiaspora.com/protocol",
2586 "me" => "http://salmon-protocol.org/ns/magic-env");
2588 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2590 logger("magic_env: ".$magic_env, LOGGER_DATA);
2595 * @brief Creates the envelope for a private message
2597 * @param string $msg The message that is to be transmitted
2598 * @param array $user The record of the sender
2599 * @param array $contact Target of the communication
2600 * @param string $prvkey The private key of the sender
2601 * @param string $pubkey The public key of the receiver
2603 * @return string The envelope
2605 private static function build_private_message($msg, $user, $contact, $prvkey, $pubkey) {
2607 logger("Message: ".$msg, LOGGER_DATA);
2609 // without a public key nothing will work
2612 logger("pubkey missing: contact id: ".$contact["id"]);
2616 $inner_aes_key = random_string(32);
2617 $b_inner_aes_key = base64_encode($inner_aes_key);
2618 $inner_iv = random_string(16);
2619 $b_inner_iv = base64_encode($inner_iv);
2621 $outer_aes_key = random_string(32);
2622 $b_outer_aes_key = base64_encode($outer_aes_key);
2623 $outer_iv = random_string(16);
2624 $b_outer_iv = base64_encode($outer_iv);
2626 $handle = self::my_handle($user);
2628 $padded_data = pkcs5_pad($msg,16);
2629 $inner_encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $inner_aes_key, $padded_data, MCRYPT_MODE_CBC, $inner_iv);
2631 $b64_data = base64_encode($inner_encrypted);
2634 $b64url_data = base64url_encode($b64_data);
2635 $data = str_replace(array("\n", "\r", " ", "\t"), array("", "", "", ""), $b64url_data);
2637 $type = "application/xml";
2638 $encoding = "base64url";
2639 $alg = "RSA-SHA256";
2641 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
2643 $signature = rsa_sign($signable_data,$prvkey);
2644 $sig = base64url_encode($signature);
2646 $xmldata = array("decrypted_header" => array("iv" => $b_inner_iv,
2647 "aes_key" => $b_inner_aes_key,
2648 "author_id" => $handle));
2650 $decrypted_header = xml::from_array($xmldata, $xml, true);
2651 $decrypted_header = pkcs5_pad($decrypted_header,16);
2653 $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $outer_aes_key, $decrypted_header, MCRYPT_MODE_CBC, $outer_iv);
2655 $outer_json = json_encode(array("iv" => $b_outer_iv, "key" => $b_outer_aes_key));
2657 $encrypted_outer_key_bundle = "";
2658 openssl_public_encrypt($outer_json, $encrypted_outer_key_bundle, $pubkey);
2660 $b64_encrypted_outer_key_bundle = base64_encode($encrypted_outer_key_bundle);
2662 logger("outer_bundle: ".$b64_encrypted_outer_key_bundle." key: ".$pubkey, LOGGER_DATA);
2664 $encrypted_header_json_object = json_encode(array("aes_key" => base64_encode($encrypted_outer_key_bundle),
2665 "ciphertext" => base64_encode($ciphertext)));
2666 $cipher_json = base64_encode($encrypted_header_json_object);
2668 $xmldata = array("diaspora" => array("encrypted_header" => $cipher_json,
2669 "me:env" => array("me:encoding" => $encoding,
2672 "@attributes" => array("type" => $type),
2673 "me:sig" => $sig)));
2675 $namespaces = array("" => "https://joindiaspora.com/protocol",
2676 "me" => "http://salmon-protocol.org/ns/magic-env");
2678 $magic_env = xml::from_array($xmldata, $xml, false, $namespaces);
2680 logger("magic_env: ".$magic_env, LOGGER_DATA);
2685 * @brief Create the envelope for a message
2687 * @param string $msg The message that is to be transmitted
2688 * @param array $user The record of the sender
2689 * @param array $contact Target of the communication
2690 * @param string $prvkey The private key of the sender
2691 * @param string $pubkey The public key of the receiver
2692 * @param bool $public Is the message public?
2694 * @return string The message that will be transmitted to other servers
2696 private static function build_message($msg, $user, $contact, $prvkey, $pubkey, $public = false) {
2699 $magic_env = self::build_public_message($msg,$user,$contact,$prvkey,$pubkey);
2701 $magic_env = self::build_private_message($msg,$user,$contact,$prvkey,$pubkey);
2703 // The data that will be transmitted is double encoded via "urlencode", strange ...
2704 $slap = "xml=".urlencode(urlencode($magic_env));
2709 * @brief Creates a signature for a message
2711 * @param array $owner the array of the owner of the message
2712 * @param array $message The message that is to be signed
2714 * @return string The signature
2716 private static function signature($owner, $message) {
2718 unset($sigmsg["author_signature"]);
2719 unset($sigmsg["parent_author_signature"]);
2721 $signed_text = implode(";", $sigmsg);
2723 return base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
2727 * @brief Transmit a message to a target server
2729 * @param array $owner the array of the item owner
2730 * @param array $contact Target of the communication
2731 * @param string $slap The message that is to be transmitted
2732 * @param bool $public_batch Is it a public post?
2733 * @param bool $queue_run Is the transmission called from the queue?
2734 * @param string $guid message guid
2736 * @return int Result of the transmission
2738 public static function transmit($owner, $contact, $slap, $public_batch, $queue_run=false, $guid = "") {
2742 $enabled = intval(get_config("system", "diaspora_enabled"));
2746 $logid = random_string(4);
2747 $dest_url = (($public_batch) ? $contact["batch"] : $contact["notify"]);
2749 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
2753 logger("transmit: ".$logid."-".$guid." ".$dest_url);
2755 if (!$queue_run && was_recently_delayed($contact["id"])) {
2758 if (!intval(get_config("system", "diaspora_test"))) {
2759 post_url($dest_url."/", $slap);
2760 $return_code = $a->get_curl_code();
2762 logger("test_mode");
2767 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
2769 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
2770 logger("queue message");
2772 $r = q("SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
2773 intval($contact["id"]),
2774 dbesc(NETWORK_DIASPORA),
2776 intval($public_batch)
2779 logger("add_to_queue ignored - identical item already in queue");
2781 // queue message for redelivery
2782 add_to_queue($contact["id"], NETWORK_DIASPORA, $slap, $public_batch);
2784 // The message could not be delivered. We mark the contact as "dead"
2785 mark_for_death($contact);
2787 } elseif (($return_code >= 200) AND ($return_code <= 299)) {
2788 // We successfully delivered a message, the contact is alive
2789 unmark_for_death($contact);
2792 return(($return_code) ? $return_code : (-1));
2797 * @brief Build the post xml
2799 * @param string $type The message type
2800 * @param array $message The message data
2802 * @return string The post XML
2804 public static function build_post_xml($type, $message) {
2806 $data = array("XML" => array("post" => array($type => $message)));
2807 return xml::from_array($data, $xml);
2811 * @brief Builds and transmit messages
2813 * @param array $owner the array of the item owner
2814 * @param array $contact Target of the communication
2815 * @param string $type The message type
2816 * @param array $message The message data
2817 * @param bool $public_batch Is it a public post?
2818 * @param string $guid message guid
2819 * @param bool $spool Should the transmission be spooled or transmitted?
2821 * @return int Result of the transmission
2823 private static function build_and_transmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false) {
2825 $msg = self::build_post_xml($type, $message);
2827 logger('message: '.$msg, LOGGER_DATA);
2828 logger('send guid '.$guid, LOGGER_DEBUG);
2830 // Fallback if the private key wasn't transmitted in the expected field
2831 if ($owner['uprvkey'] == "")
2832 $owner['uprvkey'] = $owner['prvkey'];
2834 $slap = self::build_message($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
2837 add_to_queue($contact['id'], NETWORK_DIASPORA, $slap, $public_batch);
2840 $return_code = self::transmit($owner, $contact, $slap, $public_batch, false, $guid);
2842 logger("guid: ".$item["guid"]." result ".$return_code, LOGGER_DEBUG);
2844 return $return_code;
2848 * @brief Sends a "share" message
2850 * @param array $owner the array of the item owner
2851 * @param array $contact Target of the communication
2853 * @return int The result of the transmission
2855 public static function send_share($owner,$contact) {
2857 $message = array("sender_handle" => self::my_handle($owner),
2858 "recipient_handle" => $contact["addr"]);
2860 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
2862 return self::build_and_transmit($owner, $contact, "request", $message);
2866 * @brief sends an "unshare"
2868 * @param array $owner the array of the item owner
2869 * @param array $contact Target of the communication
2871 * @return int The result of the transmission
2873 public static function send_unshare($owner,$contact) {
2875 $message = array("post_guid" => $owner["guid"],
2876 "diaspora_handle" => self::my_handle($owner),
2877 "type" => "Person");
2879 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
2881 return self::build_and_transmit($owner, $contact, "retraction", $message);
2885 * @brief Checks a message body if it is a reshare
2887 * @param string $body The message body that is to be check
2888 * @param bool $complete Should it be a complete check or a simple check?
2890 * @return array|bool Reshare details or "false" if no reshare
2892 public static function is_reshare($body, $complete = true) {
2893 $body = trim($body);
2895 // Skip if it isn't a pure repeated messages
2896 // Does it start with a share?
2897 if ((strpos($body, "[share") > 0) AND $complete)
2900 // Does it end with a share?
2901 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2904 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2905 // Skip if there is no shared message in there
2906 if ($body == $attributes)
2909 // If we don't do the complete check we quit here
2914 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
2915 if ($matches[1] != "")
2916 $guid = $matches[1];
2918 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
2919 if ($matches[1] != "")
2920 $guid = $matches[1];
2923 $r = q("SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
2924 dbesc($guid), NETWORK_DFRN, NETWORK_DIASPORA);
2927 $ret["root_handle"] = self::handle_from_contact($r[0]["contact-id"]);
2928 $ret["root_guid"] = $guid;
2934 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2935 if ($matches[1] != "")
2936 $profile = $matches[1];
2938 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2939 if ($matches[1] != "")
2940 $profile = $matches[1];
2944 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
2945 if (($ret["root_handle"] == $profile) OR ($ret["root_handle"] == ""))
2949 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2950 if ($matches[1] != "")
2951 $link = $matches[1];
2953 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2954 if ($matches[1] != "")
2955 $link = $matches[1];
2957 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
2958 if (($ret["root_guid"] == $link) OR (trim($ret["root_guid"]) == ""))
2965 * @brief Create an event array
2967 * @param integer $event_id The id of the event
2969 * @return array with event data
2971 private static function build_event($event_id) {
2973 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
2974 if (!dbm::is_result($r)) {
2980 $eventdata = array();
2982 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
2983 if (!dbm::is_result($r)) {
2989 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
2990 if (!dbm::is_result($r)) {
2996 $eventdata['author'] = self::my_handle($owner);
2998 if ($event['guid']) {
2999 $eventdata['guid'] = $event['guid'];
3002 $mask = 'Y-m-d\TH:i:s\Z';
3004 /// @todo - establish "all day" events in Friendica
3005 $eventdata["all_day"] = "false";
3007 if (!$event['adjust']) {
3008 $eventdata['timezone'] = $user['timezone'];
3010 if ($eventdata['timezone'] == "") {
3011 $eventdata['timezone'] = 'UTC';
3015 if ($event['start']) {
3016 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3018 if ($event['finish'] AND !$event['nofinish']) {
3019 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3021 if ($event['summary']) {
3022 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3024 if ($event['desc']) {
3025 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3027 if ($event['location']) {
3028 $location = array();
3029 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3030 $location["lat"] = 0;
3031 $location["lng"] = 0;
3032 $eventdata['location'] = $location;
3039 * @brief Create a post (status message or reshare)
3041 * @param array $item The item that will be exported
3042 * @param array $owner the array of the item owner
3045 * 'type' -> Message type ("status_message" or "reshare")
3046 * 'message' -> Array of XML elements of the status
3048 public static function build_status($item, $owner) {
3050 $cachekey = "diaspora:build_status:".$item['guid'];
3052 $result = Cache::get($cachekey);
3053 if (!is_null($result)) {
3057 $myaddr = self::my_handle($owner);
3059 $public = (($item["private"]) ? "false" : "true");
3061 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3063 // Detect a share element and do a reshare
3064 if (!$item['private'] AND ($ret = self::is_reshare($item["body"]))) {
3065 $message = array("root_diaspora_id" => $ret["root_handle"],
3066 "root_guid" => $ret["root_guid"],
3067 "guid" => $item["guid"],
3068 "diaspora_handle" => $myaddr,
3069 "public" => $public,
3070 "created_at" => $created,
3071 "provider_display_name" => $item["app"]);
3075 $title = $item["title"];
3076 $body = $item["body"];
3078 // convert to markdown
3079 $body = html_entity_decode(bb2diaspora($body));
3083 $body = "## ".html_entity_decode($title)."\n\n".$body;
3085 if ($item["attach"]) {
3086 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3088 $body .= "\n".t("Attachments:")."\n";
3089 foreach($matches as $mtch)
3090 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3094 $location = array();
3096 if ($item["location"] != "")
3097 $location["address"] = $item["location"];
3099 if ($item["coord"] != "") {
3100 $coord = explode(" ", $item["coord"]);
3101 $location["lat"] = $coord[0];
3102 $location["lng"] = $coord[1];
3105 $message = array("raw_message" => $body,
3106 "location" => $location,
3107 "guid" => $item["guid"],
3108 "diaspora_handle" => $myaddr,
3109 "public" => $public,
3110 "created_at" => $created,
3111 "provider_display_name" => $item["app"]);
3113 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3114 if (!isset($location["lat"]) OR !isset($location["lng"])) {
3115 unset($message["location"]);
3118 if ($item['event-id'] > 0) {
3119 $event = self::build_event($item['event-id']);
3120 if (count($event)) {
3121 $message['event'] = $event;
3123 /// @todo Once Diaspora supports it, we will remove the body
3124 // $message['raw_message'] = '';
3128 $type = "status_message";
3131 $msg = array("type" => $type, "message" => $message);
3133 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3139 * @brief Sends a post
3141 * @param array $item The item that will be exported
3142 * @param array $owner the array of the item owner
3143 * @param array $contact Target of the communication
3144 * @param bool $public_batch Is it a public post?
3146 * @return int The result of the transmission
3148 public static function send_status($item, $owner, $contact, $public_batch = false) {
3150 $status = self::build_status($item, $owner);
3152 return self::build_and_transmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3156 * @brief Creates a "like" object
3158 * @param array $item The item that will be exported
3159 * @param array $owner the array of the item owner
3161 * @return array The data for a "like"
3163 private static function construct_like($item, $owner) {
3165 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3166 dbesc($item["thr-parent"]));
3167 if (!dbm::is_result($p))
3172 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3173 if ($item['verb'] === ACTIVITY_LIKE) {
3175 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3176 $positive = "false";
3179 return(array("positive" => $positive,
3180 "guid" => $item["guid"],
3181 "target_type" => $target_type,
3182 "parent_guid" => $parent["guid"],
3183 "author_signature" => "",
3184 "diaspora_handle" => self::my_handle($owner)));
3188 * @brief Creates an "EventParticipation" object
3190 * @param array $item The item that will be exported
3191 * @param array $owner the array of the item owner
3193 * @return array The data for an "EventParticipation"
3195 private static function construct_attend($item, $owner) {
3197 $p = q("SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3198 dbesc($item["thr-parent"]));
3199 if (!dbm::is_result($p))
3204 switch ($item['verb']) {
3205 case ACTIVITY_ATTEND:
3206 $attend_answer = 'accepted';
3208 case ACTIVITY_ATTENDNO:
3209 $attend_answer = 'declined';
3211 case ACTIVITY_ATTENDMAYBE:
3212 $attend_answer = 'tentative';
3215 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3219 return(array("author" => self::my_handle($owner),
3220 "guid" => $item["guid"],
3221 "parent_guid" => $parent["guid"],
3222 "status" => $attend_answer,
3223 "author_signature" => ""));
3227 * @brief Creates the object for a comment
3229 * @param array $item The item that will be exported
3230 * @param array $owner the array of the item owner
3232 * @return array The data for a comment
3234 private static function construct_comment($item, $owner) {
3236 $cachekey = "diaspora:construct_comment:".$item['guid'];
3238 $result = Cache::get($cachekey);
3239 if (!is_null($result)) {
3243 $p = q("SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3244 intval($item["parent"]),
3245 intval($item["parent"])
3248 if (!dbm::is_result($p))
3253 $text = html_entity_decode(bb2diaspora($item["body"]));
3254 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3256 $comment = array("guid" => $item["guid"],
3257 "parent_guid" => $parent["guid"],
3258 "author_signature" => "",
3260 /// @todo Currently disabled until Diaspora supports it: "created_at" => $created,
3261 "diaspora_handle" => self::my_handle($owner));
3263 // Send the thread parent guid only if it is a threaded comment
3264 if ($item['thr-parent'] != $item['parent-uri']) {
3265 $comment['thread_parent_guid'] = self::get_guid_from_uri($item['thr-parent'], $item['uid']);
3268 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3274 * @brief Send a like or a comment
3276 * @param array $item The item that will be exported
3277 * @param array $owner the array of the item owner
3278 * @param array $contact Target of the communication
3279 * @param bool $public_batch Is it a public post?
3281 * @return int The result of the transmission
3283 public static function send_followup($item,$owner,$contact,$public_batch = false) {
3285 if (in_array($item['verb'], array(ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE))) {
3286 $message = self::construct_attend($item, $owner);
3287 $type = "event_participation";
3288 } elseif (in_array($item["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE))) {
3289 $message = self::construct_like($item, $owner);
3292 $message = self::construct_comment($item, $owner);
3299 $message["author_signature"] = self::signature($owner, $message);
3301 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3305 * @brief Creates a message from a signature record entry
3307 * @param array $item The item that will be exported
3308 * @param array $signature The entry of the "sign" record
3310 * @return string The message
3312 private static function message_from_signature($item, $signature) {
3314 // Split the signed text
3315 $signed_parts = explode(";", $signature['signed_text']);
3317 if ($item["deleted"])
3318 $message = array("parent_author_signature" => "",
3319 "target_guid" => $signed_parts[0],
3320 "target_type" => $signed_parts[1],
3321 "sender_handle" => $signature['signer'],
3322 "target_author_signature" => $signature['signature']);
3323 elseif ($item['verb'] === ACTIVITY_LIKE)
3324 $message = array("positive" => $signed_parts[0],
3325 "guid" => $signed_parts[1],
3326 "target_type" => $signed_parts[2],
3327 "parent_guid" => $signed_parts[3],
3328 "parent_author_signature" => "",
3329 "author_signature" => $signature['signature'],
3330 "diaspora_handle" => $signed_parts[4]);
3332 // Remove the comment guid
3333 $guid = array_shift($signed_parts);
3335 // Remove the parent guid
3336 $parent_guid = array_shift($signed_parts);
3338 // Remove the handle
3339 $handle = array_pop($signed_parts);
3341 // Glue the parts together
3342 $text = implode(";", $signed_parts);
3344 $message = array("guid" => $guid,
3345 "parent_guid" => $parent_guid,
3346 "parent_author_signature" => "",
3347 "author_signature" => $signature['signature'],
3348 "text" => implode(";", $signed_parts),
3349 "diaspora_handle" => $handle);
3355 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3357 * @param array $item The item that will be exported
3358 * @param array $owner the array of the item owner
3359 * @param array $contact Target of the communication
3360 * @param bool $public_batch Is it a public post?
3362 * @return int The result of the transmission
3364 public static function send_relay($item, $owner, $contact, $public_batch = false) {
3366 if ($item["deleted"])
3367 return self::send_retraction($item, $owner, $contact, $public_batch, true);
3368 elseif ($item['verb'] === ACTIVITY_LIKE)
3373 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3375 // fetch the original signature
3377 $r = q("SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3378 intval($item["id"]));
3381 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3387 // Old way - is used by the internal Friendica functions
3388 /// @todo Change all signatur storing functions to the new format
3389 if ($signature['signed_text'] AND $signature['signature'] AND $signature['signer'])
3390 $message = self::message_from_signature($item, $signature);
3392 $msg = json_decode($signature['signed_text'], true);
3395 if (is_array($msg)) {
3396 foreach ($msg AS $field => $data) {
3397 if (!$item["deleted"]) {
3398 if ($field == "author")
3399 $field = "diaspora_handle";
3400 if ($field == "parent_type")
3401 $field = "target_type";
3404 $message[$field] = $data;
3407 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3410 $message["parent_author_signature"] = self::signature($owner, $message);
3412 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
3414 return self::build_and_transmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3418 * @brief Sends a retraction (deletion) of a message, like or comment
3420 * @param array $item The item that will be exported
3421 * @param array $owner the array of the item owner
3422 * @param array $contact Target of the communication
3423 * @param bool $public_batch Is it a public post?
3424 * @param bool $relay Is the retraction transmitted from a relay?
3426 * @return int The result of the transmission
3428 public static function send_retraction($item, $owner, $contact, $public_batch = false, $relay = false) {
3430 $itemaddr = self::handle_from_contact($item["contact-id"], $item["gcontact-id"]);
3432 // Check whether the retraction is for a top-level post or whether it's a relayable
3433 if ($item["uri"] !== $item["parent-uri"]) {
3434 $msg_type = "relayable_retraction";
3435 $target_type = (($item["verb"] === ACTIVITY_LIKE) ? "Like" : "Comment");
3437 $msg_type = "signed_retraction";
3438 $target_type = "StatusMessage";
3441 if ($relay AND ($item["uri"] !== $item["parent-uri"]))
3442 $signature = "parent_author_signature";
3444 $signature = "target_author_signature";
3446 $signed_text = $item["guid"].";".$target_type;
3448 $message = array("target_guid" => $item['guid'],
3449 "target_type" => $target_type,
3450 "sender_handle" => $itemaddr,
3451 $signature => base64_encode(rsa_sign($signed_text,$owner['uprvkey'],'sha256')));
3453 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
3455 return self::build_and_transmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
3459 * @brief Sends a mail
3461 * @param array $item The item that will be exported
3462 * @param array $owner The owner
3463 * @param array $contact Target of the communication
3465 * @return int The result of the transmission
3467 public static function send_mail($item, $owner, $contact) {
3469 $myaddr = self::my_handle($owner);
3471 $r = q("SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
3472 intval($item["convid"]),
3473 intval($item["uid"])
3476 if (!dbm::is_result($r)) {
3477 logger("conversation not found.");
3483 "guid" => $cnv["guid"],
3484 "subject" => $cnv["subject"],
3485 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3486 "diaspora_handle" => $cnv["creator"],
3487 "participant_handles" => $cnv["recips"]
3490 $body = bb2diaspora($item["body"]);
3491 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3493 $signed_text = $item["guid"].";".$cnv["guid"].";".$body.";".$created.";".$myaddr.";".$cnv['guid'];
3494 $sig = base64_encode(rsa_sign($signed_text, $owner["uprvkey"], "sha256"));
3497 "guid" => $item["guid"],
3498 "parent_guid" => $cnv["guid"],
3499 "parent_author_signature" => $sig,
3500 "author_signature" => $sig,
3502 "created_at" => $created,
3503 "diaspora_handle" => $myaddr,
3504 "conversation_guid" => $cnv["guid"]
3507 if ($item["reply"]) {
3511 $message = array("guid" => $cnv["guid"],
3512 "subject" => $cnv["subject"],
3513 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
3515 "diaspora_handle" => $cnv["creator"],
3516 "participant_handles" => $cnv["recips"]);
3518 $type = "conversation";
3521 return self::build_and_transmit($owner, $contact, $type, $message, false, $item["guid"]);
3525 * @brief Sends profile data
3527 * @param int $uid The user id
3529 public static function send_profile($uid, $recips = false) {
3535 $recips = q("SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
3536 AND `uid` = %d AND `rel` != %d",
3537 dbesc(NETWORK_DIASPORA),
3539 intval(CONTACT_IS_SHARING)
3544 $r = q("SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
3546 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
3547 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
3548 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
3557 $handle = $profile["addr"];
3558 $first = ((strpos($profile['name'],' ')
3559 ? trim(substr($profile['name'],0,strpos($profile['name'],' '))) : $profile['name']));
3560 $last = (($first === $profile['name']) ? '' : trim(substr($profile['name'], strlen($first))));
3561 $large = App::get_baseurl().'/photo/custom/300/'.$profile['uid'].'.jpg';
3562 $medium = App::get_baseurl().'/photo/custom/100/'.$profile['uid'].'.jpg';
3563 $small = App::get_baseurl().'/photo/custom/50/' .$profile['uid'].'.jpg';
3564 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
3566 if ($searchable === 'true') {
3567 $dob = '1000-00-00';
3569 if (($profile['dob']) && ($profile['dob'] != '0000-00-00'))
3570 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC','UTC',$profile['dob'],'m-d');
3572 $about = $profile['about'];
3573 $about = strip_tags(bbcode($about));
3575 $location = formatted_location($profile);
3577 if ($profile['pub_keywords']) {
3578 $kw = str_replace(',',' ',$profile['pub_keywords']);
3579 $kw = str_replace(' ',' ',$kw);
3580 $arr = explode(' ',$profile['pub_keywords']);
3582 for($x = 0; $x < 5; $x ++) {
3584 $tags .= '#'. trim($arr[$x]) .' ';
3588 $tags = trim($tags);
3591 $message = array("diaspora_handle" => $handle,
3592 "first_name" => $first,
3593 "last_name" => $last,
3594 "image_url" => $large,
3595 "image_url_medium" => $medium,
3596 "image_url_small" => $small,
3598 "gender" => $profile['gender'],
3600 "location" => $location,
3601 "searchable" => $searchable,
3602 "tag_string" => $tags);
3604 foreach($recips as $recip) {
3605 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
3606 self::build_and_transmit($profile, $recip, "profile", $message, false, "", true);
3611 * @brief Stores the signature for likes that are created on our system
3613 * @param array $contact The contact array of the "like"
3614 * @param int $post_id The post id of the "like"
3616 * @return bool Success
3618 public static function store_like_signature($contact, $post_id) {
3620 // Is the contact the owner? Then fetch the private key
3621 if (!$contact['self'] OR ($contact['uid'] == 0)) {
3622 logger("No owner post, so not storing signature", LOGGER_DEBUG);
3626 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
3630 $contact["uprvkey"] = $r[0]['prvkey'];
3632 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
3636 if (!in_array($r[0]["verb"], array(ACTIVITY_LIKE, ACTIVITY_DISLIKE)))
3639 $message = self::construct_like($r[0], $contact);
3640 $message["author_signature"] = self::signature($contact, $message);
3642 // We now store the signature more flexible to dynamically support new fields.
3643 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3644 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3645 intval($message_id),
3646 dbesc(json_encode($message))
3649 logger('Stored diaspora like signature');
3654 * @brief Stores the signature for comments that are created on our system
3656 * @param array $item The item array of the comment
3657 * @param array $contact The contact array of the item owner
3658 * @param string $uprvkey The private key of the sender
3659 * @param int $message_id The message id of the comment
3661 * @return bool Success
3663 public static function store_comment_signature($item, $contact, $uprvkey, $message_id) {
3665 if ($uprvkey == "") {
3666 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
3670 $contact["uprvkey"] = $uprvkey;
3672 $message = self::construct_comment($item, $contact);
3673 $message["author_signature"] = self::signature($contact, $message);
3675 // We now store the signature more flexible to dynamically support new fields.
3676 // This will break Diaspora compatibility with Friendica versions prior to 3.5.
3677 q("INSERT INTO `sign` (`iid`,`signed_text`) VALUES (%d,'%s')",
3678 intval($message_id),
3679 dbesc(json_encode($message))
3682 logger('Stored diaspora comment signature');