DatabaseInterface.class.php 82 KB

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