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\L10n;
17 use Friendica\Core\PConfig;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBM;
20 use Friendica\Model\Contact;
21 use Friendica\Model\GContact;
22 use Friendica\Model\Group;
23 use Friendica\Model\Profile;
24 use Friendica\Model\Queue;
25 use Friendica\Model\User;
26 use Friendica\Network\Probe;
27 use Friendica\Util\Crypto;
28 use Friendica\Util\Network;
29 use Friendica\Util\XML;
33 require_once 'include/dba.php';
34 require_once 'include/items.php';
35 require_once 'include/bb2diaspora.php';
36 require_once 'include/datetime.php';
39 * @brief This class contain functions to create and send Diaspora XML files
45 * @brief Return a list of relay servers
47 * This is an experimental Diaspora feature.
49 * @return array of relay servers
51 public static function relayList()
53 $serverdata = Config::get("system", "relay_server");
54 if ($serverdata == "") {
60 $servers = explode(",", $serverdata);
62 foreach ($servers as $server) {
63 $server = trim($server);
64 $addr = "relay@".str_replace("http://", "", normalise_link($server));
65 $batch = $server."/receive/public";
68 "SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
71 dbesc(normalise_link($server))
76 "INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
77 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
82 dbesc(normalise_link($server)),
84 dbesc(NETWORK_DIASPORA),
85 intval(CONTACT_IS_FOLLOWER),
86 dbesc(datetime_convert()),
87 dbesc(datetime_convert()),
88 dbesc(datetime_convert())
91 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
93 $relay[] = $relais[0];
96 $relay[] = $relais[0];
104 * @brief Return a list of participating contacts for a thread
106 * This is used for the participation feature.
107 * One of the parameters is a contact array.
108 * This is done to avoid duplicates.
110 * @param integer $thread The id of the thread
111 * @param array $contacts The previously fetched contacts
113 * @return array of relay servers
115 public static function participantsForThread($thread, $contacts)
117 $r = dba::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
118 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
119 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
120 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
121 WHERE `participation`.`iid` = ?", $thread);
123 while ($contact = dba::fetch($r)) {
124 if (!empty($contact['fnetwork'])) {
125 $contact['network'] = $contact['fnetwork'];
127 unset($contact['fnetwork']);
129 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
130 $contact['batch'] = $contact['fbatch'];
132 unset($contact['fbatch']);
135 foreach ($contacts as $entry) {
136 if ($entry['batch'] == $contact['batch']) {
142 $contacts[] = $contact;
151 * @brief repairs a signature that was double encoded
153 * The function is unused at the moment. It was copied from the old implementation.
155 * @param string $signature The signature
156 * @param string $handle The handle of the signature owner
157 * @param integer $level This value is only set inside this function to avoid endless loops
159 * @return string the repaired signature
161 private static function repairSignature($signature, $handle = "", $level = 1)
163 if ($signature == "") {
167 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
168 $signature = base64_decode($signature);
169 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
171 // Do a recursive call to be able to fix even multiple levels
173 $signature = self::repairSignature($signature, $handle, ++$level);
181 * @brief verify the envelope and return the verified data
183 * @param string $envelope The magic envelope
185 * @return string verified data
187 private static function verifyMagicEnvelope($envelope)
189 $basedom = Network::parseXmlString($envelope);
191 if (!is_object($basedom)) {
192 logger("Envelope is no XML file");
196 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
198 if (sizeof($children) == 0) {
199 logger("XML has no children");
205 $data = base64url_decode($children->data);
206 $type = $children->data->attributes()->type[0];
208 $encoding = $children->encoding;
210 $alg = $children->alg;
212 $sig = base64url_decode($children->sig);
213 $key_id = $children->sig->attributes()->key_id[0];
215 $handle = base64url_decode($key_id);
218 $b64url_data = base64url_encode($data);
219 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
221 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
223 $key = self::key($handle);
225 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
227 logger('Message did not verify. Discarding.');
235 * @brief encrypts data via AES
237 * @param string $key The AES key
238 * @param string $iv The IV (is used for CBC encoding)
239 * @param string $data The data that is to be encrypted
241 * @return string encrypted data
243 private static function aesEncrypt($key, $iv, $data)
245 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
249 * @brief decrypts data via AES
251 * @param string $key The AES key
252 * @param string $iv The IV (is used for CBC encoding)
253 * @param string $encrypted The encrypted data
255 * @return string decrypted data
257 private static function aesDecrypt($key, $iv, $encrypted)
259 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
263 * @brief: Decodes incoming Diaspora message in the new format
265 * @param array $importer Array of the importer user
266 * @param string $raw raw post message
269 * 'message' -> decoded Diaspora XML message
270 * 'author' -> author diaspora handle
271 * 'key' -> author public key (converted to pkcs#8)
273 public static function decodeRaw($importer, $raw)
275 $data = json_decode($raw);
277 // Is it a private post? Then decrypt the outer Salmon
278 if (is_object($data)) {
279 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
280 $ciphertext = base64_decode($data->encrypted_magic_envelope);
282 $outer_key_bundle = '';
283 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
284 $j_outer_key_bundle = json_decode($outer_key_bundle);
286 if (!is_object($j_outer_key_bundle)) {
287 logger('Outer Salmon did not verify. Discarding.');
288 Network::httpStatusExit(400);
291 $outer_iv = base64_decode($j_outer_key_bundle->iv);
292 $outer_key = base64_decode($j_outer_key_bundle->key);
294 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
299 $basedom = Network::parseXmlString($xml);
301 if (!is_object($basedom)) {
302 logger('Received data does not seem to be an XML. Discarding. '.$xml);
303 Network::httpStatusExit(400);
306 $base = $basedom->children(NAMESPACE_SALMON_ME);
308 // Not sure if this cleaning is needed
309 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
311 // Build the signed data
312 $type = $base->data[0]->attributes()->type[0];
313 $encoding = $base->encoding;
315 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
317 // This is the signature
318 $signature = base64url_decode($base->sig);
320 // Get the senders' public key
321 $key_id = $base->sig[0]->attributes()->key_id[0];
322 $author_addr = base64_decode($key_id);
323 $key = self::key($author_addr);
325 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
327 logger('Message did not verify. Discarding.');
328 Network::httpStatusExit(400);
331 return ['message' => (string)base64url_decode($base->data),
332 'author' => unxmlify($author_addr),
333 'key' => (string)$key];
337 * @brief: Decodes incoming Diaspora message in the deprecated format
339 * @param array $importer Array of the importer user
340 * @param string $xml urldecoded Diaspora salmon
343 * 'message' -> decoded Diaspora XML message
344 * 'author' -> author diaspora handle
345 * 'key' -> author public key (converted to pkcs#8)
347 public static function decode($importer, $xml)
350 $basedom = Network::parseXmlString($xml);
352 if (!is_object($basedom)) {
353 logger("XML is not parseable.");
356 $children = $basedom->children('https://joindiaspora.com/protocol');
358 if ($children->header) {
360 $author_link = str_replace('acct:', '', $children->header->author_id);
362 // This happens with posts from a relais
364 logger("This is no private post in the old format", LOGGER_DEBUG);
368 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
370 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
371 $ciphertext = base64_decode($encrypted_header->ciphertext);
373 $outer_key_bundle = '';
374 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
376 $j_outer_key_bundle = json_decode($outer_key_bundle);
378 $outer_iv = base64_decode($j_outer_key_bundle->iv);
379 $outer_key = base64_decode($j_outer_key_bundle->key);
381 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
383 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
384 $idom = Network::parseXmlString($decrypted);
386 $inner_iv = base64_decode($idom->iv);
387 $inner_aes_key = base64_decode($idom->aes_key);
389 $author_link = str_replace('acct:', '', $idom->author_id);
392 $dom = $basedom->children(NAMESPACE_SALMON_ME);
394 // figure out where in the DOM tree our data is hiding
396 if ($dom->provenance->data) {
397 $base = $dom->provenance;
398 } elseif ($dom->env->data) {
400 } elseif ($dom->data) {
405 logger('unable to locate salmon data in xml');
406 Network::httpStatusExit(400);
410 // Stash the signature away for now. We have to find their key or it won't be good for anything.
411 $signature = base64url_decode($base->sig);
415 // strip whitespace so our data element will return to one big base64 blob
416 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
419 // stash away some other stuff for later
421 $type = $base->data[0]->attributes()->type[0];
422 $keyhash = $base->sig[0]->attributes()->keyhash[0];
423 $encoding = $base->encoding;
427 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
431 $data = base64url_decode($data);
435 $inner_decrypted = $data;
437 // Decode the encrypted blob
438 $inner_encrypted = base64_decode($data);
439 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
443 logger('Could not retrieve author URI.');
444 Network::httpStatusExit(400);
446 // Once we have the author URI, go to the web and try to find their public key
447 // (first this will look it up locally if it is in the fcontact cache)
448 // This will also convert diaspora public key from pkcs#1 to pkcs#8
450 logger('Fetching key for '.$author_link);
451 $key = self::key($author_link);
454 logger('Could not retrieve author key.');
455 Network::httpStatusExit(400);
458 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
461 logger('Message did not verify. Discarding.');
462 Network::httpStatusExit(400);
465 logger('Message verified.');
467 return ['message' => (string)$inner_decrypted,
468 'author' => unxmlify($author_link),
469 'key' => (string)$key];
474 * @brief Dispatches public messages and find the fitting receivers
476 * @param array $msg The post that will be dispatched
478 * @return int The message id of the generated message, "true" or "false" if there was an error
480 public static function dispatchPublic($msg)
482 $enabled = intval(Config::get("system", "diaspora_enabled"));
484 logger("diaspora is disabled");
488 if (!($postdata = self::validPosting($msg))) {
489 logger("Invalid posting");
493 $fields = $postdata['fields'];
495 // Is it a an action (comment, like, ...) for our own post?
496 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
497 $guid = notags(unxmlify($fields->parent_guid));
498 $importer = self::importerForGuid($guid);
499 if (is_array($importer)) {
500 logger("delivering to origin: ".$importer["name"]);
501 $message_id = self::dispatch($importer, $msg, $fields);
506 // Process item retractions. This has to be done separated from the other stuff,
507 // since retractions for comments could come even from non followers.
508 if (!empty($fields) && in_array($fields->getName(), ['retraction'])) {
509 $target = notags(unxmlify($fields->target_type));
510 if (in_array($target, ["Comment", "Like", "Post", "Reshare", "StatusMessage"])) {
511 logger('processing retraction for '.$target, LOGGER_DEBUG);
512 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
513 $message_id = self::dispatch($importer, $msg, $fields);
518 // Now distribute it to the followers
520 "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
521 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
522 AND NOT `account_expired` AND NOT `account_removed`",
523 dbesc(NETWORK_DIASPORA),
524 dbesc($msg["author"])
527 if (DBM::is_result($r)) {
528 foreach ($r as $rr) {
529 logger("delivering to: ".$rr["username"]);
530 self::dispatch($rr, $msg, $fields);
532 } elseif (!Config::get('system', 'relay_subscribe', false)) {
533 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
535 // Use a dummy importer to import the data for the public copy
536 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
537 $message_id = self::dispatch($importer, $msg, $fields);
544 * @brief Dispatches the different message types to the different functions
546 * @param array $importer Array of the importer user
547 * @param array $msg The post that will be dispatched
548 * @param object $fields SimpleXML object that contains the message
550 * @return int The message id of the generated message, "true" or "false" if there was an error
552 public static function dispatch($importer, $msg, $fields = null)
554 // The sender is the handle of the contact that sent the message.
555 // This will often be different with relayed messages (for example "like" and "comment")
556 $sender = $msg["author"];
558 // This is only needed for private postings since this is already done for public ones before
559 if (is_null($fields)) {
560 if (!($postdata = self::validPosting($msg))) {
561 logger("Invalid posting");
564 $fields = $postdata['fields'];
567 $type = $fields->getName();
569 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
572 case "account_migration":
573 return self::receiveAccountMigration($importer, $fields);
575 case "account_deletion":
576 return self::receiveAccountDeletion($importer, $fields);
579 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
582 return self::receiveContactRequest($importer, $fields);
585 return self::receiveConversation($importer, $msg, $fields);
588 return self::receiveLike($importer, $sender, $fields);
591 return self::receiveMessage($importer, $fields);
593 case "participation":
594 return self::receiveParticipation($importer, $fields);
596 case "photo": // Not implemented
597 return self::receivePhoto($importer, $fields);
599 case "poll_participation": // Not implemented
600 return self::receivePollParticipation($importer, $fields);
603 return self::receiveProfile($importer, $fields);
606 return self::receiveReshare($importer, $fields, $msg["message"]);
609 return self::receiveRetraction($importer, $sender, $fields);
611 case "status_message":
612 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
615 logger("Unknown message type ".$type);
623 * @brief Checks if a posting is valid and fetches the data fields.
625 * This function does not only check the signature.
626 * It also does the conversion between the old and the new diaspora format.
628 * @param array $msg Array with the XML, the sender handle and the sender signature
630 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
632 private static function validPosting($msg)
634 $data = Network::parseXmlString($msg["message"]);
636 if (!is_object($data)) {
637 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
641 $first_child = $data->getName();
643 // Is this the new or the old version?
644 if ($data->getName() == "XML") {
646 foreach ($data->post->children() as $child) {
654 $type = $element->getName();
657 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
659 // All retractions are handled identically from now on.
660 // In the new version there will only be "retraction".
661 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
662 $type = "retraction";
664 if ($type == "request") {
668 $fields = new SimpleXMLElement("<".$type."/>");
672 foreach ($element->children() as $fieldname => $entry) {
674 // Translation for the old XML structure
675 if ($fieldname == "diaspora_handle") {
676 $fieldname = "author";
678 if ($fieldname == "participant_handles") {
679 $fieldname = "participants";
681 if (in_array($type, ["like", "participation"])) {
682 if ($fieldname == "target_type") {
683 $fieldname = "parent_type";
686 if ($fieldname == "sender_handle") {
687 $fieldname = "author";
689 if ($fieldname == "recipient_handle") {
690 $fieldname = "recipient";
692 if ($fieldname == "root_diaspora_id") {
693 $fieldname = "root_author";
695 if ($type == "status_message") {
696 if ($fieldname == "raw_message") {
700 if ($type == "retraction") {
701 if ($fieldname == "post_guid") {
702 $fieldname = "target_guid";
704 if ($fieldname == "type") {
705 $fieldname = "target_type";
710 if (($fieldname == "author_signature") && ($entry != "")) {
711 $author_signature = base64_decode($entry);
712 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
713 $parent_author_signature = base64_decode($entry);
714 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
715 if ($signed_data != "") {
719 $signed_data .= $entry;
721 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
722 || ($orig_type == "relayable_retraction")
724 XML::copy($entry, $fields, $fieldname);
728 // This is something that shouldn't happen at all.
729 if (in_array($type, ["status_message", "reshare", "profile"])) {
730 if ($msg["author"] != $fields->author) {
731 logger("Message handle is not the same as envelope sender. Quitting this message.");
736 // Only some message types have signatures. So we quit here for the other types.
737 if (!in_array($type, ["comment", "like"])) {
738 return ["fields" => $fields, "relayed" => false];
740 // No author_signature? This is a must, so we quit.
741 if (!isset($author_signature)) {
742 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
746 if (isset($parent_author_signature)) {
749 $key = self::key($msg["author"]);
751 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
752 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);
759 $key = self::key($fields->author);
761 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
762 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
765 return ["fields" => $fields, "relayed" => $relayed];
770 * @brief Fetches the public key for a given handle
772 * @param string $handle The handle
774 * @return string The public key
776 private static function key($handle)
778 $handle = strval($handle);
780 logger("Fetching diaspora key for: ".$handle);
782 $r = self::personByHandle($handle);
791 * @brief Fetches data for a given handle
793 * @param string $handle The handle
795 * @return array the queried data
797 public static function personByHandle($handle)
800 "SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
801 dbesc(NETWORK_DIASPORA),
806 logger("In cache " . print_r($r, true), LOGGER_DEBUG);
808 // update record occasionally so it doesn't get stale
809 $d = strtotime($person["updated"]." +00:00");
810 if ($d < strtotime("now - 14 days")) {
814 if ($person["guid"] == "") {
819 if (!$person || $update) {
820 logger("create or refresh", LOGGER_DEBUG);
821 $r = Probe::uri($handle, NETWORK_DIASPORA);
823 // Note that Friendica contacts will return a "Diaspora person"
824 // if Diaspora connectivity is enabled on their server
825 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
826 self::addFContact($r, $update);
834 * @brief Updates the fcontact table
836 * @param array $arr The fcontact data
837 * @param bool $update Update or insert?
839 * @return string The id of the fcontact entry
841 private static function addFContact($arr, $update = false)
845 "UPDATE `fcontact` SET
859 WHERE `url` = '%s' AND `network` = '%s'",
861 dbesc($arr["photo"]),
862 dbesc($arr["request"]),
864 dbesc(strtolower($arr["addr"])),
866 dbesc($arr["batch"]),
867 dbesc($arr["notify"]),
869 dbesc($arr["confirm"]),
870 dbesc($arr["alias"]),
871 dbesc($arr["pubkey"]),
872 dbesc(datetime_convert()),
874 dbesc($arr["network"])
878 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
879 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
880 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
883 dbesc($arr["photo"]),
884 dbesc($arr["request"]),
888 dbesc($arr["batch"]),
889 dbesc($arr["notify"]),
891 dbesc($arr["confirm"]),
892 dbesc($arr["network"]),
893 dbesc($arr["alias"]),
894 dbesc($arr["pubkey"]),
895 dbesc(datetime_convert())
903 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
905 * @param int $contact_id The id in the contact table
906 * @param int $gcontact_id The id in the gcontact table
908 * @return string the handle
910 public static function handleFromContact($contact_id, $gcontact_id = 0)
914 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
916 if ($gcontact_id != 0) {
918 "SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
922 if (DBM::is_result($r)) {
923 return strtolower($r[0]["addr"]);
928 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
932 if (DBM::is_result($r)) {
935 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
937 if ($contact['addr'] != "") {
938 $handle = $contact['addr'];
940 $baseurl_start = strpos($contact['url'], '://') + 3;
941 // allows installations in a subdirectory--not sure how Diaspora will handle
942 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
943 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
944 $handle = $contact['nick'].'@'.$baseurl;
948 return strtolower($handle);
952 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
955 * @param mixed $fcontact_guid Hexadecimal string guid
957 * @return string the contact url or null
959 public static function urlFromContactGuid($fcontact_guid)
961 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
964 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
965 dbesc(NETWORK_DIASPORA),
966 dbesc($fcontact_guid)
969 if (DBM::is_result($r)) {
977 * @brief Get a contact id for a given handle
979 * @todo Move to Friendica\Model\Contact
981 * @param int $uid The user id
982 * @param string $handle The handle in the format user@domain.tld
984 * @return int Contact id
986 private static function contactByHandle($uid, $handle)
988 // First do a direct search on the contact table
990 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
995 if (DBM::is_result($r)) {
999 * We haven't found it?
1000 * We use another function for it that will possibly create a contact entry.
1002 $cid = Contact::getIdForURL($handle, $uid);
1005 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1006 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1008 if (DBM::is_result($r)) {
1014 $handle_parts = explode("@", $handle);
1015 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1017 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1018 dbesc(NETWORK_DFRN),
1022 if (DBM::is_result($r)) {
1026 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1031 * @brief Check if posting is allowed for this contact
1033 * @param array $importer Array of the importer user
1034 * @param array $contact The contact that is checked
1035 * @param bool $is_comment Is the check for a comment?
1037 * @return bool is the contact allowed to post?
1039 private static function postAllow($importer, $contact, $is_comment = false)
1042 * Perhaps we were already sharing with this person. Now they're sharing with us.
1043 * That makes us friends.
1044 * Normally this should have handled by getting a request - but this could get lost
1046 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1047 // It is not removed by now. Possibly the code is needed?
1048 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1051 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1052 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1055 // $contact["rel"] = CONTACT_IS_FRIEND;
1056 // logger("defining user ".$contact["nick"]." as friend");
1059 // We don't seem to like that person
1060 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
1061 // Maybe blocked, don't accept.
1063 // We are following this person?
1064 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1065 // Yes, then it is fine.
1067 // Is it a post to a community?
1068 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1071 // Is the message a global user or a comment?
1072 } elseif (($importer["uid"] == 0) || $is_comment) {
1073 // Messages for the global users and comments are always accepted
1081 * @brief Fetches the contact id for a handle and checks if posting is allowed
1083 * @param array $importer Array of the importer user
1084 * @param string $handle The checked handle in the format user@domain.tld
1085 * @param bool $is_comment Is the check for a comment?
1087 * @return array The contact data
1089 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1091 $contact = self::contactByHandle($importer["uid"], $handle);
1093 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1094 // If a contact isn't found, we accept it anyway if it is a comment
1102 if (!self::postAllow($importer, $contact, $is_comment)) {
1103 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1110 * @brief Does the message already exists on the system?
1112 * @param int $uid The user id
1113 * @param string $guid The guid of the message
1115 * @return int|bool message id if the message already was stored into the system - or false.
1117 private static function messageExists($uid, $guid)
1120 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1125 if (DBM::is_result($r)) {
1126 logger("message ".$guid." already exists for user ".$uid);
1134 * @brief Checks for links to posts in a message
1136 * @param array $item The item array
1139 private static function fetchGuid($item)
1141 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1142 preg_replace_callback(
1144 function ($match) use ($item) {
1145 self::fetchGuidSub($match, $item);
1150 preg_replace_callback(
1151 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1152 function ($match) use ($item) {
1153 self::fetchGuidSub($match, $item);
1160 * @brief Checks for relative /people/* links in an item body to match local
1161 * contacts or prepends the remote host taken from the author link.
1163 * @param string $body The item body to replace links from
1164 * @param string $author_link The author link for missing local contact fallback
1166 * @return string the replaced string
1168 public static function replacePeopleGuid($body, $author_link)
1170 $return = preg_replace_callback(
1171 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1172 function ($match) use ($author_link) {
1174 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1175 // 1 => '0123456789abcdef'
1177 $handle = self::urlFromContactGuid($match[1]);
1180 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1182 // No local match, restoring absolute remote URL from author scheme and host
1183 $author_url = parse_url($author_link);
1184 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1196 * @brief sub function of "fetchGuid" which checks for links in messages
1198 * @param array $match array containing a link that has to be checked for a message link
1199 * @param array $item The item array
1202 private static function fetchGuidSub($match, $item)
1204 if (!self::storeByGuid($match[1], $item["author-link"])) {
1205 self::storeByGuid($match[1], $item["owner-link"]);
1210 * @brief Fetches an item with a given guid from a given server
1212 * @param string $guid the message guid
1213 * @param string $server The server address
1214 * @param int $uid The user id of the user
1216 * @return int the message id of the stored message or false
1218 private static function storeByGuid($guid, $server, $uid = 0)
1220 $serverparts = parse_url($server);
1221 $server = $serverparts["scheme"]."://".$serverparts["host"];
1223 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1225 $msg = self::message($guid, $server);
1231 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1233 // Now call the dispatcher
1234 return self::dispatchPublic($msg);
1238 * @brief Fetches a message from a server
1240 * @param string $guid message guid
1241 * @param string $server The url of the server
1242 * @param int $level Endless loop prevention
1245 * 'message' => The message XML
1246 * 'author' => The author handle
1247 * 'key' => The public key of the author
1249 private static function message($guid, $server, $level = 0)
1255 // This will work for new Diaspora servers and Friendica servers from 3.5
1256 $source_url = $server."/fetch/post/".urlencode($guid);
1258 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1260 $envelope = Network::fetchURL($source_url);
1262 logger("Envelope was fetched.", LOGGER_DEBUG);
1263 $x = self::verifyMagicEnvelope($envelope);
1265 logger("Envelope could not be verified.", LOGGER_DEBUG);
1267 logger("Envelope was verified.", LOGGER_DEBUG);
1273 // This will work for older Diaspora and Friendica servers
1275 $source_url = $server."/p/".urlencode($guid).".xml";
1276 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1278 $x = Network::fetchURL($source_url);
1284 $source_xml = Network::parseXmlString($x);
1286 if (!is_object($source_xml)) {
1290 if ($source_xml->post->reshare) {
1291 // Reshare of a reshare - old Diaspora version
1292 logger("Message is a reshare", LOGGER_DEBUG);
1293 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1294 } elseif ($source_xml->getName() == "reshare") {
1295 // Reshare of a reshare - new Diaspora version
1296 logger("Message is a new reshare", LOGGER_DEBUG);
1297 return self::message($source_xml->root_guid, $server, ++$level);
1302 // Fetch the author - for the old and the new Diaspora version
1303 if ($source_xml->post->status_message->diaspora_handle) {
1304 $author = (string)$source_xml->post->status_message->diaspora_handle;
1305 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1306 $author = (string)$source_xml->author;
1309 // If this isn't a "status_message" then quit
1311 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1315 $msg = ["message" => $x, "author" => $author];
1317 $msg["key"] = self::key($msg["author"]);
1323 * @brief Fetches the item record of a given guid
1325 * @param int $uid The user id
1326 * @param string $guid message guid
1327 * @param string $author The handle of the item
1328 * @param array $contact The contact of the item owner
1330 * @return array the item record
1332 private static function parentItem($uid, $guid, $author, $contact)
1335 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1336 `author-name`, `author-link`, `author-avatar`,
1337 `owner-name`, `owner-link`, `owner-avatar`
1338 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1344 $result = self::storeByGuid($guid, $contact["url"], $uid);
1347 $person = self::personByHandle($author);
1348 $result = self::storeByGuid($guid, $person["url"], $uid);
1352 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1355 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1356 `author-name`, `author-link`, `author-avatar`,
1357 `owner-name`, `owner-link`, `owner-avatar`
1358 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1366 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1369 logger("parent item found: parent: ".$guid." - user: ".$uid);
1375 * @brief returns contact details
1377 * @param array $contact The default contact if the person isn't found
1378 * @param array $person The record of the person
1379 * @param int $uid The user id
1382 * 'cid' => contact id
1383 * 'network' => network type
1385 private static function authorContactByUrl($contact, $person, $uid)
1388 "SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1389 dbesc(normalise_link($person["url"])),
1394 $network = $r[0]["network"];
1396 $cid = $contact["id"];
1397 $network = NETWORK_DIASPORA;
1400 return ["cid" => $cid, "network" => $network];
1404 * @brief Is the profile a hubzilla profile?
1406 * @param string $url The profile link
1408 * @return bool is it a hubzilla server?
1410 public static function isRedmatrix($url)
1412 return(strstr($url, "/channel/"));
1416 * @brief Generate a post link with a given handle and message guid
1418 * @param string $addr The user handle
1419 * @param string $guid message guid
1420 * @param string $parent_guid optional parent guid
1422 * @return string the post link
1424 private static function plink($addr, $guid, $parent_guid = '')
1426 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1429 if (!DBM::is_result($r)) {
1430 if ($parent_guid != '') {
1431 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1433 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1437 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1438 // So we try another way as well.
1439 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1440 if (DBM::is_result($s)) {
1441 $r[0]["network"] = $s[0]["network"];
1444 if ($r[0]["network"] == NETWORK_DFRN) {
1445 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1448 if (self::isRedmatrix($r[0]["url"])) {
1449 return $r[0]["url"]."/?f=&mid=".$guid;
1452 if ($parent_guid != '') {
1453 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1455 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1460 * @brief Receives account migration
1462 * @param array $importer Array of the importer user
1463 * @param object $data The message object
1465 * @return bool Success
1467 private static function receiveAccountMigration($importer, $data)
1469 $old_handle = notags(unxmlify($data->author));
1470 $new_handle = notags(unxmlify($data->profile->author));
1471 $signature = notags(unxmlify($data->signature));
1473 $contact = self::contactByHandle($importer["uid"], $old_handle);
1475 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1479 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1482 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1483 $key = self::key($old_handle);
1484 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1485 logger('No valid signature for migration.');
1489 // Update the profile
1490 self::receiveProfile($importer, $data->profile);
1492 // change the technical stuff in contact and gcontact
1493 $data = Probe::uri($new_handle);
1494 if ($data['network'] == NETWORK_PHANTOM) {
1495 logger('Account for '.$new_handle." couldn't be probed.");
1499 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1500 'name' => $data['name'], 'nick' => $data['nick'],
1501 'addr' => $data['addr'], 'batch' => $data['batch'],
1502 'notify' => $data['notify'], 'poll' => $data['poll'],
1503 'network' => $data['network']];
1505 dba::update('contact', $fields, ['addr' => $old_handle]);
1507 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1508 'name' => $data['name'], 'nick' => $data['nick'],
1509 'addr' => $data['addr'], 'connect' => $data['addr'],
1510 'notify' => $data['notify'], 'photo' => $data['photo'],
1511 'server_url' => $data['baseurl'], 'network' => $data['network']];
1513 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1515 logger('Contacts are updated.');
1518 /// @todo This is an extreme performance killer
1520 'owner-link' => [$contact["url"], $data["url"]],
1521 'author-link' => [$contact["url"], $data["url"]],
1523 foreach ($fields as $n => $f) {
1525 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1528 intval($importer["uid"])
1531 if (DBM::is_result($r)) {
1533 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1538 intval($importer["uid"])
1547 logger('Items are updated.');
1553 * @brief Processes an account deletion
1555 * @param array $importer Array of the importer user
1556 * @param object $data The message object
1558 * @return bool Success
1560 private static function receiveAccountDeletion($importer, $data)
1562 /// @todo Account deletion should remove the contact from the global contacts as well
1564 $author = notags(unxmlify($data->author));
1566 $contact = self::contactByHandle($importer["uid"], $author);
1568 logger("cannot find contact for author: ".$author);
1572 // We now remove the contact
1573 Contact::remove($contact["id"]);
1578 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1580 * @param string $author Author handle
1581 * @param string $guid Message guid
1582 * @param boolean $onlyfound Only return uri when found in the database
1584 * @return string The constructed uri or the one from our database
1586 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1588 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1589 if (DBM::is_result($r)) {
1590 return $r[0]["uri"];
1591 } elseif (!$onlyfound) {
1592 return $author.":".$guid;
1599 * @brief Fetch the guid from our database with a given uri
1601 * @param string $uri Message uri
1602 * @param string $uid Author handle
1604 * @return string The post guid
1606 private static function getGuidFromUri($uri, $uid)
1608 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1609 if (DBM::is_result($r)) {
1610 return $r[0]["guid"];
1617 * @brief Find the best importer for a comment, like, ...
1619 * @param string $guid The guid of the item
1621 * @return array|boolean the origin owner of that post - or false
1623 private static function importerForGuid($guid)
1625 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1627 if (DBM::is_result($item)) {
1628 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1629 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1630 if (DBM::is_result($contact)) {
1638 * @brief Processes an incoming comment
1640 * @param array $importer Array of the importer user
1641 * @param string $sender The sender of the message
1642 * @param object $data The message object
1643 * @param string $xml The original XML of the message
1645 * @return int The message id of the generated comment or "false" if there was an error
1647 private static function receiveComment($importer, $sender, $data, $xml)
1649 $author = notags(unxmlify($data->author));
1650 $guid = notags(unxmlify($data->guid));
1651 $parent_guid = notags(unxmlify($data->parent_guid));
1652 $text = unxmlify($data->text);
1654 if (isset($data->created_at)) {
1655 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1657 $created_at = datetime_convert();
1660 if (isset($data->thread_parent_guid)) {
1661 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1662 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1667 $contact = self::allowedContactByHandle($importer, $sender, true);
1672 $message_id = self::messageExists($importer["uid"], $guid);
1677 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1678 if (!$parent_item) {
1682 $person = self::personByHandle($author);
1683 if (!is_array($person)) {
1684 logger("unable to find author details");
1688 // Fetch the contact id - if we know this contact
1689 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1693 $datarray["uid"] = $importer["uid"];
1694 $datarray["contact-id"] = $author_contact["cid"];
1695 $datarray["network"] = $author_contact["network"];
1697 $datarray["author-name"] = $person["name"];
1698 $datarray["author-link"] = $person["url"];
1699 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1701 $datarray["owner-name"] = $contact["name"];
1702 $datarray["owner-link"] = $contact["url"];
1703 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1705 $datarray["guid"] = $guid;
1706 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1708 $datarray["type"] = "remote-comment";
1709 $datarray["verb"] = ACTIVITY_POST;
1710 $datarray["gravity"] = GRAVITY_COMMENT;
1712 if ($thr_uri != "") {
1713 $datarray["parent-uri"] = $thr_uri;
1715 $datarray["parent-uri"] = $parent_item["uri"];
1718 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1720 $datarray["protocol"] = PROTOCOL_DIASPORA;
1721 $datarray["source"] = $xml;
1723 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1725 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1727 $body = diaspora2bb($text);
1729 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1731 self::fetchGuid($datarray);
1733 $message_id = item_store($datarray);
1735 if ($message_id <= 0) {
1740 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1743 // If we are the origin of the parent we store the original data and notify our followers
1744 if ($message_id && $parent_item["origin"]) {
1745 // Formerly we stored the signed text, the signature and the author in different fields.
1746 // We now store the raw data so that we are more flexible.
1747 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1750 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1757 * @brief processes and stores private messages
1759 * @param array $importer Array of the importer user
1760 * @param array $contact The contact of the message
1761 * @param object $data The message object
1762 * @param array $msg Array of the processed message, author handle and key
1763 * @param object $mesg The private message
1764 * @param array $conversation The conversation record to which this message belongs
1766 * @return bool "true" if it was successful
1768 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1770 $author = notags(unxmlify($data->author));
1771 $guid = notags(unxmlify($data->guid));
1772 $subject = notags(unxmlify($data->subject));
1774 // "diaspora_handle" is the element name from the old version
1775 // "author" is the element name from the new version
1776 if ($mesg->author) {
1777 $msg_author = notags(unxmlify($mesg->author));
1778 } elseif ($mesg->diaspora_handle) {
1779 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1784 $msg_guid = notags(unxmlify($mesg->guid));
1785 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1786 $msg_text = unxmlify($mesg->text);
1787 $msg_created_at = datetime_convert("UTC", "UTC", notags(unxmlify($mesg->created_at)));
1789 if ($msg_conversation_guid != $guid) {
1790 logger("message conversation guid does not belong to the current conversation.");
1794 $body = diaspora2bb($msg_text);
1795 $message_uri = $msg_author.":".$msg_guid;
1797 $person = self::personByHandle($msg_author);
1802 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1804 intval($importer["uid"])
1806 if (DBM::is_result($r)) {
1807 logger("duplicate message already delivered.", LOGGER_DEBUG);
1812 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1813 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1814 intval($importer["uid"]),
1816 intval($conversation["id"]),
1817 dbesc($person["name"]),
1818 dbesc($person["photo"]),
1819 dbesc($person["url"]),
1820 intval($contact["id"]),
1825 dbesc($message_uri),
1826 dbesc($author.":".$guid),
1827 dbesc($msg_created_at)
1832 dba::update('conv', ['updated' => datetime_convert()], ['id' => $conversation["id"]]);
1836 "type" => NOTIFY_MAIL,
1837 "notify_flags" => $importer["notify-flags"],
1838 "language" => $importer["language"],
1839 "to_name" => $importer["username"],
1840 "to_email" => $importer["email"],
1841 "uid" =>$importer["uid"],
1842 "item" => ["subject" => $subject, "body" => $body],
1843 "source_name" => $person["name"],
1844 "source_link" => $person["url"],
1845 "source_photo" => $person["thumb"],
1846 "verb" => ACTIVITY_POST,
1853 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1855 * @param array $importer Array of the importer user
1856 * @param array $msg Array of the processed message, author handle and key
1857 * @param object $data The message object
1859 * @return bool Success
1861 private static function receiveConversation($importer, $msg, $data)
1863 $author = notags(unxmlify($data->author));
1864 $guid = notags(unxmlify($data->guid));
1865 $subject = notags(unxmlify($data->subject));
1866 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
1867 $participants = notags(unxmlify($data->participants));
1869 $messages = $data->message;
1871 if (!count($messages)) {
1872 logger("empty conversation");
1876 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1881 $conversation = null;
1884 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1885 intval($importer["uid"]),
1889 $conversation = $c[0];
1892 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1893 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1894 intval($importer["uid"]),
1898 dbesc(datetime_convert()),
1900 dbesc($participants)
1904 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1905 intval($importer["uid"]),
1911 $conversation = $c[0];
1914 if (!$conversation) {
1915 logger("unable to create conversation.");
1919 foreach ($messages as $mesg) {
1920 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1927 * @brief Creates the body for a "like" message
1929 * @param array $contact The contact that send us the "like"
1930 * @param array $parent_item The item array of the parent item
1931 * @param string $guid message guid
1933 * @return string the body
1935 private static function constructLikeBody($contact, $parent_item, $guid)
1937 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1939 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1940 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1941 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
1943 return sprintf($bodyverb, $ulink, $alink, $plink);
1947 * @brief Creates a XML object for a "like"
1949 * @param array $importer Array of the importer user
1950 * @param array $parent_item The item array of the parent item
1952 * @return string The XML
1954 private static function constructLikeObject($importer, $parent_item)
1956 $objtype = ACTIVITY_OBJ_NOTE;
1957 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1958 $parent_body = $parent_item["body"];
1960 $xmldata = ["object" => ["type" => $objtype,
1962 "id" => $parent_item["uri"],
1965 "content" => $parent_body]];
1967 return XML::fromArray($xmldata, $xml, true);
1971 * @brief Processes "like" messages
1973 * @param array $importer Array of the importer user
1974 * @param string $sender The sender of the message
1975 * @param object $data The message object
1977 * @return int The message id of the generated like or "false" if there was an error
1979 private static function receiveLike($importer, $sender, $data)
1981 $author = notags(unxmlify($data->author));
1982 $guid = notags(unxmlify($data->guid));
1983 $parent_guid = notags(unxmlify($data->parent_guid));
1984 $parent_type = notags(unxmlify($data->parent_type));
1985 $positive = notags(unxmlify($data->positive));
1987 // likes on comments aren't supported by Diaspora - only on posts
1988 // But maybe this will be supported in the future, so we will accept it.
1989 if (!in_array($parent_type, ["Post", "Comment"])) {
1993 $contact = self::allowedContactByHandle($importer, $sender, true);
1998 $message_id = self::messageExists($importer["uid"], $guid);
2003 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2004 if (!$parent_item) {
2008 $person = self::personByHandle($author);
2009 if (!is_array($person)) {
2010 logger("unable to find author details");
2014 // Fetch the contact id - if we know this contact
2015 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2017 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2018 // We would accept this anyhow.
2019 if ($positive == "true") {
2020 $verb = ACTIVITY_LIKE;
2022 $verb = ACTIVITY_DISLIKE;
2027 $datarray["protocol"] = PROTOCOL_DIASPORA;
2029 $datarray["uid"] = $importer["uid"];
2030 $datarray["contact-id"] = $author_contact["cid"];
2031 $datarray["network"] = $author_contact["network"];
2033 $datarray["author-name"] = $person["name"];
2034 $datarray["author-link"] = $person["url"];
2035 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2037 $datarray["owner-name"] = $contact["name"];
2038 $datarray["owner-link"] = $contact["url"];
2039 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2041 $datarray["guid"] = $guid;
2042 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2044 $datarray["type"] = "activity";
2045 $datarray["verb"] = $verb;
2046 $datarray["gravity"] = GRAVITY_LIKE;
2047 $datarray["parent-uri"] = $parent_item["uri"];
2049 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2050 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2052 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2054 $message_id = item_store($datarray);
2056 if ($message_id <= 0) {
2061 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2064 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2065 if ($parent_item["id"] != $parent_item["parent"]) {
2066 $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2067 $origin = $toplevel["origin"];
2069 $origin = $parent_item["origin"];
2072 // If we are the origin of the parent we store the original data and notify our followers
2073 if ($message_id && $origin) {
2074 // Formerly we stored the signed text, the signature and the author in different fields.
2075 // We now store the raw data so that we are more flexible.
2076 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2079 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2086 * @brief Processes private messages
2088 * @param array $importer Array of the importer user
2089 * @param object $data The message object
2091 * @return bool Success?
2093 private static function receiveMessage($importer, $data)
2095 $author = notags(unxmlify($data->author));
2096 $guid = notags(unxmlify($data->guid));
2097 $conversation_guid = notags(unxmlify($data->conversation_guid));
2098 $text = unxmlify($data->text);
2099 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2101 $contact = self::allowedContactByHandle($importer, $author, true);
2106 $conversation = null;
2109 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2110 intval($importer["uid"]),
2111 dbesc($conversation_guid)
2114 $conversation = $c[0];
2116 logger("conversation not available.");
2120 $message_uri = $author.":".$guid;
2122 $person = self::personByHandle($author);
2124 logger("unable to find author details");
2128 $body = diaspora2bb($text);
2130 $body = self::replacePeopleGuid($body, $person["url"]);
2135 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2137 intval($importer["uid"])
2139 if (DBM::is_result($r)) {
2140 logger("duplicate message already delivered.", LOGGER_DEBUG);
2145 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2146 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2147 intval($importer["uid"]),
2149 intval($conversation["id"]),
2150 dbesc($person["name"]),
2151 dbesc($person["photo"]),
2152 dbesc($person["url"]),
2153 intval($contact["id"]),
2154 dbesc($conversation["subject"]),
2158 dbesc($message_uri),
2159 dbesc($author.":".$conversation["guid"]),
2165 dba::update('conv', ['updated' => datetime_convert()], ['id' => $conversation["id"]]);
2170 * @brief Processes participations - unsupported by now
2172 * @param array $importer Array of the importer user
2173 * @param object $data The message object
2175 * @return bool always true
2177 private static function receiveParticipation($importer, $data)
2179 $author = strtolower(notags(unxmlify($data->author)));
2180 $parent_guid = notags(unxmlify($data->parent_guid));
2182 $contact_id = Contact::getIdForURL($author);
2184 logger('Contact not found: '.$author);
2188 $person = self::personByHandle($author);
2189 if (!is_array($person)) {
2190 logger("Person not found: ".$author);
2194 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2195 if (!DBM::is_result($item)) {
2196 logger('Item not found, no origin or private: '.$parent_guid);
2200 $author_parts = explode('@', $author);
2201 if (isset($author_parts[1])) {
2202 $server = $author_parts[1];
2204 // Should never happen
2208 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2209 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2211 // Send all existing comments and likes to the requesting server
2212 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2214 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2215 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2216 while ($comment = dba::fetch($comments)) {
2217 if ($comment['verb'] == ACTIVITY_POST) {
2218 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2220 $cmd = $comment['self'] ? 'like' : 'comment-import';
2222 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2223 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2225 dba::close($comments);
2231 * @brief Processes photos - unneeded
2233 * @param array $importer Array of the importer user
2234 * @param object $data The message object
2236 * @return bool always true
2238 private static function receivePhoto($importer, $data)
2240 // There doesn't seem to be a reason for this function,
2241 // since the photo data is transmitted in the status message as well
2246 * @brief Processes poll participations - unssupported
2248 * @param array $importer Array of the importer user
2249 * @param object $data The message object
2251 * @return bool always true
2253 private static function receivePollParticipation($importer, $data)
2255 // We don't support polls by now
2260 * @brief Processes incoming profile updates
2262 * @param array $importer Array of the importer user
2263 * @param object $data The message object
2265 * @return bool Success
2267 private static function receiveProfile($importer, $data)
2269 $author = strtolower(notags(unxmlify($data->author)));
2271 $contact = self::contactByHandle($importer["uid"], $author);
2276 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2277 $image_url = unxmlify($data->image_url);
2278 $birthday = unxmlify($data->birthday);
2279 $gender = unxmlify($data->gender);
2280 $about = diaspora2bb(unxmlify($data->bio));
2281 $location = diaspora2bb(unxmlify($data->location));
2282 $searchable = (unxmlify($data->searchable) == "true");
2283 $nsfw = (unxmlify($data->nsfw) == "true");
2284 $tags = unxmlify($data->tag_string);
2286 $tags = explode("#", $tags);
2289 foreach ($tags as $tag) {
2290 $tag = trim(strtolower($tag));
2296 $keywords = implode(", ", $keywords);
2298 $handle_parts = explode("@", $author);
2299 $nick = $handle_parts[0];
2302 $name = $handle_parts[0];
2305 if (preg_match("|^https?://|", $image_url) === 0) {
2306 $image_url = "http://".$handle_parts[1].$image_url;
2309 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2311 // Generic birthday. We don't know the timezone. The year is irrelevant.
2313 $birthday = str_replace("1000", "1901", $birthday);
2315 if ($birthday != "") {
2316 $birthday = datetime_convert("UTC", "UTC", $birthday, "Y-m-d");
2319 // this is to prevent multiple birthday notifications in a single year
2320 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2322 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2323 $birthday = $contact["bd"];
2327 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2328 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2332 dbesc(datetime_convert()),
2338 intval($contact["id"]),
2339 intval($importer["uid"])
2342 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2343 "photo" => $image_url, "name" => $name, "location" => $location,
2344 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2345 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2346 "hide" => !$searchable, "nsfw" => $nsfw];
2348 $gcid = GContact::update($gcontact);
2350 GContact::link($gcid, $importer["uid"], $contact["id"]);
2352 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2358 * @brief Processes incoming friend requests
2360 * @param array $importer Array of the importer user
2361 * @param array $contact The contact that send the request
2364 private static function receiveRequestMakeFriend($importer, $contact)
2368 if ($contact["rel"] == CONTACT_IS_SHARING) {
2371 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2372 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2375 // send notification
2378 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2379 intval($importer["uid"])
2382 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2384 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2385 intval($importer["uid"])
2388 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2390 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2392 $arr["protocol"] = PROTOCOL_DIASPORA;
2393 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2394 $arr["uid"] = $importer["uid"];
2395 $arr["contact-id"] = $self[0]["id"];
2397 $arr["type"] = 'wall';
2398 $arr["gravity"] = 0;
2400 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2401 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2402 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2403 $arr["verb"] = ACTIVITY_FRIEND;
2404 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2406 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2407 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2408 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2409 $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
2411 $arr["object"] = self::constructNewFriendObject($contact);
2413 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2415 $arr["allow_cid"] = $user["allow_cid"];
2416 $arr["allow_gid"] = $user["allow_gid"];
2417 $arr["deny_cid"] = $user["deny_cid"];
2418 $arr["deny_gid"] = $user["deny_gid"];
2420 $i = item_store($arr);
2422 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2429 * @brief Creates a XML object for a "new friend" message
2431 * @param array $contact Array of the contact
2433 * @return string The XML
2435 private static function constructNewFriendObject($contact)
2437 $objtype = ACTIVITY_OBJ_PERSON;
2438 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2439 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2441 $xmldata = ["object" => ["type" => $objtype,
2442 "title" => $contact["name"],
2443 "id" => $contact["url"]."/".$contact["name"],
2446 return XML::fromArray($xmldata, $xml, true);
2450 * @brief Processes incoming sharing notification
2452 * @param array $importer Array of the importer user
2453 * @param object $data The message object
2455 * @return bool Success
2457 private static function receiveContactRequest($importer, $data)
2459 $author = unxmlify($data->author);
2460 $recipient = unxmlify($data->recipient);
2462 if (!$author || !$recipient) {
2466 // the current protocol version doesn't know these fields
2467 // That means that we will assume their existance
2468 if (isset($data->following)) {
2469 $following = (unxmlify($data->following) == "true");
2474 if (isset($data->sharing)) {
2475 $sharing = (unxmlify($data->sharing) == "true");
2480 $contact = self::contactByHandle($importer["uid"], $author);
2482 // perhaps we were already sharing with this person. Now they're sharing with us.
2483 // That makes us friends.
2486 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2487 self::receiveRequestMakeFriend($importer, $contact);
2489 // refetch the contact array
2490 $contact = self::contactByHandle($importer["uid"], $author);
2492 // If we are now friends, we are sending a share message.
2493 // Normally we needn't to do so, but the first message could have been vanished.
2494 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2495 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2497 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2498 $ret = self::sendShare($u[0], $contact);
2503 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2504 lose_follower($importer, $contact);
2509 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2510 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2512 } elseif (!$following && !$sharing) {
2513 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2515 } elseif (!$following && $sharing) {
2516 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2517 } elseif ($following && $sharing) {
2518 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2519 } elseif ($following && !$sharing) {
2520 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2523 $ret = self::personByHandle($author);
2525 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2526 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2530 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2533 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2534 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2535 intval($importer["uid"]),
2536 dbesc($ret["network"]),
2537 dbesc($ret["addr"]),
2540 dbesc(normalise_link($ret["url"])),
2542 dbesc($ret["name"]),
2543 dbesc($ret["nick"]),
2544 dbesc($ret["photo"]),
2545 dbesc($ret["pubkey"]),
2546 dbesc($ret["notify"]),
2547 dbesc($ret["poll"]),
2552 // find the contact record we just created
2554 $contact_record = self::contactByHandle($importer["uid"], $author);
2556 if (!$contact_record) {
2557 logger("unable to locate newly created contact record.");
2561 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2563 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2565 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2567 if ($importer["page-flags"] == PAGE_NORMAL) {
2568 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2570 $hash = random_string().(string)time(); // Generate a confirm_key
2573 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2574 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2575 intval($importer["uid"]),
2576 intval($contact_record["id"]),
2579 dbesc(L10n::t("Sharing notification from Diaspora network")),
2581 dbesc(datetime_convert())
2584 // automatic friend approval
2586 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2588 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2590 // technically they are sharing with us (CONTACT_IS_SHARING),
2591 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2592 // we are going to change the relationship and make them a follower.
2594 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2595 $new_relation = CONTACT_IS_FRIEND;
2596 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2597 $new_relation = CONTACT_IS_SHARING;
2599 $new_relation = CONTACT_IS_FOLLOWER;
2603 "UPDATE `contact` SET `rel` = %d,
2611 intval($new_relation),
2612 dbesc(datetime_convert()),
2613 dbesc(datetime_convert()),
2614 intval($contact_record["id"])
2617 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2619 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2620 $ret = self::sendShare($u[0], $contact_record);
2622 // Send the profile data, maybe it weren't transmitted before
2623 self::sendProfile($importer["uid"], [$contact_record]);
2631 * @brief Fetches a message with a given guid
2633 * @param string $guid message guid
2634 * @param string $orig_author handle of the original post
2635 * @param string $author handle of the sharer
2637 * @return array The fetched item
2639 private static function originalItem($guid, $orig_author, $author)
2641 // Do we already have this item?
2643 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2644 `author-name`, `author-link`, `author-avatar`
2645 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2649 if (DBM::is_result($r)) {
2650 logger("reshared message ".$guid." already exists on system.");
2652 // Maybe it is already a reshared item?
2653 // Then refetch the content, if it is a reshare from a reshare.
2654 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2655 if (self::isReshare($r[0]["body"], true)) {
2657 } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2658 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2660 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2662 // Add OEmbed and other information to the body
2663 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2671 if (!DBM::is_result($r)) {
2672 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2673 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2674 $item_id = self::storeByGuid($guid, $server);
2677 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2678 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2679 $item_id = self::storeByGuid($guid, $server);
2684 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2685 `author-name`, `author-link`, `author-avatar`
2686 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2690 if (DBM::is_result($r)) {
2691 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2692 if (self::isReshare($r[0]["body"], false)) {
2693 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2694 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2705 * @brief Processes a reshare message
2707 * @param array $importer Array of the importer user
2708 * @param object $data The message object
2709 * @param string $xml The original XML of the message
2711 * @return int the message id
2713 private static function receiveReshare($importer, $data, $xml)
2715 $author = notags(unxmlify($data->author));
2716 $guid = notags(unxmlify($data->guid));
2717 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2718 $root_author = notags(unxmlify($data->root_author));
2719 $root_guid = notags(unxmlify($data->root_guid));
2720 /// @todo handle unprocessed property "provider_display_name"
2721 $public = notags(unxmlify($data->public));
2723 $contact = self::allowedContactByHandle($importer, $author, false);
2728 $message_id = self::messageExists($importer["uid"], $guid);
2733 $original_item = self::originalItem($root_guid, $root_author, $author);
2734 if (!$original_item) {
2738 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2742 $datarray["uid"] = $importer["uid"];
2743 $datarray["contact-id"] = $contact["id"];
2744 $datarray["network"] = NETWORK_DIASPORA;
2746 $datarray["author-name"] = $contact["name"];
2747 $datarray["author-link"] = $contact["url"];
2748 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2750 $datarray["owner-name"] = $datarray["author-name"];
2751 $datarray["owner-link"] = $datarray["author-link"];
2752 $datarray["owner-avatar"] = $datarray["author-avatar"];
2754 $datarray["guid"] = $guid;
2755 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2757 $datarray["verb"] = ACTIVITY_POST;
2758 $datarray["gravity"] = GRAVITY_PARENT;
2760 $datarray["protocol"] = PROTOCOL_DIASPORA;
2761 $datarray["source"] = $xml;
2763 $prefix = share_header(
2764 $original_item["author-name"],
2765 $original_item["author-link"],
2766 $original_item["author-avatar"],
2767 $original_item["guid"],
2768 $original_item["created"],
2771 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2773 $datarray["tag"] = $original_item["tag"];
2774 $datarray["app"] = $original_item["app"];
2776 $datarray["plink"] = self::plink($author, $guid);
2777 $datarray["private"] = (($public == "false") ? 1 : 0);
2778 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2780 $datarray["object-type"] = $original_item["object-type"];
2782 self::fetchGuid($datarray);
2783 $message_id = item_store($datarray);
2785 self::sendParticipation($contact, $datarray);
2788 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2796 * @brief Processes retractions
2798 * @param array $importer Array of the importer user
2799 * @param array $contact The contact of the item owner
2800 * @param object $data The message object
2802 * @return bool success
2804 private static function itemRetraction($importer, $contact, $data)
2806 $author = notags(unxmlify($data->author));
2807 $target_guid = notags(unxmlify($data->target_guid));
2808 $target_type = notags(unxmlify($data->target_type));
2810 $person = self::personByHandle($author);
2811 if (!is_array($person)) {
2812 logger("unable to find author detail for ".$author);
2816 if (empty($contact["url"])) {
2817 $contact["url"] = $person["url"];
2820 // Fetch items that are about to be deleted
2821 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2823 // When we receive a public retraction, we delete every item that we find.
2824 if ($importer['uid'] == 0) {
2825 $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2827 $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2829 $r = dba::select('item', $fields, $condition);
2830 if (!DBM::is_result($r)) {
2831 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2835 while ($item = dba::fetch($r)) {
2836 // Fetch the parent item
2837 $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2839 // Only delete it if the parent author really fits
2840 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2841 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2845 // Currently we don't have a central deletion function that we could use in this case.
2846 // The function "item_drop" doesn't work for that case
2853 'edited' => datetime_convert(),
2854 'changed' => datetime_convert()],
2855 ['id' => $item["id"]]
2858 // Delete the thread - if it is a starting post and not a comment
2859 if ($target_type != 'Comment') {
2860 delete_thread($item["id"], $item["parent-uri"]);
2863 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2865 // Now check if the retraction needs to be relayed by us
2866 if ($parent["origin"]) {
2868 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2876 * @brief Receives retraction messages
2878 * @param array $importer Array of the importer user
2879 * @param string $sender The sender of the message
2880 * @param object $data The message object
2882 * @return bool Success
2884 private static function receiveRetraction($importer, $sender, $data)
2886 $target_type = notags(unxmlify($data->target_type));
2888 $contact = self::contactByHandle($importer["uid"], $sender);
2889 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2890 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2894 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2896 switch ($target_type) {
2901 case "StatusMessage":
2902 return self::itemRetraction($importer, $contact, $data);
2906 /// @todo What should we do with an "unshare"?
2907 // Removing the contact isn't correct since we still can read the public items
2908 Contact::remove($contact["id"]);
2912 logger("Unknown target type ".$target_type);
2919 * @brief Receives status messages
2921 * @param array $importer Array of the importer user
2922 * @param object $data The message object
2923 * @param string $xml The original XML of the message
2925 * @return int The message id of the newly created item
2927 private static function receiveStatusMessage($importer, $data, $xml)
2929 $author = notags(unxmlify($data->author));
2930 $guid = notags(unxmlify($data->guid));
2931 $created_at = datetime_convert("UTC", "UTC", notags(unxmlify($data->created_at)));
2932 $public = notags(unxmlify($data->public));
2933 $text = unxmlify($data->text);
2934 $provider_display_name = notags(unxmlify($data->provider_display_name));
2936 $contact = self::allowedContactByHandle($importer, $author, false);
2941 $message_id = self::messageExists($importer["uid"], $guid);
2947 if ($data->location) {
2948 foreach ($data->location->children() as $fieldname => $data) {
2949 $address[$fieldname] = notags(unxmlify($data));
2953 $body = diaspora2bb($text);
2957 // Attach embedded pictures to the body
2959 foreach ($data->photo as $photo) {
2960 $body = "[img]".unxmlify($photo->remote_photo_path).
2961 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2964 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2966 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2968 // Add OEmbed and other information to the body
2969 if (!self::isRedmatrix($contact["url"])) {
2970 $body = add_page_info_to_body($body, false, true);
2974 /// @todo enable support for polls
2975 //if ($data->poll) {
2976 // foreach ($data->poll AS $poll)
2981 /// @todo enable support for events
2983 $datarray["uid"] = $importer["uid"];
2984 $datarray["contact-id"] = $contact["id"];
2985 $datarray["network"] = NETWORK_DIASPORA;
2987 $datarray["author-name"] = $contact["name"];
2988 $datarray["author-link"] = $contact["url"];
2989 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2991 $datarray["owner-name"] = $datarray["author-name"];
2992 $datarray["owner-link"] = $datarray["author-link"];
2993 $datarray["owner-avatar"] = $datarray["author-avatar"];
2995 $datarray["guid"] = $guid;
2996 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2998 $datarray["verb"] = ACTIVITY_POST;
2999 $datarray["gravity"] = GRAVITY_PARENT;
3001 $datarray["protocol"] = PROTOCOL_DIASPORA;
3002 $datarray["source"] = $xml;
3004 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3006 if ($provider_display_name != "") {
3007 $datarray["app"] = $provider_display_name;
3010 $datarray["plink"] = self::plink($author, $guid);
3011 $datarray["private"] = (($public == "false") ? 1 : 0);
3012 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3014 if (isset($address["address"])) {
3015 $datarray["location"] = $address["address"];
3018 if (isset($address["lat"]) && isset($address["lng"])) {
3019 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3022 self::fetchGuid($datarray);
3023 $message_id = item_store($datarray);
3025 self::sendParticipation($contact, $datarray);
3028 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3035 /* ************************************************************************************** *
3036 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3037 * ************************************************************************************** */
3040 * @brief returnes the handle of a contact
3042 * @param array $contact contact array
3044 * @return string the handle in the format user@domain.tld
3046 private static function myHandle($contact)
3048 if ($contact["addr"] != "") {
3049 return $contact["addr"];
3052 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3053 // So - just in case - we build the the address here.
3054 if ($contact["nickname"] != "") {
3055 $nick = $contact["nickname"];
3057 $nick = $contact["nick"];
3060 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3065 * @brief Creates the data for a private message in the new format
3067 * @param string $msg The message that is to be transmitted
3068 * @param array $user The record of the sender
3069 * @param array $contact Target of the communication
3070 * @param string $prvkey The private key of the sender
3071 * @param string $pubkey The public key of the receiver
3073 * @return string The encrypted data
3075 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3077 logger("Message: ".$msg, LOGGER_DATA);
3079 // without a public key nothing will work
3081 logger("pubkey missing: contact id: ".$contact["id"]);
3085 $aes_key = openssl_random_pseudo_bytes(32);
3086 $b_aes_key = base64_encode($aes_key);
3087 $iv = openssl_random_pseudo_bytes(16);
3088 $b_iv = base64_encode($iv);
3090 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3092 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3094 $encrypted_key_bundle = "";
3095 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3097 $json_object = json_encode(
3098 ["aes_key" => base64_encode($encrypted_key_bundle),
3099 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3102 return $json_object;
3106 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3108 * @param string $msg The message that is to be transmitted
3109 * @param array $user The record of the sender
3111 * @return string The envelope
3113 public static function buildMagicEnvelope($msg, $user)
3115 $b64url_data = base64url_encode($msg);
3116 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3118 $key_id = base64url_encode(self::myHandle($user));
3119 $type = "application/xml";
3120 $encoding = "base64url";
3121 $alg = "RSA-SHA256";
3122 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3124 // Fallback if the private key wasn't transmitted in the expected field
3125 if ($user['uprvkey'] == "") {
3126 $user['uprvkey'] = $user['prvkey'];
3129 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3130 $sig = base64url_encode($signature);
3132 $xmldata = ["me:env" => ["me:data" => $data,
3133 "@attributes" => ["type" => $type],
3134 "me:encoding" => $encoding,
3137 "@attributes2" => ["key_id" => $key_id]]];
3139 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3141 return XML::fromArray($xmldata, $xml, false, $namespaces);
3145 * @brief Create the envelope for a message
3147 * @param string $msg The message that is to be transmitted
3148 * @param array $user The record of the sender
3149 * @param array $contact Target of the communication
3150 * @param string $prvkey The private key of the sender
3151 * @param string $pubkey The public key of the receiver
3152 * @param bool $public Is the message public?
3154 * @return string The message that will be transmitted to other servers
3156 private static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3158 // The message is put into an envelope with the sender's signature
3159 $envelope = self::buildMagicEnvelope($msg, $user);
3161 // Private messages are put into a second envelope, encrypted with the receivers public key
3163 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3170 * @brief Creates a signature for a message
3172 * @param array $owner the array of the owner of the message
3173 * @param array $message The message that is to be signed
3175 * @return string The signature
3177 private static function signature($owner, $message)
3180 unset($sigmsg["author_signature"]);
3181 unset($sigmsg["parent_author_signature"]);
3183 $signed_text = implode(";", $sigmsg);
3185 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3189 * @brief Transmit a message to a target server
3191 * @param array $owner the array of the item owner
3192 * @param array $contact Target of the communication
3193 * @param string $envelope The message that is to be transmitted
3194 * @param bool $public_batch Is it a public post?
3195 * @param bool $queue_run Is the transmission called from the queue?
3196 * @param string $guid message guid
3198 * @return int Result of the transmission
3200 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "")
3204 $enabled = intval(Config::get("system", "diaspora_enabled"));
3209 $logid = random_string(4);
3210 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3212 // Fetch the fcontact entry when there is missing data
3213 // Will possibly happen when data is transmitted to a DFRN contact
3214 if (empty($dest_url) && !empty($contact['addr'])) {
3215 $fcontact = self::personByHandle($contact['addr']);
3216 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3220 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3224 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3226 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3229 if (!intval(Config::get("system", "diaspora_test"))) {
3230 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3232 Network::postURL($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3233 $return_code = $a->get_curl_code();
3235 logger("test_mode");
3240 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3242 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3243 logger("queue message");
3246 "SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
3247 intval($contact["id"]),
3248 dbesc(NETWORK_DIASPORA),
3250 intval($public_batch)
3253 logger("add_to_queue ignored - identical item already in queue");
3255 // queue message for redelivery
3256 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch);
3258 // The message could not be delivered. We mark the contact as "dead"
3259 Contact::markForArchival($contact);
3261 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3262 // We successfully delivered a message, the contact is alive
3263 Contact::unmarkForArchival($contact);
3266 return(($return_code) ? $return_code : (-1));
3271 * @brief Build the post xml
3273 * @param string $type The message type
3274 * @param array $message The message data
3276 * @return string The post XML
3278 public static function buildPostXml($type, $message)
3280 $data = [$type => $message];
3282 return XML::fromArray($data, $xml);
3286 * @brief Builds and transmit messages
3288 * @param array $owner the array of the item owner
3289 * @param array $contact Target of the communication
3290 * @param string $type The message type
3291 * @param array $message The message data
3292 * @param bool $public_batch Is it a public post?
3293 * @param string $guid message guid
3294 * @param bool $spool Should the transmission be spooled or transmitted?
3296 * @return int Result of the transmission
3298 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3300 $msg = self::buildPostXml($type, $message);
3302 logger('message: '.$msg, LOGGER_DATA);
3303 logger('send guid '.$guid, LOGGER_DEBUG);
3305 // Fallback if the private key wasn't transmitted in the expected field
3306 if ($owner['uprvkey'] == "") {
3307 $owner['uprvkey'] = $owner['prvkey'];
3310 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3313 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch);
3316 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3319 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3321 return $return_code;
3325 * @brief sends a participation (Used to get all further updates)
3327 * @param array $contact Target of the communication
3328 * @param array $item Item array
3330 * @return int The result of the transmission
3332 private static function sendParticipation($contact, $item)
3334 // Don't send notifications for private postings
3335 if ($item['private']) {
3339 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3341 $result = Cache::get($cachekey);
3342 if (!is_null($result)) {
3346 // Fetch some user id to have a valid handle to transmit the participation.
3347 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3348 // If the item belongs to a user, we take this user id.
3349 if ($item['uid'] == 0) {
3350 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3351 $first_user = dba::selectFirst('user', ['uid'], $condition);
3352 $owner = User::getOwnerDataById($first_user['uid']);
3354 $owner = User::getOwnerDataById($item['uid']);
3357 $author = self::myHandle($owner);
3359 $message = ["author" => $author,
3360 "guid" => get_guid(32),
3361 "parent_type" => "Post",
3362 "parent_guid" => $item["guid"]];
3364 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3366 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3367 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3369 return self::buildAndTransmit($owner, $contact, "participation", $message);
3373 * @brief sends an account migration
3375 * @param array $owner the array of the item owner
3376 * @param array $contact Target of the communication
3377 * @param int $uid User ID
3379 * @return int The result of the transmission
3381 public static function sendAccountMigration($owner, $contact, $uid)
3383 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3384 $profile = self::createProfileData($uid);
3386 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3387 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3389 $message = ["author" => $old_handle,
3390 "profile" => $profile,
3391 "signature" => $signature];
3393 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3395 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3399 * @brief Sends a "share" message
3401 * @param array $owner the array of the item owner
3402 * @param array $contact Target of the communication
3404 * @return int The result of the transmission
3406 public static function sendShare($owner, $contact)
3409 * @todo support the different possible combinations of "following" and "sharing"
3410 * Currently, Diaspora only interprets the "sharing" field
3412 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3416 switch ($contact["rel"]) {
3417 case CONTACT_IS_FRIEND:
3420 case CONTACT_IS_SHARING:
3423 case CONTACT_IS_FOLLOWER:
3429 $message = ["author" => self::myHandle($owner),
3430 "recipient" => $contact["addr"],
3431 "following" => "true",
3432 "sharing" => "true"];
3434 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3436 return self::buildAndTransmit($owner, $contact, "contact", $message);
3440 * @brief sends an "unshare"
3442 * @param array $owner the array of the item owner
3443 * @param array $contact Target of the communication
3445 * @return int The result of the transmission
3447 public static function sendUnshare($owner, $contact)
3449 $message = ["author" => self::myHandle($owner),
3450 "recipient" => $contact["addr"],
3451 "following" => "false",
3452 "sharing" => "false"];
3454 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3456 return self::buildAndTransmit($owner, $contact, "contact", $message);
3460 * @brief Checks a message body if it is a reshare
3462 * @param string $body The message body that is to be check
3463 * @param bool $complete Should it be a complete check or a simple check?
3465 * @return array|bool Reshare details or "false" if no reshare
3467 public static function isReshare($body, $complete = true)
3469 $body = trim($body);
3471 // Skip if it isn't a pure repeated messages
3472 // Does it start with a share?
3473 if ((strpos($body, "[share") > 0) && $complete) {
3477 // Does it end with a share?
3478 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3482 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3483 // Skip if there is no shared message in there
3484 if ($body == $attributes) {
3488 // If we don't do the complete check we quit here
3494 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3495 if ($matches[1] != "") {
3496 $guid = $matches[1];
3499 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3500 if ($matches[1] != "") {
3501 $guid = $matches[1];
3506 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3513 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3514 $ret["root_guid"] = $guid;
3520 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3521 if ($matches[1] != "") {
3522 $profile = $matches[1];
3525 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3526 if ($matches[1] != "") {
3527 $profile = $matches[1];
3532 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3533 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3538 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3539 if ($matches[1] != "") {
3540 $link = $matches[1];
3543 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3544 if ($matches[1] != "") {
3545 $link = $matches[1];
3548 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3549 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3557 * @brief Create an event array
3559 * @param integer $event_id The id of the event
3561 * @return array with event data
3563 private static function buildEvent($event_id)
3565 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3566 if (!DBM::is_result($r)) {
3574 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3575 if (!DBM::is_result($r)) {
3581 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3582 if (!DBM::is_result($r)) {
3588 $eventdata['author'] = self::myHandle($owner);
3590 if ($event['guid']) {
3591 $eventdata['guid'] = $event['guid'];
3594 $mask = 'Y-m-d\TH:i:s\Z';
3596 /// @todo - establish "all day" events in Friendica
3597 $eventdata["all_day"] = "false";
3599 if (!$event['adjust']) {
3600 $eventdata['timezone'] = $user['timezone'];
3602 if ($eventdata['timezone'] == "") {
3603 $eventdata['timezone'] = 'UTC';
3607 if ($event['start']) {
3608 $eventdata['start'] = datetime_convert($eventdata['timezone'], "UTC", $event['start'], $mask);
3610 if ($event['finish'] && !$event['nofinish']) {
3611 $eventdata['end'] = datetime_convert($eventdata['timezone'], "UTC", $event['finish'], $mask);
3613 if ($event['summary']) {
3614 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3616 if ($event['desc']) {
3617 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3619 if ($event['location']) {
3621 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3622 $location["lat"] = 0;
3623 $location["lng"] = 0;
3624 $eventdata['location'] = $location;
3631 * @brief Create a post (status message or reshare)
3633 * @param array $item The item that will be exported
3634 * @param array $owner the array of the item owner
3637 * 'type' -> Message type ("status_message" or "reshare")
3638 * 'message' -> Array of XML elements of the status
3640 public static function buildStatus($item, $owner)
3642 $cachekey = "diaspora:buildStatus:".$item['guid'];
3644 $result = Cache::get($cachekey);
3645 if (!is_null($result)) {
3649 $myaddr = self::myHandle($owner);
3651 $public = (($item["private"]) ? "false" : "true");
3653 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3655 // Detect a share element and do a reshare
3656 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3657 $message = ["author" => $myaddr,
3658 "guid" => $item["guid"],
3659 "created_at" => $created,
3660 "root_author" => $ret["root_handle"],
3661 "root_guid" => $ret["root_guid"],
3662 "provider_display_name" => $item["app"],
3663 "public" => $public];
3667 $title = $item["title"];
3668 $body = $item["body"];
3670 // convert to markdown
3671 $body = html_entity_decode(bb2diaspora($body));
3674 if (strlen($title)) {
3675 $body = "## ".html_entity_decode($title)."\n\n".$body;
3678 if ($item["attach"]) {
3679 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3681 $body .= "\n".L10n::t("Attachments:")."\n";
3682 foreach ($matches as $mtch) {
3683 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3690 if ($item["location"] != "")
3691 $location["address"] = $item["location"];
3693 if ($item["coord"] != "") {
3694 $coord = explode(" ", $item["coord"]);
3695 $location["lat"] = $coord[0];
3696 $location["lng"] = $coord[1];
3699 $message = ["author" => $myaddr,
3700 "guid" => $item["guid"],
3701 "created_at" => $created,
3702 "public" => $public,
3704 "provider_display_name" => $item["app"],
3705 "location" => $location];
3707 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3708 if (!isset($location["lat"]) || !isset($location["lng"])) {
3709 unset($message["location"]);
3712 if ($item['event-id'] > 0) {
3713 $event = self::buildEvent($item['event-id']);
3714 if (count($event)) {
3715 $message['event'] = $event;
3717 /// @todo Once Diaspora supports it, we will remove the body
3718 // $message['text'] = '';
3722 $type = "status_message";
3725 $msg = ["type" => $type, "message" => $message];
3727 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3733 * @brief Sends a post
3735 * @param array $item The item that will be exported
3736 * @param array $owner the array of the item owner
3737 * @param array $contact Target of the communication
3738 * @param bool $public_batch Is it a public post?
3740 * @return int The result of the transmission
3742 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3744 $status = self::buildStatus($item, $owner);
3746 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3750 * @brief Creates a "like" object
3752 * @param array $item The item that will be exported
3753 * @param array $owner the array of the item owner
3755 * @return array The data for a "like"
3757 private static function constructLike($item, $owner)
3760 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3761 dbesc($item["thr-parent"])
3763 if (!DBM::is_result($p)) {
3769 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3770 if ($item['verb'] === ACTIVITY_LIKE) {
3772 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3773 $positive = "false";
3776 return(["author" => self::myHandle($owner),
3777 "guid" => $item["guid"],
3778 "parent_guid" => $parent["guid"],
3779 "parent_type" => $target_type,
3780 "positive" => $positive,
3781 "author_signature" => ""]);
3785 * @brief Creates an "EventParticipation" object
3787 * @param array $item The item that will be exported
3788 * @param array $owner the array of the item owner
3790 * @return array The data for an "EventParticipation"
3792 private static function constructAttend($item, $owner)
3795 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3796 dbesc($item["thr-parent"])
3798 if (!DBM::is_result($p)) {
3804 switch ($item['verb']) {
3805 case ACTIVITY_ATTEND:
3806 $attend_answer = 'accepted';
3808 case ACTIVITY_ATTENDNO:
3809 $attend_answer = 'declined';
3811 case ACTIVITY_ATTENDMAYBE:
3812 $attend_answer = 'tentative';
3815 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3819 return(["author" => self::myHandle($owner),
3820 "guid" => $item["guid"],
3821 "parent_guid" => $parent["guid"],
3822 "status" => $attend_answer,
3823 "author_signature" => ""]);
3827 * @brief Creates the object for a comment
3829 * @param array $item The item that will be exported
3830 * @param array $owner the array of the item owner
3832 * @return array The data for a comment
3834 private static function constructComment($item, $owner)
3836 $cachekey = "diaspora:constructComment:".$item['guid'];
3838 $result = Cache::get($cachekey);
3839 if (!is_null($result)) {
3844 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3845 intval($item["parent"]),
3846 intval($item["parent"])
3849 if (!DBM::is_result($p)) {
3855 $text = html_entity_decode(bb2diaspora($item["body"]));
3856 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
3858 $comment = ["author" => self::myHandle($owner),
3859 "guid" => $item["guid"],
3860 "created_at" => $created,
3861 "parent_guid" => $parent["guid"],
3863 "author_signature" => ""];
3865 // Send the thread parent guid only if it is a threaded comment
3866 if ($item['thr-parent'] != $item['parent-uri']) {
3867 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3870 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3876 * @brief Send a like or a comment
3878 * @param array $item The item that will be exported
3879 * @param array $owner the array of the item owner
3880 * @param array $contact Target of the communication
3881 * @param bool $public_batch Is it a public post?
3883 * @return int The result of the transmission
3885 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3887 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3888 $message = self::constructAttend($item, $owner);
3889 $type = "event_participation";
3890 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3891 $message = self::constructLike($item, $owner);
3894 $message = self::constructComment($item, $owner);
3902 $message["author_signature"] = self::signature($owner, $message);
3904 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3908 * @brief Creates a message from a signature record entry
3910 * @param array $item The item that will be exported
3911 * @param array $signature The entry of the "sign" record
3913 * @return string The message
3915 private static function messageFromSignature($item, $signature)
3917 // Split the signed text
3918 $signed_parts = explode(";", $signature['signed_text']);
3920 if ($item["deleted"]) {
3921 $message = ["author" => $signature['signer'],
3922 "target_guid" => $signed_parts[0],
3923 "target_type" => $signed_parts[1]];
3924 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3925 $message = ["author" => $signed_parts[4],
3926 "guid" => $signed_parts[1],
3927 "parent_guid" => $signed_parts[3],
3928 "parent_type" => $signed_parts[2],
3929 "positive" => $signed_parts[0],
3930 "author_signature" => $signature['signature'],
3931 "parent_author_signature" => ""];
3933 // Remove the comment guid
3934 $guid = array_shift($signed_parts);
3936 // Remove the parent guid
3937 $parent_guid = array_shift($signed_parts);
3939 // Remove the handle
3940 $handle = array_pop($signed_parts);
3942 // Glue the parts together
3943 $text = implode(";", $signed_parts);
3945 $message = ["author" => $handle,
3947 "parent_guid" => $parent_guid,
3948 "text" => implode(";", $signed_parts),
3949 "author_signature" => $signature['signature'],
3950 "parent_author_signature" => ""];
3956 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3958 * @param array $item The item that will be exported
3959 * @param array $owner the array of the item owner
3960 * @param array $contact Target of the communication
3961 * @param bool $public_batch Is it a public post?
3963 * @return int The result of the transmission
3965 public static function sendRelay($item, $owner, $contact, $public_batch = false)
3967 if ($item["deleted"]) {
3968 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3969 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3975 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3977 // fetch the original signature
3980 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3985 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3991 // Old way - is used by the internal Friendica functions
3992 /// @todo Change all signatur storing functions to the new format
3993 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3994 $message = self::messageFromSignature($item, $signature);
3996 $msg = json_decode($signature['signed_text'], true);
3999 if (is_array($msg)) {
4000 foreach ($msg as $field => $data) {
4001 if (!$item["deleted"]) {
4002 if ($field == "diaspora_handle") {
4005 if ($field == "target_type") {
4006 $field = "parent_type";
4010 $message[$field] = $data;
4013 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
4017 $message["parent_author_signature"] = self::signature($owner, $message);
4019 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
4021 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4025 * @brief Sends a retraction (deletion) of a message, like or comment
4027 * @param array $item The item that will be exported
4028 * @param array $owner the array of the item owner
4029 * @param array $contact Target of the communication
4030 * @param bool $public_batch Is it a public post?
4031 * @param bool $relay Is the retraction transmitted from a relay?
4033 * @return int The result of the transmission
4035 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4037 $itemaddr = self::handleFromContact($item["contact-id"], $item["gcontact-id"]);
4039 $msg_type = "retraction";
4041 if ($item['id'] == $item['parent']) {
4042 $target_type = "Post";
4043 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4044 $target_type = "Like";
4046 $target_type = "Comment";
4049 $message = ["author" => $itemaddr,
4050 "target_guid" => $item['guid'],
4051 "target_type" => $target_type];
4053 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4055 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4059 * @brief Sends a mail
4061 * @param array $item The item that will be exported
4062 * @param array $owner The owner
4063 * @param array $contact Target of the communication
4065 * @return int The result of the transmission
4067 public static function sendMail($item, $owner, $contact)
4069 $myaddr = self::myHandle($owner);
4072 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4073 intval($item["convid"]),
4074 intval($item["uid"])
4077 if (!DBM::is_result($r)) {
4078 logger("conversation not found.");
4084 "author" => $cnv["creator"],
4085 "guid" => $cnv["guid"],
4086 "subject" => $cnv["subject"],
4087 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
4088 "participants" => $cnv["recips"]
4091 $body = bb2diaspora($item["body"]);
4092 $created = datetime_convert("UTC", "UTC", $item["created"], 'Y-m-d\TH:i:s\Z');
4095 "author" => $myaddr,
4096 "guid" => $item["guid"],
4097 "conversation_guid" => $cnv["guid"],
4099 "created_at" => $created,
4102 if ($item["reply"]) {
4107 "author" => $cnv["creator"],
4108 "guid" => $cnv["guid"],
4109 "subject" => $cnv["subject"],
4110 "created_at" => datetime_convert("UTC", "UTC", $cnv['created'], 'Y-m-d\TH:i:s\Z'),
4111 "participants" => $cnv["recips"],
4114 $type = "conversation";
4117 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4121 * @brief Split a name into first name and last name
4123 * @param string $name The name
4125 * @return array The array with "first" and "last"
4127 public static function splitName($name) {
4128 $name = trim($name);
4130 // Is the name longer than 64 characters? Then cut the rest of it.
4131 if (strlen($name) > 64) {
4132 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4133 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4135 $name = substr($name, 0, 64);
4139 // Take the first word as first name
4140 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4141 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4142 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4143 return ['first' => $first, 'last' => $last];
4146 // Take the last word as last name
4147 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4148 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4150 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4151 return ['first' => $first, 'last' => $last];
4154 // Take the first 32 characters if there is no space in the first 32 characters
4155 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4156 $first = substr($name, 0, 32);
4157 $last = substr($name, 32);
4158 return ['first' => $first, 'last' => $last];
4161 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4162 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4164 // Check if the last name is longer than 32 characters
4165 if (strlen($last) > 32) {
4166 if (strpos($last, ' ') <= 32) {
4167 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4169 $last = substr($last, 0, 32);
4173 return ['first' => $first, 'last' => $last];
4177 * @brief Create profile data
4179 * @param int $uid The user id
4181 * @return array The profile data
4183 private static function createProfileData($uid)
4186 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4188 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4189 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4190 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4199 $handle = $profile["addr"];
4201 $split_name = self::splitName($profile['name']);
4202 $first = $split_name['first'];
4203 $last = $split_name['last'];
4205 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4206 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4207 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4208 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4210 if ($searchable === 'true') {
4213 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4214 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4218 $dob = datetime_convert('UTC', 'UTC', $year . '-' . $month . '-'. $day, 'Y-m-d');
4221 $about = $profile['about'];
4222 $about = strip_tags(bbcode($about));
4224 $location = Profile::formatLocation($profile);
4226 if ($profile['pub_keywords']) {
4227 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4228 $kw = str_replace(' ', ' ', $kw);
4229 $arr = explode(' ', $profile['pub_keywords']);
4231 for ($x = 0; $x < 5; $x ++) {
4232 if (trim($arr[$x])) {
4233 $tags .= '#'. trim($arr[$x]) .' ';
4238 $tags = trim($tags);
4241 return ["author" => $handle,
4242 "first_name" => $first,
4243 "last_name" => $last,
4244 "image_url" => $large,
4245 "image_url_medium" => $medium,
4246 "image_url_small" => $small,
4248 "gender" => $profile['gender'],
4250 "location" => $location,
4251 "searchable" => $searchable,
4253 "tag_string" => $tags];
4257 * @brief Sends profile data
4259 * @param int $uid The user id
4260 * @param bool $recips optional, default false
4263 public static function sendProfile($uid, $recips = false)
4269 $owner = User::getOwnerDataById($uid);
4276 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4277 AND `uid` = %d AND `rel` != %d",
4278 dbesc(NETWORK_DIASPORA),
4280 intval(CONTACT_IS_SHARING)
4288 $message = self::createProfileData($uid);
4290 foreach ($recips as $recip) {
4291 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4292 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4297 * @brief Stores the signature for likes that are created on our system
4299 * @param array $contact The contact array of the "like"
4300 * @param int $post_id The post id of the "like"
4302 * @return bool Success
4304 public static function storeLikeSignature($contact, $post_id)
4306 // Is the contact the owner? Then fetch the private key
4307 if (!$contact['self'] || ($contact['uid'] == 0)) {
4308 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4312 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4313 if (!DBM::is_result($r)) {
4317 $contact["uprvkey"] = $r[0]['prvkey'];
4319 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4320 if (!DBM::is_result($r)) {
4324 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4328 $message = self::constructLike($r[0], $contact);
4329 if ($message === false) {
4333 $message["author_signature"] = self::signature($contact, $message);
4336 * Now store the signature more flexible to dynamically support new fields.
4337 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4339 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4341 logger('Stored diaspora like signature');
4346 * @brief Stores the signature for comments that are created on our system
4348 * @param array $item The item array of the comment
4349 * @param array $contact The contact array of the item owner
4350 * @param string $uprvkey The private key of the sender
4351 * @param int $message_id The message id of the comment
4353 * @return bool Success
4355 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4357 if ($uprvkey == "") {
4358 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4362 $contact["uprvkey"] = $uprvkey;
4364 $message = self::constructComment($item, $contact);
4365 if ($message === false) {
4369 $message["author_signature"] = self::signature($contact, $message);
4372 * Now store the signature more flexible to dynamically support new fields.
4373 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4375 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4377 logger('Stored diaspora comment signature');