Relation.php 78 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * Set of functions used with the relation and PDF feature
  5. *
  6. * @package PhpMyAdmin
  7. */
  8. namespace PhpMyAdmin;
  9. use PhpMyAdmin\Core;
  10. use PhpMyAdmin\DatabaseInterface;
  11. use PhpMyAdmin\Message;
  12. use PhpMyAdmin\RecentFavoriteTable;
  13. use PhpMyAdmin\SqlParser\Parser;
  14. use PhpMyAdmin\SqlParser\Utils\Table as TableUtils;
  15. use PhpMyAdmin\Table;
  16. use PhpMyAdmin\Template;
  17. use PhpMyAdmin\Url;
  18. use PhpMyAdmin\Util;
  19. /**
  20. * Set of functions used with the relation and PDF feature
  21. *
  22. * @package PhpMyAdmin
  23. */
  24. class Relation
  25. {
  26. /**
  27. * Executes a query as controluser if possible, otherwise as normal user
  28. *
  29. * @param string $sql the query to execute
  30. * @param boolean $show_error whether to display SQL error messages or not
  31. * @param int $options query options
  32. *
  33. * @return resource|boolean the result set, or false if no result set
  34. *
  35. * @access public
  36. *
  37. */
  38. public function queryAsControlUser($sql, $show_error = true, $options = 0)
  39. {
  40. // Avoid caching of the number of rows affected; for example, this function
  41. // is called for tracking purposes but we want to display the correct number
  42. // of rows affected by the original query, not by the query generated for
  43. // tracking.
  44. $cache_affected_rows = false;
  45. if ($show_error) {
  46. $result = $GLOBALS['dbi']->query(
  47. $sql,
  48. DatabaseInterface::CONNECT_CONTROL,
  49. $options,
  50. $cache_affected_rows
  51. );
  52. } else {
  53. $result = @$GLOBALS['dbi']->tryQuery(
  54. $sql,
  55. DatabaseInterface::CONNECT_CONTROL,
  56. $options,
  57. $cache_affected_rows
  58. );
  59. } // end if... else...
  60. if ($result) {
  61. return $result;
  62. }
  63. return false;
  64. }
  65. /**
  66. * Returns current relation parameters
  67. *
  68. * @return array $cfgRelation
  69. */
  70. public function getRelationsParam()
  71. {
  72. if (empty($_SESSION['relation'][$GLOBALS['server']])
  73. || (empty($_SESSION['relation'][$GLOBALS['server']]['PMA_VERSION']))
  74. || $_SESSION['relation'][$GLOBALS['server']]['PMA_VERSION'] != PMA_VERSION
  75. ) {
  76. $_SESSION['relation'][$GLOBALS['server']] = $this->checkRelationsParam();
  77. }
  78. // just for BC but needs to be before getRelationsParamDiagnostic()
  79. // which uses it
  80. $GLOBALS['cfgRelation'] = $_SESSION['relation'][$GLOBALS['server']];
  81. return $_SESSION['relation'][$GLOBALS['server']];
  82. }
  83. /**
  84. * prints out diagnostic info for pma relation feature
  85. *
  86. * @param array $cfgRelation Relation configuration
  87. *
  88. * @return string
  89. */
  90. public function getRelationsParamDiagnostic(array $cfgRelation)
  91. {
  92. $retval = '<br>';
  93. $messages = array();
  94. $messages['error'] = '<span style="color:red"><strong>'
  95. . __('not OK')
  96. . '</strong></span>';
  97. $messages['ok'] = '<span style="color:green"><strong>'
  98. . _pgettext('Correctly working', 'OK')
  99. . '</strong></span>';
  100. $messages['enabled'] = '<span style="color:green">' . __('Enabled') . '</span>';
  101. $messages['disabled'] = '<span style="color:red">' . __('Disabled') . '</span>';
  102. if (strlen($cfgRelation['db']) == 0) {
  103. $retval .= __('Configuration of pmadb…') . ' '
  104. . $messages['error']
  105. . Util::showDocu('setup', 'linked-tables')
  106. . '<br />' . "\n"
  107. . __('General relation features')
  108. . ' <font color="green">' . __('Disabled')
  109. . '</font>' . "\n";
  110. if ($GLOBALS['cfg']['ZeroConf']) {
  111. if (strlen($GLOBALS['db']) == 0) {
  112. $retval .= $this->getHtmlFixPmaTables(true, true);
  113. } else {
  114. $retval .= $this->getHtmlFixPmaTables(true);
  115. }
  116. }
  117. } else {
  118. $retval .= '<table>' . "\n";
  119. if (! $cfgRelation['allworks']
  120. && $GLOBALS['cfg']['ZeroConf']
  121. // Avoid showing a "Create missing tables" link if it's a
  122. // problem of missing definition
  123. && $this->arePmadbTablesDefined()
  124. ) {
  125. $retval .= $this->getHtmlFixPmaTables(false);
  126. $retval .= '<br />';
  127. }
  128. $retval .= $this->getDiagMessageForParameter(
  129. 'pmadb',
  130. $cfgRelation['db'],
  131. $messages,
  132. 'pmadb'
  133. );
  134. $retval .= $this->getDiagMessageForParameter(
  135. 'relation',
  136. isset($cfgRelation['relation']),
  137. $messages,
  138. 'relation'
  139. );
  140. $retval .= $this->getDiagMessageForFeature(
  141. __('General relation features'),
  142. 'relwork',
  143. $messages
  144. );
  145. $retval .= $this->getDiagMessageForParameter(
  146. 'table_info',
  147. isset($cfgRelation['table_info']),
  148. $messages,
  149. 'table_info'
  150. );
  151. $retval .= $this->getDiagMessageForFeature(
  152. __('Display Features'),
  153. 'displaywork',
  154. $messages
  155. );
  156. $retval .= $this->getDiagMessageForParameter(
  157. 'table_coords',
  158. isset($cfgRelation['table_coords']),
  159. $messages,
  160. 'table_coords'
  161. );
  162. $retval .= $this->getDiagMessageForParameter(
  163. 'pdf_pages',
  164. isset($cfgRelation['pdf_pages']),
  165. $messages,
  166. 'pdf_pages'
  167. );
  168. $retval .= $this->getDiagMessageForFeature(
  169. __('Designer and creation of PDFs'),
  170. 'pdfwork',
  171. $messages
  172. );
  173. $retval .= $this->getDiagMessageForParameter(
  174. 'column_info',
  175. isset($cfgRelation['column_info']),
  176. $messages,
  177. 'column_info'
  178. );
  179. $retval .= $this->getDiagMessageForFeature(
  180. __('Displaying Column Comments'),
  181. 'commwork',
  182. $messages,
  183. false
  184. );
  185. $retval .= $this->getDiagMessageForFeature(
  186. __('Browser transformation'),
  187. 'mimework',
  188. $messages
  189. );
  190. if ($cfgRelation['commwork'] && ! $cfgRelation['mimework']) {
  191. $retval .= '<tr><td colspan=2 class="left error">';
  192. $retval .= __(
  193. 'Please see the documentation on how to'
  194. . ' update your column_info table.'
  195. );
  196. $retval .= Util::showDocu(
  197. 'config',
  198. 'cfg_Servers_column_info'
  199. );
  200. $retval .= '</td></tr>';
  201. }
  202. $retval .= $this->getDiagMessageForParameter(
  203. 'bookmarktable',
  204. isset($cfgRelation['bookmark']),
  205. $messages,
  206. 'bookmark'
  207. );
  208. $retval .= $this->getDiagMessageForFeature(
  209. __('Bookmarked SQL query'),
  210. 'bookmarkwork',
  211. $messages
  212. );
  213. $retval .= $this->getDiagMessageForParameter(
  214. 'history',
  215. isset($cfgRelation['history']),
  216. $messages,
  217. 'history'
  218. );
  219. $retval .= $this->getDiagMessageForFeature(
  220. __('SQL history'),
  221. 'historywork',
  222. $messages
  223. );
  224. $retval .= $this->getDiagMessageForParameter(
  225. 'recent',
  226. isset($cfgRelation['recent']),
  227. $messages,
  228. 'recent'
  229. );
  230. $retval .= $this->getDiagMessageForFeature(
  231. __('Persistent recently used tables'),
  232. 'recentwork',
  233. $messages
  234. );
  235. $retval .= $this->getDiagMessageForParameter(
  236. 'favorite',
  237. isset($cfgRelation['favorite']),
  238. $messages,
  239. 'favorite'
  240. );
  241. $retval .= $this->getDiagMessageForFeature(
  242. __('Persistent favorite tables'),
  243. 'favoritework',
  244. $messages
  245. );
  246. $retval .= $this->getDiagMessageForParameter(
  247. 'table_uiprefs',
  248. isset($cfgRelation['table_uiprefs']),
  249. $messages,
  250. 'table_uiprefs'
  251. );
  252. $retval .= $this->getDiagMessageForFeature(
  253. __('Persistent tables\' UI preferences'),
  254. 'uiprefswork',
  255. $messages
  256. );
  257. $retval .= $this->getDiagMessageForParameter(
  258. 'tracking',
  259. isset($cfgRelation['tracking']),
  260. $messages,
  261. 'tracking'
  262. );
  263. $retval .= $this->getDiagMessageForFeature(
  264. __('Tracking'),
  265. 'trackingwork',
  266. $messages
  267. );
  268. $retval .= $this->getDiagMessageForParameter(
  269. 'userconfig',
  270. isset($cfgRelation['userconfig']),
  271. $messages,
  272. 'userconfig'
  273. );
  274. $retval .= $this->getDiagMessageForFeature(
  275. __('User preferences'),
  276. 'userconfigwork',
  277. $messages
  278. );
  279. $retval .= $this->getDiagMessageForParameter(
  280. 'users',
  281. isset($cfgRelation['users']),
  282. $messages,
  283. 'users'
  284. );
  285. $retval .= $this->getDiagMessageForParameter(
  286. 'usergroups',
  287. isset($cfgRelation['usergroups']),
  288. $messages,
  289. 'usergroups'
  290. );
  291. $retval .= $this->getDiagMessageForFeature(
  292. __('Configurable menus'),
  293. 'menuswork',
  294. $messages
  295. );
  296. $retval .= $this->getDiagMessageForParameter(
  297. 'navigationhiding',
  298. isset($cfgRelation['navigationhiding']),
  299. $messages,
  300. 'navigationhiding'
  301. );
  302. $retval .= $this->getDiagMessageForFeature(
  303. __('Hide/show navigation items'),
  304. 'navwork',
  305. $messages
  306. );
  307. $retval .= $this->getDiagMessageForParameter(
  308. 'savedsearches',
  309. isset($cfgRelation['savedsearches']),
  310. $messages,
  311. 'savedsearches'
  312. );
  313. $retval .= $this->getDiagMessageForFeature(
  314. __('Saving Query-By-Example searches'),
  315. 'savedsearcheswork',
  316. $messages
  317. );
  318. $retval .= $this->getDiagMessageForParameter(
  319. 'central_columns',
  320. isset($cfgRelation['central_columns']),
  321. $messages,
  322. 'central_columns'
  323. );
  324. $retval .= $this->getDiagMessageForFeature(
  325. __('Managing Central list of columns'),
  326. 'centralcolumnswork',
  327. $messages
  328. );
  329. $retval .= $this->getDiagMessageForParameter(
  330. 'designer_settings',
  331. isset($cfgRelation['designer_settings']),
  332. $messages,
  333. 'designer_settings'
  334. );
  335. $retval .= $this->getDiagMessageForFeature(
  336. __('Remembering Designer Settings'),
  337. 'designersettingswork',
  338. $messages
  339. );
  340. $retval .= $this->getDiagMessageForParameter(
  341. 'export_templates',
  342. isset($cfgRelation['export_templates']),
  343. $messages,
  344. 'export_templates'
  345. );
  346. $retval .= $this->getDiagMessageForFeature(
  347. __('Saving export templates'),
  348. 'exporttemplateswork',
  349. $messages
  350. );
  351. $retval .= '</table>' . "\n";
  352. if (! $cfgRelation['allworks']) {
  353. $retval .= '<p>' . __('Quick steps to set up advanced features:')
  354. . '</p>';
  355. $items = array();
  356. $items[] = sprintf(
  357. __(
  358. 'Create the needed tables with the '
  359. . '<code>%screate_tables.sql</code>.'
  360. ),
  361. htmlspecialchars(SQL_DIR)
  362. ) . ' ' . Util::showDocu('setup', 'linked-tables');
  363. $items[] = __('Create a pma user and give access to these tables.') . ' '
  364. . Util::showDocu('config', 'cfg_Servers_controluser');
  365. $items[] = __(
  366. 'Enable advanced features in configuration file '
  367. . '(<code>config.inc.php</code>), for example by '
  368. . 'starting from <code>config.sample.inc.php</code>.'
  369. ) . ' ' . Util::showDocu('setup', 'quick-install');
  370. $items[] = __(
  371. 'Re-login to phpMyAdmin to load the updated configuration file.'
  372. );
  373. $retval .= Template::get('list/unordered')->render(
  374. array('items' => $items,)
  375. );
  376. }
  377. }
  378. return $retval;
  379. }
  380. /**
  381. * prints out one diagnostic message for a feature
  382. *
  383. * @param string $feature_name feature name in a message string
  384. * @param string $relation_parameter the $GLOBALS['cfgRelation'] parameter to check
  385. * @param array $messages utility messages
  386. * @param boolean $skip_line whether to skip a line after the message
  387. *
  388. * @return string
  389. */
  390. public function getDiagMessageForFeature($feature_name,
  391. $relation_parameter, array $messages, $skip_line = true
  392. ) {
  393. $retval = ' <tr><td colspan=2 class="right">' . $feature_name . ': ';
  394. if (isset($GLOBALS['cfgRelation'][$relation_parameter])
  395. && $GLOBALS['cfgRelation'][$relation_parameter]
  396. ) {
  397. $retval .= $messages['enabled'];
  398. } else {
  399. $retval .= $messages['disabled'];
  400. }
  401. $retval .= '</td></tr>';
  402. if ($skip_line) {
  403. $retval .= '<tr><td>&nbsp;</td></tr>';
  404. }
  405. return $retval;
  406. }
  407. /**
  408. * prints out one diagnostic message for a configuration parameter
  409. *
  410. * @param string $parameter config parameter name to display
  411. * @param boolean $relationParameterSet whether this parameter is set
  412. * @param array $messages utility messages
  413. * @param string $docAnchor anchor in documentation
  414. *
  415. * @return string
  416. */
  417. public function getDiagMessageForParameter($parameter,
  418. $relationParameterSet, array $messages, $docAnchor
  419. ) {
  420. $retval = '<tr><th class="left">';
  421. $retval .= '$cfg[\'Servers\'][$i][\'' . $parameter . '\'] ... ';
  422. $retval .= '</th><td class="right">';
  423. if ($relationParameterSet) {
  424. $retval .= $messages['ok'];
  425. } else {
  426. $retval .= sprintf(
  427. $messages['error'],
  428. Util::getDocuLink('config', 'cfg_Servers_' . $docAnchor)
  429. );
  430. }
  431. $retval .= '</td></tr>' . "\n";
  432. return $retval;
  433. }
  434. /**
  435. * Defines the relation parameters for the current user
  436. * just a copy of the functions used for relations ;-)
  437. * but added some stuff to check what will work
  438. *
  439. * @access protected
  440. * @return array the relation parameters for the current user
  441. */
  442. public function checkRelationsParam()
  443. {
  444. $cfgRelation = array();
  445. $cfgRelation['PMA_VERSION'] = PMA_VERSION;
  446. $workToTable = array(
  447. 'relwork' => 'relation',
  448. 'displaywork' => array('relation', 'table_info'),
  449. 'bookmarkwork' => 'bookmarktable',
  450. 'pdfwork' => array('table_coords', 'pdf_pages'),
  451. 'commwork' => 'column_info',
  452. 'mimework' => 'column_info',
  453. 'historywork' => 'history',
  454. 'recentwork' => 'recent',
  455. 'favoritework' => 'favorite',
  456. 'uiprefswork' => 'table_uiprefs',
  457. 'trackingwork' => 'tracking',
  458. 'userconfigwork' => 'userconfig',
  459. 'menuswork' => array('users', 'usergroups'),
  460. 'navwork' => 'navigationhiding',
  461. 'savedsearcheswork' => 'savedsearches',
  462. 'centralcolumnswork' => 'central_columns',
  463. 'designersettingswork' => 'designer_settings',
  464. 'exporttemplateswork' => 'export_templates',
  465. );
  466. foreach ($workToTable as $work => $table) {
  467. $cfgRelation[$work] = false;
  468. }
  469. $cfgRelation['allworks'] = false;
  470. $cfgRelation['user'] = null;
  471. $cfgRelation['db'] = null;
  472. if ($GLOBALS['server'] == 0
  473. || empty($GLOBALS['cfg']['Server']['pmadb'])
  474. || ! $GLOBALS['dbi']->selectDb(
  475. $GLOBALS['cfg']['Server']['pmadb'], DatabaseInterface::CONNECT_CONTROL
  476. )
  477. ) {
  478. // No server selected -> no bookmark table
  479. // we return the array with the falses in it,
  480. // to avoid some 'Uninitialized string offset' errors later
  481. $GLOBALS['cfg']['Server']['pmadb'] = false;
  482. return $cfgRelation;
  483. }
  484. $cfgRelation['user'] = $GLOBALS['cfg']['Server']['user'];
  485. $cfgRelation['db'] = $GLOBALS['cfg']['Server']['pmadb'];
  486. // Now I just check if all tables that i need are present so I can for
  487. // example enable relations but not pdf...
  488. // I was thinking of checking if they have all required columns but I
  489. // fear it might be too slow
  490. $tab_query = 'SHOW TABLES FROM '
  491. . Util::backquote(
  492. $GLOBALS['cfg']['Server']['pmadb']
  493. );
  494. $tab_rs = $this->queryAsControlUser(
  495. $tab_query, false, DatabaseInterface::QUERY_STORE
  496. );
  497. if (! $tab_rs) {
  498. // query failed ... ?
  499. //$GLOBALS['cfg']['Server']['pmadb'] = false;
  500. return $cfgRelation;
  501. }
  502. while ($curr_table = @$GLOBALS['dbi']->fetchRow($tab_rs)) {
  503. if ($curr_table[0] == $GLOBALS['cfg']['Server']['bookmarktable']) {
  504. $cfgRelation['bookmark'] = $curr_table[0];
  505. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['relation']) {
  506. $cfgRelation['relation'] = $curr_table[0];
  507. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_info']) {
  508. $cfgRelation['table_info'] = $curr_table[0];
  509. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_coords']) {
  510. $cfgRelation['table_coords'] = $curr_table[0];
  511. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['column_info']) {
  512. $cfgRelation['column_info'] = $curr_table[0];
  513. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['pdf_pages']) {
  514. $cfgRelation['pdf_pages'] = $curr_table[0];
  515. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['history']) {
  516. $cfgRelation['history'] = $curr_table[0];
  517. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['recent']) {
  518. $cfgRelation['recent'] = $curr_table[0];
  519. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['favorite']) {
  520. $cfgRelation['favorite'] = $curr_table[0];
  521. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_uiprefs']) {
  522. $cfgRelation['table_uiprefs'] = $curr_table[0];
  523. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['tracking']) {
  524. $cfgRelation['tracking'] = $curr_table[0];
  525. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['userconfig']) {
  526. $cfgRelation['userconfig'] = $curr_table[0];
  527. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['users']) {
  528. $cfgRelation['users'] = $curr_table[0];
  529. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['usergroups']) {
  530. $cfgRelation['usergroups'] = $curr_table[0];
  531. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['navigationhiding']) {
  532. $cfgRelation['navigationhiding'] = $curr_table[0];
  533. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['savedsearches']) {
  534. $cfgRelation['savedsearches'] = $curr_table[0];
  535. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['central_columns']) {
  536. $cfgRelation['central_columns'] = $curr_table[0];
  537. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['designer_settings']) {
  538. $cfgRelation['designer_settings'] = $curr_table[0];
  539. } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['export_templates']) {
  540. $cfgRelation['export_templates'] = $curr_table[0];
  541. }
  542. } // end while
  543. $GLOBALS['dbi']->freeResult($tab_rs);
  544. if (isset($cfgRelation['relation'])) {
  545. if ($this->canAccessStorageTable($cfgRelation['relation'])) {
  546. $cfgRelation['relwork'] = true;
  547. }
  548. }
  549. if (isset($cfgRelation['relation']) && isset($cfgRelation['table_info'])) {
  550. if ($this->canAccessStorageTable($cfgRelation['table_info'])) {
  551. $cfgRelation['displaywork'] = true;
  552. }
  553. }
  554. if (isset($cfgRelation['table_coords']) && isset($cfgRelation['pdf_pages'])) {
  555. if ($this->canAccessStorageTable($cfgRelation['table_coords'])) {
  556. if ($this->canAccessStorageTable($cfgRelation['pdf_pages'])) {
  557. $cfgRelation['pdfwork'] = true;
  558. }
  559. }
  560. }
  561. if (isset($cfgRelation['column_info'])) {
  562. if ($this->canAccessStorageTable($cfgRelation['column_info'])) {
  563. $cfgRelation['commwork'] = true;
  564. // phpMyAdmin 4.3+
  565. // Check for input transformations upgrade.
  566. $cfgRelation['mimework'] = $this->tryUpgradeTransformations();
  567. }
  568. }
  569. if (isset($cfgRelation['history'])) {
  570. if ($this->canAccessStorageTable($cfgRelation['history'])) {
  571. $cfgRelation['historywork'] = true;
  572. }
  573. }
  574. if (isset($cfgRelation['recent'])) {
  575. if ($this->canAccessStorageTable($cfgRelation['recent'])) {
  576. $cfgRelation['recentwork'] = true;
  577. }
  578. }
  579. if (isset($cfgRelation['favorite'])) {
  580. if ($this->canAccessStorageTable($cfgRelation['favorite'])) {
  581. $cfgRelation['favoritework'] = true;
  582. }
  583. }
  584. if (isset($cfgRelation['table_uiprefs'])) {
  585. if ($this->canAccessStorageTable($cfgRelation['table_uiprefs'])) {
  586. $cfgRelation['uiprefswork'] = true;
  587. }
  588. }
  589. if (isset($cfgRelation['tracking'])) {
  590. if ($this->canAccessStorageTable($cfgRelation['tracking'])) {
  591. $cfgRelation['trackingwork'] = true;
  592. }
  593. }
  594. if (isset($cfgRelation['userconfig'])) {
  595. if ($this->canAccessStorageTable($cfgRelation['userconfig'])) {
  596. $cfgRelation['userconfigwork'] = true;
  597. }
  598. }
  599. if (isset($cfgRelation['bookmark'])) {
  600. if ($this->canAccessStorageTable($cfgRelation['bookmark'])) {
  601. $cfgRelation['bookmarkwork'] = true;
  602. }
  603. }
  604. if (isset($cfgRelation['users']) && isset($cfgRelation['usergroups'])) {
  605. if ($this->canAccessStorageTable($cfgRelation['users'])) {
  606. if ($this->canAccessStorageTable($cfgRelation['usergroups'])) {
  607. $cfgRelation['menuswork'] = true;
  608. }
  609. }
  610. }
  611. if (isset($cfgRelation['navigationhiding'])) {
  612. if ($this->canAccessStorageTable($cfgRelation['navigationhiding'])) {
  613. $cfgRelation['navwork'] = true;
  614. }
  615. }
  616. if (isset($cfgRelation['savedsearches'])) {
  617. if ($this->canAccessStorageTable($cfgRelation['savedsearches'])) {
  618. $cfgRelation['savedsearcheswork'] = true;
  619. }
  620. }
  621. if (isset($cfgRelation['central_columns'])) {
  622. if ($this->canAccessStorageTable($cfgRelation['central_columns'])) {
  623. $cfgRelation['centralcolumnswork'] = true;
  624. }
  625. }
  626. if (isset($cfgRelation['designer_settings'])) {
  627. if ($this->canAccessStorageTable($cfgRelation['designer_settings'])) {
  628. $cfgRelation['designersettingswork'] = true;
  629. }
  630. }
  631. if (isset($cfgRelation['export_templates'])) {
  632. if ($this->canAccessStorageTable($cfgRelation['export_templates'])) {
  633. $cfgRelation['exporttemplateswork'] = true;
  634. }
  635. }
  636. $allWorks = true;
  637. foreach ($workToTable as $work => $table) {
  638. if (! $cfgRelation[$work]) {
  639. if (is_string($table)) {
  640. if (isset($GLOBALS['cfg']['Server'][$table])
  641. && $GLOBALS['cfg']['Server'][$table] !== false
  642. ) {
  643. $allWorks = false;
  644. break;
  645. }
  646. } elseif (is_array($table)) {
  647. $oneNull = false;
  648. foreach ($table as $t) {
  649. if (isset($GLOBALS['cfg']['Server'][$t])
  650. && $GLOBALS['cfg']['Server'][$t] === false
  651. ) {
  652. $oneNull = true;
  653. break;
  654. }
  655. }
  656. if (! $oneNull) {
  657. $allWorks = false;
  658. break;
  659. }
  660. }
  661. }
  662. }
  663. $cfgRelation['allworks'] = $allWorks;
  664. return $cfgRelation;
  665. }
  666. /**
  667. * Check if the table is accessible
  668. *
  669. * @param string $tableDbName The table or table.db
  670. * @return boolean The table is accessible
  671. */
  672. public function canAccessStorageTable($tableDbName) {
  673. $result = $this->queryAsControlUser(
  674. 'SELECT NULL FROM ' . $tableDbName . ' LIMIT 0',
  675. false,
  676. DatabaseInterface::QUERY_STORE
  677. );
  678. return $result !== false;
  679. }
  680. /**
  681. * Check whether column_info table input transformation
  682. * upgrade is required and try to upgrade silently
  683. *
  684. * @return bool false if upgrade failed
  685. *
  686. * @access public
  687. */
  688. public function tryUpgradeTransformations()
  689. {
  690. // From 4.3, new input oriented transformation feature was introduced.
  691. // Check whether column_info table has input transformation columns
  692. $new_cols = array(
  693. "input_transformation",
  694. "input_transformation_options"
  695. );
  696. $query = 'SHOW COLUMNS FROM '
  697. . Util::backquote($GLOBALS['cfg']['Server']['pmadb'])
  698. . '.' . Util::backquote(
  699. $GLOBALS['cfg']['Server']['column_info']
  700. )
  701. . ' WHERE Field IN (\'' . implode('\', \'', $new_cols) . '\')';
  702. $result = $this->queryAsControlUser(
  703. $query, false, DatabaseInterface::QUERY_STORE
  704. );
  705. if ($result) {
  706. $rows = $GLOBALS['dbi']->numRows($result);
  707. $GLOBALS['dbi']->freeResult($result);
  708. // input transformations are present
  709. // no need to upgrade
  710. if ($rows === 2) {
  711. return true;
  712. // try silent upgrade without disturbing the user
  713. }
  714. // read upgrade query file
  715. $query = @file_get_contents(SQL_DIR . 'upgrade_column_info_4_3_0+.sql');
  716. // replace database name from query to with set in config.inc.php
  717. $query = str_replace(
  718. '`phpmyadmin`',
  719. Util::backquote($GLOBALS['cfg']['Server']['pmadb']),
  720. $query
  721. );
  722. // replace pma__column_info table name from query
  723. // to with set in config.inc.php
  724. $query = str_replace(
  725. '`pma__column_info`',
  726. Util::backquote(
  727. $GLOBALS['cfg']['Server']['column_info']
  728. ),
  729. $query
  730. );
  731. $GLOBALS['dbi']->tryMultiQuery($query, DatabaseInterface::CONNECT_CONTROL);
  732. // skips result sets of query as we are not interested in it
  733. while ($GLOBALS['dbi']->moreResults(DatabaseInterface::CONNECT_CONTROL)
  734. && $GLOBALS['dbi']->nextResult(DatabaseInterface::CONNECT_CONTROL)
  735. ) {
  736. }
  737. $error = $GLOBALS['dbi']->getError(DatabaseInterface::CONNECT_CONTROL);
  738. // return true if no error exists otherwise false
  739. return empty($error);
  740. }
  741. // some failure, either in upgrading or something else
  742. // make some noise, time to wake up user.
  743. return false;
  744. }
  745. /**
  746. * Gets all Relations to foreign tables for a given table or
  747. * optionally a given column in a table
  748. *
  749. * @param string $db the name of the db to check for
  750. * @param string $table the name of the table to check for
  751. * @param string $column the name of the column to check for
  752. * @param string $source the source for foreign key information
  753. *
  754. * @return array db,table,column
  755. *
  756. * @access public
  757. */
  758. public function getForeigners($db, $table, $column = '', $source = 'both')
  759. {
  760. $cfgRelation = $this->getRelationsParam();
  761. $foreign = array();
  762. if ($cfgRelation['relwork'] && ($source == 'both' || $source == 'internal')) {
  763. $rel_query = '
  764. SELECT `master_field`,
  765. `foreign_db`,
  766. `foreign_table`,
  767. `foreign_field`
  768. FROM ' . Util::backquote($cfgRelation['db'])
  769. . '.' . Util::backquote($cfgRelation['relation']) . '
  770. WHERE `master_db` = \'' . $GLOBALS['dbi']->escapeString($db) . '\'
  771. AND `master_table` = \'' . $GLOBALS['dbi']->escapeString($table)
  772. . '\' ';
  773. if (strlen($column) > 0) {
  774. $rel_query .= ' AND `master_field` = '
  775. . '\'' . $GLOBALS['dbi']->escapeString($column) . '\'';
  776. }
  777. $foreign = $GLOBALS['dbi']->fetchResult(
  778. $rel_query, 'master_field', null, DatabaseInterface::CONNECT_CONTROL
  779. );
  780. }
  781. if (($source == 'both' || $source == 'foreign') && strlen($table) > 0) {
  782. $tableObj = new Table($table, $db);
  783. $show_create_table = $tableObj->showCreate();
  784. if ($show_create_table) {
  785. $parser = new Parser($show_create_table);
  786. /**
  787. * @var \PhpMyAdmin\SqlParser\Statements\CreateStatement $stmt
  788. */
  789. $stmt = $parser->statements[0];
  790. $foreign['foreign_keys_data'] = TableUtils::getForeignKeys(
  791. $stmt
  792. );
  793. }
  794. }
  795. /**
  796. * Emulating relations for some information_schema tables
  797. */
  798. $isInformationSchema = mb_strtolower($db) == 'information_schema';
  799. $isMysql = mb_strtolower($db) == 'mysql';
  800. if (($isInformationSchema || $isMysql)
  801. && ($source == 'internal' || $source == 'both')
  802. ) {
  803. if ($isInformationSchema) {
  804. $relations_key = 'information_schema_relations';
  805. include_once './libraries/information_schema_relations.inc.php';
  806. } else {
  807. $relations_key = 'mysql_relations';
  808. include_once './libraries/mysql_relations.inc.php';
  809. }
  810. if (isset($GLOBALS[$relations_key][$table])) {
  811. foreach ($GLOBALS[$relations_key][$table] as $field => $relations) {
  812. if ((strlen($column) === 0 || $column == $field)
  813. && (! isset($foreign[$field])
  814. || strlen($foreign[$field]) === 0)
  815. ) {
  816. $foreign[$field] = $relations;
  817. }
  818. }
  819. }
  820. }
  821. return $foreign;
  822. }
  823. /**
  824. * Gets the display field of a table
  825. *
  826. * @param string $db the name of the db to check for
  827. * @param string $table the name of the table to check for
  828. *
  829. * @return string field name
  830. *
  831. * @access public
  832. */
  833. public function getDisplayField($db, $table)
  834. {
  835. $cfgRelation = $this->getRelationsParam();
  836. /**
  837. * Try to fetch the display field from DB.
  838. */
  839. if ($cfgRelation['displaywork']) {
  840. $disp_query = '
  841. SELECT `display_field`
  842. FROM ' . Util::backquote($cfgRelation['db'])
  843. . '.' . Util::backquote($cfgRelation['table_info']) . '
  844. WHERE `db_name` = \'' . $GLOBALS['dbi']->escapeString($db) . '\'
  845. AND `table_name` = \'' . $GLOBALS['dbi']->escapeString($table)
  846. . '\'';
  847. $row = $GLOBALS['dbi']->fetchSingleRow(
  848. $disp_query, 'ASSOC', DatabaseInterface::CONNECT_CONTROL
  849. );
  850. if (isset($row['display_field'])) {
  851. return $row['display_field'];
  852. }
  853. }
  854. /**
  855. * Emulating the display field for some information_schema tables.
  856. */
  857. if ($db == 'information_schema') {
  858. switch ($table) {
  859. case 'CHARACTER_SETS':
  860. return 'DESCRIPTION';
  861. case 'TABLES':
  862. return 'TABLE_COMMENT';
  863. }
  864. }
  865. /**
  866. * Pick first char field
  867. */
  868. $columns = $GLOBALS['dbi']->getColumnsFull($db, $table);
  869. if ($columns) {
  870. foreach ($columns as $column) {
  871. if ($GLOBALS['dbi']->types->getTypeClass($column['DATA_TYPE']) == 'CHAR') {
  872. return $column['COLUMN_NAME'];
  873. }
  874. }
  875. }
  876. return false;
  877. }
  878. /**
  879. * Gets the comments for all columns of a table or the db itself
  880. *
  881. * @param string $db the name of the db to check for
  882. * @param string $table the name of the table to check for
  883. *
  884. * @return array [column_name] = comment
  885. *
  886. * @access public
  887. */
  888. public function getComments($db, $table = '')
  889. {
  890. $comments = array();
  891. if ($table != '') {
  892. // MySQL native column comments
  893. $columns = $GLOBALS['dbi']->getColumns($db, $table, null, true);
  894. if ($columns) {
  895. foreach ($columns as $column) {
  896. if (! empty($column['Comment'])) {
  897. $comments[$column['Field']] = $column['Comment'];
  898. }
  899. }
  900. }
  901. } else {
  902. $comments[] = $this->getDbComment($db);
  903. }
  904. return $comments;
  905. }
  906. /**
  907. * Gets the comment for a db
  908. *
  909. * @param string $db the name of the db to check for
  910. *
  911. * @return string comment
  912. *
  913. * @access public
  914. */
  915. public function getDbComment($db)
  916. {
  917. $cfgRelation = $this->getRelationsParam();
  918. $comment = '';
  919. if ($cfgRelation['commwork']) {
  920. // pmadb internal db comment
  921. $com_qry = "
  922. SELECT `comment`
  923. FROM " . Util::backquote($cfgRelation['db'])
  924. . "." . Util::backquote($cfgRelation['column_info'])
  925. . "
  926. WHERE db_name = '" . $GLOBALS['dbi']->escapeString($db) . "'
  927. AND table_name = ''
  928. AND column_name = '(db_comment)'";
  929. $com_rs = $this->queryAsControlUser(
  930. $com_qry, false, DatabaseInterface::QUERY_STORE
  931. );
  932. if ($com_rs && $GLOBALS['dbi']->numRows($com_rs) > 0) {
  933. $row = $GLOBALS['dbi']->fetchAssoc($com_rs);
  934. $comment = $row['comment'];
  935. }
  936. $GLOBALS['dbi']->freeResult($com_rs);
  937. }
  938. return $comment;
  939. }
  940. /**
  941. * Gets the comment for a db
  942. *
  943. * @access public
  944. *
  945. * @return string comment
  946. */
  947. public function getDbComments()
  948. {
  949. $cfgRelation = $this->getRelationsParam();
  950. $comments = array();
  951. if ($cfgRelation['commwork']) {
  952. // pmadb internal db comment
  953. $com_qry = "
  954. SELECT `db_name`, `comment`
  955. FROM " . Util::backquote($cfgRelation['db'])
  956. . "." . Util::backquote($cfgRelation['column_info'])
  957. . "
  958. WHERE `column_name` = '(db_comment)'";
  959. $com_rs = $this->queryAsControlUser(
  960. $com_qry, false, DatabaseInterface::QUERY_STORE
  961. );
  962. if ($com_rs && $GLOBALS['dbi']->numRows($com_rs) > 0) {
  963. while ($row = $GLOBALS['dbi']->fetchAssoc($com_rs)) {
  964. $comments[$row['db_name']] = $row['comment'];
  965. }
  966. }
  967. $GLOBALS['dbi']->freeResult($com_rs);
  968. }
  969. return $comments;
  970. }
  971. /**
  972. * Set a database comment to a certain value.
  973. *
  974. * @param string $db the name of the db
  975. * @param string $comment the value of the column
  976. *
  977. * @return boolean true, if comment-query was made.
  978. *
  979. * @access public
  980. */
  981. public function setDbComment($db, $comment = '')
  982. {
  983. $cfgRelation = $this->getRelationsParam();
  984. if (! $cfgRelation['commwork']) {
  985. return false;
  986. }
  987. if (strlen($comment) > 0) {
  988. $upd_query = 'INSERT INTO '
  989. . Util::backquote($cfgRelation['db']) . '.'
  990. . Util::backquote($cfgRelation['column_info'])
  991. . ' (`db_name`, `table_name`, `column_name`, `comment`)'
  992. . ' VALUES (\''
  993. . $GLOBALS['dbi']->escapeString($db)
  994. . "', '', '(db_comment)', '"
  995. . $GLOBALS['dbi']->escapeString($comment)
  996. . "') "
  997. . ' ON DUPLICATE KEY UPDATE '
  998. . "`comment` = '" . $GLOBALS['dbi']->escapeString($comment) . "'";
  999. } else {
  1000. $upd_query = 'DELETE FROM '
  1001. . Util::backquote($cfgRelation['db']) . '.'
  1002. . Util::backquote($cfgRelation['column_info'])
  1003. . ' WHERE `db_name` = \'' . $GLOBALS['dbi']->escapeString($db)
  1004. . '\'
  1005. AND `table_name` = \'\'
  1006. AND `column_name` = \'(db_comment)\'';
  1007. }
  1008. if (isset($upd_query)) {
  1009. return $this->queryAsControlUser($upd_query);
  1010. }
  1011. return false;
  1012. }
  1013. /**
  1014. * Set a SQL history entry
  1015. *
  1016. * @param string $db the name of the db
  1017. * @param string $table the name of the table
  1018. * @param string $username the username
  1019. * @param string $sqlquery the sql query
  1020. *
  1021. * @return void
  1022. *
  1023. * @access public
  1024. */
  1025. public function setHistory($db, $table, $username, $sqlquery)
  1026. {
  1027. $maxCharactersInDisplayedSQL = $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'];
  1028. // Prevent to run this automatically on Footer class destroying in testsuite
  1029. if (defined('TESTSUITE')
  1030. || mb_strlen($sqlquery) > $maxCharactersInDisplayedSQL
  1031. ) {
  1032. return;
  1033. }
  1034. $cfgRelation = $this->getRelationsParam();
  1035. if (! isset($_SESSION['sql_history'])) {
  1036. $_SESSION['sql_history'] = array();
  1037. }
  1038. $_SESSION['sql_history'][] = array(
  1039. 'db' => $db,
  1040. 'table' => $table,
  1041. 'sqlquery' => $sqlquery,
  1042. );
  1043. if (count($_SESSION['sql_history']) > $GLOBALS['cfg']['QueryHistoryMax']) {
  1044. // history should not exceed a maximum count
  1045. array_shift($_SESSION['sql_history']);
  1046. }
  1047. if (! $cfgRelation['historywork'] || ! $GLOBALS['cfg']['QueryHistoryDB']) {
  1048. return;
  1049. }
  1050. $this->queryAsControlUser(
  1051. 'INSERT INTO '
  1052. . Util::backquote($cfgRelation['db']) . '.'
  1053. . Util::backquote($cfgRelation['history']) . '
  1054. (`username`,
  1055. `db`,
  1056. `table`,
  1057. `timevalue`,
  1058. `sqlquery`)
  1059. VALUES
  1060. (\'' . $GLOBALS['dbi']->escapeString($username) . '\',
  1061. \'' . $GLOBALS['dbi']->escapeString($db) . '\',
  1062. \'' . $GLOBALS['dbi']->escapeString($table) . '\',
  1063. NOW(),
  1064. \'' . $GLOBALS['dbi']->escapeString($sqlquery) . '\')'
  1065. );
  1066. $this->purgeHistory($username);
  1067. }
  1068. /**
  1069. * Gets a SQL history entry
  1070. *
  1071. * @param string $username the username
  1072. *
  1073. * @return array list of history items
  1074. *
  1075. * @access public
  1076. */
  1077. public function getHistory($username)
  1078. {
  1079. $cfgRelation = $this->getRelationsParam();
  1080. if (! $cfgRelation['historywork']) {
  1081. return false;
  1082. }
  1083. /**
  1084. * if db-based history is disabled but there exists a session-based
  1085. * history, use it
  1086. */
  1087. if (! $GLOBALS['cfg']['QueryHistoryDB']) {
  1088. if (isset($_SESSION['sql_history'])) {
  1089. return array_reverse($_SESSION['sql_history']);
  1090. }
  1091. return false;
  1092. }
  1093. $hist_query = '
  1094. SELECT `db`,
  1095. `table`,
  1096. `sqlquery`,
  1097. `timevalue`
  1098. FROM ' . Util::backquote($cfgRelation['db'])
  1099. . '.' . Util::backquote($cfgRelation['history']) . '
  1100. WHERE `username` = \'' . $GLOBALS['dbi']->escapeString($username) . '\'
  1101. ORDER BY `id` DESC';
  1102. return $GLOBALS['dbi']->fetchResult(
  1103. $hist_query, null, null, DatabaseInterface::CONNECT_CONTROL
  1104. );
  1105. }
  1106. /**
  1107. * purges SQL history
  1108. *
  1109. * deletes entries that exceeds $cfg['QueryHistoryMax'], oldest first, for the
  1110. * given user
  1111. *
  1112. * @param string $username the username
  1113. *
  1114. * @return void
  1115. *
  1116. * @access public
  1117. */
  1118. public function purgeHistory($username)
  1119. {
  1120. $cfgRelation = $this->getRelationsParam();
  1121. if (! $GLOBALS['cfg']['QueryHistoryDB'] || ! $cfgRelation['historywork']) {
  1122. return;
  1123. }
  1124. if (! $cfgRelation['historywork']) {
  1125. return;
  1126. }
  1127. $search_query = '
  1128. SELECT `timevalue`
  1129. FROM ' . Util::backquote($cfgRelation['db'])
  1130. . '.' . Util::backquote($cfgRelation['history']) . '
  1131. WHERE `username` = \'' . $GLOBALS['dbi']->escapeString($username) . '\'
  1132. ORDER BY `timevalue` DESC
  1133. LIMIT ' . $GLOBALS['cfg']['QueryHistoryMax'] . ', 1';
  1134. if ($max_time = $GLOBALS['dbi']->fetchValue(
  1135. $search_query, 0, 0, DatabaseInterface::CONNECT_CONTROL
  1136. )) {
  1137. $this->queryAsControlUser(
  1138. 'DELETE FROM '
  1139. . Util::backquote($cfgRelation['db']) . '.'
  1140. . Util::backquote($cfgRelation['history']) . '
  1141. WHERE `username` = \'' . $GLOBALS['dbi']->escapeString($username)
  1142. . '\'
  1143. AND `timevalue` <= \'' . $max_time . '\''
  1144. );
  1145. }
  1146. }
  1147. /**
  1148. * Prepares the dropdown for one mode
  1149. *
  1150. * @param array $foreign the keys and values for foreigns
  1151. * @param string $data the current data of the dropdown
  1152. * @param string $mode the needed mode
  1153. *
  1154. * @return array the <option value=""><option>s
  1155. *
  1156. * @access protected
  1157. */
  1158. public function buildForeignDropdown(array $foreign, $data, $mode)
  1159. {
  1160. $reloptions = array();
  1161. // id-only is a special mode used when no foreign display column
  1162. // is available
  1163. if ($mode == 'id-content' || $mode == 'id-only') {
  1164. // sort for id-content
  1165. if ($GLOBALS['cfg']['NaturalOrder']) {
  1166. uksort($foreign, 'strnatcasecmp');
  1167. } else {
  1168. ksort($foreign);
  1169. }
  1170. } elseif ($mode == 'content-id') {
  1171. // sort for content-id
  1172. if ($GLOBALS['cfg']['NaturalOrder']) {
  1173. natcasesort($foreign);
  1174. } else {
  1175. asort($foreign);
  1176. }
  1177. }
  1178. foreach ($foreign as $key => $value) {
  1179. if (mb_strlen($value) <= $GLOBALS['cfg']['LimitChars']
  1180. ) {
  1181. $vtitle = '';
  1182. $value = htmlspecialchars($value);
  1183. } else {
  1184. $vtitle = htmlspecialchars($value);
  1185. $value = htmlspecialchars(
  1186. mb_substr(
  1187. $value, 0, $GLOBALS['cfg']['LimitChars']
  1188. ) . '...'
  1189. );
  1190. }
  1191. $reloption = '<option value="' . htmlspecialchars($key) . '"';
  1192. if ($vtitle != '') {
  1193. $reloption .= ' title="' . $vtitle . '"';
  1194. }
  1195. if ((string) $key == (string) $data) {
  1196. $reloption .= ' selected="selected"';
  1197. }
  1198. if ($mode == 'content-id') {
  1199. $reloptions[] = $reloption . '>'
  1200. . $value . '&nbsp;-&nbsp;' . htmlspecialchars($key) . '</option>';
  1201. } elseif ($mode == 'id-content') {
  1202. $reloptions[] = $reloption . '>'
  1203. . htmlspecialchars($key) . '&nbsp;-&nbsp;' . $value . '</option>';
  1204. } elseif ($mode == 'id-only') {
  1205. $reloptions[] = $reloption . '>'
  1206. . htmlspecialchars($key) . '</option>';
  1207. }
  1208. } // end foreach
  1209. return $reloptions;
  1210. }
  1211. /**
  1212. * Outputs dropdown with values of foreign fields
  1213. *
  1214. * @param array $disp_row array of the displayed row
  1215. * @param string $foreign_field the foreign field
  1216. * @param string $foreign_display the foreign field to display
  1217. * @param string $data the current data of the dropdown (field in row)
  1218. * @param int $max maximum number of items in the dropdown
  1219. *
  1220. * @return string the <option value=""><option>s
  1221. *
  1222. * @access public
  1223. */
  1224. public function foreignDropdown(array $disp_row, $foreign_field, $foreign_display, $data,
  1225. $max = null
  1226. ) {
  1227. if (null === $max) {
  1228. $max = $GLOBALS['cfg']['ForeignKeyMaxLimit'];
  1229. }
  1230. $foreign = array();
  1231. // collect the data
  1232. foreach ($disp_row as $relrow) {
  1233. $key = $relrow[$foreign_field];
  1234. // if the display field has been defined for this foreign table
  1235. if ($foreign_display) {
  1236. $value = $relrow[$foreign_display];
  1237. } else {
  1238. $value = '';
  1239. } // end if ($foreign_display)
  1240. $foreign[$key] = $value;
  1241. } // end foreach
  1242. // put the dropdown sections in correct order
  1243. $top = array();
  1244. $bottom = array();
  1245. if ($foreign_display) {
  1246. if (Core::isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'], 'array')) {
  1247. if (Core::isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][0])) {
  1248. $top = $this->buildForeignDropdown(
  1249. $foreign,
  1250. $data,
  1251. $GLOBALS['cfg']['ForeignKeyDropdownOrder'][0]
  1252. );
  1253. }
  1254. if (Core::isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][1])) {
  1255. $bottom = $this->buildForeignDropdown(
  1256. $foreign,
  1257. $data,
  1258. $GLOBALS['cfg']['ForeignKeyDropdownOrder'][1]
  1259. );
  1260. }
  1261. } else {
  1262. $top = $this->buildForeignDropdown($foreign, $data, 'id-content');
  1263. $bottom = $this->buildForeignDropdown($foreign, $data, 'content-id');
  1264. }
  1265. } else {
  1266. $top = $this->buildForeignDropdown($foreign, $data, 'id-only');
  1267. }
  1268. // beginning of dropdown
  1269. $ret = '<option value="">&nbsp;</option>';
  1270. $top_count = count($top);
  1271. if ($max == -1 || $top_count < $max) {
  1272. $ret .= implode('', $top);
  1273. if ($foreign_display && $top_count > 0) {
  1274. // this empty option is to visually mark the beginning of the
  1275. // second series of values (bottom)
  1276. $ret .= '<option value="">&nbsp;</option>';
  1277. }
  1278. }
  1279. if ($foreign_display) {
  1280. $ret .= implode('', $bottom);
  1281. }
  1282. return $ret;
  1283. }
  1284. /**
  1285. * Gets foreign keys in preparation for a drop-down selector
  1286. *
  1287. * @param array|boolean $foreigners array of the foreign keys
  1288. * @param string $field the foreign field name
  1289. * @param bool $override_total whether to override the total
  1290. * @param string $foreign_filter a possible filter
  1291. * @param string $foreign_limit a possible LIMIT clause
  1292. * @param bool $get_total optional, whether to get total num of rows
  1293. * in $foreignData['the_total;]
  1294. * (has an effect of performance)
  1295. *
  1296. * @return array data about the foreign keys
  1297. *
  1298. * @access public
  1299. */
  1300. public function getForeignData(
  1301. $foreigners, $field, $override_total,
  1302. $foreign_filter, $foreign_limit, $get_total=false
  1303. ) {
  1304. // we always show the foreign field in the drop-down; if a display
  1305. // field is defined, we show it besides the foreign field
  1306. $foreign_link = false;
  1307. do {
  1308. if (! $foreigners) {
  1309. break;
  1310. }
  1311. $foreigner = $this->searchColumnInForeigners($foreigners, $field);
  1312. if ($foreigner != false) {
  1313. $foreign_db = $foreigner['foreign_db'];
  1314. $foreign_table = $foreigner['foreign_table'];
  1315. $foreign_field = $foreigner['foreign_field'];
  1316. } else {
  1317. break;
  1318. }
  1319. // Count number of rows in the foreign table. Currently we do
  1320. // not use a drop-down if more than ForeignKeyMaxLimit rows in the
  1321. // foreign table,
  1322. // for speed reasons and because we need a better interface for this.
  1323. //
  1324. // We could also do the SELECT anyway, with a LIMIT, and ensure that
  1325. // the current value of the field is one of the choices.
  1326. // Check if table has more rows than specified by
  1327. // $GLOBALS['cfg']['ForeignKeyMaxLimit']
  1328. $moreThanLimit = $GLOBALS['dbi']->getTable($foreign_db, $foreign_table)
  1329. ->checkIfMinRecordsExist($GLOBALS['cfg']['ForeignKeyMaxLimit']);
  1330. if ($override_total == true
  1331. || !$moreThanLimit
  1332. ) {
  1333. // foreign_display can be false if no display field defined:
  1334. $foreign_display = $this->getDisplayField($foreign_db, $foreign_table);
  1335. $f_query_main = 'SELECT ' . Util::backquote($foreign_field)
  1336. . (
  1337. ($foreign_display == false)
  1338. ? ''
  1339. : ', ' . Util::backquote($foreign_display)
  1340. );
  1341. $f_query_from = ' FROM ' . Util::backquote($foreign_db)
  1342. . '.' . Util::backquote($foreign_table);
  1343. $f_query_filter = empty($foreign_filter) ? '' : ' WHERE '
  1344. . Util::backquote($foreign_field)
  1345. . ' LIKE "%' . $GLOBALS['dbi']->escapeString($foreign_filter) . '%"'
  1346. . (
  1347. ($foreign_display == false)
  1348. ? ''
  1349. : ' OR ' . Util::backquote($foreign_display)
  1350. . ' LIKE "%' . $GLOBALS['dbi']->escapeString($foreign_filter)
  1351. . '%"'
  1352. );
  1353. $f_query_order = ($foreign_display == false) ? '' :' ORDER BY '
  1354. . Util::backquote($foreign_table) . '.'
  1355. . Util::backquote($foreign_display);
  1356. $f_query_limit = ! empty($foreign_limit) ? ($foreign_limit) : '';
  1357. if (!empty($foreign_filter)) {
  1358. $the_total = $GLOBALS['dbi']->fetchValue(
  1359. 'SELECT COUNT(*)' . $f_query_from . $f_query_filter
  1360. );
  1361. if ($the_total === false) {
  1362. $the_total = 0;
  1363. }
  1364. }
  1365. $disp = $GLOBALS['dbi']->tryQuery(
  1366. $f_query_main . $f_query_from . $f_query_filter
  1367. . $f_query_order . $f_query_limit
  1368. );
  1369. if ($disp && $GLOBALS['dbi']->numRows($disp) > 0) {
  1370. // If a resultset has been created, pre-cache it in the $disp_row
  1371. // array. This helps us from not needing to use mysql_data_seek by
  1372. // accessing a pre-cached PHP array. Usually those resultsets are
  1373. // not that big, so a performance hit should not be expected.
  1374. $disp_row = array();
  1375. while ($single_disp_row = @$GLOBALS['dbi']->fetchAssoc($disp)) {
  1376. $disp_row[] = $single_disp_row;
  1377. }
  1378. @$GLOBALS['dbi']->freeResult($disp);
  1379. } else {
  1380. // Either no data in the foreign table or
  1381. // user does not have select permission to foreign table/field
  1382. // Show an input field with a 'Browse foreign values' link
  1383. $disp_row = null;
  1384. $foreign_link = true;
  1385. }
  1386. } else {
  1387. $disp_row = null;
  1388. $foreign_link = true;
  1389. }
  1390. } while (false);
  1391. if ($get_total) {
  1392. $the_total = $GLOBALS['dbi']->getTable($foreign_db, $foreign_table)
  1393. ->countRecords(true);
  1394. }
  1395. $foreignData = array();
  1396. $foreignData['foreign_link'] = $foreign_link;
  1397. $foreignData['the_total'] = isset($the_total) ? $the_total : null;
  1398. $foreignData['foreign_display'] = (
  1399. isset($foreign_display) ? $foreign_display : null
  1400. );
  1401. $foreignData['disp_row'] = isset($disp_row) ? $disp_row : null;
  1402. $foreignData['foreign_field'] = isset($foreign_field) ? $foreign_field : null;
  1403. return $foreignData;
  1404. }
  1405. /**
  1406. * Rename a field in relation tables
  1407. *
  1408. * usually called after a column in a table was renamed
  1409. *
  1410. * @param string $db database name
  1411. * @param string $table table name
  1412. * @param string $field old field name
  1413. * @param string $new_name new field name
  1414. *
  1415. * @return void
  1416. */
  1417. public function renameField($db, $table, $field, $new_name)
  1418. {
  1419. $cfgRelation = $this->getRelationsParam();
  1420. if ($cfgRelation['displaywork']) {
  1421. $table_query = 'UPDATE '
  1422. . Util::backquote($cfgRelation['db']) . '.'
  1423. . Util::backquote($cfgRelation['table_info'])
  1424. . ' SET display_field = \'' . $GLOBALS['dbi']->escapeString(
  1425. $new_name
  1426. ) . '\''
  1427. . ' WHERE db_name = \'' . $GLOBALS['dbi']->escapeString($db)
  1428. . '\''
  1429. . ' AND table_name = \'' . $GLOBALS['dbi']->escapeString($table)
  1430. . '\''
  1431. . ' AND display_field = \'' . $GLOBALS['dbi']->escapeString($field)
  1432. . '\'';
  1433. $this->queryAsControlUser($table_query);
  1434. }
  1435. if ($cfgRelation['relwork']) {
  1436. $table_query = 'UPDATE '
  1437. . Util::backquote($cfgRelation['db']) . '.'
  1438. . Util::backquote($cfgRelation['relation'])
  1439. . ' SET master_field = \'' . $GLOBALS['dbi']->escapeString(
  1440. $new_name
  1441. ) . '\''
  1442. . ' WHERE master_db = \'' . $GLOBALS['dbi']->escapeString($db)
  1443. . '\''
  1444. . ' AND master_table = \'' . $GLOBALS['dbi']->escapeString($table)
  1445. . '\''
  1446. . ' AND master_field = \'' . $GLOBALS['dbi']->escapeString($field)
  1447. . '\'';
  1448. $this->queryAsControlUser($table_query);
  1449. $table_query = 'UPDATE '
  1450. . Util::backquote($cfgRelation['db']) . '.'
  1451. . Util::backquote($cfgRelation['relation'])
  1452. . ' SET foreign_field = \'' . $GLOBALS['dbi']->escapeString(
  1453. $new_name
  1454. ) . '\''
  1455. . ' WHERE foreign_db = \'' . $GLOBALS['dbi']->escapeString($db)
  1456. . '\''
  1457. . ' AND foreign_table = \'' . $GLOBALS['dbi']->escapeString($table)
  1458. . '\''
  1459. . ' AND foreign_field = \'' . $GLOBALS['dbi']->escapeString($field)
  1460. . '\'';
  1461. $this->queryAsControlUser($table_query);
  1462. }
  1463. }
  1464. /**
  1465. * Performs SQL query used for renaming table.
  1466. *
  1467. * @param string $table Relation table to use
  1468. * @param string $source_db Source database name
  1469. * @param string $target_db Target database name
  1470. * @param string $source_table Source table name
  1471. * @param string $target_table Target table name
  1472. * @param string $db_field Name of database field
  1473. * @param string $table_field Name of table field
  1474. *
  1475. * @return void
  1476. */
  1477. public function renameSingleTable($table,
  1478. $source_db, $target_db,
  1479. $source_table, $target_table,
  1480. $db_field, $table_field
  1481. ) {
  1482. $query = 'UPDATE '
  1483. . Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
  1484. . Util::backquote($GLOBALS['cfgRelation'][$table])
  1485. . ' SET '
  1486. . $db_field . ' = \'' . $GLOBALS['dbi']->escapeString($target_db)
  1487. . '\', '
  1488. . $table_field . ' = \'' . $GLOBALS['dbi']->escapeString($target_table)
  1489. . '\''
  1490. . ' WHERE '
  1491. . $db_field . ' = \'' . $GLOBALS['dbi']->escapeString($source_db) . '\''
  1492. . ' AND '
  1493. . $table_field . ' = \'' . $GLOBALS['dbi']->escapeString($source_table)
  1494. . '\'';
  1495. $this->queryAsControlUser($query);
  1496. }
  1497. /**
  1498. * Rename a table in relation tables
  1499. *
  1500. * usually called after table has been moved
  1501. *
  1502. * @param string $source_db Source database name
  1503. * @param string $target_db Target database name
  1504. * @param string $source_table Source table name
  1505. * @param string $target_table Target table name
  1506. *
  1507. * @return void
  1508. */
  1509. public function renameTable($source_db, $target_db, $source_table, $target_table)
  1510. {
  1511. // Move old entries from PMA-DBs to new table
  1512. if ($GLOBALS['cfgRelation']['commwork']) {
  1513. $this->renameSingleTable(
  1514. 'column_info',
  1515. $source_db, $target_db,
  1516. $source_table, $target_table,
  1517. 'db_name', 'table_name'
  1518. );
  1519. }
  1520. // updating bookmarks is not possible since only a single table is
  1521. // moved, and not the whole DB.
  1522. if ($GLOBALS['cfgRelation']['displaywork']) {
  1523. $this->renameSingleTable(
  1524. 'table_info',
  1525. $source_db, $target_db,
  1526. $source_table, $target_table,
  1527. 'db_name', 'table_name'
  1528. );
  1529. }
  1530. if ($GLOBALS['cfgRelation']['relwork']) {
  1531. $this->renameSingleTable(
  1532. 'relation',
  1533. $source_db, $target_db,
  1534. $source_table, $target_table,
  1535. 'foreign_db', 'foreign_table'
  1536. );
  1537. $this->renameSingleTable(
  1538. 'relation',
  1539. $source_db, $target_db,
  1540. $source_table, $target_table,
  1541. 'master_db', 'master_table'
  1542. );
  1543. }
  1544. if ($GLOBALS['cfgRelation']['pdfwork']) {
  1545. if ($source_db == $target_db) {
  1546. // rename within the database can be handled
  1547. $this->renameSingleTable(
  1548. 'table_coords',
  1549. $source_db, $target_db,
  1550. $source_table, $target_table,
  1551. 'db_name', 'table_name'
  1552. );
  1553. } else {
  1554. // if the table is moved out of the database we can no loger keep the
  1555. // record for table coordinate
  1556. $remove_query = "DELETE FROM "
  1557. . Util::backquote($GLOBALS['cfgRelation']['db']) . "."
  1558. . Util::backquote($GLOBALS['cfgRelation']['table_coords'])
  1559. . " WHERE db_name = '" . $GLOBALS['dbi']->escapeString($source_db) . "'"
  1560. . " AND table_name = '" . $GLOBALS['dbi']->escapeString($source_table)
  1561. . "'";
  1562. $this->queryAsControlUser($remove_query);
  1563. }
  1564. }
  1565. if ($GLOBALS['cfgRelation']['uiprefswork']) {
  1566. $this->renameSingleTable(
  1567. 'table_uiprefs',
  1568. $source_db, $target_db,
  1569. $source_table, $target_table,
  1570. 'db_name', 'table_name'
  1571. );
  1572. }
  1573. if ($GLOBALS['cfgRelation']['navwork']) {
  1574. // update hidden items inside table
  1575. $this->renameSingleTable(
  1576. 'navigationhiding',
  1577. $source_db, $target_db,
  1578. $source_table, $target_table,
  1579. 'db_name', 'table_name'
  1580. );
  1581. // update data for hidden table
  1582. $query = "UPDATE "
  1583. . Util::backquote($GLOBALS['cfgRelation']['db']) . "."
  1584. . Util::backquote(
  1585. $GLOBALS['cfgRelation']['navigationhiding']
  1586. )
  1587. . " SET db_name = '" . $GLOBALS['dbi']->escapeString($target_db)
  1588. . "',"
  1589. . " item_name = '" . $GLOBALS['dbi']->escapeString($target_table)
  1590. . "'"
  1591. . " WHERE db_name = '" . $GLOBALS['dbi']->escapeString($source_db)
  1592. . "'"
  1593. . " AND item_name = '" . $GLOBALS['dbi']->escapeString($source_table)
  1594. . "'"
  1595. . " AND item_type = 'table'";
  1596. $this->queryAsControlUser($query);
  1597. }
  1598. }
  1599. /**
  1600. * Create a PDF page
  1601. *
  1602. * @param string $newpage name of the new PDF page
  1603. * @param array $cfgRelation Relation configuration
  1604. * @param string $db database name
  1605. *
  1606. * @return int $pdf_page_number
  1607. */
  1608. public function createPage($newpage, array $cfgRelation, $db)
  1609. {
  1610. if (! isset($newpage) || $newpage == '') {
  1611. $newpage = __('no description');
  1612. }
  1613. $ins_query = 'INSERT INTO '
  1614. . Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
  1615. . Util::backquote($cfgRelation['pdf_pages'])
  1616. . ' (db_name, page_descr)'
  1617. . ' VALUES (\''
  1618. . $GLOBALS['dbi']->escapeString($db) . '\', \''
  1619. . $GLOBALS['dbi']->escapeString($newpage) . '\')';
  1620. $this->queryAsControlUser($ins_query, false);
  1621. return $GLOBALS['dbi']->insertId(DatabaseInterface::CONNECT_CONTROL);
  1622. }
  1623. /**
  1624. * Get child table references for a table column.
  1625. * This works only if 'DisableIS' is false. An empty array is returned otherwise.
  1626. *
  1627. * @param string $db name of master table db.
  1628. * @param string $table name of master table.
  1629. * @param string $column name of master table column.
  1630. *
  1631. * @return array $child_references
  1632. */
  1633. public function getChildReferences($db, $table, $column = '')
  1634. {
  1635. $child_references = array();
  1636. if (! $GLOBALS['cfg']['Server']['DisableIS']) {
  1637. $rel_query = "SELECT `column_name`, `table_name`,"
  1638. . " `table_schema`, `referenced_column_name`"
  1639. . " FROM `information_schema`.`key_column_usage`"
  1640. . " WHERE `referenced_table_name` = '"
  1641. . $GLOBALS['dbi']->escapeString($table) . "'"
  1642. . " AND `referenced_table_schema` = '"
  1643. . $GLOBALS['dbi']->escapeString($db) . "'";
  1644. if ($column) {
  1645. $rel_query .= " AND `referenced_column_name` = '"
  1646. . $GLOBALS['dbi']->escapeString($column) . "'";
  1647. }
  1648. $child_references = $GLOBALS['dbi']->fetchResult(
  1649. $rel_query, array('referenced_column_name', null)
  1650. );
  1651. }
  1652. return $child_references;
  1653. }
  1654. /**
  1655. * Check child table references and foreign key for a table column.
  1656. *
  1657. * @param string $db name of master table db.
  1658. * @param string $table name of master table.
  1659. * @param string $column name of master table column.
  1660. * @param array|null $foreigners_full foreiners array for the whole table.
  1661. * @param array|null $child_references_full child references for the whole table.
  1662. *
  1663. * @return array $column_status telling about references if foreign key.
  1664. */
  1665. public function checkChildForeignReferences(
  1666. $db, $table, $column, $foreigners_full = null, $child_references_full = null
  1667. ) {
  1668. $column_status = array();
  1669. $column_status['isEditable'] = false;
  1670. $column_status['isReferenced'] = false;
  1671. $column_status['isForeignKey'] = false;
  1672. $column_status['references'] = array();
  1673. $foreigners = array();
  1674. if ($foreigners_full !== null) {
  1675. if (isset($foreigners_full[$column])) {
  1676. $foreigners[$column] = $foreigners_full[$column];
  1677. }
  1678. if (isset($foreigners_full['foreign_keys_data'])) {
  1679. $foreigners['foreign_keys_data'] = $foreigners_full['foreign_keys_data'];
  1680. }
  1681. } else {
  1682. $foreigners = $this->getForeigners($db, $table, $column, 'foreign');
  1683. }
  1684. $foreigner = $this->searchColumnInForeigners($foreigners, $column);
  1685. $child_references = array();
  1686. if ($child_references_full !== null) {
  1687. if (isset($child_references_full[$column])) {
  1688. $child_references = $child_references_full[$column];
  1689. }
  1690. } else {
  1691. $child_references = $this->getChildReferences($db, $table, $column);
  1692. }
  1693. if (sizeof($child_references, 0) > 0
  1694. || $foreigner
  1695. ) {
  1696. if (sizeof($child_references, 0) > 0) {
  1697. $column_status['isReferenced'] = true;
  1698. foreach ($child_references as $columns) {
  1699. array_push(
  1700. $column_status['references'],
  1701. Util::backquote($columns['table_schema'])
  1702. . '.' . Util::backquote($columns['table_name'])
  1703. );
  1704. }
  1705. }
  1706. if ($foreigner) {
  1707. $column_status['isForeignKey'] = true;
  1708. }
  1709. } else {
  1710. $column_status['isEditable'] = true;
  1711. }
  1712. return $column_status;
  1713. }
  1714. /**
  1715. * Search a table column in foreign data.
  1716. *
  1717. * @param array $foreigners Table Foreign data
  1718. * @param string $column Column name
  1719. *
  1720. * @return bool|array
  1721. */
  1722. public function searchColumnInForeigners(array $foreigners, $column)
  1723. {
  1724. if (isset($foreigners[$column])) {
  1725. return $foreigners[$column];
  1726. }
  1727. $foreigner = array();
  1728. foreach ($foreigners['foreign_keys_data'] as $one_key) {
  1729. $column_index = array_search($column, $one_key['index_list']);
  1730. if ($column_index !== false) {
  1731. $foreigner['foreign_field']
  1732. = $one_key['ref_index_list'][$column_index];
  1733. $foreigner['foreign_db'] = isset($one_key['ref_db_name'])
  1734. ? $one_key['ref_db_name']
  1735. : $GLOBALS['db'];
  1736. $foreigner['foreign_table'] = $one_key['ref_table_name'];
  1737. $foreigner['constraint'] = $one_key['constraint'];
  1738. $foreigner['on_update'] = isset($one_key['on_update'])
  1739. ? $one_key['on_update']
  1740. : 'RESTRICT';
  1741. $foreigner['on_delete'] = isset($one_key['on_delete'])
  1742. ? $one_key['on_delete']
  1743. : 'RESTRICT';
  1744. return $foreigner;
  1745. }
  1746. }
  1747. return false;
  1748. }
  1749. /**
  1750. * Returns default PMA table names and their create queries.
  1751. *
  1752. * @return array table name, create query
  1753. */
  1754. public function getDefaultPmaTableNames()
  1755. {
  1756. $pma_tables = array();
  1757. $create_tables_file = file_get_contents(
  1758. SQL_DIR . 'create_tables.sql'
  1759. );
  1760. $queries = explode(';', $create_tables_file);
  1761. foreach ($queries as $query) {
  1762. if (preg_match(
  1763. '/CREATE TABLE IF NOT EXISTS `(.*)` \(/',
  1764. $query,
  1765. $table
  1766. )
  1767. ) {
  1768. $pma_tables[$table[1]] = $query . ';';
  1769. }
  1770. }
  1771. return $pma_tables;
  1772. }
  1773. /**
  1774. * Create a table named phpmyadmin to be used as configuration storage
  1775. *
  1776. * @return bool
  1777. */
  1778. public function createPmaDatabase()
  1779. {
  1780. $GLOBALS['dbi']->tryQuery("CREATE DATABASE IF NOT EXISTS `phpmyadmin`");
  1781. if ($error = $GLOBALS['dbi']->getError()) {
  1782. if ($GLOBALS['errno'] == 1044) {
  1783. $GLOBALS['message'] = __(
  1784. 'You do not have necessary privileges to create a database named'
  1785. . ' \'phpmyadmin\'. You may go to \'Operations\' tab of any'
  1786. . ' database to set up the phpMyAdmin configuration storage there.'
  1787. );
  1788. } else {
  1789. $GLOBALS['message'] = $error;
  1790. }
  1791. return false;
  1792. }
  1793. return true;
  1794. }
  1795. /**
  1796. * Creates PMA tables in the given db, updates if already exists.
  1797. *
  1798. * @param string $db database
  1799. * @param boolean $create whether to create tables if they don't exist.
  1800. *
  1801. * @return void
  1802. */
  1803. public function fixPmaTables($db, $create = true)
  1804. {
  1805. $tablesToFeatures = array(
  1806. 'pma__bookmark' => 'bookmarktable',
  1807. 'pma__relation' => 'relation',
  1808. 'pma__table_info' => 'table_info',
  1809. 'pma__table_coords' => 'table_coords',
  1810. 'pma__pdf_pages' => 'pdf_pages',
  1811. 'pma__column_info' => 'column_info',
  1812. 'pma__history' => 'history',
  1813. 'pma__recent' => 'recent',
  1814. 'pma__favorite' => 'favorite',
  1815. 'pma__table_uiprefs' => 'table_uiprefs',
  1816. 'pma__tracking' => 'tracking',
  1817. 'pma__userconfig' => 'userconfig',
  1818. 'pma__users' => 'users',
  1819. 'pma__usergroups' => 'usergroups',
  1820. 'pma__navigationhiding' => 'navigationhiding',
  1821. 'pma__savedsearches' => 'savedsearches',
  1822. 'pma__central_columns' => 'central_columns',
  1823. 'pma__designer_settings' => 'designer_settings',
  1824. 'pma__export_templates' => 'export_templates',
  1825. );
  1826. $existingTables = $GLOBALS['dbi']->getTables($db, DatabaseInterface::CONNECT_CONTROL);
  1827. $createQueries = null;
  1828. $foundOne = false;
  1829. foreach ($tablesToFeatures as $table => $feature) {
  1830. if (! in_array($table, $existingTables)) {
  1831. if ($create) {
  1832. if ($createQueries == null) { // first create
  1833. $createQueries = $this->getDefaultPmaTableNames();
  1834. $GLOBALS['dbi']->selectDb($db);
  1835. }
  1836. $GLOBALS['dbi']->tryQuery($createQueries[$table]);
  1837. if ($error = $GLOBALS['dbi']->getError()) {
  1838. $GLOBALS['message'] = $error;
  1839. return;
  1840. }
  1841. $foundOne = true;
  1842. $GLOBALS['cfg']['Server'][$feature] = $table;
  1843. }
  1844. } else {
  1845. $foundOne = true;
  1846. $GLOBALS['cfg']['Server'][$feature] = $table;
  1847. }
  1848. }
  1849. if (! $foundOne) {
  1850. return;
  1851. }
  1852. $GLOBALS['cfg']['Server']['pmadb'] = $db;
  1853. $_SESSION['relation'][$GLOBALS['server']] = $this->checkRelationsParam();
  1854. $cfgRelation = $this->getRelationsParam();
  1855. if ($cfgRelation['recentwork'] || $cfgRelation['favoritework']) {
  1856. // Since configuration storage is updated, we need to
  1857. // re-initialize the favorite and recent tables stored in the
  1858. // session from the current configuration storage.
  1859. if ($cfgRelation['favoritework']) {
  1860. $fav_tables = RecentFavoriteTable::getInstance('favorite');
  1861. $_SESSION['tmpval']['favorite_tables'][$GLOBALS['server']]
  1862. = $fav_tables->getFromDb();
  1863. }
  1864. if ($cfgRelation['recentwork']) {
  1865. $recent_tables = RecentFavoriteTable::getInstance('recent');
  1866. $_SESSION['tmpval']['recent_tables'][$GLOBALS['server']]
  1867. = $recent_tables->getFromDb();
  1868. }
  1869. // Reload navi panel to update the recent/favorite lists.
  1870. $GLOBALS['reload'] = true;
  1871. }
  1872. }
  1873. /**
  1874. * Get Html for PMA tables fixing anchor.
  1875. *
  1876. * @param boolean $allTables whether to create all tables
  1877. * @param boolean $createDb whether to create the pmadb also
  1878. *
  1879. * @return string Html
  1880. */
  1881. public function getHtmlFixPmaTables($allTables, $createDb = false)
  1882. {
  1883. $retval = '';
  1884. $url_query = Url::getCommon(array('db' => $GLOBALS['db']), '');
  1885. if ($allTables) {
  1886. if ($createDb) {
  1887. $url_query .= '&amp;goto=db_operations.php&amp;create_pmadb=1';
  1888. $message = Message::notice(
  1889. __(
  1890. '%sCreate%s a database named \'phpmyadmin\' and setup '
  1891. . 'the phpMyAdmin configuration storage there.'
  1892. )
  1893. );
  1894. } else {
  1895. $url_query .= '&amp;goto=db_operations.php&amp;fixall_pmadb=1';
  1896. $message = Message::notice(
  1897. __(
  1898. '%sCreate%s the phpMyAdmin configuration storage in the '
  1899. . 'current database.'
  1900. )
  1901. );
  1902. }
  1903. } else {
  1904. $url_query .= '&amp;goto=db_operations.php&amp;fix_pmadb=1';
  1905. $message = Message::notice(
  1906. __('%sCreate%s missing phpMyAdmin configuration storage tables.')
  1907. );
  1908. }
  1909. $message->addParamHtml('<a href="./chk_rel.php" data-post="' . $url_query . '">');
  1910. $message->addParamHtml('</a>');
  1911. $retval .= $message->getDisplay();
  1912. return $retval;
  1913. }
  1914. /**
  1915. * Gets the relations info and status, depending on the condition
  1916. *
  1917. * @param boolean $condition whether to look for foreigners or not
  1918. * @param string $db database name
  1919. * @param string $table table name
  1920. *
  1921. * @return array ($res_rel, $have_rel)
  1922. */
  1923. public function getRelationsAndStatus($condition, $db, $table)
  1924. {
  1925. if ($condition) {
  1926. // Find which tables are related with the current one and write it in
  1927. // an array
  1928. $res_rel = $this->getForeigners($db, $table);
  1929. if (count($res_rel) > 0) {
  1930. $have_rel = true;
  1931. } else {
  1932. $have_rel = false;
  1933. }
  1934. } else {
  1935. $have_rel = false;
  1936. $res_rel = array();
  1937. } // end if
  1938. return(array($res_rel, $have_rel));
  1939. }
  1940. /**
  1941. * Verifies if all the pmadb tables are defined
  1942. *
  1943. * @return boolean
  1944. */
  1945. public function arePmadbTablesDefined()
  1946. {
  1947. if (empty($GLOBALS['cfg']['Server']['bookmarktable'])
  1948. || empty($GLOBALS['cfg']['Server']['relation'])
  1949. || empty($GLOBALS['cfg']['Server']['table_info'])
  1950. || empty($GLOBALS['cfg']['Server']['table_coords'])
  1951. || empty($GLOBALS['cfg']['Server']['column_info'])
  1952. || empty($GLOBALS['cfg']['Server']['pdf_pages'])
  1953. || empty($GLOBALS['cfg']['Server']['history'])
  1954. || empty($GLOBALS['cfg']['Server']['recent'])
  1955. || empty($GLOBALS['cfg']['Server']['favorite'])
  1956. || empty($GLOBALS['cfg']['Server']['table_uiprefs'])
  1957. || empty($GLOBALS['cfg']['Server']['tracking'])
  1958. || empty($GLOBALS['cfg']['Server']['userconfig'])
  1959. || empty($GLOBALS['cfg']['Server']['users'])
  1960. || empty($GLOBALS['cfg']['Server']['usergroups'])
  1961. || empty($GLOBALS['cfg']['Server']['navigationhiding'])
  1962. || empty($GLOBALS['cfg']['Server']['savedsearches'])
  1963. || empty($GLOBALS['cfg']['Server']['central_columns'])
  1964. || empty($GLOBALS['cfg']['Server']['designer_settings'])
  1965. || empty($GLOBALS['cfg']['Server']['export_templates'])
  1966. ) {
  1967. return false;
  1968. }
  1969. return true;
  1970. }
  1971. /**
  1972. * Get tables for foreign key constraint
  1973. *
  1974. * @param string $foreignDb Database name
  1975. * @param string $tblStorageEngine Table storage engine
  1976. *
  1977. * @return array Table names
  1978. */
  1979. public function getTables($foreignDb, $tblStorageEngine)
  1980. {
  1981. $tables = array();
  1982. $tablesRows = $GLOBALS['dbi']->query(
  1983. 'SHOW TABLE STATUS FROM ' . Util::backquote($foreignDb),
  1984. DatabaseInterface::CONNECT_USER,
  1985. DatabaseInterface::QUERY_STORE
  1986. );
  1987. while ($row = $GLOBALS['dbi']->fetchRow($tablesRows)) {
  1988. if (isset($row[1]) && mb_strtoupper($row[1]) == $tblStorageEngine) {
  1989. $tables[] = $row[0];
  1990. }
  1991. }
  1992. if ($GLOBALS['cfg']['NaturalOrder']) {
  1993. usort($tables, 'strnatcasecmp');
  1994. }
  1995. return $tables;
  1996. }
  1997. }