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