Bug: Live query chart always zero
[phpmyadmin/tyronm.git] / libraries / relation.lib.php
blob44117434b9274645843094379be6e114c2355a74
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 the query to execute
16 * @param boolean whether to display SQL error messages or not
18 * @return integer the result set, or false if no result set
20 * @access public
23 function PMA_query_as_controluser($sql, $show_error = true, $options = 0)
25 // Avoid caching of the number of rows affected; for example, this function
26 // is called for tracking purposes but we want to display the correct number
27 // of rows affected by the original query, not by the query generated for
28 // tracking.
29 $cache_affected_rows = false;
31 if ($show_error) {
32 $result = PMA_DBI_query($sql, $GLOBALS['controllink'], $options, $cache_affected_rows);
33 } else {
34 $result = @PMA_DBI_try_query($sql, $GLOBALS['controllink'], $options, $cache_affected_rows);
35 } // end if... else...
37 if ($result) {
38 return $result;
39 } else {
40 return false;
42 } // end of the "PMA_query_as_controluser()" function
44 /**
45 * @param bool $verbose whether to print diagnostic info
46 * @return array $cfgRelation
48 function PMA_getRelationsParam($verbose = false)
50 if (empty($_SESSION['relation'][$GLOBALS['server']])) {
51 $_SESSION['relation'][$GLOBALS['server']] = PMA__getRelationsParam();
54 // just for BC but needs to be before PMA_printRelationsParamDiagnostic()
55 // which uses it
56 $GLOBALS['cfgRelation'] = $_SESSION['relation'][$GLOBALS['server']];
58 if ($verbose) {
59 PMA_printRelationsParamDiagnostic($_SESSION['relation'][$GLOBALS['server']]);
62 return $_SESSION['relation'][$GLOBALS['server']];
65 /**
66 * prints out diagnostic info for pma relation feature
68 * @param array $cfgRelation
70 function PMA_printRelationsParamDiagnostic($cfgRelation)
72 $messages['error'] = '<font color="red"><strong>' . __('not OK')
73 . '</strong></font> [ <a href="Documentation.html#%s" target="documentation">'
74 . __('Documentation') . '</a> ]';
76 $messages['ok'] = '<font color="green"><strong>' . __('OK') . '</strong></font>';
77 $messages['enabled'] = '<font color="green">' . __('Enabled') . '</font>';
78 $messages['disabled'] = '<font color="red">' . __('Disabled') . '</font>';
80 if (false === $GLOBALS['cfg']['Server']['pmadb']) {
81 echo 'PMA Database ... '
82 . sprintf($messages['error'], 'pmadb')
83 . '<br />' . "\n"
84 . __('General relation features')
85 . ' <font color="green">' . __('Disabled')
86 . '</font>' . "\n";
87 return;
90 echo '<table>' . "\n";
92 PMA_printDiagMessageForParameter('pmadb', $GLOBALS['cfg']['Server']['pmadb'], $messages, 'pmadb');
94 PMA_printDiagMessageForParameter('relation', isset($cfgRelation['relation']), $messages, 'relation');
96 PMA_printDiagMessageForFeature(__('General relation features'), 'relwork', $messages);
98 PMA_printDiagMessageForParameter('table_info', isset($cfgRelation['table_info']), $messages, 'table_info');
100 PMA_printDiagMessageForFeature(__('Display Features'), 'displaywork', $messages);
102 PMA_printDiagMessageForParameter('table_coords', isset($cfgRelation['table_coords']), $messages, 'table_coords');
104 PMA_printDiagMessageForParameter('pdf_pages', isset($cfgRelation['pdf_pages']), $messages, 'table_coords');
106 PMA_printDiagMessageForFeature(__('Creation of PDFs'), 'pdfwork', $messages);
108 PMA_printDiagMessageForParameter('column_info', isset($cfgRelation['column_info']), $messages, 'col_com');
110 PMA_printDiagMessageForFeature(__('Displaying Column Comments'), 'commwork', $messages, false);
112 PMA_printDiagMessageForFeature(__('Browser transformation'), 'mimework', $messages);
114 if ($cfgRelation['commwork'] && ! $cfgRelation['mimework']) {
115 echo '<tr><td colspan=2 align="left">' . __('Please see the documentation on how to update your column_comments table') . '</td></tr>' . "\n";
118 PMA_printDiagMessageForParameter('bookmarktable', isset($cfgRelation['bookmark']), $messages, 'bookmark');
120 PMA_printDiagMessageForFeature(__('Bookmarked SQL query'), 'bookmarkwork', $messages);
122 PMA_printDiagMessageForParameter('history', isset($cfgRelation['history']), $messages, 'history');
124 PMA_printDiagMessageForFeature(__('SQL history'), 'historywork', $messages);
126 PMA_printDiagMessageForParameter('designer_coords', isset($cfgRelation['designer_coords']), $messages, 'designer_coords');
128 PMA_printDiagMessageForFeature(__('Designer'), 'designerwork', $messages);
130 PMA_printDiagMessageForParameter('recent', isset($cfgRelation['recent']), $messages, 'recent');
132 PMA_printDiagMessageForFeature(__('Persistent recently used tables'), 'recentwork', $messages);
134 PMA_printDiagMessageForParameter('table_uiprefs', isset($cfgRelation['table_uiprefs']), $messages, 'table_uiprefs');
136 PMA_printDiagMessageForFeature(__('Persistent tables\' UI preferences'), 'uiprefswork', $messages);
138 PMA_printDiagMessageForParameter('tracking', isset($cfgRelation['tracking']), $messages, 'tracking');
140 PMA_printDiagMessageForFeature(__('Tracking'), 'trackingwork', $messages);
142 PMA_printDiagMessageForParameter('userconfig', isset($cfgRelation['userconfig']), $messages, 'userconfig');
144 PMA_printDiagMessageForFeature(__('User preferences'), 'userconfigwork', $messages);
146 echo '</table>' . "\n";
148 echo '<p>' . __('Quick steps to setup advanced features:') . '</p>';
149 echo '<ul>';
150 echo '<li>' . __('Create the needed tables with the <code>script/create_tables.sql</code>.') . ' ' . PMA_showDocu('linked-tables') . '</li>';
151 echo '<li>' . __('Create a pma user and give access to these tables.') . ' ' . PMA_showDocu('pmausr') . '</li>';
152 echo '<li>' . __('Enable advanced features in configuration file (<code>config.inc.php</code>), for example by starting from <code>config.sample.inc.php</code>.') . ' ' . PMA_showDocu('quick_install') . '</li>';
153 echo '<li>' . __('Re-login to phpMyAdmin to load the updated configuration file.') . '</li>';
154 echo '</ul>';
158 * prints out one diagnostic message for a feature
160 * @param string feature name in a message string
161 * @param string the $GLOBALS['cfgRelation'] parameter to check
162 * @param array utility messages
163 * @param boolean whether to skip a line after the message
165 function PMA_printDiagMessageForFeature($feature_name, $relation_parameter, $messages, $skip_line=true)
167 echo ' <tr><td colspan=2 align="right">' . $feature_name . ': '
168 . ($GLOBALS['cfgRelation'][$relation_parameter] ? $messages['enabled'] : $messages['disabled'])
169 . '</td></tr>' . "\n";
170 if ($skip_line) {
171 echo ' <tr><td>&nbsp;</td></tr>' . "\n";
176 * prints out one diagnostic message for a configuration parameter
178 * @param string config parameter name to display
179 * @param boolean whether this parameter is set
180 * @param array utility messages
181 * @param string anchor in Documentation.html
183 function PMA_printDiagMessageForParameter($parameter, $relation_parameter_set, $messages, $doc_anchor)
185 echo ' <tr><th align="left">';
186 echo '$cfg[\'Servers\'][$i][\'' . $parameter . '\'] ... </th><td align="right">';
187 echo ($relation_parameter_set ? $messages['ok'] : sprintf($messages['error'], $doc_anchor)) . '</td></tr>' . "\n";
192 * Defines the relation parameters for the current user
193 * just a copy of the functions used for relations ;-)
194 * but added some stuff to check what will work
196 * @access protected
197 * @return array the relation parameters for the current user
199 function PMA__getRelationsParam()
201 $cfgRelation = array();
202 $cfgRelation['relwork'] = false;
203 $cfgRelation['displaywork'] = false;
204 $cfgRelation['bookmarkwork']= false;
205 $cfgRelation['pdfwork'] = false;
206 $cfgRelation['commwork'] = false;
207 $cfgRelation['mimework'] = false;
208 $cfgRelation['historywork'] = false;
209 $cfgRelation['recentwork'] = false;
210 $cfgRelation['uiprefswork'] = false;
211 $cfgRelation['trackingwork'] = false;
212 $cfgRelation['designerwork'] = false;
213 $cfgRelation['userconfigwork'] = false;
214 $cfgRelation['allworks'] = false;
215 $cfgRelation['user'] = null;
216 $cfgRelation['db'] = null;
218 if ($GLOBALS['server'] == 0 || empty($GLOBALS['cfg']['Server']['pmadb'])
219 || ! PMA_DBI_select_db($GLOBALS['cfg']['Server']['pmadb'], $GLOBALS['controllink'])) {
220 // No server selected -> no bookmark table
221 // we return the array with the falses in it,
222 // to avoid some 'Unitialized string offset' errors later
223 $GLOBALS['cfg']['Server']['pmadb'] = false;
224 return $cfgRelation;
228 $cfgRelation['user'] = $GLOBALS['cfg']['Server']['user'];
229 $cfgRelation['db'] = $GLOBALS['cfg']['Server']['pmadb'];
231 // Now I just check if all tables that i need are present so I can for
232 // example enable relations but not pdf...
233 // I was thinking of checking if they have all required columns but I
234 // fear it might be too slow
236 $tab_query = 'SHOW TABLES FROM ' . PMA_backquote($GLOBALS['cfg']['Server']['pmadb']);
237 $tab_rs = PMA_query_as_controluser($tab_query, false, PMA_DBI_QUERY_STORE);
239 if (! $tab_rs) {
240 // query failed ... ?
241 //$GLOBALS['cfg']['Server']['pmadb'] = false;
242 return $cfgRelation;
245 while ($curr_table = @PMA_DBI_fetch_row($tab_rs)) {
246 if ($curr_table[0] == $GLOBALS['cfg']['Server']['bookmarktable']) {
247 $cfgRelation['bookmark'] = $curr_table[0];
248 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['relation']) {
249 $cfgRelation['relation'] = $curr_table[0];
250 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_info']) {
251 $cfgRelation['table_info'] = $curr_table[0];
252 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_coords']) {
253 $cfgRelation['table_coords'] = $curr_table[0];
254 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['designer_coords']) {
255 $cfgRelation['designer_coords'] = $curr_table[0];
256 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['column_info']) {
257 $cfgRelation['column_info'] = $curr_table[0];
258 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['pdf_pages']) {
259 $cfgRelation['pdf_pages'] = $curr_table[0];
260 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['history']) {
261 $cfgRelation['history'] = $curr_table[0];
262 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['recent']) {
263 $cfgRelation['recent'] = $curr_table[0];
264 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_uiprefs']) {
265 $cfgRelation['table_uiprefs'] = $curr_table[0];
266 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['tracking']) {
267 $cfgRelation['tracking'] = $curr_table[0];
268 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['userconfig']) {
269 $cfgRelation['userconfig'] = $curr_table[0];
271 } // end while
272 PMA_DBI_free_result($tab_rs);
274 if (isset($cfgRelation['relation'])) {
275 $cfgRelation['relwork'] = true;
276 if (isset($cfgRelation['table_info'])) {
277 $cfgRelation['displaywork'] = true;
281 if (isset($cfgRelation['table_coords']) && isset($cfgRelation['pdf_pages'])) {
282 $cfgRelation['pdfwork'] = true;
285 if (isset($cfgRelation['column_info'])) {
286 $cfgRelation['commwork'] = true;
288 if ($GLOBALS['cfg']['Server']['verbose_check']) {
289 $mime_query = 'SHOW FIELDS FROM '
290 . PMA_backquote($cfgRelation['db']) . '.'
291 . PMA_backquote($cfgRelation['column_info']);
292 $mime_rs = PMA_query_as_controluser($mime_query, false);
294 $mime_field_mimetype = false;
295 $mime_field_transformation = false;
296 $mime_field_transformation_options = false;
297 while ($curr_mime_field = @PMA_DBI_fetch_row($mime_rs)) {
298 if ($curr_mime_field[0] == 'mimetype') {
299 $mime_field_mimetype = true;
300 } elseif ($curr_mime_field[0] == 'transformation') {
301 $mime_field_transformation = true;
302 } elseif ($curr_mime_field[0] == 'transformation_options') {
303 $mime_field_transformation_options = true;
306 PMA_DBI_free_result($mime_rs);
308 if ($mime_field_mimetype
309 && $mime_field_transformation
310 && $mime_field_transformation_options) {
311 $cfgRelation['mimework'] = true;
313 } else {
314 $cfgRelation['mimework'] = true;
318 if (isset($cfgRelation['history'])) {
319 $cfgRelation['historywork'] = true;
322 if (isset($cfgRelation['recent'])) {
323 $cfgRelation['recentwork'] = true;
326 if (isset($cfgRelation['table_uiprefs'])) {
327 $cfgRelation['uiprefswork'] = true;
330 if (isset($cfgRelation['tracking'])) {
331 $cfgRelation['trackingwork'] = true;
334 if (isset($cfgRelation['userconfig'])) {
335 $cfgRelation['userconfigwork'] = true;
338 // we do not absolutely need that the internal relations or the PDF
339 // schema feature be activated
340 if (isset($cfgRelation['designer_coords'])) {
341 $cfgRelation['designerwork'] = true;
344 if (isset($cfgRelation['bookmark'])) {
345 $cfgRelation['bookmarkwork'] = true;
348 if ($cfgRelation['relwork'] && $cfgRelation['displaywork']
349 && $cfgRelation['pdfwork'] && $cfgRelation['commwork']
350 && $cfgRelation['mimework'] && $cfgRelation['historywork']
351 && $cfgRelation['recentwork'] && $cfgRelation['uiprefswork']
352 && $cfgRelation['trackingwork'] && $cfgRelation['userconfigwork']
353 && $cfgRelation['bookmarkwork'] && $cfgRelation['designerwork']) {
354 $cfgRelation['allworks'] = true;
357 return $cfgRelation;
358 } // end of the 'PMA_getRelationsParam()' function
361 * Gets all Relations to foreign tables for a given table or
362 * optionally a given column in a table
364 * @access public
365 * @param string $db the name of the db to check for
366 * @param string $table the name of the table to check for
367 * @param string $column the name of the column to check for
368 * @param string $source the source for foreign key information
369 * @return array db,table,column
371 function PMA_getForeigners($db, $table, $column = '', $source = 'both')
373 $cfgRelation = PMA_getRelationsParam();
374 $foreign = array();
376 if ($cfgRelation['relwork'] && ($source == 'both' || $source == 'internal')) {
377 $rel_query = '
378 SELECT `master_field`,
379 `foreign_db`,
380 `foreign_table`,
381 `foreign_field`
382 FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation']) . '
383 WHERE `master_db` = \'' . PMA_sqlAddSlashes($db) . '\'
384 AND `master_table` = \'' . PMA_sqlAddSlashes($table) . '\' ';
385 if (strlen($column)) {
386 $rel_query .= ' AND `master_field` = \'' . PMA_sqlAddSlashes($column) . '\'';
388 $foreign = PMA_DBI_fetch_result($rel_query, 'master_field', null, $GLOBALS['controllink']);
391 if (($source == 'both' || $source == 'foreign') && strlen($table)) {
392 $show_create_table_query = 'SHOW CREATE TABLE '
393 . PMA_backquote($db) . '.' . PMA_backquote($table);
394 $show_create_table = PMA_DBI_fetch_value($show_create_table_query, 0, 1);
395 $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
397 foreach ($analyzed_sql[0]['foreign_keys'] as $one_key) {
398 // The analyzer may return more than one column name in the
399 // index list or the ref_index_list; if this happens,
400 // the current logic just discards the whole index; having
401 // more than one index field is currently unsupported (see FAQ 3.6)
402 if (count($one_key['index_list']) == 1) {
403 foreach ($one_key['index_list'] as $i => $field) {
404 // If a foreign key is defined in the 'internal' source (pmadb)
405 // and as a native foreign key, we won't get it twice
406 // if $source='both' because we use $field as key
408 // The parser looks for a CONSTRAINT clause just before
409 // the FOREIGN KEY clause. It finds it (as output from
410 // SHOW CREATE TABLE) in MySQL 4.0.13, but not in older
411 // versions like 3.23.58.
412 // In those cases, the FOREIGN KEY parsing will put numbers
413 // like -1, 0, 1... instead of the constraint number.
415 if (isset($one_key['constraint'])) {
416 $foreign[$field]['constraint'] = $one_key['constraint'];
419 if (isset($one_key['ref_db_name'])) {
420 $foreign[$field]['foreign_db'] = $one_key['ref_db_name'];
421 } else {
422 $foreign[$field]['foreign_db'] = $db;
424 $foreign[$field]['foreign_table'] = $one_key['ref_table_name'];
425 $foreign[$field]['foreign_field'] = $one_key['ref_index_list'][$i];
426 if (isset($one_key['on_delete'])) {
427 $foreign[$field]['on_delete'] = $one_key['on_delete'];
429 if (isset($one_key['on_update'])) {
430 $foreign[$field]['on_update'] = $one_key['on_update'];
438 * Emulating relations for some information_schema tables
440 if ($db == 'information_schema'
441 && ($source == 'internal' || $source == 'both')) {
442 require_once './libraries/information_schema_relations.lib.php';
444 if (isset($GLOBALS['information_schema_relations'][$table])) {
445 foreach ($GLOBALS['information_schema_relations'][$table] as $field => $relations) {
446 if ((! strlen($column) || $column == $field)
447 && (! isset($foreign[$field]) || ! strlen($foreign[$field]))) {
448 $foreign[$field] = $relations;
454 return $foreign;
455 } // end of the 'PMA_getForeigners()' function
458 * Gets the display field of a table
460 * @access public
461 * @param string $db the name of the db to check for
462 * @param string $table the name of the table to check for
463 * @return string field name
465 function PMA_getDisplayField($db, $table)
467 $cfgRelation = PMA_getRelationsParam();
470 * Try to fetch the display field from DB.
472 if ($cfgRelation['displaywork']) {
473 $disp_query = '
474 SELECT `display_field`
475 FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['table_info']) . '
476 WHERE `db_name` = \'' . PMA_sqlAddSlashes($db) . '\'
477 AND `table_name` = \'' . PMA_sqlAddSlashes($table) . '\'';
479 $row = PMA_DBI_fetch_single_row($disp_query, 'ASSOC', $GLOBALS['controllink']);
480 if (isset($row['display_field'])) {
481 return $row['display_field'];
486 * Emulating the display field for some information_schema tables.
488 if ($db == 'information_schema') {
489 switch ($table) {
490 case 'CHARACTER_SETS': return 'DESCRIPTION';
491 case 'TABLES': return 'TABLE_COMMENT';
496 * No Luck...
498 return false;
500 } // end of the 'PMA_getDisplayField()' function
503 * Gets the comments for all rows of a table or the db itself
505 * @access public
506 * @param string the name of the db to check for
507 * @param string the name of the table to check for
508 * @return array [field_name] = comment
510 function PMA_getComments($db, $table = '')
512 $comments = array();
514 if ($table != '') {
515 // MySQL native column comments
516 $fields = PMA_DBI_get_columns($db, $table, true);
517 if ($fields) {
518 foreach ($fields as $field) {
519 if (! empty($field['Comment'])) {
520 $comments[$field['Field']] = $field['Comment'];
524 } else {
525 $comments[] = PMA_getDbComment($db);
528 return $comments;
529 } // end of the 'PMA_getComments()' function
532 * Gets the comment for a db
534 * @access public
535 * @param string the name of the db to check for
536 * @return string comment
538 function PMA_getDbComment($db)
540 $cfgRelation = PMA_getRelationsParam();
541 $comment = '';
543 if ($cfgRelation['commwork']) {
544 // pmadb internal db comment
545 $com_qry = "
546 SELECT `comment`
547 FROM " . PMA_backquote($cfgRelation['db']) . "." . PMA_backquote($cfgRelation['column_info']) . "
548 WHERE db_name = '" . PMA_sqlAddSlashes($db) . "'
549 AND table_name = ''
550 AND column_name = '(db_comment)'";
551 $com_rs = PMA_query_as_controluser($com_qry, true, PMA_DBI_QUERY_STORE);
553 if ($com_rs && PMA_DBI_num_rows($com_rs) > 0) {
554 $row = PMA_DBI_fetch_assoc($com_rs);
555 $comment = $row['comment'];
557 PMA_DBI_free_result($com_rs);
560 return $comment;
561 } // end of the 'PMA_getDbComment()' function
564 * Gets the comment for a db
566 * @access public
567 * @param string the name of the db to check for
568 * @return string comment
570 function PMA_getDbComments()
572 $cfgRelation = PMA_getRelationsParam();
573 $comments = array();
575 if ($cfgRelation['commwork']) {
576 // pmadb internal db comment
577 $com_qry = "
578 SELECT `db_name`, `comment`
579 FROM " . PMA_backquote($cfgRelation['db']) . "." . PMA_backquote($cfgRelation['column_info']) . "
580 WHERE `column_name` = '(db_comment)'";
581 $com_rs = PMA_query_as_controluser($com_qry, true, PMA_DBI_QUERY_STORE);
583 if ($com_rs && PMA_DBI_num_rows($com_rs) > 0) {
584 while ($row = PMA_DBI_fetch_assoc($com_rs)) {
585 $comments[$row['db_name']] = $row['comment'];
588 PMA_DBI_free_result($com_rs);
591 return $comments;
592 } // end of the 'PMA_getDbComments()' function
595 * Set a database comment to a certain value.
597 * @access public
598 * @param string $db the name of the db
599 * @param string $comment the value of the column
600 * @return boolean true, if comment-query was made.
602 function PMA_setDbComment($db, $comment = '')
604 $cfgRelation = PMA_getRelationsParam();
606 if (! $cfgRelation['commwork']) {
607 return false;
610 if (strlen($comment)) {
611 $upd_query = "
612 INSERT INTO
613 " . PMA_backquote($cfgRelation['db']) . "." . PMA_backquote($cfgRelation['column_info']) . "
614 (`db_name`, `table_name`, `column_name`, `comment`)
615 VALUES (
616 '" . PMA_sqlAddSlashes($db) . "',
618 '(db_comment)',
619 '" . PMA_sqlAddSlashes($comment) . "')
620 ON DUPLICATE KEY UPDATE
621 `comment` = '" . PMA_sqlAddSlashes($comment) . "'";
622 } else {
623 $upd_query = '
624 DELETE FROM
625 ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['column_info']) . '
626 WHERE `db_name` = \'' . PMA_sqlAddSlashes($db) . '\'
627 AND `table_name` = \'\'
628 AND `column_name` = \'(db_comment)\'';
631 if (isset($upd_query)) {
632 return PMA_query_as_controluser($upd_query);
635 return false;
636 } // end of 'PMA_setDbComment()' function
639 * Set a SQL history entry
641 * @param string $db the name of the db
642 * @param string $table the name of the table
643 * @param string $username the username
644 * @param string $sqlquery the sql query
645 * @access public
647 function PMA_setHistory($db, $table, $username, $sqlquery)
649 if (strlen($sqlquery) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
650 return;
653 $cfgRelation = PMA_getRelationsParam();
655 if (! isset($_SESSION['sql_history'])) {
656 $_SESSION['sql_history'] = array();
659 $key = md5($sqlquery . $db . $table);
661 if (isset($_SESSION['sql_history'][$key])) {
662 unset($_SESSION['sql_history'][$key]);
665 $_SESSION['sql_history'][$key] = array(
666 'db' => $db,
667 'table' => $table,
668 'sqlquery' => $sqlquery,
671 if (count($_SESSION['sql_history']) > $GLOBALS['cfg']['QueryHistoryMax']) {
672 // history should not exceed a maximum count
673 array_shift($_SESSION['sql_history']);
676 if (! $cfgRelation['historywork'] || ! $GLOBALS['cfg']['QueryHistoryDB']) {
677 return;
680 PMA_query_as_controluser('
681 INSERT INTO
682 ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['history']) . '
683 (`username`,
684 `db`,
685 `table`,
686 `timevalue`,
687 `sqlquery`)
688 VALUES
689 (\'' . PMA_sqlAddSlashes($username) . '\',
690 \'' . PMA_sqlAddSlashes($db) . '\',
691 \'' . PMA_sqlAddSlashes($table) . '\',
692 NOW(),
693 \'' . PMA_sqlAddSlashes($sqlquery) . '\')');
694 } // end of 'PMA_setHistory()' function
697 * Gets a SQL history entry
699 * @param string $username the username
700 * @return array list of history items
701 * @access public
703 function PMA_getHistory($username)
705 $cfgRelation = PMA_getRelationsParam();
707 if (! $cfgRelation['historywork']) {
708 return false;
711 $hist_query = '
712 SELECT `db`,
713 `table`,
714 `sqlquery`
715 FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['history']) . '
716 WHERE `username` = \'' . PMA_sqlAddSlashes($username) . '\'
717 ORDER BY `id` DESC';
719 return PMA_DBI_fetch_result($hist_query, null, null, $GLOBALS['controllink']);
720 } // end of 'PMA_getHistory()' function
723 * purges SQL history
725 * deletes entries that exceeds $cfg['QueryHistoryMax'], oldest first, for the
726 * given user
728 * @param string $username the username
729 * @access public
731 function PMA_purgeHistory($username)
733 $cfgRelation = PMA_getRelationsParam();
734 if (! $GLOBALS['cfg']['QueryHistoryDB'] || ! $cfgRelation['historywork']) {
735 return;
738 if (! $cfgRelation['historywork']) {
739 return;
742 $search_query = '
743 SELECT `timevalue`
744 FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['history']) . '
745 WHERE `username` = \'' . PMA_sqlAddSlashes($username) . '\'
746 ORDER BY `timevalue` DESC
747 LIMIT ' . $GLOBALS['cfg']['QueryHistoryMax'] . ', 1';
749 if ($max_time = PMA_DBI_fetch_value($search_query, 0, 0, $GLOBALS['controllink'])) {
750 PMA_query_as_controluser('
751 DELETE FROM
752 ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['history']) . '
753 WHERE `username` = \'' . PMA_sqlAddSlashes($username) . '\'
754 AND `timevalue` <= \'' . $max_time . '\'');
756 } // end of 'PMA_purgeHistory()' function
759 * Prepares the dropdown for one mode
761 * @param array $foreign the keys and values for foreigns
762 * @param string $data the current data of the dropdown
763 * @param string $mode the needed mode
765 * @return array the <option value=""><option>s
767 * @access protected
769 function PMA__foreignDropdownBuild($foreign, $data, $mode)
771 $reloptions = array();
773 // id-only is a special mode used when no foreign display column
774 // is available
775 if ($mode == 'id-content' || $mode == 'id-only') {
776 // sort for id-content
777 if ($GLOBALS['cfg']['NaturalOrder']) {
778 uksort($foreign, 'strnatcasecmp');
779 } else {
780 ksort($foreign);
782 } elseif ($mode == 'content-id') {
783 // sort for content-id
784 if ($GLOBALS['cfg']['NaturalOrder']) {
785 natcasesort($foreign);
786 } else {
787 asort($foreign);
791 foreach ($foreign as $key => $value) {
792 if (PMA_strlen($value) <= $GLOBALS['cfg']['LimitChars']) {
793 $vtitle = '';
794 $value = htmlspecialchars($value);
795 } else {
796 $vtitle = htmlspecialchars($value);
797 $value = htmlspecialchars(substr($value, 0, $GLOBALS['cfg']['LimitChars']) . '...');
800 $reloption = '<option value="' . htmlspecialchars($key) . '"';
801 if ($vtitle != '') {
802 $reloption .= ' title="' . $vtitle . '"';
805 if ((string) $key == (string) $data) {
806 $reloption .= ' selected="selected"';
809 if ($mode == 'content-id') {
810 $reloptions[] = $reloption . '>' . $value . '&nbsp;-&nbsp;' . htmlspecialchars($key) . '</option>';
811 } elseif ($mode == 'id-content') {
812 $reloptions[] = $reloption . '>' . htmlspecialchars($key) . '&nbsp;-&nbsp;' . $value . '</option>';
813 } elseif ($mode == 'id-only') {
814 $reloptions[] = $reloption . '>' . htmlspecialchars($key) . '</option>';
816 } // end foreach
818 return $reloptions;
819 } // end of 'PMA__foreignDropdownBuild' function
822 * Outputs dropdown with values of foreign fields
824 * @param array array of the displayed row
825 * @param string the foreign field
826 * @param string the foreign field to display
827 * @param string the current data of the dropdown (field in row)
828 * @return string the <option value=""><option>s
829 * @access public
831 function PMA_foreignDropdown($disp_row, $foreign_field, $foreign_display, $data,
832 $max = null)
834 if (null === $max) {
835 $max = $GLOBALS['cfg']['ForeignKeyMaxLimit'];
838 $foreign = array();
840 // collect the data
841 foreach ($disp_row as $relrow) {
842 $key = $relrow[$foreign_field];
844 // if the display field has been defined for this foreign table
845 if ($foreign_display) {
846 $value = $relrow[$foreign_display];
847 } else {
848 $value = '';
849 } // end if ($foreign_display)
851 $foreign[$key] = $value;
852 } // end foreach
854 // put the dropdown sections in correct order
855 $top = array();
856 $bottom = array();
857 if ($foreign_display) {
858 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'], 'array')) {
859 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][0])) {
860 $top = PMA__foreignDropdownBuild($foreign, $data,
861 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][0]);
863 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][1])) {
864 $bottom = PMA__foreignDropdownBuild($foreign, $data,
865 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][1]);
867 } else {
868 $top = PMA__foreignDropdownBuild($foreign, $data, 'id-content');
869 $bottom = PMA__foreignDropdownBuild($foreign, $data, 'content-id');
871 } else {
872 $top = PMA__foreignDropdownBuild($foreign, $data, 'id-only');
875 // beginning of dropdown
876 $ret = '<option value="">&nbsp;</option>';
877 $top_count = count($top);
878 if ($max == -1 || $top_count < $max) {
879 $ret .= implode('', $top);
880 if ($foreign_display && $top_count > 0) {
881 // this empty option is to visually mark the beginning of the
882 // second series of values (bottom)
883 $ret .= '<option value="">&nbsp;</option>';
886 if ($foreign_display) {
887 $ret .= implode('', $bottom);
890 return $ret;
891 } // end of 'PMA_foreignDropdown()' function
894 * Gets foreign keys in preparation for a drop-down selector
896 * @param array array of the foreign keys
897 * @param string the foreign field name
898 * @param bool whether to override the total
899 * @param string a possible filter
900 * @param string a possible LIMIT clause
901 * @return array data about the foreign keys
902 * @access public
905 function PMA_getForeignData($foreigners, $field, $override_total, $foreign_filter, $foreign_limit)
907 // we always show the foreign field in the drop-down; if a display
908 // field is defined, we show it besides the foreign field
909 $foreign_link = false;
910 if ($foreigners && isset($foreigners[$field])) {
911 $foreigner = $foreigners[$field];
912 $foreign_db = $foreigner['foreign_db'];
913 $foreign_table = $foreigner['foreign_table'];
914 $foreign_field = $foreigner['foreign_field'];
916 // Count number of rows in the foreign table. Currently we do
917 // not use a drop-down if more than 200 rows in the foreign table,
918 // for speed reasons and because we need a better interface for this.
920 // We could also do the SELECT anyway, with a LIMIT, and ensure that
921 // the current value of the field is one of the choices.
923 $the_total = PMA_Table::countRecords($foreign_db, $foreign_table);
925 if ($override_total == true || $the_total < $GLOBALS['cfg']['ForeignKeyMaxLimit']) {
926 // foreign_display can be false if no display field defined:
927 $foreign_display = PMA_getDisplayField($foreign_db, $foreign_table);
929 $f_query_main = 'SELECT ' . PMA_backquote($foreign_field)
930 . (($foreign_display == false) ? '' : ', ' . PMA_backquote($foreign_display));
931 $f_query_from = ' FROM ' . PMA_backquote($foreign_db) . '.' . PMA_backquote($foreign_table);
932 $f_query_filter = empty($foreign_filter) ? '' : ' WHERE ' . PMA_backquote($foreign_field)
933 . ' LIKE "%' . PMA_sqlAddSlashes($foreign_filter, true) . '%"'
934 . (($foreign_display == false) ? '' : ' OR ' . PMA_backquote($foreign_display)
935 . ' LIKE "%' . PMA_sqlAddSlashes($foreign_filter, true) . '%"'
937 $f_query_order = ($foreign_display == false) ? '' :' ORDER BY ' . PMA_backquote($foreign_table) . '.' . PMA_backquote($foreign_display);
938 $f_query_limit = isset($foreign_limit) ? $foreign_limit : '';
940 if (!empty($foreign_filter)) {
941 $res = PMA_DBI_query('SELECT COUNT(*)' . $f_query_from . $f_query_filter);
942 if ($res) {
943 $the_total = PMA_DBI_fetch_value($res);
944 @PMA_DBI_free_result($res);
945 } else {
946 $the_total = 0;
950 $disp = PMA_DBI_query($f_query_main . $f_query_from . $f_query_filter . $f_query_order . $f_query_limit);
951 if ($disp && PMA_DBI_num_rows($disp) > 0) {
952 // If a resultset has been created, pre-cache it in the $disp_row array
953 // This helps us from not needing to use mysql_data_seek by accessing a pre-cached
954 // PHP array. Usually those resultsets are not that big, so a performance hit should
955 // not be expected.
956 $disp_row = array();
957 while ($single_disp_row = @PMA_DBI_fetch_assoc($disp)) {
958 $disp_row[] = $single_disp_row;
960 @PMA_DBI_free_result($disp);
962 } else {
963 $disp_row = null;
964 $foreign_link = true;
966 } // end if $foreigners
968 $foreignData['foreign_link'] = $foreign_link;
969 $foreignData['the_total'] = isset($the_total) ? $the_total : null;
970 $foreignData['foreign_display'] = isset($foreign_display) ? $foreign_display : null;
971 $foreignData['disp_row'] = isset($disp_row) ? $disp_row : null;
972 $foreignData['foreign_field'] = isset($foreign_field) ? $foreign_field : null;
973 return $foreignData;
974 } // end of 'PMA_getForeignData()' function
977 * Finds all related tables
979 * @param string whether to go from master to foreign or vice versa
980 * @return boolean always true
981 * @global array $tab_left the list of tables that we still couldn't connect
982 * @global array $tab_know the list of allready connected tables
983 * @global string $fromclause
985 * @access private
987 function PMA_getRelatives($from)
989 global $tab_left, $tab_know, $fromclause;
991 if ($from == 'master') {
992 $to = 'foreign';
993 } else {
994 $to = 'master';
996 $in_know = '(\'' . implode('\', \'', $tab_know) . '\')';
997 $in_left = '(\'' . implode('\', \'', $tab_left) . '\')';
999 $rel_query = 'SELECT *'
1000 . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db'])
1001 . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
1002 . ' WHERE ' . $from . '_db = \'' . PMA_sqlAddSlashes($GLOBALS['db']) . '\''
1003 . ' AND ' . $to . '_db = \'' . PMA_sqlAddSlashes($GLOBALS['db']) . '\''
1004 . ' AND ' . $from . '_table IN ' . $in_know
1005 . ' AND ' . $to . '_table IN ' . $in_left;
1006 $relations = @PMA_DBI_query($rel_query, $GLOBALS['controllink']);
1007 while ($row = PMA_DBI_fetch_assoc($relations)) {
1008 $found_table = $row[$to . '_table'];
1009 if (isset($tab_left[$found_table])) {
1010 $fromclause
1011 .= "\n" . ' LEFT JOIN '
1012 . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($row[$to . '_table']) . ' ON '
1013 . PMA_backquote($row[$from . '_table']) . '.'
1014 . PMA_backquote($row[$from . '_field']) . ' = '
1015 . PMA_backquote($row[$to . '_table']) . '.'
1016 . PMA_backquote($row[$to . '_field']) . ' ';
1017 $tab_know[$found_table] = $found_table;
1018 unset($tab_left[$found_table]);
1020 } // end while
1022 return true;
1023 } // end of the "PMA_getRelatives()" function
1026 * Rename a field in relation tables
1028 * usually called after a field in a table was renamed in tbl_alter.php
1030 * @param string $db
1031 * @param string $table
1032 * @param string $field
1033 * @param string $new_name
1035 function PMA_REL_renameField($db, $table, $field, $new_name)
1037 $cfgRelation = PMA_getRelationsParam();
1039 if ($cfgRelation['displaywork']) {
1040 $table_query = 'UPDATE ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
1041 . ' SET display_field = \'' . PMA_sqlAddSlashes($new_name) . '\''
1042 . ' WHERE db_name = \'' . PMA_sqlAddSlashes($db) . '\''
1043 . ' AND table_name = \'' . PMA_sqlAddSlashes($table) . '\''
1044 . ' AND display_field = \'' . PMA_sqlAddSlashes($field) . '\'';
1045 PMA_query_as_controluser($table_query);
1048 if ($cfgRelation['relwork']) {
1049 $table_query = 'UPDATE ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation'])
1050 . ' SET master_field = \'' . PMA_sqlAddSlashes($new_name) . '\''
1051 . ' WHERE master_db = \'' . PMA_sqlAddSlashes($db) . '\''
1052 . ' AND master_table = \'' . PMA_sqlAddSlashes($table) . '\''
1053 . ' AND master_field = \'' . PMA_sqlAddSlashes($field) . '\'';
1054 PMA_query_as_controluser($table_query);
1056 $table_query = 'UPDATE ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation'])
1057 . ' SET foreign_field = \'' . PMA_sqlAddSlashes($new_name) . '\''
1058 . ' WHERE foreign_db = \'' . PMA_sqlAddSlashes($db) . '\''
1059 . ' AND foreign_table = \'' . PMA_sqlAddSlashes($table) . '\''
1060 . ' AND foreign_field = \'' . PMA_sqlAddSlashes($field) . '\'';
1061 PMA_query_as_controluser($table_query);
1062 } // end if relwork
1066 * Create a PDF page
1068 * @param string $newpage
1069 * @param array $cfgRelation
1070 * @param string $db
1071 * @return string $pdf_page_number
1073 function PMA_REL_create_page($newpage, $cfgRelation, $db)
1075 if (! isset($newpage) || $newpage == '') {
1076 $newpage = __('no description');
1078 $ins_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['pdf_pages'])
1079 . ' (db_name, page_descr)'
1080 . ' VALUES (\'' . PMA_sqlAddSlashes($db) . '\', \'' . PMA_sqlAddSlashes($newpage) . '\')';
1081 PMA_query_as_controluser($ins_query, false);
1082 return PMA_DBI_insert_id(isset($GLOBALS['controllink']) ? $GLOBALS['controllink'] : '');