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