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