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