Translated using Weblate (Norwegian Bokmål)
[phpmyadmin.git] / libraries / relation.lib.php
blobe10f4a18adddab9317269d8962d85873c04b3eca
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 if (! defined('PHPMYADMIN')) {
9 exit;
12 /**
13 * Executes a query as controluser if possible, otherwise as normal user
15 * @param string $sql the query to execute
16 * @param boolean $show_error whether to display SQL error messages or not
17 * @param int $options query options
19 * @return integer the result set, or false if no result set
21 * @access public
24 function PMA_queryAsControlUser($sql, $show_error = true, $options = 0)
26 // Avoid caching of the number of rows affected; for example, this function
27 // is called for tracking purposes but we want to display the correct number
28 // of rows affected by the original query, not by the query generated for
29 // tracking.
30 $cache_affected_rows = false;
32 if ($show_error) {
33 $result = $GLOBALS['dbi']->query(
34 $sql,
35 $GLOBALS['controllink'],
36 $options,
37 $cache_affected_rows
39 } else {
40 $result = @$GLOBALS['dbi']->tryQuery(
41 $sql,
42 $GLOBALS['controllink'],
43 $options,
44 $cache_affected_rows
46 } // end if... else...
48 if ($result) {
49 return $result;
50 } else {
51 return false;
53 } // end of the "PMA_queryAsControlUser()" function
55 /**
56 * Returns current relation parameters
58 * @return array $cfgRelation
60 function PMA_getRelationsParam()
62 if (empty($_SESSION['relation'][$GLOBALS['server']])) {
63 $_SESSION['relation'][$GLOBALS['server']] = PMA_checkRelationsParam();
66 // just for BC but needs to be before PMA_getRelationsParamDiagnostic()
67 // which uses it
68 $GLOBALS['cfgRelation'] = $_SESSION['relation'][$GLOBALS['server']];
70 return $_SESSION['relation'][$GLOBALS['server']];
73 /**
74 * prints out diagnostic info for pma relation feature
76 * @param array $cfgRelation Relation configuration
78 * @return string
80 function PMA_getRelationsParamDiagnostic($cfgRelation)
82 $retval = '<br>';
84 $messages = array();
85 $messages['error'] = '<font color="red"><strong>'
86 . __('not OK')
87 . '</strong></font>';
89 $messages['ok'] = '<font color="green"><strong>'
90 . _pgettext('Correctly working', 'OK')
91 . '</strong></font>';
93 $messages['enabled'] = '<font color="green">' . __('Enabled') . '</font>';
94 $messages['disabled'] = '<font color="red">' . __('Disabled') . '</font>';
96 if (empty($cfgRelation['db'])) {
97 $retval .= __('Configuration of pmadb… ')
98 . $messages['error']
99 . PMA_Util::showDocu('setup', 'linked-tables')
100 . '<br />' . "\n"
101 . __('General relation features')
102 . ' <font color="green">' . __('Disabled')
103 . '</font>' . "\n";
104 if ($GLOBALS['cfg']['ZeroConf']) {
105 if (empty($GLOBALS['db'])) {
106 $retval .= PMA_getHtmlFixPMATables(true, true);
107 } else {
108 $retval .= PMA_getHtmlFixPMATables(true);
111 } else {
112 $retval .= '<table>' . "\n";
114 if (! $cfgRelation['allworks'] && $GLOBALS['cfg']['ZeroConf']) {
115 $retval .= PMA_getHtmlFixPMATables(false);
116 $retval .= '<br />';
119 $retval .= PMA_getDiagMessageForParameter(
120 'pmadb',
121 $cfgRelation['db'],
122 $messages,
123 'pmadb'
125 $retval .= PMA_getDiagMessageForParameter(
126 'relation',
127 isset($cfgRelation['relation']),
128 $messages,
129 'relation'
131 $retval .= PMA_getDiagMessageForFeature(
132 __('General relation features'),
133 'relwork',
134 $messages
136 $retval .= PMA_getDiagMessageForParameter(
137 'table_info',
138 isset($cfgRelation['table_info']),
139 $messages,
140 'table_info'
142 $retval .= PMA_getDiagMessageForFeature(
143 __('Display Features'),
144 'displaywork',
145 $messages
147 $retval .= PMA_getDiagMessageForParameter(
148 'table_coords',
149 isset($cfgRelation['table_coords']),
150 $messages,
151 'table_coords'
153 $retval .= PMA_getDiagMessageForParameter(
154 'pdf_pages',
155 isset($cfgRelation['pdf_pages']),
156 $messages,
157 'pdf_pages'
159 $retval .= PMA_getDiagMessageForFeature(
160 __('Designer and creation of PDFs'),
161 'pdfwork',
162 $messages
164 $retval .= PMA_getDiagMessageForParameter(
165 'column_info',
166 isset($cfgRelation['column_info']),
167 $messages,
168 'column_info'
170 $retval .= PMA_getDiagMessageForFeature(
171 __('Displaying Column Comments'),
172 'commwork',
173 $messages,
174 false
176 $retval .= PMA_getDiagMessageForFeature(
177 __('Browser transformation'),
178 'mimework',
179 $messages
181 if ($cfgRelation['commwork'] && ! $cfgRelation['mimework']) {
182 $retval .= '<tr><td colspan=2 class="left error">';
183 $retval .= __(
184 'Please see the documentation on how to'
185 . ' update your column_info table. '
187 $retval .= PMA_Util::showDocu('config', 'cfg_Servers_column_info');
188 $retval .= '</td></tr>';
190 $retval .= PMA_getDiagMessageForParameter(
191 'bookmarktable',
192 isset($cfgRelation['bookmark']),
193 $messages,
194 'bookmark'
196 $retval .= PMA_getDiagMessageForFeature(
197 __('Bookmarked SQL query'),
198 'bookmarkwork',
199 $messages
201 $retval .= PMA_getDiagMessageForParameter(
202 'history',
203 isset($cfgRelation['history']),
204 $messages,
205 'history'
207 $retval .= PMA_getDiagMessageForFeature(
208 __('SQL history'),
209 'historywork',
210 $messages
212 $retval .= PMA_getDiagMessageForParameter(
213 'recent',
214 isset($cfgRelation['recent']),
215 $messages,
216 'recent'
218 $retval .= PMA_getDiagMessageForFeature(
219 __('Persistent recently used tables'),
220 'recentwork',
221 $messages
223 $retval .= PMA_getDiagMessageForParameter(
224 'favorite',
225 isset($cfgRelation['favorite']),
226 $messages,
227 'favorite'
229 $retval .= PMA_getDiagMessageForFeature(
230 __('Persistent favorite tables'),
231 'favoritework',
232 $messages
234 $retval .= PMA_getDiagMessageForParameter(
235 'table_uiprefs',
236 isset($cfgRelation['table_uiprefs']),
237 $messages,
238 'table_uiprefs'
240 $retval .= PMA_getDiagMessageForFeature(
241 __('Persistent tables\' UI preferences'),
242 'uiprefswork',
243 $messages
245 $retval .= PMA_getDiagMessageForParameter(
246 'tracking',
247 isset($cfgRelation['tracking']),
248 $messages,
249 'tracking'
251 $retval .= PMA_getDiagMessageForFeature(
252 __('Tracking'),
253 'trackingwork',
254 $messages
256 $retval .= PMA_getDiagMessageForParameter(
257 'userconfig',
258 isset($cfgRelation['userconfig']),
259 $messages,
260 'userconfig'
262 $retval .= PMA_getDiagMessageForFeature(
263 __('User preferences'),
264 'userconfigwork',
265 $messages
267 $retval .= PMA_getDiagMessageForParameter(
268 'users',
269 isset($cfgRelation['users']),
270 $messages,
271 'users'
273 $retval .= PMA_getDiagMessageForParameter(
274 'usergroups',
275 isset($cfgRelation['usergroups']),
276 $messages,
277 'usergroups'
279 $retval .= PMA_getDiagMessageForFeature(
280 __('Configurable menus'),
281 'menuswork',
282 $messages
284 $retval .= PMA_getDiagMessageForParameter(
285 'navigationhiding',
286 isset($cfgRelation['navigationhiding']),
287 $messages,
288 'navigationhiding'
290 $retval .= PMA_getDiagMessageForFeature(
291 __('Hide/show navigation items'),
292 'navwork',
293 $messages
295 $retval .= PMA_getDiagMessageForParameter(
296 'savedsearches',
297 isset($cfgRelation['savedsearches']),
298 $messages,
299 'savedsearches'
301 $retval .= PMA_getDiagMessageForFeature(
302 __('Saving Query-By-Example searches'),
303 'savedsearcheswork',
304 $messages
306 $retval .= PMA_getDiagMessageForParameter(
307 'central_columns',
308 isset($cfgRelation['central_columns']),
309 $messages,
310 'central_columns'
312 $retval .= PMA_getDiagMessageForFeature(
313 __('Managing Central list of columns'),
314 'central_columnswork',
315 $messages
317 $retval .= '</table>' . "\n";
319 if (! $cfgRelation['allworks']) {
321 $retval .= '<p>' . __('Quick steps to setup advanced features:')
322 . '</p>';
323 $retval .= '<ul>';
324 $retval .= '<li>';
325 $retval .= sprintf(
327 'Create the needed tables with the '
328 . '<code>%screate_tables.sql</code>.'
330 htmlspecialchars(SQL_DIR)
332 $retval .= ' ' . PMA_Util::showDocu('setup', 'linked-tables');
333 $retval .= '</li>';
334 $retval .= '<li>';
335 $retval .= __('Create a pma user and give access to these tables.');
336 $retval .= ' ' . PMA_Util::showDocu('config', 'cfg_Servers_controluser');
337 $retval .= '</li>';
338 $retval .= '<li>';
339 $retval .= __(
340 'Enable advanced features in configuration file '
341 . '(<code>config.inc.php</code>), for example by '
342 . 'starting from <code>config.sample.inc.php</code>.'
344 $retval .= ' ' . PMA_Util::showDocu('setup', 'quick-install');
345 $retval .= '</li>';
346 $retval .= '<li>';
347 $retval .= __(
348 'Re-login to phpMyAdmin to load the updated configuration file.'
350 $retval .= '</li>';
351 $retval .= '</ul>';
355 return $retval;
359 * prints out one diagnostic message for a feature
361 * @param string $feature_name feature name in a message string
362 * @param string $relation_parameter the $GLOBALS['cfgRelation'] parameter to check
363 * @param array $messages utility messages
364 * @param boolean $skip_line whether to skip a line after the message
366 * @return string
368 function PMA_getDiagMessageForFeature($feature_name,
369 $relation_parameter, $messages, $skip_line = true
371 $retval = ' <tr><td colspan=2 class="right">' . $feature_name . ': ';
372 if (isset($GLOBALS['cfgRelation'][$relation_parameter])
373 && $GLOBALS['cfgRelation'][$relation_parameter]
375 $retval .= $messages['enabled'];
376 } else {
377 $retval .= $messages['disabled'];
379 $retval .= '</td></tr>';
380 if ($skip_line) {
381 $retval .= '<tr><td>&nbsp;</td></tr>';
383 return $retval;
387 * prints out one diagnostic message for a configuration parameter
389 * @param string $parameter config parameter name to display
390 * @param boolean $relationParameterSet whether this parameter is set
391 * @param array $messages utility messages
392 * @param string $docAnchor anchor in documentation
394 * @return string
396 function PMA_getDiagMessageForParameter($parameter,
397 $relationParameterSet, $messages, $docAnchor
399 $retval = '<tr><th class="left">';
400 $retval .= '$cfg[\'Servers\'][$i][\'' . $parameter . '\'] ... ';
401 $retval .= '</th><td class="right">';
402 if ($relationParameterSet) {
403 $retval .= $messages['ok'];
404 } else {
405 $retval .= sprintf(
406 $messages['error'],
407 PMA_Util::getDocuLink('config', 'cfg_Servers_' . $docAnchor)
410 $retval .= '</td></tr>' . "\n";
411 return $retval;
416 * Defines the relation parameters for the current user
417 * just a copy of the functions used for relations ;-)
418 * but added some stuff to check what will work
420 * @access protected
421 * @return array the relation parameters for the current user
423 function PMA_checkRelationsParam()
425 $cfgRelation = array();
426 $cfgRelation['relwork'] = false;
427 $cfgRelation['displaywork'] = false;
428 $cfgRelation['bookmarkwork'] = false;
429 $cfgRelation['pdfwork'] = false;
430 $cfgRelation['commwork'] = false;
431 $cfgRelation['mimework'] = false;
432 $cfgRelation['historywork'] = false;
433 $cfgRelation['recentwork'] = false;
434 $cfgRelation['favoritework'] = false;
435 $cfgRelation['uiprefswork'] = false;
436 $cfgRelation['trackingwork'] = false;
437 $cfgRelation['userconfigwork'] = false;
438 $cfgRelation['menuswork'] = false;
439 $cfgRelation['navwork'] = false;
440 $cfgRelation['allworks'] = false;
441 $cfgRelation['savedsearcheswork'] = false;
442 $cfgRelation['central_columnswork'] = false;
443 $cfgRelation['user'] = null;
444 $cfgRelation['db'] = null;
446 if ($GLOBALS['server'] == 0
447 || empty($GLOBALS['cfg']['Server']['pmadb'])
448 || ! $GLOBALS['dbi']->selectDb(
449 $GLOBALS['cfg']['Server']['pmadb'], $GLOBALS['controllink']
452 // No server selected -> no bookmark table
453 // we return the array with the falses in it,
454 // to avoid some 'Uninitialized string offset' errors later
455 $GLOBALS['cfg']['Server']['pmadb'] = false;
456 return $cfgRelation;
459 $cfgRelation['user'] = $GLOBALS['cfg']['Server']['user'];
460 $cfgRelation['db'] = $GLOBALS['cfg']['Server']['pmadb'];
462 // Now I just check if all tables that i need are present so I can for
463 // example enable relations but not pdf...
464 // I was thinking of checking if they have all required columns but I
465 // fear it might be too slow
467 $tab_query = 'SHOW TABLES FROM '
468 . PMA_Util::backquote(
469 $GLOBALS['cfg']['Server']['pmadb']
471 $tab_rs = PMA_queryAsControlUser(
472 $tab_query, false, PMA_DatabaseInterface::QUERY_STORE
475 if (! $tab_rs) {
476 // query failed ... ?
477 //$GLOBALS['cfg']['Server']['pmadb'] = false;
478 return $cfgRelation;
481 while ($curr_table = @$GLOBALS['dbi']->fetchRow($tab_rs)) {
482 if ($curr_table[0] == $GLOBALS['cfg']['Server']['bookmarktable']) {
483 $cfgRelation['bookmark'] = $curr_table[0];
484 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['relation']) {
485 $cfgRelation['relation'] = $curr_table[0];
486 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_info']) {
487 $cfgRelation['table_info'] = $curr_table[0];
488 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_coords']) {
489 $cfgRelation['table_coords'] = $curr_table[0];
490 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['column_info']) {
491 $cfgRelation['column_info'] = $curr_table[0];
492 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['pdf_pages']) {
493 $cfgRelation['pdf_pages'] = $curr_table[0];
494 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['history']) {
495 $cfgRelation['history'] = $curr_table[0];
496 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['recent']) {
497 $cfgRelation['recent'] = $curr_table[0];
498 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['favorite']) {
499 $cfgRelation['favorite'] = $curr_table[0];
500 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_uiprefs']) {
501 $cfgRelation['table_uiprefs'] = $curr_table[0];
502 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['tracking']) {
503 $cfgRelation['tracking'] = $curr_table[0];
504 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['userconfig']) {
505 $cfgRelation['userconfig'] = $curr_table[0];
506 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['users']) {
507 $cfgRelation['users'] = $curr_table[0];
508 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['usergroups']) {
509 $cfgRelation['usergroups'] = $curr_table[0];
510 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['navigationhiding']) {
511 $cfgRelation['navigationhiding'] = $curr_table[0];
512 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['savedsearches']) {
513 $cfgRelation['savedsearches'] = $curr_table[0];
514 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['central_columns']) {
515 $cfgRelation['central_columns'] = $curr_table[0];
517 } // end while
518 $GLOBALS['dbi']->freeResult($tab_rs);
520 if (isset($cfgRelation['relation'])) {
521 $cfgRelation['relwork'] = true;
522 if (isset($cfgRelation['table_info'])) {
523 $cfgRelation['displaywork'] = true;
527 if (isset($cfgRelation['table_coords']) && isset($cfgRelation['pdf_pages'])) {
528 $cfgRelation['pdfwork'] = true;
531 if (isset($cfgRelation['column_info'])) {
532 $cfgRelation['commwork'] = true;
533 // phpMyAdmin 4.3+
534 // Check for input transformations upgrade.
535 $cfgRelation['mimework'] = PMA_tryUpgradeTransformations();
538 if (isset($cfgRelation['history'])) {
539 $cfgRelation['historywork'] = true;
542 if (isset($cfgRelation['recent'])) {
543 $cfgRelation['recentwork'] = true;
546 if (isset($cfgRelation['favorite'])) {
547 $cfgRelation['favoritework'] = true;
550 if (isset($cfgRelation['table_uiprefs'])) {
551 $cfgRelation['uiprefswork'] = true;
554 if (isset($cfgRelation['tracking'])) {
555 $cfgRelation['trackingwork'] = true;
558 if (isset($cfgRelation['userconfig'])) {
559 $cfgRelation['userconfigwork'] = true;
562 if (isset($cfgRelation['bookmark'])) {
563 $cfgRelation['bookmarkwork'] = true;
566 if (isset($cfgRelation['users']) && isset($cfgRelation['usergroups'])) {
567 $cfgRelation['menuswork'] = true;
570 if (isset($cfgRelation['navigationhiding'])) {
571 $cfgRelation['navwork'] = true;
574 if (isset($cfgRelation['savedsearches'])) {
575 $cfgRelation['savedsearcheswork'] = true;
578 if (isset($cfgRelation['central_columns'])) {
579 $cfgRelation['central_columnswork'] = true;
582 if ($cfgRelation['relwork'] && $cfgRelation['displaywork']
583 && $cfgRelation['pdfwork'] && $cfgRelation['commwork']
584 && $cfgRelation['mimework'] && $cfgRelation['historywork']
585 && $cfgRelation['recentwork'] && $cfgRelation['uiprefswork']
586 && $cfgRelation['trackingwork'] && $cfgRelation['userconfigwork']
587 && $cfgRelation['bookmarkwork'] && $cfgRelation['central_columnswork']
588 && $cfgRelation['menuswork'] && $cfgRelation['navwork']
589 && $cfgRelation['savedsearcheswork'] && $cfgRelation['favoritework']
591 $cfgRelation['allworks'] = true;
594 return $cfgRelation;
595 } // end of the 'PMA_checkRelationsParam()' function
598 * Check whether column_info table input transformation
599 * upgrade is required and try to upgrade silently
601 * @return bool false if upgrade failed
603 * @access public
605 function PMA_tryUpgradeTransformations()
607 // From 4.3, new input oriented transformation feature was introduced.
608 // Check whether column_info table has input transformation columns
609 $new_cols = array(
610 "input_transformation",
611 "input_transformation_options"
613 $query = 'SHOW COLUMNS FROM '
614 . PMA_Util::backquote($GLOBALS['cfg']['Server']['pmadb'])
615 . '.' . PMA_Util::backquote($GLOBALS['cfg']['Server']['column_info'])
616 . ' WHERE Field IN (\'' . implode('\', \'', $new_cols) . '\')';
617 $result = PMA_queryAsControlUser(
618 $query, false, PMA_DatabaseInterface::QUERY_STORE
620 if ($result) {
621 $rows = $GLOBALS['dbi']->numRows($result);
622 $GLOBALS['dbi']->freeResult($result);
623 // input transformations are present
624 // no need to upgrade
625 if ($rows === 2) {
626 return true;
627 // try silent upgrade without disturbing the user
628 } else {
629 // read upgrade query file
630 $query = @file_get_contents(SQL_DIR . 'upgrade_column_info_4_3_0+.sql');
631 // replace database name from query to with set in config.inc.php
632 $query = str_replace(
633 '`phpmyadmin`',
634 PMA_Util::backquote($GLOBALS['cfg']['Server']['pmadb']),
635 $query
637 // replace pma__column_info table name from query
638 // to with set in config.inc.php
639 $query = str_replace(
640 '`pma__column_info`',
641 PMA_Util::backquote($GLOBALS['cfg']['Server']['column_info']),
642 $query
644 $GLOBALS['dbi']->tryMultiQuery($query, $GLOBALS['controllink']);
645 // skips result sets of query as we are not interested in it
646 while ($GLOBALS['dbi']->moreResults($GLOBALS['controllink'])
647 && $GLOBALS['dbi']->nextResult($GLOBALS['controllink'])
650 $error = $GLOBALS['dbi']->getError($GLOBALS['controllink']);
651 // return true if no error exists otherwise false
652 return empty($error);
655 // some failure, either in upgrading or something else
656 // make some noise, time to wake up user.
657 return false;
661 * Gets all Relations to foreign tables for a given table or
662 * optionally a given column in a table
664 * @param string $db the name of the db to check for
665 * @param string $table the name of the table to check for
666 * @param string $column the name of the column to check for
667 * @param string $source the source for foreign key information
669 * @return array db,table,column
671 * @access public
673 function PMA_getForeigners($db, $table, $column = '', $source = 'both')
675 $cfgRelation = PMA_getRelationsParam();
676 $foreign = array();
678 if ($cfgRelation['relwork'] && ($source == 'both' || $source == 'internal')) {
679 $rel_query = '
680 SELECT `master_field`,
681 `foreign_db`,
682 `foreign_table`,
683 `foreign_field`
684 FROM ' . PMA_Util::backquote($cfgRelation['db'])
685 . '.' . PMA_Util::backquote($cfgRelation['relation']) . '
686 WHERE `master_db` = \'' . PMA_Util::sqlAddSlashes($db) . '\'
687 AND `master_table` = \'' . PMA_Util::sqlAddSlashes($table) . '\' ';
688 if (/*overload*/mb_strlen($column)) {
689 $rel_query .= ' AND `master_field` = '
690 . '\'' . PMA_Util::sqlAddSlashes($column) . '\'';
692 $foreign = $GLOBALS['dbi']->fetchResult(
693 $rel_query, 'master_field', null, $GLOBALS['controllink']
697 if (($source == 'both' || $source == 'foreign') && /*overload*/mb_strlen($table)
700 $showCreateTableQuery = 'SHOW CREATE TABLE '
701 . PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table);
702 $show_create_table = $GLOBALS['dbi']->fetchValue(
703 $showCreateTableQuery, 0, 1
705 if ($show_create_table) {
706 $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
707 $foreign['foreign_keys_data'] = $analyzed_sql[0]['foreign_keys'];
712 * Emulating relations for some information_schema and data_dictionary tables
714 $isInformationSchema = /*overload*/mb_strtolower($db) == 'information_schema';
715 $is_data_dictionary = PMA_DRIZZLE
716 && /*overload*/mb_strtolower($db) == 'data_dictionary';
717 $isMysql = /*overload*/mb_strtolower($db) == 'mysql';
718 if (($isInformationSchema || $is_data_dictionary || $isMysql)
719 && ($source == 'internal' || $source == 'both')
721 if ($isInformationSchema) {
722 $relations_key = 'information_schema_relations';
723 include_once './libraries/information_schema_relations.lib.php';
724 } else if ($is_data_dictionary) {
725 $relations_key = 'data_dictionary_relations';
726 include_once './libraries/data_dictionary_relations.lib.php';
727 } else {
728 $relations_key = 'mysql_relations';
729 include_once './libraries/mysql_relations.lib.php';
731 if (isset($GLOBALS[$relations_key][$table])) {
732 foreach ($GLOBALS[$relations_key][$table] as $field => $relations) {
733 if ((! /*overload*/mb_strlen($column) || $column == $field)
734 && (! isset($foreign[$field])
735 || ! /*overload*/mb_strlen($foreign[$field]))
737 $foreign[$field] = $relations;
743 return $foreign;
744 } // end of the 'PMA_getForeigners()' function
747 * Gets the display field of a table
749 * @param string $db the name of the db to check for
750 * @param string $table the name of the table to check for
752 * @return string field name
754 * @access public
756 function PMA_getDisplayField($db, $table)
758 $cfgRelation = PMA_getRelationsParam();
761 * Try to fetch the display field from DB.
763 if ($cfgRelation['displaywork']) {
764 $disp_query = '
765 SELECT `display_field`
766 FROM ' . PMA_Util::backquote($cfgRelation['db'])
767 . '.' . PMA_Util::backquote($cfgRelation['table_info']) . '
768 WHERE `db_name` = \'' . PMA_Util::sqlAddSlashes($db) . '\'
769 AND `table_name` = \'' . PMA_Util::sqlAddSlashes($table) . '\'';
771 $row = $GLOBALS['dbi']->fetchSingleRow(
772 $disp_query, 'ASSOC', $GLOBALS['controllink']
774 if (isset($row['display_field'])) {
775 return $row['display_field'];
780 * Emulating the display field for some information_schema tables.
782 if ($db == 'information_schema') {
783 switch ($table) {
784 case 'CHARACTER_SETS':
785 return 'DESCRIPTION';
786 case 'TABLES':
787 return 'TABLE_COMMENT';
792 * No Luck...
794 return false;
796 } // end of the 'PMA_getDisplayField()' function
799 * Gets the comments for all columns of a table or the db itself
801 * @param string $db the name of the db to check for
802 * @param string $table the name of the table to check for
804 * @return array [column_name] = comment
806 * @access public
808 function PMA_getComments($db, $table = '')
810 $comments = array();
812 if ($table != '') {
813 // MySQL native column comments
814 $columns = $GLOBALS['dbi']->getColumns($db, $table, null, true);
815 if ($columns) {
816 foreach ($columns as $column) {
817 if (! empty($column['Comment'])) {
818 $comments[$column['Field']] = $column['Comment'];
822 } else {
823 $comments[] = PMA_getDbComment($db);
826 return $comments;
827 } // end of the 'PMA_getComments()' function
830 * Gets the comment for a db
832 * @param string $db the name of the db to check for
834 * @return string comment
836 * @access public
838 function PMA_getDbComment($db)
840 $cfgRelation = PMA_getRelationsParam();
841 $comment = '';
843 if ($cfgRelation['commwork']) {
844 // pmadb internal db comment
845 $com_qry = "
846 SELECT `comment`
847 FROM " . PMA_Util::backquote($cfgRelation['db'])
848 . "." . PMA_Util::backquote($cfgRelation['column_info']) . "
849 WHERE db_name = '" . PMA_Util::sqlAddSlashes($db) . "'
850 AND table_name = ''
851 AND column_name = '(db_comment)'";
852 $com_rs = PMA_queryAsControlUser(
853 $com_qry, true, PMA_DatabaseInterface::QUERY_STORE
856 if ($com_rs && $GLOBALS['dbi']->numRows($com_rs) > 0) {
857 $row = $GLOBALS['dbi']->fetchAssoc($com_rs);
858 $comment = $row['comment'];
860 $GLOBALS['dbi']->freeResult($com_rs);
863 return $comment;
864 } // end of the 'PMA_getDbComment()' function
867 * Gets the comment for a db
869 * @access public
871 * @return string comment
873 function PMA_getDbComments()
875 $cfgRelation = PMA_getRelationsParam();
876 $comments = array();
878 if ($cfgRelation['commwork']) {
879 // pmadb internal db comment
880 $com_qry = "
881 SELECT `db_name`, `comment`
882 FROM " . PMA_Util::backquote($cfgRelation['db'])
883 . "." . PMA_Util::backquote($cfgRelation['column_info']) . "
884 WHERE `column_name` = '(db_comment)'";
885 $com_rs = PMA_queryAsControlUser(
886 $com_qry, true, PMA_DatabaseInterface::QUERY_STORE
889 if ($com_rs && $GLOBALS['dbi']->numRows($com_rs) > 0) {
890 while ($row = $GLOBALS['dbi']->fetchAssoc($com_rs)) {
891 $comments[$row['db_name']] = $row['comment'];
894 $GLOBALS['dbi']->freeResult($com_rs);
897 return $comments;
898 } // end of the 'PMA_getDbComments()' function
901 * Set a database comment to a certain value.
903 * @param string $db the name of the db
904 * @param string $comment the value of the column
906 * @return boolean true, if comment-query was made.
908 * @access public
910 function PMA_setDbComment($db, $comment = '')
912 $cfgRelation = PMA_getRelationsParam();
914 if (! $cfgRelation['commwork']) {
915 return false;
918 if (/*overload*/mb_strlen($comment)) {
919 $upd_query = 'INSERT INTO '
920 . PMA_Util::backquote($cfgRelation['db']) . '.'
921 . PMA_Util::backquote($cfgRelation['column_info'])
922 . ' (`db_name`, `table_name`, `column_name`, `comment`)'
923 . ' VALUES (\''
924 . PMA_Util::sqlAddSlashes($db)
925 . "', '', '(db_comment)', '"
926 . PMA_Util::sqlAddSlashes($comment)
927 . "') "
928 . ' ON DUPLICATE KEY UPDATE '
929 . "`comment` = '" . PMA_Util::sqlAddSlashes($comment) . "'";
930 } else {
931 $upd_query = 'DELETE FROM '
932 . PMA_Util::backquote($cfgRelation['db']) . '.'
933 . PMA_Util::backquote($cfgRelation['column_info'])
934 . ' WHERE `db_name` = \'' . PMA_Util::sqlAddSlashes($db) . '\'
935 AND `table_name` = \'\'
936 AND `column_name` = \'(db_comment)\'';
939 if (isset($upd_query)) {
940 return PMA_queryAsControlUser($upd_query);
943 return false;
944 } // end of 'PMA_setDbComment()' function
947 * Set a SQL history entry
949 * @param string $db the name of the db
950 * @param string $table the name of the table
951 * @param string $username the username
952 * @param string $sqlquery the sql query
954 * @return void
956 * @access public
958 function PMA_setHistory($db, $table, $username, $sqlquery)
960 $maxCharactersInDisplayedSQL = $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'];
961 // Prevent to run this automatically on Footer class destroying in testsuite
962 if (defined('TESTSUITE')
963 || /*overload*/mb_strlen($sqlquery) > $maxCharactersInDisplayedSQL
965 return;
968 $cfgRelation = PMA_getRelationsParam();
970 if (! isset($_SESSION['sql_history'])) {
971 $_SESSION['sql_history'] = array();
974 $_SESSION['sql_history'][] = array(
975 'db' => $db,
976 'table' => $table,
977 'sqlquery' => $sqlquery,
980 if (count($_SESSION['sql_history']) > $GLOBALS['cfg']['QueryHistoryMax']) {
981 // history should not exceed a maximum count
982 array_shift($_SESSION['sql_history']);
985 if (! $cfgRelation['historywork'] || ! $GLOBALS['cfg']['QueryHistoryDB']) {
986 return;
989 PMA_queryAsControlUser(
990 'INSERT INTO '
991 . PMA_Util::backquote($cfgRelation['db']) . '.'
992 . PMA_Util::backquote($cfgRelation['history']) . '
993 (`username`,
994 `db`,
995 `table`,
996 `timevalue`,
997 `sqlquery`)
998 VALUES
999 (\'' . PMA_Util::sqlAddSlashes($username) . '\',
1000 \'' . PMA_Util::sqlAddSlashes($db) . '\',
1001 \'' . PMA_Util::sqlAddSlashes($table) . '\',
1002 NOW(),
1003 \'' . PMA_Util::sqlAddSlashes($sqlquery) . '\')'
1006 PMA_purgeHistory($username);
1008 } // end of 'PMA_setHistory()' function
1011 * Gets a SQL history entry
1013 * @param string $username the username
1015 * @return array list of history items
1017 * @access public
1019 function PMA_getHistory($username)
1021 $cfgRelation = PMA_getRelationsParam();
1023 if (! $cfgRelation['historywork']) {
1024 return false;
1028 * if db-based history is disabled but there exists a session-based
1029 * history, use it
1031 if (! $GLOBALS['cfg']['QueryHistoryDB']) {
1032 if (isset($_SESSION['sql_history'])) {
1033 return array_reverse($_SESSION['sql_history']);
1035 return false;
1038 $hist_query = '
1039 SELECT `db`,
1040 `table`,
1041 `sqlquery`,
1042 `timevalue`
1043 FROM ' . PMA_Util::backquote($cfgRelation['db'])
1044 . '.' . PMA_Util::backquote($cfgRelation['history']) . '
1045 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
1046 ORDER BY `id` DESC';
1048 return $GLOBALS['dbi']->fetchResult(
1049 $hist_query, null, null, $GLOBALS['controllink']
1051 } // end of 'PMA_getHistory()' function
1054 * purges SQL history
1056 * deletes entries that exceeds $cfg['QueryHistoryMax'], oldest first, for the
1057 * given user
1059 * @param string $username the username
1061 * @return void
1063 * @access public
1065 function PMA_purgeHistory($username)
1067 $cfgRelation = PMA_getRelationsParam();
1068 if (! $GLOBALS['cfg']['QueryHistoryDB'] || ! $cfgRelation['historywork']) {
1069 return;
1072 if (! $cfgRelation['historywork']) {
1073 return;
1076 $search_query = '
1077 SELECT `timevalue`
1078 FROM ' . PMA_Util::backquote($cfgRelation['db'])
1079 . '.' . PMA_Util::backquote($cfgRelation['history']) . '
1080 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
1081 ORDER BY `timevalue` DESC
1082 LIMIT ' . $GLOBALS['cfg']['QueryHistoryMax'] . ', 1';
1084 if ($max_time = $GLOBALS['dbi']->fetchValue(
1085 $search_query, 0, 0, $GLOBALS['controllink']
1086 )) {
1087 PMA_queryAsControlUser(
1088 'DELETE FROM '
1089 . PMA_Util::backquote($cfgRelation['db']) . '.'
1090 . PMA_Util::backquote($cfgRelation['history']) . '
1091 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
1092 AND `timevalue` <= \'' . $max_time . '\''
1095 } // end of 'PMA_purgeHistory()' function
1098 * Prepares the dropdown for one mode
1100 * @param array $foreign the keys and values for foreigns
1101 * @param string $data the current data of the dropdown
1102 * @param string $mode the needed mode
1104 * @return array the <option value=""><option>s
1106 * @access protected
1108 function PMA_buildForeignDropdown($foreign, $data, $mode)
1110 $reloptions = array();
1112 // id-only is a special mode used when no foreign display column
1113 // is available
1114 if ($mode == 'id-content' || $mode == 'id-only') {
1115 // sort for id-content
1116 if ($GLOBALS['cfg']['NaturalOrder']) {
1117 uksort($foreign, 'strnatcasecmp');
1118 } else {
1119 ksort($foreign);
1121 } elseif ($mode == 'content-id') {
1122 // sort for content-id
1123 if ($GLOBALS['cfg']['NaturalOrder']) {
1124 natcasesort($foreign);
1125 } else {
1126 asort($foreign);
1130 foreach ($foreign as $key => $value) {
1131 if (/*overload*/mb_strlen($value) <= $GLOBALS['cfg']['LimitChars']
1133 $vtitle = '';
1134 $value = htmlspecialchars($value);
1135 } else {
1136 $vtitle = htmlspecialchars($value);
1137 $value = htmlspecialchars(
1138 /*overload*/mb_substr(
1139 $value, 0, $GLOBALS['cfg']['LimitChars']
1140 ) . '...'
1144 $reloption = '<option value="' . htmlspecialchars($key) . '"';
1145 if ($vtitle != '') {
1146 $reloption .= ' title="' . $vtitle . '"';
1149 if ((string) $key == (string) $data) {
1150 $reloption .= ' selected="selected"';
1153 if ($mode == 'content-id') {
1154 $reloptions[] = $reloption . '>'
1155 . $value . '&nbsp;-&nbsp;' . htmlspecialchars($key) . '</option>';
1156 } elseif ($mode == 'id-content') {
1157 $reloptions[] = $reloption . '>'
1158 . htmlspecialchars($key) . '&nbsp;-&nbsp;' . $value . '</option>';
1159 } elseif ($mode == 'id-only') {
1160 $reloptions[] = $reloption . '>'
1161 . htmlspecialchars($key) . '</option>';
1163 } // end foreach
1165 return $reloptions;
1166 } // end of 'PMA_buildForeignDropdown' function
1169 * Outputs dropdown with values of foreign fields
1171 * @param array $disp_row array of the displayed row
1172 * @param string $foreign_field the foreign field
1173 * @param string $foreign_display the foreign field to display
1174 * @param string $data the current data of the dropdown (field in row)
1175 * @param int $max maximum number of items in the dropdown
1177 * @return string the <option value=""><option>s
1179 * @access public
1181 function PMA_foreignDropdown($disp_row, $foreign_field, $foreign_display, $data,
1182 $max = null
1184 if (null === $max) {
1185 $max = $GLOBALS['cfg']['ForeignKeyMaxLimit'];
1188 $foreign = array();
1190 // collect the data
1191 foreach ($disp_row as $relrow) {
1192 $key = $relrow[$foreign_field];
1194 // if the display field has been defined for this foreign table
1195 if ($foreign_display) {
1196 $value = $relrow[$foreign_display];
1197 } else {
1198 $value = '';
1199 } // end if ($foreign_display)
1201 $foreign[$key] = $value;
1202 } // end foreach
1204 // put the dropdown sections in correct order
1205 $top = array();
1206 $bottom = array();
1207 if ($foreign_display) {
1208 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'], 'array')) {
1209 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][0])) {
1210 $top = PMA_buildForeignDropdown(
1211 $foreign,
1212 $data,
1213 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][0]
1216 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][1])) {
1217 $bottom = PMA_buildForeignDropdown(
1218 $foreign,
1219 $data,
1220 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][1]
1223 } else {
1224 $top = PMA_buildForeignDropdown($foreign, $data, 'id-content');
1225 $bottom = PMA_buildForeignDropdown($foreign, $data, 'content-id');
1227 } else {
1228 $top = PMA_buildForeignDropdown($foreign, $data, 'id-only');
1231 // beginning of dropdown
1232 $ret = '<option value="">&nbsp;</option>';
1233 $top_count = count($top);
1234 if ($max == -1 || $top_count < $max) {
1235 $ret .= implode('', $top);
1236 if ($foreign_display && $top_count > 0) {
1237 // this empty option is to visually mark the beginning of the
1238 // second series of values (bottom)
1239 $ret .= '<option value="">&nbsp;</option>';
1242 if ($foreign_display) {
1243 $ret .= implode('', $bottom);
1246 return $ret;
1247 } // end of 'PMA_foreignDropdown()' function
1250 * Gets foreign keys in preparation for a drop-down selector
1252 * @param array|boolean $foreigners array of the foreign keys
1253 * @param string $field the foreign field name
1254 * @param bool $override_total whether to override the total
1255 * @param string $foreign_filter a possible filter
1256 * @param string $foreign_limit a possible LIMIT clause
1258 * @return array data about the foreign keys
1260 * @access public
1262 function PMA_getForeignData(
1263 $foreigners, $field, $override_total, $foreign_filter, $foreign_limit
1265 // we always show the foreign field in the drop-down; if a display
1266 // field is defined, we show it besides the foreign field
1267 $foreign_link = false;
1268 do {
1269 if (! $foreigners) {
1270 break;
1272 $foreigner = PMA_searchColumnInForeigners($foreigners, $field);
1273 if ($foreigner != false) {
1274 $foreign_db = $foreigner['foreign_db'];
1275 $foreign_table = $foreigner['foreign_table'];
1276 $foreign_field = $foreigner['foreign_field'];
1277 } else {
1278 break;
1281 // Count number of rows in the foreign table. Currently we do
1282 // not use a drop-down if more than ForeignKeyMaxLimit rows in the
1283 // foreign table,
1284 // for speed reasons and because we need a better interface for this.
1286 // We could also do the SELECT anyway, with a LIMIT, and ensure that
1287 // the current value of the field is one of the choices.
1289 $the_total = PMA_Table::countRecords($foreign_db, $foreign_table, true);
1291 if ($override_total == true
1292 || $the_total < $GLOBALS['cfg']['ForeignKeyMaxLimit']
1294 // foreign_display can be false if no display field defined:
1295 $foreign_display = PMA_getDisplayField($foreign_db, $foreign_table);
1297 $f_query_main = 'SELECT ' . PMA_Util::backquote($foreign_field)
1299 ($foreign_display == false)
1300 ? ''
1301 : ', ' . PMA_Util::backquote($foreign_display)
1303 $f_query_from = ' FROM ' . PMA_Util::backquote($foreign_db)
1304 . '.' . PMA_Util::backquote($foreign_table);
1305 $f_query_filter = empty($foreign_filter) ? '' : ' WHERE '
1306 . PMA_Util::backquote($foreign_field)
1307 . ' LIKE "%' . PMA_Util::sqlAddSlashes($foreign_filter, true) . '%"'
1309 ($foreign_display == false)
1310 ? ''
1311 : ' OR ' . PMA_Util::backquote($foreign_display)
1312 . ' LIKE "%' . PMA_Util::sqlAddSlashes($foreign_filter, true)
1313 . '%"'
1315 $f_query_order = ($foreign_display == false) ? '' :' ORDER BY '
1316 . PMA_Util::backquote($foreign_table) . '.'
1317 . PMA_Util::backquote($foreign_display);
1318 $f_query_limit = isset($foreign_limit) ? $foreign_limit : '';
1320 if (!empty($foreign_filter)) {
1321 $the_total = $GLOBALS['dbi']->fetchValue(
1322 'SELECT COUNT(*)' . $f_query_from . $f_query_filter
1324 if ($the_total === false) {
1325 $the_total = 0;
1329 $disp = $GLOBALS['dbi']->tryQuery(
1330 $f_query_main . $f_query_from . $f_query_filter
1331 . $f_query_order . $f_query_limit
1333 if ($disp && $GLOBALS['dbi']->numRows($disp) > 0) {
1334 // If a resultset has been created, pre-cache it in the $disp_row
1335 // array. This helps us from not needing to use mysql_data_seek by
1336 // accessing a pre-cached PHP array. Usually those resultsets are
1337 // not that big, so a performance hit should not be expected.
1338 $disp_row = array();
1339 while ($single_disp_row = @$GLOBALS['dbi']->fetchAssoc($disp)) {
1340 $disp_row[] = $single_disp_row;
1342 @$GLOBALS['dbi']->freeResult($disp);
1343 } else {
1344 // Either no data in the foreign table or
1345 // user does not have select permission to foreign table/field
1346 // Show an input field with a 'Browse foreign values' link
1347 $disp_row = null;
1348 $foreign_link = true;
1350 } else {
1351 $disp_row = null;
1352 $foreign_link = true;
1354 } while (false);
1356 $foreignData = array();
1357 $foreignData['foreign_link'] = $foreign_link;
1358 $foreignData['the_total'] = isset($the_total) ? $the_total : null;
1359 $foreignData['foreign_display'] = (
1360 isset($foreign_display) ? $foreign_display : null
1362 $foreignData['disp_row'] = isset($disp_row) ? $disp_row : null;
1363 $foreignData['foreign_field'] = isset($foreign_field) ? $foreign_field : null;
1364 return $foreignData;
1365 } // end of 'PMA_getForeignData()' function
1368 * Finds all related tables
1370 * @param array $all_tables All the involved tables
1371 * @param string $master The master table to form the LEFT JOIN clause
1373 * @return string LEFT JOIN
1374 * @access private
1376 function PMA_getRelatives($all_tables, $master)
1378 $fromclause = '';
1379 $left_joins = array();
1380 $emerg = '';
1381 $ignore_internal_relations = false;
1383 // The list of tables that we still couldn't connect
1384 $remaining_tables = $all_tables;
1385 unset($remaining_tables[$master]);
1386 // The list of already connected tables
1387 $known_tables = array();
1388 $known_tables[$master] = $master;
1389 $run = 0;
1390 while ($GLOBALS['cfgRelation']['relwork'] && count($remaining_tables) > 0) {
1391 // Whether to go from master to foreign or vice versa
1392 if ($run % 2 == 0) {
1393 $from = 'master';
1394 $to = 'foreign';
1395 } else {
1396 $from = 'foreign';
1397 $to = 'master';
1399 $in_know = '(\'' . implode('\', \'', $known_tables) . '\')';
1400 $in_left = '(\'' . implode('\', \'', $remaining_tables) . '\')';
1401 $rel_query = 'SELECT *'
1402 . ' FROM ' . PMA_Util::backquote($GLOBALS['cfgRelation']['db'])
1403 . '.' . PMA_Util::backquote($GLOBALS['cfgRelation']['relation'])
1404 . ' WHERE ' . $from . '_db = \''
1405 . PMA_Util::sqlAddSlashes($GLOBALS['db']) . '\''
1406 . ' AND ' . $to . '_db = \''
1407 . PMA_Util::sqlAddSlashes($GLOBALS['db']) . '\''
1408 . ' AND ' . $from . '_table IN ' . $in_know
1409 . ' AND ' . $to . '_table IN ' . $in_left;
1410 $relations = @$GLOBALS['dbi']->query($rel_query, $GLOBALS['controllink']);
1411 while ($row = $GLOBALS['dbi']->fetchAssoc($relations)) {
1412 $found_table = $row[$to . '_table'];
1413 if (isset($remaining_tables[$found_table])) {
1414 $left_join_with = PMA_Util::backquote($GLOBALS['db']) . '.'
1415 . PMA_Util::backquote($row[$to . '_table']);
1416 $on_condition = PMA_Util::backquote($row[$from . '_table']) . '.'
1417 . PMA_Util::backquote($row[$from . '_field']) . ' = '
1418 . PMA_Util::backquote($row[$to . '_table']) . '.'
1419 . PMA_Util::backquote($row[$to . '_field']);
1421 $left_joins[$left_join_with] = array(
1422 'left_join_with' => $left_join_with,
1423 'on_condition' => array($on_condition)
1426 $known_tables[$found_table] = $found_table;
1427 unset($remaining_tables[$found_table]);
1429 } // end while
1430 $run++;
1431 if ($run > 5) {
1432 foreach ($remaining_tables as $table) {
1433 $emerg .= ', ' . PMA_Util::backquote($table);
1434 unset($remaining_tables[$table]);
1437 } // end while
1439 // Generate 'LEFT JOIN's for InnoDB foreign keys.
1440 $remaining_tables = $all_tables;
1441 foreach ($remaining_tables as $one_table) {
1442 $foreigners = PMA_getForeigners($GLOBALS['db'], $one_table, '', 'foreign');
1443 foreach ($foreigners['foreign_keys_data'] as $one_key) {
1444 if (in_array($one_key['ref_table_name'], $all_tables)
1445 && ! isset($one_key['ref_db_name'])
1446 && ($one_key['ref_table_name'] == $master
1447 || $one_key['ref_table_name'] == $one_table)
1449 $left_join_with = PMA_Util::backquote($GLOBALS['db']) . '.'
1450 . PMA_Util::backquote($one_table);
1451 if (! isset($left_joins[$left_join_with])) {
1452 $left_joins[$left_join_with] = array(
1453 'left_join_with' =>$left_join_with,
1454 'on_condition' => array()
1458 foreach ($one_key['ref_index_list'] as $key => $one_column) {
1459 $on_condition = PMA_Util::backquote($one_key['ref_table_name'])
1460 . '.' . PMA_Util::backquote($one_column) . ' = '
1461 . PMA_Util::backquote($one_table) . '.'
1462 . PMA_Util::backquote($one_key['index_list'][$key]);
1464 if (! in_array($on_condition, $left_joins[$left_join_with]['on_condition'])) {
1465 $left_joins[$left_join_with]['on_condition'][]
1466 = $on_condition;
1469 $ignore_internal_relations = true;
1470 unset($remaining_tables[$one_table]);
1475 if ($ignore_internal_relations) {
1476 $emerg = '';
1479 // Build the 'FROM' clause.
1480 foreach ($left_joins as $one_join) {
1481 $fromclause .= "\n" . ' LEFT JOIN '
1482 . $one_join['left_join_with']
1483 . ' ON '
1484 . implode(' AND ', $one_join['on_condition']);
1487 $fromclause = $emerg . $fromclause;
1488 return $fromclause;
1489 } // end of the "PMA_getRelatives()" function
1492 * Rename a field in relation tables
1494 * usually called after a column in a table was renamed
1496 * @param string $db database name
1497 * @param string $table table name
1498 * @param string $field old field name
1499 * @param string $new_name new field name
1501 * @return void
1503 function PMA_REL_renameField($db, $table, $field, $new_name)
1505 $cfgRelation = PMA_getRelationsParam();
1507 if ($cfgRelation['displaywork']) {
1508 $table_query = 'UPDATE '
1509 . PMA_Util::backquote($cfgRelation['db']) . '.'
1510 . PMA_Util::backquote($cfgRelation['table_info'])
1511 . ' SET display_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1512 . ' WHERE db_name = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1513 . ' AND table_name = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1514 . ' AND display_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1515 PMA_queryAsControlUser($table_query);
1518 if ($cfgRelation['relwork']) {
1519 $table_query = 'UPDATE '
1520 . PMA_Util::backquote($cfgRelation['db']) . '.'
1521 . PMA_Util::backquote($cfgRelation['relation'])
1522 . ' SET master_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1523 . ' WHERE master_db = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1524 . ' AND master_table = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1525 . ' AND master_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1526 PMA_queryAsControlUser($table_query);
1528 $table_query = 'UPDATE '
1529 . PMA_Util::backquote($cfgRelation['db']) . '.'
1530 . PMA_Util::backquote($cfgRelation['relation'])
1531 . ' SET foreign_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1532 . ' WHERE foreign_db = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1533 . ' AND foreign_table = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1534 . ' AND foreign_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1535 PMA_queryAsControlUser($table_query);
1537 } // end if relwork
1542 * Performs SQL query used for renaming table.
1544 * @param string $table Relation table to use
1545 * @param string $source_db Source database name
1546 * @param string $target_db Target database name
1547 * @param string $source_table Source table name
1548 * @param string $target_table Target table name
1549 * @param string $db_field Name of database field
1550 * @param string $table_field Name of table field
1552 * @return void
1554 function PMA_REL_renameSingleTable($table,
1555 $source_db, $target_db,
1556 $source_table, $target_table,
1557 $db_field, $table_field
1559 $query = 'UPDATE '
1560 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
1561 . PMA_Util::backquote($GLOBALS['cfgRelation'][$table])
1562 . ' SET '
1563 . $db_field . ' = \'' . PMA_Util::sqlAddSlashes($target_db) . '\', '
1564 . $table_field . ' = \'' . PMA_Util::sqlAddSlashes($target_table) . '\''
1565 . ' WHERE '
1566 . $db_field . ' = \'' . PMA_Util::sqlAddSlashes($source_db) . '\''
1567 . ' AND '
1568 . $table_field . ' = \'' . PMA_Util::sqlAddSlashes($source_table) . '\'';
1569 PMA_queryAsControlUser($query);
1574 * Rename a table in relation tables
1576 * usually called after table has been moved
1578 * @param string $source_db Source database name
1579 * @param string $target_db Target database name
1580 * @param string $source_table Source table name
1581 * @param string $target_table Target table name
1583 * @return void
1585 function PMA_REL_renameTable($source_db, $target_db, $source_table, $target_table)
1587 // Move old entries from PMA-DBs to new table
1588 if ($GLOBALS['cfgRelation']['commwork']) {
1589 PMA_REL_renameSingleTable(
1590 'column_info',
1591 $source_db, $target_db,
1592 $source_table, $target_table,
1593 'db_name', 'table_name'
1597 // updating bookmarks is not possible since only a single table is
1598 // moved, and not the whole DB.
1600 if ($GLOBALS['cfgRelation']['displaywork']) {
1601 PMA_REL_renameSingleTable(
1602 'table_info',
1603 $source_db, $target_db,
1604 $source_table, $target_table,
1605 'db_name', 'table_name'
1609 if ($GLOBALS['cfgRelation']['relwork']) {
1610 PMA_REL_renameSingleTable(
1611 'relation',
1612 $source_db, $target_db,
1613 $source_table, $target_table,
1614 'foreign_db', 'foreign_table'
1617 PMA_REL_renameSingleTable(
1618 'relation',
1619 $source_db, $target_db,
1620 $source_table, $target_table,
1621 'master_db', 'master_table'
1625 if ($GLOBALS['cfgRelation']['pdfwork']) {
1626 if ($source_db == $target_db) {
1627 // rename within the database can be handled
1628 PMA_REL_renameSingleTable(
1629 'table_coords',
1630 $source_db, $target_db,
1631 $source_table, $target_table,
1632 'db_name', 'table_name'
1634 } else {
1635 // if the table is moved out of the database we can no loger keep the
1636 // record for table coordinate
1637 $remove_query = "DELETE FROM "
1638 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . "."
1639 . PMA_Util::backquote($GLOBALS['cfgRelation']['table_coords'])
1640 . " WHERE db_name = '" . PMA_Util::sqlAddSlashes($source_db) . "'"
1641 . " AND table_name = '" . PMA_Util::sqlAddSlashes($source_table)
1642 . "'";
1643 PMA_queryAsControlUser($remove_query);
1647 if ($GLOBALS['cfgRelation']['uiprefswork']) {
1648 PMA_REL_renameSingleTable(
1649 'table_uiprefs',
1650 $source_db, $target_db,
1651 $source_table, $target_table,
1652 'db_name', 'table_name'
1656 if ($GLOBALS['cfgRelation']['navwork']) {
1657 // update hidden items inside table
1658 PMA_REL_renameSingleTable(
1659 'navigationhiding',
1660 $source_db, $target_db,
1661 $source_table, $target_table,
1662 'db_name', 'table_name'
1665 // update data for hidden table
1666 $query = "UPDATE "
1667 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . "."
1668 . PMA_Util::backquote($GLOBALS['cfgRelation']['navigationhiding'])
1669 . " SET db_name = '" . PMA_Util::sqlAddSlashes($target_db) . "',"
1670 . " item_name = '" . PMA_Util::sqlAddSlashes($target_table) . "'"
1671 . " WHERE db_name = '" . PMA_Util::sqlAddSlashes($source_db) . "'"
1672 . " AND item_name = '" . PMA_Util::sqlAddSlashes($source_table) . "'"
1673 . " AND item_type = 'table'";
1674 PMA_queryAsControlUser($query);
1679 * Create a PDF page
1681 * @param string $newpage name of the new PDF page
1682 * @param array $cfgRelation Relation configuration
1683 * @param string $db database name
1685 * @return string $pdf_page_number
1687 function PMA_REL_createPage($newpage, $cfgRelation, $db)
1689 if (! isset($newpage) || $newpage == '') {
1690 $newpage = __('no description');
1692 $ins_query = 'INSERT INTO '
1693 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
1694 . PMA_Util::backquote($cfgRelation['pdf_pages'])
1695 . ' (db_name, page_descr)'
1696 . ' VALUES (\''
1697 . PMA_Util::sqlAddSlashes($db) . '\', \''
1698 . PMA_Util::sqlAddSlashes($newpage) . '\')';
1699 PMA_queryAsControlUser($ins_query, false);
1701 return $GLOBALS['dbi']->insertId(
1702 isset($GLOBALS['controllink']) ? $GLOBALS['controllink'] : ''
1707 * Get child table references for a table column.
1708 * This works only if 'DisableIS' is false. An empty array is returned otherwise.
1710 * @param string $db name of master table db.
1711 * @param string $table name of master table.
1712 * @param string $column name of master table column.
1714 * @return array $child_references
1716 function PMA_getChildReferences($db, $table, $column = '')
1718 $child_references = array();
1719 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1720 $rel_query = "SELECT `column_name`, `table_name`,"
1721 . " `table_schema`, `referenced_column_name`"
1722 . " FROM `information_schema`.`key_column_usage`"
1723 . " WHERE `referenced_table_name` = '"
1724 . PMA_Util::sqlAddSlashes($table) . "'"
1725 . " AND `referenced_table_schema` = '"
1726 . PMA_Util::sqlAddSlashes($db) . "'";
1727 if ($column) {
1728 $rel_query .= " AND `referenced_column_name` = '"
1729 . PMA_Util::sqlAddSlashes($column) . "'";
1732 $child_references = $GLOBALS['dbi']->fetchResult(
1733 $rel_query, array('referenced_column_name', null)
1736 return $child_references;
1740 * Check child table references and foreign key for a table column.
1742 * @param string $db name of master table db.
1743 * @param string $table name of master table.
1744 * @param string $column name of master table column.
1745 * @param array $foreigners_full foreiners array for the whole table.
1746 * @param array $child_references_full child references for the whole table.
1748 * @return array $column_status telling about references if foreign key.
1750 function PMA_checkChildForeignReferences(
1751 $db, $table, $column, $foreigners_full = null, $child_references_full = null
1753 $column_status = array();
1754 $column_status['isEditable'] = false;
1755 $column_status['isReferenced'] = false;
1756 $column_status['isForeignKey'] = false;
1757 $column_status['references'] = array();
1759 $foreigners = array();
1760 if ($foreigners_full !== null) {
1761 if (isset($foreigners_full[$column])) {
1762 $foreigners[$column] = $foreigners_full[$column];
1764 if (isset($foreigners_full['foreign_keys_data'])) {
1765 $foreigners['foreign_keys_data'] = $foreigners_full['foreign_keys_data'];
1767 } else {
1768 $foreigners = PMA_getForeigners($db, $table, $column, 'foreign');
1770 $foreigner = PMA_searchColumnInForeigners($foreigners, $column);
1772 $child_references = array();
1773 if ($child_references_full !== null) {
1774 if (isset($child_references_full[$column])) {
1775 $child_references = $child_references_full[$column];
1777 } else {
1778 $child_references = PMA_getChildReferences($db, $table, $column);
1781 if (sizeof($child_references, 0) > 0
1782 || $foreigner
1784 if (sizeof($child_references, 0) > 0) {
1785 $column_status['isReferenced'] = true;
1786 foreach ($child_references as $row => $columns) {
1787 array_push(
1788 $column_status['references'],
1789 PMA_Util::backquote($columns['table_schema'])
1790 . '.' . PMA_Util::backquote($columns['table_name'])
1795 if ($foreigner) {
1796 $column_status['isForeignKey'] = true;
1798 } else {
1799 $column_status['isEditable'] = true;
1802 return $column_status;
1806 * Search a table column in foreign data.
1808 * @param array $foreigners Table Foreign data
1809 * @param string $column Column name
1811 * @return bool|array
1813 function PMA_searchColumnInForeigners($foreigners, $column)
1815 if (isset($foreigners[$column])) {
1816 return $foreigners[$column];
1817 } else {
1818 $foreigner = array();
1819 foreach ($foreigners['foreign_keys_data'] as $key => $one_key) {
1820 $column_index = array_search($column, $one_key['index_list']);
1821 if ($column_index !== false) {
1822 $foreigner['foreign_field']
1823 = $one_key['ref_index_list'][$column_index];
1824 $foreigner['foreign_db'] = isset($one_key['ref_db_name'])
1825 ? $one_key['ref_db_name']
1826 : $GLOBALS['db'];
1827 $foreigner['foreign_table'] = $one_key['ref_table_name'];
1828 $foreigner['constraint'] = $one_key['constraint'];
1829 $foreigner['on_update'] = isset($one_key['on_update'])
1830 ? $one_key['on_update']
1831 : 'RESTRICT';
1832 $foreigner['on_delete'] = isset($one_key['on_delete'])
1833 ? $one_key['on_delete']
1834 : 'RESTRICT';
1836 return $foreigner;
1841 return false;
1845 * Returns default PMA table names and their create queries.
1847 * @return array table name, create query
1849 function PMA_getDefaultPMATableNames()
1851 $pma_tables = array();
1852 if (PMA_DRIZZLE) {
1853 $create_tables_file = file_get_contents(
1854 SQL_DIR . 'create_tables_drizzle.sql'
1856 } else {
1857 $create_tables_file = file_get_contents(
1858 SQL_DIR . 'create_tables.sql'
1862 $queries = explode(';', $create_tables_file);
1864 foreach ($queries as $query) {
1865 if (preg_match(
1866 '/CREATE TABLE IF NOT EXISTS `(.*)` \(/',
1867 $query,
1868 $table
1871 $pma_tables[$table[1]] = $query . ';';
1875 return $pma_tables;
1879 * Create a table named phpmyadmin to be used as configuration storage
1881 * @return bool
1883 function PMA_createPMADatabase()
1885 $GLOBALS['dbi']->tryQuery("CREATE DATABASE IF NOT EXISTS `phpmyadmin`");
1886 if ($error = $GLOBALS['dbi']->getError()) {
1887 if ($GLOBALS['errno'] == 1044) {
1888 $GLOBALS['message'] = __(
1889 'You do not have necessary privileges to create a database named'
1890 . ' \'phpmyadmin\'. You may go to \'Operations\' tab of any'
1891 . ' database to set up the phpMyAdmin configuration storage there.'
1893 } else {
1894 $GLOBALS['message'] = $error;
1896 return false;
1898 return true;
1902 * Creates PMA tables in the given db, updates if already exists.
1904 * @param string $db database
1905 * @param boolean $create whether to create tables if they don't exist.
1907 * @return void
1909 function PMA_fixPMATables($db, $create = true)
1911 $tablesToFeatures = array(
1912 'pma__bookmark' => 'bookmarktable',
1913 'pma__relation' => 'relation',
1914 'pma__table_info' => 'table_info',
1915 'pma__table_coords' => 'table_coords',
1916 'pma__pdf_pages' => 'pdf_pages',
1917 'pma__column_info' => 'column_info',
1918 'pma__history' => 'history',
1919 'pma__recent' => 'recent',
1920 'pma__favorite' => 'favorite',
1921 'pma__table_uiprefs' => 'table_uiprefs',
1922 'pma__tracking' => 'tracking',
1923 'pma__userconfig' => 'userconfig',
1924 'pma__users' => 'users',
1925 'pma__usergroups' => 'usergroups',
1926 'pma__navigationhiding' => 'navigationhiding',
1927 'pma__savedsearches' => 'savedsearches',
1928 'pma__central_columns' => 'central_columns'
1931 $existingTables = $GLOBALS['dbi']->getTables($db, $GLOBALS['controllink']);
1933 $createQueries = null;
1934 $foundOne = false;
1935 foreach ($tablesToFeatures as $table => $feature) {
1936 if (! in_array($table, $existingTables)) {
1937 if ($create) {
1938 if ($createQueries == null) { // first create
1939 $createQueries = PMA_getDefaultPMATableNames();
1940 $GLOBALS['dbi']->selectDb($db);
1942 $GLOBALS['dbi']->tryQuery($createQueries[$table]);
1943 if ($error = $GLOBALS['dbi']->getError()) {
1944 $GLOBALS['message'] = $error;
1945 return;
1947 $foundOne = true;
1948 $GLOBALS['cfg']['Server'][$feature] = $table;
1950 } else {
1951 $foundOne = true;
1952 $GLOBALS['cfg']['Server'][$feature] = $table;
1956 if (! $foundOne) {
1957 return;
1959 $GLOBALS['cfg']['Server']['pmadb'] = $db;
1960 $_SESSION['relation'][$GLOBALS['server']] = PMA_checkRelationsParam();
1962 $cfgRelation = PMA_getRelationsParam();
1963 if ($cfgRelation['recentwork'] || $cfgRelation['favoritework']) {
1964 // Since configuration storage is updated, we need to
1965 // re-initialize the favorite and recent tables stored in the
1966 // session from the current configuration storage.
1967 include_once 'libraries/RecentFavoriteTable.class.php';
1969 if ($cfgRelation['favoritework']) {
1970 $fav_tables = PMA_RecentFavoriteTable::getInstance('favorite');
1971 $_SESSION['tmpval']['favorite_tables'][$GLOBALS['server']]
1972 = $fav_tables->getFromDb();
1975 if ($cfgRelation['recentwork']) {
1976 $recent_tables = PMA_RecentFavoriteTable::getInstance('recent');
1977 $_SESSION['tmpval']['recent_tables'][$GLOBALS['server']]
1978 = $recent_tables->getFromDb();
1981 // Reload navi panel to update the recent/favorite lists.
1982 $GLOBALS['reload'] = true;
1987 * Get Html for PMA tables fixing anchor.
1989 * @param boolean $allTables whether to create all tables
1990 * @param boolean $createDb whether to create the pmadb also
1992 * @return string Html
1994 function PMA_getHtmlFixPMATables($allTables, $createDb = false)
1996 $retval = '';
1998 $url_query = PMA_URL_getCommon(array('db' => $GLOBALS['db']));
1999 if ($allTables) {
2000 if ($createDb) {
2001 $url_query .= '&amp;goto=db_operations.php&amp;create_pmadb=1';
2002 $message = PMA_Message::notice(
2004 '%sCreate%s a database named \'phpmyadmin\' and setup '
2005 . 'the phpMyAdmin configuration storage there.'
2008 } else {
2009 $url_query .= '&amp;goto=db_operations.php&amp;fixall_pmadb=1';
2010 $message = PMA_Message::notice(
2012 '%sCreate%s the phpMyAdmin configuration storage in the '
2013 . 'current database.'
2017 } else {
2018 $url_query .= '&amp;goto=db_operations.php&amp;fix_pmadb=1';
2019 $message = PMA_Message::notice(
2020 __('%sCreate%s missing phpMyAdmin configuration storage tables.')
2023 $message->addParam(
2024 '<a href="' . $GLOBALS['cfg']['PmaAbsoluteUri']
2025 . 'chk_rel.php' . $url_query . '">',
2026 false
2028 $message->addParam('</a>', false);
2030 $retval .= $message->getDisplay();
2032 return $retval;
2036 * Gets the relations info and status, depending on the condition
2038 * @param boolean $condition whether to look for foreigners or not
2039 * @param string $db database name
2040 * @param string $table table name
2042 * @return array ($res_rel, $have_rel)
2044 function PMA_getRelationsAndStatus($condition, $db, $table)
2046 if ($condition) {
2047 // Find which tables are related with the current one and write it in
2048 // an array
2049 $res_rel = PMA_getForeigners($db, $table);
2051 if (count($res_rel) > 0) {
2052 $have_rel = true;
2053 } else {
2054 $have_rel = false;
2056 } else {
2057 $have_rel = false;
2058 $res_rel = array();
2059 } // end if
2060 return(array($res_rel, $have_rel));