Translated using Weblate (Hindi)
[phpmyadmin.git] / libraries / relation.lib.php
blob1e191c321f2b7a8150e12addfe1316c53dfc893c
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 = '';
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 (! empty($GLOBALS['db']) && $GLOBALS['cfg']['ZeroConf']) {
105 $retval .= PMA_getHtmlFixPMATables(true);
107 } else {
108 $retval .= '<table>' . "\n";
110 if (! $cfgRelation['allworks'] && $GLOBALS['cfg']['ZeroConf']) {
111 $retval .= PMA_getHtmlFixPMATables(false);
112 $retval .= '<br />';
115 $retval .= PMA_getDiagMessageForParameter(
116 'pmadb',
117 $cfgRelation['db'],
118 $messages,
119 'pmadb'
121 $retval .= PMA_getDiagMessageForParameter(
122 'relation',
123 isset($cfgRelation['relation']),
124 $messages,
125 'relation'
127 $retval .= PMA_getDiagMessageForFeature(
128 __('General relation features'),
129 'relwork',
130 $messages
132 $retval .= PMA_getDiagMessageForParameter(
133 'table_info',
134 isset($cfgRelation['table_info']),
135 $messages,
136 'table_info'
138 $retval .= PMA_getDiagMessageForFeature(
139 __('Display Features'),
140 'displaywork',
141 $messages
143 $retval .= PMA_getDiagMessageForParameter(
144 'table_coords',
145 isset($cfgRelation['table_coords']),
146 $messages,
147 'table_coords'
149 $retval .= PMA_getDiagMessageForParameter(
150 'pdf_pages',
151 isset($cfgRelation['pdf_pages']),
152 $messages,
153 'pdf_pages'
155 $retval .= PMA_getDiagMessageForFeature(
156 __('Designer and creation of PDFs'),
157 'pdfwork',
158 $messages
160 $retval .= PMA_getDiagMessageForParameter(
161 'column_info',
162 isset($cfgRelation['column_info']),
163 $messages,
164 'column_info'
166 $retval .= PMA_getDiagMessageForFeature(
167 __('Displaying Column Comments'),
168 'commwork',
169 $messages,
170 false
172 $retval .= PMA_getDiagMessageForFeature(
173 __('Browser transformation'),
174 'mimework',
175 $messages
177 if ($cfgRelation['commwork'] && ! $cfgRelation['mimework']) {
178 $retval .= '<tr><td colspan=2 class="left error">';
179 $retval .= __(
180 'Please see the documentation on how to'
181 . ' update your column_info table. '
183 $retval .= PMA_Util::showDocu('config', 'cfg_Servers_column_info');
184 $retval .= '</td></tr>';
186 $retval .= PMA_getDiagMessageForParameter(
187 'bookmarktable',
188 isset($cfgRelation['bookmark']),
189 $messages,
190 'bookmark'
192 $retval .= PMA_getDiagMessageForFeature(
193 __('Bookmarked SQL query'),
194 'bookmarkwork',
195 $messages
197 $retval .= PMA_getDiagMessageForParameter(
198 'history',
199 isset($cfgRelation['history']),
200 $messages,
201 'history'
203 $retval .= PMA_getDiagMessageForFeature(
204 __('SQL history'),
205 'historywork',
206 $messages
208 $retval .= PMA_getDiagMessageForParameter(
209 'recent',
210 isset($cfgRelation['recent']),
211 $messages,
212 'recent'
214 $retval .= PMA_getDiagMessageForFeature(
215 __('Persistent recently used tables'),
216 'recentwork',
217 $messages
219 $retval .= PMA_getDiagMessageForParameter(
220 'favorite',
221 isset($cfgRelation['favorite']),
222 $messages,
223 'favorite'
225 $retval .= PMA_getDiagMessageForFeature(
226 __('Persistent favorite tables'),
227 'favoritework',
228 $messages
230 $retval .= PMA_getDiagMessageForParameter(
231 'table_uiprefs',
232 isset($cfgRelation['table_uiprefs']),
233 $messages,
234 'table_uiprefs'
236 $retval .= PMA_getDiagMessageForFeature(
237 __('Persistent tables\' UI preferences'),
238 'uiprefswork',
239 $messages
241 $retval .= PMA_getDiagMessageForParameter(
242 'tracking',
243 isset($cfgRelation['tracking']),
244 $messages,
245 'tracking'
247 $retval .= PMA_getDiagMessageForFeature(
248 __('Tracking'),
249 'trackingwork',
250 $messages
252 $retval .= PMA_getDiagMessageForParameter(
253 'userconfig',
254 isset($cfgRelation['userconfig']),
255 $messages,
256 'userconfig'
258 $retval .= PMA_getDiagMessageForFeature(
259 __('User preferences'),
260 'userconfigwork',
261 $messages
263 $retval .= PMA_getDiagMessageForParameter(
264 'users',
265 isset($cfgRelation['users']),
266 $messages,
267 'users'
269 $retval .= PMA_getDiagMessageForParameter(
270 'usergroups',
271 isset($cfgRelation['usergroups']),
272 $messages,
273 'usergroups'
275 $retval .= PMA_getDiagMessageForFeature(
276 __('Configurable menus'),
277 'menuswork',
278 $messages
280 $retval .= PMA_getDiagMessageForParameter(
281 'navigationhiding',
282 isset($cfgRelation['navigationhiding']),
283 $messages,
284 'navigationhiding'
286 $retval .= PMA_getDiagMessageForFeature(
287 __('Hide/show navigation items'),
288 'navwork',
289 $messages
291 $retval .= PMA_getDiagMessageForParameter(
292 'savedsearches',
293 isset($cfgRelation['savedsearches']),
294 $messages,
295 'savedsearches'
297 $retval .= PMA_getDiagMessageForFeature(
298 __('Saving Query-By-Example searches'),
299 'savedsearcheswork',
300 $messages
302 $retval .= PMA_getDiagMessageForParameter(
303 'central_columns',
304 isset($cfgRelation['central_columns']),
305 $messages,
306 'central_columns'
308 $retval .= PMA_getDiagMessageForFeature(
309 __('Managing Central list of columns'),
310 'central_columnswork',
311 $messages
313 $retval .= '</table>' . "\n";
315 if (! $cfgRelation['allworks']) {
317 $retval .= '<p>' . __('Quick steps to setup advanced features:')
318 . '</p>';
319 $retval .= '<ul>';
320 $retval .= '<li>';
321 $retval .= sprintf(
323 'Create the needed tables with the '
324 . '<code>%screate_tables.sql</code>.'
326 htmlspecialchars(SQL_DIR)
328 $retval .= ' ' . PMA_Util::showDocu('setup', 'linked-tables');
329 $retval .= '</li>';
330 $retval .= '<li>';
331 $retval .= __('Create a pma user and give access to these tables.');
332 $retval .= ' ' . PMA_Util::showDocu('config', 'cfg_Servers_controluser');
333 $retval .= '</li>';
334 $retval .= '<li>';
335 $retval .= __(
336 'Enable advanced features in configuration file '
337 . '(<code>config.inc.php</code>), for example by '
338 . 'starting from <code>config.sample.inc.php</code>.'
340 $retval .= ' ' . PMA_Util::showDocu('setup', 'quick-install');
341 $retval .= '</li>';
342 $retval .= '<li>';
343 $retval .= __(
344 'Re-login to phpMyAdmin to load the updated configuration file.'
346 $retval .= '</li>';
347 $retval .= '</ul>';
351 return $retval;
355 * prints out one diagnostic message for a feature
357 * @param string $feature_name feature name in a message string
358 * @param string $relation_parameter the $GLOBALS['cfgRelation'] parameter to check
359 * @param array $messages utility messages
360 * @param boolean $skip_line whether to skip a line after the message
362 * @return string
364 function PMA_getDiagMessageForFeature($feature_name,
365 $relation_parameter, $messages, $skip_line = true
367 $retval = ' <tr><td colspan=2 class="right">' . $feature_name . ': ';
368 if (isset($GLOBALS['cfgRelation'][$relation_parameter])
369 && $GLOBALS['cfgRelation'][$relation_parameter]
371 $retval .= $messages['enabled'];
372 } else {
373 $retval .= $messages['disabled'];
375 $retval .= '</td></tr>';
376 if ($skip_line) {
377 $retval .= '<tr><td>&nbsp;</td></tr>';
379 return $retval;
383 * prints out one diagnostic message for a configuration parameter
385 * @param string $parameter config parameter name to display
386 * @param boolean $relationParameterSet whether this parameter is set
387 * @param array $messages utility messages
388 * @param string $docAnchor anchor in documentation
390 * @return string
392 function PMA_getDiagMessageForParameter($parameter,
393 $relationParameterSet, $messages, $docAnchor
395 $retval = '<tr><th class="left">';
396 $retval .= '$cfg[\'Servers\'][$i][\'' . $parameter . '\'] ... ';
397 $retval .= '</th><td class="right">';
398 if ($relationParameterSet) {
399 $retval .= $messages['ok'];
400 } else {
401 $retval .= sprintf(
402 $messages['error'],
403 PMA_Util::getDocuLink('config', 'cfg_Servers_' . $docAnchor)
406 $retval .= '</td></tr>' . "\n";
407 return $retval;
412 * Defines the relation parameters for the current user
413 * just a copy of the functions used for relations ;-)
414 * but added some stuff to check what will work
416 * @access protected
417 * @return array the relation parameters for the current user
419 function PMA_checkRelationsParam()
421 $cfgRelation = array();
422 $cfgRelation['relwork'] = false;
423 $cfgRelation['displaywork'] = false;
424 $cfgRelation['bookmarkwork'] = false;
425 $cfgRelation['pdfwork'] = false;
426 $cfgRelation['commwork'] = false;
427 $cfgRelation['mimework'] = false;
428 $cfgRelation['historywork'] = false;
429 $cfgRelation['recentwork'] = false;
430 $cfgRelation['favoritework'] = false;
431 $cfgRelation['uiprefswork'] = false;
432 $cfgRelation['trackingwork'] = false;
433 $cfgRelation['userconfigwork'] = false;
434 $cfgRelation['menuswork'] = false;
435 $cfgRelation['navwork'] = false;
436 $cfgRelation['allworks'] = false;
437 $cfgRelation['savedsearcheswork'] = false;
438 $cfgRelation['central_columnswork'] = false;
439 $cfgRelation['user'] = null;
440 $cfgRelation['db'] = null;
442 if ($GLOBALS['server'] == 0
443 || empty($GLOBALS['cfg']['Server']['pmadb'])
444 || ! $GLOBALS['dbi']->selectDb(
445 $GLOBALS['cfg']['Server']['pmadb'], $GLOBALS['controllink']
448 // No server selected -> no bookmark table
449 // we return the array with the falses in it,
450 // to avoid some 'Uninitialized string offset' errors later
451 $GLOBALS['cfg']['Server']['pmadb'] = false;
452 return $cfgRelation;
455 $cfgRelation['user'] = $GLOBALS['cfg']['Server']['user'];
456 $cfgRelation['db'] = $GLOBALS['cfg']['Server']['pmadb'];
458 // Now I just check if all tables that i need are present so I can for
459 // example enable relations but not pdf...
460 // I was thinking of checking if they have all required columns but I
461 // fear it might be too slow
463 $tab_query = 'SHOW TABLES FROM '
464 . PMA_Util::backquote(
465 $GLOBALS['cfg']['Server']['pmadb']
467 $tab_rs = PMA_queryAsControlUser(
468 $tab_query, false, PMA_DatabaseInterface::QUERY_STORE
471 if (! $tab_rs) {
472 // query failed ... ?
473 //$GLOBALS['cfg']['Server']['pmadb'] = false;
474 return $cfgRelation;
477 while ($curr_table = @$GLOBALS['dbi']->fetchRow($tab_rs)) {
478 if ($curr_table[0] == $GLOBALS['cfg']['Server']['bookmarktable']) {
479 $cfgRelation['bookmark'] = $curr_table[0];
480 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['relation']) {
481 $cfgRelation['relation'] = $curr_table[0];
482 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_info']) {
483 $cfgRelation['table_info'] = $curr_table[0];
484 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_coords']) {
485 $cfgRelation['table_coords'] = $curr_table[0];
486 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['column_info']) {
487 $cfgRelation['column_info'] = $curr_table[0];
488 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['pdf_pages']) {
489 $cfgRelation['pdf_pages'] = $curr_table[0];
490 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['history']) {
491 $cfgRelation['history'] = $curr_table[0];
492 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['recent']) {
493 $cfgRelation['recent'] = $curr_table[0];
494 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['favorite']) {
495 $cfgRelation['favorite'] = $curr_table[0];
496 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_uiprefs']) {
497 $cfgRelation['table_uiprefs'] = $curr_table[0];
498 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['tracking']) {
499 $cfgRelation['tracking'] = $curr_table[0];
500 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['userconfig']) {
501 $cfgRelation['userconfig'] = $curr_table[0];
502 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['users']) {
503 $cfgRelation['users'] = $curr_table[0];
504 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['usergroups']) {
505 $cfgRelation['usergroups'] = $curr_table[0];
506 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['navigationhiding']) {
507 $cfgRelation['navigationhiding'] = $curr_table[0];
508 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['savedsearches']) {
509 $cfgRelation['savedsearches'] = $curr_table[0];
510 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['central_columns']) {
511 $cfgRelation['central_columns'] = $curr_table[0];
513 } // end while
514 $GLOBALS['dbi']->freeResult($tab_rs);
516 if (isset($cfgRelation['relation'])) {
517 $cfgRelation['relwork'] = true;
518 if (isset($cfgRelation['table_info'])) {
519 $cfgRelation['displaywork'] = true;
523 if (isset($cfgRelation['table_coords']) && isset($cfgRelation['pdf_pages'])) {
524 $cfgRelation['pdfwork'] = true;
527 if (isset($cfgRelation['column_info'])) {
528 $cfgRelation['commwork'] = true;
529 // phpMyAdmin 4.3+
530 // Check for input transformations upgrade.
531 $cfgRelation['mimework'] = PMA_tryUpgradeTransformations();
534 if (isset($cfgRelation['history'])) {
535 $cfgRelation['historywork'] = true;
538 if (isset($cfgRelation['recent'])) {
539 $cfgRelation['recentwork'] = true;
542 if (isset($cfgRelation['favorite'])) {
543 $cfgRelation['favoritework'] = true;
546 if (isset($cfgRelation['table_uiprefs'])) {
547 $cfgRelation['uiprefswork'] = true;
550 if (isset($cfgRelation['tracking'])) {
551 $cfgRelation['trackingwork'] = true;
554 if (isset($cfgRelation['userconfig'])) {
555 $cfgRelation['userconfigwork'] = true;
558 if (isset($cfgRelation['bookmark'])) {
559 $cfgRelation['bookmarkwork'] = true;
562 if (isset($cfgRelation['users']) && isset($cfgRelation['usergroups'])) {
563 $cfgRelation['menuswork'] = true;
566 if (isset($cfgRelation['navigationhiding'])) {
567 $cfgRelation['navwork'] = true;
570 if (isset($cfgRelation['savedsearches'])) {
571 $cfgRelation['savedsearcheswork'] = true;
574 if (isset($cfgRelation['central_columns'])) {
575 $cfgRelation['central_columnswork'] = true;
578 if ($cfgRelation['relwork'] && $cfgRelation['displaywork']
579 && $cfgRelation['pdfwork'] && $cfgRelation['commwork']
580 && $cfgRelation['mimework'] && $cfgRelation['historywork']
581 && $cfgRelation['recentwork'] && $cfgRelation['uiprefswork']
582 && $cfgRelation['trackingwork'] && $cfgRelation['userconfigwork']
583 && $cfgRelation['bookmarkwork'] && $cfgRelation['central_columnswork']
584 && $cfgRelation['menuswork'] && $cfgRelation['navwork']
585 && $cfgRelation['savedsearcheswork'] && $cfgRelation['favoritework']
587 $cfgRelation['allworks'] = true;
590 return $cfgRelation;
591 } // end of the 'PMA_checkRelationsParam()' function
594 * Check whether column_info table input transformation
595 * upgrade is required and try to upgrade silently
597 * @return bool false if upgrade failed
599 * @access public
601 function PMA_tryUpgradeTransformations()
603 // From 4.3, new input oriented transformation feature was introduced.
604 // Check whether column_info table has input transformation columns
605 $new_cols = array(
606 "input_transformation",
607 "input_transformation_options"
609 $query = 'SHOW COLUMNS FROM '
610 . PMA_Util::backquote($GLOBALS['cfg']['Server']['pmadb'])
611 . '.' . PMA_Util::backquote($GLOBALS['cfg']['Server']['column_info'])
612 . ' WHERE Field IN (\'' . implode('\', \'', $new_cols) . '\')';
613 $result = PMA_queryAsControlUser(
614 $query, false, PMA_DatabaseInterface::QUERY_STORE
616 if ($result) {
617 $rows = $GLOBALS['dbi']->numRows($result);
618 $GLOBALS['dbi']->freeResult($result);
619 // input transformations are present
620 // no need to upgrade
621 if ($rows === 2) {
622 return true;
623 // try silent upgrade without disturbing the user
624 } else {
625 // read upgrade query file
626 $query = @file_get_contents(SQL_DIR . 'upgrade_column_info_4_3_0+.sql');
627 // replace database name from query to with set in config.inc.php
628 $query = str_replace(
629 '`phpmyadmin`',
630 PMA_Util::backquote($GLOBALS['cfg']['Server']['pmadb']),
631 $query
633 // replace pma__column_info table name from query
634 // to with set in config.inc.php
635 $query = str_replace(
636 '`pma__column_info`',
637 PMA_Util::backquote($GLOBALS['cfg']['Server']['column_info']),
638 $query
640 $GLOBALS['dbi']->tryMultiQuery($query, $GLOBALS['controllink']);
641 // skips result sets of query as we are not interested in it
642 while ($GLOBALS['dbi']->moreResults($GLOBALS['controllink'])
643 && $GLOBALS['dbi']->nextResult($GLOBALS['controllink'])
646 $error = $GLOBALS['dbi']->getError($GLOBALS['controllink']);
647 // return true if no error exists otherwise false
648 return empty($error);
651 // some failure, either in upgrading or something else
652 // make some noise, time to wake up user.
653 return false;
657 * Gets all Relations to foreign tables for a given table or
658 * optionally a given column in a table
660 * @param string $db the name of the db to check for
661 * @param string $table the name of the table to check for
662 * @param string $column the name of the column to check for
663 * @param string $source the source for foreign key information
665 * @return array db,table,column
667 * @access public
669 function PMA_getForeigners($db, $table, $column = '', $source = 'both')
671 $cfgRelation = PMA_getRelationsParam();
672 $foreign = array();
674 if ($cfgRelation['relwork'] && ($source == 'both' || $source == 'internal')) {
675 $rel_query = '
676 SELECT `master_field`,
677 `foreign_db`,
678 `foreign_table`,
679 `foreign_field`
680 FROM ' . PMA_Util::backquote($cfgRelation['db'])
681 . '.' . PMA_Util::backquote($cfgRelation['relation']) . '
682 WHERE `master_db` = \'' . PMA_Util::sqlAddSlashes($db) . '\'
683 AND `master_table` = \'' . PMA_Util::sqlAddSlashes($table) . '\' ';
684 if (/*overload*/mb_strlen($column)) {
685 $rel_query .= ' AND `master_field` = '
686 . '\'' . PMA_Util::sqlAddSlashes($column) . '\'';
688 $foreign = $GLOBALS['dbi']->fetchResult(
689 $rel_query, 'master_field', null, $GLOBALS['controllink']
693 if (($source == 'both' || $source == 'foreign') && /*overload*/mb_strlen($table)
696 $showCreateTableQuery = 'SHOW CREATE TABLE '
697 . PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table);
698 $show_create_table = $GLOBALS['dbi']->fetchValue(
699 $showCreateTableQuery, 0, 1
701 if ($show_create_table) {
702 $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
703 $foreign['foreign_keys_data'] = $analyzed_sql[0]['foreign_keys'];
708 * Emulating relations for some information_schema and data_dictionary tables
710 $isInformationSchema = /*overload*/mb_strtolower($db) == 'information_schema';
711 $is_data_dictionary = PMA_DRIZZLE
712 && /*overload*/mb_strtolower($db) == 'data_dictionary';
713 $isMysql = /*overload*/mb_strtolower($db) == 'mysql';
714 if (($isInformationSchema || $is_data_dictionary || $isMysql)
715 && ($source == 'internal' || $source == 'both')
717 if ($isInformationSchema) {
718 $relations_key = 'information_schema_relations';
719 include_once './libraries/information_schema_relations.lib.php';
720 } else if ($is_data_dictionary) {
721 $relations_key = 'data_dictionary_relations';
722 include_once './libraries/data_dictionary_relations.lib.php';
723 } else {
724 $relations_key = 'mysql_relations';
725 include_once './libraries/mysql_relations.lib.php';
727 if (isset($GLOBALS[$relations_key][$table])) {
728 foreach ($GLOBALS[$relations_key][$table] as $field => $relations) {
729 if ((! /*overload*/mb_strlen($column) || $column == $field)
730 && (! isset($foreign[$field])
731 || ! /*overload*/mb_strlen($foreign[$field]))
733 $foreign[$field] = $relations;
739 return $foreign;
740 } // end of the 'PMA_getForeigners()' function
743 * Gets the display field of a table
745 * @param string $db the name of the db to check for
746 * @param string $table the name of the table to check for
748 * @return string field name
750 * @access public
752 function PMA_getDisplayField($db, $table)
754 $cfgRelation = PMA_getRelationsParam();
757 * Try to fetch the display field from DB.
759 if ($cfgRelation['displaywork']) {
760 $disp_query = '
761 SELECT `display_field`
762 FROM ' . PMA_Util::backquote($cfgRelation['db'])
763 . '.' . PMA_Util::backquote($cfgRelation['table_info']) . '
764 WHERE `db_name` = \'' . PMA_Util::sqlAddSlashes($db) . '\'
765 AND `table_name` = \'' . PMA_Util::sqlAddSlashes($table) . '\'';
767 $row = $GLOBALS['dbi']->fetchSingleRow(
768 $disp_query, 'ASSOC', $GLOBALS['controllink']
770 if (isset($row['display_field'])) {
771 return $row['display_field'];
776 * Emulating the display field for some information_schema tables.
778 if ($db == 'information_schema') {
779 switch ($table) {
780 case 'CHARACTER_SETS':
781 return 'DESCRIPTION';
782 case 'TABLES':
783 return 'TABLE_COMMENT';
788 * No Luck...
790 return false;
792 } // end of the 'PMA_getDisplayField()' function
795 * Gets the comments for all columns of a table or the db itself
797 * @param string $db the name of the db to check for
798 * @param string $table the name of the table to check for
800 * @return array [column_name] = comment
802 * @access public
804 function PMA_getComments($db, $table = '')
806 $comments = array();
808 if ($table != '') {
809 // MySQL native column comments
810 $columns = $GLOBALS['dbi']->getColumns($db, $table, null, true);
811 if ($columns) {
812 foreach ($columns as $column) {
813 if (! empty($column['Comment'])) {
814 $comments[$column['Field']] = $column['Comment'];
818 } else {
819 $comments[] = PMA_getDbComment($db);
822 return $comments;
823 } // end of the 'PMA_getComments()' function
826 * Gets the comment for a db
828 * @param string $db the name of the db to check for
830 * @return string comment
832 * @access public
834 function PMA_getDbComment($db)
836 $cfgRelation = PMA_getRelationsParam();
837 $comment = '';
839 if ($cfgRelation['commwork']) {
840 // pmadb internal db comment
841 $com_qry = "
842 SELECT `comment`
843 FROM " . PMA_Util::backquote($cfgRelation['db'])
844 . "." . PMA_Util::backquote($cfgRelation['column_info']) . "
845 WHERE db_name = '" . PMA_Util::sqlAddSlashes($db) . "'
846 AND table_name = ''
847 AND column_name = '(db_comment)'";
848 $com_rs = PMA_queryAsControlUser(
849 $com_qry, true, PMA_DatabaseInterface::QUERY_STORE
852 if ($com_rs && $GLOBALS['dbi']->numRows($com_rs) > 0) {
853 $row = $GLOBALS['dbi']->fetchAssoc($com_rs);
854 $comment = $row['comment'];
856 $GLOBALS['dbi']->freeResult($com_rs);
859 return $comment;
860 } // end of the 'PMA_getDbComment()' function
863 * Gets the comment for a db
865 * @access public
867 * @return string comment
869 function PMA_getDbComments()
871 $cfgRelation = PMA_getRelationsParam();
872 $comments = array();
874 if ($cfgRelation['commwork']) {
875 // pmadb internal db comment
876 $com_qry = "
877 SELECT `db_name`, `comment`
878 FROM " . PMA_Util::backquote($cfgRelation['db'])
879 . "." . PMA_Util::backquote($cfgRelation['column_info']) . "
880 WHERE `column_name` = '(db_comment)'";
881 $com_rs = PMA_queryAsControlUser(
882 $com_qry, true, PMA_DatabaseInterface::QUERY_STORE
885 if ($com_rs && $GLOBALS['dbi']->numRows($com_rs) > 0) {
886 while ($row = $GLOBALS['dbi']->fetchAssoc($com_rs)) {
887 $comments[$row['db_name']] = $row['comment'];
890 $GLOBALS['dbi']->freeResult($com_rs);
893 return $comments;
894 } // end of the 'PMA_getDbComments()' function
897 * Set a database comment to a certain value.
899 * @param string $db the name of the db
900 * @param string $comment the value of the column
902 * @return boolean true, if comment-query was made.
904 * @access public
906 function PMA_setDbComment($db, $comment = '')
908 $cfgRelation = PMA_getRelationsParam();
910 if (! $cfgRelation['commwork']) {
911 return false;
914 if (/*overload*/mb_strlen($comment)) {
915 $upd_query = 'INSERT INTO '
916 . PMA_Util::backquote($cfgRelation['db']) . '.'
917 . PMA_Util::backquote($cfgRelation['column_info'])
918 . ' (`db_name`, `table_name`, `column_name`, `comment`)'
919 . ' VALUES (\''
920 . PMA_Util::sqlAddSlashes($db)
921 . "', '', '(db_comment)', '"
922 . PMA_Util::sqlAddSlashes($comment)
923 . "') "
924 . ' ON DUPLICATE KEY UPDATE '
925 . "`comment` = '" . PMA_Util::sqlAddSlashes($comment) . "'";
926 } else {
927 $upd_query = 'DELETE FROM '
928 . PMA_Util::backquote($cfgRelation['db']) . '.'
929 . PMA_Util::backquote($cfgRelation['column_info'])
930 . ' WHERE `db_name` = \'' . PMA_Util::sqlAddSlashes($db) . '\'
931 AND `table_name` = \'\'
932 AND `column_name` = \'(db_comment)\'';
935 if (isset($upd_query)) {
936 return PMA_queryAsControlUser($upd_query);
939 return false;
940 } // end of 'PMA_setDbComment()' function
943 * Set a SQL history entry
945 * @param string $db the name of the db
946 * @param string $table the name of the table
947 * @param string $username the username
948 * @param string $sqlquery the sql query
950 * @return void
952 * @access public
954 function PMA_setHistory($db, $table, $username, $sqlquery)
956 $maxCharactersInDisplayedSQL = $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'];
957 // Prevent to run this automatically on Footer class destroying in testsuite
958 if (defined('TESTSUITE')
959 || /*overload*/mb_strlen($sqlquery) > $maxCharactersInDisplayedSQL
961 return;
964 $cfgRelation = PMA_getRelationsParam();
966 if (! isset($_SESSION['sql_history'])) {
967 $_SESSION['sql_history'] = array();
970 $_SESSION['sql_history'][] = array(
971 'db' => $db,
972 'table' => $table,
973 'sqlquery' => $sqlquery,
976 if (count($_SESSION['sql_history']) > $GLOBALS['cfg']['QueryHistoryMax']) {
977 // history should not exceed a maximum count
978 array_shift($_SESSION['sql_history']);
981 if (! $cfgRelation['historywork'] || ! $GLOBALS['cfg']['QueryHistoryDB']) {
982 return;
985 PMA_queryAsControlUser(
986 'INSERT INTO '
987 . PMA_Util::backquote($cfgRelation['db']) . '.'
988 . PMA_Util::backquote($cfgRelation['history']) . '
989 (`username`,
990 `db`,
991 `table`,
992 `timevalue`,
993 `sqlquery`)
994 VALUES
995 (\'' . PMA_Util::sqlAddSlashes($username) . '\',
996 \'' . PMA_Util::sqlAddSlashes($db) . '\',
997 \'' . PMA_Util::sqlAddSlashes($table) . '\',
998 NOW(),
999 \'' . PMA_Util::sqlAddSlashes($sqlquery) . '\')'
1002 PMA_purgeHistory($username);
1004 } // end of 'PMA_setHistory()' function
1007 * Gets a SQL history entry
1009 * @param string $username the username
1011 * @return array list of history items
1013 * @access public
1015 function PMA_getHistory($username)
1017 $cfgRelation = PMA_getRelationsParam();
1019 if (! $cfgRelation['historywork']) {
1020 return false;
1024 * if db-based history is disabled but there exists a session-based
1025 * history, use it
1027 if (! $GLOBALS['cfg']['QueryHistoryDB']) {
1028 if (isset($_SESSION['sql_history'])) {
1029 return array_reverse($_SESSION['sql_history']);
1031 return false;
1034 $hist_query = '
1035 SELECT `db`,
1036 `table`,
1037 `sqlquery`,
1038 `timevalue`
1039 FROM ' . PMA_Util::backquote($cfgRelation['db'])
1040 . '.' . PMA_Util::backquote($cfgRelation['history']) . '
1041 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
1042 ORDER BY `id` DESC';
1044 return $GLOBALS['dbi']->fetchResult(
1045 $hist_query, null, null, $GLOBALS['controllink']
1047 } // end of 'PMA_getHistory()' function
1050 * purges SQL history
1052 * deletes entries that exceeds $cfg['QueryHistoryMax'], oldest first, for the
1053 * given user
1055 * @param string $username the username
1057 * @return void
1059 * @access public
1061 function PMA_purgeHistory($username)
1063 $cfgRelation = PMA_getRelationsParam();
1064 if (! $GLOBALS['cfg']['QueryHistoryDB'] || ! $cfgRelation['historywork']) {
1065 return;
1068 if (! $cfgRelation['historywork']) {
1069 return;
1072 $search_query = '
1073 SELECT `timevalue`
1074 FROM ' . PMA_Util::backquote($cfgRelation['db'])
1075 . '.' . PMA_Util::backquote($cfgRelation['history']) . '
1076 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
1077 ORDER BY `timevalue` DESC
1078 LIMIT ' . $GLOBALS['cfg']['QueryHistoryMax'] . ', 1';
1080 if ($max_time = $GLOBALS['dbi']->fetchValue(
1081 $search_query, 0, 0, $GLOBALS['controllink']
1082 )) {
1083 PMA_queryAsControlUser(
1084 'DELETE FROM '
1085 . PMA_Util::backquote($cfgRelation['db']) . '.'
1086 . PMA_Util::backquote($cfgRelation['history']) . '
1087 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
1088 AND `timevalue` <= \'' . $max_time . '\''
1091 } // end of 'PMA_purgeHistory()' function
1094 * Prepares the dropdown for one mode
1096 * @param array $foreign the keys and values for foreigns
1097 * @param string $data the current data of the dropdown
1098 * @param string $mode the needed mode
1100 * @return array the <option value=""><option>s
1102 * @access protected
1104 function PMA_buildForeignDropdown($foreign, $data, $mode)
1106 $reloptions = array();
1108 // id-only is a special mode used when no foreign display column
1109 // is available
1110 if ($mode == 'id-content' || $mode == 'id-only') {
1111 // sort for id-content
1112 if ($GLOBALS['cfg']['NaturalOrder']) {
1113 uksort($foreign, 'strnatcasecmp');
1114 } else {
1115 ksort($foreign);
1117 } elseif ($mode == 'content-id') {
1118 // sort for content-id
1119 if ($GLOBALS['cfg']['NaturalOrder']) {
1120 natcasesort($foreign);
1121 } else {
1122 asort($foreign);
1126 foreach ($foreign as $key => $value) {
1127 if (/*overload*/mb_strlen($value) <= $GLOBALS['cfg']['LimitChars']
1129 $vtitle = '';
1130 $value = htmlspecialchars($value);
1131 } else {
1132 $vtitle = htmlspecialchars($value);
1133 $value = htmlspecialchars(
1134 /*overload*/mb_substr(
1135 $value, 0, $GLOBALS['cfg']['LimitChars']
1136 ) . '...'
1140 $reloption = '<option value="' . htmlspecialchars($key) . '"';
1141 if ($vtitle != '') {
1142 $reloption .= ' title="' . $vtitle . '"';
1145 if ((string) $key == (string) $data) {
1146 $reloption .= ' selected="selected"';
1149 if ($mode == 'content-id') {
1150 $reloptions[] = $reloption . '>'
1151 . $value . '&nbsp;-&nbsp;' . htmlspecialchars($key) . '</option>';
1152 } elseif ($mode == 'id-content') {
1153 $reloptions[] = $reloption . '>'
1154 . htmlspecialchars($key) . '&nbsp;-&nbsp;' . $value . '</option>';
1155 } elseif ($mode == 'id-only') {
1156 $reloptions[] = $reloption . '>'
1157 . htmlspecialchars($key) . '</option>';
1159 } // end foreach
1161 return $reloptions;
1162 } // end of 'PMA_buildForeignDropdown' function
1165 * Outputs dropdown with values of foreign fields
1167 * @param array $disp_row array of the displayed row
1168 * @param string $foreign_field the foreign field
1169 * @param string $foreign_display the foreign field to display
1170 * @param string $data the current data of the dropdown (field in row)
1171 * @param int $max maximum number of items in the dropdown
1173 * @return string the <option value=""><option>s
1175 * @access public
1177 function PMA_foreignDropdown($disp_row, $foreign_field, $foreign_display, $data,
1178 $max = null
1180 if (null === $max) {
1181 $max = $GLOBALS['cfg']['ForeignKeyMaxLimit'];
1184 $foreign = array();
1186 // collect the data
1187 foreach ($disp_row as $relrow) {
1188 $key = $relrow[$foreign_field];
1190 // if the display field has been defined for this foreign table
1191 if ($foreign_display) {
1192 $value = $relrow[$foreign_display];
1193 } else {
1194 $value = '';
1195 } // end if ($foreign_display)
1197 $foreign[$key] = $value;
1198 } // end foreach
1200 // put the dropdown sections in correct order
1201 $top = array();
1202 $bottom = array();
1203 if ($foreign_display) {
1204 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'], 'array')) {
1205 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][0])) {
1206 $top = PMA_buildForeignDropdown(
1207 $foreign,
1208 $data,
1209 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][0]
1212 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][1])) {
1213 $bottom = PMA_buildForeignDropdown(
1214 $foreign,
1215 $data,
1216 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][1]
1219 } else {
1220 $top = PMA_buildForeignDropdown($foreign, $data, 'id-content');
1221 $bottom = PMA_buildForeignDropdown($foreign, $data, 'content-id');
1223 } else {
1224 $top = PMA_buildForeignDropdown($foreign, $data, 'id-only');
1227 // beginning of dropdown
1228 $ret = '<option value="">&nbsp;</option>';
1229 $top_count = count($top);
1230 if ($max == -1 || $top_count < $max) {
1231 $ret .= implode('', $top);
1232 if ($foreign_display && $top_count > 0) {
1233 // this empty option is to visually mark the beginning of the
1234 // second series of values (bottom)
1235 $ret .= '<option value="">&nbsp;</option>';
1238 if ($foreign_display) {
1239 $ret .= implode('', $bottom);
1242 return $ret;
1243 } // end of 'PMA_foreignDropdown()' function
1246 * Gets foreign keys in preparation for a drop-down selector
1248 * @param array|boolean $foreigners array of the foreign keys
1249 * @param string $field the foreign field name
1250 * @param bool $override_total whether to override the total
1251 * @param string $foreign_filter a possible filter
1252 * @param string $foreign_limit a possible LIMIT clause
1254 * @return array data about the foreign keys
1256 * @access public
1259 function PMA_getForeignData(
1260 $foreigners, $field, $override_total, $foreign_filter, $foreign_limit
1262 // we always show the foreign field in the drop-down; if a display
1263 // field is defined, we show it besides the foreign field
1264 $foreign_link = false;
1265 do {
1266 if (! $foreigners) {
1267 break;
1269 $foreigner = PMA_searchColumnInForeigners($foreigners, $field);
1270 if ($foreigner != false) {
1271 $foreign_db = $foreigner['foreign_db'];
1272 $foreign_table = $foreigner['foreign_table'];
1273 $foreign_field = $foreigner['foreign_field'];
1274 } else {
1275 break;
1278 // Count number of rows in the foreign table. Currently we do
1279 // not use a drop-down if more than ForeignKeyMaxLimit rows in the
1280 // foreign table,
1281 // for speed reasons and because we need a better interface for this.
1283 // We could also do the SELECT anyway, with a LIMIT, and ensure that
1284 // the current value of the field is one of the choices.
1286 $the_total = PMA_Table::countRecords($foreign_db, $foreign_table, true);
1288 if ($override_total == true
1289 || $the_total < $GLOBALS['cfg']['ForeignKeyMaxLimit']
1291 // foreign_display can be false if no display field defined:
1292 $foreign_display = PMA_getDisplayField($foreign_db, $foreign_table);
1294 $f_query_main = 'SELECT ' . PMA_Util::backquote($foreign_field)
1296 ($foreign_display == false)
1297 ? ''
1298 : ', ' . PMA_Util::backquote($foreign_display)
1300 $f_query_from = ' FROM ' . PMA_Util::backquote($foreign_db)
1301 . '.' . PMA_Util::backquote($foreign_table);
1302 $f_query_filter = empty($foreign_filter) ? '' : ' WHERE '
1303 . PMA_Util::backquote($foreign_field)
1304 . ' LIKE "%' . PMA_Util::sqlAddSlashes($foreign_filter, true) . '%"'
1306 ($foreign_display == false)
1307 ? ''
1308 : ' OR ' . PMA_Util::backquote($foreign_display)
1309 . ' LIKE "%' . PMA_Util::sqlAddSlashes($foreign_filter, true)
1310 . '%"'
1312 $f_query_order = ($foreign_display == false) ? '' :' ORDER BY '
1313 . PMA_Util::backquote($foreign_table) . '.'
1314 . PMA_Util::backquote($foreign_display);
1315 $f_query_limit = isset($foreign_limit) ? $foreign_limit : '';
1317 if (!empty($foreign_filter)) {
1318 $the_total = $GLOBALS['dbi']->fetchValue(
1319 'SELECT COUNT(*)' . $f_query_from . $f_query_filter
1321 if ($the_total === false) {
1322 $the_total = 0;
1326 $disp = $GLOBALS['dbi']->tryQuery(
1327 $f_query_main . $f_query_from . $f_query_filter
1328 . $f_query_order . $f_query_limit
1330 if ($disp && $GLOBALS['dbi']->numRows($disp) > 0) {
1331 // If a resultset has been created, pre-cache it in the $disp_row
1332 // array. This helps us from not needing to use mysql_data_seek by
1333 // accessing a pre-cached PHP array. Usually those resultsets are
1334 // not that big, so a performance hit should not be expected.
1335 $disp_row = array();
1336 while ($single_disp_row = @$GLOBALS['dbi']->fetchAssoc($disp)) {
1337 $disp_row[] = $single_disp_row;
1339 @$GLOBALS['dbi']->freeResult($disp);
1340 } else {
1341 // Either no data in the foreign table or
1342 // user does not have select permission to foreign table/field
1343 // Show an input field with a 'Browse foreign values' link
1344 $disp_row = null;
1345 $foreign_link = true;
1347 } else {
1348 $disp_row = null;
1349 $foreign_link = true;
1351 } while (false);
1353 $foreignData = array();
1354 $foreignData['foreign_link'] = $foreign_link;
1355 $foreignData['the_total'] = isset($the_total) ? $the_total : null;
1356 $foreignData['foreign_display'] = (
1357 isset($foreign_display) ? $foreign_display : null
1359 $foreignData['disp_row'] = isset($disp_row) ? $disp_row : null;
1360 $foreignData['foreign_field'] = isset($foreign_field) ? $foreign_field : null;
1361 return $foreignData;
1362 } // end of 'PMA_getForeignData()' function
1365 * Finds all related tables
1367 * @param array $all_tables All the involved tables
1368 * @param string $master The master table to form the LEFT JOIN clause
1370 * @return string LEFT JOIN
1371 * @access private
1373 function PMA_getRelatives($all_tables, $master)
1375 $fromclause = '';
1376 $left_joins = array();
1377 $emerg = '';
1378 $ignore_internal_relations = false;
1380 // The list of tables that we still couldn't connect
1381 $remaining_tables = $all_tables;
1382 unset($remaining_tables[$master]);
1383 // The list of already connected tables
1384 $known_tables = array();
1385 $known_tables[$master] = $master;
1386 $run = 0;
1387 while ($GLOBALS['cfgRelation']['relwork'] && count($remaining_tables) > 0) {
1388 // Whether to go from master to foreign or vice versa
1389 if ($run % 2 == 0) {
1390 $from = 'master';
1391 $to = 'foreign';
1392 } else {
1393 $from = 'foreign';
1394 $to = 'master';
1396 $in_know = '(\'' . implode('\', \'', $known_tables) . '\')';
1397 $in_left = '(\'' . implode('\', \'', $remaining_tables) . '\')';
1398 $rel_query = 'SELECT *'
1399 . ' FROM ' . PMA_Util::backquote($GLOBALS['cfgRelation']['db'])
1400 . '.' . PMA_Util::backquote($GLOBALS['cfgRelation']['relation'])
1401 . ' WHERE ' . $from . '_db = \''
1402 . PMA_Util::sqlAddSlashes($GLOBALS['db']) . '\''
1403 . ' AND ' . $to . '_db = \''
1404 . PMA_Util::sqlAddSlashes($GLOBALS['db']) . '\''
1405 . ' AND ' . $from . '_table IN ' . $in_know
1406 . ' AND ' . $to . '_table IN ' . $in_left;
1407 $relations = @$GLOBALS['dbi']->query($rel_query, $GLOBALS['controllink']);
1408 while ($row = $GLOBALS['dbi']->fetchAssoc($relations)) {
1409 $found_table = $row[$to . '_table'];
1410 if (isset($remaining_tables[$found_table])) {
1411 $left_join_with = PMA_Util::backquote($GLOBALS['db']) . '.'
1412 . PMA_Util::backquote($row[$to . '_table']);
1413 $on_condition = PMA_Util::backquote($row[$from . '_table']) . '.'
1414 . PMA_Util::backquote($row[$from . '_field']) . ' = '
1415 . PMA_Util::backquote($row[$to . '_table']) . '.'
1416 . PMA_Util::backquote($row[$to . '_field']);
1418 $left_joins[$left_join_with] = array(
1419 'left_join_with' => $left_join_with,
1420 'on_condition' => array($on_condition)
1423 $known_tables[$found_table] = $found_table;
1424 unset($remaining_tables[$found_table]);
1426 } // end while
1427 $run++;
1428 if ($run > 5) {
1429 foreach ($remaining_tables as $table) {
1430 $emerg .= ', ' . PMA_Util::backquote($table);
1431 unset($remaining_tables[$table]);
1434 } // end while
1436 // Generate 'LEFT JOIN's for InnoDB foreign keys.
1437 $remaining_tables = $all_tables;
1438 foreach ($remaining_tables as $one_table) {
1439 $foreigners = PMA_getForeigners($GLOBALS['db'], $one_table, '', 'foreign');
1440 foreach ($foreigners['foreign_keys_data'] as $one_key) {
1441 if (in_array($one_key['ref_table_name'], $all_tables)
1442 && ! isset($one_key['ref_db_name'])
1443 && ($one_key['ref_table_name'] == $master
1444 || $one_key['ref_table_name'] == $one_table)
1446 $left_join_with = PMA_Util::backquote($GLOBALS['db']) . '.'
1447 . PMA_Util::backquote($one_table);
1448 if (! isset($left_joins[$left_join_with])) {
1449 $left_joins[$left_join_with] = array(
1450 'left_join_with' =>$left_join_with,
1451 'on_condition' => array()
1455 foreach ($one_key['ref_index_list'] as $key => $one_column) {
1456 $on_condition = PMA_Util::backquote($one_key['ref_table_name'])
1457 . '.' . PMA_Util::backquote($one_column) . ' = '
1458 . PMA_Util::backquote($one_table) . '.'
1459 . PMA_Util::backquote($one_key['index_list'][$key]);
1461 if (! in_array($on_condition, $left_joins[$left_join_with]['on_condition'])) {
1462 $left_joins[$left_join_with]['on_condition'][]
1463 = $on_condition;
1466 $ignore_internal_relations = true;
1467 unset($remaining_tables[$one_table]);
1472 if ($ignore_internal_relations) {
1473 $emerg = '';
1476 // Build the 'FROM' clause.
1477 foreach ($left_joins as $one_join) {
1478 $fromclause .= "\n" . ' LEFT JOIN '
1479 . $one_join['left_join_with']
1480 . ' ON '
1481 . implode(' AND ', $one_join['on_condition']);
1484 $fromclause = $emerg . $fromclause;
1485 return $fromclause;
1486 } // end of the "PMA_getRelatives()" function
1489 * Rename a field in relation tables
1491 * usually called after a column in a table was renamed
1493 * @param string $db database name
1494 * @param string $table table name
1495 * @param string $field old field name
1496 * @param string $new_name new field name
1498 * @return void
1500 function PMA_REL_renameField($db, $table, $field, $new_name)
1502 $cfgRelation = PMA_getRelationsParam();
1504 if ($cfgRelation['displaywork']) {
1505 $table_query = 'UPDATE '
1506 . PMA_Util::backquote($cfgRelation['db']) . '.'
1507 . PMA_Util::backquote($cfgRelation['table_info'])
1508 . ' SET display_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1509 . ' WHERE db_name = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1510 . ' AND table_name = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1511 . ' AND display_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1512 PMA_queryAsControlUser($table_query);
1515 if ($cfgRelation['relwork']) {
1516 $table_query = 'UPDATE '
1517 . PMA_Util::backquote($cfgRelation['db']) . '.'
1518 . PMA_Util::backquote($cfgRelation['relation'])
1519 . ' SET master_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1520 . ' WHERE master_db = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1521 . ' AND master_table = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1522 . ' AND master_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1523 PMA_queryAsControlUser($table_query);
1525 $table_query = 'UPDATE '
1526 . PMA_Util::backquote($cfgRelation['db']) . '.'
1527 . PMA_Util::backquote($cfgRelation['relation'])
1528 . ' SET foreign_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1529 . ' WHERE foreign_db = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1530 . ' AND foreign_table = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1531 . ' AND foreign_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1532 PMA_queryAsControlUser($table_query);
1534 } // end if relwork
1539 * Performs SQL query used for renaming table.
1541 * @param string $table Relation table to use
1542 * @param string $source_db Source database name
1543 * @param string $target_db Target database name
1544 * @param string $source_table Source table name
1545 * @param string $target_table Target table name
1546 * @param string $db_field Name of database field
1547 * @param string $table_field Name of table field
1549 * @return void
1551 function PMA_REL_renameSingleTable($table,
1552 $source_db, $target_db,
1553 $source_table, $target_table,
1554 $db_field, $table_field
1556 $query = 'UPDATE '
1557 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
1558 . PMA_Util::backquote($GLOBALS['cfgRelation'][$table])
1559 . ' SET '
1560 . $db_field . ' = \'' . PMA_Util::sqlAddSlashes($target_db) . '\', '
1561 . $table_field . ' = \'' . PMA_Util::sqlAddSlashes($target_table) . '\''
1562 . ' WHERE '
1563 . $db_field . ' = \'' . PMA_Util::sqlAddSlashes($source_db) . '\''
1564 . ' AND '
1565 . $table_field . ' = \'' . PMA_Util::sqlAddSlashes($source_table) . '\'';
1566 PMA_queryAsControlUser($query);
1571 * Rename a table in relation tables
1573 * usually called after table has been moved
1575 * @param string $source_db Source database name
1576 * @param string $target_db Target database name
1577 * @param string $source_table Source table name
1578 * @param string $target_table Target table name
1580 * @return void
1582 function PMA_REL_renameTable($source_db, $target_db, $source_table, $target_table)
1584 // Move old entries from PMA-DBs to new table
1585 if ($GLOBALS['cfgRelation']['commwork']) {
1586 PMA_REL_renameSingleTable(
1587 'column_info',
1588 $source_db, $target_db,
1589 $source_table, $target_table,
1590 'db_name', 'table_name'
1594 // updating bookmarks is not possible since only a single table is
1595 // moved, and not the whole DB.
1597 if ($GLOBALS['cfgRelation']['displaywork']) {
1598 PMA_REL_renameSingleTable(
1599 'table_info',
1600 $source_db, $target_db,
1601 $source_table, $target_table,
1602 'db_name', 'table_name'
1606 if ($GLOBALS['cfgRelation']['relwork']) {
1607 PMA_REL_renameSingleTable(
1608 'relation',
1609 $source_db, $target_db,
1610 $source_table, $target_table,
1611 'foreign_db', 'foreign_table'
1614 PMA_REL_renameSingleTable(
1615 'relation',
1616 $source_db, $target_db,
1617 $source_table, $target_table,
1618 'master_db', 'master_table'
1622 if ($GLOBALS['cfgRelation']['pdfwork']) {
1623 if ($source_db == $target_db) {
1624 // rename within the database can be handled
1625 PMA_REL_renameSingleTable(
1626 'table_coords',
1627 $source_db, $target_db,
1628 $source_table, $target_table,
1629 'db_name', 'table_name'
1631 } else {
1632 // if the table is moved out of the database we can no loger keep the
1633 // record for table coordinate
1634 $remove_query = "DELETE FROM "
1635 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . "."
1636 . PMA_Util::backquote($GLOBALS['cfgRelation']['table_coords'])
1637 . " WHERE db_name = '" . PMA_Util::sqlAddSlashes($source_db) . "'"
1638 . " AND table_name = '" . PMA_Util::sqlAddSlashes($source_table)
1639 . "'";
1640 PMA_queryAsControlUser($remove_query);
1644 if ($GLOBALS['cfgRelation']['uiprefswork']) {
1645 PMA_REL_renameSingleTable(
1646 'table_uiprefs',
1647 $source_db, $target_db,
1648 $source_table, $target_table,
1649 'db_name', 'table_name'
1653 if ($GLOBALS['cfgRelation']['navwork']) {
1654 // update hidden items inside table
1655 PMA_REL_renameSingleTable(
1656 'navigationhiding',
1657 $source_db, $target_db,
1658 $source_table, $target_table,
1659 'db_name', 'table_name'
1662 // update data for hidden table
1663 $query = "UPDATE "
1664 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . "."
1665 . PMA_Util::backquote($GLOBALS['cfgRelation']['navigationhiding'])
1666 . " SET db_name = '" . PMA_Util::sqlAddSlashes($target_db) . "',"
1667 . " item_name = '" . PMA_Util::sqlAddSlashes($target_table) . "'"
1668 . " WHERE db_name = '" . PMA_Util::sqlAddSlashes($source_db) . "'"
1669 . " AND item_name = '" . PMA_Util::sqlAddSlashes($source_table) . "'"
1670 . " AND item_type = 'table'";
1671 PMA_queryAsControlUser($query);
1676 * Create a PDF page
1678 * @param string $newpage name of the new PDF page
1679 * @param array $cfgRelation Relation configuration
1680 * @param string $db database name
1682 * @return string $pdf_page_number
1684 function PMA_REL_createPage($newpage, $cfgRelation, $db)
1686 if (! isset($newpage) || $newpage == '') {
1687 $newpage = __('no description');
1689 $ins_query = 'INSERT INTO '
1690 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
1691 . PMA_Util::backquote($cfgRelation['pdf_pages'])
1692 . ' (db_name, page_descr)'
1693 . ' VALUES (\''
1694 . PMA_Util::sqlAddSlashes($db) . '\', \''
1695 . PMA_Util::sqlAddSlashes($newpage) . '\')';
1696 PMA_queryAsControlUser($ins_query, false);
1698 return $GLOBALS['dbi']->insertId(
1699 isset($GLOBALS['controllink']) ? $GLOBALS['controllink'] : ''
1704 * Get child table references for a table column.
1705 * This works only if 'DisableIS' is false. An empty array is returned otherwise.
1707 * @param string $db name of master table db.
1708 * @param string $table name of master table.
1709 * @param string $column name of master table column.
1711 * @return array $child_references
1713 function PMA_getChildReferences($db, $table, $column = '')
1715 $child_references = array();
1716 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1717 $rel_query = "SELECT `column_name`, `table_name`,"
1718 . " `table_schema`, `referenced_column_name`"
1719 . " FROM `information_schema`.`key_column_usage`"
1720 . " WHERE `referenced_table_name` = '"
1721 . PMA_Util::sqlAddSlashes($table) . "'"
1722 . " AND `referenced_table_schema` = '"
1723 . PMA_Util::sqlAddSlashes($db) . "'";
1724 if ($column) {
1725 $rel_query .= " AND `referenced_column_name` = '"
1726 . PMA_Util::sqlAddSlashes($column) . "'";
1729 $child_references = $GLOBALS['dbi']->fetchResult(
1730 $rel_query, array('referenced_column_name', null)
1733 return $child_references;
1737 * Check child table references and foreign key for a table column.
1739 * @param string $db name of master table db.
1740 * @param string $table name of master table.
1741 * @param string $column name of master table column.
1742 * @param array $foreigners_full foreiners array for the whole table.
1743 * @param array $child_references_full child references for the whole table.
1745 * @return array $column_status telling about references if foreign key.
1747 function PMA_checkChildForeignReferences(
1748 $db, $table, $column, $foreigners_full = null, $child_references_full = null
1750 $column_status = array();
1751 $column_status['isEditable'] = false;
1752 $column_status['isReferenced'] = false;
1753 $column_status['isForeignKey'] = false;
1754 $column_status['references'] = array();
1756 $foreigners = array();
1757 if ($foreigners_full !== null) {
1758 if (isset($foreigners_full[$column])) {
1759 $foreigners[$column] = $foreigners_full[$column];
1761 if (isset($foreigners_full['foreign_keys_data'])) {
1762 $foreigners['foreign_keys_data'] = $foreigners_full['foreign_keys_data'];
1764 } else {
1765 $foreigners = PMA_getForeigners($db, $table, $column, 'foreign');
1767 $foreigner = PMA_searchColumnInForeigners($foreigners, $column);
1769 $child_references = array();
1770 if ($child_references_full !== null) {
1771 if (isset($child_references_full[$column])) {
1772 $child_references = $child_references_full[$column];
1774 } else {
1775 $child_references = PMA_getChildReferences($db, $table, $column);
1778 if (sizeof($child_references, 0) > 0
1779 || $foreigner
1781 if (sizeof($child_references, 0) > 0) {
1782 $column_status['isReferenced'] = true;
1783 foreach ($child_references as $row => $columns) {
1784 array_push(
1785 $column_status['references'],
1786 PMA_Util::backquote($columns['table_schema'])
1787 . '.' . PMA_Util::backquote($columns['table_name'])
1792 if ($foreigner) {
1793 $column_status['isForeignKey'] = true;
1795 } else {
1796 $column_status['isEditable'] = true;
1799 return $column_status;
1803 * Search a table column in foreign data.
1805 * @param array $foreigners Table Foreign data
1806 * @param string $column Column name
1808 * @return bool|array
1810 function PMA_searchColumnInForeigners($foreigners, $column)
1812 if (isset($foreigners[$column])) {
1813 return $foreigners[$column];
1814 } else {
1815 $foreigner = array();
1816 foreach ($foreigners['foreign_keys_data'] as $key => $one_key) {
1817 $column_index = array_search($column, $one_key['index_list']);
1818 if ($column_index !== false) {
1819 $foreigner['foreign_field']
1820 = $one_key['ref_index_list'][$column_index];
1821 $foreigner['foreign_db'] = isset($one_key['ref_db_name'])
1822 ? $one_key['ref_db_name']
1823 : $GLOBALS['db'];
1824 $foreigner['foreign_table'] = $one_key['ref_table_name'];
1825 $foreigner['constraint'] = $one_key['constraint'];
1826 $foreigner['on_update'] = isset($one_key['on_update'])
1827 ? $one_key['on_update']
1828 : 'RESTRICT';
1829 $foreigner['on_delete'] = isset($one_key['on_delete'])
1830 ? $one_key['on_delete']
1831 : 'RESTRICT';
1833 return $foreigner;
1838 return false;
1842 * Returns default PMA table names and their create queries.
1844 * @return array table name, create query
1846 function PMA_getDefaultPMATableNames()
1848 $pma_tables = array();
1849 if (PMA_DRIZZLE) {
1850 $create_tables_file = file_get_contents(
1851 SQL_DIR . 'create_tables_drizzle.sql'
1853 } else {
1854 $create_tables_file = file_get_contents(
1855 SQL_DIR . 'create_tables.sql'
1859 $queries = explode(';', $create_tables_file);
1861 foreach ($queries as $query) {
1862 if (preg_match(
1863 '/CREATE TABLE IF NOT EXISTS `(.*)` \(/',
1864 $query,
1865 $table
1868 $pma_tables[$table[1]] = $query . ';';
1872 return $pma_tables;
1876 * Creates PMA tables in the given db, updates if already exists.
1878 * @param string $db database
1879 * @param boolean $create whether to create tables if they don't exist.
1881 * @return void
1883 function PMA_fixPMATables($db, $create = true)
1885 $tablesToFeatures = array(
1886 'pma__bookmark' => 'bookmarktable',
1887 'pma__relation' => 'relation',
1888 'pma__table_info' => 'table_info',
1889 'pma__table_coords' => 'table_coords',
1890 'pma__pdf_pages' => 'pdf_pages',
1891 'pma__column_info' => 'column_info',
1892 'pma__history' => 'history',
1893 'pma__recent' => 'recent',
1894 'pma__favorite' => 'favorite',
1895 'pma__table_uiprefs' => 'table_uiprefs',
1896 'pma__tracking' => 'tracking',
1897 'pma__userconfig' => 'userconfig',
1898 'pma__users' => 'users',
1899 'pma__usergroups' => 'usergroups',
1900 'pma__navigationhiding' => 'navigationhiding',
1901 'pma__savedsearches' => 'savedsearches',
1902 'pma__central_columns' => 'central_columns'
1905 $existingTables = $GLOBALS['dbi']->getTables($db, $GLOBALS['controllink']);
1907 $createQueries = null;
1908 $foundOne = false;
1909 foreach ($tablesToFeatures as $table => $feature) {
1910 if (! in_array($table, $existingTables)) {
1911 if ($create) {
1912 if ($createQueries == null) { // first create
1913 $createQueries = PMA_getDefaultPMATableNames();
1914 $GLOBALS['dbi']->selectDb($db);
1916 $GLOBALS['dbi']->tryQuery($createQueries[$table]);
1917 if ($error = $GLOBALS['dbi']->getError()) {
1918 $GLOBALS['message'] = $error;
1919 return;
1921 $GLOBALS['cfg']['Server'][$feature] = $table;
1923 } else {
1924 $foundOne = true;
1925 $GLOBALS['cfg']['Server'][$feature] = $table;
1929 if (! $foundOne) {
1930 return;
1932 $GLOBALS['cfg']['Server']['pmadb'] = $db;
1933 $_SESSION['relation'][$GLOBALS['server']] = PMA_checkRelationsParam();
1935 $cfgRelation = PMA_getRelationsParam();
1936 if ($cfgRelation['recentwork'] || $cfgRelation['favoritework']) {
1937 // Since configuration storage is updated, we need to
1938 // re-initialize the favorite and recent tables stored in the
1939 // session from the current configuration storage.
1940 include_once 'libraries/RecentFavoriteTable.class.php';
1942 if ($cfgRelation['favoritework']) {
1943 $fav_tables = PMA_RecentFavoriteTable::getInstance('favorite');
1944 $_SESSION['tmpval']['favorite_tables'][$GLOBALS['server']]
1945 = $fav_tables->getFromDb();
1948 if ($cfgRelation['recentwork']) {
1949 $recent_tables = PMA_RecentFavoriteTable::getInstance('recent');
1950 $_SESSION['tmpval']['recent_tables'][$GLOBALS['server']]
1951 = $recent_tables->getFromDb();
1954 // Reload navi panel to update the recent/favorite lists.
1955 $GLOBALS['reload'] = true;
1960 * Get Html for PMA tables fixing anchor.
1962 * @param boolean $allTables whether to create all tables
1964 * @return string Html
1966 function PMA_getHtmlFixPMATables($allTables)
1968 $retval = '';
1970 $url_query = PMA_URL_getCommon(array('db' => $GLOBALS['db']));
1971 if ($allTables) {
1972 $url_query .= '&amp;goto=db_operations.php&amp;create_pmadb=1';
1973 $message = PMA_Message::notice(
1975 '%sCreate%s the phpMyAdmin configuration storage in the '
1976 . 'current database.'
1979 } else {
1980 $url_query .= '&amp;goto=db_operations.php&amp;fix_pmadb=1';
1981 $message = PMA_Message::notice(
1982 __('%sCreate%s missing phpMyAdmin configuration storage tables.')
1985 $message->addParam(
1986 '<a href="' . $GLOBALS['cfg']['PmaAbsoluteUri']
1987 . 'chk_rel.php' . $url_query . '">',
1988 false
1990 $message->addParam('</a>', false);
1992 $retval .= $message->getDisplay();
1994 return $retval;
1998 * Gets the relations info and status, depending on the condition
2000 * @param boolean $condition whether to look for foreigners or not
2001 * @param string $db database name
2002 * @param string $table table name
2004 * @return array ($res_rel, $have_rel)
2006 function PMA_getRelationsAndStatus($condition, $db, $table)
2008 if ($condition) {
2009 // Find which tables are related with the current one and write it in
2010 // an array
2011 $res_rel = PMA_getForeigners($db, $table);
2013 if (count($res_rel) > 0) {
2014 $have_rel = true;
2015 } else {
2016 $have_rel = false;
2018 } else {
2019 $have_rel = false;
2020 $res_rel = array();
2021 } // end if
2022 return(array($res_rel, $have_rel));