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