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