forked from shifuture/rpc_helper
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.php
More file actions
executable file
·1559 lines (1415 loc) · 52.8 KB
/
functions.php
File metadata and controls
executable file
·1559 lines (1415 loc) · 52.8 KB
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Initialiation actions.
*
* @return void
*/
function init()
{
// Load configuration file
loadConfig();
if (!defined('NAME')) {
define('NAME', 'Web Service Tester');
}
if ( !defined('LIB_PATH') ) {
define( 'LIB_PATH', dirname( __FILE__ ) . '/lib/' );
}
if (defined('TIMEZONE')) {
date_default_timezone_set(TIMEZONE);
}
// Setup content type
header('Content-Type: text/html; charset=UTF-8');
// load Text_Highlighter if possible
@include_once('Text/Highlighter.php');
// Session setup
session_name('webservicetesttool');
session_start();
}
/**
* Loads configuration file.
*
* @return void
*/
function loadConfig()
{
global $typesCast, $types;
define('CONFIG_FILE_DIR', dirname(__FILE__));
$defaultConfigFile = CONFIG_FILE_DIR . '/config.php';
// Load configuration file
if (file_exists($defaultConfigFile)) {
require_once $defaultConfigFile;
} else {
die('Config file ' . $defaultConfigFile . ' does not exist!');
}
if (!defined('UPLOAD_DIR')) {
die('UPLOAD_DIR not defined in config file!');
} else {
if (!is_dir(UPLOAD_DIR) || !is_writable(UPLOAD_DIR)) {
die('Upload dir ' . UPLOAD_DIR . ' does not exist or is not writable!');
}
}
}
/**
* Transforms a realative path to an canonicalized absolute path.
* Relative paths are resolved relative to this file directory.
*
* @param string $path the path to be transformed
* @param string $pwd base folder for the relative paths
* @param boolean $create attempt to create folder if it doesn't exist
* @return string the absolute path
*/
function getAbsolutePath($path, $pwd, $create = false)
{
if (DIRECTORY_SEPARATOR !== $path[0]) {
$path = $pwd . DIRECTORY_SEPARATOR . $path;
}
if ($create && !is_dir($path) && !mkdir($path)) {
throw new Exception('Cannot create folder ' . $path);
}
$realpath = realpath($path);
// if realpath does not exist we will return it this way
return $realpath ? $realpath : $path;
}
/**
* Safe html output.
*
* @param string $str string to escape
* @return string escaped string
*/
function esc($str)
{
return htmlentities($str);
}
/**
* Output a selectBox with $params and options from $values.
*
* @param string $params Html parameters for the select (name, id, onChange etc)
* @param array $values An array as $key=>$val
* @param string $selected The key of the selected option
* @return void Outputs directly the list
*/
function showList($params, $values, $selected = null)
{
$arr = [];
$s = '';
foreach ($values as $k => $v) {
$v1 = explode('.', $v);
if ($s != $v1[0]) {
$arr[] = [$v1[0], false, ''];
$s = $v1[0];
}
unset($v1[0]);
$arr[] = ['¦− '.implode('.', $v1), true, $v];
}
$list = '<select '.$params.'>';
foreach ($arr as $v) {
$list .= '<option value="'.esc($v[2]).'" '.($v[2] === $selected ? 'selected' : '').'" '.(! $v[1] ? 'disabled' : '').'>'.esc($v[0]).'</option>';
}
$list .= '</select>';
echo $list;
}
/* Define array_combine for PHP4 */
if (!function_exists('array_combine'))
{
function array_combine($arr1,$arr2)
{
$out = array();
foreach($arr1 as $key1 => $value1)
{
$out[$value1] = $arr2[$key1];
}
return $out;
}
}
/**
* Returns HTML string with Appkey & AppSecret fields according to params $p
*
* @param string $p array of parameters
* @return string HTML string
*/
function displayAppKey(&$p) {
return '<table>'.
'<tr><td><b>X-GSAE-UA</b></td><td><input style="width:400px" name="xGsaeUa" type="text" value="'
.(isset($_SESSION['xGsaeUa']) ? $_SESSION['xGsaeUa'] : '').'"></td></tr>'.
'<tr><td><b>X-GSAE-LF</b></td><td><input style="width:400px" name="xGsaeLf" type="text" value="'
.(isset($_SESSION['xGsaeLf']) ? $_SESSION['xGsaeLf'] : '').'"></td></tr>'.
'<tr><td><b>X-GSAE-AUTH</b></td><td><input style="width:400px" name="customHeader" type="text" value="'
.(isset($_SESSION['customHeader']) ? $_SESSION['customHeader'] : '').'"></td></tr>'.
'<tr><td><b>X-GSAE-ROLE-INDEX-ID</b></td><td><input style="width:400px" name="xGsaeRoleIndexId" type="text" value="'
.(isset($_SESSION['xGsaeRoleIndexId']) ? $_SESSION['xGsaeRoleIndexId'] : '').'"></td></tr>'.
'<tr><td><b>REQ-SN</b></td><td><input style="width:400px" name="reqSn" type="text" value="'.session_id().'-rpcHelper"></td></tr>'.
'</table>';
}
/**
* Returns a HTML string with the input fields accoding to array of params $p.
* This function is called recursively.
*
* @param string $p array of parameters
* @param string $n children name for substructures
* @param boolean $multiply show multiplier for current parameter (used for array members)
* @return string HTML string
*/
function displayParams($p, $n = 'params', $multiply = false, $depth = 0) {
global $types;
$str = "";
$str .= '<table id="mainTable">';
$paramNr = count($p);
$str .= '<tr><td>Name</td><td>Value</td><td>Type</td><td>Set</td><td>Null</td></tr>';
for($i = 0 ; $i < $paramNr; $i++) {
$val = $p[$i];
$str .= '<tr valign="top"><td class="label">'.$val['name'];
// Identifiers
$toChildren = $n.'['.$i.']';
$toChildrenValue = $toChildren . "[value]";
$toChildrenNull = $toChildren . "[null]";
$toChildrenEnabled = $toChildren . "[enabled]";
// error messages
$toChildrenBlank = $toChildren . "[blank]";
$toChildrenInt = $toChildren . "[int]";
// special parameter for files
$toChildrenFile = $toChildren . "[file]";
// parameter value
//
$isDisabled = (boolean)(!$val['enabled']);
$disabledOptions = ($isDisabled) ? ' class="disabled"' : '';
// show multiply link
if ($multiply) {
$str .= '<br /><a href="index.php?multiply=' . $toChildren . '" onclick="multiplyParameter(\'' . $toChildren .'\', false);return false;">增加</a>';
}
// show remove link
if ($multiply && $i > 0) {
$str .= '<br /><a href="index.php?remove=' . $toChildren . '" onclick="multiplyParameter(\'' . $toChildren .'\', true);return false;">去除</a>';
}
$str .= '</td>'."\n";
// call recursive for complex types
if ($val['type'] == 'array' || $val['type'] == 'struct') {
$str .= '<td><span id="'. $toChildrenValue . '"' . $disabledOptions . '>' . displayParams($val['members'], $toChildren . "[members]", $val['type'] == 'array', 1) . '</span></td>';
} else {
$str .= '<td>';
if ($val['type'] == 'file') {
//$str .= '<input type="file" name="' . $toChildrenValue . '" id="' . $toChildrenValue . '" value=""' . $disabledOptions . '/><input type="text" name="' . $toChildrenFile . '" style="display: none;"/>';
$str .= '<div id="'. $toChildrenValue . '" name="' . $toChildrenValue . '" ' . $disabledOptions . '><input type="text" id="' . $toChildrenFile . '" name="' . $toChildrenFile . '" value="' . $val['value']. '"/><input type="button" class="button" value="Upload"/></div>';
}
elseif ($val['type'] == 'boolean') {
$str .= '<select name="' . $toChildrenValue . '" id="' . $toChildrenValue . '"' . $disabledOptions . '">';
$str .= '<option value=""></option>';
$str .= '<option value="0"' . ((isset($val['value']) && '0' == $val['value']) ? 'selected="selected"' : '') . '>false</option>';
$str .= '<option value="1"' . ((isset($val['value']) && '1' == $val['value']) ? 'selected="selected"' : '') . '>true</option>';
$str .= '</select>';
} else {
if (0 == $i && 0 == $depth && count($_SESSION['storedSessions']) && FILL_FIRST_METHOD_PARAMETER_WITH_SESSION) {
$paramValue = $_SESSION['session'];
} else {
$paramValue = isset($val['value']) ? htmlentities($val['value']) : "";
}
$str .= '<input type="text" id="' . $toChildrenValue . '" name="' . $toChildrenValue . '" value="' . $paramValue . '" ' . $disabledOptions .'/>';
if ( $val['type'] == 'datetime' ) {
$str .= "<script>$('#".str_replace(array('[', ']'), array('\\\\[', '\\\\]'), $toChildrenValue)."').datetimepicker({lang:'zh', format:'Y-m-d H:i:s'});</script>";
}
}
// add error messages labels for integer blank fields
if($val['type'] == 'int') {
$str .= '<div class="error" id="' . $toChildrenBlank . '" style="display: none;">Field cannot be left blank.</div>';
$str .= '<div class="error" id="' . $toChildrenInt . '" style="display: none;">Field should be integer.</div>';
}
$str .= '</td>'."\n";
}
// parameter type
//
$str .= '<td>' . (isset($types[trim($val['type'])]) ? $types[trim($val['type'])] : $val['type']) . ', ' . ($val['optional'] == true ? (empty($val['comment']) ? "<span style=\"color: #008B00\">选填</span>" : "<span style=\"color: #8B0000\">选填</span>") : "<span style=\"color: red\">必填</span>") . '</td>' . "\n";
// enable/disable checkbox
//
$isEnabled = true;
$isChecked = (boolean)($val['enabled']);
$isHidden = false;
$enabledOptions = ($isEnabled) ? ' onclick="enableField(\'' . $toChildren . '\')"' : ' disabled="disabled"';
$checkedOptions = ($isChecked) ? ' checked="checked"' : '';
$hiddenOptions = ($isHidden) ? ' style="visibility: hidden;"' : '';
$str .= '<td><input name = "' . $toChildrenEnabled . '" type="checkbox"' . $enabledOptions . $checkedOptions . $hiddenOptions . '/></td>';
// null checkbox
//
$isDisabled = (boolean)($val['optional'] && $val['enabled'] == false);
$isChecked = (boolean)(is_null($val['value']) && $val['enabled']);
$isHidden = false;
$disabledOptions = ($isDisabled) ? ' disabled="disabled"' : '';
$checkedOptions = ($isChecked) ? ' checked="checked"' : '';
$hiddenOptions = ($isHidden) ? ' style="visibility: hidden;"' : '';
$str .= '<td><input name = "' . $toChildrenNull . '" id = "' . $toChildrenNull . '" type="checkbox" onclick="nullField(\'' . $toChildren . '\')"' . $disabledOptions . $checkedOptions . $hiddenOptions . '">';
// null the field if nullbox is checked
if ($isChecked) {
$str .= '<script type="text/javascript">nullField(\'' . $toChildren . '\');</script>';
}
$str .= '</td>'."\n";
$str .= '<td style="vertical-align: middle">';
$comment = isset($val['comment']) ? $val['comment'] : '';
$str .= "<span style=\"color: #8B0000\">$comment</span>";
$str .= '</td>'."\n";
// parameter description if any
$str .= '<td class="description">' . $val['description'] . '</td>';
$str .= '</tr>';
}
$str .= '</table>';
return $str;
}
/**
* Makes the request and outputs the HTML response.
* Uses $_SESSION['functionParams'] to get the function parameters.
*
* @return string outputs directly the HTML response
*/
function showResult()
{
$params = makeMessageParams($_SESSION['functionParams'], $_POST['protocol']);
if (!empty($_POST['customPacket'])) {
$response = sendRequest($_SESSION['selectedFunction'], $params, $_POST['protocol'], $_SESSION['URL'], $_POST['customPacket']);
} else {
$response = sendRequest($_SESSION['selectedFunction'], $params, $_POST['protocol'], $_SESSION['URL']);
}
// save the attachments
foreach ($response['attachments'] as $filename => $content) {
file_put_contents(dirname(__FILE__) . '/upload/' . $filename, $content);
}
$serverURL = $_SESSION['URL'];
displayResponse($serverURL, $response);
echo $response['log'];
}
/**
* Check if a request is AjaxRequest
*
* @return boolean
*/
function isAjax()
{
return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER ['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest');
}
/**
* Return the result from xmlRpc server.
*
* @param string $functionName The name of the function to call
* @param array $params Array of parameters to send
* @param string $protocol 'xmlrpc', 'jsonrpc' or 'soap 1.1'
* @param string $serverURL url of the RPC server
* @param string $payload Used when we want to send a custom packet
* @param string $encoding encoding of the request
* @return array('response', 'attachments') Response from server
*/
function sendRequest($functionName, $params, $protocol, $serverURL, $payload = '', $encoding = 'utf-8')
{
$html = '';
// correspondence rpc protocol - language (used for highlighter)
$language = array(
'xmlrpc' => 'xml',
'jsonrpc' => 'javascript'
);
// correspondence rpc protocol - Content-Type (used for HTTP request)
$contentType = array(
'xmlrpc' => 'text/xml',
'jsonrpc' => 'application/json'
);
$options = array('version' => $protocol,
'encoding' => $encoding
);
$message = ($payload !== '') ? $payload : rpc_encode_request($functionName, $params, $options);
if ($_SESSION['DEBUG']) {
$html .= '<div class="t2">请求内容</div>';
$html .= '<pre id="request" class="t1">'.htmlspecialchars($message).'</pre>';
}
// Prepare to send the request using cURL (Client URL Library)
// will inject the message through a file
$tmpfile = UPLOAD_DIR . '/' . uniqid('message_');
// write the message to temp file
$execTime1 = microtime(true);
if ($_SESSION['RSA']) {
$message = rsaEncode($message);
}
$execTime2 = microtime(true);
file_put_contents($tmpfile, $message);
$fh = fopen($tmpfile, 'r');
// set options
$header = array(
'X-Client: ' . CLIENT_TYPE,
'Content-Type: ' . $contentType[$protocol],
'Content-Length: ' . strlen($message),
'Expect:'
);
// set customHeader
if (isset($_REQUEST['customHeader'])) {
$_SESSION['customHeader'] = $_REQUEST['customHeader'];
$customHeader = $_REQUEST['customHeader'];
if ($customHeader != '') {
$header[] = 'X-GSAE-AUTH: '.$customHeader;
}
}
if (isset($_REQUEST['reqSn'])) {
$reqSn = $_REQUEST['reqSn'];
if ($reqSn != '') {
$header[] = 'REQ-SN: '.$reqSn;
}
}
$_SESSION['xGsaeUa'] = '';
if (isset($_REQUEST['xGsaeUa'])) {
$_SESSION['xGsaeUa'] = $_REQUEST['xGsaeUa'];
$xGsaeUa = $_REQUEST['xGsaeUa'];
if ($xGsaeUa != '') {
$header[] = 'X-GSAE-UA: '.$xGsaeUa;
}
}
$_SESSION['xGsaeLf'] = '';
if (isset($_REQUEST['xGsaeLf'])) {
$_SESSION['xGsaeLf'] = $_REQUEST['xGsaeLf'];
$xGsaeLf = $_REQUEST['xGsaeLf'];
if ($xGsaeLf != '') {
$header[] = 'X-GSAE-LF: '.$xGsaeLf;
}
}
$_SESSION['xGsaeRoleIndexId'] = '';
if (isset($_REQUEST['xGsaeRoleIndexId'])) {
$_SESSION['xGsaeRoleIndexId'] = $_REQUEST['xGsaeRoleIndexId'];
$xGsaeRoleIndexId = $_REQUEST['xGsaeRoleIndexId'];
if ($xGsaeRoleIndexId != '') {
$header[] = 'X-GSAE-ROLE-INDEX-ID: '.$xGsaeRoleIndexId;
}
}
$options = array(
CURLOPT_HTTPHEADER => $header, // set custom headers
CURLOPT_POST => true, // do a POST request
CURLOPT_INFILE => $fh, // read the message from file handler
CURLOPT_INFILESIZE => strlen($message), // lenght of the message
CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'], // set User-Agent to the server user agent
CURLOPT_HEADER => true, // get the headers also in the response
CURLOPT_RETURNTRANSFER => true // return the response
);
if ($_SESSION['DEBUG']) {
$html .= '<div class="t2">请求头</div>';
$html .= '<pre class="t1">' . implode(PHP_EOL, $header) . '</pre>';
}
// set session cookie
if (isset($_SESSION['session']) && $functionName !== LOGIN_METHOD) {
$options[CURLOPT_COOKIE] = sprintf('%s=%s', $_SESSION['storedSessions'][$_SESSION['session']]['sessionName'], $_SESSION['session']);
}
// set http basic auth
if (defined("HTTP_BASIC_AUTH_USER") && defined("HTTP_BASIC_AUTH_PASS")
&& HTTP_BASIC_AUTH_USER != "" && HTTP_BASIC_AUTH_PASS != "") {
$userpwd = HTTP_BASIC_AUTH_USER . ':' . HTTP_BASIC_AUTH_PASS;
$options[CURLOPT_USERPWD] = $userpwd;
}
// initialize the curl session
$execTime3 = microtime(true);
$ch = curl_init($serverURL);
curl_setopt_array($ch, $options);
// get the response
$response = curl_exec($ch);
// close curl session
curl_close($ch);
$execTime4 = microtime(true);
// close the file handler and remove the file
fclose($fh);
unlink($tmpfile);
$data = $response;
if (!$data || is_null($data)) {
$exception = new Exception('There is no response from server ' . $serverURL, 1);
throw $exception;
}
// separate the headers and the data from the response
$headers = null;
if ($n = strpos($response, "\r\n\r\n")) { // CRLF CRLF
$headers = substr($response, 0, $n);
$data = substr($response, $n + 4);
}
$execTime5 = microtime(true);
if ( $_SESSION['RSA']) {
$data = rsaDecode($data);
}
$execTime6 = microtime(true);
// get content type
preg_match('/Content-Type:.*/', $headers, $matches);
$contentType = isset($matches[0])?$matches[0]:"";
if ($_SESSION['DEBUG']) {
$html .= '<div class="t2">响应内容 <b>'.round((mb_strlen($data, '8bit'))/1024, 3).'KB</b></div>';
$html .= '<pre id="response" class="t1">' . htmlspecialchars($data). '</pre>';
$html .= '<div class="t2">响应头</div>';
$html .= '<pre id="headers" class="t1">' . $headers . '</pre>';
$html .= '<div class="t2">耗时分析</div>';
$execArr = [
'请求内容加密:'.((intval($execTime2*10000) - intval($execTime1*10000))/10).'ms',
'接口响应耗时:'.((intval($execTime4*10000) - intval($execTime3*10000))/10).'ms',
'响应内容解密:'.((intval($execTime6*10000) - intval($execTime5*10000))/10).'ms',
'开始请求:'.date('Y-m-d H:i:s', $execTime3).' '.$execTime3,
'开始响应:'.date('Y-m-d H:i:s', $execTime4).' '.$execTime4,
];
$html .= '<pre id="headers" class="t1">'.implode(PHP_EOL, $execArr).'</pre>';
}
//forward X HTTP headers
$headersArray = explode("\n", $headers);
foreach ($headersArray as $header) {
if(substr($header, 0, 2) === 'X-') {
// header($header);
}
}
// Session handling
// if it was a login action store the new session
if (defined('LOGIN_METHOD') && $functionName === LOGIN_METHOD) {
if (preg_match('/Set-Cookie: (\w*)=(.*?);/m', $headers, $matches)) {
$sessionId = $matches[2];
$sessionData = array(
'sessionName' => $matches[1],
'server' => $_SESSION['server'],
'params' => rpc_encode($params[0], 'jsonrpc')
);
$_SESSION['storedSessions'][$sessionId] = $sessionData;
$_SESSION['session'] = $sessionId;
}
}
// if it was a logout action destroy the session
if (defined('LOGOUT_METHOD') && $functionName === LOGOUT_METHOD) {
$sessionId = $_SESSION['session'];
unset($_SESSION['storedSessions'][$sessionId]);
if (count($_SESSION['storedSessions'])) {
$_SESSION['session'] = key($_SESSION['storedSessions']);
} else {
unset($_SESSION['session']);
}
}
$attachments = array();
// if content type is multipart/mixed
if (0 === strpos($contentType, 'Content-Type: multipart/mixed')) {
// get the boundary - try with and without quoted value
if (!preg_match('/boundary="(.*)"/', $contentType, $matches)) {
preg_match('/boundary=(.*)$/', $contentType, $matches);
}
$boundary = $matches[1];
// split message body into parts
$message = Zend_Mime_Message::createFromMessage($data, $boundary);
// iterate over message parts, and map name to content
foreach($message->getParts() as $part) {
if (!isset($methodResponse)) {
// the first one is the method response
$methodResponse = $part->getContent();
} else {
// get the name
$headers = $part->getHeaders();
if (0 !== preg_match('/name="(.*)"/', $headers, $matches) || 0 !== preg_match('/name=(.*)$/', $headers, $matches)) {
$name = $matches[1];
}
$attachments[$name] = $part->getContent();
}
}
} else {
$methodResponse = $data;
}
// decode response
$decodedResponse = rpc_decode(trim($methodResponse), $protocol);
if ($protocol == 'jsonrpc' && is_array($decodedResponse) && isset($decodedResponse['result'])) {
$decodedResponse = $decodedResponse['result'];
}
return array('response' => $decodedResponse, 'attachments' => $attachments, 'log' => $html);
/*
// SSL REQUESTS
if (strtolower($url['scheme']) == "https" || strtolower($url['scheme']) == "ssl")
{
if (defined("SSL_CERTIFICATE") && SSL_CERTIFICATE != "") {
$client->setCertificate(SSL_CERTIFICATE, SSL_PASSPHRASE);
} else {
$client->setSSLVerifyPeer(false);
$client->setSSLVerifyHost(false);
}
}
*/
}
/**
* Create the formated params for the rpc message.
*
* @param string $p Array of parameters to send
* @param string $protocol rpc protocol
* @return array the final array of formatted parameters ready to be encoded into rpc
*/
function makeMessageParams($p, $protocol)
{
// creates the processed array of params
$parsedParams = formatArray($p);
// create final function parameters
$params = array();
foreach($parsedParams as $paramProperties) {
if ($protocol == 'soap 1.1') {
// for SOAP we have named parameters
$params[$paramProperties['name']] = parseInternalParams($paramProperties['value'], $paramProperties['type']);
} else {
// for XML-RPC and JSON-RPC we have positional params
$params[] = parseInternalParams($paramProperties['value'], $paramProperties['type'], $protocol);
}
}
return $params;
}
/**
* Create the final php value for parameter.
* Parameter values are casted to the associated data type.
*
* @param mixed $p parameter
* @param string $type rpc type
* @return mixed a final php variable representating the parameters ready to be encoded into rpc
*/
function parseInternalParams($p, $type)
{
$return = null;
// if value is null return
if (is_null($p)) {
return $return;
}
switch ($type) {
case 'array':
$params = array();
foreach($p as $paramProperties) {
$params[] = parseInternalParams($paramProperties['value'], $paramProperties['type']);
}
$return = $params;
break;
case 'struct':
$params = array();
foreach($p as $paramProperties) {
$params[$paramProperties['name']] = parseInternalParams($paramProperties['value'], $paramProperties['type']);
}
if(empty($params)) {
$params = new stdClass();
}
$return = $params;
break;
case 'int':
$return = (int)$p;
break;
case 'string':
$return = (string)$p;
break;
case 'boolean':
$return = (boolean)$p;
break;
case 'base64':
rpc_set_type($p, 'base64');
$return = $p;
break;
case 'dateTime':
rpc_set_type($p, 'datetime');
$return = $p;
break;
case 'long':
rpc_set_type($p, 'long');
$return = $p;
break;
default:
$return = $p;
break;
}
return $return;
}
/**
* Create a processed array of params
*
* @param array $arr Array of parameters
* @return array processed array of params
*/
function formatArray($arr)
{
global $typesCast;
$newArray = array();
foreach ($arr as $key => $element) {
// element type is a complex type (struct or array)
if (($element['type'] == 'array' || $element['type'] == 'struct')) {
if ($element['enabled']) {
$newArray[$key] = array(
'name' => $element['name'],
'type' => $element['type'],
'value' => is_null($element['value']) ? null : formatArray($element['members']),
);
} elseif (SEND_DISABLED_FIELDS_AS_NULL) {
$newArray[$key] = array(
'name' => $element['name'],
'type' => $typesCast[$element['type']],
'value' => null,
);
}
// element type is a simple type
} else {
if($element['enabled']) {
// for file parameters put file contents into element's value
if($element['type'] == 'file') {
$element['value'] = file_get_contents(UPLOAD_DIR . '/' . $element['value']);
}
$newArray[$key] = array(
'name' => $element['name'],
'type' => $typesCast[$element['type']],
'value' => $element['value'],
);
} elseif (SEND_DISABLED_FIELDS_AS_NULL) {
$newArray[$key] = array(
'name' => $element['name'],
'type' => $typesCast[$element['type']],
'value' => null,
);
}
}
}
return $newArray;
}
/**
* Multiply or remove a member of an array in params array.
*
* @param string $member member to multiply (ex: params[1][members][0])
* @param array $params
* @param boolean $remove if set to true it will remove the parameter from array members
* @return array|boolean updated params array or false if there was an error
*/
function multiplyParameter($member, $params, $remove = false)
{
if (preg_match('/(.*)\[(\d*)\]$/', $member, $matches)) {
$members = str_replace('members', '"members"', $matches[1]);
$key = $matches[2];
$code = '$membersArray = $' . $members .';';
eval($code);
if (!$remove) {
// replace $membersArray[$key] with $membersArray[$key] x 2
array_splice($membersArray, $key, 1, array($membersArray[$key], $membersArray[$key]));
} else {
// remove $membersArray[$key]
array_splice($membersArray, $key, 1);
}
// replace the members with the new membersArray
$code = '$' . $members . ' = $membersArray;';
eval($code);
return $params;
} else {
return false;
}
}
/**
* Updates a file parameter.
*
* @param array $p parameters array
* @param array $name array with filename ($_FILES['file']['name'])
* @param array $tmp_name array with temporary filename ($_FILES['file']['tmp_name'])
* @return array (string filename, string tmpfilename)
*/
function updateFile(&$p, $name, $tmp_name)
{
$fileValue = &$p;
while(is_array($name)) {
$key = key($name);
$name = $name[$key];
$tmp_name = $tmp_name[$key];
$fileValue = &$fileValue[$key];
}
$fileValue = $name;
return array($name, $tmp_name);
}
/**
* Update array of params with $vals.
*
* @param array $p parameters array
* @param array $vals new values
* @return array new array of params
*/
function updateVals($p, $vals)
{
foreach($vals as $key => $val)
{
// to skip 'enabled' and 'null' fields recursive structured type
if (is_array($val)) {
// set enabled field
// is always enabled for non-optional values
$p[$key]['enabled'] = isset($val['enabled']) ? true : false;
// structured type - call update recursively for members
if (isset($val['members']))
{
$p[$key]['value'] = isset($val['null']) ? null : '';
$p[$key]['members'] = updateVals($p[$key]['members'], $val['members']);
}
else
{
if (isset($val['null'])) {
$p[$key]['value'] = null;
} elseif (isset($val['value']) && $p[$key]['type'] != 'file') {
// Exception: values for 'file' parameters are set on file upload
$p[$key]['value'] = $val['value'];
}
}
}
}
return $p;
}
/**
* Pad a string on the left to certain lenght with spaces.
*
* @param string $input input string
* @param integer $lenght the padding length
* @return string padded string
*/
function pad($input, $lenght)
{
return str_pad($input, $lenght + strlen($input), ' ', STR_PAD_LEFT);
}
/**
* Returns a parsable string representation of an introspection array
*
* @param mixed $var variable
* @param integer $pad the number of spaces to pad the result
* @param integer $highlight return a highlighted result
* @return string the string represention of the introspection array
*/
function decorator($var, $pad = 0)
{
switch(true) {
case is_array($var):
$return = "array(\n";
$end = count($var);
$count = 0;
// if it's a numeric indexed array
if (isset($var[0])) {
foreach($var as $value) {
$suffix = (++$count == $end) ? "" : ","; // the last comma
$return .= pad(decorator($value, $pad + TAB_WIDTH) . "$suffix\n", $pad + TAB_WIDTH);
}
$return .= pad(")", $pad);
// if it's a hash
} else {
foreach($var as $key => $value) {
// transform $value to a decorated string:
switch(true)
{
// null
case is_null($value):
$processedValue = 'null';
break;
// array
case is_array($value):
$processedValue = decorator($value, $pad + TAB_WIDTH);
break;
// numeric
case (is_bool($value) || is_int($value) || is_double($value)):
$processedValue = $value;
break;
// string
case is_string($value):
$processedValue = "'" . $value . "'";
break;
}
$suffix = (++$count == $end) ? "" : ","; // the last comma
$return .= pad(sprintf("'%s' => %s\n", $key, $processedValue . $suffix), $pad + TAB_WIDTH);
}
$return .= pad(")", $pad);
}
break;
// null
case is_null($var):
$return = 'null';
break;
// array
case is_array($var):
$return = decorator($var, $pad + TAB_WIDTH);
break;
// numeric
case (is_bool($var) || is_int($var) || is_double($var)):
$return = $var;
break;
// string
case is_string($var):
$return = "'$var'";
break;
}
return $return;
}
/**
* Highlights php code and strips the begin and closing tags
*
* @param string $code code to highlight
* @return string the highlighted code
*/
function highlight($code)
{
// prepare data for highlight
$data = "<?php " . $code . " ?>";
$data = highlight_string($data, true);
// eliminate php begin and closing tags
$data = str_replace('<?php ', '', $data);
$data = str_replace('?>', '', $data);
$data = str_replace("\n", '', $data);
return $data;
}
/**
* Outputs or returns decorated html of a parsable string representation of a variable
*
* @param mixed $var variable
* @param boolean $return if true will return the variable representation instead of outputing it
* @return string highlighted html code
*/
function var_decorate($var, $return = false)
{
$decorated = highlight(decorator($var));
if (!$return) {
echo $decorated;
}
return $return ? $decorated : null;
}
/**
* Outputs the response
*
* @param string $url RPC server url
* @param string $response Response from server
* @return void Outputs directly
*/
function displayResponse($url, $response)
{
?>
<br/><label style="color:blue;">Response from server ("<?php print $url ?>"):</label><br/>
<div id="parsedResponse" style="margin-bottom: 10px;"><pre><?php if(is_null($response['response'])) { echo '<label style="color: red;">There is a problem with the response: enable debugging to examine incoming payload.</label>'; } else {
if ($fault = getFault($response['response'])) {
echo '<label><span style="color: blue;">' . $fault['faultCode'] . '</span> <span style="color: red;">' . $fault['faultString'] . '</span></label>';
} else {
// decorate and highlight the response
var_decorate($response['response']);
}
} ?></pre></div>
<?php
if (!empty($response['attachments'])) {
echo '<span id="attachments">Attachments:</span> ';
$attachmentBaseUrl = 'upload/';
foreach (array_keys($response['attachments']) as $filename) {
echo '<a href="'. $attachmentBaseUrl . $filename . '">' . $filename . '</a> ';
}
}
}
/**
* Tests whether a variable is a RPC fault structure
*
* @param mixed $var a variable
* @return mixed array with 'faultCode' and 'faultString' set if the variable is a fault structure, false otherwise
*/
function getFault($var)
{
if (isXmlRpcFault($var) || isJsonRpcError($var) || isSoapFault($var)) {
$fault = array();
if (isXmlRpcFault($var)) {
$fault['faultCode'] = $var['faultCode'];
$fault['faultString'] = $var['faultString'];
}
else if (isJsonRpcError($var)) {
$fault['faultCode'] = $var['code'];
$fault['faultString'] = $var['message'];
}
else if (isSoapFault($var)) {
$fault['faultCode'] = $var['faultcode'];
$fault['faultString'] = $var['faultstring'];
}
return $fault;
}
return false;