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\Item;
24 use Friendica\Model\Profile;
25 use Friendica\Model\Queue;
26 use Friendica\Model\User;
27 use Friendica\Network\Probe;
28 use Friendica\Util\Crypto;
29 use Friendica\Util\Network;
30 use Friendica\Util\Temporal;
31 use Friendica\Util\XML;
35 require_once 'include/dba.php';
36 require_once 'include/items.php';
37 require_once 'include/bb2diaspora.php';
38 require_once 'include/datetime.php';
41 * @brief This class contain functions to create and send Diaspora XML files
47 * @brief Return a list of relay servers
49 * This is an experimental Diaspora feature.
51 * @return array of relay servers
53 public static function relayList()
55 $serverdata = Config::get("system", "relay_server");
56 if ($serverdata == "") {
62 $servers = explode(",", $serverdata);
64 foreach ($servers as $server) {
65 $server = trim($server);
66 $addr = "relay@".str_replace("http://", "", normalise_link($server));
67 $batch = $server."/receive/public";
70 "SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
73 dbesc(normalise_link($server))
78 "INSERT INTO `contact` (`uid`, `created`, `name`, `nick`, `addr`, `url`, `nurl`, `batch`, `network`, `rel`, `blocked`, `pending`, `writable`, `name-date`, `uri-date`, `avatar-date`)
79 VALUES (0, '%s', '%s', 'relay', '%s', '%s', '%s', '%s', '%s', %d, 0, 0, 1, '%s', '%s', '%s')",
84 dbesc(normalise_link($server)),
86 dbesc(NETWORK_DIASPORA),
87 intval(CONTACT_IS_FOLLOWER),
88 dbesc(Temporal::convert()),
89 dbesc(Temporal::convert()),
90 dbesc(Temporal::convert())
93 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
95 $relay[] = $relais[0];
98 $relay[] = $relais[0];
106 * @brief Return a list of participating contacts for a thread
108 * This is used for the participation feature.
109 * One of the parameters is a contact array.
110 * This is done to avoid duplicates.
112 * @param integer $thread The id of the thread
113 * @param array $contacts The previously fetched contacts
115 * @return array of relay servers
117 public static function participantsForThread($thread, $contacts)
119 $r = dba::p("SELECT `contact`.`batch`, `contact`.`id`, `contact`.`name`, `contact`.`network`,
120 `fcontact`.`batch` AS `fbatch`, `fcontact`.`network` AS `fnetwork` FROM `participation`
121 INNER JOIN `contact` ON `contact`.`id` = `participation`.`cid`
122 INNER JOIN `fcontact` ON `fcontact`.`id` = `participation`.`fid`
123 WHERE `participation`.`iid` = ?", $thread);
125 while ($contact = dba::fetch($r)) {
126 if (!empty($contact['fnetwork'])) {
127 $contact['network'] = $contact['fnetwork'];
129 unset($contact['fnetwork']);
131 if (empty($contact['batch']) && !empty($contact['fbatch'])) {
132 $contact['batch'] = $contact['fbatch'];
134 unset($contact['fbatch']);
137 foreach ($contacts as $entry) {
138 if ($entry['batch'] == $contact['batch']) {
144 $contacts[] = $contact;
153 * @brief repairs a signature that was double encoded
155 * The function is unused at the moment. It was copied from the old implementation.
157 * @param string $signature The signature
158 * @param string $handle The handle of the signature owner
159 * @param integer $level This value is only set inside this function to avoid endless loops
161 * @return string the repaired signature
163 private static function repairSignature($signature, $handle = "", $level = 1)
165 if ($signature == "") {
169 if (base64_encode(base64_decode(base64_decode($signature))) == base64_decode($signature)) {
170 $signature = base64_decode($signature);
171 logger("Repaired double encoded signature from Diaspora/Hubzilla handle ".$handle." - level ".$level, LOGGER_DEBUG);
173 // Do a recursive call to be able to fix even multiple levels
175 $signature = self::repairSignature($signature, $handle, ++$level);
183 * @brief verify the envelope and return the verified data
185 * @param string $envelope The magic envelope
187 * @return string verified data
189 private static function verifyMagicEnvelope($envelope)
191 $basedom = XML::parseString($envelope);
193 if (!is_object($basedom)) {
194 logger("Envelope is no XML file");
198 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
200 if (sizeof($children) == 0) {
201 logger("XML has no children");
207 $data = base64url_decode($children->data);
208 $type = $children->data->attributes()->type[0];
210 $encoding = $children->encoding;
212 $alg = $children->alg;
214 $sig = base64url_decode($children->sig);
215 $key_id = $children->sig->attributes()->key_id[0];
217 $handle = base64url_decode($key_id);
220 $b64url_data = base64url_encode($data);
221 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
223 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
225 $key = self::key($handle);
227 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
229 logger('Message did not verify. Discarding.');
237 * @brief encrypts data via AES
239 * @param string $key The AES key
240 * @param string $iv The IV (is used for CBC encoding)
241 * @param string $data The data that is to be encrypted
243 * @return string encrypted data
245 private static function aesEncrypt($key, $iv, $data)
247 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
251 * @brief decrypts data via AES
253 * @param string $key The AES key
254 * @param string $iv The IV (is used for CBC encoding)
255 * @param string $encrypted The encrypted data
257 * @return string decrypted data
259 private static function aesDecrypt($key, $iv, $encrypted)
261 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
265 * @brief: Decodes incoming Diaspora message in the new format
267 * @param array $importer Array of the importer user
268 * @param string $raw raw post message
271 * 'message' -> decoded Diaspora XML message
272 * 'author' -> author diaspora handle
273 * 'key' -> author public key (converted to pkcs#8)
275 public static function decodeRaw($importer, $raw)
277 $data = json_decode($raw);
279 // Is it a private post? Then decrypt the outer Salmon
280 if (is_object($data)) {
281 $encrypted_aes_key_bundle = base64_decode($data->aes_key);
282 $ciphertext = base64_decode($data->encrypted_magic_envelope);
284 $outer_key_bundle = '';
285 @openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
286 $j_outer_key_bundle = json_decode($outer_key_bundle);
288 if (!is_object($j_outer_key_bundle)) {
289 logger('Outer Salmon did not verify. Discarding.');
290 System::httpExit(400);
293 $outer_iv = base64_decode($j_outer_key_bundle->iv);
294 $outer_key = base64_decode($j_outer_key_bundle->key);
296 $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
301 $basedom = XML::parseString($xml);
303 if (!is_object($basedom)) {
304 logger('Received data does not seem to be an XML. Discarding. '.$xml);
305 System::httpExit(400);
308 $base = $basedom->children(NAMESPACE_SALMON_ME);
310 // Not sure if this cleaning is needed
311 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
313 // Build the signed data
314 $type = $base->data[0]->attributes()->type[0];
315 $encoding = $base->encoding;
317 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
319 // This is the signature
320 $signature = base64url_decode($base->sig);
322 // Get the senders' public key
323 $key_id = $base->sig[0]->attributes()->key_id[0];
324 $author_addr = base64_decode($key_id);
325 $key = self::key($author_addr);
327 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
329 logger('Message did not verify. Discarding.');
330 System::httpExit(400);
333 return ['message' => (string)base64url_decode($base->data),
334 'author' => unxmlify($author_addr),
335 'key' => (string)$key];
339 * @brief: Decodes incoming Diaspora message in the deprecated format
341 * @param array $importer Array of the importer user
342 * @param string $xml urldecoded Diaspora salmon
345 * 'message' -> decoded Diaspora XML message
346 * 'author' -> author diaspora handle
347 * 'key' -> author public key (converted to pkcs#8)
349 public static function decode($importer, $xml)
352 $basedom = XML::parseString($xml);
354 if (!is_object($basedom)) {
355 logger("XML is not parseable.");
358 $children = $basedom->children('https://joindiaspora.com/protocol');
360 if ($children->header) {
362 $author_link = str_replace('acct:', '', $children->header->author_id);
364 // This happens with posts from a relais
366 logger("This is no private post in the old format", LOGGER_DEBUG);
370 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
372 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
373 $ciphertext = base64_decode($encrypted_header->ciphertext);
375 $outer_key_bundle = '';
376 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
378 $j_outer_key_bundle = json_decode($outer_key_bundle);
380 $outer_iv = base64_decode($j_outer_key_bundle->iv);
381 $outer_key = base64_decode($j_outer_key_bundle->key);
383 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
385 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
386 $idom = XML::parseString($decrypted);
388 $inner_iv = base64_decode($idom->iv);
389 $inner_aes_key = base64_decode($idom->aes_key);
391 $author_link = str_replace('acct:', '', $idom->author_id);
394 $dom = $basedom->children(NAMESPACE_SALMON_ME);
396 // figure out where in the DOM tree our data is hiding
398 if ($dom->provenance->data) {
399 $base = $dom->provenance;
400 } elseif ($dom->env->data) {
402 } elseif ($dom->data) {
407 logger('unable to locate salmon data in xml');
408 System::httpExit(400);
412 // Stash the signature away for now. We have to find their key or it won't be good for anything.
413 $signature = base64url_decode($base->sig);
417 // strip whitespace so our data element will return to one big base64 blob
418 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
421 // stash away some other stuff for later
423 $type = $base->data[0]->attributes()->type[0];
424 $keyhash = $base->sig[0]->attributes()->keyhash[0];
425 $encoding = $base->encoding;
429 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
433 $data = base64url_decode($data);
437 $inner_decrypted = $data;
439 // Decode the encrypted blob
440 $inner_encrypted = base64_decode($data);
441 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
445 logger('Could not retrieve author URI.');
446 System::httpExit(400);
448 // Once we have the author URI, go to the web and try to find their public key
449 // (first this will look it up locally if it is in the fcontact cache)
450 // This will also convert diaspora public key from pkcs#1 to pkcs#8
452 logger('Fetching key for '.$author_link);
453 $key = self::key($author_link);
456 logger('Could not retrieve author key.');
457 System::httpExit(400);
460 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
463 logger('Message did not verify. Discarding.');
464 System::httpExit(400);
467 logger('Message verified.');
469 return ['message' => (string)$inner_decrypted,
470 'author' => unxmlify($author_link),
471 'key' => (string)$key];
476 * @brief Dispatches public messages and find the fitting receivers
478 * @param array $msg The post that will be dispatched
480 * @return int The message id of the generated message, "true" or "false" if there was an error
482 public static function dispatchPublic($msg)
484 $enabled = intval(Config::get("system", "diaspora_enabled"));
486 logger("diaspora is disabled");
490 if (!($postdata = self::validPosting($msg))) {
491 logger("Invalid posting");
495 $fields = $postdata['fields'];
497 // Is it a an action (comment, like, ...) for our own post?
498 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
499 $guid = notags(unxmlify($fields->parent_guid));
500 $importer = self::importerForGuid($guid);
501 if (is_array($importer)) {
502 logger("delivering to origin: ".$importer["name"]);
503 $message_id = self::dispatch($importer, $msg, $fields);
508 // Process item retractions. This has to be done separated from the other stuff,
509 // since retractions for comments could come even from non followers.
510 if (!empty($fields) && in_array($fields->getName(), ['retraction'])) {
511 $target = notags(unxmlify($fields->target_type));
512 if (in_array($target, ["Comment", "Like", "Post", "Reshare", "StatusMessage"])) {
513 logger('processing retraction for '.$target, LOGGER_DEBUG);
514 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
515 $message_id = self::dispatch($importer, $msg, $fields);
520 // Now distribute it to the followers
522 "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
523 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
524 AND NOT `account_expired` AND NOT `account_removed`",
525 dbesc(NETWORK_DIASPORA),
526 dbesc($msg["author"])
529 if (DBM::is_result($r)) {
530 foreach ($r as $rr) {
531 logger("delivering to: ".$rr["username"]);
532 self::dispatch($rr, $msg, $fields);
534 } elseif (!Config::get('system', 'relay_subscribe', false)) {
535 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
537 // Use a dummy importer to import the data for the public copy
538 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
539 $message_id = self::dispatch($importer, $msg, $fields);
546 * @brief Dispatches the different message types to the different functions
548 * @param array $importer Array of the importer user
549 * @param array $msg The post that will be dispatched
550 * @param object $fields SimpleXML object that contains the message
552 * @return int The message id of the generated message, "true" or "false" if there was an error
554 public static function dispatch($importer, $msg, $fields = null)
556 // The sender is the handle of the contact that sent the message.
557 // This will often be different with relayed messages (for example "like" and "comment")
558 $sender = $msg["author"];
560 // This is only needed for private postings since this is already done for public ones before
561 if (is_null($fields)) {
562 if (!($postdata = self::validPosting($msg))) {
563 logger("Invalid posting");
566 $fields = $postdata['fields'];
569 $type = $fields->getName();
571 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
574 case "account_migration":
575 return self::receiveAccountMigration($importer, $fields);
577 case "account_deletion":
578 return self::receiveAccountDeletion($importer, $fields);
581 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
584 return self::receiveContactRequest($importer, $fields);
587 return self::receiveConversation($importer, $msg, $fields);
590 return self::receiveLike($importer, $sender, $fields);
593 return self::receiveMessage($importer, $fields);
595 case "participation":
596 return self::receiveParticipation($importer, $fields);
598 case "photo": // Not implemented
599 return self::receivePhoto($importer, $fields);
601 case "poll_participation": // Not implemented
602 return self::receivePollParticipation($importer, $fields);
605 return self::receiveProfile($importer, $fields);
608 return self::receiveReshare($importer, $fields, $msg["message"]);
611 return self::receiveRetraction($importer, $sender, $fields);
613 case "status_message":
614 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
617 logger("Unknown message type ".$type);
625 * @brief Checks if a posting is valid and fetches the data fields.
627 * This function does not only check the signature.
628 * It also does the conversion between the old and the new diaspora format.
630 * @param array $msg Array with the XML, the sender handle and the sender signature
632 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
634 private static function validPosting($msg)
636 $data = XML::parseString($msg["message"]);
638 if (!is_object($data)) {
639 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
643 $first_child = $data->getName();
645 // Is this the new or the old version?
646 if ($data->getName() == "XML") {
648 foreach ($data->post->children() as $child) {
656 $type = $element->getName();
659 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
661 // All retractions are handled identically from now on.
662 // In the new version there will only be "retraction".
663 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
664 $type = "retraction";
666 if ($type == "request") {
670 $fields = new SimpleXMLElement("<".$type."/>");
674 foreach ($element->children() as $fieldname => $entry) {
676 // Translation for the old XML structure
677 if ($fieldname == "diaspora_handle") {
678 $fieldname = "author";
680 if ($fieldname == "participant_handles") {
681 $fieldname = "participants";
683 if (in_array($type, ["like", "participation"])) {
684 if ($fieldname == "target_type") {
685 $fieldname = "parent_type";
688 if ($fieldname == "sender_handle") {
689 $fieldname = "author";
691 if ($fieldname == "recipient_handle") {
692 $fieldname = "recipient";
694 if ($fieldname == "root_diaspora_id") {
695 $fieldname = "root_author";
697 if ($type == "status_message") {
698 if ($fieldname == "raw_message") {
702 if ($type == "retraction") {
703 if ($fieldname == "post_guid") {
704 $fieldname = "target_guid";
706 if ($fieldname == "type") {
707 $fieldname = "target_type";
712 if (($fieldname == "author_signature") && ($entry != "")) {
713 $author_signature = base64_decode($entry);
714 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
715 $parent_author_signature = base64_decode($entry);
716 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
717 if ($signed_data != "") {
721 $signed_data .= $entry;
723 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
724 || ($orig_type == "relayable_retraction")
726 XML::copy($entry, $fields, $fieldname);
730 // This is something that shouldn't happen at all.
731 if (in_array($type, ["status_message", "reshare", "profile"])) {
732 if ($msg["author"] != $fields->author) {
733 logger("Message handle is not the same as envelope sender. Quitting this message.");
738 // Only some message types have signatures. So we quit here for the other types.
739 if (!in_array($type, ["comment", "like"])) {
740 return ["fields" => $fields, "relayed" => false];
742 // No author_signature? This is a must, so we quit.
743 if (!isset($author_signature)) {
744 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
748 if (isset($parent_author_signature)) {
751 $key = self::key($msg["author"]);
753 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
754 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);
761 $key = self::key($fields->author);
763 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
764 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
767 return ["fields" => $fields, "relayed" => $relayed];
772 * @brief Fetches the public key for a given handle
774 * @param string $handle The handle
776 * @return string The public key
778 private static function key($handle)
780 $handle = strval($handle);
782 logger("Fetching diaspora key for: ".$handle);
784 $r = self::personByHandle($handle);
793 * @brief Fetches data for a given handle
795 * @param string $handle The handle
797 * @return array the queried data
799 public static function personByHandle($handle)
802 "SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
803 dbesc(NETWORK_DIASPORA),
808 logger("In cache " . print_r($r, true), LOGGER_DEBUG);
810 // update record occasionally so it doesn't get stale
811 $d = strtotime($person["updated"]." +00:00");
812 if ($d < strtotime("now - 14 days")) {
816 if ($person["guid"] == "") {
821 if (!$person || $update) {
822 logger("create or refresh", LOGGER_DEBUG);
823 $r = Probe::uri($handle, NETWORK_DIASPORA);
825 // Note that Friendica contacts will return a "Diaspora person"
826 // if Diaspora connectivity is enabled on their server
827 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
828 self::addFContact($r, $update);
836 * @brief Updates the fcontact table
838 * @param array $arr The fcontact data
839 * @param bool $update Update or insert?
841 * @return string The id of the fcontact entry
843 private static function addFContact($arr, $update = false)
847 "UPDATE `fcontact` SET
861 WHERE `url` = '%s' AND `network` = '%s'",
863 dbesc($arr["photo"]),
864 dbesc($arr["request"]),
866 dbesc(strtolower($arr["addr"])),
868 dbesc($arr["batch"]),
869 dbesc($arr["notify"]),
871 dbesc($arr["confirm"]),
872 dbesc($arr["alias"]),
873 dbesc($arr["pubkey"]),
874 dbesc(Temporal::convert()),
876 dbesc($arr["network"])
880 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
881 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
882 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
885 dbesc($arr["photo"]),
886 dbesc($arr["request"]),
890 dbesc($arr["batch"]),
891 dbesc($arr["notify"]),
893 dbesc($arr["confirm"]),
894 dbesc($arr["network"]),
895 dbesc($arr["alias"]),
896 dbesc($arr["pubkey"]),
897 dbesc(Temporal::convert())
905 * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
907 * @param int $contact_id The id in the contact table
908 * @param int $gcontact_id The id in the gcontact table
910 * @return string the handle
912 public static function handleFromContact($contact_id, $gcontact_id = 0)
916 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
918 if ($gcontact_id != 0) {
920 "SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
924 if (DBM::is_result($r)) {
925 return strtolower($r[0]["addr"]);
930 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
934 if (DBM::is_result($r)) {
937 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
939 if ($contact['addr'] != "") {
940 $handle = $contact['addr'];
942 $baseurl_start = strpos($contact['url'], '://') + 3;
943 // allows installations in a subdirectory--not sure how Diaspora will handle
944 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
945 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
946 $handle = $contact['nick'].'@'.$baseurl;
950 return strtolower($handle);
954 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
957 * @param mixed $fcontact_guid Hexadecimal string guid
959 * @return string the contact url or null
961 public static function urlFromContactGuid($fcontact_guid)
963 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
966 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
967 dbesc(NETWORK_DIASPORA),
968 dbesc($fcontact_guid)
971 if (DBM::is_result($r)) {
979 * @brief Get a contact id for a given handle
981 * @todo Move to Friendica\Model\Contact
983 * @param int $uid The user id
984 * @param string $handle The handle in the format user@domain.tld
986 * @return int Contact id
988 private static function contactByHandle($uid, $handle)
990 // First do a direct search on the contact table
992 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
997 if (DBM::is_result($r)) {
1001 * We haven't found it?
1002 * We use another function for it that will possibly create a contact entry.
1004 $cid = Contact::getIdForURL($handle, $uid);
1007 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1008 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1010 if (DBM::is_result($r)) {
1016 $handle_parts = explode("@", $handle);
1017 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1019 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1020 dbesc(NETWORK_DFRN),
1024 if (DBM::is_result($r)) {
1028 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1033 * @brief Check if posting is allowed for this contact
1035 * @param array $importer Array of the importer user
1036 * @param array $contact The contact that is checked
1037 * @param bool $is_comment Is the check for a comment?
1039 * @return bool is the contact allowed to post?
1041 private static function postAllow($importer, $contact, $is_comment = false)
1044 * Perhaps we were already sharing with this person. Now they're sharing with us.
1045 * That makes us friends.
1046 * Normally this should have handled by getting a request - but this could get lost
1048 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1049 // It is not removed by now. Possibly the code is needed?
1050 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1053 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1054 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1057 // $contact["rel"] = CONTACT_IS_FRIEND;
1058 // logger("defining user ".$contact["nick"]." as friend");
1061 // We don't seem to like that person
1062 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
1063 // Maybe blocked, don't accept.
1065 // We are following this person?
1066 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1067 // Yes, then it is fine.
1069 // Is it a post to a community?
1070 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1073 // Is the message a global user or a comment?
1074 } elseif (($importer["uid"] == 0) || $is_comment) {
1075 // Messages for the global users and comments are always accepted
1083 * @brief Fetches the contact id for a handle and checks if posting is allowed
1085 * @param array $importer Array of the importer user
1086 * @param string $handle The checked handle in the format user@domain.tld
1087 * @param bool $is_comment Is the check for a comment?
1089 * @return array The contact data
1091 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1093 $contact = self::contactByHandle($importer["uid"], $handle);
1095 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1096 // If a contact isn't found, we accept it anyway if it is a comment
1104 if (!self::postAllow($importer, $contact, $is_comment)) {
1105 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1112 * @brief Does the message already exists on the system?
1114 * @param int $uid The user id
1115 * @param string $guid The guid of the message
1117 * @return int|bool message id if the message already was stored into the system - or false.
1119 private static function messageExists($uid, $guid)
1122 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1127 if (DBM::is_result($r)) {
1128 logger("message ".$guid." already exists for user ".$uid);
1136 * @brief Checks for links to posts in a message
1138 * @param array $item The item array
1141 private static function fetchGuid($item)
1143 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1144 preg_replace_callback(
1146 function ($match) use ($item) {
1147 self::fetchGuidSub($match, $item);
1152 preg_replace_callback(
1153 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1154 function ($match) use ($item) {
1155 self::fetchGuidSub($match, $item);
1162 * @brief Checks for relative /people/* links in an item body to match local
1163 * contacts or prepends the remote host taken from the author link.
1165 * @param string $body The item body to replace links from
1166 * @param string $author_link The author link for missing local contact fallback
1168 * @return string the replaced string
1170 public static function replacePeopleGuid($body, $author_link)
1172 $return = preg_replace_callback(
1173 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1174 function ($match) use ($author_link) {
1176 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1177 // 1 => '0123456789abcdef'
1179 $handle = self::urlFromContactGuid($match[1]);
1182 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1184 // No local match, restoring absolute remote URL from author scheme and host
1185 $author_url = parse_url($author_link);
1186 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1198 * @brief sub function of "fetchGuid" which checks for links in messages
1200 * @param array $match array containing a link that has to be checked for a message link
1201 * @param array $item The item array
1204 private static function fetchGuidSub($match, $item)
1206 if (!self::storeByGuid($match[1], $item["author-link"])) {
1207 self::storeByGuid($match[1], $item["owner-link"]);
1212 * @brief Fetches an item with a given guid from a given server
1214 * @param string $guid the message guid
1215 * @param string $server The server address
1216 * @param int $uid The user id of the user
1218 * @return int the message id of the stored message or false
1220 private static function storeByGuid($guid, $server, $uid = 0)
1222 $serverparts = parse_url($server);
1223 $server = $serverparts["scheme"]."://".$serverparts["host"];
1225 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1227 $msg = self::message($guid, $server);
1233 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1235 // Now call the dispatcher
1236 return self::dispatchPublic($msg);
1240 * @brief Fetches a message from a server
1242 * @param string $guid message guid
1243 * @param string $server The url of the server
1244 * @param int $level Endless loop prevention
1247 * 'message' => The message XML
1248 * 'author' => The author handle
1249 * 'key' => The public key of the author
1251 private static function message($guid, $server, $level = 0)
1257 // This will work for new Diaspora servers and Friendica servers from 3.5
1258 $source_url = $server."/fetch/post/".urlencode($guid);
1260 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1262 $envelope = Network::fetchUrl($source_url);
1264 logger("Envelope was fetched.", LOGGER_DEBUG);
1265 $x = self::verifyMagicEnvelope($envelope);
1267 logger("Envelope could not be verified.", LOGGER_DEBUG);
1269 logger("Envelope was verified.", LOGGER_DEBUG);
1275 // This will work for older Diaspora and Friendica servers
1277 $source_url = $server."/p/".urlencode($guid).".xml";
1278 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1280 $x = Network::fetchUrl($source_url);
1286 $source_xml = XML::parseString($x);
1288 if (!is_object($source_xml)) {
1292 if ($source_xml->post->reshare) {
1293 // Reshare of a reshare - old Diaspora version
1294 logger("Message is a reshare", LOGGER_DEBUG);
1295 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1296 } elseif ($source_xml->getName() == "reshare") {
1297 // Reshare of a reshare - new Diaspora version
1298 logger("Message is a new reshare", LOGGER_DEBUG);
1299 return self::message($source_xml->root_guid, $server, ++$level);
1304 // Fetch the author - for the old and the new Diaspora version
1305 if ($source_xml->post->status_message->diaspora_handle) {
1306 $author = (string)$source_xml->post->status_message->diaspora_handle;
1307 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1308 $author = (string)$source_xml->author;
1311 // If this isn't a "status_message" then quit
1313 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1317 $msg = ["message" => $x, "author" => $author];
1319 $msg["key"] = self::key($msg["author"]);
1325 * @brief Fetches the item record of a given guid
1327 * @param int $uid The user id
1328 * @param string $guid message guid
1329 * @param string $author The handle of the item
1330 * @param array $contact The contact of the item owner
1332 * @return array the item record
1334 private static function parentItem($uid, $guid, $author, $contact)
1337 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1338 `author-name`, `author-link`, `author-avatar`,
1339 `owner-name`, `owner-link`, `owner-avatar`
1340 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1346 $result = self::storeByGuid($guid, $contact["url"], $uid);
1349 $person = self::personByHandle($author);
1350 $result = self::storeByGuid($guid, $person["url"], $uid);
1354 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1357 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1358 `author-name`, `author-link`, `author-avatar`,
1359 `owner-name`, `owner-link`, `owner-avatar`
1360 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1368 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1371 logger("parent item found: parent: ".$guid." - user: ".$uid);
1377 * @brief returns contact details
1379 * @param array $contact The default contact if the person isn't found
1380 * @param array $person The record of the person
1381 * @param int $uid The user id
1384 * 'cid' => contact id
1385 * 'network' => network type
1387 private static function authorContactByUrl($contact, $person, $uid)
1390 "SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1391 dbesc(normalise_link($person["url"])),
1396 $network = $r[0]["network"];
1398 $cid = $contact["id"];
1399 $network = NETWORK_DIASPORA;
1402 return ["cid" => $cid, "network" => $network];
1406 * @brief Is the profile a hubzilla profile?
1408 * @param string $url The profile link
1410 * @return bool is it a hubzilla server?
1412 public static function isRedmatrix($url)
1414 return(strstr($url, "/channel/"));
1418 * @brief Generate a post link with a given handle and message guid
1420 * @param string $addr The user handle
1421 * @param string $guid message guid
1422 * @param string $parent_guid optional parent guid
1424 * @return string the post link
1426 private static function plink($addr, $guid, $parent_guid = '')
1428 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1431 if (!DBM::is_result($r)) {
1432 if ($parent_guid != '') {
1433 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1435 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1439 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1440 // So we try another way as well.
1441 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1442 if (DBM::is_result($s)) {
1443 $r[0]["network"] = $s[0]["network"];
1446 if ($r[0]["network"] == NETWORK_DFRN) {
1447 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1450 if (self::isRedmatrix($r[0]["url"])) {
1451 return $r[0]["url"]."/?f=&mid=".$guid;
1454 if ($parent_guid != '') {
1455 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1457 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1462 * @brief Receives account migration
1464 * @param array $importer Array of the importer user
1465 * @param object $data The message object
1467 * @return bool Success
1469 private static function receiveAccountMigration($importer, $data)
1471 $old_handle = notags(unxmlify($data->author));
1472 $new_handle = notags(unxmlify($data->profile->author));
1473 $signature = notags(unxmlify($data->signature));
1475 $contact = self::contactByHandle($importer["uid"], $old_handle);
1477 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1481 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1484 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1485 $key = self::key($old_handle);
1486 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1487 logger('No valid signature for migration.');
1491 // Update the profile
1492 self::receiveProfile($importer, $data->profile);
1494 // change the technical stuff in contact and gcontact
1495 $data = Probe::uri($new_handle);
1496 if ($data['network'] == NETWORK_PHANTOM) {
1497 logger('Account for '.$new_handle." couldn't be probed.");
1501 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1502 'name' => $data['name'], 'nick' => $data['nick'],
1503 'addr' => $data['addr'], 'batch' => $data['batch'],
1504 'notify' => $data['notify'], 'poll' => $data['poll'],
1505 'network' => $data['network']];
1507 dba::update('contact', $fields, ['addr' => $old_handle]);
1509 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1510 'name' => $data['name'], 'nick' => $data['nick'],
1511 'addr' => $data['addr'], 'connect' => $data['addr'],
1512 'notify' => $data['notify'], 'photo' => $data['photo'],
1513 'server_url' => $data['baseurl'], 'network' => $data['network']];
1515 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1517 logger('Contacts are updated.');
1520 /// @todo This is an extreme performance killer
1522 'owner-link' => [$contact["url"], $data["url"]],
1523 'author-link' => [$contact["url"], $data["url"]],
1525 foreach ($fields as $n => $f) {
1527 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1530 intval($importer["uid"])
1533 if (DBM::is_result($r)) {
1535 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1540 intval($importer["uid"])
1549 logger('Items are updated.');
1555 * @brief Processes an account deletion
1557 * @param array $importer Array of the importer user
1558 * @param object $data The message object
1560 * @return bool Success
1562 private static function receiveAccountDeletion($importer, $data)
1564 /// @todo Account deletion should remove the contact from the global contacts as well
1566 $author = notags(unxmlify($data->author));
1568 $contact = self::contactByHandle($importer["uid"], $author);
1570 logger("cannot find contact for author: ".$author);
1574 // We now remove the contact
1575 Contact::remove($contact["id"]);
1580 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1582 * @param string $author Author handle
1583 * @param string $guid Message guid
1584 * @param boolean $onlyfound Only return uri when found in the database
1586 * @return string The constructed uri or the one from our database
1588 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1590 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1591 if (DBM::is_result($r)) {
1592 return $r[0]["uri"];
1593 } elseif (!$onlyfound) {
1594 return $author.":".$guid;
1601 * @brief Fetch the guid from our database with a given uri
1603 * @param string $uri Message uri
1604 * @param string $uid Author handle
1606 * @return string The post guid
1608 private static function getGuidFromUri($uri, $uid)
1610 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1611 if (DBM::is_result($r)) {
1612 return $r[0]["guid"];
1619 * @brief Find the best importer for a comment, like, ...
1621 * @param string $guid The guid of the item
1623 * @return array|boolean the origin owner of that post - or false
1625 private static function importerForGuid($guid)
1627 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1629 if (DBM::is_result($item)) {
1630 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1631 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1632 if (DBM::is_result($contact)) {
1640 * @brief Processes an incoming comment
1642 * @param array $importer Array of the importer user
1643 * @param string $sender The sender of the message
1644 * @param object $data The message object
1645 * @param string $xml The original XML of the message
1647 * @return int The message id of the generated comment or "false" if there was an error
1649 private static function receiveComment($importer, $sender, $data, $xml)
1651 $author = notags(unxmlify($data->author));
1652 $guid = notags(unxmlify($data->guid));
1653 $parent_guid = notags(unxmlify($data->parent_guid));
1654 $text = unxmlify($data->text);
1656 if (isset($data->created_at)) {
1657 $created_at = Temporal::convert(notags(unxmlify($data->created_at)));
1659 $created_at = Temporal::convert();
1662 if (isset($data->thread_parent_guid)) {
1663 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1664 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1669 $contact = self::allowedContactByHandle($importer, $sender, true);
1674 $message_id = self::messageExists($importer["uid"], $guid);
1679 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1680 if (!$parent_item) {
1684 $person = self::personByHandle($author);
1685 if (!is_array($person)) {
1686 logger("unable to find author details");
1690 // Fetch the contact id - if we know this contact
1691 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1695 $datarray["uid"] = $importer["uid"];
1696 $datarray["contact-id"] = $author_contact["cid"];
1697 $datarray["network"] = $author_contact["network"];
1699 $datarray["author-name"] = $person["name"];
1700 $datarray["author-link"] = $person["url"];
1701 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1703 $datarray["owner-name"] = $contact["name"];
1704 $datarray["owner-link"] = $contact["url"];
1705 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1707 $datarray["guid"] = $guid;
1708 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1710 $datarray["type"] = "remote-comment";
1711 $datarray["verb"] = ACTIVITY_POST;
1712 $datarray["gravity"] = GRAVITY_COMMENT;
1714 if ($thr_uri != "") {
1715 $datarray["parent-uri"] = $thr_uri;
1717 $datarray["parent-uri"] = $parent_item["uri"];
1720 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1722 $datarray["protocol"] = PROTOCOL_DIASPORA;
1723 $datarray["source"] = $xml;
1725 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1727 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1729 $body = diaspora2bb($text);
1731 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1733 self::fetchGuid($datarray);
1735 $message_id = Item::insert($datarray);
1737 if ($message_id <= 0) {
1742 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1745 // If we are the origin of the parent we store the original data and notify our followers
1746 if ($message_id && $parent_item["origin"]) {
1747 // Formerly we stored the signed text, the signature and the author in different fields.
1748 // We now store the raw data so that we are more flexible.
1749 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1752 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1759 * @brief processes and stores private messages
1761 * @param array $importer Array of the importer user
1762 * @param array $contact The contact of the message
1763 * @param object $data The message object
1764 * @param array $msg Array of the processed message, author handle and key
1765 * @param object $mesg The private message
1766 * @param array $conversation The conversation record to which this message belongs
1768 * @return bool "true" if it was successful
1770 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1772 $author = notags(unxmlify($data->author));
1773 $guid = notags(unxmlify($data->guid));
1774 $subject = notags(unxmlify($data->subject));
1776 // "diaspora_handle" is the element name from the old version
1777 // "author" is the element name from the new version
1778 if ($mesg->author) {
1779 $msg_author = notags(unxmlify($mesg->author));
1780 } elseif ($mesg->diaspora_handle) {
1781 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1786 $msg_guid = notags(unxmlify($mesg->guid));
1787 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1788 $msg_text = unxmlify($mesg->text);
1789 $msg_created_at = Temporal::convert(notags(unxmlify($mesg->created_at)));
1791 if ($msg_conversation_guid != $guid) {
1792 logger("message conversation guid does not belong to the current conversation.");
1796 $body = diaspora2bb($msg_text);
1797 $message_uri = $msg_author.":".$msg_guid;
1799 $person = self::personByHandle($msg_author);
1804 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1806 intval($importer["uid"])
1808 if (DBM::is_result($r)) {
1809 logger("duplicate message already delivered.", LOGGER_DEBUG);
1814 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1815 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1816 intval($importer["uid"]),
1818 intval($conversation["id"]),
1819 dbesc($person["name"]),
1820 dbesc($person["photo"]),
1821 dbesc($person["url"]),
1822 intval($contact["id"]),
1827 dbesc($message_uri),
1828 dbesc($author.":".$guid),
1829 dbesc($msg_created_at)
1834 dba::update('conv', ['updated' => Temporal::convert()], ['id' => $conversation["id"]]);
1838 "type" => NOTIFY_MAIL,
1839 "notify_flags" => $importer["notify-flags"],
1840 "language" => $importer["language"],
1841 "to_name" => $importer["username"],
1842 "to_email" => $importer["email"],
1843 "uid" =>$importer["uid"],
1844 "item" => ["subject" => $subject, "body" => $body],
1845 "source_name" => $person["name"],
1846 "source_link" => $person["url"],
1847 "source_photo" => $person["thumb"],
1848 "verb" => ACTIVITY_POST,
1855 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1857 * @param array $importer Array of the importer user
1858 * @param array $msg Array of the processed message, author handle and key
1859 * @param object $data The message object
1861 * @return bool Success
1863 private static function receiveConversation($importer, $msg, $data)
1865 $author = notags(unxmlify($data->author));
1866 $guid = notags(unxmlify($data->guid));
1867 $subject = notags(unxmlify($data->subject));
1868 $created_at = Temporal::convert(notags(unxmlify($data->created_at)));
1869 $participants = notags(unxmlify($data->participants));
1871 $messages = $data->message;
1873 if (!count($messages)) {
1874 logger("empty conversation");
1878 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1883 $conversation = null;
1886 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1887 intval($importer["uid"]),
1891 $conversation = $c[0];
1894 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1895 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1896 intval($importer["uid"]),
1900 dbesc(Temporal::convert()),
1902 dbesc($participants)
1906 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1907 intval($importer["uid"]),
1913 $conversation = $c[0];
1916 if (!$conversation) {
1917 logger("unable to create conversation.");
1921 foreach ($messages as $mesg) {
1922 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1929 * @brief Creates the body for a "like" message
1931 * @param array $contact The contact that send us the "like"
1932 * @param array $parent_item The item array of the parent item
1933 * @param string $guid message guid
1935 * @return string the body
1937 private static function constructLikeBody($contact, $parent_item, $guid)
1939 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1941 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1942 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1943 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
1945 return sprintf($bodyverb, $ulink, $alink, $plink);
1949 * @brief Creates a XML object for a "like"
1951 * @param array $importer Array of the importer user
1952 * @param array $parent_item The item array of the parent item
1954 * @return string The XML
1956 private static function constructLikeObject($importer, $parent_item)
1958 $objtype = ACTIVITY_OBJ_NOTE;
1959 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1960 $parent_body = $parent_item["body"];
1962 $xmldata = ["object" => ["type" => $objtype,
1964 "id" => $parent_item["uri"],
1967 "content" => $parent_body]];
1969 return XML::fromArray($xmldata, $xml, true);
1973 * @brief Processes "like" messages
1975 * @param array $importer Array of the importer user
1976 * @param string $sender The sender of the message
1977 * @param object $data The message object
1979 * @return int The message id of the generated like or "false" if there was an error
1981 private static function receiveLike($importer, $sender, $data)
1983 $author = notags(unxmlify($data->author));
1984 $guid = notags(unxmlify($data->guid));
1985 $parent_guid = notags(unxmlify($data->parent_guid));
1986 $parent_type = notags(unxmlify($data->parent_type));
1987 $positive = notags(unxmlify($data->positive));
1989 // likes on comments aren't supported by Diaspora - only on posts
1990 // But maybe this will be supported in the future, so we will accept it.
1991 if (!in_array($parent_type, ["Post", "Comment"])) {
1995 $contact = self::allowedContactByHandle($importer, $sender, true);
2000 $message_id = self::messageExists($importer["uid"], $guid);
2005 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2006 if (!$parent_item) {
2010 $person = self::personByHandle($author);
2011 if (!is_array($person)) {
2012 logger("unable to find author details");
2016 // Fetch the contact id - if we know this contact
2017 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2019 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2020 // We would accept this anyhow.
2021 if ($positive == "true") {
2022 $verb = ACTIVITY_LIKE;
2024 $verb = ACTIVITY_DISLIKE;
2029 $datarray["protocol"] = PROTOCOL_DIASPORA;
2031 $datarray["uid"] = $importer["uid"];
2032 $datarray["contact-id"] = $author_contact["cid"];
2033 $datarray["network"] = $author_contact["network"];
2035 $datarray["author-name"] = $person["name"];
2036 $datarray["author-link"] = $person["url"];
2037 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2039 $datarray["owner-name"] = $contact["name"];
2040 $datarray["owner-link"] = $contact["url"];
2041 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2043 $datarray["guid"] = $guid;
2044 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2046 $datarray["type"] = "activity";
2047 $datarray["verb"] = $verb;
2048 $datarray["gravity"] = GRAVITY_LIKE;
2049 $datarray["parent-uri"] = $parent_item["uri"];
2051 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2052 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2054 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2056 $message_id = Item::insert($datarray);
2058 if ($message_id <= 0) {
2063 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2066 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2067 if ($parent_item["id"] != $parent_item["parent"]) {
2068 $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2069 $origin = $toplevel["origin"];
2071 $origin = $parent_item["origin"];
2074 // If we are the origin of the parent we store the original data and notify our followers
2075 if ($message_id && $origin) {
2076 // Formerly we stored the signed text, the signature and the author in different fields.
2077 // We now store the raw data so that we are more flexible.
2078 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2081 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2088 * @brief Processes private messages
2090 * @param array $importer Array of the importer user
2091 * @param object $data The message object
2093 * @return bool Success?
2095 private static function receiveMessage($importer, $data)
2097 $author = notags(unxmlify($data->author));
2098 $guid = notags(unxmlify($data->guid));
2099 $conversation_guid = notags(unxmlify($data->conversation_guid));
2100 $text = unxmlify($data->text);
2101 $created_at = Temporal::convert(notags(unxmlify($data->created_at)));
2103 $contact = self::allowedContactByHandle($importer, $author, true);
2108 $conversation = null;
2111 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2112 intval($importer["uid"]),
2113 dbesc($conversation_guid)
2116 $conversation = $c[0];
2118 logger("conversation not available.");
2122 $message_uri = $author.":".$guid;
2124 $person = self::personByHandle($author);
2126 logger("unable to find author details");
2130 $body = diaspora2bb($text);
2132 $body = self::replacePeopleGuid($body, $person["url"]);
2137 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2139 intval($importer["uid"])
2141 if (DBM::is_result($r)) {
2142 logger("duplicate message already delivered.", LOGGER_DEBUG);
2147 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2148 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2149 intval($importer["uid"]),
2151 intval($conversation["id"]),
2152 dbesc($person["name"]),
2153 dbesc($person["photo"]),
2154 dbesc($person["url"]),
2155 intval($contact["id"]),
2156 dbesc($conversation["subject"]),
2160 dbesc($message_uri),
2161 dbesc($author.":".$conversation["guid"]),
2167 dba::update('conv', ['updated' => Temporal::convert()], ['id' => $conversation["id"]]);
2172 * @brief Processes participations - unsupported by now
2174 * @param array $importer Array of the importer user
2175 * @param object $data The message object
2177 * @return bool always true
2179 private static function receiveParticipation($importer, $data)
2181 $author = strtolower(notags(unxmlify($data->author)));
2182 $parent_guid = notags(unxmlify($data->parent_guid));
2184 $contact_id = Contact::getIdForURL($author);
2186 logger('Contact not found: '.$author);
2190 $person = self::personByHandle($author);
2191 if (!is_array($person)) {
2192 logger("Person not found: ".$author);
2196 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2197 if (!DBM::is_result($item)) {
2198 logger('Item not found, no origin or private: '.$parent_guid);
2202 $author_parts = explode('@', $author);
2203 if (isset($author_parts[1])) {
2204 $server = $author_parts[1];
2206 // Should never happen
2210 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2211 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2213 // Send all existing comments and likes to the requesting server
2214 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2216 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2217 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2218 while ($comment = dba::fetch($comments)) {
2219 if ($comment['verb'] == ACTIVITY_POST) {
2220 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2222 $cmd = $comment['self'] ? 'like' : 'comment-import';
2224 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2225 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2227 dba::close($comments);
2233 * @brief Processes photos - unneeded
2235 * @param array $importer Array of the importer user
2236 * @param object $data The message object
2238 * @return bool always true
2240 private static function receivePhoto($importer, $data)
2242 // There doesn't seem to be a reason for this function,
2243 // since the photo data is transmitted in the status message as well
2248 * @brief Processes poll participations - unssupported
2250 * @param array $importer Array of the importer user
2251 * @param object $data The message object
2253 * @return bool always true
2255 private static function receivePollParticipation($importer, $data)
2257 // We don't support polls by now
2262 * @brief Processes incoming profile updates
2264 * @param array $importer Array of the importer user
2265 * @param object $data The message object
2267 * @return bool Success
2269 private static function receiveProfile($importer, $data)
2271 $author = strtolower(notags(unxmlify($data->author)));
2273 $contact = self::contactByHandle($importer["uid"], $author);
2278 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2279 $image_url = unxmlify($data->image_url);
2280 $birthday = unxmlify($data->birthday);
2281 $gender = unxmlify($data->gender);
2282 $about = diaspora2bb(unxmlify($data->bio));
2283 $location = diaspora2bb(unxmlify($data->location));
2284 $searchable = (unxmlify($data->searchable) == "true");
2285 $nsfw = (unxmlify($data->nsfw) == "true");
2286 $tags = unxmlify($data->tag_string);
2288 $tags = explode("#", $tags);
2291 foreach ($tags as $tag) {
2292 $tag = trim(strtolower($tag));
2298 $keywords = implode(", ", $keywords);
2300 $handle_parts = explode("@", $author);
2301 $nick = $handle_parts[0];
2304 $name = $handle_parts[0];
2307 if (preg_match("|^https?://|", $image_url) === 0) {
2308 $image_url = "http://".$handle_parts[1].$image_url;
2311 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2313 // Generic birthday. We don't know the timezone. The year is irrelevant.
2315 $birthday = str_replace("1000", "1901", $birthday);
2317 if ($birthday != "") {
2318 $birthday = Temporal::convert($birthday, "UTC", "UTC", "Y-m-d");
2321 // this is to prevent multiple birthday notifications in a single year
2322 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2324 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2325 $birthday = $contact["bd"];
2329 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2330 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2334 dbesc(Temporal::convert()),
2340 intval($contact["id"]),
2341 intval($importer["uid"])
2344 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2345 "photo" => $image_url, "name" => $name, "location" => $location,
2346 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2347 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2348 "hide" => !$searchable, "nsfw" => $nsfw];
2350 $gcid = GContact::update($gcontact);
2352 GContact::link($gcid, $importer["uid"], $contact["id"]);
2354 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2360 * @brief Processes incoming friend requests
2362 * @param array $importer Array of the importer user
2363 * @param array $contact The contact that send the request
2366 private static function receiveRequestMakeFriend($importer, $contact)
2370 if ($contact["rel"] == CONTACT_IS_SHARING) {
2373 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2374 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2377 // send notification
2380 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2381 intval($importer["uid"])
2384 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2386 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2387 intval($importer["uid"])
2390 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2392 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2394 $arr["protocol"] = PROTOCOL_DIASPORA;
2395 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2396 $arr["uid"] = $importer["uid"];
2397 $arr["contact-id"] = $self[0]["id"];
2399 $arr["type"] = 'wall';
2400 $arr["gravity"] = 0;
2402 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2403 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2404 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2405 $arr["verb"] = ACTIVITY_FRIEND;
2406 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2408 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2409 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2410 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2411 $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
2413 $arr["object"] = self::constructNewFriendObject($contact);
2415 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2417 $arr["allow_cid"] = $user["allow_cid"];
2418 $arr["allow_gid"] = $user["allow_gid"];
2419 $arr["deny_cid"] = $user["deny_cid"];
2420 $arr["deny_gid"] = $user["deny_gid"];
2422 $i = Item::insert($arr);
2424 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2431 * @brief Creates a XML object for a "new friend" message
2433 * @param array $contact Array of the contact
2435 * @return string The XML
2437 private static function constructNewFriendObject($contact)
2439 $objtype = ACTIVITY_OBJ_PERSON;
2440 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2441 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2443 $xmldata = ["object" => ["type" => $objtype,
2444 "title" => $contact["name"],
2445 "id" => $contact["url"]."/".$contact["name"],
2448 return XML::fromArray($xmldata, $xml, true);
2452 * @brief Processes incoming sharing notification
2454 * @param array $importer Array of the importer user
2455 * @param object $data The message object
2457 * @return bool Success
2459 private static function receiveContactRequest($importer, $data)
2461 $author = unxmlify($data->author);
2462 $recipient = unxmlify($data->recipient);
2464 if (!$author || !$recipient) {
2468 // the current protocol version doesn't know these fields
2469 // That means that we will assume their existance
2470 if (isset($data->following)) {
2471 $following = (unxmlify($data->following) == "true");
2476 if (isset($data->sharing)) {
2477 $sharing = (unxmlify($data->sharing) == "true");
2482 $contact = self::contactByHandle($importer["uid"], $author);
2484 // perhaps we were already sharing with this person. Now they're sharing with us.
2485 // That makes us friends.
2488 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2489 self::receiveRequestMakeFriend($importer, $contact);
2491 // refetch the contact array
2492 $contact = self::contactByHandle($importer["uid"], $author);
2494 // If we are now friends, we are sending a share message.
2495 // Normally we needn't to do so, but the first message could have been vanished.
2496 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2497 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2499 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2500 $ret = self::sendShare($u[0], $contact);
2505 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2506 Contact::removeFollower($importer, $contact);
2511 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2512 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2514 } elseif (!$following && !$sharing) {
2515 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2517 } elseif (!$following && $sharing) {
2518 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2519 } elseif ($following && $sharing) {
2520 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2521 } elseif ($following && !$sharing) {
2522 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2525 $ret = self::personByHandle($author);
2527 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2528 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2532 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2535 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2536 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2537 intval($importer["uid"]),
2538 dbesc($ret["network"]),
2539 dbesc($ret["addr"]),
2540 Temporal::convert(),
2542 dbesc(normalise_link($ret["url"])),
2544 dbesc($ret["name"]),
2545 dbesc($ret["nick"]),
2546 dbesc($ret["photo"]),
2547 dbesc($ret["pubkey"]),
2548 dbesc($ret["notify"]),
2549 dbesc($ret["poll"]),
2554 // find the contact record we just created
2556 $contact_record = self::contactByHandle($importer["uid"], $author);
2558 if (!$contact_record) {
2559 logger("unable to locate newly created contact record.");
2563 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2565 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2567 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2569 if ($importer["page-flags"] == PAGE_NORMAL) {
2570 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2572 $hash = random_string().(string)time(); // Generate a confirm_key
2575 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2576 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2577 intval($importer["uid"]),
2578 intval($contact_record["id"]),
2581 dbesc(L10n::t("Sharing notification from Diaspora network")),
2583 dbesc(Temporal::convert())
2586 // automatic friend approval
2588 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2590 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2592 // technically they are sharing with us (CONTACT_IS_SHARING),
2593 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2594 // we are going to change the relationship and make them a follower.
2596 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2597 $new_relation = CONTACT_IS_FRIEND;
2598 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2599 $new_relation = CONTACT_IS_SHARING;
2601 $new_relation = CONTACT_IS_FOLLOWER;
2605 "UPDATE `contact` SET `rel` = %d,
2613 intval($new_relation),
2614 dbesc(Temporal::convert()),
2615 dbesc(Temporal::convert()),
2616 intval($contact_record["id"])
2619 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2621 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2622 $ret = self::sendShare($u[0], $contact_record);
2624 // Send the profile data, maybe it weren't transmitted before
2625 self::sendProfile($importer["uid"], [$contact_record]);
2633 * @brief Fetches a message with a given guid
2635 * @param string $guid message guid
2636 * @param string $orig_author handle of the original post
2637 * @param string $author handle of the sharer
2639 * @return array The fetched item
2641 private static function originalItem($guid, $orig_author, $author)
2643 // Do we already have this item?
2645 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2646 `author-name`, `author-link`, `author-avatar`
2647 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2651 if (DBM::is_result($r)) {
2652 logger("reshared message ".$guid." already exists on system.");
2654 // Maybe it is already a reshared item?
2655 // Then refetch the content, if it is a reshare from a reshare.
2656 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2657 if (self::isReshare($r[0]["body"], true)) {
2659 } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2660 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2662 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2664 // Add OEmbed and other information to the body
2665 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2673 if (!DBM::is_result($r)) {
2674 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2675 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2676 $item_id = self::storeByGuid($guid, $server);
2679 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2680 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2681 $item_id = self::storeByGuid($guid, $server);
2686 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2687 `author-name`, `author-link`, `author-avatar`
2688 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2692 if (DBM::is_result($r)) {
2693 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2694 if (self::isReshare($r[0]["body"], false)) {
2695 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2696 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2707 * @brief Processes a reshare message
2709 * @param array $importer Array of the importer user
2710 * @param object $data The message object
2711 * @param string $xml The original XML of the message
2713 * @return int the message id
2715 private static function receiveReshare($importer, $data, $xml)
2717 $author = notags(unxmlify($data->author));
2718 $guid = notags(unxmlify($data->guid));
2719 $created_at = Temporal::convert(notags(unxmlify($data->created_at)));
2720 $root_author = notags(unxmlify($data->root_author));
2721 $root_guid = notags(unxmlify($data->root_guid));
2722 /// @todo handle unprocessed property "provider_display_name"
2723 $public = notags(unxmlify($data->public));
2725 $contact = self::allowedContactByHandle($importer, $author, false);
2730 $message_id = self::messageExists($importer["uid"], $guid);
2735 $original_item = self::originalItem($root_guid, $root_author, $author);
2736 if (!$original_item) {
2740 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2744 $datarray["uid"] = $importer["uid"];
2745 $datarray["contact-id"] = $contact["id"];
2746 $datarray["network"] = NETWORK_DIASPORA;
2748 $datarray["author-name"] = $contact["name"];
2749 $datarray["author-link"] = $contact["url"];
2750 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2752 $datarray["owner-name"] = $datarray["author-name"];
2753 $datarray["owner-link"] = $datarray["author-link"];
2754 $datarray["owner-avatar"] = $datarray["author-avatar"];
2756 $datarray["guid"] = $guid;
2757 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2759 $datarray["verb"] = ACTIVITY_POST;
2760 $datarray["gravity"] = GRAVITY_PARENT;
2762 $datarray["protocol"] = PROTOCOL_DIASPORA;
2763 $datarray["source"] = $xml;
2765 $prefix = share_header(
2766 $original_item["author-name"],
2767 $original_item["author-link"],
2768 $original_item["author-avatar"],
2769 $original_item["guid"],
2770 $original_item["created"],
2773 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2775 $datarray["tag"] = $original_item["tag"];
2776 $datarray["app"] = $original_item["app"];
2778 $datarray["plink"] = self::plink($author, $guid);
2779 $datarray["private"] = (($public == "false") ? 1 : 0);
2780 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2782 $datarray["object-type"] = $original_item["object-type"];
2784 self::fetchGuid($datarray);
2785 $message_id = Item::insert($datarray);
2787 self::sendParticipation($contact, $datarray);
2790 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2798 * @brief Processes retractions
2800 * @param array $importer Array of the importer user
2801 * @param array $contact The contact of the item owner
2802 * @param object $data The message object
2804 * @return bool success
2806 private static function itemRetraction($importer, $contact, $data)
2808 $author = notags(unxmlify($data->author));
2809 $target_guid = notags(unxmlify($data->target_guid));
2810 $target_type = notags(unxmlify($data->target_type));
2812 $person = self::personByHandle($author);
2813 if (!is_array($person)) {
2814 logger("unable to find author detail for ".$author);
2818 if (empty($contact["url"])) {
2819 $contact["url"] = $person["url"];
2822 // Fetch items that are about to be deleted
2823 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2825 // When we receive a public retraction, we delete every item that we find.
2826 if ($importer['uid'] == 0) {
2827 $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2829 $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2831 $r = dba::select('item', $fields, $condition);
2832 if (!DBM::is_result($r)) {
2833 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2837 while ($item = dba::fetch($r)) {
2838 // Fetch the parent item
2839 $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2841 // Only delete it if the parent author really fits
2842 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2843 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2847 // Currently we don't have a central deletion function that we could use in this case.
2848 // The function "item_drop" doesn't work for that case
2855 'edited' => Temporal::convert(),
2856 'changed' => Temporal::convert()],
2857 ['id' => $item["id"]]
2860 // Delete the thread - if it is a starting post and not a comment
2861 if ($target_type != 'Comment') {
2862 delete_thread($item["id"], $item["parent-uri"]);
2865 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2867 // Now check if the retraction needs to be relayed by us
2868 if ($parent["origin"]) {
2870 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2878 * @brief Receives retraction messages
2880 * @param array $importer Array of the importer user
2881 * @param string $sender The sender of the message
2882 * @param object $data The message object
2884 * @return bool Success
2886 private static function receiveRetraction($importer, $sender, $data)
2888 $target_type = notags(unxmlify($data->target_type));
2890 $contact = self::contactByHandle($importer["uid"], $sender);
2891 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2892 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2896 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2898 switch ($target_type) {
2903 case "StatusMessage":
2904 return self::itemRetraction($importer, $contact, $data);
2908 /// @todo What should we do with an "unshare"?
2909 // Removing the contact isn't correct since we still can read the public items
2910 Contact::remove($contact["id"]);
2914 logger("Unknown target type ".$target_type);
2921 * @brief Receives status messages
2923 * @param array $importer Array of the importer user
2924 * @param object $data The message object
2925 * @param string $xml The original XML of the message
2927 * @return int The message id of the newly created item
2929 private static function receiveStatusMessage($importer, $data, $xml)
2931 $author = notags(unxmlify($data->author));
2932 $guid = notags(unxmlify($data->guid));
2933 $created_at = Temporal::convert(notags(unxmlify($data->created_at)));
2934 $public = notags(unxmlify($data->public));
2935 $text = unxmlify($data->text);
2936 $provider_display_name = notags(unxmlify($data->provider_display_name));
2938 $contact = self::allowedContactByHandle($importer, $author, false);
2943 $message_id = self::messageExists($importer["uid"], $guid);
2949 if ($data->location) {
2950 foreach ($data->location->children() as $fieldname => $data) {
2951 $address[$fieldname] = notags(unxmlify($data));
2955 $body = diaspora2bb($text);
2959 // Attach embedded pictures to the body
2961 foreach ($data->photo as $photo) {
2962 $body = "[img]".unxmlify($photo->remote_photo_path).
2963 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2966 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2968 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2970 // Add OEmbed and other information to the body
2971 if (!self::isRedmatrix($contact["url"])) {
2972 $body = add_page_info_to_body($body, false, true);
2976 /// @todo enable support for polls
2977 //if ($data->poll) {
2978 // foreach ($data->poll AS $poll)
2983 /// @todo enable support for events
2985 $datarray["uid"] = $importer["uid"];
2986 $datarray["contact-id"] = $contact["id"];
2987 $datarray["network"] = NETWORK_DIASPORA;
2989 $datarray["author-name"] = $contact["name"];
2990 $datarray["author-link"] = $contact["url"];
2991 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2993 $datarray["owner-name"] = $datarray["author-name"];
2994 $datarray["owner-link"] = $datarray["author-link"];
2995 $datarray["owner-avatar"] = $datarray["author-avatar"];
2997 $datarray["guid"] = $guid;
2998 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
3000 $datarray["verb"] = ACTIVITY_POST;
3001 $datarray["gravity"] = GRAVITY_PARENT;
3003 $datarray["protocol"] = PROTOCOL_DIASPORA;
3004 $datarray["source"] = $xml;
3006 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3008 if ($provider_display_name != "") {
3009 $datarray["app"] = $provider_display_name;
3012 $datarray["plink"] = self::plink($author, $guid);
3013 $datarray["private"] = (($public == "false") ? 1 : 0);
3014 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3016 if (isset($address["address"])) {
3017 $datarray["location"] = $address["address"];
3020 if (isset($address["lat"]) && isset($address["lng"])) {
3021 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3024 self::fetchGuid($datarray);
3025 $message_id = Item::insert($datarray);
3027 self::sendParticipation($contact, $datarray);
3030 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3037 /* ************************************************************************************** *
3038 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3039 * ************************************************************************************** */
3042 * @brief returnes the handle of a contact
3044 * @param array $contact contact array
3046 * @return string the handle in the format user@domain.tld
3048 private static function myHandle($contact)
3050 if ($contact["addr"] != "") {
3051 return $contact["addr"];
3054 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3055 // So - just in case - we build the the address here.
3056 if ($contact["nickname"] != "") {
3057 $nick = $contact["nickname"];
3059 $nick = $contact["nick"];
3062 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3067 * @brief Creates the data for a private message in the new format
3069 * @param string $msg The message that is to be transmitted
3070 * @param array $user The record of the sender
3071 * @param array $contact Target of the communication
3072 * @param string $prvkey The private key of the sender
3073 * @param string $pubkey The public key of the receiver
3075 * @return string The encrypted data
3077 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3079 logger("Message: ".$msg, LOGGER_DATA);
3081 // without a public key nothing will work
3083 logger("pubkey missing: contact id: ".$contact["id"]);
3087 $aes_key = openssl_random_pseudo_bytes(32);
3088 $b_aes_key = base64_encode($aes_key);
3089 $iv = openssl_random_pseudo_bytes(16);
3090 $b_iv = base64_encode($iv);
3092 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3094 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3096 $encrypted_key_bundle = "";
3097 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3099 $json_object = json_encode(
3100 ["aes_key" => base64_encode($encrypted_key_bundle),
3101 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3104 return $json_object;
3108 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3110 * @param string $msg The message that is to be transmitted
3111 * @param array $user The record of the sender
3113 * @return string The envelope
3115 public static function buildMagicEnvelope($msg, $user)
3117 $b64url_data = base64url_encode($msg);
3118 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3120 $key_id = base64url_encode(self::myHandle($user));
3121 $type = "application/xml";
3122 $encoding = "base64url";
3123 $alg = "RSA-SHA256";
3124 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3126 // Fallback if the private key wasn't transmitted in the expected field
3127 if ($user['uprvkey'] == "") {
3128 $user['uprvkey'] = $user['prvkey'];
3131 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3132 $sig = base64url_encode($signature);
3134 $xmldata = ["me:env" => ["me:data" => $data,
3135 "@attributes" => ["type" => $type],
3136 "me:encoding" => $encoding,
3139 "@attributes2" => ["key_id" => $key_id]]];
3141 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3143 return XML::fromArray($xmldata, $xml, false, $namespaces);
3147 * @brief Create the envelope for a message
3149 * @param string $msg The message that is to be transmitted
3150 * @param array $user The record of the sender
3151 * @param array $contact Target of the communication
3152 * @param string $prvkey The private key of the sender
3153 * @param string $pubkey The public key of the receiver
3154 * @param bool $public Is the message public?
3156 * @return string The message that will be transmitted to other servers
3158 private static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3160 // The message is put into an envelope with the sender's signature
3161 $envelope = self::buildMagicEnvelope($msg, $user);
3163 // Private messages are put into a second envelope, encrypted with the receivers public key
3165 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3172 * @brief Creates a signature for a message
3174 * @param array $owner the array of the owner of the message
3175 * @param array $message The message that is to be signed
3177 * @return string The signature
3179 private static function signature($owner, $message)
3182 unset($sigmsg["author_signature"]);
3183 unset($sigmsg["parent_author_signature"]);
3185 $signed_text = implode(";", $sigmsg);
3187 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3191 * @brief Transmit a message to a target server
3193 * @param array $owner the array of the item owner
3194 * @param array $contact Target of the communication
3195 * @param string $envelope The message that is to be transmitted
3196 * @param bool $public_batch Is it a public post?
3197 * @param bool $queue_run Is the transmission called from the queue?
3198 * @param string $guid message guid
3200 * @return int Result of the transmission
3202 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "")
3206 $enabled = intval(Config::get("system", "diaspora_enabled"));
3211 $logid = random_string(4);
3212 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3214 // Fetch the fcontact entry when there is missing data
3215 // Will possibly happen when data is transmitted to a DFRN contact
3216 if (empty($dest_url) && !empty($contact['addr'])) {
3217 $fcontact = self::personByHandle($contact['addr']);
3218 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3222 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3226 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3228 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3231 if (!intval(Config::get("system", "diaspora_test"))) {
3232 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3234 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3235 $return_code = $a->get_curl_code();
3237 logger("test_mode");
3242 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3244 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3245 logger("queue message");
3248 "SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
3249 intval($contact["id"]),
3250 dbesc(NETWORK_DIASPORA),
3252 intval($public_batch)
3255 logger("add_to_queue ignored - identical item already in queue");
3257 // queue message for redelivery
3258 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch);
3260 // The message could not be delivered. We mark the contact as "dead"
3261 Contact::markForArchival($contact);
3263 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3264 // We successfully delivered a message, the contact is alive
3265 Contact::unmarkForArchival($contact);
3268 return(($return_code) ? $return_code : (-1));
3273 * @brief Build the post xml
3275 * @param string $type The message type
3276 * @param array $message The message data
3278 * @return string The post XML
3280 public static function buildPostXml($type, $message)
3282 $data = [$type => $message];
3284 return XML::fromArray($data, $xml);
3288 * @brief Builds and transmit messages
3290 * @param array $owner the array of the item owner
3291 * @param array $contact Target of the communication
3292 * @param string $type The message type
3293 * @param array $message The message data
3294 * @param bool $public_batch Is it a public post?
3295 * @param string $guid message guid
3296 * @param bool $spool Should the transmission be spooled or transmitted?
3298 * @return int Result of the transmission
3300 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3302 $msg = self::buildPostXml($type, $message);
3304 logger('message: '.$msg, LOGGER_DATA);
3305 logger('send guid '.$guid, LOGGER_DEBUG);
3307 // Fallback if the private key wasn't transmitted in the expected field
3308 if ($owner['uprvkey'] == "") {
3309 $owner['uprvkey'] = $owner['prvkey'];
3312 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3315 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch);
3318 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3321 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3323 return $return_code;
3327 * @brief sends a participation (Used to get all further updates)
3329 * @param array $contact Target of the communication
3330 * @param array $item Item array
3332 * @return int The result of the transmission
3334 private static function sendParticipation($contact, $item)
3336 // Don't send notifications for private postings
3337 if ($item['private']) {
3341 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3343 $result = Cache::get($cachekey);
3344 if (!is_null($result)) {
3348 // Fetch some user id to have a valid handle to transmit the participation.
3349 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3350 // If the item belongs to a user, we take this user id.
3351 if ($item['uid'] == 0) {
3352 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3353 $first_user = dba::selectFirst('user', ['uid'], $condition);
3354 $owner = User::getOwnerDataById($first_user['uid']);
3356 $owner = User::getOwnerDataById($item['uid']);
3359 $author = self::myHandle($owner);
3361 $message = ["author" => $author,
3362 "guid" => get_guid(32),
3363 "parent_type" => "Post",
3364 "parent_guid" => $item["guid"]];
3366 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3368 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3369 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3371 return self::buildAndTransmit($owner, $contact, "participation", $message);
3375 * @brief sends an account migration
3377 * @param array $owner the array of the item owner
3378 * @param array $contact Target of the communication
3379 * @param int $uid User ID
3381 * @return int The result of the transmission
3383 public static function sendAccountMigration($owner, $contact, $uid)
3385 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3386 $profile = self::createProfileData($uid);
3388 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3389 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3391 $message = ["author" => $old_handle,
3392 "profile" => $profile,
3393 "signature" => $signature];
3395 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3397 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3401 * @brief Sends a "share" message
3403 * @param array $owner the array of the item owner
3404 * @param array $contact Target of the communication
3406 * @return int The result of the transmission
3408 public static function sendShare($owner, $contact)
3411 * @todo support the different possible combinations of "following" and "sharing"
3412 * Currently, Diaspora only interprets the "sharing" field
3414 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3418 switch ($contact["rel"]) {
3419 case CONTACT_IS_FRIEND:
3422 case CONTACT_IS_SHARING:
3425 case CONTACT_IS_FOLLOWER:
3431 $message = ["author" => self::myHandle($owner),
3432 "recipient" => $contact["addr"],
3433 "following" => "true",
3434 "sharing" => "true"];
3436 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3438 return self::buildAndTransmit($owner, $contact, "contact", $message);
3442 * @brief sends an "unshare"
3444 * @param array $owner the array of the item owner
3445 * @param array $contact Target of the communication
3447 * @return int The result of the transmission
3449 public static function sendUnshare($owner, $contact)
3451 $message = ["author" => self::myHandle($owner),
3452 "recipient" => $contact["addr"],
3453 "following" => "false",
3454 "sharing" => "false"];
3456 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3458 return self::buildAndTransmit($owner, $contact, "contact", $message);
3462 * @brief Checks a message body if it is a reshare
3464 * @param string $body The message body that is to be check
3465 * @param bool $complete Should it be a complete check or a simple check?
3467 * @return array|bool Reshare details or "false" if no reshare
3469 public static function isReshare($body, $complete = true)
3471 $body = trim($body);
3473 // Skip if it isn't a pure repeated messages
3474 // Does it start with a share?
3475 if ((strpos($body, "[share") > 0) && $complete) {
3479 // Does it end with a share?
3480 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3484 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3485 // Skip if there is no shared message in there
3486 if ($body == $attributes) {
3490 // If we don't do the complete check we quit here
3496 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3497 if ($matches[1] != "") {
3498 $guid = $matches[1];
3501 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3502 if ($matches[1] != "") {
3503 $guid = $matches[1];
3508 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3515 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3516 $ret["root_guid"] = $guid;
3522 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3523 if ($matches[1] != "") {
3524 $profile = $matches[1];
3527 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3528 if ($matches[1] != "") {
3529 $profile = $matches[1];
3534 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3535 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3540 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3541 if ($matches[1] != "") {
3542 $link = $matches[1];
3545 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3546 if ($matches[1] != "") {
3547 $link = $matches[1];
3550 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3551 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3559 * @brief Create an event array
3561 * @param integer $event_id The id of the event
3563 * @return array with event data
3565 private static function buildEvent($event_id)
3567 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3568 if (!DBM::is_result($r)) {
3576 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3577 if (!DBM::is_result($r)) {
3583 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3584 if (!DBM::is_result($r)) {
3590 $eventdata['author'] = self::myHandle($owner);
3592 if ($event['guid']) {
3593 $eventdata['guid'] = $event['guid'];
3596 $mask = 'Y-m-d\TH:i:s\Z';
3598 /// @todo - establish "all day" events in Friendica
3599 $eventdata["all_day"] = "false";
3601 if (!$event['adjust']) {
3602 $eventdata['timezone'] = $user['timezone'];
3604 if ($eventdata['timezone'] == "") {
3605 $eventdata['timezone'] = 'UTC';
3609 if ($event['start']) {
3610 $eventdata['start'] = Temporal::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3612 if ($event['finish'] && !$event['nofinish']) {
3613 $eventdata['end'] = Temporal::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3615 if ($event['summary']) {
3616 $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3618 if ($event['desc']) {
3619 $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3621 if ($event['location']) {
3623 $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3624 $location["lat"] = 0;
3625 $location["lng"] = 0;
3626 $eventdata['location'] = $location;
3633 * @brief Create a post (status message or reshare)
3635 * @param array $item The item that will be exported
3636 * @param array $owner the array of the item owner
3639 * 'type' -> Message type ("status_message" or "reshare")
3640 * 'message' -> Array of XML elements of the status
3642 public static function buildStatus($item, $owner)
3644 $cachekey = "diaspora:buildStatus:".$item['guid'];
3646 $result = Cache::get($cachekey);
3647 if (!is_null($result)) {
3651 $myaddr = self::myHandle($owner);
3653 $public = (($item["private"]) ? "false" : "true");
3655 $created = Temporal::convert($item["created"], "UTC", "UTC", 'Y-m-d\TH:i:s\Z');
3657 // Detect a share element and do a reshare
3658 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3659 $message = ["author" => $myaddr,
3660 "guid" => $item["guid"],
3661 "created_at" => $created,
3662 "root_author" => $ret["root_handle"],
3663 "root_guid" => $ret["root_guid"],
3664 "provider_display_name" => $item["app"],
3665 "public" => $public];
3669 $title = $item["title"];
3670 $body = $item["body"];
3672 // convert to markdown
3673 $body = html_entity_decode(bb2diaspora($body));
3676 if (strlen($title)) {
3677 $body = "## ".html_entity_decode($title)."\n\n".$body;
3680 if ($item["attach"]) {
3681 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3683 $body .= "\n".L10n::t("Attachments:")."\n";
3684 foreach ($matches as $mtch) {
3685 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3692 if ($item["location"] != "")
3693 $location["address"] = $item["location"];
3695 if ($item["coord"] != "") {
3696 $coord = explode(" ", $item["coord"]);
3697 $location["lat"] = $coord[0];
3698 $location["lng"] = $coord[1];
3701 $message = ["author" => $myaddr,
3702 "guid" => $item["guid"],
3703 "created_at" => $created,
3704 "public" => $public,
3706 "provider_display_name" => $item["app"],
3707 "location" => $location];
3709 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3710 if (!isset($location["lat"]) || !isset($location["lng"])) {
3711 unset($message["location"]);
3714 if ($item['event-id'] > 0) {
3715 $event = self::buildEvent($item['event-id']);
3716 if (count($event)) {
3717 $message['event'] = $event;
3719 /// @todo Once Diaspora supports it, we will remove the body
3720 // $message['text'] = '';
3724 $type = "status_message";
3727 $msg = ["type" => $type, "message" => $message];
3729 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3735 * @brief Sends a post
3737 * @param array $item The item that will be exported
3738 * @param array $owner the array of the item owner
3739 * @param array $contact Target of the communication
3740 * @param bool $public_batch Is it a public post?
3742 * @return int The result of the transmission
3744 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3746 $status = self::buildStatus($item, $owner);
3748 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3752 * @brief Creates a "like" object
3754 * @param array $item The item that will be exported
3755 * @param array $owner the array of the item owner
3757 * @return array The data for a "like"
3759 private static function constructLike($item, $owner)
3762 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3763 dbesc($item["thr-parent"])
3765 if (!DBM::is_result($p)) {
3771 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3772 if ($item['verb'] === ACTIVITY_LIKE) {
3774 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3775 $positive = "false";
3778 return(["author" => self::myHandle($owner),
3779 "guid" => $item["guid"],
3780 "parent_guid" => $parent["guid"],
3781 "parent_type" => $target_type,
3782 "positive" => $positive,
3783 "author_signature" => ""]);
3787 * @brief Creates an "EventParticipation" object
3789 * @param array $item The item that will be exported
3790 * @param array $owner the array of the item owner
3792 * @return array The data for an "EventParticipation"
3794 private static function constructAttend($item, $owner)
3797 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3798 dbesc($item["thr-parent"])
3800 if (!DBM::is_result($p)) {
3806 switch ($item['verb']) {
3807 case ACTIVITY_ATTEND:
3808 $attend_answer = 'accepted';
3810 case ACTIVITY_ATTENDNO:
3811 $attend_answer = 'declined';
3813 case ACTIVITY_ATTENDMAYBE:
3814 $attend_answer = 'tentative';
3817 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3821 return(["author" => self::myHandle($owner),
3822 "guid" => $item["guid"],
3823 "parent_guid" => $parent["guid"],
3824 "status" => $attend_answer,
3825 "author_signature" => ""]);
3829 * @brief Creates the object for a comment
3831 * @param array $item The item that will be exported
3832 * @param array $owner the array of the item owner
3834 * @return array The data for a comment
3836 private static function constructComment($item, $owner)
3838 $cachekey = "diaspora:constructComment:".$item['guid'];
3840 $result = Cache::get($cachekey);
3841 if (!is_null($result)) {
3846 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3847 intval($item["parent"]),
3848 intval($item["parent"])
3851 if (!DBM::is_result($p)) {
3857 $text = html_entity_decode(bb2diaspora($item["body"]));
3858 $created = Temporal::convert($item["created"], "UTC", "UTC", 'Y-m-d\TH:i:s\Z');
3860 $comment = ["author" => self::myHandle($owner),
3861 "guid" => $item["guid"],
3862 "created_at" => $created,
3863 "parent_guid" => $parent["guid"],
3865 "author_signature" => ""];
3867 // Send the thread parent guid only if it is a threaded comment
3868 if ($item['thr-parent'] != $item['parent-uri']) {
3869 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3872 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3878 * @brief Send a like or a comment
3880 * @param array $item The item that will be exported
3881 * @param array $owner the array of the item owner
3882 * @param array $contact Target of the communication
3883 * @param bool $public_batch Is it a public post?
3885 * @return int The result of the transmission
3887 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3889 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3890 $message = self::constructAttend($item, $owner);
3891 $type = "event_participation";
3892 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3893 $message = self::constructLike($item, $owner);
3896 $message = self::constructComment($item, $owner);
3904 $message["author_signature"] = self::signature($owner, $message);
3906 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3910 * @brief Creates a message from a signature record entry
3912 * @param array $item The item that will be exported
3913 * @param array $signature The entry of the "sign" record
3915 * @return string The message
3917 private static function messageFromSignature($item, $signature)
3919 // Split the signed text
3920 $signed_parts = explode(";", $signature['signed_text']);
3922 if ($item["deleted"]) {
3923 $message = ["author" => $signature['signer'],
3924 "target_guid" => $signed_parts[0],
3925 "target_type" => $signed_parts[1]];
3926 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3927 $message = ["author" => $signed_parts[4],
3928 "guid" => $signed_parts[1],
3929 "parent_guid" => $signed_parts[3],
3930 "parent_type" => $signed_parts[2],
3931 "positive" => $signed_parts[0],
3932 "author_signature" => $signature['signature'],
3933 "parent_author_signature" => ""];
3935 // Remove the comment guid
3936 $guid = array_shift($signed_parts);
3938 // Remove the parent guid
3939 $parent_guid = array_shift($signed_parts);
3941 // Remove the handle
3942 $handle = array_pop($signed_parts);
3944 // Glue the parts together
3945 $text = implode(";", $signed_parts);
3947 $message = ["author" => $handle,
3949 "parent_guid" => $parent_guid,
3950 "text" => implode(";", $signed_parts),
3951 "author_signature" => $signature['signature'],
3952 "parent_author_signature" => ""];
3958 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3960 * @param array $item The item that will be exported
3961 * @param array $owner the array of the item owner
3962 * @param array $contact Target of the communication
3963 * @param bool $public_batch Is it a public post?
3965 * @return int The result of the transmission
3967 public static function sendRelay($item, $owner, $contact, $public_batch = false)
3969 if ($item["deleted"]) {
3970 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3971 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3977 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3979 // fetch the original signature
3982 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3987 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3993 // Old way - is used by the internal Friendica functions
3994 /// @todo Change all signatur storing functions to the new format
3995 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3996 $message = self::messageFromSignature($item, $signature);
3998 $msg = json_decode($signature['signed_text'], true);
4001 if (is_array($msg)) {
4002 foreach ($msg as $field => $data) {
4003 if (!$item["deleted"]) {
4004 if ($field == "diaspora_handle") {
4007 if ($field == "target_type") {
4008 $field = "parent_type";
4012 $message[$field] = $data;
4015 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
4019 $message["parent_author_signature"] = self::signature($owner, $message);
4021 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
4023 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4027 * @brief Sends a retraction (deletion) of a message, like or comment
4029 * @param array $item The item that will be exported
4030 * @param array $owner the array of the item owner
4031 * @param array $contact Target of the communication
4032 * @param bool $public_batch Is it a public post?
4033 * @param bool $relay Is the retraction transmitted from a relay?
4035 * @return int The result of the transmission
4037 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4039 $itemaddr = self::handleFromContact($item["contact-id"], $item["gcontact-id"]);
4041 $msg_type = "retraction";
4043 if ($item['id'] == $item['parent']) {
4044 $target_type = "Post";
4045 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4046 $target_type = "Like";
4048 $target_type = "Comment";
4051 $message = ["author" => $itemaddr,
4052 "target_guid" => $item['guid'],
4053 "target_type" => $target_type];
4055 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4057 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4061 * @brief Sends a mail
4063 * @param array $item The item that will be exported
4064 * @param array $owner The owner
4065 * @param array $contact Target of the communication
4067 * @return int The result of the transmission
4069 public static function sendMail($item, $owner, $contact)
4071 $myaddr = self::myHandle($owner);
4074 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4075 intval($item["convid"]),
4076 intval($item["uid"])
4079 if (!DBM::is_result($r)) {
4080 logger("conversation not found.");
4086 "author" => $cnv["creator"],
4087 "guid" => $cnv["guid"],
4088 "subject" => $cnv["subject"],
4089 "created_at" => Temporal::convert($cnv['created'], "UTC", "UTC", 'Y-m-d\TH:i:s\Z'),
4090 "participants" => $cnv["recips"]
4093 $body = bb2diaspora($item["body"]);
4094 $created = Temporal::convert($item["created"], "UTC", "UTC", 'Y-m-d\TH:i:s\Z');
4097 "author" => $myaddr,
4098 "guid" => $item["guid"],
4099 "conversation_guid" => $cnv["guid"],
4101 "created_at" => $created,
4104 if ($item["reply"]) {
4109 "author" => $cnv["creator"],
4110 "guid" => $cnv["guid"],
4111 "subject" => $cnv["subject"],
4112 "created_at" => Temporal::convert($cnv['created'], "UTC", "UTC", 'Y-m-d\TH:i:s\Z'),
4113 "participants" => $cnv["recips"],
4116 $type = "conversation";
4119 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4123 * @brief Split a name into first name and last name
4125 * @param string $name The name
4127 * @return array The array with "first" and "last"
4129 public static function splitName($name) {
4130 $name = trim($name);
4132 // Is the name longer than 64 characters? Then cut the rest of it.
4133 if (strlen($name) > 64) {
4134 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4135 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4137 $name = substr($name, 0, 64);
4141 // Take the first word as first name
4142 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4143 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4144 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4145 return ['first' => $first, 'last' => $last];
4148 // Take the last word as last name
4149 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4150 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4152 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4153 return ['first' => $first, 'last' => $last];
4156 // Take the first 32 characters if there is no space in the first 32 characters
4157 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4158 $first = substr($name, 0, 32);
4159 $last = substr($name, 32);
4160 return ['first' => $first, 'last' => $last];
4163 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4164 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4166 // Check if the last name is longer than 32 characters
4167 if (strlen($last) > 32) {
4168 if (strpos($last, ' ') <= 32) {
4169 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4171 $last = substr($last, 0, 32);
4175 return ['first' => $first, 'last' => $last];
4179 * @brief Create profile data
4181 * @param int $uid The user id
4183 * @return array The profile data
4185 private static function createProfileData($uid)
4188 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4190 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4191 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4192 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4201 $handle = $profile["addr"];
4203 $split_name = self::splitName($profile['name']);
4204 $first = $split_name['first'];
4205 $last = $split_name['last'];
4207 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4208 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4209 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4210 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4212 if ($searchable === 'true') {
4215 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4216 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4220 $dob = Temporal::convert($year . '-' . $month . '-'. $day, 'UTC', 'UTC', 'Y-m-d');
4223 $about = $profile['about'];
4224 $about = strip_tags(bbcode($about));
4226 $location = Profile::formatLocation($profile);
4228 if ($profile['pub_keywords']) {
4229 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4230 $kw = str_replace(' ', ' ', $kw);
4231 $arr = explode(' ', $profile['pub_keywords']);
4233 for ($x = 0; $x < 5; $x ++) {
4234 if (trim($arr[$x])) {
4235 $tags .= '#'. trim($arr[$x]) .' ';
4240 $tags = trim($tags);
4243 return ["author" => $handle,
4244 "first_name" => $first,
4245 "last_name" => $last,
4246 "image_url" => $large,
4247 "image_url_medium" => $medium,
4248 "image_url_small" => $small,
4250 "gender" => $profile['gender'],
4252 "location" => $location,
4253 "searchable" => $searchable,
4255 "tag_string" => $tags];
4259 * @brief Sends profile data
4261 * @param int $uid The user id
4262 * @param bool $recips optional, default false
4265 public static function sendProfile($uid, $recips = false)
4271 $owner = User::getOwnerDataById($uid);
4278 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4279 AND `uid` = %d AND `rel` != %d",
4280 dbesc(NETWORK_DIASPORA),
4282 intval(CONTACT_IS_SHARING)
4290 $message = self::createProfileData($uid);
4292 foreach ($recips as $recip) {
4293 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4294 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4299 * @brief Stores the signature for likes that are created on our system
4301 * @param array $contact The contact array of the "like"
4302 * @param int $post_id The post id of the "like"
4304 * @return bool Success
4306 public static function storeLikeSignature($contact, $post_id)
4308 // Is the contact the owner? Then fetch the private key
4309 if (!$contact['self'] || ($contact['uid'] == 0)) {
4310 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4314 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4315 if (!DBM::is_result($r)) {
4319 $contact["uprvkey"] = $r[0]['prvkey'];
4321 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4322 if (!DBM::is_result($r)) {
4326 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4330 $message = self::constructLike($r[0], $contact);
4331 if ($message === false) {
4335 $message["author_signature"] = self::signature($contact, $message);
4338 * Now store the signature more flexible to dynamically support new fields.
4339 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4341 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4343 logger('Stored diaspora like signature');
4348 * @brief Stores the signature for comments that are created on our system
4350 * @param array $item The item array of the comment
4351 * @param array $contact The contact array of the item owner
4352 * @param string $uprvkey The private key of the sender
4353 * @param int $message_id The message id of the comment
4355 * @return bool Success
4357 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4359 if ($uprvkey == "") {
4360 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4364 $contact["uprvkey"] = $uprvkey;
4366 $message = self::constructComment($item, $contact);
4367 if ($message === false) {
4371 $message["author_signature"] = self::signature($contact, $message);
4374 * Now store the signature more flexible to dynamically support new fields.
4375 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4377 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4379 logger('Stored diaspora comment signature');