display message when search returns zero rows
[phpmyadmin/dkf.git] / libraries / import.lib.php
blob98221def86cf109c16cc0ba75171294b234e4e1a
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);
411 define("BIGINT", 4);
413 /* Decimal size defs */
414 define("M", 0);
415 define("D", 1);
416 define("FULL", 2);
418 /* Table array defs */
419 define("TBL_NAME", 0);
420 define("COL_NAMES", 1);
421 define("ROWS", 2);
423 /* Analysis array defs */
424 define("TYPES", 0);
425 define("SIZES", 1);
428 * Obtains the precision (total # of digits) from a size of type decimal
431 * @access public
433 * @uses substr()
434 * @uses strpos()
435 * @param string $last_cumulative_size
436 * @return int Precision of the given decimal size notation
438 function PMA_getM($last_cumulative_size) {
439 return (int)substr($last_cumulative_size, 0, strpos($last_cumulative_size, ","));
443 * Obtains the scale (# of digits to the right of the decimal point) from a size of type decimal
446 * @access public
448 * @uses substr()
449 * @uses strpos()
450 * @uses strlen()
451 * @param string $last_cumulative_size
452 * @return int Scale of the given decimal size notation
454 function PMA_getD($last_cumulative_size) {
455 return (int)substr($last_cumulative_size, (strpos($last_cumulative_size, ",") + 1), (strlen($last_cumulative_size) - strpos($last_cumulative_size, ",")));
459 * Obtains the decimal size of a given cell
462 * @access public
464 * @uses strlen()
465 * @uses strpos()
466 * @param string &$cell
467 * @return array Contains the precision, scale, and full size representation of the given decimal cell
469 function PMA_getDecimalSize(&$cell) {
470 $curr_size = strlen((string)$cell);
471 $decPos = strpos($cell, ".");
472 $decPrecision = ($curr_size - 1) - $decPos;
474 $m = $curr_size - 1;
475 $d = $decPrecision;
477 return array($m, $d, ($m . "," . $d));
481 * Obtains the size of the given cell
484 * @todo Handle the error cases more elegantly
486 * @access public
488 * @uses M
489 * @uses D
490 * @uses FULL
491 * @uses VARCHAR
492 * @uses DECIMAL
493 * @uses BIGINT
494 * @uses INT
495 * @uses NONE
496 * @uses strcmp()
497 * @uses strlen()
498 * @uses PMA_getM()
499 * @uses PMA_getD()
500 * @uses PMA_getDecimalSize()
501 * @param string $last_cumulative_size Last cumulative column size
502 * @param int $last_cumulative_type Last cumulative column type (NONE or VARCHAR or DECIMAL or INT or BIGINT)
503 * @param int $curr_type Type of the current cell (NONE or VARCHAR or DECIMAL or INT or BIGINT)
504 * @param string &$cell The current cell
505 * @return string Size of the given cell in the type-appropriate format
507 function PMA_detectSize($last_cumulative_size, $last_cumulative_type, $curr_type, &$cell) {
508 $curr_size = strlen((string)$cell);
511 * If the cell is NULL, don't treat it as a varchar
513 if (! strcmp('NULL', $cell)) {
514 return $last_cumulative_size;
517 * What to do if the current cell is of type VARCHAR
519 elseif ($curr_type == VARCHAR) {
521 * The last cumulative type was VARCHAR
523 if ($last_cumulative_type == VARCHAR) {
524 if ($curr_size >= $last_cumulative_size) {
525 return $curr_size;
526 } else {
527 return $last_cumulative_size;
531 * The last cumulative type was DECIMAL
533 elseif ($last_cumulative_type == DECIMAL) {
534 $oldM = PMA_getM($last_cumulative_size);
536 if ($curr_size >= $oldM) {
537 return $curr_size;
538 } else {
539 return $oldM;
543 * The last cumulative type was BIGINT or INT
545 elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
546 if ($curr_size >= $last_cumulative_size) {
547 return $curr_size;
548 } else {
549 return $last_cumulative_size;
553 * This is the first row to be analyzed
555 elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
556 return $curr_size;
559 * An error has DEFINITELY occurred
561 else {
563 * TODO: Handle this MUCH more elegantly
566 return -1;
570 * What to do if the current cell is of type DECIMAL
572 elseif ($curr_type == DECIMAL) {
574 * The last cumulative type was VARCHAR
576 if ($last_cumulative_type == VARCHAR) {
577 /* Convert $last_cumulative_size from varchar to decimal format */
578 $size = PMA_getDecimalSize($cell);
580 if ($size[M] >= $last_cumulative_size) {
581 return $size[M];
582 } else {
583 return $last_cumulative_size;
587 * The last cumulative type was DECIMAL
589 elseif ($last_cumulative_type == DECIMAL) {
590 $size = PMA_getDecimalSize($cell);
592 $oldM = PMA_getM($last_cumulative_size);
593 $oldD = PMA_getD($last_cumulative_size);
595 /* New val if M or D is greater than current largest */
596 if ($size[M] > $oldM || $size[D] > $oldD) {
597 /* Take the largest of both types */
598 return (string)((($size[M] > $oldM) ? $size[M] : $oldM) . "," . (($size[D] > $oldD) ? $size[D] : $oldD));
599 } else {
600 return $last_cumulative_size;
604 * The last cumulative type was BIGINT or INT
606 elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
607 /* Convert $last_cumulative_size from int to decimal format */
608 $size = PMA_getDecimalSize($cell);
610 if ($size[M] >= $last_cumulative_size) {
611 return $size[FULL];
612 } else {
613 return ($last_cumulative_size.",".$size[D]);
617 * This is the first row to be analyzed
619 elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
620 /* First row of the column */
621 $size = PMA_getDecimalSize($cell);
623 return $size[FULL];
626 * An error has DEFINITELY occurred
628 else {
630 * TODO: Handle this MUCH more elegantly
633 return -1;
637 * What to do if the current cell is of type BIGINT or INT
639 elseif ($curr_type == BIGINT || $curr_type == INT) {
641 * The last cumulative type was VARCHAR
643 if ($last_cumulative_type == VARCHAR) {
644 if ($curr_size >= $last_cumulative_size) {
645 return $curr_size;
646 } else {
647 return $last_cumulative_size;
651 * The last cumulative type was DECIMAL
653 elseif ($last_cumulative_type == DECIMAL) {
654 $oldM = PMA_getM($last_cumulative_size);
655 $oldD = PMA_getD($last_cumulative_size);
656 $oldInt = $oldM - $oldD;
657 $newInt = strlen((string)$cell);
659 /* See which has the larger integer length */
660 if ($oldInt >= $newInt) {
661 /* Use old decimal size */
662 return $last_cumulative_size;
663 } else {
664 /* Use $newInt + $oldD as new M */
665 return (($newInt + $oldD) . "," . $oldD);
669 * The last cumulative type was BIGINT or INT
671 elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
672 if ($curr_size >= $last_cumulative_size) {
673 return $curr_size;
674 } else {
675 return $last_cumulative_size;
679 * This is the first row to be analyzed
681 elseif (!isset($last_cumulative_type) || $last_cumulative_type == NONE) {
682 return $curr_size;
685 * An error has DEFINITELY occurred
687 else {
689 * TODO: Handle this MUCH more elegantly
692 return -1;
696 * An error has DEFINITELY occurred
698 else {
700 * TODO: Handle this MUCH more elegantly
703 return -1;
708 * Determines what MySQL type a cell is
711 * @access public
713 * @uses DECIMAL
714 * @uses BIGINT
715 * @uses INT
716 * @uses VARCHAR
717 * @uses NONE
718 * @uses is_numeric()
719 * @uses strcmp()
720 * @uses strpos()
721 * @uses substr_count()
722 * @param int $last_cumulative_type Last cumulative column type (VARCHAR or INT or BIGINT or DECIMAL or NONE)
723 * @param string &$cell String representation of the cell for which a best-fit type is to be determined
724 * @return int The MySQL type representation (VARCHAR or INT or BIGINT or DECIMAL or NONE)
726 function PMA_detectType($last_cumulative_type, &$cell) {
728 * If numeric, determine if decimal, int or bigint
729 * Else, we call it varchar for simplicity
732 if (! strcmp('NULL', $cell)) {
733 if ($last_cumulative_type === NULL || $last_cumulative_type == NONE) {
734 return NONE;
735 } else {
736 return $last_cumulative_type;
738 } elseif (is_numeric($cell)) {
739 if ($cell == (string)(float)$cell && strpos($cell, ".") !== false && substr_count($cell, ".") == 1) {
740 return DECIMAL;
741 } else {
742 if (abs($cell) > 2147483647) {
743 return BIGINT;
744 } else {
745 return INT;
748 } else {
749 return VARCHAR;
754 * Determines if the column types are int, decimal, or string
757 * @link http://wiki.phpmyadmin.net/pma/Devel:Import
759 * @todo Handle the error case more elegantly
761 * @access public
763 * @uses TBL_NAME
764 * @uses COL_NAMES
765 * @uses ROWS
766 * @uses VARCHAR
767 * @uses DECIMAL
768 * @uses BIGINT
769 * @uses INT
770 * @uses NONE
771 * @uses count()
772 * @uses is_array()
773 * @uses PMA_detectType()
774 * @uses PMA_detectSize()
775 * @param &$table array(string $table_name, array $col_names, array $rows)
776 * @return array array(array $types, array $sizes)
778 function PMA_analyzeTable(&$table) {
779 /* Get number of rows in table */
780 $numRows = count($table[ROWS]);
781 /* Get number of columns */
782 $numCols = count($table[COL_NAMES]);
783 /* Current type for each column */
784 $types = array();
785 $sizes = array();
787 /* Initialize $sizes to all 0's */
788 for ($i = 0; $i < $numCols; ++$i) {
789 $sizes[$i] = 0;
792 /* Initialize $types to NONE */
793 for ($i = 0; $i < $numCols; ++$i) {
794 $types[$i] = NONE;
797 /* Temp vars */
798 $curr_type = NONE;
799 $curr_size = 0;
801 /* If the passed array is not of the correct form, do not process it */
802 if (is_array($table) && ! is_array($table[TBL_NAME]) && is_array($table[COL_NAMES]) && is_array($table[ROWS])) {
803 /* Analyze each column */
804 for ($i = 0; $i < $numCols; ++$i) {
805 /* Analyze the column in each row */
806 for ($j = 0; $j < $numRows; ++$j) {
807 /* Determine type of the current cell */
808 $curr_type = PMA_detectType($types[$i], $table[ROWS][$j][$i]);
809 /* Determine size of the current cell */
810 $sizes[$i] = PMA_detectSize($sizes[$i], $types[$i], $curr_type, $table[ROWS][$j][$i]);
813 * If a type for this column has already been declared,
814 * only alter it if it was a number and a varchar was found
816 if ($curr_type != NONE) {
817 if ($curr_type == VARCHAR) {
818 $types[$i] = VARCHAR;
819 } else if ($curr_type == DECIMAL) {
820 if ($types[$i] != VARCHAR) {
821 $types[$i] = DECIMAL;
823 } else if ($curr_type == BIGINT) {
824 if ($types[$i] != VARCHAR && $types[$i] != DECIMAL) {
825 $types[$i] = BIGINT;
827 } else if ($curr_type == INT) {
828 if ($types[$i] != VARCHAR && $types[$i] != DECIMAL && $types[$i] != BIGINT) {
829 $types[$i] = INT;
836 /* Check to ensure that all types are valid */
837 $len = count($types);
838 for ($n = 0; $n < $len; ++$n) {
839 if (! strcmp(NONE, $types[$n])) {
840 $types[$n] = VARCHAR;
841 $sizes[$n] = '10';
845 return array($types, $sizes);
847 else
850 * TODO: Handle this better
853 return false;
857 /* Needed to quell the beast that is PMA_Message */
858 $import_notice = NULL;
861 * Builds and executes SQL statements to create the database and tables
862 * as necessary, as well as insert all the data.
865 * @link http://wiki.phpmyadmin.net/pma/Devel:Import
867 * @access public
869 * @uses TBL_NAME
870 * @uses COL_NAMES
871 * @uses ROWS
872 * @uses TYPES
873 * @uses SIZES
874 * @uses strcmp()
875 * @uses count()
876 * @uses preg_match()
877 * @uses preg_replace()
878 * @uses PMA_isView()
879 * @uses PMA_backquote()
880 * @uses PMA_importRunQuery()
881 * @uses PMA_generate_common_url()
882 * @uses PMA_Message::notice()
883 * @param string $db_name Name of the database
884 * @param array &$tables Array of tables for the specified database
885 * @param array &$analyses = NULL Analyses of the tables
886 * @param array &$additional_sql = NULL Additional SQL statements to be executed
887 * @param array $options = NULL Associative array of options
888 * @return void
890 function PMA_buildSQL($db_name, &$tables, &$analyses = NULL, &$additional_sql = NULL, $options = NULL) {
891 /* Take care of the options */
892 if (isset($options['db_collation'])) {
893 $collation = $options['db_collation'];
894 } else {
895 $collation = "utf8_general_ci";
898 if (isset($options['db_charset'])) {
899 $charset = $options['db_charset'];
900 } else {
901 $charset = "utf8";
904 if (isset($options['create_db'])) {
905 $create_db = $options['create_db'];
906 } else {
907 $create_db = true;
910 /* Create SQL code to handle the database */
911 $sql = array();
913 if ($create_db) {
914 $sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_backquote($db_name) . " DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation;
918 * The calling plug-in should include this statement, if necessary, in the $additional_sql parameter
920 * $sql[] = "USE " . PMA_backquote($db_name);
923 /* Execute the SQL statements create above */
924 $sql_len = count($sql);
925 for ($i = 0; $i < $sql_len; ++$i) {
926 PMA_importRunQuery($sql[$i], $sql[$i]);
929 /* No longer needed */
930 unset($sql);
932 /* Run the $additional_sql statements supplied by the caller plug-in */
933 if ($additional_sql != NULL) {
934 /* Clean the SQL first */
935 $additional_sql_len = count($additional_sql);
938 * Only match tables for now, because CREATE IF NOT EXISTS
939 * syntax is lacking or nonexisting for views, triggers,
940 * functions, and procedures.
942 * See: http://bugs.mysql.com/bug.php?id=15287
944 * To the best of my knowledge this is still an issue.
946 * $pattern = 'CREATE (TABLE|VIEW|TRIGGER|FUNCTION|PROCEDURE)';
948 $pattern = '/CREATE .*(TABLE)/';
949 $replacement = 'CREATE \\1 IF NOT EXISTS';
951 /* Change CREATE statements to CREATE IF NOT EXISTS to support inserting into existing structures */
952 for ($i = 0; $i < $additional_sql_len; ++$i) {
953 $additional_sql[$i] = preg_replace($pattern, $replacement, $additional_sql[$i]);
954 /* Execute the resulting statements */
955 PMA_importRunQuery($additional_sql[$i], $additional_sql[$i]);
959 if ($analyses != NULL) {
960 $type_array = array(NONE => "NULL", VARCHAR => "varchar", INT => "int", DECIMAL => "decimal", BIGINT => "bigint");
962 /* TODO: Do more checking here to make sure they really are matched */
963 if (count($tables) != count($analyses)) {
964 exit();
967 /* Create SQL code to create the tables */
968 $tempSQLStr = "";
969 $num_tables = count($tables);
970 for ($i = 0; $i < $num_tables; ++$i) {
971 $num_cols = count($tables[$i][COL_NAMES]);
972 $tempSQLStr = "CREATE TABLE IF NOT EXISTS " . PMA_backquote($db_name) . '.' . PMA_backquote($tables[$i][TBL_NAME]) . " (";
973 for ($j = 0; $j < $num_cols; ++$j) {
974 $size = $analyses[$i][SIZES][$j];
975 if ((int)$size == 0) {
976 $size = 10;
979 $tempSQLStr .= PMA_backquote($tables[$i][COL_NAMES][$j]) . " " . $type_array[$analyses[$i][TYPES][$j]] . "(" . $size . ")";
981 if ($j != (count($tables[$i][COL_NAMES]) - 1)) {
982 $tempSQLStr .= ", ";
985 $tempSQLStr .= ") ENGINE=MyISAM DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation . ";";
988 * Each SQL statement is executed immediately
989 * after it is formed so that we don't have
990 * to store them in a (possibly large) buffer
992 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
997 * Create the SQL statements to insert all the data
999 * Only one insert query is formed for each table
1001 $tempSQLStr = "";
1002 $col_count = 0;
1003 $num_tables = count($tables);
1004 for ($i = 0; $i < $num_tables; ++$i) {
1005 $num_cols = count($tables[$i][COL_NAMES]);
1006 $num_rows = count($tables[$i][ROWS]);
1008 $tempSQLStr = "INSERT INTO " . PMA_backquote($db_name) . '.' . PMA_backquote($tables[$i][TBL_NAME]) . " (";
1010 for ($m = 0; $m < $num_cols; ++$m) {
1011 $tempSQLStr .= PMA_backquote($tables[$i][COL_NAMES][$m]);
1013 if ($m != ($num_cols - 1)) {
1014 $tempSQLStr .= ", ";
1018 $tempSQLStr .= ") VALUES ";
1020 for ($j = 0; $j < $num_rows; ++$j) {
1021 $tempSQLStr .= "(";
1023 for ($k = 0; $k < $num_cols; ++$k) {
1024 if ($analyses != NULL) {
1025 $is_varchar = ($analyses[$i][TYPES][$col_count] === VARCHAR);
1026 } else {
1027 $is_varchar = !is_numeric($tables[$i][ROWS][$j][$k]);
1030 /* Don't put quotes around NULL fields */
1031 if (! strcmp($tables[$i][ROWS][$j][$k], 'NULL')) {
1032 $is_varchar = false;
1035 $tempSQLStr .= (($is_varchar) ? "'" : "");
1036 $tempSQLStr .= PMA_sqlAddslashes((string)$tables[$i][ROWS][$j][$k]);
1037 $tempSQLStr .= (($is_varchar) ? "'" : "");
1039 if ($k != ($num_cols - 1)) {
1040 $tempSQLStr .= ", ";
1043 if ($col_count == ($num_cols - 1)) {
1044 $col_count = 0;
1045 } else {
1046 $col_count++;
1049 /* Delete the cell after we are done with it */
1050 unset($tables[$i][ROWS][$j][$k]);
1053 $tempSQLStr .= ")";
1055 if ($j != ($num_rows - 1)) {
1056 $tempSQLStr .= ",\n ";
1059 $col_count = 0;
1060 /* Delete the row after we are done with it */
1061 unset($tables[$i][ROWS][$j]);
1064 $tempSQLStr .= ";";
1067 * Each SQL statement is executed immediately
1068 * after it is formed so that we don't have
1069 * to store them in a (possibly large) buffer
1071 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
1074 /* No longer needed */
1075 unset($tempSQLStr);
1078 * A work in progress
1081 /* Add the viewable structures from $additional_sql to $tables so they are also displayed */
1083 $view_pattern = '@VIEW `[^`]+`\.`([^`]+)@';
1084 $table_pattern = '@CREATE TABLE IF NOT EXISTS `([^`]+)`@';
1085 /* Check a third pattern to make sure its not a "USE `db_name`;" statement */
1087 $regs = array();
1089 $inTables = false;
1091 $additional_sql_len = count($additional_sql);
1092 for ($i = 0; $i < $additional_sql_len; ++$i) {
1093 preg_match($view_pattern, $additional_sql[$i], $regs);
1095 if (count($regs) == 0) {
1096 preg_match($table_pattern, $additional_sql[$i], $regs);
1099 if (count($regs)) {
1100 for ($n = 0; $n < $num_tables; ++$n) {
1101 if (!strcmp($regs[1], $tables[$n][TBL_NAME])) {
1102 $inTables = true;
1103 break;
1107 if (!$inTables) {
1108 $tables[] = array(TBL_NAME => $regs[1]);
1112 /* Reset the array */
1113 $regs = array();
1114 $inTables = false;
1117 $params = array('db' => (string)$db_name);
1118 $db_url = 'db_structure.php' . PMA_generate_common_url($params);
1119 $db_ops_url = 'db_operations.php' . PMA_generate_common_url($params);
1121 $message = '<br /><br />';
1122 $message .= '<strong>' . __('The following structures have either been created or altered. Here you can:') . '</strong><br />';
1123 $message .= '<ul><li>' . __('View a structure`s contents by clicking on its name') . '</li>';
1124 $message .= '<li>' . __('Change any of its settings by clicking the corresponding "Options" link') . '</li>';
1125 $message .= '<li>' . __('Edit its structure by following the "Structure" link') . '</li>';
1126 $message .= sprintf('<br /><li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . __('Options') . '</a>)</li>',
1127 $db_url,
1128 __('Go to database') . ': ' . PMA_backquote($db_name),
1129 $db_name,
1130 $db_ops_url,
1131 __('Edit') . ' ' . PMA_backquote($db_name) . ' ' . __('settings'));
1133 $message .= '<ul>';
1135 unset($params);
1137 $num_tables = count($tables);
1138 for ($i = 0; $i < $num_tables; ++$i)
1140 $params = array('db' => (string)$db_name, 'table' => (string)$tables[$i][TBL_NAME]);
1141 $tbl_url = 'sql.php' . PMA_generate_common_url($params);
1142 $tbl_struct_url = 'tbl_structure.php' . PMA_generate_common_url($params);
1143 $tbl_ops_url = 'tbl_operations.php' . PMA_generate_common_url($params);
1145 unset($params);
1147 if (! PMA_isView($db_name, $tables[$i][TBL_NAME])) {
1148 $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>',
1149 $tbl_url,
1150 __('Go to table') . ': ' . PMA_backquote($tables[$i][TBL_NAME]),
1151 $tables[$i][TBL_NAME],
1152 $tbl_struct_url,
1153 PMA_backquote($tables[$i][TBL_NAME]) . ' ' . __('structure'),
1154 $tbl_ops_url,
1155 __('Edit') . ' ' . PMA_backquote($tables[$i][TBL_NAME]) . ' ' . __('settings'));
1156 } else {
1157 $message .= sprintf('<li><a href="%s" title="%s">%s</a></li>',
1158 $tbl_url,
1159 __('Go to view') . ': ' . PMA_backquote($tables[$i][TBL_NAME]),
1160 $tables[$i][TBL_NAME]);
1164 $message .= '</ul></ul>';
1166 global $import_notice;
1167 $import_notice = $message;
1169 unset($tables);