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