database_interface.lib.php 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Common Option Constants For DBI Functions
  5. *
  6. * @package PhpMyAdmin-DBI
  7. */
  8. if (! defined('PHPMYADMIN')) {
  9. exit;
  10. }
  11. /**
  12. * Force STORE_RESULT method, ignored by classic MySQL.
  13. */
  14. define('PMA_DBI_QUERY_STORE', 1);
  15. /**
  16. * Do not read whole query.
  17. */
  18. define('PMA_DBI_QUERY_UNBUFFERED', 2);
  19. /**
  20. * Get session variable.
  21. */
  22. define('PMA_DBI_GETVAR_SESSION', 1);
  23. /**
  24. * Get global variable.
  25. */
  26. define('PMA_DBI_GETVAR_GLOBAL', 2);
  27. /**
  28. * Checks whether database extension is loaded
  29. *
  30. * @param string $extension mysql extension to check
  31. *
  32. * @return bool
  33. */
  34. function PMA_DBI_checkDbExtension($extension = 'mysql')
  35. {
  36. if ($extension == 'drizzle' && function_exists('drizzle_create')) {
  37. return true;
  38. } else if (function_exists($extension . '_connect')) {
  39. return true;
  40. }
  41. return false;
  42. }
  43. if (defined('TESTSUITE')) {
  44. /**
  45. * For testsuite we use dummy driver which can fake some queries.
  46. */
  47. include_once './libraries/dbi/dummy.lib.php';
  48. } else {
  49. /**
  50. * check for requested extension
  51. */
  52. if (! PMA_DBI_checkDbExtension($GLOBALS['cfg']['Server']['extension'])) {
  53. // if it fails try alternative extension ...
  54. // and display an error ...
  55. $docurl = PMA_Util::getDocuLink('faq', 'faqmysql');
  56. $doclink = sprintf(
  57. __('See %sour documentation%s for more information.'),
  58. '[a@' . $docurl . '@documentation]',
  59. '[/a]'
  60. );
  61. /**
  62. * @todo add different messages for alternative extension
  63. * and complete fail (no alternative extension too)
  64. */
  65. PMA_warnMissingExtension(
  66. $GLOBALS['cfg']['Server']['extension'],
  67. false,
  68. $doclink
  69. );
  70. if ($GLOBALS['cfg']['Server']['extension'] === 'mysql') {
  71. $alternativ_extension = 'mysqli';
  72. } else {
  73. $alternativ_extension = 'mysql';
  74. }
  75. if (! PMA_DBI_checkDbExtension($alternativ_extension)) {
  76. // if alternative fails too ...
  77. PMA_warnMissingExtension(
  78. $GLOBALS['cfg']['Server']['extension'],
  79. true,
  80. $doclink
  81. );
  82. }
  83. $GLOBALS['cfg']['Server']['extension'] = $alternativ_extension;
  84. unset($alternativ_extension);
  85. }
  86. /**
  87. * Including The DBI Plugin
  88. */
  89. include_once './libraries/dbi/'
  90. . $GLOBALS['cfg']['Server']['extension'] . '.dbi.lib.php';
  91. }
  92. /**
  93. * runs a query
  94. *
  95. * @param string $query SQL query to execte
  96. * @param mixed $link optional database link to use
  97. * @param int $options optional query options
  98. * @param bool $cache_affected_rows whether to cache affected rows
  99. *
  100. * @return mixed
  101. */
  102. function PMA_DBI_query($query, $link = null, $options = 0,
  103. $cache_affected_rows = true
  104. ) {
  105. $res = PMA_DBI_try_query($query, $link, $options, $cache_affected_rows)
  106. or PMA_Util::mysqlDie(PMA_DBI_getError($link), $query);
  107. return $res;
  108. }
  109. /**
  110. * Stores query data into session data for debugging purposes
  111. *
  112. * @param string $query Query text
  113. * @param resource $link database link
  114. * @param resource $result Query result
  115. * @param integer $time Time to execute query
  116. *
  117. * @return void
  118. */
  119. function PMA_DBI_DBG_query($query, $link, $result, $time)
  120. {
  121. $hash = md5($query);
  122. if (isset($_SESSION['debug']['queries'][$hash])) {
  123. $_SESSION['debug']['queries'][$hash]['count']++;
  124. } else {
  125. $_SESSION['debug']['queries'][$hash] = array();
  126. if ($result == false) {
  127. $_SESSION['debug']['queries'][$hash]['error'] = '<b style="color:red">'
  128. . htmlspecialchars(mysqli_error($link)) . '</b>';
  129. }
  130. $_SESSION['debug']['queries'][$hash]['count'] = 1;
  131. $_SESSION['debug']['queries'][$hash]['query'] = htmlspecialchars($query);
  132. $_SESSION['debug']['queries'][$hash]['time'] = $time;
  133. }
  134. $trace = array();
  135. foreach (debug_backtrace() as $trace_step) {
  136. $trace[]
  137. = (isset($trace_step['file'])
  138. ? PMA_Error::relPath($trace_step['file'])
  139. : '')
  140. . (isset($trace_step['line'])
  141. ? '#' . $trace_step['line'] . ': '
  142. : '')
  143. . (isset($trace_step['class']) ? $trace_step['class'] : '')
  144. . (isset($trace_step['type']) ? $trace_step['type'] : '')
  145. . (isset($trace_step['function']) ? $trace_step['function'] : '')
  146. . '('
  147. . (isset($trace_step['params'])
  148. ? implode(', ', $trace_step['params'])
  149. : ''
  150. )
  151. . ')'
  152. ;
  153. }
  154. $_SESSION['debug']['queries'][$hash]['trace'][] = $trace;
  155. }
  156. /**
  157. * runs a query and returns the result
  158. *
  159. * @param string $query query to run
  160. * @param resource $link mysql link resource
  161. * @param integer $options query options
  162. * @param bool $cache_affected_rows whether to cache affected row
  163. *
  164. * @return mixed
  165. */
  166. function PMA_DBI_try_query($query, $link = null, $options = 0,
  167. $cache_affected_rows = true
  168. ) {
  169. if (empty($link)) {
  170. if (isset($GLOBALS['userlink'])) {
  171. $link = $GLOBALS['userlink'];
  172. } else {
  173. return false;
  174. }
  175. }
  176. if ($GLOBALS['cfg']['DBG']['sql']) {
  177. $time = microtime(true);
  178. }
  179. $result = PMA_DBI_real_query($query, $link, $options);
  180. if ($cache_affected_rows) {
  181. $GLOBALS['cached_affected_rows'] = PMA_DBI_affected_rows($link, false);
  182. }
  183. if ($GLOBALS['cfg']['DBG']['sql']) {
  184. $time = microtime(true) - $time;
  185. PMA_DBI_DBG_query($query, $link, $result, $time);
  186. }
  187. if ($result != false && PMA_Tracker::isActive() == true ) {
  188. PMA_Tracker::handleQuery($query);
  189. }
  190. return $result;
  191. }
  192. /**
  193. * Run multi query statement and return results
  194. *
  195. * @param string $multi_query multi query statement to execute
  196. * @param mysqli $link mysqli object
  197. *
  198. * @return mysqli_result collection | boolean(false)
  199. */
  200. function PMA_DBI_try_multi_query($multi_query = '', $link = null)
  201. {
  202. if (empty($link)) {
  203. if (isset($GLOBALS['userlink'])) {
  204. $link = $GLOBALS['userlink'];
  205. } else {
  206. return false;
  207. }
  208. }
  209. return PMA_DBI_real_multi_query($link, $multi_query);
  210. }
  211. /**
  212. * converts charset of a mysql message, usually coming from mysql_error(),
  213. * into PMA charset, usally UTF-8
  214. * uses language to charset mapping from mysql/share/errmsg.txt
  215. * and charset names to ISO charset from information_schema.CHARACTER_SETS
  216. *
  217. * @param string $message the message
  218. *
  219. * @return string $message
  220. */
  221. function PMA_DBI_convert_message($message)
  222. {
  223. // latin always last!
  224. $encodings = array(
  225. 'japanese' => 'EUC-JP', //'ujis',
  226. 'japanese-sjis' => 'Shift-JIS', //'sjis',
  227. 'korean' => 'EUC-KR', //'euckr',
  228. 'russian' => 'KOI8-R', //'koi8r',
  229. 'ukrainian' => 'KOI8-U', //'koi8u',
  230. 'greek' => 'ISO-8859-7', //'greek',
  231. 'serbian' => 'CP1250', //'cp1250',
  232. 'estonian' => 'ISO-8859-13', //'latin7',
  233. 'slovak' => 'ISO-8859-2', //'latin2',
  234. 'czech' => 'ISO-8859-2', //'latin2',
  235. 'hungarian' => 'ISO-8859-2', //'latin2',
  236. 'polish' => 'ISO-8859-2', //'latin2',
  237. 'romanian' => 'ISO-8859-2', //'latin2',
  238. 'spanish' => 'CP1252', //'latin1',
  239. 'swedish' => 'CP1252', //'latin1',
  240. 'italian' => 'CP1252', //'latin1',
  241. 'norwegian-ny' => 'CP1252', //'latin1',
  242. 'norwegian' => 'CP1252', //'latin1',
  243. 'portuguese' => 'CP1252', //'latin1',
  244. 'danish' => 'CP1252', //'latin1',
  245. 'dutch' => 'CP1252', //'latin1',
  246. 'english' => 'CP1252', //'latin1',
  247. 'french' => 'CP1252', //'latin1',
  248. 'german' => 'CP1252', //'latin1',
  249. );
  250. $server_language = PMA_DBI_fetch_value(
  251. 'SHOW VARIABLES LIKE \'language\';',
  252. 0,
  253. 1
  254. );
  255. if ($server_language) {
  256. $found = array();
  257. $match = preg_match(
  258. '&(?:\\\|\\/)([^\\\\\/]*)(?:\\\|\\/)$&i',
  259. $server_language,
  260. $found
  261. );
  262. if ($match) {
  263. $server_language = $found[1];
  264. }
  265. }
  266. if (! empty($server_language) && isset($encodings[$server_language])) {
  267. $encoding = $encodings[$server_language];
  268. } else {
  269. /* Fallback to CP1252 if we can not detect */
  270. $encoding = 'CP1252';
  271. }
  272. if (function_exists('iconv')) {
  273. if ((@stristr(PHP_OS, 'AIX'))
  274. && (@strcasecmp(ICONV_IMPL, 'unknown') == 0)
  275. && (@strcasecmp(ICONV_VERSION, 'unknown') == 0)
  276. ) {
  277. include_once './libraries/iconv_wrapper.lib.php';
  278. $message = PMA_aix_iconv_wrapper(
  279. $encoding,
  280. 'utf-8' . $GLOBALS['cfg']['IconvExtraParams'],
  281. $message
  282. );
  283. } else {
  284. $message = iconv(
  285. $encoding,
  286. 'utf-8' . $GLOBALS['cfg']['IconvExtraParams'],
  287. $message
  288. );
  289. }
  290. } elseif (function_exists('recode_string')) {
  291. $message = recode_string(
  292. $encoding . '..' . 'utf-8',
  293. $message
  294. );
  295. } elseif (function_exists('libiconv')) {
  296. $message = libiconv($encoding, 'utf-8', $message);
  297. } elseif (function_exists('mb_convert_encoding')) {
  298. // do not try unsupported charsets
  299. if (! in_array($server_language, array('ukrainian', 'greek', 'serbian'))) {
  300. $message = mb_convert_encoding(
  301. $message,
  302. 'utf-8',
  303. $encoding
  304. );
  305. }
  306. }
  307. return $message;
  308. }
  309. /**
  310. * returns array with table names for given db
  311. *
  312. * @param string $database name of database
  313. * @param mixed $link mysql link resource|object
  314. *
  315. * @return array tables names
  316. */
  317. function PMA_DBI_get_tables($database, $link = null)
  318. {
  319. return PMA_DBI_fetch_result(
  320. 'SHOW TABLES FROM ' . PMA_Util::backquote($database) . ';',
  321. null,
  322. 0,
  323. $link,
  324. PMA_DBI_QUERY_STORE
  325. );
  326. }
  327. /**
  328. * usort comparison callback
  329. *
  330. * @param string $a first argument to sort
  331. * @param string $b second argument to sort
  332. *
  333. * @return integer a value representing whether $a should be before $b in the
  334. * sorted array or not
  335. *
  336. * @access private
  337. */
  338. function PMA_usort_comparison_callback($a, $b)
  339. {
  340. if ($GLOBALS['cfg']['NaturalOrder']) {
  341. $sorter = 'strnatcasecmp';
  342. } else {
  343. $sorter = 'strcasecmp';
  344. }
  345. /* No sorting when key is not present */
  346. if (! isset($a[$GLOBALS['callback_sort_by']])
  347. || ! isset($b[$GLOBALS['callback_sort_by']])
  348. ) {
  349. return 0;
  350. }
  351. // produces f.e.:
  352. // return -1 * strnatcasecmp($a["SCHEMA_TABLES"], $b["SCHEMA_TABLES"])
  353. return ($GLOBALS['callback_sort_order'] == 'ASC' ? 1 : -1) * $sorter(
  354. $a[$GLOBALS['callback_sort_by']], $b[$GLOBALS['callback_sort_by']]
  355. );
  356. } // end of the 'PMA_usort_comparison_callback()' function
  357. /**
  358. * returns array of all tables in given db or dbs
  359. * this function expects unquoted names:
  360. * RIGHT: my_database
  361. * WRONG: `my_database`
  362. * WRONG: my\_database
  363. * if $tbl_is_group is true, $table is used as filter for table names
  364. * if $tbl_is_group is 'comment, $table is used as filter for table comments
  365. *
  366. * <code>
  367. * PMA_DBI_get_tables_full('my_database');
  368. * PMA_DBI_get_tables_full('my_database', 'my_table'));
  369. * PMA_DBI_get_tables_full('my_database', 'my_tables_', true));
  370. * PMA_DBI_get_tables_full('my_database', 'my_tables_', 'comment'));
  371. * </code>
  372. *
  373. * @param string $database database
  374. * @param string|bool $table table or false
  375. * @param boolean|string $tbl_is_group $table is a table group
  376. * @param mixed $link mysql link
  377. * @param integer $limit_offset zero-based offset for the count
  378. * @param boolean|integer $limit_count number of tables to return
  379. * @param string $sort_by table attribute to sort by
  380. * @param string $sort_order direction to sort (ASC or DESC)
  381. *
  382. * @todo move into PMA_Table
  383. *
  384. * @return array list of tables in given db(s)
  385. */
  386. function PMA_DBI_get_tables_full($database, $table = false,
  387. $tbl_is_group = false, $link = null, $limit_offset = 0,
  388. $limit_count = false, $sort_by = 'Name', $sort_order = 'ASC'
  389. ) {
  390. if (true === $limit_count) {
  391. $limit_count = $GLOBALS['cfg']['MaxTableList'];
  392. }
  393. // prepare and check parameters
  394. if (! is_array($database)) {
  395. $databases = array($database);
  396. } else {
  397. $databases = $database;
  398. }
  399. $tables = array();
  400. if (! $GLOBALS['cfg']['Server']['DisableIS']) {
  401. // get table information from information_schema
  402. if ($table) {
  403. if (true === $tbl_is_group) {
  404. $sql_where_table = 'AND t.`TABLE_NAME` LIKE \''
  405. . PMA_Util::escapeMysqlWildcards(PMA_Util::sqlAddSlashes($table))
  406. . '%\'';
  407. } elseif ('comment' === $tbl_is_group) {
  408. $sql_where_table = 'AND t.`TABLE_COMMENT` LIKE \''
  409. . PMA_Util::escapeMysqlWildcards(PMA_Util::sqlAddSlashes($table))
  410. . '%\'';
  411. } else {
  412. $sql_where_table = 'AND t.`TABLE_NAME` = \''
  413. . PMA_Util::sqlAddSlashes($table) . '\'';
  414. }
  415. } else {
  416. $sql_where_table = '';
  417. }
  418. // for PMA bc:
  419. // `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME`
  420. //
  421. // on non-Windows servers,
  422. // added BINARY in the WHERE clause to force a case sensitive
  423. // comparison (if we are looking for the db Aa we don't want
  424. // to find the db aa)
  425. $this_databases = array_map('PMA_Util::sqlAddSlashes', $databases);
  426. if (PMA_DRIZZLE) {
  427. $engine_info = PMA_Util::cacheGet('drizzle_engines', true);
  428. $stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
  429. if (isset($engine_info['InnoDB'])
  430. && $engine_info['InnoDB']['module_library'] == 'innobase'
  431. ) {
  432. $stats_join = "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS stat"
  433. . " ON (t.ENGINE = 'InnoDB' AND stat.NAME"
  434. . " = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)";
  435. }
  436. // data_dictionary.table_cache may not contain any data for some tables,
  437. // it's just a table cache
  438. // auto_increment == 0 is cast to NULL because currently (2011.03.13 GA)
  439. // Drizzle doesn't provide correct value
  440. $sql = "
  441. SELECT t.*,
  442. t.TABLE_SCHEMA AS `Db`,
  443. t.TABLE_NAME AS `Name`,
  444. t.TABLE_TYPE AS `TABLE_TYPE`,
  445. t.ENGINE AS `Engine`,
  446. t.ENGINE AS `Type`,
  447. t.TABLE_VERSION AS `Version`,-- VERSION
  448. t.ROW_FORMAT AS `Row_format`,
  449. coalesce(tc.ROWS, stat.NUM_ROWS)
  450. AS `Rows`,-- TABLE_ROWS,
  451. coalesce(tc.ROWS, stat.NUM_ROWS)
  452. AS `TABLE_ROWS`,
  453. tc.AVG_ROW_LENGTH AS `Avg_row_length`, -- AVG_ROW_LENGTH
  454. tc.TABLE_SIZE AS `Data_length`, -- DATA_LENGTH
  455. NULL AS `Max_data_length`, -- MAX_DATA_LENGTH
  456. NULL AS `Index_length`, -- INDEX_LENGTH
  457. NULL AS `Data_free`, -- DATA_FREE
  458. nullif(t.AUTO_INCREMENT, 0)
  459. AS `Auto_increment`,
  460. t.TABLE_CREATION_TIME AS `Create_time`, -- CREATE_TIME
  461. t.TABLE_UPDATE_TIME AS `Update_time`, -- UPDATE_TIME
  462. NULL AS `Check_time`, -- CHECK_TIME
  463. t.TABLE_COLLATION AS `Collation`,
  464. NULL AS `Checksum`, -- CHECKSUM
  465. NULL AS `Create_options`, -- CREATE_OPTIONS
  466. t.TABLE_COMMENT AS `Comment`
  467. FROM data_dictionary.TABLES t
  468. LEFT JOIN data_dictionary.TABLE_CACHE tc
  469. ON tc.TABLE_SCHEMA = t.TABLE_SCHEMA AND tc.TABLE_NAME
  470. = t.TABLE_NAME
  471. $stats_join
  472. WHERE t.TABLE_SCHEMA IN ('" . implode("', '", $this_databases) . "')
  473. " . $sql_where_table;
  474. } else {
  475. $sql = '
  476. SELECT *,
  477. `TABLE_SCHEMA` AS `Db`,
  478. `TABLE_NAME` AS `Name`,
  479. `TABLE_TYPE` AS `TABLE_TYPE`,
  480. `ENGINE` AS `Engine`,
  481. `ENGINE` AS `Type`,
  482. `VERSION` AS `Version`,
  483. `ROW_FORMAT` AS `Row_format`,
  484. `TABLE_ROWS` AS `Rows`,
  485. `AVG_ROW_LENGTH` AS `Avg_row_length`,
  486. `DATA_LENGTH` AS `Data_length`,
  487. `MAX_DATA_LENGTH` AS `Max_data_length`,
  488. `INDEX_LENGTH` AS `Index_length`,
  489. `DATA_FREE` AS `Data_free`,
  490. `AUTO_INCREMENT` AS `Auto_increment`,
  491. `CREATE_TIME` AS `Create_time`,
  492. `UPDATE_TIME` AS `Update_time`,
  493. `CHECK_TIME` AS `Check_time`,
  494. `TABLE_COLLATION` AS `Collation`,
  495. `CHECKSUM` AS `Checksum`,
  496. `CREATE_OPTIONS` AS `Create_options`,
  497. `TABLE_COMMENT` AS `Comment`
  498. FROM `information_schema`.`TABLES` t
  499. WHERE ' . (PMA_IS_WINDOWS ? '' : 'BINARY') . ' `TABLE_SCHEMA`
  500. IN (\'' . implode("', '", $this_databases) . '\')
  501. ' . $sql_where_table;
  502. }
  503. // Sort the tables
  504. $sql .= " ORDER BY $sort_by $sort_order";
  505. if ($limit_count) {
  506. $sql .= ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
  507. }
  508. $tables = PMA_DBI_fetch_result(
  509. $sql, array('TABLE_SCHEMA', 'TABLE_NAME'), null, $link
  510. );
  511. unset($sql_where_table, $sql);
  512. if (PMA_DRIZZLE) {
  513. // correct I_S and D_D names returned by D_D.TABLES -
  514. // Drizzle generally uses lower case for them,
  515. // but TABLES returns uppercase
  516. foreach ((array)$database as $db) {
  517. $db_upper = strtoupper($db);
  518. if (!isset($tables[$db]) && isset($tables[$db_upper])) {
  519. $tables[$db] = $tables[$db_upper];
  520. unset($tables[$db_upper]);
  521. }
  522. }
  523. }
  524. if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
  525. // here, the array's first key is by schema name
  526. foreach ($tables as $one_database_name => $one_database_tables) {
  527. uksort($one_database_tables, 'strnatcasecmp');
  528. if ($sort_order == 'DESC') {
  529. $one_database_tables = array_reverse($one_database_tables);
  530. }
  531. $tables[$one_database_name] = $one_database_tables;
  532. }
  533. }
  534. } // end (get information from table schema)
  535. // If permissions are wrong on even one database directory,
  536. // information_schema does not return any table info for any database
  537. // this is why we fall back to SHOW TABLE STATUS even for MySQL >= 50002
  538. if (empty($tables) && !PMA_DRIZZLE) {
  539. foreach ($databases as $each_database) {
  540. if ($table || (true === $tbl_is_group)) {
  541. $sql = 'SHOW TABLE STATUS FROM '
  542. . PMA_Util::backquote($each_database)
  543. .' LIKE \''
  544. . PMA_Util::escapeMysqlWildcards(
  545. PMA_Util::sqlAddSlashes($table, true)
  546. )
  547. . '%\'';
  548. } else {
  549. $sql = 'SHOW TABLE STATUS FROM '
  550. . PMA_Util::backquote($each_database);
  551. }
  552. $useStatusCache = false;
  553. if (extension_loaded('apc')
  554. && isset($GLOBALS['cfg']['Server']['StatusCacheDatabases'])
  555. && ! empty($GLOBALS['cfg']['Server']['StatusCacheLifetime'])
  556. ) {
  557. $statusCacheDatabases
  558. = (array) $GLOBALS['cfg']['Server']['StatusCacheDatabases'];
  559. if (in_array($each_database, $statusCacheDatabases)) {
  560. $useStatusCache = true;
  561. }
  562. }
  563. $each_tables = null;
  564. if ($useStatusCache) {
  565. $cacheKey = 'phpMyAdmin_tableStatus_'
  566. . sha1($GLOBALS['cfg']['Server']['host'] . '_' . $sql);
  567. $each_tables = apc_fetch($cacheKey);
  568. }
  569. if (!$each_tables) {
  570. $each_tables = PMA_DBI_fetch_result($sql, 'Name', null, $link);
  571. }
  572. if ($useStatusCache) {
  573. apc_store(
  574. $cacheKey, $each_tables,
  575. $GLOBALS['cfg']['Server']['StatusCacheLifetime']
  576. );
  577. }
  578. // Sort naturally if the config allows it and we're sorting
  579. // the Name column.
  580. if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
  581. uksort($each_tables, 'strnatcasecmp');
  582. if ($sort_order == 'DESC') {
  583. $each_tables = array_reverse($each_tables);
  584. }
  585. } else {
  586. // Prepare to sort by creating array of the selected sort
  587. // value to pass to array_multisort
  588. // Size = Data_length + Index_length
  589. if ($sort_by == 'Data_length') {
  590. foreach ($each_tables as $table_name => $table_data) {
  591. ${$sort_by}[$table_name] = strtolower(
  592. $table_data['Data_length'] + $table_data['Index_length']
  593. );
  594. }
  595. } else {
  596. foreach ($each_tables as $table_name => $table_data) {
  597. ${$sort_by}[$table_name] = strtolower($table_data[$sort_by]);
  598. }
  599. }
  600. if ($sort_order == 'DESC') {
  601. array_multisort($$sort_by, SORT_DESC, $each_tables);
  602. } else {
  603. array_multisort($$sort_by, SORT_ASC, $each_tables);
  604. }
  605. // cleanup the temporary sort array
  606. unset($$sort_by);
  607. }
  608. if ($limit_count) {
  609. $each_tables = array_slice(
  610. $each_tables, $limit_offset, $limit_count
  611. );
  612. }
  613. foreach ($each_tables as $table_name => $each_table) {
  614. if ('comment' === $tbl_is_group
  615. && 0 === strpos($each_table['Comment'], $table)
  616. ) {
  617. // remove table from list
  618. unset($each_tables[$table_name]);
  619. continue;
  620. }
  621. if (! isset($each_tables[$table_name]['Type'])
  622. && isset($each_tables[$table_name]['Engine'])
  623. ) {
  624. // pma BC, same parts of PMA still uses 'Type'
  625. $each_tables[$table_name]['Type']
  626. =& $each_tables[$table_name]['Engine'];
  627. } elseif (! isset($each_tables[$table_name]['Engine'])
  628. && isset($each_tables[$table_name]['Type'])) {
  629. // old MySQL reports Type, newer MySQL reports Engine
  630. $each_tables[$table_name]['Engine']
  631. =& $each_tables[$table_name]['Type'];
  632. }
  633. // MySQL forward compatibility
  634. // so pma could use this array as if every server is of version >5.0
  635. // todo : remove and check usage in the rest of the code,
  636. // MySQL 5.0 is required by current PMA version
  637. $each_tables[$table_name]['TABLE_SCHEMA'] = $each_database;
  638. $each_tables[$table_name]['TABLE_NAME']
  639. =& $each_tables[$table_name]['Name'];
  640. $each_tables[$table_name]['ENGINE']
  641. =& $each_tables[$table_name]['Engine'];
  642. $each_tables[$table_name]['VERSION']
  643. =& $each_tables[$table_name]['Version'];
  644. $each_tables[$table_name]['ROW_FORMAT']
  645. =& $each_tables[$table_name]['Row_format'];
  646. $each_tables[$table_name]['TABLE_ROWS']
  647. =& $each_tables[$table_name]['Rows'];
  648. $each_tables[$table_name]['AVG_ROW_LENGTH']
  649. =& $each_tables[$table_name]['Avg_row_length'];
  650. $each_tables[$table_name]['DATA_LENGTH']
  651. =& $each_tables[$table_name]['Data_length'];
  652. $each_tables[$table_name]['MAX_DATA_LENGTH']
  653. =& $each_tables[$table_name]['Max_data_length'];
  654. $each_tables[$table_name]['INDEX_LENGTH']
  655. =& $each_tables[$table_name]['Index_length'];
  656. $each_tables[$table_name]['DATA_FREE']
  657. =& $each_tables[$table_name]['Data_free'];
  658. $each_tables[$table_name]['AUTO_INCREMENT']
  659. =& $each_tables[$table_name]['Auto_increment'];
  660. $each_tables[$table_name]['CREATE_TIME']
  661. =& $each_tables[$table_name]['Create_time'];
  662. $each_tables[$table_name]['UPDATE_TIME']
  663. =& $each_tables[$table_name]['Update_time'];
  664. $each_tables[$table_name]['CHECK_TIME']
  665. =& $each_tables[$table_name]['Check_time'];
  666. $each_tables[$table_name]['TABLE_COLLATION']
  667. =& $each_tables[$table_name]['Collation'];
  668. $each_tables[$table_name]['CHECKSUM']
  669. =& $each_tables[$table_name]['Checksum'];
  670. $each_tables[$table_name]['CREATE_OPTIONS']
  671. =& $each_tables[$table_name]['Create_options'];
  672. $each_tables[$table_name]['TABLE_COMMENT']
  673. =& $each_tables[$table_name]['Comment'];
  674. if (strtoupper($each_tables[$table_name]['Comment']) === 'VIEW'
  675. && $each_tables[$table_name]['Engine'] == null
  676. ) {
  677. $each_tables[$table_name]['TABLE_TYPE'] = 'VIEW';
  678. } else {
  679. /**
  680. * @todo difference between 'TEMPORARY' and 'BASE TABLE'
  681. * but how to detect?
  682. */
  683. $each_tables[$table_name]['TABLE_TYPE'] = 'BASE TABLE';
  684. }
  685. }
  686. $tables[$each_database] = $each_tables;
  687. }
  688. }
  689. // cache table data
  690. // so PMA_Table does not require to issue SHOW TABLE STATUS again
  691. // Note: I don't see why we would need array_merge_recursive() here,
  692. // as it creates double entries for the same table (for example a double
  693. // entry for Comment when changing the storage engine in Operations)
  694. // Note 2: Instead of array_merge(), simply use the + operator because
  695. // array_merge() renumbers numeric keys starting with 0, therefore
  696. // we would lose a db name thats consists only of numbers
  697. foreach ($tables as $one_database => $its_tables) {
  698. if (isset(PMA_Table::$cache[$one_database])) {
  699. PMA_Table::$cache[$one_database]
  700. = PMA_Table::$cache[$one_database] + $tables[$one_database];
  701. } else {
  702. PMA_Table::$cache[$one_database] = $tables[$one_database];
  703. }
  704. }
  705. unset($one_database, $its_tables);
  706. if (! is_array($database)) {
  707. if (isset($tables[$database])) {
  708. return $tables[$database];
  709. } elseif (isset($tables[strtolower($database)])) {
  710. // on windows with lower_case_table_names = 1
  711. // MySQL returns
  712. // with SHOW DATABASES or information_schema.SCHEMATA: `Test`
  713. // but information_schema.TABLES gives `test`
  714. // bug #2036
  715. // https://sourceforge.net/p/phpmyadmin/bugs/2036/
  716. return $tables[strtolower($database)];
  717. } else {
  718. // one database but inexact letter case match
  719. // as Drizzle is always case insensitive,
  720. // we can safely return the only result
  721. if (PMA_DRIZZLE && count($tables) == 1) {
  722. $keys = array_keys($tables);
  723. if (strlen(array_pop($keys)) == strlen($database)) {
  724. return array_pop($tables);
  725. }
  726. }
  727. return $tables;
  728. }
  729. } else {
  730. return $tables;
  731. }
  732. }
  733. /**
  734. * Get VIEWs in a particular database
  735. *
  736. * @param string $db Database name to look in
  737. *
  738. * @return array $views Set of VIEWs inside the database
  739. */
  740. function PMA_DBI_getVirtualTables($db)
  741. {
  742. $tables_full = PMA_DBI_get_tables_full($db);
  743. $views = array();
  744. foreach ($tables_full as $table=>$tmp) {
  745. if (PMA_Table::isView($db, $table)) {
  746. $views[] = $table;
  747. }
  748. }
  749. return $views;
  750. }
  751. /**
  752. * returns array with databases containing extended infos about them
  753. *
  754. * @param string $database database
  755. * @param boolean $force_stats retrieve stats also for MySQL < 5
  756. * @param resource $link mysql link
  757. * @param string $sort_by column to order by
  758. * @param string $sort_order ASC or DESC
  759. * @param integer $limit_offset starting offset for LIMIT
  760. * @param bool|int $limit_count row count for LIMIT or true
  761. * for $GLOBALS['cfg']['MaxDbList']
  762. *
  763. * @todo move into PMA_List_Database?
  764. *
  765. * @return array $databases
  766. */
  767. function PMA_DBI_get_databases_full($database = null, $force_stats = false,
  768. $link = null, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC',
  769. $limit_offset = 0, $limit_count = false
  770. ) {
  771. $sort_order = strtoupper($sort_order);
  772. if (true === $limit_count) {
  773. $limit_count = $GLOBALS['cfg']['MaxDbList'];
  774. }
  775. // initialize to avoid errors when there are no databases
  776. $databases = array();
  777. $apply_limit_and_order_manual = true;
  778. if (! $GLOBALS['cfg']['Server']['DisableIS']) {
  779. /**
  780. * if $GLOBALS['cfg']['NaturalOrder'] is enabled, we cannot use LIMIT
  781. * cause MySQL does not support natural ordering, we have to do it afterward
  782. */
  783. $limit = '';
  784. if (!$GLOBALS['cfg']['NaturalOrder']) {
  785. if ($limit_count) {
  786. $limit = ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
  787. }
  788. $apply_limit_and_order_manual = false;
  789. }
  790. // get table information from information_schema
  791. if ($database) {
  792. $sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \''
  793. . PMA_Util::sqlAddSlashes($database) . '\'';
  794. } else {
  795. $sql_where_schema = '';
  796. }
  797. if (PMA_DRIZZLE) {
  798. // data_dictionary.table_cache may not contain any data for some
  799. // tables, it's just a table cache
  800. $sql = 'SELECT
  801. s.SCHEMA_NAME,
  802. s.DEFAULT_COLLATION_NAME';
  803. if ($force_stats) {
  804. // no TABLE_CACHE data, stable results are better than
  805. // constantly changing
  806. $sql .= ',
  807. COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
  808. SUM(stat.NUM_ROWS) AS SCHEMA_TABLE_ROWS';
  809. }
  810. $sql .= '
  811. FROM data_dictionary.SCHEMAS s';
  812. if ($force_stats) {
  813. $engine_info = PMA_Util::cacheGet('drizzle_engines', true);
  814. $stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
  815. if (isset($engine_info['InnoDB'])
  816. && $engine_info['InnoDB']['module_library'] == 'innobase'
  817. ) {
  818. $stats_join = "LEFT JOIN data_dictionary.INNODB_SYS_TABLESTATS"
  819. . " stat ON (t.ENGINE = 'InnoDB' AND stat.NAME"
  820. . " = (t.TABLE_SCHEMA || '/') || t.TABLE_NAME)";
  821. }
  822. $sql .= "
  823. LEFT JOIN data_dictionary.TABLES t
  824. ON t.TABLE_SCHEMA = s.SCHEMA_NAME
  825. $stats_join";
  826. }
  827. $sql .= $sql_where_schema . '
  828. GROUP BY s.SCHEMA_NAME
  829. ORDER BY ' . PMA_Util::backquote($sort_by) . ' ' . $sort_order
  830. . $limit;
  831. } else {
  832. $sql = 'SELECT
  833. s.SCHEMA_NAME,
  834. s.DEFAULT_COLLATION_NAME';
  835. if ($force_stats) {
  836. $sql .= ',
  837. COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
  838. SUM(t.TABLE_ROWS) AS SCHEMA_TABLE_ROWS,
  839. SUM(t.DATA_LENGTH) AS SCHEMA_DATA_LENGTH,
  840. SUM(t.MAX_DATA_LENGTH) AS SCHEMA_MAX_DATA_LENGTH,
  841. SUM(t.INDEX_LENGTH) AS SCHEMA_INDEX_LENGTH,
  842. SUM(t.DATA_LENGTH + t.INDEX_LENGTH)
  843. AS SCHEMA_LENGTH,
  844. SUM(t.DATA_FREE) AS SCHEMA_DATA_FREE';
  845. }
  846. $sql .= '
  847. FROM `information_schema`.SCHEMATA s';
  848. if ($force_stats) {
  849. $sql .= '
  850. LEFT JOIN `information_schema`.TABLES t
  851. ON BINARY t.TABLE_SCHEMA = BINARY s.SCHEMA_NAME';
  852. }
  853. $sql .= $sql_where_schema . '
  854. GROUP BY BINARY s.SCHEMA_NAME
  855. ORDER BY BINARY ' . PMA_Util::backquote($sort_by)
  856. . ' ' . $sort_order
  857. . $limit;
  858. }
  859. $databases = PMA_DBI_fetch_result($sql, 'SCHEMA_NAME', null, $link);
  860. $mysql_error = PMA_DBI_getError($link);
  861. if (! count($databases) && $GLOBALS['errno']) {
  862. PMA_Util::mysqlDie($mysql_error, $sql);
  863. }
  864. // display only databases also in official database list
  865. // f.e. to apply hide_db and only_db
  866. $drops = array_diff(
  867. array_keys($databases), (array) $GLOBALS['pma']->databases
  868. );
  869. if (count($drops)) {
  870. foreach ($drops as $drop) {
  871. unset($databases[$drop]);
  872. }
  873. unset($drop);
  874. }
  875. unset($sql_where_schema, $sql, $drops);
  876. } else {
  877. foreach ($GLOBALS['pma']->databases as $database_name) {
  878. // MySQL forward compatibility
  879. // so pma could use this array as if every server is of version >5.0
  880. // todo : remove and check the rest of the code for usage,
  881. // MySQL 5.0 or higher is required for current PMA version
  882. $databases[$database_name]['SCHEMA_NAME'] = $database_name;
  883. if ($force_stats) {
  884. include_once './libraries/mysql_charsets.lib.php';
  885. $databases[$database_name]['DEFAULT_COLLATION_NAME']
  886. = PMA_getDbCollation($database_name);
  887. // get additional info about tables
  888. $databases[$database_name]['SCHEMA_TABLES'] = 0;
  889. $databases[$database_name]['SCHEMA_TABLE_ROWS'] = 0;
  890. $databases[$database_name]['SCHEMA_DATA_LENGTH'] = 0;
  891. $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 0;
  892. $databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 0;
  893. $databases[$database_name]['SCHEMA_LENGTH'] = 0;
  894. $databases[$database_name]['SCHEMA_DATA_FREE'] = 0;
  895. $res = PMA_DBI_query(
  896. 'SHOW TABLE STATUS FROM '
  897. . PMA_Util::backquote($database_name) . ';'
  898. );
  899. while ($row = PMA_DBI_fetch_assoc($res)) {
  900. $databases[$database_name]['SCHEMA_TABLES']++;
  901. $databases[$database_name]['SCHEMA_TABLE_ROWS']
  902. += $row['Rows'];
  903. $databases[$database_name]['SCHEMA_DATA_LENGTH']
  904. += $row['Data_length'];
  905. $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH']
  906. += $row['Max_data_length'];
  907. $databases[$database_name]['SCHEMA_INDEX_LENGTH']
  908. += $row['Index_length'];
  909. // for InnoDB, this does not contain the number of
  910. // overhead bytes but the total free space
  911. if ('InnoDB' != $row['Engine']) {
  912. $databases[$database_name]['SCHEMA_DATA_FREE']
  913. += $row['Data_free'];
  914. }
  915. $databases[$database_name]['SCHEMA_LENGTH']
  916. += $row['Data_length'] + $row['Index_length'];
  917. }
  918. PMA_DBI_free_result($res);
  919. unset($res);
  920. }
  921. }
  922. }
  923. /**
  924. * apply limit and order manually now
  925. * (caused by older MySQL < 5 or $GLOBALS['cfg']['NaturalOrder'])
  926. */
  927. if ($apply_limit_and_order_manual) {
  928. $GLOBALS['callback_sort_order'] = $sort_order;
  929. $GLOBALS['callback_sort_by'] = $sort_by;
  930. usort($databases, 'PMA_usort_comparison_callback');
  931. unset($GLOBALS['callback_sort_order'], $GLOBALS['callback_sort_by']);
  932. /**
  933. * now apply limit
  934. */
  935. if ($limit_count) {
  936. $databases = array_slice($databases, $limit_offset, $limit_count);
  937. }
  938. }
  939. return $databases;
  940. }
  941. /**
  942. * returns detailed array with all columns for given table in database,
  943. * or all tables/databases
  944. *
  945. * @param string $database name of database
  946. * @param string $table name of table to retrieve columns from
  947. * @param string $column name of specific column
  948. * @param mixed $link mysql link resource
  949. *
  950. * @return array
  951. */
  952. function PMA_DBI_get_columns_full($database = null, $table = null,
  953. $column = null, $link = null
  954. ) {
  955. $columns = array();
  956. if (! $GLOBALS['cfg']['Server']['DisableIS']) {
  957. $sql_wheres = array();
  958. $array_keys = array();
  959. // get columns information from information_schema
  960. if (null !== $database) {
  961. $sql_wheres[] = '`TABLE_SCHEMA` = \''
  962. . PMA_Util::sqlAddSlashes($database) . '\' ';
  963. } else {
  964. $array_keys[] = 'TABLE_SCHEMA';
  965. }
  966. if (null !== $table) {
  967. $sql_wheres[] = '`TABLE_NAME` = \''
  968. . PMA_Util::sqlAddSlashes($table) . '\' ';
  969. } else {
  970. $array_keys[] = 'TABLE_NAME';
  971. }
  972. if (null !== $column) {
  973. $sql_wheres[] = '`COLUMN_NAME` = \''
  974. . PMA_Util::sqlAddSlashes($column) . '\' ';
  975. } else {
  976. $array_keys[] = 'COLUMN_NAME';
  977. }
  978. // for PMA bc:
  979. // `[SCHEMA_FIELD_NAME]` AS `[SHOW_FULL_COLUMNS_FIELD_NAME]`
  980. if (PMA_DRIZZLE) {
  981. $sql = "SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME,
  982. column_name AS `Field`,
  983. (CASE
  984. WHEN character_maximum_length > 0
  985. THEN concat(lower(data_type), '(', character_maximum_length, ')')
  986. WHEN numeric_precision > 0 OR numeric_scale > 0
  987. THEN concat(lower(data_type), '(', numeric_precision,
  988. ',', numeric_scale, ')')
  989. WHEN enum_values IS NOT NULL
  990. THEN concat(lower(data_type), '(', enum_values, ')')
  991. ELSE lower(data_type) END)
  992. AS `Type`,
  993. collation_name AS `Collation`,
  994. (CASE is_nullable
  995. WHEN 1 THEN 'YES'
  996. ELSE 'NO' END) AS `Null`,
  997. (CASE
  998. WHEN is_used_in_primary THEN 'PRI'
  999. ELSE '' END) AS `Key`,
  1000. column_default AS `Default`,
  1001. (CASE
  1002. WHEN is_auto_increment THEN 'auto_increment'
  1003. WHEN column_default_update
  1004. THEN 'on update ' || column_default_update
  1005. ELSE '' END) AS `Extra`,
  1006. NULL AS `Privileges`,
  1007. column_comment AS `Comment`
  1008. FROM data_dictionary.columns";
  1009. } else {
  1010. $sql = '
  1011. SELECT *,
  1012. `COLUMN_NAME` AS `Field`,
  1013. `COLUMN_TYPE` AS `Type`,
  1014. `COLLATION_NAME` AS `Collation`,
  1015. `IS_NULLABLE` AS `Null`,
  1016. `COLUMN_KEY` AS `Key`,
  1017. `COLUMN_DEFAULT` AS `Default`,
  1018. `EXTRA` AS `Extra`,
  1019. `PRIVILEGES` AS `Privileges`,
  1020. `COLUMN_COMMENT` AS `Comment`
  1021. FROM `information_schema`.`COLUMNS`';
  1022. }
  1023. if (count($sql_wheres)) {
  1024. $sql .= "\n" . ' WHERE ' . implode(' AND ', $sql_wheres);
  1025. }
  1026. $columns = PMA_DBI_fetch_result($sql, $array_keys, null, $link);
  1027. unset($sql_wheres, $sql);
  1028. } else {
  1029. if (null === $database) {
  1030. foreach ($GLOBALS['pma']->databases as $database) {
  1031. $columns[$database] = PMA_DBI_get_columns_full(
  1032. $database, null, null, $link
  1033. );
  1034. }
  1035. return $columns;
  1036. } elseif (null === $table) {
  1037. $tables = PMA_DBI_get_tables($database);
  1038. foreach ($tables as $table) {
  1039. $columns[$table] = PMA_DBI_get_columns_full(
  1040. $database, $table, null, $link
  1041. );
  1042. }
  1043. return $columns;
  1044. }
  1045. $sql = 'SHOW FULL COLUMNS FROM '
  1046. . PMA_Util::backquote($database) . '.' . PMA_Util::backquote($table);
  1047. if (null !== $column) {
  1048. $sql .= " LIKE '" . PMA_Util::sqlAddSlashes($column, true) . "'";
  1049. }
  1050. $columns = PMA_DBI_fetch_result($sql, 'Field', null, $link);
  1051. }
  1052. $ordinal_position = 1;
  1053. foreach ($columns as $column_name => $each_column) {
  1054. // MySQL forward compatibility
  1055. // so pma could use this array as if every server is of version >5.0
  1056. // todo : remove and check the rest of the code for usage,
  1057. // MySQL 5.0 or higher is required for current PMA version
  1058. $columns[$column_name]['COLUMN_NAME'] =& $columns[$column_name]['Field'];
  1059. $columns[$column_name]['COLUMN_TYPE'] =& $columns[$column_name]['Type'];
  1060. $columns[$column_name]['COLLATION_NAME']
  1061. =& $columns[$column_name]['Collation'];
  1062. $columns[$column_name]['IS_NULLABLE'] =& $columns[$column_name]['Null'];
  1063. $columns[$column_name]['COLUMN_KEY'] =& $columns[$column_name]['Key'];
  1064. $columns[$column_name]['COLUMN_DEFAULT']
  1065. =& $columns[$column_name]['Default'];
  1066. $columns[$column_name]['EXTRA']
  1067. =& $columns[$column_name]['Extra'];
  1068. $columns[$column_name]['PRIVILEGES']
  1069. =& $columns[$column_name]['Privileges'];
  1070. $columns[$column_name]['COLUMN_COMMENT']
  1071. =& $columns[$column_name]['Comment'];
  1072. $columns[$column_name]['TABLE_CATALOG'] = null;
  1073. $columns[$column_name]['TABLE_SCHEMA'] = $database;
  1074. $columns[$column_name]['TABLE_NAME'] = $table;
  1075. $columns[$column_name]['ORDINAL_POSITION'] = $ordinal_position;
  1076. $columns[$column_name]['DATA_TYPE']
  1077. = substr(
  1078. $columns[$column_name]['COLUMN_TYPE'],
  1079. 0,
  1080. strpos($columns[$column_name]['COLUMN_TYPE'], '(')
  1081. );
  1082. /**
  1083. * @todo guess CHARACTER_MAXIMUM_LENGTH from COLUMN_TYPE
  1084. */
  1085. $columns[$column_name]['CHARACTER_MAXIMUM_LENGTH'] = null;
  1086. /**
  1087. * @todo guess CHARACTER_OCTET_LENGTH from CHARACTER_MAXIMUM_LENGTH
  1088. */
  1089. $columns[$column_name]['CHARACTER_OCTET_LENGTH'] = null;
  1090. $columns[$column_name]['NUMERIC_PRECISION'] = null;
  1091. $columns[$column_name]['NUMERIC_SCALE'] = null;
  1092. $columns[$column_name]['CHARACTER_SET_NAME']
  1093. = substr(
  1094. $columns[$column_name]['COLLATION_NAME'],
  1095. 0,
  1096. strpos($columns[$column_name]['COLLATION_NAME'], '_')
  1097. );
  1098. $ordinal_position++;
  1099. }
  1100. if (null !== $column) {
  1101. reset($columns);
  1102. $columns = current($columns);
  1103. }
  1104. return $columns;
  1105. }
  1106. /**
  1107. * Returns SQL query for fetching columns for a table
  1108. *
  1109. * The 'Key' column is not calculated properly, use PMA_DBI_get_columns() to get
  1110. * correct values.
  1111. *
  1112. * @param string $database name of database
  1113. * @param string $table name of table to retrieve columns from
  1114. * @param string $column name of column, null to show all columns
  1115. * @param boolean $full whether to return full info or only column names
  1116. *
  1117. * @see PMA_DBI_get_columns()
  1118. *
  1119. * @return string
  1120. */
  1121. function PMA_DBI_get_columns_sql($database, $table, $column = null, $full = false)
  1122. {
  1123. if (PMA_DRIZZLE) {
  1124. // `Key` column:
  1125. // * used in primary key => PRI
  1126. // * unique one-column => UNI
  1127. // * indexed, one-column or first in multi-column => MUL
  1128. // Promotion of UNI to PRI in case no promary index exists
  1129. // is done after query is executed
  1130. $sql = "SELECT
  1131. column_name AS `Field`,
  1132. (CASE
  1133. WHEN character_maximum_length > 0
  1134. THEN concat(lower(data_type), '(', character_maximum_length, ')')
  1135. WHEN numeric_precision > 0 OR numeric_scale > 0
  1136. THEN concat(lower(data_type), '(', numeric_precision,
  1137. ',', numeric_scale, ')')
  1138. WHEN enum_values IS NOT NULL
  1139. THEN concat(lower(data_type), '(', enum_values, ')')
  1140. ELSE lower(data_type) END)
  1141. AS `Type`,
  1142. " . ($full ? "
  1143. collation_name AS `Collation`," : '') . "
  1144. (CASE is_nullable
  1145. WHEN 1 THEN 'YES'
  1146. ELSE 'NO' END) AS `Null`,
  1147. (CASE
  1148. WHEN is_used_in_primary THEN 'PRI'
  1149. WHEN is_unique AND NOT is_multi THEN 'UNI'
  1150. WHEN is_indexed
  1151. AND (NOT is_multi OR is_first_in_multi) THEN 'MUL'
  1152. ELSE '' END) AS `Key`,
  1153. column_default AS `Default`,
  1154. (CASE
  1155. WHEN is_auto_increment THEN 'auto_increment'
  1156. WHEN column_default_update <> ''
  1157. THEN 'on update ' || column_default_update
  1158. ELSE '' END) AS `Extra`
  1159. " . ($full ? " ,
  1160. NULL AS `Privileges`,
  1161. column_comment AS `Comment`" : '') . "
  1162. FROM data_dictionary.columns
  1163. WHERE table_schema = '" . PMA_Util::sqlAddSlashes($database) . "'
  1164. AND table_name = '" . PMA_Util::sqlAddSlashes($table) . "'
  1165. " . (($column != null) ? "
  1166. AND column_name = '" . PMA_Util::sqlAddSlashes($column) . "'" : '');
  1167. // ORDER BY ordinal_position
  1168. } else {
  1169. $sql = 'SHOW ' . ($full ? 'FULL' : '') . ' COLUMNS FROM '
  1170. . PMA_Util::backquote($database) . '.' . PMA_Util::backquote($table)
  1171. . (($column != null) ? "LIKE '"
  1172. . PMA_Util::sqlAddSlashes($column, true) . "'" : '');
  1173. }
  1174. return $sql;
  1175. }
  1176. /**
  1177. * Returns descriptions of columns in given table (all or given by $column)
  1178. *
  1179. * @param string $database name of database
  1180. * @param string $table name of table to retrieve columns from
  1181. * @param string $column name of column, null to show all columns
  1182. * @param boolean $full whether to return full info or only column names
  1183. * @param mixed $link mysql link resource
  1184. *
  1185. * @return false|array array indexed by column names or,
  1186. * if $column is given, flat array description
  1187. */
  1188. function PMA_DBI_get_columns($database, $table, $column = null, $full = false,
  1189. $link = null
  1190. ) {
  1191. $sql = PMA_DBI_get_columns_sql($database, $table, $column, $full);
  1192. $fields = PMA_DBI_fetch_result($sql, 'Field', null, $link);
  1193. if (! is_array($fields) || count($fields) == 0) {
  1194. return null;
  1195. }
  1196. if (PMA_DRIZZLE) {
  1197. // fix Key column, it's much simpler in PHP than in SQL
  1198. $has_pk = false;
  1199. $has_pk_candidates = false;
  1200. foreach ($fields as $f) {
  1201. if ($f['Key'] == 'PRI') {
  1202. $has_pk = true;
  1203. break;
  1204. } else if ($f['Null'] == 'NO'
  1205. && ($f['Key'] == 'MUL'
  1206. || $f['Key'] == 'UNI')
  1207. ) {
  1208. $has_pk_candidates = true;
  1209. }
  1210. }
  1211. if (!$has_pk && $has_pk_candidates) {
  1212. // check whether we can promote some unique index to PRI
  1213. $sql = "
  1214. SELECT i.index_name, p.column_name
  1215. FROM data_dictionary.indexes i
  1216. JOIN data_dictionary.index_parts p
  1217. USING (table_schema, table_name)
  1218. WHERE i.table_schema = '" . PMA_Util::sqlAddSlashes($database) . "'
  1219. AND i.table_name = '" . PMA_Util::sqlAddSlashes($table) . "'
  1220. AND i.is_unique
  1221. AND NOT i.is_nullable";
  1222. $fs = PMA_DBI_fetch_result($sql, 'index_name', null, $link);
  1223. $fs = $fs ? array_shift($fs) : array();
  1224. foreach ($fs as $f) {
  1225. $fields[$f]['Key'] = 'PRI';
  1226. }
  1227. }
  1228. }
  1229. return ($column != null) ? array_shift($fields) : $fields;
  1230. }
  1231. /**
  1232. * Returns all column names in given table
  1233. *
  1234. * @param string $database name of database
  1235. * @param string $table name of table to retrieve columns from
  1236. * @param mixed $link mysql link resource
  1237. *
  1238. * @return null|array
  1239. */
  1240. function PMA_DBI_get_column_names($database, $table, $link = null)
  1241. {
  1242. $sql = PMA_DBI_get_columns_sql($database, $table);
  1243. // We only need the 'Field' column which contains the table's column names
  1244. $fields = array_keys(PMA_DBI_fetch_result($sql, 'Field', null, $link));
  1245. if ( ! is_array($fields) || count($fields) == 0 ) {
  1246. return null;
  1247. }
  1248. return $fields;
  1249. }
  1250. /**
  1251. * Returns SQL for fetching information on table indexes (SHOW INDEXES)
  1252. *
  1253. * @param string $database name of database
  1254. * @param string $table name of the table whose indexes are to be retreived
  1255. * @param string $where additional conditions for WHERE
  1256. *
  1257. * @return array $indexes
  1258. */
  1259. function PMA_DBI_get_table_indexes_sql($database, $table, $where = null)
  1260. {
  1261. if (PMA_DRIZZLE) {
  1262. $sql = "SELECT
  1263. ip.table_name AS `Table`,
  1264. (NOT ip.is_unique) AS Non_unique,
  1265. ip.index_name AS Key_name,
  1266. ip.sequence_in_index+1 AS Seq_in_index,
  1267. ip.column_name AS Column_name,
  1268. (CASE
  1269. WHEN i.index_type = 'BTREE' THEN 'A'
  1270. ELSE NULL END) AS Collation,
  1271. NULL AS Cardinality,
  1272. compare_length AS Sub_part,
  1273. NULL AS Packed,
  1274. ip.is_nullable AS `Null`,
  1275. i.index_type AS Index_type,
  1276. NULL AS Comment,
  1277. i.index_comment AS Index_comment
  1278. FROM data_dictionary.index_parts ip
  1279. LEFT JOIN data_dictionary.indexes i
  1280. USING (table_schema, table_name, index_name)
  1281. WHERE table_schema = '" . PMA_Util::sqlAddSlashes($database) . "'
  1282. AND table_name = '" . PMA_Util::sqlAddSlashes($table) . "'
  1283. ";
  1284. } else {
  1285. $sql = 'SHOW INDEXES FROM ' . PMA_Util::backquote($database) . '.'
  1286. . PMA_Util::backquote($table);
  1287. }
  1288. if ($where) {
  1289. $sql .= (PMA_DRIZZLE ? ' AND (' : ' WHERE (') . $where . ')';
  1290. }
  1291. return $sql;
  1292. }
  1293. /**
  1294. * Returns indexes of a table
  1295. *
  1296. * @param string $database name of database
  1297. * @param string $table name of the table whose indexes are to be retrieved
  1298. * @param mixed $link mysql link resource
  1299. *
  1300. * @return array $indexes
  1301. */
  1302. function PMA_DBI_get_table_indexes($database, $table, $link = null)
  1303. {
  1304. $sql = PMA_DBI_get_table_indexes_sql($database, $table);
  1305. $indexes = PMA_DBI_fetch_result($sql, null, null, $link);
  1306. if (! is_array($indexes) || count($indexes) < 1) {
  1307. return array();
  1308. }
  1309. return $indexes;
  1310. }
  1311. /**
  1312. * returns value of given mysql server variable
  1313. *
  1314. * @param string $var mysql server variable name
  1315. * @param int $type PMA_DBI_GETVAR_SESSION|PMA_DBI_GETVAR_GLOBAL
  1316. * @param mixed $link mysql link resource|object
  1317. *
  1318. * @return mixed value for mysql server variable
  1319. */
  1320. function PMA_DBI_get_variable($var, $type = PMA_DBI_GETVAR_SESSION, $link = null)
  1321. {
  1322. if ($link === null) {
  1323. if (isset($GLOBALS['userlink'])) {
  1324. $link = $GLOBALS['userlink'];
  1325. } else {
  1326. return false;
  1327. }
  1328. }
  1329. switch ($type) {
  1330. case PMA_DBI_GETVAR_SESSION:
  1331. $modifier = ' SESSION';
  1332. break;
  1333. case PMA_DBI_GETVAR_GLOBAL:
  1334. $modifier = ' GLOBAL';
  1335. break;
  1336. default:
  1337. $modifier = '';
  1338. }
  1339. return PMA_DBI_fetch_value(
  1340. 'SHOW' . $modifier . ' VARIABLES LIKE \'' . $var . '\';', 0, 1, $link
  1341. );
  1342. }
  1343. /**
  1344. * Function called just after a connection to the MySQL database server has
  1345. * been established. It sets the connection collation, and determins the
  1346. * version of MySQL which is running.
  1347. *
  1348. * @param mixed $link mysql link resource|object
  1349. * @param boolean $is_controluser whether link is for control user
  1350. *
  1351. * @return void
  1352. */
  1353. function PMA_DBI_postConnect($link, $is_controluser = false)
  1354. {
  1355. if ($is_controluser) {
  1356. return;
  1357. }
  1358. if (! defined('PMA_MYSQL_INT_VERSION')) {
  1359. if (PMA_Util::cacheExists('PMA_MYSQL_INT_VERSION', true)) {
  1360. define(
  1361. 'PMA_MYSQL_INT_VERSION',
  1362. PMA_Util::cacheGet('PMA_MYSQL_INT_VERSION', true)
  1363. );
  1364. define(
  1365. 'PMA_MYSQL_MAJOR_VERSION',
  1366. PMA_Util::cacheGet('PMA_MYSQL_MAJOR_VERSION', true)
  1367. );
  1368. define(
  1369. 'PMA_MYSQL_STR_VERSION',
  1370. PMA_Util::cacheGet('PMA_MYSQL_STR_VERSION', true)
  1371. );
  1372. define(
  1373. 'PMA_MYSQL_VERSION_COMMENT',
  1374. PMA_Util::cacheGet('PMA_MYSQL_VERSION_COMMENT', true)
  1375. );
  1376. define(
  1377. 'PMA_DRIZZLE',
  1378. PMA_Util::cacheGet('PMA_DRIZZLE', true)
  1379. );
  1380. } else {
  1381. $version = PMA_DBI_fetch_single_row(
  1382. 'SELECT @@version, @@version_comment',
  1383. 'ASSOC',
  1384. $link
  1385. );
  1386. if ($version) {
  1387. $match = explode('.', $version['@@version']);
  1388. define('PMA_MYSQL_MAJOR_VERSION', (int)$match[0]);
  1389. define(
  1390. 'PMA_MYSQL_INT_VERSION',
  1391. (int) sprintf(
  1392. '%d%02d%02d', $match[0], $match[1], intval($match[2])
  1393. )
  1394. );
  1395. define('PMA_MYSQL_STR_VERSION', $version['@@version']);
  1396. define('PMA_MYSQL_VERSION_COMMENT', $version['@@version_comment']);
  1397. } else {
  1398. define('PMA_MYSQL_INT_VERSION', 50015);
  1399. define('PMA_MYSQL_MAJOR_VERSION', 5);
  1400. define('PMA_MYSQL_STR_VERSION', '5.00.15');
  1401. define('PMA_MYSQL_VERSION_COMMENT', '');
  1402. }
  1403. PMA_Util::cacheSet(
  1404. 'PMA_MYSQL_INT_VERSION',
  1405. PMA_MYSQL_INT_VERSION,
  1406. true
  1407. );
  1408. PMA_Util::cacheSet(
  1409. 'PMA_MYSQL_MAJOR_VERSION',
  1410. PMA_MYSQL_MAJOR_VERSION,
  1411. true
  1412. );
  1413. PMA_Util::cacheSet(
  1414. 'PMA_MYSQL_STR_VERSION',
  1415. PMA_MYSQL_STR_VERSION,
  1416. true
  1417. );
  1418. PMA_Util::cacheSet(
  1419. 'PMA_MYSQL_VERSION_COMMENT',
  1420. PMA_MYSQL_VERSION_COMMENT,
  1421. true
  1422. );
  1423. // Detect Drizzle - it does not support character sets
  1424. $charset_result = PMA_DBI_get_variable(
  1425. 'character_set_results',
  1426. PMA_DBI_GETVAR_GLOBAL,
  1427. $link
  1428. );
  1429. if ($charset_result) {
  1430. define('PMA_DRIZZLE', false);
  1431. } else {
  1432. define('PMA_DRIZZLE', true);
  1433. }
  1434. PMA_Util::cacheSet(
  1435. 'PMA_DRIZZLE',
  1436. PMA_DRIZZLE,
  1437. true
  1438. );
  1439. }
  1440. }
  1441. // Skip charsets for Drizzle
  1442. if (!PMA_DRIZZLE) {
  1443. if (! empty($GLOBALS['collation_connection'])) {
  1444. PMA_DBI_query("SET CHARACTER SET 'utf8';", $link, PMA_DBI_QUERY_STORE);
  1445. $set_collation_con_query = "SET collation_connection = '"
  1446. . PMA_Util::sqlAddSlashes($GLOBALS['collation_connection']) . "';";
  1447. $result = PMA_DBI_try_query(
  1448. $set_collation_con_query,
  1449. $link,
  1450. PMA_DBI_QUERY_STORE
  1451. );
  1452. if ($result === false) {
  1453. trigger_error(
  1454. __('Failed to set configured collation connection!'),
  1455. E_USER_WARNING
  1456. );
  1457. $result = PMA_DBI_query(
  1458. "SET collation_connection = 'utf8_general_ci'",
  1459. $link,
  1460. PMA_DBI_QUERY_STORE
  1461. );
  1462. }
  1463. } else {
  1464. PMA_DBI_query(
  1465. "SET NAMES 'utf8' COLLATE 'utf8_general_ci';",
  1466. $link,
  1467. PMA_DBI_QUERY_STORE
  1468. );
  1469. }
  1470. }
  1471. // Cache plugin list for Drizzle
  1472. if (PMA_DRIZZLE && !PMA_Util::cacheExists('drizzle_engines', true)) {
  1473. $sql = "SELECT p.plugin_name, m.module_library
  1474. FROM data_dictionary.plugins p
  1475. JOIN data_dictionary.modules m USING (module_name)
  1476. WHERE p.plugin_type = 'StorageEngine'
  1477. AND p.plugin_name NOT IN ('FunctionEngine', 'schema')
  1478. AND p.is_active = 'YES'";
  1479. $engines = PMA_DBI_fetch_result($sql, 'plugin_name', null, $link);
  1480. PMA_Util::cacheSet('drizzle_engines', $engines, true);
  1481. }
  1482. }
  1483. /**
  1484. * returns a single value from the given result or query,
  1485. * if the query or the result has more than one row or field
  1486. * the first field of the first row is returned
  1487. *
  1488. * <code>
  1489. * $sql = 'SELECT `name` FROM `user` WHERE `id` = 123';
  1490. * $user_name = PMA_DBI_fetch_value($sql);
  1491. * // produces
  1492. * // $user_name = 'John Doe'
  1493. * </code>
  1494. *
  1495. * @param string|mysql_result $result query or mysql result
  1496. * @param integer $row_number row to fetch the value from,
  1497. * starting at 0, with 0 being default
  1498. * @param integer|string $field field to fetch the value from,
  1499. * starting at 0, with 0 being default
  1500. * @param resource $link mysql link
  1501. *
  1502. * @return mixed value of first field in first row from result
  1503. * or false if not found
  1504. */
  1505. function PMA_DBI_fetch_value($result, $row_number = 0, $field = 0, $link = null)
  1506. {
  1507. $value = false;
  1508. if (is_string($result)) {
  1509. $result = PMA_DBI_try_query($result, $link, PMA_DBI_QUERY_STORE, false);
  1510. }
  1511. // return false if result is empty or false
  1512. // or requested row is larger than rows in result
  1513. if (PMA_DBI_num_rows($result) < ($row_number + 1)) {
  1514. return $value;
  1515. }
  1516. // if $field is an integer use non associative mysql fetch function
  1517. if (is_int($field)) {
  1518. $fetch_function = 'PMA_DBI_fetch_row';
  1519. } else {
  1520. $fetch_function = 'PMA_DBI_fetch_assoc';
  1521. }
  1522. // get requested row
  1523. for ($i = 0; $i <= $row_number; $i++) {
  1524. $row = $fetch_function($result);
  1525. }
  1526. PMA_DBI_free_result($result);
  1527. // return requested field
  1528. if (isset($row[$field])) {
  1529. $value = $row[$field];
  1530. }
  1531. unset($row);
  1532. return $value;
  1533. }
  1534. /**
  1535. * returns only the first row from the result
  1536. *
  1537. * <code>
  1538. * $sql = 'SELECT * FROM `user` WHERE `id` = 123';
  1539. * $user = PMA_DBI_fetch_single_row($sql);
  1540. * // produces
  1541. * // $user = array('id' => 123, 'name' => 'John Doe')
  1542. * </code>
  1543. *
  1544. * @param string|mysql_result $result query or mysql result
  1545. * @param string $type NUM|ASSOC|BOTH
  1546. * returned array should either numeric
  1547. * associativ or booth
  1548. * @param resource $link mysql link
  1549. *
  1550. * @return array|boolean first row from result
  1551. * or false if result is empty
  1552. */
  1553. function PMA_DBI_fetch_single_row($result, $type = 'ASSOC', $link = null)
  1554. {
  1555. if (is_string($result)) {
  1556. $result = PMA_DBI_try_query($result, $link, PMA_DBI_QUERY_STORE, false);
  1557. }
  1558. // return null if result is empty or false
  1559. if (! PMA_DBI_num_rows($result)) {
  1560. return false;
  1561. }
  1562. switch ($type) {
  1563. case 'NUM' :
  1564. $fetch_function = 'PMA_DBI_fetch_row';
  1565. break;
  1566. case 'ASSOC' :
  1567. $fetch_function = 'PMA_DBI_fetch_assoc';
  1568. break;
  1569. case 'BOTH' :
  1570. default :
  1571. $fetch_function = 'PMA_DBI_fetch_array';
  1572. break;
  1573. }
  1574. $row = $fetch_function($result);
  1575. PMA_DBI_free_result($result);
  1576. return $row;
  1577. }
  1578. /**
  1579. * returns all rows in the resultset in one array
  1580. *
  1581. * <code>
  1582. * $sql = 'SELECT * FROM `user`';
  1583. * $users = PMA_DBI_fetch_result($sql);
  1584. * // produces
  1585. * // $users[] = array('id' => 123, 'name' => 'John Doe')
  1586. *
  1587. * $sql = 'SELECT `id`, `name` FROM `user`';
  1588. * $users = PMA_DBI_fetch_result($sql, 'id');
  1589. * // produces
  1590. * // $users['123'] = array('id' => 123, 'name' => 'John Doe')
  1591. *
  1592. * $sql = 'SELECT `id`, `name` FROM `user`';
  1593. * $users = PMA_DBI_fetch_result($sql, 0);
  1594. * // produces
  1595. * // $users['123'] = array(0 => 123, 1 => 'John Doe')
  1596. *
  1597. * $sql = 'SELECT `id`, `name` FROM `user`';
  1598. * $users = PMA_DBI_fetch_result($sql, 'id', 'name');
  1599. * // or
  1600. * $users = PMA_DBI_fetch_result($sql, 0, 1);
  1601. * // produces
  1602. * // $users['123'] = 'John Doe'
  1603. *
  1604. * $sql = 'SELECT `name` FROM `user`';
  1605. * $users = PMA_DBI_fetch_result($sql);
  1606. * // produces
  1607. * // $users[] = 'John Doe'
  1608. *
  1609. * $sql = 'SELECT `group`, `name` FROM `user`'
  1610. * $users = PMA_DBI_fetch_result($sql, array('group', null), 'name');
  1611. * // produces
  1612. * // $users['admin'][] = 'John Doe'
  1613. *
  1614. * $sql = 'SELECT `group`, `name` FROM `user`'
  1615. * $users = PMA_DBI_fetch_result($sql, array('group', 'name'), 'id');
  1616. * // produces
  1617. * // $users['admin']['John Doe'] = '123'
  1618. * </code>
  1619. *
  1620. * @param string|mysql_result $result query or mysql result
  1621. * @param string|integer $key field-name or offset
  1622. * used as key for array
  1623. * @param string|integer $value value-name or offset
  1624. * used as value for array
  1625. * @param resource $link mysql link
  1626. * @param mixed $options query options
  1627. *
  1628. * @return array resultrows or values indexed by $key
  1629. */
  1630. function PMA_DBI_fetch_result($result, $key = null, $value = null,
  1631. $link = null, $options = 0
  1632. ) {
  1633. $resultrows = array();
  1634. if (is_string($result)) {
  1635. $result = PMA_DBI_try_query($result, $link, $options, false);
  1636. }
  1637. // return empty array if result is empty or false
  1638. if (! $result) {
  1639. return $resultrows;
  1640. }
  1641. $fetch_function = 'PMA_DBI_fetch_assoc';
  1642. // no nested array if only one field is in result
  1643. if (null === $key && 1 === PMA_DBI_num_fields($result)) {
  1644. $value = 0;
  1645. $fetch_function = 'PMA_DBI_fetch_row';
  1646. }
  1647. // if $key is an integer use non associative mysql fetch function
  1648. if (is_int($key)) {
  1649. $fetch_function = 'PMA_DBI_fetch_row';
  1650. }
  1651. if (null === $key && null === $value) {
  1652. while ($row = $fetch_function($result)) {
  1653. $resultrows[] = $row;
  1654. }
  1655. } elseif (null === $key) {
  1656. while ($row = $fetch_function($result)) {
  1657. $resultrows[] = $row[$value];
  1658. }
  1659. } elseif (null === $value) {
  1660. if (is_array($key)) {
  1661. while ($row = $fetch_function($result)) {
  1662. $result_target =& $resultrows;
  1663. foreach ($key as $key_index) {
  1664. if (null === $key_index) {
  1665. $result_target =& $result_target[];
  1666. continue;
  1667. }
  1668. if (! isset($result_target[$row[$key_index]])) {
  1669. $result_target[$row[$key_index]] = array();
  1670. }
  1671. $result_target =& $result_target[$row[$key_index]];
  1672. }
  1673. $result_target = $row;
  1674. }
  1675. } else {
  1676. while ($row = $fetch_function($result)) {
  1677. $resultrows[$row[$key]] = $row;
  1678. }
  1679. }
  1680. } else {
  1681. if (is_array($key)) {
  1682. while ($row = $fetch_function($result)) {
  1683. $result_target =& $resultrows;
  1684. foreach ($key as $key_index) {
  1685. if (null === $key_index) {
  1686. $result_target =& $result_target[];
  1687. continue;
  1688. }
  1689. if (! isset($result_target[$row[$key_index]])) {
  1690. $result_target[$row[$key_index]] = array();
  1691. }
  1692. $result_target =& $result_target[$row[$key_index]];
  1693. }
  1694. $result_target = $row[$value];
  1695. }
  1696. } else {
  1697. while ($row = $fetch_function($result)) {
  1698. $resultrows[$row[$key]] = $row[$value];
  1699. }
  1700. }
  1701. }
  1702. PMA_DBI_free_result($result);
  1703. return $resultrows;
  1704. }
  1705. /**
  1706. * Get supported SQL compatibility modes
  1707. *
  1708. * @return array supported SQL compatibility modes
  1709. */
  1710. function PMA_DBI_getCompatibilities()
  1711. {
  1712. // Drizzle doesn't support compatibility modes
  1713. if (PMA_DRIZZLE) {
  1714. return array();
  1715. }
  1716. $compats = array('NONE');
  1717. $compats[] = 'ANSI';
  1718. $compats[] = 'DB2';
  1719. $compats[] = 'MAXDB';
  1720. $compats[] = 'MYSQL323';
  1721. $compats[] = 'MYSQL40';
  1722. $compats[] = 'MSSQL';
  1723. $compats[] = 'ORACLE';
  1724. // removed; in MySQL 5.0.33, this produces exports that
  1725. // can't be read by POSTGRESQL (see our bug #1596328)
  1726. //$compats[] = 'POSTGRESQL';
  1727. $compats[] = 'TRADITIONAL';
  1728. return $compats;
  1729. }
  1730. /**
  1731. * returns warnings for last query
  1732. *
  1733. * @param resource $link mysql link resource
  1734. *
  1735. * @return array warnings
  1736. */
  1737. function PMA_DBI_get_warnings($link = null)
  1738. {
  1739. if (empty($link)) {
  1740. if (isset($GLOBALS['userlink'])) {
  1741. $link = $GLOBALS['userlink'];
  1742. } else {
  1743. return array();
  1744. }
  1745. }
  1746. return PMA_DBI_fetch_result('SHOW WARNINGS', null, null, $link);
  1747. }
  1748. /**
  1749. * returns true (int > 0) if current user is superuser
  1750. * otherwise 0
  1751. *
  1752. * @return bool Whether use is a superuser
  1753. */
  1754. function PMA_isSuperuser()
  1755. {
  1756. if (PMA_Util::cacheExists('is_superuser', true)) {
  1757. return PMA_Util::cacheGet('is_superuser', true);
  1758. }
  1759. // when connection failed we don't have a $userlink
  1760. if (isset($GLOBALS['userlink'])) {
  1761. if (PMA_DRIZZLE) {
  1762. // Drizzle has no authorization by default, so when no plugin is
  1763. // enabled everyone is a superuser
  1764. // Known authorization libraries: regex_policy, simple_user_policy
  1765. // Plugins limit object visibility (dbs, tables, processes), we can
  1766. // safely assume we always deal with superuser
  1767. $result = true;
  1768. } else {
  1769. // check access to mysql.user table
  1770. $result = (bool) PMA_DBI_try_query(
  1771. 'SELECT COUNT(*) FROM mysql.user',
  1772. $GLOBALS['userlink'],
  1773. PMA_DBI_QUERY_STORE
  1774. );
  1775. }
  1776. PMA_Util::cacheSet('is_superuser', $result, true);
  1777. } else {
  1778. PMA_Util::cacheSet('is_superuser', false, true);
  1779. }
  1780. return PMA_Util::cacheGet('is_superuser', true);
  1781. }
  1782. /**
  1783. * returns an array of PROCEDURE or FUNCTION names for a db
  1784. *
  1785. * @param string $db db name
  1786. * @param string $which PROCEDURE | FUNCTION
  1787. * @param resource $link mysql link
  1788. *
  1789. * @return array the procedure names or function names
  1790. */
  1791. function PMA_DBI_get_procedures_or_functions($db, $which, $link = null)
  1792. {
  1793. if (PMA_DRIZZLE) {
  1794. // Drizzle doesn't support functions and procedures
  1795. return array();
  1796. }
  1797. $shows = PMA_DBI_fetch_result('SHOW ' . $which . ' STATUS;', null, null, $link);
  1798. $result = array();
  1799. foreach ($shows as $one_show) {
  1800. if ($one_show['Db'] == $db && $one_show['Type'] == $which) {
  1801. $result[] = $one_show['Name'];
  1802. }
  1803. }
  1804. return($result);
  1805. }
  1806. /**
  1807. * returns the definition of a specific PROCEDURE, FUNCTION, EVENT or VIEW
  1808. *
  1809. * @param string $db db name
  1810. * @param string $which PROCEDURE | FUNCTION | EVENT | VIEW
  1811. * @param string $name the procedure|function|event|view name
  1812. * @param resource $link mysql link
  1813. *
  1814. * @return string the definition
  1815. */
  1816. function PMA_DBI_get_definition($db, $which, $name, $link = null)
  1817. {
  1818. $returned_field = array(
  1819. 'PROCEDURE' => 'Create Procedure',
  1820. 'FUNCTION' => 'Create Function',
  1821. 'EVENT' => 'Create Event',
  1822. 'VIEW' => 'Create View'
  1823. );
  1824. $query = 'SHOW CREATE ' . $which . ' '
  1825. . PMA_Util::backquote($db) . '.'
  1826. . PMA_Util::backquote($name);
  1827. return(PMA_DBI_fetch_value($query, 0, $returned_field[$which]));
  1828. }
  1829. /**
  1830. * returns details about the TRIGGERs for a specific table or database
  1831. *
  1832. * @param string $db db name
  1833. * @param string $table table name
  1834. * @param string $delimiter the delimiter to use (may be empty)
  1835. *
  1836. * @return array information about triggers (may be empty)
  1837. */
  1838. function PMA_DBI_get_triggers($db, $table = '', $delimiter = '//')
  1839. {
  1840. if (PMA_DRIZZLE) {
  1841. // Drizzle doesn't support triggers
  1842. return array();
  1843. }
  1844. $result = array();
  1845. if (! $GLOBALS['cfg']['Server']['DisableIS']) {
  1846. // Note: in http://dev.mysql.com/doc/refman/5.0/en/faqs-triggers.html
  1847. // their example uses WHERE TRIGGER_SCHEMA='dbname' so let's use this
  1848. // instead of WHERE EVENT_OBJECT_SCHEMA='dbname'
  1849. $query = 'SELECT TRIGGER_SCHEMA, TRIGGER_NAME, EVENT_MANIPULATION'
  1850. . ', EVENT_OBJECT_TABLE, ACTION_TIMING, ACTION_STATEMENT'
  1851. . ', EVENT_OBJECT_SCHEMA, EVENT_OBJECT_TABLE, DEFINER'
  1852. . ' FROM information_schema.TRIGGERS'
  1853. . ' WHERE TRIGGER_SCHEMA= \'' . PMA_Util::sqlAddSlashes($db) . '\'';
  1854. if (! empty($table)) {
  1855. $query .= " AND EVENT_OBJECT_TABLE = '"
  1856. . PMA_Util::sqlAddSlashes($table) . "';";
  1857. }
  1858. } else {
  1859. $query = "SHOW TRIGGERS FROM " . PMA_Util::backquote($db);
  1860. if (! empty($table)) {
  1861. $query .= " LIKE '" . PMA_Util::sqlAddSlashes($table, true) . "';";
  1862. }
  1863. }
  1864. if ($triggers = PMA_DBI_fetch_result($query)) {
  1865. foreach ($triggers as $trigger) {
  1866. if ($GLOBALS['cfg']['Server']['DisableIS']) {
  1867. $trigger['TRIGGER_NAME'] = $trigger['Trigger'];
  1868. $trigger['ACTION_TIMING'] = $trigger['Timing'];
  1869. $trigger['EVENT_MANIPULATION'] = $trigger['Event'];
  1870. $trigger['EVENT_OBJECT_TABLE'] = $trigger['Table'];
  1871. $trigger['ACTION_STATEMENT'] = $trigger['Statement'];
  1872. $trigger['DEFINER'] = $trigger['Definer'];
  1873. }
  1874. $one_result = array();
  1875. $one_result['name'] = $trigger['TRIGGER_NAME'];
  1876. $one_result['table'] = $trigger['EVENT_OBJECT_TABLE'];
  1877. $one_result['action_timing'] = $trigger['ACTION_TIMING'];
  1878. $one_result['event_manipulation'] = $trigger['EVENT_MANIPULATION'];
  1879. $one_result['definition'] = $trigger['ACTION_STATEMENT'];
  1880. $one_result['definer'] = $trigger['DEFINER'];
  1881. // do not prepend the schema name; this way, importing the
  1882. // definition into another schema will work
  1883. $one_result['full_trigger_name'] = PMA_Util::backquote(
  1884. $trigger['TRIGGER_NAME']
  1885. );
  1886. $one_result['drop'] = 'DROP TRIGGER IF EXISTS '
  1887. . $one_result['full_trigger_name'];
  1888. $one_result['create'] = 'CREATE TRIGGER '
  1889. . $one_result['full_trigger_name'] . ' '
  1890. . $trigger['ACTION_TIMING']. ' '
  1891. . $trigger['EVENT_MANIPULATION']
  1892. . ' ON ' . PMA_Util::backquote($trigger['EVENT_OBJECT_TABLE'])
  1893. . "\n" . ' FOR EACH ROW '
  1894. . $trigger['ACTION_STATEMENT'] . "\n" . $delimiter . "\n";
  1895. $result[] = $one_result;
  1896. }
  1897. }
  1898. // Sort results by name
  1899. $name = array();
  1900. foreach ($result as $value) {
  1901. $name[] = $value['name'];
  1902. }
  1903. array_multisort($name, SORT_ASC, $result);
  1904. return($result);
  1905. }
  1906. /**
  1907. * Formats database error message in a friendly way.
  1908. * This is needed because some errors messages cannot
  1909. * be obtained by mysql_error().
  1910. *
  1911. * @param int $error_number Error code
  1912. * @param string $error_message Error message as returned by server
  1913. *
  1914. * @return string HML text with error details
  1915. */
  1916. function PMA_DBI_formatError($error_number, $error_message)
  1917. {
  1918. if (! empty($error_message)) {
  1919. $error_message = PMA_DBI_convert_message($error_message);
  1920. }
  1921. $error_message = htmlspecialchars($error_message);
  1922. $error = '#' . ((string) $error_number);
  1923. if ($error_number == 2002) {
  1924. $error .= ' - ' . $error_message;
  1925. $error .= '<br />';
  1926. $error .= __(
  1927. 'The server is not responding (or the local server\'s socket'
  1928. . ' is not correctly configured).'
  1929. );
  1930. } elseif ($error_number == 2003) {
  1931. $error .= ' - ' . $error_message;
  1932. $error .= '<br />' . __('The server is not responding.');
  1933. } elseif ($error_number == 1005) {
  1934. if (strpos($error_message, 'errno: 13') !== false) {
  1935. $error .= ' - ' . $error_message;
  1936. $error .= '<br />'
  1937. . __('Please check privileges of directory containing database.');
  1938. } else {
  1939. /* InnoDB contraints, see
  1940. * http://dev.mysql.com/doc/refman/5.0/en/
  1941. * innodb-foreign-key-constraints.html
  1942. */
  1943. $error .= ' - ' . $error_message .
  1944. ' (<a href="server_engines.php' .
  1945. PMA_generate_common_url(
  1946. array('engine' => 'InnoDB', 'page' => 'Status')
  1947. ) . '">' . __('Details…') . '</a>)';
  1948. }
  1949. } else {
  1950. $error .= ' - ' . $error_message;
  1951. }
  1952. return $error;
  1953. }
  1954. /**
  1955. * Checks whether given schema is a system schema: information_schema
  1956. * (MySQL and Drizzle) or data_dictionary (Drizzle)
  1957. *
  1958. * @param string $schema_name Name of schema (database) to test
  1959. * @param bool $test_for_mysql_schema Whether 'mysql' schema should
  1960. * be treated the same as IS and DD
  1961. *
  1962. * @return bool
  1963. */
  1964. function PMA_is_system_schema($schema_name, $test_for_mysql_schema = false)
  1965. {
  1966. return strtolower($schema_name) == 'information_schema'
  1967. || (!PMA_DRIZZLE && strtolower($schema_name) == 'performance_schema')
  1968. || (PMA_DRIZZLE && strtolower($schema_name) == 'data_dictionary')
  1969. || ($test_for_mysql_schema && !PMA_DRIZZLE && $schema_name == 'mysql');
  1970. }
  1971. /**
  1972. * Get regular expression which occur first inside the given sql query.
  1973. *
  1974. * @param Array $regex_array Comparing regular expressions.
  1975. * @param String $query SQL query to be checked.
  1976. *
  1977. * @return String Matching regular expression.
  1978. */
  1979. function PMA_getFirstOccurringRegularExpression($regex_array, $query)
  1980. {
  1981. $minimum_first_occurence_index = null;
  1982. $regex = null;
  1983. for ($i = 0; $i < count($regex_array); $i++) {
  1984. if (preg_match($regex_array[$i], $query, $matches, PREG_OFFSET_CAPTURE)) {
  1985. if (is_null($minimum_first_occurence_index)
  1986. || ($matches[0][1] < $minimum_first_occurence_index)
  1987. ) {
  1988. $regex = $regex_array[$i];
  1989. $minimum_first_occurence_index = $matches[0][1];
  1990. }
  1991. }
  1992. }
  1993. return $regex;
  1994. }
  1995. ?>