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