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