Translated using Weblate (Slovenian)
[phpmyadmin.git] / libraries / relation.lib.php
blobe590f49fa8558b865254f154b6262b1749128d70
1 <?php
2 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 /**
4 * Set of functions used with the relation and pdf feature
6 * @package PhpMyAdmin
7 */
8 use PMA\libraries\Message;
9 use PMA\libraries\Table;
10 use PMA\libraries\RecentFavoriteTable;
11 use PMA\libraries\URL;
13 /**
14 * Executes a query as controluser if possible, otherwise as normal user
16 * @param string $sql the query to execute
17 * @param boolean $show_error whether to display SQL error messages or not
18 * @param int $options query options
20 * @return resource|boolean the result set, or false if no result set
22 * @access public
25 function PMA_queryAsControlUser($sql, $show_error = true, $options = 0)
27 // Avoid caching of the number of rows affected; for example, this function
28 // is called for tracking purposes but we want to display the correct number
29 // of rows affected by the original query, not by the query generated for
30 // tracking.
31 $cache_affected_rows = false;
33 if ($show_error) {
34 $result = $GLOBALS['dbi']->query(
35 $sql,
36 $GLOBALS['controllink'],
37 $options,
38 $cache_affected_rows
40 } else {
41 $result = @$GLOBALS['dbi']->tryQuery(
42 $sql,
43 $GLOBALS['controllink'],
44 $options,
45 $cache_affected_rows
47 } // end if... else...
49 if ($result) {
50 return $result;
51 } else {
52 return false;
54 } // end of the "PMA_queryAsControlUser()" function
56 /**
57 * Returns current relation parameters
59 * @return array $cfgRelation
61 function PMA_getRelationsParam()
63 if (empty($_SESSION['relation'][$GLOBALS['server']])
64 || (empty($_SESSION['relation'][$GLOBALS['server']]['PMA_VERSION']))
65 || $_SESSION['relation'][$GLOBALS['server']]['PMA_VERSION'] != PMA_VERSION
66 ) {
67 $_SESSION['relation'][$GLOBALS['server']] = PMA_checkRelationsParam();
70 // just for BC but needs to be before PMA_getRelationsParamDiagnostic()
71 // which uses it
72 $GLOBALS['cfgRelation'] = $_SESSION['relation'][$GLOBALS['server']];
74 return $_SESSION['relation'][$GLOBALS['server']];
77 /**
78 * prints out diagnostic info for pma relation feature
80 * @param array $cfgRelation Relation configuration
82 * @return string
84 function PMA_getRelationsParamDiagnostic($cfgRelation)
86 $retval = '<br>';
88 $messages = array();
89 $messages['error'] = '<span style="color:red"><strong>'
90 . __('not OK')
91 . '</strong></span>';
93 $messages['ok'] = '<span style="color:green"><strong>'
94 . _pgettext('Correctly working', 'OK')
95 . '</strong></span>';
97 $messages['enabled'] = '<span style="color:green">' . __('Enabled') . '</span>';
98 $messages['disabled'] = '<span style="color:red">' . __('Disabled') . '</span>';
100 if (empty($cfgRelation['db'])) {
101 $retval .= __('Configuration of pmadb…') . ' '
102 . $messages['error']
103 . PMA\libraries\Util::showDocu('setup', 'linked-tables')
104 . '<br />' . "\n"
105 . __('General relation features')
106 . ' <font color="green">' . __('Disabled')
107 . '</font>' . "\n";
108 if ($GLOBALS['cfg']['ZeroConf']) {
109 if (empty($GLOBALS['db'])) {
110 $retval .= PMA_getHtmlFixPMATables(true, true);
111 } else {
112 $retval .= PMA_getHtmlFixPMATables(true);
115 } else {
116 $retval .= '<table>' . "\n";
118 if (! $cfgRelation['allworks']
119 && $GLOBALS['cfg']['ZeroConf']
120 // Avoid showing a "Create missing tables" link if it's a
121 // problem of missing definition
122 && PMA_arePmadbTablesDefined()
124 $retval .= PMA_getHtmlFixPMATables(false);
125 $retval .= '<br />';
128 $retval .= PMA_getDiagMessageForParameter(
129 'pmadb',
130 $cfgRelation['db'],
131 $messages,
132 'pmadb'
134 $retval .= PMA_getDiagMessageForParameter(
135 'relation',
136 isset($cfgRelation['relation']),
137 $messages,
138 'relation'
140 $retval .= PMA_getDiagMessageForFeature(
141 __('General relation features'),
142 'relwork',
143 $messages
145 $retval .= PMA_getDiagMessageForParameter(
146 'table_info',
147 isset($cfgRelation['table_info']),
148 $messages,
149 'table_info'
151 $retval .= PMA_getDiagMessageForFeature(
152 __('Display Features'),
153 'displaywork',
154 $messages
156 $retval .= PMA_getDiagMessageForParameter(
157 'table_coords',
158 isset($cfgRelation['table_coords']),
159 $messages,
160 'table_coords'
162 $retval .= PMA_getDiagMessageForParameter(
163 'pdf_pages',
164 isset($cfgRelation['pdf_pages']),
165 $messages,
166 'pdf_pages'
168 $retval .= PMA_getDiagMessageForFeature(
169 __('Designer and creation of PDFs'),
170 'pdfwork',
171 $messages
173 $retval .= PMA_getDiagMessageForParameter(
174 'column_info',
175 isset($cfgRelation['column_info']),
176 $messages,
177 'column_info'
179 $retval .= PMA_getDiagMessageForFeature(
180 __('Displaying Column Comments'),
181 'commwork',
182 $messages,
183 false
185 $retval .= PMA_getDiagMessageForFeature(
186 __('Browser transformation'),
187 'mimework',
188 $messages
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.'
196 $retval .= PMA\libraries\Util::showDocu(
197 'config',
198 'cfg_Servers_column_info'
200 $retval .= '</td></tr>';
202 $retval .= PMA_getDiagMessageForParameter(
203 'bookmarktable',
204 isset($cfgRelation['bookmark']),
205 $messages,
206 'bookmark'
208 $retval .= PMA_getDiagMessageForFeature(
209 __('Bookmarked SQL query'),
210 'bookmarkwork',
211 $messages
213 $retval .= PMA_getDiagMessageForParameter(
214 'history',
215 isset($cfgRelation['history']),
216 $messages,
217 'history'
219 $retval .= PMA_getDiagMessageForFeature(
220 __('SQL history'),
221 'historywork',
222 $messages
224 $retval .= PMA_getDiagMessageForParameter(
225 'recent',
226 isset($cfgRelation['recent']),
227 $messages,
228 'recent'
230 $retval .= PMA_getDiagMessageForFeature(
231 __('Persistent recently used tables'),
232 'recentwork',
233 $messages
235 $retval .= PMA_getDiagMessageForParameter(
236 'favorite',
237 isset($cfgRelation['favorite']),
238 $messages,
239 'favorite'
241 $retval .= PMA_getDiagMessageForFeature(
242 __('Persistent favorite tables'),
243 'favoritework',
244 $messages
246 $retval .= PMA_getDiagMessageForParameter(
247 'table_uiprefs',
248 isset($cfgRelation['table_uiprefs']),
249 $messages,
250 'table_uiprefs'
252 $retval .= PMA_getDiagMessageForFeature(
253 __('Persistent tables\' UI preferences'),
254 'uiprefswork',
255 $messages
257 $retval .= PMA_getDiagMessageForParameter(
258 'tracking',
259 isset($cfgRelation['tracking']),
260 $messages,
261 'tracking'
263 $retval .= PMA_getDiagMessageForFeature(
264 __('Tracking'),
265 'trackingwork',
266 $messages
268 $retval .= PMA_getDiagMessageForParameter(
269 'userconfig',
270 isset($cfgRelation['userconfig']),
271 $messages,
272 'userconfig'
274 $retval .= PMA_getDiagMessageForFeature(
275 __('User preferences'),
276 'userconfigwork',
277 $messages
279 $retval .= PMA_getDiagMessageForParameter(
280 'users',
281 isset($cfgRelation['users']),
282 $messages,
283 'users'
285 $retval .= PMA_getDiagMessageForParameter(
286 'usergroups',
287 isset($cfgRelation['usergroups']),
288 $messages,
289 'usergroups'
291 $retval .= PMA_getDiagMessageForFeature(
292 __('Configurable menus'),
293 'menuswork',
294 $messages
296 $retval .= PMA_getDiagMessageForParameter(
297 'navigationhiding',
298 isset($cfgRelation['navigationhiding']),
299 $messages,
300 'navigationhiding'
302 $retval .= PMA_getDiagMessageForFeature(
303 __('Hide/show navigation items'),
304 'navwork',
305 $messages
307 $retval .= PMA_getDiagMessageForParameter(
308 'savedsearches',
309 isset($cfgRelation['savedsearches']),
310 $messages,
311 'savedsearches'
313 $retval .= PMA_getDiagMessageForFeature(
314 __('Saving Query-By-Example searches'),
315 'savedsearcheswork',
316 $messages
318 $retval .= PMA_getDiagMessageForParameter(
319 'central_columns',
320 isset($cfgRelation['central_columns']),
321 $messages,
322 'central_columns'
324 $retval .= PMA_getDiagMessageForFeature(
325 __('Managing Central list of columns'),
326 'centralcolumnswork',
327 $messages
329 $retval .= PMA_getDiagMessageForParameter(
330 'designer_settings',
331 isset($cfgRelation['designer_settings']),
332 $messages,
333 'designer_settings'
335 $retval .= PMA_getDiagMessageForFeature(
336 __('Remembering Designer Settings'),
337 'designersettingswork',
338 $messages
340 $retval .= PMA_getDiagMessageForParameter(
341 'export_templates',
342 isset($cfgRelation['export_templates']),
343 $messages,
344 'export_templates'
346 $retval .= PMA_getDiagMessageForFeature(
347 __('Saving export templates'),
348 'exporttemplateswork',
349 $messages
351 $retval .= '</table>' . "\n";
353 if (! $cfgRelation['allworks']) {
355 $retval .= '<p>' . __('Quick steps to set up advanced features:')
356 . '</p>';
358 $items = array();
359 $items[] = sprintf(
361 'Create the needed tables with the '
362 . '<code>%screate_tables.sql</code>.'
364 htmlspecialchars(SQL_DIR)
365 ) . ' ' . PMA\libraries\Util::showDocu('setup', 'linked-tables');
366 $items[] = __('Create a pma user and give access to these tables.') . ' '
367 . PMA\libraries\Util::showDocu('config', 'cfg_Servers_controluser');
368 $items[] = __(
369 'Enable advanced features in configuration file '
370 . '(<code>config.inc.php</code>), for example by '
371 . 'starting from <code>config.sample.inc.php</code>.'
372 ) . ' ' . PMA\libraries\Util::showDocu('setup', 'quick-install');
373 $items[] = __(
374 'Re-login to phpMyAdmin to load the updated configuration file.'
377 $retval .= PMA\libraries\Template::get('list/unordered')->render(
378 array('items' => $items,)
383 return $retval;
387 * prints out one diagnostic message for a feature
389 * @param string $feature_name feature name in a message string
390 * @param string $relation_parameter the $GLOBALS['cfgRelation'] parameter to check
391 * @param array $messages utility messages
392 * @param boolean $skip_line whether to skip a line after the message
394 * @return string
396 function PMA_getDiagMessageForFeature($feature_name,
397 $relation_parameter, $messages, $skip_line = true
399 $retval = ' <tr><td colspan=2 class="right">' . $feature_name . ': ';
400 if (isset($GLOBALS['cfgRelation'][$relation_parameter])
401 && $GLOBALS['cfgRelation'][$relation_parameter]
403 $retval .= $messages['enabled'];
404 } else {
405 $retval .= $messages['disabled'];
407 $retval .= '</td></tr>';
408 if ($skip_line) {
409 $retval .= '<tr><td>&nbsp;</td></tr>';
411 return $retval;
415 * prints out one diagnostic message for a configuration parameter
417 * @param string $parameter config parameter name to display
418 * @param boolean $relationParameterSet whether this parameter is set
419 * @param array $messages utility messages
420 * @param string $docAnchor anchor in documentation
422 * @return string
424 function PMA_getDiagMessageForParameter($parameter,
425 $relationParameterSet, $messages, $docAnchor
427 $retval = '<tr><th class="left">';
428 $retval .= '$cfg[\'Servers\'][$i][\'' . $parameter . '\'] ... ';
429 $retval .= '</th><td class="right">';
430 if ($relationParameterSet) {
431 $retval .= $messages['ok'];
432 } else {
433 $retval .= sprintf(
434 $messages['error'],
435 PMA\libraries\Util::getDocuLink('config', 'cfg_Servers_' . $docAnchor)
438 $retval .= '</td></tr>' . "\n";
439 return $retval;
444 * Defines the relation parameters for the current user
445 * just a copy of the functions used for relations ;-)
446 * but added some stuff to check what will work
448 * @access protected
449 * @return array the relation parameters for the current user
451 function PMA_checkRelationsParam()
453 $cfgRelation = array();
454 $cfgRelation['PMA_VERSION'] = PMA_VERSION;
456 $workToTable = array(
457 'relwork' => 'relation',
458 'displaywork' => array('relation', 'table_info'),
459 'bookmarkwork' => 'bookmarktable',
460 'pdfwork' => array('table_coords', 'pdf_pages'),
461 'commwork' => 'column_info',
462 'mimework' => 'column_info',
463 'historywork' => 'history',
464 'recentwork' => 'recent',
465 'favoritework' => 'favorite',
466 'uiprefswork' => 'table_uiprefs',
467 'trackingwork' => 'tracking',
468 'userconfigwork' => 'userconfig',
469 'menuswork' => array('users', 'usergroups'),
470 'navwork' => 'navigationhiding',
471 'savedsearcheswork' => 'savedsearches',
472 'centralcolumnswork' => 'central_columns',
473 'designersettingswork' => 'designer_settings',
474 'exporttemplateswork' => 'export_templates',
477 foreach ($workToTable as $work => $table) {
478 $cfgRelation[$work] = false;
480 $cfgRelation['allworks'] = false;
481 $cfgRelation['user'] = null;
482 $cfgRelation['db'] = null;
484 if ($GLOBALS['server'] == 0
485 || empty($GLOBALS['cfg']['Server']['pmadb'])
486 || empty($GLOBALS['controllink'])
487 || ! $GLOBALS['dbi']->selectDb(
488 $GLOBALS['cfg']['Server']['pmadb'], $GLOBALS['controllink']
491 // No server selected -> no bookmark table
492 // we return the array with the falses in it,
493 // to avoid some 'Uninitialized string offset' errors later
494 $GLOBALS['cfg']['Server']['pmadb'] = false;
495 return $cfgRelation;
498 $cfgRelation['user'] = $GLOBALS['cfg']['Server']['user'];
499 $cfgRelation['db'] = $GLOBALS['cfg']['Server']['pmadb'];
501 // Now I just check if all tables that i need are present so I can for
502 // example enable relations but not pdf...
503 // I was thinking of checking if they have all required columns but I
504 // fear it might be too slow
506 $tab_query = 'SHOW TABLES FROM '
507 . PMA\libraries\Util::backquote(
508 $GLOBALS['cfg']['Server']['pmadb']
510 $tab_rs = PMA_queryAsControlUser(
511 $tab_query, false, PMA\libraries\DatabaseInterface::QUERY_STORE
514 if (! $tab_rs) {
515 // query failed ... ?
516 //$GLOBALS['cfg']['Server']['pmadb'] = false;
517 return $cfgRelation;
520 while ($curr_table = @$GLOBALS['dbi']->fetchRow($tab_rs)) {
521 if ($curr_table[0] == $GLOBALS['cfg']['Server']['bookmarktable']) {
522 $cfgRelation['bookmark'] = $curr_table[0];
523 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['relation']) {
524 $cfgRelation['relation'] = $curr_table[0];
525 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_info']) {
526 $cfgRelation['table_info'] = $curr_table[0];
527 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_coords']) {
528 $cfgRelation['table_coords'] = $curr_table[0];
529 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['column_info']) {
530 $cfgRelation['column_info'] = $curr_table[0];
531 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['pdf_pages']) {
532 $cfgRelation['pdf_pages'] = $curr_table[0];
533 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['history']) {
534 $cfgRelation['history'] = $curr_table[0];
535 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['recent']) {
536 $cfgRelation['recent'] = $curr_table[0];
537 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['favorite']) {
538 $cfgRelation['favorite'] = $curr_table[0];
539 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_uiprefs']) {
540 $cfgRelation['table_uiprefs'] = $curr_table[0];
541 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['tracking']) {
542 $cfgRelation['tracking'] = $curr_table[0];
543 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['userconfig']) {
544 $cfgRelation['userconfig'] = $curr_table[0];
545 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['users']) {
546 $cfgRelation['users'] = $curr_table[0];
547 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['usergroups']) {
548 $cfgRelation['usergroups'] = $curr_table[0];
549 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['navigationhiding']) {
550 $cfgRelation['navigationhiding'] = $curr_table[0];
551 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['savedsearches']) {
552 $cfgRelation['savedsearches'] = $curr_table[0];
553 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['central_columns']) {
554 $cfgRelation['central_columns'] = $curr_table[0];
555 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['designer_settings']) {
556 $cfgRelation['designer_settings'] = $curr_table[0];
557 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['export_templates']) {
558 $cfgRelation['export_templates'] = $curr_table[0];
560 } // end while
561 $GLOBALS['dbi']->freeResult($tab_rs);
563 if (isset($cfgRelation['relation'])) {
564 $cfgRelation['relwork'] = true;
567 if (isset($cfgRelation['relation']) && isset($cfgRelation['table_info'])) {
568 $cfgRelation['displaywork'] = true;
571 if (isset($cfgRelation['table_coords']) && isset($cfgRelation['pdf_pages'])) {
572 $cfgRelation['pdfwork'] = true;
575 if (isset($cfgRelation['column_info'])) {
576 $cfgRelation['commwork'] = true;
577 // phpMyAdmin 4.3+
578 // Check for input transformations upgrade.
579 $cfgRelation['mimework'] = PMA_tryUpgradeTransformations();
582 if (isset($cfgRelation['history'])) {
583 $cfgRelation['historywork'] = true;
586 if (isset($cfgRelation['recent'])) {
587 $cfgRelation['recentwork'] = true;
590 if (isset($cfgRelation['favorite'])) {
591 $cfgRelation['favoritework'] = true;
594 if (isset($cfgRelation['table_uiprefs'])) {
595 $cfgRelation['uiprefswork'] = true;
598 if (isset($cfgRelation['tracking'])) {
599 $cfgRelation['trackingwork'] = true;
602 if (isset($cfgRelation['userconfig'])) {
603 $cfgRelation['userconfigwork'] = true;
606 if (isset($cfgRelation['bookmark'])) {
607 $cfgRelation['bookmarkwork'] = true;
610 if (isset($cfgRelation['users']) && isset($cfgRelation['usergroups'])) {
611 $cfgRelation['menuswork'] = true;
614 if (isset($cfgRelation['navigationhiding'])) {
615 $cfgRelation['navwork'] = true;
618 if (isset($cfgRelation['savedsearches'])) {
619 $cfgRelation['savedsearcheswork'] = true;
622 if (isset($cfgRelation['central_columns'])) {
623 $cfgRelation['centralcolumnswork'] = true;
626 if (isset($cfgRelation['designer_settings'])) {
627 $cfgRelation['designersettingswork'] = true;
630 if (isset($cfgRelation['export_templates'])) {
631 $cfgRelation['exporttemplateswork'] = true;
634 $allWorks = true;
635 foreach ($workToTable as $work => $table) {
636 if (! $cfgRelation[$work]) {
637 if (is_string($table)) {
638 if (isset($GLOBALS['cfg']['Server'][$table])
639 && $GLOBALS['cfg']['Server'][$table] !== false
641 $allWorks = false;
642 break;
644 } else if (is_array($table)) {
645 $oneNull = false;
646 foreach ($table as $t) {
647 if (isset($GLOBALS['cfg']['Server'][$t])
648 && $GLOBALS['cfg']['Server'][$t] === false
650 $oneNull = true;
651 break;
654 if (! $oneNull) {
655 $allWorks = false;
656 break;
661 $cfgRelation['allworks'] = $allWorks;
663 return $cfgRelation;
664 } // end of the 'PMA_checkRelationsParam()' function
667 * Check whether column_info table input transformation
668 * upgrade is required and try to upgrade silently
670 * @return bool false if upgrade failed
672 * @access public
674 function PMA_tryUpgradeTransformations()
676 // From 4.3, new input oriented transformation feature was introduced.
677 // Check whether column_info table has input transformation columns
678 $new_cols = array(
679 "input_transformation",
680 "input_transformation_options"
682 $query = 'SHOW COLUMNS FROM '
683 . PMA\libraries\Util::backquote($GLOBALS['cfg']['Server']['pmadb'])
684 . '.' . PMA\libraries\Util::backquote(
685 $GLOBALS['cfg']['Server']['column_info']
687 . ' WHERE Field IN (\'' . implode('\', \'', $new_cols) . '\')';
688 $result = PMA_queryAsControlUser(
689 $query, false, PMA\libraries\DatabaseInterface::QUERY_STORE
691 if ($result) {
692 $rows = $GLOBALS['dbi']->numRows($result);
693 $GLOBALS['dbi']->freeResult($result);
694 // input transformations are present
695 // no need to upgrade
696 if ($rows === 2) {
697 return true;
698 // try silent upgrade without disturbing the user
699 } else {
700 // read upgrade query file
701 $query = @file_get_contents(SQL_DIR . 'upgrade_column_info_4_3_0+.sql');
702 // replace database name from query to with set in config.inc.php
703 $query = str_replace(
704 '`phpmyadmin`',
705 PMA\libraries\Util::backquote($GLOBALS['cfg']['Server']['pmadb']),
706 $query
708 // replace pma__column_info table name from query
709 // to with set in config.inc.php
710 $query = str_replace(
711 '`pma__column_info`',
712 PMA\libraries\Util::backquote(
713 $GLOBALS['cfg']['Server']['column_info']
715 $query
717 $GLOBALS['dbi']->tryMultiQuery($query, $GLOBALS['controllink']);
718 // skips result sets of query as we are not interested in it
719 while ($GLOBALS['dbi']->moreResults($GLOBALS['controllink'])
720 && $GLOBALS['dbi']->nextResult($GLOBALS['controllink'])
723 $error = $GLOBALS['dbi']->getError($GLOBALS['controllink']);
724 // return true if no error exists otherwise false
725 return empty($error);
728 // some failure, either in upgrading or something else
729 // make some noise, time to wake up user.
730 return false;
734 * Gets all Relations to foreign tables for a given table or
735 * optionally a given column in a table
737 * @param string $db the name of the db to check for
738 * @param string $table the name of the table to check for
739 * @param string $column the name of the column to check for
740 * @param string $source the source for foreign key information
742 * @return array db,table,column
744 * @access public
746 function PMA_getForeigners($db, $table, $column = '', $source = 'both')
748 $cfgRelation = PMA_getRelationsParam();
749 $foreign = array();
751 if ($cfgRelation['relwork'] && ($source == 'both' || $source == 'internal')) {
752 $rel_query = '
753 SELECT `master_field`,
754 `foreign_db`,
755 `foreign_table`,
756 `foreign_field`
757 FROM ' . PMA\libraries\Util::backquote($cfgRelation['db'])
758 . '.' . PMA\libraries\Util::backquote($cfgRelation['relation']) . '
759 WHERE `master_db` = \'' . $GLOBALS['dbi']->escapeString($db) . '\'
760 AND `master_table` = \'' . $GLOBALS['dbi']->escapeString($table)
761 . '\' ';
762 if (strlen($column) > 0) {
763 $rel_query .= ' AND `master_field` = '
764 . '\'' . $GLOBALS['dbi']->escapeString($column) . '\'';
766 $foreign = $GLOBALS['dbi']->fetchResult(
767 $rel_query, 'master_field', null, $GLOBALS['controllink']
771 if (($source == 'both' || $source == 'foreign') && strlen($table) > 0) {
772 $tableObj = new Table($table, $db);
773 $show_create_table = $tableObj->showCreate();
774 if ($show_create_table) {
775 $parser = new \PhpMyAdmin\SqlParser\Parser($show_create_table);
777 * @var \PhpMyAdmin\SqlParser\Statements\CreateStatement $stmt
779 $stmt = $parser->statements[0];
780 $foreign['foreign_keys_data'] = \PhpMyAdmin\SqlParser\Utils\Table::getForeignKeys(
781 $stmt
787 * Emulating relations for some information_schema tables
789 $isInformationSchema = mb_strtolower($db) == 'information_schema';
790 $isMysql = mb_strtolower($db) == 'mysql';
791 if (($isInformationSchema || $isMysql)
792 && ($source == 'internal' || $source == 'both')
794 if ($isInformationSchema) {
795 $relations_key = 'information_schema_relations';
796 include_once './libraries/information_schema_relations.lib.php';
797 } else {
798 $relations_key = 'mysql_relations';
799 include_once './libraries/mysql_relations.lib.php';
801 if (isset($GLOBALS[$relations_key][$table])) {
802 foreach ($GLOBALS[$relations_key][$table] as $field => $relations) {
803 if ((strlen($column) === 0 || $column == $field)
804 && (! isset($foreign[$field])
805 || strlen($foreign[$field]) === 0)
807 $foreign[$field] = $relations;
813 return $foreign;
814 } // end of the 'PMA_getForeigners()' function
817 * Gets the display field of a table
819 * @param string $db the name of the db to check for
820 * @param string $table the name of the table to check for
822 * @return string field name
824 * @access public
826 function PMA_getDisplayField($db, $table)
828 $cfgRelation = PMA_getRelationsParam();
831 * Try to fetch the display field from DB.
833 if ($cfgRelation['displaywork']) {
834 $disp_query = '
835 SELECT `display_field`
836 FROM ' . PMA\libraries\Util::backquote($cfgRelation['db'])
837 . '.' . PMA\libraries\Util::backquote($cfgRelation['table_info']) . '
838 WHERE `db_name` = \'' . $GLOBALS['dbi']->escapeString($db) . '\'
839 AND `table_name` = \'' . $GLOBALS['dbi']->escapeString($table)
840 . '\'';
842 $row = $GLOBALS['dbi']->fetchSingleRow(
843 $disp_query, 'ASSOC', $GLOBALS['controllink']
845 if (isset($row['display_field'])) {
846 return $row['display_field'];
851 * Emulating the display field for some information_schema tables.
853 if ($db == 'information_schema') {
854 switch ($table) {
855 case 'CHARACTER_SETS':
856 return 'DESCRIPTION';
857 case 'TABLES':
858 return 'TABLE_COMMENT';
863 * No Luck...
865 return false;
867 } // end of the 'PMA_getDisplayField()' function
870 * Gets the comments for all columns of a table or the db itself
872 * @param string $db the name of the db to check for
873 * @param string $table the name of the table to check for
875 * @return array [column_name] = comment
877 * @access public
879 function PMA_getComments($db, $table = '')
881 $comments = array();
883 if ($table != '') {
884 // MySQL native column comments
885 $columns = $GLOBALS['dbi']->getColumns($db, $table, null, true);
886 if ($columns) {
887 foreach ($columns as $column) {
888 if (! empty($column['Comment'])) {
889 $comments[$column['Field']] = $column['Comment'];
893 } else {
894 $comments[] = PMA_getDbComment($db);
897 return $comments;
898 } // end of the 'PMA_getComments()' function
901 * Gets the comment for a db
903 * @param string $db the name of the db to check for
905 * @return string comment
907 * @access public
909 function PMA_getDbComment($db)
911 $cfgRelation = PMA_getRelationsParam();
912 $comment = '';
914 if ($cfgRelation['commwork']) {
915 // pmadb internal db comment
916 $com_qry = "
917 SELECT `comment`
918 FROM " . PMA\libraries\Util::backquote($cfgRelation['db'])
919 . "." . PMA\libraries\Util::backquote($cfgRelation['column_info'])
921 WHERE db_name = '" . $GLOBALS['dbi']->escapeString($db) . "'
922 AND table_name = ''
923 AND column_name = '(db_comment)'";
924 $com_rs = PMA_queryAsControlUser(
925 $com_qry, true, PMA\libraries\DatabaseInterface::QUERY_STORE
928 if ($com_rs && $GLOBALS['dbi']->numRows($com_rs) > 0) {
929 $row = $GLOBALS['dbi']->fetchAssoc($com_rs);
930 $comment = $row['comment'];
932 $GLOBALS['dbi']->freeResult($com_rs);
935 return $comment;
936 } // end of the 'PMA_getDbComment()' function
939 * Gets the comment for a db
941 * @access public
943 * @return string comment
945 function PMA_getDbComments()
947 $cfgRelation = PMA_getRelationsParam();
948 $comments = array();
950 if ($cfgRelation['commwork']) {
951 // pmadb internal db comment
952 $com_qry = "
953 SELECT `db_name`, `comment`
954 FROM " . PMA\libraries\Util::backquote($cfgRelation['db'])
955 . "." . PMA\libraries\Util::backquote($cfgRelation['column_info'])
957 WHERE `column_name` = '(db_comment)'";
958 $com_rs = PMA_queryAsControlUser(
959 $com_qry, true, PMA\libraries\DatabaseInterface::QUERY_STORE
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'];
967 $GLOBALS['dbi']->freeResult($com_rs);
970 return $comments;
971 } // end of the 'PMA_getDbComments()' function
974 * Set a database comment to a certain value.
976 * @param string $db the name of the db
977 * @param string $comment the value of the column
979 * @return boolean true, if comment-query was made.
981 * @access public
983 function PMA_setDbComment($db, $comment = '')
985 $cfgRelation = PMA_getRelationsParam();
987 if (! $cfgRelation['commwork']) {
988 return false;
991 if (strlen($comment) > 0) {
992 $upd_query = 'INSERT INTO '
993 . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
994 . PMA\libraries\Util::backquote($cfgRelation['column_info'])
995 . ' (`db_name`, `table_name`, `column_name`, `comment`)'
996 . ' VALUES (\''
997 . $GLOBALS['dbi']->escapeString($db)
998 . "', '', '(db_comment)', '"
999 . $GLOBALS['dbi']->escapeString($comment)
1000 . "') "
1001 . ' ON DUPLICATE KEY UPDATE '
1002 . "`comment` = '" . $GLOBALS['dbi']->escapeString($comment) . "'";
1003 } else {
1004 $upd_query = 'DELETE FROM '
1005 . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
1006 . PMA\libraries\Util::backquote($cfgRelation['column_info'])
1007 . ' WHERE `db_name` = \'' . $GLOBALS['dbi']->escapeString($db)
1008 . '\'
1009 AND `table_name` = \'\'
1010 AND `column_name` = \'(db_comment)\'';
1013 if (isset($upd_query)) {
1014 return PMA_queryAsControlUser($upd_query);
1017 return false;
1018 } // end of 'PMA_setDbComment()' function
1021 * Set a SQL history entry
1023 * @param string $db the name of the db
1024 * @param string $table the name of the table
1025 * @param string $username the username
1026 * @param string $sqlquery the sql query
1028 * @return void
1030 * @access public
1032 function PMA_setHistory($db, $table, $username, $sqlquery)
1034 $maxCharactersInDisplayedSQL = $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'];
1035 // Prevent to run this automatically on Footer class destroying in testsuite
1036 if (defined('TESTSUITE')
1037 || mb_strlen($sqlquery) > $maxCharactersInDisplayedSQL
1039 return;
1042 $cfgRelation = PMA_getRelationsParam();
1044 if (! isset($_SESSION['sql_history'])) {
1045 $_SESSION['sql_history'] = array();
1048 $_SESSION['sql_history'][] = array(
1049 'db' => $db,
1050 'table' => $table,
1051 'sqlquery' => $sqlquery,
1054 if (count($_SESSION['sql_history']) > $GLOBALS['cfg']['QueryHistoryMax']) {
1055 // history should not exceed a maximum count
1056 array_shift($_SESSION['sql_history']);
1059 if (! $cfgRelation['historywork'] || ! $GLOBALS['cfg']['QueryHistoryDB']) {
1060 return;
1063 PMA_queryAsControlUser(
1064 'INSERT INTO '
1065 . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
1066 . PMA\libraries\Util::backquote($cfgRelation['history']) . '
1067 (`username`,
1068 `db`,
1069 `table`,
1070 `timevalue`,
1071 `sqlquery`)
1072 VALUES
1073 (\'' . $GLOBALS['dbi']->escapeString($username) . '\',
1074 \'' . $GLOBALS['dbi']->escapeString($db) . '\',
1075 \'' . $GLOBALS['dbi']->escapeString($table) . '\',
1076 NOW(),
1077 \'' . $GLOBALS['dbi']->escapeString($sqlquery) . '\')'
1080 PMA_purgeHistory($username);
1082 } // end of 'PMA_setHistory()' function
1085 * Gets a SQL history entry
1087 * @param string $username the username
1089 * @return array list of history items
1091 * @access public
1093 function PMA_getHistory($username)
1095 $cfgRelation = PMA_getRelationsParam();
1097 if (! $cfgRelation['historywork']) {
1098 return false;
1102 * if db-based history is disabled but there exists a session-based
1103 * history, use it
1105 if (! $GLOBALS['cfg']['QueryHistoryDB']) {
1106 if (isset($_SESSION['sql_history'])) {
1107 return array_reverse($_SESSION['sql_history']);
1109 return false;
1112 $hist_query = '
1113 SELECT `db`,
1114 `table`,
1115 `sqlquery`,
1116 `timevalue`
1117 FROM ' . PMA\libraries\Util::backquote($cfgRelation['db'])
1118 . '.' . PMA\libraries\Util::backquote($cfgRelation['history']) . '
1119 WHERE `username` = \'' . $GLOBALS['dbi']->escapeString($username) . '\'
1120 ORDER BY `id` DESC';
1122 return $GLOBALS['dbi']->fetchResult(
1123 $hist_query, null, null, $GLOBALS['controllink']
1125 } // end of 'PMA_getHistory()' function
1128 * purges SQL history
1130 * deletes entries that exceeds $cfg['QueryHistoryMax'], oldest first, for the
1131 * given user
1133 * @param string $username the username
1135 * @return void
1137 * @access public
1139 function PMA_purgeHistory($username)
1141 $cfgRelation = PMA_getRelationsParam();
1142 if (! $GLOBALS['cfg']['QueryHistoryDB'] || ! $cfgRelation['historywork']) {
1143 return;
1146 if (! $cfgRelation['historywork']) {
1147 return;
1150 $search_query = '
1151 SELECT `timevalue`
1152 FROM ' . PMA\libraries\Util::backquote($cfgRelation['db'])
1153 . '.' . PMA\libraries\Util::backquote($cfgRelation['history']) . '
1154 WHERE `username` = \'' . $GLOBALS['dbi']->escapeString($username) . '\'
1155 ORDER BY `timevalue` DESC
1156 LIMIT ' . $GLOBALS['cfg']['QueryHistoryMax'] . ', 1';
1158 if ($max_time = $GLOBALS['dbi']->fetchValue(
1159 $search_query, 0, 0, $GLOBALS['controllink']
1160 )) {
1161 PMA_queryAsControlUser(
1162 'DELETE FROM '
1163 . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
1164 . PMA\libraries\Util::backquote($cfgRelation['history']) . '
1165 WHERE `username` = \'' . $GLOBALS['dbi']->escapeString($username)
1166 . '\'
1167 AND `timevalue` <= \'' . $max_time . '\''
1170 } // end of 'PMA_purgeHistory()' function
1173 * Prepares the dropdown for one mode
1175 * @param array $foreign the keys and values for foreigns
1176 * @param string $data the current data of the dropdown
1177 * @param string $mode the needed mode
1179 * @return array the <option value=""><option>s
1181 * @access protected
1183 function PMA_buildForeignDropdown($foreign, $data, $mode)
1185 $reloptions = array();
1187 // id-only is a special mode used when no foreign display column
1188 // is available
1189 if ($mode == 'id-content' || $mode == 'id-only') {
1190 // sort for id-content
1191 if ($GLOBALS['cfg']['NaturalOrder']) {
1192 uksort($foreign, 'strnatcasecmp');
1193 } else {
1194 ksort($foreign);
1196 } elseif ($mode == 'content-id') {
1197 // sort for content-id
1198 if ($GLOBALS['cfg']['NaturalOrder']) {
1199 natcasesort($foreign);
1200 } else {
1201 asort($foreign);
1205 foreach ($foreign as $key => $value) {
1206 if (mb_strlen($value) <= $GLOBALS['cfg']['LimitChars']
1208 $vtitle = '';
1209 $value = htmlspecialchars($value);
1210 } else {
1211 $vtitle = htmlspecialchars($value);
1212 $value = htmlspecialchars(
1213 mb_substr(
1214 $value, 0, $GLOBALS['cfg']['LimitChars']
1215 ) . '...'
1219 $reloption = '<option value="' . htmlspecialchars($key) . '"';
1220 if ($vtitle != '') {
1221 $reloption .= ' title="' . $vtitle . '"';
1224 if ((string) $key == (string) $data) {
1225 $reloption .= ' selected="selected"';
1228 if ($mode == 'content-id') {
1229 $reloptions[] = $reloption . '>'
1230 . $value . '&nbsp;-&nbsp;' . htmlspecialchars($key) . '</option>';
1231 } elseif ($mode == 'id-content') {
1232 $reloptions[] = $reloption . '>'
1233 . htmlspecialchars($key) . '&nbsp;-&nbsp;' . $value . '</option>';
1234 } elseif ($mode == 'id-only') {
1235 $reloptions[] = $reloption . '>'
1236 . htmlspecialchars($key) . '</option>';
1238 } // end foreach
1240 return $reloptions;
1241 } // end of 'PMA_buildForeignDropdown' function
1244 * Outputs dropdown with values of foreign fields
1246 * @param array $disp_row array of the displayed row
1247 * @param string $foreign_field the foreign field
1248 * @param string $foreign_display the foreign field to display
1249 * @param string $data the current data of the dropdown (field in row)
1250 * @param int $max maximum number of items in the dropdown
1252 * @return string the <option value=""><option>s
1254 * @access public
1256 function PMA_foreignDropdown($disp_row, $foreign_field, $foreign_display, $data,
1257 $max = null
1259 if (null === $max) {
1260 $max = $GLOBALS['cfg']['ForeignKeyMaxLimit'];
1263 $foreign = array();
1265 // collect the data
1266 foreach ($disp_row as $relrow) {
1267 $key = $relrow[$foreign_field];
1269 // if the display field has been defined for this foreign table
1270 if ($foreign_display) {
1271 $value = $relrow[$foreign_display];
1272 } else {
1273 $value = '';
1274 } // end if ($foreign_display)
1276 $foreign[$key] = $value;
1277 } // end foreach
1279 // put the dropdown sections in correct order
1280 $top = array();
1281 $bottom = array();
1282 if ($foreign_display) {
1283 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'], 'array')) {
1284 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][0])) {
1285 $top = PMA_buildForeignDropdown(
1286 $foreign,
1287 $data,
1288 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][0]
1291 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][1])) {
1292 $bottom = PMA_buildForeignDropdown(
1293 $foreign,
1294 $data,
1295 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][1]
1298 } else {
1299 $top = PMA_buildForeignDropdown($foreign, $data, 'id-content');
1300 $bottom = PMA_buildForeignDropdown($foreign, $data, 'content-id');
1302 } else {
1303 $top = PMA_buildForeignDropdown($foreign, $data, 'id-only');
1306 // beginning of dropdown
1307 $ret = '<option value="">&nbsp;</option>';
1308 $top_count = count($top);
1309 if ($max == -1 || $top_count < $max) {
1310 $ret .= implode('', $top);
1311 if ($foreign_display && $top_count > 0) {
1312 // this empty option is to visually mark the beginning of the
1313 // second series of values (bottom)
1314 $ret .= '<option value="">&nbsp;</option>';
1317 if ($foreign_display) {
1318 $ret .= implode('', $bottom);
1321 return $ret;
1322 } // end of 'PMA_foreignDropdown()' function
1325 * Gets foreign keys in preparation for a drop-down selector
1327 * @param array|boolean $foreigners array of the foreign keys
1328 * @param string $field the foreign field name
1329 * @param bool $override_total whether to override the total
1330 * @param string $foreign_filter a possible filter
1331 * @param string $foreign_limit a possible LIMIT clause
1332 * @param bool $get_total optional, whether to get total num of rows
1333 * in $foreignData['the_total;]
1334 * (has an effect of performance)
1336 * @return array data about the foreign keys
1338 * @access public
1340 function PMA_getForeignData(
1341 $foreigners, $field, $override_total,
1342 $foreign_filter, $foreign_limit, $get_total=false
1344 // we always show the foreign field in the drop-down; if a display
1345 // field is defined, we show it besides the foreign field
1346 $foreign_link = false;
1347 do {
1348 if (! $foreigners) {
1349 break;
1351 $foreigner = PMA_searchColumnInForeigners($foreigners, $field);
1352 if ($foreigner != false) {
1353 $foreign_db = $foreigner['foreign_db'];
1354 $foreign_table = $foreigner['foreign_table'];
1355 $foreign_field = $foreigner['foreign_field'];
1356 } else {
1357 break;
1360 // Count number of rows in the foreign table. Currently we do
1361 // not use a drop-down if more than ForeignKeyMaxLimit rows in the
1362 // foreign table,
1363 // for speed reasons and because we need a better interface for this.
1365 // We could also do the SELECT anyway, with a LIMIT, and ensure that
1366 // the current value of the field is one of the choices.
1368 // Check if table has more rows than specified by
1369 // $GLOBALS['cfg']['ForeignKeyMaxLimit']
1370 $moreThanLimit = $GLOBALS['dbi']->getTable($foreign_db, $foreign_table)
1371 ->checkIfMinRecordsExist($GLOBALS['cfg']['ForeignKeyMaxLimit']);
1373 if ($override_total == true
1374 || !$moreThanLimit
1376 // foreign_display can be false if no display field defined:
1377 $foreign_display = PMA_getDisplayField($foreign_db, $foreign_table);
1379 $f_query_main = 'SELECT ' . PMA\libraries\Util::backquote($foreign_field)
1381 ($foreign_display == false)
1382 ? ''
1383 : ', ' . PMA\libraries\Util::backquote($foreign_display)
1385 $f_query_from = ' FROM ' . PMA\libraries\Util::backquote($foreign_db)
1386 . '.' . PMA\libraries\Util::backquote($foreign_table);
1387 $f_query_filter = empty($foreign_filter) ? '' : ' WHERE '
1388 . PMA\libraries\Util::backquote($foreign_field)
1389 . ' LIKE "%' . $GLOBALS['dbi']->escapeString($foreign_filter) . '%"'
1391 ($foreign_display == false)
1392 ? ''
1393 : ' OR ' . PMA\libraries\Util::backquote($foreign_display)
1394 . ' LIKE "%' . $GLOBALS['dbi']->escapeString($foreign_filter)
1395 . '%"'
1397 $f_query_order = ($foreign_display == false) ? '' :' ORDER BY '
1398 . PMA\libraries\Util::backquote($foreign_table) . '.'
1399 . PMA\libraries\Util::backquote($foreign_display);
1401 $f_query_limit = ! empty($foreign_limit) ? ($foreign_limit) : '';
1403 if (!empty($foreign_filter)) {
1404 $the_total = $GLOBALS['dbi']->fetchValue(
1405 'SELECT COUNT(*)' . $f_query_from . $f_query_filter
1407 if ($the_total === false) {
1408 $the_total = 0;
1412 $disp = $GLOBALS['dbi']->tryQuery(
1413 $f_query_main . $f_query_from . $f_query_filter
1414 . $f_query_order . $f_query_limit
1416 if ($disp && $GLOBALS['dbi']->numRows($disp) > 0) {
1417 // If a resultset has been created, pre-cache it in the $disp_row
1418 // array. This helps us from not needing to use mysql_data_seek by
1419 // accessing a pre-cached PHP array. Usually those resultsets are
1420 // not that big, so a performance hit should not be expected.
1421 $disp_row = array();
1422 while ($single_disp_row = @$GLOBALS['dbi']->fetchAssoc($disp)) {
1423 $disp_row[] = $single_disp_row;
1425 @$GLOBALS['dbi']->freeResult($disp);
1426 } else {
1427 // Either no data in the foreign table or
1428 // user does not have select permission to foreign table/field
1429 // Show an input field with a 'Browse foreign values' link
1430 $disp_row = null;
1431 $foreign_link = true;
1433 } else {
1434 $disp_row = null;
1435 $foreign_link = true;
1437 } while (false);
1439 if ($get_total) {
1440 $the_total = $GLOBALS['dbi']->getTable($foreign_db, $foreign_table)
1441 ->countRecords(true);
1444 $foreignData = array();
1445 $foreignData['foreign_link'] = $foreign_link;
1446 $foreignData['the_total'] = isset($the_total) ? $the_total : null;
1447 $foreignData['foreign_display'] = (
1448 isset($foreign_display) ? $foreign_display : null
1450 $foreignData['disp_row'] = isset($disp_row) ? $disp_row : null;
1451 $foreignData['foreign_field'] = isset($foreign_field) ? $foreign_field : null;
1453 return $foreignData;
1454 } // end of 'PMA_getForeignData()' function
1457 * Rename a field in relation tables
1459 * usually called after a column in a table was renamed
1461 * @param string $db database name
1462 * @param string $table table name
1463 * @param string $field old field name
1464 * @param string $new_name new field name
1466 * @return void
1468 function PMA_REL_renameField($db, $table, $field, $new_name)
1470 $cfgRelation = PMA_getRelationsParam();
1472 if ($cfgRelation['displaywork']) {
1473 $table_query = 'UPDATE '
1474 . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
1475 . PMA\libraries\Util::backquote($cfgRelation['table_info'])
1476 . ' SET display_field = \'' . $GLOBALS['dbi']->escapeString(
1477 $new_name
1478 ) . '\''
1479 . ' WHERE db_name = \'' . $GLOBALS['dbi']->escapeString($db)
1480 . '\''
1481 . ' AND table_name = \'' . $GLOBALS['dbi']->escapeString($table)
1482 . '\''
1483 . ' AND display_field = \'' . $GLOBALS['dbi']->escapeString($field)
1484 . '\'';
1485 PMA_queryAsControlUser($table_query);
1488 if ($cfgRelation['relwork']) {
1489 $table_query = 'UPDATE '
1490 . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
1491 . PMA\libraries\Util::backquote($cfgRelation['relation'])
1492 . ' SET master_field = \'' . $GLOBALS['dbi']->escapeString(
1493 $new_name
1494 ) . '\''
1495 . ' WHERE master_db = \'' . $GLOBALS['dbi']->escapeString($db)
1496 . '\''
1497 . ' AND master_table = \'' . $GLOBALS['dbi']->escapeString($table)
1498 . '\''
1499 . ' AND master_field = \'' . $GLOBALS['dbi']->escapeString($field)
1500 . '\'';
1501 PMA_queryAsControlUser($table_query);
1503 $table_query = 'UPDATE '
1504 . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
1505 . PMA\libraries\Util::backquote($cfgRelation['relation'])
1506 . ' SET foreign_field = \'' . $GLOBALS['dbi']->escapeString(
1507 $new_name
1508 ) . '\''
1509 . ' WHERE foreign_db = \'' . $GLOBALS['dbi']->escapeString($db)
1510 . '\''
1511 . ' AND foreign_table = \'' . $GLOBALS['dbi']->escapeString($table)
1512 . '\''
1513 . ' AND foreign_field = \'' . $GLOBALS['dbi']->escapeString($field)
1514 . '\'';
1515 PMA_queryAsControlUser($table_query);
1517 } // end if relwork
1522 * Performs SQL query used for renaming table.
1524 * @param string $table Relation table to use
1525 * @param string $source_db Source database name
1526 * @param string $target_db Target database name
1527 * @param string $source_table Source table name
1528 * @param string $target_table Target table name
1529 * @param string $db_field Name of database field
1530 * @param string $table_field Name of table field
1532 * @return void
1534 function PMA_REL_renameSingleTable($table,
1535 $source_db, $target_db,
1536 $source_table, $target_table,
1537 $db_field, $table_field
1539 $query = 'UPDATE '
1540 . PMA\libraries\Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
1541 . PMA\libraries\Util::backquote($GLOBALS['cfgRelation'][$table])
1542 . ' SET '
1543 . $db_field . ' = \'' . $GLOBALS['dbi']->escapeString($target_db)
1544 . '\', '
1545 . $table_field . ' = \'' . $GLOBALS['dbi']->escapeString($target_table)
1546 . '\''
1547 . ' WHERE '
1548 . $db_field . ' = \'' . $GLOBALS['dbi']->escapeString($source_db) . '\''
1549 . ' AND '
1550 . $table_field . ' = \'' . $GLOBALS['dbi']->escapeString($source_table)
1551 . '\'';
1552 PMA_queryAsControlUser($query);
1557 * Rename a table in relation tables
1559 * usually called after table has been moved
1561 * @param string $source_db Source database name
1562 * @param string $target_db Target database name
1563 * @param string $source_table Source table name
1564 * @param string $target_table Target table name
1566 * @return void
1568 function PMA_REL_renameTable($source_db, $target_db, $source_table, $target_table)
1570 // Move old entries from PMA-DBs to new table
1571 if ($GLOBALS['cfgRelation']['commwork']) {
1572 PMA_REL_renameSingleTable(
1573 'column_info',
1574 $source_db, $target_db,
1575 $source_table, $target_table,
1576 'db_name', 'table_name'
1580 // updating bookmarks is not possible since only a single table is
1581 // moved, and not the whole DB.
1583 if ($GLOBALS['cfgRelation']['displaywork']) {
1584 PMA_REL_renameSingleTable(
1585 'table_info',
1586 $source_db, $target_db,
1587 $source_table, $target_table,
1588 'db_name', 'table_name'
1592 if ($GLOBALS['cfgRelation']['relwork']) {
1593 PMA_REL_renameSingleTable(
1594 'relation',
1595 $source_db, $target_db,
1596 $source_table, $target_table,
1597 'foreign_db', 'foreign_table'
1600 PMA_REL_renameSingleTable(
1601 'relation',
1602 $source_db, $target_db,
1603 $source_table, $target_table,
1604 'master_db', 'master_table'
1608 if ($GLOBALS['cfgRelation']['pdfwork']) {
1609 if ($source_db == $target_db) {
1610 // rename within the database can be handled
1611 PMA_REL_renameSingleTable(
1612 'table_coords',
1613 $source_db, $target_db,
1614 $source_table, $target_table,
1615 'db_name', 'table_name'
1617 } else {
1618 // if the table is moved out of the database we can no loger keep the
1619 // record for table coordinate
1620 $remove_query = "DELETE FROM "
1621 . PMA\libraries\Util::backquote($GLOBALS['cfgRelation']['db']) . "."
1622 . PMA\libraries\Util::backquote($GLOBALS['cfgRelation']['table_coords'])
1623 . " WHERE db_name = '" . $GLOBALS['dbi']->escapeString($source_db) . "'"
1624 . " AND table_name = '" . $GLOBALS['dbi']->escapeString($source_table)
1625 . "'";
1626 PMA_queryAsControlUser($remove_query);
1630 if ($GLOBALS['cfgRelation']['uiprefswork']) {
1631 PMA_REL_renameSingleTable(
1632 'table_uiprefs',
1633 $source_db, $target_db,
1634 $source_table, $target_table,
1635 'db_name', 'table_name'
1639 if ($GLOBALS['cfgRelation']['navwork']) {
1640 // update hidden items inside table
1641 PMA_REL_renameSingleTable(
1642 'navigationhiding',
1643 $source_db, $target_db,
1644 $source_table, $target_table,
1645 'db_name', 'table_name'
1648 // update data for hidden table
1649 $query = "UPDATE "
1650 . PMA\libraries\Util::backquote($GLOBALS['cfgRelation']['db']) . "."
1651 . PMA\libraries\Util::backquote(
1652 $GLOBALS['cfgRelation']['navigationhiding']
1654 . " SET db_name = '" . $GLOBALS['dbi']->escapeString($target_db)
1655 . "',"
1656 . " item_name = '" . $GLOBALS['dbi']->escapeString($target_table)
1657 . "'"
1658 . " WHERE db_name = '" . $GLOBALS['dbi']->escapeString($source_db)
1659 . "'"
1660 . " AND item_name = '" . $GLOBALS['dbi']->escapeString($source_table)
1661 . "'"
1662 . " AND item_type = 'table'";
1663 PMA_queryAsControlUser($query);
1668 * Create a PDF page
1670 * @param string $newpage name of the new PDF page
1671 * @param array $cfgRelation Relation configuration
1672 * @param string $db database name
1674 * @return int $pdf_page_number
1676 function PMA_REL_createPage($newpage, $cfgRelation, $db)
1678 if (! isset($newpage) || $newpage == '') {
1679 $newpage = __('no description');
1681 $ins_query = 'INSERT INTO '
1682 . PMA\libraries\Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
1683 . PMA\libraries\Util::backquote($cfgRelation['pdf_pages'])
1684 . ' (db_name, page_descr)'
1685 . ' VALUES (\''
1686 . $GLOBALS['dbi']->escapeString($db) . '\', \''
1687 . $GLOBALS['dbi']->escapeString($newpage) . '\')';
1688 PMA_queryAsControlUser($ins_query, false);
1690 return $GLOBALS['dbi']->insertId(
1691 isset($GLOBALS['controllink']) ? $GLOBALS['controllink'] : ''
1696 * Get child table references for a table column.
1697 * This works only if 'DisableIS' is false. An empty array is returned otherwise.
1699 * @param string $db name of master table db.
1700 * @param string $table name of master table.
1701 * @param string $column name of master table column.
1703 * @return array $child_references
1705 function PMA_getChildReferences($db, $table, $column = '')
1707 $child_references = array();
1708 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1709 $rel_query = "SELECT `column_name`, `table_name`,"
1710 . " `table_schema`, `referenced_column_name`"
1711 . " FROM `information_schema`.`key_column_usage`"
1712 . " WHERE `referenced_table_name` = '"
1713 . $GLOBALS['dbi']->escapeString($table) . "'"
1714 . " AND `referenced_table_schema` = '"
1715 . $GLOBALS['dbi']->escapeString($db) . "'";
1716 if ($column) {
1717 $rel_query .= " AND `referenced_column_name` = '"
1718 . $GLOBALS['dbi']->escapeString($column) . "'";
1721 $child_references = $GLOBALS['dbi']->fetchResult(
1722 $rel_query, array('referenced_column_name', null)
1725 return $child_references;
1729 * Check child table references and foreign key for a table column.
1731 * @param string $db name of master table db.
1732 * @param string $table name of master table.
1733 * @param string $column name of master table column.
1734 * @param array $foreigners_full foreiners array for the whole table.
1735 * @param array $child_references_full child references for the whole table.
1737 * @return array $column_status telling about references if foreign key.
1739 function PMA_checkChildForeignReferences(
1740 $db, $table, $column, $foreigners_full = null, $child_references_full = null
1742 $column_status = array();
1743 $column_status['isEditable'] = false;
1744 $column_status['isReferenced'] = false;
1745 $column_status['isForeignKey'] = false;
1746 $column_status['references'] = array();
1748 $foreigners = array();
1749 if ($foreigners_full !== null) {
1750 if (isset($foreigners_full[$column])) {
1751 $foreigners[$column] = $foreigners_full[$column];
1753 if (isset($foreigners_full['foreign_keys_data'])) {
1754 $foreigners['foreign_keys_data'] = $foreigners_full['foreign_keys_data'];
1756 } else {
1757 $foreigners = PMA_getForeigners($db, $table, $column, 'foreign');
1759 $foreigner = PMA_searchColumnInForeigners($foreigners, $column);
1761 $child_references = array();
1762 if ($child_references_full !== null) {
1763 if (isset($child_references_full[$column])) {
1764 $child_references = $child_references_full[$column];
1766 } else {
1767 $child_references = PMA_getChildReferences($db, $table, $column);
1770 if (sizeof($child_references, 0) > 0
1771 || $foreigner
1773 if (sizeof($child_references, 0) > 0) {
1774 $column_status['isReferenced'] = true;
1775 foreach ($child_references as $columns) {
1776 array_push(
1777 $column_status['references'],
1778 PMA\libraries\Util::backquote($columns['table_schema'])
1779 . '.' . PMA\libraries\Util::backquote($columns['table_name'])
1784 if ($foreigner) {
1785 $column_status['isForeignKey'] = true;
1787 } else {
1788 $column_status['isEditable'] = true;
1791 return $column_status;
1795 * Search a table column in foreign data.
1797 * @param array $foreigners Table Foreign data
1798 * @param string $column Column name
1800 * @return bool|array
1802 function PMA_searchColumnInForeigners($foreigners, $column)
1804 if (isset($foreigners[$column])) {
1805 return $foreigners[$column];
1806 } else {
1807 $foreigner = array();
1808 foreach ($foreigners['foreign_keys_data'] as $one_key) {
1809 $column_index = array_search($column, $one_key['index_list']);
1810 if ($column_index !== false) {
1811 $foreigner['foreign_field']
1812 = $one_key['ref_index_list'][$column_index];
1813 $foreigner['foreign_db'] = isset($one_key['ref_db_name'])
1814 ? $one_key['ref_db_name']
1815 : $GLOBALS['db'];
1816 $foreigner['foreign_table'] = $one_key['ref_table_name'];
1817 $foreigner['constraint'] = $one_key['constraint'];
1818 $foreigner['on_update'] = isset($one_key['on_update'])
1819 ? $one_key['on_update']
1820 : 'RESTRICT';
1821 $foreigner['on_delete'] = isset($one_key['on_delete'])
1822 ? $one_key['on_delete']
1823 : 'RESTRICT';
1825 return $foreigner;
1830 return false;
1834 * Returns default PMA table names and their create queries.
1836 * @return array table name, create query
1838 function PMA_getDefaultPMATableNames()
1840 $pma_tables = array();
1841 $create_tables_file = file_get_contents(
1842 SQL_DIR . 'create_tables.sql'
1845 $queries = explode(';', $create_tables_file);
1847 foreach ($queries as $query) {
1848 if (preg_match(
1849 '/CREATE TABLE IF NOT EXISTS `(.*)` \(/',
1850 $query,
1851 $table
1854 $pma_tables[$table[1]] = $query . ';';
1858 return $pma_tables;
1862 * Create a table named phpmyadmin to be used as configuration storage
1864 * @return bool
1866 function PMA_createPMADatabase()
1868 $GLOBALS['dbi']->tryQuery("CREATE DATABASE IF NOT EXISTS `phpmyadmin`");
1869 if ($error = $GLOBALS['dbi']->getError()) {
1870 if ($GLOBALS['errno'] == 1044) {
1871 $GLOBALS['message'] = __(
1872 'You do not have necessary privileges to create a database named'
1873 . ' \'phpmyadmin\'. You may go to \'Operations\' tab of any'
1874 . ' database to set up the phpMyAdmin configuration storage there.'
1876 } else {
1877 $GLOBALS['message'] = $error;
1879 return false;
1881 return true;
1885 * Creates PMA tables in the given db, updates if already exists.
1887 * @param string $db database
1888 * @param boolean $create whether to create tables if they don't exist.
1890 * @return void
1892 function PMA_fixPMATables($db, $create = true)
1894 $tablesToFeatures = array(
1895 'pma__bookmark' => 'bookmarktable',
1896 'pma__relation' => 'relation',
1897 'pma__table_info' => 'table_info',
1898 'pma__table_coords' => 'table_coords',
1899 'pma__pdf_pages' => 'pdf_pages',
1900 'pma__column_info' => 'column_info',
1901 'pma__history' => 'history',
1902 'pma__recent' => 'recent',
1903 'pma__favorite' => 'favorite',
1904 'pma__table_uiprefs' => 'table_uiprefs',
1905 'pma__tracking' => 'tracking',
1906 'pma__userconfig' => 'userconfig',
1907 'pma__users' => 'users',
1908 'pma__usergroups' => 'usergroups',
1909 'pma__navigationhiding' => 'navigationhiding',
1910 'pma__savedsearches' => 'savedsearches',
1911 'pma__central_columns' => 'central_columns',
1912 'pma__designer_settings' => 'designer_settings',
1913 'pma__export_templates' => 'export_templates',
1916 $existingTables = $GLOBALS['dbi']->getTables($db, $GLOBALS['controllink']);
1918 $createQueries = null;
1919 $foundOne = false;
1920 foreach ($tablesToFeatures as $table => $feature) {
1921 if (! in_array($table, $existingTables)) {
1922 if ($create) {
1923 if ($createQueries == null) { // first create
1924 $createQueries = PMA_getDefaultPMATableNames();
1925 $GLOBALS['dbi']->selectDb($db);
1927 $GLOBALS['dbi']->tryQuery($createQueries[$table]);
1928 if ($error = $GLOBALS['dbi']->getError()) {
1929 $GLOBALS['message'] = $error;
1930 return;
1932 $foundOne = true;
1933 $GLOBALS['cfg']['Server'][$feature] = $table;
1935 } else {
1936 $foundOne = true;
1937 $GLOBALS['cfg']['Server'][$feature] = $table;
1941 if (! $foundOne) {
1942 return;
1944 $GLOBALS['cfg']['Server']['pmadb'] = $db;
1945 $_SESSION['relation'][$GLOBALS['server']] = PMA_checkRelationsParam();
1947 $cfgRelation = PMA_getRelationsParam();
1948 if ($cfgRelation['recentwork'] || $cfgRelation['favoritework']) {
1949 // Since configuration storage is updated, we need to
1950 // re-initialize the favorite and recent tables stored in the
1951 // session from the current configuration storage.
1952 if ($cfgRelation['favoritework']) {
1953 $fav_tables = RecentFavoriteTable::getInstance('favorite');
1954 $_SESSION['tmpval']['favorite_tables'][$GLOBALS['server']]
1955 = $fav_tables->getFromDb();
1958 if ($cfgRelation['recentwork']) {
1959 $recent_tables = RecentFavoriteTable::getInstance('recent');
1960 $_SESSION['tmpval']['recent_tables'][$GLOBALS['server']]
1961 = $recent_tables->getFromDb();
1964 // Reload navi panel to update the recent/favorite lists.
1965 $GLOBALS['reload'] = true;
1970 * Get Html for PMA tables fixing anchor.
1972 * @param boolean $allTables whether to create all tables
1973 * @param boolean $createDb whether to create the pmadb also
1975 * @return string Html
1977 function PMA_getHtmlFixPMATables($allTables, $createDb = false)
1979 $retval = '';
1981 $url_query = URL::getCommon(array('db' => $GLOBALS['db']));
1982 if ($allTables) {
1983 if ($createDb) {
1984 $url_query .= '&amp;goto=db_operations.php&amp;create_pmadb=1';
1985 $message = Message::notice(
1987 '%sCreate%s a database named \'phpmyadmin\' and setup '
1988 . 'the phpMyAdmin configuration storage there.'
1991 } else {
1992 $url_query .= '&amp;goto=db_operations.php&amp;fixall_pmadb=1';
1993 $message = Message::notice(
1995 '%sCreate%s the phpMyAdmin configuration storage in the '
1996 . 'current database.'
2000 } else {
2001 $url_query .= '&amp;goto=db_operations.php&amp;fix_pmadb=1';
2002 $message = Message::notice(
2003 __('%sCreate%s missing phpMyAdmin configuration storage tables.')
2006 $message->addParamHtml('<a href="./chk_rel.php' . $url_query . '">');
2007 $message->addParamHtml('</a>');
2009 $retval .= $message->getDisplay();
2011 return $retval;
2015 * Gets the relations info and status, depending on the condition
2017 * @param boolean $condition whether to look for foreigners or not
2018 * @param string $db database name
2019 * @param string $table table name
2021 * @return array ($res_rel, $have_rel)
2023 function PMA_getRelationsAndStatus($condition, $db, $table)
2025 if ($condition) {
2026 // Find which tables are related with the current one and write it in
2027 // an array
2028 $res_rel = PMA_getForeigners($db, $table);
2030 if (count($res_rel) > 0) {
2031 $have_rel = true;
2032 } else {
2033 $have_rel = false;
2035 } else {
2036 $have_rel = false;
2037 $res_rel = array();
2038 } // end if
2039 return(array($res_rel, $have_rel));
2043 * Verifies if all the pmadb tables are defined
2045 * @return boolean
2047 function PMA_arePmadbTablesDefined()
2049 if (empty($GLOBALS['cfg']['Server']['bookmarktable'])
2050 || empty($GLOBALS['cfg']['Server']['relation'])
2051 || empty($GLOBALS['cfg']['Server']['table_info'])
2052 || empty($GLOBALS['cfg']['Server']['table_coords'])
2053 || empty($GLOBALS['cfg']['Server']['column_info'])
2054 || empty($GLOBALS['cfg']['Server']['pdf_pages'])
2055 || empty($GLOBALS['cfg']['Server']['history'])
2056 || empty($GLOBALS['cfg']['Server']['recent'])
2057 || empty($GLOBALS['cfg']['Server']['favorite'])
2058 || empty($GLOBALS['cfg']['Server']['table_uiprefs'])
2059 || empty($GLOBALS['cfg']['Server']['tracking'])
2060 || empty($GLOBALS['cfg']['Server']['userconfig'])
2061 || empty($GLOBALS['cfg']['Server']['users'])
2062 || empty($GLOBALS['cfg']['Server']['usergroups'])
2063 || empty($GLOBALS['cfg']['Server']['navigationhiding'])
2064 || empty($GLOBALS['cfg']['Server']['savedsearches'])
2065 || empty($GLOBALS['cfg']['Server']['central_columns'])
2066 || empty($GLOBALS['cfg']['Server']['designer_settings'])
2067 || empty($GLOBALS['cfg']['Server']['export_templates'])
2069 return false;
2070 } else {
2071 return true;