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