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.
11 namespace Friendica\Protocol;
13 use Friendica\Content\Text\BBCode;
14 use Friendica\Content\Text\Markdown;
15 use Friendica\Core\Cache;
16 use Friendica\Core\Config;
17 use Friendica\Core\L10n;
18 use Friendica\Core\PConfig;
19 use Friendica\Core\System;
20 use Friendica\Core\Worker;
21 use Friendica\Database\DBM;
22 use Friendica\Model\Contact;
23 use Friendica\Model\GContact;
24 use Friendica\Model\Group;
25 use Friendica\Model\Item;
26 use Friendica\Model\Profile;
27 use Friendica\Model\Queue;
28 use Friendica\Model\User;
29 use Friendica\Network\Probe;
30 use Friendica\Util\Crypto;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
37 require_once 'include/dba.php';
38 require_once 'include/items.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')",
80 DateTimeFormat::utcNow(),
84 dbesc(normalise_link($server)),
86 dbesc(NETWORK_DIASPORA),
87 intval(CONTACT_IS_FOLLOWER),
88 dbesc(DateTimeFormat::utcNow()),
89 dbesc(DateTimeFormat::utcNow()),
90 dbesc(DateTimeFormat::utcNow())
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 $inner_aes_key = null;
363 if ($children->header) {
365 $author_link = str_replace('acct:', '', $children->header->author_id);
367 // This happens with posts from a relais
369 logger("This is no private post in the old format", LOGGER_DEBUG);
373 $encrypted_header = json_decode(base64_decode($children->encrypted_header));
375 $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
376 $ciphertext = base64_decode($encrypted_header->ciphertext);
378 $outer_key_bundle = '';
379 openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
381 $j_outer_key_bundle = json_decode($outer_key_bundle);
383 $outer_iv = base64_decode($j_outer_key_bundle->iv);
384 $outer_key = base64_decode($j_outer_key_bundle->key);
386 $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
388 logger('decrypted: '.$decrypted, LOGGER_DEBUG);
389 $idom = XML::parseString($decrypted);
391 $inner_iv = base64_decode($idom->iv);
392 $inner_aes_key = base64_decode($idom->aes_key);
394 $author_link = str_replace('acct:', '', $idom->author_id);
397 $dom = $basedom->children(NAMESPACE_SALMON_ME);
399 // figure out where in the DOM tree our data is hiding
402 if ($dom->provenance->data) {
403 $base = $dom->provenance;
404 } elseif ($dom->env->data) {
406 } elseif ($dom->data) {
411 logger('unable to locate salmon data in xml');
412 System::httpExit(400);
416 // Stash the signature away for now. We have to find their key or it won't be good for anything.
417 $signature = base64url_decode($base->sig);
421 // strip whitespace so our data element will return to one big base64 blob
422 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
425 // stash away some other stuff for later
427 $type = $base->data[0]->attributes()->type[0];
428 $keyhash = $base->sig[0]->attributes()->keyhash[0];
429 $encoding = $base->encoding;
433 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
437 $data = base64url_decode($data);
441 $inner_decrypted = $data;
443 // Decode the encrypted blob
444 $inner_encrypted = base64_decode($data);
445 $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
449 logger('Could not retrieve author URI.');
450 System::httpExit(400);
452 // Once we have the author URI, go to the web and try to find their public key
453 // (first this will look it up locally if it is in the fcontact cache)
454 // This will also convert diaspora public key from pkcs#1 to pkcs#8
456 logger('Fetching key for '.$author_link);
457 $key = self::key($author_link);
460 logger('Could not retrieve author key.');
461 System::httpExit(400);
464 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
467 logger('Message did not verify. Discarding.');
468 System::httpExit(400);
471 logger('Message verified.');
473 return ['message' => (string)$inner_decrypted,
474 'author' => unxmlify($author_link),
475 'key' => (string)$key];
480 * @brief Dispatches public messages and find the fitting receivers
482 * @param array $msg The post that will be dispatched
484 * @return int The message id of the generated message, "true" or "false" if there was an error
486 public static function dispatchPublic($msg)
488 $enabled = intval(Config::get("system", "diaspora_enabled"));
490 logger("diaspora is disabled");
494 if (!($postdata = self::validPosting($msg))) {
495 logger("Invalid posting");
499 $fields = $postdata['fields'];
501 // Is it a an action (comment, like, ...) for our own post?
502 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
503 $guid = notags(unxmlify($fields->parent_guid));
504 $importer = self::importerForGuid($guid);
505 if (is_array($importer)) {
506 logger("delivering to origin: ".$importer["name"]);
507 $message_id = self::dispatch($importer, $msg, $fields);
512 // Process item retractions. This has to be done separated from the other stuff,
513 // since retractions for comments could come even from non followers.
514 if (!empty($fields) && in_array($fields->getName(), ['retraction'])) {
515 $target = notags(unxmlify($fields->target_type));
516 if (in_array($target, ["Comment", "Like", "Post", "Reshare", "StatusMessage"])) {
517 logger('processing retraction for '.$target, LOGGER_DEBUG);
518 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
519 $message_id = self::dispatch($importer, $msg, $fields);
524 // Now distribute it to the followers
526 "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
527 (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
528 AND NOT `account_expired` AND NOT `account_removed`",
529 dbesc(NETWORK_DIASPORA),
530 dbesc($msg["author"])
533 if (DBM::is_result($r)) {
534 foreach ($r as $rr) {
535 logger("delivering to: ".$rr["username"]);
536 self::dispatch($rr, $msg, $fields);
538 } elseif (!Config::get('system', 'relay_subscribe', false)) {
539 logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
541 // Use a dummy importer to import the data for the public copy
542 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
543 $message_id = self::dispatch($importer, $msg, $fields);
550 * @brief Dispatches the different message types to the different functions
552 * @param array $importer Array of the importer user
553 * @param array $msg The post that will be dispatched
554 * @param object $fields SimpleXML object that contains the message
556 * @return int The message id of the generated message, "true" or "false" if there was an error
558 public static function dispatch($importer, $msg, $fields = null)
560 // The sender is the handle of the contact that sent the message.
561 // This will often be different with relayed messages (for example "like" and "comment")
562 $sender = $msg["author"];
564 // This is only needed for private postings since this is already done for public ones before
565 if (is_null($fields)) {
566 if (!($postdata = self::validPosting($msg))) {
567 logger("Invalid posting");
570 $fields = $postdata['fields'];
573 $type = $fields->getName();
575 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
578 case "account_migration":
579 return self::receiveAccountMigration($importer, $fields);
581 case "account_deletion":
582 return self::receiveAccountDeletion($importer, $fields);
585 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
588 return self::receiveContactRequest($importer, $fields);
591 return self::receiveConversation($importer, $msg, $fields);
594 return self::receiveLike($importer, $sender, $fields);
597 return self::receiveMessage($importer, $fields);
599 case "participation":
600 return self::receiveParticipation($importer, $fields);
602 case "photo": // Not implemented
603 return self::receivePhoto($importer, $fields);
605 case "poll_participation": // Not implemented
606 return self::receivePollParticipation($importer, $fields);
609 return self::receiveProfile($importer, $fields);
612 return self::receiveReshare($importer, $fields, $msg["message"]);
615 return self::receiveRetraction($importer, $sender, $fields);
617 case "status_message":
618 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
621 logger("Unknown message type ".$type);
629 * @brief Checks if a posting is valid and fetches the data fields.
631 * This function does not only check the signature.
632 * It also does the conversion between the old and the new diaspora format.
634 * @param array $msg Array with the XML, the sender handle and the sender signature
636 * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
638 private static function validPosting($msg)
640 $data = XML::parseString($msg["message"]);
642 if (!is_object($data)) {
643 logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
647 // Is this the new or the old version?
648 if ($data->getName() == "XML") {
650 foreach ($data->post->children() as $child) {
658 $type = $element->getName();
661 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
663 // All retractions are handled identically from now on.
664 // In the new version there will only be "retraction".
665 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
666 $type = "retraction";
668 if ($type == "request") {
672 $fields = new SimpleXMLElement("<".$type."/>");
675 $author_signature = null;
676 $parent_author_signature = null;
678 foreach ($element->children() as $fieldname => $entry) {
680 // Translation for the old XML structure
681 if ($fieldname == "diaspora_handle") {
682 $fieldname = "author";
684 if ($fieldname == "participant_handles") {
685 $fieldname = "participants";
687 if (in_array($type, ["like", "participation"])) {
688 if ($fieldname == "target_type") {
689 $fieldname = "parent_type";
692 if ($fieldname == "sender_handle") {
693 $fieldname = "author";
695 if ($fieldname == "recipient_handle") {
696 $fieldname = "recipient";
698 if ($fieldname == "root_diaspora_id") {
699 $fieldname = "root_author";
701 if ($type == "status_message") {
702 if ($fieldname == "raw_message") {
706 if ($type == "retraction") {
707 if ($fieldname == "post_guid") {
708 $fieldname = "target_guid";
710 if ($fieldname == "type") {
711 $fieldname = "target_type";
716 if (($fieldname == "author_signature") && ($entry != "")) {
717 $author_signature = base64_decode($entry);
718 } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
719 $parent_author_signature = base64_decode($entry);
720 } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
721 if ($signed_data != "") {
725 $signed_data .= $entry;
727 if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
728 || ($orig_type == "relayable_retraction")
730 XML::copy($entry, $fields, $fieldname);
734 // This is something that shouldn't happen at all.
735 if (in_array($type, ["status_message", "reshare", "profile"])) {
736 if ($msg["author"] != $fields->author) {
737 logger("Message handle is not the same as envelope sender. Quitting this message.");
742 // Only some message types have signatures. So we quit here for the other types.
743 if (!in_array($type, ["comment", "like"])) {
744 return ["fields" => $fields, "relayed" => false];
746 // No author_signature? This is a must, so we quit.
747 if (!isset($author_signature)) {
748 logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
752 if (isset($parent_author_signature)) {
755 $key = self::key($msg["author"]);
757 if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
758 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);
765 $key = self::key($fields->author);
767 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
768 logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
771 return ["fields" => $fields, "relayed" => $relayed];
776 * @brief Fetches the public key for a given handle
778 * @param string $handle The handle
780 * @return string The public key
782 private static function key($handle)
784 $handle = strval($handle);
786 logger("Fetching diaspora key for: ".$handle);
788 $r = self::personByHandle($handle);
797 * @brief Fetches data for a given handle
799 * @param string $handle The handle
801 * @return array the queried data
803 public static function personByHandle($handle)
807 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
808 if (DBM::is_result($person)) {
809 logger("In cache " . print_r($person, true), LOGGER_DEBUG);
811 // update record occasionally so it doesn't get stale
812 $d = strtotime($person["updated"]." +00:00");
813 if ($d < strtotime("now - 14 days")) {
817 if ($person["guid"] == "") {
822 if (!DBM::is_result($person) || $update) {
823 logger("create or refresh", LOGGER_DEBUG);
824 $r = Probe::uri($handle, NETWORK_DIASPORA);
826 // Note that Friendica contacts will return a "Diaspora person"
827 // if Diaspora connectivity is enabled on their server
828 if ($r && ($r["network"] === NETWORK_DIASPORA)) {
829 self::addFContact($r, $update);
831 // Fetch the updated or added contact
832 $person = dba::selectFirst('fcontact', [], ['network' => NETWORK_DIASPORA, 'addr' => $handle]);
833 if (!DBM::is_result($person)) {
843 * @brief Updates the fcontact table
845 * @param array $arr The fcontact data
846 * @param bool $update Update or insert?
848 * @return string The id of the fcontact entry
850 private static function addFContact($arr, $update = false)
854 "UPDATE `fcontact` SET
868 WHERE `url` = '%s' AND `network` = '%s'",
870 dbesc($arr["photo"]),
871 dbesc($arr["request"]),
873 dbesc(strtolower($arr["addr"])),
875 dbesc($arr["batch"]),
876 dbesc($arr["notify"]),
878 dbesc($arr["confirm"]),
879 dbesc($arr["alias"]),
880 dbesc($arr["pubkey"]),
881 dbesc(DateTimeFormat::utcNow()),
883 dbesc($arr["network"])
887 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
888 `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
889 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
892 dbesc($arr["photo"]),
893 dbesc($arr["request"]),
897 dbesc($arr["batch"]),
898 dbesc($arr["notify"]),
900 dbesc($arr["confirm"]),
901 dbesc($arr["network"]),
902 dbesc($arr["alias"]),
903 dbesc($arr["pubkey"]),
904 dbesc(DateTimeFormat::utcNow())
912 * @brief get a handle (user@domain.tld) from a given contact id
914 * @param int $contact_id The id in the contact table
915 * @param int $pcontact_id The id in the contact table (Used for the public contact)
917 * @return string the handle
919 private static function handleFromContact($contact_id, $pcontact_id = 0)
923 logger("contact id is ".$contact_id." - pcontact id is ".$pcontact_id, LOGGER_DEBUG);
925 if ($pcontact_id != 0) {
927 "SELECT `addr` FROM `contact` WHERE `id` = %d AND `addr` != ''",
931 if (DBM::is_result($r)) {
932 return strtolower($r[0]["addr"]);
937 "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
941 if (DBM::is_result($r)) {
944 logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
946 if ($contact['addr'] != "") {
947 $handle = $contact['addr'];
949 $baseurl_start = strpos($contact['url'], '://') + 3;
950 // allows installations in a subdirectory--not sure how Diaspora will handle
951 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
952 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
953 $handle = $contact['nick'].'@'.$baseurl;
957 return strtolower($handle);
961 * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
964 * @param mixed $fcontact_guid Hexadecimal string guid
966 * @return string the contact url or null
968 public static function urlFromContactGuid($fcontact_guid)
970 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
973 "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
974 dbesc(NETWORK_DIASPORA),
975 dbesc($fcontact_guid)
978 if (DBM::is_result($r)) {
986 * @brief Get a contact id for a given handle
988 * @todo Move to Friendica\Model\Contact
990 * @param int $uid The user id
991 * @param string $handle The handle in the format user@domain.tld
993 * @return int Contact id
995 private static function contactByHandle($uid, $handle)
997 // First do a direct search on the contact table
999 "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
1004 if (DBM::is_result($r)) {
1008 * We haven't found it?
1009 * We use another function for it that will possibly create a contact entry.
1011 $cid = Contact::getIdForURL($handle, $uid);
1014 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1015 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1017 if (DBM::is_result($r)) {
1023 $handle_parts = explode("@", $handle);
1024 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1026 "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1027 dbesc(NETWORK_DFRN),
1031 if (DBM::is_result($r)) {
1035 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1040 * @brief Check if posting is allowed for this contact
1042 * @param array $importer Array of the importer user
1043 * @param array $contact The contact that is checked
1044 * @param bool $is_comment Is the check for a comment?
1046 * @return bool is the contact allowed to post?
1048 private static function postAllow($importer, $contact, $is_comment = false)
1051 * Perhaps we were already sharing with this person. Now they're sharing with us.
1052 * That makes us friends.
1053 * Normally this should have handled by getting a request - but this could get lost
1055 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1056 // It is not removed by now. Possibly the code is needed?
1057 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1060 // array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1061 // array('id' => $contact["id"], 'uid' => $contact["uid"])
1064 // $contact["rel"] = CONTACT_IS_FRIEND;
1065 // logger("defining user ".$contact["nick"]." as friend");
1068 // We don't seem to like that person
1069 if ($contact["blocked"] || $contact["readonly"]) {
1070 // Maybe blocked, don't accept.
1072 // We are following this person?
1073 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1074 // Yes, then it is fine.
1076 // Is it a post to a community?
1077 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1080 // Is the message a global user or a comment?
1081 } elseif (($importer["uid"] == 0) || $is_comment) {
1082 // Messages for the global users and comments are always accepted
1090 * @brief Fetches the contact id for a handle and checks if posting is allowed
1092 * @param array $importer Array of the importer user
1093 * @param string $handle The checked handle in the format user@domain.tld
1094 * @param bool $is_comment Is the check for a comment?
1096 * @return array The contact data
1098 private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1100 $contact = self::contactByHandle($importer["uid"], $handle);
1102 logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1103 // If a contact isn't found, we accept it anyway if it is a comment
1111 if (!self::postAllow($importer, $contact, $is_comment)) {
1112 logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1119 * @brief Does the message already exists on the system?
1121 * @param int $uid The user id
1122 * @param string $guid The guid of the message
1124 * @return int|bool message id if the message already was stored into the system - or false.
1126 private static function messageExists($uid, $guid)
1129 "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1134 if (DBM::is_result($r)) {
1135 logger("message ".$guid." already exists for user ".$uid);
1143 * @brief Checks for links to posts in a message
1145 * @param array $item The item array
1148 private static function fetchGuid($item)
1150 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1151 preg_replace_callback(
1153 function ($match) use ($item) {
1154 self::fetchGuidSub($match, $item);
1159 preg_replace_callback(
1160 "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1161 function ($match) use ($item) {
1162 self::fetchGuidSub($match, $item);
1169 * @brief Checks for relative /people/* links in an item body to match local
1170 * contacts or prepends the remote host taken from the author link.
1172 * @param string $body The item body to replace links from
1173 * @param string $author_link The author link for missing local contact fallback
1175 * @return string the replaced string
1177 public static function replacePeopleGuid($body, $author_link)
1179 $return = preg_replace_callback(
1180 "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1181 function ($match) use ($author_link) {
1183 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1184 // 1 => '0123456789abcdef'
1186 $handle = self::urlFromContactGuid($match[1]);
1189 $return = '@[url='.$handle.']'.$match[2].'[/url]';
1191 // No local match, restoring absolute remote URL from author scheme and host
1192 $author_url = parse_url($author_link);
1193 $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1205 * @brief sub function of "fetchGuid" which checks for links in messages
1207 * @param array $match array containing a link that has to be checked for a message link
1208 * @param array $item The item array
1211 private static function fetchGuidSub($match, $item)
1213 if (!self::storeByGuid($match[1], $item["author-link"])) {
1214 self::storeByGuid($match[1], $item["owner-link"]);
1219 * @brief Fetches an item with a given guid from a given server
1221 * @param string $guid the message guid
1222 * @param string $server The server address
1223 * @param int $uid The user id of the user
1225 * @return int the message id of the stored message or false
1227 private static function storeByGuid($guid, $server, $uid = 0)
1229 $serverparts = parse_url($server);
1230 $server = $serverparts["scheme"]."://".$serverparts["host"];
1232 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1234 $msg = self::message($guid, $server);
1240 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1242 // Now call the dispatcher
1243 return self::dispatchPublic($msg);
1247 * @brief Fetches a message from a server
1249 * @param string $guid message guid
1250 * @param string $server The url of the server
1251 * @param int $level Endless loop prevention
1254 * 'message' => The message XML
1255 * 'author' => The author handle
1256 * 'key' => The public key of the author
1258 private static function message($guid, $server, $level = 0)
1264 // This will work for new Diaspora servers and Friendica servers from 3.5
1265 $source_url = $server."/fetch/post/".urlencode($guid);
1267 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1269 $envelope = Network::fetchUrl($source_url);
1271 logger("Envelope was fetched.", LOGGER_DEBUG);
1272 $x = self::verifyMagicEnvelope($envelope);
1274 logger("Envelope could not be verified.", LOGGER_DEBUG);
1276 logger("Envelope was verified.", LOGGER_DEBUG);
1282 // This will work for older Diaspora and Friendica servers
1284 $source_url = $server."/p/".urlencode($guid).".xml";
1285 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1287 $x = Network::fetchUrl($source_url);
1293 $source_xml = XML::parseString($x);
1295 if (!is_object($source_xml)) {
1299 if ($source_xml->post->reshare) {
1300 // Reshare of a reshare - old Diaspora version
1301 logger("Message is a reshare", LOGGER_DEBUG);
1302 return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1303 } elseif ($source_xml->getName() == "reshare") {
1304 // Reshare of a reshare - new Diaspora version
1305 logger("Message is a new reshare", LOGGER_DEBUG);
1306 return self::message($source_xml->root_guid, $server, ++$level);
1311 // Fetch the author - for the old and the new Diaspora version
1312 if ($source_xml->post->status_message->diaspora_handle) {
1313 $author = (string)$source_xml->post->status_message->diaspora_handle;
1314 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1315 $author = (string)$source_xml->author;
1318 // If this isn't a "status_message" then quit
1320 logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1324 $msg = ["message" => $x, "author" => $author];
1326 $msg["key"] = self::key($msg["author"]);
1332 * @brief Fetches the item record of a given guid
1334 * @param int $uid The user id
1335 * @param string $guid message guid
1336 * @param string $author The handle of the item
1337 * @param array $contact The contact of the item owner
1339 * @return array the item record
1341 private static function parentItem($uid, $guid, $author, $contact)
1344 "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1345 `author-name`, `author-link`, `author-avatar`,
1346 `owner-name`, `owner-link`, `owner-avatar`
1347 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1353 $result = self::storeByGuid($guid, $contact["url"], $uid);
1356 $person = self::personByHandle($author);
1357 $result = self::storeByGuid($guid, $person["url"], $uid);
1361 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1364 "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1365 `author-name`, `author-link`, `author-avatar`,
1366 `owner-name`, `owner-link`, `owner-avatar`
1367 FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1375 logger("parent item not found: parent: ".$guid." - user: ".$uid);
1378 logger("parent item found: parent: ".$guid." - user: ".$uid);
1384 * @brief returns contact details
1386 * @param array $def_contact The default contact if the person isn't found
1387 * @param array $person The record of the person
1388 * @param int $uid The user id
1391 * 'cid' => contact id
1392 * 'network' => network type
1394 private static function authorContactByUrl($def_contact, $person, $uid)
1396 $condition = ['nurl' => normalise_link($person["url"]), 'uid' => $uid];
1397 $contact = dba::selectFirst('contact', ['id', 'network'], $condition);
1398 if (DBM::is_result($contact)) {
1399 $cid = $contact["id"];
1400 $network = $contact["network"];
1402 $cid = $def_contact["id"];
1403 $network = NETWORK_DIASPORA;
1406 return ["cid" => $cid, "network" => $network];
1410 * @brief Is the profile a hubzilla profile?
1412 * @param string $url The profile link
1414 * @return bool is it a hubzilla server?
1416 public static function isRedmatrix($url)
1418 return(strstr($url, "/channel/"));
1422 * @brief Generate a post link with a given handle and message guid
1424 * @param string $addr The user handle
1425 * @param string $guid message guid
1426 * @param string $parent_guid optional parent guid
1428 * @return string the post link
1430 private static function plink($addr, $guid, $parent_guid = '')
1432 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1435 if (!DBM::is_result($r)) {
1436 if ($parent_guid != '') {
1437 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1439 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1443 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1444 // So we try another way as well.
1445 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1446 if (DBM::is_result($s)) {
1447 $r[0]["network"] = $s[0]["network"];
1450 if ($r[0]["network"] == NETWORK_DFRN) {
1451 return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1454 if (self::isRedmatrix($r[0]["url"])) {
1455 return $r[0]["url"]."/?f=&mid=".$guid;
1458 if ($parent_guid != '') {
1459 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1461 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1466 * @brief Receives account migration
1468 * @param array $importer Array of the importer user
1469 * @param object $data The message object
1471 * @return bool Success
1473 private static function receiveAccountMigration($importer, $data)
1475 $old_handle = notags(unxmlify($data->author));
1476 $new_handle = notags(unxmlify($data->profile->author));
1477 $signature = notags(unxmlify($data->signature));
1479 $contact = self::contactByHandle($importer["uid"], $old_handle);
1481 logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1485 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1488 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1489 $key = self::key($old_handle);
1490 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1491 logger('No valid signature for migration.');
1495 // Update the profile
1496 self::receiveProfile($importer, $data->profile);
1498 // change the technical stuff in contact and gcontact
1499 $data = Probe::uri($new_handle);
1500 if ($data['network'] == NETWORK_PHANTOM) {
1501 logger('Account for '.$new_handle." couldn't be probed.");
1505 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1506 'name' => $data['name'], 'nick' => $data['nick'],
1507 'addr' => $data['addr'], 'batch' => $data['batch'],
1508 'notify' => $data['notify'], 'poll' => $data['poll'],
1509 'network' => $data['network']];
1511 dba::update('contact', $fields, ['addr' => $old_handle]);
1513 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1514 'name' => $data['name'], 'nick' => $data['nick'],
1515 'addr' => $data['addr'], 'connect' => $data['addr'],
1516 'notify' => $data['notify'], 'photo' => $data['photo'],
1517 'server_url' => $data['baseurl'], 'network' => $data['network']];
1519 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1521 logger('Contacts are updated.');
1524 /// @todo This is an extreme performance killer
1526 'owner-link' => [$contact["url"], $data["url"]],
1527 'author-link' => [$contact["url"], $data["url"]],
1529 foreach ($fields as $n => $f) {
1531 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1534 intval($importer["uid"])
1537 if (DBM::is_result($r)) {
1539 "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1544 intval($importer["uid"])
1553 logger('Items are updated.');
1559 * @brief Processes an account deletion
1561 * @param array $importer Array of the importer user
1562 * @param object $data The message object
1564 * @return bool Success
1566 private static function receiveAccountDeletion($importer, $data)
1568 /// @todo Account deletion should remove the contact from the global contacts as well
1570 $author = notags(unxmlify($data->author));
1572 $contact = self::contactByHandle($importer["uid"], $author);
1574 logger("cannot find contact for author: ".$author);
1578 // We now remove the contact
1579 Contact::remove($contact["id"]);
1584 * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1586 * @param string $author Author handle
1587 * @param string $guid Message guid
1588 * @param boolean $onlyfound Only return uri when found in the database
1590 * @return string The constructed uri or the one from our database
1592 private static function getUriFromGuid($author, $guid, $onlyfound = false)
1594 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1595 if (DBM::is_result($r)) {
1596 return $r[0]["uri"];
1597 } elseif (!$onlyfound) {
1598 return $author.":".$guid;
1605 * @brief Fetch the guid from our database with a given uri
1607 * @param string $uri Message uri
1608 * @param string $uid Author handle
1610 * @return string The post guid
1612 private static function getGuidFromUri($uri, $uid)
1614 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1615 if (DBM::is_result($r)) {
1616 return $r[0]["guid"];
1623 * @brief Find the best importer for a comment, like, ...
1625 * @param string $guid The guid of the item
1627 * @return array|boolean the origin owner of that post - or false
1629 private static function importerForGuid($guid)
1631 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1633 if (DBM::is_result($item)) {
1634 logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1635 $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1636 if (DBM::is_result($contact)) {
1644 * @brief Processes an incoming comment
1646 * @param array $importer Array of the importer user
1647 * @param string $sender The sender of the message
1648 * @param object $data The message object
1649 * @param string $xml The original XML of the message
1651 * @return int The message id of the generated comment or "false" if there was an error
1653 private static function receiveComment($importer, $sender, $data, $xml)
1655 $author = notags(unxmlify($data->author));
1656 $guid = notags(unxmlify($data->guid));
1657 $parent_guid = notags(unxmlify($data->parent_guid));
1658 $text = unxmlify($data->text);
1660 if (isset($data->created_at)) {
1661 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1663 $created_at = DateTimeFormat::utcNow();
1666 if (isset($data->thread_parent_guid)) {
1667 $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1668 $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1673 $contact = self::allowedContactByHandle($importer, $sender, true);
1678 $message_id = self::messageExists($importer["uid"], $guid);
1683 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1684 if (!$parent_item) {
1688 $person = self::personByHandle($author);
1689 if (!is_array($person)) {
1690 logger("unable to find author details");
1694 // Fetch the contact id - if we know this contact
1695 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1699 $datarray["uid"] = $importer["uid"];
1700 $datarray["contact-id"] = $author_contact["cid"];
1701 $datarray["network"] = $author_contact["network"];
1703 $datarray["author-name"] = $person["name"];
1704 $datarray["author-link"] = $person["url"];
1705 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1707 $datarray["owner-name"] = $contact["name"];
1708 $datarray["owner-link"] = $contact["url"];
1709 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1711 $datarray["guid"] = $guid;
1712 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1714 $datarray["type"] = "remote-comment";
1715 $datarray["verb"] = ACTIVITY_POST;
1716 $datarray["gravity"] = GRAVITY_COMMENT;
1718 if ($thr_uri != "") {
1719 $datarray["parent-uri"] = $thr_uri;
1721 $datarray["parent-uri"] = $parent_item["uri"];
1724 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1726 $datarray["protocol"] = PROTOCOL_DIASPORA;
1727 $datarray["source"] = $xml;
1729 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1731 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1733 $body = Markdown::toBBCode($text);
1735 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1737 self::fetchGuid($datarray);
1739 $message_id = Item::insert($datarray);
1741 if ($message_id <= 0) {
1746 logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1749 // If we are the origin of the parent we store the original data and notify our followers
1750 if ($message_id && $parent_item["origin"]) {
1751 // Formerly we stored the signed text, the signature and the author in different fields.
1752 // We now store the raw data so that we are more flexible.
1753 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1756 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1763 * @brief processes and stores private messages
1765 * @param array $importer Array of the importer user
1766 * @param array $contact The contact of the message
1767 * @param object $data The message object
1768 * @param array $msg Array of the processed message, author handle and key
1769 * @param object $mesg The private message
1770 * @param array $conversation The conversation record to which this message belongs
1772 * @return bool "true" if it was successful
1774 private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1776 $author = notags(unxmlify($data->author));
1777 $guid = notags(unxmlify($data->guid));
1778 $subject = notags(unxmlify($data->subject));
1780 // "diaspora_handle" is the element name from the old version
1781 // "author" is the element name from the new version
1782 if ($mesg->author) {
1783 $msg_author = notags(unxmlify($mesg->author));
1784 } elseif ($mesg->diaspora_handle) {
1785 $msg_author = notags(unxmlify($mesg->diaspora_handle));
1790 $msg_guid = notags(unxmlify($mesg->guid));
1791 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1792 $msg_text = unxmlify($mesg->text);
1793 $msg_created_at = DateTimeFormat::utc(notags(unxmlify($mesg->created_at)));
1795 if ($msg_conversation_guid != $guid) {
1796 logger("message conversation guid does not belong to the current conversation.");
1800 $body = Markdown::toBBCode($msg_text);
1801 $message_uri = $msg_author.":".$msg_guid;
1803 $person = self::personByHandle($msg_author);
1808 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1810 intval($importer["uid"])
1812 if (DBM::is_result($r)) {
1813 logger("duplicate message already delivered.", LOGGER_DEBUG);
1818 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1819 VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1820 intval($importer["uid"]),
1822 intval($conversation["id"]),
1823 dbesc($person["name"]),
1824 dbesc($person["photo"]),
1825 dbesc($person["url"]),
1826 intval($contact["id"]),
1831 dbesc($message_uri),
1832 dbesc($author.":".$guid),
1833 dbesc($msg_created_at)
1838 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
1842 "type" => NOTIFY_MAIL,
1843 "notify_flags" => $importer["notify-flags"],
1844 "language" => $importer["language"],
1845 "to_name" => $importer["username"],
1846 "to_email" => $importer["email"],
1847 "uid" =>$importer["uid"],
1848 "item" => ["subject" => $subject, "body" => $body],
1849 "source_name" => $person["name"],
1850 "source_link" => $person["url"],
1851 "source_photo" => $person["thumb"],
1852 "verb" => ACTIVITY_POST,
1859 * @brief Processes new private messages (answers to private messages are processed elsewhere)
1861 * @param array $importer Array of the importer user
1862 * @param array $msg Array of the processed message, author handle and key
1863 * @param object $data The message object
1865 * @return bool Success
1867 private static function receiveConversation($importer, $msg, $data)
1869 $author = notags(unxmlify($data->author));
1870 $guid = notags(unxmlify($data->guid));
1871 $subject = notags(unxmlify($data->subject));
1872 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
1873 $participants = notags(unxmlify($data->participants));
1875 $messages = $data->message;
1877 if (!count($messages)) {
1878 logger("empty conversation");
1882 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1887 $conversation = null;
1890 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1891 intval($importer["uid"]),
1895 $conversation = $c[0];
1898 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1899 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1900 intval($importer["uid"]),
1904 dbesc(DateTimeFormat::utcNow()),
1906 dbesc($participants)
1910 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1911 intval($importer["uid"]),
1917 $conversation = $c[0];
1920 if (!$conversation) {
1921 logger("unable to create conversation.");
1925 foreach ($messages as $mesg) {
1926 self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1933 * @brief Creates the body for a "like" message
1935 * @param array $contact The contact that send us the "like"
1936 * @param array $parent_item The item array of the parent item
1937 * @param string $guid message guid
1939 * @return string the body
1941 private static function constructLikeBody($contact, $parent_item, $guid)
1943 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1945 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1946 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1947 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
1949 return sprintf($bodyverb, $ulink, $alink, $plink);
1953 * @brief Creates a XML object for a "like"
1955 * @param array $importer Array of the importer user
1956 * @param array $parent_item The item array of the parent item
1958 * @return string The XML
1960 private static function constructLikeObject($importer, $parent_item)
1962 $objtype = ACTIVITY_OBJ_NOTE;
1963 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1964 $parent_body = $parent_item["body"];
1966 $xmldata = ["object" => ["type" => $objtype,
1968 "id" => $parent_item["uri"],
1971 "content" => $parent_body]];
1973 return XML::fromArray($xmldata, $xml, true);
1977 * @brief Processes "like" messages
1979 * @param array $importer Array of the importer user
1980 * @param string $sender The sender of the message
1981 * @param object $data The message object
1983 * @return int The message id of the generated like or "false" if there was an error
1985 private static function receiveLike($importer, $sender, $data)
1987 $author = notags(unxmlify($data->author));
1988 $guid = notags(unxmlify($data->guid));
1989 $parent_guid = notags(unxmlify($data->parent_guid));
1990 $parent_type = notags(unxmlify($data->parent_type));
1991 $positive = notags(unxmlify($data->positive));
1993 // likes on comments aren't supported by Diaspora - only on posts
1994 // But maybe this will be supported in the future, so we will accept it.
1995 if (!in_array($parent_type, ["Post", "Comment"])) {
1999 $contact = self::allowedContactByHandle($importer, $sender, true);
2004 $message_id = self::messageExists($importer["uid"], $guid);
2009 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2010 if (!$parent_item) {
2014 $person = self::personByHandle($author);
2015 if (!is_array($person)) {
2016 logger("unable to find author details");
2020 // Fetch the contact id - if we know this contact
2021 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2023 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2024 // We would accept this anyhow.
2025 if ($positive == "true") {
2026 $verb = ACTIVITY_LIKE;
2028 $verb = ACTIVITY_DISLIKE;
2033 $datarray["protocol"] = PROTOCOL_DIASPORA;
2035 $datarray["uid"] = $importer["uid"];
2036 $datarray["contact-id"] = $author_contact["cid"];
2037 $datarray["network"] = $author_contact["network"];
2039 $datarray["author-name"] = $person["name"];
2040 $datarray["author-link"] = $person["url"];
2041 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2043 $datarray["owner-name"] = $contact["name"];
2044 $datarray["owner-link"] = $contact["url"];
2045 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2047 $datarray["guid"] = $guid;
2048 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2050 $datarray["type"] = "activity";
2051 $datarray["verb"] = $verb;
2052 $datarray["gravity"] = GRAVITY_LIKE;
2053 $datarray["parent-uri"] = $parent_item["uri"];
2055 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2056 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2058 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2060 $message_id = Item::insert($datarray);
2062 if ($message_id <= 0) {
2067 logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2070 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2071 if ($parent_item["id"] != $parent_item["parent"]) {
2072 $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2073 $origin = $toplevel["origin"];
2075 $origin = $parent_item["origin"];
2078 // If we are the origin of the parent we store the original data and notify our followers
2079 if ($message_id && $origin) {
2080 // Formerly we stored the signed text, the signature and the author in different fields.
2081 // We now store the raw data so that we are more flexible.
2082 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2085 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2092 * @brief Processes private messages
2094 * @param array $importer Array of the importer user
2095 * @param object $data The message object
2097 * @return bool Success?
2099 private static function receiveMessage($importer, $data)
2101 $author = notags(unxmlify($data->author));
2102 $guid = notags(unxmlify($data->guid));
2103 $conversation_guid = notags(unxmlify($data->conversation_guid));
2104 $text = unxmlify($data->text);
2105 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2107 $contact = self::allowedContactByHandle($importer, $author, true);
2112 $conversation = null;
2115 "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2116 intval($importer["uid"]),
2117 dbesc($conversation_guid)
2120 $conversation = $c[0];
2122 logger("conversation not available.");
2126 $message_uri = $author.":".$guid;
2128 $person = self::personByHandle($author);
2130 logger("unable to find author details");
2134 $body = Markdown::toBBCode($text);
2136 $body = self::replacePeopleGuid($body, $person["url"]);
2141 "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2143 intval($importer["uid"])
2145 if (DBM::is_result($r)) {
2146 logger("duplicate message already delivered.", LOGGER_DEBUG);
2151 "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2152 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2153 intval($importer["uid"]),
2155 intval($conversation["id"]),
2156 dbesc($person["name"]),
2157 dbesc($person["photo"]),
2158 dbesc($person["url"]),
2159 intval($contact["id"]),
2160 dbesc($conversation["subject"]),
2164 dbesc($message_uri),
2165 dbesc($author.":".$conversation["guid"]),
2171 dba::update('conv', ['updated' => DateTimeFormat::utcNow()], ['id' => $conversation["id"]]);
2176 * @brief Processes participations - unsupported by now
2178 * @param array $importer Array of the importer user
2179 * @param object $data The message object
2181 * @return bool always true
2183 private static function receiveParticipation($importer, $data)
2185 $author = strtolower(notags(unxmlify($data->author)));
2186 $parent_guid = notags(unxmlify($data->parent_guid));
2188 $contact_id = Contact::getIdForURL($author);
2190 logger('Contact not found: '.$author);
2194 $person = self::personByHandle($author);
2195 if (!is_array($person)) {
2196 logger("Person not found: ".$author);
2200 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2201 if (!DBM::is_result($item)) {
2202 logger('Item not found, no origin or private: '.$parent_guid);
2206 $author_parts = explode('@', $author);
2207 if (isset($author_parts[1])) {
2208 $server = $author_parts[1];
2210 // Should never happen
2214 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2215 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2217 // Send all existing comments and likes to the requesting server
2218 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2220 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2221 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2222 while ($comment = dba::fetch($comments)) {
2223 if ($comment['verb'] == ACTIVITY_POST) {
2224 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2226 $cmd = $comment['self'] ? 'like' : 'comment-import';
2228 logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2229 Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2231 dba::close($comments);
2237 * @brief Processes photos - unneeded
2239 * @param array $importer Array of the importer user
2240 * @param object $data The message object
2242 * @return bool always true
2244 private static function receivePhoto($importer, $data)
2246 // There doesn't seem to be a reason for this function,
2247 // since the photo data is transmitted in the status message as well
2252 * @brief Processes poll participations - unssupported
2254 * @param array $importer Array of the importer user
2255 * @param object $data The message object
2257 * @return bool always true
2259 private static function receivePollParticipation($importer, $data)
2261 // We don't support polls by now
2266 * @brief Processes incoming profile updates
2268 * @param array $importer Array of the importer user
2269 * @param object $data The message object
2271 * @return bool Success
2273 private static function receiveProfile($importer, $data)
2275 $author = strtolower(notags(unxmlify($data->author)));
2277 $contact = self::contactByHandle($importer["uid"], $author);
2282 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2283 $image_url = unxmlify($data->image_url);
2284 $birthday = unxmlify($data->birthday);
2285 $gender = unxmlify($data->gender);
2286 $about = Markdown::toBBCode(unxmlify($data->bio));
2287 $location = Markdown::toBBCode(unxmlify($data->location));
2288 $searchable = (unxmlify($data->searchable) == "true");
2289 $nsfw = (unxmlify($data->nsfw) == "true");
2290 $tags = unxmlify($data->tag_string);
2292 $tags = explode("#", $tags);
2295 foreach ($tags as $tag) {
2296 $tag = trim(strtolower($tag));
2302 $keywords = implode(", ", $keywords);
2304 $handle_parts = explode("@", $author);
2305 $nick = $handle_parts[0];
2308 $name = $handle_parts[0];
2311 if (preg_match("|^https?://|", $image_url) === 0) {
2312 $image_url = "http://".$handle_parts[1].$image_url;
2315 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2317 // Generic birthday. We don't know the timezone. The year is irrelevant.
2319 $birthday = str_replace("1000", "1901", $birthday);
2321 if ($birthday != "") {
2322 $birthday = DateTimeFormat::utc($birthday, "Y-m-d");
2325 // this is to prevent multiple birthday notifications in a single year
2326 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2328 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2329 $birthday = $contact["bd"];
2333 "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2334 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2338 dbesc(DateTimeFormat::utcNow()),
2344 intval($contact["id"]),
2345 intval($importer["uid"])
2348 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2349 "photo" => $image_url, "name" => $name, "location" => $location,
2350 "about" => $about, "birthday" => $birthday, "gender" => $gender,
2351 "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2352 "hide" => !$searchable, "nsfw" => $nsfw];
2354 $gcid = GContact::update($gcontact);
2356 GContact::link($gcid, $importer["uid"], $contact["id"]);
2358 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2364 * @brief Processes incoming friend requests
2366 * @param array $importer Array of the importer user
2367 * @param array $contact The contact that send the request
2370 private static function receiveRequestMakeFriend($importer, $contact)
2374 if ($contact["rel"] == CONTACT_IS_SHARING) {
2377 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2378 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2381 // send notification
2384 "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2385 intval($importer["uid"])
2388 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2390 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2391 intval($importer["uid"])
2394 // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2396 if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2398 $arr["protocol"] = PROTOCOL_DIASPORA;
2399 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2400 $arr["uid"] = $importer["uid"];
2401 $arr["contact-id"] = $self[0]["id"];
2403 $arr["type"] = 'wall';
2404 $arr["gravity"] = 0;
2406 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2407 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2408 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2409 $arr["verb"] = ACTIVITY_FRIEND;
2410 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2412 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2413 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2414 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2415 $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
2417 $arr["object"] = self::constructNewFriendObject($contact);
2419 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2421 $arr["allow_cid"] = $user["allow_cid"];
2422 $arr["allow_gid"] = $user["allow_gid"];
2423 $arr["deny_cid"] = $user["deny_cid"];
2424 $arr["deny_gid"] = $user["deny_gid"];
2426 $i = Item::insert($arr);
2428 Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2435 * @brief Creates a XML object for a "new friend" message
2437 * @param array $contact Array of the contact
2439 * @return string The XML
2441 private static function constructNewFriendObject($contact)
2443 $objtype = ACTIVITY_OBJ_PERSON;
2444 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2445 '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2447 $xmldata = ["object" => ["type" => $objtype,
2448 "title" => $contact["name"],
2449 "id" => $contact["url"]."/".$contact["name"],
2452 return XML::fromArray($xmldata, $xml, true);
2456 * @brief Processes incoming sharing notification
2458 * @param array $importer Array of the importer user
2459 * @param object $data The message object
2461 * @return bool Success
2463 private static function receiveContactRequest($importer, $data)
2465 $author = unxmlify($data->author);
2466 $recipient = unxmlify($data->recipient);
2468 if (!$author || !$recipient) {
2472 // the current protocol version doesn't know these fields
2473 // That means that we will assume their existance
2474 if (isset($data->following)) {
2475 $following = (unxmlify($data->following) == "true");
2480 if (isset($data->sharing)) {
2481 $sharing = (unxmlify($data->sharing) == "true");
2486 $contact = self::contactByHandle($importer["uid"], $author);
2488 // perhaps we were already sharing with this person. Now they're sharing with us.
2489 // That makes us friends.
2492 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2493 self::receiveRequestMakeFriend($importer, $contact);
2495 // refetch the contact array
2496 $contact = self::contactByHandle($importer["uid"], $author);
2498 // If we are now friends, we are sending a share message.
2499 // Normally we needn't to do so, but the first message could have been vanished.
2500 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2501 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2503 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2504 $ret = self::sendShare($u[0], $contact);
2509 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2510 Contact::removeFollower($importer, $contact);
2515 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2516 logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2518 } elseif (!$following && !$sharing) {
2519 logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2521 } elseif (!$following && $sharing) {
2522 logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2523 } elseif ($following && $sharing) {
2524 logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2525 } elseif ($following && !$sharing) {
2526 logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2529 $ret = self::personByHandle($author);
2531 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2532 logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2536 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2539 "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2540 VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2541 intval($importer["uid"]),
2542 dbesc($ret["network"]),
2543 dbesc($ret["addr"]),
2544 DateTimeFormat::utcNow(),
2546 dbesc(normalise_link($ret["url"])),
2548 dbesc($ret["name"]),
2549 dbesc($ret["nick"]),
2550 dbesc($ret["photo"]),
2551 dbesc($ret["pubkey"]),
2552 dbesc($ret["notify"]),
2553 dbesc($ret["poll"]),
2558 // find the contact record we just created
2560 $contact_record = self::contactByHandle($importer["uid"], $author);
2562 if (!$contact_record) {
2563 logger("unable to locate newly created contact record.");
2567 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2569 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2571 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2573 if ($importer["page-flags"] == PAGE_NORMAL) {
2574 logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2576 $hash = random_string().(string)time(); // Generate a confirm_key
2579 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2580 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2581 intval($importer["uid"]),
2582 intval($contact_record["id"]),
2585 dbesc(L10n::t("Sharing notification from Diaspora network")),
2587 dbesc(DateTimeFormat::utcNow())
2590 // automatic friend approval
2592 logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2594 Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2596 // technically they are sharing with us (CONTACT_IS_SHARING),
2597 // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2598 // we are going to change the relationship and make them a follower.
2600 if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2601 $new_relation = CONTACT_IS_FRIEND;
2602 } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2603 $new_relation = CONTACT_IS_SHARING;
2605 $new_relation = CONTACT_IS_FOLLOWER;
2609 "UPDATE `contact` SET `rel` = %d,
2617 intval($new_relation),
2618 dbesc(DateTimeFormat::utcNow()),
2619 dbesc(DateTimeFormat::utcNow()),
2620 intval($contact_record["id"])
2623 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2625 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2626 $ret = self::sendShare($u[0], $contact_record);
2628 // Send the profile data, maybe it weren't transmitted before
2629 self::sendProfile($importer["uid"], [$contact_record]);
2637 * @brief Fetches a message with a given guid
2639 * @param string $guid message guid
2640 * @param string $orig_author handle of the original post
2641 * @param string $author handle of the sharer
2643 * @return array The fetched item
2645 private static function originalItem($guid, $orig_author, $author)
2647 // Do we already have this item?
2649 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2650 `author-name`, `author-link`, `author-avatar`
2651 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2655 if (DBM::is_result($r)) {
2656 logger("reshared message ".$guid." already exists on system.");
2658 // Maybe it is already a reshared item?
2659 // Then refetch the content, if it is a reshare from a reshare.
2660 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2661 if (self::isReshare($r[0]["body"], true)) {
2663 } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2664 $r[0]["body"] = Markdown::toBBCode(BBCode::toMarkdown($r[0]["body"]));
2666 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2668 // Add OEmbed and other information to the body
2669 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2677 if (!DBM::is_result($r)) {
2678 $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2679 logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2680 $item_id = self::storeByGuid($guid, $server);
2683 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2684 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2685 $item_id = self::storeByGuid($guid, $server);
2690 "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2691 `author-name`, `author-link`, `author-avatar`
2692 FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2696 if (DBM::is_result($r)) {
2697 // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2698 if (self::isReshare($r[0]["body"], false)) {
2699 $r[0]["body"] = Markdown::toBBCode(BBCode::toMarkdown($r[0]["body"]));
2700 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2711 * @brief Processes a reshare message
2713 * @param array $importer Array of the importer user
2714 * @param object $data The message object
2715 * @param string $xml The original XML of the message
2717 * @return int the message id
2719 private static function receiveReshare($importer, $data, $xml)
2721 $author = notags(unxmlify($data->author));
2722 $guid = notags(unxmlify($data->guid));
2723 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2724 $root_author = notags(unxmlify($data->root_author));
2725 $root_guid = notags(unxmlify($data->root_guid));
2726 /// @todo handle unprocessed property "provider_display_name"
2727 $public = notags(unxmlify($data->public));
2729 $contact = self::allowedContactByHandle($importer, $author, false);
2734 $message_id = self::messageExists($importer["uid"], $guid);
2739 $original_item = self::originalItem($root_guid, $root_author, $author);
2740 if (!$original_item) {
2744 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2748 $datarray["uid"] = $importer["uid"];
2749 $datarray["contact-id"] = $contact["id"];
2750 $datarray["network"] = NETWORK_DIASPORA;
2752 $datarray["author-name"] = $contact["name"];
2753 $datarray["author-link"] = $contact["url"];
2754 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2756 $datarray["owner-name"] = $datarray["author-name"];
2757 $datarray["owner-link"] = $datarray["author-link"];
2758 $datarray["owner-avatar"] = $datarray["author-avatar"];
2760 $datarray["guid"] = $guid;
2761 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2763 $datarray["verb"] = ACTIVITY_POST;
2764 $datarray["gravity"] = GRAVITY_PARENT;
2766 $datarray["protocol"] = PROTOCOL_DIASPORA;
2767 $datarray["source"] = $xml;
2769 $prefix = share_header(
2770 $original_item["author-name"],
2771 $original_item["author-link"],
2772 $original_item["author-avatar"],
2773 $original_item["guid"],
2774 $original_item["created"],
2777 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2779 $datarray["tag"] = $original_item["tag"];
2780 $datarray["app"] = $original_item["app"];
2782 $datarray["plink"] = self::plink($author, $guid);
2783 $datarray["private"] = (($public == "false") ? 1 : 0);
2784 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2786 $datarray["object-type"] = $original_item["object-type"];
2788 self::fetchGuid($datarray);
2789 $message_id = Item::insert($datarray);
2791 self::sendParticipation($contact, $datarray);
2794 logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2802 * @brief Processes retractions
2804 * @param array $importer Array of the importer user
2805 * @param array $contact The contact of the item owner
2806 * @param object $data The message object
2808 * @return bool success
2810 private static function itemRetraction($importer, $contact, $data)
2812 $author = notags(unxmlify($data->author));
2813 $target_guid = notags(unxmlify($data->target_guid));
2814 $target_type = notags(unxmlify($data->target_type));
2816 $person = self::personByHandle($author);
2817 if (!is_array($person)) {
2818 logger("unable to find author detail for ".$author);
2822 if (empty($contact["url"])) {
2823 $contact["url"] = $person["url"];
2826 // Fetch items that are about to be deleted
2827 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2829 // When we receive a public retraction, we delete every item that we find.
2830 if ($importer['uid'] == 0) {
2831 $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2833 $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2835 $r = dba::select('item', $fields, $condition);
2836 if (!DBM::is_result($r)) {
2837 logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2841 while ($item = dba::fetch($r)) {
2842 // Fetch the parent item
2843 $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2845 // Only delete it if the parent author really fits
2846 if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2847 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2851 Item::deleteById($item["id"]);
2853 logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2855 // Now check if the retraction needs to be relayed by us
2856 if ($parent["origin"]) {
2858 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2866 * @brief Receives retraction messages
2868 * @param array $importer Array of the importer user
2869 * @param string $sender The sender of the message
2870 * @param object $data The message object
2872 * @return bool Success
2874 private static function receiveRetraction($importer, $sender, $data)
2876 $target_type = notags(unxmlify($data->target_type));
2878 $contact = self::contactByHandle($importer["uid"], $sender);
2879 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2880 logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2884 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2886 switch ($target_type) {
2891 case "StatusMessage":
2892 return self::itemRetraction($importer, $contact, $data);
2896 /// @todo What should we do with an "unshare"?
2897 // Removing the contact isn't correct since we still can read the public items
2898 Contact::remove($contact["id"]);
2902 logger("Unknown target type ".$target_type);
2909 * @brief Receives status messages
2911 * @param array $importer Array of the importer user
2912 * @param object $data The message object
2913 * @param string $xml The original XML of the message
2915 * @return int The message id of the newly created item
2917 private static function receiveStatusMessage($importer, $data, $xml)
2919 $author = notags(unxmlify($data->author));
2920 $guid = notags(unxmlify($data->guid));
2921 $created_at = DateTimeFormat::utc(notags(unxmlify($data->created_at)));
2922 $public = notags(unxmlify($data->public));
2923 $text = unxmlify($data->text);
2924 $provider_display_name = notags(unxmlify($data->provider_display_name));
2926 $contact = self::allowedContactByHandle($importer, $author, false);
2931 $message_id = self::messageExists($importer["uid"], $guid);
2937 if ($data->location) {
2938 foreach ($data->location->children() as $fieldname => $data) {
2939 $address[$fieldname] = notags(unxmlify($data));
2943 $body = Markdown::toBBCode($text);
2947 // Attach embedded pictures to the body
2949 foreach ($data->photo as $photo) {
2950 $body = "[img]".unxmlify($photo->remote_photo_path).
2951 unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2954 $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2956 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2958 // Add OEmbed and other information to the body
2959 if (!self::isRedmatrix($contact["url"])) {
2960 $body = add_page_info_to_body($body, false, true);
2964 /// @todo enable support for polls
2965 //if ($data->poll) {
2966 // foreach ($data->poll AS $poll)
2971 /// @todo enable support for events
2973 $datarray["uid"] = $importer["uid"];
2974 $datarray["contact-id"] = $contact["id"];
2975 $datarray["network"] = NETWORK_DIASPORA;
2977 $datarray["author-name"] = $contact["name"];
2978 $datarray["author-link"] = $contact["url"];
2979 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2981 $datarray["owner-name"] = $datarray["author-name"];
2982 $datarray["owner-link"] = $datarray["author-link"];
2983 $datarray["owner-avatar"] = $datarray["author-avatar"];
2985 $datarray["guid"] = $guid;
2986 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2988 $datarray["verb"] = ACTIVITY_POST;
2989 $datarray["gravity"] = GRAVITY_PARENT;
2991 $datarray["protocol"] = PROTOCOL_DIASPORA;
2992 $datarray["source"] = $xml;
2994 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
2996 if ($provider_display_name != "") {
2997 $datarray["app"] = $provider_display_name;
3000 $datarray["plink"] = self::plink($author, $guid);
3001 $datarray["private"] = (($public == "false") ? 1 : 0);
3002 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3004 if (isset($address["address"])) {
3005 $datarray["location"] = $address["address"];
3008 if (isset($address["lat"]) && isset($address["lng"])) {
3009 $datarray["coord"] = $address["lat"]." ".$address["lng"];
3012 self::fetchGuid($datarray);
3013 $message_id = Item::insert($datarray);
3015 self::sendParticipation($contact, $datarray);
3018 logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3025 /* ************************************************************************************** *
3026 * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3027 * ************************************************************************************** */
3030 * @brief returnes the handle of a contact
3032 * @param array $contact contact array
3034 * @return string the handle in the format user@domain.tld
3036 private static function myHandle($contact)
3038 if ($contact["addr"] != "") {
3039 return $contact["addr"];
3042 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3043 // So - just in case - we build the the address here.
3044 if ($contact["nickname"] != "") {
3045 $nick = $contact["nickname"];
3047 $nick = $contact["nick"];
3050 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3055 * @brief Creates the data for a private message in the new format
3057 * @param string $msg The message that is to be transmitted
3058 * @param array $user The record of the sender
3059 * @param array $contact Target of the communication
3060 * @param string $prvkey The private key of the sender
3061 * @param string $pubkey The public key of the receiver
3063 * @return string The encrypted data
3065 public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3067 logger("Message: ".$msg, LOGGER_DATA);
3069 // without a public key nothing will work
3071 logger("pubkey missing: contact id: ".$contact["id"]);
3075 $aes_key = openssl_random_pseudo_bytes(32);
3076 $b_aes_key = base64_encode($aes_key);
3077 $iv = openssl_random_pseudo_bytes(16);
3078 $b_iv = base64_encode($iv);
3080 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3082 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3084 $encrypted_key_bundle = "";
3085 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3087 $json_object = json_encode(
3088 ["aes_key" => base64_encode($encrypted_key_bundle),
3089 "encrypted_magic_envelope" => base64_encode($ciphertext)]
3092 return $json_object;
3096 * @brief Creates the envelope for the "fetch" endpoint and for the new format
3098 * @param string $msg The message that is to be transmitted
3099 * @param array $user The record of the sender
3101 * @return string The envelope
3103 public static function buildMagicEnvelope($msg, $user)
3105 $b64url_data = base64url_encode($msg);
3106 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3108 $key_id = base64url_encode(self::myHandle($user));
3109 $type = "application/xml";
3110 $encoding = "base64url";
3111 $alg = "RSA-SHA256";
3112 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3114 // Fallback if the private key wasn't transmitted in the expected field
3115 if ($user['uprvkey'] == "") {
3116 $user['uprvkey'] = $user['prvkey'];
3119 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3120 $sig = base64url_encode($signature);
3122 $xmldata = ["me:env" => ["me:data" => $data,
3123 "@attributes" => ["type" => $type],
3124 "me:encoding" => $encoding,
3127 "@attributes2" => ["key_id" => $key_id]]];
3129 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3131 return XML::fromArray($xmldata, $xml, false, $namespaces);
3135 * @brief Create the envelope for a message
3137 * @param string $msg The message that is to be transmitted
3138 * @param array $user The record of the sender
3139 * @param array $contact Target of the communication
3140 * @param string $prvkey The private key of the sender
3141 * @param string $pubkey The public key of the receiver
3142 * @param bool $public Is the message public?
3144 * @return string The message that will be transmitted to other servers
3146 private static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3148 // The message is put into an envelope with the sender's signature
3149 $envelope = self::buildMagicEnvelope($msg, $user);
3151 // Private messages are put into a second envelope, encrypted with the receivers public key
3153 $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3160 * @brief Creates a signature for a message
3162 * @param array $owner the array of the owner of the message
3163 * @param array $message The message that is to be signed
3165 * @return string The signature
3167 private static function signature($owner, $message)
3170 unset($sigmsg["author_signature"]);
3171 unset($sigmsg["parent_author_signature"]);
3173 $signed_text = implode(";", $sigmsg);
3175 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3179 * @brief Transmit a message to a target server
3181 * @param array $owner the array of the item owner
3182 * @param array $contact Target of the communication
3183 * @param string $envelope The message that is to be transmitted
3184 * @param bool $public_batch Is it a public post?
3185 * @param bool $queue_run Is the transmission called from the queue?
3186 * @param string $guid message guid
3188 * @return int Result of the transmission
3190 public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "", $no_queue = false)
3194 $enabled = intval(Config::get("system", "diaspora_enabled"));
3199 $logid = random_string(4);
3200 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3202 // Fetch the fcontact entry when there is missing data
3203 // Will possibly happen when data is transmitted to a DFRN contact
3204 if (empty($dest_url) && !empty($contact['addr'])) {
3205 $fcontact = self::personByHandle($contact['addr']);
3206 $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3210 logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3214 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3216 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3219 if (!intval(Config::get("system", "diaspora_test"))) {
3220 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3222 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3223 $return_code = $a->get_curl_code();
3225 logger("test_mode");
3230 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3232 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3234 logger("queue message");
3235 // queue message for redelivery
3236 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3239 // The message could not be delivered. We mark the contact as "dead"
3240 Contact::markForArchival($contact);
3241 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3242 // We successfully delivered a message, the contact is alive
3243 Contact::unmarkForArchival($contact);
3246 return $return_code ? $return_code : -1;
3251 * @brief Build the post xml
3253 * @param string $type The message type
3254 * @param array $message The message data
3256 * @return string The post XML
3258 public static function buildPostXml($type, $message)
3260 $data = [$type => $message];
3262 return XML::fromArray($data, $xml);
3266 * @brief Builds and transmit messages
3268 * @param array $owner the array of the item owner
3269 * @param array $contact Target of the communication
3270 * @param string $type The message type
3271 * @param array $message The message data
3272 * @param bool $public_batch Is it a public post?
3273 * @param string $guid message guid
3274 * @param bool $spool Should the transmission be spooled or transmitted?
3276 * @return int Result of the transmission
3278 private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3280 $msg = self::buildPostXml($type, $message);
3282 logger('message: '.$msg, LOGGER_DATA);
3283 logger('send guid '.$guid, LOGGER_DEBUG);
3285 // Fallback if the private key wasn't transmitted in the expected field
3286 if ($owner['uprvkey'] == "") {
3287 $owner['uprvkey'] = $owner['prvkey'];
3290 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3293 Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch, $guid);
3296 $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3299 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3301 return $return_code;
3305 * @brief sends a participation (Used to get all further updates)
3307 * @param array $contact Target of the communication
3308 * @param array $item Item array
3310 * @return int The result of the transmission
3312 private static function sendParticipation($contact, $item)
3314 // Don't send notifications for private postings
3315 if ($item['private']) {
3319 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3321 $result = Cache::get($cachekey);
3322 if (!is_null($result)) {
3326 // Fetch some user id to have a valid handle to transmit the participation.
3327 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3328 // If the item belongs to a user, we take this user id.
3329 if ($item['uid'] == 0) {
3330 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3331 $first_user = dba::selectFirst('user', ['uid'], $condition);
3332 $owner = User::getOwnerDataById($first_user['uid']);
3334 $owner = User::getOwnerDataById($item['uid']);
3337 $author = self::myHandle($owner);
3339 $message = ["author" => $author,
3340 "guid" => get_guid(32),
3341 "parent_type" => "Post",
3342 "parent_guid" => $item["guid"]];
3344 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3346 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3347 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3349 return self::buildAndTransmit($owner, $contact, "participation", $message);
3353 * @brief sends an account migration
3355 * @param array $owner the array of the item owner
3356 * @param array $contact Target of the communication
3357 * @param int $uid User ID
3359 * @return int The result of the transmission
3361 public static function sendAccountMigration($owner, $contact, $uid)
3363 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3364 $profile = self::createProfileData($uid);
3366 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3367 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3369 $message = ["author" => $old_handle,
3370 "profile" => $profile,
3371 "signature" => $signature];
3373 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3375 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3379 * @brief Sends a "share" message
3381 * @param array $owner the array of the item owner
3382 * @param array $contact Target of the communication
3384 * @return int The result of the transmission
3386 public static function sendShare($owner, $contact)
3389 * @todo support the different possible combinations of "following" and "sharing"
3390 * Currently, Diaspora only interprets the "sharing" field
3392 * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3396 switch ($contact["rel"]) {
3397 case CONTACT_IS_FRIEND:
3400 case CONTACT_IS_SHARING:
3403 case CONTACT_IS_FOLLOWER:
3409 $message = ["author" => self::myHandle($owner),
3410 "recipient" => $contact["addr"],
3411 "following" => "true",
3412 "sharing" => "true"];
3414 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3416 return self::buildAndTransmit($owner, $contact, "contact", $message);
3420 * @brief sends an "unshare"
3422 * @param array $owner the array of the item owner
3423 * @param array $contact Target of the communication
3425 * @return int The result of the transmission
3427 public static function sendUnshare($owner, $contact)
3429 $message = ["author" => self::myHandle($owner),
3430 "recipient" => $contact["addr"],
3431 "following" => "false",
3432 "sharing" => "false"];
3434 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3436 return self::buildAndTransmit($owner, $contact, "contact", $message);
3440 * @brief Checks a message body if it is a reshare
3442 * @param string $body The message body that is to be check
3443 * @param bool $complete Should it be a complete check or a simple check?
3445 * @return array|bool Reshare details or "false" if no reshare
3447 public static function isReshare($body, $complete = true)
3449 $body = trim($body);
3451 // Skip if it isn't a pure repeated messages
3452 // Does it start with a share?
3453 if ((strpos($body, "[share") > 0) && $complete) {
3457 // Does it end with a share?
3458 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3462 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3463 // Skip if there is no shared message in there
3464 if ($body == $attributes) {
3468 // If we don't do the complete check we quit here
3474 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3475 if ($matches[1] != "") {
3476 $guid = $matches[1];
3479 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3480 if ($matches[1] != "") {
3481 $guid = $matches[1];
3486 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3493 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3494 $ret["root_guid"] = $guid;
3500 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3501 if ($matches[1] != "") {
3502 $profile = $matches[1];
3505 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3506 if ($matches[1] != "") {
3507 $profile = $matches[1];
3512 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3513 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3518 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3519 if ($matches[1] != "") {
3520 $link = $matches[1];
3523 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3524 if ($matches[1] != "") {
3525 $link = $matches[1];
3528 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3529 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3537 * @brief Create an event array
3539 * @param integer $event_id The id of the event
3541 * @return array with event data
3543 private static function buildEvent($event_id)
3545 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3546 if (!DBM::is_result($r)) {
3554 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3555 if (!DBM::is_result($r)) {
3561 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3562 if (!DBM::is_result($r)) {
3568 $eventdata['author'] = self::myHandle($owner);
3570 if ($event['guid']) {
3571 $eventdata['guid'] = $event['guid'];
3574 $mask = DateTimeFormat::ATOM;
3576 /// @todo - establish "all day" events in Friendica
3577 $eventdata["all_day"] = "false";
3579 if (!$event['adjust']) {
3580 $eventdata['timezone'] = $user['timezone'];
3582 if ($eventdata['timezone'] == "") {
3583 $eventdata['timezone'] = 'UTC';
3587 if ($event['start']) {
3588 $eventdata['start'] = DateTimeFormat::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3590 if ($event['finish'] && !$event['nofinish']) {
3591 $eventdata['end'] = DateTimeFormat::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3593 if ($event['summary']) {
3594 $eventdata['summary'] = html_entity_decode(BBCode::toMarkdown($event['summary']));
3596 if ($event['desc']) {
3597 $eventdata['description'] = html_entity_decode(BBCode::toMarkdown($event['desc']));
3599 if ($event['location']) {
3601 $location["address"] = html_entity_decode(BBCode::toMarkdown($event['location']));
3602 $location["lat"] = 0;
3603 $location["lng"] = 0;
3604 $eventdata['location'] = $location;
3611 * @brief Create a post (status message or reshare)
3613 * @param array $item The item that will be exported
3614 * @param array $owner the array of the item owner
3617 * 'type' -> Message type ("status_message" or "reshare")
3618 * 'message' -> Array of XML elements of the status
3620 public static function buildStatus($item, $owner)
3622 $cachekey = "diaspora:buildStatus:".$item['guid'];
3624 $result = Cache::get($cachekey);
3625 if (!is_null($result)) {
3629 $myaddr = self::myHandle($owner);
3631 $public = (($item["private"]) ? "false" : "true");
3633 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3635 // Detect a share element and do a reshare
3636 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3637 $message = ["author" => $myaddr,
3638 "guid" => $item["guid"],
3639 "created_at" => $created,
3640 "root_author" => $ret["root_handle"],
3641 "root_guid" => $ret["root_guid"],
3642 "provider_display_name" => $item["app"],
3643 "public" => $public];
3647 $title = $item["title"];
3648 $body = $item["body"];
3650 // convert to markdown
3651 $body = html_entity_decode(BBCode::toMarkdown($body));
3654 if (strlen($title)) {
3655 $body = "## ".html_entity_decode($title)."\n\n".$body;
3658 if ($item["attach"]) {
3659 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3661 $body .= "\n".L10n::t("Attachments:")."\n";
3662 foreach ($matches as $mtch) {
3663 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3670 if ($item["location"] != "")
3671 $location["address"] = $item["location"];
3673 if ($item["coord"] != "") {
3674 $coord = explode(" ", $item["coord"]);
3675 $location["lat"] = $coord[0];
3676 $location["lng"] = $coord[1];
3679 $message = ["author" => $myaddr,
3680 "guid" => $item["guid"],
3681 "created_at" => $created,
3682 "public" => $public,
3684 "provider_display_name" => $item["app"],
3685 "location" => $location];
3687 // Diaspora rejects messages when they contain a location without "lat" or "lng"
3688 if (!isset($location["lat"]) || !isset($location["lng"])) {
3689 unset($message["location"]);
3692 if ($item['event-id'] > 0) {
3693 $event = self::buildEvent($item['event-id']);
3694 if (count($event)) {
3695 $message['event'] = $event;
3697 /// @todo Once Diaspora supports it, we will remove the body
3698 // $message['text'] = '';
3702 $type = "status_message";
3705 $msg = ["type" => $type, "message" => $message];
3707 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3713 * @brief Sends a post
3715 * @param array $item The item that will be exported
3716 * @param array $owner the array of the item owner
3717 * @param array $contact Target of the communication
3718 * @param bool $public_batch Is it a public post?
3720 * @return int The result of the transmission
3722 public static function sendStatus($item, $owner, $contact, $public_batch = false)
3724 $status = self::buildStatus($item, $owner);
3726 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3730 * @brief Creates a "like" object
3732 * @param array $item The item that will be exported
3733 * @param array $owner the array of the item owner
3735 * @return array The data for a "like"
3737 private static function constructLike($item, $owner)
3740 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3741 dbesc($item["thr-parent"])
3743 if (!DBM::is_result($p)) {
3749 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3751 if ($item['verb'] === ACTIVITY_LIKE) {
3753 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3754 $positive = "false";
3757 return(["author" => self::myHandle($owner),
3758 "guid" => $item["guid"],
3759 "parent_guid" => $parent["guid"],
3760 "parent_type" => $target_type,
3761 "positive" => $positive,
3762 "author_signature" => ""]);
3766 * @brief Creates an "EventParticipation" object
3768 * @param array $item The item that will be exported
3769 * @param array $owner the array of the item owner
3771 * @return array The data for an "EventParticipation"
3773 private static function constructAttend($item, $owner)
3776 "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3777 dbesc($item["thr-parent"])
3779 if (!DBM::is_result($p)) {
3785 switch ($item['verb']) {
3786 case ACTIVITY_ATTEND:
3787 $attend_answer = 'accepted';
3789 case ACTIVITY_ATTENDNO:
3790 $attend_answer = 'declined';
3792 case ACTIVITY_ATTENDMAYBE:
3793 $attend_answer = 'tentative';
3796 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3800 return(["author" => self::myHandle($owner),
3801 "guid" => $item["guid"],
3802 "parent_guid" => $parent["guid"],
3803 "status" => $attend_answer,
3804 "author_signature" => ""]);
3808 * @brief Creates the object for a comment
3810 * @param array $item The item that will be exported
3811 * @param array $owner the array of the item owner
3813 * @return array The data for a comment
3815 private static function constructComment($item, $owner)
3817 $cachekey = "diaspora:constructComment:".$item['guid'];
3819 $result = Cache::get($cachekey);
3820 if (!is_null($result)) {
3825 "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3826 intval($item["parent"]),
3827 intval($item["parent"])
3830 if (!DBM::is_result($p)) {
3836 $text = html_entity_decode(BBCode::toMarkdown($item["body"]));
3837 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
3839 $comment = ["author" => self::myHandle($owner),
3840 "guid" => $item["guid"],
3841 "created_at" => $created,
3842 "parent_guid" => $parent["guid"],
3844 "author_signature" => ""];
3846 // Send the thread parent guid only if it is a threaded comment
3847 if ($item['thr-parent'] != $item['parent-uri']) {
3848 $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3851 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3857 * @brief Send a like or a comment
3859 * @param array $item The item that will be exported
3860 * @param array $owner the array of the item owner
3861 * @param array $contact Target of the communication
3862 * @param bool $public_batch Is it a public post?
3864 * @return int The result of the transmission
3866 public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3868 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3869 $message = self::constructAttend($item, $owner);
3870 $type = "event_participation";
3871 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3872 $message = self::constructLike($item, $owner);
3875 $message = self::constructComment($item, $owner);
3883 $message["author_signature"] = self::signature($owner, $message);
3885 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3889 * @brief Creates a message from a signature record entry
3891 * @param array $item The item that will be exported
3892 * @param array $signature The entry of the "sign" record
3894 * @return string The message
3896 private static function messageFromSignature($item, $signature)
3898 // Split the signed text
3899 $signed_parts = explode(";", $signature['signed_text']);
3901 if ($item["deleted"]) {
3902 $message = ["author" => $signature['signer'],
3903 "target_guid" => $signed_parts[0],
3904 "target_type" => $signed_parts[1]];
3905 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3906 $message = ["author" => $signed_parts[4],
3907 "guid" => $signed_parts[1],
3908 "parent_guid" => $signed_parts[3],
3909 "parent_type" => $signed_parts[2],
3910 "positive" => $signed_parts[0],
3911 "author_signature" => $signature['signature'],
3912 "parent_author_signature" => ""];
3914 // Remove the comment guid
3915 $guid = array_shift($signed_parts);
3917 // Remove the parent guid
3918 $parent_guid = array_shift($signed_parts);
3920 // Remove the handle
3921 $handle = array_pop($signed_parts);
3923 // Glue the parts together
3924 $text = implode(";", $signed_parts);
3926 $message = ["author" => $handle,
3928 "parent_guid" => $parent_guid,
3929 "text" => implode(";", $signed_parts),
3930 "author_signature" => $signature['signature'],
3931 "parent_author_signature" => ""];
3937 * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3939 * @param array $item The item that will be exported
3940 * @param array $owner the array of the item owner
3941 * @param array $contact Target of the communication
3942 * @param bool $public_batch Is it a public post?
3944 * @return int The result of the transmission
3946 public static function sendRelay($item, $owner, $contact, $public_batch = false)
3948 if ($item["deleted"]) {
3949 return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3950 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3956 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3958 // fetch the original signature
3961 "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3966 logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3972 // Old way - is used by the internal Friendica functions
3973 /// @todo Change all signatur storing functions to the new format
3974 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3975 $message = self::messageFromSignature($item, $signature);
3977 $msg = json_decode($signature['signed_text'], true);
3980 if (is_array($msg)) {
3981 foreach ($msg as $field => $data) {
3982 if (!$item["deleted"]) {
3983 if ($field == "diaspora_handle") {
3986 if ($field == "target_type") {
3987 $field = "parent_type";
3991 $message[$field] = $data;
3994 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
3998 $message["parent_author_signature"] = self::signature($owner, $message);
4000 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
4002 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4006 * @brief Sends a retraction (deletion) of a message, like or comment
4008 * @param array $item The item that will be exported
4009 * @param array $owner the array of the item owner
4010 * @param array $contact Target of the communication
4011 * @param bool $public_batch Is it a public post?
4012 * @param bool $relay Is the retraction transmitted from a relay?
4014 * @return int The result of the transmission
4016 public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4018 $itemaddr = self::handleFromContact($item["contact-id"], $item["author-id"]);
4020 $msg_type = "retraction";
4022 if ($item['id'] == $item['parent']) {
4023 $target_type = "Post";
4024 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4025 $target_type = "Like";
4027 $target_type = "Comment";
4030 $message = ["author" => $itemaddr,
4031 "target_guid" => $item['guid'],
4032 "target_type" => $target_type];
4034 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4036 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4040 * @brief Sends a mail
4042 * @param array $item The item that will be exported
4043 * @param array $owner The owner
4044 * @param array $contact Target of the communication
4046 * @return int The result of the transmission
4048 public static function sendMail($item, $owner, $contact)
4050 $myaddr = self::myHandle($owner);
4053 "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4054 intval($item["convid"]),
4055 intval($item["uid"])
4058 if (!DBM::is_result($r)) {
4059 logger("conversation not found.");
4065 "author" => $cnv["creator"],
4066 "guid" => $cnv["guid"],
4067 "subject" => $cnv["subject"],
4068 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4069 "participants" => $cnv["recips"]
4072 $body = BBCode::toMarkdown($item["body"]);
4073 $created = DateTimeFormat::utc($item["created"], DateTimeFormat::ATOM);
4076 "author" => $myaddr,
4077 "guid" => $item["guid"],
4078 "conversation_guid" => $cnv["guid"],
4080 "created_at" => $created,
4083 if ($item["reply"]) {
4088 "author" => $cnv["creator"],
4089 "guid" => $cnv["guid"],
4090 "subject" => $cnv["subject"],
4091 "created_at" => DateTimeFormat::utc($cnv['created'], DateTimeFormat::ATOM),
4092 "participants" => $cnv["recips"],
4095 $type = "conversation";
4098 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4102 * @brief Split a name into first name and last name
4104 * @param string $name The name
4106 * @return array The array with "first" and "last"
4108 public static function splitName($name) {
4109 $name = trim($name);
4111 // Is the name longer than 64 characters? Then cut the rest of it.
4112 if (strlen($name) > 64) {
4113 if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4114 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4116 $name = substr($name, 0, 64);
4120 // Take the first word as first name
4121 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4122 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4123 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4124 return ['first' => $first, 'last' => $last];
4127 // Take the last word as last name
4128 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4129 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4131 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4132 return ['first' => $first, 'last' => $last];
4135 // Take the first 32 characters if there is no space in the first 32 characters
4136 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4137 $first = substr($name, 0, 32);
4138 $last = substr($name, 32);
4139 return ['first' => $first, 'last' => $last];
4142 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4143 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4145 // Check if the last name is longer than 32 characters
4146 if (strlen($last) > 32) {
4147 if (strpos($last, ' ') <= 32) {
4148 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4150 $last = substr($last, 0, 32);
4154 return ['first' => $first, 'last' => $last];
4158 * @brief Create profile data
4160 * @param int $uid The user id
4162 * @return array The profile data
4164 private static function createProfileData($uid)
4167 "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4169 INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4170 INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4171 WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4180 $handle = $profile["addr"];
4182 $split_name = self::splitName($profile['name']);
4183 $first = $split_name['first'];
4184 $last = $split_name['last'];
4186 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4187 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4188 $small = System::baseUrl().'/photo/custom/50/' .$profile['uid'].'.jpg';
4189 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4195 if ($searchable === 'true') {
4198 if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4199 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4203 $dob = DateTimeFormat::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4206 $about = $profile['about'];
4207 $about = strip_tags(BBCode::convert($about));
4209 $location = Profile::formatLocation($profile);
4211 if ($profile['pub_keywords']) {
4212 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4213 $kw = str_replace(' ', ' ', $kw);
4214 $arr = explode(' ', $profile['pub_keywords']);
4216 for ($x = 0; $x < 5; $x ++) {
4217 if (trim($arr[$x])) {
4218 $tags .= '#'. trim($arr[$x]) .' ';
4223 $tags = trim($tags);
4226 return ["author" => $handle,
4227 "first_name" => $first,
4228 "last_name" => $last,
4229 "image_url" => $large,
4230 "image_url_medium" => $medium,
4231 "image_url_small" => $small,
4233 "gender" => $profile['gender'],
4235 "location" => $location,
4236 "searchable" => $searchable,
4238 "tag_string" => $tags];
4242 * @brief Sends profile data
4244 * @param int $uid The user id
4245 * @param bool $recips optional, default false
4248 public static function sendProfile($uid, $recips = false)
4254 $owner = User::getOwnerDataById($uid);
4261 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4262 AND `uid` = %d AND `rel` != %d",
4263 dbesc(NETWORK_DIASPORA),
4265 intval(CONTACT_IS_SHARING)
4273 $message = self::createProfileData($uid);
4275 foreach ($recips as $recip) {
4276 logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4277 self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4282 * @brief Stores the signature for likes that are created on our system
4284 * @param array $contact The contact array of the "like"
4285 * @param int $post_id The post id of the "like"
4287 * @return bool Success
4289 public static function storeLikeSignature($contact, $post_id)
4291 // Is the contact the owner? Then fetch the private key
4292 if (!$contact['self'] || ($contact['uid'] == 0)) {
4293 logger("No owner post, so not storing signature", LOGGER_DEBUG);
4297 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4298 if (!DBM::is_result($r)) {
4302 $contact["uprvkey"] = $r[0]['prvkey'];
4304 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4305 if (!DBM::is_result($r)) {
4309 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4313 $message = self::constructLike($r[0], $contact);
4314 if ($message === false) {
4318 $message["author_signature"] = self::signature($contact, $message);
4321 * Now store the signature more flexible to dynamically support new fields.
4322 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4324 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4326 logger('Stored diaspora like signature');
4331 * @brief Stores the signature for comments that are created on our system
4333 * @param array $item The item array of the comment
4334 * @param array $contact The contact array of the item owner
4335 * @param string $uprvkey The private key of the sender
4336 * @param int $message_id The message id of the comment
4338 * @return bool Success
4340 public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4342 if ($uprvkey == "") {
4343 logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4347 $contact["uprvkey"] = $uprvkey;
4349 $message = self::constructComment($item, $contact);
4350 if ($message === false) {
4354 $message["author_signature"] = self::signature($contact, $message);
4357 * Now store the signature more flexible to dynamically support new fields.
4358 * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4360 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4362 logger('Stored diaspora comment signature');