]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Diaspora.php
Simplify include/bb2diaspora event format
[friendica.git] / src / Protocol / Diaspora.php
1 <?php
2 /**
3  * @file src/Protocol/diaspora.php
4  * @brief The implementation of the diaspora protocol
5  *
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.
9  */
10 namespace Friendica\Protocol;
11
12 use Friendica\App;
13 use Friendica\Core\System;
14 use Friendica\Core\Cache;
15 use Friendica\Core\Config;
16 use Friendica\Core\L10n;
17 use Friendica\Core\PConfig;
18 use Friendica\Core\Worker;
19 use Friendica\Database\DBM;
20 use Friendica\Model\Contact;
21 use Friendica\Model\GContact;
22 use Friendica\Model\Group;
23 use Friendica\Model\Item;
24 use Friendica\Model\Profile;
25 use Friendica\Model\Queue;
26 use Friendica\Model\User;
27 use Friendica\Network\Probe;
28 use Friendica\Util\Crypto;
29 use Friendica\Util\Network;
30 use Friendica\Util\Temporal;
31 use Friendica\Util\XML;
32 use dba;
33 use SimpleXMLElement;
34
35 require_once 'include/dba.php';
36 require_once 'include/items.php';
37 require_once 'include/bb2diaspora.php';
38 require_once 'include/datetime.php';
39
40 /**
41  * @brief This class contain functions to create and send Diaspora XML files
42  *
43  */
44 class Diaspora
45 {
46         /**
47          * @brief Return a list of relay servers
48          *
49          * This is an experimental Diaspora feature.
50          *
51          * @return array of relay servers
52          */
53         public static function relayList()
54         {
55                 $serverdata = Config::get("system", "relay_server");
56                 if ($serverdata == "") {
57                         return [];
58                 }
59
60                 $relay = [];
61
62                 $servers = explode(",", $serverdata);
63
64                 foreach ($servers as $server) {
65                         $server = trim($server);
66                         $addr = "relay@".str_replace("http://", "", normalise_link($server));
67                         $batch = $server."/receive/public";
68
69                         $relais = q(
70                                 "SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' AND `addr` = '%s' AND `nurl` = '%s' LIMIT 1",
71                                 dbesc($batch),
72                                 dbesc($addr),
73                                 dbesc(normalise_link($server))
74                         );
75
76                         if (!$relais) {
77                                 $r = q(
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                                         Temporal::utcNow(),
81                                         dbesc($addr),
82                                         dbesc($addr),
83                                         dbesc($server),
84                                         dbesc(normalise_link($server)),
85                                         dbesc($batch),
86                                         dbesc(NETWORK_DIASPORA),
87                                         intval(CONTACT_IS_FOLLOWER),
88                                         dbesc(Temporal::utcNow()),
89                                         dbesc(Temporal::utcNow()),
90                                         dbesc(Temporal::utcNow())
91                                 );
92
93                                 $relais = q("SELECT `batch`, `id`, `name`,`network` FROM `contact` WHERE `uid` = 0 AND `batch` = '%s' LIMIT 1", dbesc($batch));
94                                 if ($relais) {
95                                         $relay[] = $relais[0];
96                                 }
97                         } else {
98                                 $relay[] = $relais[0];
99                         }
100                 }
101
102                 return $relay;
103         }
104
105         /**
106          * @brief Return a list of participating contacts for a thread
107          *
108          * This is used for the participation feature.
109          * One of the parameters is a contact array.
110          * This is done to avoid duplicates.
111          *
112          * @param integer $thread   The id of the thread
113          * @param array   $contacts The previously fetched contacts
114          *
115          * @return array of relay servers
116          */
117         public static function participantsForThread($thread, $contacts)
118         {
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);
124
125                 while ($contact = dba::fetch($r)) {
126                         if (!empty($contact['fnetwork'])) {
127                                 $contact['network'] = $contact['fnetwork'];
128                         }
129                         unset($contact['fnetwork']);
130
131                         if (empty($contact['batch']) && !empty($contact['fbatch'])) {
132                                 $contact['batch'] = $contact['fbatch'];
133                         }
134                         unset($contact['fbatch']);
135
136                         $exists = false;
137                         foreach ($contacts as $entry) {
138                                 if ($entry['batch'] == $contact['batch']) {
139                                         $exists = true;
140                                 }
141                         }
142
143                         if (!$exists) {
144                                 $contacts[] = $contact;
145                         }
146                 }
147                 dba::close($r);
148
149                 return $contacts;
150         }
151
152         /**
153          * @brief repairs a signature that was double encoded
154          *
155          * The function is unused at the moment. It was copied from the old implementation.
156          *
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
160          *
161          * @return string the repaired signature
162          */
163         private static function repairSignature($signature, $handle = "", $level = 1)
164         {
165                 if ($signature == "") {
166                         return ($signature);
167                 }
168
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);
172
173                         // Do a recursive call to be able to fix even multiple levels
174                         if ($level < 10) {
175                                 $signature = self::repairSignature($signature, $handle, ++$level);
176                         }
177                 }
178
179                 return($signature);
180         }
181
182         /**
183          * @brief verify the envelope and return the verified data
184          *
185          * @param string $envelope The magic envelope
186          *
187          * @return string verified data
188          */
189         private static function verifyMagicEnvelope($envelope)
190         {
191                 $basedom = XML::parseString($envelope);
192
193                 if (!is_object($basedom)) {
194                         logger("Envelope is no XML file");
195                         return false;
196                 }
197
198                 $children = $basedom->children('http://salmon-protocol.org/ns/magic-env');
199
200                 if (sizeof($children) == 0) {
201                         logger("XML has no children");
202                         return false;
203                 }
204
205                 $handle = "";
206
207                 $data = base64url_decode($children->data);
208                 $type = $children->data->attributes()->type[0];
209
210                 $encoding = $children->encoding;
211
212                 $alg = $children->alg;
213
214                 $sig = base64url_decode($children->sig);
215                 $key_id = $children->sig->attributes()->key_id[0];
216                 if ($key_id != "") {
217                         $handle = base64url_decode($key_id);
218                 }
219
220                 $b64url_data = base64url_encode($data);
221                 $msg = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
222
223                 $signable_data = $msg.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
224
225                 $key = self::key($handle);
226
227                 $verify = Crypto::rsaVerify($signable_data, $sig, $key);
228                 if (!$verify) {
229                         logger('Message did not verify. Discarding.');
230                         return false;
231                 }
232
233                 return $data;
234         }
235
236         /**
237          * @brief encrypts data via AES
238          *
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
242          *
243          * @return string encrypted data
244          */
245         private static function aesEncrypt($key, $iv, $data)
246         {
247                 return openssl_encrypt($data, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
248         }
249
250         /**
251          * @brief decrypts data via AES
252          *
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
256          *
257          * @return string decrypted data
258          */
259         private static function aesDecrypt($key, $iv, $encrypted)
260         {
261                 return openssl_decrypt($encrypted, 'aes-256-cbc', str_pad($key, 32, "\0"), OPENSSL_RAW_DATA, str_pad($iv, 16, "\0"));
262         }
263
264         /**
265          * @brief: Decodes incoming Diaspora message in the new format
266          *
267          * @param array  $importer Array of the importer user
268          * @param string $raw      raw post message
269          *
270          * @return array
271          * 'message' -> decoded Diaspora XML message
272          * 'author' -> author diaspora handle
273          * 'key' -> author public key (converted to pkcs#8)
274          */
275         public static function decodeRaw($importer, $raw)
276         {
277                 $data = json_decode($raw);
278
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);
283
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);
287
288                         if (!is_object($j_outer_key_bundle)) {
289                                 logger('Outer Salmon did not verify. Discarding.');
290                                 System::httpExit(400);
291                         }
292
293                         $outer_iv = base64_decode($j_outer_key_bundle->iv);
294                         $outer_key = base64_decode($j_outer_key_bundle->key);
295
296                         $xml = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
297                 } else {
298                         $xml = $raw;
299                 }
300
301                 $basedom = XML::parseString($xml);
302
303                 if (!is_object($basedom)) {
304                         logger('Received data does not seem to be an XML. Discarding. '.$xml);
305                         System::httpExit(400);
306                 }
307
308                 $base = $basedom->children(NAMESPACE_SALMON_ME);
309
310                 // Not sure if this cleaning is needed
311                 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
312
313                 // Build the signed data
314                 $type = $base->data[0]->attributes()->type[0];
315                 $encoding = $base->encoding;
316                 $alg = $base->alg;
317                 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
318
319                 // This is the signature
320                 $signature = base64url_decode($base->sig);
321
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);
326
327                 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
328                 if (!$verify) {
329                         logger('Message did not verify. Discarding.');
330                         System::httpExit(400);
331                 }
332
333                 return ['message' => (string)base64url_decode($base->data),
334                                 'author' => unxmlify($author_addr),
335                                 'key' => (string)$key];
336         }
337
338         /**
339          * @brief: Decodes incoming Diaspora message in the deprecated format
340          *
341          * @param array  $importer Array of the importer user
342          * @param string $xml      urldecoded Diaspora salmon
343          *
344          * @return array
345          * 'message' -> decoded Diaspora XML message
346          * 'author' -> author diaspora handle
347          * 'key' -> author public key (converted to pkcs#8)
348          */
349         public static function decode($importer, $xml)
350         {
351                 $public = false;
352                 $basedom = XML::parseString($xml);
353
354                 if (!is_object($basedom)) {
355                         logger("XML is not parseable.");
356                         return false;
357                 }
358                 $children = $basedom->children('https://joindiaspora.com/protocol');
359
360                 if ($children->header) {
361                         $public = true;
362                         $author_link = str_replace('acct:', '', $children->header->author_id);
363                 } else {
364                         // This happens with posts from a relais
365                         if (!$importer) {
366                                 logger("This is no private post in the old format", LOGGER_DEBUG);
367                                 return false;
368                         }
369
370                         $encrypted_header = json_decode(base64_decode($children->encrypted_header));
371
372                         $encrypted_aes_key_bundle = base64_decode($encrypted_header->aes_key);
373                         $ciphertext = base64_decode($encrypted_header->ciphertext);
374
375                         $outer_key_bundle = '';
376                         openssl_private_decrypt($encrypted_aes_key_bundle, $outer_key_bundle, $importer['prvkey']);
377
378                         $j_outer_key_bundle = json_decode($outer_key_bundle);
379
380                         $outer_iv = base64_decode($j_outer_key_bundle->iv);
381                         $outer_key = base64_decode($j_outer_key_bundle->key);
382
383                         $decrypted = self::aesDecrypt($outer_key, $outer_iv, $ciphertext);
384
385                         logger('decrypted: '.$decrypted, LOGGER_DEBUG);
386                         $idom = XML::parseString($decrypted);
387
388                         $inner_iv = base64_decode($idom->iv);
389                         $inner_aes_key = base64_decode($idom->aes_key);
390
391                         $author_link = str_replace('acct:', '', $idom->author_id);
392                 }
393
394                 $dom = $basedom->children(NAMESPACE_SALMON_ME);
395
396                 // figure out where in the DOM tree our data is hiding
397
398                 if ($dom->provenance->data) {
399                         $base = $dom->provenance;
400                 } elseif ($dom->env->data) {
401                         $base = $dom->env;
402                 } elseif ($dom->data) {
403                         $base = $dom;
404                 }
405
406                 if (!$base) {
407                         logger('unable to locate salmon data in xml');
408                         System::httpExit(400);
409                 }
410
411
412                 // Stash the signature away for now. We have to find their key or it won't be good for anything.
413                 $signature = base64url_decode($base->sig);
414
415                 // unpack the  data
416
417                 // strip whitespace so our data element will return to one big base64 blob
418                 $data = str_replace([" ", "\t", "\r", "\n"], ["", "", "", ""], $base->data);
419
420
421                 // stash away some other stuff for later
422
423                 $type = $base->data[0]->attributes()->type[0];
424                 $keyhash = $base->sig[0]->attributes()->keyhash[0];
425                 $encoding = $base->encoding;
426                 $alg = $base->alg;
427
428
429                 $signed_data = $data.'.'.base64url_encode($type).'.'.base64url_encode($encoding).'.'.base64url_encode($alg);
430
431
432                 // decode the data
433                 $data = base64url_decode($data);
434
435
436                 if ($public) {
437                         $inner_decrypted = $data;
438                 } else {
439                         // Decode the encrypted blob
440                         $inner_encrypted = base64_decode($data);
441                         $inner_decrypted = self::aesDecrypt($inner_aes_key, $inner_iv, $inner_encrypted);
442                 }
443
444                 if (!$author_link) {
445                         logger('Could not retrieve author URI.');
446                         System::httpExit(400);
447                 }
448                 // Once we have the author URI, go to the web and try to find their public key
449                 // (first this will look it up locally if it is in the fcontact cache)
450                 // This will also convert diaspora public key from pkcs#1 to pkcs#8
451
452                 logger('Fetching key for '.$author_link);
453                 $key = self::key($author_link);
454
455                 if (!$key) {
456                         logger('Could not retrieve author key.');
457                         System::httpExit(400);
458                 }
459
460                 $verify = Crypto::rsaVerify($signed_data, $signature, $key);
461
462                 if (!$verify) {
463                         logger('Message did not verify. Discarding.');
464                         System::httpExit(400);
465                 }
466
467                 logger('Message verified.');
468
469                 return ['message' => (string)$inner_decrypted,
470                                 'author' => unxmlify($author_link),
471                                 'key' => (string)$key];
472         }
473
474
475         /**
476          * @brief Dispatches public messages and find the fitting receivers
477          *
478          * @param array $msg The post that will be dispatched
479          *
480          * @return int The message id of the generated message, "true" or "false" if there was an error
481          */
482         public static function dispatchPublic($msg)
483         {
484                 $enabled = intval(Config::get("system", "diaspora_enabled"));
485                 if (!$enabled) {
486                         logger("diaspora is disabled");
487                         return false;
488                 }
489
490                 if (!($postdata = self::validPosting($msg))) {
491                         logger("Invalid posting");
492                         return false;
493                 }
494
495                 $fields = $postdata['fields'];
496
497                 // Is it a an action (comment, like, ...) for our own post?
498                 if (isset($fields->parent_guid) && !$postdata["relayed"]) {
499                         $guid = notags(unxmlify($fields->parent_guid));
500                         $importer = self::importerForGuid($guid);
501                         if (is_array($importer)) {
502                                 logger("delivering to origin: ".$importer["name"]);
503                                 $message_id = self::dispatch($importer, $msg, $fields);
504                                 return $message_id;
505                         }
506                 }
507
508                 // Process item retractions. This has to be done separated from the other stuff,
509                 // since retractions for comments could come even from non followers.
510                 if (!empty($fields) && in_array($fields->getName(), ['retraction'])) {
511                         $target = notags(unxmlify($fields->target_type));
512                         if (in_array($target, ["Comment", "Like", "Post", "Reshare", "StatusMessage"])) {
513                                 logger('processing retraction for '.$target, LOGGER_DEBUG);
514                                 $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
515                                 $message_id = self::dispatch($importer, $msg, $fields);
516                                 return $message_id;
517                         }
518                 }
519
520                 // Now distribute it to the followers
521                 $r = q(
522                         "SELECT `user`.* FROM `user` WHERE `user`.`uid` IN
523                         (SELECT `contact`.`uid` FROM `contact` WHERE `contact`.`network` = '%s' AND `contact`.`addr` = '%s')
524                         AND NOT `account_expired` AND NOT `account_removed`",
525                         dbesc(NETWORK_DIASPORA),
526                         dbesc($msg["author"])
527                 );
528
529                 if (DBM::is_result($r)) {
530                         foreach ($r as $rr) {
531                                 logger("delivering to: ".$rr["username"]);
532                                 self::dispatch($rr, $msg, $fields);
533                         }
534                 } elseif (!Config::get('system', 'relay_subscribe', false)) {
535                         logger("Unwanted message from ".$msg["author"]." send by ".$_SERVER["REMOTE_ADDR"]." with ".$_SERVER["HTTP_USER_AGENT"].": ".print_r($msg, true), LOGGER_DEBUG);
536                 } else {
537                         // Use a dummy importer to import the data for the public copy
538                         $importer = ["uid" => 0, "page-flags" => PAGE_FREELOVE];
539                         $message_id = self::dispatch($importer, $msg, $fields);
540                 }
541
542                 return $message_id;
543         }
544
545         /**
546          * @brief Dispatches the different message types to the different functions
547          *
548          * @param array  $importer Array of the importer user
549          * @param array  $msg      The post that will be dispatched
550          * @param object $fields   SimpleXML object that contains the message
551          *
552          * @return int The message id of the generated message, "true" or "false" if there was an error
553          */
554         public static function dispatch($importer, $msg, $fields = null)
555         {
556                 // The sender is the handle of the contact that sent the message.
557                 // This will often be different with relayed messages (for example "like" and "comment")
558                 $sender = $msg["author"];
559
560                 // This is only needed for private postings since this is already done for public ones before
561                 if (is_null($fields)) {
562                         if (!($postdata = self::validPosting($msg))) {
563                                 logger("Invalid posting");
564                                 return false;
565                         }
566                         $fields = $postdata['fields'];
567                 }
568
569                 $type = $fields->getName();
570
571                 logger("Received message type ".$type." from ".$sender." for user ".$importer["uid"], LOGGER_DEBUG);
572
573                 switch ($type) {
574                         case "account_migration":
575                                 return self::receiveAccountMigration($importer, $fields);
576
577                         case "account_deletion":
578                                 return self::receiveAccountDeletion($importer, $fields);
579
580                         case "comment":
581                                 return self::receiveComment($importer, $sender, $fields, $msg["message"]);
582
583                         case "contact":
584                                 return self::receiveContactRequest($importer, $fields);
585
586                         case "conversation":
587                                 return self::receiveConversation($importer, $msg, $fields);
588
589                         case "like":
590                                 return self::receiveLike($importer, $sender, $fields);
591
592                         case "message":
593                                 return self::receiveMessage($importer, $fields);
594
595                         case "participation":
596                                 return self::receiveParticipation($importer, $fields);
597
598                         case "photo": // Not implemented
599                                 return self::receivePhoto($importer, $fields);
600
601                         case "poll_participation": // Not implemented
602                                 return self::receivePollParticipation($importer, $fields);
603
604                         case "profile":
605                                 return self::receiveProfile($importer, $fields);
606
607                         case "reshare":
608                                 return self::receiveReshare($importer, $fields, $msg["message"]);
609
610                         case "retraction":
611                                 return self::receiveRetraction($importer, $sender, $fields);
612
613                         case "status_message":
614                                 return self::receiveStatusMessage($importer, $fields, $msg["message"]);
615
616                         default:
617                                 logger("Unknown message type ".$type);
618                                 return false;
619                 }
620
621                 return true;
622         }
623
624         /**
625          * @brief Checks if a posting is valid and fetches the data fields.
626          *
627          * This function does not only check the signature.
628          * It also does the conversion between the old and the new diaspora format.
629          *
630          * @param array $msg Array with the XML, the sender handle and the sender signature
631          *
632          * @return bool|array If the posting is valid then an array with an SimpleXML object is returned
633          */
634         private static function validPosting($msg)
635         {
636                 $data = XML::parseString($msg["message"]);
637
638                 if (!is_object($data)) {
639                         logger("No valid XML ".$msg["message"], LOGGER_DEBUG);
640                         return false;
641                 }
642
643                 $first_child = $data->getName();
644
645                 // Is this the new or the old version?
646                 if ($data->getName() == "XML") {
647                         $oldXML = true;
648                         foreach ($data->post->children() as $child) {
649                                 $element = $child;
650                         }
651                 } else {
652                         $oldXML = false;
653                         $element = $data;
654                 }
655
656                 $type = $element->getName();
657                 $orig_type = $type;
658
659                 logger("Got message type ".$type.": ".$msg["message"], LOGGER_DATA);
660
661                 // All retractions are handled identically from now on.
662                 // In the new version there will only be "retraction".
663                 if (in_array($type, ["signed_retraction", "relayable_retraction"]))
664                         $type = "retraction";
665
666                 if ($type == "request") {
667                         $type = "contact";
668                 }
669
670                 $fields = new SimpleXMLElement("<".$type."/>");
671
672                 $signed_data = "";
673
674                 foreach ($element->children() as $fieldname => $entry) {
675                         if ($oldXML) {
676                                 // Translation for the old XML structure
677                                 if ($fieldname == "diaspora_handle") {
678                                         $fieldname = "author";
679                                 }
680                                 if ($fieldname == "participant_handles") {
681                                         $fieldname = "participants";
682                                 }
683                                 if (in_array($type, ["like", "participation"])) {
684                                         if ($fieldname == "target_type") {
685                                                 $fieldname = "parent_type";
686                                         }
687                                 }
688                                 if ($fieldname == "sender_handle") {
689                                         $fieldname = "author";
690                                 }
691                                 if ($fieldname == "recipient_handle") {
692                                         $fieldname = "recipient";
693                                 }
694                                 if ($fieldname == "root_diaspora_id") {
695                                         $fieldname = "root_author";
696                                 }
697                                 if ($type == "status_message") {
698                                         if ($fieldname == "raw_message") {
699                                                 $fieldname = "text";
700                                         }
701                                 }
702                                 if ($type == "retraction") {
703                                         if ($fieldname == "post_guid") {
704                                                 $fieldname = "target_guid";
705                                         }
706                                         if ($fieldname == "type") {
707                                                 $fieldname = "target_type";
708                                         }
709                                 }
710                         }
711
712                         if (($fieldname == "author_signature") && ($entry != "")) {
713                                 $author_signature = base64_decode($entry);
714                         } elseif (($fieldname == "parent_author_signature") && ($entry != "")) {
715                                 $parent_author_signature = base64_decode($entry);
716                         } elseif (!in_array($fieldname, ["author_signature", "parent_author_signature", "target_author_signature"])) {
717                                 if ($signed_data != "") {
718                                         $signed_data .= ";";
719                                 }
720
721                                 $signed_data .= $entry;
722                         }
723                         if (!in_array($fieldname, ["parent_author_signature", "target_author_signature"])
724                                 || ($orig_type == "relayable_retraction")
725                         ) {
726                                 XML::copy($entry, $fields, $fieldname);
727                         }
728                 }
729
730                 // This is something that shouldn't happen at all.
731                 if (in_array($type, ["status_message", "reshare", "profile"])) {
732                         if ($msg["author"] != $fields->author) {
733                                 logger("Message handle is not the same as envelope sender. Quitting this message.");
734                                 return false;
735                         }
736                 }
737
738                 // Only some message types have signatures. So we quit here for the other types.
739                 if (!in_array($type, ["comment", "like"])) {
740                         return ["fields" => $fields, "relayed" => false];
741                 }
742                 // No author_signature? This is a must, so we quit.
743                 if (!isset($author_signature)) {
744                         logger("No author signature for type ".$type." - Message: ".$msg["message"], LOGGER_DEBUG);
745                         return false;
746                 }
747
748                 if (isset($parent_author_signature)) {
749                         $relayed = true;
750
751                         $key = self::key($msg["author"]);
752
753                         if (!Crypto::rsaVerify($signed_data, $parent_author_signature, $key, "sha256")) {
754                                 logger("No valid parent author signature for parent author ".$msg["author"]. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$parent_author_signature, LOGGER_DEBUG);
755                                 return false;
756                         }
757                 } else {
758                         $relayed = false;
759                 }
760
761                 $key = self::key($fields->author);
762
763                 if (!Crypto::rsaVerify($signed_data, $author_signature, $key, "sha256")) {
764                         logger("No valid author signature for author ".$fields->author. " in type ".$type." - signed data: ".$signed_data." - Message: ".$msg["message"]." - Signature ".$author_signature, LOGGER_DEBUG);
765                         return false;
766                 } else {
767                         return ["fields" => $fields, "relayed" => $relayed];
768                 }
769         }
770
771         /**
772          * @brief Fetches the public key for a given handle
773          *
774          * @param string $handle The handle
775          *
776          * @return string The public key
777          */
778         private static function key($handle)
779         {
780                 $handle = strval($handle);
781
782                 logger("Fetching diaspora key for: ".$handle);
783
784                 $r = self::personByHandle($handle);
785                 if ($r) {
786                         return $r["pubkey"];
787                 }
788
789                 return "";
790         }
791
792         /**
793          * @brief Fetches data for a given handle
794          *
795          * @param string $handle The handle
796          *
797          * @return array the queried data
798          */
799         public static function personByHandle($handle)
800         {
801                 $r = q(
802                         "SELECT * FROM `fcontact` WHERE `network` = '%s' AND `addr` = '%s' LIMIT 1",
803                         dbesc(NETWORK_DIASPORA),
804                         dbesc($handle)
805                 );
806                 if ($r) {
807                         $person = $r[0];
808                         logger("In cache " . print_r($r, true), LOGGER_DEBUG);
809
810                         // update record occasionally so it doesn't get stale
811                         $d = strtotime($person["updated"]." +00:00");
812                         if ($d < strtotime("now - 14 days")) {
813                                 $update = true;
814                         }
815
816                         if ($person["guid"] == "") {
817                                 $update = true;
818                         }
819                 }
820
821                 if (!$person || $update) {
822                         logger("create or refresh", LOGGER_DEBUG);
823                         $r = Probe::uri($handle, NETWORK_DIASPORA);
824
825                         // Note that Friendica contacts will return a "Diaspora person"
826                         // if Diaspora connectivity is enabled on their server
827                         if ($r && ($r["network"] === NETWORK_DIASPORA)) {
828                                 self::addFContact($r, $update);
829                                 $person = $r;
830                         }
831                 }
832                 return $person;
833         }
834
835         /**
836          * @brief Updates the fcontact table
837          *
838          * @param array $arr    The fcontact data
839          * @param bool  $update Update or insert?
840          *
841          * @return string The id of the fcontact entry
842          */
843         private static function addFContact($arr, $update = false)
844         {
845                 if ($update) {
846                         $r = q(
847                                 "UPDATE `fcontact` SET
848                                         `name` = '%s',
849                                         `photo` = '%s',
850                                         `request` = '%s',
851                                         `nick` = '%s',
852                                         `addr` = '%s',
853                                         `guid` = '%s',
854                                         `batch` = '%s',
855                                         `notify` = '%s',
856                                         `poll` = '%s',
857                                         `confirm` = '%s',
858                                         `alias` = '%s',
859                                         `pubkey` = '%s',
860                                         `updated` = '%s'
861                                 WHERE `url` = '%s' AND `network` = '%s'",
862                                 dbesc($arr["name"]),
863                                 dbesc($arr["photo"]),
864                                 dbesc($arr["request"]),
865                                 dbesc($arr["nick"]),
866                                 dbesc(strtolower($arr["addr"])),
867                                 dbesc($arr["guid"]),
868                                 dbesc($arr["batch"]),
869                                 dbesc($arr["notify"]),
870                                 dbesc($arr["poll"]),
871                                 dbesc($arr["confirm"]),
872                                 dbesc($arr["alias"]),
873                                 dbesc($arr["pubkey"]),
874                                 dbesc(Temporal::utcNow()),
875                                 dbesc($arr["url"]),
876                                 dbesc($arr["network"])
877                         );
878                 } else {
879                         $r = q(
880                                 "INSERT INTO `fcontact` (`url`,`name`,`photo`,`request`,`nick`,`addr`, `guid`,
881                                         `batch`, `notify`,`poll`,`confirm`,`network`,`alias`,`pubkey`,`updated`)
882                                 VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')",
883                                 dbesc($arr["url"]),
884                                 dbesc($arr["name"]),
885                                 dbesc($arr["photo"]),
886                                 dbesc($arr["request"]),
887                                 dbesc($arr["nick"]),
888                                 dbesc($arr["addr"]),
889                                 dbesc($arr["guid"]),
890                                 dbesc($arr["batch"]),
891                                 dbesc($arr["notify"]),
892                                 dbesc($arr["poll"]),
893                                 dbesc($arr["confirm"]),
894                                 dbesc($arr["network"]),
895                                 dbesc($arr["alias"]),
896                                 dbesc($arr["pubkey"]),
897                                 dbesc(Temporal::utcNow())
898                         );
899                 }
900
901                 return $r;
902         }
903
904         /**
905          * @brief get a handle (user@domain.tld) from a given contact id or gcontact id
906          *
907          * @param int $contact_id  The id in the contact table
908          * @param int $gcontact_id The id in the gcontact table
909          *
910          * @return string the handle
911          */
912         public static function handleFromContact($contact_id, $gcontact_id = 0)
913         {
914                 $handle = false;
915
916                 logger("contact id is ".$contact_id." - gcontact id is ".$gcontact_id, LOGGER_DEBUG);
917
918                 if ($gcontact_id != 0) {
919                         $r = q(
920                                 "SELECT `addr` FROM `gcontact` WHERE `id` = %d AND `addr` != ''",
921                                 intval($gcontact_id)
922                         );
923
924                         if (DBM::is_result($r)) {
925                                 return strtolower($r[0]["addr"]);
926                         }
927                 }
928
929                 $r = q(
930                         "SELECT `network`, `addr`, `self`, `url`, `nick` FROM `contact` WHERE `id` = %d",
931                         intval($contact_id)
932                 );
933
934                 if (DBM::is_result($r)) {
935                         $contact = $r[0];
936
937                         logger("contact 'self' = ".$contact['self']." 'url' = ".$contact['url'], LOGGER_DEBUG);
938
939                         if ($contact['addr'] != "") {
940                                 $handle = $contact['addr'];
941                         } else {
942                                 $baseurl_start = strpos($contact['url'], '://') + 3;
943                                 // allows installations in a subdirectory--not sure how Diaspora will handle
944                                 $baseurl_length = strpos($contact['url'], '/profile') - $baseurl_start;
945                                 $baseurl = substr($contact['url'], $baseurl_start, $baseurl_length);
946                                 $handle = $contact['nick'].'@'.$baseurl;
947                         }
948                 }
949
950                 return strtolower($handle);
951         }
952
953         /**
954          * @brief get a url (scheme://domain.tld/u/user) from a given Diaspora*
955          * fcontact guid
956          *
957          * @param mixed $fcontact_guid Hexadecimal string guid
958          *
959          * @return string the contact url or null
960          */
961         public static function urlFromContactGuid($fcontact_guid)
962         {
963                 logger("fcontact guid is ".$fcontact_guid, LOGGER_DEBUG);
964
965                 $r = q(
966                         "SELECT `url` FROM `fcontact` WHERE `url` != '' AND `network` = '%s' AND `guid` = '%s'",
967                         dbesc(NETWORK_DIASPORA),
968                         dbesc($fcontact_guid)
969                 );
970
971                 if (DBM::is_result($r)) {
972                         return $r[0]['url'];
973                 }
974
975                 return null;
976         }
977
978         /**
979          * @brief Get a contact id for a given handle
980          *
981          * @todo Move to Friendica\Model\Contact
982          *
983          * @param int    $uid    The user id
984          * @param string $handle The handle in the format user@domain.tld
985          *
986          * @return int Contact id
987          */
988         private static function contactByHandle($uid, $handle)
989         {
990                 // First do a direct search on the contact table
991                 $r = q(
992                         "SELECT * FROM `contact` WHERE `uid` = %d AND `addr` = '%s' LIMIT 1",
993                         intval($uid),
994                         dbesc($handle)
995                 );
996
997                 if (DBM::is_result($r)) {
998                         return $r[0];
999                 } else {
1000                         /*
1001                          * We haven't found it?
1002                          * We use another function for it that will possibly create a contact entry.
1003                          */
1004                         $cid = Contact::getIdForURL($handle, $uid);
1005
1006                         if ($cid > 0) {
1007                                 /// @TODO Contact retrieval should be encapsulated into an "entity" class like `Contact`
1008                                 $r = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1", intval($cid));
1009
1010                                 if (DBM::is_result($r)) {
1011                                         return $r[0];
1012                                 }
1013                         }
1014                 }
1015
1016                 $handle_parts = explode("@", $handle);
1017                 $nurl_sql = "%%://".$handle_parts[1]."%%/profile/".$handle_parts[0];
1018                 $r = q(
1019                         "SELECT * FROM `contact` WHERE `network` = '%s' AND `uid` = %d AND `nurl` LIKE '%s' LIMIT 1",
1020                         dbesc(NETWORK_DFRN),
1021                         intval($uid),
1022                         dbesc($nurl_sql)
1023                 );
1024                 if (DBM::is_result($r)) {
1025                         return $r[0];
1026                 }
1027
1028                 logger("Haven't found contact for user ".$uid." and handle ".$handle, LOGGER_DEBUG);
1029                 return false;
1030         }
1031
1032         /**
1033          * @brief Check if posting is allowed for this contact
1034          *
1035          * @param array $importer   Array of the importer user
1036          * @param array $contact    The contact that is checked
1037          * @param bool  $is_comment Is the check for a comment?
1038          *
1039          * @return bool is the contact allowed to post?
1040          */
1041         private static function postAllow($importer, $contact, $is_comment = false)
1042         {
1043                 /*
1044                  * Perhaps we were already sharing with this person. Now they're sharing with us.
1045                  * That makes us friends.
1046                  * Normally this should have handled by getting a request - but this could get lost
1047                  */
1048                 // It is deactivated by now, due to side effects. See issue https://github.com/friendica/friendica/pull/4033
1049                 // It is not removed by now. Possibly the code is needed?
1050                 //if (!$is_comment && $contact["rel"] == CONTACT_IS_FOLLOWER && in_array($importer["page-flags"], array(PAGE_FREELOVE))) {
1051                 //      dba::update(
1052                 //              'contact',
1053                 //              array('rel' => CONTACT_IS_FRIEND, 'writable' => true),
1054                 //              array('id' => $contact["id"], 'uid' => $contact["uid"])
1055                 //      );
1056                 //
1057                 //      $contact["rel"] = CONTACT_IS_FRIEND;
1058                 //      logger("defining user ".$contact["nick"]." as friend");
1059                 //}
1060
1061                 // We don't seem to like that person
1062                 if ($contact["blocked"] || $contact["readonly"] || $contact["archive"]) {
1063                         // Maybe blocked, don't accept.
1064                         return false;
1065                         // We are following this person?
1066                 } elseif (($contact["rel"] == CONTACT_IS_SHARING) || ($contact["rel"] == CONTACT_IS_FRIEND)) {
1067                         // Yes, then it is fine.
1068                         return true;
1069                         // Is it a post to a community?
1070                 } elseif (($contact["rel"] == CONTACT_IS_FOLLOWER) && ($importer["page-flags"] == PAGE_COMMUNITY)) {
1071                         // That's good
1072                         return true;
1073                         // Is the message a global user or a comment?
1074                 } elseif (($importer["uid"] == 0) || $is_comment) {
1075                         // Messages for the global users and comments are always accepted
1076                         return true;
1077                 }
1078
1079                 return false;
1080         }
1081
1082         /**
1083          * @brief Fetches the contact id for a handle and checks if posting is allowed
1084          *
1085          * @param array  $importer   Array of the importer user
1086          * @param string $handle     The checked handle in the format user@domain.tld
1087          * @param bool   $is_comment Is the check for a comment?
1088          *
1089          * @return array The contact data
1090          */
1091         private static function allowedContactByHandle($importer, $handle, $is_comment = false)
1092         {
1093                 $contact = self::contactByHandle($importer["uid"], $handle);
1094                 if (!$contact) {
1095                         logger("A Contact for handle ".$handle." and user ".$importer["uid"]." was not found");
1096                         // If a contact isn't found, we accept it anyway if it is a comment
1097                         if ($is_comment) {
1098                                 return $importer;
1099                         } else {
1100                                 return false;
1101                         }
1102                 }
1103
1104                 if (!self::postAllow($importer, $contact, $is_comment)) {
1105                         logger("The handle: ".$handle." is not allowed to post to user ".$importer["uid"]);
1106                         return false;
1107                 }
1108                 return $contact;
1109         }
1110
1111         /**
1112          * @brief Does the message already exists on the system?
1113          *
1114          * @param int    $uid  The user id
1115          * @param string $guid The guid of the message
1116          *
1117          * @return int|bool message id if the message already was stored into the system - or false.
1118          */
1119         private static function messageExists($uid, $guid)
1120         {
1121                 $r = q(
1122                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1123                         intval($uid),
1124                         dbesc($guid)
1125                 );
1126
1127                 if (DBM::is_result($r)) {
1128                         logger("message ".$guid." already exists for user ".$uid);
1129                         return $r[0]["id"];
1130                 }
1131
1132                 return false;
1133         }
1134
1135         /**
1136          * @brief Checks for links to posts in a message
1137          *
1138          * @param array $item The item array
1139          * @return void
1140          */
1141         private static function fetchGuid($item)
1142         {
1143                 $expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
1144                 preg_replace_callback(
1145                         $expression,
1146                         function ($match) use ($item) {
1147                                 self::fetchGuidSub($match, $item);
1148                         },
1149                         $item["body"]
1150                 );
1151
1152                 preg_replace_callback(
1153                         "&\[url=/posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
1154                         function ($match) use ($item) {
1155                                 self::fetchGuidSub($match, $item);
1156                         },
1157                         $item["body"]
1158                 );
1159         }
1160
1161         /**
1162          * @brief Checks for relative /people/* links in an item body to match local
1163          * contacts or prepends the remote host taken from the author link.
1164          *
1165          * @param string $body        The item body to replace links from
1166          * @param string $author_link The author link for missing local contact fallback
1167          *
1168          * @return string the replaced string
1169          */
1170         public static function replacePeopleGuid($body, $author_link)
1171         {
1172                 $return = preg_replace_callback(
1173                         "&\[url=/people/([^\[\]]*)\](.*)\[\/url\]&Usi",
1174                         function ($match) use ($author_link) {
1175                                 // $match
1176                                 // 0 => '[url=/people/0123456789abcdef]Foo Bar[/url]'
1177                                 // 1 => '0123456789abcdef'
1178                                 // 2 => 'Foo Bar'
1179                                 $handle = self::urlFromContactGuid($match[1]);
1180
1181                                 if ($handle) {
1182                                         $return = '@[url='.$handle.']'.$match[2].'[/url]';
1183                                 } else {
1184                                         // No local match, restoring absolute remote URL from author scheme and host
1185                                         $author_url = parse_url($author_link);
1186                                         $return = '[url='.$author_url['scheme'].'://'.$author_url['host'].'/people/'.$match[1].']'.$match[2].'[/url]';
1187                                 }
1188
1189                                 return $return;
1190                         },
1191                         $body
1192                 );
1193
1194                 return $return;
1195         }
1196
1197         /**
1198          * @brief sub function of "fetchGuid" which checks for links in messages
1199          *
1200          * @param array $match array containing a link that has to be checked for a message link
1201          * @param array $item  The item array
1202          * @return void
1203          */
1204         private static function fetchGuidSub($match, $item)
1205         {
1206                 if (!self::storeByGuid($match[1], $item["author-link"])) {
1207                         self::storeByGuid($match[1], $item["owner-link"]);
1208                 }
1209         }
1210
1211         /**
1212          * @brief Fetches an item with a given guid from a given server
1213          *
1214          * @param string $guid   the message guid
1215          * @param string $server The server address
1216          * @param int    $uid    The user id of the user
1217          *
1218          * @return int the message id of the stored message or false
1219          */
1220         private static function storeByGuid($guid, $server, $uid = 0)
1221         {
1222                 $serverparts = parse_url($server);
1223                 $server = $serverparts["scheme"]."://".$serverparts["host"];
1224
1225                 logger("Trying to fetch item ".$guid." from ".$server, LOGGER_DEBUG);
1226
1227                 $msg = self::message($guid, $server);
1228
1229                 if (!$msg) {
1230                         return false;
1231                 }
1232
1233                 logger("Successfully fetched item ".$guid." from ".$server, LOGGER_DEBUG);
1234
1235                 // Now call the dispatcher
1236                 return self::dispatchPublic($msg);
1237         }
1238
1239         /**
1240          * @brief Fetches a message from a server
1241          *
1242          * @param string $guid   message guid
1243          * @param string $server The url of the server
1244          * @param int    $level  Endless loop prevention
1245          *
1246          * @return array
1247          *      'message' => The message XML
1248          *      'author' => The author handle
1249          *      'key' => The public key of the author
1250          */
1251         private static function message($guid, $server, $level = 0)
1252         {
1253                 if ($level > 5) {
1254                         return false;
1255                 }
1256
1257                 // This will work for new Diaspora servers and Friendica servers from 3.5
1258                 $source_url = $server."/fetch/post/".urlencode($guid);
1259
1260                 logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1261
1262                 $envelope = Network::fetchUrl($source_url);
1263                 if ($envelope) {
1264                         logger("Envelope was fetched.", LOGGER_DEBUG);
1265                         $x = self::verifyMagicEnvelope($envelope);
1266                         if (!$x) {
1267                                 logger("Envelope could not be verified.", LOGGER_DEBUG);
1268                         } else {
1269                                 logger("Envelope was verified.", LOGGER_DEBUG);
1270                         }
1271                 } else {
1272                         $x = false;
1273                 }
1274
1275                 // This will work for older Diaspora and Friendica servers
1276                 if (!$x) {
1277                         $source_url = $server."/p/".urlencode($guid).".xml";
1278                         logger("Fetch post from ".$source_url, LOGGER_DEBUG);
1279
1280                         $x = Network::fetchUrl($source_url);
1281                         if (!$x) {
1282                                 return false;
1283                         }
1284                 }
1285
1286                 $source_xml = XML::parseString($x);
1287
1288                 if (!is_object($source_xml)) {
1289                         return false;
1290                 }
1291
1292                 if ($source_xml->post->reshare) {
1293                         // Reshare of a reshare - old Diaspora version
1294                         logger("Message is a reshare", LOGGER_DEBUG);
1295                         return self::message($source_xml->post->reshare->root_guid, $server, ++$level);
1296                 } elseif ($source_xml->getName() == "reshare") {
1297                         // Reshare of a reshare - new Diaspora version
1298                         logger("Message is a new reshare", LOGGER_DEBUG);
1299                         return self::message($source_xml->root_guid, $server, ++$level);
1300                 }
1301
1302                 $author = "";
1303
1304                 // Fetch the author - for the old and the new Diaspora version
1305                 if ($source_xml->post->status_message->diaspora_handle) {
1306                         $author = (string)$source_xml->post->status_message->diaspora_handle;
1307                 } elseif ($source_xml->author && ($source_xml->getName() == "status_message")) {
1308                         $author = (string)$source_xml->author;
1309                 }
1310
1311                 // If this isn't a "status_message" then quit
1312                 if (!$author) {
1313                         logger("Message doesn't seem to be a status message", LOGGER_DEBUG);
1314                         return false;
1315                 }
1316
1317                 $msg = ["message" => $x, "author" => $author];
1318
1319                 $msg["key"] = self::key($msg["author"]);
1320
1321                 return $msg;
1322         }
1323
1324         /**
1325          * @brief Fetches the item record of a given guid
1326          *
1327          * @param int    $uid     The user id
1328          * @param string $guid    message guid
1329          * @param string $author  The handle of the item
1330          * @param array  $contact The contact of the item owner
1331          *
1332          * @return array the item record
1333          */
1334         private static function parentItem($uid, $guid, $author, $contact)
1335         {
1336                 $r = q(
1337                         "SELECT `id`, `parent`, `body`, `wall`, `uri`, `guid`, `private`, `origin`,
1338                                 `author-name`, `author-link`, `author-avatar`,
1339                                 `owner-name`, `owner-link`, `owner-avatar`
1340                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1341                         intval($uid),
1342                         dbesc($guid)
1343                 );
1344
1345                 if (!$r) {
1346                         $result = self::storeByGuid($guid, $contact["url"], $uid);
1347
1348                         if (!$result) {
1349                                 $person = self::personByHandle($author);
1350                                 $result = self::storeByGuid($guid, $person["url"], $uid);
1351                         }
1352
1353                         if ($result) {
1354                                 logger("Fetched missing item ".$guid." - result: ".$result, LOGGER_DEBUG);
1355
1356                                 $r = q(
1357                                         "SELECT `id`, `body`, `wall`, `uri`, `private`, `origin`,
1358                                                 `author-name`, `author-link`, `author-avatar`,
1359                                                 `owner-name`, `owner-link`, `owner-avatar`
1360                                         FROM `item` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1361                                         intval($uid),
1362                                         dbesc($guid)
1363                                 );
1364                         }
1365                 }
1366
1367                 if (!$r) {
1368                         logger("parent item not found: parent: ".$guid." - user: ".$uid);
1369                         return false;
1370                 } else {
1371                         logger("parent item found: parent: ".$guid." - user: ".$uid);
1372                         return $r[0];
1373                 }
1374         }
1375
1376         /**
1377          * @brief returns contact details
1378          *
1379          * @param array $contact The default contact if the person isn't found
1380          * @param array $person  The record of the person
1381          * @param int   $uid     The user id
1382          *
1383          * @return array
1384          *      'cid' => contact id
1385          *      'network' => network type
1386          */
1387         private static function authorContactByUrl($contact, $person, $uid)
1388         {
1389                 $r = q(
1390                         "SELECT `id`, `network`, `url` FROM `contact` WHERE `nurl` = '%s' AND `uid` = %d LIMIT 1",
1391                         dbesc(normalise_link($person["url"])),
1392                         intval($uid)
1393                 );
1394                 if ($r) {
1395                         $cid = $r[0]["id"];
1396                         $network = $r[0]["network"];
1397                 } else {
1398                         $cid = $contact["id"];
1399                         $network = NETWORK_DIASPORA;
1400                 }
1401
1402                 return ["cid" => $cid, "network" => $network];
1403         }
1404
1405         /**
1406          * @brief Is the profile a hubzilla profile?
1407          *
1408          * @param string $url The profile link
1409          *
1410          * @return bool is it a hubzilla server?
1411          */
1412         public static function isRedmatrix($url)
1413         {
1414                 return(strstr($url, "/channel/"));
1415         }
1416
1417         /**
1418          * @brief Generate a post link with a given handle and message guid
1419          *
1420          * @param string $addr        The user handle
1421          * @param string $guid        message guid
1422          * @param string $parent_guid optional parent guid
1423          *
1424          * @return string the post link
1425          */
1426         private static function plink($addr, $guid, $parent_guid = '')
1427         {
1428                 $r = q("SELECT `url`, `nick`, `network` FROM `fcontact` WHERE `addr`='%s' LIMIT 1", dbesc($addr));
1429
1430                 // Fallback
1431                 if (!DBM::is_result($r)) {
1432                         if ($parent_guid != '') {
1433                                 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1434                         } else {
1435                                 return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1436                         }
1437                 }
1438
1439                 // Friendica contacts are often detected as Diaspora contacts in the "fcontact" table
1440                 // So we try another way as well.
1441                 $s = q("SELECT `network` FROM `gcontact` WHERE `nurl`='%s' LIMIT 1", dbesc(normalise_link($r[0]["url"])));
1442                 if (DBM::is_result($s)) {
1443                         $r[0]["network"] = $s[0]["network"];
1444                 }
1445
1446                 if ($r[0]["network"] == NETWORK_DFRN) {
1447                         return str_replace("/profile/".$r[0]["nick"]."/", "/display/".$guid, $r[0]["url"]."/");
1448                 }
1449
1450                 if (self::isRedmatrix($r[0]["url"])) {
1451                         return $r[0]["url"]."/?f=&mid=".$guid;
1452                 }
1453
1454                 if ($parent_guid != '') {
1455                         return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $parent_guid . "#" . $guid;
1456                 } else {
1457                         return "https://".substr($addr, strpos($addr, "@") + 1) . "/posts/" . $guid;
1458                 }
1459         }
1460
1461         /**
1462          * @brief Receives account migration
1463          *
1464          * @param array  $importer Array of the importer user
1465          * @param object $data     The message object
1466          *
1467          * @return bool Success
1468          */
1469         private static function receiveAccountMigration($importer, $data)
1470         {
1471                 $old_handle = notags(unxmlify($data->author));
1472                 $new_handle = notags(unxmlify($data->profile->author));
1473                 $signature = notags(unxmlify($data->signature));
1474
1475                 $contact = self::contactByHandle($importer["uid"], $old_handle);
1476                 if (!$contact) {
1477                         logger("cannot find contact for sender: ".$old_handle." and user ".$importer["uid"]);
1478                         return false;
1479                 }
1480
1481                 logger("Got migration for ".$old_handle.", to ".$new_handle." with user ".$importer["uid"]);
1482
1483                 // Check signature
1484                 $signed_text = 'AccountMigration:'.$old_handle.':'.$new_handle;
1485                 $key = self::key($old_handle);
1486                 if (!Crypto::rsaVerify($signed_text, $signature, $key, "sha256")) {
1487                         logger('No valid signature for migration.');
1488                         return false;
1489                 }
1490
1491                 // Update the profile
1492                 self::receiveProfile($importer, $data->profile);
1493
1494                 // change the technical stuff in contact and gcontact
1495                 $data = Probe::uri($new_handle);
1496                 if ($data['network'] == NETWORK_PHANTOM) {
1497                         logger('Account for '.$new_handle." couldn't be probed.");
1498                         return false;
1499                 }
1500
1501                 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1502                                 'name' => $data['name'], 'nick' => $data['nick'],
1503                                 'addr' => $data['addr'], 'batch' => $data['batch'],
1504                                 'notify' => $data['notify'], 'poll' => $data['poll'],
1505                                 'network' => $data['network']];
1506
1507                 dba::update('contact', $fields, ['addr' => $old_handle]);
1508
1509                 $fields = ['url' => $data['url'], 'nurl' => normalise_link($data['url']),
1510                                 'name' => $data['name'], 'nick' => $data['nick'],
1511                                 'addr' => $data['addr'], 'connect' => $data['addr'],
1512                                 'notify' => $data['notify'], 'photo' => $data['photo'],
1513                                 'server_url' => $data['baseurl'], 'network' => $data['network']];
1514
1515                 dba::update('gcontact', $fields, ['addr' => $old_handle]);
1516
1517                 logger('Contacts are updated.');
1518
1519                 // update items
1520                 /// @todo This is an extreme performance killer
1521                 $fields = [
1522                         'owner-link' => [$contact["url"], $data["url"]],
1523                         'author-link' => [$contact["url"], $data["url"]],
1524                 ];
1525                 foreach ($fields as $n => $f) {
1526                         $r = q(
1527                                 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1528                                 $n,
1529                                 dbesc($f[0]),
1530                                 intval($importer["uid"])
1531                         );
1532
1533                         if (DBM::is_result($r)) {
1534                                 $x = q(
1535                                         "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1536                                         $n,
1537                                         dbesc($f[1]),
1538                                         $n,
1539                                         dbesc($f[0]),
1540                                         intval($importer["uid"])
1541                                 );
1542
1543                                 if ($x === false) {
1544                                         return false;
1545                                 }
1546                         }
1547                 }
1548
1549                 logger('Items are updated.');
1550
1551                 return true;
1552         }
1553
1554         /**
1555          * @brief Processes an account deletion
1556          *
1557          * @param array  $importer Array of the importer user
1558          * @param object $data     The message object
1559          *
1560          * @return bool Success
1561          */
1562         private static function receiveAccountDeletion($importer, $data)
1563         {
1564                 /// @todo Account deletion should remove the contact from the global contacts as well
1565
1566                 $author = notags(unxmlify($data->author));
1567
1568                 $contact = self::contactByHandle($importer["uid"], $author);
1569                 if (!$contact) {
1570                         logger("cannot find contact for author: ".$author);
1571                         return false;
1572                 }
1573
1574                 // We now remove the contact
1575                 Contact::remove($contact["id"]);
1576                 return true;
1577         }
1578
1579         /**
1580          * @brief Fetch the uri from our database if we already have this item (maybe from ourselves)
1581          *
1582          * @param string  $author    Author handle
1583          * @param string  $guid      Message guid
1584          * @param boolean $onlyfound Only return uri when found in the database
1585          *
1586          * @return string The constructed uri or the one from our database
1587          */
1588         private static function getUriFromGuid($author, $guid, $onlyfound = false)
1589         {
1590                 $r = q("SELECT `uri` FROM `item` WHERE `guid` = '%s' LIMIT 1", dbesc($guid));
1591                 if (DBM::is_result($r)) {
1592                         return $r[0]["uri"];
1593                 } elseif (!$onlyfound) {
1594                         return $author.":".$guid;
1595                 }
1596
1597                 return "";
1598         }
1599
1600         /**
1601          * @brief Fetch the guid from our database with a given uri
1602          *
1603          * @param string $uri Message uri
1604          * @param string $uid Author handle
1605          *
1606          * @return string The post guid
1607          */
1608         private static function getGuidFromUri($uri, $uid)
1609         {
1610                 $r = q("SELECT `guid` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", dbesc($uri), intval($uid));
1611                 if (DBM::is_result($r)) {
1612                         return $r[0]["guid"];
1613                 } else {
1614                         return false;
1615                 }
1616         }
1617
1618         /**
1619          * @brief Find the best importer for a comment, like, ...
1620          *
1621          * @param string $guid The guid of the item
1622          *
1623          * @return array|boolean the origin owner of that post - or false
1624          */
1625         private static function importerForGuid($guid)
1626         {
1627                 $item = dba::fetch_first("SELECT `uid` FROM `item` WHERE `origin` AND `guid` = ? LIMIT 1", $guid);
1628
1629                 if (DBM::is_result($item)) {
1630                         logger("Found user ".$item['uid']." as owner of item ".$guid, LOGGER_DEBUG);
1631                         $contact = dba::fetch_first("SELECT * FROM `contact` WHERE `self` AND `uid` = ?", $item['uid']);
1632                         if (DBM::is_result($contact)) {
1633                                 return $contact;
1634                         }
1635                 }
1636                 return false;
1637         }
1638
1639         /**
1640          * @brief Processes an incoming comment
1641          *
1642          * @param array  $importer Array of the importer user
1643          * @param string $sender   The sender of the message
1644          * @param object $data     The message object
1645          * @param string $xml      The original XML of the message
1646          *
1647          * @return int The message id of the generated comment or "false" if there was an error
1648          */
1649         private static function receiveComment($importer, $sender, $data, $xml)
1650         {
1651                 $author = notags(unxmlify($data->author));
1652                 $guid = notags(unxmlify($data->guid));
1653                 $parent_guid = notags(unxmlify($data->parent_guid));
1654                 $text = unxmlify($data->text);
1655
1656                 if (isset($data->created_at)) {
1657                         $created_at = Temporal::utc(notags(unxmlify($data->created_at)));
1658                 } else {
1659                         $created_at = Temporal::utcNow();
1660                 }
1661
1662                 if (isset($data->thread_parent_guid)) {
1663                         $thread_parent_guid = notags(unxmlify($data->thread_parent_guid));
1664                         $thr_uri = self::getUriFromGuid("", $thread_parent_guid, true);
1665                 } else {
1666                         $thr_uri = "";
1667                 }
1668
1669                 $contact = self::allowedContactByHandle($importer, $sender, true);
1670                 if (!$contact) {
1671                         return false;
1672                 }
1673
1674                 $message_id = self::messageExists($importer["uid"], $guid);
1675                 if ($message_id) {
1676                         return true;
1677                 }
1678
1679                 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
1680                 if (!$parent_item) {
1681                         return false;
1682                 }
1683
1684                 $person = self::personByHandle($author);
1685                 if (!is_array($person)) {
1686                         logger("unable to find author details");
1687                         return false;
1688                 }
1689
1690                 // Fetch the contact id - if we know this contact
1691                 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
1692
1693                 $datarray = [];
1694
1695                 $datarray["uid"] = $importer["uid"];
1696                 $datarray["contact-id"] = $author_contact["cid"];
1697                 $datarray["network"]  = $author_contact["network"];
1698
1699                 $datarray["author-name"] = $person["name"];
1700                 $datarray["author-link"] = $person["url"];
1701                 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
1702
1703                 $datarray["owner-name"] = $contact["name"];
1704                 $datarray["owner-link"] = $contact["url"];
1705                 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
1706
1707                 $datarray["guid"] = $guid;
1708                 $datarray["uri"] = self::getUriFromGuid($author, $guid);
1709
1710                 $datarray["type"] = "remote-comment";
1711                 $datarray["verb"] = ACTIVITY_POST;
1712                 $datarray["gravity"] = GRAVITY_COMMENT;
1713
1714                 if ($thr_uri != "") {
1715                         $datarray["parent-uri"] = $thr_uri;
1716                 } else {
1717                         $datarray["parent-uri"] = $parent_item["uri"];
1718                 }
1719
1720                 $datarray["object-type"] = ACTIVITY_OBJ_COMMENT;
1721
1722                 $datarray["protocol"] = PROTOCOL_DIASPORA;
1723                 $datarray["source"] = $xml;
1724
1725                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
1726
1727                 $datarray["plink"] = self::plink($author, $guid, $parent_item['guid']);
1728
1729                 $body = diaspora2bb($text);
1730
1731                 $datarray["body"] = self::replacePeopleGuid($body, $person["url"]);
1732
1733                 self::fetchGuid($datarray);
1734
1735                 $message_id = Item::insert($datarray);
1736
1737                 if ($message_id <= 0) {
1738                         return false;
1739                 }
1740
1741                 if ($message_id) {
1742                         logger("Stored comment ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
1743                 }
1744
1745                 // If we are the origin of the parent we store the original data and notify our followers
1746                 if ($message_id && $parent_item["origin"]) {
1747                         // Formerly we stored the signed text, the signature and the author in different fields.
1748                         // We now store the raw data so that we are more flexible.
1749                         dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
1750
1751                         // notify others
1752                         Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
1753                 }
1754
1755                 return true;
1756         }
1757
1758         /**
1759          * @brief processes and stores private messages
1760          *
1761          * @param array  $importer     Array of the importer user
1762          * @param array  $contact      The contact of the message
1763          * @param object $data         The message object
1764          * @param array  $msg          Array of the processed message, author handle and key
1765          * @param object $mesg         The private message
1766          * @param array  $conversation The conversation record to which this message belongs
1767          *
1768          * @return bool "true" if it was successful
1769          */
1770         private static function receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation)
1771         {
1772                 $author = notags(unxmlify($data->author));
1773                 $guid = notags(unxmlify($data->guid));
1774                 $subject = notags(unxmlify($data->subject));
1775
1776                 // "diaspora_handle" is the element name from the old version
1777                 // "author" is the element name from the new version
1778                 if ($mesg->author) {
1779                         $msg_author = notags(unxmlify($mesg->author));
1780                 } elseif ($mesg->diaspora_handle) {
1781                         $msg_author = notags(unxmlify($mesg->diaspora_handle));
1782                 } else {
1783                         return false;
1784                 }
1785
1786                 $msg_guid = notags(unxmlify($mesg->guid));
1787                 $msg_conversation_guid = notags(unxmlify($mesg->conversation_guid));
1788                 $msg_text = unxmlify($mesg->text);
1789                 $msg_created_at = Temporal::utc(notags(unxmlify($mesg->created_at)));
1790
1791                 if ($msg_conversation_guid != $guid) {
1792                         logger("message conversation guid does not belong to the current conversation.");
1793                         return false;
1794                 }
1795
1796                 $body = diaspora2bb($msg_text);
1797                 $message_uri = $msg_author.":".$msg_guid;
1798
1799                 $person = self::personByHandle($msg_author);
1800
1801                 dba::lock('mail');
1802
1803                 $r = q(
1804                         "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
1805                         dbesc($msg_guid),
1806                         intval($importer["uid"])
1807                 );
1808                 if (DBM::is_result($r)) {
1809                         logger("duplicate message already delivered.", LOGGER_DEBUG);
1810                         return false;
1811                 }
1812
1813                 q(
1814                         "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
1815                         VALUES (%d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
1816                         intval($importer["uid"]),
1817                         dbesc($msg_guid),
1818                         intval($conversation["id"]),
1819                         dbesc($person["name"]),
1820                         dbesc($person["photo"]),
1821                         dbesc($person["url"]),
1822                         intval($contact["id"]),
1823                         dbesc($subject),
1824                         dbesc($body),
1825                         0,
1826                         0,
1827                         dbesc($message_uri),
1828                         dbesc($author.":".$guid),
1829                         dbesc($msg_created_at)
1830                 );
1831
1832                 dba::unlock();
1833
1834                 dba::update('conv', ['updated' => Temporal::utcNow()], ['id' => $conversation["id"]]);
1835
1836                 notification(
1837                         [
1838                         "type" => NOTIFY_MAIL,
1839                         "notify_flags" => $importer["notify-flags"],
1840                         "language" => $importer["language"],
1841                         "to_name" => $importer["username"],
1842                         "to_email" => $importer["email"],
1843                         "uid" =>$importer["uid"],
1844                         "item" => ["subject" => $subject, "body" => $body],
1845                         "source_name" => $person["name"],
1846                         "source_link" => $person["url"],
1847                         "source_photo" => $person["thumb"],
1848                         "verb" => ACTIVITY_POST,
1849                         "otype" => "mail"]
1850                 );
1851                 return true;
1852         }
1853
1854         /**
1855          * @brief Processes new private messages (answers to private messages are processed elsewhere)
1856          *
1857          * @param array  $importer Array of the importer user
1858          * @param array  $msg      Array of the processed message, author handle and key
1859          * @param object $data     The message object
1860          *
1861          * @return bool Success
1862          */
1863         private static function receiveConversation($importer, $msg, $data)
1864         {
1865                 $author = notags(unxmlify($data->author));
1866                 $guid = notags(unxmlify($data->guid));
1867                 $subject = notags(unxmlify($data->subject));
1868                 $created_at = Temporal::utc(notags(unxmlify($data->created_at)));
1869                 $participants = notags(unxmlify($data->participants));
1870
1871                 $messages = $data->message;
1872
1873                 if (!count($messages)) {
1874                         logger("empty conversation");
1875                         return false;
1876                 }
1877
1878                 $contact = self::allowedContactByHandle($importer, $msg["author"], true);
1879                 if (!$contact) {
1880                         return false;
1881                 }
1882
1883                 $conversation = null;
1884
1885                 $c = q(
1886                         "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1887                         intval($importer["uid"]),
1888                         dbesc($guid)
1889                 );
1890                 if ($c)
1891                         $conversation = $c[0];
1892                 else {
1893                         $r = q(
1894                                 "INSERT INTO `conv` (`uid`, `guid`, `creator`, `created`, `updated`, `subject`, `recips`)
1895                                 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s')",
1896                                 intval($importer["uid"]),
1897                                 dbesc($guid),
1898                                 dbesc($author),
1899                                 dbesc($created_at),
1900                                 dbesc(Temporal::utcNow()),
1901                                 dbesc($subject),
1902                                 dbesc($participants)
1903                         );
1904                         if ($r) {
1905                                 $c = q(
1906                                         "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
1907                                         intval($importer["uid"]),
1908                                         dbesc($guid)
1909                                 );
1910                         }
1911
1912                         if ($c) {
1913                                 $conversation = $c[0];
1914                         }
1915                 }
1916                 if (!$conversation) {
1917                         logger("unable to create conversation.");
1918                         return false;
1919                 }
1920
1921                 foreach ($messages as $mesg) {
1922                         self::receiveConversationMessage($importer, $contact, $data, $msg, $mesg, $conversation);
1923                 }
1924
1925                 return true;
1926         }
1927
1928         /**
1929          * @brief Creates the body for a "like" message
1930          *
1931          * @param array  $contact     The contact that send us the "like"
1932          * @param array  $parent_item The item array of the parent item
1933          * @param string $guid        message guid
1934          *
1935          * @return string the body
1936          */
1937         private static function constructLikeBody($contact, $parent_item, $guid)
1938         {
1939                 $bodyverb = L10n::t('%1$s likes %2$s\'s %3$s');
1940
1941                 $ulink = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
1942                 $alink = "[url=".$parent_item["author-link"]."]".$parent_item["author-name"]."[/url]";
1943                 $plink = "[url=".System::baseUrl()."/display/".urlencode($guid)."]".L10n::t("status")."[/url]";
1944
1945                 return sprintf($bodyverb, $ulink, $alink, $plink);
1946         }
1947
1948         /**
1949          * @brief Creates a XML object for a "like"
1950          *
1951          * @param array $importer    Array of the importer user
1952          * @param array $parent_item The item array of the parent item
1953          *
1954          * @return string The XML
1955          */
1956         private static function constructLikeObject($importer, $parent_item)
1957         {
1958                 $objtype = ACTIVITY_OBJ_NOTE;
1959                 $link = '<link rel="alternate" type="text/html" href="'.System::baseUrl()."/display/".$importer["nickname"]."/".$parent_item["id"].'" />';
1960                 $parent_body = $parent_item["body"];
1961
1962                 $xmldata = ["object" => ["type" => $objtype,
1963                                                 "local" => "1",
1964                                                 "id" => $parent_item["uri"],
1965                                                 "link" => $link,
1966                                                 "title" => "",
1967                                                 "content" => $parent_body]];
1968
1969                 return XML::fromArray($xmldata, $xml, true);
1970         }
1971
1972         /**
1973          * @brief Processes "like" messages
1974          *
1975          * @param array  $importer Array of the importer user
1976          * @param string $sender   The sender of the message
1977          * @param object $data     The message object
1978          *
1979          * @return int The message id of the generated like or "false" if there was an error
1980          */
1981         private static function receiveLike($importer, $sender, $data)
1982         {
1983                 $author = notags(unxmlify($data->author));
1984                 $guid = notags(unxmlify($data->guid));
1985                 $parent_guid = notags(unxmlify($data->parent_guid));
1986                 $parent_type = notags(unxmlify($data->parent_type));
1987                 $positive = notags(unxmlify($data->positive));
1988
1989                 // likes on comments aren't supported by Diaspora - only on posts
1990                 // But maybe this will be supported in the future, so we will accept it.
1991                 if (!in_array($parent_type, ["Post", "Comment"])) {
1992                         return false;
1993                 }
1994
1995                 $contact = self::allowedContactByHandle($importer, $sender, true);
1996                 if (!$contact) {
1997                         return false;
1998                 }
1999
2000                 $message_id = self::messageExists($importer["uid"], $guid);
2001                 if ($message_id) {
2002                         return true;
2003                 }
2004
2005                 $parent_item = self::parentItem($importer["uid"], $parent_guid, $author, $contact);
2006                 if (!$parent_item) {
2007                         return false;
2008                 }
2009
2010                 $person = self::personByHandle($author);
2011                 if (!is_array($person)) {
2012                         logger("unable to find author details");
2013                         return false;
2014                 }
2015
2016                 // Fetch the contact id - if we know this contact
2017                 $author_contact = self::authorContactByUrl($contact, $person, $importer["uid"]);
2018
2019                 // "positive" = "false" would be a Dislike - wich isn't currently supported by Diaspora
2020                 // We would accept this anyhow.
2021                 if ($positive == "true") {
2022                         $verb = ACTIVITY_LIKE;
2023                 } else {
2024                         $verb = ACTIVITY_DISLIKE;
2025                 }
2026
2027                 $datarray = [];
2028
2029                 $datarray["protocol"] = PROTOCOL_DIASPORA;
2030
2031                 $datarray["uid"] = $importer["uid"];
2032                 $datarray["contact-id"] = $author_contact["cid"];
2033                 $datarray["network"]  = $author_contact["network"];
2034
2035                 $datarray["author-name"] = $person["name"];
2036                 $datarray["author-link"] = $person["url"];
2037                 $datarray["author-avatar"] = ((x($person, "thumb")) ? $person["thumb"] : $person["photo"]);
2038
2039                 $datarray["owner-name"] = $contact["name"];
2040                 $datarray["owner-link"] = $contact["url"];
2041                 $datarray["owner-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2042
2043                 $datarray["guid"] = $guid;
2044                 $datarray["uri"] = self::getUriFromGuid($author, $guid);
2045
2046                 $datarray["type"] = "activity";
2047                 $datarray["verb"] = $verb;
2048                 $datarray["gravity"] = GRAVITY_LIKE;
2049                 $datarray["parent-uri"] = $parent_item["uri"];
2050
2051                 $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2052                 $datarray["object"] = self::constructLikeObject($importer, $parent_item);
2053
2054                 $datarray["body"] = self::constructLikeBody($contact, $parent_item, $guid);
2055
2056                 $message_id = Item::insert($datarray);
2057
2058                 if ($message_id <= 0) {
2059                         return false;
2060                 }
2061
2062                 if ($message_id) {
2063                         logger("Stored like ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2064                 }
2065
2066                 // like on comments have the comment as parent. So we need to fetch the toplevel parent
2067                 if ($parent_item["id"] != $parent_item["parent"]) {
2068                         $toplevel = dba::selectFirst('item', ['origin'], ['id' => $parent_item["parent"]]);
2069                         $origin = $toplevel["origin"];
2070                 } else {
2071                         $origin = $parent_item["origin"];
2072                 }
2073
2074                 // If we are the origin of the parent we store the original data and notify our followers
2075                 if ($message_id && $origin) {
2076                         // Formerly we stored the signed text, the signature and the author in different fields.
2077                         // We now store the raw data so that we are more flexible.
2078                         dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($data)]);
2079
2080                         // notify others
2081                         Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $message_id);
2082                 }
2083
2084                 return true;
2085         }
2086
2087         /**
2088          * @brief Processes private messages
2089          *
2090          * @param array  $importer Array of the importer user
2091          * @param object $data     The message object
2092          *
2093          * @return bool Success?
2094          */
2095         private static function receiveMessage($importer, $data)
2096         {
2097                 $author = notags(unxmlify($data->author));
2098                 $guid = notags(unxmlify($data->guid));
2099                 $conversation_guid = notags(unxmlify($data->conversation_guid));
2100                 $text = unxmlify($data->text);
2101                 $created_at = Temporal::utc(notags(unxmlify($data->created_at)));
2102
2103                 $contact = self::allowedContactByHandle($importer, $author, true);
2104                 if (!$contact) {
2105                         return false;
2106                 }
2107
2108                 $conversation = null;
2109
2110                 $c = q(
2111                         "SELECT * FROM `conv` WHERE `uid` = %d AND `guid` = '%s' LIMIT 1",
2112                         intval($importer["uid"]),
2113                         dbesc($conversation_guid)
2114                 );
2115                 if ($c) {
2116                         $conversation = $c[0];
2117                 } else {
2118                         logger("conversation not available.");
2119                         return false;
2120                 }
2121
2122                 $message_uri = $author.":".$guid;
2123
2124                 $person = self::personByHandle($author);
2125                 if (!$person) {
2126                         logger("unable to find author details");
2127                         return false;
2128                 }
2129
2130                 $body = diaspora2bb($text);
2131
2132                 $body = self::replacePeopleGuid($body, $person["url"]);
2133
2134                 dba::lock('mail');
2135
2136                 $r = q(
2137                         "SELECT `id` FROM `mail` WHERE `guid` = '%s' AND `uid` = %d LIMIT 1",
2138                         dbesc($guid),
2139                         intval($importer["uid"])
2140                 );
2141                 if (DBM::is_result($r)) {
2142                         logger("duplicate message already delivered.", LOGGER_DEBUG);
2143                         return false;
2144                 }
2145
2146                 q(
2147                         "INSERT INTO `mail` (`uid`, `guid`, `convid`, `from-name`,`from-photo`,`from-url`,`contact-id`,`title`,`body`,`seen`,`reply`,`uri`,`parent-uri`,`created`)
2148                                 VALUES ( %d, '%s', %d, '%s', '%s', '%s', %d, '%s', '%s', %d, %d, '%s','%s','%s')",
2149                         intval($importer["uid"]),
2150                         dbesc($guid),
2151                         intval($conversation["id"]),
2152                         dbesc($person["name"]),
2153                         dbesc($person["photo"]),
2154                         dbesc($person["url"]),
2155                         intval($contact["id"]),
2156                         dbesc($conversation["subject"]),
2157                         dbesc($body),
2158                         0,
2159                         1,
2160                         dbesc($message_uri),
2161                         dbesc($author.":".$conversation["guid"]),
2162                         dbesc($created_at)
2163                 );
2164
2165                 dba::unlock();
2166
2167                 dba::update('conv', ['updated' => Temporal::utcNow()], ['id' => $conversation["id"]]);
2168                 return true;
2169         }
2170
2171         /**
2172          * @brief Processes participations - unsupported by now
2173          *
2174          * @param array  $importer Array of the importer user
2175          * @param object $data     The message object
2176          *
2177          * @return bool always true
2178          */
2179         private static function receiveParticipation($importer, $data)
2180         {
2181                 $author = strtolower(notags(unxmlify($data->author)));
2182                 $parent_guid = notags(unxmlify($data->parent_guid));
2183
2184                 $contact_id = Contact::getIdForURL($author);
2185                 if (!$contact_id) {
2186                         logger('Contact not found: '.$author);
2187                         return false;
2188                 }
2189
2190                 $person = self::personByHandle($author);
2191                 if (!is_array($person)) {
2192                         logger("Person not found: ".$author);
2193                         return false;
2194                 }
2195
2196                 $item = dba::selectFirst('item', ['id'], ['guid' => $parent_guid, 'origin' => true, 'private' => false]);
2197                 if (!DBM::is_result($item)) {
2198                         logger('Item not found, no origin or private: '.$parent_guid);
2199                         return false;
2200                 }
2201
2202                 $author_parts = explode('@', $author);
2203                 if (isset($author_parts[1])) {
2204                         $server = $author_parts[1];
2205                 } else {
2206                         // Should never happen
2207                         $server = $author;
2208                 }
2209
2210                 logger('Received participation for ID: '.$item['id'].' - Contact: '.$contact_id.' - Server: '.$server, LOGGER_DEBUG);
2211                 dba::insert('participation', ['iid' => $item['id'], 'cid' => $contact_id, 'fid' => $person['id'], 'server' => $server]);
2212
2213                 // Send all existing comments and likes to the requesting server
2214                 $comments = dba::p("SELECT `item`.`id`, `item`.`verb`, `contact`.`self`
2215                                 FROM `item`
2216                                 INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2217                                 WHERE `item`.`parent` = ? AND `item`.`id` != `item`.`parent`", $item['id']);
2218                 while ($comment = dba::fetch($comments)) {
2219                         if ($comment['verb'] == ACTIVITY_POST) {
2220                                 $cmd = $comment['self'] ? 'comment-new' : 'comment-import';
2221                         } else {
2222                                 $cmd = $comment['self'] ? 'like' : 'comment-import';
2223                         }
2224                         logger("Send ".$cmd." for item ".$comment['id']." to contact ".$contact_id, LOGGER_DEBUG);
2225                         Worker::add(PRIORITY_HIGH, 'Delivery', $cmd, $comment['id'], $contact_id);
2226                 }
2227                 dba::close($comments);
2228
2229                 return true;
2230         }
2231
2232         /**
2233          * @brief Processes photos - unneeded
2234          *
2235          * @param array  $importer Array of the importer user
2236          * @param object $data     The message object
2237          *
2238          * @return bool always true
2239          */
2240         private static function receivePhoto($importer, $data)
2241         {
2242                 // There doesn't seem to be a reason for this function,
2243                 // since the photo data is transmitted in the status message as well
2244                 return true;
2245         }
2246
2247         /**
2248          * @brief Processes poll participations - unssupported
2249          *
2250          * @param array  $importer Array of the importer user
2251          * @param object $data     The message object
2252          *
2253          * @return bool always true
2254          */
2255         private static function receivePollParticipation($importer, $data)
2256         {
2257                 // We don't support polls by now
2258                 return true;
2259         }
2260
2261         /**
2262          * @brief Processes incoming profile updates
2263          *
2264          * @param array  $importer Array of the importer user
2265          * @param object $data     The message object
2266          *
2267          * @return bool Success
2268          */
2269         private static function receiveProfile($importer, $data)
2270         {
2271                 $author = strtolower(notags(unxmlify($data->author)));
2272
2273                 $contact = self::contactByHandle($importer["uid"], $author);
2274                 if (!$contact) {
2275                         return false;
2276                 }
2277
2278                 $name = unxmlify($data->first_name).((strlen($data->last_name)) ? " ".unxmlify($data->last_name) : "");
2279                 $image_url = unxmlify($data->image_url);
2280                 $birthday = unxmlify($data->birthday);
2281                 $gender = unxmlify($data->gender);
2282                 $about = diaspora2bb(unxmlify($data->bio));
2283                 $location = diaspora2bb(unxmlify($data->location));
2284                 $searchable = (unxmlify($data->searchable) == "true");
2285                 $nsfw = (unxmlify($data->nsfw) == "true");
2286                 $tags = unxmlify($data->tag_string);
2287
2288                 $tags = explode("#", $tags);
2289
2290                 $keywords = [];
2291                 foreach ($tags as $tag) {
2292                         $tag = trim(strtolower($tag));
2293                         if ($tag != "") {
2294                                 $keywords[] = $tag;
2295                         }
2296                 }
2297
2298                 $keywords = implode(", ", $keywords);
2299
2300                 $handle_parts = explode("@", $author);
2301                 $nick = $handle_parts[0];
2302
2303                 if ($name === "") {
2304                         $name = $handle_parts[0];
2305                 }
2306
2307                 if (preg_match("|^https?://|", $image_url) === 0) {
2308                         $image_url = "http://".$handle_parts[1].$image_url;
2309                 }
2310
2311                 Contact::updateAvatar($image_url, $importer["uid"], $contact["id"]);
2312
2313                 // Generic birthday. We don't know the timezone. The year is irrelevant.
2314
2315                 $birthday = str_replace("1000", "1901", $birthday);
2316
2317                 if ($birthday != "") {
2318                         $birthday = Temporal::utc($birthday, "Y-m-d");
2319                 }
2320
2321                 // this is to prevent multiple birthday notifications in a single year
2322                 // if we already have a stored birthday and the 'm-d' part hasn't changed, preserve the entry, which will preserve the notify year
2323
2324                 if (substr($birthday, 5) === substr($contact["bd"], 5)) {
2325                         $birthday = $contact["bd"];
2326                 }
2327
2328                 $r = q(
2329                         "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `addr` = '%s', `name-date` = '%s', `bd` = '%s',
2330                                 `location` = '%s', `about` = '%s', `keywords` = '%s', `gender` = '%s' WHERE `id` = %d AND `uid` = %d",
2331                         dbesc($name),
2332                         dbesc($nick),
2333                         dbesc($author),
2334                         dbesc(Temporal::utcNow()),
2335                         dbesc($birthday),
2336                         dbesc($location),
2337                         dbesc($about),
2338                         dbesc($keywords),
2339                         dbesc($gender),
2340                         intval($contact["id"]),
2341                         intval($importer["uid"])
2342                 );
2343
2344                 $gcontact = ["url" => $contact["url"], "network" => NETWORK_DIASPORA, "generation" => 2,
2345                                         "photo" => $image_url, "name" => $name, "location" => $location,
2346                                         "about" => $about, "birthday" => $birthday, "gender" => $gender,
2347                                         "addr" => $author, "nick" => $nick, "keywords" => $keywords,
2348                                         "hide" => !$searchable, "nsfw" => $nsfw];
2349
2350                 $gcid = GContact::update($gcontact);
2351
2352                 GContact::link($gcid, $importer["uid"], $contact["id"]);
2353
2354                 logger("Profile of contact ".$contact["id"]." stored for user ".$importer["uid"], LOGGER_DEBUG);
2355
2356                 return true;
2357         }
2358
2359         /**
2360          * @brief Processes incoming friend requests
2361          *
2362          * @param array $importer Array of the importer user
2363          * @param array $contact  The contact that send the request
2364          * @return void
2365          */
2366         private static function receiveRequestMakeFriend($importer, $contact)
2367         {
2368                 $a = get_app();
2369
2370                 if ($contact["rel"] == CONTACT_IS_SHARING) {
2371                         dba::update(
2372                                 'contact',
2373                                 ['rel' => CONTACT_IS_FRIEND, 'writable' => true],
2374                                 ['id' => $contact["id"], 'uid' => $importer["uid"]]
2375                         );
2376                 }
2377                 // send notification
2378
2379                 $r = q(
2380                         "SELECT `hide-friends` FROM `profile` WHERE `uid` = %d AND `is-default` = 1 LIMIT 1",
2381                         intval($importer["uid"])
2382                 );
2383
2384                 if ($r && !$r[0]["hide-friends"] && !$contact["hidden"] && intval(PConfig::get($importer["uid"], "system", "post_newfriend"))) {
2385                         $self = q(
2386                                 "SELECT * FROM `contact` WHERE `self` AND `uid` = %d LIMIT 1",
2387                                 intval($importer["uid"])
2388                         );
2389
2390                         // they are not CONTACT_IS_FOLLOWER anymore but that's what we have in the array
2391
2392                         if ($self && $contact["rel"] == CONTACT_IS_FOLLOWER) {
2393                                 $arr = [];
2394                                 $arr["protocol"] = PROTOCOL_DIASPORA;
2395                                 $arr["uri"] = $arr["parent-uri"] = item_new_uri($a->get_hostname(), $importer["uid"]);
2396                                 $arr["uid"] = $importer["uid"];
2397                                 $arr["contact-id"] = $self[0]["id"];
2398                                 $arr["wall"] = 1;
2399                                 $arr["type"] = 'wall';
2400                                 $arr["gravity"] = 0;
2401                                 $arr["origin"] = 1;
2402                                 $arr["author-name"] = $arr["owner-name"] = $self[0]["name"];
2403                                 $arr["author-link"] = $arr["owner-link"] = $self[0]["url"];
2404                                 $arr["author-avatar"] = $arr["owner-avatar"] = $self[0]["thumb"];
2405                                 $arr["verb"] = ACTIVITY_FRIEND;
2406                                 $arr["object-type"] = ACTIVITY_OBJ_PERSON;
2407
2408                                 $A = "[url=".$self[0]["url"]."]".$self[0]["name"]."[/url]";
2409                                 $B = "[url=".$contact["url"]."]".$contact["name"]."[/url]";
2410                                 $BPhoto = "[url=".$contact["url"]."][img]".$contact["thumb"]."[/img][/url]";
2411                                 $arr["body"] = L10n::t('%1$s is now friends with %2$s', $A, $B)."\n\n\n".$BPhoto;
2412
2413                                 $arr["object"] = self::constructNewFriendObject($contact);
2414
2415                                 $user = dba::selectFirst('user', ['allow_cid', 'allow_gid', 'deny_cid', 'deny_gid'], ['uid' => $importer["uid"]]);
2416
2417                                 $arr["allow_cid"] = $user["allow_cid"];
2418                                 $arr["allow_gid"] = $user["allow_gid"];
2419                                 $arr["deny_cid"]  = $user["deny_cid"];
2420                                 $arr["deny_gid"]  = $user["deny_gid"];
2421
2422                                 $i = Item::insert($arr);
2423                                 if ($i) {
2424                                         Worker::add(PRIORITY_HIGH, "Notifier", "activity", $i);
2425                                 }
2426                         }
2427                 }
2428         }
2429
2430         /**
2431          * @brief Creates a XML object for a "new friend" message
2432          *
2433          * @param array $contact Array of the contact
2434          *
2435          * @return string The XML
2436          */
2437         private static function constructNewFriendObject($contact)
2438         {
2439                 $objtype = ACTIVITY_OBJ_PERSON;
2440                 $link = '<link rel="alternate" type="text/html" href="'.$contact["url"].'" />'."\n".
2441                         '<link rel="photo" type="image/jpeg" href="'.$contact["thumb"].'" />'."\n";
2442
2443                 $xmldata = ["object" => ["type" => $objtype,
2444                                                 "title" => $contact["name"],
2445                                                 "id" => $contact["url"]."/".$contact["name"],
2446                                                 "link" => $link]];
2447
2448                 return XML::fromArray($xmldata, $xml, true);
2449         }
2450
2451         /**
2452          * @brief Processes incoming sharing notification
2453          *
2454          * @param array  $importer Array of the importer user
2455          * @param object $data     The message object
2456          *
2457          * @return bool Success
2458          */
2459         private static function receiveContactRequest($importer, $data)
2460         {
2461                 $author = unxmlify($data->author);
2462                 $recipient = unxmlify($data->recipient);
2463
2464                 if (!$author || !$recipient) {
2465                         return false;
2466                 }
2467
2468                 // the current protocol version doesn't know these fields
2469                 // That means that we will assume their existance
2470                 if (isset($data->following)) {
2471                         $following = (unxmlify($data->following) == "true");
2472                 } else {
2473                         $following = true;
2474                 }
2475
2476                 if (isset($data->sharing)) {
2477                         $sharing = (unxmlify($data->sharing) == "true");
2478                 } else {
2479                         $sharing = true;
2480                 }
2481
2482                 $contact = self::contactByHandle($importer["uid"], $author);
2483
2484                 // perhaps we were already sharing with this person. Now they're sharing with us.
2485                 // That makes us friends.
2486                 if ($contact) {
2487                         if ($following) {
2488                                 logger("Author ".$author." (Contact ".$contact["id"].") wants to follow us.", LOGGER_DEBUG);
2489                                 self::receiveRequestMakeFriend($importer, $contact);
2490
2491                                 // refetch the contact array
2492                                 $contact = self::contactByHandle($importer["uid"], $author);
2493
2494                                 // If we are now friends, we are sending a share message.
2495                                 // Normally we needn't to do so, but the first message could have been vanished.
2496                                 if (in_array($contact["rel"], [CONTACT_IS_FRIEND])) {
2497                                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2498                                         if ($u) {
2499                                                 logger("Sending share message to author ".$author." - Contact: ".$contact["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2500                                                 $ret = self::sendShare($u[0], $contact);
2501                                         }
2502                                 }
2503                                 return true;
2504                         } else {
2505                                 logger("Author ".$author." doesn't want to follow us anymore.", LOGGER_DEBUG);
2506                                 Contact::removeFollower($importer, $contact);
2507                                 return true;
2508                         }
2509                 }
2510
2511                 if (!$following && $sharing && in_array($importer["page-flags"], [PAGE_SOAPBOX, PAGE_NORMAL])) {
2512                         logger("Author ".$author." wants to share with us - but doesn't want to listen. Request is ignored.", LOGGER_DEBUG);
2513                         return false;
2514                 } elseif (!$following && !$sharing) {
2515                         logger("Author ".$author." doesn't want anything - and we don't know the author. Request is ignored.", LOGGER_DEBUG);
2516                         return false;
2517                 } elseif (!$following && $sharing) {
2518                         logger("Author ".$author." wants to share with us.", LOGGER_DEBUG);
2519                 } elseif ($following && $sharing) {
2520                         logger("Author ".$author." wants to have a bidirectional conection.", LOGGER_DEBUG);
2521                 } elseif ($following && !$sharing) {
2522                         logger("Author ".$author." wants to listen to us.", LOGGER_DEBUG);
2523                 }
2524
2525                 $ret = self::personByHandle($author);
2526
2527                 if (!$ret || ($ret["network"] != NETWORK_DIASPORA)) {
2528                         logger("Cannot resolve diaspora handle ".$author." for ".$recipient);
2529                         return false;
2530                 }
2531
2532                 $batch = (($ret["batch"]) ? $ret["batch"] : implode("/", array_slice(explode("/", $ret["url"]), 0, 3))."/receive/public");
2533
2534                 $r = q(
2535                         "INSERT INTO `contact` (`uid`, `network`,`addr`,`created`,`url`,`nurl`,`batch`,`name`,`nick`,`photo`,`pubkey`,`notify`,`poll`,`blocked`,`priority`)
2536                         VALUES (%d, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s','%s','%s',%d,%d)",
2537                         intval($importer["uid"]),
2538                         dbesc($ret["network"]),
2539                         dbesc($ret["addr"]),
2540                         Temporal::utcNow(),
2541                         dbesc($ret["url"]),
2542                         dbesc(normalise_link($ret["url"])),
2543                         dbesc($batch),
2544                         dbesc($ret["name"]),
2545                         dbesc($ret["nick"]),
2546                         dbesc($ret["photo"]),
2547                         dbesc($ret["pubkey"]),
2548                         dbesc($ret["notify"]),
2549                         dbesc($ret["poll"]),
2550                         1,
2551                         2
2552                 );
2553
2554                 // find the contact record we just created
2555
2556                 $contact_record = self::contactByHandle($importer["uid"], $author);
2557
2558                 if (!$contact_record) {
2559                         logger("unable to locate newly created contact record.");
2560                         return;
2561                 }
2562
2563                 logger("Author ".$author." was added as contact number ".$contact_record["id"].".", LOGGER_DEBUG);
2564
2565                 Group::addMember(User::getDefaultGroup($importer['uid'], $ret["network"]), $contact_record['id']);
2566
2567                 Contact::updateAvatar($ret["photo"], $importer['uid'], $contact_record["id"], true);
2568
2569                 if ($importer["page-flags"] == PAGE_NORMAL) {
2570                         logger("Sending intra message for author ".$author.".", LOGGER_DEBUG);
2571
2572                         $hash = random_string().(string)time();   // Generate a confirm_key
2573
2574                         $ret = q(
2575                                 "INSERT INTO `intro` (`uid`, `contact-id`, `blocked`, `knowyou`, `note`, `hash`, `datetime`)
2576                                 VALUES (%d, %d, %d, %d, '%s', '%s', '%s')",
2577                                 intval($importer["uid"]),
2578                                 intval($contact_record["id"]),
2579                                 0,
2580                                 0,
2581                                 dbesc(L10n::t("Sharing notification from Diaspora network")),
2582                                 dbesc($hash),
2583                                 dbesc(Temporal::utcNow())
2584                         );
2585                 } else {
2586                         // automatic friend approval
2587
2588                         logger("Does an automatic friend approval for author ".$author.".", LOGGER_DEBUG);
2589
2590                         Contact::updateAvatar($contact_record["photo"], $importer["uid"], $contact_record["id"]);
2591
2592                         // technically they are sharing with us (CONTACT_IS_SHARING),
2593                         // but if our page-type is PAGE_COMMUNITY or PAGE_SOAPBOX
2594                         // we are going to change the relationship and make them a follower.
2595
2596                         if (($importer["page-flags"] == PAGE_FREELOVE) && $sharing && $following) {
2597                                 $new_relation = CONTACT_IS_FRIEND;
2598                         } elseif (($importer["page-flags"] == PAGE_FREELOVE) && $sharing) {
2599                                 $new_relation = CONTACT_IS_SHARING;
2600                         } else {
2601                                 $new_relation = CONTACT_IS_FOLLOWER;
2602                         }
2603
2604                         $r = q(
2605                                 "UPDATE `contact` SET `rel` = %d,
2606                                 `name-date` = '%s',
2607                                 `uri-date` = '%s',
2608                                 `blocked` = 0,
2609                                 `pending` = 0,
2610                                 `writable` = 1
2611                                 WHERE `id` = %d
2612                                 ",
2613                                 intval($new_relation),
2614                                 dbesc(Temporal::utcNow()),
2615                                 dbesc(Temporal::utcNow()),
2616                                 intval($contact_record["id"])
2617                         );
2618
2619                         $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1", intval($importer["uid"]));
2620                         if ($u) {
2621                                 logger("Sending share message (Relation: ".$new_relation.") to author ".$author." - Contact: ".$contact_record["id"]." - User: ".$importer["uid"], LOGGER_DEBUG);
2622                                 $ret = self::sendShare($u[0], $contact_record);
2623
2624                                 // Send the profile data, maybe it weren't transmitted before
2625                                 self::sendProfile($importer["uid"], [$contact_record]);
2626                         }
2627                 }
2628
2629                 return true;
2630         }
2631
2632         /**
2633          * @brief Fetches a message with a given guid
2634          *
2635          * @param string $guid        message guid
2636          * @param string $orig_author handle of the original post
2637          * @param string $author      handle of the sharer
2638          *
2639          * @return array The fetched item
2640          */
2641         private static function originalItem($guid, $orig_author, $author)
2642         {
2643                 // Do we already have this item?
2644                 $r = q(
2645                         "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2646                                 `author-name`, `author-link`, `author-avatar`
2647                                 FROM `item` WHERE `guid` = '%s' AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2648                         dbesc($guid)
2649                 );
2650
2651                 if (DBM::is_result($r)) {
2652                         logger("reshared message ".$guid." already exists on system.");
2653
2654                         // Maybe it is already a reshared item?
2655                         // Then refetch the content, if it is a reshare from a reshare.
2656                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2657                         if (self::isReshare($r[0]["body"], true)) {
2658                                 $r = [];
2659                         } elseif (self::isReshare($r[0]["body"], false) || strstr($r[0]["body"], "[share")) {
2660                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2661
2662                                 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2663
2664                                 // Add OEmbed and other information to the body
2665                                 $r[0]["body"] = add_page_info_to_body($r[0]["body"], false, true);
2666
2667                                 return $r[0];
2668                         } else {
2669                                 return $r[0];
2670                         }
2671                 }
2672
2673                 if (!DBM::is_result($r)) {
2674                         $server = "https://".substr($orig_author, strpos($orig_author, "@") + 1);
2675                         logger("1st try: reshared message ".$guid." will be fetched via SSL from the server ".$server);
2676                         $item_id = self::storeByGuid($guid, $server);
2677
2678                         if (!$item_id) {
2679                                 $server = "http://".substr($orig_author, strpos($orig_author, "@") + 1);
2680                                 logger("2nd try: reshared message ".$guid." will be fetched without SLL from the server ".$server);
2681                                 $item_id = self::storeByGuid($guid, $server);
2682                         }
2683
2684                         if ($item_id) {
2685                                 $r = q(
2686                                         "SELECT `body`, `tag`, `app`, `created`, `object-type`, `uri`, `guid`,
2687                                                 `author-name`, `author-link`, `author-avatar`
2688                                         FROM `item` WHERE `id` = %d AND `visible` AND NOT `deleted` AND `body` != '' LIMIT 1",
2689                                         intval($item_id)
2690                                 );
2691
2692                                 if (DBM::is_result($r)) {
2693                                         // If it is a reshared post from another network then reformat to avoid display problems with two share elements
2694                                         if (self::isReshare($r[0]["body"], false)) {
2695                                                 $r[0]["body"] = diaspora2bb(bb2diaspora($r[0]["body"]));
2696                                                 $r[0]["body"] = self::replacePeopleGuid($r[0]["body"], $r[0]["author-link"]);
2697                                         }
2698
2699                                         return $r[0];
2700                                 }
2701                         }
2702                 }
2703                 return false;
2704         }
2705
2706         /**
2707          * @brief Processes a reshare message
2708          *
2709          * @param array  $importer Array of the importer user
2710          * @param object $data     The message object
2711          * @param string $xml      The original XML of the message
2712          *
2713          * @return int the message id
2714          */
2715         private static function receiveReshare($importer, $data, $xml)
2716         {
2717                 $author = notags(unxmlify($data->author));
2718                 $guid = notags(unxmlify($data->guid));
2719                 $created_at = Temporal::utc(notags(unxmlify($data->created_at)));
2720                 $root_author = notags(unxmlify($data->root_author));
2721                 $root_guid = notags(unxmlify($data->root_guid));
2722                 /// @todo handle unprocessed property "provider_display_name"
2723                 $public = notags(unxmlify($data->public));
2724
2725                 $contact = self::allowedContactByHandle($importer, $author, false);
2726                 if (!$contact) {
2727                         return false;
2728                 }
2729
2730                 $message_id = self::messageExists($importer["uid"], $guid);
2731                 if ($message_id) {
2732                         return true;
2733                 }
2734
2735                 $original_item = self::originalItem($root_guid, $root_author, $author);
2736                 if (!$original_item) {
2737                         return false;
2738                 }
2739
2740                 $orig_url = System::baseUrl()."/display/".$original_item["guid"];
2741
2742                 $datarray = [];
2743
2744                 $datarray["uid"] = $importer["uid"];
2745                 $datarray["contact-id"] = $contact["id"];
2746                 $datarray["network"]  = NETWORK_DIASPORA;
2747
2748                 $datarray["author-name"] = $contact["name"];
2749                 $datarray["author-link"] = $contact["url"];
2750                 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2751
2752                 $datarray["owner-name"] = $datarray["author-name"];
2753                 $datarray["owner-link"] = $datarray["author-link"];
2754                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2755
2756                 $datarray["guid"] = $guid;
2757                 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2758
2759                 $datarray["verb"] = ACTIVITY_POST;
2760                 $datarray["gravity"] = GRAVITY_PARENT;
2761
2762                 $datarray["protocol"] = PROTOCOL_DIASPORA;
2763                 $datarray["source"] = $xml;
2764
2765                 $prefix = share_header(
2766                         $original_item["author-name"],
2767                         $original_item["author-link"],
2768                         $original_item["author-avatar"],
2769                         $original_item["guid"],
2770                         $original_item["created"],
2771                         $orig_url
2772                 );
2773                 $datarray["body"] = $prefix.$original_item["body"]."[/share]";
2774
2775                 $datarray["tag"] = $original_item["tag"];
2776                 $datarray["app"]  = $original_item["app"];
2777
2778                 $datarray["plink"] = self::plink($author, $guid);
2779                 $datarray["private"] = (($public == "false") ? 1 : 0);
2780                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
2781
2782                 $datarray["object-type"] = $original_item["object-type"];
2783
2784                 self::fetchGuid($datarray);
2785                 $message_id = Item::insert($datarray);
2786
2787                 self::sendParticipation($contact, $datarray);
2788
2789                 if ($message_id) {
2790                         logger("Stored reshare ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
2791                         return true;
2792                 } else {
2793                         return false;
2794                 }
2795         }
2796
2797         /**
2798          * @brief Processes retractions
2799          *
2800          * @param array  $importer Array of the importer user
2801          * @param array  $contact  The contact of the item owner
2802          * @param object $data     The message object
2803          *
2804          * @return bool success
2805          */
2806         private static function itemRetraction($importer, $contact, $data)
2807         {
2808                 $author = notags(unxmlify($data->author));
2809                 $target_guid = notags(unxmlify($data->target_guid));
2810                 $target_type = notags(unxmlify($data->target_type));
2811
2812                 $person = self::personByHandle($author);
2813                 if (!is_array($person)) {
2814                         logger("unable to find author detail for ".$author);
2815                         return false;
2816                 }
2817
2818                 if (empty($contact["url"])) {
2819                         $contact["url"] = $person["url"];
2820                 }
2821
2822                 // Fetch items that are about to be deleted
2823                 $fields = ['uid', 'id', 'parent', 'parent-uri', 'author-link'];
2824
2825                 // When we receive a public retraction, we delete every item that we find.
2826                 if ($importer['uid'] == 0) {
2827                         $condition = ["`guid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid];
2828                 } else {
2829                         $condition = ["`guid` = ? AND `uid` = ? AND NOT `file` LIKE '%%[%%' AND NOT `deleted`", $target_guid, $importer['uid']];
2830                 }
2831                 $r = dba::select('item', $fields, $condition);
2832                 if (!DBM::is_result($r)) {
2833                         logger("Target guid ".$target_guid." was not found on this system for user ".$importer['uid'].".");
2834                         return false;
2835                 }
2836
2837                 while ($item = dba::fetch($r)) {
2838                         // Fetch the parent item
2839                         $parent = dba::selectFirst('item', ['author-link', 'origin'], ['id' => $item["parent"]]);
2840
2841                         // Only delete it if the parent author really fits
2842                         if (!link_compare($parent["author-link"], $contact["url"]) && !link_compare($item["author-link"], $contact["url"])) {
2843                                 logger("Thread author ".$parent["author-link"]." and item author ".$item["author-link"]." don't fit to expected contact ".$contact["url"], LOGGER_DEBUG);
2844                                 continue;
2845                         }
2846
2847                         // Currently we don't have a central deletion function that we could use in this case.
2848                         // The function "item_drop" doesn't work for that case
2849                         dba::update(
2850                                 'item',
2851                                 [
2852                                         'deleted' => true,
2853                                         'title' => '',
2854                                         'body' => '',
2855                                         'edited' => Temporal::utcNow(),
2856                                         'changed' => Temporal::utcNow()],
2857                                 ['id' => $item["id"]]
2858                         );
2859
2860                         // Delete the thread - if it is a starting post and not a comment
2861                         if ($target_type != 'Comment') {
2862                                 delete_thread($item["id"], $item["parent-uri"]);
2863                         }
2864
2865                         logger("Deleted target ".$target_guid." (".$item["id"].") from user ".$item["uid"]." parent: ".$item["parent"], LOGGER_DEBUG);
2866
2867                         // Now check if the retraction needs to be relayed by us
2868                         if ($parent["origin"]) {
2869                                 // notify others
2870                                 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2871                         }
2872                 }
2873
2874                 return true;
2875         }
2876
2877         /**
2878          * @brief Receives retraction messages
2879          *
2880          * @param array  $importer Array of the importer user
2881          * @param string $sender   The sender of the message
2882          * @param object $data     The message object
2883          *
2884          * @return bool Success
2885          */
2886         private static function receiveRetraction($importer, $sender, $data)
2887         {
2888                 $target_type = notags(unxmlify($data->target_type));
2889
2890                 $contact = self::contactByHandle($importer["uid"], $sender);
2891                 if (!$contact && (in_array($target_type, ["Contact", "Person"]))) {
2892                         logger("cannot find contact for sender: ".$sender." and user ".$importer["uid"]);
2893                         return false;
2894                 }
2895
2896                 logger("Got retraction for ".$target_type.", sender ".$sender." and user ".$importer["uid"], LOGGER_DEBUG);
2897
2898                 switch ($target_type) {
2899                         case "Comment":
2900                         case "Like":
2901                         case "Post":
2902                         case "Reshare":
2903                         case "StatusMessage":
2904                                 return self::itemRetraction($importer, $contact, $data);
2905
2906                         case "Contact":
2907                         case "Person":
2908                                 /// @todo What should we do with an "unshare"?
2909                                 // Removing the contact isn't correct since we still can read the public items
2910                                 Contact::remove($contact["id"]);
2911                                 return true;
2912
2913                         default:
2914                                 logger("Unknown target type ".$target_type);
2915                                 return false;
2916                 }
2917                 return true;
2918         }
2919
2920         /**
2921          * @brief Receives status messages
2922          *
2923          * @param array  $importer Array of the importer user
2924          * @param object $data     The message object
2925          * @param string $xml      The original XML of the message
2926          *
2927          * @return int The message id of the newly created item
2928          */
2929         private static function receiveStatusMessage($importer, $data, $xml)
2930         {
2931                 $author = notags(unxmlify($data->author));
2932                 $guid = notags(unxmlify($data->guid));
2933                 $created_at = Temporal::utc(notags(unxmlify($data->created_at)));
2934                 $public = notags(unxmlify($data->public));
2935                 $text = unxmlify($data->text);
2936                 $provider_display_name = notags(unxmlify($data->provider_display_name));
2937
2938                 $contact = self::allowedContactByHandle($importer, $author, false);
2939                 if (!$contact) {
2940                         return false;
2941                 }
2942
2943                 $message_id = self::messageExists($importer["uid"], $guid);
2944                 if ($message_id) {
2945                         return true;
2946                 }
2947
2948                 $address = [];
2949                 if ($data->location) {
2950                         foreach ($data->location->children() as $fieldname => $data) {
2951                                 $address[$fieldname] = notags(unxmlify($data));
2952                         }
2953                 }
2954
2955                 $body = diaspora2bb($text);
2956
2957                 $datarray = [];
2958
2959                 // Attach embedded pictures to the body
2960                 if ($data->photo) {
2961                         foreach ($data->photo as $photo) {
2962                                 $body = "[img]".unxmlify($photo->remote_photo_path).
2963                                         unxmlify($photo->remote_photo_name)."[/img]\n".$body;
2964                         }
2965
2966                         $datarray["object-type"] = ACTIVITY_OBJ_IMAGE;
2967                 } else {
2968                         $datarray["object-type"] = ACTIVITY_OBJ_NOTE;
2969
2970                         // Add OEmbed and other information to the body
2971                         if (!self::isRedmatrix($contact["url"])) {
2972                                 $body = add_page_info_to_body($body, false, true);
2973                         }
2974                 }
2975
2976                 /// @todo enable support for polls
2977                 //if ($data->poll) {
2978                 //      foreach ($data->poll AS $poll)
2979                 //              print_r($poll);
2980                 //      die("poll!\n");
2981                 //}
2982
2983                 /// @todo enable support for events
2984
2985                 $datarray["uid"] = $importer["uid"];
2986                 $datarray["contact-id"] = $contact["id"];
2987                 $datarray["network"] = NETWORK_DIASPORA;
2988
2989                 $datarray["author-name"] = $contact["name"];
2990                 $datarray["author-link"] = $contact["url"];
2991                 $datarray["author-avatar"] = ((x($contact, "thumb")) ? $contact["thumb"] : $contact["photo"]);
2992
2993                 $datarray["owner-name"] = $datarray["author-name"];
2994                 $datarray["owner-link"] = $datarray["author-link"];
2995                 $datarray["owner-avatar"] = $datarray["author-avatar"];
2996
2997                 $datarray["guid"] = $guid;
2998                 $datarray["uri"] = $datarray["parent-uri"] = self::getUriFromGuid($author, $guid);
2999
3000                 $datarray["verb"] = ACTIVITY_POST;
3001                 $datarray["gravity"] = GRAVITY_PARENT;
3002
3003                 $datarray["protocol"] = PROTOCOL_DIASPORA;
3004                 $datarray["source"] = $xml;
3005
3006                 $datarray["body"] = self::replacePeopleGuid($body, $contact["url"]);
3007
3008                 if ($provider_display_name != "") {
3009                         $datarray["app"] = $provider_display_name;
3010                 }
3011
3012                 $datarray["plink"] = self::plink($author, $guid);
3013                 $datarray["private"] = (($public == "false") ? 1 : 0);
3014                 $datarray["changed"] = $datarray["created"] = $datarray["edited"] = $created_at;
3015
3016                 if (isset($address["address"])) {
3017                         $datarray["location"] = $address["address"];
3018                 }
3019
3020                 if (isset($address["lat"]) && isset($address["lng"])) {
3021                         $datarray["coord"] = $address["lat"]." ".$address["lng"];
3022                 }
3023
3024                 self::fetchGuid($datarray);
3025                 $message_id = Item::insert($datarray);
3026
3027                 self::sendParticipation($contact, $datarray);
3028
3029                 if ($message_id) {
3030                         logger("Stored item ".$datarray["guid"]." with message id ".$message_id, LOGGER_DEBUG);
3031                         return true;
3032                 } else {
3033                         return false;
3034                 }
3035         }
3036
3037         /* ************************************************************************************** *
3038          * Here are all the functions that are needed to transmit data with the Diaspora protocol *
3039          * ************************************************************************************** */
3040
3041         /**
3042          * @brief returnes the handle of a contact
3043          *
3044          * @param array $contact contact array
3045          *
3046          * @return string the handle in the format user@domain.tld
3047          */
3048         private static function myHandle($contact)
3049         {
3050                 if ($contact["addr"] != "") {
3051                         return $contact["addr"];
3052                 }
3053
3054                 // Normally we should have a filled "addr" field - but in the past this wasn't the case
3055                 // So - just in case - we build the the address here.
3056                 if ($contact["nickname"] != "") {
3057                         $nick = $contact["nickname"];
3058                 } else {
3059                         $nick = $contact["nick"];
3060                 }
3061
3062                 return $nick."@".substr(System::baseUrl(), strpos(System::baseUrl(), "://") + 3);
3063         }
3064
3065
3066         /**
3067          * @brief Creates the data for a private message in the new format
3068          *
3069          * @param string $msg     The message that is to be transmitted
3070          * @param array  $user    The record of the sender
3071          * @param array  $contact Target of the communication
3072          * @param string $prvkey  The private key of the sender
3073          * @param string $pubkey  The public key of the receiver
3074          *
3075          * @return string The encrypted data
3076          */
3077         public static function encodePrivateData($msg, $user, $contact, $prvkey, $pubkey)
3078         {
3079                 logger("Message: ".$msg, LOGGER_DATA);
3080
3081                 // without a public key nothing will work
3082                 if (!$pubkey) {
3083                         logger("pubkey missing: contact id: ".$contact["id"]);
3084                         return false;
3085                 }
3086
3087                 $aes_key = openssl_random_pseudo_bytes(32);
3088                 $b_aes_key = base64_encode($aes_key);
3089                 $iv = openssl_random_pseudo_bytes(16);
3090                 $b_iv = base64_encode($iv);
3091
3092                 $ciphertext = self::aesEncrypt($aes_key, $iv, $msg);
3093
3094                 $json = json_encode(["iv" => $b_iv, "key" => $b_aes_key]);
3095
3096                 $encrypted_key_bundle = "";
3097                 openssl_public_encrypt($json, $encrypted_key_bundle, $pubkey);
3098
3099                 $json_object = json_encode(
3100                         ["aes_key" => base64_encode($encrypted_key_bundle),
3101                                         "encrypted_magic_envelope" => base64_encode($ciphertext)]
3102                 );
3103
3104                 return $json_object;
3105         }
3106
3107         /**
3108          * @brief Creates the envelope for the "fetch" endpoint and for the new format
3109          *
3110          * @param string $msg  The message that is to be transmitted
3111          * @param array  $user The record of the sender
3112          *
3113          * @return string The envelope
3114          */
3115         public static function buildMagicEnvelope($msg, $user)
3116         {
3117                 $b64url_data = base64url_encode($msg);
3118                 $data = str_replace(["\n", "\r", " ", "\t"], ["", "", "", ""], $b64url_data);
3119
3120                 $key_id = base64url_encode(self::myHandle($user));
3121                 $type = "application/xml";
3122                 $encoding = "base64url";
3123                 $alg = "RSA-SHA256";
3124                 $signable_data = $data.".".base64url_encode($type).".".base64url_encode($encoding).".".base64url_encode($alg);
3125
3126                 // Fallback if the private key wasn't transmitted in the expected field
3127                 if ($user['uprvkey'] == "") {
3128                         $user['uprvkey'] = $user['prvkey'];
3129                 }
3130
3131                 $signature = Crypto::rsaSign($signable_data, $user["uprvkey"]);
3132                 $sig = base64url_encode($signature);
3133
3134                 $xmldata = ["me:env" => ["me:data" => $data,
3135                                                         "@attributes" => ["type" => $type],
3136                                                         "me:encoding" => $encoding,
3137                                                         "me:alg" => $alg,
3138                                                         "me:sig" => $sig,
3139                                                         "@attributes2" => ["key_id" => $key_id]]];
3140
3141                 $namespaces = ["me" => "http://salmon-protocol.org/ns/magic-env"];
3142
3143                 return XML::fromArray($xmldata, $xml, false, $namespaces);
3144         }
3145
3146         /**
3147          * @brief Create the envelope for a message
3148          *
3149          * @param string $msg     The message that is to be transmitted
3150          * @param array  $user    The record of the sender
3151          * @param array  $contact Target of the communication
3152          * @param string $prvkey  The private key of the sender
3153          * @param string $pubkey  The public key of the receiver
3154          * @param bool   $public  Is the message public?
3155          *
3156          * @return string The message that will be transmitted to other servers
3157          */
3158         private static function buildMessage($msg, $user, $contact, $prvkey, $pubkey, $public = false)
3159         {
3160                 // The message is put into an envelope with the sender's signature
3161                 $envelope = self::buildMagicEnvelope($msg, $user);
3162
3163                 // Private messages are put into a second envelope, encrypted with the receivers public key
3164                 if (!$public) {
3165                         $envelope = self::encodePrivateData($envelope, $user, $contact, $prvkey, $pubkey);
3166                 }
3167
3168                 return $envelope;
3169         }
3170
3171         /**
3172          * @brief Creates a signature for a message
3173          *
3174          * @param array $owner   the array of the owner of the message
3175          * @param array $message The message that is to be signed
3176          *
3177          * @return string The signature
3178          */
3179         private static function signature($owner, $message)
3180         {
3181                 $sigmsg = $message;
3182                 unset($sigmsg["author_signature"]);
3183                 unset($sigmsg["parent_author_signature"]);
3184
3185                 $signed_text = implode(";", $sigmsg);
3186
3187                 return base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3188         }
3189
3190         /**
3191          * @brief Transmit a message to a target server
3192          *
3193          * @param array  $owner        the array of the item owner
3194          * @param array  $contact      Target of the communication
3195          * @param string $envelope     The message that is to be transmitted
3196          * @param bool   $public_batch Is it a public post?
3197          * @param bool   $queue_run    Is the transmission called from the queue?
3198          * @param string $guid         message guid
3199          *
3200          * @return int Result of the transmission
3201          */
3202         public static function transmit($owner, $contact, $envelope, $public_batch, $queue_run = false, $guid = "")
3203         {
3204                 $a = get_app();
3205
3206                 $enabled = intval(Config::get("system", "diaspora_enabled"));
3207                 if (!$enabled) {
3208                         return 200;
3209                 }
3210
3211                 $logid = random_string(4);
3212                 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
3213
3214                 // Fetch the fcontact entry when there is missing data
3215                 // Will possibly happen when data is transmitted to a DFRN contact
3216                 if (empty($dest_url) && !empty($contact['addr'])) {
3217                         $fcontact = self::personByHandle($contact['addr']);
3218                         $dest_url = ($public_batch ? $fcontact["batch"] : $fcontact["notify"]);
3219                 }
3220
3221                 if (!$dest_url) {
3222                         logger("no url for contact: ".$contact["id"]." batch mode =".$public_batch);
3223                         return 0;
3224                 }
3225
3226                 logger("transmit: ".$logid."-".$guid." ".$dest_url);
3227
3228                 if (!$queue_run && Queue::wasDelayed($contact["id"])) {
3229                         $return_code = 0;
3230                 } else {
3231                         if (!intval(Config::get("system", "diaspora_test"))) {
3232                                 $content_type = (($public_batch) ? "application/magic-envelope+xml" : "application/json");
3233
3234                                 Network::post($dest_url."/", $envelope, ["Content-Type: ".$content_type]);
3235                                 $return_code = $a->get_curl_code();
3236                         } else {
3237                                 logger("test_mode");
3238                                 return 200;
3239                         }
3240                 }
3241
3242                 logger("transmit: ".$logid."-".$guid." returns: ".$return_code);
3243
3244                 if (!$return_code || (($return_code == 503) && (stristr($a->get_curl_headers(), "retry-after")))) {
3245                         logger("queue message");
3246
3247                         $r = q(
3248                                 "SELECT `id` FROM `queue` WHERE `cid` = %d AND `network` = '%s' AND `content` = '%s' AND `batch` = %d LIMIT 1",
3249                                 intval($contact["id"]),
3250                                 dbesc(NETWORK_DIASPORA),
3251                                 dbesc($envelope),
3252                                 intval($public_batch)
3253                         );
3254                         if ($r) {
3255                                 logger("add_to_queue ignored - identical item already in queue");
3256                         } else {
3257                                 // queue message for redelivery
3258                                 Queue::add($contact["id"], NETWORK_DIASPORA, $envelope, $public_batch);
3259
3260                                 // The message could not be delivered. We mark the contact as "dead"
3261                                 Contact::markForArchival($contact);
3262                         }
3263                 } elseif (($return_code >= 200) && ($return_code <= 299)) {
3264                         // We successfully delivered a message, the contact is alive
3265                         Contact::unmarkForArchival($contact);
3266                 }
3267
3268                 return(($return_code) ? $return_code : (-1));
3269         }
3270
3271
3272         /**
3273          * @brief Build the post xml
3274          *
3275          * @param string $type    The message type
3276          * @param array  $message The message data
3277          *
3278          * @return string The post XML
3279          */
3280         public static function buildPostXml($type, $message)
3281         {
3282                 $data = [$type => $message];
3283
3284                 return XML::fromArray($data, $xml);
3285         }
3286
3287         /**
3288          * @brief Builds and transmit messages
3289          *
3290          * @param array  $owner        the array of the item owner
3291          * @param array  $contact      Target of the communication
3292          * @param string $type         The message type
3293          * @param array  $message      The message data
3294          * @param bool   $public_batch Is it a public post?
3295          * @param string $guid         message guid
3296          * @param bool   $spool        Should the transmission be spooled or transmitted?
3297          *
3298          * @return int Result of the transmission
3299          */
3300         private static function buildAndTransmit($owner, $contact, $type, $message, $public_batch = false, $guid = "", $spool = false)
3301         {
3302                 $msg = self::buildPostXml($type, $message);
3303
3304                 logger('message: '.$msg, LOGGER_DATA);
3305                 logger('send guid '.$guid, LOGGER_DEBUG);
3306
3307                 // Fallback if the private key wasn't transmitted in the expected field
3308                 if ($owner['uprvkey'] == "") {
3309                         $owner['uprvkey'] = $owner['prvkey'];
3310                 }
3311
3312                 $envelope = self::buildMessage($msg, $owner, $contact, $owner['uprvkey'], $contact['pubkey'], $public_batch);
3313
3314                 if ($spool) {
3315                         Queue::add($contact['id'], NETWORK_DIASPORA, $envelope, $public_batch);
3316                         return true;
3317                 } else {
3318                         $return_code = self::transmit($owner, $contact, $envelope, $public_batch, false, $guid);
3319                 }
3320
3321                 logger("guid: ".$guid." result ".$return_code, LOGGER_DEBUG);
3322
3323                 return $return_code;
3324         }
3325
3326         /**
3327          * @brief sends a participation (Used to get all further updates)
3328          *
3329          * @param array $contact Target of the communication
3330          * @param array $item    Item array
3331          *
3332          * @return int The result of the transmission
3333          */
3334         private static function sendParticipation($contact, $item)
3335         {
3336                 // Don't send notifications for private postings
3337                 if ($item['private']) {
3338                         return;
3339                 }
3340
3341                 $cachekey = "diaspora:sendParticipation:".$item['guid'];
3342
3343                 $result = Cache::get($cachekey);
3344                 if (!is_null($result)) {
3345                         return;
3346                 }
3347
3348                 // Fetch some user id to have a valid handle to transmit the participation.
3349                 // In fact it doesn't matter which user sends this - but it is needed by the protocol.
3350                 // If the item belongs to a user, we take this user id.
3351                 if ($item['uid'] == 0) {
3352                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false];
3353                         $first_user = dba::selectFirst('user', ['uid'], $condition);
3354                         $owner = User::getOwnerDataById($first_user['uid']);
3355                 } else {
3356                         $owner = User::getOwnerDataById($item['uid']);
3357                 }
3358
3359                 $author = self::myHandle($owner);
3360
3361                 $message = ["author" => $author,
3362                                 "guid" => get_guid(32),
3363                                 "parent_type" => "Post",
3364                                 "parent_guid" => $item["guid"]];
3365
3366                 logger("Send participation for ".$item["guid"]." by ".$author, LOGGER_DEBUG);
3367
3368                 // It doesn't matter what we store, we only want to avoid sending repeated notifications for the same item
3369                 Cache::set($cachekey, $item["guid"], CACHE_QUARTER_HOUR);
3370
3371                 return self::buildAndTransmit($owner, $contact, "participation", $message);
3372         }
3373
3374         /**
3375          * @brief sends an account migration
3376          *
3377          * @param array $owner   the array of the item owner
3378          * @param array $contact Target of the communication
3379          * @param int   $uid     User ID
3380          *
3381          * @return int The result of the transmission
3382          */
3383         public static function sendAccountMigration($owner, $contact, $uid)
3384         {
3385                 $old_handle = PConfig::get($uid, 'system', 'previous_addr');
3386                 $profile = self::createProfileData($uid);
3387
3388                 $signed_text = 'AccountMigration:'.$old_handle.':'.$profile['author'];
3389                 $signature = base64_encode(Crypto::rsaSign($signed_text, $owner["uprvkey"], "sha256"));
3390
3391                 $message = ["author" => $old_handle,
3392                                 "profile" => $profile,
3393                                 "signature" => $signature];
3394
3395                 logger("Send account migration ".print_r($message, true), LOGGER_DEBUG);
3396
3397                 return self::buildAndTransmit($owner, $contact, "account_migration", $message);
3398         }
3399
3400         /**
3401          * @brief Sends a "share" message
3402          *
3403          * @param array $owner   the array of the item owner
3404          * @param array $contact Target of the communication
3405          *
3406          * @return int The result of the transmission
3407          */
3408         public static function sendShare($owner, $contact)
3409         {
3410                 /**
3411                  * @todo support the different possible combinations of "following" and "sharing"
3412                  * Currently, Diaspora only interprets the "sharing" field
3413                  *
3414                  * Before switching this code productive, we have to check all "sendShare" calls if "rel" is set correctly
3415                  */
3416
3417                 /*
3418                 switch ($contact["rel"]) {
3419                         case CONTACT_IS_FRIEND:
3420                                 $following = true;
3421                                 $sharing = true;
3422                         case CONTACT_IS_SHARING:
3423                                 $following = false;
3424                                 $sharing = true;
3425                         case CONTACT_IS_FOLLOWER:
3426                                 $following = true;
3427                                 $sharing = false;
3428                 }
3429                 */
3430
3431                 $message = ["author" => self::myHandle($owner),
3432                                 "recipient" => $contact["addr"],
3433                                 "following" => "true",
3434                                 "sharing" => "true"];
3435
3436                 logger("Send share ".print_r($message, true), LOGGER_DEBUG);
3437
3438                 return self::buildAndTransmit($owner, $contact, "contact", $message);
3439         }
3440
3441         /**
3442          * @brief sends an "unshare"
3443          *
3444          * @param array $owner   the array of the item owner
3445          * @param array $contact Target of the communication
3446          *
3447          * @return int The result of the transmission
3448          */
3449         public static function sendUnshare($owner, $contact)
3450         {
3451                 $message = ["author" => self::myHandle($owner),
3452                                 "recipient" => $contact["addr"],
3453                                 "following" => "false",
3454                                 "sharing" => "false"];
3455
3456                 logger("Send unshare ".print_r($message, true), LOGGER_DEBUG);
3457
3458                 return self::buildAndTransmit($owner, $contact, "contact", $message);
3459         }
3460
3461         /**
3462          * @brief Checks a message body if it is a reshare
3463          *
3464          * @param string $body     The message body that is to be check
3465          * @param bool   $complete Should it be a complete check or a simple check?
3466          *
3467          * @return array|bool Reshare details or "false" if no reshare
3468          */
3469         public static function isReshare($body, $complete = true)
3470         {
3471                 $body = trim($body);
3472
3473                 // Skip if it isn't a pure repeated messages
3474                 // Does it start with a share?
3475                 if ((strpos($body, "[share") > 0) && $complete) {
3476                         return(false);
3477                 }
3478
3479                 // Does it end with a share?
3480                 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
3481                         return(false);
3482                 }
3483
3484                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
3485                 // Skip if there is no shared message in there
3486                 if ($body == $attributes) {
3487                         return(false);
3488                 }
3489
3490                 // If we don't do the complete check we quit here
3491                 if (!$complete) {
3492                         return true;
3493                 }
3494
3495                 $guid = "";
3496                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
3497                 if ($matches[1] != "") {
3498                         $guid = $matches[1];
3499                 }
3500
3501                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
3502                 if ($matches[1] != "") {
3503                         $guid = $matches[1];
3504                 }
3505
3506                 if ($guid != "") {
3507                         $r = q(
3508                                 "SELECT `contact-id` FROM `item` WHERE `guid` = '%s' AND `network` IN ('%s', '%s') LIMIT 1",
3509                                 dbesc($guid),
3510                                 NETWORK_DFRN,
3511                                 NETWORK_DIASPORA
3512                         );
3513                         if ($r) {
3514                                 $ret= [];
3515                                 $ret["root_handle"] = self::handleFromContact($r[0]["contact-id"]);
3516                                 $ret["root_guid"] = $guid;
3517                                 return($ret);
3518                         }
3519                 }
3520
3521                 $profile = "";
3522                 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
3523                 if ($matches[1] != "") {
3524                         $profile = $matches[1];
3525                 }
3526
3527                 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
3528                 if ($matches[1] != "") {
3529                         $profile = $matches[1];
3530                 }
3531
3532                 $ret= [];
3533
3534                 $ret["root_handle"] = preg_replace("=https?://(.*)/u/(.*)=ism", "$2@$1", $profile);
3535                 if (($ret["root_handle"] == $profile) || ($ret["root_handle"] == "")) {
3536                         return(false);
3537                 }
3538
3539                 $link = "";
3540                 preg_match("/link='(.*?)'/ism", $attributes, $matches);
3541                 if ($matches[1] != "") {
3542                         $link = $matches[1];
3543                 }
3544
3545                 preg_match('/link="(.*?)"/ism', $attributes, $matches);
3546                 if ($matches[1] != "") {
3547                         $link = $matches[1];
3548                 }
3549
3550                 $ret["root_guid"] = preg_replace("=https?://(.*)/posts/(.*)=ism", "$2", $link);
3551                 if (($ret["root_guid"] == $link) || (trim($ret["root_guid"]) == "")) {
3552                         return(false);
3553                 }
3554
3555                 return($ret);
3556         }
3557
3558         /**
3559          * @brief Create an event array
3560          *
3561          * @param integer $event_id The id of the event
3562          *
3563          * @return array with event data
3564          */
3565         private static function buildEvent($event_id)
3566         {
3567                 $r = q("SELECT `guid`, `uid`, `start`, `finish`, `nofinish`, `summary`, `desc`, `location`, `adjust` FROM `event` WHERE `id` = %d", intval($event_id));
3568                 if (!DBM::is_result($r)) {
3569                         return [];
3570                 }
3571
3572                 $event = $r[0];
3573
3574                 $eventdata = [];
3575
3576                 $r = q("SELECT `timezone` FROM `user` WHERE `uid` = %d", intval($event['uid']));
3577                 if (!DBM::is_result($r)) {
3578                         return [];
3579                 }
3580
3581                 $user = $r[0];
3582
3583                 $r = q("SELECT `addr`, `nick` FROM `contact` WHERE `uid` = %d AND `self`", intval($event['uid']));
3584                 if (!DBM::is_result($r)) {
3585                         return [];
3586                 }
3587
3588                 $owner = $r[0];
3589
3590                 $eventdata['author'] = self::myHandle($owner);
3591
3592                 if ($event['guid']) {
3593                         $eventdata['guid'] = $event['guid'];
3594                 }
3595
3596                 $mask = Temporal::ATOM;
3597
3598                 /// @todo - establish "all day" events in Friendica
3599                 $eventdata["all_day"] = "false";
3600
3601                 if (!$event['adjust']) {
3602                         $eventdata['timezone'] = $user['timezone'];
3603
3604                         if ($eventdata['timezone'] == "") {
3605                                 $eventdata['timezone'] = 'UTC';
3606                         }
3607                 }
3608
3609                 if ($event['start']) {
3610                         $eventdata['start'] = Temporal::convert($event['start'], "UTC", $eventdata['timezone'], $mask);
3611                 }
3612                 if ($event['finish'] && !$event['nofinish']) {
3613                         $eventdata['end'] = Temporal::convert($event['finish'], "UTC", $eventdata['timezone'], $mask);
3614                 }
3615                 if ($event['summary']) {
3616                         $eventdata['summary'] = html_entity_decode(bb2diaspora($event['summary']));
3617                 }
3618                 if ($event['desc']) {
3619                         $eventdata['description'] = html_entity_decode(bb2diaspora($event['desc']));
3620                 }
3621                 if ($event['location']) {
3622                         $location = [];
3623                         $location["address"] = html_entity_decode(bb2diaspora($event['location']));
3624                         $location["lat"] = 0;
3625                         $location["lng"] = 0;
3626                         $eventdata['location'] = $location;
3627                 }
3628
3629                 return $eventdata;
3630         }
3631
3632         /**
3633          * @brief Create a post (status message or reshare)
3634          *
3635          * @param array $item  The item that will be exported
3636          * @param array $owner the array of the item owner
3637          *
3638          * @return array
3639          * 'type' -> Message type ("status_message" or "reshare")
3640          * 'message' -> Array of XML elements of the status
3641          */
3642         public static function buildStatus($item, $owner)
3643         {
3644                 $cachekey = "diaspora:buildStatus:".$item['guid'];
3645
3646                 $result = Cache::get($cachekey);
3647                 if (!is_null($result)) {
3648                         return $result;
3649                 }
3650
3651                 $myaddr = self::myHandle($owner);
3652
3653                 $public = (($item["private"]) ? "false" : "true");
3654
3655                 $created = Temporal::utc($item["created"], Temporal::ATOM);
3656
3657                 // Detect a share element and do a reshare
3658                 if (!$item['private'] && ($ret = self::isReshare($item["body"]))) {
3659                         $message = ["author" => $myaddr,
3660                                         "guid" => $item["guid"],
3661                                         "created_at" => $created,
3662                                         "root_author" => $ret["root_handle"],
3663                                         "root_guid" => $ret["root_guid"],
3664                                         "provider_display_name" => $item["app"],
3665                                         "public" => $public];
3666
3667                         $type = "reshare";
3668                 } else {
3669                         $title = $item["title"];
3670                         $body = $item["body"];
3671
3672                         // convert to markdown
3673                         $body = html_entity_decode(bb2diaspora($body));
3674
3675                         // Adding the title
3676                         if (strlen($title)) {
3677                                 $body = "## ".html_entity_decode($title)."\n\n".$body;
3678                         }
3679
3680                         if ($item["attach"]) {
3681                                 $cnt = preg_match_all('/href=\"(.*?)\"(.*?)title=\"(.*?)\"/ism', $item["attach"], $matches, PREG_SET_ORDER);
3682                                 if (cnt) {
3683                                         $body .= "\n".L10n::t("Attachments:")."\n";
3684                                         foreach ($matches as $mtch) {
3685                                                 $body .= "[".$mtch[3]."](".$mtch[1].")\n";
3686                                         }
3687                                 }
3688                         }
3689
3690                         $location = [];
3691
3692                         if ($item["location"] != "")
3693                                 $location["address"] = $item["location"];
3694
3695                         if ($item["coord"] != "") {
3696                                 $coord = explode(" ", $item["coord"]);
3697                                 $location["lat"] = $coord[0];
3698                                 $location["lng"] = $coord[1];
3699                         }
3700
3701                         $message = ["author" => $myaddr,
3702                                         "guid" => $item["guid"],
3703                                         "created_at" => $created,
3704                                         "public" => $public,
3705                                         "text" => $body,
3706                                         "provider_display_name" => $item["app"],
3707                                         "location" => $location];
3708
3709                         // Diaspora rejects messages when they contain a location without "lat" or "lng"
3710                         if (!isset($location["lat"]) || !isset($location["lng"])) {
3711                                 unset($message["location"]);
3712                         }
3713
3714                         if ($item['event-id'] > 0) {
3715                                 $event = self::buildEvent($item['event-id']);
3716                                 if (count($event)) {
3717                                         $message['event'] = $event;
3718
3719                                         /// @todo Once Diaspora supports it, we will remove the body
3720                                         // $message['text'] = '';
3721                                 }
3722                         }
3723
3724                         $type = "status_message";
3725                 }
3726
3727                 $msg = ["type" => $type, "message" => $message];
3728
3729                 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
3730
3731                 return $msg;
3732         }
3733
3734         /**
3735          * @brief Sends a post
3736          *
3737          * @param array $item         The item that will be exported
3738          * @param array $owner        the array of the item owner
3739          * @param array $contact      Target of the communication
3740          * @param bool  $public_batch Is it a public post?
3741          *
3742          * @return int The result of the transmission
3743          */
3744         public static function sendStatus($item, $owner, $contact, $public_batch = false)
3745         {
3746                 $status = self::buildStatus($item, $owner);
3747
3748                 return self::buildAndTransmit($owner, $contact, $status["type"], $status["message"], $public_batch, $item["guid"]);
3749         }
3750
3751         /**
3752          * @brief Creates a "like" object
3753          *
3754          * @param array $item  The item that will be exported
3755          * @param array $owner the array of the item owner
3756          *
3757          * @return array The data for a "like"
3758          */
3759         private static function constructLike($item, $owner)
3760         {
3761                 $p = q(
3762                         "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3763                         dbesc($item["thr-parent"])
3764                 );
3765                 if (!DBM::is_result($p)) {
3766                         return false;
3767                 }
3768
3769                 $parent = $p[0];
3770
3771                 $target_type = ($parent["uri"] === $parent["parent-uri"] ? "Post" : "Comment");
3772                 if ($item['verb'] === ACTIVITY_LIKE) {
3773                         $positive = "true";
3774                 } elseif ($item['verb'] === ACTIVITY_DISLIKE) {
3775                         $positive = "false";
3776                 }
3777
3778                 return(["author" => self::myHandle($owner),
3779                                 "guid" => $item["guid"],
3780                                 "parent_guid" => $parent["guid"],
3781                                 "parent_type" => $target_type,
3782                                 "positive" => $positive,
3783                                 "author_signature" => ""]);
3784         }
3785
3786         /**
3787          * @brief Creates an "EventParticipation" object
3788          *
3789          * @param array $item  The item that will be exported
3790          * @param array $owner the array of the item owner
3791          *
3792          * @return array The data for an "EventParticipation"
3793          */
3794         private static function constructAttend($item, $owner)
3795         {
3796                 $p = q(
3797                         "SELECT `guid`, `uri`, `parent-uri` FROM `item` WHERE `uri` = '%s' LIMIT 1",
3798                         dbesc($item["thr-parent"])
3799                 );
3800                 if (!DBM::is_result($p)) {
3801                         return false;
3802                 }
3803
3804                 $parent = $p[0];
3805
3806                 switch ($item['verb']) {
3807                         case ACTIVITY_ATTEND:
3808                                 $attend_answer = 'accepted';
3809                                 break;
3810                         case ACTIVITY_ATTENDNO:
3811                                 $attend_answer = 'declined';
3812                                 break;
3813                         case ACTIVITY_ATTENDMAYBE:
3814                                 $attend_answer = 'tentative';
3815                                 break;
3816                         default:
3817                                 logger('Unknown verb '.$item['verb'].' in item '.$item['guid']);
3818                                 return false;
3819                 }
3820
3821                 return(["author" => self::myHandle($owner),
3822                                 "guid" => $item["guid"],
3823                                 "parent_guid" => $parent["guid"],
3824                                 "status" => $attend_answer,
3825                                 "author_signature" => ""]);
3826         }
3827
3828         /**
3829          * @brief Creates the object for a comment
3830          *
3831          * @param array $item  The item that will be exported
3832          * @param array $owner the array of the item owner
3833          *
3834          * @return array The data for a comment
3835          */
3836         private static function constructComment($item, $owner)
3837         {
3838                 $cachekey = "diaspora:constructComment:".$item['guid'];
3839
3840                 $result = Cache::get($cachekey);
3841                 if (!is_null($result)) {
3842                         return $result;
3843                 }
3844
3845                 $p = q(
3846                         "SELECT `guid` FROM `item` WHERE `parent` = %d AND `id` = %d LIMIT 1",
3847                         intval($item["parent"]),
3848                         intval($item["parent"])
3849                 );
3850
3851                 if (!DBM::is_result($p)) {
3852                         return false;
3853                 }
3854
3855                 $parent = $p[0];
3856
3857                 $text = html_entity_decode(bb2diaspora($item["body"]));
3858                 $created = Temporal::utc($item["created"], Temporal::ATOM);
3859
3860                 $comment = ["author" => self::myHandle($owner),
3861                                 "guid" => $item["guid"],
3862                                 "created_at" => $created,
3863                                 "parent_guid" => $parent["guid"],
3864                                 "text" => $text,
3865                                 "author_signature" => ""];
3866
3867                 // Send the thread parent guid only if it is a threaded comment
3868                 if ($item['thr-parent'] != $item['parent-uri']) {
3869                         $comment['thread_parent_guid'] = self::getGuidFromUri($item['thr-parent'], $item['uid']);
3870                 }
3871
3872                 Cache::set($cachekey, $comment, CACHE_QUARTER_HOUR);
3873
3874                 return($comment);
3875         }
3876
3877         /**
3878          * @brief Send a like or a comment
3879          *
3880          * @param array $item         The item that will be exported
3881          * @param array $owner        the array of the item owner
3882          * @param array $contact      Target of the communication
3883          * @param bool  $public_batch Is it a public post?
3884          *
3885          * @return int The result of the transmission
3886          */
3887         public static function sendFollowup($item, $owner, $contact, $public_batch = false)
3888         {
3889                 if (in_array($item['verb'], [ACTIVITY_ATTEND, ACTIVITY_ATTENDNO, ACTIVITY_ATTENDMAYBE])) {
3890                         $message = self::constructAttend($item, $owner);
3891                         $type = "event_participation";
3892                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3893                         $message = self::constructLike($item, $owner);
3894                         $type = "like";
3895                 } else {
3896                         $message = self::constructComment($item, $owner);
3897                         $type = "comment";
3898                 }
3899
3900                 if (!$message) {
3901                         return false;
3902                 }
3903
3904                 $message["author_signature"] = self::signature($owner, $message);
3905
3906                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
3907         }
3908
3909         /**
3910          * @brief Creates a message from a signature record entry
3911          *
3912          * @param array $item      The item that will be exported
3913          * @param array $signature The entry of the "sign" record
3914          *
3915          * @return string The message
3916          */
3917         private static function messageFromSignature($item, $signature)
3918         {
3919                 // Split the signed text
3920                 $signed_parts = explode(";", $signature['signed_text']);
3921
3922                 if ($item["deleted"]) {
3923                         $message = ["author" => $signature['signer'],
3924                                         "target_guid" => $signed_parts[0],
3925                                         "target_type" => $signed_parts[1]];
3926                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3927                         $message = ["author" => $signed_parts[4],
3928                                         "guid" => $signed_parts[1],
3929                                         "parent_guid" => $signed_parts[3],
3930                                         "parent_type" => $signed_parts[2],
3931                                         "positive" => $signed_parts[0],
3932                                         "author_signature" => $signature['signature'],
3933                                         "parent_author_signature" => ""];
3934                 } else {
3935                         // Remove the comment guid
3936                         $guid = array_shift($signed_parts);
3937
3938                         // Remove the parent guid
3939                         $parent_guid = array_shift($signed_parts);
3940
3941                         // Remove the handle
3942                         $handle = array_pop($signed_parts);
3943
3944                         // Glue the parts together
3945                         $text = implode(";", $signed_parts);
3946
3947                         $message = ["author" => $handle,
3948                                         "guid" => $guid,
3949                                         "parent_guid" => $parent_guid,
3950                                         "text" => implode(";", $signed_parts),
3951                                         "author_signature" => $signature['signature'],
3952                                         "parent_author_signature" => ""];
3953                 }
3954                 return $message;
3955         }
3956
3957         /**
3958          * @brief Relays messages (like, comment, retraction) to other servers if we are the thread owner
3959          *
3960          * @param array $item         The item that will be exported
3961          * @param array $owner        the array of the item owner
3962          * @param array $contact      Target of the communication
3963          * @param bool  $public_batch Is it a public post?
3964          *
3965          * @return int The result of the transmission
3966          */
3967         public static function sendRelay($item, $owner, $contact, $public_batch = false)
3968         {
3969                 if ($item["deleted"]) {
3970                         return self::sendRetraction($item, $owner, $contact, $public_batch, true);
3971                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
3972                         $type = "like";
3973                 } else {
3974                         $type = "comment";
3975                 }
3976
3977                 logger("Got relayable data ".$type." for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3978
3979                 // fetch the original signature
3980
3981                 $r = q(
3982                         "SELECT `signed_text`, `signature`, `signer` FROM `sign` WHERE `iid` = %d LIMIT 1",
3983                         intval($item["id"])
3984                 );
3985
3986                 if (!$r) {
3987                         logger("Couldn't fetch signatur for item ".$item["guid"]." (".$item["id"].")", LOGGER_DEBUG);
3988                         return false;
3989                 }
3990
3991                 $signature = $r[0];
3992
3993                 // Old way - is used by the internal Friendica functions
3994                 /// @todo Change all signatur storing functions to the new format
3995                 if ($signature['signed_text'] && $signature['signature'] && $signature['signer']) {
3996                         $message = self::messageFromSignature($item, $signature);
3997                 } else {// New way
3998                         $msg = json_decode($signature['signed_text'], true);
3999
4000                         $message = [];
4001                         if (is_array($msg)) {
4002                                 foreach ($msg as $field => $data) {
4003                                         if (!$item["deleted"]) {
4004                                                 if ($field == "diaspora_handle") {
4005                                                         $field = "author";
4006                                                 }
4007                                                 if ($field == "target_type") {
4008                                                         $field = "parent_type";
4009                                                 }
4010                                         }
4011
4012                                         $message[$field] = $data;
4013                                 }
4014                         } else {
4015                                 logger("Signature text for item ".$item["guid"]." (".$item["id"].") couldn't be extracted: ".$signature['signed_text'], LOGGER_DEBUG);
4016                         }
4017                 }
4018
4019                 $message["parent_author_signature"] = self::signature($owner, $message);
4020
4021                 logger("Relayed data ".print_r($message, true), LOGGER_DEBUG);
4022
4023                 return self::buildAndTransmit($owner, $contact, $type, $message, $public_batch, $item["guid"]);
4024         }
4025
4026         /**
4027          * @brief Sends a retraction (deletion) of a message, like or comment
4028          *
4029          * @param array $item         The item that will be exported
4030          * @param array $owner        the array of the item owner
4031          * @param array $contact      Target of the communication
4032          * @param bool  $public_batch Is it a public post?
4033          * @param bool  $relay        Is the retraction transmitted from a relay?
4034          *
4035          * @return int The result of the transmission
4036          */
4037         public static function sendRetraction($item, $owner, $contact, $public_batch = false, $relay = false)
4038         {
4039                 $itemaddr = self::handleFromContact($item["contact-id"], $item["gcontact-id"]);
4040
4041                 $msg_type = "retraction";
4042
4043                 if ($item['id'] == $item['parent']) {
4044                         $target_type = "Post";
4045                 } elseif (in_array($item["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4046                         $target_type = "Like";
4047                 } else {
4048                         $target_type = "Comment";
4049                 }
4050
4051                 $message = ["author" => $itemaddr,
4052                                 "target_guid" => $item['guid'],
4053                                 "target_type" => $target_type];
4054
4055                 logger("Got message ".print_r($message, true), LOGGER_DEBUG);
4056
4057                 return self::buildAndTransmit($owner, $contact, $msg_type, $message, $public_batch, $item["guid"]);
4058         }
4059
4060         /**
4061          * @brief Sends a mail
4062          *
4063          * @param array $item    The item that will be exported
4064          * @param array $owner   The owner
4065          * @param array $contact Target of the communication
4066          *
4067          * @return int The result of the transmission
4068          */
4069         public static function sendMail($item, $owner, $contact)
4070         {
4071                 $myaddr = self::myHandle($owner);
4072
4073                 $r = q(
4074                         "SELECT * FROM `conv` WHERE `id` = %d AND `uid` = %d LIMIT 1",
4075                         intval($item["convid"]),
4076                         intval($item["uid"])
4077                 );
4078
4079                 if (!DBM::is_result($r)) {
4080                         logger("conversation not found.");
4081                         return;
4082                 }
4083                 $cnv = $r[0];
4084
4085                 $conv = [
4086                         "author" => $cnv["creator"],
4087                         "guid" => $cnv["guid"],
4088                         "subject" => $cnv["subject"],
4089                         "created_at" => Temporal::utc($cnv['created'], Temporal::ATOM),
4090                         "participants" => $cnv["recips"]
4091                 ];
4092
4093                 $body = bb2diaspora($item["body"]);
4094                 $created = Temporal::utc($item["created"], Temporal::ATOM);
4095
4096                 $msg = [
4097                         "author" => $myaddr,
4098                         "guid" => $item["guid"],
4099                         "conversation_guid" => $cnv["guid"],
4100                         "text" => $body,
4101                         "created_at" => $created,
4102                 ];
4103
4104                 if ($item["reply"]) {
4105                         $message = $msg;
4106                         $type = "message";
4107                 } else {
4108                         $message = [
4109                                         "author" => $cnv["creator"],
4110                                         "guid" => $cnv["guid"],
4111                                         "subject" => $cnv["subject"],
4112                                         "created_at" => Temporal::utc($cnv['created'], Temporal::ATOM),
4113                                         "participants" => $cnv["recips"],
4114                                         "message" => $msg];
4115
4116                         $type = "conversation";
4117                 }
4118
4119                 return self::buildAndTransmit($owner, $contact, $type, $message, false, $item["guid"]);
4120         }
4121
4122         /**
4123          * @brief Split a name into first name and last name
4124          *
4125          * @param string $name The name
4126          *
4127          * @return array The array with "first" and "last"
4128          */
4129         public static function splitName($name) {
4130                 $name = trim($name);
4131
4132                 // Is the name longer than 64 characters? Then cut the rest of it.
4133                 if (strlen($name) > 64) {
4134                         if ((strpos($name, ' ') <= 64) && (strpos($name, ' ') !== false)) {
4135                                 $name = trim(substr($name, 0, strrpos(substr($name, 0, 65), ' ')));
4136                         } else {
4137                                 $name = substr($name, 0, 64);
4138                         }
4139                 }
4140
4141                 // Take the first word as first name
4142                 $first = ((strpos($name, ' ') ? trim(substr($name, 0, strpos($name, ' '))) : $name));
4143                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4144                 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4145                         return ['first' => $first, 'last' => $last];
4146                 }
4147
4148                 // Take the last word as last name
4149                 $first = ((strrpos($name, ' ') ? trim(substr($name, 0, strrpos($name, ' '))) : $name));
4150                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4151
4152                 if ((strlen($first) < 32) && (strlen($last) < 32)) {
4153                         return ['first' => $first, 'last' => $last];
4154                 }
4155
4156                 // Take the first 32 characters if there is no space in the first 32 characters
4157                 if ((strpos($name, ' ') > 32) || (strpos($name, ' ') === false)) {
4158                         $first = substr($name, 0, 32);
4159                         $last = substr($name, 32);
4160                         return ['first' => $first, 'last' => $last];
4161                 }
4162
4163                 $first = trim(substr($name, 0, strrpos(substr($name, 0, 33), ' ')));
4164                 $last = (($first === $name) ? '' : trim(substr($name, strlen($first))));
4165
4166                 // Check if the last name is longer than 32 characters
4167                 if (strlen($last) > 32) {
4168                         if (strpos($last, ' ') <= 32) {
4169                                 $last = trim(substr($last, 0, strrpos(substr($last, 0, 33), ' ')));
4170                         } else {
4171                                 $last = substr($last, 0, 32);
4172                         }
4173                 }
4174
4175                 return ['first' => $first, 'last' => $last];
4176         }
4177
4178         /**
4179          * @brief Create profile data
4180          *
4181          * @param int $uid The user id
4182          *
4183          * @return array The profile data
4184          */
4185         private static function createProfileData($uid)
4186         {
4187                 $r = q(
4188                         "SELECT `profile`.`uid` AS `profile_uid`, `profile`.* , `user`.*, `user`.`prvkey` AS `uprvkey`, `contact`.`addr`
4189                         FROM `profile`
4190                         INNER JOIN `user` ON `profile`.`uid` = `user`.`uid`
4191                         INNER JOIN `contact` ON `profile`.`uid` = `contact`.`uid`
4192                         WHERE `user`.`uid` = %d AND `profile`.`is-default` AND `contact`.`self` LIMIT 1",
4193                         intval($uid)
4194                 );
4195
4196                 if (!$r) {
4197                         return [];
4198                 }
4199
4200                 $profile = $r[0];
4201                 $handle = $profile["addr"];
4202
4203                 $split_name = self::splitName($profile['name']);
4204                 $first = $split_name['first'];
4205                 $last = $split_name['last'];
4206
4207                 $large = System::baseUrl().'/photo/custom/300/'.$profile['uid'].'.jpg';
4208                 $medium = System::baseUrl().'/photo/custom/100/'.$profile['uid'].'.jpg';
4209                 $small = System::baseUrl().'/photo/custom/50/'  .$profile['uid'].'.jpg';
4210                 $searchable = (($profile['publish'] && $profile['net-publish']) ? 'true' : 'false');
4211
4212                 if ($searchable === 'true') {
4213                         $dob = '';
4214
4215                         if ($profile['dob'] && ($profile['dob'] > '0000-00-00')) {
4216                                 list($year, $month, $day) = sscanf($profile['dob'], '%4d-%2d-%2d');
4217                                 if ($year < 1004) {
4218                                         $year = 1004;
4219                                 }
4220                                 $dob = Temporal::utc($year . '-' . $month . '-'. $day, 'Y-m-d');
4221                         }
4222
4223                         $about = $profile['about'];
4224                         $about = strip_tags(bbcode($about));
4225
4226                         $location = Profile::formatLocation($profile);
4227                         $tags = '';
4228                         if ($profile['pub_keywords']) {
4229                                 $kw = str_replace(',', ' ', $profile['pub_keywords']);
4230                                 $kw = str_replace('  ', ' ', $kw);
4231                                 $arr = explode(' ', $profile['pub_keywords']);
4232                                 if (count($arr)) {
4233                                         for ($x = 0; $x < 5; $x ++) {
4234                                                 if (trim($arr[$x])) {
4235                                                         $tags .= '#'. trim($arr[$x]) .' ';
4236                                                 }
4237                                         }
4238                                 }
4239                         }
4240                         $tags = trim($tags);
4241                 }
4242
4243                 return ["author" => $handle,
4244                                 "first_name" => $first,
4245                                 "last_name" => $last,
4246                                 "image_url" => $large,
4247                                 "image_url_medium" => $medium,
4248                                 "image_url_small" => $small,
4249                                 "birthday" => $dob,
4250                                 "gender" => $profile['gender'],
4251                                 "bio" => $about,
4252                                 "location" => $location,
4253                                 "searchable" => $searchable,
4254                                 "nsfw" => "false",
4255                                 "tag_string" => $tags];
4256         }
4257
4258         /**
4259          * @brief Sends profile data
4260          *
4261          * @param int  $uid    The user id
4262          * @param bool $recips optional, default false
4263          * @return void
4264          */
4265         public static function sendProfile($uid, $recips = false)
4266         {
4267                 if (!$uid) {
4268                         return;
4269                 }
4270
4271                 $owner = User::getOwnerDataById($uid);
4272                 if (!$owner) {
4273                         return;
4274                 }
4275
4276                 if (!$recips) {
4277                         $recips = q(
4278                                 "SELECT `id`,`name`,`network`,`pubkey`,`notify` FROM `contact` WHERE `network` = '%s'
4279                                 AND `uid` = %d AND `rel` != %d",
4280                                 dbesc(NETWORK_DIASPORA),
4281                                 intval($uid),
4282                                 intval(CONTACT_IS_SHARING)
4283                         );
4284                 }
4285
4286                 if (!$recips) {
4287                         return;
4288                 }
4289
4290                 $message = self::createProfileData($uid);
4291
4292                 foreach ($recips as $recip) {
4293                         logger("Send updated profile data for user ".$uid." to contact ".$recip["id"], LOGGER_DEBUG);
4294                         self::buildAndTransmit($owner, $recip, "profile", $message, false, "", false);
4295                 }
4296         }
4297
4298         /**
4299          * @brief Stores the signature for likes that are created on our system
4300          *
4301          * @param array $contact The contact array of the "like"
4302          * @param int   $post_id The post id of the "like"
4303          *
4304          * @return bool Success
4305          */
4306         public static function storeLikeSignature($contact, $post_id)
4307         {
4308                 // Is the contact the owner? Then fetch the private key
4309                 if (!$contact['self'] || ($contact['uid'] == 0)) {
4310                         logger("No owner post, so not storing signature", LOGGER_DEBUG);
4311                         return false;
4312                 }
4313
4314                 $r = q("SELECT `prvkey` FROM `user` WHERE `uid` = %d LIMIT 1", intval($contact['uid']));
4315                 if (!DBM::is_result($r)) {
4316                         return false;
4317                 }
4318
4319                 $contact["uprvkey"] = $r[0]['prvkey'];
4320
4321                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1", intval($post_id));
4322                 if (!DBM::is_result($r)) {
4323                         return false;
4324                 }
4325
4326                 if (!in_array($r[0]["verb"], [ACTIVITY_LIKE, ACTIVITY_DISLIKE])) {
4327                         return false;
4328                 }
4329
4330                 $message = self::constructLike($r[0], $contact);
4331                 if ($message === false) {
4332                         return false;
4333                 }
4334
4335                 $message["author_signature"] = self::signature($contact, $message);
4336
4337                 /*
4338                  * Now store the signature more flexible to dynamically support new fields.
4339                  * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4340                  */
4341                 dba::insert('sign', ['iid' => $post_id, 'signed_text' => json_encode($message)]);
4342
4343                 logger('Stored diaspora like signature');
4344                 return true;
4345         }
4346
4347         /**
4348          * @brief Stores the signature for comments that are created on our system
4349          *
4350          * @param array  $item       The item array of the comment
4351          * @param array  $contact    The contact array of the item owner
4352          * @param string $uprvkey    The private key of the sender
4353          * @param int    $message_id The message id of the comment
4354          *
4355          * @return bool Success
4356          */
4357         public static function storeCommentSignature($item, $contact, $uprvkey, $message_id)
4358         {
4359                 if ($uprvkey == "") {
4360                         logger('No private key, so not storing comment signature', LOGGER_DEBUG);
4361                         return false;
4362                 }
4363
4364                 $contact["uprvkey"] = $uprvkey;
4365
4366                 $message = self::constructComment($item, $contact);
4367                 if ($message === false) {
4368                         return false;
4369                 }
4370
4371                 $message["author_signature"] = self::signature($contact, $message);
4372
4373                 /*
4374                  * Now store the signature more flexible to dynamically support new fields.
4375                  * This will break Diaspora compatibility with Friendica versions prior to 3.5.
4376                  */
4377                 dba::insert('sign', ['iid' => $message_id, 'signed_text' => json_encode($message)]);
4378
4379                 logger('Stored diaspora comment signature');
4380                 return true;
4381         }
4382 }