Merge pull request #431 from xmujay/0609_monitor
[phpmyadmin/aamir.git] / libraries / relation.lib.php
blobdd6054d8858df7927e058790383f47856609706f
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['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_checkRelationsParam()
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
368 || empty($GLOBALS['cfg']['Server']['pmadb'])
369 || ! $GLOBALS['dbi']->selectDb($GLOBALS['cfg']['Server']['pmadb'], $GLOBALS['controllink'])
371 // No server selected -> no bookmark table
372 // we return the array with the falses in it,
373 // to avoid some 'Unitialized string offset' errors later
374 $GLOBALS['cfg']['Server']['pmadb'] = false;
375 return $cfgRelation;
379 $cfgRelation['user'] = $GLOBALS['cfg']['Server']['user'];
380 $cfgRelation['db'] = $GLOBALS['cfg']['Server']['pmadb'];
382 // Now I just check if all tables that i need are present so I can for
383 // example enable relations but not pdf...
384 // I was thinking of checking if they have all required columns but I
385 // fear it might be too slow
387 $tab_query = 'SHOW TABLES FROM '
388 . PMA_Util::backquote(
389 $GLOBALS['cfg']['Server']['pmadb']
391 $tab_rs = PMA_queryAsControlUser(
392 $tab_query, false, PMA_DatabaseInterface::QUERY_STORE
395 if (! $tab_rs) {
396 // query failed ... ?
397 //$GLOBALS['cfg']['Server']['pmadb'] = false;
398 return $cfgRelation;
401 while ($curr_table = @$GLOBALS['dbi']->fetchRow($tab_rs)) {
402 if ($curr_table[0] == $GLOBALS['cfg']['Server']['bookmarktable']) {
403 $cfgRelation['bookmark'] = $curr_table[0];
404 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['relation']) {
405 $cfgRelation['relation'] = $curr_table[0];
406 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_info']) {
407 $cfgRelation['table_info'] = $curr_table[0];
408 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_coords']) {
409 $cfgRelation['table_coords'] = $curr_table[0];
410 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['designer_coords']) {
411 $cfgRelation['designer_coords'] = $curr_table[0];
412 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['column_info']) {
413 $cfgRelation['column_info'] = $curr_table[0];
414 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['pdf_pages']) {
415 $cfgRelation['pdf_pages'] = $curr_table[0];
416 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['history']) {
417 $cfgRelation['history'] = $curr_table[0];
418 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['recent']) {
419 $cfgRelation['recent'] = $curr_table[0];
420 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_uiprefs']) {
421 $cfgRelation['table_uiprefs'] = $curr_table[0];
422 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['tracking']) {
423 $cfgRelation['tracking'] = $curr_table[0];
424 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['userconfig']) {
425 $cfgRelation['userconfig'] = $curr_table[0];
427 } // end while
428 $GLOBALS['dbi']->freeResult($tab_rs);
430 if (isset($cfgRelation['relation'])) {
431 $cfgRelation['relwork'] = true;
432 if (isset($cfgRelation['table_info'])) {
433 $cfgRelation['displaywork'] = true;
437 if (isset($cfgRelation['table_coords']) && isset($cfgRelation['pdf_pages'])) {
438 $cfgRelation['pdfwork'] = true;
441 if (isset($cfgRelation['column_info'])) {
442 $cfgRelation['commwork'] = true;
443 $cfgRelation['mimework'] = true;
446 if (isset($cfgRelation['history'])) {
447 $cfgRelation['historywork'] = true;
450 if (isset($cfgRelation['recent'])) {
451 $cfgRelation['recentwork'] = true;
454 if (isset($cfgRelation['table_uiprefs'])) {
455 $cfgRelation['uiprefswork'] = true;
458 if (isset($cfgRelation['tracking'])) {
459 $cfgRelation['trackingwork'] = true;
462 if (isset($cfgRelation['userconfig'])) {
463 $cfgRelation['userconfigwork'] = true;
466 // we do not absolutely need that the internal relations or the PDF
467 // schema feature be activated
468 if (isset($cfgRelation['designer_coords'])) {
469 $cfgRelation['designerwork'] = true;
472 if (isset($cfgRelation['bookmark'])) {
473 $cfgRelation['bookmarkwork'] = true;
476 if ($cfgRelation['relwork'] && $cfgRelation['displaywork']
477 && $cfgRelation['pdfwork'] && $cfgRelation['commwork']
478 && $cfgRelation['mimework'] && $cfgRelation['historywork']
479 && $cfgRelation['recentwork'] && $cfgRelation['uiprefswork']
480 && $cfgRelation['trackingwork'] && $cfgRelation['userconfigwork']
481 && $cfgRelation['bookmarkwork'] && $cfgRelation['designerwork']
483 $cfgRelation['allworks'] = true;
486 return $cfgRelation;
487 } // end of the 'PMA_getRelationsParam()' function
490 * Gets all Relations to foreign tables for a given table or
491 * optionally a given column in a table
493 * @param string $db the name of the db to check for
494 * @param string $table the name of the table to check for
495 * @param string $column the name of the column to check for
496 * @param string $source the source for foreign key information
498 * @return array db,table,column
500 * @access public
502 function PMA_getForeigners($db, $table, $column = '', $source = 'both')
504 $cfgRelation = PMA_getRelationsParam();
505 $foreign = array();
507 if ($cfgRelation['relwork'] && ($source == 'both' || $source == 'internal')) {
508 $rel_query = '
509 SELECT `master_field`,
510 `foreign_db`,
511 `foreign_table`,
512 `foreign_field`
513 FROM ' . PMA_Util::backquote($cfgRelation['db'])
514 . '.' . PMA_Util::backquote($cfgRelation['relation']) . '
515 WHERE `master_db` = \'' . PMA_Util::sqlAddSlashes($db) . '\'
516 AND `master_table` = \'' . PMA_Util::sqlAddSlashes($table) . '\' ';
517 if (strlen($column)) {
518 $rel_query .= ' AND `master_field` = '
519 . '\'' . PMA_Util::sqlAddSlashes($column) . '\'';
521 $foreign = $GLOBALS['dbi']->fetchResult(
522 $rel_query, 'master_field', null, $GLOBALS['controllink']
526 if (($source == 'both' || $source == 'foreign') && strlen($table)) {
528 $show_create_table_query = 'SHOW CREATE TABLE '
529 . PMA_Util::backquote($db) . '.' . PMA_Util::backquote($table);
530 $show_create_table = $GLOBALS['dbi']->fetchValue($show_create_table_query, 0, 1);
531 $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
533 foreach ($analyzed_sql[0]['foreign_keys'] as $one_key) {
534 // The analyzer may return more than one column name in the
535 // index list or the ref_index_list; if this happens,
536 // the current logic just discards the whole index; having
537 // more than one index field is currently unsupported (see FAQ 3.6)
538 if (count($one_key['index_list']) == 1) {
539 foreach ($one_key['index_list'] as $i => $field) {
540 // If a foreign key is defined in the 'internal' source (pmadb)
541 // and as a native foreign key, we won't get it twice
542 // if $source='both' because we use $field as key
544 // The parser looks for a CONSTRAINT clause just before
545 // the FOREIGN KEY clause. It finds it (as output from
546 // SHOW CREATE TABLE) in MySQL 4.0.13, but not in older
547 // versions like 3.23.58.
548 // In those cases, the FOREIGN KEY parsing will put numbers
549 // like -1, 0, 1... instead of the constraint number.
551 if (isset($one_key['constraint'])) {
552 $foreign[$field]['constraint'] = $one_key['constraint'];
555 if (isset($one_key['ref_db_name'])) {
556 $foreign[$field]['foreign_db'] = $one_key['ref_db_name'];
557 } else {
558 $foreign[$field]['foreign_db'] = $db;
560 $foreign[$field]['foreign_table'] = $one_key['ref_table_name'];
561 $foreign[$field]['foreign_field'] = $one_key['ref_index_list'][$i];
562 if (isset($one_key['on_delete'])) {
563 $foreign[$field]['on_delete'] = $one_key['on_delete'];
565 if (isset($one_key['on_update'])) {
566 $foreign[$field]['on_update'] = $one_key['on_update'];
574 * Emulating relations for some information_schema and data_dictionary tables
576 $is_information_schema = strtolower($db) == 'information_schema';
577 $is_data_dictionary = PMA_DRIZZLE && strtolower($db) == 'data_dictionary';
578 if (($is_information_schema || $is_data_dictionary)
579 && ($source == 'internal' || $source == 'both')
581 if ($is_information_schema) {
582 $relations_key = 'information_schema_relations';
583 include_once './libraries/information_schema_relations.lib.php';
584 } else {
585 $relations_key = 'data_dictionary_relations';
586 include_once './libraries/data_dictionary_relations.lib.php';
588 if (isset($GLOBALS[$relations_key][$table])) {
589 foreach ($GLOBALS[$relations_key][$table] as $field => $relations) {
590 if ((! strlen($column) || $column == $field)
591 && (! isset($foreign[$field]) || ! strlen($foreign[$field]))
593 $foreign[$field] = $relations;
599 return $foreign;
600 } // end of the 'PMA_getForeigners()' function
603 * Gets the display field of a table
605 * @param string $db the name of the db to check for
606 * @param string $table the name of the table to check for
608 * @return string field name
610 * @access public
612 function PMA_getDisplayField($db, $table)
614 $cfgRelation = PMA_getRelationsParam();
617 * Try to fetch the display field from DB.
619 if ($cfgRelation['displaywork']) {
620 $disp_query = '
621 SELECT `display_field`
622 FROM ' . PMA_Util::backquote($cfgRelation['db'])
623 . '.' . PMA_Util::backquote($cfgRelation['table_info']) . '
624 WHERE `db_name` = \'' . PMA_Util::sqlAddSlashes($db) . '\'
625 AND `table_name` = \'' . PMA_Util::sqlAddSlashes($table) . '\'';
627 $row = $GLOBALS['dbi']->fetchSingleRow(
628 $disp_query, 'ASSOC', $GLOBALS['controllink']
630 if (isset($row['display_field'])) {
631 return $row['display_field'];
636 * Emulating the display field for some information_schema tables.
638 if ($db == 'information_schema') {
639 switch ($table) {
640 case 'CHARACTER_SETS':
641 return 'DESCRIPTION';
642 case 'TABLES':
643 return 'TABLE_COMMENT';
648 * No Luck...
650 return false;
652 } // end of the 'PMA_getDisplayField()' function
655 * Gets the comments for all columns of a table or the db itself
657 * @param string $db the name of the db to check for
658 * @param string $table the name of the table to check for
660 * @return array [column_name] = comment
662 * @access public
664 function PMA_getComments($db, $table = '')
666 $comments = array();
668 if ($table != '') {
669 // MySQL native column comments
670 $columns = $GLOBALS['dbi']->getColumns($db, $table, null, true);
671 if ($columns) {
672 foreach ($columns as $column) {
673 if (! empty($column['Comment'])) {
674 $comments[$column['Field']] = $column['Comment'];
678 } else {
679 $comments[] = PMA_getDbComment($db);
682 return $comments;
683 } // end of the 'PMA_getComments()' function
686 * Gets the comment for a db
688 * @param string $db the name of the db to check for
690 * @return string comment
692 * @access public
694 function PMA_getDbComment($db)
696 $cfgRelation = PMA_getRelationsParam();
697 $comment = '';
699 if ($cfgRelation['commwork']) {
700 // pmadb internal db comment
701 $com_qry = "
702 SELECT `comment`
703 FROM " . PMA_Util::backquote($cfgRelation['db'])
704 . "." . PMA_Util::backquote($cfgRelation['column_info']) . "
705 WHERE db_name = '" . PMA_Util::sqlAddSlashes($db) . "'
706 AND table_name = ''
707 AND column_name = '(db_comment)'";
708 $com_rs = PMA_queryAsControlUser(
709 $com_qry, true, PMA_DatabaseInterface::QUERY_STORE
712 if ($com_rs && $GLOBALS['dbi']->numRows($com_rs) > 0) {
713 $row = $GLOBALS['dbi']->fetchAssoc($com_rs);
714 $comment = $row['comment'];
716 $GLOBALS['dbi']->freeResult($com_rs);
719 return $comment;
720 } // end of the 'PMA_getDbComment()' function
723 * Gets the comment for a db
725 * @access public
727 * @return string comment
729 function PMA_getDbComments()
731 $cfgRelation = PMA_getRelationsParam();
732 $comments = array();
734 if ($cfgRelation['commwork']) {
735 // pmadb internal db comment
736 $com_qry = "
737 SELECT `db_name`, `comment`
738 FROM " . PMA_Util::backquote($cfgRelation['db'])
739 . "." . PMA_Util::backquote($cfgRelation['column_info']) . "
740 WHERE `column_name` = '(db_comment)'";
741 $com_rs = PMA_queryAsControlUser(
742 $com_qry, true, PMA_DatabaseInterface::QUERY_STORE
745 if ($com_rs && $GLOBALS['dbi']->numRows($com_rs) > 0) {
746 while ($row = $GLOBALS['dbi']->fetchAssoc($com_rs)) {
747 $comments[$row['db_name']] = $row['comment'];
750 $GLOBALS['dbi']->freeResult($com_rs);
753 return $comments;
754 } // end of the 'PMA_getDbComments()' function
757 * Set a database comment to a certain value.
759 * @param string $db the name of the db
760 * @param string $comment the value of the column
762 * @return boolean true, if comment-query was made.
764 * @access public
766 function PMA_setDbComment($db, $comment = '')
768 $cfgRelation = PMA_getRelationsParam();
770 if (! $cfgRelation['commwork']) {
771 return false;
774 if (strlen($comment)) {
775 $upd_query = 'INSERT INTO '
776 . PMA_Util::backquote($cfgRelation['db']) . '.'
777 . PMA_Util::backquote($cfgRelation['column_info'])
778 . ' (`db_name`, `table_name`, `column_name`, `comment`)'
779 . ' VALUES (\''
780 . PMA_Util::sqlAddSlashes($db)
781 . "', '', '(db_comment)', '"
782 . PMA_Util::sqlAddSlashes($comment)
783 . "') "
784 . ' ON DUPLICATE KEY UPDATE '
785 . "`comment` = '" . PMA_Util::sqlAddSlashes($comment) . "'";
786 } else {
787 $upd_query = 'DELETE FROM '
788 . PMA_Util::backquote($cfgRelation['db']) . '.'
789 . PMA_Util::backquote($cfgRelation['column_info'])
790 . ' WHERE `db_name` = \'' . PMA_Util::sqlAddSlashes($db) . '\'
791 AND `table_name` = \'\'
792 AND `column_name` = \'(db_comment)\'';
795 if (isset($upd_query)) {
796 return PMA_queryAsControlUser($upd_query);
799 return false;
800 } // end of 'PMA_setDbComment()' function
803 * Set a SQL history entry
805 * @param string $db the name of the db
806 * @param string $table the name of the table
807 * @param string $username the username
808 * @param string $sqlquery the sql query
810 * @return void
812 * @access public
814 function PMA_setHistory($db, $table, $username, $sqlquery)
816 // Prevent to run this automatically on Footer class destroying in testsuite
817 if (defined('TESTSUITE')
818 || strlen($sqlquery) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']
820 return;
823 $cfgRelation = PMA_getRelationsParam();
825 if (! isset($_SESSION['sql_history'])) {
826 $_SESSION['sql_history'] = array();
829 $key = md5($sqlquery . $db . $table);
831 if (isset($_SESSION['sql_history'][$key])) {
832 unset($_SESSION['sql_history'][$key]);
835 $_SESSION['sql_history'][$key] = array(
836 'db' => $db,
837 'table' => $table,
838 'sqlquery' => $sqlquery,
841 if (count($_SESSION['sql_history']) > $GLOBALS['cfg']['QueryHistoryMax']) {
842 // history should not exceed a maximum count
843 array_shift($_SESSION['sql_history']);
846 if (! $cfgRelation['historywork'] || ! $GLOBALS['cfg']['QueryHistoryDB']) {
847 return;
850 PMA_queryAsControlUser(
851 'INSERT INTO '
852 . PMA_Util::backquote($cfgRelation['db']) . '.'
853 . PMA_Util::backquote($cfgRelation['history']) . '
854 (`username`,
855 `db`,
856 `table`,
857 `timevalue`,
858 `sqlquery`)
859 VALUES
860 (\'' . PMA_Util::sqlAddSlashes($username) . '\',
861 \'' . PMA_Util::sqlAddSlashes($db) . '\',
862 \'' . PMA_Util::sqlAddSlashes($table) . '\',
863 NOW(),
864 \'' . PMA_Util::sqlAddSlashes($sqlquery) . '\')'
866 } // end of 'PMA_setHistory()' function
869 * Gets a SQL history entry
871 * @param string $username the username
873 * @return array list of history items
875 * @access public
877 function PMA_getHistory($username)
879 $cfgRelation = PMA_getRelationsParam();
881 if (! $cfgRelation['historywork']) {
882 return false;
885 $hist_query = '
886 SELECT `db`,
887 `table`,
888 `sqlquery`
889 FROM ' . PMA_Util::backquote($cfgRelation['db'])
890 . '.' . PMA_Util::backquote($cfgRelation['history']) . '
891 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
892 ORDER BY `id` DESC';
894 return $GLOBALS['dbi']->fetchResult($hist_query, null, null, $GLOBALS['controllink']);
895 } // end of 'PMA_getHistory()' function
898 * purges SQL history
900 * deletes entries that exceeds $cfg['QueryHistoryMax'], oldest first, for the
901 * given user
903 * @param string $username the username
905 * @return void
907 * @access public
909 function PMA_purgeHistory($username)
911 $cfgRelation = PMA_getRelationsParam();
912 if (! $GLOBALS['cfg']['QueryHistoryDB'] || ! $cfgRelation['historywork']) {
913 return;
916 if (! $cfgRelation['historywork']) {
917 return;
920 $search_query = '
921 SELECT `timevalue`
922 FROM ' . PMA_Util::backquote($cfgRelation['db'])
923 . '.' . PMA_Util::backquote($cfgRelation['history']) . '
924 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
925 ORDER BY `timevalue` DESC
926 LIMIT ' . $GLOBALS['cfg']['QueryHistoryMax'] . ', 1';
928 if ($max_time = $GLOBALS['dbi']->fetchValue($search_query, 0, 0, $GLOBALS['controllink'])) {
929 PMA_queryAsControlUser(
930 'DELETE FROM '
931 . PMA_Util::backquote($cfgRelation['db']) . '.'
932 . PMA_Util::backquote($cfgRelation['history']) . '
933 WHERE `username` = \'' . PMA_Util::sqlAddSlashes($username) . '\'
934 AND `timevalue` <= \'' . $max_time . '\''
937 } // end of 'PMA_purgeHistory()' function
940 * Prepares the dropdown for one mode
942 * @param array $foreign the keys and values for foreigns
943 * @param string $data the current data of the dropdown
944 * @param string $mode the needed mode
946 * @return array the <option value=""><option>s
948 * @access protected
950 function PMA_buildForeignDropdown($foreign, $data, $mode)
952 $reloptions = array();
954 // id-only is a special mode used when no foreign display column
955 // is available
956 if ($mode == 'id-content' || $mode == 'id-only') {
957 // sort for id-content
958 if ($GLOBALS['cfg']['NaturalOrder']) {
959 uksort($foreign, 'strnatcasecmp');
960 } else {
961 ksort($foreign);
963 } elseif ($mode == 'content-id') {
964 // sort for content-id
965 if ($GLOBALS['cfg']['NaturalOrder']) {
966 natcasesort($foreign);
967 } else {
968 asort($foreign);
972 foreach ($foreign as $key => $value) {
973 if (PMA_strlen($value) <= $GLOBALS['cfg']['LimitChars']) {
974 $vtitle = '';
975 $value = htmlspecialchars($value);
976 } else {
977 $vtitle = htmlspecialchars($value);
978 $value = htmlspecialchars(
979 substr($value, 0, $GLOBALS['cfg']['LimitChars']) . '...'
983 $reloption = '<option value="' . htmlspecialchars($key) . '"';
984 if ($vtitle != '') {
985 $reloption .= ' title="' . $vtitle . '"';
988 if ((string) $key == (string) $data) {
989 $reloption .= ' selected="selected"';
992 if ($mode == 'content-id') {
993 $reloptions[] = $reloption . '>'
994 . $value . '&nbsp;-&nbsp;' . htmlspecialchars($key) . '</option>';
995 } elseif ($mode == 'id-content') {
996 $reloptions[] = $reloption . '>'
997 . htmlspecialchars($key) . '&nbsp;-&nbsp;' . $value . '</option>';
998 } elseif ($mode == 'id-only') {
999 $reloptions[] = $reloption . '>'
1000 . htmlspecialchars($key) . '</option>';
1002 } // end foreach
1004 return $reloptions;
1005 } // end of 'PMA_buildForeignDropdown' function
1008 * Outputs dropdown with values of foreign fields
1010 * @param array $disp_row array of the displayed row
1011 * @param string $foreign_field the foreign field
1012 * @param string $foreign_display the foreign field to display
1013 * @param string $data the current data of the dropdown (field in row)
1014 * @param int $max maximum number of items in the dropdown
1016 * @return string the <option value=""><option>s
1018 * @access public
1020 function PMA_foreignDropdown($disp_row, $foreign_field, $foreign_display, $data,
1021 $max = null
1023 if (null === $max) {
1024 $max = $GLOBALS['cfg']['ForeignKeyMaxLimit'];
1027 $foreign = array();
1029 // collect the data
1030 foreach ($disp_row as $relrow) {
1031 $key = $relrow[$foreign_field];
1033 // if the display field has been defined for this foreign table
1034 if ($foreign_display) {
1035 $value = $relrow[$foreign_display];
1036 } else {
1037 $value = '';
1038 } // end if ($foreign_display)
1040 $foreign[$key] = $value;
1041 } // end foreach
1043 // put the dropdown sections in correct order
1044 $top = array();
1045 $bottom = array();
1046 if ($foreign_display) {
1047 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'], 'array')) {
1048 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][0])) {
1049 $top = PMA_buildForeignDropdown(
1050 $foreign,
1051 $data,
1052 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][0]
1055 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][1])) {
1056 $bottom = PMA_buildForeignDropdown(
1057 $foreign,
1058 $data,
1059 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][1]
1062 } else {
1063 $top = PMA_buildForeignDropdown($foreign, $data, 'id-content');
1064 $bottom = PMA_buildForeignDropdown($foreign, $data, 'content-id');
1066 } else {
1067 $top = PMA_buildForeignDropdown($foreign, $data, 'id-only');
1070 // beginning of dropdown
1071 $ret = '<option value="">&nbsp;</option>';
1072 $top_count = count($top);
1073 if ($max == -1 || $top_count < $max) {
1074 $ret .= implode('', $top);
1075 if ($foreign_display && $top_count > 0) {
1076 // this empty option is to visually mark the beginning of the
1077 // second series of values (bottom)
1078 $ret .= '<option value="">&nbsp;</option>';
1081 if ($foreign_display) {
1082 $ret .= implode('', $bottom);
1085 return $ret;
1086 } // end of 'PMA_foreignDropdown()' function
1089 * Gets foreign keys in preparation for a drop-down selector
1091 * @param array $foreigners array of the foreign keys
1092 * @param string $field the foreign field name
1093 * @param bool $override_total whether to override the total
1094 * @param string $foreign_filter a possible filter
1095 * @param string $foreign_limit a possible LIMIT clause
1097 * @return array data about the foreign keys
1099 * @access public
1102 function PMA_getForeignData(
1103 $foreigners, $field, $override_total, $foreign_filter, $foreign_limit
1105 // we always show the foreign field in the drop-down; if a display
1106 // field is defined, we show it besides the foreign field
1107 $foreign_link = false;
1108 if ($foreigners && isset($foreigners[$field])) {
1109 $foreigner = $foreigners[$field];
1110 $foreign_db = $foreigner['foreign_db'];
1111 $foreign_table = $foreigner['foreign_table'];
1112 $foreign_field = $foreigner['foreign_field'];
1114 // Count number of rows in the foreign table. Currently we do
1115 // not use a drop-down if more than ForeignKeyMaxLimit rows in the
1116 // foreign table,
1117 // for speed reasons and because we need a better interface for this.
1119 // We could also do the SELECT anyway, with a LIMIT, and ensure that
1120 // the current value of the field is one of the choices.
1122 $the_total = PMA_Table::countRecords($foreign_db, $foreign_table, true);
1124 if ($override_total == true
1125 || $the_total < $GLOBALS['cfg']['ForeignKeyMaxLimit']
1127 // foreign_display can be false if no display field defined:
1128 $foreign_display = PMA_getDisplayField($foreign_db, $foreign_table);
1130 $f_query_main = 'SELECT ' . PMA_Util::backquote($foreign_field)
1131 . (($foreign_display == false) ? '' : ', ' . PMA_Util::backquote($foreign_display));
1132 $f_query_from = ' FROM ' . PMA_Util::backquote($foreign_db)
1133 . '.' . PMA_Util::backquote($foreign_table);
1134 $f_query_filter = empty($foreign_filter) ? '' : ' WHERE '
1135 . PMA_Util::backquote($foreign_field)
1136 . ' LIKE "%' . PMA_Util::sqlAddSlashes($foreign_filter, true) . '%"'
1137 . (($foreign_display == false) ? '' : ' OR ' . PMA_Util::backquote($foreign_display)
1138 . ' LIKE "%' . PMA_Util::sqlAddSlashes($foreign_filter, true) . '%"'
1140 $f_query_order = ($foreign_display == false) ? '' :' ORDER BY '
1141 . PMA_Util::backquote($foreign_table) . '.'
1142 . PMA_Util::backquote($foreign_display);
1143 $f_query_limit = isset($foreign_limit) ? $foreign_limit : '';
1145 if (!empty($foreign_filter)) {
1146 $res = $GLOBALS['dbi']->query(
1147 'SELECT COUNT(*)' . $f_query_from . $f_query_filter
1149 if ($res) {
1150 $the_total = $GLOBALS['dbi']->fetchValue($res);
1151 @$GLOBALS['dbi']->freeResult($res);
1152 } else {
1153 $the_total = 0;
1157 $disp = $GLOBALS['dbi']->query(
1158 $f_query_main . $f_query_from . $f_query_filter
1159 . $f_query_order . $f_query_limit
1161 if ($disp && $GLOBALS['dbi']->numRows($disp) > 0) {
1162 // If a resultset has been created, pre-cache it in the $disp_row
1163 // array. This helps us from not needing to use mysql_data_seek by
1164 // accessing a pre-cached PHP array. Usually those resultsets are
1165 // not that big, so a performance hit should not be expected.
1166 $disp_row = array();
1167 while ($single_disp_row = @$GLOBALS['dbi']->fetchAssoc($disp)) {
1168 $disp_row[] = $single_disp_row;
1170 @$GLOBALS['dbi']->freeResult($disp);
1172 } else {
1173 $disp_row = null;
1174 $foreign_link = true;
1176 } // end if $foreigners
1178 $foreignData['foreign_link'] = $foreign_link;
1179 $foreignData['the_total'] = isset($the_total) ? $the_total : null;
1180 $foreignData['foreign_display'] = (
1181 isset($foreign_display) ? $foreign_display : null
1183 $foreignData['disp_row'] = isset($disp_row) ? $disp_row : null;
1184 $foreignData['foreign_field'] = isset($foreign_field) ? $foreign_field : null;
1185 return $foreignData;
1186 } // end of 'PMA_getForeignData()' function
1189 * Finds all related tables
1191 * @param array $all_tables All the involved tables
1192 * @param string $master The master table to form the LEFT JOIN clause
1194 * @return string LEFT JOIN
1195 * @access private
1197 function PMA_getRelatives($all_tables, $master)
1199 $fromclause = '';
1200 $emerg = '';
1202 // The list of tables that we still couldn't connect
1203 $remaining_tables = $all_tables;
1204 unset($remaining_tables[$master]);
1205 // The list of allready connected tables
1206 $known_tables[$master] = $master;
1207 $run = 0;
1208 while (count($remaining_tables) > 0) {
1209 // Whether to go from master to foreign or vice versa
1210 if ($run % 2 == 0) {
1211 $from = 'master';
1212 $to = 'foreign';
1213 } else {
1214 $from = 'foreign';
1215 $to = 'master';
1217 $in_know = '(\'' . implode('\', \'', $known_tables) . '\')';
1218 $in_left = '(\'' . implode('\', \'', $remaining_tables) . '\')';
1219 $rel_query = 'SELECT *'
1220 . ' FROM ' . PMA_Util::backquote($GLOBALS['cfgRelation']['db'])
1221 . '.' . PMA_Util::backquote($GLOBALS['cfgRelation']['relation'])
1222 . ' WHERE ' . $from . '_db = \'' . PMA_Util::sqlAddSlashes($GLOBALS['db']) . '\''
1223 . ' AND ' . $to . '_db = \'' . PMA_Util::sqlAddSlashes($GLOBALS['db']) . '\''
1224 . ' AND ' . $from . '_table IN ' . $in_know
1225 . ' AND ' . $to . '_table IN ' . $in_left;
1226 $relations = @$GLOBALS['dbi']->query($rel_query, $GLOBALS['controllink']);
1227 while ($row = $GLOBALS['dbi']->fetchAssoc($relations)) {
1228 $found_table = $row[$to . '_table'];
1229 if (isset($remaining_tables[$found_table])) {
1230 $fromclause
1231 .= "\n" . ' LEFT JOIN '
1232 . PMA_Util::backquote($GLOBALS['db']) . '.' . PMA_Util::backquote($row[$to . '_table']) . ' ON '
1233 . PMA_Util::backquote($row[$from . '_table']) . '.'
1234 . PMA_Util::backquote($row[$from . '_field']) . ' = '
1235 . PMA_Util::backquote($row[$to . '_table']) . '.'
1236 . PMA_Util::backquote($row[$to . '_field']) . ' ';
1237 $known_tables[$found_table] = $found_table;
1238 unset($remaining_tables[$found_table]);
1240 } // end while
1241 $run++;
1242 if ($run > 5) {
1243 foreach ($remaining_tables as $table) {
1244 $emerg .= ', ' . PMA_Util::backquote($table);
1245 unset($remaining_tables[$table]);
1248 } // end while
1249 $fromclause = $emerg . $fromclause;
1250 return $fromclause;
1251 } // end of the "PMA_getRelatives()" function
1254 * Rename a field in relation tables
1256 * usually called after a column in a table was renamed
1258 * @param string $db databse name
1259 * @param string $table table name
1260 * @param string $field old field name
1261 * @param string $new_name new field name
1263 * @return void
1265 function PMA_REL_renameField($db, $table, $field, $new_name)
1267 $cfgRelation = PMA_getRelationsParam();
1269 if ($cfgRelation['displaywork']) {
1270 $table_query = 'UPDATE '
1271 . PMA_Util::backquote($cfgRelation['db']) . '.'
1272 . PMA_Util::backquote($cfgRelation['table_info'])
1273 . ' SET display_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1274 . ' WHERE db_name = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1275 . ' AND table_name = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1276 . ' AND display_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1277 PMA_queryAsControlUser($table_query);
1280 if ($cfgRelation['relwork']) {
1281 $table_query = 'UPDATE '
1282 . PMA_Util::backquote($cfgRelation['db']) . '.'
1283 . PMA_Util::backquote($cfgRelation['relation'])
1284 . ' SET master_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1285 . ' WHERE master_db = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1286 . ' AND master_table = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1287 . ' AND master_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1288 PMA_queryAsControlUser($table_query);
1290 $table_query = 'UPDATE '
1291 . PMA_Util::backquote($cfgRelation['db']) . '.'
1292 . PMA_Util::backquote($cfgRelation['relation'])
1293 . ' SET foreign_field = \'' . PMA_Util::sqlAddSlashes($new_name) . '\''
1294 . ' WHERE foreign_db = \'' . PMA_Util::sqlAddSlashes($db) . '\''
1295 . ' AND foreign_table = \'' . PMA_Util::sqlAddSlashes($table) . '\''
1296 . ' AND foreign_field = \'' . PMA_Util::sqlAddSlashes($field) . '\'';
1297 PMA_queryAsControlUser($table_query);
1299 } // end if relwork
1304 * Performs SQL query used for renaming table.
1306 * @param string $table Relation table to use
1307 * @param string $source_db Source database name
1308 * @param string $target_db Target database name
1309 * @param string $source_table Source table name
1310 * @param string $target_table Target table name
1311 * @param string $db_field Name of database field
1312 * @param string $table_field Name of table field
1314 * @return nothing.
1316 function PMA_REL_renameSingleTable($table,
1317 $source_db, $target_db,
1318 $source_table, $target_table,
1319 $db_field, $table_field
1321 $query = 'UPDATE '
1322 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
1323 . PMA_Util::backquote($GLOBALS['cfgRelation'][$table])
1324 . ' SET '
1325 . $db_field . ' = \'' . PMA_Util::sqlAddSlashes($target_db) . '\', '
1326 . $table_field . ' = \'' . PMA_Util::sqlAddSlashes($target_table) . '\''
1327 . ' WHERE '
1328 . $db_field . ' = \'' . PMA_Util::sqlAddSlashes($source_db) . '\''
1329 . ' AND '
1330 . $table_field . ' = \'' . PMA_Util::sqlAddSlashes($source_table) . '\'';
1331 PMA_queryAsControlUser($query);
1336 * Rename a table in relation tables
1338 * usually called after table has been moved
1340 * @param string $source_db Source database name
1341 * @param string $target_db Target database name
1342 * @param string $source_table Source table name
1343 * @param string $target_table Target table name
1345 * @return nothing
1347 function PMA_REL_renameTable($source_db, $target_db, $source_table, $target_table)
1349 // Move old entries from PMA-DBs to new table
1350 if ($GLOBALS['cfgRelation']['commwork']) {
1351 PMA_REL_renameSingleTable(
1352 'column_info',
1353 $source_db, $target_db,
1354 $source_table, $target_table,
1355 'db_name', 'table_name'
1359 // updating bookmarks is not possible since only a single table is
1360 // moved, and not the whole DB.
1362 if ($GLOBALS['cfgRelation']['displaywork']) {
1363 PMA_REL_renameSingleTable(
1364 'table_info',
1365 $source_db, $target_db,
1366 $source_table, $target_table,
1367 'db_name', 'table_name'
1371 if ($GLOBALS['cfgRelation']['relwork']) {
1372 PMA_REL_renameSingleTable(
1373 'relation',
1374 $source_db, $target_db,
1375 $source_table, $target_table,
1376 'foreign_db', 'foreign_table'
1379 PMA_REL_renameSingleTable(
1380 'relation',
1381 $source_db, $target_db,
1382 $source_table, $target_table,
1383 'master_db', 'master_table'
1388 * @todo Can't get moving PDFs the right way. The page numbers
1389 * always get screwed up independently from duplication because the
1390 * numbers do not seem to be stored on a per-database basis. Would
1391 * the author of pdf support please have a look at it?
1394 if ($GLOBALS['cfgRelation']['pdfwork']) {
1395 PMA_REL_renameSingleTable(
1396 'table_coords',
1397 $source_db, $target_db,
1398 $source_table, $target_table,
1399 'db_name', 'table_name'
1403 if ($GLOBALS['cfgRelation']['designerwork']) {
1404 PMA_REL_renameSingleTable(
1405 'designer_coords',
1406 $source_db, $target_db,
1407 $source_table, $target_table,
1408 'db_name', 'table_name'
1414 * Create a PDF page
1416 * @param string $newpage name of the new PDF page
1417 * @param array $cfgRelation Relation configuration
1418 * @param string $db database name
1420 * @return string $pdf_page_number
1422 function PMA_REL_createPage($newpage, $cfgRelation, $db)
1424 if (! isset($newpage) || $newpage == '') {
1425 $newpage = __('no description');
1427 $ins_query = 'INSERT INTO '
1428 . PMA_Util::backquote($GLOBALS['cfgRelation']['db']) . '.'
1429 . PMA_Util::backquote($cfgRelation['pdf_pages'])
1430 . ' (db_name, page_descr)'
1431 . ' VALUES (\''
1432 . PMA_Util::sqlAddSlashes($db) . '\', \''
1433 . PMA_Util::sqlAddSlashes($newpage) . '\')';
1434 PMA_queryAsControlUser($ins_query, false);
1436 return $GLOBALS['dbi']->insertId(
1437 isset($GLOBALS['controllink']) ? $GLOBALS['controllink'] : ''