Translation update done using Pootle.
[phpmyadmin-themes.git] / libraries / import.lib.php
blob8ef38f65505a33ef7ef9fcbb5a6ed01405eb3b25
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Library that provides common import functions that are used by import plugins
6 * @package phpMyAdmin
7 */
8 if (! defined('PHPMYADMIN')) {
9 exit;
12 /**
13 * We need to know something about user
15 require_once './libraries/check_user_privileges.lib.php';
17 /**
18 * We do this check, DROP DATABASE does not need to be confirmed elsewhere
20 define('PMA_CHK_DROP', 1);
22 /**
23 * Check whether timeout is getting close
25 * @return boolean true if timeout is close
26 * @access public
28 function PMA_checkTimeout()
30 global $timestamp, $maximum_time, $timeout_passed;
31 if ($maximum_time == 0) {
32 return FALSE;
33 } elseif ($timeout_passed) {
34 return TRUE;
35 /* 5 in next row might be too much */
36 } elseif ((time() - $timestamp) > ($maximum_time - 5)) {
37 $timeout_passed = TRUE;
38 return TRUE;
39 } else {
40 return FALSE;
44 /**
45 * Detects what compression filse uses
47 * @param string filename to check
48 * @return string MIME type of compression, none for none
49 * @access public
51 function PMA_detectCompression($filepath)
53 $file = @fopen($filepath, 'rb');
54 if (!$file) {
55 return FALSE;
57 $test = fread($file, 4);
58 $len = strlen($test);
59 fclose($file);
60 if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
61 return 'application/gzip';
63 if ($len >= 3 && substr($test, 0, 3) == 'BZh') {
64 return 'application/bzip2';
66 if ($len >= 4 && $test == "PK\003\004") {
67 return 'application/zip';
69 return 'none';
72 /**
73 * Runs query inside import buffer. This is needed to allow displaying
74 * of last SELECT, SHOW or HANDLER results and similar nice stuff.
76 * @uses $GLOBALS['finished'] read and write
77 * @param string query to run
78 * @param string query to display, this might be commented
79 * @param bool whether to use control user for queries
80 * @access public
82 function PMA_importRunQuery($sql = '', $full = '', $controluser = false)
84 global $import_run_buffer, $go_sql, $complete_query, $display_query,
85 $sql_query, $my_die, $error, $reload,
86 $last_query_with_results,
87 $skip_queries, $executed_queries, $max_sql_len, $read_multiply,
88 $cfg, $sql_query_disabled, $db, $run_query, $is_superuser;
89 $read_multiply = 1;
90 if (isset($import_run_buffer)) {
91 // Should we skip something?
92 if ($skip_queries > 0) {
93 $skip_queries--;
94 } else {
95 if (!empty($import_run_buffer['sql']) && trim($import_run_buffer['sql']) != '') {
96 $max_sql_len = max($max_sql_len, strlen($import_run_buffer['sql']));
97 if (!$sql_query_disabled) {
98 $sql_query .= $import_run_buffer['full'];
100 if (!$cfg['AllowUserDropDatabase']
101 && !$is_superuser
102 && preg_match('@^[[:space:]]*DROP[[:space:]]+(IF EXISTS[[:space:]]+)?DATABASE @i', $import_run_buffer['sql'])) {
103 $GLOBALS['message'] = PMA_Message::error(__('"DROP DATABASE" statements are disabled.'));
104 $error = TRUE;
105 } else {
106 $executed_queries++;
107 if ($run_query && $GLOBALS['finished'] && empty($sql) && !$error && (
108 (!empty($import_run_buffer['sql']) && preg_match('/^[\s]*(SELECT|SHOW|HANDLER)/i', $import_run_buffer['sql'])) ||
109 ($executed_queries == 1)
110 )) {
111 $go_sql = TRUE;
112 if (!$sql_query_disabled) {
113 $complete_query = $sql_query;
114 $display_query = $sql_query;
115 } else {
116 $complete_query = '';
117 $display_query = '';
119 $sql_query = $import_run_buffer['sql'];
120 } elseif ($run_query) {
121 if ($controluser) {
122 $result = PMA_query_as_controluser($import_run_buffer['sql']);
123 } else {
124 $result = PMA_DBI_try_query($import_run_buffer['sql']);
126 $msg = '# ';
127 if ($result === FALSE) { // execution failed
128 if (!isset($my_die)) {
129 $my_die = array();
131 $my_die[] = array('sql' => $import_run_buffer['full'], 'error' => PMA_DBI_getError());
133 if ($cfg['VerboseMultiSubmit']) {
134 $msg .= __('Error');
137 if (!$cfg['IgnoreMultiSubmitErrors']) {
138 $error = TRUE;
139 return;
141 } elseif ($cfg['VerboseMultiSubmit']) {
142 $a_num_rows = (int)@PMA_DBI_num_rows($result);
143 $a_aff_rows = (int)@PMA_DBI_affected_rows();
144 if ($a_num_rows > 0) {
145 $msg .= __('Rows'). ': ' . $a_num_rows;
146 $last_query_with_results = $import_run_buffer['sql'];
147 } elseif ($a_aff_rows > 0) {
148 $message = PMA_Message::affected_rows($a_aff_rows);
149 $msg .= $message->getMessage();
150 } else {
151 $msg .= __('MySQL returned an empty result set (i.e. zero rows).');
154 if (!$sql_query_disabled) {
155 $sql_query .= $msg . "\n";
158 // If a 'USE <db>' SQL-clause was found and the query succeeded, set our current $db to the new one
159 if ($result != FALSE && preg_match('@^[\s]*USE[[:space:]]*([\S]+)@i', $import_run_buffer['sql'], $match)) {
160 $db = trim($match[1]);
161 $db = trim($db,';'); // for example, USE abc;
162 $reload = TRUE;
165 if ($result != FALSE && preg_match('@^[\s]*(DROP|CREATE)[\s]+(IF EXISTS[[:space:]]+)?(TABLE|DATABASE)[[:space:]]+(.+)@im', $import_run_buffer['sql'])) {
166 $reload = TRUE;
168 } // end run query
169 } // end if not DROP DATABASE
170 } // end non empty query
171 elseif (!empty($import_run_buffer['full'])) {
172 if ($go_sql) {
173 $complete_query .= $import_run_buffer['full'];
174 $display_query .= $import_run_buffer['full'];
175 } else {
176 if (!$sql_query_disabled) {
177 $sql_query .= $import_run_buffer['full'];
181 // check length of query unless we decided to pass it to sql.php
182 // (if $run_query is false, we are just displaying so show
183 // the complete query in the textarea)
184 if (! $go_sql && $run_query) {
185 if ($cfg['VerboseMultiSubmit'] && ! empty($sql_query)) {
186 if (strlen($sql_query) > 50000 || $executed_queries > 50 || $max_sql_len > 1000) {
187 $sql_query = '';
188 $sql_query_disabled = TRUE;
190 } else {
191 if (strlen($sql_query) > 10000 || $executed_queries > 10 || $max_sql_len > 500) {
192 $sql_query = '';
193 $sql_query_disabled = TRUE;
197 } // end do query (no skip)
198 } // end buffer exists
200 // Do we have something to push into buffer?
201 if (!empty($sql) || !empty($full)) {
202 $import_run_buffer = array('sql' => $sql, 'full' => $full);
203 } else {
204 unset($GLOBALS['import_run_buffer']);
210 * Returns next part of imported file/buffer
212 * @uses $GLOBALS['offset'] read and write
213 * @uses $GLOBALS['import_file'] read only
214 * @uses $GLOBALS['import_text'] read and write
215 * @uses $GLOBALS['finished'] read and write
216 * @uses $GLOBALS['read_limit'] read only
217 * @param integer size of buffer to read (this is maximal size
218 * function will return)
219 * @return string part of file/buffer
220 * @access public
222 function PMA_importGetNextChunk($size = 32768)
224 global $compression, $import_handle, $charset_conversion, $charset_of_file,
225 $charset, $read_multiply;
227 // Add some progression while reading large amount of data
228 if ($read_multiply <= 8) {
229 $size *= $read_multiply;
230 } else {
231 $size *= 8;
233 $read_multiply++;
235 // We can not read too much
236 if ($size > $GLOBALS['read_limit']) {
237 $size = $GLOBALS['read_limit'];
240 if (PMA_checkTimeout()) {
241 return FALSE;
243 if ($GLOBALS['finished']) {
244 return TRUE;
247 if ($GLOBALS['import_file'] == 'none') {
248 // Well this is not yet supported and tested, but should return content of textarea
249 if (strlen($GLOBALS['import_text']) < $size) {
250 $GLOBALS['finished'] = TRUE;
251 return $GLOBALS['import_text'];
252 } else {
253 $r = substr($GLOBALS['import_text'], 0, $size);
254 $GLOBALS['offset'] += $size;
255 $GLOBALS['import_text'] = substr($GLOBALS['import_text'], $size);
256 return $r;
260 switch ($compression) {
261 case 'application/bzip2':
262 $result = bzread($import_handle, $size);
263 $GLOBALS['finished'] = feof($import_handle);
264 break;
265 case 'application/gzip':
266 $result = gzread($import_handle, $size);
267 $GLOBALS['finished'] = feof($import_handle);
268 break;
269 case 'application/zip':
270 $result = substr($GLOBALS['import_text'], 0, $size);
271 $GLOBALS['import_text'] = substr($GLOBALS['import_text'], $size);
272 $GLOBALS['finished'] = empty($GLOBALS['import_text']);
273 break;
274 case 'none':
275 $result = fread($import_handle, $size);
276 $GLOBALS['finished'] = feof($import_handle);
277 break;
279 $GLOBALS['offset'] += $size;
281 if ($charset_conversion) {
282 return PMA_convert_string($charset_of_file, $charset, $result);
283 } else {
285 * Skip possible byte order marks (I do not think we need more
286 * charsets, but feel free to add more, you can use wikipedia for
287 * reference: <http://en.wikipedia.org/wiki/Byte_Order_Mark>)
289 * @todo BOM could be used for charset autodetection
291 if ($GLOBALS['offset'] == $size) {
292 // UTF-8
293 if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
294 $result = substr($result, 3);
295 // UTF-16 BE, LE
296 } elseif (strncmp($result, "\xFE\xFF", 2) == 0 || strncmp($result, "\xFF\xFE", 2) == 0) {
297 $result = substr($result, 2);
300 return $result;
305 * Returns the "Excel" column name (i.e. 1 = "A", 26 = "Z", 27 = "AA", etc.)
307 * This functions uses recursion to build the Excel column name.
309 * The column number (1-26) is converted to the responding ASCII character (A-Z) and returned.
311 * If the column number is bigger than 26 (= num of letters in alfabet),
312 * an extra character needs to be added. To find this extra character, the number is divided by 26
313 * and this value is passed to another instance of the same function (hence recursion).
314 * In that new instance the number is evaluated again, and if it is still bigger than 26, it is divided again
315 * and passed to another instance of the same function. This continues until the number is smaller than 26.
316 * Then the last called function returns the corresponding ASCII character to the function that called it.
317 * Each time a called function ends an extra character is added to the column name.
318 * When the first function is reached, the last character is addded and the complete column name is returned.
320 * @access public
322 * @uses chr()
323 * @param int $num
324 * @return string The column's "Excel" name
326 function PMA_getColumnAlphaName($num)
328 $A = 65; // ASCII value for capital "A"
329 $col_name = "";
331 if ($num > 26) {
332 $div = (int)($num / 26);
333 $remain = (int)($num % 26);
335 // subtract 1 of divided value in case the modulus is 0,
336 // this is necessary because A-Z has no 'zero'
337 if ($remain == 0) {
338 $div--;
341 // recursive function call
342 $col_name = PMA_getColumnAlphaName($div);
343 // use modulus as new column number
344 $num = $remain;
347 if ($num == 0) {
348 // use 'Z' if column number is 0,
349 // this is necessary because A-Z has no 'zero'
350 $col_name .= chr(($A + 26) - 1);
351 } else {
352 // convert column number to ASCII character
353 $col_name .= chr(($A + $num) - 1);
356 return $col_name;
360 * Returns the column number based on the Excel name.
361 * So "A" = 1, "Z" = 26, "AA" = 27, etc.
363 * Basicly this is a base26 (A-Z) to base10 (0-9) conversion.
364 * It iterates through all characters in the column name and
365 * calculates the corresponding value, based on character value
366 * (A = 1, ..., Z = 26) and position in the string.
368 * @access public
370 * @uses strtoupper()
371 * @uses strlen()
372 * @uses ord()
373 * @param string $name (i.e. "A", or "BC", etc.)
374 * @return int The column number
376 function PMA_getColumnNumberFromName($name) {
377 if (!empty($name)) {
378 $name = strtoupper($name);
379 $num_chars = strlen($name);
380 $column_number = 0;
381 for ($i = 0; $i < $num_chars; ++$i) {
382 // read string from back to front
383 $char_pos = ($num_chars - 1) - $i;
385 // convert capital character to ASCII value
386 // and subtract 64 to get corresponding decimal value
387 // ASCII value of "A" is 65, "B" is 66, etc.
388 // Decimal equivalent of "A" is 1, "B" is 2, etc.
389 $number = (ord($name[$char_pos]) - 64);
391 // base26 to base10 conversion : multiply each number
392 // with corresponding value of the position, in this case
393 // $i=0 : 1; $i=1 : 26; $i=2 : 676; ...
394 $column_number += $number * pow(26,$i);
396 return $column_number;
397 } else {
398 return 0;
403 * Constants definitions
406 /* MySQL type defs */
407 define("NONE", 0);
408 define("VARCHAR", 1);
409 define("INT", 2);
410 define("DECIMAL", 3);
412 /* Decimal size defs */
413 define("M", 0);
414 define("D", 1);
415 define("FULL", 2);
417 /* Table array defs */
418 define("TBL_NAME", 0);
419 define("COL_NAMES", 1);
420 define("ROWS", 2);
422 /* Analysis array defs */
423 define("TYPES", 0);
424 define("SIZES", 1);
427 * Obtains the precision (total # of digits) from a size of type decimal
430 * @access public
432 * @uses substr()
433 * @uses strpos()
434 * @param string $last_cumulative_size
435 * @return int Precision of the given decimal size notation
437 function PMA_getM($last_cumulative_size) {
438 return (int)substr($last_cumulative_size, 0, strpos($last_cumulative_size, ","));
442 * Obtains the scale (# of digits to the right of the decimal point) from a size of type decimal
445 * @access public
447 * @uses substr()
448 * @uses strpos()
449 * @uses strlen()
450 * @param string $last_cumulative_size
451 * @return int Scale of the given decimal size notation
453 function PMA_getD($last_cumulative_size) {
454 return (int)substr($last_cumulative_size, (strpos($last_cumulative_size, ",") + 1), (strlen($last_cumulative_size) - strpos($last_cumulative_size, ",")));
458 * Obtains the decimal size of a given cell
461 * @access public
463 * @uses strlen()
464 * @uses strpos()
465 * @param string &$cell
466 * @return array Contains the precision, scale, and full size representation of the given decimal cell
468 function PMA_getDecimalSize(&$cell) {
469 $curr_size = strlen((string)$cell);
470 $decPos = strpos($cell, ".");
471 $decPrecision = ($curr_size - 1) - $decPos;
473 $m = $curr_size - 1;
474 $d = $decPrecision;
476 return array($m, $d, ($m . "," . $d));
480 * Obtains the size of the given cell
483 * @todo Handle the error cases more elegantly
485 * @access public
487 * @uses M
488 * @uses D
489 * @uses FULL
490 * @uses VARCHAR
491 * @uses DECIMAL
492 * @uses INT
493 * @uses NONE
494 * @uses strcmp()
495 * @uses strlen()
496 * @uses PMA_getM()
497 * @uses PMA_getD()
498 * @uses PMA_getDecimalSize()
499 * @param string $last_cumulative_size Last cumulative column size
500 * @param int $last_cumulative_type Last cumulative column type (NONE or VARCHAR or DECIMAL or INT)
501 * @param int $curr_type Type of the current cell (NONE or VARCHAR or DECIMAL or INT)
502 * @param string &$cell The current cell
503 * @return string Size of the given cell in the type-appropriate format
505 function PMA_detectSize($last_cumulative_size, $last_cumulative_type, $curr_type, &$cell) {
506 $curr_size = strlen((string)$cell);
509 * If the cell is NULL, don't treat it as a varchar
511 if (! strcmp('NULL', $cell)) {
512 return $last_cumulative_size;
515 * What to do if the current cell is of type VARCHAR
517 elseif ($curr_type == VARCHAR) {
519 * The last cumlative type was VARCHAR
521 if ($last_cumulative_type == VARCHAR) {
522 if ($curr_size >= $last_cumulative_size) {
523 return $curr_size;
524 } else {
525 return $last_cumulative_size;
529 * The last cumlative type was DECIMAL
531 elseif ($last_cumulative_type == DECIMAL) {
532 $oldM = PMA_getM($last_cumulative_size);
534 if ($curr_size >= $oldM) {
535 return $curr_size;
536 } else {
537 return $oldM;
541 * The last cumlative type was INT
543 elseif ($last_cumulative_type == INT) {
544 if ($curr_size >= $last_cumulative_size) {
545 return $curr_size;
546 } else {
547 return $last_cumulative_size;
551 * This is the first row to be analyzed
553 elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
554 return $curr_size;
557 * An error has DEFINITELY occurred
559 else {
561 * TODO: Handle this MUCH more elegantly
564 return -1;
568 * What to do if the current cell is of type DECIMAL
570 elseif ($curr_type == DECIMAL) {
572 * The last cumlative type was VARCHAR
574 if ($last_cumulative_type == VARCHAR) {
575 /* Convert $last_cumulative_size from varchar to decimal format */
576 $size = PMA_getDecimalSize($cell);
578 if ($size[M] >= $last_cumulative_size) {
579 return $size[M];
580 } else {
581 return $last_cumulative_size;
585 * The last cumlative type was DECIMAL
587 elseif ($last_cumulative_type == DECIMAL) {
588 $size = PMA_getDecimalSize($cell);
590 $oldM = PMA_getM($last_cumulative_size);
591 $oldD = PMA_getD($last_cumulative_size);
593 /* New val if M or D is greater than current largest */
594 if ($size[M] > $oldM || $size[D] > $oldD) {
595 /* Take the largest of both types */
596 return (string)((($size[M] > $oldM) ? $size[M] : $oldM) . "," . (($size[D] > $oldD) ? $size[D] : $oldD));
597 } else {
598 return $last_cumulative_size;
602 * The last cumlative type was INT
604 elseif ($last_cumulative_type == INT) {
605 /* Convert $last_cumulative_size from int to decimal format */
606 $size = PMA_getDecimalSize($cell);
608 if ($size[M] >= $last_cumulative_size) {
609 return $size[FULL];
610 } else {
611 return ($last_cumulative_size.",".$size[D]);
615 * This is the first row to be analyzed
617 elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
618 /* First row of the column */
619 $size = PMA_getDecimalSize($cell);
621 return $size[FULL];
624 * An error has DEFINITELY occurred
626 else {
628 * TODO: Handle this MUCH more elegantly
631 return -1;
635 * What to do if the current cell is of type INT
637 elseif ($curr_type == INT) {
639 * The last cumlative type was VARCHAR
641 if ($last_cumulative_type == VARCHAR) {
642 if ($curr_size >= $last_cumulative_size) {
643 return $curr_size;
644 } else {
645 return $last_cumulative_size;
649 * The last cumlative type was DECIMAL
651 elseif ($last_cumulative_type == DECIMAL) {
652 $oldM = PMA_getM($last_cumulative_size);
653 $oldD = PMA_getD($last_cumulative_size);
654 $oldInt = $oldM - $oldD;
655 $newInt = strlen((string)$cell);
657 /* See which has the larger integer length */
658 if ($oldInt >= $newInt) {
659 /* Use old decimal size */
660 return $last_cumulative_size;
661 } else {
662 /* Use $newInt + $oldD as new M */
663 return (($newInt + $oldD) . "," . $oldD);
667 * The last cumlative type was INT
669 elseif ($last_cumulative_type == INT) {
670 if ($curr_size >= $last_cumulative_size) {
671 return $curr_size;
672 } else {
673 return $last_cumulative_size;
677 * This is the first row to be analyzed
679 elseif (!isset($last_cumulative_type) || $last_cumulative_type == NONE) {
680 return $curr_size;
683 * An error has DEFINITELY occurred
685 else {
687 * TODO: Handle this MUCH more elegantly
690 return -1;
694 * An error has DEFINITELY occurred
696 else {
698 * TODO: Handle this MUCH more elegantly
701 return -1;
706 * Determines what MySQL type a cell is
709 * @access public
711 * @uses DECIMAL
712 * @uses INT
713 * @uses VARCHAR
714 * @uses NONE
715 * @uses is_numeric()
716 * @uses strcmp()
717 * @uses strpos()
718 * @uses substr_count()
719 * @param int $last_cumulative_type Last cumulative column type (VARCHAR or INT or DECIMAL or NONE)
720 * @param string &$cell String representation of the cell for which a best-fit type is to be determined
721 * @return int The MySQL type representation (VARCHAR or INT or DECIMAL or NONE)
723 function PMA_detectType($last_cumulative_type, &$cell) {
725 * If numeric, determine if decimal or int
726 * Else, we call it varchar for simplicity
729 if (! strcmp('NULL', $cell)) {
730 if ($last_cumulative_type === NULL || $last_cumulative_type == NONE) {
731 return NONE;
732 } else {
733 return $last_cumulative_type;
735 } elseif (is_numeric($cell)) {
736 if ($cell == (string)(float)$cell && strpos($cell, ".") !== false && substr_count($cell, ".") == 1) {
737 return DECIMAL;
738 } else {
739 return INT;
741 } else {
742 return VARCHAR;
747 * Determines if the column types are int, decimal, or string
750 * @link http://wiki.phpmyadmin.net/pma/Devel:Import
752 * @todo Handle the error case more elegantly
754 * @access public
756 * @uses TBL_NAME
757 * @uses COL_NAMES
758 * @uses ROWS
759 * @uses VARCHAR
760 * @uses DECIMAL
761 * @uses INT
762 * @uses NONE
763 * @uses count()
764 * @uses is_array()
765 * @uses PMA_detectType()
766 * @uses PMA_detectSize()
767 * @param &$table array(string $table_name, array $col_names, array $rows)
768 * @return array array(array $types, array $sizes)
770 function PMA_analyzeTable(&$table) {
771 /* Get number of rows in table */
772 $numRows = count($table[ROWS]);
773 /* Get number of columns */
774 $numCols = count($table[COL_NAMES]);
775 /* Current type for each column */
776 $types = array();
777 $sizes = array();
779 /* Initialize $sizes to all 0's */
780 for ($i = 0; $i < $numCols; ++$i) {
781 $sizes[$i] = 0;
784 /* Initialize $types to NONE */
785 for ($i = 0; $i < $numCols; ++$i) {
786 $types[$i] = NONE;
789 /* Temp vars */
790 $curr_type = NONE;
791 $curr_size = 0;
793 /* If the passed array is not of the correct form, do not process it */
794 if (is_array($table) && ! is_array($table[TBL_NAME]) && is_array($table[COL_NAMES]) && is_array($table[ROWS])) {
795 /* Analyze each column */
796 for ($i = 0; $i < $numCols; ++$i) {
797 /* Analyze the column in each row */
798 for ($j = 0; $j < $numRows; ++$j) {
799 /* Determine type of the current cell */
800 $curr_type = PMA_detectType($types[$i], $table[ROWS][$j][$i]);
801 /* Determine size of the current cell */
802 $sizes[$i] = PMA_detectSize($sizes[$i], $types[$i], $curr_type, $table[ROWS][$j][$i]);
805 * If a type for this column has alreday been delcared,
806 * only alter it if it was a number and a varchar was found
808 if ($curr_type != NONE) {
809 if ($curr_type == VARCHAR) {
810 $types[$i] = VARCHAR;
811 } else if ($curr_type == DECIMAL) {
812 if ($types[$i] != VARCHAR) {
813 $types[$i] = DECIMAL;
815 } else if ($curr_type == INT) {
816 if ($types[$i] != VARCHAR && $types[$i] != DECIMAL) {
817 $types[$i] = INT;
824 /* Check to ensure that all types are valid */
825 $len = count($types);
826 for ($n = 0; $n < $len; ++$n) {
827 if (! strcmp(NONE, $types[$n])) {
828 $types[$n] = VARCHAR;
829 $sizes[$n] = '10';
833 return array($types, $sizes);
835 else
838 * TODO: Handle this better
841 return false;
845 /* Needed to quell the beast that is PMA_Message */
846 $import_notice = NULL;
849 * Builds and executes SQL statements to create the database and tables
850 * as necessary, as well as insert all the data.
853 * @link http://wiki.phpmyadmin.net/pma/Devel:Import
855 * @access public
857 * @uses TBL_NAME
858 * @uses COL_NAMES
859 * @uses ROWS
860 * @uses TYPES
861 * @uses SIZES
862 * @uses strcmp()
863 * @uses count()
864 * @uses preg_match()
865 * @uses preg_replace()
866 * @uses PMA_isView()
867 * @uses PMA_backquote()
868 * @uses PMA_importRunQuery()
869 * @uses PMA_generate_common_url()
870 * @uses PMA_Message::notice()
871 * @param string $db_name Name of the database
872 * @param array &$tables Array of tables for the specified database
873 * @param array &$analyses = NULL Analyses of the tables
874 * @param array &$additional_sql = NULL Additional SQL statements to be executed
875 * @param array $options = NULL Associative array of options
876 * @return void
878 function PMA_buildSQL($db_name, &$tables, &$analyses = NULL, &$additional_sql = NULL, $options = NULL) {
879 /* Take care of the options */
880 if (isset($options['db_collation'])) {
881 $collation = $options['db_collation'];
882 } else {
883 $collation = "utf8_general_ci";
886 if (isset($options['db_charset'])) {
887 $charset = $options['db_charset'];
888 } else {
889 $charset = "utf8";
892 if (isset($options['create_db'])) {
893 $create_db = $options['create_db'];
894 } else {
895 $create_db = true;
898 /* Create SQL code to handle the database */
899 $sql = array();
901 if ($create_db) {
902 $sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_backquote($db_name) . " DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation;
906 * The calling plug-in should include this statement, if necessary, in the $additional_sql parameter
908 * $sql[] = "USE " . PMA_backquote($db_name);
911 /* Execute the SQL statements create above */
912 $sql_len = count($sql);
913 for ($i = 0; $i < $sql_len; ++$i) {
914 PMA_importRunQuery($sql[$i], $sql[$i]);
917 /* No longer needed */
918 unset($sql);
920 /* Run the $additional_sql statements supplied by the caller plug-in */
921 if ($additional_sql != NULL) {
922 /* Clean the SQL first */
923 $additional_sql_len = count($additional_sql);
926 * Only match tables for now, because CREATE IF NOT EXISTS
927 * syntax is lacking or nonexisting for views, triggers,
928 * functions, and procedures.
930 * See: http://bugs.mysql.com/bug.php?id=15287
932 * To the best of my knowledge this is still an issue.
934 * $pattern = 'CREATE (TABLE|VIEW|TRIGGER|FUNCTION|PROCEDURE)';
936 $pattern = '/CREATE .*(TABLE)/';
937 $replacement = 'CREATE \\1 IF NOT EXISTS';
939 /* Change CREATE statements to CREATE IF NOT EXISTS to support inserting into existing structures */
940 for ($i = 0; $i < $additional_sql_len; ++$i) {
941 $additional_sql[$i] = preg_replace($pattern, $replacement, $additional_sql[$i]);
942 /* Execute the resulting statements */
943 PMA_importRunQuery($additional_sql[$i], $additional_sql[$i]);
947 if ($analyses != NULL) {
948 $type_array = array(NONE => "NULL", VARCHAR => "varchar", INT => "int", DECIMAL => "decimal");
950 /* TODO: Do more checking here to make sure they really are matched */
951 if (count($tables) != count($analyses)) {
952 exit();
955 /* Create SQL code to create the tables */
956 $tempSQLStr = "";
957 $num_tables = count($tables);
958 for ($i = 0; $i < $num_tables; ++$i) {
959 $num_cols = count($tables[$i][COL_NAMES]);
960 $tempSQLStr = "CREATE TABLE IF NOT EXISTS " . PMA_backquote($db_name) . '.' . PMA_backquote($tables[$i][TBL_NAME]) . " (";
961 for ($j = 0; $j < $num_cols; ++$j) {
962 $size = $analyses[$i][SIZES][$j];
963 if ((int)$size == 0) {
964 $size = 10;
967 $tempSQLStr .= PMA_backquote($tables[$i][COL_NAMES][$j]) . " " . $type_array[$analyses[$i][TYPES][$j]] . "(" . $size . ")";
969 if ($j != (count($tables[$i][COL_NAMES]) - 1)) {
970 $tempSQLStr .= ", ";
973 $tempSQLStr .= ") ENGINE=MyISAM DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation . ";";
976 * Each SQL statement is executed immediately
977 * after it is formed so that we don't have
978 * to store them in a (possibly large) buffer
980 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
985 * Create the SQL statements to insert all the data
987 * Only one insert query is formed for each table
989 $tempSQLStr = "";
990 $col_count = 0;
991 $num_tables = count($tables);
992 for ($i = 0; $i < $num_tables; ++$i) {
993 $num_cols = count($tables[$i][COL_NAMES]);
994 $num_rows = count($tables[$i][ROWS]);
996 $tempSQLStr = "INSERT INTO " . PMA_backquote($db_name) . '.' . PMA_backquote($tables[$i][TBL_NAME]) . " (";
998 for ($m = 0; $m < $num_cols; ++$m) {
999 $tempSQLStr .= PMA_backquote($tables[$i][COL_NAMES][$m]);
1001 if ($m != ($num_cols - 1)) {
1002 $tempSQLStr .= ", ";
1006 $tempSQLStr .= ") VALUES ";
1008 for ($j = 0; $j < $num_rows; ++$j) {
1009 $tempSQLStr .= "(";
1011 for ($k = 0; $k < $num_cols; ++$k) {
1012 if ($analyses != NULL) {
1013 $is_varchar = ($analyses[$i][TYPES][$col_count] === VARCHAR);
1014 } else {
1015 $is_varchar = !is_numeric($tables[$i][ROWS][$j][$k]);
1018 /* Don't put quotes around NULL fields */
1019 if (! strcmp($tables[$i][ROWS][$j][$k], 'NULL')) {
1020 $is_varchar = false;
1023 $tempSQLStr .= (($is_varchar) ? "'" : "");
1024 $tempSQLStr .= PMA_sqlAddslashes((string)$tables[$i][ROWS][$j][$k]);
1025 $tempSQLStr .= (($is_varchar) ? "'" : "");
1027 if ($k != ($num_cols - 1)) {
1028 $tempSQLStr .= ", ";
1031 if ($col_count == ($num_cols - 1)) {
1032 $col_count = 0;
1033 } else {
1034 $col_count++;
1037 /* Delete the cell after we are done with it */
1038 unset($tables[$i][ROWS][$j][$k]);
1041 $tempSQLStr .= ")";
1043 if ($j != ($num_rows - 1)) {
1044 $tempSQLStr .= ",\n ";
1047 $col_count = 0;
1048 /* Delete the row after we are done with it */
1049 unset($tables[$i][ROWS][$j]);
1052 $tempSQLStr .= ";";
1055 * Each SQL statement is executed immediately
1056 * after it is formed so that we don't have
1057 * to store them in a (possibly large) buffer
1059 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
1062 /* No longer needed */
1063 unset($tempSQLStr);
1066 * A work in progress
1069 /* Add the viewable structures from $additional_sql to $tables so they are also displayed */
1071 $view_pattern = '@VIEW `[^`]+`\.`([^`]+)@';
1072 $table_pattern = '@CREATE TABLE IF NOT EXISTS `([^`]+)`@';
1073 /* Check a third pattern to make sure its not a "USE `db_name`;" statement */
1075 $regs = array();
1077 $inTables = false;
1079 $additional_sql_len = count($additional_sql);
1080 for ($i = 0; $i < $additional_sql_len; ++$i) {
1081 preg_match($view_pattern, $additional_sql[$i], $regs);
1083 if (count($regs) == 0) {
1084 preg_match($table_pattern, $additional_sql[$i], $regs);
1087 if (count($regs)) {
1088 for ($n = 0; $n < $num_tables; ++$n) {
1089 if (!strcmp($regs[1], $tables[$n][TBL_NAME])) {
1090 $inTables = true;
1091 break;
1095 if (!$inTables) {
1096 $tables[] = array(TBL_NAME => $regs[1]);
1100 /* Reset the array */
1101 $regs = array();
1102 $inTables = false;
1105 $params = array('db' => (string)$db_name);
1106 $db_url = 'db_structure.php' . PMA_generate_common_url($params);
1107 $db_ops_url = 'db_operations.php' . PMA_generate_common_url($params);
1109 $message = '<br /><br />';
1110 $message .= '<strong>' . __('The following structures have either been created or altered. Here you can:') . '</strong><br />';
1111 $message .= '<ul><li>' . __('View a structure`s contents by clicking on its name') . '</li>';
1112 $message .= '<li>' . __('Change any of its settings by clicking the corresponding "Options" link') . '</li>';
1113 $message .= '<li>' . __('Edit its structure by following the "Structure" link') . '</li>';
1114 $message .= sprintf('<br /><li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . __('Options') . '</a>)</li>',
1115 $db_url,
1116 __('Go to database') . ': ' . PMA_backquote($db_name),
1117 $db_name,
1118 $db_ops_url,
1119 __('Edit') . ' ' . PMA_backquote($db_name) . ' ' . __('settings'));
1121 $message .= '<ul>';
1123 unset($params);
1125 $num_tables = count($tables);
1126 for ($i = 0; $i < $num_tables; ++$i)
1128 $params = array('db' => (string)$db_name, 'table' => (string)$tables[$i][TBL_NAME]);
1129 $tbl_url = 'sql.php' . PMA_generate_common_url($params);
1130 $tbl_struct_url = 'tbl_structure.php' . PMA_generate_common_url($params);
1131 $tbl_ops_url = 'tbl_operations.php' . PMA_generate_common_url($params);
1133 unset($params);
1135 if (! PMA_isView($db_name, $tables[$i][TBL_NAME])) {
1136 $message .= sprintf('<li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . __('Structure') . '</a>) (<a href="%s" title="%s">' . __('Options') . '</a>)</li>',
1137 $tbl_url,
1138 __('Go to table') . ': ' . PMA_backquote($tables[$i][TBL_NAME]),
1139 $tables[$i][TBL_NAME],
1140 $tbl_struct_url,
1141 PMA_backquote($tables[$i][TBL_NAME]) . ' ' . __('structure'),
1142 $tbl_ops_url,
1143 __('Edit') . ' ' . PMA_backquote($tables[$i][TBL_NAME]) . ' ' . __('settings'));
1144 } else {
1145 $message .= sprintf('<li><a href="%s" title="%s">%s</a></li>',
1146 $tbl_url,
1147 __('Go to view') . ': ' . PMA_backquote($tables[$i][TBL_NAME]),
1148 $tables[$i][TBL_NAME]);
1152 $message .= '</ul></ul>';
1154 global $import_notice;
1155 $import_notice = $message;
1157 unset($tables);