DatabaseInterface.php 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113
  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. namespace PhpMyAdmin;
  9. use PhpMyAdmin\Core;
  10. use PhpMyAdmin\Database\DatabaseList;
  11. use PhpMyAdmin\Dbi\DbiExtension;
  12. use PhpMyAdmin\Dbi\DbiDummy;
  13. use PhpMyAdmin\Dbi\DbiMysql;
  14. use PhpMyAdmin\Dbi\DbiMysqli;
  15. use PhpMyAdmin\Di\Container;
  16. use PhpMyAdmin\Error;
  17. use PhpMyAdmin\Index;
  18. use PhpMyAdmin\LanguageManager;
  19. use PhpMyAdmin\Relation;
  20. use PhpMyAdmin\SystemDatabase;
  21. use PhpMyAdmin\Table;
  22. use PhpMyAdmin\Types;
  23. use PhpMyAdmin\Tracker;
  24. use PhpMyAdmin\Url;
  25. use PhpMyAdmin\Util;
  26. /**
  27. * Main interface for database interactions
  28. *
  29. * @package PhpMyAdmin-DBI
  30. */
  31. class DatabaseInterface
  32. {
  33. /**
  34. * Force STORE_RESULT method, ignored by classic MySQL.
  35. */
  36. const QUERY_STORE = 1;
  37. /**
  38. * Do not read whole query.
  39. */
  40. const QUERY_UNBUFFERED = 2;
  41. /**
  42. * Get session variable.
  43. */
  44. const GETVAR_SESSION = 1;
  45. /**
  46. * Get global variable.
  47. */
  48. const GETVAR_GLOBAL = 2;
  49. /**
  50. * User connection.
  51. */
  52. const CONNECT_USER = 0x100;
  53. /**
  54. * Control user connection.
  55. */
  56. const CONNECT_CONTROL = 0x101;
  57. /**
  58. * Auxiliary connection.
  59. *
  60. * Used for example for replication setup.
  61. */
  62. const CONNECT_AUXILIARY = 0x102;
  63. /**
  64. * @var DbiExtension
  65. */
  66. private $_extension;
  67. /**
  68. * Opened database links
  69. *
  70. * @var array
  71. */
  72. private $_links;
  73. /**
  74. * @var array Table data cache
  75. */
  76. private $_table_cache;
  77. /**
  78. * @var array Current user and host cache
  79. */
  80. private $_current_user;
  81. /**
  82. * @var null|string lower_case_table_names value cache
  83. */
  84. private $_lower_case_table_names = null;
  85. /**
  86. * @var boolean Whether connection is MariaDB
  87. */
  88. private $_is_mariadb = false;
  89. /**
  90. * @var boolean Whether connection is Percona
  91. */
  92. private $_is_percona = false;
  93. /**
  94. * @var integer Server version as number
  95. */
  96. private $_version_int = 55000;
  97. /**
  98. * @var string Server version
  99. */
  100. private $_version_str = '5.50.0';
  101. /**
  102. * @var string Server version comment
  103. */
  104. private $_version_comment = '';
  105. /**
  106. * @var Types MySQL types data
  107. */
  108. public $types;
  109. /**
  110. * @var Relation $relation
  111. */
  112. private $relation;
  113. /**
  114. * Constructor
  115. *
  116. * @param DbiExtension $ext Object to be used for database queries
  117. */
  118. public function __construct($ext)
  119. {
  120. $this->_extension = $ext;
  121. $this->_links = array();
  122. if (defined('TESTSUITE')) {
  123. $this->_links[DatabaseInterface::CONNECT_USER] = 1;
  124. $this->_links[DatabaseInterface::CONNECT_CONTROL] = 2;
  125. }
  126. $this->_table_cache = array();
  127. $this->_current_user = array();
  128. $this->types = new Types($this);
  129. $this->relation = new Relation();
  130. }
  131. /**
  132. * Checks whether database extension is loaded
  133. *
  134. * @param string $extension mysql extension to check
  135. *
  136. * @return bool
  137. */
  138. public static function checkDbExtension($extension = 'mysql')
  139. {
  140. return function_exists($extension . '_connect');
  141. }
  142. /**
  143. * runs a query
  144. *
  145. * @param string $query SQL query to execute
  146. * @param mixed $link optional database link to use
  147. * @param int $options optional query options
  148. * @param bool $cache_affected_rows whether to cache affected rows
  149. *
  150. * @return mixed
  151. */
  152. public function query($query, $link = DatabaseInterface::CONNECT_USER, $options = 0,
  153. $cache_affected_rows = true
  154. ) {
  155. $res = $this->tryQuery($query, $link, $options, $cache_affected_rows)
  156. or Util::mysqlDie($this->getError($link), $query);
  157. return $res;
  158. }
  159. /**
  160. * Get a cached value from table cache.
  161. *
  162. * @param array $contentPath Array of the name of the target value
  163. * @param mixed $default Return value on cache miss
  164. *
  165. * @return mixed cached value or default
  166. */
  167. public function getCachedTableContent(array $contentPath, $default = null)
  168. {
  169. return Util::getValueByKey($this->_table_cache, $contentPath, $default);
  170. }
  171. /**
  172. * Set an item in table cache using dot notation.
  173. *
  174. * @param array $contentPath Array with the target path
  175. * @param mixed $value Target value
  176. *
  177. * @return void
  178. */
  179. public function cacheTableContent(array $contentPath, $value)
  180. {
  181. $loc = &$this->_table_cache;
  182. if (!isset($contentPath)) {
  183. $loc = $value;
  184. return;
  185. }
  186. while (count($contentPath) > 1) {
  187. $key = array_shift($contentPath);
  188. // If the key doesn't exist at this depth, we will just create an empty
  189. // array to hold the next value, allowing us to create the arrays to hold
  190. // final values at the correct depth. Then we'll keep digging into the
  191. // array.
  192. if (!isset($loc[$key]) || !is_array($loc[$key])) {
  193. $loc[$key] = array();
  194. }
  195. $loc = &$loc[$key];
  196. }
  197. $loc[array_shift($contentPath)] = $value;
  198. }
  199. /**
  200. * Clear the table cache.
  201. *
  202. * @return void
  203. */
  204. public function clearTableCache()
  205. {
  206. $this->_table_cache = array();
  207. }
  208. /**
  209. * Caches table data so Table does not require to issue
  210. * SHOW TABLE STATUS again
  211. *
  212. * @param array $tables information for tables of some databases
  213. * @param string $table table name
  214. *
  215. * @return void
  216. */
  217. private function _cacheTableData(array $tables, $table)
  218. {
  219. // Note: I don't see why we would need array_merge_recursive() here,
  220. // as it creates double entries for the same table (for example a double
  221. // entry for Comment when changing the storage engine in Operations)
  222. // Note 2: Instead of array_merge(), simply use the + operator because
  223. // array_merge() renumbers numeric keys starting with 0, therefore
  224. // we would lose a db name that consists only of numbers
  225. foreach ($tables as $one_database => $its_tables) {
  226. if (isset($this->_table_cache[$one_database])) {
  227. // the + operator does not do the intended effect
  228. // when the cache for one table already exists
  229. if ($table
  230. && isset($this->_table_cache[$one_database][$table])
  231. ) {
  232. unset($this->_table_cache[$one_database][$table]);
  233. }
  234. $this->_table_cache[$one_database]
  235. = $this->_table_cache[$one_database] + $tables[$one_database];
  236. } else {
  237. $this->_table_cache[$one_database] = $tables[$one_database];
  238. }
  239. }
  240. }
  241. /**
  242. * Stores query data into session data for debugging purposes
  243. *
  244. * @param string $query Query text
  245. * @param integer $link link type
  246. * @param object|boolean $result Query result
  247. * @param integer $time Time to execute query
  248. *
  249. * @return void
  250. */
  251. private function _dbgQuery($query, $link, $result, $time)
  252. {
  253. $dbgInfo = array();
  254. $error_message = $this->getError($link);
  255. if ($result == false && is_string($error_message)) {
  256. $dbgInfo['error']
  257. = '<span style="color:red">'
  258. . htmlspecialchars($error_message) . '</span>';
  259. }
  260. $dbgInfo['query'] = htmlspecialchars($query);
  261. $dbgInfo['time'] = $time;
  262. // Get and slightly format backtrace, this is used
  263. // in the javascript console.
  264. // Strip call to _dbgQuery
  265. $dbgInfo['trace'] = Error::processBacktrace(
  266. array_slice(debug_backtrace(), 1)
  267. );
  268. $dbgInfo['hash'] = md5($query);
  269. $_SESSION['debug']['queries'][] = $dbgInfo;
  270. }
  271. /**
  272. * runs a query and returns the result
  273. *
  274. * @param string $query query to run
  275. * @param integer $link link type
  276. * @param integer $options query options
  277. * @param bool $cache_affected_rows whether to cache affected row
  278. *
  279. * @return mixed
  280. */
  281. public function tryQuery($query, $link = DatabaseInterface::CONNECT_USER, $options = 0,
  282. $cache_affected_rows = true
  283. ) {
  284. $debug = isset($GLOBALS['cfg']['DBG']) ? $GLOBALS['cfg']['DBG']['sql'] : false;
  285. if (! isset($this->_links[$link])) {
  286. return false;
  287. }
  288. if ($debug) {
  289. $time = microtime(true);
  290. }
  291. $result = $this->_extension->realQuery($query, $this->_links[$link], $options);
  292. if ($cache_affected_rows) {
  293. $GLOBALS['cached_affected_rows'] = $this->affectedRows($link, false);
  294. }
  295. if ($debug) {
  296. $time = microtime(true) - $time;
  297. $this->_dbgQuery($query, $link, $result, $time);
  298. if ($GLOBALS['cfg']['DBG']['sqllog']) {
  299. $warningsCount = '';
  300. if (($options & DatabaseInterface::QUERY_STORE) == DatabaseInterface::QUERY_STORE) {
  301. if (isset($this->_links[$link]->warning_count)) {
  302. $warningsCount = $this->_links[$link]->warning_count;
  303. }
  304. }
  305. openlog('phpMyAdmin', LOG_NDELAY | LOG_PID, LOG_USER);
  306. syslog(
  307. LOG_INFO,
  308. 'SQL[' . basename($_SERVER['SCRIPT_NAME']) . ']: '
  309. . sprintf('%0.3f', $time) . '(W:' . $warningsCount . ') > ' . $query
  310. );
  311. closelog();
  312. }
  313. }
  314. if ($result !== false && Tracker::isActive()) {
  315. Tracker::handleQuery($query);
  316. }
  317. return $result;
  318. }
  319. /**
  320. * Run multi query statement and return results
  321. *
  322. * @param string $multi_query multi query statement to execute
  323. * @param mysqli $link mysqli object
  324. *
  325. * @return mysqli_result collection | boolean(false)
  326. */
  327. public function tryMultiQuery($multi_query = '', $link = DatabaseInterface::CONNECT_USER)
  328. {
  329. if (! isset($this->_links[$link])) {
  330. return false;
  331. }
  332. return $this->_extension->realMultiQuery($this->_links[$link], $multi_query);
  333. }
  334. /**
  335. * returns array with table names for given db
  336. *
  337. * @param string $database name of database
  338. * @param mixed $link mysql link resource|object
  339. *
  340. * @return array tables names
  341. */
  342. public function getTables($database, $link = DatabaseInterface::CONNECT_USER)
  343. {
  344. $tables = $this->fetchResult(
  345. 'SHOW TABLES FROM ' . Util::backquote($database) . ';',
  346. null,
  347. 0,
  348. $link,
  349. self::QUERY_STORE
  350. );
  351. if ($GLOBALS['cfg']['NaturalOrder']) {
  352. usort($tables, 'strnatcasecmp');
  353. }
  354. return $tables;
  355. }
  356. /**
  357. * returns
  358. *
  359. * @param string $database name of database
  360. * @param array $tables list of tables to search for for relations
  361. * @param int $link mysql link resource|object
  362. *
  363. * @return array array of found foreign keys
  364. */
  365. public function getForeignKeyConstrains($database, array $tables, $link = DatabaseInterface::CONNECT_USER)
  366. {
  367. $tablesListForQuery = '';
  368. foreach($tables as $table){
  369. $tablesListForQuery .= "'" . $this->escapeString($table) . "',";
  370. }
  371. $tablesListForQuery = rtrim($tablesListForQuery, ',');
  372. $foreignKeyConstrains = $this->fetchResult(
  373. "SELECT"
  374. . " TABLE_NAME,"
  375. . " COLUMN_NAME,"
  376. . " REFERENCED_TABLE_NAME,"
  377. . " REFERENCED_COLUMN_NAME"
  378. . " FROM information_schema.key_column_usage"
  379. . " WHERE referenced_table_name IS NOT NULL"
  380. . " AND TABLE_SCHEMA = '" . $this->escapeString($database) . "'"
  381. . " AND TABLE_NAME IN (" . $tablesListForQuery . ")"
  382. . " AND REFERENCED_TABLE_NAME IN (" . $tablesListForQuery . ");",
  383. null,
  384. null,
  385. $link,
  386. self::QUERY_STORE
  387. );
  388. return $foreignKeyConstrains;
  389. }
  390. /**
  391. * returns a segment of the SQL WHERE clause regarding table name and type
  392. *
  393. * @param array|string $table table(s)
  394. * @param boolean $tbl_is_group $table is a table group
  395. * @param string $table_type whether table or view
  396. *
  397. * @return string a segment of the WHERE clause
  398. */
  399. private function _getTableCondition($table, $tbl_is_group, $table_type)
  400. {
  401. // get table information from information_schema
  402. if ($table) {
  403. if (is_array($table)) {
  404. $sql_where_table = 'AND t.`TABLE_NAME` '
  405. . Util::getCollateForIS() . ' IN (\''
  406. . implode(
  407. '\', \'',
  408. array_map(
  409. array($this, 'escapeString'),
  410. $table
  411. )
  412. )
  413. . '\')';
  414. } elseif (true === $tbl_is_group) {
  415. $sql_where_table = 'AND t.`TABLE_NAME` LIKE \''
  416. . Util::escapeMysqlWildcards(
  417. $GLOBALS['dbi']->escapeString($table)
  418. )
  419. . '%\'';
  420. } else {
  421. $sql_where_table = 'AND t.`TABLE_NAME` '
  422. . Util::getCollateForIS() . ' = \''
  423. . $GLOBALS['dbi']->escapeString($table) . '\'';
  424. }
  425. } else {
  426. $sql_where_table = '';
  427. }
  428. if ($table_type) {
  429. if ($table_type == 'view') {
  430. $sql_where_table .= " AND t.`TABLE_TYPE` NOT IN ('BASE TABLE', 'SYSTEM VERSIONED')";
  431. } elseif ($table_type == 'table') {
  432. $sql_where_table .= " AND t.`TABLE_TYPE` IN ('BASE TABLE', 'SYSTEM VERSIONED')";
  433. }
  434. }
  435. return $sql_where_table;
  436. }
  437. /**
  438. * returns the beginning of the SQL statement to fetch the list of tables
  439. *
  440. * @param string[] $this_databases databases to list
  441. * @param string $sql_where_table additional condition
  442. *
  443. * @return string the SQL statement
  444. */
  445. private function _getSqlForTablesFull($this_databases, $sql_where_table)
  446. {
  447. $sql = '
  448. SELECT *,
  449. `TABLE_SCHEMA` AS `Db`,
  450. `TABLE_NAME` AS `Name`,
  451. `TABLE_TYPE` AS `TABLE_TYPE`,
  452. `ENGINE` AS `Engine`,
  453. `ENGINE` AS `Type`,
  454. `VERSION` AS `Version`,
  455. `ROW_FORMAT` AS `Row_format`,
  456. `TABLE_ROWS` AS `Rows`,
  457. `AVG_ROW_LENGTH` AS `Avg_row_length`,
  458. `DATA_LENGTH` AS `Data_length`,
  459. `MAX_DATA_LENGTH` AS `Max_data_length`,
  460. `INDEX_LENGTH` AS `Index_length`,
  461. `DATA_FREE` AS `Data_free`,
  462. `AUTO_INCREMENT` AS `Auto_increment`,
  463. `CREATE_TIME` AS `Create_time`,
  464. `UPDATE_TIME` AS `Update_time`,
  465. `CHECK_TIME` AS `Check_time`,
  466. `TABLE_COLLATION` AS `Collation`,
  467. `CHECKSUM` AS `Checksum`,
  468. `CREATE_OPTIONS` AS `Create_options`,
  469. `TABLE_COMMENT` AS `Comment`
  470. FROM `information_schema`.`TABLES` t
  471. WHERE `TABLE_SCHEMA` ' . Util::getCollateForIS() . '
  472. IN (\'' . implode("', '", $this_databases) . '\')
  473. ' . $sql_where_table;
  474. return $sql;
  475. }
  476. /**
  477. * returns array of all tables in given db or dbs
  478. * this function expects unquoted names:
  479. * RIGHT: my_database
  480. * WRONG: `my_database`
  481. * WRONG: my\_database
  482. * if $tbl_is_group is true, $table is used as filter for table names
  483. *
  484. * <code>
  485. * $GLOBALS['dbi']->getTablesFull('my_database');
  486. * $GLOBALS['dbi']->getTablesFull('my_database', 'my_table'));
  487. * $GLOBALS['dbi']->getTablesFull('my_database', 'my_tables_', true));
  488. * </code>
  489. *
  490. * @param string $database database
  491. * @param string|array $table table name(s)
  492. * @param boolean $tbl_is_group $table is a table group
  493. * @param integer $limit_offset zero-based offset for the count
  494. * @param boolean|integer $limit_count number of tables to return
  495. * @param string $sort_by table attribute to sort by
  496. * @param string $sort_order direction to sort (ASC or DESC)
  497. * @param string $table_type whether table or view
  498. * @param integer $link link type
  499. *
  500. * @todo move into Table
  501. *
  502. * @return array list of tables in given db(s)
  503. */
  504. public function getTablesFull($database, $table = '',
  505. $tbl_is_group = false, $limit_offset = 0,
  506. $limit_count = false, $sort_by = 'Name', $sort_order = 'ASC',
  507. $table_type = null, $link = DatabaseInterface::CONNECT_USER
  508. ) {
  509. if (true === $limit_count) {
  510. $limit_count = $GLOBALS['cfg']['MaxTableList'];
  511. }
  512. // prepare and check parameters
  513. if (! is_array($database)) {
  514. $databases = array($database);
  515. } else {
  516. $databases = $database;
  517. }
  518. $tables = array();
  519. if (! $GLOBALS['cfg']['Server']['DisableIS']) {
  520. $sql_where_table = $this->_getTableCondition(
  521. $table, $tbl_is_group, $table_type
  522. );
  523. // for PMA bc:
  524. // `SCHEMA_FIELD_NAME` AS `SHOW_TABLE_STATUS_FIELD_NAME`
  525. //
  526. // on non-Windows servers,
  527. // added BINARY in the WHERE clause to force a case sensitive
  528. // comparison (if we are looking for the db Aa we don't want
  529. // to find the db aa)
  530. $this_databases = array_map(
  531. array($this, 'escapeString'),
  532. $databases
  533. );
  534. $sql = $this->_getSqlForTablesFull($this_databases, $sql_where_table);
  535. // Sort the tables
  536. $sql .= " ORDER BY $sort_by $sort_order";
  537. if ($limit_count) {
  538. $sql .= ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
  539. }
  540. $tables = $this->fetchResult(
  541. $sql, array('TABLE_SCHEMA', 'TABLE_NAME'), null, $link
  542. );
  543. if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
  544. // here, the array's first key is by schema name
  545. foreach ($tables as $one_database_name => $one_database_tables) {
  546. uksort($one_database_tables, 'strnatcasecmp');
  547. if ($sort_order == 'DESC') {
  548. $one_database_tables = array_reverse($one_database_tables);
  549. }
  550. $tables[$one_database_name] = $one_database_tables;
  551. }
  552. } elseif ($sort_by == 'Data_length') {
  553. // Size = Data_length + Index_length
  554. foreach ($tables as $one_database_name => $one_database_tables) {
  555. uasort(
  556. $one_database_tables,
  557. function ($a, $b) {
  558. $aLength = $a['Data_length'] + $a['Index_length'];
  559. $bLength = $b['Data_length'] + $b['Index_length'];
  560. return $aLength == $bLength
  561. ? 0
  562. : ($aLength < $bLength ? -1 : 1);
  563. }
  564. );
  565. if ($sort_order == 'DESC') {
  566. $one_database_tables = array_reverse($one_database_tables);
  567. }
  568. $tables[$one_database_name] = $one_database_tables;
  569. }
  570. }
  571. } // end (get information from table schema)
  572. // If permissions are wrong on even one database directory,
  573. // information_schema does not return any table info for any database
  574. // this is why we fall back to SHOW TABLE STATUS even for MySQL >= 50002
  575. if (empty($tables)) {
  576. foreach ($databases as $each_database) {
  577. if ($table || (true === $tbl_is_group) || ! empty($table_type)) {
  578. $sql = 'SHOW TABLE STATUS FROM '
  579. . Util::backquote($each_database)
  580. . ' WHERE';
  581. $needAnd = false;
  582. if ($table || (true === $tbl_is_group)) {
  583. if (is_array($table)) {
  584. $sql .= ' `Name` IN (\''
  585. . implode(
  586. '\', \'',
  587. array_map(
  588. array($this, 'escapeString'),
  589. $table,
  590. $link
  591. )
  592. ) . '\')';
  593. } else {
  594. $sql .= " `Name` LIKE '"
  595. . Util::escapeMysqlWildcards(
  596. $this->escapeString($table, $link)
  597. )
  598. . "%'";
  599. }
  600. $needAnd = true;
  601. }
  602. if (! empty($table_type)) {
  603. if ($needAnd) {
  604. $sql .= " AND";
  605. }
  606. if ($table_type == 'view') {
  607. $sql .= " `Comment` = 'VIEW'";
  608. } elseif ($table_type == 'table') {
  609. $sql .= " `Comment` != 'VIEW'";
  610. }
  611. }
  612. } else {
  613. $sql = 'SHOW TABLE STATUS FROM '
  614. . Util::backquote($each_database);
  615. }
  616. $each_tables = $this->fetchResult($sql, 'Name', null, $link);
  617. // Sort naturally if the config allows it and we're sorting
  618. // the Name column.
  619. if ($sort_by == 'Name' && $GLOBALS['cfg']['NaturalOrder']) {
  620. uksort($each_tables, 'strnatcasecmp');
  621. if ($sort_order == 'DESC') {
  622. $each_tables = array_reverse($each_tables);
  623. }
  624. } else {
  625. // Prepare to sort by creating array of the selected sort
  626. // value to pass to array_multisort
  627. // Size = Data_length + Index_length
  628. if ($sort_by == 'Data_length') {
  629. foreach ($each_tables as $table_name => $table_data) {
  630. ${$sort_by}[$table_name] = strtolower(
  631. $table_data['Data_length']
  632. + $table_data['Index_length']
  633. );
  634. }
  635. } else {
  636. foreach ($each_tables as $table_name => $table_data) {
  637. ${$sort_by}[$table_name]
  638. = strtolower($table_data[$sort_by]);
  639. }
  640. }
  641. if (! empty($$sort_by)) {
  642. if ($sort_order == 'DESC') {
  643. array_multisort($$sort_by, SORT_DESC, $each_tables);
  644. } else {
  645. array_multisort($$sort_by, SORT_ASC, $each_tables);
  646. }
  647. }
  648. // cleanup the temporary sort array
  649. unset($$sort_by);
  650. }
  651. if ($limit_count) {
  652. $each_tables = array_slice(
  653. $each_tables, $limit_offset, $limit_count
  654. );
  655. }
  656. foreach ($each_tables as $table_name => $each_table) {
  657. if (! isset($each_tables[$table_name]['Type'])
  658. && isset($each_tables[$table_name]['Engine'])
  659. ) {
  660. // pma BC, same parts of PMA still uses 'Type'
  661. $each_tables[$table_name]['Type']
  662. =& $each_tables[$table_name]['Engine'];
  663. } elseif (! isset($each_tables[$table_name]['Engine'])
  664. && isset($each_tables[$table_name]['Type'])
  665. ) {
  666. // old MySQL reports Type, newer MySQL reports Engine
  667. $each_tables[$table_name]['Engine']
  668. =& $each_tables[$table_name]['Type'];
  669. }
  670. // Compatibility with INFORMATION_SCHEMA output
  671. $each_tables[$table_name]['TABLE_SCHEMA']
  672. = $each_database;
  673. $each_tables[$table_name]['TABLE_NAME']
  674. =& $each_tables[$table_name]['Name'];
  675. $each_tables[$table_name]['ENGINE']
  676. =& $each_tables[$table_name]['Engine'];
  677. $each_tables[$table_name]['VERSION']
  678. =& $each_tables[$table_name]['Version'];
  679. $each_tables[$table_name]['ROW_FORMAT']
  680. =& $each_tables[$table_name]['Row_format'];
  681. $each_tables[$table_name]['TABLE_ROWS']
  682. =& $each_tables[$table_name]['Rows'];
  683. $each_tables[$table_name]['AVG_ROW_LENGTH']
  684. =& $each_tables[$table_name]['Avg_row_length'];
  685. $each_tables[$table_name]['DATA_LENGTH']
  686. =& $each_tables[$table_name]['Data_length'];
  687. $each_tables[$table_name]['MAX_DATA_LENGTH']
  688. =& $each_tables[$table_name]['Max_data_length'];
  689. $each_tables[$table_name]['INDEX_LENGTH']
  690. =& $each_tables[$table_name]['Index_length'];
  691. $each_tables[$table_name]['DATA_FREE']
  692. =& $each_tables[$table_name]['Data_free'];
  693. $each_tables[$table_name]['AUTO_INCREMENT']
  694. =& $each_tables[$table_name]['Auto_increment'];
  695. $each_tables[$table_name]['CREATE_TIME']
  696. =& $each_tables[$table_name]['Create_time'];
  697. $each_tables[$table_name]['UPDATE_TIME']
  698. =& $each_tables[$table_name]['Update_time'];
  699. $each_tables[$table_name]['CHECK_TIME']
  700. =& $each_tables[$table_name]['Check_time'];
  701. $each_tables[$table_name]['TABLE_COLLATION']
  702. =& $each_tables[$table_name]['Collation'];
  703. $each_tables[$table_name]['CHECKSUM']
  704. =& $each_tables[$table_name]['Checksum'];
  705. $each_tables[$table_name]['CREATE_OPTIONS']
  706. =& $each_tables[$table_name]['Create_options'];
  707. $each_tables[$table_name]['TABLE_COMMENT']
  708. =& $each_tables[$table_name]['Comment'];
  709. if (strtoupper($each_tables[$table_name]['Comment']) === 'VIEW'
  710. && $each_tables[$table_name]['Engine'] == null
  711. ) {
  712. $each_tables[$table_name]['TABLE_TYPE'] = 'VIEW';
  713. } elseif ($each_database == 'information_schema') {
  714. $each_tables[$table_name]['TABLE_TYPE'] = 'SYSTEM VIEW';
  715. } else {
  716. /**
  717. * @todo difference between 'TEMPORARY' and 'BASE TABLE'
  718. * but how to detect?
  719. */
  720. $each_tables[$table_name]['TABLE_TYPE'] = 'BASE TABLE';
  721. }
  722. }
  723. $tables[$each_database] = $each_tables;
  724. }
  725. }
  726. // cache table data
  727. // so Table does not require to issue SHOW TABLE STATUS again
  728. $this->_cacheTableData($tables, $table);
  729. if (is_array($database)) {
  730. return $tables;
  731. }
  732. if (isset($tables[$database])) {
  733. return $tables[$database];
  734. }
  735. if (isset($tables[mb_strtolower($database)])) {
  736. // on windows with lower_case_table_names = 1
  737. // MySQL returns
  738. // with SHOW DATABASES or information_schema.SCHEMATA: `Test`
  739. // but information_schema.TABLES gives `test`
  740. // see https://github.com/phpmyadmin/phpmyadmin/issues/8402
  741. return $tables[mb_strtolower($database)];
  742. }
  743. return $tables;
  744. }
  745. /**
  746. * Get VIEWs in a particular database
  747. *
  748. * @param string $db Database name to look in
  749. *
  750. * @return array $views Set of VIEWs inside the database
  751. */
  752. public function getVirtualTables($db)
  753. {
  754. $tables_full = $this->getTablesFull($db);
  755. $views = array();
  756. foreach ($tables_full as $table=>$tmp) {
  757. $_table = $this->getTable($db, $table);
  758. if ($_table->isView()) {
  759. $views[] = $table;
  760. }
  761. }
  762. return $views;
  763. }
  764. /**
  765. * returns array with databases containing extended infos about them
  766. *
  767. * @param string $database database
  768. * @param boolean $force_stats retrieve stats also for MySQL < 5
  769. * @param integer $link link type
  770. * @param string $sort_by column to order by
  771. * @param string $sort_order ASC or DESC
  772. * @param integer $limit_offset starting offset for LIMIT
  773. * @param bool|int $limit_count row count for LIMIT or true
  774. * for $GLOBALS['cfg']['MaxDbList']
  775. *
  776. * @todo move into ListDatabase?
  777. *
  778. * @return array $databases
  779. */
  780. public function getDatabasesFull($database = null, $force_stats = false,
  781. $link = DatabaseInterface::CONNECT_USER, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC',
  782. $limit_offset = 0, $limit_count = false
  783. ) {
  784. $sort_order = strtoupper($sort_order);
  785. if (true === $limit_count) {
  786. $limit_count = $GLOBALS['cfg']['MaxDbList'];
  787. }
  788. $apply_limit_and_order_manual = true;
  789. if (! $GLOBALS['cfg']['Server']['DisableIS']) {
  790. /**
  791. * if $GLOBALS['cfg']['NaturalOrder'] is enabled, we cannot use LIMIT
  792. * cause MySQL does not support natural ordering,
  793. * we have to do it afterward
  794. */
  795. $limit = '';
  796. if (! $GLOBALS['cfg']['NaturalOrder']) {
  797. if ($limit_count) {
  798. $limit = ' LIMIT ' . $limit_count . ' OFFSET ' . $limit_offset;
  799. }
  800. $apply_limit_and_order_manual = false;
  801. }
  802. // get table information from information_schema
  803. if (! empty($database)) {
  804. $sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \''
  805. . $this->escapeString($database, $link) . '\'';
  806. } else {
  807. $sql_where_schema = '';
  808. }
  809. $sql = 'SELECT *,
  810. CAST(BIN_NAME AS CHAR CHARACTER SET utf8) AS SCHEMA_NAME
  811. FROM (';
  812. $sql .= 'SELECT
  813. BINARY s.SCHEMA_NAME AS BIN_NAME,
  814. s.DEFAULT_COLLATION_NAME';
  815. if ($force_stats) {
  816. $sql .= ',
  817. COUNT(t.TABLE_SCHEMA) AS SCHEMA_TABLES,
  818. SUM(t.TABLE_ROWS) AS SCHEMA_TABLE_ROWS,
  819. SUM(t.DATA_LENGTH) AS SCHEMA_DATA_LENGTH,
  820. SUM(t.MAX_DATA_LENGTH) AS SCHEMA_MAX_DATA_LENGTH,
  821. SUM(t.INDEX_LENGTH) AS SCHEMA_INDEX_LENGTH,
  822. SUM(t.DATA_LENGTH + t.INDEX_LENGTH)
  823. AS SCHEMA_LENGTH,
  824. SUM(IF(t.ENGINE <> \'InnoDB\', t.DATA_FREE, 0))
  825. AS SCHEMA_DATA_FREE';
  826. }
  827. $sql .= '
  828. FROM `information_schema`.SCHEMATA s ';
  829. if ($force_stats) {
  830. $sql .= '
  831. LEFT JOIN `information_schema`.TABLES t
  832. ON BINARY t.TABLE_SCHEMA = BINARY s.SCHEMA_NAME';
  833. }
  834. $sql .= $sql_where_schema . '
  835. GROUP BY BINARY s.SCHEMA_NAME, s.DEFAULT_COLLATION_NAME
  836. ORDER BY ';
  837. if ($sort_by == 'SCHEMA_NAME'
  838. || $sort_by == 'DEFAULT_COLLATION_NAME'
  839. ) {
  840. $sql .= 'BINARY ';
  841. }
  842. $sql .= Util::backquote($sort_by)
  843. . ' ' . $sort_order
  844. . $limit;
  845. $sql .= ') a';
  846. $databases = $this->fetchResult($sql, 'SCHEMA_NAME', null, $link);
  847. $mysql_error = $this->getError($link);
  848. if (! count($databases) && $GLOBALS['errno']) {
  849. Util::mysqlDie($mysql_error, $sql);
  850. }
  851. // display only databases also in official database list
  852. // f.e. to apply hide_db and only_db
  853. $drops = array_diff(
  854. array_keys($databases), (array) $GLOBALS['dblist']->databases
  855. );
  856. foreach ($drops as $drop) {
  857. unset($databases[$drop]);
  858. }
  859. } else {
  860. $databases = array();
  861. foreach ($GLOBALS['dblist']->databases as $database_name) {
  862. // Compatibility with INFORMATION_SCHEMA output
  863. $databases[$database_name]['SCHEMA_NAME'] = $database_name;
  864. $databases[$database_name]['DEFAULT_COLLATION_NAME']
  865. = $this->getDbCollation($database_name);
  866. if (!$force_stats) {
  867. continue;
  868. }
  869. // get additional info about tables
  870. $databases[$database_name]['SCHEMA_TABLES'] = 0;
  871. $databases[$database_name]['SCHEMA_TABLE_ROWS'] = 0;
  872. $databases[$database_name]['SCHEMA_DATA_LENGTH'] = 0;
  873. $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH'] = 0;
  874. $databases[$database_name]['SCHEMA_INDEX_LENGTH'] = 0;
  875. $databases[$database_name]['SCHEMA_LENGTH'] = 0;
  876. $databases[$database_name]['SCHEMA_DATA_FREE'] = 0;
  877. $res = $this->query(
  878. 'SHOW TABLE STATUS FROM '
  879. . Util::backquote($database_name) . ';'
  880. );
  881. if ($res === false) {
  882. unset($res);
  883. continue;
  884. }
  885. while ($row = $this->fetchAssoc($res)) {
  886. $databases[$database_name]['SCHEMA_TABLES']++;
  887. $databases[$database_name]['SCHEMA_TABLE_ROWS']
  888. += $row['Rows'];
  889. $databases[$database_name]['SCHEMA_DATA_LENGTH']
  890. += $row['Data_length'];
  891. $databases[$database_name]['SCHEMA_MAX_DATA_LENGTH']
  892. += $row['Max_data_length'];
  893. $databases[$database_name]['SCHEMA_INDEX_LENGTH']
  894. += $row['Index_length'];
  895. // for InnoDB, this does not contain the number of
  896. // overhead bytes but the total free space
  897. if ('InnoDB' != $row['Engine']) {
  898. $databases[$database_name]['SCHEMA_DATA_FREE']
  899. += $row['Data_free'];
  900. }
  901. $databases[$database_name]['SCHEMA_LENGTH']
  902. += $row['Data_length'] + $row['Index_length'];
  903. }
  904. $this->freeResult($res);
  905. unset($res);
  906. }
  907. }
  908. /**
  909. * apply limit and order manually now
  910. * (caused by older MySQL < 5 or $GLOBALS['cfg']['NaturalOrder'])
  911. */
  912. if ($apply_limit_and_order_manual) {
  913. $GLOBALS['callback_sort_order'] = $sort_order;
  914. $GLOBALS['callback_sort_by'] = $sort_by;
  915. usort(
  916. $databases,
  917. array(self::class, '_usortComparisonCallback')
  918. );
  919. unset($GLOBALS['callback_sort_order'], $GLOBALS['callback_sort_by']);
  920. /**
  921. * now apply limit
  922. */
  923. if ($limit_count) {
  924. $databases = array_slice($databases, $limit_offset, $limit_count);
  925. }
  926. }
  927. return $databases;
  928. }
  929. /**
  930. * usort comparison callback
  931. *
  932. * @param string $a first argument to sort
  933. * @param string $b second argument to sort
  934. *
  935. * @return integer a value representing whether $a should be before $b in the
  936. * sorted array or not
  937. *
  938. * @access private
  939. */
  940. private static function _usortComparisonCallback($a, $b)
  941. {
  942. if ($GLOBALS['cfg']['NaturalOrder']) {
  943. $sorter = 'strnatcasecmp';
  944. } else {
  945. $sorter = 'strcasecmp';
  946. }
  947. /* No sorting when key is not present */
  948. if (! isset($a[$GLOBALS['callback_sort_by']])
  949. || ! isset($b[$GLOBALS['callback_sort_by']])
  950. ) {
  951. return 0;
  952. }
  953. // produces f.e.:
  954. // return -1 * strnatcasecmp($a["SCHEMA_TABLES"], $b["SCHEMA_TABLES"])
  955. return ($GLOBALS['callback_sort_order'] == 'ASC' ? 1 : -1) * $sorter(
  956. $a[$GLOBALS['callback_sort_by']], $b[$GLOBALS['callback_sort_by']]
  957. );
  958. } // end of the '_usortComparisonCallback()' method
  959. /**
  960. * returns detailed array with all columns for sql
  961. *
  962. * @param string $sql_query target SQL query to get columns
  963. * @param array $view_columns alias for columns
  964. *
  965. * @return array
  966. */
  967. public function getColumnMapFromSql($sql_query, array $view_columns = array())
  968. {
  969. $result = $this->tryQuery($sql_query);
  970. if ($result === false) {
  971. return array();
  972. }
  973. $meta = $this->getFieldsMeta(
  974. $result
  975. );
  976. $nbFields = count($meta);
  977. if ($nbFields <= 0) {
  978. return array();
  979. }
  980. $column_map = array();
  981. $nbColumns = count($view_columns);
  982. for ($i=0; $i < $nbFields; $i++) {
  983. $map = array();
  984. $map['table_name'] = $meta[$i]->table;
  985. $map['refering_column'] = $meta[$i]->name;
  986. if ($nbColumns > 1) {
  987. $map['real_column'] = $view_columns[$i];
  988. }
  989. $column_map[] = $map;
  990. }
  991. return $column_map;
  992. }
  993. /**
  994. * returns detailed array with all columns for given table in database,
  995. * or all tables/databases
  996. *
  997. * @param string $database name of database
  998. * @param string $table name of table to retrieve columns from
  999. * @param string $column name of specific column
  1000. * @param mixed $link mysql link resource
  1001. *
  1002. * @return array
  1003. */
  1004. public function getColumnsFull($database = null, $table = null,
  1005. $column = null, $link = DatabaseInterface::CONNECT_USER
  1006. ) {
  1007. if (! $GLOBALS['cfg']['Server']['DisableIS']) {
  1008. $sql_wheres = array();
  1009. $array_keys = array();
  1010. // get columns information from information_schema
  1011. if (null !== $database) {
  1012. $sql_wheres[] = '`TABLE_SCHEMA` = \''
  1013. . $this->escapeString($database, $link) . '\' ';
  1014. } else {
  1015. $array_keys[] = 'TABLE_SCHEMA';
  1016. }
  1017. if (null !== $table) {
  1018. $sql_wheres[] = '`TABLE_NAME` = \''
  1019. . $this->escapeString($table, $link) . '\' ';
  1020. } else {
  1021. $array_keys[] = 'TABLE_NAME';
  1022. }
  1023. if (null !== $column) {
  1024. $sql_wheres[] = '`COLUMN_NAME` = \''
  1025. . $this->escapeString($column, $link) . '\' ';
  1026. } else {
  1027. $array_keys[] = 'COLUMN_NAME';
  1028. }
  1029. // for PMA bc:
  1030. // `[SCHEMA_FIELD_NAME]` AS `[SHOW_FULL_COLUMNS_FIELD_NAME]`
  1031. $sql = '
  1032. SELECT *,
  1033. `COLUMN_NAME` AS `Field`,
  1034. `COLUMN_TYPE` AS `Type`,
  1035. `COLLATION_NAME` AS `Collation`,
  1036. `IS_NULLABLE` AS `Null`,
  1037. `COLUMN_KEY` AS `Key`,
  1038. `COLUMN_DEFAULT` AS `Default`,
  1039. `EXTRA` AS `Extra`,
  1040. `PRIVILEGES` AS `Privileges`,
  1041. `COLUMN_COMMENT` AS `Comment`
  1042. FROM `information_schema`.`COLUMNS`';
  1043. if (count($sql_wheres)) {
  1044. $sql .= "\n" . ' WHERE ' . implode(' AND ', $sql_wheres);
  1045. }
  1046. return $this->fetchResult($sql, $array_keys, null, $link);
  1047. }
  1048. $columns = array();
  1049. if (null === $database) {
  1050. foreach ($GLOBALS['dblist']->databases as $database) {
  1051. $columns[$database] = $this->getColumnsFull(
  1052. $database, null, null, $link
  1053. );
  1054. }
  1055. return $columns;
  1056. } elseif (null === $table) {
  1057. $tables = $this->getTables($database);
  1058. foreach ($tables as $table) {
  1059. $columns[$table] = $this->getColumnsFull(
  1060. $database, $table, null, $link
  1061. );
  1062. }
  1063. return $columns;
  1064. }
  1065. $sql = 'SHOW FULL COLUMNS FROM '
  1066. . Util::backquote($database) . '.' . Util::backquote($table);
  1067. if (null !== $column) {
  1068. $sql .= " LIKE '" . $this->escapeString($column, $link) . "'";
  1069. }
  1070. $columns = $this->fetchResult($sql, 'Field', null, $link);
  1071. $ordinal_position = 1;
  1072. foreach ($columns as $column_name => $each_column) {
  1073. // Compatibility with INFORMATION_SCHEMA output
  1074. $columns[$column_name]['COLUMN_NAME']
  1075. =& $columns[$column_name]['Field'];
  1076. $columns[$column_name]['COLUMN_TYPE']
  1077. =& $columns[$column_name]['Type'];
  1078. $columns[$column_name]['COLLATION_NAME']
  1079. =& $columns[$column_name]['Collation'];
  1080. $columns[$column_name]['IS_NULLABLE']
  1081. =& $columns[$column_name]['Null'];
  1082. $columns[$column_name]['COLUMN_KEY']
  1083. =& $columns[$column_name]['Key'];
  1084. $columns[$column_name]['COLUMN_DEFAULT']
  1085. =& $columns[$column_name]['Default'];
  1086. $columns[$column_name]['EXTRA']
  1087. =& $columns[$column_name]['Extra'];
  1088. $columns[$column_name]['PRIVILEGES']
  1089. =& $columns[$column_name]['Privileges'];
  1090. $columns[$column_name]['COLUMN_COMMENT']
  1091. =& $columns[$column_name]['Comment'];
  1092. $columns[$column_name]['TABLE_CATALOG'] = null;
  1093. $columns[$column_name]['TABLE_SCHEMA'] = $database;
  1094. $columns[$column_name]['TABLE_NAME'] = $table;
  1095. $columns[$column_name]['ORDINAL_POSITION'] = $ordinal_position;
  1096. $columns[$column_name]['DATA_TYPE']
  1097. = substr(
  1098. $columns[$column_name]['COLUMN_TYPE'],
  1099. 0,
  1100. strpos($columns[$column_name]['COLUMN_TYPE'], '(')
  1101. );
  1102. /**
  1103. * @todo guess CHARACTER_MAXIMUM_LENGTH from COLUMN_TYPE
  1104. */
  1105. $columns[$column_name]['CHARACTER_MAXIMUM_LENGTH'] = null;
  1106. /**
  1107. * @todo guess CHARACTER_OCTET_LENGTH from CHARACTER_MAXIMUM_LENGTH
  1108. */
  1109. $columns[$column_name]['CHARACTER_OCTET_LENGTH'] = null;
  1110. $columns[$column_name]['NUMERIC_PRECISION'] = null;
  1111. $columns[$column_name]['NUMERIC_SCALE'] = null;
  1112. $columns[$column_name]['CHARACTER_SET_NAME']
  1113. = substr(
  1114. $columns[$column_name]['COLLATION_NAME'],
  1115. 0,
  1116. strpos($columns[$column_name]['COLLATION_NAME'], '_')
  1117. );
  1118. $ordinal_position++;
  1119. }
  1120. if (null !== $column) {
  1121. return reset($columns);
  1122. }
  1123. return $columns;
  1124. }
  1125. /**
  1126. * Returns SQL query for fetching columns for a table
  1127. *
  1128. * The 'Key' column is not calculated properly, use $GLOBALS['dbi']->getColumns()
  1129. * to get correct values.
  1130. *
  1131. * @param string $database name of database
  1132. * @param string $table name of table to retrieve columns from
  1133. * @param string $column name of column, null to show all columns
  1134. * @param boolean $full whether to return full info or only column names
  1135. *
  1136. * @see getColumns()
  1137. *
  1138. * @return string
  1139. */
  1140. public function getColumnsSql($database, $table, $column = null, $full = false)
  1141. {
  1142. $sql = 'SHOW ' . ($full ? 'FULL' : '') . ' COLUMNS FROM '
  1143. . Util::backquote($database) . '.' . Util::backquote($table)
  1144. . (($column !== null) ? "LIKE '"
  1145. . $GLOBALS['dbi']->escapeString($column) . "'" : '');
  1146. return $sql;
  1147. }
  1148. /**
  1149. * Returns descriptions of columns in given table (all or given by $column)
  1150. *
  1151. * @param string $database name of database
  1152. * @param string $table name of table to retrieve columns from
  1153. * @param string $column name of column, null to show all columns
  1154. * @param boolean $full whether to return full info or only column names
  1155. * @param integer $link link type
  1156. *
  1157. * @return array array indexed by column names or,
  1158. * if $column is given, flat array description
  1159. */
  1160. public function getColumns($database, $table, $column = null, $full = false,
  1161. $link = DatabaseInterface::CONNECT_USER
  1162. ) {
  1163. $sql = $this->getColumnsSql($database, $table, $column, $full);
  1164. $fields = $this->fetchResult($sql, 'Field', null, $link);
  1165. if (! is_array($fields) || count($fields) == 0) {
  1166. return array();
  1167. }
  1168. // Check if column is a part of multiple-column index and set its 'Key'.
  1169. $indexes = Index::getFromTable($table, $database);
  1170. foreach ($fields as $field => $field_data) {
  1171. if (!empty($field_data['Key'])) {
  1172. continue;
  1173. }
  1174. foreach ($indexes as $index) {
  1175. /** @var Index $index */
  1176. if (!$index->hasColumn($field)) {
  1177. continue;
  1178. }
  1179. $index_columns = $index->getColumns();
  1180. if ($index_columns[$field]->getSeqInIndex() > 1) {
  1181. if ($index->isUnique()) {
  1182. $fields[$field]['Key'] = 'UNI';
  1183. } else {
  1184. $fields[$field]['Key'] = 'MUL';
  1185. }
  1186. }
  1187. }
  1188. }
  1189. return ($column != null) ? array_shift($fields) : $fields;
  1190. }
  1191. /**
  1192. * Returns all column names in given table
  1193. *
  1194. * @param string $database name of database
  1195. * @param string $table name of table to retrieve columns from
  1196. * @param mixed $link mysql link resource
  1197. *
  1198. * @return null|array
  1199. */
  1200. public function getColumnNames($database, $table, $link = DatabaseInterface::CONNECT_USER)
  1201. {
  1202. $sql = $this->getColumnsSql($database, $table);
  1203. // We only need the 'Field' column which contains the table's column names
  1204. $fields = array_keys($this->fetchResult($sql, 'Field', null, $link));
  1205. if (! is_array($fields) || count($fields) == 0) {
  1206. return null;
  1207. }
  1208. return $fields;
  1209. }
  1210. /**
  1211. * Returns SQL for fetching information on table indexes (SHOW INDEXES)
  1212. *
  1213. * @param string $database name of database
  1214. * @param string $table name of the table whose indexes are to be retrieved
  1215. * @param string $where additional conditions for WHERE
  1216. *
  1217. * @return string SQL for getting indexes
  1218. */
  1219. public function getTableIndexesSql($database, $table, $where = null)
  1220. {
  1221. $sql = 'SHOW INDEXES FROM ' . Util::backquote($database) . '.'
  1222. . Util::backquote($table);
  1223. if ($where) {
  1224. $sql .= ' WHERE (' . $where . ')';
  1225. }
  1226. return $sql;
  1227. }
  1228. /**
  1229. * Returns indexes of a table
  1230. *
  1231. * @param string $database name of database
  1232. * @param string $table name of the table whose indexes are to be retrieved
  1233. * @param mixed $link mysql link resource
  1234. *
  1235. * @return array $indexes
  1236. */
  1237. public function getTableIndexes($database, $table, $link = DatabaseInterface::CONNECT_USER)
  1238. {
  1239. $sql = $this->getTableIndexesSql($database, $table);
  1240. $indexes = $this->fetchResult($sql, null, null, $link);
  1241. if (! is_array($indexes) || count($indexes) < 1) {
  1242. return array();
  1243. }
  1244. return $indexes;
  1245. }
  1246. /**
  1247. * returns value of given mysql server variable
  1248. *
  1249. * @param string $var mysql server variable name
  1250. * @param int $type DatabaseInterface::GETVAR_SESSION |
  1251. * DatabaseInterface::GETVAR_GLOBAL
  1252. * @param mixed $link mysql link resource|object
  1253. *
  1254. * @return mixed value for mysql server variable
  1255. */
  1256. public function getVariable(
  1257. $var, $type = self::GETVAR_SESSION, $link = DatabaseInterface::CONNECT_USER
  1258. ) {
  1259. switch ($type) {
  1260. case self::GETVAR_SESSION:
  1261. $modifier = ' SESSION';
  1262. break;
  1263. case self::GETVAR_GLOBAL:
  1264. $modifier = ' GLOBAL';
  1265. break;
  1266. default:
  1267. $modifier = '';
  1268. }
  1269. return $this->fetchValue(
  1270. 'SHOW' . $modifier . ' VARIABLES LIKE \'' . $var . '\';', 0, 1, $link
  1271. );
  1272. }
  1273. /**
  1274. * Sets new value for a variable if it is different from the current value
  1275. *
  1276. * @param string $var variable name
  1277. * @param string $value value to set
  1278. * @param mixed $link mysql link resource|object
  1279. *
  1280. * @return bool whether query was a successful
  1281. */
  1282. public function setVariable($var, $value, $link = DatabaseInterface::CONNECT_USER)
  1283. {
  1284. $current_value = $this->getVariable(
  1285. $var, self::GETVAR_SESSION, $link
  1286. );
  1287. if ($current_value == $value) {
  1288. return true;
  1289. }
  1290. return $this->query("SET " . $var . " = " . $value . ';', $link);
  1291. }
  1292. /**
  1293. * Convert version string to integer.
  1294. *
  1295. * @param string $version MySQL server version
  1296. *
  1297. * @return int
  1298. */
  1299. public static function versionToInt($version)
  1300. {
  1301. $match = explode('.', $version);
  1302. return (int) sprintf('%d%02d%02d', $match[0], $match[1], intval($match[2]));
  1303. }
  1304. /**
  1305. * Function called just after a connection to the MySQL database server has
  1306. * been established. It sets the connection collation, and determines the
  1307. * version of MySQL which is running.
  1308. *
  1309. * @return void
  1310. */
  1311. public function postConnect()
  1312. {
  1313. $version = $this->fetchSingleRow(
  1314. 'SELECT @@version, @@version_comment',
  1315. 'ASSOC',
  1316. DatabaseInterface::CONNECT_USER
  1317. );
  1318. if ($version) {
  1319. $this->_version_str = isset($version['@@version']) ? $version['@@version'] : '';
  1320. $this->_version_int = self::versionToInt($this->_version_str);
  1321. $this->_version_comment = isset($version['@@version_comment']) ? $version['@@version_comment'] : '';
  1322. if (stripos($this->_version_str, 'mariadb') !== false) {
  1323. $this->_is_mariadb = true;
  1324. }
  1325. if (stripos($this->_version_comment, 'percona') !== false) {
  1326. $this->_is_percona = true;
  1327. }
  1328. }
  1329. if ($this->_version_int > 50503) {
  1330. $default_charset = 'utf8mb4';
  1331. $default_collation = 'utf8mb4_general_ci';
  1332. } else {
  1333. $default_charset = 'utf8';
  1334. $default_collation = 'utf8_general_ci';
  1335. }
  1336. $GLOBALS['collation_connection'] = $default_collation;
  1337. $GLOBALS['charset_connection'] = $default_charset;
  1338. $this->query(
  1339. "SET NAMES '$default_charset' COLLATE '$default_collation';",
  1340. DatabaseInterface::CONNECT_USER,
  1341. self::QUERY_STORE
  1342. );
  1343. /* Locale for messages */
  1344. $locale = LanguageManager::getInstance()->getCurrentLanguage()->getMySQLLocale();
  1345. if (! empty($locale)) {
  1346. $this->query(
  1347. "SET lc_messages = '" . $locale . "';",
  1348. DatabaseInterface::CONNECT_USER,
  1349. self::QUERY_STORE
  1350. );
  1351. }
  1352. // Set timezone for the session, if required.
  1353. if ($GLOBALS['cfg']['Server']['SessionTimeZone'] != '') {
  1354. $sql_query_tz = 'SET ' . Util::backquote('time_zone') . ' = '
  1355. . '\''
  1356. . $this->escapeString($GLOBALS['cfg']['Server']['SessionTimeZone'])
  1357. . '\'';
  1358. if (! $this->tryQuery($sql_query_tz)) {
  1359. $error_message_tz = sprintf(
  1360. __(
  1361. 'Unable to use timezone "%1$s" for server %2$d. '
  1362. . 'Please check your configuration setting for '
  1363. . '[em]$cfg[\'Servers\'][%3$d][\'SessionTimeZone\'][/em]. '
  1364. . 'phpMyAdmin is currently using the default time zone '
  1365. . 'of the database server.'
  1366. ),
  1367. $GLOBALS['cfg']['Server']['SessionTimeZone'],
  1368. $GLOBALS['server'],
  1369. $GLOBALS['server']
  1370. );
  1371. trigger_error($error_message_tz, E_USER_WARNING);
  1372. }
  1373. }
  1374. /* Loads closest context to this version. */
  1375. \PhpMyAdmin\SqlParser\Context::loadClosest(
  1376. ($this->_is_mariadb ? 'MariaDb' : 'MySql') . $this->_version_int
  1377. );
  1378. /**
  1379. * the DatabaseList class as a stub for the ListDatabase class
  1380. */
  1381. $GLOBALS['dblist'] = new DatabaseList();
  1382. }
  1383. /**
  1384. * Sets collation connection for user link
  1385. *
  1386. * @param string $collation collation to set
  1387. */
  1388. public function setCollation($collation)
  1389. {
  1390. $charset = $GLOBALS['charset_connection'];
  1391. /* Automatically adjust collation if not supported by server */
  1392. if ($charset == 'utf8' && strncmp('utf8mb4_', $collation, 8) == 0) {
  1393. $collation = 'utf8_' . substr($collation, 8);
  1394. }
  1395. $result = $this->tryQuery(
  1396. "SET collation_connection = '"
  1397. . $this->escapeString($collation, DatabaseInterface::CONNECT_USER)
  1398. . "';",
  1399. DatabaseInterface::CONNECT_USER,
  1400. self::QUERY_STORE
  1401. );
  1402. if ($result === false) {
  1403. trigger_error(
  1404. __('Failed to set configured collation connection!'),
  1405. E_USER_WARNING
  1406. );
  1407. } else {
  1408. $GLOBALS['collation_connection'] = $collation;
  1409. }
  1410. }
  1411. /**
  1412. * This function checks and initialises the phpMyAdmin configuration
  1413. * storage state before it is used into session cache.
  1414. *
  1415. * @return void
  1416. */
  1417. public function initRelationParamsCache()
  1418. {
  1419. $storageDbName = isset($GLOBALS['cfg']['Server']['pmadb']) ? $GLOBALS['cfg']['Server']['pmadb'] : '';
  1420. // Use "phpmyadmin" as a default database name to check to keep the behavior consistent
  1421. $storageDbName = $storageDbName !== null
  1422. && is_string($storageDbName)
  1423. && $storageDbName !== '' ? $storageDbName : 'phpmyadmin';
  1424. // This will make users not having explicitly listed databases
  1425. // have config values filled by the default phpMyAdmin storage table name values
  1426. $this->relation->fixPmaTables($storageDbName, false);
  1427. // This global will be changed if fixPmaTables did find one valid table
  1428. $storageDbName = isset($GLOBALS['cfg']['Server']['pmadb']) ? $GLOBALS['cfg']['Server']['pmadb'] : '';
  1429. // Empty means that until now no pmadb was found eligible
  1430. if (empty($storageDbName)) {
  1431. $this->relation->fixPmaTables($GLOBALS['db'], false);
  1432. }
  1433. }
  1434. /**
  1435. * Function called just after a connection to the MySQL database server has
  1436. * been established. It sets the connection collation, and determines the
  1437. * version of MySQL which is running.
  1438. *
  1439. * @return void
  1440. */
  1441. public function postConnectControl()
  1442. {
  1443. // If Zero configuration mode enabled, check PMA tables in current db.
  1444. if ($GLOBALS['cfg']['ZeroConf'] == true) {
  1445. /**
  1446. * the DatabaseList class as a stub for the ListDatabase class
  1447. */
  1448. $GLOBALS['dblist'] = new DatabaseList();
  1449. $this->initRelationParamsCache();
  1450. }
  1451. }
  1452. /**
  1453. * returns a single value from the given result or query,
  1454. * if the query or the result has more than one row or field
  1455. * the first field of the first row is returned
  1456. *
  1457. * <code>
  1458. * $sql = 'SELECT `name` FROM `user` WHERE `id` = 123';
  1459. * $user_name = $GLOBALS['dbi']->fetchValue($sql);
  1460. * // produces
  1461. * // $user_name = 'John Doe'
  1462. * </code>
  1463. *
  1464. * @param string $query The query to execute
  1465. * @param integer $row_number row to fetch the value from,
  1466. * starting at 0, with 0 being default
  1467. * @param integer|string $field field to fetch the value from,
  1468. * starting at 0, with 0 being default
  1469. * @param integer $link link type
  1470. *
  1471. * @return mixed value of first field in first row from result
  1472. * or false if not found
  1473. */
  1474. public function fetchValue($query, $row_number = 0, $field = 0, $link = DatabaseInterface::CONNECT_USER)
  1475. {
  1476. $value = false;
  1477. $result = $this->tryQuery(
  1478. $query,
  1479. $link,
  1480. self::QUERY_STORE,
  1481. false
  1482. );
  1483. if ($result === false) {
  1484. return false;
  1485. }
  1486. // return false if result is empty or false
  1487. // or requested row is larger than rows in result
  1488. if ($this->numRows($result) < ($row_number + 1)) {
  1489. return $value;
  1490. }
  1491. // if $field is an integer use non associative mysql fetch function
  1492. if (is_int($field)) {
  1493. $fetch_function = 'fetchRow';
  1494. } else {
  1495. $fetch_function = 'fetchAssoc';
  1496. }
  1497. // get requested row
  1498. for ($i = 0; $i <= $row_number; $i++) {
  1499. $row = $this->$fetch_function($result);
  1500. }
  1501. $this->freeResult($result);
  1502. // return requested field
  1503. if (isset($row[$field])) {
  1504. $value = $row[$field];
  1505. }
  1506. return $value;
  1507. }
  1508. /**
  1509. * returns only the first row from the result
  1510. *
  1511. * <code>
  1512. * $sql = 'SELECT * FROM `user` WHERE `id` = 123';
  1513. * $user = $GLOBALS['dbi']->fetchSingleRow($sql);
  1514. * // produces
  1515. * // $user = array('id' => 123, 'name' => 'John Doe')
  1516. * </code>
  1517. *
  1518. * @param string $query The query to execute
  1519. * @param string $type NUM|ASSOC|BOTH returned array should either numeric
  1520. * associative or both
  1521. * @param integer $link link type
  1522. *
  1523. * @return array|boolean first row from result
  1524. * or false if result is empty
  1525. */
  1526. public function fetchSingleRow($query, $type = 'ASSOC', $link = DatabaseInterface::CONNECT_USER)
  1527. {
  1528. $result = $this->tryQuery(
  1529. $query,
  1530. $link,
  1531. self::QUERY_STORE,
  1532. false
  1533. );
  1534. if ($result === false) {
  1535. return false;
  1536. }
  1537. // return false if result is empty or false
  1538. if (! $this->numRows($result)) {
  1539. return false;
  1540. }
  1541. switch ($type) {
  1542. case 'NUM' :
  1543. $fetch_function = 'fetchRow';
  1544. break;
  1545. case 'ASSOC' :
  1546. $fetch_function = 'fetchAssoc';
  1547. break;
  1548. case 'BOTH' :
  1549. default :
  1550. $fetch_function = 'fetchArray';
  1551. break;
  1552. }
  1553. $row = $this->$fetch_function($result);
  1554. $this->freeResult($result);
  1555. return $row;
  1556. }
  1557. /**
  1558. * Returns row or element of a row
  1559. *
  1560. * @param array $row Row to process
  1561. * @param string|null $value Which column to return
  1562. *
  1563. * @return mixed
  1564. */
  1565. private function _fetchValue(array $row, $value)
  1566. {
  1567. if (is_null($value)) {
  1568. return $row;
  1569. }
  1570. return $row[$value];
  1571. }
  1572. /**
  1573. * returns all rows in the resultset in one array
  1574. *
  1575. * <code>
  1576. * $sql = 'SELECT * FROM `user`';
  1577. * $users = $GLOBALS['dbi']->fetchResult($sql);
  1578. * // produces
  1579. * // $users[] = array('id' => 123, 'name' => 'John Doe')
  1580. *
  1581. * $sql = 'SELECT `id`, `name` FROM `user`';
  1582. * $users = $GLOBALS['dbi']->fetchResult($sql, 'id');
  1583. * // produces
  1584. * // $users['123'] = array('id' => 123, 'name' => 'John Doe')
  1585. *
  1586. * $sql = 'SELECT `id`, `name` FROM `user`';
  1587. * $users = $GLOBALS['dbi']->fetchResult($sql, 0);
  1588. * // produces
  1589. * // $users['123'] = array(0 => 123, 1 => 'John Doe')
  1590. *
  1591. * $sql = 'SELECT `id`, `name` FROM `user`';
  1592. * $users = $GLOBALS['dbi']->fetchResult($sql, 'id', 'name');
  1593. * // or
  1594. * $users = $GLOBALS['dbi']->fetchResult($sql, 0, 1);
  1595. * // produces
  1596. * // $users['123'] = 'John Doe'
  1597. *
  1598. * $sql = 'SELECT `name` FROM `user`';
  1599. * $users = $GLOBALS['dbi']->fetchResult($sql);
  1600. * // produces
  1601. * // $users[] = 'John Doe'
  1602. *
  1603. * $sql = 'SELECT `group`, `name` FROM `user`'
  1604. * $users = $GLOBALS['dbi']->fetchResult($sql, array('group', null), 'name');
  1605. * // produces
  1606. * // $users['admin'][] = 'John Doe'
  1607. *
  1608. * $sql = 'SELECT `group`, `name` FROM `user`'
  1609. * $users = $GLOBALS['dbi']->fetchResult($sql, array('group', 'name'), 'id');
  1610. * // produces
  1611. * // $users['admin']['John Doe'] = '123'
  1612. * </code>
  1613. *
  1614. * @param string $query query to execute
  1615. * @param string|integer|array $key field-name or offset
  1616. * used as key for array
  1617. * or array of those
  1618. * @param string|integer $value value-name or offset
  1619. * used as value for array
  1620. * @param integer $link link type
  1621. * @param integer $options query options
  1622. *
  1623. * @return array resultrows or values indexed by $key
  1624. */
  1625. public function fetchResult($query, $key = null, $value = null,
  1626. $link = DatabaseInterface::CONNECT_USER, $options = 0
  1627. ) {
  1628. $resultrows = array();
  1629. $result = $this->tryQuery($query, $link, $options, false);
  1630. // return empty array if result is empty or false
  1631. if ($result === false) {
  1632. return $resultrows;
  1633. }
  1634. $fetch_function = 'fetchAssoc';
  1635. // no nested array if only one field is in result
  1636. if (null === $key && 1 === $this->numFields($result)) {
  1637. $value = 0;
  1638. $fetch_function = 'fetchRow';
  1639. }
  1640. // if $key is an integer use non associative mysql fetch function
  1641. if (is_int($key)) {
  1642. $fetch_function = 'fetchRow';
  1643. }
  1644. if (null === $key) {
  1645. while ($row = $this->$fetch_function($result)) {
  1646. $resultrows[] = $this->_fetchValue($row, $value);
  1647. }
  1648. } else {
  1649. if (is_array($key)) {
  1650. while ($row = $this->$fetch_function($result)) {
  1651. $result_target =& $resultrows;
  1652. foreach ($key as $key_index) {
  1653. if (null === $key_index) {
  1654. $result_target =& $result_target[];
  1655. continue;
  1656. }
  1657. if (! isset($result_target[$row[$key_index]])) {
  1658. $result_target[$row[$key_index]] = array();
  1659. }
  1660. $result_target =& $result_target[$row[$key_index]];
  1661. }
  1662. $result_target = $this->_fetchValue($row, $value);
  1663. }
  1664. } else {
  1665. while ($row = $this->$fetch_function($result)) {
  1666. $resultrows[$row[$key]] = $this->_fetchValue($row, $value);
  1667. }
  1668. }
  1669. }
  1670. $this->freeResult($result);
  1671. return $resultrows;
  1672. }
  1673. /**
  1674. * Get supported SQL compatibility modes
  1675. *
  1676. * @return array supported SQL compatibility modes
  1677. */
  1678. public function getCompatibilities()
  1679. {
  1680. $compats = array('NONE');
  1681. $compats[] = 'ANSI';
  1682. $compats[] = 'DB2';
  1683. $compats[] = 'MAXDB';
  1684. $compats[] = 'MYSQL323';
  1685. $compats[] = 'MYSQL40';
  1686. $compats[] = 'MSSQL';
  1687. $compats[] = 'ORACLE';
  1688. // removed; in MySQL 5.0.33, this produces exports that
  1689. // can't be read by POSTGRESQL (see our bug #1596328)
  1690. //$compats[] = 'POSTGRESQL';
  1691. $compats[] = 'TRADITIONAL';
  1692. return $compats;
  1693. }
  1694. /**
  1695. * returns warnings for last query
  1696. *
  1697. * @param integer $link link type
  1698. *
  1699. * @return array warnings
  1700. */
  1701. public function getWarnings($link = DatabaseInterface::CONNECT_USER)
  1702. {
  1703. return $this->fetchResult('SHOW WARNINGS', null, null, $link);
  1704. }
  1705. /**
  1706. * returns an array of PROCEDURE or FUNCTION names for a db
  1707. *
  1708. * @param string $db db name
  1709. * @param string $which PROCEDURE | FUNCTION
  1710. * @param integer $link link type
  1711. *
  1712. * @return array the procedure names or function names
  1713. */
  1714. public function getProceduresOrFunctions($db, $which, $link = DatabaseInterface::CONNECT_USER)
  1715. {
  1716. $shows = $this->fetchResult(
  1717. 'SHOW ' . $which . ' STATUS;', null, null, $link
  1718. );
  1719. $result = array();
  1720. foreach ($shows as $one_show) {
  1721. if ($one_show['Db'] == $db && $one_show['Type'] == $which) {
  1722. $result[] = $one_show['Name'];
  1723. }
  1724. }
  1725. return($result);
  1726. }
  1727. /**
  1728. * returns the definition of a specific PROCEDURE, FUNCTION, EVENT or VIEW
  1729. *
  1730. * @param string $db db name
  1731. * @param string $which PROCEDURE | FUNCTION | EVENT | VIEW
  1732. * @param string $name the procedure|function|event|view name
  1733. * @param integer $link link type
  1734. *
  1735. * @return string the definition
  1736. */
  1737. public function getDefinition($db, $which, $name, $link = DatabaseInterface::CONNECT_USER)
  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. . Util::backquote($db) . '.'
  1747. . Util::backquote($name);
  1748. return($this->fetchValue($query, 0, $returned_field[$which], $link));
  1749. }
  1750. /**
  1751. * returns details about the PROCEDUREs or FUNCTIONs for a specific database
  1752. * or details about a specific routine
  1753. *
  1754. * @param string $db db name
  1755. * @param string $which PROCEDURE | FUNCTION or null for both
  1756. * @param string $name name of the routine (to fetch a specific routine)
  1757. *
  1758. * @return array information about ROCEDUREs or FUNCTIONs
  1759. */
  1760. public function getRoutines($db, $which = null, $name = '')
  1761. {
  1762. $routines = array();
  1763. if (! $GLOBALS['cfg']['Server']['DisableIS']) {
  1764. $query = "SELECT"
  1765. . " `ROUTINE_SCHEMA` AS `Db`,"
  1766. . " `SPECIFIC_NAME` AS `Name`,"
  1767. . " `ROUTINE_TYPE` AS `Type`,"
  1768. . " `DEFINER` AS `Definer`,"
  1769. . " `LAST_ALTERED` AS `Modified`,"
  1770. . " `CREATED` AS `Created`,"
  1771. . " `SECURITY_TYPE` AS `Security_type`,"
  1772. . " `ROUTINE_COMMENT` AS `Comment`,"
  1773. . " `CHARACTER_SET_CLIENT` AS `character_set_client`,"
  1774. . " `COLLATION_CONNECTION` AS `collation_connection`,"
  1775. . " `DATABASE_COLLATION` AS `Database Collation`,"
  1776. . " `DTD_IDENTIFIER`"
  1777. . " FROM `information_schema`.`ROUTINES`"
  1778. . " WHERE `ROUTINE_SCHEMA` " . Util::getCollateForIS()
  1779. . " = '" . $GLOBALS['dbi']->escapeString($db) . "'";
  1780. if (Core::isValid($which, array('FUNCTION','PROCEDURE'))) {
  1781. $query .= " AND `ROUTINE_TYPE` = '" . $which . "'";
  1782. }
  1783. if (! empty($name)) {
  1784. $query .= " AND `SPECIFIC_NAME`"
  1785. . " = '" . $GLOBALS['dbi']->escapeString($name) . "'";
  1786. }
  1787. $result = $this->fetchResult($query);
  1788. if (!empty($result)) {
  1789. $routines = $result;
  1790. }
  1791. } else {
  1792. if ($which == 'FUNCTION' || $which == null) {
  1793. $query = "SHOW FUNCTION STATUS"
  1794. . " WHERE `Db` = '" . $GLOBALS['dbi']->escapeString($db) . "'";
  1795. if (! empty($name)) {
  1796. $query .= " AND `Name` = '"
  1797. . $GLOBALS['dbi']->escapeString($name) . "'";
  1798. }
  1799. $result = $this->fetchResult($query);
  1800. if (!empty($result)) {
  1801. $routines = array_merge($routines, $result);
  1802. }
  1803. }
  1804. if ($which == 'PROCEDURE' || $which == null) {
  1805. $query = "SHOW PROCEDURE STATUS"
  1806. . " WHERE `Db` = '" . $GLOBALS['dbi']->escapeString($db) . "'";
  1807. if (! empty($name)) {
  1808. $query .= " AND `Name` = '"
  1809. . $GLOBALS['dbi']->escapeString($name) . "'";
  1810. }
  1811. $result = $this->fetchResult($query);
  1812. if (!empty($result)) {
  1813. $routines = array_merge($routines, $result);
  1814. }
  1815. }
  1816. }
  1817. $ret = array();
  1818. foreach ($routines as $routine) {
  1819. $one_result = array();
  1820. $one_result['db'] = $routine['Db'];
  1821. $one_result['name'] = $routine['Name'];
  1822. $one_result['type'] = $routine['Type'];
  1823. $one_result['definer'] = $routine['Definer'];
  1824. $one_result['returns'] = isset($routine['DTD_IDENTIFIER'])
  1825. ? $routine['DTD_IDENTIFIER'] : "";
  1826. $ret[] = $one_result;
  1827. }
  1828. // Sort results by name
  1829. $name = array();
  1830. foreach ($ret as $value) {
  1831. $name[] = $value['name'];
  1832. }
  1833. array_multisort($name, SORT_ASC, $ret);
  1834. return($ret);
  1835. }
  1836. /**
  1837. * returns details about the EVENTs for a specific database
  1838. *
  1839. * @param string $db db name
  1840. * @param string $name event name
  1841. *
  1842. * @return array information about EVENTs
  1843. */
  1844. public function getEvents($db, $name = '')
  1845. {
  1846. if (! $GLOBALS['cfg']['Server']['DisableIS']) {
  1847. $query = "SELECT"
  1848. . " `EVENT_SCHEMA` AS `Db`,"
  1849. . " `EVENT_NAME` AS `Name`,"
  1850. . " `DEFINER` AS `Definer`,"
  1851. . " `TIME_ZONE` AS `Time zone`,"
  1852. . " `EVENT_TYPE` AS `Type`,"
  1853. . " `EXECUTE_AT` AS `Execute at`,"
  1854. . " `INTERVAL_VALUE` AS `Interval value`,"
  1855. . " `INTERVAL_FIELD` AS `Interval field`,"
  1856. . " `STARTS` AS `Starts`,"
  1857. . " `ENDS` AS `Ends`,"
  1858. . " `STATUS` AS `Status`,"
  1859. . " `ORIGINATOR` AS `Originator`,"
  1860. . " `CHARACTER_SET_CLIENT` AS `character_set_client`,"
  1861. . " `COLLATION_CONNECTION` AS `collation_connection`, "
  1862. . "`DATABASE_COLLATION` AS `Database Collation`"
  1863. . " FROM `information_schema`.`EVENTS`"
  1864. . " WHERE `EVENT_SCHEMA` " . Util::getCollateForIS()
  1865. . " = '" . $GLOBALS['dbi']->escapeString($db) . "'";
  1866. if (! empty($name)) {
  1867. $query .= " AND `EVENT_NAME`"
  1868. . " = '" . $GLOBALS['dbi']->escapeString($name) . "'";
  1869. }
  1870. } else {
  1871. $query = "SHOW EVENTS FROM " . Util::backquote($db);
  1872. if (! empty($name)) {
  1873. $query .= " AND `Name` = '"
  1874. . $GLOBALS['dbi']->escapeString($name) . "'";
  1875. }
  1876. }
  1877. $result = array();
  1878. if ($events = $this->fetchResult($query)) {
  1879. foreach ($events as $event) {
  1880. $one_result = array();
  1881. $one_result['name'] = $event['Name'];
  1882. $one_result['type'] = $event['Type'];
  1883. $one_result['status'] = $event['Status'];
  1884. $result[] = $one_result;
  1885. }
  1886. }
  1887. // Sort results by name
  1888. $name = array();
  1889. foreach ($result as $value) {
  1890. $name[] = $value['name'];
  1891. }
  1892. array_multisort($name, SORT_ASC, $result);
  1893. return $result;
  1894. }
  1895. /**
  1896. * returns details about the TRIGGERs for a specific table or database
  1897. *
  1898. * @param string $db db name
  1899. * @param string $table table name
  1900. * @param string $delimiter the delimiter to use (may be empty)
  1901. *
  1902. * @return array information about triggers (may be empty)
  1903. */
  1904. public function getTriggers($db, $table = '', $delimiter = '//')
  1905. {
  1906. $result = array();
  1907. if (! $GLOBALS['cfg']['Server']['DisableIS']) {
  1908. $query = 'SELECT TRIGGER_SCHEMA, TRIGGER_NAME, EVENT_MANIPULATION'
  1909. . ', EVENT_OBJECT_TABLE, ACTION_TIMING, ACTION_STATEMENT'
  1910. . ', EVENT_OBJECT_SCHEMA, EVENT_OBJECT_TABLE, DEFINER'
  1911. . ' FROM information_schema.TRIGGERS'
  1912. . ' WHERE EVENT_OBJECT_SCHEMA ' . Util::getCollateForIS() . '='
  1913. . ' \'' . $GLOBALS['dbi']->escapeString($db) . '\'';
  1914. if (! empty($table)) {
  1915. $query .= " AND EVENT_OBJECT_TABLE " . Util::getCollateForIS()
  1916. . " = '" . $GLOBALS['dbi']->escapeString($table) . "';";
  1917. }
  1918. } else {
  1919. $query = "SHOW TRIGGERS FROM " . Util::backquote($db);
  1920. if (! empty($table)) {
  1921. $query .= " LIKE '" . $GLOBALS['dbi']->escapeString($table) . "';";
  1922. }
  1923. }
  1924. if ($triggers = $this->fetchResult($query)) {
  1925. foreach ($triggers as $trigger) {
  1926. if ($GLOBALS['cfg']['Server']['DisableIS']) {
  1927. $trigger['TRIGGER_NAME'] = $trigger['Trigger'];
  1928. $trigger['ACTION_TIMING'] = $trigger['Timing'];
  1929. $trigger['EVENT_MANIPULATION'] = $trigger['Event'];
  1930. $trigger['EVENT_OBJECT_TABLE'] = $trigger['Table'];
  1931. $trigger['ACTION_STATEMENT'] = $trigger['Statement'];
  1932. $trigger['DEFINER'] = $trigger['Definer'];
  1933. }
  1934. $one_result = array();
  1935. $one_result['name'] = $trigger['TRIGGER_NAME'];
  1936. $one_result['table'] = $trigger['EVENT_OBJECT_TABLE'];
  1937. $one_result['action_timing'] = $trigger['ACTION_TIMING'];
  1938. $one_result['event_manipulation'] = $trigger['EVENT_MANIPULATION'];
  1939. $one_result['definition'] = $trigger['ACTION_STATEMENT'];
  1940. $one_result['definer'] = $trigger['DEFINER'];
  1941. // do not prepend the schema name; this way, importing the
  1942. // definition into another schema will work
  1943. $one_result['full_trigger_name'] = Util::backquote(
  1944. $trigger['TRIGGER_NAME']
  1945. );
  1946. $one_result['drop'] = 'DROP TRIGGER IF EXISTS '
  1947. . $one_result['full_trigger_name'];
  1948. $one_result['create'] = 'CREATE TRIGGER '
  1949. . $one_result['full_trigger_name'] . ' '
  1950. . $trigger['ACTION_TIMING'] . ' '
  1951. . $trigger['EVENT_MANIPULATION']
  1952. . ' ON ' . Util::backquote($trigger['EVENT_OBJECT_TABLE'])
  1953. . "\n" . ' FOR EACH ROW '
  1954. . $trigger['ACTION_STATEMENT'] . "\n" . $delimiter . "\n";
  1955. $result[] = $one_result;
  1956. }
  1957. }
  1958. // Sort results by name
  1959. $name = array();
  1960. foreach ($result as $value) {
  1961. $name[] = $value['name'];
  1962. }
  1963. array_multisort($name, SORT_ASC, $result);
  1964. return($result);
  1965. }
  1966. /**
  1967. * Formats database error message in a friendly way.
  1968. * This is needed because some errors messages cannot
  1969. * be obtained by mysql_error().
  1970. *
  1971. * @param int $error_number Error code
  1972. * @param string $error_message Error message as returned by server
  1973. *
  1974. * @return string HML text with error details
  1975. */
  1976. public static function formatError($error_number, $error_message)
  1977. {
  1978. $error_message = htmlspecialchars($error_message);
  1979. $error = '#' . ((string) $error_number);
  1980. $separator = ' &mdash; ';
  1981. if ($error_number == 2002) {
  1982. $error .= ' - ' . $error_message;
  1983. $error .= $separator;
  1984. $error .= __(
  1985. 'The server is not responding (or the local server\'s socket'
  1986. . ' is not correctly configured).'
  1987. );
  1988. } elseif ($error_number == 2003) {
  1989. $error .= ' - ' . $error_message;
  1990. $error .= $separator . __('The server is not responding.');
  1991. } elseif ($error_number == 1698 ) {
  1992. $error .= ' - ' . $error_message;
  1993. $error .= $separator . '<a href="logout.php' . Url::getCommon() . '" class="disableAjax">';
  1994. $error .= __('Logout and try as another user.') . '</a>';
  1995. } elseif ($error_number == 1005) {
  1996. if (strpos($error_message, 'errno: 13') !== false) {
  1997. $error .= ' - ' . $error_message;
  1998. $error .= $separator
  1999. . __(
  2000. 'Please check privileges of directory containing database.'
  2001. );
  2002. } else {
  2003. /* InnoDB constraints, see
  2004. * https://dev.mysql.com/doc/refman/5.0/en/
  2005. * innodb-foreign-key-constraints.html
  2006. */
  2007. $error .= ' - ' . $error_message .
  2008. ' (<a href="server_engines.php' .
  2009. Url::getCommon(
  2010. array('engine' => 'InnoDB', 'page' => 'Status')
  2011. ) . '">' . __('Details…') . '</a>)';
  2012. }
  2013. } else {
  2014. $error .= ' - ' . $error_message;
  2015. }
  2016. return $error;
  2017. }
  2018. /**
  2019. * gets the current user with host
  2020. *
  2021. * @return string the current user i.e. user@host
  2022. */
  2023. public function getCurrentUser()
  2024. {
  2025. if (Util::cacheExists('mysql_cur_user')) {
  2026. return Util::cacheGet('mysql_cur_user');
  2027. }
  2028. $user = $this->fetchValue('SELECT CURRENT_USER();');
  2029. if ($user !== false) {
  2030. Util::cacheSet('mysql_cur_user', $user);
  2031. return $user;
  2032. }
  2033. return '@';
  2034. }
  2035. /**
  2036. * Checks if current user is superuser
  2037. *
  2038. * @return bool Whether user is a superuser
  2039. */
  2040. public function isSuperuser()
  2041. {
  2042. return self::isUserType('super');
  2043. }
  2044. /**
  2045. * Checks if current user has global create user/grant privilege
  2046. * or is a superuser (i.e. SELECT on mysql.users)
  2047. * while caching the result in session.
  2048. *
  2049. * @param string $type type of user to check for
  2050. * i.e. 'create', 'grant', 'super'
  2051. *
  2052. * @return bool Whether user is a given type of user
  2053. */
  2054. public function isUserType($type)
  2055. {
  2056. if (Util::cacheExists('is_' . $type . 'user')) {
  2057. return Util::cacheGet('is_' . $type . 'user');
  2058. }
  2059. // when connection failed we don't have a $userlink
  2060. if (! isset($this->_links[DatabaseInterface::CONNECT_USER])) {
  2061. return false;
  2062. }
  2063. // checking if user is logged in
  2064. if ($type === 'logged') {
  2065. return true;
  2066. }
  2067. if (! $GLOBALS['cfg']['Server']['DisableIS'] || $type === 'super') {
  2068. // Prepare query for each user type check
  2069. $query = '';
  2070. if ($type === 'super') {
  2071. $query = 'SELECT 1 FROM mysql.user LIMIT 1';
  2072. } elseif ($type === 'create') {
  2073. list($user, $host) = $this->getCurrentUserAndHost();
  2074. $query = "SELECT 1 FROM `INFORMATION_SCHEMA`.`USER_PRIVILEGES` "
  2075. . "WHERE `PRIVILEGE_TYPE` = 'CREATE USER' AND "
  2076. . "'''" . $user . "''@''" . $host . "''' LIKE `GRANTEE` LIMIT 1";
  2077. } elseif ($type === 'grant') {
  2078. list($user, $host) = $this->getCurrentUserAndHost();
  2079. $query = "SELECT 1 FROM ("
  2080. . "SELECT `GRANTEE`, `IS_GRANTABLE` FROM "
  2081. . "`INFORMATION_SCHEMA`.`COLUMN_PRIVILEGES` UNION "
  2082. . "SELECT `GRANTEE`, `IS_GRANTABLE` FROM "
  2083. . "`INFORMATION_SCHEMA`.`TABLE_PRIVILEGES` UNION "
  2084. . "SELECT `GRANTEE`, `IS_GRANTABLE` FROM "
  2085. . "`INFORMATION_SCHEMA`.`SCHEMA_PRIVILEGES` UNION "
  2086. . "SELECT `GRANTEE`, `IS_GRANTABLE` FROM "
  2087. . "`INFORMATION_SCHEMA`.`USER_PRIVILEGES`) t "
  2088. . "WHERE `IS_GRANTABLE` = 'YES' AND "
  2089. . "'''" . $user . "''@''" . $host . "''' LIKE `GRANTEE` LIMIT 1";
  2090. }
  2091. $is = false;
  2092. $result = $this->tryQuery(
  2093. $query,
  2094. self::CONNECT_USER,
  2095. self::QUERY_STORE
  2096. );
  2097. if ($result) {
  2098. $is = (bool) $this->numRows($result);
  2099. }
  2100. $this->freeResult($result);
  2101. } else {
  2102. $is = false;
  2103. $grants = $this->fetchResult(
  2104. "SHOW GRANTS FOR CURRENT_USER();",
  2105. null,
  2106. null,
  2107. self::CONNECT_USER,
  2108. self::QUERY_STORE
  2109. );
  2110. if ($grants) {
  2111. foreach ($grants as $grant) {
  2112. if ($type === 'create') {
  2113. if (strpos($grant, "ALL PRIVILEGES ON *.*") !== false
  2114. || strpos($grant, "CREATE USER") !== false
  2115. ) {
  2116. $is = true;
  2117. break;
  2118. }
  2119. } elseif ($type === 'grant') {
  2120. if (strpos($grant, "WITH GRANT OPTION") !== false) {
  2121. $is = true;
  2122. break;
  2123. }
  2124. }
  2125. }
  2126. }
  2127. }
  2128. Util::cacheSet('is_' . $type . 'user', $is);
  2129. return $is;
  2130. }
  2131. /**
  2132. * Get the current user and host
  2133. *
  2134. * @return array array of username and hostname
  2135. */
  2136. public function getCurrentUserAndHost()
  2137. {
  2138. if (count($this->_current_user) == 0) {
  2139. $user = $this->getCurrentUser();
  2140. $this->_current_user = explode("@", $user);
  2141. }
  2142. return $this->_current_user;
  2143. }
  2144. /**
  2145. * Returns value for lower_case_table_names variable
  2146. *
  2147. * @return string
  2148. */
  2149. public function getLowerCaseNames()
  2150. {
  2151. if (is_null($this->_lower_case_table_names)) {
  2152. $this->_lower_case_table_names = $this->fetchValue(
  2153. "SELECT @@lower_case_table_names"
  2154. );
  2155. }
  2156. return $this->_lower_case_table_names;
  2157. }
  2158. /**
  2159. * Get the list of system schemas
  2160. *
  2161. * @return array list of system schemas
  2162. */
  2163. public function getSystemSchemas()
  2164. {
  2165. $schemas = array(
  2166. 'information_schema', 'performance_schema', 'mysql', 'sys'
  2167. );
  2168. $systemSchemas = array();
  2169. foreach ($schemas as $schema) {
  2170. if ($this->isSystemSchema($schema, true)) {
  2171. $systemSchemas[] = $schema;
  2172. }
  2173. }
  2174. return $systemSchemas;
  2175. }
  2176. /**
  2177. * Checks whether given schema is a system schema
  2178. *
  2179. * @param string $schema_name Name of schema (database) to test
  2180. * @param bool $testForMysqlSchema Whether 'mysql' schema should
  2181. * be treated the same as IS and DD
  2182. *
  2183. * @return bool
  2184. */
  2185. public function isSystemSchema($schema_name, $testForMysqlSchema = false)
  2186. {
  2187. $schema_name = strtolower($schema_name);
  2188. return $schema_name == 'information_schema'
  2189. || $schema_name == 'performance_schema'
  2190. || ($schema_name == 'mysql' && $testForMysqlSchema)
  2191. || $schema_name == 'sys';
  2192. }
  2193. /**
  2194. * Return connection parameters for the database server
  2195. *
  2196. * @param integer $mode Connection mode on of CONNECT_USER, CONNECT_CONTROL
  2197. * or CONNECT_AUXILIARY.
  2198. * @param array|null $server Server information like host/port/socket/persistent
  2199. *
  2200. * @return array user, host and server settings array
  2201. */
  2202. public function getConnectionParams($mode, $server = null)
  2203. {
  2204. global $cfg;
  2205. $user = null;
  2206. $password = null;
  2207. if ($mode == DatabaseInterface::CONNECT_USER) {
  2208. $user = $cfg['Server']['user'];
  2209. $password = $cfg['Server']['password'];
  2210. $server = $cfg['Server'];
  2211. } elseif ($mode == DatabaseInterface::CONNECT_CONTROL) {
  2212. $user = $cfg['Server']['controluser'];
  2213. $password = $cfg['Server']['controlpass'];
  2214. $server = array();
  2215. $server['hide_connection_errors'] = $cfg['Server']['hide_connection_errors'];
  2216. if (! empty($cfg['Server']['controlhost'])) {
  2217. $server['host'] = $cfg['Server']['controlhost'];
  2218. } else {
  2219. $server['host'] = $cfg['Server']['host'];
  2220. }
  2221. // Share the settings if the host is same
  2222. if ($server['host'] == $cfg['Server']['host']) {
  2223. $shared = array(
  2224. 'port', 'socket', 'compress',
  2225. 'ssl', 'ssl_key', 'ssl_cert', 'ssl_ca',
  2226. 'ssl_ca_path', 'ssl_ciphers', 'ssl_verify',
  2227. );
  2228. foreach ($shared as $item) {
  2229. if (isset($cfg['Server'][$item])) {
  2230. $server[$item] = $cfg['Server'][$item];
  2231. }
  2232. }
  2233. }
  2234. // Set configured port
  2235. if (! empty($cfg['Server']['controlport'])) {
  2236. $server['port'] = $cfg['Server']['controlport'];
  2237. }
  2238. // Set any configuration with control_ prefix
  2239. foreach ($cfg['Server'] as $key => $val) {
  2240. if (substr($key, 0, 8) === 'control_') {
  2241. $server[substr($key, 8)] = $val;
  2242. }
  2243. }
  2244. } else {
  2245. if (is_null($server)) {
  2246. return array(null, null, null);
  2247. }
  2248. if (isset($server['user'])) {
  2249. $user = $server['user'];
  2250. }
  2251. if (isset($server['password'])) {
  2252. $password = $server['password'];
  2253. }
  2254. }
  2255. // Perform sanity checks on some variables
  2256. if (empty($server['port'])) {
  2257. $server['port'] = 0;
  2258. } else {
  2259. $server['port'] = intval($server['port']);
  2260. }
  2261. if (empty($server['socket'])) {
  2262. $server['socket'] = null;
  2263. }
  2264. if (empty($server['host'])) {
  2265. $server['host'] = 'localhost';
  2266. }
  2267. if (!isset($server['ssl'])) {
  2268. $server['ssl'] = false;
  2269. }
  2270. if (!isset($server['compress'])) {
  2271. $server['compress'] = false;
  2272. }
  2273. if (! isset($server['hide_connection_errors'])) {
  2274. $server['hide_connection_errors'] = false;
  2275. }
  2276. return array($user, $password, $server);
  2277. }
  2278. /**
  2279. * connects to the database server
  2280. *
  2281. * @param integer $mode Connection mode on of CONNECT_USER, CONNECT_CONTROL
  2282. * or CONNECT_AUXILIARY.
  2283. * @param array|null $server Server information like host/port/socket/persistent
  2284. * @param integer $target How to store connection link, defaults to $mode
  2285. *
  2286. * @return mixed false on error or a connection object on success
  2287. */
  2288. public function connect($mode, $server = null, $target = null)
  2289. {
  2290. list($user, $password, $server) = $this->getConnectionParams($mode, $server);
  2291. if (is_null($target)) {
  2292. $target = $mode;
  2293. }
  2294. if (is_null($user) || is_null($password)) {
  2295. trigger_error(
  2296. __('Missing connection parameters!'),
  2297. E_USER_WARNING
  2298. );
  2299. return false;
  2300. }
  2301. // Do not show location and backtrace for connection errors
  2302. $GLOBALS['error_handler']->setHideLocation(true);
  2303. $result = $this->_extension->connect(
  2304. $user, $password, $server
  2305. );
  2306. $GLOBALS['error_handler']->setHideLocation(false);
  2307. if ($result) {
  2308. $this->_links[$target] = $result;
  2309. /* Run post connect for user connections */
  2310. if ($target == DatabaseInterface::CONNECT_USER) {
  2311. $this->postConnect();
  2312. }
  2313. return $result;
  2314. }
  2315. if ($mode == DatabaseInterface::CONNECT_CONTROL) {
  2316. trigger_error(
  2317. __(
  2318. 'Connection for controluser as defined in your '
  2319. . 'configuration failed.'
  2320. ),
  2321. E_USER_WARNING
  2322. );
  2323. return false;
  2324. } elseif ($mode == DatabaseInterface::CONNECT_AUXILIARY) {
  2325. // Do not go back to main login if connection failed
  2326. // (currently used only in unit testing)
  2327. return false;
  2328. }
  2329. return $result;
  2330. }
  2331. /**
  2332. * selects given database
  2333. *
  2334. * @param string $dbname database name to select
  2335. * @param integer $link link type
  2336. *
  2337. * @return boolean
  2338. */
  2339. public function selectDb($dbname, $link = DatabaseInterface::CONNECT_USER)
  2340. {
  2341. if (! isset($this->_links[$link])) {
  2342. return false;
  2343. }
  2344. return $this->_extension->selectDb($dbname, $this->_links[$link]);
  2345. }
  2346. /**
  2347. * returns array of rows with associative and numeric keys from $result
  2348. *
  2349. * @param object $result result set identifier
  2350. *
  2351. * @return array
  2352. */
  2353. public function fetchArray($result)
  2354. {
  2355. return $this->_extension->fetchArray($result);
  2356. }
  2357. /**
  2358. * returns array of rows with associative keys from $result
  2359. *
  2360. * @param object $result result set identifier
  2361. *
  2362. * @return array
  2363. */
  2364. public function fetchAssoc($result)
  2365. {
  2366. return $this->_extension->fetchAssoc($result);
  2367. }
  2368. /**
  2369. * returns array of rows with numeric keys from $result
  2370. *
  2371. * @param object $result result set identifier
  2372. *
  2373. * @return array
  2374. */
  2375. public function fetchRow($result)
  2376. {
  2377. return $this->_extension->fetchRow($result);
  2378. }
  2379. /**
  2380. * Adjusts the result pointer to an arbitrary row in the result
  2381. *
  2382. * @param object $result database result
  2383. * @param integer $offset offset to seek
  2384. *
  2385. * @return bool true on success, false on failure
  2386. */
  2387. public function dataSeek($result, $offset)
  2388. {
  2389. return $this->_extension->dataSeek($result, $offset);
  2390. }
  2391. /**
  2392. * Frees memory associated with the result
  2393. *
  2394. * @param object $result database result
  2395. *
  2396. * @return void
  2397. */
  2398. public function freeResult($result)
  2399. {
  2400. $this->_extension->freeResult($result);
  2401. }
  2402. /**
  2403. * Check if there are any more query results from a multi query
  2404. *
  2405. * @param integer $link link type
  2406. *
  2407. * @return bool true or false
  2408. */
  2409. public function moreResults($link = DatabaseInterface::CONNECT_USER)
  2410. {
  2411. if (! isset($this->_links[$link])) {
  2412. return false;
  2413. }
  2414. return $this->_extension->moreResults($this->_links[$link]);
  2415. }
  2416. /**
  2417. * Prepare next result from multi_query
  2418. *
  2419. * @param integer $link link type
  2420. *
  2421. * @return bool true or false
  2422. */
  2423. public function nextResult($link = DatabaseInterface::CONNECT_USER)
  2424. {
  2425. if (! isset($this->_links[$link])) {
  2426. return false;
  2427. }
  2428. return $this->_extension->nextResult($this->_links[$link]);
  2429. }
  2430. /**
  2431. * Store the result returned from multi query
  2432. *
  2433. * @param integer $link link type
  2434. *
  2435. * @return mixed false when empty results / result set when not empty
  2436. */
  2437. public function storeResult($link = DatabaseInterface::CONNECT_USER)
  2438. {
  2439. if (! isset($this->_links[$link])) {
  2440. return false;
  2441. }
  2442. return $this->_extension->storeResult($this->_links[$link]);
  2443. }
  2444. /**
  2445. * Returns a string representing the type of connection used
  2446. *
  2447. * @param integer $link link type
  2448. *
  2449. * @return string type of connection used
  2450. */
  2451. public function getHostInfo($link = DatabaseInterface::CONNECT_USER)
  2452. {
  2453. if (! isset($this->_links[$link])) {
  2454. return false;
  2455. }
  2456. return $this->_extension->getHostInfo($this->_links[$link]);
  2457. }
  2458. /**
  2459. * Returns the version of the MySQL protocol used
  2460. *
  2461. * @param integer $link link type
  2462. *
  2463. * @return integer version of the MySQL protocol used
  2464. */
  2465. public function getProtoInfo($link = DatabaseInterface::CONNECT_USER)
  2466. {
  2467. if (! isset($this->_links[$link])) {
  2468. return false;
  2469. }
  2470. return $this->_extension->getProtoInfo($this->_links[$link]);
  2471. }
  2472. /**
  2473. * returns a string that represents the client library version
  2474. *
  2475. * @return string MySQL client library version
  2476. */
  2477. public function getClientInfo()
  2478. {
  2479. return $this->_extension->getClientInfo();
  2480. }
  2481. /**
  2482. * returns last error message or false if no errors occurred
  2483. *
  2484. * @param integer $link link type
  2485. *
  2486. * @return string|bool $error or false
  2487. */
  2488. public function getError($link = DatabaseInterface::CONNECT_USER)
  2489. {
  2490. if (! isset($this->_links[$link])) {
  2491. return false;
  2492. }
  2493. return $this->_extension->getError($this->_links[$link]);
  2494. }
  2495. /**
  2496. * returns the number of rows returned by last query
  2497. *
  2498. * @param object $result result set identifier
  2499. *
  2500. * @return string|int
  2501. */
  2502. public function numRows($result)
  2503. {
  2504. return $this->_extension->numRows($result);
  2505. }
  2506. /**
  2507. * returns last inserted auto_increment id for given $link
  2508. * or $GLOBALS['userlink']
  2509. *
  2510. * @param integer $link link type
  2511. *
  2512. * @return int|boolean
  2513. */
  2514. public function insertId($link = DatabaseInterface::CONNECT_USER)
  2515. {
  2516. // If the primary key is BIGINT we get an incorrect result
  2517. // (sometimes negative, sometimes positive)
  2518. // and in the present function we don't know if the PK is BIGINT
  2519. // so better play safe and use LAST_INSERT_ID()
  2520. //
  2521. // When no controluser is defined, using mysqli_insert_id($link)
  2522. // does not always return the last insert id due to a mixup with
  2523. // the tracking mechanism, but this works:
  2524. return $this->fetchValue('SELECT LAST_INSERT_ID();', 0, 0, $link);
  2525. }
  2526. /**
  2527. * returns the number of rows affected by last query
  2528. *
  2529. * @param integer $link link type
  2530. * @param bool $get_from_cache whether to retrieve from cache
  2531. *
  2532. * @return int|boolean
  2533. */
  2534. public function affectedRows($link = DatabaseInterface::CONNECT_USER, $get_from_cache = true)
  2535. {
  2536. if (! isset($this->_links[$link])) {
  2537. return false;
  2538. }
  2539. if ($get_from_cache) {
  2540. return $GLOBALS['cached_affected_rows'];
  2541. }
  2542. return $this->_extension->affectedRows($this->_links[$link]);
  2543. }
  2544. /**
  2545. * returns metainfo for fields in $result
  2546. *
  2547. * @param object $result result set identifier
  2548. *
  2549. * @return array meta info for fields in $result
  2550. */
  2551. public function getFieldsMeta($result)
  2552. {
  2553. $result = $this->_extension->getFieldsMeta($result);
  2554. if ($this->getLowerCaseNames() === '2') {
  2555. /**
  2556. * Fixup orgtable for lower_case_table_names = 2
  2557. *
  2558. * In this setup MySQL server reports table name lower case
  2559. * but we still need to operate on original case to properly
  2560. * match existing strings
  2561. */
  2562. foreach ($result as $value) {
  2563. if (strlen($value->orgtable) !== 0 &&
  2564. mb_strtolower($value->orgtable) === mb_strtolower($value->table)) {
  2565. $value->orgtable = $value->table;
  2566. }
  2567. }
  2568. }
  2569. return $result;
  2570. }
  2571. /**
  2572. * return number of fields in given $result
  2573. *
  2574. * @param object $result result set identifier
  2575. *
  2576. * @return int field count
  2577. */
  2578. public function numFields($result)
  2579. {
  2580. return $this->_extension->numFields($result);
  2581. }
  2582. /**
  2583. * returns the length of the given field $i in $result
  2584. *
  2585. * @param object $result result set identifier
  2586. * @param int $i field
  2587. *
  2588. * @return int length of field
  2589. */
  2590. public function fieldLen($result, $i)
  2591. {
  2592. return $this->_extension->fieldLen($result, $i);
  2593. }
  2594. /**
  2595. * returns name of $i. field in $result
  2596. *
  2597. * @param object $result result set identifier
  2598. * @param int $i field
  2599. *
  2600. * @return string name of $i. field in $result
  2601. */
  2602. public function fieldName($result, $i)
  2603. {
  2604. return $this->_extension->fieldName($result, $i);
  2605. }
  2606. /**
  2607. * returns concatenated string of human readable field flags
  2608. *
  2609. * @param object $result result set identifier
  2610. * @param int $i field
  2611. *
  2612. * @return string field flags
  2613. */
  2614. public function fieldFlags($result, $i)
  2615. {
  2616. return $this->_extension->fieldFlags($result, $i);
  2617. }
  2618. /**
  2619. * returns properly escaped string for use in MySQL queries
  2620. *
  2621. * @param string $str string to be escaped
  2622. * @param mixed $link optional database link to use
  2623. *
  2624. * @return string a MySQL escaped string
  2625. */
  2626. public function escapeString($str, $link = DatabaseInterface::CONNECT_USER)
  2627. {
  2628. if ($this->_extension === null || !isset($this->_links[$link])) {
  2629. return $str;
  2630. }
  2631. return $this->_extension->escapeString($this->_links[$link], $str);
  2632. }
  2633. /**
  2634. * Checks if this database server is running on Amazon RDS.
  2635. *
  2636. * @return boolean
  2637. */
  2638. public function isAmazonRds()
  2639. {
  2640. if (Util::cacheExists('is_amazon_rds')) {
  2641. return Util::cacheGet('is_amazon_rds');
  2642. }
  2643. $sql = 'SELECT @@basedir';
  2644. $result = $this->fetchValue($sql);
  2645. $rds = (substr($result, 0, 10) == '/rdsdbbin/');
  2646. Util::cacheSet('is_amazon_rds', $rds);
  2647. return $rds;
  2648. }
  2649. /**
  2650. * Gets SQL for killing a process.
  2651. *
  2652. * @param int $process Process ID
  2653. *
  2654. * @return string
  2655. */
  2656. public function getKillQuery($process)
  2657. {
  2658. if ($this->isAmazonRds()) {
  2659. return 'CALL mysql.rds_kill(' . $process . ');';
  2660. }
  2661. return 'KILL ' . $process . ';';
  2662. }
  2663. /**
  2664. * Get the phpmyadmin database manager
  2665. *
  2666. * @return SystemDatabase
  2667. */
  2668. public function getSystemDatabase()
  2669. {
  2670. return new SystemDatabase($this);
  2671. }
  2672. /**
  2673. * Get a table with database name and table name
  2674. *
  2675. * @param string $db_name DB name
  2676. * @param string $table_name Table name
  2677. *
  2678. * @return Table
  2679. */
  2680. public function getTable($db_name, $table_name)
  2681. {
  2682. return new Table($table_name, $db_name, $this);
  2683. }
  2684. /**
  2685. * returns collation of given db
  2686. *
  2687. * @param string $db name of db
  2688. *
  2689. * @return string collation of $db
  2690. */
  2691. public function getDbCollation($db)
  2692. {
  2693. if ($this->isSystemSchema($db)) {
  2694. // We don't have to check the collation of the virtual
  2695. // information_schema database: We know it!
  2696. return 'utf8_general_ci';
  2697. }
  2698. if (! $GLOBALS['cfg']['Server']['DisableIS']) {
  2699. // this is slow with thousands of databases
  2700. $sql = 'SELECT DEFAULT_COLLATION_NAME FROM information_schema.SCHEMATA'
  2701. . ' WHERE SCHEMA_NAME = \'' . $this->escapeString($db)
  2702. . '\' LIMIT 1';
  2703. return $this->fetchValue($sql);
  2704. }
  2705. $this->selectDb($db);
  2706. $return = $this->fetchValue('SELECT @@collation_database');
  2707. if ($db !== $GLOBALS['db']) {
  2708. $this->selectDb($GLOBALS['db']);
  2709. }
  2710. return $return;
  2711. }
  2712. /**
  2713. * returns default server collation from show variables
  2714. *
  2715. * @return string $server_collation
  2716. */
  2717. function getServerCollation()
  2718. {
  2719. return $this->fetchValue('SELECT @@collation_server');
  2720. }
  2721. /**
  2722. * Server version as number
  2723. *
  2724. * @return integer
  2725. */
  2726. public function getVersion()
  2727. {
  2728. return $this->_version_int;
  2729. }
  2730. /**
  2731. * Server version
  2732. *
  2733. * @return string
  2734. */
  2735. public function getVersionString()
  2736. {
  2737. return $this->_version_str;
  2738. }
  2739. /**
  2740. * Server version comment
  2741. *
  2742. * @return string
  2743. */
  2744. public function getVersionComment()
  2745. {
  2746. return $this->_version_comment;
  2747. }
  2748. /**
  2749. * Whether connection is MariaDB
  2750. *
  2751. * @return boolean
  2752. */
  2753. public function isMariaDB()
  2754. {
  2755. return $this->_is_mariadb;
  2756. }
  2757. /**
  2758. * Whether connection is Percona
  2759. *
  2760. * @return boolean
  2761. */
  2762. public function isPercona()
  2763. {
  2764. return $this->_is_percona;
  2765. }
  2766. /**
  2767. * Load correct database driver
  2768. *
  2769. * @return void
  2770. */
  2771. public static function load()
  2772. {
  2773. if (defined('TESTSUITE')) {
  2774. /**
  2775. * For testsuite we use dummy driver which can fake some queries.
  2776. */
  2777. $extension = new DbiDummy();
  2778. } else {
  2779. /**
  2780. * First check for the mysqli extension, as it's the one recommended
  2781. * for the MySQL server's version that we support
  2782. * (if PHP 7+, it's the only one supported)
  2783. */
  2784. $extension = 'mysqli';
  2785. if (! self::checkDbExtension($extension)) {
  2786. $docurl = Util::getDocuLink('faq', 'faqmysql');
  2787. $doclink = sprintf(
  2788. __('See %sour documentation%s for more information.'),
  2789. '[a@' . $docurl . '@documentation]',
  2790. '[/a]'
  2791. );
  2792. if (PHP_VERSION_ID < 70000) {
  2793. $extension = 'mysql';
  2794. if (! self::checkDbExtension($extension)) {
  2795. // warn about both extensions missing and exit
  2796. Core::warnMissingExtension(
  2797. 'mysqli',
  2798. true,
  2799. $doclink
  2800. );
  2801. } elseif (empty($_SESSION['mysqlwarning'])) {
  2802. trigger_error(
  2803. __(
  2804. 'You are using the mysql extension which is deprecated in '
  2805. . 'phpMyAdmin. Please consider installing the mysqli '
  2806. . 'extension.'
  2807. ) . ' ' . $doclink,
  2808. E_USER_WARNING
  2809. );
  2810. // tell the user just once per session
  2811. $_SESSION['mysqlwarning'] = true;
  2812. }
  2813. } else {
  2814. // mysql extension is not part of PHP 7+, so warn and exit
  2815. Core::warnMissingExtension(
  2816. 'mysqli',
  2817. true,
  2818. $doclink
  2819. );
  2820. }
  2821. }
  2822. /**
  2823. * Including The DBI Plugin
  2824. */
  2825. switch($extension) {
  2826. case 'mysql' :
  2827. $extension = new DbiMysql();
  2828. break;
  2829. case 'mysqli' :
  2830. $extension = new DbiMysqli();
  2831. break;
  2832. }
  2833. }
  2834. $GLOBALS['dbi'] = new DatabaseInterface($extension);
  2835. $container = Container::getDefaultContainer();
  2836. $container->set('PMA_DatabaseInterface', $GLOBALS['dbi']);
  2837. $container->alias('dbi', 'PMA_DatabaseInterface');
  2838. }
  2839. }