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