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