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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
|
<?php
/***************************************************************************
* admin_database.php
* -------------------
* begin : Thu May 31, 2001
* copyright : (C) 2001 The phpBB Group
* email : support@phpbb.com
*
* $Id$
*
****************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
if ( !empty($setmodules) )
{
if ( !$auth->get_acl_admin('general') )
{
return;
}
$filename = basename(__FILE__);
$module['DB']['DB_Backup'] = $filename . "$SID&mode=backup";
$file_uploads = @ini_get('file_uploads');
if (!empty($file_uploads) && $file_uploads !== 0 && strtolower($file_uploads) != 'off' && @phpversion() != '4.0.4pl1' )
{
$module['DB']['DB_Restore'] = $filename . "$SID&mode=restore";
}
return;
}
define('IN_PHPBB', 1);
//
// Load default header
//
$phpbb_root_path = '../';
require($phpbb_root_path . 'extension.inc');
require('pagestart.' . $phpEx);
include($phpbb_root_path . 'includes/functions_admin.'.$phpEx);
//
// Do we have DB backup/restore permissions?
//
if ( !$auth->get_acl_admin('general') )
{
message_die(MESSAGE, $lang['No_admin']);
}
//
// Increase maximum execution time, but don't complain about it if it isn't
// allowed.
//
@set_time_limit(1200);
$mode = ( isset($HTTP_GET_VARS['mode']) ) ? $HTTP_GET_VARS['mode'] : '';
//
// Begin program proper
//
switch( $mode )
{
case 'backup':
if ( SQL_LAYER == 'oracle' || SQL_LAYER == 'odbc' || SQL_LAYER == 'mssql' )
{
switch ( SQL_LAYER )
{
case 'oracle':
$db_type = 'Oracle';
break;
case 'odbc':
$db_type = 'ODBC';
break;
case 'mssql':
$db_type = 'MSSQL';
break;
}
message_die(MESSAGE, $lang['Backups_not_supported']);
break;
}
$additional_tables = ( isset($HTTP_POST_VARS['tables']) ) ? $HTTP_POST_VARS['tables'] : ( ( isset($HTTP_GET_VARS['tables']) ) ? $HTTP_GET_VARS['tables'] : '' );
$backup_type = ( isset($HTTP_POST_VARS['type']) ) ? $HTTP_POST_VARS['type'] : ( ( isset($HTTP_GET_VARS['type']) ) ? $HTTP_GET_VARS['type'] : '' );
$search = ( !empty($HTTP_POST_VARS['search']) ) ? intval($HTTP_POST_VARS['search']) : ( ( !empty($HTTP_GET_VARS['search']) ) ? intval($HTTP_GET_VARS['search']) : 0 );
$store_path = ( isset($HTTP_POST_VARS['store']) ) ? $HTTP_POST_VARS['store'] : ( ( isset($HTTP_GET_VARS['store']) ) ? $HTTP_GET_VARS['store'] : '' );
$compress = ( !empty($HTTP_POST_VARS['compress']) ) ? $HTTP_POST_VARS['compress'] : ( ( !empty($HTTP_GET_VARS['compress']) ) ? $HTTP_GET_VARS['compress'] : 'none' );
if ( !isset($HTTP_POST_VARS['backupstart']) && !isset($HTTP_GET_VARS['backupstart']) )
{
page_header($lang['DB_Backup']);
?>
<h1><?php echo $lang['DB_Backup']; ?></h1>
<p><?php echo $lang['Backup_explain']; ?></p>
<form method="post" action="<?php echo "admin_database.$phpEx$SID&mode=$mode"; ?>"><table class="bg" width="80%" cellspacing="1" cellpadding="4" border="0" align="center">
<tr>
<th colspan="2"><?php echo $lang['Backup_options']; ?></th>
</tr>
<tr>
<td class="row1"><?php echo $lang['Backup_type']; ?>: </td>
<td class="row2"><input type="radio" name="type" value="full" checked="checked" /> <?php echo $lang['Full_backup']; ?> <input type="radio" name="type" value="structure" /> <?php echo $lang['Structure_only']; ?> <input type="radio" name="type" value="data" /> <?php echo $lang['Data_only']; ?></td>
</tr>
<tr>
<td class="row1"><?php echo $lang['Include_search_index']; ?>: <br /><span class="gensmall"><?php echo $lang['Include_search_index_explain']; ?></span></td>
<td class="row2"><input type="radio" name="search" value="0" /> <?php echo $lang['No']; ?> <input type="radio" name="search" value="1" checked="checked" /> <?php echo $lang['Yes']; ?></td>
</tr>
<tr>
<td class="row1"><?php echo $lang['Additional_tables']; ?>: <br /><span class="gensmall"><?php echo $lang['Additional_tables_explain']; ?></span></td>
<td class="row2"><input type="text" name="tables" size="40" /></td>
</tr>
<tr>
<td class="row1"><?php echo $lang['Store_local']; ?>: <br /><span class="gensmall"><?php echo $lang['Store_local_explain']; ?></span></td>
<td class="row2"><input type="text" name="store" size="40" /></td>
</tr>
<?php
if ( extension_loaded('zlib') || extension_loaded('bz2') )
{
?>
<tr>
<td class="row1"><?php echo $lang['Compress_file']; ?>: </td>
<td class="row2"><input type="radio" name="compress" value="none" checked="checked" /> <?php echo $lang['None']; ?><?php
if ( extension_loaded('zlib') )
{
?> <input type="radio" name="compress" value="gzip" />.gz <input type="radio" name="compress" value="zip" />.zip<?php
}
if ( extension_loaded('bz2') )
{
?> <input type="radio" name="compress" value="bzip" />.bz2<?php
}
?></td>
</tr>
<?php
}
?>
<tr>
<td class="cat" colspan="2" align="center"><input type="submit" name="backupstart" value="<?php echo $lang['Start_backup']; ?>" class="mainoption" /></td>
</tr>
</table></form>
<?php
break;
}
else if ( !isset($HTTP_POST_VARS['startdownload']) && !isset($HTTP_GET_VARS['startdownload']) )
{
$meta = "<meta http-equiv=\"refresh\" content=\"0;url=admin_database.$phpEx?mode=backup&type=$backup_type&tables=" . quotemeta($additional_tables) . "&search=$search&store=" . quotemeta($store_path) . "&compress=$compress&backupstart=1&startdownload=1\">";
$message = ( empty($store_path) ) ? $lang['Backup_download'] : $lang['Backup_writing'];
page_header($lang['DB_Backup'], $meta);
page_message($lang['DB_Backup'], $message);
page_footer();
}
$tables = ( SQL_LAYER != 'postgresql' ) ? mysql_get_tables() : pg_get_tables();
@sort($tables);
if ( !empty($additional_tables) )
{
$additional_tables = explode(',', $additional_tables);
for($i = 0; $i < count($additional_tables); $i++)
{
$tables[] = trim($additional_tables[$i]);
}
unset($additional_tables);
}
//
// Enable output buffering
//
@ob_start();
@ob_implicit_flush(0);
//
// Build the sql script file...
//
echo "#\n";
echo "# phpBB Backup Script\n";
echo "# Dump of tables for $dbname\n";
echo "#\n# DATE : " . gmdate("d-m-Y H:i:s", time()) . " GMT\n";
echo "#\n";
if ( SQL_LAYER == 'postgresql' )
{
echo "\n" . pg_get_sequences("\n", $backup_type);
}
for($i = 0; $i < count($tables); $i++)
{
$table_name = $tables[$i];
if ( SQL_LAYER != 'mysql4' )
{
$table_def_function = "get_table_def_" . SQL_LAYER;
$table_content_function = "get_table_content_" . SQL_LAYER;
}
else
{
$table_def_function = "get_table_def_mysql";
$table_content_function = "get_table_content_mysql";
}
if ( $backup_type != 'data' )
{
echo "#\n# TABLE: " . $table_name . "\n#\n";
echo $table_def_function($table_name, "\n") . "\n";
}
if ( $backup_type != 'structure' )
{
//
// Skip search table data?
//
if ( $search || ( !$search && !preg_match('/search_word/', $table_name) ) )
{
$table_content_function($table_name, "output_table_content");
}
}
}
//
// Flush the buffer, send the file
//
switch ( $compress )
{
case 'gzip':
$extension = 'sql.gz';
$contents = gzencode(ob_get_contents());
ob_end_clean();
break;
case 'zip':
$extension = 'zip';
$zip = new zipfile;
$zip->addFile(ob_get_contents(), "phpbb_db_backup.sql", time());
ob_end_clean();
$contents = $zip->file();
break;
case 'bzip':
$extension = 'bz2';
$contents = bzcompress(ob_get_contents());
ob_end_clean();
break;
default:
$extension = 'sql';
$contents = ob_get_contents();
ob_end_clean();
}
add_admin_log('log_db_backup');
if ( empty($store_path) )
{
header("Pragma: no-cache");
header("Content-Type: text/x-delimtext; name=\"phpbb_db_backup.$extension\"");
header("Content-disposition: attachment; filename=phpbb_db_backup.$extension");
echo $contents;
unset($contents);
}
else
{
if ( !($fp = fopen('./../' . $store_path . "/phpbb_db_backup.$extension", 'wb')) )
{
message_die(ERROR, 'Could not open backup file');
}
if ( !fwrite($fp, $contents) )
{
message_die(ERROR, 'Could not write backup file content');
}
fclose($fp);
unset($contents);
message_die(MESSAGE, $lang['Backup_success']);
}
exit;
break;
case 'restore':
if ( isset($HTTP_POST_VARS['restorestart']) )
{
//
// Handle the file upload ....
// If no file was uploaded report an error...
//
if ( !empty($HTTP_POST_VARS['local']) )
{
$file_tmpname = './../' . str_replace('\\\\', '/', $HTTP_POST_VARS['local']);
$filename = substr($file_tmpname, strrpos($file_tmpname, '/'));
}
else
{
$filename = ( !empty($HTTP_POST_FILES['backup_file']['name']) ) ? $HTTP_POST_FILES['backup_file']['name'] : '';
$file_tmpname = ( $HTTP_POST_FILES['backup_file']['tmp_name'] != 'none' ) ? $HTTP_POST_FILES['backup_file']['tmp_name'] : '';
}
if ( $file_tmpname == '' || $filename == '' || !file_exists($file_tmpname) )
{
message_die(MESSAGE, $lang['Restore_Error_no_file']);
}
$ext = substr($filename, strrpos($filename, '.') + 1);
if ( !preg_match('/^(sql|gz|bz2)$/', $ext) )
{
message_die(MESSAGE, $lang['Restore_Error_filename']);
}
if ( ( !extension_loaded('zlib') && $ext == 'gz' ) || ( !extension_loaded('zip') && $ext == 'zip' ) || ( $ext == 'bz2' && !extension_loaded('bz2') ) )
{
message_die(MESSAGE, $lang['Compress_unsupported']);
}
$sql_query = '';
switch ( $ext )
{
case 'gz':
$fp = gzopen($file_tmpname, 'rb');
while ( !gzeof($fp) )
{
$sql_query .= gzgets($fp, 100000);
}
gzclose($fp);
break;
case 'bz2':
$sql_query = bzdecompress(fread(fopen($file_tmpname, 'rb'), filesize($file_tmpname)));
break;
default;
$sql_query = fread(fopen($file_tmpname, 'r'), filesize($file_tmpname));
}
if ( $sql_query != '' )
{
// Strip out sql comments...
$sql_query = remove_remarks($sql_query);
$pieces = split_sql_file($sql_query, ';');
$sql_count = count($pieces);
for($i = 0; $i < $sql_count; $i++)
{
$sql = trim($pieces[$i]);
if ( !empty($sql) && $sql[0] != '#' )
{
$db->sql_query($sql);
}
}
}
add_admin_log('log_db_restore');
message_die(MESSAGE, $lang['Restore_success']);
}
//
// Restore page
//
page_header($lang['DB_Restore']);
?>
<h1><?php echo $lang['DB_Restore']; ?></h1>
<p><?php echo $lang['Restore_explain']; ?></p>
<form enctype="multipart/form-data" method="post" action="<?php echo "admin_database.$phpEx$SID&mode=$mode"; ?>"><table class="bg" width="80%" cellspacing="1" cellpadding="4" border="0" align="center">
<th colspan="2"><?php echo $lang['Select_file']; ?></th>
</tr>
<tr>
<td class="row1"><?php echo $lang['Upload_file']; ?>: <br /><span class="gensmall"><?php
echo $lang['Supported_extensions'];
$types = ': <u>sql</u>';
if ( extension_loaded('zlib') )
{
$types .= ', <u>sql.gz</u>';
}
if ( extension_loaded('bz2') )
{
$types .= ', <u>bz2</u>';
}
echo $types;
?></span></td>
<td class="row2"><input type="file" name="backup_file" /></td>
</tr>
<tr>
<td class="row1"><?php echo $lang['Local_backup_file']; ?>: <br /><span class="gensmall"><?php echo $lang['Local_backup_file_explain']; ?></span></td>
<td class="row2"><input type="text" name="local" size="40" /></td>
</tr>
<tr>
<td class="cat" colspan="2" align="center"><input type="submit" name="restorestart" value="<?php echo $lang['Start_Restore']; ?>" class="mainoption" /></td>
</tr>
</table></form>
<?php
break;
default:
exit;
}
page_footer();
// -----------------------------------------------
// Begin Functions
//
//
// Table defns (not from phpMyAdmin)
//
function mysql_get_tables()
{
global $db, $table_prefix;
$tables = array();
$result = mysql_list_tables($db->dbname, $db->db_connect_id);
if ( $row = $db->sql_fetchrow($result) )
{
do
{
if ( preg_match('/^' . $table_prefix . '/', $row[0]) )
{
$tables[] = $row[0];
}
}
while ( $row = $db->sql_fetchrow($result) );
}
return $tables;
}
//
// The following functions are adapted from phpMyAdmin and upgrade_20.php
//
// This function is used for grabbing the sequences for postgres...
//
function pg_get_sequences($crlf, $backup_type)
{
global $db;
$get_seq_sql = "SELECT relname FROM pg_class WHERE NOT relname ~ 'pg_.*'
AND relkind = 'S' ORDER BY relname";
$seq = $db->sql_query($get_seq_sql);
if( !$num_seq = $db->sql_numrows($seq) )
{
$return_val = "# No Sequences Found $crlf";
}
else
{
$return_val = "# Sequences $crlf";
$i_seq = 0;
while($i_seq < $num_seq)
{
$row = $db->sql_fetchrow($seq);
$sequence = $row['relname'];
$get_props_sql = "SELECT * FROM $sequence";
$seq_props = $db->sql_query($get_props_sql);
if($db->sql_numrows($seq_props) > 0)
{
$row1 = $db->sql_fetchrow($seq_props);
if($backup_type == 'structure')
{
$row['last_value'] = 1;
}
$return_val .= "CREATE SEQUENCE $sequence start " . $row['last_value'] . ' increment ' . $row['increment_by'] . ' maxvalue ' . $row['max_value'] . ' minvalue ' . $row['min_value'] . ' cache ' . $row['cache_value'] . "; $crlf";
} // End if numrows > 0
if(($row['last_value'] > 1) && ($backup_type != 'structure'))
{
$return_val .= "SELECT NEXTVALE('$sequence'); $crlf";
unset($row['last_value']);
}
$i_seq++;
} // End while..
} // End else...
return $returnval;
} // End function...
//
// The following functions will return the "CREATE TABLE syntax for the
// varying DBMS's
//
// This function returns, will return the table def's for postgres...
//
function get_table_def_postgresql($table, $crlf)
{
global $db;
$schema_create = "";
//
// Get a listing of the fields, with their associated types, etc.
//
$field_query = "SELECT a.attnum, a.attname AS field, t.typname as type, a.attlen AS length, a.atttypmod as lengthvar, a.attnotnull as notnull
FROM pg_class c, pg_attribute a, pg_type t
WHERE c.relname = '$table'
AND a.attnum > 0
AND a.attrelid = c.oid
AND a.atttypid = t.oid
ORDER BY a.attnum";
$result = $db->sql_query($field_query);
if(!$result)
{
message_die(GENERAL_ERROR, "Failed in get_table_def (show fields)", "", __LINE__, __FILE__, $field_query);
} // end if..
$schema_create .= "DROP TABLE $table;$crlf";
//
// Ok now we actually start building the SQL statements to restore the tables
//
$schema_create .= "CREATE TABLE $table($crlf";
while ($row = $db->sql_fetchrow($result))
{
//
// Get the data from the table
//
$sql_get_default = "SELECT d.adsrc AS rowdefault
FROM pg_attrdef d, pg_class c
WHERE (c.relname = '$table')
AND (c.oid = d.adrelid)
AND d.adnum = " . $row['attnum'];
$def_res = $db->sql_query($sql_get_default);
if (!$def_res)
{
unset($row['rowdefault']);
}
else
{
$row['rowdefault'] = @pg_result($def_res, 0, 'rowdefault');
}
if ($row['type'] == 'bpchar')
{
// Internally stored as bpchar, but isn't accepted in a CREATE TABLE statement.
$row['type'] = 'char';
}
$schema_create .= ' ' . $row['field'] . ' ' . $row['type'];
if (eregi('char', $row['type']))
{
if ($row['lengthvar'] > 0)
{
$schema_create .= '(' . ($row['lengthvar'] -4) . ')';
}
}
if (eregi('numeric', $row['type']))
{
$schema_create .= '(';
$schema_create .= sprintf("%s,%s", (($row['lengthvar'] >> 16) & 0xffff), (($row['lengthvar'] - 4) & 0xffff));
$schema_create .= ')';
}
if (!empty($row['rowdefault']))
{
$schema_create .= ' DEFAULT ' . $row['rowdefault'];
}
if ($row['notnull'] == 't')
{
$schema_create .= ' NOT NULL';
}
$schema_create .= ",$crlf";
}
//
// Get the listing of primary keys.
//
$sql_pri_keys = "SELECT ic.relname AS index_name, bc.relname AS tab_name, ta.attname AS column_name, i.indisunique AS unique_key, i.indisprimary AS primary_key
FROM pg_class bc, pg_class ic, pg_index i, pg_attribute ta, pg_attribute ia
WHERE (bc.oid = i.indrelid)
AND (ic.oid = i.indexrelid)
AND (ia.attrelid = i.indexrelid)
AND (ta.attrelid = bc.oid)
AND (bc.relname = '$table')
AND (ta.attrelid = i.indrelid)
AND (ta.attnum = i.indkey[ia.attnum-1])
ORDER BY index_name, tab_name, column_name ";
$result = $db->sql_query($sql_pri_keys);
if(!$result)
{
message_die(GENERAL_ERROR, "Failed in get_table_def (show fields)", "", __LINE__, __FILE__, $sql_pri_keys);
}
while ( $row = $db->sql_fetchrow($result))
{
if ($row['primary_key'] == 't')
{
if (!empty($primary_key))
{
$primary_key .= ', ';
}
$primary_key .= $row['column_name'];
$primary_key_name = $row['index_name'];
}
else
{
//
// We have to store this all this info because it is possible to have a multi-column key...
// we can loop through it again and build the statement
//
$index_rows[$row['index_name']]['table'] = $table;
$index_rows[$row['index_name']]['unique'] = ($row['unique_key'] == 't') ? ' UNIQUE ' : '';
$index_rows[$row['index_name']]['column_names'] .= $row['column_name'] . ', ';
}
}
if (!empty($index_rows))
{
while(list($idx_name, $props) = each($index_rows))
{
$props['column_names'] = ereg_replace(", $", "" , $props['column_names']);
$index_create .= 'CREATE ' . $props['unique'] . " INDEX $idx_name ON $table (" . $props['column_names'] . ");$crlf";
}
}
if (!empty($primary_key))
{
$schema_create .= " CONSTRAINT $primary_key_name PRIMARY KEY ($primary_key),$crlf";
}
//
// Generate constraint clauses for CHECK constraints
//
$sql_checks = "SELECT rcname as index_name, rcsrc
FROM pg_relcheck, pg_class bc
WHERE rcrelid = bc.oid
AND bc.relname = '$table'
AND NOT EXISTS (
SELECT *
FROM pg_relcheck as c, pg_inherits as i
WHERE i.inhrelid = pg_relcheck.rcrelid
AND c.rcname = pg_relcheck.rcname
AND c.rcsrc = pg_relcheck.rcsrc
AND c.rcrelid = i.inhparent
)";
$result = $db->sql_query($sql_checks);
if (!$result)
{
message_die(GENERAL_ERROR, "Failed in get_table_def (show fields)", "", __LINE__, __FILE__, $sql_checks);
}
//
// Add the constraints to the sql file.
//
while ($row = $db->sql_fetchrow($result))
{
$schema_create .= ' CONSTRAINT ' . $row['index_name'] . ' CHECK ' . $row['rcsrc'] . ",$crlf";
}
$schema_create = ereg_replace(',' . $crlf . '$', '', $schema_create);
$index_create = ereg_replace(',' . $crlf . '$', '', $index_create);
$schema_create .= "$crlf);$crlf";
if (!empty($index_create))
{
$schema_create .= $index_create;
}
//
// Ok now we've built all the sql return it to the calling function.
//
return (stripslashes($schema_create));
}
//
// This function returns the "CREATE TABLE" syntax for mysql dbms...
//
function get_table_def_mysql($table, $crlf)
{
global $db;
$schema_create = "";
$field_query = "SHOW FIELDS FROM $table";
$key_query = "SHOW KEYS FROM $table";
//
// If the user has selected to drop existing tables when doing a restore.
// Then we add the statement to drop the tables....
//
$schema_create .= "DROP TABLE IF EXISTS $table;$crlf";
$schema_create .= "CREATE TABLE $table($crlf";
//
// Ok lets grab the fields...
//
$result = $db->sql_query($field_query);
if(!result)
{
message_die(GENERAL_ERROR, "Failed in get_table_def (show fields)", "", __LINE__, __FILE__, $field_query);
}
while ($row = $db->sql_fetchrow($result))
{
$schema_create .= ' ' . $row['Field'] . ' ' . $row['Type'];
if(!empty($row['Default']))
{
$schema_create .= ' DEFAULT \'' . $row['Default'] . '\'';
}
if($row['Null'] != "YES")
{
$schema_create .= ' NOT NULL';
}
if($row['Extra'] != "")
{
$schema_create .= ' ' . $row['Extra'];
}
$schema_create .= ",$crlf";
}
//
// Drop the last ',$crlf' off ;)
//
$schema_create = ereg_replace(',' . $crlf . '$', "", $schema_create);
//
// Get any Indexed fields from the database...
//
$result = $db->sql_query($key_query);
while($row = $db->sql_fetchrow($result))
{
$kname = $row['Key_name'];
if(($kname != 'PRIMARY') && ($row['Non_unique'] == 0))
{
$kname = "UNIQUE|$kname";
}
if(!is_array($index[$kname]))
{
$index[$kname] = array();
}
$index[$kname][] = $row['Column_name'];
}
while(list($x, $columns) = @each($index))
{
$schema_create .= ", $crlf";
if($x == 'PRIMARY')
{
$schema_create .= ' PRIMARY KEY (' . implode($columns, ', ') . ')';
}
elseif (substr($x,0,6) == 'UNIQUE')
{
$schema_create .= ' UNIQUE ' . substr($x,7) . ' (' . implode($columns, ', ') . ')';
}
else
{
$schema_create .= " KEY $x (" . implode($columns, ', ') . ')';
}
}
$schema_create .= "$crlf);";
if(get_magic_quotes_runtime())
{
return(stripslashes($schema_create));
}
else
{
return($schema_create);
}
} // End get_table_def_mysql
//
// This fuction will return a tables create definition to be used as an sql
// statement.
//
//
// The following functions Get the data from the tables and format it as a
// series of INSERT statements, for each different DBMS...
// After every row a custom callback function $handler gets called.
// $handler must accept one parameter ($sql_insert);
//
//
// Here is the function for postgres...
//
function get_table_content_postgresql($table, $handler)
{
global $db;
//
// Grab all of the data from current table.
//
$result = $db->sql_query("SELECT * FROM $table");
$i_num_fields = $db->sql_numfields($result);
for ($i = 0; $i < $i_num_fields; $i++)
{
$aryType[] = $db->sql_fieldtype($i, $result);
$aryName[] = $db->sql_fieldname($i, $result);
}
$iRec = 0;
while ( $row = $db->sql_fetchrow($result) )
{
unset($schema_vals);
unset($schema_fields);
unset($schema_insert);
//
// Build the SQL statement to recreate the data.
//
for($i = 0; $i < $i_num_fields; $i++)
{
$strVal = $row[$aryName[$i]];
if (eregi("char|text|bool", $aryType[$i]))
{
$strQuote = "'";
$strEmpty = "";
$strVal = addslashes($strVal);
}
elseif (eregi("date|timestamp", $aryType[$i]))
{
if ($empty($strVal))
{
$strQuote = "";
}
else
{
$strQuote = "'";
}
}
else
{
$strQuote = "";
$strEmpty = "NULL";
}
if (empty($strVal) && $strVal != "0")
{
$strVal = $strEmpty;
}
$schema_vals .= " $strQuote$strVal$strQuote,";
$schema_fields .= " $aryName[$i],";
}
$schema_vals = ereg_replace(",$", "", $schema_vals);
$schema_vals = ereg_replace("^ ", "", $schema_vals);
$schema_fields = ereg_replace(",$", "", $schema_fields);
$schema_fields = ereg_replace("^ ", "", $schema_fields);
//
// Take the ordered fields and their associated data and build it
// into a valid sql statement to recreate that field in the data.
//
$schema_insert = "INSERT INTO $table ($schema_fields) VALUES($schema_vals);";
$handler(trim($schema_insert));
}
return(true);
}// end function get_table_content_postgres...
//
// This function is for getting the data from a mysql table.
//
function get_table_content_mysql($table, $handler)
{
global $db;
//
// Grab the data from the table.
//
$result = $db->sql_query("SELECT * FROM $table");
//
// Loop through the resulting rows and build the sql statement.
//
$schema_insert = "";
if ( $row = $db->sql_fetchrow($result) )
{
$schema_insert = "\n#\n# Table Data for $table\n#\n";
$handler($schema_insert);
do
{
$table_list = '(';
$num_fields = $db->sql_numfields($result);
//
// Grab the list of field names.
//
for ($j = 0; $j < $num_fields; $j++)
{
$table_list .= $db->sql_fieldname($j, $result) . ', ';
}
//
// Get rid of the last comma
//
$table_list = ereg_replace(', $', '', $table_list);
$table_list .= ')';
//
// Start building the SQL statement.
//
$schema_insert = "INSERT INTO $table $table_list VALUES(";
//
// Loop through the rows and fill in data for each column
//
for ($j = 0; $j < $num_fields; $j++)
{
if(!isset($row[$j]))
{
//
// If there is no data for the column set it to null.
// There was a problem here with an extra space causing the
// sql file not to reimport if the last column was null in
// any table. Should be fixed now :) JLH
//
$schema_insert .= ' NULL,';
}
elseif ($row[$j] != '')
{
$schema_insert .= ' \'' . addslashes($row[$j]) . '\',';
}
else
{
$schema_insert .= '\'\',';
}
}
//
// Get rid of the the last comma.
//
$schema_insert = ereg_replace(',$', '', $schema_insert);
$schema_insert .= ');';
//
// Go ahead and send the insert statement to the handler function.
//
$handler(trim($schema_insert));
}
while ( $row = $db->sql_fetchrow($result) );
}
return true;
}
function output_table_content($content)
{
global $tempfile;
//fwrite($tempfile, $content . "\n");
//$backup_sql .= $content . "\n";
echo $content ."\n";
return;
}
//
// Zip creation class from phpMyAdmin 2.3.0 (c) Tobias Ratschiller, Olivier Müller, Loïc Chapeaux, Marc Delisle
// http://www.phpmyadmin.net/
//
// Based on work by Eric Mueller and Denis125
// Official ZIP file format: http://www.pkware.com/appnote.txt
//
class zipfile
{
var $datasec = array();
var $ctrl_dir = array();
var $eof_ctrl_dir = "\x50\x4b\x05\x06\x00\x00\x00\x00";
var $old_offset = 0;
function unix2DosTime($unixtime = 0)
{
$timearray = ( $unixtime == 0 ) ? getdate() : getdate($unixtime);
if ($timearray['year'] < 1980)
{
$timearray['year'] = 1980;
$timearray['mon'] = 1;
$timearray['mday'] = 1;
$timearray['hours'] = 0;
$timearray['minutes'] = 0;
$timearray['seconds'] = 0;
}
return ( ( $timearray['year'] - 1980) << 25 ) | ( $timearray['mon'] << 21 ) | ( $timearray['mday'] << 16 ) |
( $timearray['hours'] << 11 ) | ( $timearray['minutes'] << 5 ) | ( $timearray['seconds'] >> 1 );
}
function addFile($data, $name, $time = 0)
{
$name = str_replace('\\', '/', $name);
$dtime = dechex($this->unix2DosTime($time));
$hexdtime = '\x' . $dtime[6] . $dtime[7]
. '\x' . $dtime[4] . $dtime[5]
. '\x' . $dtime[2] . $dtime[3]
. '\x' . $dtime[0] . $dtime[1];
eval('$hexdtime = "' . $hexdtime . '";');
$fr = "\x50\x4b\x03\x04";
$fr .= "\x14\x00"; // ver needed to extract
$fr .= "\x00\x00"; // gen purpose bit flag
$fr .= "\x08\x00"; // compression method
$fr .= $hexdtime; // last mod time and date
$unc_len = strlen($data);
$crc = crc32($data);
$zdata = gzcompress($data);
$zdata = substr(substr($zdata, 0, strlen($zdata) - 4), 2); // fix crc bug
$c_len = strlen($zdata);
$fr .= pack('V', $crc); // crc32
$fr .= pack('V', $c_len); // compressed filesize
$fr .= pack('V', $unc_len); // uncompressed filesize
$fr .= pack('v', strlen($name)); // length of filename
$fr .= pack('v', 0); // extra field length
$fr .= $name;
// "file data" segment
$fr .= $zdata;
// "data descriptor" segment (optional but necessary if archive is not
// served as file)
$fr .= pack('V', $crc); // crc32
$fr .= pack('V', $c_len); // compressed filesize
$fr .= pack('V', $unc_len); // uncompressed filesize
// add this entry to array
$this -> datasec[] = $fr;
$new_offset = strlen(implode('', $this->datasec));
// now add to central directory record
$cdrec = "\x50\x4b\x01\x02";
$cdrec .= "\x00\x00"; // version made by
$cdrec .= "\x14\x00"; // version needed to extract
$cdrec .= "\x00\x00"; // gen purpose bit flag
$cdrec .= "\x08\x00"; // compression method
$cdrec .= $hexdtime; // last mod time & date
$cdrec .= pack('V', $crc); // crc32
$cdrec .= pack('V', $c_len); // compressed filesize
$cdrec .= pack('V', $unc_len); // uncompressed filesize
$cdrec .= pack('v', strlen($name) ); // length of filename
$cdrec .= pack('v', 0 ); // extra field length
$cdrec .= pack('v', 0 ); // file comment length
$cdrec .= pack('v', 0 ); // disk number start
$cdrec .= pack('v', 0 ); // internal file attributes
$cdrec .= pack('V', 32 ); // external file attributes - 'archive' bit set
$cdrec .= pack('V', $this -> old_offset ); // relative offset of local header
$this -> old_offset = $new_offset;
$cdrec .= $name;
// optional extra field, file comment goes here
// save to central directory
$this -> ctrl_dir[] = $cdrec;
}
function file()
{
$data = implode('', $this -> datasec);
$ctrldir = implode('', $this -> ctrl_dir);
return $data . $ctrldir . $this -> eof_ctrl_dir .
pack('v', sizeof($this -> ctrl_dir)) . // total # of entries "on this disk"
pack('v', sizeof($this -> ctrl_dir)) . // total # of entries overall
pack('V', strlen($ctrldir)) . // size of central dir
pack('V', strlen($data)) . // offset to start of central dir
"\x00\x00"; // .zip file comment length
}
}
//
// End Functions
// -----------------------------------------------
?>
|