-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmdbpxy.php
1417 lines (1158 loc) · 36.4 KB
/
mdbpxy.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
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
// create user "phproxy" with password 'phproxy' name 'phproxy' schema "sys";
// grant select on voyages to phproxy;
define("monetdb_host","localhost");
define("monetdb_port","50001");
define("monetdb_user","phproxy");
define("monetdb_pass","phproxy");
define("monetdb_dbnm","clueweb-segment0");
// inlining php_mapi.inc
/**
* Implementation of the MAPI protocol (v9).
*
*
* Provides:
* - mapi_query($data) {
* - mapi_store($data) {
* - php_parse_tuples($rows) {
* - mapi_connect() {
* - mapi_authenticate($user, $passwd, $hash, $salt, $dbname) {
* - mapi_read() {
* - mapi_write($msg) {
* - set_timezone() {
* - format_command($cmd) {
* - mapi_connect_proxy() {
* - mapi_open() {
* - mapi_close() {
*
**/
define("MAX_PACKET_SIZE", 8190); // Maximum packet size
define("REPLY_SIZE", "250"); // Set the initial reply size
define("Q_TABLE", "1"); // SELECT operation
define("Q_UPDATE", "2"); // INSERT/UPDATE operations
define("Q_CREATE", "3"); // CREATE/DROP TABLE operations
define("Q_TRANSACTION", "4"); // TRANSACTION
define("Q_PREPARE", "5");
define("Q_BLOCK", "6"); // QBLOCK message
define("MSG_REDIRECT", "^"); // auth redirection through merovingian
define("MSG_QUERY", "&");
define("MSG_SCHEMA_HEADER", "%");
define("MSG_INFO", "!"); // info response from mserver
define("MSG_TUPLE", "[");
define("MSG_PROMPT", "");
define("PROTOCOL_v9", 9); // supported protocol(s)
define("LANG_SQL", "sql");
define("MEROVINGIAN", "merovingian");
define("MSERVER", "mserver");
define("MONETDB", "monetdb");
define('MAX_MEROVINGIAN_ITER', 10); // Maximum number of iterations during proxied auth through merovingian
define('PLACEHOLDER', '?'); // Used for string escaping.
/**
* $connection_pool contains a list of the active database connections
*/
$connection_pool = array();
/**
* Stores the last error reported by the server
*/
$last_error = "";
/**
* Execute an SQL query and return the resulting handle by reference.
*/
function mapi_execute($conn=NULL, $query) {
global $connection_pool;
global $rows;
/**
* Query handle
*
* "conn" - id of the connection that fired the query
* "header" - table header
* "record_set" - retrieved record set (if present)
* "operation" - query type
*
*/
// if multiple connections are present, require the user to specify which one to use.
if ($conn == NULL) {
return FALSE;
} else if (($socket = $conn["socket"]) == NULL) {
return FALSE;
}
/* Fire the query and read back the response */
$buf = mapi_write($socket, format_query($query, $conn["lang"]));
$data = mapi_read($socket);
if ($conn['lang'] == LANG_SQL) {
$handle = array("conn" => "", "header" => array(), "query" => "", "record_set" => array(), "operation" => -1, "last_row" => 0);
$handle["conn"] = $conn["id"];
if ( ($operation = mapi_store($data, $handle)) == FALSE) {
return FALSE;
}
/* The query produced a record set */
if ($operation == Q_TABLE || $operation == Q_BLOCK) {
// fetch the whole result set
if ($handle["query"]["index"] < $handle["query"]["rows"]) {
mapi_fetch_next($conn, $handle);
}
}
if ($handle == NULL) {
return FALSE;
}
return $handle;
}
}
function mapi_fetch_next($conn, &$handle){
if ($conn['socket'] == NULL){
return FALSE;
}
$socket = $conn['socket'];
$offset = 10;
while ($handle["query"]["index"] < $handle["query"]["rows"]) {
// export a new window
$left_rows = $handle["query"]["rows"] - $handle["query"]["index"];
$exp_size = min($offset, $left_rows);
$offset += 100;
mapi_write($socket, format_command("export " . $handle["query"]["id"] . " " . $handle["query"]["index"] . " " . $exp_size));
$data = mapi_read($socket);
if ( ($operation = mapi_store($data, $handle)) == FALSE ) {
return FALSE;
}
$handle["query"]["index"] += $exp_size;
$handle["operation"] = $operation;
}
return $handle;
}
function mapi_store($data, &$handle) {
global $last_error;
// global $rows;
$data = explode("\n", $data);
$operation = "";
$header = ""; // store temporary header informations;
$rows = ""; // stores (partially) retrieved rows
foreach ($data as $row) {
/*
PHP5.2 complains when $row[0] is accessed with:
Notice: Uninitialized string offset: 0
In order to avoid the E_NOTICE error substr($row, 0, 1) is used
to access the first character of a string
*/
if (substr($row, 0, 1) == MSG_QUERY) {
if ($row[1] == Q_TABLE) {
$operation = Q_TABLE;
// save info about the query
$fields = explode(" ", $row);
$handle["query"] = array("id" => $fields[1], "rows" => $fields[2], "cols" => $fields[3], "index" => $fields[4]);
} else if ($row[1] == Q_UPDATE) {
$operation = Q_UPDATE;
$fields = explode(" ", $row);
$handle["query"] = array("affected" => $fields[1]);
} else if ($row[1] == Q_CREATE) {
$operation = Q_CREATE;
} else if ($row[1] == Q_TRANSACTION) {
$operation = Q_TRANSACTION;
} else if ($row[1] == Q_BLOCK) {
// add Q_BLOCK to the record set
$operation = Q_BLOCK;
}
} else if (substr($row, 0, 1) == MSG_SCHEMA_HEADER){
// process the table header
$header = $header . $row . "\n";
} else if (substr($row, 0, 1) == MSG_TUPLE) {
// process tuples
$rows .= $row;
} else if (substr($row, 0, 1) == MSG_PROMPT) {
fast_array_merge($handle["record_set"], php_parse_tuples($rows));
} else if (substr($row, 0, 1) == MSG_INFO) {
$last_error = $row;
return FALSE;
}
}
/*
if ($record_set != "") {
//$handle["record_set"] = array_merge($handle["record_set"], $record_set);
$handle["record_set"] = $handle["record_set"] . $record_set;
}*/
if ($header != "") {
$handle["header"] = php_parse_header($header);
/* Store the number of fields returned by the dataset */
if ($operation == Q_TABLE || $operation == Q_BLOCK ) {
$handle["query"]["fields"] = count($handle["header"]["fields"]);
}
}
$handle["operation"] = $operation;
return $operation;
}
/* Concatenates two arrays in place */
function fast_array_merge(&$a1, $a2) {
foreach ($a2 as $row) {
$a1[] = $row;
}
}
function php_parse_tuples($rows) {
//$parsed_rows = "";
$rows = rtrim($rows, "\t]");
return explode("\t]", $rows);
// print_r($parsed_rows);
/*
foreach ($rows as &$row) {
$row = ltrim($row, "[ ");
$row = explode(",\t", $row);
foreach ($row as &$field) {
$field = stripslashes($field);
// strip left/right \" chars and right ','
$field = rtrim($field, '"');
$field = ltrim($field, '"');
}
$parsed_rows[] = $row;
}
*/
// return $parsed_rows;
}
function php_parse_row($row) {
$row = ltrim($row, "[ ");
$row = explode(",\t", $row);
foreach ($row as &$field) {
if ($field == "NULL") {
$field = NULL;
}
else {
$field = stripslashes($field);
// strip left/right \" chars and right ','
$field = rtrim($field, '"');
$field = ltrim($field, '"');
}
}
return $row;
}
function php_parse_header($header) {
$header = explode("\n", $header);
$name = $header[0];
$header_array = array();
/* Field names */
$header[1] = ltrim($header[1], "% ");
$header[1] = explode("#", $header[1]);
$header_array["fields"] = explode(",\t", $header[1][0]);
/* Field types */
$header[2] = ltrim($header[2], "% ");
$header[2] = explode("#", $header[2]);
$header_array["types"] = explode(",\t", $header[2][0]);
return $header_array;
}
/*
$conn_opts is an array containing:
username =>
password =>
host =>
port =>
database =>
hash =>
*/
function mapi_connect(&$socket, &$options, $merovingian_iter=NULL) {
global $last_error;
global $connection_pool;
$host = $options["host"];
$port = $options["port"];
$user = $options["username"];
$passwd = $options["password"];
$hash = $options["hashfunc"];
$dbname = $options["database"];
$lang = $options["lang"];
/* No merovingian redirect. Perform an actual connection. */
if ($merovingian_iter == NULL) {
if (socket_connect($socket, $host, $port) == FALSE) {
$last_error = socket_strerror(socket_last_error());
exit();
}
}
// get server challenge
$challenge = mapi_read($socket);
/*
Array
(
[0] => void
[1] => merovingian
[2] => 8
[3] => plain
[4] => LIT
)
*/
$credentials = explode(":", $challenge);
$algos = explode(',', $credentials[3]);
// $challenge[0] contains the salt
if ($credentials[2] == PROTOCOL_v9) {
// $credentials[5] contains pwhash
// $credentials[0] contains the hash
mapi_authenticate_v9($socket, $user, $passwd, $hash, $algos, $credentials[0], $dbname, $credentials[5]);
} else {
$last_error = "Protocol " . $credentials[2] . " not supported. Aborting.";
return FALSE;
}
$response = mapi_read($socket);
/* Follow the first redirect */
if ($response != MSG_PROMPT) {
// not ready to authenticate yet
if ($response[0] == MSG_REDIRECT) {
$redirects = explode("\n", $response);
/* Follow the first redirect */
if ( ($redirects[0] == "") || (substr($redirects[0], 0, 6) != "^mapi:") ) {
print "Invalid redirect " . $redirects[0] . "\n";
return FALSE;
}
$link = substr($redirects[0], 6, strlen($redirects[0]));
$redirect_to = parse_url($link);
//print_r($redirect_to);
if ($redirect_to['scheme'] == MEROVINGIAN) {
if ($merovingian_iter < MAX_MEROVINGIAN_ITER) {
$merovingian_iter++;
if (mapi_connect($socket, $options, $merovingian_iter) == FALSE) {
return FALSE;
}
} else {
$last_error = "Maximum number of merovingian iterations exceeded during authentication\n";
return FALSE;
}
}
else if($redirect_to['scheme'] == MONETDB ) {
$options['host'] = $redirect_to['host'];
$options['port'] = $redirect_to['port'];
$options['database'] = ltrim($redirect_to['path'], '/');
socket_close($socket);
$socket = mapi_open();
if (mapi_connect($socket, $options) == FALSE) {
return FALSE;
}
} else {
print $response;
return FALSE;
}
} else if ($response[0] == MSG_INFO) {
$last_error = $response;
return FALSE;
}
}
return TRUE;
}
/* Hash function names have to be uppercase */
function mapi_authenticate_v9($socket, $user, $passwd, $hash, $algos, $salt, $dbname, $pwhash) {
$auth_string = "";
if ( (is_array($algos) && (! in_array(strtoupper($hash), $algos)) ) ) {
$last_error = "Hash function " . $hash . " not supported";
return FALSE;
}
$pwhashsum = hash(strtolower($pwhash), $passwd);
$hashsum = hash(strtolower($hash), $pwhashsum . $salt);
$auth_string = "BIG:" . $user . ":{" . strtoupper($hash) . "}" . $hashsum . ":sql:" . $dbname . ":";
mapi_write($socket, $auth_string);
}
// decode the header and get the requested amount of data
function mapi_read($socket=NULL) {
# get the first 2 bytes
if ( ($header = socket_read($socket, 2)) == FALSE) {
$last_error = socket_strerror(socket_last_error());
exit();
}
$data = "";
$chunk_size = ((ord($header[1]) << 7) | (ord($header[0]) >> 1));
// keep reading until we have everything
while (strlen($data) < $chunk_size) {
$data .= socket_read($socket, $chunk_size - strlen($data));
}
while ((ord($header[0]) & 1) == 0 ) {
if ( ($header = socket_read($socket, 2)) == FALSE) {
$last_error = socket_strerror(socket_last_error());
exit();
}
$chunk_size = ( ((ord($header[1])) << 7) | (ord($header[0]) >> 1) );
$block = "";
while (strlen($block) < $chunk_size) {
if ( ($block .= socket_read($socket, $chunk_size - strlen($block))) == FALSE) {
$last_error = socket_strerror(socket_last_error());
exit();
}
}
$data = $data . $block;
}
if (strlen($data) == 0) {
return "";
}
return $data;
}
// encode data and send it to the server. Returns the number of bytes sent.
function mapi_write($socket=NULL, $msg) {
// print "Msg_len: " . strlen($msg) . "\n";
global $last_error;
$fb = 0;
$sb = 0;
$pos = 0;
$data = "";
$buf = 0;
$is_final = FALSE;
while (! $is_final) {
$data = substr($msg, $pos, min(MAX_PACKET_SIZE, (strlen($msg) - $pos)) );
$pos += strlen($data);
$end = 0; // more packets will follow
if ( (strlen($msg) - $pos) == 0) {
$is_final = TRUE;
$end = 1;
}
$fb = (strlen($data) << 1) | $end;
/**
* socket_write() does not guarantee all data to be transmitted.
* Make sure that the buffer is flushed.
*/
if ( ($buf = socket_flush($socket, pack("v", $fb) . $data)) == FALSE) {
$last_error = socket_strerror(socket_last_error());
return -1;
}
}
return $buf;
}
function set_timezone($socket=NULL) {
global $last_error;
$tz_offset = "'" . date('P') . "'"; /* Difference to Greenwich time (GMT) with colon between hours and minutes */
$query = "SET TIME ZONE INTERVAL " . $tz_offset . " HOUR TO MINUTE";
$buf = mapi_write($socket, format_query($query, LANG_SQL)); // set_timezone is called only when connecting to an sql db
$response = mapi_read($socket);
if ($response == "") {
return TRUE;
} else {
$last_error = $response;
return $response;
}
}
function format_command($cmd) {
return "X" . $cmd;
}
function mapi_connect_proxy(&$options) {
global $last_error;
global $connection_pool;
global $pconnect_count;
$merovingian_iter = 0;
/**
* When connecting, the function would first try to find a (persistent) link that's already
* open with the same host, username and password. If one is found, an identifier for it will be returned
* instead of opening a new connection.
* TODO: move this check to mapi_connect() to deal with options arrays rewritten by redirects.
*/
if ($options['persistent'] == TRUE) {
if (count($connection_pool) > 0) {
foreach ($connection_pool as $conn) {
if ( ($conn["persistent"] == TRUE) && ($conn["dbname"] == $options['database']) && ($conn['username'] == $options['username']) && ($conn["password"] == hash($options['hashfunc'], $options['password']) && ($conn['host']) == $options['host']) && ( $conn['port'] == $options['port'] ) ) {
return $conn;
}
}
}
}
$socket = mapi_open();
if ( mapi_connect($socket, $options, $merovingian_iter) == TRUE ) {
/* Connected */
// Create a new connection instance and insert an entry in the connections table
$id = mapi_generate_id();
if ($options['lang'] == LANG_SQL) {
/*
PHP requires a timezone to be specified in the configuration environment; if not specified
either in php.ini or via date_default_timezone_set(), a default is set 'Europe/Berlin'.
PHP complains in case we query the OS to get system's timezone (E_STRICT error).
To avoid unexpected behaviours and warnings at execution time we set a timezone on mserver
only if PHP interpreter is aware of it (php.ini contains a date.timezone entry).
*/
if (ini_get("date.timezone")) {
set_timezone($socket); // set the timezone according to the system's configuration
}
// export the reply size (max number of tuples returned at query executions)
mapi_write($socket, format_command("reply_size " . REPLY_SIZE));
if (strlen($response = mapi_read($socket)) > 0 ) {
// something went wrong
$last_error = $response;
return FALSE;
}
} else {
return FALSE;
}
} else {
socket_close($socket);
return FALSE;
}
$connection = array("id" => $id, "socket" => $socket, "host" => $options["host"], "port" => $options["port"], "dbname" => $options['database'], "username" => $options["username"], "password" => hash($options['hashfunc'], $options["password"]), "transactions" => array(), "persistent" => $options["persistent"], "lang" => $options['lang']);
$connection_pool[] = $connection;
return $connection;
}
function mapi_connected($conn=NULL) {
global $last_error;
global $connection_pool;
if ($conn == NULL) {
return FALSE;
} else {
return mapi_ping($conn);
}
return FALSE;
}
function mapi_ping($conn=NULL) {
if ($conn != NULL) {
switch($conn['lang']) {
case LANG_SQL:
$res = mapi_execute($conn, "select true;");
break;
}
if ($res != NULL) {
if (!is_array($res['query']) ||
!array_key_exists('id', $res['query']) ||
mapi_free_result($conn['id'], $res['query']['id']))
{
return TRUE;
}
}
}
return FALSE;
}
/* Returns a pointer to the current (last initialized) connection */
function mapi_get_current_conn() {
global $connection_pool;
if (count($connection_pool) > 0) {
return end($connection_pool);
} else {
return FALSE;
}
}
/* Returns a socket */
function mapi_open() {
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket == FALSE) {
$last_error = socket_strerror(socket_last_error());
return FALSE;
}
return $socket;
}
function mapi_close($conn=NULL) {
global $connection_pool;
/* TODO: start closing connection at the end of the array! */
if ($conn == NULL) {
if ((count($connection_pool) == 1) && ($connection_pool[0]["persistent"]) == FALSE) {
$socket = $connection_pool[0]["socket"];
socket_close($socket);
foreach ($connection_pool as $field) {
if (isset($field)) {
unset($field);
}
}
unset($connection_pool);
return TRUE;
}
} else {
$socket = $conn["socket"];
socket_close($socket);
/* remove the $conn from the pool */
// Create anonymous callback function to filter results for connection.
$function_body = 'return ( $input[\'id\'] != "'.$conn["id"].'" );';
$function_name = create_function('$input', $function_body);
// Filter the results array using the anonymous callback function.
$connection_pool = array_filter($connection_pool, $function_name);
if (isset($conn)) {
foreach ($conn as $field) {
if (isset($field)) {
unset($field);
}
}
unset($conn);
}
return TRUE;
}
return FALSE;
}
function mapi_free_result($conn_id, $res_id) {
global $connection_pool;
global $last_error;
/* Fetch the connection from the pool */
$conn = NULL;
foreach ($connection_pool as $connection) {
if ($connection["id"] == $conn_id) {
$conn = $connection;
break;
}
}
if ($conn == NULL) {
return FALSE;
}
$socket = $conn["socket"];
/* Send a close command */
$cmd = "close " . $res_id;
mapi_write($socket, format_command($cmd));
$last_error = mapi_read($socket);
if ($last_error != "") {
return FALSE;
}
return TRUE;
}
function mapi_generate_id(){
global $connection_pool;
$connections = array();
if ($connection_pool !== null) {
foreach($connection_pool as $conn) {
$connections[] = $conn["id"];
}
}
$id = hash("sha1", time());
if (count($connections) > 0) {
while (in_array($id, $connections) ) {
$id = hash("sha1", time());
}
}
return $id;
}
function format_query($query, $lang) {
if ($lang == LANG_SQL) {
return "s" . $query . ";";
}
return FALSE;
}
/* Write data through a socket; make sure that the buffer is actually flushed */
function socket_flush($socket, $data) {
$buf = 0;
$bytes = strlen($data);
if ($socket == NULL) {
return FALSE;
}
while ( ($bytes - $buf) > 0 ) {
$buf += socket_write($socket, substr($data, $buf, $bytes), $bytes - $buf);
//print "Buf: " . $buf . "\n";
if ($buf == FALSE) {
return FALSE;
}
}
return $buf;
}
function mapi_quote($string, $size) {
$quoted_string = ""; # upper bound: $size * 2 + 1
$index = 0; // current position in the original string
$t = 0; // current position in the quoted string
/* Parse the original string character by character and copy it in a new buffer escaping characters */
while ($size < 0 ? $quoted_string[$t] : $size > 0) {
if ($size > 0)
$size--;
switch ($string[$index]) {
case '\n':
$quoted_string[$t++] = '\\';
$quoted_string[$t++] = 'n';
break;
case '\t':
$quoted_string[$t++] = '\\';
$quoted_string[$t++] = 't';
break;
case PLACEHOLDER:
$quoted_string[$t++] = '\\';
$quoted_string[$t++] = PLACEHOLDER;
break;
case '\\':
$quoted_string[$t++] = '\\';
$quoted_string[$t++] = '\\';
break;
case '\'':
$quoted_string[$t++] = '\'';
break;
case '\"':
$quoted_string[$t++] = '\\';
$quoted_string[$t++] = '"';
break;
case '\0':
$quoted_string[$t++] = '\\';
$quoted_string[$t++] = '0';
break;
default:
$quoted_string[$t++] = $string[$index];
break;
}
$index++;
/* also deal with binaries */
}
if (is_array($quoted_string)) {
$quoted_string = implode($quoted_string);
}
return $quoted_string;
}
// inlining php_monetdb.php
/**
* php_monetdb.php
* Implementation of the driver API.
*
* This library relies on the native PHP mapi implementation.
*
* This file should be included by all pages that want to make use of a
* database connection.
*
* Synopsis of the provided functions:
*
* function monetdb_connect() *
* function monetdb_disconnect() *
* function monetdb_connected() *
* function monetdb_query($query) *
* function monetdb_fetch_assoc($hdl) *
* function monetdb_fetch_object($hdl)
* function monetdb_num_rows($hdl) *
* function monetdb_affected_rows($hdl) *
* function monetdb_last_error() *
* function monetdb_insert_id($seq) *
* function monetdb_quote_ident($str) *
* function monetdb_escape_string($str) *
**/
/**
* php_mapi.inc is a native (socket based) php implementation of the MAPI communication protocol.
*/
//require 'php_mapi.inc';
/**
* register a 'monetdb' extension to retain compatibility with wht Cimpl based scripts.
*/
/**
* Opens a connection to a MonetDB server.
*
* @param string language to be used (sql)
* @param string hostname to connect to (default is localhost)
* @param int port to use (default is 50000)
* @param string username (default is monetdb)
* @param string password (default is monetdb)
* @param string database to use (default is demo)
* @param string hash function to use during authentication (defaults to SHA1)
* @return bool TRUE on success or FALSE on failure
*/
function monetdb_connect($lang = "sql", $host = "127.0.0.1", $port = 50000, $username = "monetdb", $password = "monetdb", $database = "demo", $hashfunc = "") {
$options["host"] = $host;
$options["port"] = $port;
$options["username"] = $username;
$options["password"] = $password;
$options["database"] = $database;
$options["persistent"] = FALSE;
if ($hashfunc == "") {
$hashfunc = "sha1";
}
if ($lang == "") {
$lang = "sql";
}
$options["hashfunc"] = $hashfunc;
$options["lang"] = $lang;
return mapi_connect_proxy($options);
}
/**
* Opens a persistent connection to a MonetDB server.
* First, when connecting, the function would first try to find a (persistent) link that's already open with the same host,
* username and password. If one is found, an identifier for it will be returned instead of opening a new connection.
*
* Second, the connection to the SQL server will not be closed when the execution of the script ends.
* Instead, the link will remain open for future use (monetdb_close() will not close links established by monetdb_pconnect()).
*
* This type of link is therefore called 'persistent'.
*
* @param string language to be used (sql)
* @param string hostname to connect to (default is localhost)
* @param int port to use (default is 50000)
* @param string username (default is monetdb)
* @param string password (default is monetdb)
* @param string database to use (default is demo)
* @param string hash function to use during authentication (defaults to SHA1)
* @return bool TRUE on success or FALSE on failure
*/
function monetdb_pconnect($lang = "sql", $host = "127.0.0.1", $port = 500000, $username = "monetdb", $password = "monetdb", $database = "demo", $hashfunc = "") {
$options["host"] = $host;
$options["port"] = $port;
$options["username"] = $username;
$options["password"] = $password;
$options["database"] = $database;
$options["persistent"] = TRUE;
if ($hashfunc == "") {
$hashfunc = "sha1";
}
if ($lang == "") {
$lang = "sql";
} else if (strstr($lang, "sql") == $lang) {
$lang = "sql";
}
$options["hashfunc"] = $hashfunc;
$options["lang"] = $lang;
return mapi_connect_proxy($options);
}
/**
* Disconnects the connection to the database.
*
* @param resource connection instance
*/
function monetdb_disconnect($conn=NULL) {
$num_args = func_num_args();
if ($num_args == 0) {
$conn = mapi_get_current_conn();
mapi_close(NULL);
} else {
mapi_close($conn);
}
}
/**
* Returns whether a connection to the database has been made, and has
* not been closed yet. Note that this function doesn't guarantee that
* the connection is alive or usable.
*
* @param resource connection instance
* @return bool TRUE if there is a connection, FALSE otherwise
*
*/
function monetdb_connected($connection=NULL) {
$num_args = func_num_args();
if ($num_args == 0){
return mapi_connected(mapi_get_current_conn());
}
return mapi_connected($connection);
}
/**
* Executes the given query on the database.
*
* @param resource connection instance
* @param string the SQL query to execute
* @return resource a query handle or FALSE on failure
*/
function monetdb_query($connection=NULL, $query="") {
$num_args = func_num_args();
if ($num_args == 1){