Translated using Weblate (Finnish)
[phpmyadmin.git] / libraries / relation.lib.php
blobfd11486868481ec3961cbe7979c1b25f7817901c
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_getRelationsParam()' 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 if (($isInformationSchema || $is_data_dictionary)
714 && ($source == 'internal' || $source == 'both')
716 if ($isInformationSchema) {
717 $relations_key = 'information_schema_relations';
718 include_once './libraries/information_schema_relations.lib.php';
719 } else {
720 $relations_key = 'data_dictionary_relations';
721 include_once './libraries/data_dictionary_relations.lib.php';
723 if (isset($GLOBALS[$relations_key][$table])) {
724 foreach ($GLOBALS[$relations_key][$table] as $field => $relations) {
725 if ((! /*overload*/mb_strlen($column) || $column == $field)
726 && (! isset($foreign[$field])
727 || ! /*overload*/mb_strlen($foreign[$field]))
729 $foreign[$field] = $relations;
735 return $foreign;
736 } // end of the 'PMA_getForeigners()' function
739 * Gets the display field of a table
741 * @param string $db the name of the db to check for
742 * @param string $table the name of the table to check for
744 * @return string field name
746 * @access public
748 function PMA_getDisplayField($db, $table)
750 $cfgRelation = PMA_getRelationsParam();
753 * Try to fetch the display field from DB.
755 if ($cfgRelation['displaywork']) {
756 $disp_query = '
757 SELECT `display_field`
758 FROM ' . PMA_Util::backquote($cfgRelation['db'])
759 . '.' . PMA_Util::backquote($cfgRelation['table_info']) . '
760 WHERE `db_name` = \'' . PMA_Util::sqlAddSlashes($db) . '\'
761 AND `table_name` = \'' . PMA_Util::sqlAddSlashes($table) . '\'';
763 $row = $GLOBALS['dbi']->fetchSingleRow(
764 $disp_query, 'ASSOC', $GLOBALS['controllink']
766 if (isset($row['display_field'])) {
767 return $row['display_field'];
772 * Emulating the display field for some information_schema tables.
774 if ($db == 'information_schema') {
775 switch ($table) {
776 case 'CHARACTER_SETS':
777 return 'DESCRIPTION';
778 case 'TABLES':
779 return 'TABLE_COMMENT';
784 * No Luck...
786 return false;
788 } // end of the 'PMA_getDisplayField()' function
791 * Gets the comments for all columns of a table or the db itself
793 * @param string $db the name of the db to check for
794 * @param string $table the name of the table to check for
796 * @return array [column_name] = comment
798 * @access public
800 function PMA_getComments($db, $table = '')
802 $comments = array();
804 if ($table != '') {
805 // MySQL native column comments
806 $columns = $GLOBALS['dbi']->getColumns($db, $table, null, true);
807 if ($columns) {
808 foreach ($columns as $column) {
809 if (! empty($column['Comment'])) {
810 $comments[$column['Field']] = $column['Comment'];
814 } else {
815 $comments[] = PMA_getDbComment($db);
818 return $comments;
819 } // end of the 'PMA_getComments()' function
822 * Gets the comment for a db
824 * @param string $db the name of the db to check for
826 * @return string comment
828 * @access public
830 function PMA_getDbComment($db)
832 $cfgRelation = PMA_getRelationsParam();
833 $comment = '';
835 if ($cfgRelation['commwork']) {
836 // pmadb internal db comment
837 $com_qry = "
838 SELECT `comment`
839 FROM " . PMA_Util::backquote($cfgRelation['db'])
840 . "." . PMA_Util::backquote($cfgRelation['column_info']) . "
841 WHERE db_name = '" . PMA_Util::sqlAddSlashes($db) . "'
842 AND table_name = ''
843 AND column_name = '(db_comment)'";
844 $com_rs = PMA_queryAsControlUser(
845 $com_qry, true, PMA_DatabaseInterface::QUERY_STORE
848 if ($com_rs && $GLOBALS['dbi']->numRows($com_rs) > 0) {
849 $row = $GLOBALS['dbi']->fetchAssoc($com_rs);
850 $comment = $row['comment'];
852 $GLOBALS['dbi']->freeResult($com_rs);
855 return $comment;
856 } // end of the 'PMA_getDbComment()' function
859 * Gets the comment for a db
861 * @access public
863 * @return string comment
865 function PMA_getDbComments()
867 $cfgRelation = PMA_getRelationsParam();
868 $comments = array();
870 if ($cfgRelation['commwork']) {
871 // pmadb internal db comment
872 $com_qry = "
873 SELECT `db_name`, `comment`
874 FROM " . PMA_Util::backquote($cfgRelation['db'])
875 . "." . PMA_Util::backquote($cfgRelation['column_info']) . "
876 WHERE `column_name` = '(db_comment)'";
877 $com_rs = PMA_queryAsControlUser(
878 $com_qry, true, PMA_DatabaseInterface::QUERY_STORE
881 if ($com_rs && $GLOBALS['dbi']->numRows($com_rs) > 0) {
882 while ($row = $GLOBALS['dbi']->fetchAssoc($com_rs)) {
883 $comments[$row['db_name']] = $row['comment'];
886 $GLOBALS['dbi']->freeResult($com_rs);
889 return $comments;
890 } // end of the 'PMA_getDbComments()' function
893 * Set a database comment to a certain value.
895 * @param string $db the name of the db
896 * @param string $comment the value of the column
898 * @return boolean true, if comment-query was made.
900 * @access public
902 function PMA_setDbComment($db, $comment = '')
904 $cfgRelation = PMA_getRelationsParam();
906 if (! $cfgRelation['commwork']) {
907 return false;
910 if (/*overload*/mb_strlen($comment)) {
911 $upd_query = 'INSERT INTO '
912 . PMA_Util::backquote($cfgRelation['db']) . '.'
913 . PMA_Util::backquote($cfgRelation['column_info'])
914 . ' (`db_name`, `table_name`, `column_name`, `comment`)'
915 . ' VALUES (\''
916 . PMA_Util::sqlAddSlashes($db)
917 . "', '', '(db_comment)', '"
918 . PMA_Util::sqlAddSlashes($comment)
919 . "') "
920 . ' ON DUPLICATE KEY UPDATE '
921 . "`comment` = '" . PMA_Util::sqlAddSlashes($comment) . "'";
922 } else {
923 $upd_query = 'DELETE FROM '
924 . PMA_Util::backquote($cfgRelation['db']) . '.'
925 . PMA_Util::backquote($cfgRelation['column_info'])
926 . ' WHERE `db_name` = \'' . PMA_Util::sqlAddSlashes($db) . '\'
927 AND `table_name` = \'\'
928 AND `column_name` = \'(db_comment)\'';
931 if (isset($upd_query)) {
932 return PMA_queryAsControlUser($upd_query);
935 return false;
936 } // end of 'PMA_setDbComment()' function
939 * Set a SQL history entry
941 * @param string $db the name of the db
942 * @param string $table the name of the table
943 * @param string $username the username
944 * @param string $sqlquery the sql query
946 * @return void
948 * @access public
950 function PMA_setHistory($db, $table, $username, $sqlquery)
952 $maxCharactersInDisplayedSQL = $GLOBALS['cfg']['MaxCharactersInDisplayedSQL'];
953 // Prevent to run this automatically on Footer class destroying in testsuite
954 if (defined('TESTSUITE')
955 || /*overload*/mb_strlen($sqlquery) > $maxCharactersInDisplayedSQL
957 return;
960 $cfgRelation = PMA_getRelationsParam();
962 if (! isset($_SESSION['sql_history'])) {
963 $_SESSION['sql_history'] = array();
966 $_SESSION['sql_history'][] = array(
967 'db' => $db,
968 'table' => $table,
969 'sqlquery' => $sqlquery,
972 if (count($_SESSION['sql_history']) > $GLOBALS['cfg']['QueryHistoryMax']) {
973 // history should not exceed a maximum count
974 array_shift($_SESSION['sql_history']);
977 if (! $cfgRelation['historywork'] || ! $GLOBALS['cfg']['QueryHistoryDB']) {
978 return;
981 PMA_queryAsControlUser(
982 'INSERT INTO '
983 . PMA_Util::backquote($cfgRelation['db']) . '.'
984 . PMA_Util::backquote($cfgRelation['history']) . '
985 (`username`,
986 `db`,
987 `table`,
988 `timevalue`,
989 `sqlquery`)
990 VALUES
991 (\'' . PMA_Util::sqlAddSlashes($username) . '\',
992 \'' . PMA_Util::sqlAddSlashes($db) . '\',
993 \'' . PMA_Util::sqlAddSlashes($table) . '\',
994 NOW(),
995 \'' . PMA_Util::sqlAddSlashes($sqlquery) . '\')'
998 PMA_purgeHistory($username);
1000 } // end of 'PMA_setHistory()' function
1003 * Gets a SQL history entry
1005 * @param string $username the username
1007 * @return array list of history items
1009 * @access public
1011 function PMA_getHistory($username)
1013 $cfgRelation = PMA_getRelationsParam();
1015 if (! $cfgRelation['historywork']) {
1016 return false;
1020 * if db-based history is disabled but there exists a session-based
1021 * history, use it
1023 if (! $GLOBALS['cfg']['QueryHistoryDB']) {
1024 if (isset($_SESSION['sql_history'])) {
1025 return array_reverse($_SESSION['sql_history']);
1027 return false;
1030 $hist_query = '
1031 SELECT `db`,
1032 `table`,
1033 `sqlquery`,
1034 `timevalue`
1035 FROM ' . PMA_Util::backquote($cfgRelation['db'])
1036 . '.' . PMA_Util::backquote($cfgRelation['history']) . '
1037 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
1038 ORDER BY `id` DESC';
1040 return $GLOBALS['dbi']->fetchResult(
1041 $hist_query, null, null, $GLOBALS['controllink']
1043 } // end of 'PMA_getHistory()' function
1046 * purges SQL history
1048 * deletes entries that exceeds $cfg['QueryHistoryMax'], oldest first, for the
1049 * given user
1051 * @param string $username the username
1053 * @return void
1055 * @access public
1057 function PMA_purgeHistory($username)
1059 $cfgRelation = PMA_getRelationsParam();
1060 if (! $GLOBALS['cfg']['QueryHistoryDB'] || ! $cfgRelation['historywork']) {
1061 return;
1064 if (! $cfgRelation['historywork']) {
1065 return;
1068 $search_query = '
1069 SELECT `timevalue`
1070 FROM ' . PMA_Util::backquote($cfgRelation['db'])
1071 . '.' . PMA_Util::backquote($cfgRelation['history']) . '
1072 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
1073 ORDER BY `timevalue` DESC
1074 LIMIT ' . $GLOBALS['cfg']['QueryHistoryMax'] . ', 1';
1076 if ($max_time = $GLOBALS['dbi']->fetchValue(
1077 $search_query, 0, 0, $GLOBALS['controllink']
1078 )) {
1079 PMA_queryAsControlUser(
1080 'DELETE FROM '
1081 . PMA_Util::backquote($cfgRelation['db']) . '.'
1082 . PMA_Util::backquote($cfgRelation['history']) . '
1083 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
1084 AND `timevalue` <= \'' . $max_time . '\''
1087 } // end of 'PMA_purgeHistory()' function
1090 * Prepares the dropdown for one mode
1092 * @param array $foreign the keys and values for foreigns
1093 * @param string $data the current data of the dropdown
1094 * @param string $mode the needed mode
1096 * @return array the <option value=""><option>s
1098 * @access protected
1100 function PMA_buildForeignDropdown($foreign, $data, $mode)
1102 $reloptions = array();
1104 // id-only is a special mode used when no foreign display column
1105 // is available
1106 if ($mode == 'id-content' || $mode == 'id-only') {
1107 // sort for id-content
1108 if ($GLOBALS['cfg']['NaturalOrder']) {
1109 uksort($foreign, 'strnatcasecmp');
1110 } else {
1111 ksort($foreign);
1113 } elseif ($mode == 'content-id') {
1114 // sort for content-id
1115 if ($GLOBALS['cfg']['NaturalOrder']) {
1116 natcasesort($foreign);
1117 } else {
1118 asort($foreign);
1122 foreach ($foreign as $key => $value) {
1123 if (/*overload*/mb_strlen($value) <= $GLOBALS['cfg']['LimitChars']
1125 $vtitle = '';
1126 $value = htmlspecialchars($value);
1127 } else {
1128 $vtitle = htmlspecialchars($value);
1129 $value = htmlspecialchars(
1130 /*overload*/mb_substr(
1131 $value, 0, $GLOBALS['cfg']['LimitChars']
1132 ) . '...'
1136 $reloption = '<option value="' . htmlspecialchars($key) . '"';
1137 if ($vtitle != '') {
1138 $reloption .= ' title="' . $vtitle . '"';
1141 if ((string) $key == (string) $data) {
1142 $reloption .= ' selected="selected"';
1145 if ($mode == 'content-id') {
1146 $reloptions[] = $reloption . '>'
1147 . $value . '&nbsp;-&nbsp;' . htmlspecialchars($key) . '</option>';
1148 } elseif ($mode == 'id-content') {
1149 $reloptions[] = $reloption . '>'
1150 . htmlspecialchars($key) . '&nbsp;-&nbsp;' . $value . '</option>';
1151 } elseif ($mode == 'id-only') {
1152 $reloptions[] = $reloption . '>'
1153 . htmlspecialchars($key) . '</option>';
1155 } // end foreach
1157 return $reloptions;
1158 } // end of 'PMA_buildForeignDropdown' function
1161 * Outputs dropdown with values of foreign fields
1163 * @param array $disp_row array of the displayed row
1164 * @param string $foreign_field the foreign field
1165 * @param string $foreign_display the foreign field to display
1166 * @param string $data the current data of the dropdown (field in row)
1167 * @param int $max maximum number of items in the dropdown
1169 * @return string the <option value=""><option>s
1171 * @access public
1173 function PMA_foreignDropdown($disp_row, $foreign_field, $foreign_display, $data,
1174 $max = null
1176 if (null === $max) {
1177 $max = $GLOBALS['cfg']['ForeignKeyMaxLimit'];
1180 $foreign = array();
1182 // collect the data
1183 foreach ($disp_row as $relrow) {
1184 $key = $relrow[$foreign_field];
1186 // if the display field has been defined for this foreign table
1187 if ($foreign_display) {
1188 $value = $relrow[$foreign_display];
1189 } else {
1190 $value = '';
1191 } // end if ($foreign_display)
1193 $foreign[$key] = $value;
1194 } // end foreach
1196 // put the dropdown sections in correct order
1197 $top = array();
1198 $bottom = array();
1199 if ($foreign_display) {
1200 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'], 'array')) {
1201 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][0])) {
1202 $top = PMA_buildForeignDropdown(
1203 $foreign,
1204 $data,
1205 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][0]
1208 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][1])) {
1209 $bottom = PMA_buildForeignDropdown(
1210 $foreign,
1211 $data,
1212 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][1]
1215 } else {
1216 $top = PMA_buildForeignDropdown($foreign, $data, 'id-content');
1217 $bottom = PMA_buildForeignDropdown($foreign, $data, 'content-id');
1219 } else {
1220 $top = PMA_buildForeignDropdown($foreign, $data, 'id-only');
1223 // beginning of dropdown
1224 $ret = '<option value="">&nbsp;</option>';
1225 $top_count = count($top);
1226 if ($max == -1 || $top_count < $max) {
1227 $ret .= implode('', $top);
1228 if ($foreign_display && $top_count > 0) {
1229 // this empty option is to visually mark the beginning of the
1230 // second series of values (bottom)
1231 $ret .= '<option value="">&nbsp;</option>';
1234 if ($foreign_display) {
1235 $ret .= implode('', $bottom);
1238 return $ret;
1239 } // end of 'PMA_foreignDropdown()' function
1242 * Gets foreign keys in preparation for a drop-down selector
1244 * @param array|boolean $foreigners array of the foreign keys
1245 * @param string $field the foreign field name
1246 * @param bool $override_total whether to override the total
1247 * @param string $foreign_filter a possible filter
1248 * @param string $foreign_limit a possible LIMIT clause
1250 * @return array data about the foreign keys
1252 * @access public
1255 function PMA_getForeignData(
1256 $foreigners, $field, $override_total, $foreign_filter, $foreign_limit
1258 // we always show the foreign field in the drop-down; if a display
1259 // field is defined, we show it besides the foreign field
1260 $foreign_link = false;
1261 do {
1262 if (! $foreigners) {
1263 break;
1265 $foreigner = PMA_searchColumnInForeigners($foreigners, $field);
1266 if ($foreigner != false) {
1267 $foreign_db = $foreigner['foreign_db'];
1268 $foreign_table = $foreigner['foreign_table'];
1269 $foreign_field = $foreigner['foreign_field'];
1270 } else {
1271 break;
1274 // Count number of rows in the foreign table. Currently we do
1275 // not use a drop-down if more than ForeignKeyMaxLimit rows in the
1276 // foreign table,
1277 // for speed reasons and because we need a better interface for this.
1279 // We could also do the SELECT anyway, with a LIMIT, and ensure that
1280 // the current value of the field is one of the choices.
1282 $the_total = PMA_Table::countRecords($foreign_db, $foreign_table, true);
1284 if ($override_total == true
1285 || $the_total < $GLOBALS['cfg']['ForeignKeyMaxLimit']
1287 // foreign_display can be false if no display field defined:
1288 $foreign_display = PMA_getDisplayField($foreign_db, $foreign_table);
1290 $f_query_main = 'SELECT ' . PMA_Util::backquote($foreign_field)
1292 ($foreign_display == false)
1293 ? ''
1294 : ', ' . PMA_Util::backquote($foreign_display)
1296 $f_query_from = ' FROM ' . PMA_Util::backquote($foreign_db)
1297 . '.' . PMA_Util::backquote($foreign_table);
1298 $f_query_filter = empty($foreign_filter) ? '' : ' WHERE '
1299 . PMA_Util::backquote($foreign_field)
1300 . ' LIKE "%' . PMA_Util::sqlAddSlashes($foreign_filter, true) . '%"'
1302 ($foreign_display == false)
1303 ? ''
1304 : ' OR ' . PMA_Util::backquote($foreign_display)
1305 . ' LIKE "%' . PMA_Util::sqlAddSlashes($foreign_filter, true)
1306 . '%"'
1308 $f_query_order = ($foreign_display == false) ? '' :' ORDER BY '
1309 . PMA_Util::backquote($foreign_table) . '.'
1310 . PMA_Util::backquote($foreign_display);
1311 $f_query_limit = isset($foreign_limit) ? $foreign_limit : '';
1313 if (!empty($foreign_filter)) {
1314 $the_total = $GLOBALS['dbi']->fetchValue(
1315 'SELECT COUNT(*)' . $f_query_from . $f_query_filter
1317 if ($the_total === false) {
1318 $the_total = 0;
1322 $disp = $GLOBALS['dbi']->tryQuery(
1323 $f_query_main . $f_query_from . $f_query_filter
1324 . $f_query_order . $f_query_limit
1326 if ($disp && $GLOBALS['dbi']->numRows($disp) > 0) {
1327 // If a resultset has been created, pre-cache it in the $disp_row
1328 // array. This helps us from not needing to use mysql_data_seek by
1329 // accessing a pre-cached PHP array. Usually those resultsets are
1330 // not that big, so a performance hit should not be expected.
1331 $disp_row = array();
1332 while ($single_disp_row = @$GLOBALS['dbi']->fetchAssoc($disp)) {
1333 $disp_row[] = $single_disp_row;
1335 @$GLOBALS['dbi']->freeResult($disp);
1336 } else {
1337 // Either no data in the foreign table or
1338 // user does not have select permission to foreign table/field
1339 // Show an input field with a 'Browse foreign values' link
1340 $disp_row = null;
1341 $foreign_link = true;
1343 } else {
1344 $disp_row = null;
1345 $foreign_link = true;
1347 } while (false);
1349 $foreignData = array();
1350 $foreignData['foreign_link'] = $foreign_link;
1351 $foreignData['the_total'] = isset($the_total) ? $the_total : null;
1352 $foreignData['foreign_display'] = (
1353 isset($foreign_display) ? $foreign_display : null
1355 $foreignData['disp_row'] = isset($disp_row) ? $disp_row : null;
1356 $foreignData['foreign_field'] = isset($foreign_field) ? $foreign_field : null;
1357 return $foreignData;
1358 } // end of 'PMA_getForeignData()' function
1361 * Finds all related tables
1363 * @param array $all_tables All the involved tables
1364 * @param string $master The master table to form the LEFT JOIN clause
1366 * @return string LEFT JOIN
1367 * @access private
1369 function PMA_getRelatives($all_tables, $master)
1371 $fromclause = '';
1372 $left_joins = array();
1373 $emerg = '';
1374 $ignore_internal_relations = false;
1376 // The list of tables that we still couldn't connect
1377 $remaining_tables = $all_tables;
1378 unset($remaining_tables[$master]);
1379 // The list of already connected tables
1380 $known_tables = array();
1381 $known_tables[$master] = $master;
1382 $run = 0;
1383 while ($GLOBALS['cfgRelation']['relwork'] && count($remaining_tables) > 0) {
1384 // Whether to go from master to foreign or vice versa
1385 if ($run % 2 == 0) {
1386 $from = 'master';
1387 $to = 'foreign';
1388 } else {
1389 $from = 'foreign';
1390 $to = 'master';
1392 $in_know = '(\'' . implode('\', \'', $known_tables) . '\')';
1393 $in_left = '(\'' . implode('\', \'', $remaining_tables) . '\')';
1394 $rel_query = 'SELECT *'
1395 . ' FROM ' . PMA_Util::backquote($GLOBALS['cfgRelation']['db'])
1396 . '.' . PMA_Util::backquote($GLOBALS['cfgRelation']['relation'])
1397 . ' WHERE ' . $from . '_db = \''
1398 . PMA_Util::sqlAddSlashes($GLOBALS['db']) . '\''
1399 . ' AND ' . $to . '_db = \''
1400 . PMA_Util::sqlAddSlashes($GLOBALS['db']) . '\''
1401 . ' AND ' . $from . '_table IN ' . $in_know
1402 . ' AND ' . $to . '_table IN ' . $in_left;
1403 $relations = @$GLOBALS['dbi']->query($rel_query, $GLOBALS['controllink']);
1404 while ($row = $GLOBALS['dbi']->fetchAssoc($relations)) {
1405 $found_table = $row[$to . '_table'];
1406 if (isset($remaining_tables[$found_table])) {
1407 $left_join_with = PMA_Util::backquote($GLOBALS['db']) . '.'
1408 . PMA_Util::backquote($row[$to . '_table']);
1409 $on_condition = PMA_Util::backquote($row[$from . '_table']) . '.'
1410 . PMA_Util::backquote($row[$from . '_field']) . ' = '
1411 . PMA_Util::backquote($row[$to . '_table']) . '.'
1412 . PMA_Util::backquote($row[$to . '_field']);
1414 $left_joins[$left_join_with] = array(
1415 'left_join_with' => $left_join_with,
1416 'on_condition' => array($on_condition)
1419 $known_tables[$found_table] = $found_table;
1420 unset($remaining_tables[$found_table]);
1422 } // end while
1423 $run++;
1424 if ($run > 5) {
1425 foreach ($remaining_tables as $table) {
1426 $emerg .= ', ' . PMA_Util::backquote($table);
1427 unset($remaining_tables[$table]);
1430 } // end while
1432 // Generate 'LEFT JOIN's for InnoDB foreign keys.
1433 $remaining_tables = $all_tables;
1434 foreach ($remaining_tables as $one_table) {
1435 $foreigners = PMA_getForeigners($GLOBALS['db'], $one_table, '', 'foreign');
1436 foreach ($foreigners['foreign_keys_data'] as $one_key) {
1437 if (in_array($one_key['ref_table_name'], $all_tables)
1438 && ! isset($one_key['ref_db_name'])
1439 && ($one_key['ref_table_name'] == $master
1440 || $one_key['ref_table_name'] == $one_table)
1442 $left_join_with = PMA_Util::backquote($GLOBALS['db']) . '.'
1443 . PMA_Util::backquote($one_table);
1444 if (! isset($left_joins[$left_join_with])) {
1445 $left_joins[$left_join_with] = array(
1446 'left_join_with' =>$left_join_with,
1447 'on_condition' => array()
1451 foreach ($one_key['ref_index_list'] as $key => $one_column) {
1452 $on_condition = PMA_Util::backquote($one_key['ref_table_name'])
1453 . '.' . PMA_Util::backquote($one_column) . ' = '
1454 . PMA_Util::backquote($one_table) . '.'
1455 . PMA_Util::backquote($one_key['index_list'][$key]);
1457 if (! in_array($on_condition, $left_joins[$left_join_with]['on_condition'])) {
1458 $left_joins[$left_join_with]['on_condition'][]
1459 = $on_condition;
1462 $ignore_internal_relations = true;
1463 unset($remaining_tables[$one_table]);
1468 if ($ignore_internal_relations) {
1469 $emerg = '';
1472 // Build the 'FROM' clause.
1473 foreach ($left_joins as $one_join) {
1474 $fromclause .= "\n" . ' LEFT JOIN '
1475 . $one_join['left_join_with']
1476 . ' ON '
1477 . implode(' AND ', $one_join['on_condition']);
1480 $fromclause = $emerg . $fromclause;
1481 return $fromclause;
1482 } // end of the "PMA_getRelatives()" function
1485 * Rename a field in relation tables
1487 * usually called after a column in a table was renamed
1489 * @param string $db database name
1490 * @param string $table table name
1491 * @param string $field old field name
1492 * @param string $new_name new field name
1494 * @return void
1496 function PMA_REL_renameField($db, $table, $field, $new_name)
1498 $cfgRelation = PMA_getRelationsParam();
1500 if ($cfgRelation['displaywork']) {
1501 $table_query = 'UPDATE '
1502 . PMA_Util::backquote($cfgRelation['db']) . '.'
1503 . PMA_Util::backquote($cfgRelation['table_info'])
1504 . ' SET display_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1505 . ' WHERE db_name = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1506 . ' AND table_name = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1507 . ' AND display_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1508 PMA_queryAsControlUser($table_query);
1511 if ($cfgRelation['relwork']) {
1512 $table_query = 'UPDATE '
1513 . PMA_Util::backquote($cfgRelation['db']) . '.'
1514 . PMA_Util::backquote($cfgRelation['relation'])
1515 . ' SET master_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1516 . ' WHERE master_db = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1517 . ' AND master_table = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1518 . ' AND master_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1519 PMA_queryAsControlUser($table_query);
1521 $table_query = 'UPDATE '
1522 . PMA_Util::backquote($cfgRelation['db']) . '.'
1523 . PMA_Util::backquote($cfgRelation['relation'])
1524 . ' SET foreign_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1525 . ' WHERE foreign_db = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1526 . ' AND foreign_table = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1527 . ' AND foreign_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1528 PMA_queryAsControlUser($table_query);
1530 } // end if relwork
1535 * Performs SQL query used for renaming table.
1537 * @param string $table Relation table to use
1538 * @param string $source_db Source database name
1539 * @param string $target_db Target database name
1540 * @param string $source_table Source table name
1541 * @param string $target_table Target table name
1542 * @param string $db_field Name of database field
1543 * @param string $table_field Name of table field
1545 * @return void
1547 function PMA_REL_renameSingleTable($table,
1548 $source_db, $target_db,
1549 $source_table, $target_table,
1550 $db_field, $table_field
1552 $query = 'UPDATE '
1553 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
1554 . PMA_Util::backquote($GLOBALS['cfgRelation'][$table])
1555 . ' SET '
1556 . $db_field . ' = \'' . PMA_Util::sqlAddSlashes($target_db) . '\', '
1557 . $table_field . ' = \'' . PMA_Util::sqlAddSlashes($target_table) . '\''
1558 . ' WHERE '
1559 . $db_field . ' = \'' . PMA_Util::sqlAddSlashes($source_db) . '\''
1560 . ' AND '
1561 . $table_field . ' = \'' . PMA_Util::sqlAddSlashes($source_table) . '\'';
1562 PMA_queryAsControlUser($query);
1567 * Rename a table in relation tables
1569 * usually called after table has been moved
1571 * @param string $source_db Source database name
1572 * @param string $target_db Target database name
1573 * @param string $source_table Source table name
1574 * @param string $target_table Target table name
1576 * @return void
1578 function PMA_REL_renameTable($source_db, $target_db, $source_table, $target_table)
1580 // Move old entries from PMA-DBs to new table
1581 if ($GLOBALS['cfgRelation']['commwork']) {
1582 PMA_REL_renameSingleTable(
1583 'column_info',
1584 $source_db, $target_db,
1585 $source_table, $target_table,
1586 'db_name', 'table_name'
1590 // updating bookmarks is not possible since only a single table is
1591 // moved, and not the whole DB.
1593 if ($GLOBALS['cfgRelation']['displaywork']) {
1594 PMA_REL_renameSingleTable(
1595 'table_info',
1596 $source_db, $target_db,
1597 $source_table, $target_table,
1598 'db_name', 'table_name'
1602 if ($GLOBALS['cfgRelation']['relwork']) {
1603 PMA_REL_renameSingleTable(
1604 'relation',
1605 $source_db, $target_db,
1606 $source_table, $target_table,
1607 'foreign_db', 'foreign_table'
1610 PMA_REL_renameSingleTable(
1611 'relation',
1612 $source_db, $target_db,
1613 $source_table, $target_table,
1614 'master_db', 'master_table'
1618 if ($GLOBALS['cfgRelation']['pdfwork']) {
1619 if ($source_db == $target_db) {
1620 // rename within the database can be handled
1621 PMA_REL_renameSingleTable(
1622 'table_coords',
1623 $source_db, $target_db,
1624 $source_table, $target_table,
1625 'db_name', 'table_name'
1627 } else {
1628 // if the table is moved out of the database we can no loger keep the
1629 // record for table coordinate
1630 $remove_query = "DELETE FROM "
1631 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . "."
1632 . PMA_Util::backquote($GLOBALS['cfgRelation']['table_coords'])
1633 . " WHERE db_name = '" . PMA_Util::sqlAddSlashes($source_db) . "'"
1634 . " AND table_name = '" . PMA_Util::sqlAddSlashes($source_table)
1635 . "'";
1636 PMA_queryAsControlUser($remove_query);
1640 if ($GLOBALS['cfgRelation']['uiprefswork']) {
1641 PMA_REL_renameSingleTable(
1642 'table_uiprefs',
1643 $source_db, $target_db,
1644 $source_table, $target_table,
1645 'db_name', 'table_name'
1649 if ($GLOBALS['cfgRelation']['navwork']) {
1650 // update hidden items inside table
1651 PMA_REL_renameSingleTable(
1652 'navigationhiding',
1653 $source_db, $target_db,
1654 $source_table, $target_table,
1655 'db_name', 'table_name'
1658 // update data for hidden table
1659 $query = "UPDATE "
1660 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . "."
1661 . PMA_Util::backquote($GLOBALS['cfgRelation']['navigationhiding'])
1662 . " SET db_name = '" . PMA_Util::sqlAddSlashes($target_db) . "',"
1663 . " item_name = '" . PMA_Util::sqlAddSlashes($target_table) . "'"
1664 . " WHERE db_name = '" . PMA_Util::sqlAddSlashes($source_db) . "'"
1665 . " AND item_name = '" . PMA_Util::sqlAddSlashes($source_table) . "'"
1666 . " AND item_type = 'table'";
1667 PMA_queryAsControlUser($query);
1672 * Create a PDF page
1674 * @param string $newpage name of the new PDF page
1675 * @param array $cfgRelation Relation configuration
1676 * @param string $db database name
1678 * @return string $pdf_page_number
1680 function PMA_REL_createPage($newpage, $cfgRelation, $db)
1682 if (! isset($newpage) || $newpage == '') {
1683 $newpage = __('no description');
1685 $ins_query = 'INSERT INTO '
1686 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
1687 . PMA_Util::backquote($cfgRelation['pdf_pages'])
1688 . ' (db_name, page_descr)'
1689 . ' VALUES (\''
1690 . PMA_Util::sqlAddSlashes($db) . '\', \''
1691 . PMA_Util::sqlAddSlashes($newpage) . '\')';
1692 PMA_queryAsControlUser($ins_query, false);
1694 return $GLOBALS['dbi']->insertId(
1695 isset($GLOBALS['controllink']) ? $GLOBALS['controllink'] : ''
1700 * Get child table references for a table column.
1701 * This works only if 'DisableIS' is false. An empty array is returned otherwise.
1703 * @param string $db name of master table db.
1704 * @param string $table name of master table.
1705 * @param string $column name of master table column.
1707 * @return array $child_references
1709 function PMA_getChildReferences($db, $table, $column = '')
1711 $child_references = array();
1712 if (! $GLOBALS['cfg']['Server']['DisableIS']) {
1713 $rel_query = "SELECT `column_name`, `table_name`,"
1714 . " `table_schema`, `referenced_column_name`"
1715 . " FROM `information_schema`.`key_column_usage`"
1716 . " WHERE `referenced_table_name` = '"
1717 . PMA_Util::sqlAddSlashes($table) . "'"
1718 . " AND `referenced_table_schema` = '"
1719 . PMA_Util::sqlAddSlashes($db) . "'";
1720 if ($column) {
1721 $rel_query .= " AND `referenced_column_name` = '"
1722 . PMA_Util::sqlAddSlashes($column) . "'";
1725 $child_references = $GLOBALS['dbi']->fetchResult(
1726 $rel_query, array('referenced_column_name', null),
1727 null, $GLOBALS['controllink']
1730 return $child_references;
1734 * Check child table references and foreign key for a table column.
1736 * @param string $db name of master table db.
1737 * @param string $table name of master table.
1738 * @param string $column name of master table column.
1739 * @param array $foreigners_full foreiners array for the whole table.
1740 * @param array $child_references_full child references for the whole table.
1742 * @return array $column_status telling about references if foreign key.
1744 function PMA_checkChildForeignReferences(
1745 $db, $table, $column, $foreigners_full = null, $child_references_full = null
1747 $column_status = array();
1748 $column_status['isEditable'] = false;
1749 $column_status['isReferenced'] = false;
1750 $column_status['isForeignKey'] = false;
1751 $column_status['references'] = array();
1753 $foreigners = array();
1754 if ($foreigners_full !== null) {
1755 if (isset($foreigners_full[$column])) {
1756 $foreigners[$column] = $foreigners_full[$column];
1758 if (isset($foreigners_full['foreign_keys_data'])) {
1759 $foreigners['foreign_keys_data'] = $foreigners_full['foreign_keys_data'];
1761 } else {
1762 $foreigners = PMA_getForeigners($db, $table, $column, 'foreign');
1764 $foreigner = PMA_searchColumnInForeigners($foreigners, $column);
1766 $child_references = array();
1767 if ($child_references_full !== null) {
1768 if (isset($child_references_full[$column])) {
1769 $child_references = $child_references_full[$column];
1771 } else {
1772 $child_references = PMA_getChildReferences($db, $table, $column);
1775 if (sizeof($child_references, 0) > 0
1776 || $foreigner
1778 if (sizeof($child_references, 0) > 0) {
1779 $column_status['isReferenced'] = true;
1780 foreach ($child_references as $row => $columns) {
1781 array_push(
1782 $column_status['references'],
1783 PMA_Util::backquote($columns['table_schema'])
1784 . '.' . PMA_Util::backquote($columns['table_name'])
1789 if ($foreigner) {
1790 $column_status['isForeignKey'] = true;
1792 } else {
1793 $column_status['isEditable'] = true;
1796 return $column_status;
1800 * Search a table column in foreign data.
1802 * @param array $foreigners Table Foreign data
1803 * @param string $column Column name
1805 * @return bool|array
1807 function PMA_searchColumnInForeigners($foreigners, $column)
1809 if (isset($foreigners[$column])) {
1810 return $foreigners[$column];
1811 } else {
1812 $foreigner = array();
1813 foreach ($foreigners['foreign_keys_data'] as $key => $one_key) {
1814 $column_index = array_search($column, $one_key['index_list']);
1815 if ($column_index !== false) {
1816 $foreigner['foreign_field']
1817 = $one_key['ref_index_list'][$column_index];
1818 $foreigner['foreign_db'] = isset($one_key['ref_db_name'])
1819 ? $one_key['ref_db_name']
1820 : $GLOBALS['db'];
1821 $foreigner['foreign_table'] = $one_key['ref_table_name'];
1822 $foreigner['constraint'] = $one_key['constraint'];
1824 return $foreigner;
1829 return false;
1833 * Returns default PMA table names and their create queries.
1835 * @return array table name, create query
1837 function PMA_getDefaultPMATableNames()
1839 $pma_tables = array();
1840 if (PMA_DRIZZLE) {
1841 $create_tables_file = file_get_contents(
1842 SQL_DIR . 'create_tables_drizzle.sql'
1844 } else {
1845 $create_tables_file = file_get_contents(
1846 SQL_DIR . 'create_tables.sql'
1850 $queries = explode(';', $create_tables_file);
1852 foreach ($queries as $query) {
1853 if (preg_match(
1854 '/CREATE TABLE IF NOT EXISTS `(.*)` \(/',
1855 $query,
1856 $table
1859 $pma_tables[$table[1]] = $query . ';';
1863 return $pma_tables;
1867 * Creates PMA tables in the given db, updates if already exists.
1869 * @param string $db database
1870 * @param boolean $create whether to create tables if they don't exist.
1872 * @return void
1874 function PMA_fixPMATables($db, $create = true)
1876 $tablesToFeatures = array(
1877 'pma__bookmark' => 'bookmarktable',
1878 'pma__relation' => 'relation',
1879 'pma__table_info' => 'table_info',
1880 'pma__table_coords' => 'table_coords',
1881 'pma__pdf_pages' => 'pdf_pages',
1882 'pma__column_info' => 'column_info',
1883 'pma__history' => 'history',
1884 'pma__recent' => 'recent',
1885 'pma__favorite' => 'favorite',
1886 'pma__table_uiprefs' => 'table_uiprefs',
1887 'pma__tracking' => 'tracking',
1888 'pma__userconfig' => 'userconfig',
1889 'pma__users' => 'users',
1890 'pma__usergroups' => 'usergroups',
1891 'pma__navigationhiding' => 'navigationhiding',
1892 'pma__savedsearches' => 'savedsearches',
1893 'pma__central_columns' => 'central_columns'
1896 $existingTables = $GLOBALS['dbi']->getTables($db, $GLOBALS['controllink']);
1898 $createQueries = null;
1899 $foundOne = false;
1900 foreach ($tablesToFeatures as $table => $feature) {
1901 if (! in_array($table, $existingTables)) {
1902 if ($create) {
1903 if ($createQueries == null) { // first create
1904 $createQueries = PMA_getDefaultPMATableNames();
1905 $GLOBALS['dbi']->selectDb($db);
1907 $GLOBALS['dbi']->tryQuery($createQueries[$table]);
1908 if ($error = $GLOBALS['dbi']->getError()) {
1909 $GLOBALS['message'] = $error;
1910 return;
1912 $GLOBALS['cfg']['Server'][$feature] = $table;
1914 } else {
1915 $foundOne = true;
1916 $GLOBALS['cfg']['Server'][$feature] = $table;
1920 if (! $foundOne) {
1921 return;
1923 $GLOBALS['cfg']['Server']['pmadb'] = $db;
1924 $_SESSION['relation'][$GLOBALS['server']] = PMA_checkRelationsParam();
1926 $cfgRelation = PMA_getRelationsParam();
1927 if ($cfgRelation['recentwork'] || $cfgRelation['favoritework']) {
1928 // Since configuration storage is updated, we need to
1929 // re-initialize the favorite and recent tables stored in the
1930 // session from the current configuration storage.
1931 include_once 'libraries/RecentFavoriteTable.class.php';
1933 if ($cfgRelation['favoritework']) {
1934 $fav_tables = PMA_RecentFavoriteTable::getInstance('favorite');
1935 $_SESSION['tmpval']['favorite_tables'][$GLOBALS['server']]
1936 = $fav_tables->getFromDb();
1939 if ($cfgRelation['recentwork']) {
1940 $recent_tables = PMA_RecentFavoriteTable::getInstance('recent');
1941 $_SESSION['tmpval']['recent_tables'][$GLOBALS['server']]
1942 = $recent_tables->getFromDb();
1945 // Reload navi panel to update the recent/favorite lists.
1946 $GLOBALS['reload'] = true;
1951 * Get Html for PMA tables fixing anchor.
1953 * @param boolean $allTables whether to create all tables
1955 * @return string Html
1957 function PMA_getHtmlFixPMATables($allTables)
1959 $retval = '';
1961 $url_query = PMA_URL_getCommon(array('db' => $GLOBALS['db']));
1962 if ($allTables) {
1963 $url_query .= '&amp;goto=db_operations.php&amp;create_pmadb=1';
1964 $message = PMA_Message::notice(
1966 '%sCreate%s the phpMyAdmin configuration storage in the '
1967 . 'current database.'
1970 } else {
1971 $url_query .= '&amp;goto=db_operations.php&amp;fix_pmadb=1';
1972 $message = PMA_Message::notice(
1973 __('%sCreate%s missing phpMyAdmin configuration storage tables.')
1976 $message->addParam(
1977 '<a href="' . $GLOBALS['cfg']['PmaAbsoluteUri']
1978 . 'chk_rel.php' . $url_query . '">',
1979 false
1981 $message->addParam('</a>', false);
1983 $retval .= $message->getDisplay();
1985 return $retval;
1989 * Gets the relations info and status, depending on the condition
1991 * @param boolean $condition whether to look for foreigners or not
1992 * @param string $db database name
1993 * @param string $table table name
1995 * @return array ($res_rel, $have_rel)
1997 function PMA_getRelationsAndStatus($condition, $db, $table)
1999 if ($condition) {
2000 // Find which tables are related with the current one and write it in
2001 // an array
2002 $res_rel = PMA_getForeigners($db, $table);
2004 if (count($res_rel) > 0) {
2005 $have_rel = true;
2006 } else {
2007 $have_rel = false;
2009 } else {
2010 $have_rel = false;
2011 $res_rel = array();
2012 } // end if
2013 return(array($res_rel, $have_rel));