Upgraded phpmyadmin to 4.0.4 (All Languages) - No modifications yet
[openemr.git] / phpmyadmin / libraries / relation.lib.php
blobefa02110ce048475d4de22a6620ec1c53c452735
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 = PMA_DBI_query(
34 $sql,
35 $GLOBALS['controllink'],
36 $options,
37 $cache_affected_rows
39 } else {
40 $result = @PMA_DBI_try_query(
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__getRelationsParam();
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['error'] = '<font color="red"><strong>'
85 . __('not OK')
86 . '</strong></font>'
87 . ' [ <a href="%s" target="documentation">'
88 . __('Documentation')
89 . '</a> ]';
91 $messages['ok'] = '<font color="green"><strong>'
92 . _pgettext('Correctly working', 'OK')
93 . '</strong></font>';
95 $messages['enabled'] = '<font color="green">' . __('Enabled') . '</font>';
96 $messages['disabled'] = '<font color="red">' . __('Disabled') . '</font>';
98 if (false === $GLOBALS['cfg']['Server']['pmadb']) {
99 $retval .= 'PMA Database ... '
100 . sprintf($messages['error'], 'pmadb')
101 . '<br />' . "\n"
102 . __('General relation features')
103 . ' <font color="green">' . __('Disabled')
104 . '</font>' . "\n";
105 } else {
106 $retval .= '<table>' . "\n";
107 $retval .= PMA_getDiagMessageForParameter(
108 'pmadb',
109 $GLOBALS['cfg']['Server']['pmadb'],
110 $messages,
111 'pmadb'
113 $retval .= PMA_getDiagMessageForParameter(
114 'relation',
115 isset($cfgRelation['relation']),
116 $messages,
117 'relation'
119 $retval .= PMA_getDiagMessageForFeature(
120 __('General relation features'),
121 'relwork',
122 $messages
124 $retval .= PMA_getDiagMessageForParameter(
125 'table_info',
126 isset($cfgRelation['table_info']),
127 $messages,
128 'table_info'
130 $retval .= PMA_getDiagMessageForFeature(
131 __('Display Features'),
132 'displaywork',
133 $messages
135 $retval .= PMA_getDiagMessageForParameter(
136 'table_coords',
137 isset($cfgRelation['table_coords']),
138 $messages,
139 'table_coords'
141 $retval .= PMA_getDiagMessageForParameter(
142 'pdf_pages',
143 isset($cfgRelation['pdf_pages']),
144 $messages,
145 'pdf_pages'
147 $retval .= PMA_getDiagMessageForFeature(
148 __('Creation of PDFs'),
149 'pdfwork',
150 $messages
152 $retval .= PMA_getDiagMessageForParameter(
153 'column_info',
154 isset($cfgRelation['column_info']),
155 $messages,
156 'column_info'
158 $retval .= PMA_getDiagMessageForFeature(
159 __('Displaying Column Comments'),
160 'commwork',
161 $messages,
162 false
164 $retval .= PMA_getDiagMessageForFeature(
165 __('Browser transformation'),
166 'mimework',
167 $messages
169 if ($cfgRelation['commwork'] && ! $cfgRelation['mimework']) {
170 $retval .= '<tr><td colspan=2 class="left">';
171 $retval .= __('Please see the documentation on how to update your column_comments table');
172 $retval .= '</td></tr>';
174 $retval .= PMA_getDiagMessageForParameter(
175 'bookmarktable',
176 isset($cfgRelation['bookmark']),
177 $messages,
178 'bookmark'
180 $retval .= PMA_getDiagMessageForFeature(
181 __('Bookmarked SQL query'),
182 'bookmarkwork',
183 $messages
185 $retval .= PMA_getDiagMessageForParameter(
186 'history',
187 isset($cfgRelation['history']),
188 $messages,
189 'history'
191 $retval .= PMA_getDiagMessageForFeature(
192 __('SQL history'),
193 'historywork',
194 $messages
196 $retval .= PMA_getDiagMessageForParameter(
197 'designer_coords',
198 isset($cfgRelation['designer_coords']),
199 $messages,
200 'designer_coords'
202 $retval .= PMA_getDiagMessageForFeature(
203 __('Designer'),
204 'designerwork',
205 $messages
207 $retval .= PMA_getDiagMessageForParameter(
208 'recent',
209 isset($cfgRelation['recent']),
210 $messages,
211 'recent'
213 $retval .= PMA_getDiagMessageForFeature(
214 __('Persistent recently used tables'),
215 'recentwork',
216 $messages
218 $retval .= PMA_getDiagMessageForParameter(
219 'table_uiprefs',
220 isset($cfgRelation['table_uiprefs']),
221 $messages,
222 'table_uiprefs'
224 $retval .= PMA_getDiagMessageForFeature(
225 __('Persistent tables\' UI preferences'),
226 'uiprefswork',
227 $messages
229 $retval .= PMA_getDiagMessageForParameter(
230 'tracking',
231 isset($cfgRelation['tracking']),
232 $messages,
233 'tracking'
235 $retval .= PMA_getDiagMessageForFeature(
236 __('Tracking'),
237 'trackingwork',
238 $messages
240 $retval .= PMA_getDiagMessageForParameter(
241 'userconfig',
242 isset($cfgRelation['userconfig']),
243 $messages,
244 'userconfig'
246 $retval .= PMA_getDiagMessageForFeature(
247 __('User preferences'),
248 'userconfigwork',
249 $messages
251 $retval .= '</table>' . "\n";
253 $retval .= '<p>' . __('Quick steps to setup advanced features:') . '</p>';
254 $retval .= '<ul>';
255 $retval .= '<li>';
256 $retval .= __(
257 'Create the needed tables with the '
258 . '<code>examples/create_tables.sql</code>.'
260 $retval .= ' ' . PMA_Util::showDocu('setup', 'linked-tables');
261 $retval .= '</li>';
262 $retval .= '<li>';
263 $retval .= __('Create a pma user and give access to these tables.');
264 $retval .= ' ' . PMA_Util::showDocu('config', 'cfg_Servers_controluser');
265 $retval .= '</li>';
266 $retval .= '<li>';
267 $retval .= __(
268 'Enable advanced features in configuration file '
269 . '(<code>config.inc.php</code>), for example by '
270 . 'starting from <code>config.sample.inc.php</code>.'
272 $retval .= ' ' . PMA_Util::showDocu('setup', 'quick-install');
273 $retval .= '</li>';
274 $retval .= '<li>';
275 $retval .= __(
276 'Re-login to phpMyAdmin to load the updated configuration file.'
278 $retval .= '</li>';
279 $retval .= '</ul>';
282 return $retval;
286 * prints out one diagnostic message for a feature
288 * @param string $feature_name feature name in a message string
289 * @param string $relation_parameter the $GLOBALS['cfgRelation'] parameter to check
290 * @param array $messages utility messages
291 * @param boolean $skip_line whether to skip a line after the message
293 * @return string
295 function PMA_getDiagMessageForFeature($feature_name,
296 $relation_parameter, $messages, $skip_line = true
298 $retval = ' <tr><td colspan=2 class="right">' . $feature_name . ': ';
299 if ($GLOBALS['cfgRelation'][$relation_parameter]) {
300 $retval .= $messages['enabled'];
301 } else {
302 $retval .= $messages['disabled'];
304 $retval .= '</td></tr>';
305 if ($skip_line) {
306 $retval .= '<tr><td>&nbsp;</td></tr>';
308 return $retval;
312 * prints out one diagnostic message for a configuration parameter
314 * @param string $parameter config parameter name to display
315 * @param boolean $relation_parameter_set whether this parameter is set
316 * @param array $messages utility messages
317 * @param string $doc_anchor anchor in documentation
319 * @return void
321 function PMA_getDiagMessageForParameter($parameter,
322 $relation_parameter_set, $messages, $doc_anchor
324 $retval = '<tr><th class="left">';
325 $retval .= '$cfg[\'Servers\'][$i][\'' . $parameter . '\'] ... ';
326 $retval .= '</th><td class="right">';
327 if ($relation_parameter_set) {
328 $retval .= $messages['ok'];
329 } else {
330 $retval .= sprintf(
331 $messages['error'],
332 PMA_Util::getDocuLink('config', 'cfg_Servers_' . $doc_anchor)
335 $retval .= '</td></tr>' . "\n";
336 return $retval;
341 * Defines the relation parameters for the current user
342 * just a copy of the functions used for relations ;-)
343 * but added some stuff to check what will work
345 * @access protected
346 * @return array the relation parameters for the current user
348 function PMA__getRelationsParam()
350 $cfgRelation = array();
351 $cfgRelation['relwork'] = false;
352 $cfgRelation['displaywork'] = false;
353 $cfgRelation['bookmarkwork']= false;
354 $cfgRelation['pdfwork'] = false;
355 $cfgRelation['commwork'] = false;
356 $cfgRelation['mimework'] = false;
357 $cfgRelation['historywork'] = false;
358 $cfgRelation['recentwork'] = false;
359 $cfgRelation['uiprefswork'] = false;
360 $cfgRelation['trackingwork'] = false;
361 $cfgRelation['designerwork'] = false;
362 $cfgRelation['userconfigwork'] = false;
363 $cfgRelation['allworks'] = false;
364 $cfgRelation['user'] = null;
365 $cfgRelation['db'] = null;
367 if ($GLOBALS['server'] == 0 || empty($GLOBALS['cfg']['Server']['pmadb'])
368 || ! PMA_DBI_select_db($GLOBALS['cfg']['Server']['pmadb'], $GLOBALS['controllink'])
370 // No server selected -> no bookmark table
371 // we return the array with the falses in it,
372 // to avoid some 'Unitialized string offset' errors later
373 $GLOBALS['cfg']['Server']['pmadb'] = false;
374 return $cfgRelation;
378 $cfgRelation['user'] = $GLOBALS['cfg']['Server']['user'];
379 $cfgRelation['db'] = $GLOBALS['cfg']['Server']['pmadb'];
381 // Now I just check if all tables that i need are present so I can for
382 // example enable relations but not pdf...
383 // I was thinking of checking if they have all required columns but I
384 // fear it might be too slow
386 $tab_query = 'SHOW TABLES FROM '
387 . PMA_Util::backquote(
388 $GLOBALS['cfg']['Server']['pmadb']
390 $tab_rs = PMA_queryAsControlUser($tab_query, false, PMA_DBI_QUERY_STORE);
392 if (! $tab_rs) {
393 // query failed ... ?
394 //$GLOBALS['cfg']['Server']['pmadb'] = false;
395 return $cfgRelation;
398 while ($curr_table = @PMA_DBI_fetch_row($tab_rs)) {
399 if ($curr_table[0] == $GLOBALS['cfg']['Server']['bookmarktable']) {
400 $cfgRelation['bookmark'] = $curr_table[0];
401 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['relation']) {
402 $cfgRelation['relation'] = $curr_table[0];
403 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_info']) {
404 $cfgRelation['table_info'] = $curr_table[0];
405 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_coords']) {
406 $cfgRelation['table_coords'] = $curr_table[0];
407 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['designer_coords']) {
408 $cfgRelation['designer_coords'] = $curr_table[0];
409 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['column_info']) {
410 $cfgRelation['column_info'] = $curr_table[0];
411 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['pdf_pages']) {
412 $cfgRelation['pdf_pages'] = $curr_table[0];
413 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['history']) {
414 $cfgRelation['history'] = $curr_table[0];
415 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['recent']) {
416 $cfgRelation['recent'] = $curr_table[0];
417 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_uiprefs']) {
418 $cfgRelation['table_uiprefs'] = $curr_table[0];
419 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['tracking']) {
420 $cfgRelation['tracking'] = $curr_table[0];
421 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['userconfig']) {
422 $cfgRelation['userconfig'] = $curr_table[0];
424 } // end while
425 PMA_DBI_free_result($tab_rs);
427 if (isset($cfgRelation['relation'])) {
428 $cfgRelation['relwork'] = true;
429 if (isset($cfgRelation['table_info'])) {
430 $cfgRelation['displaywork'] = true;
434 if (isset($cfgRelation['table_coords']) && isset($cfgRelation['pdf_pages'])) {
435 $cfgRelation['pdfwork'] = true;
438 if (isset($cfgRelation['column_info'])) {
439 $cfgRelation['commwork'] = true;
440 $cfgRelation['mimework'] = true;
443 if (isset($cfgRelation['history'])) {
444 $cfgRelation['historywork'] = true;
447 if (isset($cfgRelation['recent'])) {
448 $cfgRelation['recentwork'] = true;
451 if (isset($cfgRelation['table_uiprefs'])) {
452 $cfgRelation['uiprefswork'] = true;
455 if (isset($cfgRelation['tracking'])) {
456 $cfgRelation['trackingwork'] = true;
459 if (isset($cfgRelation['userconfig'])) {
460 $cfgRelation['userconfigwork'] = true;
463 // we do not absolutely need that the internal relations or the PDF
464 // schema feature be activated
465 if (isset($cfgRelation['designer_coords'])) {
466 $cfgRelation['designerwork'] = true;
469 if (isset($cfgRelation['bookmark'])) {
470 $cfgRelation['bookmarkwork'] = true;
473 if ($cfgRelation['relwork'] && $cfgRelation['displaywork']
474 && $cfgRelation['pdfwork'] && $cfgRelation['commwork']
475 && $cfgRelation['mimework'] && $cfgRelation['historywork']
476 && $cfgRelation['recentwork'] && $cfgRelation['uiprefswork']
477 && $cfgRelation['trackingwork'] && $cfgRelation['userconfigwork']
478 && $cfgRelation['bookmarkwork'] && $cfgRelation['designerwork']
480 $cfgRelation['allworks'] = true;
483 return $cfgRelation;
484 } // end of the 'PMA_getRelationsParam()' function
487 * Gets all Relations to foreign tables for a given table or
488 * optionally a given column in a table
490 * @param string $db the name of the db to check for
491 * @param string $table the name of the table to check for
492 * @param string $column the name of the column to check for
493 * @param string $source the source for foreign key information
495 * @return array db,table,column
497 * @access public
499 function PMA_getForeigners($db, $table, $column = '', $source = 'both')
501 $cfgRelation = PMA_getRelationsParam();
502 $foreign = array();
504 if ($cfgRelation['relwork'] && ($source == 'both' || $source == 'internal')) {
505 $rel_query = '
506 SELECT `master_field`,
507 `foreign_db`,
508 `foreign_table`,
509 `foreign_field`
510 FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['relation']) . '
511 WHERE `master_db` = \'' . PMA_Util::sqlAddSlashes($db) . '\'
512 AND `master_table` = \'' . PMA_Util::sqlAddSlashes($table) . '\' ';
513 if (strlen($column)) {
514 $rel_query .= ' AND `master_field` = \'' . PMA_Util::sqlAddSlashes($column) . '\'';
516 $foreign = PMA_DBI_fetch_result($rel_query, 'master_field', null, $GLOBALS['controllink']);
519 if (($source == 'both' || $source == 'foreign') && strlen($table)) {
521 $show_create_table_query = 'SHOW CREATE TABLE '
522 . PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table);
523 $show_create_table = PMA_DBI_fetch_value($show_create_table_query, 0, 1);
524 $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
526 foreach ($analyzed_sql[0]['foreign_keys'] as $one_key) {
527 // The analyzer may return more than one column name in the
528 // index list or the ref_index_list; if this happens,
529 // the current logic just discards the whole index; having
530 // more than one index field is currently unsupported (see FAQ 3.6)
531 if (count($one_key['index_list']) == 1) {
532 foreach ($one_key['index_list'] as $i => $field) {
533 // If a foreign key is defined in the 'internal' source (pmadb)
534 // and as a native foreign key, we won't get it twice
535 // if $source='both' because we use $field as key
537 // The parser looks for a CONSTRAINT clause just before
538 // the FOREIGN KEY clause. It finds it (as output from
539 // SHOW CREATE TABLE) in MySQL 4.0.13, but not in older
540 // versions like 3.23.58.
541 // In those cases, the FOREIGN KEY parsing will put numbers
542 // like -1, 0, 1... instead of the constraint number.
544 if (isset($one_key['constraint'])) {
545 $foreign[$field]['constraint'] = $one_key['constraint'];
548 if (isset($one_key['ref_db_name'])) {
549 $foreign[$field]['foreign_db'] = $one_key['ref_db_name'];
550 } else {
551 $foreign[$field]['foreign_db'] = $db;
553 $foreign[$field]['foreign_table'] = $one_key['ref_table_name'];
554 $foreign[$field]['foreign_field'] = $one_key['ref_index_list'][$i];
555 if (isset($one_key['on_delete'])) {
556 $foreign[$field]['on_delete'] = $one_key['on_delete'];
558 if (isset($one_key['on_update'])) {
559 $foreign[$field]['on_update'] = $one_key['on_update'];
567 * Emulating relations for some information_schema and data_dictionary tables
569 $is_information_schema = strtolower($db) == 'information_schema';
570 $is_data_dictionary = PMA_DRIZZLE && strtolower($db) == 'data_dictionary';
571 if (($is_information_schema || $is_data_dictionary) && ($source == 'internal' || $source == 'both')) {
572 if ($is_information_schema) {
573 $relations_key = 'information_schema_relations';
574 include_once './libraries/information_schema_relations.lib.php';
575 } else {
576 $relations_key = 'data_dictionary_relations';
577 include_once './libraries/data_dictionary_relations.lib.php';
579 if (isset($GLOBALS[$relations_key][$table])) {
580 foreach ($GLOBALS[$relations_key][$table] as $field => $relations) {
581 if ((! strlen($column) || $column == $field)
582 && (! isset($foreign[$field]) || ! strlen($foreign[$field]))
584 $foreign[$field] = $relations;
590 return $foreign;
591 } // end of the 'PMA_getForeigners()' function
594 * Gets the display field of a table
596 * @param string $db the name of the db to check for
597 * @param string $table the name of the table to check for
599 * @return string field name
601 * @access public
603 function PMA_getDisplayField($db, $table)
605 $cfgRelation = PMA_getRelationsParam();
608 * Try to fetch the display field from DB.
610 if ($cfgRelation['displaywork']) {
611 $disp_query = '
612 SELECT `display_field`
613 FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['table_info']) . '
614 WHERE `db_name` = \'' . PMA_Util::sqlAddSlashes($db) . '\'
615 AND `table_name` = \'' . PMA_Util::sqlAddSlashes($table) . '\'';
617 $row = PMA_DBI_fetch_single_row($disp_query, 'ASSOC', $GLOBALS['controllink']);
618 if (isset($row['display_field'])) {
619 return $row['display_field'];
624 * Emulating the display field for some information_schema tables.
626 if ($db == 'information_schema') {
627 switch ($table) {
628 case 'CHARACTER_SETS':
629 return 'DESCRIPTION';
630 case 'TABLES':
631 return 'TABLE_COMMENT';
636 * No Luck...
638 return false;
640 } // end of the 'PMA_getDisplayField()' function
643 * Gets the comments for all columns of a table or the db itself
645 * @param string $db the name of the db to check for
646 * @param string $table the name of the table to check for
648 * @return array [column_name] = comment
650 * @access public
652 function PMA_getComments($db, $table = '')
654 $comments = array();
656 if ($table != '') {
657 // MySQL native column comments
658 $columns = PMA_DBI_get_columns($db, $table, null, true);
659 if ($columns) {
660 foreach ($columns as $column) {
661 if (! empty($column['Comment'])) {
662 $comments[$column['Field']] = $column['Comment'];
666 } else {
667 $comments[] = PMA_getDbComment($db);
670 return $comments;
671 } // end of the 'PMA_getComments()' function
674 * Gets the comment for a db
676 * @param string $db the name of the db to check for
678 * @return string comment
680 * @access public
682 function PMA_getDbComment($db)
684 $cfgRelation = PMA_getRelationsParam();
685 $comment = '';
687 if ($cfgRelation['commwork']) {
688 // pmadb internal db comment
689 $com_qry = "
690 SELECT `comment`
691 FROM " . PMA_Util::backquote($cfgRelation['db']) . "." . PMA_Util::backquote($cfgRelation['column_info']) . "
692 WHERE db_name = '" . PMA_Util::sqlAddSlashes($db) . "'
693 AND table_name = ''
694 AND column_name = '(db_comment)'";
695 $com_rs = PMA_queryAsControlUser($com_qry, true, PMA_DBI_QUERY_STORE);
697 if ($com_rs && PMA_DBI_num_rows($com_rs) > 0) {
698 $row = PMA_DBI_fetch_assoc($com_rs);
699 $comment = $row['comment'];
701 PMA_DBI_free_result($com_rs);
704 return $comment;
705 } // end of the 'PMA_getDbComment()' function
708 * Gets the comment for a db
710 * @access public
712 * @return string comment
714 function PMA_getDbComments()
716 $cfgRelation = PMA_getRelationsParam();
717 $comments = array();
719 if ($cfgRelation['commwork']) {
720 // pmadb internal db comment
721 $com_qry = "
722 SELECT `db_name`, `comment`
723 FROM " . PMA_Util::backquote($cfgRelation['db']) . "." . PMA_Util::backquote($cfgRelation['column_info']) . "
724 WHERE `column_name` = '(db_comment)'";
725 $com_rs = PMA_queryAsControlUser($com_qry, true, PMA_DBI_QUERY_STORE);
727 if ($com_rs && PMA_DBI_num_rows($com_rs) > 0) {
728 while ($row = PMA_DBI_fetch_assoc($com_rs)) {
729 $comments[$row['db_name']] = $row['comment'];
732 PMA_DBI_free_result($com_rs);
735 return $comments;
736 } // end of the 'PMA_getDbComments()' function
739 * Set a database comment to a certain value.
741 * @param string $db the name of the db
742 * @param string $comment the value of the column
744 * @return boolean true, if comment-query was made.
746 * @access public
748 function PMA_setDbComment($db, $comment = '')
750 $cfgRelation = PMA_getRelationsParam();
752 if (! $cfgRelation['commwork']) {
753 return false;
756 if (strlen($comment)) {
757 $upd_query = "
758 INSERT INTO
759 " . PMA_Util::backquote($cfgRelation['db']) . "." . PMA_Util::backquote($cfgRelation['column_info']) . "
760 (`db_name`, `table_name`, `column_name`, `comment`)
761 VALUES (
762 '" . PMA_Util::sqlAddSlashes($db) . "',
764 '(db_comment)',
765 '" . PMA_Util::sqlAddSlashes($comment) . "')
766 ON DUPLICATE KEY UPDATE
767 `comment` = '" . PMA_Util::sqlAddSlashes($comment) . "'";
768 } else {
769 $upd_query = '
770 DELETE FROM
771 ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['column_info']) . '
772 WHERE `db_name` = \'' . PMA_Util::sqlAddSlashes($db) . '\'
773 AND `table_name` = \'\'
774 AND `column_name` = \'(db_comment)\'';
777 if (isset($upd_query)) {
778 return PMA_queryAsControlUser($upd_query);
781 return false;
782 } // end of 'PMA_setDbComment()' function
785 * Set a SQL history entry
787 * @param string $db the name of the db
788 * @param string $table the name of the table
789 * @param string $username the username
790 * @param string $sqlquery the sql query
792 * @return void
794 * @access public
796 function PMA_setHistory($db, $table, $username, $sqlquery)
798 // Prevent to run this automatically on Footer class destroying in testsuite
799 if (defined('TESTSUITE') || strlen($sqlquery) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
800 return;
803 $cfgRelation = PMA_getRelationsParam();
805 if (! isset($_SESSION['sql_history'])) {
806 $_SESSION['sql_history'] = array();
809 $key = md5($sqlquery . $db . $table);
811 if (isset($_SESSION['sql_history'][$key])) {
812 unset($_SESSION['sql_history'][$key]);
815 $_SESSION['sql_history'][$key] = array(
816 'db' => $db,
817 'table' => $table,
818 'sqlquery' => $sqlquery,
821 if (count($_SESSION['sql_history']) > $GLOBALS['cfg']['QueryHistoryMax']) {
822 // history should not exceed a maximum count
823 array_shift($_SESSION['sql_history']);
826 if (! $cfgRelation['historywork'] || ! $GLOBALS['cfg']['QueryHistoryDB']) {
827 return;
830 PMA_queryAsControlUser(
831 'INSERT INTO
832 ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['history']) . '
833 (`username`,
834 `db`,
835 `table`,
836 `timevalue`,
837 `sqlquery`)
838 VALUES
839 (\'' . PMA_Util::sqlAddSlashes($username) . '\',
840 \'' . PMA_Util::sqlAddSlashes($db) . '\',
841 \'' . PMA_Util::sqlAddSlashes($table) . '\',
842 NOW(),
843 \'' . PMA_Util::sqlAddSlashes($sqlquery) . '\')'
845 } // end of 'PMA_setHistory()' function
848 * Gets a SQL history entry
850 * @param string $username the username
852 * @return array list of history items
854 * @access public
856 function PMA_getHistory($username)
858 $cfgRelation = PMA_getRelationsParam();
860 if (! $cfgRelation['historywork']) {
861 return false;
864 $hist_query = '
865 SELECT `db`,
866 `table`,
867 `sqlquery`
868 FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['history']) . '
869 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
870 ORDER BY `id` DESC';
872 return PMA_DBI_fetch_result($hist_query, null, null, $GLOBALS['controllink']);
873 } // end of 'PMA_getHistory()' function
876 * purges SQL history
878 * deletes entries that exceeds $cfg['QueryHistoryMax'], oldest first, for the
879 * given user
881 * @param string $username the username
883 * @return void
885 * @access public
887 function PMA_purgeHistory($username)
889 $cfgRelation = PMA_getRelationsParam();
890 if (! $GLOBALS['cfg']['QueryHistoryDB'] || ! $cfgRelation['historywork']) {
891 return;
894 if (! $cfgRelation['historywork']) {
895 return;
898 $search_query = '
899 SELECT `timevalue`
900 FROM ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['history']) . '
901 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
902 ORDER BY `timevalue` DESC
903 LIMIT ' . $GLOBALS['cfg']['QueryHistoryMax'] . ', 1';
905 if ($max_time = PMA_DBI_fetch_value($search_query, 0, 0, $GLOBALS['controllink'])) {
906 PMA_queryAsControlUser(
907 'DELETE FROM
908 ' . PMA_Util::backquote($cfgRelation['db']) . '.' . PMA_Util::backquote($cfgRelation['history']) . '
909 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
910 AND `timevalue` <= \'' . $max_time . '\''
913 } // end of 'PMA_purgeHistory()' function
916 * Prepares the dropdown for one mode
918 * @param array $foreign the keys and values for foreigns
919 * @param string $data the current data of the dropdown
920 * @param string $mode the needed mode
922 * @return array the <option value=""><option>s
924 * @access protected
926 function PMA__foreignDropdownBuild($foreign, $data, $mode)
928 $reloptions = array();
930 // id-only is a special mode used when no foreign display column
931 // is available
932 if ($mode == 'id-content' || $mode == 'id-only') {
933 // sort for id-content
934 if ($GLOBALS['cfg']['NaturalOrder']) {
935 uksort($foreign, 'strnatcasecmp');
936 } else {
937 ksort($foreign);
939 } elseif ($mode == 'content-id') {
940 // sort for content-id
941 if ($GLOBALS['cfg']['NaturalOrder']) {
942 natcasesort($foreign);
943 } else {
944 asort($foreign);
948 foreach ($foreign as $key => $value) {
949 if (PMA_strlen($value) <= $GLOBALS['cfg']['LimitChars']) {
950 $vtitle = '';
951 $value = htmlspecialchars($value);
952 } else {
953 $vtitle = htmlspecialchars($value);
954 $value = htmlspecialchars(substr($value, 0, $GLOBALS['cfg']['LimitChars']) . '...');
957 $reloption = '<option value="' . htmlspecialchars($key) . '"';
958 if ($vtitle != '') {
959 $reloption .= ' title="' . $vtitle . '"';
962 if ((string) $key == (string) $data) {
963 $reloption .= ' selected="selected"';
966 if ($mode == 'content-id') {
967 $reloptions[] = $reloption . '>' . $value . '&nbsp;-&nbsp;' . htmlspecialchars($key) . '</option>';
968 } elseif ($mode == 'id-content') {
969 $reloptions[] = $reloption . '>' . htmlspecialchars($key) . '&nbsp;-&nbsp;' . $value . '</option>';
970 } elseif ($mode == 'id-only') {
971 $reloptions[] = $reloption . '>' . htmlspecialchars($key) . '</option>';
973 } // end foreach
975 return $reloptions;
976 } // end of 'PMA__foreignDropdownBuild' function
979 * Outputs dropdown with values of foreign fields
981 * @param array $disp_row array of the displayed row
982 * @param string $foreign_field the foreign field
983 * @param string $foreign_display the foreign field to display
984 * @param string $data the current data of the dropdown (field in row)
985 * @param int $max maximum number of items in the dropdown
987 * @return string the <option value=""><option>s
989 * @access public
991 function PMA_foreignDropdown($disp_row, $foreign_field, $foreign_display, $data,
992 $max = null
994 if (null === $max) {
995 $max = $GLOBALS['cfg']['ForeignKeyMaxLimit'];
998 $foreign = array();
1000 // collect the data
1001 foreach ($disp_row as $relrow) {
1002 $key = $relrow[$foreign_field];
1004 // if the display field has been defined for this foreign table
1005 if ($foreign_display) {
1006 $value = $relrow[$foreign_display];
1007 } else {
1008 $value = '';
1009 } // end if ($foreign_display)
1011 $foreign[$key] = $value;
1012 } // end foreach
1014 // put the dropdown sections in correct order
1015 $top = array();
1016 $bottom = array();
1017 if ($foreign_display) {
1018 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'], 'array')) {
1019 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][0])) {
1020 $top = PMA__foreignDropdownBuild(
1021 $foreign,
1022 $data,
1023 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][0]
1026 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][1])) {
1027 $bottom = PMA__foreignDropdownBuild(
1028 $foreign,
1029 $data,
1030 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][1]
1033 } else {
1034 $top = PMA__foreignDropdownBuild($foreign, $data, 'id-content');
1035 $bottom = PMA__foreignDropdownBuild($foreign, $data, 'content-id');
1037 } else {
1038 $top = PMA__foreignDropdownBuild($foreign, $data, 'id-only');
1041 // beginning of dropdown
1042 $ret = '<option value="">&nbsp;</option>';
1043 $top_count = count($top);
1044 if ($max == -1 || $top_count < $max) {
1045 $ret .= implode('', $top);
1046 if ($foreign_display && $top_count > 0) {
1047 // this empty option is to visually mark the beginning of the
1048 // second series of values (bottom)
1049 $ret .= '<option value="">&nbsp;</option>';
1052 if ($foreign_display) {
1053 $ret .= implode('', $bottom);
1056 return $ret;
1057 } // end of 'PMA_foreignDropdown()' function
1060 * Gets foreign keys in preparation for a drop-down selector
1062 * @param array $foreigners array of the foreign keys
1063 * @param string $field the foreign field name
1064 * @param bool $override_total whether to override the total
1065 * @param string $foreign_filter a possible filter
1066 * @param string $foreign_limit a possible LIMIT clause
1068 * @return array data about the foreign keys
1070 * @access public
1073 function PMA_getForeignData($foreigners, $field, $override_total, $foreign_filter, $foreign_limit)
1075 // we always show the foreign field in the drop-down; if a display
1076 // field is defined, we show it besides the foreign field
1077 $foreign_link = false;
1078 if ($foreigners && isset($foreigners[$field])) {
1079 $foreigner = $foreigners[$field];
1080 $foreign_db = $foreigner['foreign_db'];
1081 $foreign_table = $foreigner['foreign_table'];
1082 $foreign_field = $foreigner['foreign_field'];
1084 // Count number of rows in the foreign table. Currently we do
1085 // not use a drop-down if more than ForeignKeyMaxLimit rows in the
1086 // foreign table,
1087 // for speed reasons and because we need a better interface for this.
1089 // We could also do the SELECT anyway, with a LIMIT, and ensure that
1090 // the current value of the field is one of the choices.
1092 $the_total = PMA_Table::countRecords($foreign_db, $foreign_table, true);
1094 if ($override_total == true || $the_total < $GLOBALS['cfg']['ForeignKeyMaxLimit']) {
1095 // foreign_display can be false if no display field defined:
1096 $foreign_display = PMA_getDisplayField($foreign_db, $foreign_table);
1098 $f_query_main = 'SELECT ' . PMA_Util::backquote($foreign_field)
1099 . (($foreign_display == false) ? '' : ', ' . PMA_Util::backquote($foreign_display));
1100 $f_query_from = ' FROM ' . PMA_Util::backquote($foreign_db) . '.' . PMA_Util::backquote($foreign_table);
1101 $f_query_filter = empty($foreign_filter) ? '' : ' WHERE ' . PMA_Util::backquote($foreign_field)
1102 . ' LIKE "%' . PMA_Util::sqlAddSlashes($foreign_filter, true) . '%"'
1103 . (($foreign_display == false) ? '' : ' OR ' . PMA_Util::backquote($foreign_display)
1104 . ' LIKE "%' . PMA_Util::sqlAddSlashes($foreign_filter, true) . '%"'
1106 $f_query_order = ($foreign_display == false) ? '' :' ORDER BY ' . PMA_Util::backquote($foreign_table) . '.' . PMA_Util::backquote($foreign_display);
1107 $f_query_limit = isset($foreign_limit) ? $foreign_limit : '';
1109 if (!empty($foreign_filter)) {
1110 $res = PMA_DBI_query('SELECT COUNT(*)' . $f_query_from . $f_query_filter);
1111 if ($res) {
1112 $the_total = PMA_DBI_fetch_value($res);
1113 @PMA_DBI_free_result($res);
1114 } else {
1115 $the_total = 0;
1119 $disp = PMA_DBI_query($f_query_main . $f_query_from . $f_query_filter . $f_query_order . $f_query_limit);
1120 if ($disp && PMA_DBI_num_rows($disp) > 0) {
1121 // If a resultset has been created, pre-cache it in the $disp_row array
1122 // This helps us from not needing to use mysql_data_seek by accessing a pre-cached
1123 // PHP array. Usually those resultsets are not that big, so a performance hit should
1124 // not be expected.
1125 $disp_row = array();
1126 while ($single_disp_row = @PMA_DBI_fetch_assoc($disp)) {
1127 $disp_row[] = $single_disp_row;
1129 @PMA_DBI_free_result($disp);
1131 } else {
1132 $disp_row = null;
1133 $foreign_link = true;
1135 } // end if $foreigners
1137 $foreignData['foreign_link'] = $foreign_link;
1138 $foreignData['the_total'] = isset($the_total) ? $the_total : null;
1139 $foreignData['foreign_display'] = isset($foreign_display) ? $foreign_display : null;
1140 $foreignData['disp_row'] = isset($disp_row) ? $disp_row : null;
1141 $foreignData['foreign_field'] = isset($foreign_field) ? $foreign_field : null;
1142 return $foreignData;
1143 } // end of 'PMA_getForeignData()' function
1146 * Finds all related tables
1148 * @param array $all_tables All the involved tables
1149 * @param string $master The master table to form the LEFT JOIN clause
1151 * @return string LEFT JOIN
1152 * @access private
1154 function PMA_getRelatives($all_tables, $master)
1156 $fromclause = '';
1157 $emerg = '';
1159 // The list of tables that we still couldn't connect
1160 $remaining_tables = $all_tables;
1161 unset($remaining_tables[$master]);
1162 // The list of allready connected tables
1163 $known_tables[$master] = $master;
1164 $run = 0;
1165 while (count($remaining_tables) > 0) {
1166 // Whether to go from master to foreign or vice versa
1167 if ($run % 2 == 0) {
1168 $from = 'master';
1169 $to = 'foreign';
1170 } else {
1171 $from = 'foreign';
1172 $to = 'master';
1174 $in_know = '(\'' . implode('\', \'', $known_tables) . '\')';
1175 $in_left = '(\'' . implode('\', \'', $remaining_tables) . '\')';
1176 $rel_query = 'SELECT *'
1177 . ' FROM ' . PMA_Util::backquote($GLOBALS['cfgRelation']['db'])
1178 . '.' . PMA_Util::backquote($GLOBALS['cfgRelation']['relation'])
1179 . ' WHERE ' . $from . '_db = \'' . PMA_Util::sqlAddSlashes($GLOBALS['db']) . '\''
1180 . ' AND ' . $to . '_db = \'' . PMA_Util::sqlAddSlashes($GLOBALS['db']) . '\''
1181 . ' AND ' . $from . '_table IN ' . $in_know
1182 . ' AND ' . $to . '_table IN ' . $in_left;
1183 $relations = @PMA_DBI_query($rel_query, $GLOBALS['controllink']);
1184 while ($row = PMA_DBI_fetch_assoc($relations)) {
1185 $found_table = $row[$to . '_table'];
1186 if (isset($remaining_tables[$found_table])) {
1187 $fromclause
1188 .= "\n" . ' LEFT JOIN '
1189 . PMA_Util::backquote($GLOBALS['db']) . '.' . PMA_Util::backquote($row[$to . '_table']) . ' ON '
1190 . PMA_Util::backquote($row[$from . '_table']) . '.'
1191 . PMA_Util::backquote($row[$from . '_field']) . ' = '
1192 . PMA_Util::backquote($row[$to . '_table']) . '.'
1193 . PMA_Util::backquote($row[$to . '_field']) . ' ';
1194 $known_tables[$found_table] = $found_table;
1195 unset($remaining_tables[$found_table]);
1197 } // end while
1198 $run++;
1199 if ($run > 5) {
1200 foreach ($remaining_tables as $table) {
1201 $emerg .= ', ' . PMA_Util::backquote($table);
1202 unset($remaining_tables[$table]);
1205 } // end while
1206 $fromclause = $emerg . $fromclause;
1207 return $fromclause;
1208 } // end of the "PMA_getRelatives()" function
1211 * Rename a field in relation tables
1213 * usually called after a column in a table was renamed
1215 * @param string $db databse name
1216 * @param string $table table name
1217 * @param string $field old field name
1218 * @param string $new_name new field name
1220 * @return void
1222 function PMA_REL_renameField($db, $table, $field, $new_name)
1224 $cfgRelation = PMA_getRelationsParam();
1226 if ($cfgRelation['displaywork']) {
1227 $table_query = 'UPDATE '
1228 . PMA_Util::backquote($cfgRelation['db']) . '.'
1229 . PMA_Util::backquote($cfgRelation['table_info'])
1230 . ' SET display_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1231 . ' WHERE db_name = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1232 . ' AND table_name = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1233 . ' AND display_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1234 PMA_queryAsControlUser($table_query);
1237 if ($cfgRelation['relwork']) {
1238 $table_query = 'UPDATE '
1239 . PMA_Util::backquote($cfgRelation['db']) . '.'
1240 . PMA_Util::backquote($cfgRelation['relation'])
1241 . ' SET master_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1242 . ' WHERE master_db = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1243 . ' AND master_table = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1244 . ' AND master_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1245 PMA_queryAsControlUser($table_query);
1247 $table_query = 'UPDATE '
1248 . PMA_Util::backquote($cfgRelation['db']) . '.'
1249 . PMA_Util::backquote($cfgRelation['relation'])
1250 . ' SET foreign_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1251 . ' WHERE foreign_db = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1252 . ' AND foreign_table = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1253 . ' AND foreign_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1254 PMA_queryAsControlUser($table_query);
1256 } // end if relwork
1261 * Performs SQL query used for renaming table.
1263 * @param string $table Relation table to use
1264 * @param string $source_db Source database name
1265 * @param string $target_db Target database name
1266 * @param string $source_table Source table name
1267 * @param string $target_table Target table name
1268 * @param string $db_field Name of database field
1269 * @param string $table_field Name of table field
1271 * @return nothing.
1273 function PMA_REL_renameSingleTable($table,
1274 $source_db, $target_db,
1275 $source_table, $target_table,
1276 $db_field, $table_field
1278 $query = 'UPDATE '
1279 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
1280 . PMA_Util::backquote($GLOBALS['cfgRelation'][$table])
1281 . ' SET ' . $db_field . ' = \'' . PMA_Util::sqlAddSlashes($target_db) . '\', '
1282 . ' ' . $table_field . ' = \'' . PMA_Util::sqlAddSlashes($target_table) . '\''
1283 . ' WHERE '
1284 . $db_field . ' = \'' . PMA_Util::sqlAddSlashes($source_db) . '\''
1285 . ' AND '
1286 . $table_field . ' = \'' . PMA_Util::sqlAddSlashes($source_table) . '\'';
1287 PMA_queryAsControlUser($query);
1292 * Rename a table in relation tables
1294 * usually called after table has been moved
1296 * @param string $source_db Source database name
1297 * @param string $target_db Target database name
1298 * @param string $source_table Source table name
1299 * @param string $target_table Target table name
1301 * @return nothing
1303 function PMA_REL_renameTable($source_db, $target_db, $source_table, $target_table)
1305 // Move old entries from PMA-DBs to new table
1306 if ($GLOBALS['cfgRelation']['commwork']) {
1307 PMA_REL_renameSingleTable(
1308 'column_info',
1309 $source_db, $target_db,
1310 $source_table, $target_table,
1311 'db_name', 'table_name'
1315 // updating bookmarks is not possible since only a single table is
1316 // moved, and not the whole DB.
1318 if ($GLOBALS['cfgRelation']['displaywork']) {
1319 PMA_REL_renameSingleTable(
1320 'table_info',
1321 $source_db, $target_db,
1322 $source_table, $target_table,
1323 'db_name', 'table_name'
1327 if ($GLOBALS['cfgRelation']['relwork']) {
1328 PMA_REL_renameSingleTable(
1329 'relation',
1330 $source_db, $target_db,
1331 $source_table, $target_table,
1332 'foreign_db', 'foreign_table'
1335 PMA_REL_renameSingleTable(
1336 'relation',
1337 $source_db, $target_db,
1338 $source_table, $target_table,
1339 'master_db', 'master_table'
1344 * @todo Can't get moving PDFs the right way. The page numbers
1345 * always get screwed up independently from duplication because the
1346 * numbers do not seem to be stored on a per-database basis. Would
1347 * the author of pdf support please have a look at it?
1350 if ($GLOBALS['cfgRelation']['pdfwork']) {
1351 PMA_REL_renameSingleTable(
1352 'table_coords',
1353 $source_db, $target_db,
1354 $source_table, $target_table,
1355 'db_name', 'table_name'
1359 if ($GLOBALS['cfgRelation']['designerwork']) {
1360 PMA_REL_renameSingleTable(
1361 'designer_coords',
1362 $source_db, $target_db,
1363 $source_table, $target_table,
1364 'db_name', 'table_name'
1370 * Create a PDF page
1372 * @param string $newpage name of the new PDF page
1373 * @param array $cfgRelation Relation configuration
1374 * @param string $db database name
1376 * @return string $pdf_page_number
1378 function PMA_REL_createPage($newpage, $cfgRelation, $db)
1380 if (! isset($newpage) || $newpage == '') {
1381 $newpage = __('no description');
1383 $ins_query = 'INSERT INTO '
1384 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
1385 . PMA_Util::backquote($cfgRelation['pdf_pages'])
1386 . ' (db_name, page_descr)'
1387 . ' VALUES (\''
1388 . PMA_Util::sqlAddSlashes($db) . '\', \''
1389 . PMA_Util::sqlAddSlashes($newpage) . '\')';
1390 PMA_queryAsControlUser($ins_query, false);
1392 return PMA_DBI_insert_id(
1393 isset($GLOBALS['controllink']) ? $GLOBALS['controllink'] : ''