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