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