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