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