forked from phpmyadmin/phpmyadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDatabaseInterface.class.php
2407 lines (2226 loc) · 88.7 KB
/
DatabaseInterface.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Main interface for database interactions
*
* @package PhpMyAdmin-DBI
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* Main interface for database interactions
*
* @package PhpMyAdmin-DBI
*/
class PMA_DatabaseInterface
{
/**
* Force STORE_RESULT method, ignored by classic MySQL.
*/
const QUERY_STORE = 1;
/**
* Do not read whole query.
*/
const QUERY_UNBUFFERED = 2;
/**
* Get session variable.
*/
const GETVAR_SESSION = 1;
/**
* Get global variable.
*/
const GETVAR_GLOBAL = 2;
private $_extension;
/**
* Constructor
*
* @param object $ext PMA_DBI_Extension object to be used for database queries
*/
public function __construct($ext)
{
$this->_extension = $ext;
}
/**
* Checks whether database extension is loaded
*
* @param string $extension mysql extension to check
*
* @return bool
*/
public static function checkDbExtension($extension = 'mysql')
{
if ($extension == 'drizzle' && function_exists('drizzle_create')) {
return true;
} else if (function_exists($extension . '_connect')) {
return true;
}
return false;
}
/**
* runs a query
*
* @param string $query SQL query to execte
* @param mixed $link optional database link to use
* @param int $options optional query options
* @param bool $cache_affected_rows whether to cache affected rows
*
* @return mixed
*/
public function query($query, $link = null, $options = 0,
$cache_affected_rows = true
) {
$res = $this->tryQuery($query, $link, $options, $cache_affected_rows)
or PMA_Util::mysqlDie($this->getError($link), $query);
return $res;
}
/**
* Stores query data into session data for debugging purposes
*
* @param string $query Query text
* @param resource $link database link
* @param resource $result Query result
* @param integer $time Time to execute query
*
* @return void
*/
private function _dbgQuery($query, $link, $result, $time)
{
$hash = md5($query);
if (isset($_SESSION['debug']['queries'][$hash])) {
$_SESSION['debug']['queries'][$hash]['count']++;
} else {
$_SESSION['debug']['queries'][$hash] = array();
if ($result == false) {
$_SESSION['debug']['queries'][$hash]['error']
= '<b style="color:red">' . mysqli_error($link) . '</b>';
}
$_SESSION['debug']['queries'][$hash]['count'] = 1;
$_SESSION['debug']['queries'][$hash]['query'] = $query;
$_SESSION['debug']['queries'][$hash]['time'] = $time;
}
$trace = array();
foreach (debug_backtrace() as $trace_step) {
$trace[]
= (isset($trace_step['file'])
? PMA_Error::relPath($trace_step['file'])
: '')
. (isset($trace_step['line'])
? '#' . $trace_step['line'] . ': '
: '')
. (isset($trace_step['class']) ? $trace_step['class'] : '')
. (isset($trace_step['type']) ? $trace_step['type'] : '')
. (isset($trace_step['function']) ? $trace_step['function'] : '')
. '('
. (isset($trace_step['params'])
? implode(', ', $trace_step['params'])
: ''
)
. ')'
;
}
$_SESSION['debug']['queries'][$hash]['trace'][] = $trace;
}
/**
* runs a query and returns the result
*
* @param string $query query to run
* @param resource $link mysql link resource
* @param integer $options query options
* @param bool $cache_affected_rows whether to cache affected row
*
* @return mixed
*/
public function tryQuery($query, $link = null, $options = 0,
$cache_affected_rows = true
) {
if (empty($link)) {
if (isset($GLOBALS['userlink'])) {
$link = $GLOBALS['userlink'];
} else {
return false;
}
}
if ($GLOBALS['cfg']['DBG']['sql']) {
$time = microtime(true);
}
$result = $this->_extension->realQuery($query, $link, $options);
if ($cache_affected_rows) {
$GLOBALS['cached_affected_rows'] = $this->affectedRows($link, false);
}
if ($GLOBALS['cfg']['DBG']['sql']) {
$time = microtime(true) - $time;
$this->_dbgQuery($query, $link, $result, $time);
}
if ($result != false && PMA_Tracker::isActive() == true ) {
PMA_Tracker::handleQuery($query);
}
return $result;
}
/**
* Run multi query statement and return results
*
* @param string $multi_query multi query statement to execute
* @param mysqli $link mysqli object
*
* @return mysqli_result collection | boolean(false)
*/
public function tryMultiQuery($multi_query = '', $link = null)
{
if (empty($link)) {
if (isset($GLOBALS['userlink'])) {
$link = $GLOBALS['userlink'];
} else {
return false;
}
}
return $this->_extension->realMultiQuery($link, $multi_query);
}
/**
* converts charset of a mysql message, usually coming from mysql_error(),
* into PMA charset, usally UTF-8
* uses language to charset mapping from mysql/share/errmsg.txt
* and charset names to ISO charset from information_schema.CHARACTER_SETS
*
* @param string $message the message
*
* @return string $message
*/
public function convertMessage($message)
{
// latin always last!
$encodings = array(
'japanese' => 'EUC-JP', //'ujis',
'japanese-sjis' => 'Shift-JIS', //'sjis',
'korean' => 'EUC-KR', //'euckr',
'russian' => 'KOI8-R', //'koi8r',
'ukrainian' => 'KOI8-U', //'koi8u',
'greek' => 'ISO-8859-7', //'greek',
'serbian' => 'CP1250', //'cp1250',
'estonian' => 'ISO-8859-13', //'latin7',
'slovak' => 'ISO-8859-2', //'latin2',
'czech' => 'ISO-8859-2', //'latin2',
'hungarian' => 'ISO-8859-2', //'latin2',
'polish' => 'ISO-8859-2', //'latin2',
'romanian' => 'ISO-8859-2', //'latin2',
'spanish' => 'CP1252', //'latin1',
'swedish' => 'CP1252', //'latin1',
'italian' => 'CP1252', //'latin1',
'norwegian-ny' => 'CP1252', //'latin1',
'norwegian' => 'CP1252', //'latin1',
'portuguese' => 'CP1252', //'latin1',
'danish' => 'CP1252', //'latin1',
'dutch' => 'CP1252', //'latin1',
'english' => 'CP1252', //'latin1',
'french' => 'CP1252', //'latin1',
'german' => 'CP1252', //'latin1',
);
$server_language = $this->fetchValue(
'SHOW VARIABLES LIKE \'language\';',
0,
1
);
if ($server_language) {
$found = array();
$match = preg_match(
'&(?:\\\|\\/)([^\\\\\/]*)(?:\\\|\\/)$&i',
$server_language,
$found
);
if ($match) {
$server_language = $found[1];
}
}
if (! empty($server_language) && isset($encodings[$server_language])) {
$encoding = $encodings[$server_language];
} else {
/* Fallback to CP1252 if we can not detect */
$encoding = 'CP1252';
}
if (function_exists('iconv')) {
if ((@stristr(PHP_OS, 'AIX'))
&& (@strcasecmp(ICONV_IMPL, 'unknown') == 0)
&& (@strcasecmp(ICONV_VERSION, 'unknown') == 0)
) {
include_once './libraries/iconv_wrapper.lib.php';
$message = PMA_aix_iconv_wrapper(
$encoding,
'utf-8' . $GLOBALS['cfg']['IconvExtraParams'],
$message
);
} else {
$message = iconv(
$encoding,
'utf-8' . $GLOBALS['cfg']['IconvExtraParams'],
$message
);
}
} elseif (function_exists('recode_string')) {
$message = recode_string(
$encoding . '..' . 'utf-8',
$message
);
} elseif (function_exists('libiconv')) {
$message = libiconv($encoding, 'utf-8', $message);
} elseif (function_exists('mb_convert_encoding')) {
// do not try unsupported charsets
if (! in_array($server_language, array('ukrainian', 'greek', 'serbian'))) {
$message = mb_convert_encoding(
$message,
'utf-8',
$encoding
);
}
}
return $message;
}
/**
* returns array with table names for given db
*
* @param string $database name of database
* @param mixed $link mysql link resource|object
*
* @return array tables names
*/
public function getTables($database, $link = null)
{
return $this->fetchResult(
'SHOW TABLES FROM ' . PMA_Util::backquote($database) . ';',
null,
0,
$link,
self::QUERY_STORE
);
}
/**
* returns array of all tables in given db or dbs
* this function expects unquoted names:
* RIGHT: my_database
* WRONG: `my_database`
* WRONG: my\_database
* if $tbl_is_group is true, $table is used as filter for table names
* if $tbl_is_group is 'comment, $table is used as filter for table comments
*
* <code>
* $GLOBALS['dbi']->getTablesFull('my_database');
* $GLOBALS['dbi']->getTablesFull('my_database', 'my_table'));
* $GLOBALS['dbi']->getTablesFull('my_database', 'my_tables_', true));
* $GLOBALS['dbi']->getTablesFull('my_database', 'my_tables_', 'comment'));
* </code>
*
* @param string $database database
* @param string|bool $table table or false
* @param boolean|string $tbl_is_group $table is a table group
* @param mixed $link mysql link
* @param integer $limit_offset zero-based offset for the count
* @param boolean|integer $limit_count number of tables to return
* @param string $sort_by table attribute to sort by
* @param string $sort_order direction to sort (ASC or DESC)
*
* @todo move into PMA_Table
*
* @return array list of tables in given db(s)
*/
public function getTablesFull($database, $table = false,
$tbl_is_group = false, $link = null, $limit_offset = 0,
$limit_count = false, $sort_by = 'Name', $sort_order = 'ASC'
) {
if (true === $limit_count) {
$limit_count = $GLOBALS['cfg']['MaxTableList'];
}
// prepare and check parameters
if (! is_array($database)) {
$databases = array($database);
} else {
$databases = $database;
}
$tables = array();
if (! $GLOBALS['cfg']['Server']['DisableIS']) {
// get table information from information_schema
if ($table) {
if (true === $tbl_is_group) {
$sql_where_table = 'AND t.`TABLE_NAME` LIKE \''
. PMA_Util::escapeMysqlWildcards(
PMA_Util::sqlAddSlashes($table)
)
. '%\'';
} elseif ('comment' === $tbl_is_group) {
$sql_where_table = 'AND t.`TABLE_COMMENT` LIKE \''
. PMA_Util::escapeMysqlWildcards(
PMA_Util::sqlAddSlashes($table)
)
. '%\'';
} else {
$sql_where_table = 'AND t.`TABLE_NAME` = \''
. PMA_Util::sqlAddSlashes($table) . '\'';
}
} else {
$sql_where_table = '';
}
// for PMA bc:
// `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME`
//
// on non-Windows servers,
// added BINARY in the WHERE clause to force a case sensitive
// comparison (if we are looking for the db Aa we don't want
// to find the db aa)
$this_databases = array_map('PMA_Util::sqlAddSlashes', $databases);
if (PMA_DRIZZLE) {
$engine_info = PMA_Util::cacheGet('drizzle_engines', true);
$stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
if (isset($engine_info['InnoDB'])
&& $engine_info['InnoDB']['module_library'] == 'innobase'
) {
$stats_join = "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS"
. " stat ON (t.ENGINE = 'InnoDB' AND stat.NAME"
. " = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)";
}
// data_dictionary.table_cache may not contain any data
// for some tables, it's just a table cache
// auto_increment == 0 is cast to NULL because currently
// (2011.03.13 GA)
// Drizzle doesn't provide correct value
$sql = "
SELECT t.*,
t.TABLE_SCHEMA AS `Db`,
t.TABLE_NAME AS `Name`,
t.TABLE_TYPE AS `TABLE_TYPE`,
t.ENGINE AS `Engine`,
t.ENGINE AS `Type`,
t.TABLE_VERSION AS `Version`,-- VERSION
t.ROW_FORMAT AS `Row_format`,
coalesce(tc.ROWS, stat.NUM_ROWS)
AS `Rows`,-- TABLE_ROWS,
coalesce(tc.ROWS, stat.NUM_ROWS)
AS `TABLE_ROWS`,
tc.AVG_ROW_LENGTH AS `Avg_row_length`, -- AVG_ROW_LENGTH
tc.TABLE_SIZE AS `Data_length`, -- DATA_LENGTH
NULL AS `Max_data_length`, -- MAX_DATA_LENGTH
NULL AS `Index_length`, -- INDEX_LENGTH
NULL AS `Data_free`, -- DATA_FREE
nullif(t.AUTO_INCREMENT, 0)
AS `Auto_increment`,
t.TABLE_CREATION_TIME AS `Create_time`, -- CREATE_TIME
t.TABLE_UPDATE_TIME AS `Update_time`, -- UPDATE_TIME
NULL AS `Check_time`, -- CHECK_TIME
t.TABLE_COLLATION AS `Collation`,
NULL AS `Checksum`, -- CHECKSUM
NULL AS `Create_options`, -- CREATE_OPTIONS
t.TABLE_COMMENT AS `Comment`
FROM data_dictionary.TABLES t
LEFT JOIN data_dictionary.TABLE_CACHE tc
ON tc.TABLE_SCHEMA = t.TABLE_SCHEMA AND tc.TABLE_NAME
= t.TABLE_NAME
$stats_join
WHERE t.TABLE_SCHEMA IN ('" . implode("', '", $this_databases) . "')
" . $sql_where_table;
} else {
$sql = '
SELECT *,
`TABLE_SCHEMA` AS `Db`,
`TABLE_NAME` AS `Name`,
`TABLE_TYPE` AS `TABLE_TYPE`,
`ENGINE` AS `Engine`,
`ENGINE` AS `Type`,
`VERSION` AS `Version`,
`ROW_FORMAT` AS `Row_format`,
`TABLE_ROWS` AS `Rows`,
`AVG_ROW_LENGTH` AS `Avg_row_length`,
`DATA_LENGTH` AS `Data_length`,
`MAX_DATA_LENGTH` AS `Max_data_length`,
`INDEX_LENGTH` AS `Index_length`,
`DATA_FREE` AS `Data_free`,
`AUTO_INCREMENT` AS `Auto_increment`,
`CREATE_TIME` AS `Create_time`,
`UPDATE_TIME` AS `Update_time`,
`CHECK_TIME` AS `Check_time`,
`TABLE_COLLATION` AS `Collation`,
`CHECKSUM` AS `Checksum`,
`CREATE_OPTIONS` AS `Create_options`,
`TABLE_COMMENT` AS `Comment`
FROM `information_schema`.`TABLES` t
WHERE ' . (PMA_IS_WINDOWS ? '' : 'BINARY') . ' `TABLE_SCHEMA`
IN (\'' . implode("', '", $this_databases) . '\')
' . $sql_where_table;
}
// Sort the tables
$sql .= " ORDER BY $sort_by $sort_order";
if ($limit_count) {
$sql .= ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
}
$tables = $this->fetchResult(
$sql, array('TABLE_SCHEMA', 'TABLE_NAME'), null, $link
);
unset($sql_where_table, $sql);
if (PMA_DRIZZLE) {
// correct I_S and D_D names returned by D_D.TABLES -
// Drizzle generally uses lower case for them,
// but TABLES returns uppercase
foreach ((array)$database as $db) {
$db_upper = strtoupper($db);
if (!isset($tables[$db]) && isset($tables[$db_upper])) {
$tables[$db] = $tables[$db_upper];
unset($tables[$db_upper]);
}
}
}
if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
// here, the array's first key is by schema name
foreach ($tables as $one_database_name => $one_database_tables) {
uksort($one_database_tables, 'strnatcasecmp');
if ($sort_order == 'DESC') {
$one_database_tables = array_reverse($one_database_tables);
}
$tables[$one_database_name] = $one_database_tables;
}
}
} // end (get information from table schema)
// If permissions are wrong on even one database directory,
// information_schema does not return any table info for any database
// this is why we fall back to SHOW TABLE STATUS even for MySQL >= 50002
if (empty($tables) && !PMA_DRIZZLE) {
foreach ($databases as $each_database) {
if ($table || (true === $tbl_is_group)) {
$sql = 'SHOW TABLE STATUS FROM '
. PMA_Util::backquote($each_database)
.' LIKE \''
. PMA_Util::escapeMysqlWildcards(
PMA_Util::sqlAddSlashes($table, true)
)
. '%\'';
} else {
$sql = 'SHOW TABLE STATUS FROM '
. PMA_Util::backquote($each_database);
}
$useStatusCache = false;
if (extension_loaded('apc')
&& isset($GLOBALS['cfg']['Server']['StatusCacheDatabases'])
&& ! empty($GLOBALS['cfg']['Server']['StatusCacheLifetime'])
) {
$statusCacheDatabases
= (array) $GLOBALS['cfg']['Server']['StatusCacheDatabases'];
if (in_array($each_database, $statusCacheDatabases)) {
$useStatusCache = true;
}
}
$each_tables = null;
if ($useStatusCache) {
$cacheKey = 'phpMyAdmin_tableStatus_'
. sha1($GLOBALS['cfg']['Server']['host'] . '_' . $sql);
$each_tables = apc_fetch($cacheKey);
}
if (! $each_tables) {
$each_tables = $this->fetchResult($sql, 'Name', null, $link);
}
if ($useStatusCache) {
apc_store(
$cacheKey, $each_tables,
$GLOBALS['cfg']['Server']['StatusCacheLifetime']
);
}
// Sort naturally if the config allows it and we're sorting
// the Name column.
if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
uksort($each_tables, 'strnatcasecmp');
if ($sort_order == 'DESC') {
$each_tables = array_reverse($each_tables);
}
} else {
// Prepare to sort by creating array of the selected sort
// value to pass to array_multisort
// Size = Data_length + Index_length
if ($sort_by == 'Data_length') {
foreach ($each_tables as $table_name => $table_data) {
${$sort_by}[$table_name] = strtolower(
$table_data['Data_length'] + $table_data['Index_length']
);
}
} else {
foreach ($each_tables as $table_name => $table_data) {
${$sort_by}[$table_name]
= strtolower($table_data[$sort_by]);
}
}
if ($sort_order == 'DESC') {
array_multisort($$sort_by, SORT_DESC, $each_tables);
} else {
array_multisort($$sort_by, SORT_ASC, $each_tables);
}
// cleanup the temporary sort array
unset($$sort_by);
}
if ($limit_count) {
$each_tables = array_slice(
$each_tables, $limit_offset, $limit_count
);
}
foreach ($each_tables as $table_name => $each_table) {
if ('comment' === $tbl_is_group
&& 0 === strpos($each_table['Comment'], $table)
) {
// remove table from list
unset($each_tables[$table_name]);
continue;
}
if (! isset($each_tables[$table_name]['Type'])
&& isset($each_tables[$table_name]['Engine'])
) {
// pma BC, same parts of PMA still uses 'Type'
$each_tables[$table_name]['Type']
=& $each_tables[$table_name]['Engine'];
} elseif (! isset($each_tables[$table_name]['Engine'])
&& isset($each_tables[$table_name]['Type'])) {
// old MySQL reports Type, newer MySQL reports Engine
$each_tables[$table_name]['Engine']
=& $each_tables[$table_name]['Type'];
}
// MySQL forward compatibility
// so pma could use this array as if every server
// is of version >5.0
// todo : remove and check usage in the rest of the code,
// MySQL 5.0 is required by current PMA version
$each_tables[$table_name]['TABLE_SCHEMA']
= $each_database;
$each_tables[$table_name]['TABLE_NAME']
=& $each_tables[$table_name]['Name'];
$each_tables[$table_name]['ENGINE']
=& $each_tables[$table_name]['Engine'];
$each_tables[$table_name]['VERSION']
=& $each_tables[$table_name]['Version'];
$each_tables[$table_name]['ROW_FORMAT']
=& $each_tables[$table_name]['Row_format'];
$each_tables[$table_name]['TABLE_ROWS']
=& $each_tables[$table_name]['Rows'];
$each_tables[$table_name]['AVG_ROW_LENGTH']
=& $each_tables[$table_name]['Avg_row_length'];
$each_tables[$table_name]['DATA_LENGTH']
=& $each_tables[$table_name]['Data_length'];
$each_tables[$table_name]['MAX_DATA_LENGTH']
=& $each_tables[$table_name]['Max_data_length'];
$each_tables[$table_name]['INDEX_LENGTH']
=& $each_tables[$table_name]['Index_length'];
$each_tables[$table_name]['DATA_FREE']
=& $each_tables[$table_name]['Data_free'];
$each_tables[$table_name]['AUTO_INCREMENT']
=& $each_tables[$table_name]['Auto_increment'];
$each_tables[$table_name]['CREATE_TIME']
=& $each_tables[$table_name]['Create_time'];
$each_tables[$table_name]['UPDATE_TIME']
=& $each_tables[$table_name]['Update_time'];
$each_tables[$table_name]['CHECK_TIME']
=& $each_tables[$table_name]['Check_time'];
$each_tables[$table_name]['TABLE_COLLATION']
=& $each_tables[$table_name]['Collation'];
$each_tables[$table_name]['CHECKSUM']
=& $each_tables[$table_name]['Checksum'];
$each_tables[$table_name]['CREATE_OPTIONS']
=& $each_tables[$table_name]['Create_options'];
$each_tables[$table_name]['TABLE_COMMENT']
=& $each_tables[$table_name]['Comment'];
if (strtoupper($each_tables[$table_name]['Comment']) === 'VIEW'
&& $each_tables[$table_name]['Engine'] == null
) {
$each_tables[$table_name]['TABLE_TYPE'] = 'VIEW';
} else {
/**
* @todo difference between 'TEMPORARY' and 'BASE TABLE'
* but how to detect?
*/
$each_tables[$table_name]['TABLE_TYPE'] = 'BASE TABLE';
}
}
$tables[$each_database] = $each_tables;
}
}
// cache table data
// so PMA_Table does not require to issue SHOW TABLE STATUS again
// Note: I don't see why we would need array_merge_recursive() here,
// as it creates double entries for the same table (for example a double
// entry for Comment when changing the storage engine in Operations)
// Note 2: Instead of array_merge(), simply use the + operator because
// array_merge() renumbers numeric keys starting with 0, therefore
// we would lose a db name thats consists only of numbers
foreach ($tables as $one_database => $its_tables) {
if (isset(PMA_Table::$cache[$one_database])) {
PMA_Table::$cache[$one_database]
= PMA_Table::$cache[$one_database] + $tables[$one_database];
} else {
PMA_Table::$cache[$one_database] = $tables[$one_database];
}
}
unset($one_database, $its_tables);
if (! is_array($database)) {
if (isset($tables[$database])) {
return $tables[$database];
} elseif (isset($tables[strtolower($database)])) {
// on windows with lower_case_table_names = 1
// MySQL returns
// with SHOW DATABASES or information_schema.SCHEMATA: `Test`
// but information_schema.TABLES gives `test`
// bug #2036
// https://sourceforge.net/p/phpmyadmin/bugs/2036/
return $tables[strtolower($database)];
} else {
// one database but inexact letter case match
// as Drizzle is always case insensitive,
// we can safely return the only result
if (PMA_DRIZZLE && count($tables) == 1) {
$keys = array_keys($tables);
if (strlen(array_pop($keys)) == strlen($database)) {
return array_pop($tables);
}
}
return $tables;
}
} else {
return $tables;
}
}
/**
* Get VIEWs in a particular database
*
* @param string $db Database name to look in
*
* @return array $views Set of VIEWs inside the database
*/
public function getVirtualTables($db)
{
$tables_full = $this->getTablesFull($db);
$views = array();
foreach ($tables_full as $table=>$tmp) {
if (PMA_Table::isView($db, $table)) {
$views[] = $table;
}
}
return $views;
}
/**
* returns array with databases containing extended infos about them
*
* @param string $database database
* @param boolean $force_stats retrieve stats also for MySQL < 5
* @param resource $link mysql link
* @param string $sort_by column to order by
* @param string $sort_order ASC or DESC
* @param integer $limit_offset starting offset for LIMIT
* @param bool|int $limit_count row count for LIMIT or true
* for $GLOBALS['cfg']['MaxDbList']
*
* @todo move into PMA_List_Database?
*
* @return array $databases
*/
public function getDatabasesFull($database = null, $force_stats = false,
$link = null, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC',
$limit_offset = 0, $limit_count = false
) {
$sort_order = strtoupper($sort_order);
if (true === $limit_count) {
$limit_count = $GLOBALS['cfg']['MaxDbList'];
}
// initialize to avoid errors when there are no databases
$databases = array();
$apply_limit_and_order_manual = true;
if (! $GLOBALS['cfg']['Server']['DisableIS']) {
/**
* if $GLOBALS['cfg']['NaturalOrder'] is enabled, we cannot use LIMIT
* cause MySQL does not support natural ordering,
* we have to do it afterward
*/
$limit = '';
if (! $GLOBALS['cfg']['NaturalOrder']) {
if ($limit_count) {
$limit = ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
}
$apply_limit_and_order_manual = false;
}
// get table information from information_schema
if ($database) {
$sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \''
. PMA_Util::sqlAddSlashes($database) . '\'';
} else {
$sql_where_schema = '';
}
if (PMA_DRIZZLE) {
// data_dictionary.table_cache may not contain any data for some
// tables, it's just a table cache
$sql = 'SELECT
s.SCHEMA_NAME,
s.DEFAULT_COLLATION_NAME';
if ($force_stats) {
// no TABLE_CACHE data, stable results are better than
// constantly changing
$sql .= ',
COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
SUM(stat.NUM_ROWS) AS SCHEMA_TABLE_ROWS';
}
$sql .= '
FROM data_dictionary.SCHEMAS s';
if ($force_stats) {
$engine_info = PMA_Util::cacheGet('drizzle_engines', true);
$stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
if (isset($engine_info['InnoDB'])
&& $engine_info['InnoDB']['module_library'] == 'innobase'
) {
$stats_join
= "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS stat"
. " ON (t.ENGINE = 'InnoDB' AND stat.NAME"
. " = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)";
}
$sql .= "
LEFT JOIN data_dictionary.TABLES t
ON t.TABLE_SCHEMA = s.SCHEMA_NAME
$stats_join";
}
$sql .= $sql_where_schema . '
GROUP BY s.SCHEMA_NAME
ORDER BY ' . PMA_Util::backquote($sort_by) . ' ' . $sort_order
. $limit;
} else {
$sql = 'SELECT
s.SCHEMA_NAME,
s.DEFAULT_COLLATION_NAME';
if ($force_stats) {
$sql .= ',
COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
SUM(t.TABLE_ROWS) AS SCHEMA_TABLE_ROWS,
SUM(t.DATA_LENGTH) AS SCHEMA_DATA_LENGTH,
SUM(t.MAX_DATA_LENGTH) AS SCHEMA_MAX_DATA_LENGTH,
SUM(t.INDEX_LENGTH) AS SCHEMA_INDEX_LENGTH,
SUM(t.DATA_LENGTH + t.INDEX_LENGTH)
AS SCHEMA_LENGTH,
SUM(t.DATA_FREE) AS SCHEMA_DATA_FREE';
}
$sql .= '
FROM `information_schema`.SCHEMATA s';
if ($force_stats) {
$sql .= '
LEFT JOIN `information_schema`.TABLES t
ON BINARY t.TABLE_SCHEMA = BINARY s.SCHEMA_NAME';
}
$sql .= $sql_where_schema . '
GROUP BY BINARY s.SCHEMA_NAME
ORDER BY BINARY ' . PMA_Util::backquote($sort_by)
. ' ' . $sort_order
. $limit;
}
$databases = $this->fetchResult($sql, 'SCHEMA_NAME', null, $link);
$mysql_error = $this->getError($link);
if (! count($databases) && $GLOBALS['errno']) {
PMA_Util::mysqlDie($mysql_error, $sql);
}
// display only databases also in official database list
// f.e. to apply hide_db and only_db
$drops = array_diff(
array_keys($databases), (array) $GLOBALS['pma']->databases
);
if (count($drops)) {
foreach ($drops as $drop) {
unset($databases[$drop]);
}
unset($drop);
}
unset($sql_where_schema, $sql, $drops);
} else {
foreach ($GLOBALS['pma']->databases as $database_name) {
// MySQL forward compatibility
// so pma could use this array as if every server is of version >5.0
// todo : remove and check the rest of the code for usage,
// MySQL 5.0 or higher is required for current PMA version
$databases[$database_name]['SCHEMA_NAME'] = $database_name;
if ($force_stats) {
include_once './libraries/mysql_charsets.inc.php';
$databases[$database_name]['DEFAULT_COLLATION_NAME']
= PMA_getDbCollation($database_name);
// get additional info about tables
$databases[$database_name]['SCHEMA_TABLES'] = 0;
$databases[$database_name]['SCHEMA_TABLE_ROWS'] = 0;
$databases[$database_name]['SCHEMA_DATA_LENGTH'] = 0;
$databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 0;
$databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 0;
$databases[$database_name]['SCHEMA_LENGTH'] = 0;
$databases[$database_name]['SCHEMA_DATA_FREE'] = 0;
$res = $this->query(
'SHOW TABLE STATUS FROM '
. PMA_Util::backquote($database_name) . ';'
);
while ($row = $this->fetchAssoc($res)) {
$databases[$database_name]['SCHEMA_TABLES']++;
$databases[$database_name]['SCHEMA_TABLE_ROWS']
+= $row['Rows'];
$databases[$database_name]['SCHEMA_DATA_LENGTH']
+= $row['Data_length'];
$databases[$database_name]['SCHEMA_MAX_DATA_LENGTH']
+= $row['Max_data_length'];
$databases[$database_name]['SCHEMA_INDEX_LENGTH']
+= $row['Index_length'];
// for InnoDB, this does not contain the number of
// overhead bytes but the total free space
if ('InnoDB' != $row['Engine']) {
$databases[$database_name]['SCHEMA_DATA_FREE']
+= $row['Data_free'];
}
$databases[$database_name]['SCHEMA_LENGTH']
+= $row['Data_length'] + $row['Index_length'];
}
$this->freeResult($res);
unset($res);
}
}
}
/**
* apply limit and order manually now
* (caused by older MySQL < 5 or $GLOBALS['cfg']['NaturalOrder'])
*/
if ($apply_limit_and_order_manual) {
$GLOBALS['callback_sort_order'] = $sort_order;
$GLOBALS['callback_sort_by'] = $sort_by;
usort(
$databases,
array('PMA_DatabaseInterface', '_usortComparisonCallback')
);
unset($GLOBALS['callback_sort_order'], $GLOBALS['callback_sort_by']);
/**
* now apply limit
*/
if ($limit_count) {
$databases = array_slice($databases, $limit_offset, $limit_count);
}
}
return $databases;
}
/**
* usort comparison callback
*
* @param string $a first argument to sort
* @param string $b second argument to sort
*
* @return integer a value representing whether $a should be before $b in the
* sorted array or not
*
* @access private
*/
private static function _usortComparisonCallback($a, $b)
{
if ($GLOBALS['cfg']['NaturalOrder']) {
$sorter = 'strnatcasecmp';
} else {
$sorter = 'strcasecmp';
}
/* No sorting when key is not present */
if (! isset($a[$GLOBALS['callback_sort_by']])
|| ! isset($b[$GLOBALS['callback_sort_by']])
) {
return 0;