Upgraded phpmyadmin to 4.0.4 (All Languages) - No modifications yet
[openemr.git] / phpmyadmin / libraries / import.lib.php
blobaa15847a6e547b2eda7dbe3ff2647e8ea53d7eb6
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-Import
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 * Checks 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 $filepath filename to check
49 * @return string MIME type of compression, none for none
50 * @access public
52 function PMA_detectCompression($filepath)
54 $file = @fopen($filepath, 'rb');
55 if (! $file) {
56 return false;
58 $test = fread($file, 4);
59 $len = strlen($test);
60 fclose($file);
61 if ($len >= 2 && $test[0] == chr(31) && $test[1] == chr(139)) {
62 return 'application/gzip';
64 if ($len >= 3 && substr($test, 0, 3) == 'BZh') {
65 return 'application/bzip2';
67 if ($len >= 4 && $test == "PK\003\004") {
68 return 'application/zip';
70 return 'none';
73 /**
74 * Runs query inside import buffer. This is needed to allow displaying
75 * of last SELECT, SHOW or HANDLER results and similar nice stuff.
77 * @param string $sql query to run
78 * @param string $full query to display, this might be commented
79 * @param bool $controluser whether to use control user for queries
80 * @param array &$sql_data
82 * @return void
83 * @access public
85 function PMA_importRunQuery($sql = '', $full = '', $controluser = false,
86 &$sql_data = array()
87 ) {
88 global $import_run_buffer, $go_sql, $complete_query, $display_query,
89 $sql_query, $my_die, $error, $reload,
90 $last_query_with_results,
91 $skip_queries, $executed_queries, $max_sql_len, $read_multiply,
92 $cfg, $sql_query_disabled, $db, $run_query, $is_superuser;
93 $read_multiply = 1;
94 if (isset($import_run_buffer)) {
95 // Should we skip something?
96 if ($skip_queries > 0) {
97 $skip_queries--;
98 } else {
99 if (! empty($import_run_buffer['sql'])
100 && trim($import_run_buffer['sql']) != ''
103 // USE query changes the database, son need to track
104 // while running multiple queries
105 $is_use_query
106 = (stripos($import_run_buffer['sql'], "use ") !== false)
107 ? true
108 : false;
110 $max_sql_len = max($max_sql_len, strlen($import_run_buffer['sql']));
111 if (! $sql_query_disabled) {
112 $sql_query .= $import_run_buffer['full'];
114 if (! $cfg['AllowUserDropDatabase']
115 && ! $is_superuser
116 && preg_match('@^[[:space:]]*DROP[[:space:]]+(IF EXISTS[[:space:]]+)?DATABASE @i', $import_run_buffer['sql'])
118 $GLOBALS['message'] = PMA_Message::error(__('"DROP DATABASE" statements are disabled.'));
119 $error = true;
120 } else {
122 $executed_queries++;
124 if ($run_query
125 && $GLOBALS['finished']
126 && empty($sql)
127 && ! $error
128 && ((! empty($import_run_buffer['sql'])
129 && preg_match('/^[\s]*(SELECT|SHOW|HANDLER)/i', $import_run_buffer['sql']))
130 || ($executed_queries == 1))
132 $go_sql = true;
133 if (! $sql_query_disabled) {
134 $complete_query = $sql_query;
135 $display_query = $sql_query;
136 } else {
137 $complete_query = '';
138 $display_query = '';
140 $sql_query = $import_run_buffer['sql'];
141 $sql_data['valid_sql'][] = $import_run_buffer['sql'];
142 $sql_data['valid_queries']++;
144 // If a 'USE <db>' SQL-clause was found,
145 // set our current $db to the new one
146 list($db, $reload) = PMA_lookForUse(
147 $import_run_buffer['sql'],
148 $db,
149 $reload
151 } elseif ($run_query) {
153 if ($controluser) {
154 $result = PMA_queryAsControlUser(
155 $import_run_buffer['sql']
157 } else {
158 $result = PMA_DBI_try_query($import_run_buffer['sql']);
161 $msg = '# ';
162 if ($result === false) { // execution failed
163 if (! isset($my_die)) {
164 $my_die = array();
166 $my_die[] = array(
167 'sql' => $import_run_buffer['full'],
168 'error' => PMA_DBI_getError()
171 $msg .= __('Error');
173 if (! $cfg['IgnoreMultiSubmitErrors']) {
174 $error = true;
175 return;
177 } else {
178 $a_num_rows = (int)@PMA_DBI_num_rows($result);
179 $a_aff_rows = (int)@PMA_DBI_affected_rows();
180 if ($a_num_rows > 0) {
181 $msg .= __('Rows'). ': ' . $a_num_rows;
182 $last_query_with_results = $import_run_buffer['sql'];
183 } elseif ($a_aff_rows > 0) {
184 $message = PMA_Message::getMessageForAffectedRows($a_aff_rows);
185 $msg .= $message->getMessage();
186 } else {
187 $msg .= __('MySQL returned an empty result set (i.e. zero rows).');
190 if (($a_num_rows > 0) || $is_use_query) {
191 $sql_data['valid_sql'][] = $import_run_buffer['sql'];
192 $sql_data['valid_queries']++;
196 if (! $sql_query_disabled) {
197 $sql_query .= $msg . "\n";
200 // If a 'USE <db>' SQL-clause was found and the query
201 // succeeded, set our current $db to the new one
202 if ($result != false) {
203 list($db, $reload) = PMA_lookForUse(
204 $import_run_buffer['sql'],
205 $db,
206 $reload
210 if ($result != false
211 && preg_match('@^[\s]*(DROP|CREATE)[\s]+(IF EXISTS[[:space:]]+)?(TABLE|DATABASE)[[:space:]]+(.+)@im', $import_run_buffer['sql'])
213 $reload = true;
215 } // end run query
216 } // end if not DROP DATABASE
217 // end non empty query
218 } elseif (! empty($import_run_buffer['full'])) {
219 if ($go_sql) {
220 $complete_query .= $import_run_buffer['full'];
221 $display_query .= $import_run_buffer['full'];
222 } else {
223 if (! $sql_query_disabled) {
224 $sql_query .= $import_run_buffer['full'];
228 // check length of query unless we decided to pass it to sql.php
229 // (if $run_query is false, we are just displaying so show
230 // the complete query in the textarea)
231 if (! $go_sql && $run_query) {
232 if (! empty($sql_query)) {
233 if (strlen($sql_query) > 50000
234 || $executed_queries > 50
235 || $max_sql_len > 1000
237 $sql_query = '';
238 $sql_query_disabled = true;
242 } // end do query (no skip)
243 } // end buffer exists
245 // Do we have something to push into buffer?
246 if (! empty($sql) || ! empty($full)) {
247 $import_run_buffer = array('sql' => $sql, 'full' => $full);
248 } else {
249 unset($GLOBALS['import_run_buffer']);
254 * Looks for the presence of USE to possibly change current db
256 * @param string $buffer buffer to examine
257 * @param string $db current db
258 * @param bool $reload reload
260 * @return array (current or new db, whether to reload)
261 * @access public
263 function PMA_lookForUse($buffer, $db, $reload)
265 if (preg_match('@^[\s]*USE[[:space:]]+([\S]+)@i', $buffer, $match)) {
266 $db = trim($match[1]);
267 $db = trim($db, ';'); // for example, USE abc;
269 // $db must not contain the escape characters generated by backquote()
270 // ( used in PMA_buildSQL() as: backquote($db_name), and then called
271 // in PMA_importRunQuery() which in turn calls PMA_lookForUse() )
272 $db = PMA_Util::unQuote($db);
274 $reload = true;
276 return(array($db, $reload));
281 * Returns next part of imported file/buffer
283 * @param int $size size of buffer to read
284 * (this is maximal size function will return)
286 * @return string part of file/buffer
287 * @access public
289 function PMA_importGetNextChunk($size = 32768)
291 global $compression, $import_handle, $charset_conversion, $charset_of_file,
292 $read_multiply;
294 // Add some progression while reading large amount of data
295 if ($read_multiply <= 8) {
296 $size *= $read_multiply;
297 } else {
298 $size *= 8;
300 $read_multiply++;
302 // We can not read too much
303 if ($size > $GLOBALS['read_limit']) {
304 $size = $GLOBALS['read_limit'];
307 if (PMA_checkTimeout()) {
308 return false;
310 if ($GLOBALS['finished']) {
311 return true;
314 if ($GLOBALS['import_file'] == 'none') {
315 // Well this is not yet supported and tested,
316 // but should return content of textarea
317 if (strlen($GLOBALS['import_text']) < $size) {
318 $GLOBALS['finished'] = true;
319 return $GLOBALS['import_text'];
320 } else {
321 $r = substr($GLOBALS['import_text'], 0, $size);
322 $GLOBALS['offset'] += $size;
323 $GLOBALS['import_text'] = substr($GLOBALS['import_text'], $size);
324 return $r;
328 switch ($compression) {
329 case 'application/bzip2':
330 $result = bzread($import_handle, $size);
331 $GLOBALS['finished'] = feof($import_handle);
332 break;
333 case 'application/gzip':
334 $result = gzread($import_handle, $size);
335 $GLOBALS['finished'] = feof($import_handle);
336 break;
337 case 'application/zip':
338 $result = substr($GLOBALS['import_text'], 0, $size);
339 $GLOBALS['import_text'] = substr($GLOBALS['import_text'], $size);
340 $GLOBALS['finished'] = empty($GLOBALS['import_text']);
341 break;
342 case 'none':
343 $result = fread($import_handle, $size);
344 $GLOBALS['finished'] = feof($import_handle);
345 break;
347 $GLOBALS['offset'] += $size;
349 if ($charset_conversion) {
350 return PMA_convert_string($charset_of_file, 'utf-8', $result);
351 } else {
353 * Skip possible byte order marks (I do not think we need more
354 * charsets, but feel free to add more, you can use wikipedia for
355 * reference: <http://en.wikipedia.org/wiki/Byte_Order_Mark>)
357 * @todo BOM could be used for charset autodetection
359 if ($GLOBALS['offset'] == $size) {
360 // UTF-8
361 if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
362 $result = substr($result, 3);
363 // UTF-16 BE, LE
364 } elseif (strncmp($result, "\xFE\xFF", 2) == 0
365 || strncmp($result, "\xFF\xFE", 2) == 0
367 $result = substr($result, 2);
370 return $result;
375 * Returns the "Excel" column name (i.e. 1 = "A", 26 = "Z", 27 = "AA", etc.)
377 * This functions uses recursion to build the Excel column name.
379 * The column number (1-26) is converted to the responding
380 * ASCII character (A-Z) and returned.
382 * If the column number is bigger than 26 (= num of letters in alfabet),
383 * an extra character needs to be added. To find this extra character,
384 * the number is divided by 26 and this value is passed to another instance
385 * of the same function (hence recursion). In that new instance the number is
386 * evaluated again, and if it is still bigger than 26, it is divided again
387 * and passed to another instance of the same function. This continues until
388 * the number is smaller than 26. Then the last called function returns
389 * the corresponding ASCII character to the function that called it.
390 * Each time a called function ends an extra character is added to the column name.
391 * When the first function is reached, the last character is addded and the complete
392 * column name is returned.
394 * @param int $num the column number
396 * @return string The column's "Excel" name
397 * @access public
399 function PMA_getColumnAlphaName($num)
401 $A = 65; // ASCII value for capital "A"
402 $col_name = "";
404 if ($num > 26) {
405 $div = (int)($num / 26);
406 $remain = (int)($num % 26);
408 // subtract 1 of divided value in case the modulus is 0,
409 // this is necessary because A-Z has no 'zero'
410 if ($remain == 0) {
411 $div--;
414 // recursive function call
415 $col_name = PMA_getColumnAlphaName($div);
416 // use modulus as new column number
417 $num = $remain;
420 if ($num == 0) {
421 // use 'Z' if column number is 0,
422 // this is necessary because A-Z has no 'zero'
423 $col_name .= chr(($A + 26) - 1);
424 } else {
425 // convert column number to ASCII character
426 $col_name .= chr(($A + $num) - 1);
429 return $col_name;
433 * Returns the column number based on the Excel name.
434 * So "A" = 1, "Z" = 26, "AA" = 27, etc.
436 * Basicly this is a base26 (A-Z) to base10 (0-9) conversion.
437 * It iterates through all characters in the column name and
438 * calculates the corresponding value, based on character value
439 * (A = 1, ..., Z = 26) and position in the string.
441 * @param string $name column name(i.e. "A", or "BC", etc.)
443 * @return int The column number
444 * @access public
446 function PMA_getColumnNumberFromName($name)
448 if (! empty($name)) {
449 $name = strtoupper($name);
450 $num_chars = strlen($name);
451 $column_number = 0;
452 for ($i = 0; $i < $num_chars; ++$i) {
453 // read string from back to front
454 $char_pos = ($num_chars - 1) - $i;
456 // convert capital character to ASCII value
457 // and subtract 64 to get corresponding decimal value
458 // ASCII value of "A" is 65, "B" is 66, etc.
459 // Decimal equivalent of "A" is 1, "B" is 2, etc.
460 $number = (ord($name[$char_pos]) - 64);
462 // base26 to base10 conversion : multiply each number
463 // with corresponding value of the position, in this case
464 // $i=0 : 1; $i=1 : 26; $i=2 : 676; ...
465 $column_number += $number * PMA_Util::pow(26, $i);
467 return $column_number;
468 } else {
469 return 0;
474 * Constants definitions
477 /* MySQL type defs */
478 define("NONE", 0);
479 define("VARCHAR", 1);
480 define("INT", 2);
481 define("DECIMAL", 3);
482 define("BIGINT", 4);
483 define("GEOMETRY", 5);
485 /* Decimal size defs */
486 define("M", 0);
487 define("D", 1);
488 define("FULL", 2);
490 /* Table array defs */
491 define("TBL_NAME", 0);
492 define("COL_NAMES", 1);
493 define("ROWS", 2);
495 /* Analysis array defs */
496 define("TYPES", 0);
497 define("SIZES", 1);
498 define("FORMATTEDSQL", 2);
501 * Obtains the precision (total # of digits) from a size of type decimal
503 * @param string $last_cumulative_size
505 * @return int Precision of the given decimal size notation
506 * @access public
508 function PMA_getM($last_cumulative_size)
510 return (int)substr($last_cumulative_size, 0, strpos($last_cumulative_size, ","));
514 * Obtains the scale (# of digits to the right of the decimal point)
515 * from a size of type decimal
517 * @param string $last_cumulative_size
519 * @return int Scale of the given decimal size notation
520 * @access public
522 function PMA_getD($last_cumulative_size)
524 return (int) substr(
525 $last_cumulative_size,
526 (strpos($last_cumulative_size, ",") + 1),
527 (strlen($last_cumulative_size) - strpos($last_cumulative_size, ","))
532 * Obtains the decimal size of a given cell
534 * @param string &$cell cell content
536 * @return array Contains the precision, scale, and full size
537 * representation of the given decimal cell
538 * @access public
540 function PMA_getDecimalSize(&$cell)
542 $curr_size = strlen((string)$cell);
543 $decPos = strpos($cell, ".");
544 $decPrecision = ($curr_size - 1) - $decPos;
546 $m = $curr_size - 1;
547 $d = $decPrecision;
549 return array($m, $d, ($m . "," . $d));
553 * Obtains the size of the given cell
555 * @param string $last_cumulative_size Last cumulative column size
556 * @param int $last_cumulative_type Last cumulative column type
557 * (NONE or VARCHAR or DECIMAL or INT or BIGINT)
558 * @param int $curr_type Type of the current cell
559 * (NONE or VARCHAR or DECIMAL or INT or BIGINT)
560 * @param string &$cell The current cell
562 * @return string Size of the given cell in the type-appropriate format
563 * @access public
565 * @todo Handle the error cases more elegantly
567 function PMA_detectSize($last_cumulative_size, $last_cumulative_type,
568 $curr_type, &$cell
570 $curr_size = strlen((string)$cell);
573 * If the cell is NULL, don't treat it as a varchar
575 if (! strcmp('NULL', $cell)) {
576 return $last_cumulative_size;
577 } elseif ($curr_type == VARCHAR) {
579 * What to do if the current cell is of type VARCHAR
582 * The last cumulative type was VARCHAR
584 if ($last_cumulative_type == VARCHAR) {
585 if ($curr_size >= $last_cumulative_size) {
586 return $curr_size;
587 } else {
588 return $last_cumulative_size;
590 } elseif ($last_cumulative_type == DECIMAL) {
592 * The last cumulative type was DECIMAL
594 $oldM = PMA_getM($last_cumulative_size);
596 if ($curr_size >= $oldM) {
597 return $curr_size;
598 } else {
599 return $oldM;
601 } elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
603 * The last cumulative type was BIGINT or INT
605 if ($curr_size >= $last_cumulative_size) {
606 return $curr_size;
607 } else {
608 return $last_cumulative_size;
610 } elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
612 * This is the first row to be analyzed
614 return $curr_size;
615 } else {
617 * An error has DEFINITELY occurred
620 * TODO: Handle this MUCH more elegantly
623 return -1;
625 } elseif ($curr_type == DECIMAL) {
627 * What to do if the current cell is of type DECIMAL
630 * The last cumulative type was VARCHAR
632 if ($last_cumulative_type == VARCHAR) {
633 /* Convert $last_cumulative_size from varchar to decimal format */
634 $size = PMA_getDecimalSize($cell);
636 if ($size[M] >= $last_cumulative_size) {
637 return $size[M];
638 } else {
639 return $last_cumulative_size;
641 } elseif ($last_cumulative_type == DECIMAL) {
643 * The last cumulative type was DECIMAL
645 $size = PMA_getDecimalSize($cell);
647 $oldM = PMA_getM($last_cumulative_size);
648 $oldD = PMA_getD($last_cumulative_size);
650 /* New val if M or D is greater than current largest */
651 if ($size[M] > $oldM || $size[D] > $oldD) {
652 /* Take the largest of both types */
653 return (string) ((($size[M] > $oldM) ? $size[M] : $oldM)
654 . "," . (($size[D] > $oldD) ? $size[D] : $oldD));
655 } else {
656 return $last_cumulative_size;
658 } elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
660 * The last cumulative type was BIGINT or INT
662 /* Convert $last_cumulative_size from int to decimal format */
663 $size = PMA_getDecimalSize($cell);
665 if ($size[M] >= $last_cumulative_size) {
666 return $size[FULL];
667 } else {
668 return ($last_cumulative_size.",".$size[D]);
670 } elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
672 * This is the first row to be analyzed
674 /* First row of the column */
675 $size = PMA_getDecimalSize($cell);
677 return $size[FULL];
678 } else {
680 * An error has DEFINITELY occurred
683 * TODO: Handle this MUCH more elegantly
686 return -1;
688 } elseif ($curr_type == BIGINT || $curr_type == INT) {
690 * What to do if the current cell is of type BIGINT or INT
693 * The last cumulative type was VARCHAR
695 if ($last_cumulative_type == VARCHAR) {
696 if ($curr_size >= $last_cumulative_size) {
697 return $curr_size;
698 } else {
699 return $last_cumulative_size;
701 } elseif ($last_cumulative_type == DECIMAL) {
703 * The last cumulative type was DECIMAL
705 $oldM = PMA_getM($last_cumulative_size);
706 $oldD = PMA_getD($last_cumulative_size);
707 $oldInt = $oldM - $oldD;
708 $newInt = strlen((string)$cell);
710 /* See which has the larger integer length */
711 if ($oldInt >= $newInt) {
712 /* Use old decimal size */
713 return $last_cumulative_size;
714 } else {
715 /* Use $newInt + $oldD as new M */
716 return (($newInt + $oldD) . "," . $oldD);
718 } elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
720 * The last cumulative type was BIGINT or INT
722 if ($curr_size >= $last_cumulative_size) {
723 return $curr_size;
724 } else {
725 return $last_cumulative_size;
727 } elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
729 * This is the first row to be analyzed
731 return $curr_size;
732 } else {
734 * An error has DEFINITELY occurred
737 * TODO: Handle this MUCH more elegantly
740 return -1;
742 } else {
744 * An error has DEFINITELY occurred
747 * TODO: Handle this MUCH more elegantly
750 return -1;
755 * Determines what MySQL type a cell is
757 * @param int $last_cumulative_type Last cumulative column type
758 * (VARCHAR or INT or BIGINT or DECIMAL or NONE)
759 * @param string &$cell String representation of the cell for which
760 * a best-fit type is to be determined
762 * @return int The MySQL type representation
763 * (VARCHAR or INT or BIGINT or DECIMAL or NONE)
764 * @access public
766 function PMA_detectType($last_cumulative_type, &$cell)
769 * If numeric, determine if decimal, int or bigint
770 * Else, we call it varchar for simplicity
773 if (! strcmp('NULL', $cell)) {
774 if ($last_cumulative_type === null || $last_cumulative_type == NONE) {
775 return NONE;
776 } else {
777 return $last_cumulative_type;
779 } elseif (is_numeric($cell)) {
780 if ($cell == (string)(float)$cell
781 && strpos($cell, ".") !== false
782 && substr_count($cell, ".") == 1
784 return DECIMAL;
785 } else {
786 if (abs($cell) > 2147483647) {
787 return BIGINT;
788 } else {
789 return INT;
792 } else {
793 return VARCHAR;
798 * Determines if the column types are int, decimal, or string
800 * @param array &$table array(string $table_name, array $col_names, array $rows)
802 * @return array array(array $types, array $sizes)
803 * @access public
805 * @link http://wiki.phpmyadmin.net/pma/Import
807 * @todo Handle the error case more elegantly
809 function PMA_analyzeTable(&$table)
811 /* Get number of rows in table */
812 $numRows = count($table[ROWS]);
813 /* Get number of columns */
814 $numCols = count($table[COL_NAMES]);
815 /* Current type for each column */
816 $types = array();
817 $sizes = array();
819 /* Initialize $sizes to all 0's */
820 for ($i = 0; $i < $numCols; ++$i) {
821 $sizes[$i] = 0;
824 /* Initialize $types to NONE */
825 for ($i = 0; $i < $numCols; ++$i) {
826 $types[$i] = NONE;
829 /* Temp vars */
830 $curr_type = NONE;
832 /* If the passed array is not of the correct form, do not process it */
833 if (is_array($table)
834 && ! is_array($table[TBL_NAME])
835 && is_array($table[COL_NAMES])
836 && is_array($table[ROWS])
838 /* Analyze each column */
839 for ($i = 0; $i < $numCols; ++$i) {
840 /* Analyze the column in each row */
841 for ($j = 0; $j < $numRows; ++$j) {
842 /* Determine type of the current cell */
843 $curr_type = PMA_detectType($types[$i], $table[ROWS][$j][$i]);
844 /* Determine size of the current cell */
845 $sizes[$i] = PMA_detectSize(
846 $sizes[$i],
847 $types[$i],
848 $curr_type,
849 $table[ROWS][$j][$i]
853 * If a type for this column has already been declared,
854 * only alter it if it was a number and a varchar was found
856 if ($curr_type != NONE) {
857 if ($curr_type == VARCHAR) {
858 $types[$i] = VARCHAR;
859 } else if ($curr_type == DECIMAL) {
860 if ($types[$i] != VARCHAR) {
861 $types[$i] = DECIMAL;
863 } else if ($curr_type == BIGINT) {
864 if ($types[$i] != VARCHAR && $types[$i] != DECIMAL) {
865 $types[$i] = BIGINT;
867 } else if ($curr_type == INT) {
868 if ($types[$i] != VARCHAR
869 && $types[$i] != DECIMAL
870 && $types[$i] != BIGINT
872 $types[$i] = INT;
879 /* Check to ensure that all types are valid */
880 $len = count($types);
881 for ($n = 0; $n < $len; ++$n) {
882 if (! strcmp(NONE, $types[$n])) {
883 $types[$n] = VARCHAR;
884 $sizes[$n] = '10';
888 return array($types, $sizes);
889 } else {
891 * TODO: Handle this better
894 return false;
898 /* Needed to quell the beast that is PMA_Message */
899 $import_notice = null;
902 * Builds and executes SQL statements to create the database and tables
903 * as necessary, as well as insert all the data.
905 * @param string $db_name Name of the database
906 * @param array &$tables Array of tables for the specified database
907 * @param array &$analyses Analyses of the tables
908 * @param array &$additional_sql Additional SQL statements to be executed
909 * @param array $options Associative array of options
911 * @return void
912 * @access public
914 * @link http://wiki.phpmyadmin.net/pma/Import
916 function PMA_buildSQL($db_name, &$tables, &$analyses = null,
917 &$additional_sql = null, $options = null
919 /* Take care of the options */
920 if (isset($options['db_collation'])&& ! is_null($options['db_collation'])) {
921 $collation = $options['db_collation'];
922 } else {
923 $collation = "utf8_general_ci";
926 if (isset($options['db_charset']) && ! is_null($options['db_charset'])) {
927 $charset = $options['db_charset'];
928 } else {
929 $charset = "utf8";
932 if (isset($options['create_db'])) {
933 $create_db = $options['create_db'];
934 } else {
935 $create_db = true;
938 /* Create SQL code to handle the database */
939 $sql = array();
941 if ($create_db) {
942 if (PMA_DRIZZLE) {
943 $sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_Util::backquote($db_name)
944 . " COLLATE " . $collation;
945 } else {
946 $sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_Util::backquote($db_name)
947 . " DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation;
952 * The calling plug-in should include this statement,
953 * if necessary, in the $additional_sql parameter
955 * $sql[] = "USE " . backquote($db_name);
958 /* Execute the SQL statements create above */
959 $sql_len = count($sql);
960 for ($i = 0; $i < $sql_len; ++$i) {
961 PMA_importRunQuery($sql[$i], $sql[$i]);
964 /* No longer needed */
965 unset($sql);
967 /* Run the $additional_sql statements supplied by the caller plug-in */
968 if ($additional_sql != null) {
969 /* Clean the SQL first */
970 $additional_sql_len = count($additional_sql);
973 * Only match tables for now, because CREATE IF NOT EXISTS
974 * syntax is lacking or nonexisting for views, triggers,
975 * functions, and procedures.
977 * See: http://bugs.mysql.com/bug.php?id=15287
979 * To the best of my knowledge this is still an issue.
981 * $pattern = 'CREATE (TABLE|VIEW|TRIGGER|FUNCTION|PROCEDURE)';
983 $pattern = '/CREATE [^`]*(TABLE)/';
984 $replacement = 'CREATE \\1 IF NOT EXISTS';
986 /* Change CREATE statements to CREATE IF NOT EXISTS to support
987 * inserting into existing structures
989 for ($i = 0; $i < $additional_sql_len; ++$i) {
990 $additional_sql[$i] = preg_replace(
991 $pattern,
992 $replacement,
993 $additional_sql[$i]
995 /* Execute the resulting statements */
996 PMA_importRunQuery($additional_sql[$i], $additional_sql[$i]);
1000 if ($analyses != null) {
1001 $type_array = array(
1002 NONE => "NULL",
1003 VARCHAR => "varchar",
1004 INT => "int",
1005 DECIMAL => "decimal",
1006 BIGINT => "bigint",
1007 GEOMETRY => 'geometry'
1010 /* TODO: Do more checking here to make sure they really are matched */
1011 if (count($tables) != count($analyses)) {
1012 exit();
1015 /* Create SQL code to create the tables */
1016 $tempSQLStr = "";
1017 $num_tables = count($tables);
1018 for ($i = 0; $i < $num_tables; ++$i) {
1019 $num_cols = count($tables[$i][COL_NAMES]);
1020 $tempSQLStr = "CREATE TABLE IF NOT EXISTS " . PMA_Util::backquote($db_name)
1021 . '.' . PMA_Util::backquote($tables[$i][TBL_NAME]) . " (";
1022 for ($j = 0; $j < $num_cols; ++$j) {
1023 $size = $analyses[$i][SIZES][$j];
1024 if ((int)$size == 0) {
1025 $size = 10;
1028 $tempSQLStr .= PMA_Util::backquote($tables[$i][COL_NAMES][$j]) . " "
1029 . $type_array[$analyses[$i][TYPES][$j]];
1030 if ($analyses[$i][TYPES][$j] != GEOMETRY) {
1031 $tempSQLStr .= "(" . $size . ")";
1034 if ($j != (count($tables[$i][COL_NAMES]) - 1)) {
1035 $tempSQLStr .= ", ";
1038 $tempSQLStr .= ")"
1039 . (PMA_DRIZZLE ? "" : " DEFAULT CHARACTER SET " . $charset)
1040 . " COLLATE " . $collation . ";";
1043 * Each SQL statement is executed immediately
1044 * after it is formed so that we don't have
1045 * to store them in a (possibly large) buffer
1047 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
1052 * Create the SQL statements to insert all the data
1054 * Only one insert query is formed for each table
1056 $tempSQLStr = "";
1057 $col_count = 0;
1058 $num_tables = count($tables);
1059 for ($i = 0; $i < $num_tables; ++$i) {
1060 $num_cols = count($tables[$i][COL_NAMES]);
1061 $num_rows = count($tables[$i][ROWS]);
1063 $tempSQLStr = "INSERT INTO " . PMA_Util::backquote($db_name) . '.'
1064 . PMA_Util::backquote($tables[$i][TBL_NAME]) . " (";
1066 for ($m = 0; $m < $num_cols; ++$m) {
1067 $tempSQLStr .= PMA_Util::backquote($tables[$i][COL_NAMES][$m]);
1069 if ($m != ($num_cols - 1)) {
1070 $tempSQLStr .= ", ";
1074 $tempSQLStr .= ") VALUES ";
1076 for ($j = 0; $j < $num_rows; ++$j) {
1077 $tempSQLStr .= "(";
1079 for ($k = 0; $k < $num_cols; ++$k) {
1080 // If fully formatted SQL, no need to enclose
1081 // with aphostrophes, add shalshes etc.
1082 if ($analyses != null
1083 && isset($analyses[$i][FORMATTEDSQL][$col_count])
1084 && $analyses[$i][FORMATTEDSQL][$col_count] == true
1086 $tempSQLStr .= (string) $tables[$i][ROWS][$j][$k];
1087 } else {
1088 if ($analyses != null) {
1089 $is_varchar = ($analyses[$i][TYPES][$col_count] === VARCHAR);
1090 } else {
1091 $is_varchar = ! is_numeric($tables[$i][ROWS][$j][$k]);
1094 /* Don't put quotes around NULL fields */
1095 if (! strcmp($tables[$i][ROWS][$j][$k], 'NULL')) {
1096 $is_varchar = false;
1099 $tempSQLStr .= (($is_varchar) ? "'" : "");
1100 $tempSQLStr .= PMA_Util::sqlAddSlashes(
1101 (string) $tables[$i][ROWS][$j][$k]
1103 $tempSQLStr .= (($is_varchar) ? "'" : "");
1106 if ($k != ($num_cols - 1)) {
1107 $tempSQLStr .= ", ";
1110 if ($col_count == ($num_cols - 1)) {
1111 $col_count = 0;
1112 } else {
1113 $col_count++;
1116 /* Delete the cell after we are done with it */
1117 unset($tables[$i][ROWS][$j][$k]);
1120 $tempSQLStr .= ")";
1122 if ($j != ($num_rows - 1)) {
1123 $tempSQLStr .= ",\n ";
1126 $col_count = 0;
1127 /* Delete the row after we are done with it */
1128 unset($tables[$i][ROWS][$j]);
1131 $tempSQLStr .= ";";
1134 * Each SQL statement is executed immediately
1135 * after it is formed so that we don't have
1136 * to store them in a (possibly large) buffer
1138 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
1141 /* No longer needed */
1142 unset($tempSQLStr);
1145 * A work in progress
1148 /* Add the viewable structures from $additional_sql
1149 * to $tables so they are also displayed
1151 $view_pattern = '@VIEW `[^`]+`\.`([^`]+)@';
1152 $table_pattern = '@CREATE TABLE IF NOT EXISTS `([^`]+)`@';
1153 /* Check a third pattern to make sure its not a "USE `db_name`;" statement */
1155 $regs = array();
1157 $inTables = false;
1159 $additional_sql_len = count($additional_sql);
1160 for ($i = 0; $i < $additional_sql_len; ++$i) {
1161 preg_match($view_pattern, $additional_sql[$i], $regs);
1163 if (count($regs) == 0) {
1164 preg_match($table_pattern, $additional_sql[$i], $regs);
1167 if (count($regs)) {
1168 for ($n = 0; $n < $num_tables; ++$n) {
1169 if (! strcmp($regs[1], $tables[$n][TBL_NAME])) {
1170 $inTables = true;
1171 break;
1175 if (! $inTables) {
1176 $tables[] = array(TBL_NAME => $regs[1]);
1180 /* Reset the array */
1181 $regs = array();
1182 $inTables = false;
1185 $params = array('db' => (string)$db_name);
1186 $db_url = 'db_structure.php' . PMA_generate_common_url($params);
1187 $db_ops_url = 'db_operations.php' . PMA_generate_common_url($params);
1189 $message = '<br /><br />';
1190 $message .= '<strong>' . __('The following structures have either been created or altered. Here you can:') . '</strong><br />';
1191 $message .= '<ul><li>' . __("View a structure's contents by clicking on its name") . '</li>';
1192 $message .= '<li>' . __('Change any of its settings by clicking the corresponding "Options" link') . '</li>';
1193 $message .= '<li>' . __('Edit structure by following the "Structure" link') . '</li>';
1194 $message .= sprintf(
1195 '<br /><li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . __('Options') . '</a>)</li>',
1196 $db_url,
1197 sprintf(__('Go to database: %s'), htmlspecialchars(PMA_Util::backquote($db_name))),
1198 htmlspecialchars($db_name),
1199 $db_ops_url,
1200 sprintf(__('Edit settings for %s'), htmlspecialchars(PMA_Util::backquote($db_name)))
1203 $message .= '<ul>';
1205 unset($params);
1207 $num_tables = count($tables);
1208 for ($i = 0; $i < $num_tables; ++$i) {
1209 $params = array(
1210 'db' => (string) $db_name,
1211 'table' => (string) $tables[$i][TBL_NAME]
1213 $tbl_url = 'sql.php' . PMA_generate_common_url($params);
1214 $tbl_struct_url = 'tbl_structure.php' . PMA_generate_common_url($params);
1215 $tbl_ops_url = 'tbl_operations.php' . PMA_generate_common_url($params);
1217 unset($params);
1219 if (! PMA_Table::isView($db_name, $tables[$i][TBL_NAME])) {
1220 $message .= sprintf(
1221 '<li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . __('Structure') . '</a>) (<a href="%s" title="%s">' . __('Options') . '</a>)</li>',
1222 $tbl_url,
1223 sprintf(__('Go to table: %s'), htmlspecialchars(PMA_Util::backquote($tables[$i][TBL_NAME]))),
1224 htmlspecialchars($tables[$i][TBL_NAME]),
1225 $tbl_struct_url,
1226 sprintf(__('Structure of %s'), htmlspecialchars(PMA_Util::backquote($tables[$i][TBL_NAME]))),
1227 $tbl_ops_url,
1228 sprintf(__('Edit settings for %s'), htmlspecialchars(PMA_Util::backquote($tables[$i][TBL_NAME])))
1230 } else {
1231 $message .= sprintf(
1232 '<li><a href="%s" title="%s">%s</a></li>',
1233 $tbl_url,
1234 sprintf(__('Go to view: %s'), htmlspecialchars(PMA_Util::backquote($tables[$i][TBL_NAME]))),
1235 htmlspecialchars($tables[$i][TBL_NAME])
1240 $message .= '</ul></ul>';
1242 global $import_notice;
1243 $import_notice = $message;
1245 unset($tables);