Refactored ConfigFile class so that it is no longer a singleton
[phpmyadmin.git] / libraries / import.lib.php
blobadf22333175bbf152d4647c3dbeeb7cfbb9ab62b
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 SQL parse data storage
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, $result, $msg,
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 if (! isset($sql_data['valid_queries'])) {
143 $sql_data['valid_queries'] = 0;
145 $sql_data['valid_queries']++;
147 // If a 'USE <db>' SQL-clause was found,
148 // set our current $db to the new one
149 list($db, $reload) = PMA_lookForUse(
150 $import_run_buffer['sql'],
151 $db,
152 $reload
154 } elseif ($run_query) {
156 if ($controluser) {
157 $result = PMA_queryAsControlUser(
158 $import_run_buffer['sql']
160 } else {
161 $result = $GLOBALS['dbi']->tryQuery($import_run_buffer['sql']);
164 $msg = '# ';
165 if ($result === false) { // execution failed
166 if (! isset($my_die)) {
167 $my_die = array();
169 $my_die[] = array(
170 'sql' => $import_run_buffer['full'],
171 'error' => $GLOBALS['dbi']->getError()
174 $msg .= __('Error');
176 if (! $cfg['IgnoreMultiSubmitErrors']) {
177 $error = true;
178 return;
180 } else {
181 $a_num_rows = (int)@$GLOBALS['dbi']->numRows($result);
182 $a_aff_rows = (int)@$GLOBALS['dbi']->affectedRows();
183 if ($a_num_rows > 0) {
184 $msg .= __('Rows'). ': ' . $a_num_rows;
185 $last_query_with_results = $import_run_buffer['sql'];
186 } elseif ($a_aff_rows > 0) {
187 $message = PMA_Message::getMessageForAffectedRows($a_aff_rows);
188 $msg .= $message->getMessage();
189 } else {
190 $msg .= __('MySQL returned an empty result set (i.e. zero rows).');
193 if (($a_num_rows > 0) || $is_use_query) {
194 $sql_data['valid_sql'][] = $import_run_buffer['sql'];
195 if (! isset($sql_data['valid_queries'])) {
196 $sql_data['valid_queries'] = 0;
198 $sql_data['valid_queries']++;
202 if (! $sql_query_disabled) {
203 $sql_query .= $msg . "\n";
206 // If a 'USE <db>' SQL-clause was found and the query
207 // succeeded, set our current $db to the new one
208 if ($result != false) {
209 list($db, $reload) = PMA_lookForUse(
210 $import_run_buffer['sql'],
211 $db,
212 $reload
216 if ($result != false
217 && preg_match('@^[\s]*(DROP|CREATE)[\s]+(IF EXISTS[[:space:]]+)?(TABLE|DATABASE)[[:space:]]+(.+)@im', $import_run_buffer['sql'])
219 $reload = true;
221 } // end run query
222 } // end if not DROP DATABASE
223 // end non empty query
224 } elseif (! empty($import_run_buffer['full'])) {
225 if ($go_sql) {
226 $complete_query .= $import_run_buffer['full'];
227 $display_query .= $import_run_buffer['full'];
228 } else {
229 if (! $sql_query_disabled) {
230 $sql_query .= $import_run_buffer['full'];
234 // check length of query unless we decided to pass it to sql.php
235 // (if $run_query is false, we are just displaying so show
236 // the complete query in the textarea)
237 if (! $go_sql && $run_query) {
238 if (! empty($sql_query)) {
239 if (strlen($sql_query) > 50000
240 || $executed_queries > 50
241 || $max_sql_len > 1000
243 $sql_query = '';
244 $sql_query_disabled = true;
248 } // end do query (no skip)
249 } // end buffer exists
251 // Do we have something to push into buffer?
252 if (! empty($sql) || ! empty($full)) {
253 $import_run_buffer = array('sql' => $sql, 'full' => $full);
254 } else {
255 unset($GLOBALS['import_run_buffer']);
260 * Looks for the presence of USE to possibly change current db
262 * @param string $buffer buffer to examine
263 * @param string $db current db
264 * @param bool $reload reload
266 * @return array (current or new db, whether to reload)
267 * @access public
269 function PMA_lookForUse($buffer, $db, $reload)
271 if (preg_match('@^[\s]*USE[[:space:]]+([\S]+)@i', $buffer, $match)) {
272 $db = trim($match[1]);
273 $db = trim($db, ';'); // for example, USE abc;
275 // $db must not contain the escape characters generated by backquote()
276 // ( used in PMA_buildSQL() as: backquote($db_name), and then called
277 // in PMA_importRunQuery() which in turn calls PMA_lookForUse() )
278 $db = PMA_Util::unQuote($db);
280 $reload = true;
282 return(array($db, $reload));
287 * Returns next part of imported file/buffer
289 * @param int $size size of buffer to read
290 * (this is maximal size function will return)
292 * @return string part of file/buffer
293 * @access public
295 function PMA_importGetNextChunk($size = 32768)
297 global $compression, $import_handle, $charset_conversion, $charset_of_file,
298 $read_multiply;
300 // Add some progression while reading large amount of data
301 if ($read_multiply <= 8) {
302 $size *= $read_multiply;
303 } else {
304 $size *= 8;
306 $read_multiply++;
308 // We can not read too much
309 if ($size > $GLOBALS['read_limit']) {
310 $size = $GLOBALS['read_limit'];
313 if (PMA_checkTimeout()) {
314 return false;
316 if ($GLOBALS['finished']) {
317 return true;
320 if ($GLOBALS['import_file'] == 'none') {
321 // Well this is not yet supported and tested,
322 // but should return content of textarea
323 if (strlen($GLOBALS['import_text']) < $size) {
324 $GLOBALS['finished'] = true;
325 return $GLOBALS['import_text'];
326 } else {
327 $r = substr($GLOBALS['import_text'], 0, $size);
328 $GLOBALS['offset'] += $size;
329 $GLOBALS['import_text'] = substr($GLOBALS['import_text'], $size);
330 return $r;
334 switch ($compression) {
335 case 'application/bzip2':
336 $result = bzread($import_handle, $size);
337 $GLOBALS['finished'] = feof($import_handle);
338 break;
339 case 'application/gzip':
340 $result = gzread($import_handle, $size);
341 $GLOBALS['finished'] = feof($import_handle);
342 break;
343 case 'application/zip':
344 $result = substr($GLOBALS['import_text'], 0, $size);
345 $GLOBALS['import_text'] = substr($GLOBALS['import_text'], $size);
346 $GLOBALS['finished'] = empty($GLOBALS['import_text']);
347 break;
348 case 'none':
349 $result = fread($import_handle, $size);
350 $GLOBALS['finished'] = feof($import_handle);
351 break;
353 $GLOBALS['offset'] += $size;
355 if ($charset_conversion) {
356 return PMA_convertString($charset_of_file, 'utf-8', $result);
357 } else {
359 * Skip possible byte order marks (I do not think we need more
360 * charsets, but feel free to add more, you can use wikipedia for
361 * reference: <http://en.wikipedia.org/wiki/Byte_Order_Mark>)
363 * @todo BOM could be used for charset autodetection
365 if ($GLOBALS['offset'] == $size) {
366 // UTF-8
367 if (strncmp($result, "\xEF\xBB\xBF", 3) == 0) {
368 $result = substr($result, 3);
369 // UTF-16 BE, LE
370 } elseif (strncmp($result, "\xFE\xFF", 2) == 0
371 || strncmp($result, "\xFF\xFE", 2) == 0
373 $result = substr($result, 2);
376 return $result;
381 * Returns the "Excel" column name (i.e. 1 = "A", 26 = "Z", 27 = "AA", etc.)
383 * This functions uses recursion to build the Excel column name.
385 * The column number (1-26) is converted to the responding
386 * ASCII character (A-Z) and returned.
388 * If the column number is bigger than 26 (= num of letters in alfabet),
389 * an extra character needs to be added. To find this extra character,
390 * the number is divided by 26 and this value is passed to another instance
391 * of the same function (hence recursion). In that new instance the number is
392 * evaluated again, and if it is still bigger than 26, it is divided again
393 * and passed to another instance of the same function. This continues until
394 * the number is smaller than 26. Then the last called function returns
395 * the corresponding ASCII character to the function that called it.
396 * Each time a called function ends an extra character is added to the column name.
397 * When the first function is reached, the last character is addded and the complete
398 * column name is returned.
400 * @param int $num the column number
402 * @return string The column's "Excel" name
403 * @access public
405 function PMA_getColumnAlphaName($num)
407 $A = 65; // ASCII value for capital "A"
408 $col_name = "";
410 if ($num > 26) {
411 $div = (int)($num / 26);
412 $remain = (int)($num % 26);
414 // subtract 1 of divided value in case the modulus is 0,
415 // this is necessary because A-Z has no 'zero'
416 if ($remain == 0) {
417 $div--;
420 // recursive function call
421 $col_name = PMA_getColumnAlphaName($div);
422 // use modulus as new column number
423 $num = $remain;
426 if ($num == 0) {
427 // use 'Z' if column number is 0,
428 // this is necessary because A-Z has no 'zero'
429 $col_name .= chr(($A + 26) - 1);
430 } else {
431 // convert column number to ASCII character
432 $col_name .= chr(($A + $num) - 1);
435 return $col_name;
439 * Returns the column number based on the Excel name.
440 * So "A" = 1, "Z" = 26, "AA" = 27, etc.
442 * Basicly this is a base26 (A-Z) to base10 (0-9) conversion.
443 * It iterates through all characters in the column name and
444 * calculates the corresponding value, based on character value
445 * (A = 1, ..., Z = 26) and position in the string.
447 * @param string $name column name(i.e. "A", or "BC", etc.)
449 * @return int The column number
450 * @access public
452 function PMA_getColumnNumberFromName($name)
454 if (! empty($name)) {
455 $name = strtoupper($name);
456 $num_chars = strlen($name);
457 $column_number = 0;
458 for ($i = 0; $i < $num_chars; ++$i) {
459 // read string from back to front
460 $char_pos = ($num_chars - 1) - $i;
462 // convert capital character to ASCII value
463 // and subtract 64 to get corresponding decimal value
464 // ASCII value of "A" is 65, "B" is 66, etc.
465 // Decimal equivalent of "A" is 1, "B" is 2, etc.
466 $number = (ord($name[$char_pos]) - 64);
468 // base26 to base10 conversion : multiply each number
469 // with corresponding value of the position, in this case
470 // $i=0 : 1; $i=1 : 26; $i=2 : 676; ...
471 $column_number += $number * PMA_Util::pow(26, $i);
473 return $column_number;
474 } else {
475 return 0;
480 * Constants definitions
483 /* MySQL type defs */
484 define("NONE", 0);
485 define("VARCHAR", 1);
486 define("INT", 2);
487 define("DECIMAL", 3);
488 define("BIGINT", 4);
489 define("GEOMETRY", 5);
491 /* Decimal size defs */
492 define("M", 0);
493 define("D", 1);
494 define("FULL", 2);
496 /* Table array defs */
497 define("TBL_NAME", 0);
498 define("COL_NAMES", 1);
499 define("ROWS", 2);
501 /* Analysis array defs */
502 define("TYPES", 0);
503 define("SIZES", 1);
504 define("FORMATTEDSQL", 2);
507 * Obtains the precision (total # of digits) from a size of type decimal
509 * @param string $last_cumulative_size
511 * @return int Precision of the given decimal size notation
512 * @access public
514 function PMA_getM($last_cumulative_size)
516 return (int)substr($last_cumulative_size, 0, strpos($last_cumulative_size, ","));
520 * Obtains the scale (# of digits to the right of the decimal point)
521 * from a size of type decimal
523 * @param string $last_cumulative_size
525 * @return int Scale of the given decimal size notation
526 * @access public
528 function PMA_getD($last_cumulative_size)
530 return (int) substr(
531 $last_cumulative_size,
532 (strpos($last_cumulative_size, ",") + 1),
533 (strlen($last_cumulative_size) - strpos($last_cumulative_size, ","))
538 * Obtains the decimal size of a given cell
540 * @param string $cell cell content
542 * @return array Contains the precision, scale, and full size
543 * representation of the given decimal cell
544 * @access public
546 function PMA_getDecimalSize($cell)
548 $curr_size = strlen((string)$cell);
549 $decPos = strpos($cell, ".");
550 $decPrecision = ($curr_size - 1) - $decPos;
552 $m = $curr_size - 1;
553 $d = $decPrecision;
555 return array($m, $d, ($m . "," . $d));
559 * Obtains the size of the given cell
561 * @param string $last_cumulative_size Last cumulative column size
562 * @param int $last_cumulative_type Last cumulative column type
563 * (NONE or VARCHAR or DECIMAL or INT or BIGINT)
564 * @param int $curr_type Type of the current cell
565 * (NONE or VARCHAR or DECIMAL or INT or BIGINT)
566 * @param string $cell The current cell
568 * @return string Size of the given cell in the type-appropriate format
569 * @access public
571 * @todo Handle the error cases more elegantly
573 function PMA_detectSize($last_cumulative_size, $last_cumulative_type,
574 $curr_type, $cell
576 $curr_size = strlen((string)$cell);
579 * If the cell is NULL, don't treat it as a varchar
581 if (! strcmp('NULL', $cell)) {
582 return $last_cumulative_size;
583 } elseif ($curr_type == VARCHAR) {
585 * What to do if the current cell is of type VARCHAR
588 * The last cumulative type was VARCHAR
590 if ($last_cumulative_type == VARCHAR) {
591 if ($curr_size >= $last_cumulative_size) {
592 return $curr_size;
593 } else {
594 return $last_cumulative_size;
596 } elseif ($last_cumulative_type == DECIMAL) {
598 * The last cumulative type was DECIMAL
600 $oldM = PMA_getM($last_cumulative_size);
602 if ($curr_size >= $oldM) {
603 return $curr_size;
604 } else {
605 return $oldM;
607 } elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
609 * The last cumulative type was BIGINT or INT
611 if ($curr_size >= $last_cumulative_size) {
612 return $curr_size;
613 } else {
614 return $last_cumulative_size;
616 } elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
618 * This is the first row to be analyzed
620 return $curr_size;
621 } else {
623 * An error has DEFINITELY occurred
626 * TODO: Handle this MUCH more elegantly
629 return -1;
631 } elseif ($curr_type == DECIMAL) {
633 * What to do if the current cell is of type DECIMAL
636 * The last cumulative type was VARCHAR
638 if ($last_cumulative_type == VARCHAR) {
639 /* Convert $last_cumulative_size from varchar to decimal format */
640 $size = PMA_getDecimalSize($cell);
642 if ($size[M] >= $last_cumulative_size) {
643 return $size[M];
644 } else {
645 return $last_cumulative_size;
647 } elseif ($last_cumulative_type == DECIMAL) {
649 * The last cumulative type was DECIMAL
651 $size = PMA_getDecimalSize($cell);
653 $oldM = PMA_getM($last_cumulative_size);
654 $oldD = PMA_getD($last_cumulative_size);
656 /* New val if M or D is greater than current largest */
657 if ($size[M] > $oldM || $size[D] > $oldD) {
658 /* Take the largest of both types */
659 return (string) ((($size[M] > $oldM) ? $size[M] : $oldM)
660 . "," . (($size[D] > $oldD) ? $size[D] : $oldD));
661 } else {
662 return $last_cumulative_size;
664 } elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
666 * The last cumulative type was BIGINT or INT
668 /* Convert $last_cumulative_size from int to decimal format */
669 $size = PMA_getDecimalSize($cell);
671 if ($size[M] >= $last_cumulative_size) {
672 return $size[FULL];
673 } else {
674 return ($last_cumulative_size.",".$size[D]);
676 } elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
678 * This is the first row to be analyzed
680 /* First row of the column */
681 $size = PMA_getDecimalSize($cell);
683 return $size[FULL];
684 } else {
686 * An error has DEFINITELY occurred
689 * TODO: Handle this MUCH more elegantly
692 return -1;
694 } elseif ($curr_type == BIGINT || $curr_type == INT) {
696 * What to do if the current cell is of type BIGINT or INT
699 * The last cumulative type was VARCHAR
701 if ($last_cumulative_type == VARCHAR) {
702 if ($curr_size >= $last_cumulative_size) {
703 return $curr_size;
704 } else {
705 return $last_cumulative_size;
707 } elseif ($last_cumulative_type == DECIMAL) {
709 * The last cumulative type was DECIMAL
711 $oldM = PMA_getM($last_cumulative_size);
712 $oldD = PMA_getD($last_cumulative_size);
713 $oldInt = $oldM - $oldD;
714 $newInt = strlen((string)$cell);
716 /* See which has the larger integer length */
717 if ($oldInt >= $newInt) {
718 /* Use old decimal size */
719 return $last_cumulative_size;
720 } else {
721 /* Use $newInt + $oldD as new M */
722 return (($newInt + $oldD) . "," . $oldD);
724 } elseif ($last_cumulative_type == BIGINT || $last_cumulative_type == INT) {
726 * The last cumulative type was BIGINT or INT
728 if ($curr_size >= $last_cumulative_size) {
729 return $curr_size;
730 } else {
731 return $last_cumulative_size;
733 } elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
735 * This is the first row to be analyzed
737 return $curr_size;
738 } else {
740 * An error has DEFINITELY occurred
743 * TODO: Handle this MUCH more elegantly
746 return -1;
748 } else {
750 * An error has DEFINITELY occurred
753 * TODO: Handle this MUCH more elegantly
756 return -1;
761 * Determines what MySQL type a cell is
763 * @param int $last_cumulative_type Last cumulative column type
764 * (VARCHAR or INT or BIGINT or DECIMAL or NONE)
765 * @param string $cell String representation of the cell for which
766 * a best-fit type is to be determined
768 * @return int The MySQL type representation
769 * (VARCHAR or INT or BIGINT or DECIMAL or NONE)
770 * @access public
772 function PMA_detectType($last_cumulative_type, $cell)
775 * If numeric, determine if decimal, int or bigint
776 * Else, we call it varchar for simplicity
779 if (! strcmp('NULL', $cell)) {
780 if ($last_cumulative_type === null || $last_cumulative_type == NONE) {
781 return NONE;
782 } else {
783 return $last_cumulative_type;
785 } elseif (is_numeric($cell)) {
786 if ($cell == (string)(float)$cell
787 && strpos($cell, ".") !== false
788 && substr_count($cell, ".") == 1
790 return DECIMAL;
791 } else {
792 if (abs($cell) > 2147483647) {
793 return BIGINT;
794 } else {
795 return INT;
798 } else {
799 return VARCHAR;
804 * Determines if the column types are int, decimal, or string
806 * @param array &$table array(string $table_name, array $col_names, array $rows)
808 * @return array array(array $types, array $sizes)
809 * @access public
811 * @link http://wiki.phpmyadmin.net/pma/Import
813 * @todo Handle the error case more elegantly
815 function PMA_analyzeTable(&$table)
817 /* Get number of rows in table */
818 $numRows = count($table[ROWS]);
819 /* Get number of columns */
820 $numCols = count($table[COL_NAMES]);
821 /* Current type for each column */
822 $types = array();
823 $sizes = array();
825 /* Initialize $sizes to all 0's */
826 for ($i = 0; $i < $numCols; ++$i) {
827 $sizes[$i] = 0;
830 /* Initialize $types to NONE */
831 for ($i = 0; $i < $numCols; ++$i) {
832 $types[$i] = NONE;
835 /* Temp vars */
836 $curr_type = NONE;
838 /* If the passed array is not of the correct form, do not process it */
839 if (is_array($table)
840 && ! is_array($table[TBL_NAME])
841 && is_array($table[COL_NAMES])
842 && is_array($table[ROWS])
844 /* Analyze each column */
845 for ($i = 0; $i < $numCols; ++$i) {
846 /* Analyze the column in each row */
847 for ($j = 0; $j < $numRows; ++$j) {
848 /* Determine type of the current cell */
849 $curr_type = PMA_detectType($types[$i], $table[ROWS][$j][$i]);
850 /* Determine size of the current cell */
851 $sizes[$i] = PMA_detectSize(
852 $sizes[$i],
853 $types[$i],
854 $curr_type,
855 $table[ROWS][$j][$i]
859 * If a type for this column has already been declared,
860 * only alter it if it was a number and a varchar was found
862 if ($curr_type != NONE) {
863 if ($curr_type == VARCHAR) {
864 $types[$i] = VARCHAR;
865 } else if ($curr_type == DECIMAL) {
866 if ($types[$i] != VARCHAR) {
867 $types[$i] = DECIMAL;
869 } else if ($curr_type == BIGINT) {
870 if ($types[$i] != VARCHAR && $types[$i] != DECIMAL) {
871 $types[$i] = BIGINT;
873 } else if ($curr_type == INT) {
874 if ($types[$i] != VARCHAR
875 && $types[$i] != DECIMAL
876 && $types[$i] != BIGINT
878 $types[$i] = INT;
885 /* Check to ensure that all types are valid */
886 $len = count($types);
887 for ($n = 0; $n < $len; ++$n) {
888 if (! strcmp(NONE, $types[$n])) {
889 $types[$n] = VARCHAR;
890 $sizes[$n] = '10';
894 return array($types, $sizes);
895 } else {
897 * TODO: Handle this better
900 return false;
904 /* Needed to quell the beast that is PMA_Message */
905 $import_notice = null;
908 * Builds and executes SQL statements to create the database and tables
909 * as necessary, as well as insert all the data.
911 * @param string $db_name Name of the database
912 * @param array &$tables Array of tables for the specified database
913 * @param array &$analyses Analyses of the tables
914 * @param array &$additional_sql Additional SQL statements to be executed
915 * @param array $options Associative array of options
917 * @return void
918 * @access public
920 * @link http://wiki.phpmyadmin.net/pma/Import
922 function PMA_buildSQL($db_name, &$tables, &$analyses = null,
923 &$additional_sql = null, $options = null
925 /* Take care of the options */
926 if (isset($options['db_collation'])&& ! is_null($options['db_collation'])) {
927 $collation = $options['db_collation'];
928 } else {
929 $collation = "utf8_general_ci";
932 if (isset($options['db_charset']) && ! is_null($options['db_charset'])) {
933 $charset = $options['db_charset'];
934 } else {
935 $charset = "utf8";
938 if (isset($options['create_db'])) {
939 $create_db = $options['create_db'];
940 } else {
941 $create_db = true;
944 /* Create SQL code to handle the database */
945 $sql = array();
947 if ($create_db) {
948 if (PMA_DRIZZLE) {
949 $sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_Util::backquote($db_name)
950 . " COLLATE " . $collation;
951 } else {
952 $sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_Util::backquote($db_name)
953 . " DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation;
958 * The calling plug-in should include this statement,
959 * if necessary, in the $additional_sql parameter
961 * $sql[] = "USE " . backquote($db_name);
964 /* Execute the SQL statements create above */
965 $sql_len = count($sql);
966 for ($i = 0; $i < $sql_len; ++$i) {
967 PMA_importRunQuery($sql[$i], $sql[$i]);
970 /* No longer needed */
971 unset($sql);
973 /* Run the $additional_sql statements supplied by the caller plug-in */
974 if ($additional_sql != null) {
975 /* Clean the SQL first */
976 $additional_sql_len = count($additional_sql);
979 * Only match tables for now, because CREATE IF NOT EXISTS
980 * syntax is lacking or nonexisting for views, triggers,
981 * functions, and procedures.
983 * See: http://bugs.mysql.com/bug.php?id=15287
985 * To the best of my knowledge this is still an issue.
987 * $pattern = 'CREATE (TABLE|VIEW|TRIGGER|FUNCTION|PROCEDURE)';
989 $pattern = '/CREATE [^`]*(TABLE)/';
990 $replacement = 'CREATE \\1 IF NOT EXISTS';
992 /* Change CREATE statements to CREATE IF NOT EXISTS to support
993 * inserting into existing structures
995 for ($i = 0; $i < $additional_sql_len; ++$i) {
996 $additional_sql[$i] = preg_replace(
997 $pattern,
998 $replacement,
999 $additional_sql[$i]
1001 /* Execute the resulting statements */
1002 PMA_importRunQuery($additional_sql[$i], $additional_sql[$i]);
1006 if ($analyses != null) {
1007 $type_array = array(
1008 NONE => "NULL",
1009 VARCHAR => "varchar",
1010 INT => "int",
1011 DECIMAL => "decimal",
1012 BIGINT => "bigint",
1013 GEOMETRY => 'geometry'
1016 /* TODO: Do more checking here to make sure they really are matched */
1017 if (count($tables) != count($analyses)) {
1018 exit();
1021 /* Create SQL code to create the tables */
1022 $tempSQLStr = "";
1023 $num_tables = count($tables);
1024 for ($i = 0; $i < $num_tables; ++$i) {
1025 $num_cols = count($tables[$i][COL_NAMES]);
1026 $tempSQLStr = "CREATE TABLE IF NOT EXISTS "
1027 . PMA_Util::backquote($db_name)
1028 . '.' . PMA_Util::backquote($tables[$i][TBL_NAME]) . " (";
1029 for ($j = 0; $j < $num_cols; ++$j) {
1030 $size = $analyses[$i][SIZES][$j];
1031 if ((int)$size == 0) {
1032 $size = 10;
1035 $tempSQLStr .= PMA_Util::backquote($tables[$i][COL_NAMES][$j]) . " "
1036 . $type_array[$analyses[$i][TYPES][$j]];
1037 if ($analyses[$i][TYPES][$j] != GEOMETRY) {
1038 $tempSQLStr .= "(" . $size . ")";
1041 if ($j != (count($tables[$i][COL_NAMES]) - 1)) {
1042 $tempSQLStr .= ", ";
1045 $tempSQLStr .= ")"
1046 . (PMA_DRIZZLE ? "" : " DEFAULT CHARACTER SET " . $charset)
1047 . " COLLATE " . $collation . ";";
1050 * Each SQL statement is executed immediately
1051 * after it is formed so that we don't have
1052 * to store them in a (possibly large) buffer
1054 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
1059 * Create the SQL statements to insert all the data
1061 * Only one insert query is formed for each table
1063 $tempSQLStr = "";
1064 $col_count = 0;
1065 $num_tables = count($tables);
1066 for ($i = 0; $i < $num_tables; ++$i) {
1067 $num_cols = count($tables[$i][COL_NAMES]);
1068 $num_rows = count($tables[$i][ROWS]);
1070 $tempSQLStr = "INSERT INTO " . PMA_Util::backquote($db_name) . '.'
1071 . PMA_Util::backquote($tables[$i][TBL_NAME]) . " (";
1073 for ($m = 0; $m < $num_cols; ++$m) {
1074 $tempSQLStr .= PMA_Util::backquote($tables[$i][COL_NAMES][$m]);
1076 if ($m != ($num_cols - 1)) {
1077 $tempSQLStr .= ", ";
1081 $tempSQLStr .= ") VALUES ";
1083 for ($j = 0; $j < $num_rows; ++$j) {
1084 $tempSQLStr .= "(";
1086 for ($k = 0; $k < $num_cols; ++$k) {
1087 // If fully formatted SQL, no need to enclose
1088 // with aphostrophes, add shalshes etc.
1089 if ($analyses != null
1090 && isset($analyses[$i][FORMATTEDSQL][$col_count])
1091 && $analyses[$i][FORMATTEDSQL][$col_count] == true
1093 $tempSQLStr .= (string) $tables[$i][ROWS][$j][$k];
1094 } else {
1095 if ($analyses != null) {
1096 $is_varchar = ($analyses[$i][TYPES][$col_count] === VARCHAR);
1097 } else {
1098 $is_varchar = ! is_numeric($tables[$i][ROWS][$j][$k]);
1101 /* Don't put quotes around NULL fields */
1102 if (! strcmp($tables[$i][ROWS][$j][$k], 'NULL')) {
1103 $is_varchar = false;
1106 $tempSQLStr .= (($is_varchar) ? "'" : "");
1107 $tempSQLStr .= PMA_Util::sqlAddSlashes(
1108 (string) $tables[$i][ROWS][$j][$k]
1110 $tempSQLStr .= (($is_varchar) ? "'" : "");
1113 if ($k != ($num_cols - 1)) {
1114 $tempSQLStr .= ", ";
1117 if ($col_count == ($num_cols - 1)) {
1118 $col_count = 0;
1119 } else {
1120 $col_count++;
1123 /* Delete the cell after we are done with it */
1124 unset($tables[$i][ROWS][$j][$k]);
1127 $tempSQLStr .= ")";
1129 if ($j != ($num_rows - 1)) {
1130 $tempSQLStr .= ",\n ";
1133 $col_count = 0;
1134 /* Delete the row after we are done with it */
1135 unset($tables[$i][ROWS][$j]);
1138 $tempSQLStr .= ";";
1141 * Each SQL statement is executed immediately
1142 * after it is formed so that we don't have
1143 * to store them in a (possibly large) buffer
1145 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
1148 /* No longer needed */
1149 unset($tempSQLStr);
1152 * A work in progress
1155 /* Add the viewable structures from $additional_sql
1156 * to $tables so they are also displayed
1158 $view_pattern = '@VIEW `[^`]+`\.`([^`]+)@';
1159 $table_pattern = '@CREATE TABLE IF NOT EXISTS `([^`]+)`@';
1160 /* Check a third pattern to make sure its not a "USE `db_name`;" statement */
1162 $regs = array();
1164 $inTables = false;
1166 $additional_sql_len = count($additional_sql);
1167 for ($i = 0; $i < $additional_sql_len; ++$i) {
1168 preg_match($view_pattern, $additional_sql[$i], $regs);
1170 if (count($regs) == 0) {
1171 preg_match($table_pattern, $additional_sql[$i], $regs);
1174 if (count($regs)) {
1175 for ($n = 0; $n < $num_tables; ++$n) {
1176 if (! strcmp($regs[1], $tables[$n][TBL_NAME])) {
1177 $inTables = true;
1178 break;
1182 if (! $inTables) {
1183 $tables[] = array(TBL_NAME => $regs[1]);
1187 /* Reset the array */
1188 $regs = array();
1189 $inTables = false;
1192 $params = array('db' => (string)$db_name);
1193 $db_url = 'db_structure.php' . PMA_URL_getCommon($params);
1194 $db_ops_url = 'db_operations.php' . PMA_URL_getCommon($params);
1196 $message = '<br /><br />';
1197 $message .= '<strong>' . __('The following structures have either been created or altered. Here you can:') . '</strong><br />';
1198 $message .= '<ul><li>' . __("View a structure's contents by clicking on its name") . '</li>';
1199 $message .= '<li>' . __('Change any of its settings by clicking the corresponding "Options" link') . '</li>';
1200 $message .= '<li>' . __('Edit structure by following the "Structure" link') . '</li>';
1201 $message .= sprintf(
1202 '<br /><li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">'
1203 . __('Options') . '</a>)</li>',
1204 $db_url,
1205 sprintf(
1206 __('Go to database: %s'),
1207 htmlspecialchars(PMA_Util::backquote($db_name))
1209 htmlspecialchars($db_name),
1210 $db_ops_url,
1211 sprintf(
1212 __('Edit settings for %s'),
1213 htmlspecialchars(PMA_Util::backquote($db_name))
1217 $message .= '<ul>';
1219 unset($params);
1221 $num_tables = count($tables);
1222 for ($i = 0; $i < $num_tables; ++$i) {
1223 $params = array(
1224 'db' => (string) $db_name,
1225 'table' => (string) $tables[$i][TBL_NAME]
1227 $tbl_url = 'sql.php' . PMA_URL_getCommon($params);
1228 $tbl_struct_url = 'tbl_structure.php' . PMA_URL_getCommon($params);
1229 $tbl_ops_url = 'tbl_operations.php' . PMA_URL_getCommon($params);
1231 unset($params);
1233 if (! PMA_Table::isView($db_name, $tables[$i][TBL_NAME])) {
1234 $message .= sprintf(
1235 '<li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . __('Structure') . '</a>) (<a href="%s" title="%s">' . __('Options') . '</a>)</li>',
1236 $tbl_url,
1237 sprintf(
1238 __('Go to table: %s'),
1239 htmlspecialchars(
1240 PMA_Util::backquote($tables[$i][TBL_NAME])
1243 htmlspecialchars($tables[$i][TBL_NAME]),
1244 $tbl_struct_url,
1245 sprintf(
1246 __('Structure of %s'),
1247 htmlspecialchars(
1248 PMA_Util::backquote($tables[$i][TBL_NAME])
1251 $tbl_ops_url,
1252 sprintf(
1253 __('Edit settings for %s'),
1254 htmlspecialchars(
1255 PMA_Util::backquote($tables[$i][TBL_NAME])
1259 } else {
1260 $message .= sprintf(
1261 '<li><a href="%s" title="%s">%s</a></li>',
1262 $tbl_url,
1263 sprintf(
1264 __('Go to view: %s'),
1265 htmlspecialchars(
1266 PMA_Util::backquote($tables[$i][TBL_NAME])
1269 htmlspecialchars($tables[$i][TBL_NAME])
1274 $message .= '</ul></ul>';
1276 global $import_notice;
1277 $import_notice = $message;
1279 unset($tables);