3 * @file src/Protocol/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 * This implementation here interprets the old and the new protocol and sends the new one.
8 * In the future we will remove most stuff from "validPosting" and interpret only the new protocol.
10 namespace Friendica\Protocol;
13 use Friendica\Core\System;
14 use Friendica\Core\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Core\PConfig;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBM;
19 use Friendica\Model\Contact;
20 use Friendica\Model\GContact;
21 use Friendica\Model\Group;
22 use Friendica\Model\Profile;
23 use Friendica\Model\Queue;
24 use Friendica\Model\User;
25 use Friendica\Network\Probe;
26 use Friendica\Util\Crypto;
27 use Friendica\Util\XML;
32 require_once 'include/dba.php';
33 require_once 'include/items.php';
34 require_once 'include/bb2diaspora.php';
35 require_once 'include/datetime.php';
38 * @brief This class contain functions to create and send Diaspora XML files
44 * @brief Return a list of relay servers
46 * This is an experimental Diaspora feature.
48 * @return array of relay servers
50 public static function relayList()
52 $serverdata = Config::get("system", "relay_server");
53 if ($serverdata == "") {
59 $servers = explode(",", $serverdata);
61 foreach ($servers as $server) {
62 $server = trim($server);
63 $addr = "relay@".str_replace("http://", "", normalise_link($server));
64 $batch = $server."/receive/public";
67 "SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
70 dbesc(normalise_link($server))
75 "INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
76 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
81 dbesc(normalise_link($server)),
83 dbesc(NETWORK_DIASPORA),
84 intval(CONTACT_IS_FOLLOWER),
85 dbesc(datetime_convert()),
86 dbesc(datetime_convert()),
87 dbesc(datetime_convert())
90 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
92 $relay[] = $relais[0];
95 $relay[] = $relais[0];
103 * @brief Return a list of participating contacts for a thread
105 * This is used for the participation feature.
106 * One of the parameters is a contact array.
107 * This is done to avoid duplicates.
109 * @param integer $thread The id of the thread
110 * @param array $contacts The previously fetched contacts
112 * @return array of relay servers
114 public static function participantsForThread($thread, $contacts)
116 $r = dba::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
117 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
118 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
119 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
120 WHERE `participation`.`iid` = ?", $thread);
122 while ($contact = dba::fetch($r)) {
123 if (!empty($contact['fnetwork'])) {
124 $contact['network'] = $contact['fnetwork'];
126 unset($contact['fnetwork']);
128 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
129 $contact['batch'] = $contact['fbatch'];
131 unset($contact['fbatch']);
134 foreach ($contacts as $entry) {
135 if ($entry['batch'] == $contact['batch']) {
141 $contacts[] = $contact;
150 * @brief repairs a signature that was double encoded
152 * The function is unused at the moment. It was copied from the old implementation.
154 * @param string $signature The signature
155 * @param string $handle The handle of the signature owner
156 * @param integer $level This value is only set inside this function to avoid endless loops
158 * @return string the repaired signature
160 private static function repairSignature($signature, $handle = "", $level = 1)
162 if ($signature == "") {
166 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
167 $signature = base64_decode($signature);
168 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
170 // Do a recursive call to be able to fix even multiple levels
172 $signature = self::repairSignature($signature, $handle, ++$level);
180 * @brief verify the envelope and return the verified data
182 * @param string $envelope The magic envelope
184 * @return string verified data
186 private static function verifyMagicEnvelope($envelope)
188 $basedom = parse_xml_string($envelope);
190 if (!is_object($basedom)) {
191 logger("Envelope is no XML file");
195 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
197 if (sizeof($children) == 0) {
198 logger("XML has no children");
204 $data = base64url_decode($children->data);
205 $type = $children->data->attributes()->type[0];
207 $encoding = $children->encoding;
209 $alg = $children->alg;
211 $sig = base64url_decode($children->sig);
212 $key_id = $children->sig->attributes()->key_id[0];
214 $handle = base64url_decode($key_id);
217 $b64url_data = base64url_encode($data);
218 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
220 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
222 $key = self::key($handle);
224 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
226 logger('Message did not verify. Discarding.');
234 * @brief encrypts data via AES
236 * @param string $key The AES key
237 * @param string $iv The IV (is used for CBC encoding)
238 * @param string $data The data that is to be encrypted
240 * @return string encrypted data
242 private static function aesEncrypt($key, $iv, $data)
244 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
248 * @brief decrypts data via AES
250 * @param string $key The AES key
251 * @param string $iv The IV (is used for CBC encoding)
252 * @param string $encrypted The encrypted data
254 * @return string decrypted data
256 private static function aesDecrypt($key, $iv, $encrypted)
258 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
262 * @brief: Decodes incoming Diaspora message in the new format
264 * @param array $importer Array of the importer user
265 * @param string $raw raw post message
268 * 'message' -> decoded Diaspora XML message
269 * 'author' -> author diaspora handle
270 * 'key' -> author public key (converted to pkcs#8)
272 public static function decodeRaw($importer, $raw)
274 $data = json_decode($raw);
276 // Is it a private post? Then decrypt the outer Salmon
277 if (is_object($data)) {
278 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
279 $ciphertext = base64_decode($data->encrypted_magic_envelope);
281 $outer_key_bundle = '';
282 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
283 $j_outer_key_bundle = json_decode($outer_key_bundle);
285 if (!is_object($j_outer_key_bundle)) {
286 logger('Outer Salmon did not verify. Discarding.');
287 http_status_exit(400);
290 $outer_iv = base64_decode($j_outer_key_bundle->iv);
291 $outer_key = base64_decode($j_outer_key_bundle->key);
293 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
298 $basedom = parse_xml_string($xml);
300 if (!is_object($basedom)) {
301 logger('Received data does not seem to be an XML. Discarding. '.$xml);
302 http_status_exit(400);
305 $base = $basedom->children(NAMESPACE_SALMON_ME);
307 // Not sure if this cleaning is needed
308 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
310 // Build the signed data
311 $type = $base->data[0]->attributes()->type[0];
312 $encoding = $base->encoding;
314 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
316 // This is the signature
317 $signature = base64url_decode($base->sig);
319 // Get the senders' public key
320 $key_id = $base->sig[0]->attributes()->key_id[0];
321 $author_addr = base64_decode($key_id);
322 $key = self::key($author_addr);
324 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
326 logger('Message did not verify. Discarding.');
327 http_status_exit(400);
330 return ['message' => (string)base64url_decode($base->data),
331 'author' => unxmlify($author_addr),
332 'key' => (string)$key];
336 * @brief: Decodes incoming Diaspora message in the deprecated format
338 * @param array $importer Array of the importer user
339 * @param string $xml urldecoded Diaspora salmon
342 * 'message' -> decoded Diaspora XML message
343 * 'author' -> author diaspora handle
344 * 'key' -> author public key (converted to pkcs#8)
346 public static function decode($importer, $xml)
349 $basedom = parse_xml_string($xml);
351 if (!is_object($basedom)) {
352 logger("XML is not parseable.");
355 $children = $basedom->children('https://joindiaspora.com/protocol');
357 if ($children->header) {
359 $author_link = str_replace('acct:', '', $children->header->author_id);
361 // This happens with posts from a relais
363 logger("This is no private post in the old format", LOGGER_DEBUG);
367 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
369 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
370 $ciphertext = base64_decode($encrypted_header->ciphertext);
372 $outer_key_bundle = '';
373 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
375 $j_outer_key_bundle = json_decode($outer_key_bundle);
377 $outer_iv = base64_decode($j_outer_key_bundle->iv);
378 $outer_key = base64_decode($j_outer_key_bundle->key);
380 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
382 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
383 $idom = parse_xml_string($decrypted);
385 $inner_iv = base64_decode($idom->iv);
386 $inner_aes_key = base64_decode($idom->aes_key);
388 $author_link = str_replace('acct:', '', $idom->author_id);
391 $dom = $basedom->children(NAMESPACE_SALMON_ME);
393 // figure out where in the DOM tree our data is hiding
395 if ($dom->provenance->data) {
396 $base = $dom->provenance;
397 } elseif ($dom->env->data) {
399 } elseif ($dom->data) {
404 logger('unable to locate salmon data in xml');
405 http_status_exit(400);
409 // Stash the signature away for now. We have to find their key or it won't be good for anything.
410 $signature = base64url_decode($base->sig);
414 // strip whitespace so our data element will return to one big base64 blob
415 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
418 // stash away some other stuff for later
420 $type = $base->data[0]->attributes()->type[0];
421 $keyhash = $base->sig[0]->attributes()->keyhash[0];
422 $encoding = $base->encoding;
426 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
430 $data = base64url_decode($data);
434 $inner_decrypted = $data;
436 // Decode the encrypted blob
437 $inner_encrypted = base64_decode($data);
438 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
442 logger('Could not retrieve author URI.');
443 http_status_exit(400);
445 // Once we have the author URI, go to the web and try to find their public key
446 // (first this will look it up locally if it is in the fcontact cache)
447 // This will also convert diaspora public key from pkcs#1 to pkcs#8
449 logger('Fetching key for '.$author_link);
450 $key = self::key($author_link);
453 logger('Could not retrieve author key.');
454 http_status_exit(400);
457 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
460 logger('Message did not verify. Discarding.');
461 http_status_exit(400);
464 logger('Message verified.');
466 return ['message' => (string)$inner_decrypted,
467 'author' => unxmlify($author_link),
468 'key' => (string)$key];
473 * @brief Dispatches public messages and find the fitting receivers
475 * @param array $msg The post that will be dispatched
477 * @return int The message id of the generated message, "true" or "false" if there was an error
479 public static function dispatchPublic($msg)
481 $enabled = intval(Config::get("system", "diaspora_enabled"));
483 logger("diaspora is disabled");
487 if (!($postdata = self::validPosting($msg))) {
488 logger("Invalid posting");
492 $fields = $postdata['fields'];
494 // Is it a an action (comment, like, ...) for our own post?
495 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
496 $guid = notags(unxmlify($fields->parent_guid));
497 $importer = self::importerForGuid($guid);
498 if (is_array($importer)) {
499 logger("delivering to origin: ".$importer["name"]);
500 $message_id = self::dispatch($importer, $msg, $fields);
505 // Process item retractions. This has to be done separated from the other stuff,
506 // since retractions for comments could come even from non followers.
507 if (!empty($fields) && in_array($fields->getName(), ['retraction'])) {
508 $target = notags(unxmlify($fields->target_type));
509 if (in_array($target, ["Comment", "Like", "Post", "Reshare", "StatusMessage"])) {
510 logger('processing retraction for '.$target, LOGGER_DEBUG);
511 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
512 $message_id = self::dispatch($importer, $msg, $fields);
517 // Now distribute it to the followers
519 "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
520 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
521 AND NOT `account_expired` AND NOT `account_removed`",
522 dbesc(NETWORK_DIASPORA),
523 dbesc($msg["author"])
526 if (DBM::is_result($r)) {
527 foreach ($r as $rr) {
528 logger("delivering to: ".$rr["username"]);
529 self::dispatch($rr, $msg, $fields);
531 } elseif (!Config::get('system', 'relay_subscribe', false)) {
532 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
534 // Use a dummy importer to import the data for the public copy
535 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
536 $message_id = self::dispatch($importer, $msg, $fields);
543 * @brief Dispatches the different message types to the different functions
545 * @param array $importer Array of the importer user
546 * @param array $msg The post that will be dispatched
547 * @param object $fields SimpleXML object that contains the message
549 * @return int The message id of the generated message, "true" or "false" if there was an error
551 public static function dispatch($importer, $msg, $fields = null)
553 // The sender is the handle of the contact that sent the message.
554 // This will often be different with relayed messages (for example "like" and "comment")
555 $sender = $msg["author"];
557 // This is only needed for private postings since this is already done for public ones before
558 if (is_null($fields)) {
559 if (!($postdata = self::validPosting($msg))) {
560 logger("Invalid posting");
563 $fields = $postdata['fields'];
566 $type = $fields->getName();
568 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
571 case "account_migration":
572 return self::receiveAccountMigration($importer, $fields);
574 case "account_deletion":
575 return self::receiveAccountDeletion($importer, $fields);
578 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
581 return self::receiveContactRequest($importer, $fields);
584 return self::receiveConversation($importer, $msg, $fields);
587 return self::receiveLike($importer, $sender, $fields);
590 return self::receiveMessage($importer, $fields);
592 case "participation":
593 return self::receiveParticipation($importer, $fields);
595 case "photo": // Not implemented
596 return self::receivePhoto($importer, $fields);
598 case "poll_participation": // Not implemented
599 return self::receivePollParticipation($importer, $fields);
602 return self::receiveProfile($importer, $fields);
605 return self::receiveReshare($importer, $fields, $msg["message"]);
608 return self::receiveRetraction($importer, $sender, $fields);
610 case "status_message":
611 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
614 logger("Unknown message type ".$type);
622 * @brief Checks if a posting is valid and fetches the data fields.
624 * This function does not only check the signature.
625 * It also does the conversion between the old and the new diaspora format.
627 * @param array $msg Array with the XML, the sender handle and the sender signature
629 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
631 private static function validPosting($msg)
633 $data = parse_xml_string($msg["message"]);
635 if (!is_object($data)) {
636 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
640 $first_child = $data->getName();
642 // Is this the new or the old version?
643 if ($data->getName() == "XML") {
645 foreach ($data->post->children() as $child) {
653 $type = $element->getName();
656 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
658 // All retractions are handled identically from now on.
659 // In the new version there will only be "retraction".
660 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
661 $type = "retraction";
663 if ($type == "request") {
667 $fields = new SimpleXMLElement("<".$type."/>");
671 foreach ($element->children() as $fieldname => $entry) {
673 // Translation for the old XML structure
674 if ($fieldname == "diaspora_handle") {
675 $fieldname = "author";
677 if ($fieldname == "participant_handles") {
678 $fieldname = "participants";
680 if (in_array($type, ["like", "participation"])) {
681 if ($fieldname == "target_type") {
682 $fieldname = "parent_type";
685 if ($fieldname == "sender_handle") {
686 $fieldname = "author";
688 if ($fieldname == "recipient_handle") {
689 $fieldname = "recipient";
691 if ($fieldname == "root_diaspora_id") {
692 $fieldname = "root_author";
694 if ($type == "status_message") {
695 if ($fieldname == "raw_message") {
699 if ($type == "retraction") {
700 if ($fieldname == "post_guid") {
701 $fieldname = "target_guid";
703 if ($fieldname == "type") {
704 $fieldname = "target_type";
709 if (($fieldname == "author_signature") && ($entry != "")) {
710 $author_signature = base64_decode($entry);
711 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
712 $parent_author_signature = base64_decode($entry);
713 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
714 if ($signed_data != "") {
718 $signed_data .= $entry;
720 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
721 || ($orig_type == "relayable_retraction")
723 XML::copy($entry, $fields, $fieldname);
727 // This is something that shouldn't happen at all.
728 if (in_array($type, ["status_message", "reshare", "profile"])) {
729 if ($msg["author"] != $fields->author) {
730 logger("Message handle is not the same as envelope sender. Quitting this message.");
735 // Only some message types have signatures. So we quit here for the other types.
736 if (!in_array($type, ["comment", "like"])) {
737 return ["fields" => $fields, "relayed" => false];
739 // No author_signature? This is a must, so we quit.
740 if (!isset($author_signature)) {
741 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
745 if (isset($parent_author_signature)) {
748 $key = self::key($msg["author"]);
750 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
751 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);
758 $key = self::key($fields->author);
760 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
761 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
764 return ["fields" => $fields, "relayed" => $relayed];
769 * @brief Fetches the public key for a given handle
771 * @param string $handle The handle
773 * @return string The public key
775 private static function key($handle)
777 $handle = strval($handle);
779 logger("Fetching diaspora key for: ".$handle);
781 $r = self::personByHandle($handle);
790 * @brief Fetches data for a given handle
792 * @param string $handle The handle
794 * @return array the queried data
796 public static function personByHandle($handle)
799 "SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
800 dbesc(NETWORK_DIASPORA),
805 logger("In cache " . print_r($r, true), LOGGER_DEBUG);
807 // update record occasionally so it doesn't get stale
808 $d = strtotime($person["updated"]." +00:00");
809 if ($d < strtotime("now - 14 days")) {
813 if ($person["guid"] == "") {
818 if (!$person || $update) {
819 logger("create or refresh", LOGGER_DEBUG);
820 $r = Probe::uri($handle, NETWORK_DIASPORA);
822 // Note that Friendica contacts will return a "Diaspora person"
823 // if Diaspora connectivity is enabled on their server
824 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
825 self::addFContact($r, $update);
833 * @brief Updates the fcontact table
835 * @param array $arr The fcontact data
836 * @param bool $update Update or insert?
838 * @return string The id of the fcontact entry
840 private static function addFContact($arr, $update = false)
844 "UPDATE `fcontact` SET
858 WHERE `url` = '%s' AND `network` = '%s'",
860 dbesc($arr["photo"]),
861 dbesc($arr["request"]),
863 dbesc(strtolower($arr["addr"])),
865 dbesc($arr["batch"]),
866 dbesc($arr["notify"]),
868 dbesc($arr["confirm"]),
869 dbesc($arr["alias"]),
870 dbesc($arr["pubkey"]),
871 dbesc(datetime_convert()),
873 dbesc($arr["network"])
877 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
878 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
879 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
882 dbesc($arr["photo"]),
883 dbesc($arr["request"]),
887 dbesc($arr["batch"]),
888 dbesc($arr["notify"]),
890 dbesc($arr["confirm"]),
891 dbesc($arr["network"]),
892 dbesc($arr["alias"]),
893 dbesc($arr["pubkey"]),
894 dbesc(datetime_convert())
902 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
904 * @param int $contact_id The id in the contact table
905 * @param int $gcontact_id The id in the gcontact table
907 * @return string the handle
909 public static function handleFromContact($contact_id, $gcontact_id = 0)
913 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
915 if ($gcontact_id != 0) {
917 "SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
921 if (DBM::is_result($r)) {
922 return strtolower($r[0]["addr"]);
927 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
931 if (DBM::is_result($r)) {
934 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
936 if ($contact['addr'] != "") {
937 $handle = $contact['addr'];
939 $baseurl_start = strpos($contact['url'], '://') + 3;
940 // allows installations in a subdirectory--not sure how Diaspora will handle
941 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
942 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
943 $handle = $contact['nick'].'@'.$baseurl;
947 return strtolower($handle);
951 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
954 * @param mixed $fcontact_guid Hexadecimal string guid
956 * @return string the contact url or null
958 public static function urlFromContactGuid($fcontact_guid)
960 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
963 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
964 dbesc(NETWORK_DIASPORA),
965 dbesc($fcontact_guid)
968 if (DBM::is_result($r)) {
976 * @brief Get a contact id for a given handle
978 * @todo Move to Friendica\Model\Contact
980 * @param int $uid The user id
981 * @param string $handle The handle in the format user@domain.tld
983 * @return int Contact id
985 private static function contactByHandle($uid, $handle)
987 // First do a direct search on the contact table
989 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
994 if (DBM::is_result($r)) {
998 * We haven't found it?
999 * We use another function for it that will possibly create a contact entry.
1001 $cid = Contact::getIdForURL($handle, $uid);
1004 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1005 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1007 if (DBM::is_result($r)) {
1013 $handle_parts = explode("@", $handle);
1014 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1016 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1017 dbesc(NETWORK_DFRN),
1021 if (DBM::is_result($r)) {
1025 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1030 * @brief Check if posting is allowed for this contact
1032 * @param array $importer Array of the importer user
1033 * @param array $contact The contact that is checked
1034 * @param bool $is_comment Is the check for a comment?
1036 * @return bool is the contact allowed to post?
1038 private static function postAllow($importer, $contact, $is_comment = false)
1041 * Perhaps we were already sharing with this person. Now they're sharing with us.
1042 * That makes us friends.
1043 * Normally this should have handled by getting a request - but this could get lost
1045 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1046 // It is not removed by now. Possibly the code is needed?
1047 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1050 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1051 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1054 // $contact["rel"] = CONTACT_IS_FRIEND;
1055 // logger("defining user ".$contact["nick"]." as friend");
1058 // We don't seem to like that person
1059 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
1060 // Maybe blocked, don't accept.
1062 // We are following this person?
1063 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1064 // Yes, then it is fine.
1066 // Is it a post to a community?
1067 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1070 // Is the message a global user or a comment?
1071 } elseif (($importer["uid"] == 0) || $is_comment) {
1072 // Messages for the global users and comments are always accepted
1080 * @brief Fetches the contact id for a handle and checks if posting is allowed
1082 * @param array $importer Array of the importer user
1083 * @param string $handle The checked handle in the format user@domain.tld
1084 * @param bool $is_comment Is the check for a comment?
1086 * @return array The contact data
1088 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1090 $contact = self::contactByHandle($importer["uid"], $handle);
1092 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1093 // If a contact isn't found, we accept it anyway if it is a comment
1101 if (!self::postAllow($importer, $contact, $is_comment)) {
1102 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1109 * @brief Does the message already exists on the system?
1111 * @param int $uid The user id
1112 * @param string $guid The guid of the message
1114 * @return int|bool message id if the message already was stored into the system - or false.
1116 private static function messageExists($uid, $guid)
1119 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1124 if (DBM::is_result($r)) {
1125 logger("message ".$guid." already exists for user ".$uid);
1133 * @brief Checks for links to posts in a message
1135 * @param array $item The item array
1138 private static function fetchGuid($item)
1140 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1141 preg_replace_callback(
1143 function ($match) use ($item) {
1144 self::fetchGuidSub($match, $item);
1149 preg_replace_callback(
1150 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1151 function ($match) use ($item) {
1152 self::fetchGuidSub($match, $item);
1159 * @brief Checks for relative /people/* links in an item body to match local
1160 * contacts or prepends the remote host taken from the author link.
1162 * @param string $body The item body to replace links from
1163 * @param string $author_link The author link for missing local contact fallback
1165 * @return string the replaced string
1167 public static function replacePeopleGuid($body, $author_link)
1169 $return = preg_replace_callback(
1170 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1171 function ($match) use ($author_link) {
1173 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1174 // 1 => '0123456789abcdef'
1176 $handle = self::urlFromContactGuid($match[1]);
1179 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1181 // No local match, restoring absolute remote URL from author scheme and host
1182 $author_url = parse_url($author_link);
1183 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1195 * @brief sub function of "fetchGuid" which checks for links in messages
1197 * @param array $match array containing a link that has to be checked for a message link
1198 * @param array $item The item array
1201 private static function fetchGuidSub($match, $item)
1203 if (!self::storeByGuid($match[1], $item["author-link"])) {
1204 self::storeByGuid($match[1], $item["owner-link"]);
1209 * @brief Fetches an item with a given guid from a given server
1211 * @param string $guid the message guid
1212 * @param string $server The server address
1213 * @param int $uid The user id of the user
1215 * @return int the message id of the stored message or false
1217 private static function storeByGuid($guid, $server, $uid = 0)
1219 $serverparts = parse_url($server);
1220 $server = $serverparts["scheme"]."://".$serverparts["host"];
1222 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1224 $msg = self::message($guid, $server);
1230 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1232 // Now call the dispatcher
1233 return self::dispatchPublic($msg);
1237 * @brief Fetches a message from a server
1239 * @param string $guid message guid
1240 * @param string $server The url of the server
1241 * @param int $level Endless loop prevention
1244 * 'message' => The message XML
1245 * 'author' => The author handle
1246 * 'key' => The public key of the author
1248 private static function message($guid, $server, $level = 0)
1254 // This will work for new Diaspora servers and Friendica servers from 3.5
1255 $source_url = $server."/fetch/post/".urlencode($guid);
1257 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1259 $envelope = fetch_url($source_url);
1261 logger("Envelope was fetched.", LOGGER_DEBUG);
1262 $x = self::verifyMagicEnvelope($envelope);
1264 logger("Envelope could not be verified.", LOGGER_DEBUG);
1266 logger("Envelope was verified.", LOGGER_DEBUG);
1272 // This will work for older Diaspora and Friendica servers
1274 $source_url = $server."/p/".urlencode($guid).".xml";
1275 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1277 $x = fetch_url($source_url);
1283 $source_xml = parse_xml_string($x);
1285 if (!is_object($source_xml)) {
1289 if ($source_xml->post->reshare) {
1290 // Reshare of a reshare - old Diaspora version
1291 logger("Message is a reshare", LOGGER_DEBUG);
1292 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1293 } elseif ($source_xml->getName() == "reshare") {
1294 // Reshare of a reshare - new Diaspora version
1295 logger("Message is a new reshare", LOGGER_DEBUG);
1296 return self::message($source_xml->root_guid, $server, ++$level);
1301 // Fetch the author - for the old and the new Diaspora version
1302 if ($source_xml->post->status_message->diaspora_handle) {
1303 $author = (string)$source_xml->post->status_message->diaspora_handle;
1304 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1305 $author = (string)$source_xml->author;
1308 // If this isn't a "status_message" then quit
1310 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1314 $msg = ["message" => $x, "author" => $author];
1316 $msg["key"] = self::key($msg["author"]);
1322 * @brief Fetches the item record of a given guid
1324 * @param int $uid The user id
1325 * @param string $guid message guid
1326 * @param string $author The handle of the item
1327 * @param array $contact The contact of the item owner
1329 * @return array the item record
1331 private static function parentItem($uid, $guid, $author, $contact)
1334 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1335 `author-name`, `author-link`, `author-avatar`,
1336 `owner-name`, `owner-link`, `owner-avatar`
1337 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1343 $result = self::storeByGuid($guid, $contact["url"], $uid);
1346 $person = self::personByHandle($author);
1347 $result = self::storeByGuid($guid, $person["url"], $uid);
1351 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1354 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1355 `author-name`, `author-link`, `author-avatar`,
1356 `owner-name`, `owner-link`, `owner-avatar`
1357 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1365 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1368 logger("parent item found: parent: ".$guid." - user: ".$uid);
1374 * @brief returns contact details
1376 * @param array $contact The default contact if the person isn't found
1377 * @param array $person The record of the person
1378 * @param int $uid The user id
1381 * 'cid' => contact id
1382 * 'network' => network type
1384 private static function authorContactByUrl($contact, $person, $uid)
1387 "SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1388 dbesc(normalise_link($person["url"])),
1393 $network = $r[0]["network"];
1395 $cid = $contact["id"];
1396 $network = NETWORK_DIASPORA;
1399 return ["cid" => $cid, "network" => $network];
1403 * @brief Is the profile a hubzilla profile?
1405 * @param string $url The profile link
1407 * @return bool is it a hubzilla server?
1409 public static function isRedmatrix($url)
1411 return(strstr($url, "/channel/"));
1415 * @brief Generate a post link with a given handle and message guid
1417 * @param string $addr The user handle
1418 * @param string $guid message guid
1419 * @param string $parent_guid optional parent guid
1421 * @return string the post link
1423 private static function plink($addr, $guid, $parent_guid = '')
1425 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1428 if (!DBM::is_result($r)) {
1429 if ($parent_guid != '') {
1430 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1432 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1436 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1437 // So we try another way as well.
1438 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1439 if (DBM::is_result($s)) {
1440 $r[0]["network"] = $s[0]["network"];
1443 if ($r[0]["network"] == NETWORK_DFRN) {
1444 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1447 if (self::isRedmatrix($r[0]["url"])) {
1448 return $r[0]["url"]."/?f=&mid=".$guid;
1451 if ($parent_guid != '') {
1452 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1454 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1459 * @brief Receives account migration
1461 * @param array $importer Array of the importer user
1462 * @param object $data The message object
1464 * @return bool Success
1466 private static function receiveAccountMigration($importer, $data)
1468 $old_handle = notags(unxmlify($data->author));
1469 $new_handle = notags(unxmlify($data->profile->author));
1470 $signature = notags(unxmlify($data->signature));
1472 $contact = self::contactByHandle($importer["uid"], $old_handle);
1474 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1478 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1481 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1482 $key = self::key($old_handle);
1483 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1484 logger('No valid signature for migration.');
1488 // Update the profile
1489 self::receiveProfile($importer, $data->profile);
1491 // change the technical stuff in contact and gcontact
1492 $data = Probe::uri($new_handle);
1493 if ($data['network'] == NETWORK_PHANTOM) {
1494 logger('Account for '.$new_handle." couldn't be probed.");
1498 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1499 'name' => $data['name'], 'nick' => $data['nick'],
1500 'addr' => $data['addr'], 'batch' => $data['batch'],
1501 'notify' => $data['notify'], 'poll' => $data['poll'],
1502 'network' => $data['network']];
1504 dba::update('contact', $fields, ['addr' => $old_handle]);
1506 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1507 'name' => $data['name'], 'nick' => $data['nick'],
1508 'addr' => $data['addr'], 'connect' => $data['addr'],
1509 'notify' => $data['notify'], 'photo' => $data['photo'],
1510 'server_url' => $data['baseurl'], 'network' => $data['network']];
1512 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1514 logger('Contacts are updated.');
1517 /// @todo This is an extreme performance killer
1519 'owner-link' => [$contact["url"], $data["url"]],
1520 'author-link' => [$contact["url"], $data["url"]],
1522 foreach ($fields as $n => $f) {
1524 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1527 intval($importer["uid"])
1530 if (DBM::is_result($r)) {
1532 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1537 intval($importer["uid"])
1546 logger('Items are updated.');
1552 * @brief Processes an account deletion
1554 * @param array $importer Array of the importer user
1555 * @param object $data The message object
1557 * @return bool Success
1559 private static function receiveAccountDeletion($importer, $data)
1561 /// @todo Account deletion should remove the contact from the global contacts as well
1563 $author = notags(unxmlify($data->author));
1565 $contact = self::contactByHandle($importer["uid"], $author);
1567 logger("cannot find contact for author: ".$author);
1571 // We now remove the contact
1572 Contact::remove($contact["id"]);
1577 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1579 * @param string $author Author handle
1580 * @param string $guid Message guid
1581 * @param boolean $onlyfound Only return uri when found in the database
1583 * @return string The constructed uri or the one from our database
1585 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1587 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1588 if (DBM::is_result($r)) {
1589 return $r[0]["uri"];
1590 } elseif (!$onlyfound) {
1591 return $author.":".$guid;
1598 * @brief Fetch the guid from our database with a given uri
1600 * @param string $uri Message uri
1601 * @param string $uid Author handle
1603 * @return string The post guid
1605 private static function getGuidFromUri($uri, $uid)
1607 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1608 if (DBM::is_result($r)) {
1609 return $r[0]["guid"];
1616 * @brief Find the best importer for a comment, like, ...
1618 * @param string $guid The guid of the item
1620 * @return array|boolean the origin owner of that post - or false
1622 private static function importerForGuid($guid)
1624 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1626 if (DBM::is_result($item)) {
1627 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1628 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1629 if (DBM::is_result($contact)) {
1637 * @brief Processes an incoming comment
1639 * @param array $importer Array of the importer user
1640 * @param string $sender The sender of the message
1641 * @param object $data The message object
1642 * @param string $xml The original XML of the message
1644 * @return int The message id of the generated comment or "false" if there was an error
1646 private static function receiveComment($importer, $sender, $data, $xml)
1648 $author = notags(unxmlify($data->author));
1649 $guid = notags(unxmlify($data->guid));
1650 $parent_guid = notags(unxmlify($data->parent_guid));
1651 $text = unxmlify($data->text);
1653 if (isset($data->created_at)) {
1654 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1656 $created_at = datetime_convert();
1659 if (isset($data->thread_parent_guid)) {
1660 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1661 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1666 $contact = self::allowedContactByHandle($importer, $sender, true);
1671 $message_id = self::messageExists($importer["uid"], $guid);
1676 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1677 if (!$parent_item) {
1681 $person = self::personByHandle($author);
1682 if (!is_array($person)) {
1683 logger("unable to find author details");
1687 // Fetch the contact id - if we know this contact
1688 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1692 $datarray["uid"] = $importer["uid"];
1693 $datarray["contact-id"] = $author_contact["cid"];
1694 $datarray["network"] = $author_contact["network"];
1696 $datarray["author-name"] = $person["name"];
1697 $datarray["author-link"] = $person["url"];
1698 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1700 $datarray["owner-name"] = $contact["name"];
1701 $datarray["owner-link"] = $contact["url"];
1702 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1704 $datarray["guid"] = $guid;
1705 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1707 $datarray["type"] = "remote-comment";
1708 $datarray["verb"] = ACTIVITY_POST;
1709 $datarray["gravity"] = GRAVITY_COMMENT;
1711 if ($thr_uri != "") {
1712 $datarray["parent-uri"] = $thr_uri;
1714 $datarray["parent-uri"] = $parent_item["uri"];
1717 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1719 $datarray["protocol"] = PROTOCOL_DIASPORA;
1720 $datarray["source"] = $xml;
1722 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1724 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1726 $body = diaspora2bb($text);
1728 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1730 self::fetchGuid($datarray);
1732 $message_id = item_store($datarray);
1734 if ($message_id <= 0) {
1739 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1742 // If we are the origin of the parent we store the original data and notify our followers
1743 if ($message_id && $parent_item["origin"]) {
1744 // Formerly we stored the signed text, the signature and the author in different fields.
1745 // We now store the raw data so that we are more flexible.
1746 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1749 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1756 * @brief processes and stores private messages
1758 * @param array $importer Array of the importer user
1759 * @param array $contact The contact of the message
1760 * @param object $data The message object
1761 * @param array $msg Array of the processed message, author handle and key
1762 * @param object $mesg The private message
1763 * @param array $conversation The conversation record to which this message belongs
1765 * @return bool "true" if it was successful
1767 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1769 $author = notags(unxmlify($data->author));
1770 $guid = notags(unxmlify($data->guid));
1771 $subject = notags(unxmlify($data->subject));
1773 // "diaspora_handle" is the element name from the old version
1774 // "author" is the element name from the new version
1775 if ($mesg->author) {
1776 $msg_author = notags(unxmlify($mesg->author));
1777 } elseif ($mesg->diaspora_handle) {
1778 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1783 $msg_guid = notags(unxmlify($mesg->guid));
1784 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1785 $msg_text = unxmlify($mesg->text);
1786 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1788 if ($msg_conversation_guid != $guid) {
1789 logger("message conversation guid does not belong to the current conversation.");
1793 $body = diaspora2bb($msg_text);
1794 $message_uri = $msg_author.":".$msg_guid;
1796 $person = self::personByHandle($msg_author);
1801 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1803 intval($importer["uid"])
1805 if (DBM::is_result($r)) {
1806 logger("duplicate message already delivered.", LOGGER_DEBUG);
1811 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1812 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1813 intval($importer["uid"]),
1815 intval($conversation["id"]),
1816 dbesc($person["name"]),
1817 dbesc($person["photo"]),
1818 dbesc($person["url"]),
1819 intval($contact["id"]),
1824 dbesc($message_uri),
1825 dbesc($author.":".$guid),
1826 dbesc($msg_created_at)
1831 dba::update('conv', ['updated' => datetime_convert()], ['id' => $conversation["id"]]);
1835 "type" => NOTIFY_MAIL,
1836 "notify_flags" => $importer["notify-flags"],
1837 "language" => $importer["language"],
1838 "to_name" => $importer["username"],
1839 "to_email" => $importer["email"],
1840 "uid" =>$importer["uid"],
1841 "item" => ["subject" => $subject, "body" => $body],
1842 "source_name" => $person["name"],
1843 "source_link" => $person["url"],
1844 "source_photo" => $person["thumb"],
1845 "verb" => ACTIVITY_POST,
1852 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1854 * @param array $importer Array of the importer user
1855 * @param array $msg Array of the processed message, author handle and key
1856 * @param object $data The message object
1858 * @return bool Success
1860 private static function receiveConversation($importer, $msg, $data)
1862 $author = notags(unxmlify($data->author));
1863 $guid = notags(unxmlify($data->guid));
1864 $subject = notags(unxmlify($data->subject));
1865 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1866 $participants = notags(unxmlify($data->participants));
1868 $messages = $data->message;
1870 if (!count($messages)) {
1871 logger("empty conversation");
1875 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1880 $conversation = null;
1883 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1884 intval($importer["uid"]),
1888 $conversation = $c[0];
1891 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1892 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1893 intval($importer["uid"]),
1897 dbesc(datetime_convert()),
1899 dbesc($participants)
1903 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1904 intval($importer["uid"]),
1910 $conversation = $c[0];
1913 if (!$conversation) {
1914 logger("unable to create conversation.");
1918 foreach ($messages as $mesg) {
1919 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1926 * @brief Creates the body for a "like" message
1928 * @param array $contact The contact that send us the "like"
1929 * @param array $parent_item The item array of the parent item
1930 * @param string $guid message guid
1932 * @return string the body
1934 private static function constructLikeBody($contact, $parent_item, $guid)
1936 $bodyverb = t('%1$s likes %2$s\'s %3$s');
1938 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1939 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1940 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".t("status")."[/url]";
1942 return sprintf($bodyverb, $ulink, $alink, $plink);
1946 * @brief Creates a XML object for a "like"
1948 * @param array $importer Array of the importer user
1949 * @param array $parent_item The item array of the parent item
1951 * @return string The XML
1953 private static function constructLikeObject($importer, $parent_item)
1955 $objtype = ACTIVITY_OBJ_NOTE;
1956 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1957 $parent_body = $parent_item["body"];
1959 $xmldata = ["object" => ["type" => $objtype,
1961 "id" => $parent_item["uri"],
1964 "content" => $parent_body]];
1966 return XML::fromArray($xmldata, $xml, true);
1970 * @brief Processes "like" messages
1972 * @param array $importer Array of the importer user
1973 * @param string $sender The sender of the message
1974 * @param object $data The message object
1976 * @return int The message id of the generated like or "false" if there was an error
1978 private static function receiveLike($importer, $sender, $data)
1980 $author = notags(unxmlify($data->author));
1981 $guid = notags(unxmlify($data->guid));
1982 $parent_guid = notags(unxmlify($data->parent_guid));
1983 $parent_type = notags(unxmlify($data->parent_type));
1984 $positive = notags(unxmlify($data->positive));
1986 // likes on comments aren't supported by Diaspora - only on posts
1987 // But maybe this will be supported in the future, so we will accept it.
1988 if (!in_array($parent_type, ["Post", "Comment"])) {
1992 $contact = self::allowedContactByHandle($importer, $sender, true);
1997 $message_id = self::messageExists($importer["uid"], $guid);
2002 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2003 if (!$parent_item) {
2007 $person = self::personByHandle($author);
2008 if (!is_array($person)) {
2009 logger("unable to find author details");
2013 // Fetch the contact id - if we know this contact
2014 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2016 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2017 // We would accept this anyhow.
2018 if ($positive == "true") {
2019 $verb = ACTIVITY_LIKE;
2021 $verb = ACTIVITY_DISLIKE;
2026 $datarray["protocol"] = PROTOCOL_DIASPORA;
2028 $datarray["uid"] = $importer["uid"];
2029 $datarray["contact-id"] = $author_contact["cid"];
2030 $datarray["network"] = $author_contact["network"];
2032 $datarray["author-name"] = $person["name"];
2033 $datarray["author-link"] = $person["url"];
2034 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2036 $datarray["owner-name"] = $contact["name"];
2037 $datarray["owner-link"] = $contact["url"];
2038 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2040 $datarray["guid"] = $guid;
2041 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2043 $datarray["type"] = "activity";
2044 $datarray["verb"] = $verb;
2045 $datarray["gravity"] = GRAVITY_LIKE;
2046 $datarray["parent-uri"] = $parent_item["uri"];
2048 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2049 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2051 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2053 $message_id = item_store($datarray);
2055 if ($message_id <= 0) {
2060 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2063 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2064 if ($parent_item["id"] != $parent_item["parent"]) {
2065 $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2066 $origin = $toplevel["origin"];
2068 $origin = $parent_item["origin"];
2071 // If we are the origin of the parent we store the original data and notify our followers
2072 if ($message_id && $origin) {
2073 // Formerly we stored the signed text, the signature and the author in different fields.
2074 // We now store the raw data so that we are more flexible.
2075 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2078 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2085 * @brief Processes private messages
2087 * @param array $importer Array of the importer user
2088 * @param object $data The message object
2090 * @return bool Success?
2092 private static function receiveMessage($importer, $data)
2094 $author = notags(unxmlify($data->author));
2095 $guid = notags(unxmlify($data->guid));
2096 $conversation_guid = notags(unxmlify($data->conversation_guid));
2097 $text = unxmlify($data->text);
2098 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2100 $contact = self::allowedContactByHandle($importer, $author, true);
2105 $conversation = null;
2108 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2109 intval($importer["uid"]),
2110 dbesc($conversation_guid)
2113 $conversation = $c[0];
2115 logger("conversation not available.");
2119 $message_uri = $author.":".$guid;
2121 $person = self::personByHandle($author);
2123 logger("unable to find author details");
2127 $body = diaspora2bb($text);
2129 $body = self::replacePeopleGuid($body, $person["url"]);
2134 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2136 intval($importer["uid"])
2138 if (DBM::is_result($r)) {
2139 logger("duplicate message already delivered.", LOGGER_DEBUG);
2144 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2145 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2146 intval($importer["uid"]),
2148 intval($conversation["id"]),
2149 dbesc($person["name"]),
2150 dbesc($person["photo"]),
2151 dbesc($person["url"]),
2152 intval($contact["id"]),
2153 dbesc($conversation["subject"]),
2157 dbesc($message_uri),
2158 dbesc($author.":".$conversation["guid"]),
2164 dba::update('conv', ['updated' => datetime_convert()], ['id' => $conversation["id"]]);
2169 * @brief Processes participations - unsupported by now
2171 * @param array $importer Array of the importer user
2172 * @param object $data The message object
2174 * @return bool always true
2176 private static function receiveParticipation($importer, $data)
2178 $author = strtolower(notags(unxmlify($data->author)));
2179 $parent_guid = notags(unxmlify($data->parent_guid));
2181 $contact_id = Contact::getIdForURL($author);
2183 logger('Contact not found: '.$author);
2187 $person = self::personByHandle($author);
2188 if (!is_array($person)) {
2189 logger("Person not found: ".$author);
2193 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2194 if (!DBM::is_result($item)) {
2195 logger('Item not found, no origin or private: '.$parent_guid);
2199 $author_parts = explode('@', $author);
2200 if (isset($author_parts[1])) {
2201 $server = $author_parts[1];
2203 // Should never happen
2207 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2208 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2210 // Send all existing comments and likes to the requesting server
2211 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2213 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2214 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2215 while ($comment = dba::fetch($comments)) {
2216 if ($comment['verb'] == ACTIVITY_POST) {
2217 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2219 $cmd = $comment['self'] ? 'like' : 'comment-import';
2221 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2222 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2224 dba::close($comments);
2230 * @brief Processes photos - unneeded
2232 * @param array $importer Array of the importer user
2233 * @param object $data The message object
2235 * @return bool always true
2237 private static function receivePhoto($importer, $data)
2239 // There doesn't seem to be a reason for this function,
2240 // since the photo data is transmitted in the status message as well
2245 * @brief Processes poll participations - unssupported
2247 * @param array $importer Array of the importer user
2248 * @param object $data The message object
2250 * @return bool always true
2252 private static function receivePollParticipation($importer, $data)
2254 // We don't support polls by now
2259 * @brief Processes incoming profile updates
2261 * @param array $importer Array of the importer user
2262 * @param object $data The message object
2264 * @return bool Success
2266 private static function receiveProfile($importer, $data)
2268 $author = strtolower(notags(unxmlify($data->author)));
2270 $contact = self::contactByHandle($importer["uid"], $author);
2275 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2276 $image_url = unxmlify($data->image_url);
2277 $birthday = unxmlify($data->birthday);
2278 $gender = unxmlify($data->gender);
2279 $about = diaspora2bb(unxmlify($data->bio));
2280 $location = diaspora2bb(unxmlify($data->location));
2281 $searchable = (unxmlify($data->searchable) == "true");
2282 $nsfw = (unxmlify($data->nsfw) == "true");
2283 $tags = unxmlify($data->tag_string);
2285 $tags = explode("#", $tags);
2288 foreach ($tags as $tag) {
2289 $tag = trim(strtolower($tag));
2295 $keywords = implode(", ", $keywords);
2297 $handle_parts = explode("@", $author);
2298 $nick = $handle_parts[0];
2301 $name = $handle_parts[0];
2304 if (preg_match("|^https?://|", $image_url) === 0) {
2305 $image_url = "http://".$handle_parts[1].$image_url;
2308 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2310 // Generic birthday. We don't know the timezone. The year is irrelevant.
2312 $birthday = str_replace("1000", "1901", $birthday);
2314 if ($birthday != "") {
2315 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
2318 // this is to prevent multiple birthday notifications in a single year
2319 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2321 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2322 $birthday = $contact["bd"];
2326 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2327 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2331 dbesc(datetime_convert()),
2337 intval($contact["id"]),
2338 intval($importer["uid"])
2341 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2342 "photo" => $image_url, "name" => $name, "location" => $location,
2343 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2344 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2345 "hide" => !$searchable, "nsfw" => $nsfw];
2347 $gcid = GContact::update($gcontact);
2349 GContact::link($gcid, $importer["uid"], $contact["id"]);
2351 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2357 * @brief Processes incoming friend requests
2359 * @param array $importer Array of the importer user
2360 * @param array $contact The contact that send the request
2363 private static function receiveRequestMakeFriend($importer, $contact)
2367 if ($contact["rel"] == CONTACT_IS_SHARING) {
2370 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2371 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2374 // send notification
2377 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2378 intval($importer["uid"])
2381 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2383 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2384 intval($importer["uid"])
2387 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2389 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2391 $arr["protocol"] = PROTOCOL_DIASPORA;
2392 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2393 $arr["uid"] = $importer["uid"];
2394 $arr["contact-id"] = $self[0]["id"];
2396 $arr["type"] = 'wall';
2397 $arr["gravity"] = 0;
2399 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2400 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2401 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2402 $arr["verb"] = ACTIVITY_FRIEND;
2403 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2405 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2406 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2407 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2408 $arr["body"] = sprintf(t('%1$s is now friends with %2$s'), $A, $B)."\n\n\n".$BPhoto;
2410 $arr["object"] = self::constructNewFriendObject($contact);
2412 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2414 $arr["allow_cid"] = $user["allow_cid"];
2415 $arr["allow_gid"] = $user["allow_gid"];
2416 $arr["deny_cid"] = $user["deny_cid"];
2417 $arr["deny_gid"] = $user["deny_gid"];
2419 $i = item_store($arr);
2421 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2428 * @brief Creates a XML object for a "new friend" message
2430 * @param array $contact Array of the contact
2432 * @return string The XML
2434 private static function constructNewFriendObject($contact)
2436 $objtype = ACTIVITY_OBJ_PERSON;
2437 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2438 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2440 $xmldata = ["object" => ["type" => $objtype,
2441 "title" => $contact["name"],
2442 "id" => $contact["url"]."/".$contact["name"],
2445 return XML::fromArray($xmldata, $xml, true);
2449 * @brief Processes incoming sharing notification
2451 * @param array $importer Array of the importer user
2452 * @param object $data The message object
2454 * @return bool Success
2456 private static function receiveContactRequest($importer, $data)
2458 $author = unxmlify($data->author);
2459 $recipient = unxmlify($data->recipient);
2461 if (!$author || !$recipient) {
2465 // the current protocol version doesn't know these fields
2466 // That means that we will assume their existance
2467 if (isset($data->following)) {
2468 $following = (unxmlify($data->following) == "true");
2473 if (isset($data->sharing)) {
2474 $sharing = (unxmlify($data->sharing) == "true");
2479 $contact = self::contactByHandle($importer["uid"], $author);
2481 // perhaps we were already sharing with this person. Now they're sharing with us.
2482 // That makes us friends.
2485 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2486 self::receiveRequestMakeFriend($importer, $contact);
2488 // refetch the contact array
2489 $contact = self::contactByHandle($importer["uid"], $author);
2491 // If we are now friends, we are sending a share message.
2492 // Normally we needn't to do so, but the first message could have been vanished.
2493 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2494 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2496 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2497 $ret = self::sendShare($u[0], $contact);
2502 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2503 lose_follower($importer, $contact);
2508 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2509 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2511 } elseif (!$following && !$sharing) {
2512 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2514 } elseif (!$following && $sharing) {
2515 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2516 } elseif ($following && $sharing) {
2517 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2518 } elseif ($following && !$sharing) {
2519 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2522 $ret = self::personByHandle($author);
2524 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2525 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2529 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2532 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2533 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2534 intval($importer["uid"]),
2535 dbesc($ret["network"]),
2536 dbesc($ret["addr"]),
2539 dbesc(normalise_link($ret["url"])),
2541 dbesc($ret["name"]),
2542 dbesc($ret["nick"]),
2543 dbesc($ret["photo"]),
2544 dbesc($ret["pubkey"]),
2545 dbesc($ret["notify"]),
2546 dbesc($ret["poll"]),
2551 // find the contact record we just created
2553 $contact_record = self::contactByHandle($importer["uid"], $author);
2555 if (!$contact_record) {
2556 logger("unable to locate newly created contact record.");
2560 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2562 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2564 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2566 if ($importer["page-flags"] == PAGE_NORMAL) {
2567 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2569 $hash = random_string().(string)time(); // Generate a confirm_key
2572 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2573 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2574 intval($importer["uid"]),
2575 intval($contact_record["id"]),
2578 dbesc(t("Sharing notification from Diaspora network")),
2580 dbesc(datetime_convert())
2583 // automatic friend approval
2585 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2587 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2589 // technically they are sharing with us (CONTACT_IS_SHARING),
2590 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2591 // we are going to change the relationship and make them a follower.
2593 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2594 $new_relation = CONTACT_IS_FRIEND;
2595 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2596 $new_relation = CONTACT_IS_SHARING;
2598 $new_relation = CONTACT_IS_FOLLOWER;
2602 "UPDATE `contact` SET `rel` = %d,
2610 intval($new_relation),
2611 dbesc(datetime_convert()),
2612 dbesc(datetime_convert()),
2613 intval($contact_record["id"])
2616 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2618 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2619 $ret = self::sendShare($u[0], $contact_record);
2621 // Send the profile data, maybe it weren't transmitted before
2622 self::sendProfile($importer["uid"], [$contact_record]);
2630 * @brief Fetches a message with a given guid
2632 * @param string $guid message guid
2633 * @param string $orig_author handle of the original post
2634 * @param string $author handle of the sharer
2636 * @return array The fetched item
2638 private static function originalItem($guid, $orig_author, $author)
2640 // Do we already have this item?
2642 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2643 `author-name`, `author-link`, `author-avatar`
2644 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2648 if (DBM::is_result($r)) {
2649 logger("reshared message ".$guid." already exists on system.");
2651 // Maybe it is already a reshared item?
2652 // Then refetch the content, if it is a reshare from a reshare.
2653 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2654 if (self::isReshare($r[0]["body"], true)) {
2656 } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2657 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2659 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2661 // Add OEmbed and other information to the body
2662 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2670 if (!DBM::is_result($r)) {
2671 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2672 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2673 $item_id = self::storeByGuid($guid, $server);
2676 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2677 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2678 $item_id = self::storeByGuid($guid, $server);
2683 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2684 `author-name`, `author-link`, `author-avatar`
2685 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2689 if (DBM::is_result($r)) {
2690 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2691 if (self::isReshare($r[0]["body"], false)) {
2692 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2693 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2704 * @brief Processes a reshare message
2706 * @param array $importer Array of the importer user
2707 * @param object $data The message object
2708 * @param string $xml The original XML of the message
2710 * @return int the message id
2712 private static function receiveReshare($importer, $data, $xml)
2714 $author = notags(unxmlify($data->author));
2715 $guid = notags(unxmlify($data->guid));
2716 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2717 $root_author = notags(unxmlify($data->root_author));
2718 $root_guid = notags(unxmlify($data->root_guid));
2719 /// @todo handle unprocessed property "provider_display_name"
2720 $public = notags(unxmlify($data->public));
2722 $contact = self::allowedContactByHandle($importer, $author, false);
2727 $message_id = self::messageExists($importer["uid"], $guid);
2732 $original_item = self::originalItem($root_guid, $root_author, $author);
2733 if (!$original_item) {
2737 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2741 $datarray["uid"] = $importer["uid"];
2742 $datarray["contact-id"] = $contact["id"];
2743 $datarray["network"] = NETWORK_DIASPORA;
2745 $datarray["author-name"] = $contact["name"];
2746 $datarray["author-link"] = $contact["url"];
2747 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2749 $datarray["owner-name"] = $datarray["author-name"];
2750 $datarray["owner-link"] = $datarray["author-link"];
2751 $datarray["owner-avatar"] = $datarray["author-avatar"];
2753 $datarray["guid"] = $guid;
2754 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2756 $datarray["verb"] = ACTIVITY_POST;
2757 $datarray["gravity"] = GRAVITY_PARENT;
2759 $datarray["protocol"] = PROTOCOL_DIASPORA;
2760 $datarray["source"] = $xml;
2762 $prefix = share_header(
2763 $original_item["author-name"],
2764 $original_item["author-link"],
2765 $original_item["author-avatar"],
2766 $original_item["guid"],
2767 $original_item["created"],
2770 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2772 $datarray["tag"] = $original_item["tag"];
2773 $datarray["app"] = $original_item["app"];
2775 $datarray["plink"] = self::plink($author, $guid);
2776 $datarray["private"] = (($public == "false") ? 1 : 0);
2777 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2779 $datarray["object-type"] = $original_item["object-type"];
2781 self::fetchGuid($datarray);
2782 $message_id = item_store($datarray);
2784 self::sendParticipation($contact, $datarray);
2787 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2795 * @brief Processes retractions
2797 * @param array $importer Array of the importer user
2798 * @param array $contact The contact of the item owner
2799 * @param object $data The message object
2801 * @return bool success
2803 private static function itemRetraction($importer, $contact, $data)
2805 $author = notags(unxmlify($data->author));
2806 $target_guid = notags(unxmlify($data->target_guid));
2807 $target_type = notags(unxmlify($data->target_type));
2809 $person = self::personByHandle($author);
2810 if (!is_array($person)) {
2811 logger("unable to find author detail for ".$author);
2815 if (empty($contact["url"])) {
2816 $contact["url"] = $person["url"];
2819 // Fetch items that are about to be deleted
2820 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2822 // When we receive a public retraction, we delete every item that we find.
2823 if ($importer['uid'] == 0) {
2824 $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2826 $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2828 $r = dba::select('item', $fields, $condition);
2829 if (!DBM::is_result($r)) {
2830 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2834 while ($item = dba::fetch($r)) {
2835 // Fetch the parent item
2836 $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2838 // Only delete it if the parent author really fits
2839 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2840 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2844 // Currently we don't have a central deletion function that we could use in this case.
2845 // The function "item_drop" doesn't work for that case
2852 'edited' => datetime_convert(),
2853 'changed' => datetime_convert()],
2854 ['id' => $item["id"]]
2857 // Delete the thread - if it is a starting post and not a comment
2858 if ($target_type != 'Comment') {
2859 delete_thread($item["id"], $item["parent-uri"]);
2862 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2864 // Now check if the retraction needs to be relayed by us
2865 if ($parent["origin"]) {
2867 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2875 * @brief Receives retraction messages
2877 * @param array $importer Array of the importer user
2878 * @param string $sender The sender of the message
2879 * @param object $data The message object
2881 * @return bool Success
2883 private static function receiveRetraction($importer, $sender, $data)
2885 $target_type = notags(unxmlify($data->target_type));
2887 $contact = self::contactByHandle($importer["uid"], $sender);
2888 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2889 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2893 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2895 switch ($target_type) {
2900 case "StatusMessage":
2901 return self::itemRetraction($importer, $contact, $data);
2905 /// @todo What should we do with an "unshare"?
2906 // Removing the contact isn't correct since we still can read the public items
2907 Contact::remove($contact["id"]);
2911 logger("Unknown target type ".$target_type);
2918 * @brief Receives status messages
2920 * @param array $importer Array of the importer user
2921 * @param object $data The message object
2922 * @param string $xml The original XML of the message
2924 * @return int The message id of the newly created item
2926 private static function receiveStatusMessage($importer, $data, $xml)
2928 $author = notags(unxmlify($data->author));
2929 $guid = notags(unxmlify($data->guid));
2930 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2931 $public = notags(unxmlify($data->public));
2932 $text = unxmlify($data->text);
2933 $provider_display_name = notags(unxmlify($data->provider_display_name));
2935 $contact = self::allowedContactByHandle($importer, $author, false);
2940 $message_id = self::messageExists($importer["uid"], $guid);
2946 if ($data->location) {
2947 foreach ($data->location->children() as $fieldname => $data) {
2948 $address[$fieldname] = notags(unxmlify($data));
2952 $body = diaspora2bb($text);
2956 // Attach embedded pictures to the body
2958 foreach ($data->photo as $photo) {
2959 $body = "[img]".unxmlify($photo->remote_photo_path).
2960 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2963 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2965 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2967 // Add OEmbed and other information to the body
2968 if (!self::isRedmatrix($contact["url"])) {
2969 $body = add_page_info_to_body($body, false, true);
2973 /// @todo enable support for polls
2974 //if ($data->poll) {
2975 // foreach ($data->poll AS $poll)
2980 /// @todo enable support for events
2982 $datarray["uid"] = $importer["uid"];
2983 $datarray["contact-id"] = $contact["id"];
2984 $datarray["network"] = NETWORK_DIASPORA;
2986 $datarray["author-name"] = $contact["name"];
2987 $datarray["author-link"] = $contact["url"];
2988 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2990 $datarray["owner-name"] = $datarray["author-name"];
2991 $datarray["owner-link"] = $datarray["author-link"];
2992 $datarray["owner-avatar"] = $datarray["author-avatar"];
2994 $datarray["guid"] = $guid;
2995 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2997 $datarray["verb"] = ACTIVITY_POST;
2998 $datarray["gravity"] = GRAVITY_PARENT;
3000 $datarray["protocol"] = PROTOCOL_DIASPORA;
3001 $datarray["source"] = $xml;
3003 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3005 if ($provider_display_name != "") {
3006 $datarray["app"] = $provider_display_name;
3009 $datarray["plink"] = self::plink($author, $guid);
3010 $datarray["private"] = (($public == "false") ? 1 : 0);
3011 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3013 if (isset($address["address"])) {
3014 $datarray["location"] = $address["address"];
3017 if (isset($address["lat"]) && isset($address["lng"])) {
3018 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3021 self::fetchGuid($datarray);
3022 $message_id = item_store($datarray);
3024 self::sendParticipation($contact, $datarray);
3027 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3034 /* ************************************************************************************** *
3035 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3036 * ************************************************************************************** */
3039 * @brief returnes the handle of a contact
3041 * @param array $contact contact array
3043 * @return string the handle in the format user@domain.tld
3045 private static function myHandle($contact)
3047 if ($contact["addr"] != "") {
3048 return $contact["addr"];
3051 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3052 // So - just in case - we build the the address here.
3053 if ($contact["nickname"] != "") {
3054 $nick = $contact["nickname"];
3056 $nick = $contact["nick"];
3059 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3064 * @brief Creates the data for a private message in the new format
3066 * @param string $msg The message that is to be transmitted
3067 * @param array $user The record of the sender
3068 * @param array $contact Target of the communication
3069 * @param string $prvkey The private key of the sender
3070 * @param string $pubkey The public key of the receiver
3072 * @return string The encrypted data
3074 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3076 logger("Message: ".$msg, LOGGER_DATA);
3078 // without a public key nothing will work
3080 logger("pubkey missing: contact id: ".$contact["id"]);
3084 $aes_key = openssl_random_pseudo_bytes(32);
3085 $b_aes_key = base64_encode($aes_key);
3086 $iv = openssl_random_pseudo_bytes(16);
3087 $b_iv = base64_encode($iv);
3089 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3091 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3093 $encrypted_key_bundle = "";
3094 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3096 $json_object = json_encode(
3097 ["aes_key" => base64_encode($encrypted_key_bundle),
3098 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3101 return $json_object;
3105 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3107 * @param string $msg The message that is to be transmitted
3108 * @param array $user The record of the sender
3110 * @return string The envelope
3112 public static function buildMagicEnvelope($msg, $user)
3114 $b64url_data = base64url_encode($msg);
3115 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3117 $key_id = base64url_encode(self::myHandle($user));
3118 $type = "application/xml";
3119 $encoding = "base64url";
3120 $alg = "RSA-SHA256";
3121 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3123 // Fallback if the private key wasn't transmitted in the expected field
3124 if ($user['uprvkey'] == "") {
3125 $user['uprvkey'] = $user['prvkey'];
3128 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3129 $sig = base64url_encode($signature);
3131 $xmldata = ["me:env" => ["me:data" => $data,
3132 "@attributes" => ["type" => $type],
3133 "me:encoding" => $encoding,
3136 "@attributes2" => ["key_id" => $key_id]]];
3138 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3140 return XML::fromArray($xmldata, $xml, false, $namespaces);
3144 * @brief Create the envelope for a message
3146 * @param string $msg The message that is to be transmitted
3147 * @param array $user The record of the sender
3148 * @param array $contact Target of the communication
3149 * @param string $prvkey The private key of the sender
3150 * @param string $pubkey The public key of the receiver
3151 * @param bool $public Is the message public?
3153 * @return string The message that will be transmitted to other servers
3155 private static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3157 // The message is put into an envelope with the sender's signature
3158 $envelope = self::buildMagicEnvelope($msg, $user);
3160 // Private messages are put into a second envelope, encrypted with the receivers public key
3162 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3169 * @brief Creates a signature for a message
3171 * @param array $owner the array of the owner of the message
3172 * @param array $message The message that is to be signed
3174 * @return string The signature
3176 private static function signature($owner, $message)
3179 unset($sigmsg["author_signature"]);
3180 unset($sigmsg["parent_author_signature"]);
3182 $signed_text = implode(";", $sigmsg);
3184 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3188 * @brief Transmit a message to a target server
3190 * @param array $owner the array of the item owner
3191 * @param array $contact Target of the communication
3192 * @param string $envelope The message that is to be transmitted
3193 * @param bool $public_batch Is it a public post?
3194 * @param bool $queue_run Is the transmission called from the queue?
3195 * @param string $guid message guid
3197 * @return int Result of the transmission
3199 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "")
3203 $enabled = intval(Config::get("system", "diaspora_enabled"));
3208 $logid = random_string(4);
3209 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3211 // Fetch the fcontact entry when there is missing data
3212 // Will possibly happen when data is transmitted to a DFRN contact
3213 if (empty($dest_url) && !empty($contact['addr'])) {
3214 $fcontact = self::personByHandle($contact['addr']);
3215 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3219 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3223 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3225 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3228 if (!intval(Config::get("system", "diaspora_test"))) {
3229 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3231 post_url($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3232 $return_code = $a->get_curl_code();
3234 logger("test_mode");
3239 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3241 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3242 logger("queue message");
3245 "SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
3246 intval($contact["id"]),
3247 dbesc(NETWORK_DIASPORA),
3249 intval($public_batch)
3252 logger("add_to_queue ignored - identical item already in queue");
3254 // queue message for redelivery
3255 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch);
3257 // The message could not be delivered. We mark the contact as "dead"
3258 Contact::markForArchival($contact);
3260 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3261 // We successfully delivered a message, the contact is alive
3262 Contact::unmarkForArchival($contact);
3265 return(($return_code) ? $return_code : (-1));
3270 * @brief Build the post xml
3272 * @param string $type The message type
3273 * @param array $message The message data
3275 * @return string The post XML
3277 public static function buildPostXml($type, $message)
3279 $data = [$type => $message];
3281 return XML::fromArray($data, $xml);
3285 * @brief Builds and transmit messages
3287 * @param array $owner the array of the item owner
3288 * @param array $contact Target of the communication
3289 * @param string $type The message type
3290 * @param array $message The message data
3291 * @param bool $public_batch Is it a public post?
3292 * @param string $guid message guid
3293 * @param bool $spool Should the transmission be spooled or transmitted?
3295 * @return int Result of the transmission
3297 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3299 $msg = self::buildPostXml($type, $message);
3301 logger('message: '.$msg, LOGGER_DATA);
3302 logger('send guid '.$guid, LOGGER_DEBUG);
3304 // Fallback if the private key wasn't transmitted in the expected field
3305 if ($owner['uprvkey'] == "") {
3306 $owner['uprvkey'] = $owner['prvkey'];
3309 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3312 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch);
3315 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3318 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3320 return $return_code;
3324 * @brief sends a participation (Used to get all further updates)
3326 * @param array $contact Target of the communication
3327 * @param array $item Item array
3329 * @return int The result of the transmission
3331 private static function sendParticipation($contact, $item)
3333 // Don't send notifications for private postings
3334 if ($item['private']) {
3338 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3340 $result = Cache::get($cachekey);
3341 if (!is_null($result)) {
3345 // Fetch some user id to have a valid handle to transmit the participation.
3346 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3347 // If the item belongs to a user, we take this user id.
3348 if ($item['uid'] == 0) {
3349 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3350 $first_user = dba::selectFirst('user', ['uid'], $condition);
3351 $owner = User::getOwnerDataById($first_user['uid']);
3353 $owner = User::getOwnerDataById($item['uid']);
3356 $author = self::myHandle($owner);
3358 $message = ["author" => $author,
3359 "guid" => get_guid(32),
3360 "parent_type" => "Post",
3361 "parent_guid" => $item["guid"]];
3363 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3365 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3366 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3368 return self::buildAndTransmit($owner, $contact, "participation", $message);
3372 * @brief sends an account migration
3374 * @param array $owner the array of the item owner
3375 * @param array $contact Target of the communication
3376 * @param int $uid User ID
3378 * @return int The result of the transmission
3380 public static function sendAccountMigration($owner, $contact, $uid)
3382 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3383 $profile = self::createProfileData($uid);
3385 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3386 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3388 $message = ["author" => $old_handle,
3389 "profile" => $profile,
3390 "signature" => $signature];
3392 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3394 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3398 * @brief Sends a "share" message
3400 * @param array $owner the array of the item owner
3401 * @param array $contact Target of the communication
3403 * @return int The result of the transmission
3405 public static function sendShare($owner, $contact)
3408 * @todo support the different possible combinations of "following" and "sharing"
3409 * Currently, Diaspora only interprets the "sharing" field
3411 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3415 switch ($contact["rel"]) {
3416 case CONTACT_IS_FRIEND:
3419 case CONTACT_IS_SHARING:
3422 case CONTACT_IS_FOLLOWER:
3428 $message = ["author" => self::myHandle($owner),
3429 "recipient" => $contact["addr"],
3430 "following" => "true",
3431 "sharing" => "true"];
3433 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3435 return self::buildAndTransmit($owner, $contact, "contact", $message);
3439 * @brief sends an "unshare"
3441 * @param array $owner the array of the item owner
3442 * @param array $contact Target of the communication
3444 * @return int The result of the transmission
3446 public static function sendUnshare($owner, $contact)
3448 $message = ["author" => self::myHandle($owner),
3449 "recipient" => $contact["addr"],
3450 "following" => "false",
3451 "sharing" => "false"];
3453 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3455 return self::buildAndTransmit($owner, $contact, "contact", $message);
3459 * @brief Checks a message body if it is a reshare
3461 * @param string $body The message body that is to be check
3462 * @param bool $complete Should it be a complete check or a simple check?
3464 * @return array|bool Reshare details or "false" if no reshare
3466 public static function isReshare($body, $complete = true)
3468 $body = trim($body);
3470 // Skip if it isn't a pure repeated messages
3471 // Does it start with a share?
3472 if ((strpos($body, "[share") > 0) && $complete) {
3476 // Does it end with a share?
3477 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3481 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3482 // Skip if there is no shared message in there
3483 if ($body == $attributes) {
3487 // If we don't do the complete check we quit here
3493 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3494 if ($matches[1] != "") {
3495 $guid = $matches[1];
3498 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3499 if ($matches[1] != "") {
3500 $guid = $matches[1];
3505 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3512 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3513 $ret["root_guid"] = $guid;
3519 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3520 if ($matches[1] != "") {
3521 $profile = $matches[1];
3524 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3525 if ($matches[1] != "") {
3526 $profile = $matches[1];
3531 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3532 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3537 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3538 if ($matches[1] != "") {
3539 $link = $matches[1];
3542 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3543 if ($matches[1] != "") {
3544 $link = $matches[1];
3547 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3548 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3556 * @brief Create an event array
3558 * @param integer $event_id The id of the event
3560 * @return array with event data
3562 private static function buildEvent($event_id)
3564 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3565 if (!DBM::is_result($r)) {
3573 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3574 if (!DBM::is_result($r)) {
3580 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3581 if (!DBM::is_result($r)) {
3587 $eventdata['author'] = self::myHandle($owner);
3589 if ($event['guid']) {
3590 $eventdata['guid'] = $event['guid'];
3593 $mask = 'Y-m-d\TH:i:s\Z';
3595 /// @todo - establish "all day" events in Friendica
3596 $eventdata["all_day"] = "false";
3598 if (!$event['adjust']) {
3599 $eventdata['timezone'] = $user['timezone'];
3601 if ($eventdata['timezone'] == "") {
3602 $eventdata['timezone'] = 'UTC';
3606 if ($event['start']) {
3607 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3609 if ($event['finish'] && !$event['nofinish']) {
3610 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3612 if ($event['summary']) {
3613 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3615 if ($event['desc']) {
3616 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3618 if ($event['location']) {
3620 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3621 $location["lat"] = 0;
3622 $location["lng"] = 0;
3623 $eventdata['location'] = $location;
3630 * @brief Create a post (status message or reshare)
3632 * @param array $item The item that will be exported
3633 * @param array $owner the array of the item owner
3636 * 'type' -> Message type ("status_message" or "reshare")
3637 * 'message' -> Array of XML elements of the status
3639 public static function buildStatus($item, $owner)
3641 $cachekey = "diaspora:buildStatus:".$item['guid'];
3643 $result = Cache::get($cachekey);
3644 if (!is_null($result)) {
3648 $myaddr = self::myHandle($owner);
3650 $public = (($item["private"]) ? "false" : "true");
3652 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3654 // Detect a share element and do a reshare
3655 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3656 $message = ["author" => $myaddr,
3657 "guid" => $item["guid"],
3658 "created_at" => $created,
3659 "root_author" => $ret["root_handle"],
3660 "root_guid" => $ret["root_guid"],
3661 "provider_display_name" => $item["app"],
3662 "public" => $public];
3666 $title = $item["title"];
3667 $body = $item["body"];
3669 // convert to markdown
3670 $body = html_entity_decode(bb2diaspora($body));
3673 if (strlen($title)) {
3674 $body = "## ".html_entity_decode($title)."\n\n".$body;
3677 if ($item["attach"]) {
3678 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3680 $body .= "\n".t("Attachments:")."\n";
3681 foreach ($matches as $mtch) {
3682 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3689 if ($item["location"] != "")
3690 $location["address"] = $item["location"];
3692 if ($item["coord"] != "") {
3693 $coord = explode(" ", $item["coord"]);
3694 $location["lat"] = $coord[0];
3695 $location["lng"] = $coord[1];
3698 $message = ["author" => $myaddr,
3699 "guid" => $item["guid"],
3700 "created_at" => $created,
3701 "public" => $public,
3703 "provider_display_name" => $item["app"],
3704 "location" => $location];
3706 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3707 if (!isset($location["lat"]) || !isset($location["lng"])) {
3708 unset($message["location"]);
3711 if ($item['event-id'] > 0) {
3712 $event = self::buildEvent($item['event-id']);
3713 if (count($event)) {
3714 $message['event'] = $event;
3716 /// @todo Once Diaspora supports it, we will remove the body
3717 // $message['text'] = '';
3721 $type = "status_message";
3724 $msg = ["type" => $type, "message" => $message];
3726 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3732 * @brief Sends a post
3734 * @param array $item The item that will be exported
3735 * @param array $owner the array of the item owner
3736 * @param array $contact Target of the communication
3737 * @param bool $public_batch Is it a public post?
3739 * @return int The result of the transmission
3741 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3743 $status = self::buildStatus($item, $owner);
3745 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3749 * @brief Creates a "like" object
3751 * @param array $item The item that will be exported
3752 * @param array $owner the array of the item owner
3754 * @return array The data for a "like"
3756 private static function constructLike($item, $owner)
3759 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3760 dbesc($item["thr-parent"])
3762 if (!DBM::is_result($p)) {
3768 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3769 if ($item['verb'] === ACTIVITY_LIKE) {
3771 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3772 $positive = "false";
3775 return(["author" => self::myHandle($owner),
3776 "guid" => $item["guid"],
3777 "parent_guid" => $parent["guid"],
3778 "parent_type" => $target_type,
3779 "positive" => $positive,
3780 "author_signature" => ""]);
3784 * @brief Creates an "EventParticipation" object
3786 * @param array $item The item that will be exported
3787 * @param array $owner the array of the item owner
3789 * @return array The data for an "EventParticipation"
3791 private static function constructAttend($item, $owner)
3794 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3795 dbesc($item["thr-parent"])
3797 if (!DBM::is_result($p)) {
3803 switch ($item['verb']) {
3804 case ACTIVITY_ATTEND:
3805 $attend_answer = 'accepted';
3807 case ACTIVITY_ATTENDNO:
3808 $attend_answer = 'declined';
3810 case ACTIVITY_ATTENDMAYBE:
3811 $attend_answer = 'tentative';
3814 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3818 return(["author" => self::myHandle($owner),
3819 "guid" => $item["guid"],
3820 "parent_guid" => $parent["guid"],
3821 "status" => $attend_answer,
3822 "author_signature" => ""]);
3826 * @brief Creates the object for a comment
3828 * @param array $item The item that will be exported
3829 * @param array $owner the array of the item owner
3831 * @return array The data for a comment
3833 private static function constructComment($item, $owner)
3835 $cachekey = "diaspora:constructComment:".$item['guid'];
3837 $result = Cache::get($cachekey);
3838 if (!is_null($result)) {
3843 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3844 intval($item["parent"]),
3845 intval($item["parent"])
3848 if (!DBM::is_result($p)) {
3854 $text = html_entity_decode(bb2diaspora($item["body"]));
3855 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3857 $comment = ["author" => self::myHandle($owner),
3858 "guid" => $item["guid"],
3859 "created_at" => $created,
3860 "parent_guid" => $parent["guid"],
3862 "author_signature" => ""];
3864 // Send the thread parent guid only if it is a threaded comment
3865 if ($item['thr-parent'] != $item['parent-uri']) {
3866 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3869 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3875 * @brief Send a like or a comment
3877 * @param array $item The item that will be exported
3878 * @param array $owner the array of the item owner
3879 * @param array $contact Target of the communication
3880 * @param bool $public_batch Is it a public post?
3882 * @return int The result of the transmission
3884 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3886 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3887 $message = self::constructAttend($item, $owner);
3888 $type = "event_participation";
3889 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3890 $message = self::constructLike($item, $owner);
3893 $message = self::constructComment($item, $owner);
3901 $message["author_signature"] = self::signature($owner, $message);
3903 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3907 * @brief Creates a message from a signature record entry
3909 * @param array $item The item that will be exported
3910 * @param array $signature The entry of the "sign" record
3912 * @return string The message
3914 private static function messageFromSignature($item, $signature)
3916 // Split the signed text
3917 $signed_parts = explode(";", $signature['signed_text']);
3919 if ($item["deleted"]) {
3920 $message = ["author" => $signature['signer'],
3921 "target_guid" => $signed_parts[0],
3922 "target_type" => $signed_parts[1]];
3923 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3924 $message = ["author" => $signed_parts[4],
3925 "guid" => $signed_parts[1],
3926 "parent_guid" => $signed_parts[3],
3927 "parent_type" => $signed_parts[2],
3928 "positive" => $signed_parts[0],
3929 "author_signature" => $signature['signature'],
3930 "parent_author_signature" => ""];
3932 // Remove the comment guid
3933 $guid = array_shift($signed_parts);
3935 // Remove the parent guid
3936 $parent_guid = array_shift($signed_parts);
3938 // Remove the handle
3939 $handle = array_pop($signed_parts);
3941 // Glue the parts together
3942 $text = implode(";", $signed_parts);
3944 $message = ["author" => $handle,
3946 "parent_guid" => $parent_guid,
3947 "text" => implode(";", $signed_parts),
3948 "author_signature" => $signature['signature'],
3949 "parent_author_signature" => ""];
3955 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3957 * @param array $item The item that will be exported
3958 * @param array $owner the array of the item owner
3959 * @param array $contact Target of the communication
3960 * @param bool $public_batch Is it a public post?
3962 * @return int The result of the transmission
3964 public static function sendRelay($item, $owner, $contact, $public_batch = false)
3966 if ($item["deleted"]) {
3967 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3968 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3974 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3976 // fetch the original signature
3979 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3984 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3990 // Old way - is used by the internal Friendica functions
3991 /// @todo Change all signatur storing functions to the new format
3992 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3993 $message = self::messageFromSignature($item, $signature);
3995 $msg = json_decode($signature['signed_text'], true);
3998 if (is_array($msg)) {
3999 foreach ($msg as $field => $data) {
4000 if (!$item["deleted"]) {
4001 if ($field == "diaspora_handle") {
4004 if ($field == "target_type") {
4005 $field = "parent_type";
4009 $message[$field] = $data;
4012 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
4016 $message["parent_author_signature"] = self::signature($owner, $message);
4018 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
4020 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4024 * @brief Sends a retraction (deletion) of a message, like or comment
4026 * @param array $item The item that will be exported
4027 * @param array $owner the array of the item owner
4028 * @param array $contact Target of the communication
4029 * @param bool $public_batch Is it a public post?
4030 * @param bool $relay Is the retraction transmitted from a relay?
4032 * @return int The result of the transmission
4034 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4036 $itemaddr = self::handleFromContact($item["contact-id"], $item["gcontact-id"]);
4038 $msg_type = "retraction";
4040 if ($item['id'] == $item['parent']) {
4041 $target_type = "Post";
4042 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4043 $target_type = "Like";
4045 $target_type = "Comment";
4048 $message = ["author" => $itemaddr,
4049 "target_guid" => $item['guid'],
4050 "target_type" => $target_type];
4052 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4054 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4058 * @brief Sends a mail
4060 * @param array $item The item that will be exported
4061 * @param array $owner The owner
4062 * @param array $contact Target of the communication
4064 * @return int The result of the transmission
4066 public static function sendMail($item, $owner, $contact)
4068 $myaddr = self::myHandle($owner);
4071 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4072 intval($item["convid"]),
4073 intval($item["uid"])
4076 if (!DBM::is_result($r)) {
4077 logger("conversation not found.");
4083 "author" => $cnv["creator"],
4084 "guid" => $cnv["guid"],
4085 "subject" => $cnv["subject"],
4086 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
4087 "participants" => $cnv["recips"]
4090 $body = bb2diaspora($item["body"]);
4091 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
4094 "author" => $myaddr,
4095 "guid" => $item["guid"],
4096 "conversation_guid" => $cnv["guid"],
4098 "created_at" => $created,
4101 if ($item["reply"]) {
4106 "author" => $cnv["creator"],
4107 "guid" => $cnv["guid"],
4108 "subject" => $cnv["subject"],
4109 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
4110 "participants" => $cnv["recips"],
4113 $type = "conversation";
4116 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4120 * @brief Split a name into first name and last name
4122 * @param string $name The name
4124 * @return array The array with "first" and "last"
4126 public static function splitName($name) {
4127 $name = trim($name);
4129 // Is the name longer than 64 characters? Then cut the rest of it.
4130 if (strlen($name) > 64) {
4131 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4132 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4134 $name = substr($name, 0, 64);
4138 // Take the first word as first name
4139 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4140 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4141 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4142 return ['first' => $first, 'last' => $last];
4145 // Take the last word as last name
4146 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4147 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4149 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4150 return ['first' => $first, 'last' => $last];
4153 // Take the first 32 characters if there is no space in the first 32 characters
4154 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4155 $first = substr($name, 0, 32);
4156 $last = substr($name, 32);
4157 return ['first' => $first, 'last' => $last];
4160 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4161 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4163 // Check if the last name is longer than 32 characters
4164 if (strlen($last) > 32) {
4165 if (strpos($last, ' ') <= 32) {
4166 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4168 $last = substr($last, 0, 32);
4172 return ['first' => $first, 'last' => $last];
4176 * @brief Create profile data
4178 * @param int $uid The user id
4180 * @return array The profile data
4182 private static function createProfileData($uid)
4185 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4187 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4188 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4189 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4198 $handle = $profile["addr"];
4200 $split_name = self::splitName($profile['name']);
4201 $first = $split_name['first'];
4202 $last = $split_name['last'];
4204 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4205 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4206 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4207 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4209 if ($searchable === 'true') {
4210 $dob = '1000-00-00';
4212 if (($profile['dob']) && ($profile['dob'] > '0001-01-01')) {
4213 $dob = ((intval($profile['dob'])) ? intval($profile['dob']) : '1000') .'-'. datetime_convert('UTC', 'UTC', $profile['dob'],'m-d');
4216 $about = $profile['about'];
4217 $about = strip_tags(bbcode($about));
4219 $location = Profile::formatLocation($profile);
4221 if ($profile['pub_keywords']) {
4222 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4223 $kw = str_replace(' ', ' ', $kw);
4224 $arr = explode(' ', $profile['pub_keywords']);
4226 for ($x = 0; $x < 5; $x ++) {
4227 if (trim($arr[$x])) {
4228 $tags .= '#'. trim($arr[$x]) .' ';
4233 $tags = trim($tags);
4236 return ["author" => $handle,
4237 "first_name" => $first,
4238 "last_name" => $last,
4239 "image_url" => $large,
4240 "image_url_medium" => $medium,
4241 "image_url_small" => $small,
4243 "gender" => $profile['gender'],
4245 "location" => $location,
4246 "searchable" => $searchable,
4248 "tag_string" => $tags];
4252 * @brief Sends profile data
4254 * @param int $uid The user id
4255 * @param bool $recips optional, default false
4258 public static function sendProfile($uid, $recips = false)
4264 $owner = User::getOwnerDataById($uid);
4271 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4272 AND `uid` = %d AND `rel` != %d",
4273 dbesc(NETWORK_DIASPORA),
4275 intval(CONTACT_IS_SHARING)
4283 $message = self::createProfileData($uid);
4285 foreach ($recips as $recip) {
4286 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4287 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", true);
4292 * @brief Stores the signature for likes that are created on our system
4294 * @param array $contact The contact array of the "like"
4295 * @param int $post_id The post id of the "like"
4297 * @return bool Success
4299 public static function storeLikeSignature($contact, $post_id)
4301 // Is the contact the owner? Then fetch the private key
4302 if (!$contact['self'] || ($contact['uid'] == 0)) {
4303 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4307 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4308 if (!DBM::is_result($r)) {
4312 $contact["uprvkey"] = $r[0]['prvkey'];
4314 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4315 if (!DBM::is_result($r)) {
4319 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4323 $message = self::constructLike($r[0], $contact);
4324 if ($message === false) {
4328 $message["author_signature"] = self::signature($contact, $message);
4331 * Now store the signature more flexible to dynamically support new fields.
4332 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4334 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4336 logger('Stored diaspora like signature');
4341 * @brief Stores the signature for comments that are created on our system
4343 * @param array $item The item array of the comment
4344 * @param array $contact The contact array of the item owner
4345 * @param string $uprvkey The private key of the sender
4346 * @param int $message_id The message id of the comment
4348 * @return bool Success
4350 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4352 if ($uprvkey == "") {
4353 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4357 $contact["uprvkey"] = $uprvkey;
4359 $message = self::constructComment($item, $contact);
4360 if ($message === false) {
4364 $message["author_signature"] = self::signature($contact, $message);
4367 * Now store the signature more flexible to dynamically support new fields.
4368 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4370 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4372 logger('Stored diaspora comment signature');