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