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