Translated using Weblate (Albanian)
[phpmyadmin.git] / libraries / relation.lib.php
blob088180888bbb801b721f7fa78ddd1a22b11ba716
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 * Pick first char field
865 $columns = $GLOBALS['dbi']->getColumnsFull($db, $table);
866 if ($columns) {
867 foreach ($columns as $column) {
868 if ($GLOBALS['PMA_Types']->getTypeClass($column['DATA_TYPE']) == 'CHAR') {
869 return $column['COLUMN_NAME'];
875 * No Luck...
877 return false;
879 } // end of the 'PMA_getDisplayField()' function
882 * Gets the comments for all columns of a table or the db itself
884 * @param string $db the name of the db to check for
885 * @param string $table the name of the table to check for
887 * @return array [column_name] = comment
889 * @access public
891 function PMA_getComments($db, $table = '')
893 $comments = array();
895 if ($table != '') {
896 // MySQL native column comments
897 $columns = $GLOBALS['dbi']->getColumns($db, $table, null, true);
898 if ($columns) {
899 foreach ($columns as $column) {
900 if (! empty($column['Comment'])) {
901 $comments[$column['Field']] = $column['Comment'];
905 } else {
906 $comments[] = PMA_getDbComment($db);
909 return $comments;
910 } // end of the 'PMA_getComments()' function
913 * Gets the comment for a db
915 * @param string $db the name of the db to check for
917 * @return string comment
919 * @access public
921 function PMA_getDbComment($db)
923 $cfgRelation = PMA_getRelationsParam();
924 $comment = '';
926 if ($cfgRelation['commwork']) {
927 // pmadb internal db comment
928 $com_qry = "
929 SELECT `comment`
930 FROM " . PMA\libraries\Util::backquote($cfgRelation['db'])
931 . "." . PMA\libraries\Util::backquote($cfgRelation['column_info'])
933 WHERE db_name = '" . $GLOBALS['dbi']->escapeString($db) . "'
934 AND table_name = ''
935 AND column_name = '(db_comment)'";
936 $com_rs = PMA_queryAsControlUser(
937 $com_qry, true, PMA\libraries\DatabaseInterface::QUERY_STORE
940 if ($com_rs && $GLOBALS['dbi']->numRows($com_rs) > 0) {
941 $row = $GLOBALS['dbi']->fetchAssoc($com_rs);
942 $comment = $row['comment'];
944 $GLOBALS['dbi']->freeResult($com_rs);
947 return $comment;
948 } // end of the 'PMA_getDbComment()' function
951 * Gets the comment for a db
953 * @access public
955 * @return string comment
957 function PMA_getDbComments()
959 $cfgRelation = PMA_getRelationsParam();
960 $comments = array();
962 if ($cfgRelation['commwork']) {
963 // pmadb internal db comment
964 $com_qry = "
965 SELECT `db_name`, `comment`
966 FROM " . PMA\libraries\Util::backquote($cfgRelation['db'])
967 . "." . PMA\libraries\Util::backquote($cfgRelation['column_info'])
969 WHERE `column_name` = '(db_comment)'";
970 $com_rs = PMA_queryAsControlUser(
971 $com_qry, true, PMA\libraries\DatabaseInterface::QUERY_STORE
974 if ($com_rs && $GLOBALS['dbi']->numRows($com_rs) > 0) {
975 while ($row = $GLOBALS['dbi']->fetchAssoc($com_rs)) {
976 $comments[$row['db_name']] = $row['comment'];
979 $GLOBALS['dbi']->freeResult($com_rs);
982 return $comments;
983 } // end of the 'PMA_getDbComments()' function
986 * Set a database comment to a certain value.
988 * @param string $db the name of the db
989 * @param string $comment the value of the column
991 * @return boolean true, if comment-query was made.
993 * @access public
995 function PMA_setDbComment($db, $comment = '')
997 $cfgRelation = PMA_getRelationsParam();
999 if (! $cfgRelation['commwork']) {
1000 return false;
1003 if (strlen($comment) > 0) {
1004 $upd_query = 'INSERT INTO '
1005 . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
1006 . PMA\libraries\Util::backquote($cfgRelation['column_info'])
1007 . ' (`db_name`, `table_name`, `column_name`, `comment`)'
1008 . ' VALUES (\''
1009 . $GLOBALS['dbi']->escapeString($db)
1010 . "', '', '(db_comment)', '"
1011 . $GLOBALS['dbi']->escapeString($comment)
1012 . "') "
1013 . ' ON DUPLICATE KEY UPDATE '
1014 . "`comment` = '" . $GLOBALS['dbi']->escapeString($comment) . "'";
1015 } else {
1016 $upd_query = 'DELETE FROM '
1017 . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
1018 . PMA\libraries\Util::backquote($cfgRelation['column_info'])
1019 . ' WHERE `db_name` = \'' . $GLOBALS['dbi']->escapeString($db)
1020 . '\'
1021 AND `table_name` = \'\'
1022 AND `column_name` = \'(db_comment)\'';
1025 if (isset($upd_query)) {
1026 return PMA_queryAsControlUser($upd_query);
1029 return false;
1030 } // end of 'PMA_setDbComment()' function
1033 * Set a SQL history entry
1035 * @param string $db the name of the db
1036 * @param string $table the name of the table
1037 * @param string $username the username
1038 * @param string $sqlquery the sql query
1040 * @return void
1042 * @access public
1044 function PMA_setHistory($db, $table, $username, $sqlquery)
1046 $maxCharactersInDisplayedSQL = $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'];
1047 // Prevent to run this automatically on Footer class destroying in testsuite
1048 if (defined('TESTSUITE')
1049 || mb_strlen($sqlquery) > $maxCharactersInDisplayedSQL
1051 return;
1054 $cfgRelation = PMA_getRelationsParam();
1056 if (! isset($_SESSION['sql_history'])) {
1057 $_SESSION['sql_history'] = array();
1060 $_SESSION['sql_history'][] = array(
1061 'db' => $db,
1062 'table' => $table,
1063 'sqlquery' => $sqlquery,
1066 if (count($_SESSION['sql_history']) > $GLOBALS['cfg']['QueryHistoryMax']) {
1067 // history should not exceed a maximum count
1068 array_shift($_SESSION['sql_history']);
1071 if (! $cfgRelation['historywork'] || ! $GLOBALS['cfg']['QueryHistoryDB']) {
1072 return;
1075 PMA_queryAsControlUser(
1076 'INSERT INTO '
1077 . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
1078 . PMA\libraries\Util::backquote($cfgRelation['history']) . '
1079 (`username`,
1080 `db`,
1081 `table`,
1082 `timevalue`,
1083 `sqlquery`)
1084 VALUES
1085 (\'' . $GLOBALS['dbi']->escapeString($username) . '\',
1086 \'' . $GLOBALS['dbi']->escapeString($db) . '\',
1087 \'' . $GLOBALS['dbi']->escapeString($table) . '\',
1088 NOW(),
1089 \'' . $GLOBALS['dbi']->escapeString($sqlquery) . '\')'
1092 PMA_purgeHistory($username);
1094 } // end of 'PMA_setHistory()' function
1097 * Gets a SQL history entry
1099 * @param string $username the username
1101 * @return array list of history items
1103 * @access public
1105 function PMA_getHistory($username)
1107 $cfgRelation = PMA_getRelationsParam();
1109 if (! $cfgRelation['historywork']) {
1110 return false;
1114 * if db-based history is disabled but there exists a session-based
1115 * history, use it
1117 if (! $GLOBALS['cfg']['QueryHistoryDB']) {
1118 if (isset($_SESSION['sql_history'])) {
1119 return array_reverse($_SESSION['sql_history']);
1121 return false;
1124 $hist_query = '
1125 SELECT `db`,
1126 `table`,
1127 `sqlquery`,
1128 `timevalue`
1129 FROM ' . PMA\libraries\Util::backquote($cfgRelation['db'])
1130 . '.' . PMA\libraries\Util::backquote($cfgRelation['history']) . '
1131 WHERE `username` = \'' . $GLOBALS['dbi']->escapeString($username) . '\'
1132 ORDER BY `id` DESC';
1134 return $GLOBALS['dbi']->fetchResult(
1135 $hist_query, null, null, $GLOBALS['controllink']
1137 } // end of 'PMA_getHistory()' function
1140 * purges SQL history
1142 * deletes entries that exceeds $cfg['QueryHistoryMax'], oldest first, for the
1143 * given user
1145 * @param string $username the username
1147 * @return void
1149 * @access public
1151 function PMA_purgeHistory($username)
1153 $cfgRelation = PMA_getRelationsParam();
1154 if (! $GLOBALS['cfg']['QueryHistoryDB'] || ! $cfgRelation['historywork']) {
1155 return;
1158 if (! $cfgRelation['historywork']) {
1159 return;
1162 $search_query = '
1163 SELECT `timevalue`
1164 FROM ' . PMA\libraries\Util::backquote($cfgRelation['db'])
1165 . '.' . PMA\libraries\Util::backquote($cfgRelation['history']) . '
1166 WHERE `username` = \'' . $GLOBALS['dbi']->escapeString($username) . '\'
1167 ORDER BY `timevalue` DESC
1168 LIMIT ' . $GLOBALS['cfg']['QueryHistoryMax'] . ', 1';
1170 if ($max_time = $GLOBALS['dbi']->fetchValue(
1171 $search_query, 0, 0, $GLOBALS['controllink']
1172 )) {
1173 PMA_queryAsControlUser(
1174 'DELETE FROM '
1175 . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
1176 . PMA\libraries\Util::backquote($cfgRelation['history']) . '
1177 WHERE `username` = \'' . $GLOBALS['dbi']->escapeString($username)
1178 . '\'
1179 AND `timevalue` <= \'' . $max_time . '\''
1182 } // end of 'PMA_purgeHistory()' function
1185 * Prepares the dropdown for one mode
1187 * @param array $foreign the keys and values for foreigns
1188 * @param string $data the current data of the dropdown
1189 * @param string $mode the needed mode
1191 * @return array the <option value=""><option>s
1193 * @access protected
1195 function PMA_buildForeignDropdown($foreign, $data, $mode)
1197 $reloptions = array();
1199 // id-only is a special mode used when no foreign display column
1200 // is available
1201 if ($mode == 'id-content' || $mode == 'id-only') {
1202 // sort for id-content
1203 if ($GLOBALS['cfg']['NaturalOrder']) {
1204 uksort($foreign, 'strnatcasecmp');
1205 } else {
1206 ksort($foreign);
1208 } elseif ($mode == 'content-id') {
1209 // sort for content-id
1210 if ($GLOBALS['cfg']['NaturalOrder']) {
1211 natcasesort($foreign);
1212 } else {
1213 asort($foreign);
1217 foreach ($foreign as $key => $value) {
1218 if (mb_strlen($value) <= $GLOBALS['cfg']['LimitChars']
1220 $vtitle = '';
1221 $value = htmlspecialchars($value);
1222 } else {
1223 $vtitle = htmlspecialchars($value);
1224 $value = htmlspecialchars(
1225 mb_substr(
1226 $value, 0, $GLOBALS['cfg']['LimitChars']
1227 ) . '...'
1231 $reloption = '<option value="' . htmlspecialchars($key) . '"';
1232 if ($vtitle != '') {
1233 $reloption .= ' title="' . $vtitle . '"';
1236 if ((string) $key == (string) $data) {
1237 $reloption .= ' selected="selected"';
1240 if ($mode == 'content-id') {
1241 $reloptions[] = $reloption . '>'
1242 . $value . '&nbsp;-&nbsp;' . htmlspecialchars($key) . '</option>';
1243 } elseif ($mode == 'id-content') {
1244 $reloptions[] = $reloption . '>'
1245 . htmlspecialchars($key) . '&nbsp;-&nbsp;' . $value . '</option>';
1246 } elseif ($mode == 'id-only') {
1247 $reloptions[] = $reloption . '>'
1248 . htmlspecialchars($key) . '</option>';
1250 } // end foreach
1252 return $reloptions;
1253 } // end of 'PMA_buildForeignDropdown' function
1256 * Outputs dropdown with values of foreign fields
1258 * @param array $disp_row array of the displayed row
1259 * @param string $foreign_field the foreign field
1260 * @param string $foreign_display the foreign field to display
1261 * @param string $data the current data of the dropdown (field in row)
1262 * @param int $max maximum number of items in the dropdown
1264 * @return string the <option value=""><option>s
1266 * @access public
1268 function PMA_foreignDropdown($disp_row, $foreign_field, $foreign_display, $data,
1269 $max = null
1271 if (null === $max) {
1272 $max = $GLOBALS['cfg']['ForeignKeyMaxLimit'];
1275 $foreign = array();
1277 // collect the data
1278 foreach ($disp_row as $relrow) {
1279 $key = $relrow[$foreign_field];
1281 // if the display field has been defined for this foreign table
1282 if ($foreign_display) {
1283 $value = $relrow[$foreign_display];
1284 } else {
1285 $value = '';
1286 } // end if ($foreign_display)
1288 $foreign[$key] = $value;
1289 } // end foreach
1291 // put the dropdown sections in correct order
1292 $top = array();
1293 $bottom = array();
1294 if ($foreign_display) {
1295 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'], 'array')) {
1296 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][0])) {
1297 $top = PMA_buildForeignDropdown(
1298 $foreign,
1299 $data,
1300 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][0]
1303 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][1])) {
1304 $bottom = PMA_buildForeignDropdown(
1305 $foreign,
1306 $data,
1307 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][1]
1310 } else {
1311 $top = PMA_buildForeignDropdown($foreign, $data, 'id-content');
1312 $bottom = PMA_buildForeignDropdown($foreign, $data, 'content-id');
1314 } else {
1315 $top = PMA_buildForeignDropdown($foreign, $data, 'id-only');
1318 // beginning of dropdown
1319 $ret = '<option value="">&nbsp;</option>';
1320 $top_count = count($top);
1321 if ($max == -1 || $top_count < $max) {
1322 $ret .= implode('', $top);
1323 if ($foreign_display && $top_count > 0) {
1324 // this empty option is to visually mark the beginning of the
1325 // second series of values (bottom)
1326 $ret .= '<option value="">&nbsp;</option>';
1329 if ($foreign_display) {
1330 $ret .= implode('', $bottom);
1333 return $ret;
1334 } // end of 'PMA_foreignDropdown()' function
1337 * Gets foreign keys in preparation for a drop-down selector
1339 * @param array|boolean $foreigners array of the foreign keys
1340 * @param string $field the foreign field name
1341 * @param bool $override_total whether to override the total
1342 * @param string $foreign_filter a possible filter
1343 * @param string $foreign_limit a possible LIMIT clause
1344 * @param bool $get_total optional, whether to get total num of rows
1345 * in $foreignData['the_total;]
1346 * (has an effect of performance)
1348 * @return array data about the foreign keys
1350 * @access public
1352 function PMA_getForeignData(
1353 $foreigners, $field, $override_total,
1354 $foreign_filter, $foreign_limit, $get_total=false
1356 // we always show the foreign field in the drop-down; if a display
1357 // field is defined, we show it besides the foreign field
1358 $foreign_link = false;
1359 do {
1360 if (! $foreigners) {
1361 break;
1363 $foreigner = PMA_searchColumnInForeigners($foreigners, $field);
1364 if ($foreigner != false) {
1365 $foreign_db = $foreigner['foreign_db'];
1366 $foreign_table = $foreigner['foreign_table'];
1367 $foreign_field = $foreigner['foreign_field'];
1368 } else {
1369 break;
1372 // Count number of rows in the foreign table. Currently we do
1373 // not use a drop-down if more than ForeignKeyMaxLimit rows in the
1374 // foreign table,
1375 // for speed reasons and because we need a better interface for this.
1377 // We could also do the SELECT anyway, with a LIMIT, and ensure that
1378 // the current value of the field is one of the choices.
1380 // Check if table has more rows than specified by
1381 // $GLOBALS['cfg']['ForeignKeyMaxLimit']
1382 $moreThanLimit = $GLOBALS['dbi']->getTable($foreign_db, $foreign_table)
1383 ->checkIfMinRecordsExist($GLOBALS['cfg']['ForeignKeyMaxLimit']);
1385 if ($override_total == true
1386 || !$moreThanLimit
1388 // foreign_display can be false if no display field defined:
1389 $foreign_display = PMA_getDisplayField($foreign_db, $foreign_table);
1391 $f_query_main = 'SELECT ' . PMA\libraries\Util::backquote($foreign_field)
1393 ($foreign_display == false)
1394 ? ''
1395 : ', ' . PMA\libraries\Util::backquote($foreign_display)
1397 $f_query_from = ' FROM ' . PMA\libraries\Util::backquote($foreign_db)
1398 . '.' . PMA\libraries\Util::backquote($foreign_table);
1399 $f_query_filter = empty($foreign_filter) ? '' : ' WHERE '
1400 . PMA\libraries\Util::backquote($foreign_field)
1401 . ' LIKE "%' . $GLOBALS['dbi']->escapeString($foreign_filter) . '%"'
1403 ($foreign_display == false)
1404 ? ''
1405 : ' OR ' . PMA\libraries\Util::backquote($foreign_display)
1406 . ' LIKE "%' . $GLOBALS['dbi']->escapeString($foreign_filter)
1407 . '%"'
1409 $f_query_order = ($foreign_display == false) ? '' :' ORDER BY '
1410 . PMA\libraries\Util::backquote($foreign_table) . '.'
1411 . PMA\libraries\Util::backquote($foreign_display);
1413 $f_query_limit = ! empty($foreign_limit) ? ($foreign_limit) : '';
1415 if (!empty($foreign_filter)) {
1416 $the_total = $GLOBALS['dbi']->fetchValue(
1417 'SELECT COUNT(*)' . $f_query_from . $f_query_filter
1419 if ($the_total === false) {
1420 $the_total = 0;
1424 $disp = $GLOBALS['dbi']->tryQuery(
1425 $f_query_main . $f_query_from . $f_query_filter
1426 . $f_query_order . $f_query_limit
1428 if ($disp && $GLOBALS['dbi']->numRows($disp) > 0) {
1429 // If a resultset has been created, pre-cache it in the $disp_row
1430 // array. This helps us from not needing to use mysql_data_seek by
1431 // accessing a pre-cached PHP array. Usually those resultsets are
1432 // not that big, so a performance hit should not be expected.
1433 $disp_row = array();
1434 while ($single_disp_row = @$GLOBALS['dbi']->fetchAssoc($disp)) {
1435 $disp_row[] = $single_disp_row;
1437 @$GLOBALS['dbi']->freeResult($disp);
1438 } else {
1439 // Either no data in the foreign table or
1440 // user does not have select permission to foreign table/field
1441 // Show an input field with a 'Browse foreign values' link
1442 $disp_row = null;
1443 $foreign_link = true;
1445 } else {
1446 $disp_row = null;
1447 $foreign_link = true;
1449 } while (false);
1451 if ($get_total) {
1452 $the_total = $GLOBALS['dbi']->getTable($foreign_db, $foreign_table)
1453 ->countRecords(true);
1456 $foreignData = array();
1457 $foreignData['foreign_link'] = $foreign_link;
1458 $foreignData['the_total'] = isset($the_total) ? $the_total : null;
1459 $foreignData['foreign_display'] = (
1460 isset($foreign_display) ? $foreign_display : null
1462 $foreignData['disp_row'] = isset($disp_row) ? $disp_row : null;
1463 $foreignData['foreign_field'] = isset($foreign_field) ? $foreign_field : null;
1465 return $foreignData;
1466 } // end of 'PMA_getForeignData()' function
1469 * Rename a field in relation tables
1471 * usually called after a column in a table was renamed
1473 * @param string $db database name
1474 * @param string $table table name
1475 * @param string $field old field name
1476 * @param string $new_name new field name
1478 * @return void
1480 function PMA_REL_renameField($db, $table, $field, $new_name)
1482 $cfgRelation = PMA_getRelationsParam();
1484 if ($cfgRelation['displaywork']) {
1485 $table_query = 'UPDATE '
1486 . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
1487 . PMA\libraries\Util::backquote($cfgRelation['table_info'])
1488 . ' SET display_field = \'' . $GLOBALS['dbi']->escapeString(
1489 $new_name
1490 ) . '\''
1491 . ' WHERE db_name = \'' . $GLOBALS['dbi']->escapeString($db)
1492 . '\''
1493 . ' AND table_name = \'' . $GLOBALS['dbi']->escapeString($table)
1494 . '\''
1495 . ' AND display_field = \'' . $GLOBALS['dbi']->escapeString($field)
1496 . '\'';
1497 PMA_queryAsControlUser($table_query);
1500 if ($cfgRelation['relwork']) {
1501 $table_query = 'UPDATE '
1502 . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
1503 . PMA\libraries\Util::backquote($cfgRelation['relation'])
1504 . ' SET master_field = \'' . $GLOBALS['dbi']->escapeString(
1505 $new_name
1506 ) . '\''
1507 . ' WHERE master_db = \'' . $GLOBALS['dbi']->escapeString($db)
1508 . '\''
1509 . ' AND master_table = \'' . $GLOBALS['dbi']->escapeString($table)
1510 . '\''
1511 . ' AND master_field = \'' . $GLOBALS['dbi']->escapeString($field)
1512 . '\'';
1513 PMA_queryAsControlUser($table_query);
1515 $table_query = 'UPDATE '
1516 . PMA\libraries\Util::backquote($cfgRelation['db']) . '.'
1517 . PMA\libraries\Util::backquote($cfgRelation['relation'])
1518 . ' SET foreign_field = \'' . $GLOBALS['dbi']->escapeString(
1519 $new_name
1520 ) . '\''
1521 . ' WHERE foreign_db = \'' . $GLOBALS['dbi']->escapeString($db)
1522 . '\''
1523 . ' AND foreign_table = \'' . $GLOBALS['dbi']->escapeString($table)
1524 . '\''
1525 . ' AND foreign_field = \'' . $GLOBALS['dbi']->escapeString($field)
1526 . '\'';
1527 PMA_queryAsControlUser($table_query);
1529 } // end if relwork
1534 * Performs SQL query used for renaming table.
1536 * @param string $table Relation table to use
1537 * @param string $source_db Source database name
1538 * @param string $target_db Target database name
1539 * @param string $source_table Source table name
1540 * @param string $target_table Target table name
1541 * @param string $db_field Name of database field
1542 * @param string $table_field Name of table field
1544 * @return void
1546 function PMA_REL_renameSingleTable($table,
1547 $source_db, $target_db,
1548 $source_table, $target_table,
1549 $db_field, $table_field
1551 $query = 'UPDATE '
1552 . PMA\libraries\Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
1553 . PMA\libraries\Util::backquote($GLOBALS['cfgRelation'][$table])
1554 . ' SET '
1555 . $db_field . ' = \'' . $GLOBALS['dbi']->escapeString($target_db)
1556 . '\', '
1557 . $table_field . ' = \'' . $GLOBALS['dbi']->escapeString($target_table)
1558 . '\''
1559 . ' WHERE '
1560 . $db_field . ' = \'' . $GLOBALS['dbi']->escapeString($source_db) . '\''
1561 . ' AND '
1562 . $table_field . ' = \'' . $GLOBALS['dbi']->escapeString($source_table)
1563 . '\'';
1564 PMA_queryAsControlUser($query);
1569 * Rename a table in relation tables
1571 * usually called after table has been moved
1573 * @param string $source_db Source database name
1574 * @param string $target_db Target database name
1575 * @param string $source_table Source table name
1576 * @param string $target_table Target table name
1578 * @return void
1580 function PMA_REL_renameTable($source_db, $target_db, $source_table, $target_table)
1582 // Move old entries from PMA-DBs to new table
1583 if ($GLOBALS['cfgRelation']['commwork']) {
1584 PMA_REL_renameSingleTable(
1585 'column_info',
1586 $source_db, $target_db,
1587 $source_table, $target_table,
1588 'db_name', 'table_name'
1592 // updating bookmarks is not possible since only a single table is
1593 // moved, and not the whole DB.
1595 if ($GLOBALS['cfgRelation']['displaywork']) {
1596 PMA_REL_renameSingleTable(
1597 'table_info',
1598 $source_db, $target_db,
1599 $source_table, $target_table,
1600 'db_name', 'table_name'
1604 if ($GLOBALS['cfgRelation']['relwork']) {
1605 PMA_REL_renameSingleTable(
1606 'relation',
1607 $source_db, $target_db,
1608 $source_table, $target_table,
1609 'foreign_db', 'foreign_table'
1612 PMA_REL_renameSingleTable(
1613 'relation',
1614 $source_db, $target_db,
1615 $source_table, $target_table,
1616 'master_db', 'master_table'
1620 if ($GLOBALS['cfgRelation']['pdfwork']) {
1621 if ($source_db == $target_db) {
1622 // rename within the database can be handled
1623 PMA_REL_renameSingleTable(
1624 'table_coords',
1625 $source_db, $target_db,
1626 $source_table, $target_table,
1627 'db_name', 'table_name'
1629 } else {
1630 // if the table is moved out of the database we can no loger keep the
1631 // record for table coordinate
1632 $remove_query = "DELETE FROM "
1633 . PMA\libraries\Util::backquote($GLOBALS['cfgRelation']['db']) . "."
1634 . PMA\libraries\Util::backquote($GLOBALS['cfgRelation']['table_coords'])
1635 . " WHERE db_name = '" . $GLOBALS['dbi']->escapeString($source_db) . "'"
1636 . " AND table_name = '" . $GLOBALS['dbi']->escapeString($source_table)
1637 . "'";
1638 PMA_queryAsControlUser($remove_query);
1642 if ($GLOBALS['cfgRelation']['uiprefswork']) {
1643 PMA_REL_renameSingleTable(
1644 'table_uiprefs',
1645 $source_db, $target_db,
1646 $source_table, $target_table,
1647 'db_name', 'table_name'
1651 if ($GLOBALS['cfgRelation']['navwork']) {
1652 // update hidden items inside table
1653 PMA_REL_renameSingleTable(
1654 'navigationhiding',
1655 $source_db, $target_db,
1656 $source_table, $target_table,
1657 'db_name', 'table_name'
1660 // update data for hidden table
1661 $query = "UPDATE "
1662 . PMA\libraries\Util::backquote($GLOBALS['cfgRelation']['db']) . "."
1663 . PMA\libraries\Util::backquote(
1664 $GLOBALS['cfgRelation']['navigationhiding']
1666 . " SET db_name = '" . $GLOBALS['dbi']->escapeString($target_db)
1667 . "',"
1668 . " item_name = '" . $GLOBALS['dbi']->escapeString($target_table)
1669 . "'"
1670 . " WHERE db_name = '" . $GLOBALS['dbi']->escapeString($source_db)
1671 . "'"
1672 . " AND item_name = '" . $GLOBALS['dbi']->escapeString($source_table)
1673 . "'"
1674 . " AND item_type = 'table'";
1675 PMA_queryAsControlUser($query);
1680 * Create a PDF page
1682 * @param string $newpage name of the new PDF page
1683 * @param array $cfgRelation Relation configuration
1684 * @param string $db database name
1686 * @return int $pdf_page_number
1688 function PMA_REL_createPage($newpage, $cfgRelation, $db)
1690 if (! isset($newpage) || $newpage == '') {
1691 $newpage = __('no description');
1693 $ins_query = 'INSERT INTO '
1694 . PMA\libraries\Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
1695 . PMA\libraries\Util::backquote($cfgRelation['pdf_pages'])
1696 . ' (db_name, page_descr)'
1697 . ' VALUES (\''
1698 . $GLOBALS['dbi']->escapeString($db) . '\', \''
1699 . $GLOBALS['dbi']->escapeString($newpage) . '\')';
1700 PMA_queryAsControlUser($ins_query, false);
1702 return $GLOBALS['dbi']->insertId(
1703 isset($GLOBALS['controllink']) ? $GLOBALS['controllink'] : ''
1708 * Get child table references for a table column.
1709 * This works only if 'DisableIS' is false. An empty array is returned otherwise.
1711 * @param string $db name of master table db.
1712 * @param string $table name of master table.
1713 * @param string $column name of master table column.
1715 * @return array $child_references
1717 function PMA_getChildReferences($db, $table, $column = '')
1719 $child_references = array();
1720 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1721 $rel_query = "SELECT `column_name`, `table_name`,"
1722 . " `table_schema`, `referenced_column_name`"
1723 . " FROM `information_schema`.`key_column_usage`"
1724 . " WHERE `referenced_table_name` = '"
1725 . $GLOBALS['dbi']->escapeString($table) . "'"
1726 . " AND `referenced_table_schema` = '"
1727 . $GLOBALS['dbi']->escapeString($db) . "'";
1728 if ($column) {
1729 $rel_query .= " AND `referenced_column_name` = '"
1730 . $GLOBALS['dbi']->escapeString($column) . "'";
1733 $child_references = $GLOBALS['dbi']->fetchResult(
1734 $rel_query, array('referenced_column_name', null)
1737 return $child_references;
1741 * Check child table references and foreign key for a table column.
1743 * @param string $db name of master table db.
1744 * @param string $table name of master table.
1745 * @param string $column name of master table column.
1746 * @param array $foreigners_full foreiners array for the whole table.
1747 * @param array $child_references_full child references for the whole table.
1749 * @return array $column_status telling about references if foreign key.
1751 function PMA_checkChildForeignReferences(
1752 $db, $table, $column, $foreigners_full = null, $child_references_full = null
1754 $column_status = array();
1755 $column_status['isEditable'] = false;
1756 $column_status['isReferenced'] = false;
1757 $column_status['isForeignKey'] = false;
1758 $column_status['references'] = array();
1760 $foreigners = array();
1761 if ($foreigners_full !== null) {
1762 if (isset($foreigners_full[$column])) {
1763 $foreigners[$column] = $foreigners_full[$column];
1765 if (isset($foreigners_full['foreign_keys_data'])) {
1766 $foreigners['foreign_keys_data'] = $foreigners_full['foreign_keys_data'];
1768 } else {
1769 $foreigners = PMA_getForeigners($db, $table, $column, 'foreign');
1771 $foreigner = PMA_searchColumnInForeigners($foreigners, $column);
1773 $child_references = array();
1774 if ($child_references_full !== null) {
1775 if (isset($child_references_full[$column])) {
1776 $child_references = $child_references_full[$column];
1778 } else {
1779 $child_references = PMA_getChildReferences($db, $table, $column);
1782 if (sizeof($child_references, 0) > 0
1783 || $foreigner
1785 if (sizeof($child_references, 0) > 0) {
1786 $column_status['isReferenced'] = true;
1787 foreach ($child_references as $columns) {
1788 array_push(
1789 $column_status['references'],
1790 PMA\libraries\Util::backquote($columns['table_schema'])
1791 . '.' . PMA\libraries\Util::backquote($columns['table_name'])
1796 if ($foreigner) {
1797 $column_status['isForeignKey'] = true;
1799 } else {
1800 $column_status['isEditable'] = true;
1803 return $column_status;
1807 * Search a table column in foreign data.
1809 * @param array $foreigners Table Foreign data
1810 * @param string $column Column name
1812 * @return bool|array
1814 function PMA_searchColumnInForeigners($foreigners, $column)
1816 if (isset($foreigners[$column])) {
1817 return $foreigners[$column];
1818 } else {
1819 $foreigner = array();
1820 foreach ($foreigners['foreign_keys_data'] as $one_key) {
1821 $column_index = array_search($column, $one_key['index_list']);
1822 if ($column_index !== false) {
1823 $foreigner['foreign_field']
1824 = $one_key['ref_index_list'][$column_index];
1825 $foreigner['foreign_db'] = isset($one_key['ref_db_name'])
1826 ? $one_key['ref_db_name']
1827 : $GLOBALS['db'];
1828 $foreigner['foreign_table'] = $one_key['ref_table_name'];
1829 $foreigner['constraint'] = $one_key['constraint'];
1830 $foreigner['on_update'] = isset($one_key['on_update'])
1831 ? $one_key['on_update']
1832 : 'RESTRICT';
1833 $foreigner['on_delete'] = isset($one_key['on_delete'])
1834 ? $one_key['on_delete']
1835 : 'RESTRICT';
1837 return $foreigner;
1842 return false;
1846 * Returns default PMA table names and their create queries.
1848 * @return array table name, create query
1850 function PMA_getDefaultPMATableNames()
1852 $pma_tables = array();
1853 $create_tables_file = file_get_contents(
1854 SQL_DIR . 'create_tables.sql'
1857 $queries = explode(';', $create_tables_file);
1859 foreach ($queries as $query) {
1860 if (preg_match(
1861 '/CREATE TABLE IF NOT EXISTS `(.*)` \(/',
1862 $query,
1863 $table
1866 $pma_tables[$table[1]] = $query . ';';
1870 return $pma_tables;
1874 * Create a table named phpmyadmin to be used as configuration storage
1876 * @return bool
1878 function PMA_createPMADatabase()
1880 $GLOBALS['dbi']->tryQuery("CREATE DATABASE IF NOT EXISTS `phpmyadmin`");
1881 if ($error = $GLOBALS['dbi']->getError()) {
1882 if ($GLOBALS['errno'] == 1044) {
1883 $GLOBALS['message'] = __(
1884 'You do not have necessary privileges to create a database named'
1885 . ' \'phpmyadmin\'. You may go to \'Operations\' tab of any'
1886 . ' database to set up the phpMyAdmin configuration storage there.'
1888 } else {
1889 $GLOBALS['message'] = $error;
1891 return false;
1893 return true;
1897 * Creates PMA tables in the given db, updates if already exists.
1899 * @param string $db database
1900 * @param boolean $create whether to create tables if they don't exist.
1902 * @return void
1904 function PMA_fixPMATables($db, $create = true)
1906 $tablesToFeatures = array(
1907 'pma__bookmark' => 'bookmarktable',
1908 'pma__relation' => 'relation',
1909 'pma__table_info' => 'table_info',
1910 'pma__table_coords' => 'table_coords',
1911 'pma__pdf_pages' => 'pdf_pages',
1912 'pma__column_info' => 'column_info',
1913 'pma__history' => 'history',
1914 'pma__recent' => 'recent',
1915 'pma__favorite' => 'favorite',
1916 'pma__table_uiprefs' => 'table_uiprefs',
1917 'pma__tracking' => 'tracking',
1918 'pma__userconfig' => 'userconfig',
1919 'pma__users' => 'users',
1920 'pma__usergroups' => 'usergroups',
1921 'pma__navigationhiding' => 'navigationhiding',
1922 'pma__savedsearches' => 'savedsearches',
1923 'pma__central_columns' => 'central_columns',
1924 'pma__designer_settings' => 'designer_settings',
1925 'pma__export_templates' => 'export_templates',
1928 $existingTables = $GLOBALS['dbi']->getTables($db, $GLOBALS['controllink']);
1930 $createQueries = null;
1931 $foundOne = false;
1932 foreach ($tablesToFeatures as $table => $feature) {
1933 if (! in_array($table, $existingTables)) {
1934 if ($create) {
1935 if ($createQueries == null) { // first create
1936 $createQueries = PMA_getDefaultPMATableNames();
1937 $GLOBALS['dbi']->selectDb($db);
1939 $GLOBALS['dbi']->tryQuery($createQueries[$table]);
1940 if ($error = $GLOBALS['dbi']->getError()) {
1941 $GLOBALS['message'] = $error;
1942 return;
1944 $foundOne = true;
1945 $GLOBALS['cfg']['Server'][$feature] = $table;
1947 } else {
1948 $foundOne = true;
1949 $GLOBALS['cfg']['Server'][$feature] = $table;
1953 if (! $foundOne) {
1954 return;
1956 $GLOBALS['cfg']['Server']['pmadb'] = $db;
1957 $_SESSION['relation'][$GLOBALS['server']] = PMA_checkRelationsParam();
1959 $cfgRelation = PMA_getRelationsParam();
1960 if ($cfgRelation['recentwork'] || $cfgRelation['favoritework']) {
1961 // Since configuration storage is updated, we need to
1962 // re-initialize the favorite and recent tables stored in the
1963 // session from the current configuration storage.
1964 if ($cfgRelation['favoritework']) {
1965 $fav_tables = RecentFavoriteTable::getInstance('favorite');
1966 $_SESSION['tmpval']['favorite_tables'][$GLOBALS['server']]
1967 = $fav_tables->getFromDb();
1970 if ($cfgRelation['recentwork']) {
1971 $recent_tables = RecentFavoriteTable::getInstance('recent');
1972 $_SESSION['tmpval']['recent_tables'][$GLOBALS['server']]
1973 = $recent_tables->getFromDb();
1976 // Reload navi panel to update the recent/favorite lists.
1977 $GLOBALS['reload'] = true;
1982 * Get Html for PMA tables fixing anchor.
1984 * @param boolean $allTables whether to create all tables
1985 * @param boolean $createDb whether to create the pmadb also
1987 * @return string Html
1989 function PMA_getHtmlFixPMATables($allTables, $createDb = false)
1991 $retval = '';
1993 $url_query = URL::getCommon(array('db' => $GLOBALS['db']));
1994 if ($allTables) {
1995 if ($createDb) {
1996 $url_query .= '&amp;goto=db_operations.php&amp;create_pmadb=1';
1997 $message = Message::notice(
1999 '%sCreate%s a database named \'phpmyadmin\' and setup '
2000 . 'the phpMyAdmin configuration storage there.'
2003 } else {
2004 $url_query .= '&amp;goto=db_operations.php&amp;fixall_pmadb=1';
2005 $message = Message::notice(
2007 '%sCreate%s the phpMyAdmin configuration storage in the '
2008 . 'current database.'
2012 } else {
2013 $url_query .= '&amp;goto=db_operations.php&amp;fix_pmadb=1';
2014 $message = Message::notice(
2015 __('%sCreate%s missing phpMyAdmin configuration storage tables.')
2018 $message->addParamHtml('<a href="./chk_rel.php' . $url_query . '">');
2019 $message->addParamHtml('</a>');
2021 $retval .= $message->getDisplay();
2023 return $retval;
2027 * Gets the relations info and status, depending on the condition
2029 * @param boolean $condition whether to look for foreigners or not
2030 * @param string $db database name
2031 * @param string $table table name
2033 * @return array ($res_rel, $have_rel)
2035 function PMA_getRelationsAndStatus($condition, $db, $table)
2037 if ($condition) {
2038 // Find which tables are related with the current one and write it in
2039 // an array
2040 $res_rel = PMA_getForeigners($db, $table);
2042 if (count($res_rel) > 0) {
2043 $have_rel = true;
2044 } else {
2045 $have_rel = false;
2047 } else {
2048 $have_rel = false;
2049 $res_rel = array();
2050 } // end if
2051 return(array($res_rel, $have_rel));
2055 * Verifies if all the pmadb tables are defined
2057 * @return boolean
2059 function PMA_arePmadbTablesDefined()
2061 if (empty($GLOBALS['cfg']['Server']['bookmarktable'])
2062 || empty($GLOBALS['cfg']['Server']['relation'])
2063 || empty($GLOBALS['cfg']['Server']['table_info'])
2064 || empty($GLOBALS['cfg']['Server']['table_coords'])
2065 || empty($GLOBALS['cfg']['Server']['column_info'])
2066 || empty($GLOBALS['cfg']['Server']['pdf_pages'])
2067 || empty($GLOBALS['cfg']['Server']['history'])
2068 || empty($GLOBALS['cfg']['Server']['recent'])
2069 || empty($GLOBALS['cfg']['Server']['favorite'])
2070 || empty($GLOBALS['cfg']['Server']['table_uiprefs'])
2071 || empty($GLOBALS['cfg']['Server']['tracking'])
2072 || empty($GLOBALS['cfg']['Server']['userconfig'])
2073 || empty($GLOBALS['cfg']['Server']['users'])
2074 || empty($GLOBALS['cfg']['Server']['usergroups'])
2075 || empty($GLOBALS['cfg']['Server']['navigationhiding'])
2076 || empty($GLOBALS['cfg']['Server']['savedsearches'])
2077 || empty($GLOBALS['cfg']['Server']['central_columns'])
2078 || empty($GLOBALS['cfg']['Server']['designer_settings'])
2079 || empty($GLOBALS['cfg']['Server']['export_templates'])
2081 return false;
2082 } else {
2083 return true;