Cannot create a table in information_schema
[phpmyadmin/ammaryasirr.git] / libraries / relation.lib.php
blob9588853f9415e58b1447c33a96a03c9b97e9f5aa
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 * @uses $_SESSION['relation'][$GLOBALS['server']] for caching
46 * @uses $GLOBALS['cfgRelation'] to set it
47 * @uses $GLOBALS['server'] to ensure we are using server-specific pmadb
48 * @uses PMA__getRelationsParam()
49 * @uses PMA_printRelationsParamDiagnostic()
50 * @param bool $verbose whether to print diagnostic info
51 * @return array $cfgRelation
53 function PMA_getRelationsParam($verbose = false)
55 if (empty($_SESSION['relation'][$GLOBALS['server']])) {
56 $_SESSION['relation'][$GLOBALS['server']] = PMA__getRelationsParam();
59 // just for BC but needs to be before PMA_printRelationsParamDiagnostic()
60 // which uses it
61 $GLOBALS['cfgRelation'] = $_SESSION['relation'][$GLOBALS['server']];
63 if ($verbose) {
64 PMA_printRelationsParamDiagnostic($_SESSION['relation'][$GLOBALS['server']]);
67 return $_SESSION['relation'][$GLOBALS['server']];
70 /**
71 * prints out diagnostic info for pma relation feature
73 * @uses $GLOBALS['server']
74 * @uses $GLOBALS['controllink']
75 * @uses $cfg['Server']['pmadb']
76 * @uses sprintf()
77 * @uses PMA_printDiagMessageForFeature()
78 * @uses PMA_printDiagMessageForParameter()
79 * @param array $cfgRelation
81 function PMA_printRelationsParamDiagnostic($cfgRelation)
83 $messages['error'] = '<font color="red"><strong>' . __('not OK')
84 . '</strong></font> [ <a href="Documentation.html#%s" target="documentation">'
85 . __('Documentation') . '</a> ]';
87 $messages['ok'] = '<font color="green"><strong>' . __('OK') . '</strong></font>';
88 $messages['enabled'] = '<font color="green">' . __('Enabled') . '</font>';
89 $messages['disabled'] = '<font color="red">' . __('Disabled') . '</font>';
91 if (false === $GLOBALS['cfg']['Server']['pmadb']) {
92 echo 'PMA Database ... '
93 . sprintf($messages['error'], 'pmadb')
94 . '<br />' . "\n"
95 . __('General relation features')
96 . ' <font color="green">' . __('Disabled')
97 . '</font>' . "\n";
98 return;
101 echo '<table>' . "\n";
103 PMA_printDiagMessageForParameter('pmadb', $GLOBALS['cfg']['Server']['pmadb'], $messages, 'pmadb');
105 PMA_printDiagMessageForParameter('relation', isset($cfgRelation['relation']), $messages, 'relation');
107 PMA_printDiagMessageForFeature(__('General relation features'), 'relwork', $messages);
109 PMA_printDiagMessageForParameter('table_info', isset($cfgRelation['table_info']), $messages, 'table_info');
111 PMA_printDiagMessageForFeature(__('Display Features'), 'displaywork', $messages);
113 PMA_printDiagMessageForParameter('table_coords', isset($cfgRelation['table_coords']), $messages, 'table_coords');
115 PMA_printDiagMessageForParameter('pdf_pages', isset($cfgRelation['pdf_pages']), $messages, 'table_coords');
117 PMA_printDiagMessageForFeature(__('Creation of PDFs'), 'pdfwork', $messages);
119 PMA_printDiagMessageForParameter('column_info', isset($cfgRelation['column_info']), $messages, 'col_com');
121 PMA_printDiagMessageForFeature(__('Displaying Column Comments'), 'commwork', $messages, false);
123 PMA_printDiagMessageForFeature(__('Browser transformation'), 'mimework', $messages);
125 if ($cfgRelation['commwork'] && ! $cfgRelation['mimework']) {
126 echo '<tr><td colspan=2 align="left">' . __('Please see the documentation on how to update your column_comments table') . '</td></tr>' . "\n";
129 PMA_printDiagMessageForParameter('bookmarktable', isset($cfgRelation['bookmark']), $messages, 'bookmark');
131 PMA_printDiagMessageForFeature(__('Bookmarked SQL query'), 'bookmarkwork', $messages);
133 PMA_printDiagMessageForParameter('history', isset($cfgRelation['history']), $messages, 'history');
135 PMA_printDiagMessageForFeature(__('SQL history'), 'historywork', $messages);
137 PMA_printDiagMessageForParameter('designer_coords', isset($cfgRelation['designer_coords']), $messages, 'designer_coords');
139 PMA_printDiagMessageForFeature(__('Designer'), 'designerwork', $messages);
141 PMA_printDiagMessageForParameter('tracking', isset($cfgRelation['tracking']), $messages, 'tracking');
143 PMA_printDiagMessageForFeature(__('Tracking'), 'trackingwork', $messages);
145 PMA_printDiagMessageForParameter('userconfig', isset($cfgRelation['userconfig']), $messages, 'userconfig');
147 PMA_printDiagMessageForFeature(__('User preferences'), 'userconfigwork', $messages);
149 echo '</table>' . "\n";
151 echo '<p>' . __('Quick steps to setup advanced features:') . '</p>';
152 echo '<ul>';
153 echo '<li>' . __('Create the needed tables with the <code>script/create_tables.sql</code>.') . ' ' . PMA_showDocu('linked-tables') . '</li>';
154 echo '<li>' . __('Create a pma user and give access to these tables.') . ' ' . PMA_showDocu('pmausr') . '</li>';
155 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>';
156 echo '<li>' . __('Re-login to phpMyAdmin to load the updated configuration file.') . '</li>';
157 echo '</ul>';
161 * prints out one diagnostic message for a feature
163 * @param string feature name in a message string
164 * @param string the $GLOBALS['cfgRelation'] parameter to check
165 * @param array utility messages
166 * @param boolean whether to skip a line after the message
168 function PMA_printDiagMessageForFeature($feature_name, $relation_parameter, $messages, $skip_line=true)
170 echo ' <tr><td colspan=2 align="right">' . $feature_name . ': '
171 . ($GLOBALS['cfgRelation'][$relation_parameter] ? $messages['enabled'] : $messages['disabled'])
172 . '</td></tr>' . "\n";
173 if ($skip_line) {
174 echo ' <tr><td>&nbsp;</td></tr>' . "\n";
179 * prints out one diagnostic message for a configuration parameter
181 * @param string config parameter name to display
182 * @param boolean whether this parameter is set
183 * @param array utility messages
184 * @param string anchor in Documentation.html
186 function PMA_printDiagMessageForParameter($parameter, $relation_parameter_set, $messages, $doc_anchor)
188 echo ' <tr><th align="left">';
189 echo '$cfg[\'Servers\'][$i][\'' . $parameter . '\'] ... </th><td align="right">';
190 echo ($relation_parameter_set ? $messages['ok'] : sprintf($messages['error'], $doc_anchor)) . '</td></tr>' . "\n";
195 * Defines the relation parameters for the current user
196 * just a copy of the functions used for relations ;-)
197 * but added some stuff to check what will work
199 * @uses $cfg['Server']['user']
200 * @uses $cfg['Server']['pmadb']
201 * @uses $cfg['Server']['verbose_check']
202 * @uses $GLOBALS['server']
203 * @uses $GLOBALS['controllink']
204 * @uses PMA_DBI_QUERY_STORE
205 * @uses PMA_DBI_select_db()
206 * @uses PMA_backquote()
207 * @uses PMA_query_as_controluser()
208 * @uses PMA_DBI_fetch_row()
209 * @uses PMA_DBI_free_result()
210 * @access protected
211 * @return array the relation parameters for the current user
213 function PMA__getRelationsParam()
215 $cfgRelation = array();
216 $cfgRelation['relwork'] = false;
217 $cfgRelation['displaywork'] = false;
218 $cfgRelation['bookmarkwork']= false;
219 $cfgRelation['pdfwork'] = false;
220 $cfgRelation['commwork'] = false;
221 $cfgRelation['mimework'] = false;
222 $cfgRelation['historywork'] = false;
223 $cfgRelation['trackingwork'] = false;
224 $cfgRelation['designerwork'] = false;
225 $cfgRelation['userconfigwork'] = false;
226 $cfgRelation['allworks'] = false;
227 $cfgRelation['user'] = null;
228 $cfgRelation['db'] = null;
230 if ($GLOBALS['server'] == 0 || empty($GLOBALS['cfg']['Server']['pmadb'])
231 || ! PMA_DBI_select_db($GLOBALS['cfg']['Server']['pmadb'], $GLOBALS['controllink'])) {
232 // No server selected -> no bookmark table
233 // we return the array with the falses in it,
234 // to avoid some 'Unitialized string offset' errors later
235 $GLOBALS['cfg']['Server']['pmadb'] = false;
236 return $cfgRelation;
240 $cfgRelation['user'] = $GLOBALS['cfg']['Server']['user'];
241 $cfgRelation['db'] = $GLOBALS['cfg']['Server']['pmadb'];
243 // Now I just check if all tables that i need are present so I can for
244 // example enable relations but not pdf...
245 // I was thinking of checking if they have all required columns but I
246 // fear it might be too slow
248 $tab_query = 'SHOW TABLES FROM ' . PMA_backquote($GLOBALS['cfg']['Server']['pmadb']);
249 $tab_rs = PMA_query_as_controluser($tab_query, false, PMA_DBI_QUERY_STORE);
251 if (! $tab_rs) {
252 // query failed ... ?
253 //$GLOBALS['cfg']['Server']['pmadb'] = false;
254 return $cfgRelation;
257 while ($curr_table = @PMA_DBI_fetch_row($tab_rs)) {
258 if ($curr_table[0] == $GLOBALS['cfg']['Server']['bookmarktable']) {
259 $cfgRelation['bookmark'] = $curr_table[0];
260 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['relation']) {
261 $cfgRelation['relation'] = $curr_table[0];
262 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_info']) {
263 $cfgRelation['table_info'] = $curr_table[0];
264 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['table_coords']) {
265 $cfgRelation['table_coords'] = $curr_table[0];
266 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['designer_coords']) {
267 $cfgRelation['designer_coords'] = $curr_table[0];
268 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['column_info']) {
269 $cfgRelation['column_info'] = $curr_table[0];
270 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['pdf_pages']) {
271 $cfgRelation['pdf_pages'] = $curr_table[0];
272 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['history']) {
273 $cfgRelation['history'] = $curr_table[0];
274 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['tracking']) {
275 $cfgRelation['tracking'] = $curr_table[0];
276 } elseif ($curr_table[0] == $GLOBALS['cfg']['Server']['userconfig']) {
277 $cfgRelation['userconfig'] = $curr_table[0];
279 } // end while
280 PMA_DBI_free_result($tab_rs);
282 if (isset($cfgRelation['relation'])) {
283 $cfgRelation['relwork'] = true;
284 if (isset($cfgRelation['table_info'])) {
285 $cfgRelation['displaywork'] = true;
288 if (isset($cfgRelation['table_coords']) && isset($cfgRelation['pdf_pages'])) {
289 $cfgRelation['pdfwork'] = true;
291 if (isset($cfgRelation['column_info'])) {
292 $cfgRelation['commwork'] = true;
294 if ($GLOBALS['cfg']['Server']['verbose_check']) {
295 $mime_query = 'SHOW FIELDS FROM '
296 . PMA_backquote($cfgRelation['db']) . '.'
297 . PMA_backquote($cfgRelation['column_info']);
298 $mime_rs = PMA_query_as_controluser($mime_query, false);
300 $mime_field_mimetype = false;
301 $mime_field_transformation = false;
302 $mime_field_transformation_options = false;
303 while ($curr_mime_field = @PMA_DBI_fetch_row($mime_rs)) {
304 if ($curr_mime_field[0] == 'mimetype') {
305 $mime_field_mimetype = true;
306 } elseif ($curr_mime_field[0] == 'transformation') {
307 $mime_field_transformation = true;
308 } elseif ($curr_mime_field[0] == 'transformation_options') {
309 $mime_field_transformation_options = true;
312 PMA_DBI_free_result($mime_rs);
314 if ($mime_field_mimetype
315 && $mime_field_transformation
316 && $mime_field_transformation_options) {
317 $cfgRelation['mimework'] = true;
319 } else {
320 $cfgRelation['mimework'] = true;
324 if (isset($cfgRelation['history'])) {
325 $cfgRelation['historywork'] = true;
328 if (isset($cfgRelation['tracking'])) {
329 $cfgRelation['trackingwork'] = true;
332 if (isset($cfgRelation['userconfig'])) {
333 $cfgRelation['userconfigwork'] = true;
336 // we do not absolutely need that the internal relations or the PDF
337 // schema feature be activated
338 if (isset($cfgRelation['designer_coords'])) {
339 $cfgRelation['designerwork'] = true;
342 if (isset($cfgRelation['bookmark'])) {
343 $cfgRelation['bookmarkwork'] = true;
346 if ($cfgRelation['relwork'] && $cfgRelation['displaywork']
347 && $cfgRelation['pdfwork'] && $cfgRelation['commwork']
348 && $cfgRelation['mimework'] && $cfgRelation['historywork']
349 && $cfgRelation['trackingwork'] && $cfgRelation['userconfigwork']
350 && $cfgRelation['bookmarkwork'] && $cfgRelation['designerwork']) {
351 $cfgRelation['allworks'] = true;
354 return $cfgRelation;
355 } // end of the 'PMA_getRelationsParam()' function
358 * Gets all Relations to foreign tables for a given table or
359 * optionally a given column in a table
361 * @access public
362 * @uses $GLOBALS['controllink']
363 * @uses $GLOBALS['information_schema_relations']
364 * @uses PMA_getRelationsParam()
365 * @uses PMA_backquote()
366 * @uses PMA_sqlAddslashes()
367 * @uses PMA_DBI_fetch_result()
368 * @uses PMA_DBI_fetch_value()
369 * @uses PMA_SQP_analyze()
370 * @uses PMA_SQP_parse()
371 * @uses count()
372 * @uses strlen()
373 * @param string $db the name of the db to check for
374 * @param string $table the name of the table to check for
375 * @param string $column the name of the column to check for
376 * @param string $source the source for foreign key information
377 * @return array db,table,column
379 function PMA_getForeigners($db, $table, $column = '', $source = 'both')
381 $cfgRelation = PMA_getRelationsParam();
382 $foreign = array();
384 if ($cfgRelation['relwork'] && ($source == 'both' || $source == 'internal')) {
385 $rel_query = '
386 SELECT `master_field`,
387 `foreign_db`,
388 `foreign_table`,
389 `foreign_field`
390 FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation']) . '
391 WHERE `master_db` = \'' . PMA_sqlAddslashes($db) . '\'
392 AND `master_table` = \'' . PMA_sqlAddslashes($table) . '\' ';
393 if (strlen($column)) {
394 $rel_query .= ' AND `master_field` = \'' . PMA_sqlAddslashes($column) . '\'';
396 $foreign = PMA_DBI_fetch_result($rel_query, 'master_field', null, $GLOBALS['controllink']);
399 if (($source == 'both' || $source == 'foreign') && strlen($table)) {
400 $show_create_table_query = 'SHOW CREATE TABLE '
401 . PMA_backquote($db) . '.' . PMA_backquote($table);
402 $show_create_table = PMA_DBI_fetch_value($show_create_table_query, 0, 1);
403 $analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
405 foreach ($analyzed_sql[0]['foreign_keys'] as $one_key) {
406 // The analyzer may return more than one column name in the
407 // index list or the ref_index_list; if this happens,
408 // the current logic just discards the whole index; having
409 // more than one index field is currently unsupported (see FAQ 3.6)
410 if (count($one_key['index_list']) == 1) {
411 foreach ($one_key['index_list'] as $i => $field) {
412 // If a foreign key is defined in the 'internal' source (pmadb)
413 // and as a native foreign key, we won't get it twice
414 // if $source='both' because we use $field as key
416 // The parser looks for a CONSTRAINT clause just before
417 // the FOREIGN KEY clause. It finds it (as output from
418 // SHOW CREATE TABLE) in MySQL 4.0.13, but not in older
419 // versions like 3.23.58.
420 // In those cases, the FOREIGN KEY parsing will put numbers
421 // like -1, 0, 1... instead of the constraint number.
423 if (isset($one_key['constraint'])) {
424 $foreign[$field]['constraint'] = $one_key['constraint'];
427 if (isset($one_key['ref_db_name'])) {
428 $foreign[$field]['foreign_db'] = $one_key['ref_db_name'];
429 } else {
430 $foreign[$field]['foreign_db'] = $db;
432 $foreign[$field]['foreign_table'] = $one_key['ref_table_name'];
433 $foreign[$field]['foreign_field'] = $one_key['ref_index_list'][$i];
434 if (isset($one_key['on_delete'])) {
435 $foreign[$field]['on_delete'] = $one_key['on_delete'];
437 if (isset($one_key['on_update'])) {
438 $foreign[$field]['on_update'] = $one_key['on_update'];
446 * Emulating relations for some information_schema tables
448 if ($db == 'information_schema'
449 && ($source == 'internal' || $source == 'both')) {
450 require_once './libraries/information_schema_relations.lib.php';
452 if (isset($GLOBALS['information_schema_relations'][$table])) {
453 foreach ($GLOBALS['information_schema_relations'][$table] as $field => $relations) {
454 if ((! strlen($column) || $column == $field)
455 && (! isset($foreign[$field]) || ! strlen($foreign[$field]))) {
456 $foreign[$field] = $relations;
462 return $foreign;
463 } // end of the 'PMA_getForeigners()' function
466 * Gets the display field of a table
468 * @access public
469 * @uses $GLOBALS['controllink']
470 * @uses PMA_getRelationsParam()
471 * @uses PMA_backquote()
472 * @uses PMA_sqlAddslashes()
473 * @uses PMA_DBI_fetch_single_row()
474 * @uses trim()
475 * @param string $db the name of the db to check for
476 * @param string $table the name of the table to check for
477 * @return string field name
479 function PMA_getDisplayField($db, $table)
481 $cfgRelation = PMA_getRelationsParam();
484 * Try to fetch the display field from DB.
486 if ($cfgRelation['displaywork']) {
487 $disp_query = '
488 SELECT `display_field`
489 FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['table_info']) . '
490 WHERE `db_name` = \'' . PMA_sqlAddslashes($db) . '\'
491 AND `table_name` = \'' . PMA_sqlAddslashes($table) . '\'';
493 $row = PMA_DBI_fetch_single_row($disp_query, 'ASSOC', $GLOBALS['controllink']);
494 if (isset($row['display_field'])) {
495 return $row['display_field'];
500 * Emulating the display field for some information_schema tables.
502 if ($db == 'information_schema') {
503 switch ($table) {
504 case 'CHARACTER_SETS': return 'DESCRIPTION';
505 case 'TABLES': return 'TABLE_COMMENT';
510 * No Luck...
512 return false;
514 } // end of the 'PMA_getDisplayField()' function
517 * Gets the comments for all rows of a table or the db itself
519 * @access public
520 * @uses PMA_DBI_get_fields()
521 * @uses PMA_getDbComment()
522 * @param string the name of the db to check for
523 * @param string the name of the table to check for
524 * @return array [field_name] = comment
526 function PMA_getComments($db, $table = '')
528 $comments = array();
530 if ($table != '') {
531 // MySQL native column comments
532 $fields = PMA_DBI_get_fields($db, $table);
533 if ($fields) {
534 foreach ($fields as $key => $field) {
535 if (! empty($field['Comment'])) {
536 $comments[$field['Field']] = $field['Comment'];
540 } else {
541 $comments[] = PMA_getDbComment($db);
544 return $comments;
545 } // end of the 'PMA_getComments()' function
548 * Gets the comment for a db
550 * @access public
551 * @uses PMA_DBI_QUERY_STORE
552 * @uses PMA_DBI_num_rows()
553 * @uses PMA_DBI_fetch_assoc()
554 * @uses PMA_DBI_free_result()
555 * @uses PMA_getRelationsParam()
556 * @uses PMA_backquote()
557 * @uses PMA_sqlAddslashes()
558 * @uses PMA_query_as_controluser()
559 * @uses strlen()
560 * @param string the name of the db to check for
561 * @return string comment
563 function PMA_getDbComment($db)
565 $cfgRelation = PMA_getRelationsParam();
566 $comment = '';
568 if ($cfgRelation['commwork']) {
569 // pmadb internal db comment
570 $com_qry = "
571 SELECT `comment`
572 FROM " . PMA_backquote($cfgRelation['db']) . "." . PMA_backquote($cfgRelation['column_info']) . "
573 WHERE db_name = '" . PMA_sqlAddslashes($db) . "'
574 AND table_name = ''
575 AND column_name = '(db_comment)'";
576 $com_rs = PMA_query_as_controluser($com_qry, true, PMA_DBI_QUERY_STORE);
578 if ($com_rs && PMA_DBI_num_rows($com_rs) > 0) {
579 $row = PMA_DBI_fetch_assoc($com_rs);
580 $comment = $row['comment'];
582 PMA_DBI_free_result($com_rs);
585 return $comment;
586 } // end of the 'PMA_getDbComment()' function
589 * Gets the comment for a db
591 * @access public
592 * @uses PMA_DBI_QUERY_STORE
593 * @uses PMA_DBI_num_rows()
594 * @uses PMA_DBI_fetch_assoc()
595 * @uses PMA_DBI_free_result()
596 * @uses PMA_getRelationsParam()
597 * @uses PMA_backquote()
598 * @uses PMA_sqlAddslashes()
599 * @uses PMA_query_as_controluser()
600 * @uses strlen()
601 * @param string the name of the db to check for
602 * @return string comment
604 function PMA_getDbComments()
606 $cfgRelation = PMA_getRelationsParam();
607 $comments = array();
609 if ($cfgRelation['commwork']) {
610 // pmadb internal db comment
611 $com_qry = "
612 SELECT `db_name`, `comment`
613 FROM " . PMA_backquote($cfgRelation['db']) . "." . PMA_backquote($cfgRelation['column_info']) . "
614 WHERE `column_name` = '(db_comment)'";
615 $com_rs = PMA_query_as_controluser($com_qry, true, PMA_DBI_QUERY_STORE);
617 if ($com_rs && PMA_DBI_num_rows($com_rs) > 0) {
618 while ($row = PMA_DBI_fetch_assoc($com_rs)) {
619 $comments[$row['db_name']] = $row['comment'];
622 PMA_DBI_free_result($com_rs);
625 return $comments;
626 } // end of the 'PMA_getDbComments()' function
629 * Set a database comment to a certain value.
631 * @uses PMA_getRelationsParam()
632 * @uses PMA_backquote()
633 * @uses PMA_sqlAddslashes()
634 * @uses PMA_query_as_controluser()
635 * @uses strlen()
636 * @access public
637 * @param string $db the name of the db
638 * @param string $comment the value of the column
639 * @return boolean true, if comment-query was made.
641 function PMA_setDbComment($db, $comment = '')
643 $cfgRelation = PMA_getRelationsParam();
645 if (! $cfgRelation['commwork']) {
646 return false;
649 if (strlen($comment)) {
650 $upd_query = "
651 INSERT INTO
652 " . PMA_backquote($cfgRelation['db']) . "." . PMA_backquote($cfgRelation['column_info']) . "
653 (`db_name`, `table_name`, `column_name`, `comment`)
654 VALUES (
655 '" . PMA_sqlAddslashes($db) . "',
657 '(db_comment)',
658 '" . PMA_sqlAddslashes($comment) . "')
659 ON DUPLICATE KEY UPDATE
660 `comment` = '" . PMA_sqlAddslashes($comment) . "'";
661 } else {
662 $upd_query = '
663 DELETE FROM
664 ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['column_info']) . '
665 WHERE `db_name` = \'' . PMA_sqlAddslashes($db) . '\'
666 AND `table_name` = \'\'
667 AND `column_name` = \'(db_comment)\'';
670 if (isset($upd_query)){
671 return PMA_query_as_controluser($upd_query);
674 return false;
675 } // end of 'PMA_setDbComment()' function
678 * Set a SQL history entry
680 * @uses $_SESSION['sql_history']
681 * @uses $cfg['QueryHistoryDB']
682 * @uses $cfg['QueryHistoryMax']
683 * @uses PMA_getRelationsParam()
684 * @uses PMA_query_as_controluser()
685 * @uses PMA_backquote()
686 * @uses PMA_sqlAddslashes()
687 * @uses count()
688 * @uses md5()
689 * @uses array_shift()
690 * @param string $db the name of the db
691 * @param string $table the name of the table
692 * @param string $username the username
693 * @param string $sqlquery the sql query
694 * @access public
696 function PMA_setHistory($db, $table, $username, $sqlquery)
698 if (strlen($sqlquery) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
699 return;
702 $cfgRelation = PMA_getRelationsParam();
704 if (! isset($_SESSION['sql_history'])) {
705 $_SESSION['sql_history'] = array();
708 $key = md5($sqlquery . $db . $table);
710 if (isset($_SESSION['sql_history'][$key])) {
711 unset($_SESSION['sql_history'][$key]);
714 $_SESSION['sql_history'][$key] = array(
715 'db' => $db,
716 'table' => $table,
717 'sqlquery' => $sqlquery,
720 if (count($_SESSION['sql_history']) > $GLOBALS['cfg']['QueryHistoryMax']) {
721 // history should not exceed a maximum count
722 array_shift($_SESSION['sql_history']);
725 if (! $cfgRelation['historywork'] || ! $GLOBALS['cfg']['QueryHistoryDB']) {
726 return;
729 PMA_query_as_controluser('
730 INSERT INTO
731 ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['history']) . '
732 (`username`,
733 `db`,
734 `table`,
735 `timevalue`,
736 `sqlquery`)
737 VALUES
738 (\'' . PMA_sqlAddslashes($username) . '\',
739 \'' . PMA_sqlAddslashes($db) . '\',
740 \'' . PMA_sqlAddslashes($table) . '\',
741 NOW(),
742 \'' . PMA_sqlAddslashes($sqlquery) . '\')');
743 } // end of 'PMA_setHistory()' function
746 * Gets a SQL history entry
748 * @uses $_SESSION['sql_history']
749 * @uses $GLOBALS['controllink']
750 * @uses PMA_getRelationsParam()
751 * @uses PMA_backquote()
752 * @uses PMA_sqlAddslashes()
753 * @uses PMA_DBI_fetch_result()
754 * @uses array_reverse()
755 * @param string $username the username
756 * @return array list of history items
757 * @access public
759 function PMA_getHistory($username)
761 $cfgRelation = PMA_getRelationsParam();
763 if (! $cfgRelation['historywork']) {
764 return false;
767 $hist_query = '
768 SELECT `db`,
769 `table`,
770 `sqlquery`
771 FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['history']) . '
772 WHERE `username` = \'' . PMA_sqlAddslashes($username) . '\'
773 ORDER BY `id` DESC';
775 return PMA_DBI_fetch_result($hist_query, null, null, $GLOBALS['controllink']);
776 } // end of 'PMA_getHistory()' function
779 * purges SQL history
781 * deletes entries that exceeds $cfg['QueryHistoryMax'], oldest first, for the
782 * given user
784 * @uses $cfg['QueryHistoryMax']
785 * @uses $cfg['QueryHistoryDB']
786 * @uses $GLOBALS['controllink']
787 * @uses PMA_backquote()
788 * @uses PMA_sqlAddSlashes()
789 * @uses PMA_query_as_controluser()
790 * @uses PMA_DBI_fetch_value()
791 * @param string $username the username
792 * @access public
794 function PMA_purgeHistory($username)
796 $cfgRelation = PMA_getRelationsParam();
797 if (! $GLOBALS['cfg']['QueryHistoryDB'] || ! $cfgRelation['historywork']) {
798 return;
801 if (! $cfgRelation['historywork']) {
802 return;
805 $search_query = '
806 SELECT `timevalue`
807 FROM ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['history']) . '
808 WHERE `username` = \'' . PMA_sqlAddSlashes($username) . '\'
809 ORDER BY `timevalue` DESC
810 LIMIT ' . $GLOBALS['cfg']['QueryHistoryMax'] . ', 1';
812 if ($max_time = PMA_DBI_fetch_value($search_query, 0, 0, $GLOBALS['controllink'])) {
813 PMA_query_as_controluser('
814 DELETE FROM
815 ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['history']) . '
816 WHERE `username` = \'' . PMA_sqlAddSlashes($username) . '\'
817 AND `timevalue` <= \'' . $max_time . '\'');
819 } // end of 'PMA_purgeHistory()' function
822 * Prepares the dropdown for one mode
824 * @uses $cfg['LimitChars']
825 * @uses $cfg['NaturalOrder']
826 * @uses PMA_strlen()
827 * @uses htmlspecialchars()
828 * @uses substr()
829 * @uses uksort()
830 * @uses ksort()
831 * @uses natcasesort()
832 * @uses asort()
833 * @param array $foreign the keys and values for foreigns
834 * @param string $data the current data of the dropdown
835 * @param string $mode the needed mode
837 * @return array the <option value=""><option>s
839 * @access protected
841 function PMA__foreignDropdownBuild($foreign, $data, $mode)
843 $reloptions = array();
845 // id-only is a special mode used when no foreign display column
846 // is available
847 if ($mode == 'id-content' || $mode == 'id-only') {
848 // sort for id-content
849 if ($GLOBALS['cfg']['NaturalOrder']) {
850 uksort($foreign, 'strnatcasecmp');
851 } else {
852 ksort($foreign);
854 } elseif ($mode == 'content-id') {
855 // sort for content-id
856 if ($GLOBALS['cfg']['NaturalOrder']) {
857 natcasesort($foreign);
858 } else {
859 asort($foreign);
863 foreach ($foreign as $key => $value) {
864 if (PMA_strlen($value) <= $GLOBALS['cfg']['LimitChars']) {
865 $vtitle = '';
866 $value = htmlspecialchars($value);
867 } else {
868 $vtitle = htmlspecialchars($value);
869 $value = htmlspecialchars(substr($value, 0, $GLOBALS['cfg']['LimitChars']) . '...');
872 $reloption = '<option value="' . htmlspecialchars($key) . '"';
873 if ($vtitle != '') {
874 $reloption .= ' title="' . $vtitle . '"';
877 if ((string) $key == (string) $data) {
878 $reloption .= ' selected="selected"';
881 if ($mode == 'content-id') {
882 $reloptions[] = $reloption . '>' . $value . '&nbsp;-&nbsp;' . htmlspecialchars($key) . '</option>';
883 } elseif ($mode == 'id-content') {
884 $reloptions[] = $reloption . '>' . htmlspecialchars($key) . '&nbsp;-&nbsp;' . $value . '</option>';
885 } elseif ($mode == 'id-only') {
886 $reloptions[] = $reloption . '>' . htmlspecialchars($key) . '</option>';
888 } // end foreach
890 return $reloptions;
891 } // end of 'PMA__foreignDropdownBuild' function
894 * Outputs dropdown with values of foreign fields
896 * @uses $cfg['ForeignKeyMaxLimit']
897 * @uses $cfg['ForeignKeyDropdownOrder']
898 * @uses PMA__foreignDropdownBuild()
899 * @uses PMA_isValid()
900 * @uses implode()
901 * @param array array of the displayed row
902 * @param string the foreign field
903 * @param string the foreign field to display
904 * @param string the current data of the dropdown (field in row)
905 * @return string the <option value=""><option>s
906 * @access public
908 function PMA_foreignDropdown($disp_row, $foreign_field, $foreign_display, $data,
909 $max = null)
911 if (null === $max) {
912 $max = $GLOBALS['cfg']['ForeignKeyMaxLimit'];
915 $foreign = array();
917 // collect the data
918 foreach ($disp_row as $relrow) {
919 $key = $relrow[$foreign_field];
921 // if the display field has been defined for this foreign table
922 if ($foreign_display) {
923 $value = $relrow[$foreign_display];
924 } else {
925 $value = '';
926 } // end if ($foreign_display)
928 $foreign[$key] = $value;
929 } // end foreach
931 // put the dropdown sections in correct order
932 $top = array();
933 $bottom = array();
934 if ($foreign_display) {
935 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'], 'array')) {
936 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][0])) {
937 $top = PMA__foreignDropdownBuild($foreign, $data,
938 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][0]);
940 if (PMA_isValid($GLOBALS['cfg']['ForeignKeyDropdownOrder'][1])) {
941 $bottom = PMA__foreignDropdownBuild($foreign, $data,
942 $GLOBALS['cfg']['ForeignKeyDropdownOrder'][1]);
944 } else {
945 $top = PMA__foreignDropdownBuild($foreign, $data, 'id-content');
946 $bottom = PMA__foreignDropdownBuild($foreign, $data, 'content-id');
948 } else {
949 $top = PMA__foreignDropdownBuild($foreign, $data, 'id-only');
952 // beginning of dropdown
953 $ret = '<option value="">&nbsp;</option>';
954 $top_count = count($top);
955 if ($max == -1 || $top_count < $max) {
956 $ret .= implode('', $top);
957 if ($foreign_display && $top_count > 0) {
958 // this empty option is to visually mark the beginning of the
959 // second series of values (bottom)
960 $ret .= '<option value="">&nbsp;</option>';
963 if ($foreign_display) {
964 $ret .= implode('', $bottom);
967 return $ret;
968 } // end of 'PMA_foreignDropdown()' function
971 * Gets foreign keys in preparation for a drop-down selector
973 * @uses PMA_Table::countRecords()
974 * @uses PMA_backquote()
975 * @uses PMA_getDisplayField()
976 * @uses PMA_sqlAddslashes()
977 * @uses PMA_DBI_fetch_value()
978 * @uses PMA_DBI_free_result()
979 * @uses PMA_DBI_query()
980 * @uses PMA_DBI_num_rows()
981 * @uses PMA_DBI_fetch_assoc()
982 * @param array array of the foreign keys
983 * @param string the foreign field name
984 * @param bool whether to override the total
985 * @param string a possible filter
986 * @param string a possible LIMIT clause
987 * @return array data about the foreign keys
988 * @access public
991 function PMA_getForeignData($foreigners, $field, $override_total, $foreign_filter, $foreign_limit)
993 // we always show the foreign field in the drop-down; if a display
994 // field is defined, we show it besides the foreign field
995 $foreign_link = false;
996 if ($foreigners && isset($foreigners[$field])) {
997 $foreigner = $foreigners[$field];
998 $foreign_db = $foreigner['foreign_db'];
999 $foreign_table = $foreigner['foreign_table'];
1000 $foreign_field = $foreigner['foreign_field'];
1002 // Count number of rows in the foreign table. Currently we do
1003 // not use a drop-down if more than 200 rows in the foreign table,
1004 // for speed reasons and because we need a better interface for this.
1006 // We could also do the SELECT anyway, with a LIMIT, and ensure that
1007 // the current value of the field is one of the choices.
1009 $the_total = PMA_Table::countRecords($foreign_db, $foreign_table);
1011 if ($override_total == true || $the_total < $GLOBALS['cfg']['ForeignKeyMaxLimit']) {
1012 // foreign_display can be FALSE if no display field defined:
1013 $foreign_display = PMA_getDisplayField($foreign_db, $foreign_table);
1015 $f_query_main = 'SELECT ' . PMA_backquote($foreign_field)
1016 . (($foreign_display == FALSE) ? '' : ', ' . PMA_backquote($foreign_display));
1017 $f_query_from = ' FROM ' . PMA_backquote($foreign_db) . '.' . PMA_backquote($foreign_table);
1018 $f_query_filter = empty($foreign_filter) ? '' : ' WHERE ' . PMA_backquote($foreign_field)
1019 . ' LIKE "%' . PMA_sqlAddslashes($foreign_filter, TRUE) . '%"'
1020 . (($foreign_display == FALSE) ? '' : ' OR ' . PMA_backquote($foreign_display)
1021 . ' LIKE "%' . PMA_sqlAddslashes($foreign_filter, TRUE) . '%"'
1023 $f_query_order = ($foreign_display == FALSE) ? '' :' ORDER BY ' . PMA_backquote($foreign_table) . '.' . PMA_backquote($foreign_display);
1024 $f_query_limit = isset($foreign_limit) ? $foreign_limit : '';
1026 if (!empty($foreign_filter)) {
1027 $res = PMA_DBI_query('SELECT COUNT(*)' . $f_query_from . $f_query_filter);
1028 if ($res) {
1029 $the_total = PMA_DBI_fetch_value($res);
1030 @PMA_DBI_free_result($res);
1031 } else {
1032 $the_total = 0;
1036 $disp = PMA_DBI_query($f_query_main . $f_query_from . $f_query_filter . $f_query_order . $f_query_limit);
1037 if ($disp && PMA_DBI_num_rows($disp) > 0) {
1038 // If a resultset has been created, pre-cache it in the $disp_row array
1039 // This helps us from not needing to use mysql_data_seek by accessing a pre-cached
1040 // PHP array. Usually those resultsets are not that big, so a performance hit should
1041 // not be expected.
1042 $disp_row = array();
1043 while ($single_disp_row = @PMA_DBI_fetch_assoc($disp)) {
1044 $disp_row[] = $single_disp_row;
1046 @PMA_DBI_free_result($disp);
1048 } else {
1049 $disp_row = null;
1050 $foreign_link = true;
1052 } // end if $foreigners
1054 $foreignData['foreign_link'] = $foreign_link;
1055 $foreignData['the_total'] = isset($the_total) ? $the_total : null;
1056 $foreignData['foreign_display'] = isset($foreign_display) ? $foreign_display : null;
1057 $foreignData['disp_row'] = isset($disp_row) ? $disp_row : null;
1058 $foreignData['foreign_field'] = isset($foreign_field) ? $foreign_field : null;
1059 return $foreignData;
1060 } // end of 'PMA_getForeignData()' function
1063 * Finds all related tables
1065 * @uses $GLOBALS['controllink']
1066 * @uses $GLOBALS['cfgRelation']
1067 * @uses $GLOBALS['db']
1068 * @param string whether to go from master to foreign or vice versa
1069 * @return boolean always TRUE
1070 * @global array $tab_left the list of tables that we still couldn't connect
1071 * @global array $tab_know the list of allready connected tables
1072 * @global string $fromclause
1074 * @access private
1076 function PMA_getRelatives($from)
1078 global $tab_left, $tab_know, $fromclause;
1080 if ($from == 'master') {
1081 $to = 'foreign';
1082 } else {
1083 $to = 'master';
1085 $in_know = '(\'' . implode('\', \'', $tab_know) . '\')';
1086 $in_left = '(\'' . implode('\', \'', $tab_left) . '\')';
1088 $rel_query = 'SELECT *'
1089 . ' FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db'])
1090 . '.' . PMA_backquote($GLOBALS['cfgRelation']['relation'])
1091 . ' WHERE ' . $from . '_db = \'' . PMA_sqlAddslashes($GLOBALS['db']) . '\''
1092 . ' AND ' . $to . '_db = \'' . PMA_sqlAddslashes($GLOBALS['db']) . '\''
1093 . ' AND ' . $from . '_table IN ' . $in_know
1094 . ' AND ' . $to . '_table IN ' . $in_left;
1095 $relations = @PMA_DBI_query($rel_query, $GLOBALS['controllink']);
1096 while ($row = PMA_DBI_fetch_assoc($relations)) {
1097 $found_table = $row[$to . '_table'];
1098 if (isset($tab_left[$found_table])) {
1099 $fromclause
1100 .= "\n" . ' LEFT JOIN '
1101 . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($row[$to . '_table']) . ' ON '
1102 . PMA_backquote($row[$from . '_table']) . '.'
1103 . PMA_backquote($row[$from . '_field']) . ' = '
1104 . PMA_backquote($row[$to . '_table']) . '.'
1105 . PMA_backquote($row[$to . '_field']) . ' ';
1106 $tab_know[$found_table] = $found_table;
1107 unset($tab_left[$found_table]);
1109 } // end while
1111 return true;
1112 } // end of the "PMA_getRelatives()" function
1115 * Rename a field in relation tables
1117 * usually called after a field in a table was renamed in tbl_alter.php
1119 * @uses PMA_getRelationsParam()
1120 * @uses PMA_backquote()
1121 * @uses PMA_sqlAddslashes()
1122 * @uses PMA_query_as_controluser()
1123 * @param string $db
1124 * @param string $table
1125 * @param string $field
1126 * @param string $new_name
1128 function PMA_REL_renameField($db, $table, $field, $new_name)
1130 $cfgRelation = PMA_getRelationsParam();
1132 if ($cfgRelation['displaywork']) {
1133 $table_query = 'UPDATE ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['table_info'])
1134 . ' SET display_field = \'' . PMA_sqlAddslashes($new_name) . '\''
1135 . ' WHERE db_name = \'' . PMA_sqlAddslashes($db) . '\''
1136 . ' AND table_name = \'' . PMA_sqlAddslashes($table) . '\''
1137 . ' AND display_field = \'' . PMA_sqlAddslashes($field) . '\'';
1138 PMA_query_as_controluser($table_query);
1141 if ($cfgRelation['relwork']) {
1142 $table_query = 'UPDATE ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation'])
1143 . ' SET master_field = \'' . PMA_sqlAddslashes($new_name) . '\''
1144 . ' WHERE master_db = \'' . PMA_sqlAddslashes($db) . '\''
1145 . ' AND master_table = \'' . PMA_sqlAddslashes($table) . '\''
1146 . ' AND master_field = \'' . PMA_sqlAddslashes($field) . '\'';
1147 PMA_query_as_controluser($table_query);
1149 $table_query = 'UPDATE ' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation'])
1150 . ' SET foreign_field = \'' . PMA_sqlAddslashes($new_name) . '\''
1151 . ' WHERE foreign_db = \'' . PMA_sqlAddslashes($db) . '\''
1152 . ' AND foreign_table = \'' . PMA_sqlAddslashes($table) . '\''
1153 . ' AND foreign_field = \'' . PMA_sqlAddslashes($field) . '\'';
1154 PMA_query_as_controluser($table_query);
1155 } // end if relwork
1159 * Create a PDF page
1161 * @uses PMA_backquote()
1162 * @uses $GLOBALS['cfgRelation']['db']
1163 * @uses PMA_sqlAddslashes()
1164 * @uses PMA_query_as_controluser()
1165 * @uses PMA_DBI_insert_id()
1166 * @uses $GLOBALS['controllink']
1167 * @param string $newpage
1168 * @param array $cfgRelation
1169 * @param string $db
1170 * @param string $query_default_option
1171 * @return string $pdf_page_number
1173 function PMA_REL_create_page($newpage, $cfgRelation, $db, $query_default_option) {
1174 if (! isset($newpage) || $newpage == '') {
1175 $newpage = __('no description');
1177 $ins_query = 'INSERT INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['pdf_pages'])
1178 . ' (db_name, page_descr)'
1179 . ' VALUES (\'' . PMA_sqlAddslashes($db) . '\', \'' . PMA_sqlAddslashes($newpage) . '\')';
1180 PMA_query_as_controluser($ins_query, FALSE, $query_default_option);
1181 return PMA_DBI_insert_id(isset($GLOBALS['controllink']) ? $GLOBALS['controllink'] : '');