Handle hostnames with upper-case letters
[webmin.git] / mysql / mysql-lib.pl
1 # mysql-lib.pl
2 # Common MySQL functions
3
4 BEGIN { push(@INC, ".."); };
5 use WebminCore;
6 &init_config();
7 if ($config{'mysql_libs'}) {
8         $ENV{$gconfig{'ld_env'}} .= ':' if ($ENV{$gconfig{'ld_env'}});
9         $ENV{$gconfig{'ld_env'}} .= $config{'mysql_libs'};
10         }
11 if ($config{'mysql'} =~ /^(\S+)\/bin\/mysql$/ && $1 ne '' && $1 ne '/usr') {
12         $ENV{$gconfig{'ld_env'}} .= ':' if ($ENV{$gconfig{'ld_env'}});
13         $ENV{$gconfig{'ld_env'}} .= "$1/lib";
14         }
15 if ($module_info{'usermin'}) {
16         # Usermin always runs this module as the logged-in Unix user.
17         # %access is faked up to prevent attempts to create and delete DBs
18         &switch_to_remote_user();
19         &create_user_config_dirs();
20         %access = ( 'create', 0,
21                     'delete', 0,
22                     'bpath', '/',
23                     'buser', 'root',
24                     'edonly', 0 );
25         if ($config{'useident'} ne 'yes') {
26                 $mysql_login = $userconfig{'login'};
27                 $mysql_pass = $userconfig{'pass'};
28                 }
29         if (open(VERSION, "$user_module_config_directory/version")) {
30                 chop($mysql_version = <VERSION>);
31                 close(VERSION);
32                 }
33         $max_dbs = $userconfig{'max_dbs'};
34         $commands_file = "$user_module_config_directory/commands";
35         $sql_charset = $userconfig{'charset'};
36         %displayconfig = %userconfig;
37         }
38 else {
39         # Webmin connects to the database as the user specified in the per-user
40         # or global config
41         %access = &get_module_acl();
42         if ($access{'user'} && !$use_global_login) {
43                 $mysql_login = $access{'user'};
44                 $mysql_pass = $access{'pass'};
45                 }
46         else {
47                 $mysql_login = $config{'login'};
48                 $mysql_pass = $config{'pass'};
49                 }
50         if (open(VERSION, "$module_config_directory/version")) {
51                 chop($mysql_version = <VERSION>);
52                 close(VERSION);
53                 }
54         else {
55                 $mysql_version = &get_mysql_version();
56                 }
57         $cron_cmd = "$module_config_directory/backup.pl";
58         $max_dbs = $config{'max_dbs'};
59         $commands_file = "$module_config_directory/commands";
60         $sql_charset = $config{'charset'};
61         %displayconfig = %config;
62         }
63 $authstr = &make_authstr();
64 $master_db = 'mysql';
65 $password_func = $config{'passwd_mode'} ? "old_password" : "password";
66
67 @type_list = ('tinyint', 'smallint', 'mediumint', 'int', 'bigint',
68             'float', 'double', 'decimal', 'date', 'datetime', 'timestamp',
69             'time', 'year', 'char', 'varchar', 'tinyblob', 'tinytext',
70             'blob', 'text', 'mediumblob', 'mediumtext', 'longblob', 'longtext',
71             'enum', 'set');
72
73 @priv_cols = ('Host', 'User', 'Password', 'Select_priv', 'Insert_priv', 'Update_priv', 'Delete_priv', 'Create_priv', 'Drop_priv', 'Reload_priv', 'Shutdown_priv', 'Process_priv', 'File_priv', 'Grant_priv', 'References_priv', 'Index_priv', 'Alter_priv', 'Show_db_priv', 'Super_priv', 'Create_tmp_table_priv', 'Lock_tables_priv', 'Execute_priv', 'Repl_slave_priv', 'Repl_client_priv', 'Create_view_priv', 'Show_view_priv', 'Create_routine_priv', 'Alter_routine_priv', 'Create_user_priv');
74
75 if (!$config{'nodbi'}) {
76         # Check if we have DBI::mysql
77         eval <<EOF;
78 use DBI;
79 \$driver_handle = DBI->install_driver("mysql");
80 EOF
81 }
82
83 $old_user_priv_cols = $mysql_version >= 4 ? 21 : 14;
84 $old_db_priv_cols = $mysql_version >= 4 ? 12 : 10;
85
86 @mysql_set_variables = ( "key_buffer", "max_allowed_packet",
87                          "sort_buffer", "net_buffer_length",
88                          "myisam_sort_buffer_size" );
89 @mysql_number_variables = ( "table_cache", "max_connections",
90                             "query_cache_size" );
91
92 # make_authstr([login], [pass], [host], [port], [sock])
93 sub make_authstr
94 {
95 local $login = defined($_[0]) ? $_[0] : $mysql_login;
96 local $pass = defined($_[1]) ? $_[1] : $mysql_pass;
97 local $host = defined($_[2]) ? $_[2] : $config{'host'};
98 local $port = defined($_[3]) ? $_[3] : $config{'port'};
99 local $sock = defined($_[4]) ? $_[4] : $config{'sock'};
100 if (&supports_env_pass()) {
101         $ENV{'MYSQL_PWD'} = $pass;
102         }
103 return ($sock ? " -S $sock" : "").
104        ($host ? " -h $host" : "").
105        ($port ? " -P $port" : "").
106        ($login ? " -u ".quotemeta($login) : "").
107        (&supports_env_pass() ? "" :     # Password comes from environment
108         $pass && $mysql_version >= 4.1 ? " --password=".quotemeta($pass) :
109         $pass ? " -p".quotemeta($pass) : "");
110 }
111
112 # is_mysql_running()
113 # Returns 1 if mysql is running, 0 if not, or -1 if running but
114 # inaccessible without a password. When called in an array context, also
115 # returns the full error message
116 sub is_mysql_running
117 {
118 # First type regular connection
119 if ($driver_handle && !$config{'nodbi'}) {
120         local $main::error_must_die = 1;
121         local ($data, $rv);
122         eval { $data = &execute_sql_safe(undef, "select version()") };
123         local $err = $@;
124         $err =~ s/\s+at\s+\S+\s+line.*$//;
125         if ($@ =~ /denied|password/i) {
126                 $rv = -1;
127                 }
128         elsif ($@ =~ /connect/i) {
129                 $rv = 0;
130                 }
131         elsif ($data->{'data'}->[0]->[0] =~ /^\d/) {
132                 $rv = 1;
133                 }
134         if (defined($rv)) {
135                 return wantarray ? ( $rv, $err ) : $rv;
136                 }
137         }
138
139 # Fall back to mysqladmin command
140 local $out = `"$config{'mysqladmin'}" $authstr status 2>&1`;
141 local $rv = $out =~ /uptime/i ? 1 :
142             $out =~ /denied|password/i ? -1 : 0;
143 $out =~ s/^.*\Q$config{'mysqladmin'}\E\s*:\s*//;
144 return wantarray ? ($rv, $out) : $rv;
145 }
146
147 # list_databases()
148 # Returns a list of all databases
149 sub list_databases
150 {
151 local @rv;
152 eval {
153         # First try using SQL
154         local $main::error_must_die = 1;
155         local $t = &execute_sql_safe($master_db, "show databases");
156         @rv = map { $_->[0] } @{$t->{'data'}};
157         };
158 if (!@rv || $@) {
159         # Fall back to mysqlshow command
160         open(DBS, "\"$config{'mysqlshow'}\" $authstr |");
161         local $t = &parse_mysql_table(DBS);
162         close(DBS);
163         ref($t) || &error("Failed to list databases : $t");
164         @rv = map { $_->[0] } @{$t->{'data'}};
165         }
166 return sort { lc($a) cmp lc($b) } @rv;
167 }
168
169 # list_tables(database, [empty-if-denied], [no-filter-views])
170 # Returns a list of tables in some database
171 sub list_tables
172 {
173 my ($db, $empty_denied, $include_views) = @_;
174 my @rv;
175 eval {
176         # First try using SQL
177         local $main::error_must_die = 1;
178         local $t = &execute_sql_safe($db, "show tables");
179         @rv = map { $_->[0] } @{$t->{'data'}};
180         };
181 if ($@) {
182         # Fall back to mysqlshow command
183         local $tspec = $db =~ /_/ ? "%" : "";
184         open(DBS, "\"$config{'mysqlshow'}\" $authstr ".
185                   quotemeta($db)." $tspec 2>&1 |");
186         local $t = &parse_mysql_table(DBS);
187         close(DBS);
188         if ($t =~ /access denied/i) {
189                 if ($empty_denied) {
190                         return ( );
191                         }
192                 else {
193                         &error($text{'edenied'});
194                         }
195                 }
196         elsif (!ref($t)) {
197                 &error("<tt>".&html_escape($t)."</tt>");
198                 }
199         @rv = map { $_->[0] } @{$t->{'data'}};
200         }
201
202 # Filter out views
203 if (!$include_views) {
204         if (&supports_views()) {
205                 my %views = map { $_, 1 } &list_views($db);
206                 @rv = grep { !$views{$_} } @rv;
207                 }
208         }
209 return @rv;
210 }
211
212 # table_structure(database, table)
213 # Returns a list of hashes detailing the structure of a table
214 sub table_structure
215 {
216 local $s = &execute_sql_safe($_[0], "desc ".&quotestr($_[1]));
217 local (@rv, $r);
218 local (%tp, $i);
219 for($i=0; $i<@{$s->{'titles'}}; $i++) {
220         $tp{lc($s->{'titles'}->[$i])} = $i;
221         }
222 my $i = 0;
223 foreach $r (@{$s->{'data'}}) {
224         push(@rv, { 'field' => $r->[$tp{'field'}],
225                     'type' => $r->[$tp{'type'}],
226                     'null' => $r->[$tp{'null'}],
227                     'key' => $r->[$tp{'key'}],
228                     'default' => $r->[$tp{'default'}],
229                     'extra' => $r->[$tp{'extra'}],
230                     'index' => $i++ });
231         }
232 return @rv;
233 }
234
235 # table_field_sizes(db, table)
236 # Returns a hash mapping field names to sizes
237 sub table_field_sizes
238 {
239 local %rv;
240 foreach my $s (&table_structure(@_)) {
241         if ($s->{'type'} =~ /^\S+\((\d+)(,\d+)?\)/) {
242                 $rv{lc($s->{'field'})} = $1;
243                 }
244         }
245 return %rv;
246 }
247
248 # execute_sql(database, command, [param, ...])
249 # Executes some SQL and returns the results, after checking for the user's
250 # readonly status.
251 sub execute_sql
252 {
253 return { } if (&is_readonly_mode());
254 return &execute_sql_safe(@_);
255 }
256
257 # execute_sql_safe(database, command, [param, ...])
258 # Executes some SQL and returns the results
259 sub execute_sql_safe
260 {
261 local $sql = $_[1];
262 @params = @_[2..$#_];
263 if ($gconfig{'debug_what_sql'}) {
264         # Write to Webmin debug log
265         local $params;
266         for(my $i=0; $i<@params; $i++) {
267                 $params .= " ".$i."=".$params[$i];
268                 }
269         &webmin_debug_log('SQL', "db=$_[0] sql=$sql".$params);
270         }
271 $sql =~ s/\\/\\\\/g;
272 if ($driver_handle && !$config{'nodbi'}) {
273         # Use the DBI interface
274         local $cstr = "database=$_[0]";
275         $cstr .= ";host=$config{'host'}" if ($config{'host'});
276         $cstr .= ";port=$config{'port'}" if ($config{'port'});
277         $cstr .= ";mysql_socket=$config{'sock'}" if ($config{'sock'});
278         $cstr .= ";mysql_read_default_file=$config{'my_cnf'}"
279                 if (-r $config{'my_cnf'});
280         local $dbh = $driver_handle->connect($cstr, $mysql_login, $mysql_pass,
281                                              { });
282         $dbh || &error("DBI connect failed : ",$driver_handle->errstr);
283         if ($sql_charset) {
284                 # Switch to correct character set
285                 local $sql = "set names '$sql_charset'";
286                 local $cmd = $dbh->prepare($sql);
287                 if (!$cmd) {
288                         &error(&text('esql', "<tt>".&html_escape($sql)."</tt>",
289                                      "<tt>".&html_escape($dbh->errstr)."</tt>"));
290                         }
291                 if (!$cmd->execute()) {
292                         &error(&text('esql', "<tt>".&html_escape($sql)."</tt>",
293                                      "<tt>".&html_escape($dbh->errstr)."</tt>"));
294                         }
295                 $cmd->finish();
296                 }
297         local $cmd = $dbh->prepare($sql);
298         if (!$cmd) {
299                 &error(&text('esql', "<tt>".&html_escape($_[1])."</tt>",
300                              "<tt>".&html_escape($dbh->errstr)."</tt>"));
301                 }
302         if (!$cmd->execute(@params)) {
303                 &error(&text('esql', "<tt>".&html_escape($_[1])."</tt>",
304                              "<tt>".&html_escape($dbh->errstr)."</tt>"));
305                 }
306         local (@data, @row);
307         local @titles = @{$cmd->{'NAME'}};
308         while(@row = $cmd->fetchrow()) {
309                 push(@data, [ @row ]);
310                 }
311         $cmd->finish();
312         $dbh->disconnect();
313         return { 'titles' => \@titles,
314                  'data' => \@data };
315         }
316 else {
317         # Use the mysql command program
318         local $temp = &transname();
319         if (@params) {
320                 # Sub in ? parameters
321                 $sql = &replace_sql_parameters($sql, @params);
322                 }
323         open(TEMP, ">$temp");
324         if ($sql_charset) {
325                 print TEMP "set names '$sql_charset';\n";
326                 }
327         print TEMP $sql,"\n";
328         close(TEMP);
329         open(DBS, "\"$config{'mysql'}\" $authstr -E -t ".quotemeta($_[0])." <$temp 2>&1 |");
330         local $t = &parse_mysql_vertical(DBS);
331         close(DBS);
332         unlink($temp);
333         if (!ref($t)) {
334                 $t =~ s/^ERROR[^:]*://;
335                 &error(&text('esql', "<tt>".&html_escape($_[1])."</tt>",
336                             "<tt>".&html_escape($t)."</tt>"));
337                 }
338         return $t;
339         }
340 }
341
342 # replace_sql_parameters(sql, params)
343 # Returns a string with ? replaced by parameter text
344 sub replace_sql_parameters
345 {
346 my ($sql, @params) = @_;
347 my $pos = -1;
348 foreach my $p (@params) {
349         $pos = index($sql, '?', $pos+1);
350         &error("Incorrect number of parameters") if ($pos < 0);
351         local $qp = $p;
352         $qp =~ s/'/''/g;
353         $qp = $qp eq '' ? 'NULL' : "'$qp'";
354         $sql = substr($sql, 0, $pos).$qp.substr($sql, $pos+1);
355         $pos += length($qp)-1;
356         }
357 return $sql;
358 }
359
360 # execute_sql_logged(database, command, param, ...)
361 # Calls execute_sql, but logs the command first
362 sub execute_sql_logged
363 {
364 local ($db, $sql, @params) = @_;
365 if (@params) {
366         eval {
367                 local $main::error_must_die = 1;
368                 $sql = &replace_sql_parameters($sql, @params);
369                 }
370         }
371 &additional_log('sql', $db, $sql);
372 return &execute_sql(@_);
373 }
374
375 # parse_mysql_table(handle)
376 # Given a filehandle, parses a text table in the format mysql uses
377 sub parse_mysql_table
378 {
379 local $fh = $_[0];
380 local ($line, $i, @edge);
381 do {
382         # skip to table top
383         $line = <$fh>;
384         return $line if ($line =~ /^(ERROR|\S*mysqlshow:)/);
385         } while($line && $line !~ /^\+/);
386 for($i=0; $i<length($line); $i++) {
387         push(@edge, $i) if (substr($line, $i, 1) eq '+');
388         }
389 $line = <$fh>;          # skip first row of -'s
390 local @titles = &parse_mysql_line($line, \@edge);
391 $line = <$fh>;          # skip next row of -'s
392 local @data;
393 while(1) {
394         $line = <$fh>;
395         last if (!$line || $line !~ /^\|/);
396         while($line !~ /\|\s+$/) {
397                 # Line has a return in it!
398                 $line .= <$fh>;
399                 }
400         push(@data, [ &parse_mysql_line($line, \@edge) ]);
401         }
402 return { 'titles' => \@titles,
403          'data' => \@data };
404 }
405
406 # parse_mysql_line(line, &edges)
407 sub parse_mysql_line
408 {
409 local @rv;
410 for($i=0; $i<@{$_[1]}-1; $i++) {
411         local $w = substr($_[0], $_[1]->[$i]+1,
412                           $_[1]->[$i+1] - $_[1]->[$i] - 2);
413         $w =~ s/^\s//;
414         $w =~ s/\s+$//;
415         $w =~ s/\\/\\\\/g;
416         $w =~ s/\n/\\n/g;
417         push(@rv, $w);
418         }
419 return @rv;
420 }
421
422 # parse_mysql_vertical(handle)
423 # Parses mysql output in the -E format
424 sub parse_mysql_vertical
425 {
426 local (@data, @titles, $row = -1, $col, %hascol);
427 local $fh = $_[0];
428 local $line = <$fh>;
429 if (!$line) {
430         # No output at all - must be a non-select
431         return { };
432         }
433 return $line if ($line =~ /^ERROR/);
434 local $errtxt = &text('eparse', "<tt>mysql</tt>", "<tt>DBI</tt>",
435                       "<tt>DBD::mysql</tt>");
436 while($line) {
437         $line =~ s/\r|\n//g;
438         if ($line =~ /^\*\*\*/) {
439                 # A row header
440                 $row++;
441                 $col = -1;
442                 $data[$row] = [ ];
443                 }
444         elsif ($line =~ /^\s*([^:\s]+): (.*)/ && ($row == 0 || $hascol{$1})) {
445                 # A new column
446                 $col++;
447                 $titles[$col] = $1;
448                 $row >= 0 || return $errtxt;
449                 $data[$row]->[$col] = $2;
450                 $hascol{$1}++;
451                 }
452         else {
453                 # Continuing the last column
454                 $row >= 0 || return $errtxt;
455                 $data[$row]->[$col] .= "\n".$line;
456                 }
457         $line = <$fh>;
458         }
459 return { 'titles' => \@titles,
460          'data' => \@data };
461 }
462
463 sub can_edit_db
464 {
465 if ($module_info{'usermin'}) {
466         foreach $l (split(/\t/, $config{'access'})) {
467                 if ($l =~ /^(\S+):\s*(.*)$/ &&
468                     ($1 eq $remote_user || $1 eq '*')) {
469                         local @dbs = split(/\s+/, $2);
470                         local $d;
471                         foreach $d (@dbs) {
472                                 $d =~ s/\$REMOTE_USER/$remote_user/g;
473                                 return 1 if ($d eq '*' || $_[0] =~ /^$d$/);
474                                 }
475                         return 0;
476                         }
477                 }
478         return 0;
479         }
480 else {
481         local $d;
482         return 1 if ($access{'dbs'} eq '*');
483         foreach $d (split(/\s+/, $access{'dbs'})) {
484                 return 1 if ($d && $d eq $_[0]);
485                 }
486         return 0;
487         }
488 }
489
490 # supports_backup_db(name)
491 # Returns 1 if some database can be backed up
492 sub supports_backup_db
493 {
494 return $_[0] ne "information_schema" &&
495        $_[0] ne "performance_schema";
496 }
497
498 # list_accessible_databases()
499 # Returns a list of databases that the current user may access to. Returns
500 # an empty list if he has all of them.
501 sub list_accessible_databases
502 {
503 if ($module_info{'usermin'}) {
504         # From Usermin list
505         local @rv;
506         foreach $l (split(/\t/, $config{'access'})) {
507                 if ($l =~ /^(\S+):\s*(.*)$/ &&
508                     ($1 eq $remote_user || $1 eq '*')) {
509                         push(@rv, split(/\s+/, $2));
510                         }
511                 }
512         return @rv;
513         }
514 else {
515         # From Webmin access control list
516         return ( ) if ($access{'dbs'} eq '*');
517         return split(/\s+/, $access{'dbs'});
518         }
519 }
520
521 # split_table(&titles, &checkboxes, &links, &col1, &col2, ...)
522 # Outputs a table that is split into two parts
523 sub split_table
524 {
525 local $mid = int((@{$_[2]}+1) / 2);
526 local ($i, $j);
527 print "<table width=100%><tr>\n";
528 foreach $s ([0, $mid-1], [$mid, @{$_[2]}-1]) {
529         print "<td width=50% valign=top>\n";
530
531         # Header
532         local @tds = $_[1] ? ( "width=5" ) : ( );
533         if ($s->[0] <= $s->[1]) {
534                 local @hcols;
535                 foreach $t (@{$_[0]}) {
536                         push(@hcols, $t);
537                         }
538                 print &ui_columns_start(\@hcols, 100, 0, \@tds);
539                 }
540
541         for($i=$s->[0]; $i<=$s->[1]; $i++) {
542                 local @cols;
543                 push(@cols, "<a href='$_[2]->[$i]'>$_[3]->[$i]</a>");
544                 for($j=4; $j<@_; $j++) {
545                         push(@cols, $_[$j]->[$i]);
546                         }
547                 if ($_[1]) {
548                         print &ui_checked_columns_row(\@cols, \@tds, "d", $_[1]->[$i]);
549                         }
550                 else {
551                         print &ui_columns_row(\@cols, \@tds);
552                         }
553                 }
554         if ($s->[0] <= $s->[1]) {
555                 print &ui_columns_end();
556                 }
557         print "</td>\n";
558         }
559 print "</tr></table>\n";
560 }
561
562 # select_db(db)
563 sub select_db
564 {
565 local $rv;
566 local @dbs = &list_databases();
567 local $d;
568 if ($access{'perms'} == 2 && $access{'dbs'} ne '*') {
569         # Can only select his own databases
570         $rv = &ui_select("dbs", $_[0],
571                          [ grep { &can_edit_db($_) } @dbs ], 1, 0, $_[0] ? 1 : 0);
572         }
573 else {
574         # Can select any databases
575         local $ind = &indexof($_[0],@dbs) >= 0;
576         $rv = &ui_radio("db_def", $_[0] eq '%' || $_[0] eq '' ? 1 :
577                                   $ind ? 2 : 0,
578                         [ [ 1, $text{'host_any'} ],
579                           [ 2, $text{'host_sel'}."&nbsp;".
580                                &ui_select("dbs", $_[0], \@dbs) ],
581                           [ 0, $text{'host_otherdb'}."&nbsp;".
582                                &ui_textbox("db", $_[0] eq '%' || $_[0] eq '' ||
583                                                  $ind ? '' : $_[0], 30) ] ]);
584         }
585 return $rv;
586 }
587
588 sub quote_table
589 {
590 return &quotestr($_[0]);
591 }
592
593 # quotestr(string)
594 sub quotestr
595 {
596 local $rv = $_[0];
597 if (&supports_quoting()) {
598         return "`$rv`";
599         }
600 else {
601         return $rv;
602         }
603 }
604
605 # escapestr(string)
606 # Returns a string with quotes escaped, for use in SQL
607 sub escapestr
608 {
609 local $rv = $_[0];
610 $rv =~ s/'/''/g;
611 return $rv;
612 }
613
614 # supports_quoting()
615 # Returns 1 if running mysql version 3.23.6 or later
616 sub supports_quoting
617 {
618 if ($mysql_version =~ /^(\d+)\.(\d+)\.(\d+)$/ &&
619     ($1 > 3 || ($1 == 3 && $2 > 23) || ($1 == 3 && $2 == 23 && $3 >= 6))) {
620         return 1;
621         }
622 elsif ($mysql_version > 4) {
623         return 1;
624         }
625 else {
626         return 0;
627         }
628 }
629
630 # supports_routines()
631 # Returns 1 if mysqldump supports routines
632 sub supports_routines
633 {
634 local $out = &backquote_command("$config{'mysqldump'} --help 2>&1 </dev/null");
635 return $out =~ /--routines/ ? 1 : 0;
636 }
637
638 # supports_views()
639 # Returns 1 if this MySQL install supports views
640 sub supports_views
641 {
642 if (!defined($supports_views_cache)) {
643         if ($mysql_version < 5) {
644                 $supports_views_cache = 0;
645                 }
646         else {
647                 local @dbs = &list_databases();
648                 if (&indexof("information_schema", @dbs) >= 0) {
649                         # Has information_schema DB .. but does it have views?
650                         local @ist = &list_tables("information_schema", 1, 1);
651                         if (&indexoflc("views", @ist) >= 0) {
652                                 $supports_views_cache = 1;
653                                 }
654                         else {
655                                 $supports_views_cache = 0;
656                                 }
657                         }
658                 else {
659                         $supports_views_cache = 0;
660                         }
661                 }
662         }
663 return $supports_views_cache;
664 }
665
666 # supports_variables()
667 # Returns 1 if running mysql version 4.0.3 or later
668 sub supports_variables
669 {
670 if ($mysql_version =~ /^(\d+)\.(\d+)\.(\d+)$/ &&
671     ($1 > 4 || ($1 == 4 && $2 > 0) || ($1 == 4 && $2 == 0 && $3 >= 3))) {
672         return 1;
673         }
674 elsif ($mysql_version > 4) {
675         return 1;
676         }
677 else {
678         return 0;
679         }
680 }
681
682 # supports_env_pass()
683 # Returns 1 if passing the password via an environment variable is supported
684 sub supports_env_pass
685 {
686 if ($mysql_version >= 4.1 && !$config{'nopwd'}) {
687         # Theortically possible .. but don't do this if ~/.my.cnf contains
688         # a [client] block with password= in it
689         my @uinfo = getpwuid($<);
690         foreach my $cf ($config{'my_cnf'}, "$uinfo[7]/.my.cnf",
691                         "$ENV{'HOME'}/.my.cnf") {
692                 next if (!$cf || !-r $cf);
693                 local @cf = &parse_mysql_config($cf);
694                 local $client = &find("client", \@cf);
695                 next if (!$client);
696                 local $password = &find("password", $client->{'members'});
697                 return 0 if ($password ne '');
698                 }
699         return 1;
700         }
701 return 0;
702 }
703
704 # working_env_pass()
705 # Returns 1 if MYSQL_PWD can be used to pass the password to mysql
706 sub working_env_pass
707 {
708 return 1 if (!&supports_env_pass());    # Not even used
709 local $config{'nodbi'} = 1;
710 local $data;
711 local $main::error_must_die = 1;
712 eval { $data = &execute_sql_safe(undef, "select version()") };
713 return $@ || !$data ? 0 : 1;
714 }
715
716 # user_priv_cols()
717 # Returns the number of columns used for privileges in the user table
718 sub user_priv_cols
719 {
720 if (!$user_priv_cols) {
721         local @str = &table_structure("mysql", "user");
722         local $s;
723         foreach $s (@str) {
724                 $user_priv_cols++ if ($s->{'field'} =~ /_priv/i);
725                 }
726         }
727 return $user_priv_cols;
728 }
729
730 # db_priv_cols()
731 # Returns the number of columns used for privileges in the db table
732 sub db_priv_cols
733 {
734 if (!$db_priv_cols) {
735         local @str = &table_structure("mysql", "db");
736         local $s;
737         foreach $s (@str) {
738                 $db_priv_cols++ if ($s->{'field'} =~ /_priv/i);
739                 }
740         }
741 return $db_priv_cols;
742 }
743
744 # host_priv_cols()
745 # Returns the number of columns used for privileges in the db table
746 sub host_priv_cols
747 {
748 if (!$host_priv_cols) {
749         local @str = &table_structure("mysql", "host");
750         local $s;
751         foreach $s (@str) {
752                 $host_priv_cols++ if ($s->{'field'} =~ /_priv/i);
753                 }
754         }
755 return $host_priv_cols;
756 }
757
758 sub is_blob
759 {
760 return $_[0]->{'type'} =~ /(text|blob)$/i;
761 }
762
763 # get_mysql_version(&out)
764 # Returns a version number, undef if one cannot be found, or -1 for a .so
765 # problem
766 sub get_mysql_version
767 {
768 local $out = &backquote_command("\"$config{'mysql'}\" -V 2>&1");
769 ${$_[0]} = $out if ($_[0]);
770 if ($out =~ /lib\S+\.so/) {
771         return -1;
772         }
773 elsif ($out =~ /distrib\s+((3|4|5|6)\.[0-9\.]*)/i) {
774         return $1;
775         }
776 else {
777         return undef;
778         }
779 }
780
781 # date_subs(filename)
782 # Does strftime-style date substitutions on a filename, if enabled
783 sub date_subs
784 {
785 if ($config{'date_subs'}) {
786         eval "use POSIX";
787         eval "use posix" if ($@);
788         local @tm = localtime(time());
789         &clear_time_locale();
790         local $rv = strftime($_[0], @tm);
791         &reset_time_locale();
792         return $rv;
793         }
794 else {
795         return $_[0];
796         }
797 }
798
799 # execute_before(db, handle, escape, path, db-for-config)
800 # Executes the before-backup command for some DB, and sends output to the
801 # given file handle. Returns 1 if the command suceeds, or 0 on failure
802 sub execute_before
803 {
804 local $cmd = $config{'backup_before_'.$_[4]};
805 if ($cmd) {
806         $ENV{'BACKUP_FILE'} = $_[3];
807         local $h = $_[1];
808         local $out;
809         local $rv = &execute_command($cmd, undef, \$out, \$out);
810         if ($h && $out) {
811                 print $h $_[2] ? "<pre>".&html_escape($out)."</pre>" : $out;
812                 }
813         return !$rv;
814         }
815 return 1;
816 }
817
818 # execute_after(db, handle, escape, path, db-for-config)
819 sub execute_after
820 {
821 local $cmd = $config{'backup_after_'.$_[4]};
822 if ($cmd) {
823         $ENV{'BACKUP_FILE'} = $_[3];
824         local $h = $_[1];
825         local $out;
826         local $rv = &execute_command($cmd, undef, \$out, \$out);
827         if ($h && $out) {
828                 print $h $_[2] ? "<pre>".&html_escape($out)."</pre>" : $out;
829                 }
830         return !$rv;
831         }
832 return 1;
833 }
834
835 # show_table_form(count)
836 sub show_table_form
837 {
838 print &ui_columns_start([ $text{'field_name'}, $text{'field_type'},
839                           $text{'field_size'}, $text{'table_nkey'},
840                           $text{'field_auto'}, $text{'field_null'},
841                           $text{'field_unsigned'}, $text{'field_default'} ]);
842 local $i;
843 for($i=0; $i<$_[0]; $i++) {
844         local @cols;
845         push(@cols, &ui_textbox("field_$i", undef, 20));
846         push(@cols, &ui_select("type_$i", "", [ "", @type_list ]));
847         push(@cols, &ui_textbox("size_$i", undef, 10));
848         push(@cols, &ui_checkbox("key_$i", 1, $text{'yes'}, 0));
849         push(@cols, &ui_checkbox("auto_$i", 1, $text{'yes'}, 0));
850         push(@cols, &ui_checkbox("null_$i", 1, $text{'yes'}, 1));
851         push(@cols, &ui_checkbox("unsigned_$i", 1, $text{'yes'}, 0));
852         push(@cols, &ui_textbox("default_$i", undef, 20));
853         print &ui_columns_row(\@cols);
854         }
855 print &ui_columns_end();
856 }
857
858 # parse_table_form(&extrafields, tablename)
859 sub parse_table_form
860 {
861 local @fields = @{$_[0]};
862 local $i;
863 local (@auto, @pri);
864 for($i=0; defined($in{"field_$i"}); $i++) {
865         next if (!$in{"field_$i"});
866         $in{"field_$i"} =~ /^\S+$/ ||
867                 &error(&text('table_efield', $in{"field_$i"}));
868         $in{"type_$i"} || &error(&text('table_etype', $in{"field_$i"}));
869         if ($in{"type_$i"} eq 'enum' || $in{"type_$i"} eq 'set') {
870                 local @ev = split(/\s+/, $in{"size_$i"});
871                 @ev || &error(&text('table_eenum', $in{"type_$i"},
872                                                    $in{"field_$i"}));
873                 $in{"size_$i"} = join(",", map { "'$_'" } @ev);
874                 }
875         if ($in{"size_$i"}) {
876                 push(@fields, sprintf "%s %s(%s)",
877                      &quotestr($in{"field_$i"}), $in{"type_$i"},$in{"size_$i"});
878                 }
879         else {
880                 push(@fields, sprintf "%s %s",
881                         &quotestr($in{"field_$i"}), $in{"type_$i"});
882                 }
883         if ($in{"unsigned_$i"}) {
884                 $fields[@fields-1] .= " unsigned";
885                 }
886         if (!$in{"null_$i"}) {
887                 $fields[@fields-1] .= " not null";
888                 }
889         if ($in{"key_$i"}) {
890                 $in{"null_$i"} && &error(&text('table_epnull',$in{"field_$i"}));
891                 push(@pri, $in{"field_$i"});
892                 }
893         if ($in{"auto_$i"}) {
894                 push(@auto, $fields[@fields-1]);
895                 push(@autokey, $in{"key_$i"});
896                 }
897         if ($in{"default_$i"}) {
898                 $fields[@fields-1] .= " default '".$in{"default_$i"}."'";
899                 }
900         }
901 @auto < 2 || &error($text{'table_eauto'});
902 @fields || &error($text{'table_enone'});
903 local @sql;
904 local $sql = "create table ".&quotestr($_[1])." (".join(",", @fields).")";
905 $sql .= " type = $in{'type'}" if ($in{'type'});
906 push(@sql, $sql);
907 if (@pri) {
908         # Setup primary fields too
909         push(@sql, "alter table ".&quotestr($_[1])." add primary key (".
910                     join(",", map { &quotestr($_) } @pri).")");
911         }
912 if (@auto) {
913         # Make field auto-increment
914         push(@sql, "alter table ".&quotestr($_[1]).
915                    " modify $auto[0] auto_increment ".
916                    ($autokey[0] ? "" : "unique"));
917         }
918 return @sql;
919 }
920
921 # execute_sql_file(database, file, [user, pass], [unix-user])
922 # Executes some file of SQL commands, and returns the exit status and output
923 sub execute_sql_file
924 {
925 if (&is_readonly_mode()) {
926         return (0, undef);
927         }
928 local ($db, $file, $user, $pass) = @_;
929 local $authstr = &make_authstr($user, $pass);
930 local $cmd = "$config{'mysql'} $authstr -t ".quotemeta($db)." <".quotemeta($file);
931 -r $file || return (1, "$file does not exist");
932 if ($_[4] && $_[4] ne 'root' && $< == 0) {
933         # Restoring as a Unix user
934         $cmd = &command_as_user($_[4], 0, $cmd);
935         }
936 local $out = &backquote_logged("$cmd 2>&1");
937 local @rv = ($?, $? ? $out || "$cmd failed" : $out);
938 &make_authstr();        # Put back old password environment variable
939 return @rv;
940 }
941
942 # start_mysql()
943 # Starts the MySQL database server, and returns undef on success or an
944 # error message on failure.
945 sub start_mysql
946 {
947 local $temp = &transname();
948 local $rv = &system_logged("($config{'start_cmd'}) >$temp 2>&1");
949 local $out = `cat $temp`; unlink($temp);
950 if ($rv || $out =~ /failed/i) {
951         return "<pre>$out</pre>";
952         }
953 return undef;
954 }
955
956 # stop_mysql()
957 # Halts the MySQL database server, and returns undef on success or an
958 # error message on failure.
959 sub stop_mysql
960 {
961 local $out;
962 if ($config{'stop_cmd'}) {
963         $out = &backquote_logged("$config{'stop_cmd'} 2>&1");
964         }
965 else {
966         $out = &backquote_logged("$config{'mysqladmin'} $authstr shutdown 2>&1");
967         }
968 if ($? || $out =~ /failed/i) {
969         return "<pre>$out</pre>";
970         }
971 return undef;
972 }
973
974 # split_enum(type)
975 # Returns a list of allowed values for an enum
976 sub split_enum
977 {
978 local ($type) = @_;
979 if ($type =~ /^(enum|set)\((.*)\)$/) {
980         $type = $2;
981         }
982 local $esize = $type;
983 local @ev;
984 while($esize =~ /^'([^']*)'(,?)(.*)$/) {
985         push(@ev, $1);
986         $esize = $3;
987         }
988 return @ev;
989 }
990
991 # Returns 1 if the mysql server being managed is on this system
992 sub is_mysql_local
993 {
994 return $config{'host'} eq '' || $config{'host'} eq 'localhost' ||
995        $config{'host'} eq &get_system_hostname() ||
996        &to_ipaddress($config{'host'}) eq &to_ipaddress(&get_system_hostname());
997 }
998
999 # get_mysql_config()
1000 # Returns the parsed my.cnf file
1001 sub get_mysql_config
1002 {
1003 if (!scalar(@mysql_config_cache)) {
1004         if (!-r $config{'my_cnf'}) {
1005                 return undef;
1006                 }
1007         @mysql_config_cache = &parse_mysql_config($config{'my_cnf'});
1008         }
1009 return \@mysql_config_cache;
1010 }
1011
1012 # parse_mysql_config(file)
1013 # Reads one MySQL config file
1014 sub parse_mysql_config
1015 {
1016 local ($file) = @_;
1017 local @rv;
1018 local $sect;
1019 local $lnum = 0;
1020 local $lref = &read_file_lines($file, 1);
1021 local $_;
1022 foreach (@$lref) {
1023         s/\r|\n//g;
1024         s/#.*$//;
1025         s/\s+$//;
1026         if (/^\s*\[(\S+)\]$/) {
1027                 # Start of a section
1028                 $sect = { 'name' => $1,
1029                           'members' => [ ],
1030                           'file' => $file,
1031                           'line' => $lnum,
1032                           'eline' => $lnum };
1033                 push(@rv, $sect);
1034                 }
1035         elsif (/^\s*(\S+)\s*=\s*(.*)$/ && $sect) {
1036                 # Variable in a section
1037                 push(@{$sect->{'members'}},
1038                      { 'name' => $1,
1039                        'value' => $2,
1040                        'file' => $file,
1041                        'line' => $lnum });
1042                 $sect->{'eline'} = $lnum;
1043                 }
1044         elsif (/^\s*(\S+)$/ && $sect) {
1045                 # Single directive in a section
1046                 push(@{$sect->{'members'}},
1047                      { 'name' => $1,
1048                        'file' => $file,
1049                        'line' => $lnum });
1050                 $sect->{'eline'} = $lnum;
1051                 }
1052         $lnum++;
1053         }
1054 return @rv;
1055 }
1056
1057 # find(name, &conf)
1058 sub find
1059 {
1060 local ($name, $conf) = @_;
1061 local @rv = grep { lc($_->{'name'}) eq lc($name) } @$conf;
1062 return wantarray ? @rv : $rv[0];
1063 }
1064
1065 # find_value(name, &conf)
1066 sub find_value
1067 {
1068 local ($name, $conf) = @_;
1069 local @rv = map { $_->{'value'} } &find($name, $conf);
1070 return wantarray ? @rv : $rv[0];
1071 }
1072
1073 # save_directive(&conf, &section, name, &values)
1074 # Updates one or multiple lines in a my.cnf section
1075 sub save_directive
1076 {
1077 local ($conf, $sect, $name, $values) = @_;
1078 local @old = &find($name, $sect->{'members'});
1079 local $lref = &read_file_lines($config{'my_cnf'});
1080
1081 for(my $i=0; $i<@old || $i<@$values; $i++) {
1082         local $old = $old[$i];
1083         local $line = $values->[$i] eq "" ? $name :
1084                         "$name = $values->[$i]";
1085         if ($old && defined($values->[$i])) {
1086                 # Updating
1087                 $lref->[$old->{'line'}] = $line;
1088                 $old->{'value'} = $values->[$i];
1089                 }
1090         elsif (!$old && defined($values->[$i])) {
1091                 # Adding
1092                 splice(@$lref, $sect->{'eline'}+1, 0, $line);
1093                 &renumber($conf, $sect->{'eline'}+1, 1);
1094                 push(@{$sect->{'members'}},
1095                         { 'name' => $name,
1096                           'value' => $values->[$i],
1097                           'line' => $sect->{'eline'}+1 });
1098                 }
1099         elsif ($old && !defined($values->[$i])) {
1100                 # Deleting
1101                 splice(@$lref, $old->{'line'}, 1);
1102                 &renumber($conf, $old->{'line'}, -1);
1103                 @{$sect->{'members'}} = grep { $_ ne $old }
1104                                              @{$sect->{'members'}};
1105                 }
1106         }
1107 }
1108
1109 sub renumber
1110 {
1111 local ($conf, $line, $offset) = @_;
1112 foreach my $sect (@$conf) {
1113         $sect->{'line'} += $offset if ($sect->{'line'} >= $line);
1114         $sect->{'eline'} += $offset if ($sect->{'eline'} >= $line);
1115         foreach my $m (@{$sect->{'members'}}) {
1116                 $m->{'line'} += $offset if ($m->{'line'} >= $line);
1117                 }
1118         }
1119 }
1120
1121 # parse_set_variables(value, ...)
1122 # Returns a hash of variable mappings
1123 sub parse_set_variables
1124 {
1125 local %vars;
1126 foreach my $v (@_) {
1127         if ($v =~ /^(\S+)=(\S+)$/) {
1128                 $vars{$1} = $2;
1129                 }
1130         }
1131 return %vars;
1132 }
1133
1134 sub mysql_size_input
1135 {
1136 local ($name, $value) = @_;
1137 local $units;
1138 if ($value =~ /^(\d+)([a-z])$/i) {
1139         $value = $1;
1140         $units = $2;
1141         }
1142 $units = "" if ($units eq "b");
1143 return &ui_textbox($name, $value, 8)."\n".
1144        &ui_select($name."_units", $units,
1145                   [ [ "", "bytes" ], [ "K", "kB" ],
1146                     [ "M", "MB" ], [ "G", "GB" ] ]);
1147 }
1148
1149 # list_indexes(db)
1150 # Returns the names of all indexes in some database
1151 sub list_indexes
1152 {
1153 local ($db) = @_;
1154 local (@rv, $r);
1155 foreach my $table (&list_tables($db)) {
1156         local $s = &execute_sql_safe($db, "show index from ".&quotestr($table));
1157         local (%tp, $i);
1158         for($i=0; $i<@{$s->{'titles'}}; $i++) {
1159                 $tp{lc($s->{'titles'}->[$i])} = $i;
1160                 }
1161         foreach $r (@{$s->{'data'}}) {
1162                 if ($r->[$tp{'key_name'}] ne 'PRIMARY') {
1163                         push(@rv, $r->[$tp{'key_name'}]);
1164                         }
1165                 }
1166         }
1167 return &unique(@rv);
1168 }
1169
1170 # index_structure(db, indexname)
1171 # Returns information on an index
1172 sub index_structure
1173 {
1174 local ($db, $index) = @_;
1175 local (@rv, $r);
1176 local $info;
1177 foreach my $table (&list_tables($db)) {
1178         local $s = &execute_sql_safe($db, "show index from ".&quotestr($table));
1179         local (%tp, $i);
1180         for($i=0; $i<@{$s->{'titles'}}; $i++) {
1181                 $tp{lc($s->{'titles'}->[$i])} = $i;
1182                 }
1183         foreach $r (@{$s->{'data'}}) {
1184                 if ($r->[$tp{'key_name'}] eq $index) {
1185                         # Found some info
1186                         $info->{'table'} = $r->[$tp{'table'}];
1187                         $info->{'name'} = $index;
1188                         $info->{'type'} = lc($r->[$tp{'index_type'}]) ||
1189                                           lc($r->[$tp{'comment'}]);
1190                         push(@{$info->{'cols'}}, $r->[$tp{'column_name'}]);
1191                         }
1192                 }
1193         }
1194 return $info;
1195 }
1196
1197 # list_views(db)
1198 # Returns the names of all views in some database
1199 sub list_views
1200 {
1201 local ($db) = @_;
1202 local @rv;
1203 local $d = &execute_sql($db, "select table_schema,table_name from information_schema.views where table_schema = ?", $db);
1204 foreach $r (@{$d->{'data'}}) {
1205         push(@rv, $r->[1]);
1206         }
1207 return @rv;
1208 }
1209
1210 # view_structure(db, viewname)
1211 # Returns information about a view
1212 sub view_structure
1213 {
1214 local ($db, $view) = @_;
1215 local $info = { 'name' => $view };
1216 local $d = &execute_sql($db, "show create view $view");
1217 local $c = $d->{'data'}->[0]->[1];
1218 if ($c =~ /algorithm\s*=\s*(\S+)/i) {
1219         $info->{'algorithm'} = lc($1);
1220         }
1221 if ($c =~ /definer\s*=\s*`(\S+)`\@`(\S+)`/i) {
1222         $info->{'definer'} = "$1\@$2";
1223         }
1224 elsif ($c =~ /definer\s*=\s*(\S+)/i) {
1225         $info->{'definer'} = $1;
1226         }
1227 if ($c =~ /sql\s+security\s+(\S+)/i) {
1228         $info->{'security'} = lc($1);
1229         }
1230 if ($c =~ s/\s+with\s+(cascaded|local)\s+check\s+option//i) {
1231         $info->{'check'} = lc($1);
1232         }
1233 if ($c =~ /view\s+(`\S+`|\S+)\s+as\s+(.*)/i) {
1234         $info->{'query'} = $2;
1235         }
1236 return $info;
1237 }
1238
1239 # list_character_sets([db])
1240 # Returns a list of supported character sets. Each row is an array ref of
1241 # a code and name
1242 sub list_character_sets
1243 {
1244 local @rv;
1245 local $db = $_[0] || $master_db;
1246 if ($mysql_version < 4.1) {
1247         local $d = &execute_sql($db, "show variables like 'character_sets'");
1248         @rv = map { [ $_, $_ ] } split(/\s+/, $d->{'data'}->[0]->[1]);
1249         }
1250 else {
1251         local $d = &execute_sql($db, "show character set");
1252         @rv = map { [ $_->[0], $_->[1] ] } @{$d->{'data'}};
1253         }
1254 return sort { lc($a->[1]) cmp lc($b->[1]) } @rv;
1255 }
1256
1257 # list_collation_orders([db])
1258 # Returns a list of supported collation orders. Each row is an array ref of
1259 # a code and character set it can work with.
1260 sub list_collation_orders
1261 {
1262 local @rv;
1263 local $db = $_[0] || $master_db;
1264 if ($mysql_version >= 5) {
1265         local $d = &execute_sql($db, "show collation");
1266         @rv = map { [ $_->[0], $_->[1] ] } @{$d->{'data'}};
1267         }
1268 return sort { lc($a->[0]) cmp lc($b->[0]) } @rv;
1269 }
1270
1271 # list_system_variables()
1272 # Returns a list of all system variables, and their default values
1273 sub list_system_variables
1274 {
1275 local $mysqld = $config{'mysqld'};
1276 if (!$mysqld) {
1277         # Mysqld path not in config .. guess from mysql path
1278         $mysqld = $config{'mysql'};
1279         $mysqld =~ s/mysql$/mysqld/g;
1280         $mysqld =~ s/bin/sbin/g;
1281         if (!-x $mysqld) {
1282                 $mysqld = $config{'mysql'};
1283                 $mysqld =~ s/mysql$/mysqld/g;
1284                 $mysqld =~ s/bin/libexec/g;
1285                 if (!-x $mysqld) {
1286                         # Look in Webmin path
1287                         &error($mysqld);
1288                         $mysqld = &has_command("mysqld");
1289                         }
1290                 }
1291         }
1292 return ( ) if (!$mysqld);
1293
1294 # Read supported variables
1295 local @rv;
1296 &open_execute_command(MYSQLD, "$mysqld --verbose --help", 1, 1);
1297 while(<MYSQLD>) {
1298         s/\r|\n//g;
1299         if (/^(\S+)\s+current\s+value:\s+(\S*)/) {
1300                 push(@rv, [ $1, $2 ]);
1301                 }
1302         elsif (/^\-\-\-\-/) {
1303                 $started = 1;
1304                 }
1305         elsif ($started && /^(\S+)\s+(.*)/) {
1306                 push(@rv, [ $1, $2 eq "(No default value)" ? undef : $2 ]);
1307                 }
1308         }
1309 close(MYSQL);
1310 return @rv;
1311 }
1312
1313 # list_compatible_formats()
1314 # Returns a list of two-element arrays, containing compatability format
1315 # codes and descriptions
1316 sub list_compatible_formats
1317 {
1318 return map { [ $_, $text{'compat_'.$_} ] }
1319            ( "ansi", "mysql323", "mysql40", "postgresql", "oracle", "mssql",
1320              "db2", "maxdb" );
1321 }
1322
1323 # list_compatible_options()
1324 # Returns a list of two-element arrays, containing compatability options
1325 sub list_compatible_options
1326 {
1327 return map { [ $_, $text{'compat_'.$_} ] }
1328            ( "no_key_options", "no_table_options", "no_field_options" );
1329 }
1330
1331 # compression_format(file)
1332 # Returns 0 if uncompressed, 1 for gzip, 2 for compress, 3 for bzip2 or
1333 # 4 for zip
1334 sub compression_format
1335 {
1336 open(BACKUP, $_[0]);
1337 local $two;
1338 read(BACKUP, $two, 2);
1339 close(BACKUP);
1340 return $two eq "\037\213" ? 1 :
1341        $two eq "\037\235" ? 2 :
1342        $two eq "PK" ? 4 :
1343        $two eq "BZ" ? 3 : 0;
1344 }
1345
1346 # backup_database(db, dest-file, compress-mode, drop-flag, where-clause,
1347 #                 charset, &compatible, &only-tables, run-as-user,
1348 #                 single-transaction-flag)
1349 # Backs up a database to the given file, optionally with compression. Returns
1350 # undef on success, or an error message on failure.
1351 sub backup_database
1352 {
1353 local ($db, $file, $compress, $drop, $where, $charset, $compatible,
1354        $tables, $user, $single) = @_;
1355 if ($compress == 0) {
1356         $writer = ">".quotemeta($file);
1357         }
1358 elsif ($compress == 1) {
1359         $writer = "| gzip -c >".quotemeta($file);
1360         }
1361 elsif ($compress == 2) {
1362         $writer = "| bzip2 -c >".quotemeta($file);
1363         }
1364 local $dropsql = $drop ? "--add-drop-table" : "";
1365 local $singlesql = $single ? "--single-transaction" : "";
1366 local $wheresql = $where ? "\"--where=$in{'where'}\"" : "";
1367 local $charsetsql = $charset ?
1368         "--default-character-set=".quotemeta($charset) : "";
1369 local $compatiblesql = @$compatible ?
1370         "--compatible=".join(",", @$compatible) : "";
1371 local $quotingsql = &supports_quoting() ? "--quote-names" : "";
1372 local $routinessql = &supports_routines() ? "--routines" : "";
1373 local $tablessql = join(" ", map { quotemeta($_) } @$tables);
1374 local $cmd = "$config{'mysqldump'} $authstr $dropsql $singlesql $wheresql $charsetsql $compatiblesql $quotingsql $routinessql ".quotemeta($db)." $tablessql 2>&1 $writer";
1375 if ($user && $user ne "root") {
1376         $cmd = &command_as_user($user, undef, $cmd);
1377         }
1378 local $out = &backquote_logged("($cmd) 2>&1");
1379 if ($? || $out) {
1380         return $out;
1381         }
1382 return undef;
1383 }
1384
1385 1;
1386