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