DatabaseInterface.php 102 KB

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