-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths3rl.php
473 lines (346 loc) · 13.9 KB
/
s3rl.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
<?php
#this script accepts inputs of url,public key and, in case an update is attemtped, an encripted message as well
#where should information on url and public key go? Special project where only admin can access.
ini_set('display_errors',0);
if($_REQUEST['su3d'])
ini_set('display_errors',1);
$format=$_REQUEST['format'];
include_once('config.inc.php');
$key=$GLOBALS['deployment_project']['key'];
include 'core.header.php';
if($_REQUEST['url']!='' && $_REQUEST['publicKey']!='')
{$case = 'registernewURL';
}
elseif(($_REQUEST['Did']!='' || $_REQUEST['url']!='') && !in_array('newUrl', array_keys($_REQUEST)))
$case = 'findURL';
elseif($_REQUEST['Did']!='' && in_array('newUrl', array_keys($_REQUEST)))
$case = 'updateURL';
else {
//echo 's3rl.php is a function to retrieve the url of a specific Did. For documentation and usage please refer to <a href="http://s3db.org/">s3db.org</a>';
echo formatReturn($GLOBALS['error_codes']['wrong_input'],'s3rl.php is a function to retrieve the url of a specific Did. For documentation and usage please refer to http://s3db.org/documentation', $format, '');
exit;
}
$url =$_REQUEST['url'];
$publicKey = urldecode($_REQUEST['publicKey']);
$Did = ($_REQUEST['s3rl']!='')?$_REQUEST['s3rl']:$_REQUEST['Did'];
$newUrl = $_REQUEST['newUrl'];
$message = $_REQUEST['message'];
$name = $_REQUEST['name'];
list($regValid, $msg) = registerURL(compact('url', 'publicKey', 'Did', 's3rl', 'newUrl', 'case', 'message','name','format'));
if($regValid)
{ $Did = $msg['deployment_id'];
$finName = $msg['name'];
if($case == 'registernewURL')
{echo formatReturn('0','URL registered', $_REQUEST['format'], array('deployment_id'=>$Did, 'name'=>$finName));
}
elseif($case == 'findURL')
{
$cols = array_keys($msg);
$data[0] = $msg;
$format =($_REQUEST['format']=='')?'html':$_REQUEST['format'];
$z = compact('data','cols', 'format');
echo outputFormat($z);
}
elseif($case == 'updateURL')
echo formatReturn($GLOBALS['error_codes']['success'],$msg,$format,array('newUrl'=>$newUrl));
exit;
}
else {
echo formatReturn($GLOBALS['error_codes']['wrong_input'],$msg,$format,'');
exit;
}
function registerURL($U)
{#this function call the db but it should NOT leave this one function
extract($U);
#include (S3DB_SERVER_ROOT.'/webActions.php');
#require_once(S3DB_SERVER_ROOT.'/s3dbcore/class.db.inc.php');
#include_once(S3DB_SERVER_ROOT.'/s3dbcore/common_functions.inc.php');
#include_once(S3DB_SERVER_ROOT.'/s3dbcore/callback.php');
#Generate Did, and, since we're on it, name if empty
if(!$Did && $case=='registernewURL')
$Did = s3id();
if(!$name && $case=='registernewURL'){
$name = 'D'.$Did;
$U['name']=$name;
}
$db = CreateObject('s3dbapi.db');
$db->Halt_On_Error = 'no';
$db->Host = $GLOBALS['s3db_info']['server']['db']['db_host'];
$db->Type = $GLOBALS['s3db_info']['server']['db']['db_type'];
$db->Database = $GLOBALS['s3db_info']['server']['db']['db_name'];
$db->User = $GLOBALS['s3db_info']['server']['db']['db_user'];
$db->Password = $GLOBALS['s3db_info']['server']['db']['db_pass'];
$db->connect();
$U['db']=$db;
list($inputValid, $errMessage)=validate_register_inputs($U);
if($inputValid){
switch ($case) {
case 'registernewURL':{
$protocol = ($_SERVER['HTTPS']!='')?'https://':'http://';
$url =ereg('localhost', $url)?$protocol.getClientIP().str_replace($protocol.'localhost', '', $url):$url;
$_REQUEST['description'] = is_base64_encoded_s($_REQUEST['description'])?base64_decode($_REQUEST['description']):$_REQUEST['description'];
$description=$_REQUEST['description'];
#echo $sql;exit;
#echo $s3rl;exit;
if($Did!=''){
$sql = "select * from s3db_deployment where deployment_id = '".$Did."'";
$db->query($sql, __LINE__, __FILE__);
if($db->next_record())
{
return array(False, 'Did already exists. Please provide another one or leave that field blank for an arbitrary value');
}
}
$sql = "insert into s3db_deployment (deployment_id, url, publickey, message, created_on) values ('".$Did."', '".$url."', '".$publicKey."', '".random_string(20)."', now())";
$db->query($sql, __LINE__, __FILE__);
$s3rl = $Did;
if($db->Errno==0){
##Now create an entry in the project of deployemnts;
#create a remote user to access this entry
$remoteUser = $url.((substr($url, strlen($url)-1,1)=='/')?'':'/').'U1';
$user_id = '1';
$s3ql=compact('user_id','db');
$s3ql['insert']='item';
$s3ql['where']['collection_id']=$GLOBALS['deployment_project']['collection_id'];
$s3ql['where']['item_id']=$Did;
$s3ql['where']['notes']=($name=='')?urlencode('Deployment '.$Did):$name;
$s3ql['format']='php';
$done = unserialize(S3QLaction($s3ql));
$msg=$done[0];
if($msg['error_code']=='0' || $msg['error_code']=='4')
{
$s3ql=compact('user_id','db');
$s3ql['insert']='user';
$s3ql['where']['item_id']=$msg['item_id'];
$s3ql['where']['user_id']=$remoteUser;
$s3ql['where']['permission_level']='222';
$s3ql['format']='php';
$done = S3QLaction($s3ql);
$item_id = $msg['item_id'];
$msg1=unserialize($done);$msg1=$msg[0];
##prepare a file to save this info
if(is_file(S3DB_SERVER_ROOT.'/tmp/mothership_info_file') && $_REQUEST['clean']=='mothership')
{ unlink(S3DB_SERVER_ROOT.'/tmp/mothership_info_file');}
if(is_file(S3DB_SERVER_ROOT.'/tmp/mothership_info_file')){
$mothership_info = unserialize(file_get_contents(S3DB_SERVER_ROOT.'/tmp/mothership_info_file'));
$rules = $mothership_info['rules'];
}
else {
#find the collectiont rules
$s3ql=compact('user_id','db');
$s3ql['from']='rules';
$s3ql['where']['subject_id']=$GLOBALS['deployment_project']['collection_id'];
$rules = S3QLaction($s3ql);
$mothership_info['rules'] = $rules;
file_put_contents(S3DB_SERVER_ROOT.'/tmp/mothership_info_file', serialize($mothership_info));
}
if(!empty($rules)){
$s3ql=compact('user_id','db');
$s3ql['insert']='statement';
$s3ql['where']['item_id']=$item_id;
foreach ($rules as $key=>$rule_info) {
if(in_array($rule_info['object'], array_keys($_REQUEST))){
$s3ql['where']['rule_id']=$rule_info['rule_id'];
if($rule_info['object']=='keywords'){
$keywords = explode(',', urldecode($_REQUEST['keywords']));
foreach ($keywords as $word) {
if(is_base64_encoded_s($word)) $word = base64_decode($word);
$s3ql['where']['value']=$word;
$done = S3QLaction($s3ql);
}
}
elseif($rule_info['object']=='url'){
$s3ql['where']['value']=$url;
$done = S3QLaction($s3ql);
}
elseif($rule_info['object']=='description'){
$v=$_REQUEST[$rule_info['object']];
if(is_base64_encoded_s($v)) $v=base64_decode($v);
$s3ql['where']['value']=$v;
$done = S3QLaction($s3ql);
}
elseif($rule_info['object']=='name'){
$s3ql['where']['value']=urldecode($name);
$done = S3QLaction($s3ql);
}
else{
$v=urldecode($_REQUEST[$rule_info['object']]);
$s3ql['where']['value']=$v;
$done = S3QLaction($s3ql);
}
}
}
}
}
#}
}
#After registering url, return Did
if($Did!='')
return array(True, array('deployment_id'=>$Did,'name'=>$name));
else {
return array(False, '');
}
break;
}
case 'findURL':{
##Let's first check if there is already a deployment in this URL
if($url!=''){
$sql = "select * from s3db_deployment where url = '".$url."'";
$db->query($sql, __LINE__, __FILE__);
if($db->next_record())
{
$reg = array('deployment_id'=>$db->f('deployment_id'), 'url'=>$db->f('url'), 'modified_on'=>$db->f('modified_on'));
return (array(True, $reg));
}
}
elseif($Did!='') {
$sql = "select * from s3db_deployment where deployment_id = '".str_replace('D', '', $Did)."'";
$db->query($sql, __LINE__, __FILE__);
if($db->next_record())
{
$reg = array('url'=>$db->f('url'),
'publicKey'=>$db->f('publickey'),
'modified_on'=>$db->f('modified_on'));
return array(True, $reg);
}
else {
return array(False, 'Did not found');
}
}
break;
}
case 'updateURL':{
#did the user send the decripted message already? Validate and change the message
if($message!='') #check if it matches whatever is in store for this Did
{
$sql = "select * from s3db_deployment where deployment_id = '".str_replace('D', '', $Did)."'";
$db->query($sql, __LINE__, __FILE__);
if($db->next_record())
{
$oldUrl= $db->f('url');
$storedMessage= $db->f('message');
#do messages match?
if($storedMessage!=$message)
{
#$sql = "update s3db_register set message= '".random_string(20)."' where deployment_id = '".str_replace('D', '', $Did)."'";
return array(False, 'Error code:<error>3</error><description> Decripted Message does not match the request</description>');
}
else {
#echo 'ahaa, you found it :-)';
#update key
$sql = "update s3db_deployment set url = '".$newUrl."', message= '".random_string(20)."', modified_on = now() where deployment_id = '".str_replace('D', '', $Did)."'";
$db->query($sql, __LINE__, __FILE__);
##Now update the entry on s3db
$sql = "update s3db_statement set url='".$newUrl."' where rule_id='' and item_id=''";
$dbdata = get_object_vars($db);
if($dbdata['Errno']=='0')
return array(True, 'Error code:<error>0</error><description> URL updated</description>');
else {
return array(False, 'Error code:<error>1</error><description> Could not update URL</description>');
}
}
}
else {
return array(False, 'Error code:<error>2</error> Could not find Did');
}
}
else{
#send a message to the url to make sure he is who he says he is
$sql = "select * from s3db_deployment where deployment_id = '".ereg_replace('^D', '', $Did)."'";
$db->query($sql);
if($db->next_record())
{
$publicKey= $db->f('publickey');
$message= $db->f('message');
}
else {
return array(False, 'Could not find URL');
}
##detect which version was used to create this public key... it's sad but necessary due to non-backward compatible RSA_crypt :(
if(ereg("BEGIN PUBLIC KEY", base64_decode($publicKey))){
set_include_path(get_include_path() . PATH_SEPARATOR . 'pearlib/phpseclib');
include('pearlib/phpseclib/Crypt/RSA.php');
$rsa = new Crypt_RSA();
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_OAEP);
$publicKey = base64_decode($publicKey);
$rsa->loadKey($publicKey);
$encripted = $rsa->encrypt($message);
}
else {
#encript it
require_once 'pearlib/RSACrypt/RSA.php';
$encripted = encrypt($message, $publicKey);
if($encripted=='')
$encripted = encrypt($message, urlencode($publicKey));
}
$ErrMessage = "For authentication, please decript this message using your private key: <message>".rawurlencode($encripted)."</message><br />(Note: you might need to remove url encoding that your browser might have added before decoding. Plase refer to http://www.asciitable.com/ for the correct characters.)";
echo formatReturn($GLOBALS['error_codes']['success'],$ErrMessage, $format, array('encripted'=>$encripted));
exit;
#echo "For authentication, please decript this message using your private key: <message>".rawurlencode($encripted)."</message>";
#echo "<br />(Note: you might need to remove url encoding that your browser might have added before decoding. Plase refer to http://www.asciitable.com/ for the correct characters.)";
# exit;
}
}
}
}
else {
echo formatReturn($GLOBALS['error_codes']['wrong_input'],$errMessage, $format, '');
}
}
function encrypt($message, $publicKey)
{
$plain_text = $message;
$public_key = $publicKey;
$key = Crypt_RSA_Key::fromString($public_key);
if($key->isError())
{return("");}
check_error($key);
$rsa_obj = new Crypt_RSA;
check_error($rsa_obj);
$enc_text = $rsa_obj->encrypt($plain_text, $key);
check_error($rsa_obj);
return ($enc_text);
}
function getClientIP() {
$ip;
if (getenv("HTTP_CLIENT_IP"))
$ip = getenv("HTTP_CLIENT_IP");
else if(getenv("HTTP_X_FORWARDED_FOR"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if(getenv("REMOTE_ADDR"))
$ip = getenv("REMOTE_ADDR");
else
$ip = "UNKNOWN";
return $ip;
}
function is_base64_encoded_s($data)
{
if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $data)) {
return TRUE;
} else {
return FALSE;
}
};
function validate_register_inputs($U)
{
extract($U);
#Things to check: name; Did
#Check name: name cannot be equal to a Did and must be unique
if($name){
$sql = "select * from s3db_deployment where deployment_id = '".ereg_replace('^D','',$name)."'";
$db->query($sql);
if($db->next_record()){
return (array(false, "Deployment names cannot be equal to an existing deployment UID."));
}
else {
#Ok, all clear, now let's check the uniqueness of the name
$sql="select * from s3db_statement where rule_id = '".$GLOBALS['deployment_project']['name']['rule_id']."' and value = '".$U['name']."'";
$db->query($sql);
if($db->next_record()){
return (array(false, "Deployment names must be unique. You may leave deployment name empty and a unique name will be generated."));
}
}
return (array(true,"Name successfully validated."));
}
return (array(true));
}
?>