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