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