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