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