remove todo, after upgrade PHPExcel
[phpmyadmin/arisferyanto.git] / libraries / import.lib.php
blob70e5f1385289103ab77a943df5e0bff92a080c3e
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 * @version $Id$
7 * @package phpMyAdmin
8 */
9 if (! defined('PHPMYADMIN')) {
10 exit;
13 /**
14 * We need to know something about user
16 require_once './libraries/check_user_privileges.lib.php';
18 /**
19 * We do this check, DROP DATABASE does not need to be confirmed elsewhere
21 define('PMA_CHK_DROP', 1);
23 /**
24 * Check whether timeout is getting close
26 * @return boolean true if timeout is close
27 * @access public
29 function PMA_checkTimeout()
31 global $timestamp, $maximum_time, $timeout_passed;
32 if ($maximum_time == 0) {
33 return FALSE;
34 } elseif ($timeout_passed) {
35 return TRUE;
36 /* 5 in next row might be too much */
37 } elseif ((time() - $timestamp) > ($maximum_time - 5)) {
38 $timeout_passed = TRUE;
39 return TRUE;
40 } else {
41 return FALSE;
45 /**
46 * Detects what compression filse uses
48 * @param string 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 * @uses $GLOBALS['finished'] read and write
78 * @param string query to run
79 * @param string query to display, this might be commented
80 * @param bool whether to use control user for queries
81 * @access public
83 function PMA_importRunQuery($sql = '', $full = '', $controluser = false)
85 global $import_run_buffer, $go_sql, $complete_query, $display_query,
86 $sql_query, $my_die, $error, $reload,
87 $last_query_with_results,
88 $skip_queries, $executed_queries, $max_sql_len, $read_multiply,
89 $cfg, $sql_query_disabled, $db, $run_query, $is_superuser;
90 $read_multiply = 1;
91 if (isset($import_run_buffer)) {
92 // Should we skip something?
93 if ($skip_queries > 0) {
94 $skip_queries--;
95 } else {
96 if (!empty($import_run_buffer['sql']) && trim($import_run_buffer['sql']) != '') {
97 $max_sql_len = max($max_sql_len, strlen($import_run_buffer['sql']));
98 if (!$sql_query_disabled) {
99 $sql_query .= $import_run_buffer['full'];
101 if (!$cfg['AllowUserDropDatabase']
102 && !$is_superuser
103 && preg_match('@^[[:space:]]*DROP[[:space:]]+(IF EXISTS[[:space:]]+)?DATABASE @i', $import_run_buffer['sql'])) {
104 $GLOBALS['message'] = PMA_Message::error('strNoDropDatabases');
105 $error = TRUE;
106 } else {
107 $executed_queries++;
108 if ($run_query && $GLOBALS['finished'] && empty($sql) && !$error && (
109 (!empty($import_run_buffer['sql']) && preg_match('/^[\s]*(SELECT|SHOW|HANDLER)/i', $import_run_buffer['sql'])) ||
110 ($executed_queries == 1)
111 )) {
112 $go_sql = TRUE;
113 if (!$sql_query_disabled) {
114 $complete_query = $sql_query;
115 $display_query = $sql_query;
116 } else {
117 $complete_query = '';
118 $display_query = '';
120 $sql_query = $import_run_buffer['sql'];
121 } elseif ($run_query) {
122 if ($controluser) {
123 $result = PMA_query_as_controluser($import_run_buffer['sql']);
124 } else {
125 $result = PMA_DBI_try_query($import_run_buffer['sql']);
127 $msg = '# ';
128 if ($result === FALSE) { // execution failed
129 if (!isset($my_die)) {
130 $my_die = array();
132 $my_die[] = array('sql' => $import_run_buffer['full'], 'error' => PMA_DBI_getError());
134 if ($cfg['VerboseMultiSubmit']) {
135 $msg .= $GLOBALS['strError'];
138 if (!$cfg['IgnoreMultiSubmitErrors']) {
139 $error = TRUE;
140 return;
142 } elseif ($cfg['VerboseMultiSubmit']) {
143 $a_num_rows = (int)@PMA_DBI_num_rows($result);
144 $a_aff_rows = (int)@PMA_DBI_affected_rows();
145 if ($a_num_rows > 0) {
146 $msg .= $GLOBALS['strRows'] . ': ' . $a_num_rows;
147 $last_query_with_results = $import_run_buffer['sql'];
148 } elseif ($a_aff_rows > 0) {
149 $msg .= sprintf($GLOBALS['strRowsAffected'], $a_aff_rows);
150 } else {
151 $msg .= $GLOBALS['strEmptyResultSet'];
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.)
306 * This algorithm only works up to ZZ. it fails on AAA (up to 701 columns)
308 * @author Derek Schaefer (derek.schaefer@gmail.com)
310 * @access public
312 * @uses chr()
313 * @param int $num
314 * @return string The column's "Excel" name
316 function PMA_getColumnAlphaName($num)
318 /* ASCII value for capital "A" */
319 $A = 65;
320 $sCol = "";
321 $iRemain = 0;
323 /* This algorithm only works up to ZZ. it fails on AAA */
325 if ($num > 701) {
326 return $num;
327 } elseif ($num <= 26) {
328 if ($num == 0) {
329 $sCol = chr(($A + 26) - 1);
330 } else {
331 $sCol = chr(($A + $num) - 1);
333 } else {
334 $iRemain = (($num / 26)) - 1;
335 if (($num % 26) == 0) {
336 $sCol = PMA_getColumnAlphaName($iRemain) . PMA_getColumnAlphaName($num % 26);
337 } else {
338 $sCol = chr($A + $iRemain) . PMA_getColumnAlphaName($num % 26);
342 return $sCol;
346 * Returns the column number based on the Excel name.
347 * So "A" = 1, "Z" = 26, "AA" = 27, etc.
349 * Basicly this is a base26 (A-Z) to base10 (0-9) conversion.
350 * It iterates through all characters in the column name and
351 * calculates the corresponding value, based on character value
352 * (A = 1, ..., Z = 26) and position in the string.
354 * @access public
356 * @uses strtoupper()
357 * @uses strlen()
358 * @uses ord()
359 * @param string $name (i.e. "A", or "BC", etc.)
360 * @return int The column number
362 function PMA_getColumnNumberFromName($name) {
363 if (!empty($name)) {
364 $name = strtoupper($name);
365 $num_chars = strlen($name);
366 $column_number = 0;
367 for ($i = 0; $i < $num_chars; ++$i) {
368 // read string from back to front
369 $char_pos = ($num_chars - 1) - $i;
371 // convert capital character to ASCII value
372 // and subtract 64 to get corresponding decimal value
373 // ASCII value of "A" is 65, "B" is 66, etc.
374 // Decimal equivalent of "A" is 1, "B" is 2, etc.
375 $number = (ord($name[$char_pos]) - 64);
377 // base26 to base10 conversion : multiply each number
378 // with corresponding value of the position, in this case
379 // $i=0 : 1; $i=1 : 26; $i=2 : 676; ...
380 $column_number += $number * pow(26,$i);
382 return $column_number;
383 } else {
384 return 0;
389 * Constants definitions
392 /* MySQL type defs */
393 define("NONE", 0);
394 define("VARCHAR", 1);
395 define("INT", 2);
396 define("DECIMAL", 3);
398 /* Decimal size defs */
399 define("M", 0);
400 define("D", 1);
401 define("FULL", 2);
403 /* Table array defs */
404 define("TBL_NAME", 0);
405 define("COL_NAMES", 1);
406 define("ROWS", 2);
408 /* Analysis array defs */
409 define("TYPES", 0);
410 define("SIZES", 1);
413 * Obtains the precision (total # of digits) from a size of type decimal
415 * @author Derek Schaefer (derek.schaefer@gmail.com)
417 * @access public
419 * @uses substr()
420 * @uses strpos()
421 * @param string $last_cumulative_size
422 * @return int Precision of the given decimal size notation
424 function PMA_getM($last_cumulative_size) {
425 return (int)substr($last_cumulative_size, 0, strpos($last_cumulative_size, ","));
429 * Obtains the scale (# of digits to the right of the decimal point) from a size of type decimal
431 * @author Derek Schaefer (derek.schaefer@gmail.com)
433 * @access public
435 * @uses substr()
436 * @uses strpos()
437 * @uses strlen()
438 * @param string $last_cumulative_size
439 * @return int Scale of the given decimal size notation
441 function PMA_getD($last_cumulative_size) {
442 return (int)substr($last_cumulative_size, (strpos($last_cumulative_size, ",") + 1), (strlen($last_cumulative_size) - strpos($last_cumulative_size, ",")));
446 * Obtains the decimal size of a given cell
448 * @author Derek Schaefer (derek.schaefer@gmail.com)
450 * @access public
452 * @uses strlen()
453 * @uses strpos()
454 * @param string &$cell
455 * @return array Contains the precision, scale, and full size representation of the given decimal cell
457 function PMA_getDecimalSize(&$cell) {
458 $curr_size = strlen((string)$cell);
459 $decPos = strpos($cell, ".");
460 $decPrecision = ($curr_size - 1) - $decPos;
462 $m = $curr_size - 1;
463 $d = $decPrecision;
465 return array($m, $d, ($m . "," . $d));
469 * Obtains the size of the given cell
471 * @author Derek Schaefer (derek.schaefer@gmail.com)
473 * @todo Handle the error cases more elegantly
475 * @access public
477 * @uses M
478 * @uses D
479 * @uses FULL
480 * @uses VARCHAR
481 * @uses DECIMAL
482 * @uses INT
483 * @uses NONE
484 * @uses strcmp()
485 * @uses strlen()
486 * @uses PMA_getM()
487 * @uses PMA_getD()
488 * @uses PMA_getDecimalSize()
489 * @param string $last_cumulative_size Last cumulative column size
490 * @param int $last_cumulative_type Last cumulative column type (NONE or VARCHAR or DECIMAL or INT)
491 * @param int $curr_type Type of the current cell (NONE or VARCHAR or DECIMAL or INT)
492 * @param string &$cell The current cell
493 * @return string Size of the given cell in the type-appropriate format
495 function PMA_detectSize($last_cumulative_size, $last_cumulative_type, $curr_type, &$cell) {
496 $curr_size = strlen((string)$cell);
499 * If the cell is NULL, don't treat it as a varchar
501 if (! strcmp('NULL', $cell)) {
502 return $last_cumulative_size;
505 * What to do if the current cell is of type VARCHAR
507 elseif ($curr_type == VARCHAR) {
509 * The last cumlative type was VARCHAR
511 if ($last_cumulative_type == VARCHAR) {
512 if ($curr_size >= $last_cumulative_size) {
513 return $curr_size;
514 } else {
515 return $last_cumulative_size;
519 * The last cumlative type was DECIMAL
521 elseif ($last_cumulative_type == DECIMAL) {
522 $oldM = PMA_getM($last_cumulative_size);
524 if ($curr_size >= $oldM) {
525 return $curr_size;
526 } else {
527 return $oldM;
531 * The last cumlative type was INT
533 elseif ($last_cumulative_type == INT) {
534 if ($curr_size >= $last_cumulative_size) {
535 return $curr_size;
536 } else {
537 return $last_cumulative_size;
541 * This is the first row to be analyzed
543 elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
544 return $curr_size;
547 * An error has DEFINITELY occurred
549 else {
551 * TODO: Handle this MUCH more elegantly
554 return -1;
558 * What to do if the current cell is of type DECIMAL
560 elseif ($curr_type == DECIMAL) {
562 * The last cumlative type was VARCHAR
564 if ($last_cumulative_type == VARCHAR) {
565 /* Convert $last_cumulative_size from varchar to decimal format */
566 $size = PMA_getDecimalSize($cell);
568 if ($size[M] >= $last_cumulative_size) {
569 return $size[M];
570 } else {
571 return $last_cumulative_size;
575 * The last cumlative type was DECIMAL
577 elseif ($last_cumulative_type == DECIMAL) {
578 $size = PMA_getDecimalSize($cell);
580 $oldM = PMA_getM($last_cumulative_size);
581 $oldD = PMA_getD($last_cumulative_size);
583 /* New val if M or D is greater than current largest */
584 if ($size[M] > $oldM || $size[D] > $oldD) {
585 /* Take the largest of both types */
586 return (string)((($size[M] > $oldM) ? $size[M] : $oldM) . "," . (($size[D] > $oldD) ? $size[D] : $oldD));
587 } else {
588 return $last_cumulative_size;
592 * The last cumlative type was INT
594 elseif ($last_cumulative_type == INT) {
595 /* Convert $last_cumulative_size from int to decimal format */
596 $size = PMA_getDecimalSize($cell);
598 if ($size[M] >= $last_cumulative_size) {
599 return $size[FULL];
600 } else {
601 return ($last_cumulative_size.",".$size[D]);
605 * This is the first row to be analyzed
607 elseif (! isset($last_cumulative_type) || $last_cumulative_type == NONE) {
608 /* First row of the column */
609 $size = PMA_getDecimalSize($cell);
611 return $size[FULL];
614 * An error has DEFINITELY occurred
616 else {
618 * TODO: Handle this MUCH more elegantly
621 return -1;
625 * What to do if the current cell is of type INT
627 elseif ($curr_type == INT) {
629 * The last cumlative type was VARCHAR
631 if ($last_cumulative_type == VARCHAR) {
632 if ($curr_size >= $last_cumulative_size) {
633 return $curr_size;
634 } else {
635 return $last_cumulative_size;
639 * The last cumlative type was DECIMAL
641 elseif ($last_cumulative_type == DECIMAL) {
642 $oldM = PMA_getM($last_cumulative_size);
643 $oldD = PMA_getD($last_cumulative_size);
644 $oldInt = $oldM - $oldD;
645 $newInt = strlen((string)$cell);
647 /* See which has the larger integer length */
648 if ($oldInt >= $newInt) {
649 /* Use old decimal size */
650 return $last_cumulative_size;
651 } else {
652 /* Use $newInt + $oldD as new M */
653 return (($newInt + $oldD) . "," . $oldD);
657 * The last cumlative type was INT
659 elseif ($last_cumulative_type == INT) {
660 if ($curr_size >= $last_cumulative_size) {
661 return $curr_size;
662 } else {
663 return $last_cumulative_size;
667 * This is the first row to be analyzed
669 elseif (!isset($last_cumulative_type) || $last_cumulative_type == NONE) {
670 return $curr_size;
673 * An error has DEFINITELY occurred
675 else {
677 * TODO: Handle this MUCH more elegantly
680 return -1;
684 * An error has DEFINITELY occurred
686 else {
688 * TODO: Handle this MUCH more elegantly
691 return -1;
696 * Determines what MySQL type a cell is
698 * @author Derek Schaefer (derek.schaefer@gmail.com)
700 * @access public
702 * @uses DECIMAL
703 * @uses INT
704 * @uses VARCHAR
705 * @uses NONE
706 * @uses is_numeric()
707 * @uses strcmp()
708 * @uses strpos()
709 * @uses substr_count()
710 * @param int $last_cumulative_type Last cumulative column type (VARCHAR or INT or DECIMAL or NONE)
711 * @param string &$cell String representation of the cell for which a best-fit type is to be determined
712 * @return int The MySQL type representation (VARCHAR or INT or DECIMAL or NONE)
714 function PMA_detectType($last_cumulative_type, &$cell) {
716 * If numeric, determine if decimal or int
717 * Else, we call it varchar for simplicity
720 if (! strcmp('NULL', $cell)) {
721 if ($last_cumulative_type === NULL || $last_cumulative_type == NONE) {
722 return NONE;
723 } else {
724 return $last_cumulative_type;
726 } elseif (is_numeric($cell)) {
727 if ($cell == (string)(float)$cell && strpos($cell, ".") !== false && substr_count($cell, ".") == 1) {
728 return DECIMAL;
729 } else {
730 return INT;
732 } else {
733 return VARCHAR;
738 * Determines if the column types are int, decimal, or string
740 * @author Derek Schaefer (derek.schaefer@gmail.com)
742 * @link http://wiki.phpmyadmin.net/pma/Devel:Import
744 * @todo Handle the error case more elegantly
746 * @access public
748 * @uses TBL_NAME
749 * @uses COL_NAMES
750 * @uses ROWS
751 * @uses VARCHAR
752 * @uses DECIMAL
753 * @uses INT
754 * @uses NONE
755 * @uses count()
756 * @uses is_array()
757 * @uses PMA_detectType()
758 * @uses PMA_detectSize()
759 * @param &$table array(string $table_name, array $col_names, array $rows)
760 * @return array array(array $types, array $sizes)
762 function PMA_analyzeTable(&$table) {
763 /* Get number of rows in table */
764 $numRows = count($table[ROWS]);
765 /* Get number of columns */
766 $numCols = count($table[COL_NAMES]);
767 /* Current type for each column */
768 $types = array();
769 $sizes = array();
771 /* Initialize $sizes to all 0's */
772 for ($i = 0; $i < $numCols; ++$i) {
773 $sizes[$i] = 0;
776 /* Initialize $types to NONE */
777 for ($i = 0; $i < $numCols; ++$i) {
778 $types[$i] = NONE;
781 /* Temp vars */
782 $curr_type = NONE;
783 $curr_size = 0;
785 /* If the passed array is not of the correct form, do not process it */
786 if (is_array($table) && ! is_array($table[TBL_NAME]) && is_array($table[COL_NAMES]) && is_array($table[ROWS])) {
787 /* Analyze each column */
788 for ($i = 0; $i < $numCols; ++$i) {
789 /* Analyze the column in each row */
790 for ($j = 0; $j < $numRows; ++$j) {
791 /* Determine type of the current cell */
792 $curr_type = PMA_detectType($types[$i], $table[ROWS][$j][$i]);
793 /* Determine size of the current cell */
794 $sizes[$i] = PMA_detectSize($sizes[$i], $types[$i], $curr_type, $table[ROWS][$j][$i]);
797 * If a type for this column has alreday been delcared,
798 * only alter it if it was a number and a varchar was found
800 if ($curr_type != NONE) {
801 if ($curr_type == VARCHAR) {
802 $types[$i] = VARCHAR;
803 } else if ($curr_type == DECIMAL) {
804 if ($types[$i] != VARCHAR) {
805 $types[$i] = DECIMAL;
807 } else if ($curr_type == INT) {
808 if ($types[$i] != VARCHAR && $types[$i] != DECIMAL) {
809 $types[$i] = INT;
816 /* Check to ensure that all types are valid */
817 $len = count($types);
818 for ($n = 0; $n < $len; ++$n) {
819 if (! strcmp(NONE, $types[$n])) {
820 $types[$n] = VARCHAR;
821 $sizes[$n] = '10';
825 return array($types, $sizes);
827 else
830 * TODO: Handle this better
833 return false;
837 /* Needed to quell the beast that is PMA_Message */
838 $import_notice = NULL;
841 * Builds and executes SQL statements to create the database and tables
842 * as necessary, as well as insert all the data.
844 * @author Derek Schaefer (derek.schaefer@gmail.com)
846 * @link http://wiki.phpmyadmin.net/pma/Devel:Import
848 * @access public
850 * @uses TBL_NAME
851 * @uses COL_NAMES
852 * @uses ROWS
853 * @uses TYPES
854 * @uses SIZES
855 * @uses strcmp()
856 * @uses count()
857 * @uses preg_match()
858 * @uses preg_replace()
859 * @uses PMA_isView()
860 * @uses PMA_backquote()
861 * @uses PMA_importRunQuery()
862 * @uses PMA_generate_common_url()
863 * @uses PMA_Message::notice()
864 * @param string $db_name Name of the database
865 * @param array &$tables Array of tables for the specified database
866 * @param array &$analyses = NULL Analyses of the tables
867 * @param array &$additional_sql = NULL Additional SQL statements to be executed
868 * @param array $options = NULL Associative array of options
869 * @return void
871 function PMA_buildSQL($db_name, &$tables, &$analyses = NULL, &$additional_sql = NULL, $options = NULL) {
872 /* Take care of the options */
873 if (isset($options['db_collation'])) {
874 $collation = $options['db_collation'];
875 } else {
876 $collation = "utf8_general_ci";
879 if (isset($options['db_charset'])) {
880 $charset = $options['db_charset'];
881 } else {
882 $charset = "utf8";
885 if (isset($options['create_db'])) {
886 $create_db = $options['create_db'];
887 } else {
888 $create_db = true;
891 /* Create SQL code to handle the database */
892 $sql = array();
894 if ($create_db) {
895 $sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_backquote($db_name) . " DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation;
899 * The calling plug-in should include this statement, if necessary, in the $additional_sql parameter
901 * $sql[] = "USE " . PMA_backquote($db_name);
904 /* Execute the SQL statements create above */
905 $sql_len = count($sql);
906 for ($i = 0; $i < $sql_len; ++$i) {
907 PMA_importRunQuery($sql[$i], $sql[$i]);
910 /* No longer needed */
911 unset($sql);
913 /* Run the $additional_sql statements supplied by the caller plug-in */
914 if ($additional_sql != NULL) {
915 /* Clean the SQL first */
916 $additional_sql_len = count($additional_sql);
919 * Only match tables for now, because CREATE IF NOT EXISTS
920 * syntax is lacking or nonexisting for views, triggers,
921 * functions, and procedures.
923 * See: http://bugs.mysql.com/bug.php?id=15287
925 * To the best of my knowledge this is still an issue.
927 * $pattern = 'CREATE (TABLE|VIEW|TRIGGER|FUNCTION|PROCEDURE)';
929 $pattern = '/CREATE .*(TABLE)/';
930 $replacement = 'CREATE \\1 IF NOT EXISTS';
932 /* Change CREATE statements to CREATE IF NOT EXISTS to support inserting into existing structures */
933 for ($i = 0; $i < $additional_sql_len; ++$i) {
934 $additional_sql[$i] = preg_replace($pattern, $replacement, $additional_sql[$i]);
935 /* Execute the resulting statements */
936 PMA_importRunQuery($additional_sql[$i], $additional_sql[$i]);
940 if ($analyses != NULL) {
941 $type_array = array(NONE => "NULL", VARCHAR => "varchar", INT => "int", DECIMAL => "decimal");
943 /* TODO: Do more checking here to make sure they really are matched */
944 if (count($tables) != count($analyses)) {
945 exit();
948 /* Create SQL code to create the tables */
949 $tempSQLStr = "";
950 $num_tables = count($tables);
951 for ($i = 0; $i < $num_tables; ++$i) {
952 $num_cols = count($tables[$i][COL_NAMES]);
953 $tempSQLStr = "CREATE TABLE IF NOT EXISTS " . PMA_backquote($db_name) . '.' . PMA_backquote($tables[$i][TBL_NAME]) . " (";
954 for ($j = 0; $j < $num_cols; ++$j) {
955 $size = $analyses[$i][SIZES][$j];
956 if ((int)$size == 0) {
957 $size = 10;
960 $tempSQLStr .= PMA_backquote($tables[$i][COL_NAMES][$j]) . " " . $type_array[$analyses[$i][TYPES][$j]] . "(" . $size . ")";
962 if ($j != (count($tables[$i][COL_NAMES]) - 1)) {
963 $tempSQLStr .= ", ";
966 $tempSQLStr .= ") ENGINE=MyISAM DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation . ";";
969 * Each SQL statement is executed immediately
970 * after it is formed so that we don't have
971 * to store them in a (possibly large) buffer
973 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
978 * Create the SQL statements to insert all the data
980 * Only one insert query is formed for each table
982 $tempSQLStr = "";
983 $col_count = 0;
984 $num_tables = count($tables);
985 for ($i = 0; $i < $num_tables; ++$i) {
986 $num_cols = count($tables[$i][COL_NAMES]);
987 $num_rows = count($tables[$i][ROWS]);
989 $tempSQLStr = "INSERT INTO " . PMA_backquote($db_name) . '.' . PMA_backquote($tables[$i][TBL_NAME]) . " (";
991 for ($m = 0; $m < $num_cols; ++$m) {
992 $tempSQLStr .= PMA_backquote($tables[$i][COL_NAMES][$m]);
994 if ($m != ($num_cols - 1)) {
995 $tempSQLStr .= ", ";
999 $tempSQLStr .= ") VALUES ";
1001 for ($j = 0; $j < $num_rows; ++$j) {
1002 $tempSQLStr .= "(";
1004 for ($k = 0; $k < $num_cols; ++$k) {
1005 if ($analyses != NULL) {
1006 $is_varchar = ($analyses[$i][TYPES][$col_count] === VARCHAR);
1007 } else {
1008 $is_varchar = !is_numeric($tables[$i][ROWS][$j][$k]);
1011 /* Don't put quotes around NULL fields */
1012 if (! strcmp($tables[$i][ROWS][$j][$k], 'NULL')) {
1013 $is_varchar = false;
1016 $tempSQLStr .= (($is_varchar) ? "'" : "");
1017 $tempSQLStr .= PMA_sqlAddslashes((string)$tables[$i][ROWS][$j][$k]);
1018 $tempSQLStr .= (($is_varchar) ? "'" : "");
1020 if ($k != ($num_cols - 1)) {
1021 $tempSQLStr .= ", ";
1024 if ($col_count == ($num_cols - 1)) {
1025 $col_count = 0;
1026 } else {
1027 $col_count++;
1030 /* Delete the cell after we are done with it */
1031 unset($tables[$i][ROWS][$j][$k]);
1034 $tempSQLStr .= ")";
1036 if ($j != ($num_rows - 1)) {
1037 $tempSQLStr .= ",\n ";
1040 $col_count = 0;
1041 /* Delete the row after we are done with it */
1042 unset($tables[$i][ROWS][$j]);
1045 $tempSQLStr .= ";";
1048 * Each SQL statement is executed immediately
1049 * after it is formed so that we don't have
1050 * to store them in a (possibly large) buffer
1052 PMA_importRunQuery($tempSQLStr, $tempSQLStr);
1055 /* No longer needed */
1056 unset($tempSQLStr);
1059 * A work in progress
1062 /* Add the viewable structures from $additional_sql to $tables so they are also displayed */
1064 $view_pattern = '@VIEW `[^`]+`\.`([^`]+)@';
1065 $table_pattern = '@CREATE TABLE IF NOT EXISTS `([^`]+)`@';
1066 /* Check a third pattern to make sure its not a "USE `db_name`;" statement */
1068 $regs = array();
1070 $inTables = false;
1072 $additional_sql_len = count($additional_sql);
1073 for ($i = 0; $i < $additional_sql_len; ++$i) {
1074 preg_match($view_pattern, $additional_sql[$i], $regs);
1076 if (count($regs) == 0) {
1077 preg_match($table_pattern, $additional_sql[$i], $regs);
1080 if (count($regs)) {
1081 for ($n = 0; $n < $num_tables; ++$n) {
1082 if (!strcmp($regs[1], $tables[$n][TBL_NAME])) {
1083 $inTables = true;
1084 break;
1088 if (!$inTables) {
1089 $tables[] = array(TBL_NAME => $regs[1]);
1093 /* Reset the array */
1094 $regs = array();
1095 $inTables = false;
1098 $params = array('db' => (string)$db_name);
1099 $db_url = 'db_structure.php' . PMA_generate_common_url($params);
1100 $db_ops_url = 'db_operations.php' . PMA_generate_common_url($params);
1102 $message = '<br /><br />';
1103 $message .= '<strong>' . $GLOBALS['strImportNoticePt1'] . '</strong><br />';
1104 $message .= '<ul><li>' . $GLOBALS['strImportNoticePt2'] . '</li>';
1105 $message .= '<li>' . $GLOBALS['strImportNoticePt3'] . '</li>';
1106 $message .= '<li>' . $GLOBALS['strImportNoticePt4'] . '</li>';
1107 $message .= sprintf('<br /><li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . $GLOBALS['strOptions'] . '</a>)</li>',
1108 $db_url,
1109 $GLOBALS['strGoToDatabase'] . ': ' . PMA_backquote($db_name),
1110 $db_name,
1111 $db_ops_url,
1112 $GLOBALS['strEdit'] . ' ' . PMA_backquote($db_name) . ' ' . $GLOBALS['strSettings']);
1114 $message .= '<ul>';
1116 unset($params);
1118 $num_tables = count($tables);
1119 for ($i = 0; $i < $num_tables; ++$i)
1121 $params = array('db' => (string)$db_name, 'table' => (string)$tables[$i][TBL_NAME]);
1122 $tbl_url = 'sql.php' . PMA_generate_common_url($params);
1123 $tbl_struct_url = 'tbl_structure.php' . PMA_generate_common_url($params);
1124 $tbl_ops_url = 'tbl_operations.php' . PMA_generate_common_url($params);
1126 unset($params);
1128 if (! PMA_isView($db_name, $tables[$i][TBL_NAME])) {
1129 $message .= sprintf('<li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . $GLOBALS['strStructure'] . '</a>) (<a href="%s" title="%s">' . $GLOBALS['strOptions'] . '</a>)</li>',
1130 $tbl_url,
1131 $GLOBALS['strGoToTable'] . ': ' . PMA_backquote($tables[$i][TBL_NAME]),
1132 $tables[$i][TBL_NAME],
1133 $tbl_struct_url,
1134 PMA_backquote($tables[$i][TBL_NAME]) . ' ' . $GLOBALS['strStructureLC'],
1135 $tbl_ops_url,
1136 $GLOBALS['strEdit'] . ' ' . PMA_backquote($tables[$i][TBL_NAME]) . ' ' . $GLOBALS['strSettings']);
1137 } else {
1138 $message .= sprintf('<li><a href="%s" title="%s">%s</a></li>',
1139 $tbl_url,
1140 $GLOBALS['strGoToView'] . ': ' . PMA_backquote($tables[$i][TBL_NAME]),
1141 $tables[$i][TBL_NAME]);
1145 $message .= '</ul></ul>';
1147 global $import_notice;
1148 $import_notice = $message;
1150 unset($tables);