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