1
0
mirror of https://github.com/phpmyadmin/phpmyadmin.git synced 2026-10-31 10:54:46 +03:00

Merge branch 'master' of github.com:thilinaa/phpmyadmin

This commit is contained in:
Thilina Buddika
2012-07-17 20:49:46 +05:30
438 changed files with 259172 additions and 233682 deletions

View File

@@ -41,8 +41,17 @@ VerboseMultiSubmit, ReplaceHelpImg
+ Ajaxified "Create View" functionality
+ [import] New plugin: import mediawiki
+ Add Ajax support to Fast filter in order to search the term in all database tables
- bug #3535015 [navi] DbFilter, TableFilter clear button hidden on Chrome
+ rfe #3528994 [interface] Allow wrapping possibly long values in replication-status table
3.5.2.0 (not yet released)
3.5.3.0 (not yet released)
- bug #3539044 [interface] Browse mode "Show" button gives blank page if no results anymore
- bug #3534979 [interface] Copy Database Ajax feedback vanishes long before copying is done
- bug #3527531 [interface] GC-maxlifetime warning incorrectly displayed
- bug #3526916 [interface] Search fails with JS error when tooltips disabled
- bug #3544366 [interface] Event comments not saved
3.5.2.0 (2012-07-07)
- bug #3521416 [interface] JS error when editing index
- bug #3521313 [core] Call to undefined function __()
- bug #3521016 [edit] NOW() function incorrectly selected
@@ -56,6 +65,9 @@ VerboseMultiSubmit, ReplaceHelpImg
- bug #3531586 [unterface] Add user form prints JSON when user presses enter
- bug #3534121 [config] duplicate line in config.sample.inc.php
- bug #3534311 [interface] Grid editing incorrectly parses ENUM/SET values
- bug #3510196 [core] More clever URL rewriting with ForceSSL
- bug #3539044 [interface] Browse mode "Show" button gives blank page if no results anymore
- bug #3534979 [interface] Copy Database Ajax feedback vanishes long before copying is done
3.5.1.0 (2012-05-03)
- bug #3510784 [edit] Limit clause ignored when sort order is remembered

View File

@@ -1561,7 +1561,7 @@ CREATE DATABASE,ALTER DATABASE,DROP DATABASE</pre>
<dt id="cfg_ShowTooltipAliasDB">$cfg['ShowTooltipAliasDB'] boolean</dt>
<dd>If tool-tips are enabled and a DB comment is set, this will flip the
comment and the real name. That means that if you have a table called
comment and the real name. That means that if you have a database called
'user0001' and add the comment 'MyName' on it, you will see the name
'MyName' used consequently in the left frame and the tool-tip shows
the real name of the DB.</dd>
@@ -2486,8 +2486,10 @@ setfacl -d -m "g:www-data:rwx" tmp
<h3 id="transformationsfiles">3. File structure</h3>
<p> All mimetypes and their transformations are defined through single files in
the directory 'libraries/transformations/'.</p>
<p> All specific transformations for mimetypes are defined through class files in
the directory 'libraries/plugins/transformations/'. Each of them extends
a certain transformation abstract class declared in
libraries/plugins/transformations/abstract.</p>
<p> They are stored in files to ease up customization and easy adding of new
transformations.</p>
@@ -2496,109 +2498,35 @@ setfacl -d -m "g:www-data:rwx" tmp
always work. It makes no sense to apply a transformation to a mimetype the
transform-function doesn't know to handle.</p>
<p> One can, however, use empty mime-types and global transformations which should work
for many mimetypes. You can also use transforms on a different mimetype than what they where built
for, but pay attention to option usage as well as what the transformation does to your
column.</p>
<p> There is a file called '<em>transformations.lib.php</em>' that provides some basic functions
which can be included by any other transform function.</p>
<p> There are 5 possible file names:</p>
<p> The file name convention is
<code>[Mimetype]_[Subtype]_[Transformation Name].class.php</code>,<br />
while the abtract class that it extends has the name
<code>[Transformation Name]TransformationsPlugin</code>.<br /><br />
All of the methods that have to be implemented by a transformations plug-in are: <Br />
<ol>
<li>getMIMEType() and getMIMESubtype() in the main class;</li>
<li>getName(), getInfo() and applyTransformation() in the abstract class it extends.</li>
</ol>
</p>
<p>The getMIMEType(), getMIMESubtype() and getName() methods return the name of the
MIME type, MIME Subtype and transformation accordingly. getInfo() returns the
transformation's description and possible options it may receive and
applyTransformation() is the method that does the actual work of the
transformation plug-in.</p>
<ol><li>A mimetype+subtype transform:<br /><br />
<p> Please see the libraries/plugins/transformations/TEMPLATE and
libraries/plugins/transformations/TEMPLATE_ABSTRACT
files for adding your own transformation plug-in. You can also generate a
new transformation plug-in (with or without the abstract transformation class),
by using
<code>libraries/plugins/transformations/generator_plugin.sh</code> or<br />
<code>libraries/plugins/transformations/generator_main_class.sh</code>.</p>
<code>[mimetype]_[subtype]__[transform].inc.php</code><br /><br />
Please not that mimetype and subtype are separated via '_', which shall
not be contained in their names. The transform function/filename may
contain only characters which cause no problems in the file system as
well as the PHP function naming convention.<br /><br />
The transform function will the be called
'<code>PMA_transform_[mimetype]_[subtype]__[transform]()</code>'.<br /><br />
<strong>Example:</strong><br /><br />
<code>text_html__formatted.inc.php</code><br />
<code>PMA_transform_text_html__formatted()</code></li>
<li>A mimetype (w/o subtype) transform:<br /><br />
<code>[mimetype]__[transform].inc.php</code><br /><br />
Please note that there are no single '_' characters.
The transform function/filename may contain only characters which cause
no problems in the file system as well as the PHP function naming
convention.<br /><br />
The transform function will the be called
'<code>PMA_transform_[mimetype]__[transform]()</code>'.<br /><br />
<strong>Example:</strong><br /><br />
<code>text__formatted.inc.php</code><br />
<code>PMA_transform_text__formatted()</code></li>
<li>A mimetype+subtype without specific transform function<br /><br />
<code>[mimetype]_[subtype].inc.php</code><br /><br />
Please note that there are no '__' characters in the filename. Do not
use special characters in the filename causing problems with the file
system.<br /><br />
No transformation function is defined in the file itself.<br /><br />
<strong>Example:</strong><br /><br />
<code>text_plain.inc.php</code><br />
(No function)</li>
<li>A mimetype (w/o subtype) without specific transform function<br /><br />
<code>[mimetype].inc.php</code><br /><br />
Please note that there are no '_' characters in the filename. Do not use
special characters in the filename causing problems with the file system.
<br /><br />
No transformation function is defined in the file itself.<br /><br />
<strong>Example:</strong><br /><br />
<code>text.inc.php</code><br />
(No function)</li>
<li>A global transform function with no specific mimetype<br /><br />
<code>global__[transform].inc.php</code><br /><br />
The transform function will the be called
'<code>PMA_transform_global__[transform]()</code>'.<br /><br />
<strong>Example:</strong><br /><br />
<code>global__formatted</code><br />
<code>PMA_transform_global__formatted()</code></li>
</ol>
<p> So generally use '_' to split up mimetype and subtype, and '__' to provide a
transform function.</p>
<p> All filenames containing no '__' in themselves are not shown as valid transform
functions in the dropdown.</p>
<p> Please see the libraries/transformations/TEMPLATE file for adding your own transform
function. See the libraries/transformations/TEMPLATE_MIMETYPE for adding a mimetype
without a transform function.</p>
<p> To create a new transform function please see
<code>libraries/transformations/template_generator.sh</code>.
To create a new, empty mimetype please see
<code>libraries/transformations/template_generator_mimetype.sh</code>.</p>
<p> A transform function always gets passed three variables:</p>
<p> The applyTransformation() method always gets passed three variables:</p>
<ol><li><strong>$buffer</strong> - Contains the text inside of the column. This is the text,
you want to transform.</li>
@@ -2615,18 +2543,6 @@ setfacl -d -m "g:www-data:rwx" tmp
column (i.e. 'text/plain', 'image/jpeg' etc.)</li>
</ol>
<p> Additionally you should also provide additional function to provide
information about the transformation to the user. This function should
have same name as transformation function just with appended
<code>_info</code> suffix. This function accepts no parameters and returns
array with information about the transformation. Currently following keys
can be used:
</p>
<dl>
<dt><code>info</code></dt>
<dd>Long description of the transformation.</dd>
</dl>
<!-- FAQ -->
<h2 id="faq">FAQ - Frequently Asked Questions</h2>

View File

@@ -11,7 +11,7 @@ require_once 'libraries/transformations.lib.php';
$field = $_REQUEST['field'];
PMA_checkParameters(array('db', 'table', 'field'));
PMA_CommonFunctions::getInstance()->checkParameters(array('db', 'table', 'field'));
$response = PMA_Response::getInstance();
$response->getFooter()->setMinimal();
@@ -65,7 +65,7 @@ if (is_array($foreignData['disp_row'])) {
$nbTotalPage = @ceil($foreignData['the_total'] / $session_max_rows);
if ($foreignData['the_total'] > $GLOBALS['cfg']['MaxRows']) {
$gotopage = PMA_pageselector(
$gotopage = PMA_CommonFunctions::getInstance()->pageselector(
$session_max_rows,
$pageNow,
$nbTotalPage,

View File

@@ -29,7 +29,7 @@ foreach ($post_params as $one_post_param) {
}
}
PMA_checkParameters(array('new_db'));
PMA_CommonFunctions::getInstance()->checkParameters(array('new_db'));
/**
* Defines the url to return to in case of error in a sql statement
@@ -39,7 +39,7 @@ $err_url = 'main.php?' . PMA_generate_common_url();
/**
* Builds and executes the db creation sql query
*/
$sql_query = 'CREATE DATABASE ' . PMA_backquote($new_db);
$sql_query = 'CREATE DATABASE ' . PMA_CommonFunctions::getInstance()->backquote($new_db);
if (! empty($db_collation)) {
list($db_charset) = explode('_', $db_collation);
if (in_array($db_charset, $mysql_charsets)
@@ -135,7 +135,12 @@ if (! $result) {
$response = PMA_Response::getInstance();
$response->addJSON('message', $message);
$response->addJSON('new_db_string', $new_db_string);
$response->addJSON('sql_query', PMA_getMessage(null, $sql_query, 'success'));
$response->addJSON(
'sql_query',
PMA_CommonFunctions::getInstance()->getMessage(
null, $sql_query, 'success'
)
);
} else {
include_once '' . $cfg['DefaultTabDatabase'];
}

View File

@@ -27,7 +27,7 @@ require_once 'libraries/Index.class.php';
/**
* Check parameters
*/
PMA_checkParameters(array('db'));
PMA_CommonFunctions::getInstance()->checkParameters(array('db'));
/**
* Defines the url to return to in case of error in a sql statement
@@ -125,7 +125,7 @@ foreach ($tables as $table) {
// http://bugs.mysql.com/20910.
$show_create_table = PMA_DBI_fetch_value(
'SHOW CREATE TABLE ' . PMA_backquote($db) . '.' . PMA_backquote($table),
'SHOW CREATE TABLE ' . PMA_CommonFunctions::getInstance()->backquote($db) . '.' . PMA_CommonFunctions::getInstance()->backquote($table),
0, 1
);
$analyzed_sql = PMA_SQP_analyze(PMA_SQP_parse($show_create_table));
@@ -183,7 +183,9 @@ foreach ($tables as $table) {
if ($row['Null'] == '') {
$row['Null'] = 'NO';
}
$extracted_columnspec = PMA_extractColumnSpec($row['Type']);
$extracted_columnspec
= PMA_CommonFunctions::getInstance()->extractColumnSpec($row['Type']);
// reformat mysql query output
// set or enum types: slashes single quotes inside options
if ('set' == $extracted_columnspec['type'] || 'enum' == $extracted_columnspec['type']) {
@@ -281,6 +283,6 @@ foreach ($tables as $table) {
/**
* Displays the footer
*/
PMA_printButton();
echo PMA_CommonFunctions::getInstance()->getButton();
?>

View File

@@ -10,7 +10,7 @@
* Include required files
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/common.lib.php';
require_once 'libraries/CommonFunctions.class.php';
/**
* Include JavaScript libraries

View File

@@ -20,9 +20,10 @@ require_once 'libraries/mysql_charsets.lib.php';
// add a javascript file for jQuery functions to handle Ajax actions
$response = PMA_Response::getInstance();
$header = $response->getHeader();
$scripts = $header->getScripts();
$header = $response->getHeader();
$scripts = $header->getScripts();
$scripts->addFile('db_operations.js');
$common_functions = PMA_CommonFunctions::getInstance();
/**
* Sets globals from $_REQUEST (we're using GET on ajax, POST otherwise)
@@ -77,7 +78,7 @@ if (strlen($db) && (! empty($db_rename) || ! empty($db_copy))) {
}
}
$local_query = 'CREATE DATABASE ' . PMA_backquote($newname);
$local_query = 'CREATE DATABASE ' . $common_functions->backquote($newname);
if (isset($db_collation)) {
$local_query .= ' DEFAULT' . PMA_generateCharsetQueryPart($db_collation);
}
@@ -134,12 +135,23 @@ if (strlen($db) && (! empty($db_rename) || ! empty($db_copy))) {
$tables_full = PMA_DBI_get_tables_full($db);
$views = array();
require_once "libraries/plugin_interface.lib.php";
// remove all foreign key constraints, otherwise we can get errors
include_once 'libraries/export/sql.php';
$export_sql_plugin = PMA_getPlugin(
"export",
"sql",
'libraries/plugins/export/',
array(
'export_type' => $export_type,
'single_table' => isset($single_table)
)
);
foreach ($tables_full as $each_table => $tmp) {
$sql_constraints = '';
$sql_drop_foreign_keys = '';
$sql_structure = PMA_getTableDef($db, $each_table, "\n", '', false, false);
$sql_structure = $export_sql_plugin->getTableDef(
$db, $each_table, "\n", '', false, false
);
if ($move && ! empty($sql_drop_foreign_keys)) {
PMA_DBI_query($sql_drop_foreign_keys);
}
@@ -157,7 +169,9 @@ if (strlen($db) && (! empty($db_rename) || ! empty($db_copy))) {
if (PMA_Table::isView($db, $each_table)) {
$views[] = $each_table;
// Create stand-in definition to resolve view dependencies
$sql_view_standin = PMA_getTableDefStandIn($db, $each_table, "\n");
$sql_view_standin = $export_sql_plugin->getTableDefStandIn(
$db, $each_table, "\n"
);
PMA_DBI_select_db($newname);
PMA_DBI_query($sql_view_standin);
$GLOBALS['sql_query'] .= "\n" . $sql_view_standin;
@@ -271,7 +285,7 @@ if (strlen($db) && (! empty($db_rename) || ! empty($db_copy))) {
// the db name
$event_names = PMA_DBI_fetch_result(
'SELECT EVENT_NAME FROM information_schema.EVENTS WHERE EVENT_SCHEMA= \''
. PMA_sqlAddSlashes($db, true) . '\';'
. $common_functions->sqlAddSlashes($db, true) . '\';'
);
if ($event_names) {
foreach ($event_names as $event_name) {
@@ -307,7 +321,7 @@ if (strlen($db) && (! empty($db_rename) || ! empty($db_copy))) {
PMA_relationsCleanupDatabase($db);
// if someday the RENAME DATABASE reappears, do not DROP
$local_query = 'DROP DATABASE ' . PMA_backquote($db) . ';';
$local_query = 'DROP DATABASE ' . $common_functions->backquote($db) . ';';
$sql_query .= "\n" . $local_query;
PMA_DBI_query($local_query);
@@ -347,7 +361,10 @@ if (strlen($db) && (! empty($db_rename) || ! empty($db_copy))) {
$response->isSuccess($message->isSuccess());
$response->addJSON('message', $message);
$response->addJSON('newname', $newname);
$response->addJSON('sql_query', PMA_getMessage(null, $sql_query));
$response->addJSON(
'sql_query',
$common_functions->getMessage(null, $sql_query)
);
exit;
}
}
@@ -381,7 +398,7 @@ if (empty($is_info)) {
echo "\n";
if (isset($message)) {
echo PMA_getMessage($message, $sql_query);
echo $common_functions->getMessage($message, $sql_query);
unset($message);
}
}
@@ -444,7 +461,7 @@ if ($db != 'mysql') {
<legend>
<?php
if ($cfg['PropertiesIconic']) {
echo PMA_getImage('b_edit.png');
echo $common_functions->getImage('b_edit.png');
}
echo __('Rename database to') . ':';
?>
@@ -471,27 +488,27 @@ if (($is_superuser || $GLOBALS['cfg']['AllowUserDropDatabase'])
<fieldset class="caution">
<legend><?php
if ($cfg['PropertiesIconic']) {
echo PMA_getImage('b_deltbl.png');
echo $common_functions->getImage('b_deltbl.png');
}
echo __('Remove database');
?></legend>
<ul>
<?php
$this_sql_query = 'DROP DATABASE ' . PMA_backquote($GLOBALS['db']);
$this_sql_query = 'DROP DATABASE ' . $common_functions->backquote($GLOBALS['db']);
$this_url_params = array(
'sql_query' => $this_sql_query,
'back' => 'db_operations.php',
'goto' => 'main.php',
'reload' => '1',
'purge' => '1',
'message_to_show' => sprintf(__('Database %s has been dropped.'), htmlspecialchars(PMA_backquote($db))),
'message_to_show' => sprintf(__('Database %s has been dropped.'), htmlspecialchars($common_functions->backquote($db))),
'db' => null,
);
?>
<li><a href="sql.php<?php echo PMA_generate_common_url($this_url_params); ?>" <?php echo ($GLOBALS['cfg']['AjaxEnable'] ? 'id="drop_db_anchor"' : ''); ?>>
<?php echo __('Drop the database (DROP)'); ?></a>
<?php echo PMA_showMySQLDocu('SQL-Syntax', 'DROP_DATABASE'); ?>
<?php echo $common_functions->showMySQLDocu('SQL-Syntax', 'DROP_DATABASE'); ?>
</li>
</ul>
</fieldset>
@@ -517,7 +534,7 @@ echo __('Remove database');
<legend>
<?php
if ($cfg['PropertiesIconic']) {
echo PMA_getImage('b_edit.png');
echo $common_functions->getImage('b_edit.png');
}
echo __('Copy database to') . ':';
$drop_clause = 'DROP TABLE / DROP VIEW';
@@ -529,7 +546,9 @@ echo __('Remove database');
'structure' => __('Structure only'),
'data' => __('Structure and data'),
'dataonly' => __('Data only'));
echo PMA_getRadioFields('what', $choices, 'data', true);
echo $common_functions->getRadioFields(
'what', $choices, 'data', true
);
unset($choices);
?>
<input type="checkbox" name="create_database_before_copying" value="1"
@@ -583,7 +602,7 @@ echo __('Remove database');
. '<fieldset>' . "\n"
. ' <legend>';
if ($cfg['PropertiesIconic']) {
echo PMA_getImage('s_asci.png');
echo $common_functions->getImage('s_asci.png');
}
echo ' <label for="select_db_collation">' . __('Collation') . ':</label>' . "\n"
. ' </legend>' . "\n"
@@ -625,16 +644,17 @@ if ($cfgRelation['pdfwork'] && $num_tables > 0) { ?>
$test_query = '
SELECT *
FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($cfgRelation['pdf_pages']) . '
WHERE db_name = \'' . PMA_sqlAddSlashes($db) . '\'';
$test_rs = PMA_query_as_controluser($test_query, null, PMA_DBI_QUERY_STORE);
FROM ' . $common_functions->backquote($GLOBALS['cfgRelation']['db'])
. '.' . $common_functions->backquote($cfgRelation['pdf_pages']) . '
WHERE db_name = \'' . $common_functions->sqlAddSlashes($db) . '\'';
$test_rs = PMA_queryAsControlUser($test_query, null, PMA_DBI_QUERY_STORE);
/*
* Export Relational Schema View
*/
echo '<div class="operations_full_width"><fieldset><a href="schema_edit.php?' . $url_query . '">';
if ($cfg['PropertiesIconic']) {
echo PMA_getImage('b_edit.png');
echo $common_functions->getImage('b_edit.png');
}
echo __('Edit or export relational schema') . '</a></fieldset></div>';
} // end if

View File

@@ -13,8 +13,9 @@ require_once 'libraries/common.inc.php';
$response = PMA_Response::getInstance();
$header = $response->getHeader();
$header->enablePrintView();
$common_functions = PMA_CommonFunctions::getInstance();
PMA_checkParameters(array('db'));
$common_functions->checkParameters(array('db'));
/**
* Defines the url to return to in case of error in a sql statement
@@ -35,7 +36,7 @@ $cfgRelation = PMA_getRelationsParam();
// speedup view on locked tables
// Special speedup for newer MySQL Versions (in 4.0 format changed)
if ($cfg['SkipLockedTables'] == true) {
$result = PMA_DBI_query('SHOW OPEN TABLES FROM ' . PMA_backquote($db) . ';');
$result = PMA_DBI_query('SHOW OPEN TABLES FROM ' . PMA_CommonFunctions::getInstance()->backquote($db) . ';');
// Blending out tables in use
if ($result != false && PMA_DBI_num_rows($result) > 0) {
while ($tmp = PMA_DBI_fetch_row($result)) {
@@ -47,11 +48,11 @@ if ($cfg['SkipLockedTables'] == true) {
PMA_DBI_free_result($result);
if (isset($sot_cache)) {
$result = PMA_DBI_query('SHOW TABLES FROM ' . PMA_backquote($db) . ';', null, PMA_DBI_QUERY_STORE);
$result = PMA_DBI_query('SHOW TABLES FROM ' . PMA_CommonFunctions::getInstance()->backquote($db) . ';', null, PMA_DBI_QUERY_STORE);
if ($result != false && PMA_DBI_num_rows($result) > 0) {
while ($tmp = PMA_DBI_fetch_row($result)) {
if (! isset($sot_cache[$tmp[0]])) {
$sts_result = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ' LIKE \'' . PMA_sqlAddSlashes($tmp[0], true) . '\';');
$sts_result = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_CommonFunctions::getInstance()->backquote($db) . ' LIKE \'' . sqlAddSlashes($tmp[0], true) . '\';');
$sts_tmp = PMA_DBI_fetch_assoc($sts_result);
$tables[] = $sts_tmp;
} else { // table in use
@@ -67,7 +68,7 @@ if ($cfg['SkipLockedTables'] == true) {
}
if (! isset($sot_ready)) {
$result = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_backquote($db) . ';');
$result = PMA_DBI_query('SHOW TABLE STATUS FROM ' . PMA_CommonFunctions::getInstance()->backquote($db) . ';');
if (PMA_DBI_num_rows($result) > 0) {
while ($sts_tmp = PMA_DBI_fetch_assoc($result)) {
$tables[] = $sts_tmp;
@@ -132,9 +133,9 @@ if ($num_tables == 0) {
<td class="right">
<?php
if ($merged_size) {
echo '<i>' . PMA_formatNumber($sts_data['TABLE_ROWS'], 0) . '</i>' . "\n";
echo '<i>' . $common_functions->formatNumber($sts_data['TABLE_ROWS'], 0) . '</i>' . "\n";
} else {
echo PMA_formatNumber($sts_data['TABLE_ROWS'], 0) . "\n";
echo $common_functions->formatNumber($sts_data['TABLE_ROWS'], 0) . "\n";
}
?>
</td>
@@ -145,7 +146,8 @@ if ($num_tables == 0) {
if ($cfg['ShowStats']) {
$tblsize = $sts_data['Data_length'] + $sts_data['Index_length'];
$sum_size += $tblsize;
list($formated_size, $unit) = PMA_formatByteDown($tblsize, 3, 1);
list($formated_size, $unit)
= $common_functions->formatByteDown($tblsize, 3, 1);
?>
<td class="right nowrap">
<?php echo $formated_size . ' ' . $unit; ?>
@@ -182,7 +184,7 @@ if ($num_tables == 0) {
?>
<tr>
<td class="right"><?php echo __('Creation') . ': '; ?></td>
<td class="right"><?php echo PMA_localisedDate(strtotime($sts_data['Create_time'])); ?></td>
<td class="right"><?php echo $common_functions->localisedDate(strtotime($sts_data['Create_time'])); ?></td>
</tr>
<?php
}
@@ -191,7 +193,7 @@ if ($num_tables == 0) {
?>
<tr>
<td class="right"><?php echo __('Last update') . ': '; ?></td>
<td class="right"><?php echo PMA_localisedDate(strtotime($sts_data['Update_time'])); ?></td>
<td class="right"><?php echo $common_functions->localisedDate(strtotime($sts_data['Update_time'])); ?></td>
</tr>
<?php
}
@@ -200,7 +202,7 @@ if ($num_tables == 0) {
?>
<tr>
<td class="right"><?php echo __('Last check') . ': '; ?></td>
<td class="right"><?php echo PMA_localisedDate(strtotime($sts_data['Check_time'])); ?></td>
<td class="right"><?php echo $common_functions->localisedDate(strtotime($sts_data['Check_time'])); ?></td>
</tr>
<?php
}
@@ -216,17 +218,18 @@ if ($num_tables == 0) {
?>
<tr>
<th class="center">
<?php echo sprintf(_ngettext('%s table', '%s tables', $num_tables), PMA_formatNumber($num_tables, 0)); ?>
<?php echo sprintf(_ngettext('%s table', '%s tables', $num_tables), $common_functions->formatNumber($num_tables, 0)); ?>
</th>
<th class="right nowrap">
<?php echo PMA_formatNumber($sum_entries, 0); ?>
<?php echo $common_functions->formatNumber($sum_entries, 0); ?>
</th>
<th class="center">
--
</th>
<?php
if ($cfg['ShowStats']) {
list($sum_formated, $unit) = PMA_formatByteDown($sum_size, 3, 1);
list($sum_formated, $unit)
= $common_functions->formatByteDown($sum_size, 3, 1);
?>
<th class="right nowrap">
<?php echo $sum_formated . ' ' . $unit; ?>
@@ -244,7 +247,7 @@ if ($num_tables == 0) {
/**
* Displays the footer
*/
PMA_printButton();
echo $common_functions->getButton();
echo "<div id='PMA_disable_floating_menubar'></div>\n";
?>

View File

@@ -11,11 +11,51 @@
*/
require_once 'libraries/common.inc.php';
/**
* Sets globals from $_POST
*/
$post_params = array(
'Field',
'Show',
'Sort'
);
foreach ($post_params as $one_post_param) {
if (isset($_POST[$one_post_param])) {
$GLOBALS[$one_post_param] = $_POST[$one_post_param];
}
}
/**
* Sets globals from $_POST patterns, for Or* variables
* (additional criteria lines)
*/
$post_patterns = array(
'/^Or/i'
);
foreach (array_keys($_POST) as $post_key) {
foreach ($post_patterns as $one_post_pattern) {
if (preg_match($one_post_pattern, $post_key)) {
$GLOBALS[$post_key] = $_POST[$post_key];
}
}
}
/**
* Initialize some more global variables
*/
$GLOBALS['curField'] = array();
$GLOBALS['curSort'] = array();
$GLOBALS['curShow'] = array();
$GLOBALS['curCriteria'] = array();
$GLOBALS['curAndOrRow'] = array();
$GLOBALS['curAndOrCol'] = array();
/**
* Gets the relation settings
*/
$cfgRelation = PMA_getRelationsParam();
$common_functions = PMA_CommonFunctions::getInstance();
/**
* A query has been submitted -> (maybe) execute it
@@ -96,7 +136,7 @@ if (PMA_isValid($_REQUEST['TableList'], 'array')) {
* Prepares the form
*/
$tbl_result = PMA_DBI_query(
'SHOW TABLES FROM ' . PMA_backquote($db) . ';',
'SHOW TABLES FROM ' . $common_functions->backquote($db) . ';',
null, PMA_DBI_QUERY_STORE
);
$tbl_result_cnt = PMA_DBI_num_rows($tbl_result);
@@ -117,10 +157,10 @@ while (list($tbl) = PMA_DBI_fetch_row($tbl_result)) {
// The fields list per selected tables
if ($tbl_names[$tbl] == ' selected="selected"') {
$each_table = PMA_backquote($tbl);
$each_table = $common_functions->backquote($tbl);
$fld[] = $each_table . '.*';
foreach ($fld_results as $each_field) {
$each_field = $each_table . '.' . PMA_backquote($each_field['Field']);
$each_field = $each_table . '.' . $common_functions->backquote($each_field['Field']);
$fld[] = $each_field;
// increase the width if necessary
@@ -139,32 +179,393 @@ $realwidth = $form_column_width . 'ex';
*/
/**
* Enter description here...
* Provides select options list containing column names
*
* @param array $columns
* @param integer $column_number
* @param string $selected
* @param array $columns All Column Names
* @param integer $column_number Column Number (0,1,2) or more
* @param string $selected Selected criteria column name
*
* @return HTML for select options
*/
function showColumnSelectCell($columns, $column_number, $selected = '')
{
?>
<td class="center">
<select name="Field[<?php echo $column_number; ?>]" size="1">
<option value="">&nbsp;</option>
<?php
$html_output = '';
$html_output .= '<td class="center">';
$html_output .= '<select name="Field[' . $column_number . ']" size="1">';
$html_output .= '<option value="">&nbsp;</option>';
foreach ($columns as $column) {
if ($column === $selected) {
$sel = ' selected="selected"';
} else {
$sel = '';
}
echo '<option value="' . htmlspecialchars($column) . '"' . $sel . '>'
. str_replace(' ', '&nbsp;', htmlspecialchars($column)) . '</option>' . "\n";
$html_output .= '<option value="' . htmlspecialchars($column) . '"'
. (($column === $selected) ? ' selected="selected"' : '') . '>'
. str_replace(' ', '&nbsp;', htmlspecialchars($column)) . '</option>';
}
?>
</select>
</td>
<?php
$html_output .= '</select>';
$html_output .= '</td>';
return $html_output;
}
/**
* Provides select options list containing sort options (ASC/DESC)
*
* @param integer $column_number Column Number (0,1,2) or more
* @param string $realwidth Largest column width found
* @param string $asc_selected Selected criteria 'Ascending'
* @param string $desc_selected Selected criteria 'Descending'
*
* @return HTML for select options
*/
function getSortSelectCell($column_number, $realwidth, $asc_selected = '',
$desc_selected = '')
{
$html_output = '<td class="center">';
$html_output .= '<select style="width: ' . $realwidth
. '" name="Sort[' . $column_number . ']" size="1">';
$html_output .= '<option value="">&nbsp;</option>';
$html_output .= '<option value="ASC"' . $asc_selected . '>' . __('Ascending')
. '</option>';
$html_output .= '<option value="DESC"' . $desc_selected . '>' . __('Descending')
. '</option>';
$html_output .= '</select>';
$html_output .= '</td>';
return $html_output;
}
/**
* Provides search form's row containing column select options
*
* @param array $criteria_column_count Number of criteria columns
* @param integer $columns All column names
* @param string $ins_col If a new criteria column is needed
* @param string $del_col If a criteria column is to be deleted
*
* @return HTML for search table's row
*/
function PMA_dbQbegetColumnNamesRow(
$criteria_column_count, $columns, $ins_col = null, $del_col = null
) {
$html_output = '<tr class="odd noclick">';
$html_output .= '<th>' . __('Column') . ':</th>';
$z = 0;
for ($column_index = 0; $column_index < $criteria_column_count; $column_index++)
{
if (isset($ins_col[$column_index]) && $ins_col[$column_index] == 'on') {
$html_output .= showColumnSelectCell($columns, $z);
$z++;
}
if (! empty($del_col) && isset($del_col[$column_index]) && $del_col[$column_index] == 'on') {
continue;
}
$selected = '';
if (isset($_REQUEST['Field'][$column_index])) {
$selected = $_REQUEST['Field'][$column_index];
$GLOBALS['curField'][$z] = $_REQUEST['Field'][$column_index];
}
$html_output .= showColumnSelectCell($columns, $z, $selected);
$z++;
} // end for
$html_output .= '</tr>';
return $html_output;
}
/**
* Provides search form's row containing sort(ASC/DESC) select options
*
* @param array $criteria_column_count Number of criteria columns
* @param string $realwidth Largest column width found
* @param string $ins_col If a new criteria column is needed
* @param string $del_col If a criteria column is to be deleted
*
* @return HTML for search table's row
*/
function PMA_dbQbegetSortRow(
$criteria_column_count, $realwidth, $ins_col = null, $del_col = null
) {
$html_output = '<tr class="even noclick">';
$html_output .= '<th>' . __('Sort') . ':</th>';
$z = 0;
for ($column_index = 0; $column_index < $criteria_column_count; $column_index++)
{
if (! empty($ins_col) && isset($ins_col[$column_index]) && $ins_col[$column_index] == 'on') {
$html_output .= getSortSelectCell($z, $realwidth);
$z++;
} // end if
if (! empty($del_col) && isset($del_col[$column_index]) && $del_col[$column_index] == 'on') {
continue;
}
// If they have chosen all fields using the * selector,
// then sorting is not available, Fix for Bug #570698
if (isset($_REQUEST['Sort'][$column_index]) && isset($_REQUEST['Field'][$column_index])
&& substr($_REQUEST['Field'][$column_index], -2) == '.*'
) {
$_REQUEST['Sort'][$column_index] = '';
} //end if
// Set asc_selected
if (isset($_REQUEST['Sort'][$column_index]) && $_REQUEST['Sort'][$column_index] == 'ASC') {
$GLOBALS['curSort'][$z] = $_REQUEST['Sort'][$column_index];
$asc_selected = ' selected="selected"';
} else {
$asc_selected = '';
} // end if
// Set desc selected
if (isset($_REQUEST['Sort'][$column_index]) && $_REQUEST['Sort'][$column_index] == 'DESC') {
$GLOBALS['curSort'][$z] = $_REQUEST['Sort'][$column_index];
$desc_selected = ' selected="selected"';
} else {
$desc_selected = '';
} // end if
$html_output .= getSortSelectCell(
$z, $realwidth, $asc_selected, $desc_selected
);
$z++;
} // end for
$html_output .= '</tr>';
return $html_output;
}
/**
* Provides search form's row containing SHOW checkboxes
*
* @param array $criteria_column_count Number of criteria columns
* @param string $ins_col If a new criteria column is needed
* @param string $del_col If a criteria column is to be deleted
*
* @return HTML for search table's row
*/
function PMA_dbQbegetShowRow(
$criteria_column_count, $ins_col = null, $del_col = null
) {
$html_output = '<tr class="odd noclick">';
$html_output .= '<th>' . __('Show') . ':</th>';
$z = 0;
for ($column_index = 0; $column_index < $criteria_column_count; $column_index++)
{
if (! empty($ins_col) && isset($ins_col[$column_index]) && $ins_col[$column_index] == 'on') {
$html_output .= '<td class="center">';
$html_output .= '<input type="checkbox" name="Show[' . $z . ']" />';
$html_output .= '</td>';
$z++;
} // end if
if (! empty($del_col) && isset($del_col[$column_index]) && $del_col[$column_index] == 'on') {
continue;
}
if (isset($_REQUEST['Show'][$column_index])) {
$checked = ' checked="checked"';
$GLOBALS['curShow'][$z] = $_REQUEST['Show'][$column_index];
} else {
$checked = '';
}
$html_output .= '<td class="center">';
$html_output .= '<input type="checkbox" name="Show[' . $z . ']"' . $checked
. ' />';
$html_output .= '</td>';
$z++;
} // end for
$html_output .= '</tr>';
return $html_output;
}
/**
* Provides search form's row containing criteria Inputboxes
*
* @param array $criteria_column_count Number of criteria columns
* @param string $realwidth Largest column width found
* @param string $criteria Already Filled criteria
* @param string $prev_criteria Previously filled criteria(hidden form field)
* @param string $ins_col If a new criteria column is needed
* @param string $del_col If a criteria column is to be deleted
*
* @return HTML for search table's row
*/
function PMA_dbQbegetCriteriaInputboxRow(
$criteria_column_count, $realwidth, $criteria, $prev_criteria,
$ins_col = null, $del_col = null
) {
$html_output = '<tr class="even noclick">';
$html_output .= '<th>' . __('Criteria') . ':</th>';
$z = 0;
for ($column_index = 0; $column_index < $criteria_column_count; $column_index++)
{
if (! empty($ins_col) && isset($ins_col[$column_index]) && $ins_col[$column_index] == 'on') {
$html_output .= '<td class="center">';
$html_output .= '<input type="text" name="criteria[' . $z . ']"'
. ' value="" class="textfield" style="width: ' . $realwidth
. '" size="20" />';
$html_output .= '</td>';
$z++;
} // end if
if (! empty($del_col) && isset($del_col[$column_index]) && $del_col[$column_index] == 'on') {
continue;
}
if (isset($criteria[$column_index])) {
$tmp_criteria = $criteria[$column_index];
}
if ((empty($prev_criteria) || ! isset($prev_criteria[$column_index]))
|| $prev_criteria[$column_index] != htmlspecialchars($tmp_criteria)
) {
$GLOBALS['curCriteria'][$z] = $tmp_criteria;
} else {
$GLOBALS['curCriteria'][$z] = $prev_criteria[$column_index];
}
$html_output .= '<td class="center">';
$html_output .= '<input type="hidden" name="prev_criteria[' . $z . ']"'
. ' value="' . htmlspecialchars($GLOBALS['curCriteria'][$z]) . '" />';
$html_output .= '<input type="text" name="criteria[' . $z . ']"'
. ' value="' . htmlspecialchars($tmp_criteria) . '" class="textfield"'
. ' style="width: ' . $realwidth . '" size="20" />';
$html_output .= '</td>';
$z++;
} // end for
$html_output .= '</tr>';
return $html_output;
}
/**
* Provides footer options for adding/deleting row/columns
*
* @param string $type Whether row or column
*
* @return HTML for footer options
*/
function PMA_dbQbeGetFootersOptions($type)
{
$html_output = '<div class="floatleft">';
$html_output .= (($type == 'row')
? __('Add/Delete criteria rows') : __('Add/Delete columns'));
$html_output .= ':<select size="1" name="'
. (($type == 'row') ? 'add_row' : 'add_col') . '">';
$html_output .= '<option value="-3">-3</option>';
$html_output .= '<option value="-2">-2</option>';
$html_output .= '<option value="-1">-1</option>';
$html_output .= '<option value="0" selected="selected">0</option>';
$html_output .= '<option value="1">1</option>';
$html_output .= '<option value="2">2</option>';
$html_output .= '<option value="3">3</option>';
$html_output .= '</select>';
$html_output .= '</div>';
return $html_output;
}
/**
* Provides search form table's footer options
*
* @return HTML for table footer
*/
function PMA_dbQbeGetTableFooters()
{
$html_output = '<fieldset class="tblFooters">';
$html_output .= PMA_dbQbeGetFootersOptions("row");
$html_output .= PMA_dbQbeGetFootersOptions("column");
$html_output .= '<div class="floatleft">';
$html_output .= '<input type="submit" name="modify"'
. 'value="' . __('Update Query') . '" />';
$html_output .= '</div>';
$html_output .= '</fieldset>';
return $html_output;
}
/**
* Provides a select list of database tables
*
* @param array $table_names Names of all the tables
*
* @return HTML for table select list
*/
function PMA_dbQbeGetTablesList($table_names)
{
$html_output = '<div class="floatleft">';
$html_output .= '<fieldset>';
$html_output .= '<legend>' . __('Use Tables') . '</legend>';
// Build the options list for each table name
$options = '';
$numTableListOptions = 0;
foreach ($table_names as $key => $val) {
$options .= '<option value="' . htmlspecialchars($key) . '"' . $val . '>'
. (str_replace(' ', '&nbsp;', htmlspecialchars($key))) . '</option>';
$numTableListOptions++;
}
$html_output .= '<select name="TableList[]" multiple="multiple" id="listTable"'
. ' size="' . (($numTableListOptions > 30) ? '15' : '7') . '">';
$html_output .= $options;
$html_output .= '</select>';
$html_output .= '</fieldset>';
$html_output .= '<fieldset class="tblFooters">';
$html_output .= '<input type="submit" name="modify" value="'
. __('Update Query') . '" />';
$html_output .= '</fieldset>';
$html_output .= '</div>';
return $html_output;
}
/**
* Provides And/Or modification cell along with Insert/Delete options
* (For modifying search form's table columns)
*
* @param integer $column_number Column Number (0,1,2) or more
* @param array $selected Selected criteria column name
*
* @return HTML for modification cell
*/
function PMA_dbQbeGetAndOrColCell($column_number, $selected = null)
{
$html_output = '<td class="center">';
$html_output .= '<strong>' . __('Or') . ':</strong>';
$html_output .= '<input type="radio" name="and_or_col[' . $column_number . ']"'
. ' value="or"' . $selected['or'] . ' />';
$html_output .= '&nbsp;&nbsp;<strong>' . __('And') . ':</strong>';
$html_output .= '<input type="radio" name="and_or_col[' . $column_number . ']"'
. ' value="and"' . $selected['and'] . ' />';
$html_output .= '<br />' . __('Ins');
$html_output .= '<input type="checkbox" name="ins_col[' . $column_number . ']" />';
$html_output .= '&nbsp;&nbsp;' . __('Del');
$html_output .= '<input type="checkbox" name="del_col[' . $column_number . ']" />';
$html_output .= '</td>';
return $html_output;
}
/**
* Provides search form's row containing column modifications options
* (For modifying search form's table columns)
*
* @param array $criteria_column_count Number of criteria columns
* @param string $realwidth Largest column width found
* @param string $criteria Already Filled criteria
* @param string $prev_criteria Previously filled criteria(hidden form field)
* @param string $ins_col If a new criteria column is needed
* @param string $del_col If a criteria column is to be deleted
*
* @return HTML for search table's row
*/
function PMA_dbQbeGetModifyColumnsRow($criteria_column_count, $and_or_col,
$ins_col = null, $del_col = null
) {
$html_output = '<tr class="even noclick">';
$html_output .= '<th>' . __('Modify') . ':</th>';
$z = 0;
for ($x = 0; $x < $criteria_column_count; $x++) {
if (! empty($ins_col) && isset($ins_col[$x]) && $ins_col[$x] == 'on') {
$html_output .= PMA_dbQbeGetAndOrColCell($z);
$z++;
} // end if
if (! empty($del_col) && isset($del_col[$x]) && $del_col[$x] == 'on') {
continue;
}
if (isset($and_or_col[$x])) {
$GLOBALS['curAndOrCol'][$z] = $and_or_col[$x];
}
if (isset($and_or_col[$x]) && $and_or_col[$x] == 'or') {
$chk['or'] = ' checked="checked"';
$chk['and'] = '';
} else {
$chk['and'] = ' checked="checked"';
$chk['or'] = '';
}
$html_output .= PMA_dbQbeGetAndOrColCell($z, $chk);
$z++;
} // end for
$html_output .= '</tr>';
return $html_output;
}
if ($cfgRelation['designerwork']) {
@@ -186,172 +587,20 @@ if ($cfgRelation['designerwork']) {
<form action="db_qbe.php" method="post">
<fieldset>
<table class="data" style="width: 100%;">
<tr class="odd noclick">
<th><?php echo __('Column'); ?>:</th>
<?php
$z = 0;
for ($x = 0; $x < $col; $x++) {
if (isset($ins_col[$x]) && $ins_col[$x] == 'on') {
showColumnSelectCell($fld, $z);
$z++;
}
if (! empty($del_col) && isset($del_col[$x]) && $del_col[$x] == 'on') {
continue;
}
$selected = '';
if (isset($Field[$x])) {
$selected = $Field[$x];
$curField[$z] = $Field[$x];
}
showColumnSelectCell($fld, $z, $selected);
$z++;
} // end for
echo PMA_dbQbegetColumnNamesRow(
$col, $fld, $ins_col, $del_col
);
echo PMA_dbQbegetSortRow(
$col, $realwidth, $ins_col, $del_col
);
echo PMA_dbQbegetShowRow(
$col, $ins_col, $del_col
);
echo PMA_dbQbegetCriteriaInputboxRow(
$col, $realwidth, $criteria, $prev_criteria, $ins_col, $del_col
);
?>
</tr>
<!-- Sort row -->
<tr class="even noclick">
<th><?php echo __('Sort'); ?>:</th>
<?php
$z = 0;
for ($x = 0; $x < $col; $x++) {
if (! empty($ins_col) && isset($ins_col[$x]) && $ins_col[$x] == 'on') {
?>
<td class="center">
<select style="width: <?php echo $realwidth; ?>" name="Sort[<?php echo $z; ?>]" size="1">
<option value="">&nbsp;</option>
<option value="ASC"><?php echo __('Ascending'); ?></option>
<option value="DESC"><?php echo __('Descending'); ?></option>
</select>
</td>
<?php
$z++;
} // end if
echo "\n";
if (! empty($del_col) && isset($del_col[$x]) && $del_col[$x] == 'on') {
continue;
}
?>
<td class="center">
<select style="width: <?php echo $realwidth; ?>" name="Sort[<?php echo $z; ?>]" size="1">
<option value="">&nbsp;</option>
<?php
echo "\n";
// If they have chosen all fields using the * selector,
// then sorting is not available
// Fix for Bug #570698
if (isset($Sort[$x]) && isset($Field[$x])
&& substr($Field[$x], -2) == '.*'
) {
$Sort[$x] = '';
} //end if
if (isset($Sort[$x]) && $Sort[$x] == 'ASC') {
$curSort[$z] = $Sort[$x];
$sel = ' selected="selected"';
} else {
$sel = '';
} // end if
echo ' ';
echo '<option value="ASC"' . $sel . '>' . __('Ascending') . '</option>' . "\n";
if (isset($Sort[$x]) && $Sort[$x] == 'DESC') {
$curSort[$z] = $Sort[$x];
$sel = ' selected="selected"';
} else {
$sel = '';
} // end if
echo ' ';
echo '<option value="DESC"' . $sel . '>' . __('Descending') . '</option>' . "\n";
?>
</select>
</td>
<?php
$z++;
echo "\n";
} // end for
?>
</tr>
<!-- Show row -->
<tr class="odd noclick">
<th><?php echo __('Show'); ?>:</th>
<?php
$z = 0;
for ($x = 0; $x < $col; $x++) {
if (! empty($ins_col) && isset($ins_col[$x]) && $ins_col[$x] == 'on') {
?>
<td class="center">
<input type="checkbox" name="Show[<?php echo $z; ?>]" />
</td>
<?php
$z++;
} // end if
echo "\n";
if (! empty($del_col) && isset($del_col[$x]) && $del_col[$x] == 'on') {
continue;
}
if (isset($Show[$x])) {
$checked = ' checked="checked"';
$curShow[$z] = $Show[$x];
} else {
$checked = '';
}
?>
<td class="center">
<input type="checkbox" name="Show[<?php echo $z; ?>]"<?php echo $checked; ?> />
</td>
<?php
$z++;
echo "\n";
} // end for
?>
</tr>
<!-- Criteria row -->
<tr class="even noclick">
<th><?php echo __('Criteria'); ?>:</th>
<?php
$z = 0;
for ($x = 0; $x < $col; $x++) {
if (! empty($ins_col) && isset($ins_col[$x]) && $ins_col[$x] == 'on') {
?>
<td class="center">
<input type="text" name="criteria[<?php echo $z; ?>]" value="" class="textfield" style="width: <?php echo $realwidth; ?>" size="20" />
</td>
<?php
$z++;
} // end if
echo "\n";
if (! empty($del_col) && isset($del_col[$x]) && $del_col[$x] == 'on') {
continue;
}
if (isset($criteria[$x])) {
$tmp_criteria = $criteria[$x];
}
if ((empty($prev_criteria) || ! isset($prev_criteria[$x]))
|| $prev_criteria[$x] != htmlspecialchars($tmp_criteria)
) {
$curCriteria[$z] = $tmp_criteria;
} else {
$curCriteria[$z] = $prev_criteria[$x];
}
?>
<td class="center">
<input type="hidden" name="prev_criteria[<?php echo $z; ?>]" value="<?php echo htmlspecialchars($curCriteria[$z]); ?>" />
<input type="text" name="criteria[<?php echo $z; ?>]" value="<?php echo htmlspecialchars($tmp_criteria); ?>" class="textfield" style="width: <?php echo $realwidth; ?>" size="20" />
</td>
<?php
$z++;
echo "\n";
} // end for
?>
</tr>
<!-- And/Or columns and rows -->
<?php
@@ -433,7 +682,7 @@ for ($y = 0; $y <= $row; $y++) {
}
if (isset($and_or_row[$y])) {
$curAndOrRow[$w] = $and_or_row[$y];
$GLOBALS['curAndOrRow'][$w] = $and_or_row[$y];
}
if (isset($and_or_row[$y]) && $and_or_row[$y] == 'and') {
$chk['and'] = ' checked="checked"';
@@ -520,73 +769,13 @@ for ($y = 0; $y <= $row; $y++) {
$odd_row =! $odd_row;
} // end for
?>
<!-- Modify columns -->
<tr class="even noclick">
<th><?php echo __('Modify'); ?>:</th>
<?php
$z = 0;
for ($x = 0; $x < $col; $x++) {
if (! empty($ins_col) && isset($ins_col[$x]) && $ins_col[$x] == 'on') {
$curAndOrCol[$z] = $and_or_col[$y];
if ($and_or_col[$z] == 'or') {
$chk['or'] = ' checked="checked"';
$chk['and'] = '';
} else {
$chk['and'] = ' checked="checked"';
$chk['or'] = '';
}
?>
<td class="center">
<strong><?php echo __('Or'); ?>:</strong>
<input type="radio" name="and_or_col[<?php echo $z; ?>]" value="or"<?php echo $chk['or']; ?> />
&nbsp;&nbsp;<strong><?php echo __('And'); ?>:</strong>
<input type="radio" name="and_or_col[<?php echo $z; ?>]" value="and"<?php echo $chk['and']; ?> />
<br />
<?php echo __('Ins') . "\n"; ?>
<input type="checkbox" name="ins_col[<?php echo $z; ?>]" />
&nbsp;&nbsp;<?php echo __('Del') . "\n"; ?>
<input type="checkbox" name="del_col[<?php echo $z; ?>]" />
</td>
<?php
$z++;
} // end if
echo "\n";
if (! empty($del_col) && isset($del_col[$x]) && $del_col[$x] == 'on') {
continue;
}
if (isset($and_or_col[$y])) {
$curAndOrCol[$z] = $and_or_col[$y];
}
if (isset($and_or_col[$z]) && $and_or_col[$z] == 'or') {
$chk['or'] = ' checked="checked"';
$chk['and'] = '';
} else {
$chk['and'] = ' checked="checked"';
$chk['or'] = '';
}
?>
<td class="center">
<strong><?php echo __('Or'); ?>:</strong>
<input type="radio" name="and_or_col[<?php echo $z; ?>]" value="or"<?php echo $chk['or']; ?> />
&nbsp;&nbsp;<strong><?php echo __('And'); ?>:</strong>
<input type="radio" name="and_or_col[<?php echo $z; ?>]" value="and"<?php echo $chk['and']; ?> />
<br />
<?php echo __('Ins') . "\n"; ?>
<input type="checkbox" name="ins_col[<?php echo $z; ?>]" />
&nbsp;&nbsp;<?php echo __('Del') . "\n"; ?>
<input type="checkbox" name="del_col[<?php echo $z; ?>]" />
</td>
<?php
$z++;
echo "\n";
} // end for
echo PMA_dbQbeGetModifyColumnsRow(
$col, $and_or_col, $ins_col, $del_col
);
?>
</tr>
</table>
<!-- Other controls -->
<?php
$w--;
$url_params['db'] = $db;
@@ -595,63 +784,15 @@ $url_params['rows'] = $w;
echo PMA_generate_common_hidden_inputs($url_params);
?>
</fieldset>
<fieldset class="tblFooters">
<div class="floatleft">
<?php echo __('Add/Delete criteria rows'); ?>:
<select size="1" name="add_row">
<option value="-3">-3</option>
<option value="-2">-2</option>
<option value="-1">-1</option>
<option value="0" selected="selected">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<div class="floatleft">
<?php echo __('Add/Delete columns'); ?>:
<select size="1" name="add_col">
<option value="-3">-3</option>
<option value="-2">-2</option>
<option value="-1">-1</option>
<option value="0" selected="selected">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
<!-- Generates a query -->
<div class="floatleft">
<input type="submit" name="modify" value="<?php echo __('Update Query'); ?>" />
</div>
</fieldset>
<div class="floatleft">
<fieldset>
<legend><?php echo __('Use Tables'); ?></legend>
<?php
$options = '';
$numTableListOptions = 0;
foreach ($tbl_names as $key => $val) {
$options .= ' ';
$options .= '<option value="' . htmlspecialchars($key) . '"' . $val . '>'
. str_replace(' ', '&nbsp;', htmlspecialchars($key)) . '</option>' . "\n";
$numTableListOptions++;
}
echo PMA_dbQbeGetTableFooters();
echo PMA_dbQbeGetTablesList($tbl_names);
?>
<select name="TableList[]" multiple="multiple" id="listTable"
size="<?php echo ($numTableListOptions > 30) ? '15' : '7'; ?>">
<?php echo $options; ?>
</select>
</fieldset>
<fieldset class="tblFooters">
<input type="submit" name="modify" value="<?php echo __('Update Query'); ?>" />
</fieldset>
</div>
<div class="floatleft">
<fieldset>
<legend><?php echo sprintf(__('SQL query on database <b>%s</b>:'), PMA_getDbLink($db)); ?>
<legend><?php echo sprintf(__('SQL query on database <b>%s</b>:'), $common_functions->getDbLink($db)); ?>
</legend>
<textarea cols="80" name="sql_query" id="textSqlquery"
rows="<?php echo ($numTableListOptions > 30) ? '15' : '7'; ?>"
@@ -663,11 +804,14 @@ if (! isset($qry_select)) {
$qry_select = '';
}
for ($x = 0; $x < $col; $x++) {
if (! empty($curField[$x]) && isset($curShow[$x]) && $curShow[$x] == 'on') {
if (! empty($GLOBALS['curField'][$x])
&& isset($GLOBALS['curShow'][$x])
&& $GLOBALS['curShow'][$x] == 'on')
{
if ($last_select) {
$qry_select .= ', ';
}
$qry_select .= $curField[$x];
$qry_select .= $GLOBALS['curField'][$x];
$last_select = 1;
}
} // end for
@@ -845,12 +989,12 @@ if (isset($Field) && count($Field) > 0) {
if ($run > 5) {
foreach ($tab_left as $tab) {
$emerg .= ', ' . PMA_backquote($tab);
$emerg .= ', ' . $common_functions->backquote($tab);
unset($tab_left[$tab]);
}
}
} // end while
$qry_from = PMA_backquote($master) . $emerg . $fromclause;
$qry_from = $common_functions->backquote($master) . $emerg . $fromclause;
} // end if ($cfgRelation['relwork'] && count($tab_all) > 0)
} // end count($Field) > 0
@@ -870,11 +1014,16 @@ if (! empty($qry_from)) {
$qry_where = '';
$criteria_cnt = 0;
for ($x = 0; $x < $col; $x++) {
if (! empty($curField[$x]) && ! empty($curCriteria[$x]) && $x && isset($last_where) && isset($curAndOrCol)) {
$qry_where .= ' ' . strtoupper($curAndOrCol[$last_where]) . ' ';
if (! empty($GLOBALS['curField'][$x])
&& ! empty($GLOBALS['curCriteria'][$x])
&& $x
&& isset($last_where)
&& isset($GLOBALS['curAndOrCol'])) {
$qry_where .= ' ' . strtoupper($GLOBALS['curAndOrCol'][$last_where]) . ' ';
}
if (! empty($curField[$x]) && ! empty($curCriteria[$x])) {
$qry_where .= '(' . $curField[$x] . ' ' . $curCriteria[$x] . ')';
if (! empty($GLOBALS['curField'][$x]) && ! empty($GLOBALS['curCriteria'][$x])) {
$qry_where .= '(' . $GLOBALS['curField'][$x] . ' '
. $GLOBALS['curCriteria'][$x] . ')';
$last_where = $x;
$criteria_cnt++;
}
@@ -883,19 +1032,19 @@ if ($criteria_cnt > 1) {
$qry_where = '(' . $qry_where . ')';
}
// OR rows ${'cur' . $or}[$x]
if (! isset($curAndOrRow)) {
$curAndOrRow = array();
if (! isset($GLOBALS['curAndOrRow'])) {
$GLOBALS['curAndOrRow'] = array();
}
for ($y = 0; $y <= $row; $y++) {
$criteria_cnt = 0;
$qry_orwhere = '';
$last_orwhere = '';
for ($x = 0; $x < $col; $x++) {
if (! empty($curField[$x]) && ! empty(${'curOr' . $y}[$x]) && $x) {
$qry_orwhere .= ' ' . strtoupper($curAndOrCol[$last_orwhere]) . ' ';
if (! empty($GLOBALS['curField'][$x]) && ! empty(${'curOr' . $y}[$x]) && $x) {
$qry_orwhere .= ' ' . strtoupper($GLOBALS['curAndOrCol'][$last_orwhere]) . ' ';
}
if (! empty($curField[$x]) && ! empty(${'curOr' . $y}[$x])) {
$qry_orwhere .= '(' . $curField[$x]
if (! empty($GLOBALS['curField'][$x]) && ! empty(${'curOr' . $y}[$x])) {
$qry_orwhere .= '(' . $GLOBALS['curField'][$x]
. ' '
. ${'curOr' . $y}[$x]
. ')';
@@ -908,7 +1057,7 @@ for ($y = 0; $y <= $row; $y++) {
}
if (! empty($qry_orwhere)) {
$qry_where .= "\n"
. strtoupper(isset($curAndOrRow[$y]) ? $curAndOrRow[$y] . ' ' : '')
. strtoupper(isset($GLOBALS['curAndOrRow'][$y]) ? $GLOBALS['curAndOrRow'][$y] . ' ' : '')
. $qry_orwhere;
} // end if
} // end for
@@ -924,15 +1073,15 @@ if (! isset($qry_orderby)) {
$qry_orderby = '';
}
for ($x = 0; $x < $col; $x++) {
if ($last_orderby && $x && ! empty($curField[$x]) && ! empty($curSort[$x])) {
if ($last_orderby && $x && ! empty($GLOBALS['curField'][$x]) && ! empty($GLOBALS['curSort'][$x])) {
$qry_orderby .= ', ';
}
if (! empty($curField[$x]) && ! empty($curSort[$x])) {
if (! empty($GLOBALS['curField'][$x]) && ! empty($GLOBALS['curSort'][$x])) {
// if they have chosen all fields using the * selector,
// then sorting is not available
// Fix for Bug #570698
if (substr($curField[$x], -2) != '.*') {
$qry_orderby .= $curField[$x] . ' ' . $curSort[$x];
if (substr($GLOBALS['curField'][$x], -2) != '.*') {
$qry_orderby .= $GLOBALS['curField'][$x] . ' ' . $GLOBALS['curSort'][$x];
$last_orderby = 1;
}
}

View File

@@ -10,7 +10,7 @@
* Include required files
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/common.lib.php';
require_once 'libraries/CommonFunctions.class.php';
require_once 'libraries/mysql_charsets.lib.php';
/**

View File

@@ -9,9 +9,10 @@
*/
/**
*
* Gets some core libraries
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/DbSearch.class.php';
$response = PMA_Response::getInstance();
$header = $response->getHeader();
@@ -21,353 +22,38 @@ $scripts->addFile('sql.js');
$scripts->addFile('makegrid.js');
$scripts->addFile('jquery/timepicker.js');
/**
* Gets some core libraries and send headers
*/
require 'libraries/db_common.inc.php';
/**
* init
*/
// If config variable $GLOBALS['cfg']['Usedbsearch'] is on false : exit.
if (! $GLOBALS['cfg']['UseDbSearch']) {
PMA_mysqlDie(__('Access denied'), '', false, $err_url);
PMA_CommonFunctions::getInstance()->mysqlDie(
__('Access denied'), '', false, $err_url
);
} // end if
$url_query .= '&amp;goto=db_search.php';
$url_params['goto'] = 'db_search.php';
/**
* @global array list of tables from the current database
* but do not clash with $tables coming from db_info.inc.php
*/
$tables_names_only = PMA_DBI_get_tables($GLOBALS['db']);
$search_options = array(
'1' => __('at least one of the words'),
'2' => __('all words'),
'3' => __('the exact phrase'),
'4' => __('as regular expression'),
);
if (empty($_REQUEST['search_option'])
|| ! is_string($_REQUEST['search_option'])
|| ! array_key_exists($_REQUEST['search_option'], $search_options)
) {
$search_option = 1;
unset($_REQUEST['submit_search']);
} else {
$search_option = (int) $_REQUEST['search_option'];
$option_str = $search_options[$_REQUEST['search_option']];
}
if (empty($_REQUEST['search_str']) || ! is_string($_REQUEST['search_str'])) {
unset($_REQUEST['submit_search']);
$searched = '';
} else {
$searched = htmlspecialchars($_REQUEST['search_str']);
// For "as regular expression" (search option 4), we should not treat
// this as an expression that contains a LIKE (second parameter of
// PMA_sqlAddSlashes()).
//
// Usage example: If user is seaching for a literal $ in a regexp search,
// he should enter \$ as the value.
$search_str = PMA_sqlAddSlashes(
$_REQUEST['search_str'], ($search_option == 4 ? false : true)
);
}
$tables_selected = array();
if (empty($_REQUEST['table_select']) || ! is_array($_REQUEST['table_select'])) {
unset($_REQUEST['submit_search']);
} elseif (! isset($_REQUEST['selectall']) && ! isset($_REQUEST['unselectall'])) {
$tables_selected = array_intersect($_REQUEST['table_select'], $tables_names_only);
}
if (isset($_REQUEST['selectall'])) {
$tables_selected = $tables_names_only;
} elseif (isset($_REQUEST['unselectall'])) {
$tables_selected = array();
}
if (empty($_REQUEST['field_str']) || ! is_string($_REQUEST['field_str'])) {
unset($field_str);
} else {
$field_str = PMA_sqlAddSlashes($_REQUEST['field_str'], true);
}
/**
* Displays top links if we are not in an Ajax request
*/
$sub_part = '';
// Create a database search instance
$db_search = new PMA_DbSearch($GLOBALS['db']);
// Display top links if we are not in an Ajax request
if ( $GLOBALS['is_ajax_request'] != true) {
include 'libraries/db_info.inc.php';
echo '<div id="searchresults">';
$response->addHTML('<div id="searchresults">');
}
/**
* 1. Main search form has been submitted
*/
// Main search form has been submitted, get results
if (isset($_REQUEST['submit_search'])) {
$response->addHTML($db_search->getSearchResults());
}
/**
* Builds the SQL search query
*
* @param string $table the table name
* @param string $field restrict the search to this field
* @param string $search_str the string to search
* @param integer $search_option type of search
* (1 -> 1 word at least, 2 -> all words,
* 3 -> exact string, 4 -> regexp)
*
* @return array 3 SQL querys (for count, display and delete results)
*
* @todo can we make use of fulltextsearch IN BOOLEAN MODE for this?
* PMA_backquote
* PMA_DBI_free_result
* PMA_DBI_fetch_assoc
* $GLOBALS['db']
* explode
* count
* strlen
*/
function PMA_getSearchSqls($table, $field, $search_str, $search_option)
{
// Statement types
$sqlstr_select = 'SELECT';
$sqlstr_delete = 'DELETE';
// Fields to select
$tblfields = PMA_DBI_get_columns($GLOBALS['db'], $table);
// Table to use
$sqlstr_from = ' FROM ' . PMA_backquote($GLOBALS['db']) . '.' . PMA_backquote($table);
$search_words = (($search_option > 2) ? array($search_str) : explode(' ', $search_str));
$like_or_regex = (($search_option == 4) ? 'REGEXP' : 'LIKE');
$automatic_wildcard = (($search_option < 3) ? '%' : '');
$fieldslikevalues = array();
foreach ($search_words as $search_word) {
// Eliminates empty values
if (strlen($search_word) === 0) {
continue;
}
$thefieldlikevalue = array();
foreach ($tblfields as $tblfield) {
if (! isset($field) || strlen($field) == 0 || $tblfield['Field'] == $field) {
// Drizzle has no CONVERT and all text columns are UTF-8
if (PMA_DRIZZLE) {
$thefieldlikevalue[] = PMA_backquote($tblfield['Field'])
. ' ' . $like_or_regex . ' '
. "'" . $automatic_wildcard
. $search_word
. $automatic_wildcard . "'";
} else {
$thefieldlikevalue[] = 'CONVERT(' . PMA_backquote($tblfield['Field']) . ' USING utf8)'
. ' ' . $like_or_regex . ' '
. "'" . $automatic_wildcard
. $search_word
. $automatic_wildcard . "'";
}
}
} // end for
if (count($thefieldlikevalue) > 0) {
$fieldslikevalues[] = implode(' OR ', $thefieldlikevalue);
}
} // end for
$implode_str = ($search_option == 1 ? ' OR ' : ' AND ');
if ( empty($fieldslikevalues)) {
// this could happen when the "inside field" does not exist
// in any selected tables
$sqlstr_where = ' WHERE FALSE';
} else {
$sqlstr_where = ' WHERE (' . implode(') ' . $implode_str . ' (', $fieldslikevalues) . ')';
}
unset($fieldslikevalues);
// Builds complete queries
$sql['select_fields'] = $sqlstr_select . ' * ' . $sqlstr_from . $sqlstr_where;
// here, I think we need to still use the COUNT clause, even for
// VIEWs, anyway we have a WHERE clause that should limit results
$sql['select_count'] = $sqlstr_select . ' COUNT(*) AS `count`' . $sqlstr_from . $sqlstr_where;
$sql['delete'] = $sqlstr_delete . $sqlstr_from . $sqlstr_where;
return $sql;
} // end of the "PMA_getSearchSqls()" function
/**
* Displays the results
*/
$this_url_params = array(
'db' => $GLOBALS['db'],
'goto' => 'db_sql.php',
'pos' => 0,
'is_js_confirmed' => 0,
);
// Displays search string
echo '<br />' . "\n"
. '<table class="data">' . "\n"
. '<caption class="tblHeaders">' . "\n"
. sprintf(
__('Search results for "<i>%s</i>" %s:'),
$searched, $option_str
) . "\n"
. '</caption>' . "\n";
$num_search_result_total = 0;
$odd_row = true;
foreach ($tables_selected as $each_table) {
// Gets the SQL statements
$newsearchsqls = PMA_getSearchSqls(
$each_table, (! empty($field_str) ? $field_str : ''),
$search_str, $search_option
);
// Executes the "COUNT" statement
$res_cnt = PMA_DBI_fetch_value($newsearchsqls['select_count']);
$num_search_result_total += $res_cnt;
$sql_query .= $newsearchsqls['select_count'];
echo '<tr class="noclick ' . ($odd_row ? 'odd' : 'even') . '">'
. '<td>' . sprintf(
_ngettext('%1$s match inside table <i>%2$s</i>', '%1$s matches inside table <i>%2$s</i>', $res_cnt),
$res_cnt, htmlspecialchars($each_table)
) . "</td>\n";
if ($res_cnt > 0) {
$this_url_params['sql_query'] = $newsearchsqls['select_fields'];
$browse_result_path = 'sql.php' . PMA_generate_common_url($this_url_params);
?>
<td> <a name="browse_search" href="<?php echo $browse_result_path; ?>" onclick="loadResult('<?php echo $browse_result_path ?> ',' <?php echo $each_table?> ' , '<?php echo PMA_generate_common_url($GLOBALS['db'], $each_table)?>','<?php echo ($GLOBALS['cfg']['AjaxEnable']); ?>');return false;" ><?php echo __('Browse') ?></a> </td>
<?php
$this_url_params['sql_query'] = $newsearchsqls['delete'];
$delete_result_path = 'sql.php' . PMA_generate_common_url($this_url_params);
?>
<td> <a name="delete_search" href="<?php echo $delete_result_path; ?>" onclick="deleteResult('<?php echo $delete_result_path ?>' , ' <?php printf(__('Delete the matches for the %s table?'), htmlspecialchars($each_table)); ?>','<?php echo ($GLOBALS['cfg']['AjaxEnable']); ?>');return false;" ><?php echo __('Delete') ?></a> </td>
<?php
} else {
echo '<td>&nbsp;</td>' . "\n"
.'<td>&nbsp;</td>' . "\n";
}// end if else
$odd_row = ! $odd_row;
echo '</tr>' . "\n";
} // end for
echo '</table>' . "\n";
if (count($tables_selected) > 1) {
echo '<p>' . sprintf(
_ngettext('<b>Total:</b> <i>%s</i> match', '<b>Total:</b> <i>%s</i> matches', $num_search_result_total),
$num_search_result_total
) . '</p>' . "\n";
}
} // end 1.
/**
* If we are in an Ajax request, we need to exit after displaying all the HTML
*/
// If we are in an Ajax request, we need to exit after displaying all the HTML
if ($GLOBALS['is_ajax_request'] == true) {
exit;
} else {
echo '</div>';//end searchresults div
$response->addHTML('</div>');//end searchresults div
}
/**
* 2. Displays the main search form
*/
// Display the search form
$response->addHTML($db_search->getSelectionForm($url_params));
?>
<a id="db_search"></a>
<form id="db_search_form"<?php echo ($GLOBALS['cfg']['AjaxEnable'] ? ' class="ajax"' : ''); ?> method="post" action="db_search.php" name="db_search">
<?php echo PMA_generate_common_hidden_inputs($GLOBALS['db']); ?>
<fieldset>
<legend><?php echo __('Search in database'); ?></legend>
<table class="formlayout">
<tr><td><?php echo __('Words or values to search for (wildcard: "%"):'); ?></td>
<td><input type="text" name="search_str" size="60"
value="<?php echo $searched; ?>" /></td>
</tr>
<tr><td class="right vtop">
<?php echo __('Find:'); ?></td>
<td><?php
$choices = array(
'1' => __('at least one of the words') . PMA_showHint(__('Words are separated by a space character (" ").')),
'2' => __('all words') . PMA_showHint(__('Words are separated by a space character (" ").')),
'3' => __('the exact phrase'),
'4' => __('as regular expression') . ' ' . PMA_showMySQLDocu('Regexp', 'Regexp')
);
// 4th parameter set to true to add line breaks
// 5th parameter set to false to avoid htmlspecialchars() escaping in the label
// since we have some HTML in some labels
echo PMA_getRadioFields('search_option', $choices, $search_option, true, false);
unset($choices);
?>
</td>
</tr>
<tr><td class="right vtop">
<?php echo __('Inside tables:'); ?></td>
<td rowspan="2">
<?php
echo ' <select name="table_select[]" size="6" multiple="multiple">' . "\n";
foreach ($tables_names_only as $each_table) {
if (in_array($each_table, $tables_selected)) {
$is_selected = ' selected="selected"';
} else {
$is_selected = '';
}
echo ' <option value="' . htmlspecialchars($each_table) . '"'
. $is_selected . '>'
. str_replace(' ', '&nbsp;', htmlspecialchars($each_table)) . '</option>' . "\n";
} // end while
echo ' </select>' . "\n";
$alter_select
= '<a href="db_search.php' . PMA_generate_common_url(array_merge($url_params, array('selectall' => 1))) . '#db_search"'
. ' onclick="setSelectOptions(\'db_search\', \'table_select[]\', true); return false;">' . __('Select All') . '</a>'
. '&nbsp;/&nbsp;'
. '<a href="db_search.php' . PMA_generate_common_url(array_merge($url_params, array('unselectall' => 1))) . '#db_search"'
. ' onclick="setSelectOptions(\'db_search\', \'table_select[]\', false); return false;">' . __('Unselect All') . '</a>';
?>
</td>
</tr>
<tr><td class="right vbottom">
<?php echo $alter_select; ?></td>
</tr>
<tr><td class="right">
<?php echo __('Inside column:'); ?></td>
<td><input type="text" name="field_str" size="60"
value="<?php echo ! empty($field_str) ? htmlspecialchars($field_str) : ''; ?>" /></td>
</tr>
</table>
</fieldset>
<fieldset class="tblFooters">
<input type="submit" name="submit_search" value="<?php echo __('Go'); ?>"
id="buttonGo" />
</fieldset>
</form>
<!-- These two table-image and table-link elements display the table name in browse search results -->
<div id='table-info'>
<a class="item" id="table-link" ></a>
</div>
<div id="browse-results">
<!-- this browse-results div is used to load the browse and delete results in the db search -->
</div>
<br class="clearfloat" />
<div id="sqlqueryform">
<!-- this sqlqueryform div is used to load the delete form in the db search -->
</div>
<!-- toggle query box link-->
<a id="togglequerybox"></a>

View File

@@ -16,6 +16,7 @@ $scripts = $header->getScripts();
$scripts->addFile('db_structure.js');
$scripts->addFile('tbl_change.js');
$scripts->addFile('jquery/timepicker.js');
$common_functions = PMA_CommonFunctions::getInstance();
/**
* Sets globals from $_POST
@@ -79,7 +80,7 @@ $db_collation = PMA_getDbCollation($db);
// in a separate file to avoid redeclaration of functions in some code paths
require_once 'libraries/db_structure.lib.php';
$titles = PMA_buildActionTitles();
$titles = $common_functions->buildActionTitles();
// 1. No tables
@@ -112,7 +113,7 @@ if (isset($_REQUEST['sort_order'])) {
$_url_params['sort_order'] = $_REQUEST['sort_order'];
}
PMA_listNavigator(
echo $common_functions->getListNavigator(
$total_num_tables, $pos, $_url_params, 'db_structure.php',
'frame_content', $GLOBALS['cfg']['MaxTableList']
);
@@ -172,11 +173,15 @@ foreach ($tables as $keyname => $each_table) {
if ($is_show_stats) {
$tblsize = doubleval($each_table['Data_length']) + doubleval($each_table['Index_length']);
$sum_size += $tblsize;
list($formatted_size, $unit) = PMA_formatByteDown($tblsize, 3, ($tblsize > 0) ? 1 : 0);
list($formatted_size, $unit) = $common_functions->formatByteDown(
$tblsize, 3, ($tblsize > 0) ? 1 : 0
);
if (isset($each_table['Data_free']) && $each_table['Data_free'] > 0) {
list($formatted_overhead, $overhead_unit) = PMA_formatByteDown(
$each_table['Data_free'], 3, ($each_table['Data_free'] > 0) ? 1 : 0
);
list($formatted_overhead, $overhead_unit)
= $common_functions->formatByteDown(
$each_table['Data_free'], 3,
($each_table['Data_free'] > 0) ? 1 : 0
);
$overhead_size += $each_table['Data_free'];
}
}
@@ -203,7 +208,9 @@ foreach ($tables as $keyname => $each_table) {
if ($is_show_stats && $each_table['Data_length'] !== null) {
$tblsize = $each_table['Data_length'] + $each_table['Index_length'];
$sum_size += $tblsize;
list($formatted_size, $unit) = PMA_formatByteDown($tblsize, 3, ($tblsize > 0) ? 1 : 0);
list($formatted_size, $unit) = $common_functions->formatByteDown(
$tblsize, 3, ($tblsize > 0) ? 1 : 0
);
}
//$display_rows = ' - ';
break;
@@ -360,7 +367,7 @@ foreach ($tables as $keyname => $each_table) {
}
$empty_table .= ' href="sql.php?' . $tbl_url_query
. '&amp;sql_query=';
$empty_table .= urlencode('TRUNCATE ' . PMA_backquote($each_table['TABLE_NAME']))
$empty_table .= urlencode('TRUNCATE ' . $common_functions->backquote($each_table['TABLE_NAME']))
. '&amp;message_to_show='
. urlencode(sprintf(__('Table %s has been emptied'), htmlspecialchars($each_table['TABLE_NAME'])))
.'">';
@@ -377,7 +384,7 @@ foreach ($tables as $keyname => $each_table) {
$drop_query = 'DROP '
. (($table_is_view || $each_table['ENGINE'] == null) ? 'VIEW' : 'TABLE')
. ' ' . PMA_backquote($each_table['TABLE_NAME']);
. ' ' . $common_functions->backquote($each_table['TABLE_NAME']);
$drop_message = sprintf(
($table_is_view || $each_table['ENGINE'] == null)? __('View %s has been dropped') : __('Table %s has been dropped'),
str_replace(' ', '&nbsp;', htmlspecialchars($each_table['TABLE_NAME']))
@@ -389,12 +396,12 @@ foreach ($tables as $keyname => $each_table) {
if (PMA_Tracker::isTracked($GLOBALS["db"], $truename)) {
$tracking_icon = '<a href="tbl_tracking.php?' . $url_query
. '&amp;table=' . $truename . '">'
. PMA_getImage('eye.png', __('Tracking is active.'))
. $common_functions->getImage('eye.png', __('Tracking is active.'))
. '</a>';
} elseif (PMA_Tracker::getVersion($GLOBALS["db"], $truename) > 0) {
$tracking_icon = '<a href="tbl_tracking.php?' . $url_query
. '&amp;table=' . $truename . '">'
. PMA_getImage('eye.png', __('Tracking is not active.'))
. $common_functions->getImage('eye.png', __('Tracking is not active.'))
. '</a>';
}
}
@@ -453,7 +460,7 @@ foreach ($tables as $keyname => $each_table) {
?>"
id="row_tbl_<?php echo $i; ?>">
<td class="center">
<input type="checkbox" name="selected_tbl[]"
<input type="checkbox" name="selected_tbl[]" class="checkall"
value="<?php echo htmlspecialchars($each_table['TABLE_NAME']); ?>"
id="checkbox_tbl_<?php echo $i; ?>"<?php echo $checked; ?> /></td>
<th><?php echo $browse_table_label; ?>
@@ -463,10 +470,10 @@ foreach ($tables as $keyname => $each_table) {
if ($server_slave_status) {
?><td class="center"><?php
echo $ignored
? PMA_getImage('s_cancel.png', 'NOT REPLICATED')
? $common_functions->getImage('s_cancel.png', 'NOT REPLICATED')
: ''.
$do
? PMA_getImage('s_success.png', 'REPLICATED')
? $common_functions->getImage('s_success.png', 'REPLICATED')
: ''; ?></td><?php
}
?>
@@ -517,7 +524,7 @@ foreach ($tables as $keyname => $each_table) {
) {
$row_count_pre = '~';
$sum_row_count_pre = '~';
$show_superscript = PMA_showHint(
$show_superscript = $common_functions->showHint(
PMA_sanitize(
sprintf(
__('This view has at least this number of rows. Please refer to %sdocumentation%s.'),
@@ -534,7 +541,7 @@ foreach ($tables as $keyname => $each_table) {
$show_superscript = '';
}
?>
<td class="value tbl_rows"><?php echo $row_count_pre . PMA_formatNumber($each_table['TABLE_ROWS'], 0) . $show_superscript; ?></td>
<td class="value tbl_rows"><?php echo $row_count_pre . $common_functions->formatNumber($each_table['TABLE_ROWS'], 0) . $show_superscript; ?></td>
<?php
if (!($cfg['PropertiesNumColumns'] > 1)) {
?>
@@ -556,17 +563,17 @@ foreach ($tables as $keyname => $each_table) {
} // end if
if ($GLOBALS['cfg']['ShowDbStructureCreation']) {
?>
<td class="value tbl_creation"><?php echo $create_time ? PMA_localisedDate(strtotime($create_time)) : '-'; ?></td>
<td class="value tbl_creation"><?php echo $create_time ? $common_functions->localisedDate(strtotime($create_time)) : '-'; ?></td>
<?php
} // end if
if ($GLOBALS['cfg']['ShowDbStructureLastUpdate']) {
?>
<td class="value tbl_last_update"><?php echo $update_time ? PMA_localisedDate(strtotime($update_time)) : '-'; ?></td>
<td class="value tbl_last_update"><?php echo $update_time ? $common_functions->localisedDate(strtotime($update_time)) : '-'; ?></td>
<?php
} // end if
if ($GLOBALS['cfg']['ShowDbStructureLastCheck']) {
?>
<td class="value tbl_last_check"><?php echo $check_time ? PMA_localisedDate(strtotime($check_time)) : '-'; ?></td>
<td class="value tbl_last_check"><?php echo $check_time ? $common_functions->localisedDate(strtotime($check_time)) : '-'; ?></td>
<?php
} // end if
} elseif ($table_is_view) {
@@ -597,9 +604,11 @@ foreach ($tables as $keyname => $each_table) {
// Show Summary
if ($is_show_stats) {
list($sum_formatted, $unit) = PMA_formatByteDown($sum_size, 3, 1);
list($sum_formatted, $unit) = $common_functions->formatByteDown(
$sum_size, 3, 1
);
list($overhead_formatted, $overhead_unit)
= PMA_formatByteDown($overhead_size, 3, 1);
= $common_functions->formatByteDown($overhead_size, 3, 1);
}
?>
</tbody>
@@ -609,7 +618,7 @@ if ($is_show_stats) {
<?php
echo sprintf(
_ngettext('%s table', '%s tables', $num_tables),
PMA_formatNumber($num_tables, 0)
$common_functions->formatNumber($num_tables, 0)
);
?>
</th>
@@ -620,7 +629,7 @@ if ($is_show_stats) {
?>
<th colspan="<?php echo ($db_is_information_schema ? 3 : 6) ?>">
<?php echo __('Sum'); ?></th>
<th class="value tbl_rows"><?php echo $sum_row_count_pre . PMA_formatNumber($sum_entries, 0); ?></th>
<th class="value tbl_rows"><?php echo $sum_row_count_pre . $common_functions->formatNumber($sum_entries, 0); ?></th>
<?php
if (!($cfg['PropertiesNumColumns'] > 1)) {
$default_engine = PMA_DBI_fetch_value('SHOW VARIABLES LIKE \'storage_engine\';', 0, 1);
@@ -647,19 +656,19 @@ if ($is_show_stats) {
if ($GLOBALS['cfg']['ShowDbStructureCreation']) {
echo ' <th class="value tbl_creation">' . "\n"
. ' ' . ($create_time_all ? PMA_localisedDate(strtotime($create_time_all)) : '-')
. ' ' . ($create_time_all ? $common_functions->localisedDate(strtotime($create_time_all)) : '-')
. ' </th>';
}
if ($GLOBALS['cfg']['ShowDbStructureLastUpdate']) {
echo ' <th class="value tbl_last_update">' . "\n"
. ' ' . ($update_time_all ? PMA_localisedDate(strtotime($update_time_all)) : '-')
. ' ' . ($update_time_all ? $common_functions->localisedDate(strtotime($update_time_all)) : '-')
. ' </th>';
}
if ($GLOBALS['cfg']['ShowDbStructureLastCheck']) {
echo ' <th class="value tbl_last_check">' . "\n"
. ' ' . ($check_time_all ? PMA_localisedDate(strtotime($check_time_all)) : '-')
. ' ' . ($check_time_all ? $common_functions->localisedDate(strtotime($check_time_all)) : '-')
. ' </th>';
}
@@ -675,13 +684,8 @@ $checkall_url = 'db_structure.php?' . PMA_generate_common_url($db);
?>
<img class="selectallarrow" src="<?php echo $pmaThemeImage .'arrow_'.$text_dir.'.png'; ?>"
width="38" height="22" alt="<?php echo __('With selected:'); ?>" />
<a href="<?php echo $checkall_url; ?>&amp;checkall=1"
onclick="if (markAllRows('tablesForm')) return false;">
<?php echo __('Check All'); ?></a>
/
<a href="<?php echo $checkall_url; ?>"
onclick="if (unMarkAllRows('tablesForm')) return false;">
<?php echo __('Uncheck All'); ?></a>
<input type="checkbox" id="checkall" title="<?php echo __('Check All'); ?>" />
<label for="checkall"><?php echo __('Check All'); ?></label>
<?php if ($overhead_check != '') { ?>
/
<a href="#" onclick="unMarkAllRows('tablesForm');
@@ -727,7 +731,7 @@ if (!$db_is_information_schema && !$cfg['DisableMultiTableMaintenance']) {
</form>
<?php
// display again the table list navigator
PMA_listNavigator(
echo $common_functions->getListNavigator(
$total_num_tables, $pos, $_url_params, 'db_structure.php',
'frame_content', $GLOBALS['cfg']['MaxTableList']
);
@@ -744,10 +748,10 @@ PMA_listNavigator(
/* Printable view of a table */
echo '<p>';
echo '<a href="db_printview.php?' . $url_query . '">';
echo PMA_getIcon('b_print.png', __('Print view'), true) . '</a>';
echo $common_functions->getIcon('b_print.png', __('Print view'), true) . '</a>';
echo '<a href="db_datadict.php?' . $url_query . '">';
echo PMA_getIcon('b_tblanalyse.png', __('Data Dictionary'), true) . '</a>';
echo $common_functions->getIcon('b_tblanalyse.png', __('Data Dictionary'), true) . '</a>';
echo '</p>';
if (empty($db_is_information_schema)) {

View File

@@ -7,36 +7,38 @@
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/common.lib.php';
require_once 'libraries/CommonFunctions.class.php';
$db = $_GET['db'];
$table_term = $_GET['table'];
$common_functions = PMA_CommonFunctions::getInstance();
$common_url_query = PMA_generate_common_url($GLOBALS['db']);
$tables_full = PMA_getTableList($db);
$tables_full = $common_functions->getTableList($db);
$tables_response = array();
foreach ($tables_full as $key => $table) {
if (strpos($key, $table_term) !== false) {
$link = '<li class="ajax_table"><a class="tableicon" title="'
. htmlspecialchars($link_title)
. ': ' . htmlspecialchars($table['Comment'])
. ' (' . PMA_formatNumber($table['Rows'], 0)
. ' ' . __('Rows') . ')"' . ' id="quick_'
. htmlspecialchars($table_db . '.' . $table['Name']) . '"'
. ' href="' . $GLOBALS['cfg']['LeftDefaultTabTable'] . '?'
. $common_url_query
. '&amp;table=' . urlencode($table['Name'])
. '&amp;goto=' . $GLOBALS['cfg']['LeftDefaultTabTable']
. '" >';
. htmlspecialchars($link_title)
. ': ' . htmlspecialchars($table['Comment'])
. ' ('
. $common_functions->formatNumber($table['Rows'], 0)
. ' ' . __('Rows') . ')"' . ' id="quick_'
. htmlspecialchars($table_db . '.' . $table['Name']) . '"'
. ' href="' . $GLOBALS['cfg']['LeftDefaultTabTable'] . '?'
. $common_url_query
. '&amp;table=' . urlencode($table['Name'])
. '&amp;goto=' . $GLOBALS['cfg']['LeftDefaultTabTable']
. '" >';
$attr = array(
'id' => 'icon_' . htmlspecialchars($table_db . '.' . $table['Name'])
);
if (PMA_Table::isView($table_db, $table['Name'])) {
$link .= PMA_getImage(
$link .= $common_functions->getImage(
's_views.png', htmlspecialchars($link_title), $attr
);
} else {
$link .= PMA_getImage(
$link .= $common_functions->getImage(
'b_browse.png', htmlspecialchars($link_title), $attr
);
}
@@ -46,17 +48,20 @@ foreach ($tables_full as $key => $table) {
. $common_url_query . '&amp;table='
. urlencode($table['Name']) . '&amp;pos=0';
$link .= '<a href="' . $href . '" title="'
. htmlspecialchars(
PMA_getTitleForTarget($GLOBALS['cfg']['DefaultTabTable'])
. ': ' . $table['Comment']
. ' (' . PMA_formatNumber($table['Rows'], 0)
. ' ' . __('Rows') . ')'
. htmlspecialchars(
$common_functions->getTitleForTarget(
$GLOBALS['cfg']['DefaultTabTable']
)
. '" id="' . htmlspecialchars($table_db . '.' . $table['Name'])
. '">'
// preserve spaces in table name
. str_replace(' ', '&nbsp;', htmlspecialchars($table['disp_name']))
. '</a>';
. ': ' . $table['Comment']
. ' (' .
$common_functions->formatNumber($table['Rows'], 0)
. ' ' . __('Rows') . ')'
)
. '" id="' . htmlspecialchars($table_db . '.' . $table['Name'])
. '">'
// preserve spaces in table name
. str_replace(' ', '&nbsp;', htmlspecialchars($table['disp_name']))
. '</a>';
$link .= '</li>' . "\n";
$table['line'] = $link;
$tables_response[] = $table;

View File

@@ -14,6 +14,7 @@ $response = PMA_Response::getInstance();
$header = $response->getHeader();
$scripts = $header->getScripts();
$scripts->addFile('db_structure.js');
$common_functions = PMA_CommonFunctions::getInstance();
/**
* If we are not in an Ajax request, then do the common work and show the links etc.
@@ -60,13 +61,13 @@ if ($num_tables == 0 && count($data['ddlog']) == 0) {
// Prepare statement to get HEAD version
$all_tables_query = ' SELECT table_name, MAX(version) as version FROM ' .
PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) . '.' .
PMA_backquote($GLOBALS['cfg']['Server']['tracking']) .
' WHERE db_name = \'' . PMA_sqlAddSlashes($_REQUEST['db']) . '\' ' .
$common_functions->backquote($GLOBALS['cfg']['Server']['pmadb']) . '.' .
$common_functions->backquote($GLOBALS['cfg']['Server']['tracking']) .
' WHERE db_name = \'' . $common_functions->sqlAddSlashes($_REQUEST['db']) . '\' ' .
' GROUP BY table_name' .
' ORDER BY table_name ASC';
$all_tables_result = PMA_query_as_controluser($all_tables_query);
$all_tables_result = PMA_queryAsControlUser($all_tables_query);
// If a HEAD version exists
if (PMA_DBI_num_rows($all_tables_result) > 0) {
@@ -94,7 +95,7 @@ if (PMA_DBI_num_rows($all_tables_result) > 0) {
$drop_image_or_text = '';
if (true == $GLOBALS['cfg']['PropertiesIconic']) {
$drop_image_or_text .= PMA_getImage('b_drop.png', __('Delete tracking data for this table'));
$drop_image_or_text .= $common_functions->getImage('b_drop.png', __('Delete tracking data for this table'));
}
if ('both' === $GLOBALS['cfg']['PropertiesIconic']
|| false === $GLOBALS['cfg']['PropertiesIconic']
@@ -106,13 +107,13 @@ if (PMA_DBI_num_rows($all_tables_result) > 0) {
while ($one_result = PMA_DBI_fetch_array($all_tables_result)) {
list($table_name, $version_number) = $one_result;
$table_query = ' SELECT * FROM ' .
PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) . '.' .
PMA_backquote($GLOBALS['cfg']['Server']['tracking']) .
' WHERE `db_name` = \'' . PMA_sqlAddSlashes($_REQUEST['db'])
. '\' AND `table_name` = \'' . PMA_sqlAddSlashes($table_name)
$common_functions->backquote($GLOBALS['cfg']['Server']['pmadb']) . '.' .
$common_functions->backquote($GLOBALS['cfg']['Server']['tracking']) .
' WHERE `db_name` = \'' . $common_functions->sqlAddSlashes($_REQUEST['db'])
. '\' AND `table_name` = \'' . $common_functions->sqlAddSlashes($table_name)
. '\' AND `version` = \'' . $version_number . '\'';
$table_result = PMA_query_as_controluser($table_query);
$table_result = PMA_queryAsControlUser($table_query);
$version_data = PMA_DBI_fetch_array($table_result);
if ($version_data['tracking_active'] == 1) {
@@ -155,7 +156,7 @@ if (PMA_DBI_num_rows($all_tables_result) > 0) {
$sep = $GLOBALS['cfg']['LeftFrameTableSeparator'];
// Get list of tables
$table_list = PMA_getTableList($GLOBALS['db']);
$table_list = $common_functions->getTableList($GLOBALS['db']);
// For each table try to get the tracking version
foreach ($table_list as $key => $value) {
@@ -200,7 +201,7 @@ if (isset($my_tables)) {
if (PMA_Tracker::getVersion($GLOBALS['db'], $tablename) == -1) {
$my_link = '<a href="tbl_tracking.php?' . $url_query
. '&amp;table=' . htmlspecialchars($tablename) .'">';
$my_link .= PMA_getIcon('eye.png', __('Track table')) . '</a>';
$my_link .= $common_functions->getIcon('eye.png', __('Track table')) . '</a>';
?>
<tr class="noclick <?php echo $style;?>">
<td><?php echo htmlspecialchars($tablename);?></td>
@@ -226,7 +227,7 @@ if (count($data['ddlog']) > 0) {
foreach ($data['ddlog'] as $entry) {
$log .= '# ' . $entry['date'] . ' ' . $entry['username'] . "\n" . $entry['statement'] . "\n";
}
echo PMA_getMessage(__('Database Log'), $log);
echo $common_functions->getMessage(__('Database Log'), $log);
}
?>

View File

@@ -13,6 +13,8 @@ require_once 'libraries/common.inc.php';
require_once 'libraries/zip.lib.php';
require_once 'libraries/plugin_interface.lib.php';
$common_functions = PMA_CommonFunctions::getInstance();
/**
* Sets globals from all $_POST (in export.php only)
* Would it not be tiresome to list all export-plugin options here?
@@ -21,11 +23,13 @@ foreach ($_POST as $one_post_param => $one_post_value) {
$GLOBALS[$one_post_param] = $one_post_value;
}
PMA_checkParameters(array('what', 'export_type'));
$common_functions->checkParameters(array('what', 'export_type'));
// Scan plugins
$export_list = PMA_getPlugins(
'libraries/export/',
// export class instance, not array of properties, as before
$export_plugin = PMA_getPlugin(
"export",
$what,
'libraries/plugins/export/',
array(
'export_type' => $export_type,
'single_table' => isset($single_table)
@@ -36,8 +40,10 @@ $export_list = PMA_getPlugins(
$type = $what;
// Check export type
if (! isset($export_list[$type])) {
if (! isset($export_plugin)) {
PMA_fatalError(__('Bad type!'));
} else {
$export_plugin_properties = $export_plugin->getProperties();
}
/**
@@ -86,7 +92,8 @@ if ($_REQUEST['output_format'] == 'astext') {
}
// Does export require to be into file?
if (isset($export_list[$type]['force_file']) && ! $asfile) {
if (isset($export_plugin_properties['force_file']) && ! $asfile) {
$message = PMA_Message::error(__('Selected export type has to be saved in file!'));
if ($export_type == 'server') {
$active_page = 'server_export.php';
@@ -118,9 +125,6 @@ if ($export_type == 'server') {
PMA_fatalError(__('Bad parameters!'));
}
// Get the functions specific to the export type
require 'libraries/export/' . PMA_securePath($type) . '.php';
/**
* Increase time limit for script execution and initializes some variables
*/
@@ -247,7 +251,7 @@ function PMA_exportOutputHandler($line)
if ($what == 'sql') {
$crlf = "\n";
} else {
$crlf = PMA_whichCrlf();
$crlf = $common_functions->whichCrlf();
}
$output_kanji_conversion = function_exists('PMA_kanji_str_conv') && $type != 'xls';
@@ -317,19 +321,18 @@ if ($asfile) {
);
}
}
$filename = PMA_expandUserString($filename_template);
$filename = PMA_sanitize_filename($filename);
$filename = $common_functions->expandUserString($filename_template);
$filename = PMA_sanitizeFilename($filename);
// Grab basic dump extension and mime type
// Check if the user already added extension;
// get the substring where the extension would be if it was included
$extension_start_pos = strlen($filename) - strlen($export_list[$type]['extension']) - 1;
// Check if the user already added extension; get the substring where the extension would be if it was included
$extension_start_pos = strlen($filename) - strlen($export_plugin_properties['extension']) - 1;
$user_extension = substr($filename, $extension_start_pos, strlen($filename));
$required_extension = "." . $export_list[$type]['extension'];
$required_extension = "." . $export_plugin_properties['extension'];
if (strtolower($user_extension) != $required_extension) {
$filename .= $required_extension;
}
$mime_type = $export_list[$type]['mime_type'];
$mime_type = $export_plugin_properties['mime_type'];
// If dump is going to be compressed, set correct mime_type and add
// compression to extension
@@ -347,22 +350,30 @@ if ($asfile) {
// Open file on server if needed
if ($save_on_server) {
$save_filename = PMA_userDir($cfg['SaveDir'])
$save_filename = $common_functions->userDir($cfg['SaveDir'])
. preg_replace('@[/\\\\]@', '_', $filename);
unset($message);
if (file_exists($save_filename)
&& ((! $quick_export && empty($onserverover))
|| ($quick_export && $_REQUEST['quick_export_onserverover'] != 'saveitover'))
|| ($quick_export
&& $_REQUEST['quick_export_onserverover'] != 'saveitover'))
) {
$message = PMA_Message::error(__('File %s already exists on server, change filename or check overwrite option.'));
$message = PMA_Message::error(__(
'File %s already exists on server, change filename or check'
. ' overwrite option.'
));
$message->addParam($save_filename);
} else {
if (is_file($save_filename) && ! is_writable($save_filename)) {
$message = PMA_Message::error(__('The web server does not have permission to save the file %s.'));
$message = PMA_Message::error(__(
'The web server does not have permission to save the file %s.'
));
$message->addParam($save_filename);
} else {
if (! $file_handle = @fopen($save_filename, 'w')) {
$message = PMA_Message::error(__('The web server does not have permission to save the file %s.'));
$message = PMA_Message::error(__(
'The web server does not have permission to save the file %s.'
));
$message->addParam($save_filename);
}
}
@@ -392,7 +403,7 @@ if (! $save_on_server) {
// (avoid rewriting data containing HTML with anchors and forms;
// this was reported to happen under Plesk)
@ini_set('url_rewriter.tags', '');
$filename = PMA_sanitize_filename($filename);
$filename = PMA_sanitizeFilename($filename);
PMA_downloadHeader($filename, $mime_type);
} else {
@@ -433,9 +444,9 @@ if (! $save_on_server) {
}
foreach ($_REQUEST as $name => $value) {
$back_button .= '&' . urlencode($name) . '=' . urlencode($value);
$back_button .= '&amp;' . urlencode($name) . '=' . urlencode($value);
}
$back_button .= '&repopulate=1">Back</a> ]</p>';
$back_button .= '&amp;repopulate=1">Back</a> ]</p>';
echo $back_button;
echo ' <form name="nofunction">' . "\n"
@@ -452,7 +463,7 @@ if (! $save_on_server) {
do {
// Add possibly some comments to export
if (! PMA_exportHeader()) {
if (! $export_plugin->exportHeader($db)) {
break;
}
@@ -468,7 +479,7 @@ do {
}
// Include dates in export?
$do_dates = isset($GLOBALS[$what . '_dates']);
$do_dates = isset($GLOBALS[$what . '_dates']);
/**
* Builds the dump
@@ -485,17 +496,17 @@ do {
&& strpos(' ' . $tmp_select, '|' . $current_db . '|'))
|| ! isset($tmp_select)
) {
if (! PMA_exportDBHeader($current_db)) {
if (! $export_plugin->exportDBHeader($current_db)) {
break 2;
}
if (! PMA_exportDBCreate($current_db)) {
if (! $export_plugin->exportDBCreate($current_db)) {
break 2;
}
if (function_exists('PMA_exportRoutines')
if (method_exists($export_plugin, 'exportRoutines')
&& strpos($GLOBALS['sql_structure_or_data'], 'structure') !== false
&& isset($GLOBALS['sql_procedure_function'])
) {
PMA_exportRoutines($current_db);
$export_plugin->exportRoutines($current_db);
}
$tables = PMA_DBI_get_tables($current_db);
@@ -512,7 +523,7 @@ do {
) {
// for a view, export a stand-in definition of the table
// to resolve view dependencies
if (! PMA_exportStructure(
if (! $export_plugin->exportStructure(
$current_db, $table, $crlf, $err_url,
$is_view ? 'stand_in' : 'create_table', $export_type,
$do_relation, $do_comments, $do_mime, $do_dates
@@ -525,9 +536,9 @@ do {
|| $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data')
&& ! ($is_view || PMA_Table::isMerge($current_db, $table))
) {
$local_query = 'SELECT * FROM ' . PMA_backquote($current_db)
. '.' . PMA_backquote($table);
if (! PMA_exportData($current_db, $table, $crlf, $err_url, $local_query)) {
$local_query = 'SELECT * FROM ' . $common_functions->backquote($current_db)
. '.' . $common_functions->backquote($table);
if (! $export_plugin->exportData($current_db, $table, $crlf, $err_url, $local_query)) {
break 3;
}
}
@@ -536,7 +547,7 @@ do {
if ($GLOBALS[$what . '_structure_or_data'] == 'structure'
|| $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data'
) {
if (! PMA_exportStructure(
if (! $export_plugin->exportStructure(
$current_db, $table, $crlf, $err_url,
'triggers', $export_type,
$do_relation, $do_comments, $do_mime, $do_dates
@@ -550,7 +561,7 @@ do {
if ($GLOBALS[$what . '_structure_or_data'] == 'structure'
|| $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data'
) {
if (! PMA_exportStructure(
if (! $export_plugin->exportStructure(
$current_db, $view, $crlf, $err_url,
'create_view', $export_type,
$do_relation, $do_comments, $do_mime, $do_dates
@@ -559,21 +570,21 @@ do {
}
}
}
if (! PMA_exportDBFooter($current_db)) {
if (! $export_plugin->exportDBFooter($current_db)) {
break 2;
}
}
}
} elseif ($export_type == 'database') {
if (! PMA_exportDBHeader($db)) {
if (! $export_plugin->exportDBHeader($db)) {
break;
}
if (function_exists('PMA_exportRoutines')
if (method_exists($export_plugin, 'exportRoutines')
&& strpos($GLOBALS['sql_structure_or_data'], 'structure') !== false
&& isset($GLOBALS['sql_procedure_function'])
) {
PMA_exportRoutines($db);
$export_plugin->exportRoutines($db);
}
$i = 0;
@@ -591,7 +602,7 @@ do {
) {
// for a view, export a stand-in definition of the table
// to resolve view dependencies
if (! PMA_exportStructure(
if (! $export_plugin->exportStructure(
$db, $table, $crlf, $err_url,
$is_view ? 'stand_in' : 'create_table', $export_type,
$do_relation, $do_comments, $do_mime, $do_dates
@@ -604,18 +615,16 @@ do {
|| $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data')
&& ! ($is_view || PMA_Table::isMerge($db, $table))
) {
$local_query = 'SELECT * FROM ' . PMA_backquote($db)
. '.' . PMA_backquote($table);
if (! PMA_exportData($db, $table, $crlf, $err_url, $local_query)) {
$local_query = 'SELECT * FROM ' . $common_functions->backquote($db)
. '.' . $common_functions->backquote($table);
if (! $export_plugin->exportData($db, $table, $crlf, $err_url, $local_query)) {
break 2;
}
}
// now export the triggers (needs to be done after the data because
// triggers can modify already imported tables)
if ($GLOBALS[$what . '_structure_or_data'] == 'structure'
|| $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data'
) {
if (! PMA_exportStructure(
if ($GLOBALS[$what . '_structure_or_data'] == 'structure' || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data') {
if (! $export_plugin->exportStructure(
$db, $table, $crlf, $err_url,
'triggers', $export_type,
$do_relation, $do_comments, $do_mime, $do_dates
@@ -626,10 +635,8 @@ do {
}
foreach ($views as $view) {
// no data export for a view
if ($GLOBALS[$what . '_structure_or_data'] == 'structure'
|| $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data'
) {
if (! PMA_exportStructure(
if ($GLOBALS[$what . '_structure_or_data'] == 'structure' || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data') {
if (! $export_plugin->exportStructure(
$db, $view, $crlf, $err_url,
'create_view', $export_type,
$do_relation, $do_comments, $do_mime, $do_dates
@@ -639,11 +646,11 @@ do {
}
}
if (! PMA_exportDBFooter($db)) {
if (! $export_plugin->exportDBFooter($db)) {
break;
}
} else {
if (! PMA_exportDBHeader($db)) {
if (! $export_plugin->exportDBHeader($db)) {
break;
}
// We export just one table
@@ -657,10 +664,8 @@ do {
}
$is_view = PMA_Table::isView($db, $table);
if ($GLOBALS[$what . '_structure_or_data'] == 'structure'
|| $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data'
) {
if (! PMA_exportStructure(
if ($GLOBALS[$what . '_structure_or_data'] == 'structure' || $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data') {
if (! $export_plugin->exportStructure(
$db, $table, $crlf, $err_url,
$is_view ? 'create_view' : 'create_table', $export_type,
$do_relation, $do_comments, $do_mime, $do_dates
@@ -684,10 +689,12 @@ do {
$local_query = $sql_query . $add_query;
PMA_DBI_select_db($db);
} else {
$local_query = 'SELECT * FROM ' . PMA_backquote($db)
. '.' . PMA_backquote($table) . $add_query;
$local_query = 'SELECT * FROM ' . $common_functions->backquote($db)
. '.' . $common_functions->backquote($table) . $add_query;
}
if (! PMA_exportData($db, $table, $crlf, $err_url, $local_query)) {
if (! $export_plugin->exportData($db, $table, $crlf, $err_url,
$local_query
)) {
break;
}
}
@@ -696,7 +703,7 @@ do {
if ($GLOBALS[$what . '_structure_or_data'] == 'structure'
|| $GLOBALS[$what . '_structure_or_data'] == 'structure_and_data'
) {
if (! PMA_exportStructure(
if (! $export_plugin->exportStructure(
$db, $table, $crlf, $err_url,
'triggers', $export_type,
$do_relation, $do_comments, $do_mime, $do_dates
@@ -704,11 +711,11 @@ do {
break 2;
}
}
if (! PMA_exportDBFooter($db)) {
if (! $export_plugin->exportDBFooter($db)) {
break;
}
}
if (! PMA_exportFooter()) {
if (! $export_plugin->exportFooter()) {
break;
}
@@ -746,9 +753,9 @@ if (! empty($asfile)) {
// 1. as a zipped file
if ($compression == 'zip') {
if (@function_exists('gzcompress')) {
$zipfile = new zipfile();
$zipfile -> addFile($dump_buffer, substr($filename, 0, -4));
$dump_buffer = $zipfile -> file();
$zipfile = new ZipFile();
$zipfile->addFile($dump_buffer, substr($filename, 0, -4));
$dump_buffer = $zipfile->file();
}
} elseif ($compression == 'bzip2') {
// 2. as a bzipped file
@@ -767,7 +774,7 @@ if (! empty($asfile)) {
if ($save_on_server) {
$write_result = @fwrite($file_handle, $dump_buffer);
fclose($file_handle);
if (strlen($dump_buffer) !=0
if (strlen($dump_buffer) > 0
&& (! $write_result || ($write_result != strlen($dump_buffer)))
) {
$message = new PMA_Message(
@@ -814,22 +821,10 @@ if (! empty($asfile)) {
?>
<script type="text/javascript">
//<![CDATA[
var bodyWidth=null; var bodyHeight=null;
if (document.getElementById('textSQLDUMP')) {
bodyWidth = self.innerWidth;
bodyHeight = self.innerHeight;
if (! bodyWidth && ! bodyHeight) {
if (document.compatMode && document.compatMode == "BackCompat") {
bodyWidth = document.body.clientWidth;
bodyHeight = document.body.clientHeight;
} else if (document.compatMode && document.compatMode == "CSS1Compat") {
bodyWidth = document.documentElement.clientWidth;
bodyHeight = document.documentElement.clientHeight;
}
}
document.getElementById('textSQLDUMP').style.width=(bodyWidth-50) + 'px';
document.getElementById('textSQLDUMP').style.height=(bodyHeight-100) + 'px';
}
var $body = $("body");
$("#textSQLDUMP")
.width($body.width() - 50)
.height($body.height() - 100);
//]]>
</script>
<?php

View File

@@ -16,6 +16,8 @@ if (isset($_REQUEST['show_as_php'])) {
$GLOBALS['show_as_php'] = $_REQUEST['show_as_php'];
}
$common_functions = PMA_CommonFunctions::getInstance();
/**
* Sets globals from $_POST
*/
@@ -113,7 +115,7 @@ foreach (array_keys($_POST) as $post_key) {
}
// Check needed parameters
PMA_checkParameters(array('import_type', 'format'));
$common_functions->checkParameters(array('import_type', 'format'));
// We don't want anything special in format
$format = PMA_securePath($format);
@@ -207,7 +209,7 @@ if (! empty($id_bookmark)) {
if (isset($bookmark_variable) && ! empty($bookmark_variable)) {
$import_text = preg_replace(
'|/\*(.*)\[VARIABLE\](.*)\*/|imsU',
'${1}' . PMA_sqlAddSlashes($bookmark_variable) . '${2}',
'${1}' . $common_functions->sqlAddSlashes($bookmark_variable) . '${2}',
$import_text
);
}
@@ -291,7 +293,9 @@ if (! empty($local_import_file) && ! empty($cfg['UploadDir'])) {
// sanitize $local_import_file as it comes from a POST
$local_import_file = PMA_securePath($local_import_file);
$import_file = PMA_userDir($cfg['UploadDir']) . $local_import_file;
$import_file = $common_functions->userDir($cfg['UploadDir'])
. $local_import_file;
} elseif (empty($import_file) || ! is_uploaded_file($import_file)) {
$import_file = 'none';
}
@@ -428,13 +432,20 @@ if (! $error && isset($skip)) {
if (! $error) {
// Check for file existance
if (!file_exists('libraries/import/' . $format . '.php')) {
require_once("libraries/plugin_interface.lib.php");
$import_plugin = PMA_getPlugin(
"import",
$format,
'libraries/plugins/import/'
);
if ($import_plugin == null) {
$error = true;
$message = PMA_Message::error(__('Could not load import plugins, please check your installation!'));
$message = PMA_Message::error(
__('Could not load import plugins, please check your installation!')
);
} else {
// Do the real import
$plugin_param = $import_type;
include 'libraries/import/' . $format . '.php';
$import_plugin->doImport();
}
}
@@ -509,7 +520,7 @@ if (strlen($sql_query) <= $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
// There was an error?
if (isset($my_die)) {
foreach ($my_die AS $key => $die) {
PMA_mysqlDie($die['error'], $die['sql'], '', $err_url, $error);
$common_functions->mysqlDie($die['error'], $die['sql'], '', $err_url, $error);
}
}

View File

@@ -24,63 +24,45 @@ if (version_compare(PHP_VERSION, '5.4.0', '>=')
&& ini_get('session.upload_progress.enabled')
) {
if (!isset($_POST['session_upload_progress'])) {
$sessionupload = array();
$prefix = ini_get('session.upload_progress.prefix');
$sessionupload = array();
define('UPLOAD_PREFIX', ini_get('session.upload_progress.prefix'));
session_start();
foreach ($_SESSION as $key => $value) {
// only copy session-prefixed data
if (substr($key, 0, strlen($prefix)) == $prefix) {
$sessionupload[$key] = $value;
}
session_start();
foreach ($_SESSION as $key => $value) {
// only copy session-prefixed data
if (substr($key, 0, strlen(UPLOAD_PREFIX)) == UPLOAD_PREFIX) {
$sessionupload[$key] = $value;
}
// perform internal self-request
$url = 'http' .
((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 's' : '') .
'://' . $_SERVER['HTTP_HOST'] .
$_SERVER['REQUEST_URI'];
if (!function_exists('curl_exec') || !function_exists('getallheaders')) {
die();
}
$headers = @getallheaders();
if (!isset($headers['Cookie'])) {
die();
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt(
$ch, CURLOPT_POSTFIELDS,
'session_upload_progress=' . rawurlencode(serialize($sessionupload))
);
curl_setopt($ch, CURLOPT_COOKIE, $headers['Cookie']);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
// to avoid problems with self-signed certs
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
// show the result of the internal request
echo @curl_exec($ch);
die();
}
// PMA will kill all variables, so let's use a constant
define('SESSIONUPLOAD', serialize($sessionupload));
session_write_close();
session_name('phpMyAdmin');
session_id($_COOKIE['phpMyAdmin']);
}
define('PMA_MINIMUM_COMMON', 1);
require_once 'libraries/common.inc.php';
require_once 'libraries/display_import_ajax.lib.php';
if (isset($_POST['session_upload_progress'])) {
// this is the internal request response
// restore sessionupload from the POSTed data (see above),
// then write sessionupload back into the loaded session
if (defined('SESSIONUPLOAD')) {
// write sessionupload back into the loaded PMA session
$sessionupload = unserialize($_POST['session_upload_progress']);
$sessionupload = unserialize(SESSIONUPLOAD);
foreach ($sessionupload as $key => $value) {
$_SESSION[$key] = $value;
}
// remove session upload data that are not set anymore
foreach ($_SESSION as $key => $value) {
if (substr($key, 0, strlen(UPLOAD_PREFIX)) == UPLOAD_PREFIX
&& ! isset($sessionupload[$key])
) {
unset($_SESSION[$key]);
}
}
}
/**

View File

@@ -107,8 +107,8 @@ $response->disable();
var token = '<?php echo PMA_escapeJsString($_SESSION[' PMA_token ']); ?>';
var text_dir = '<?php echo PMA_escapeJsString($GLOBALS['text_dir']); ?>';
var pma_absolute_uri = '<?php echo PMA_escapeJsString($GLOBALS['cfg']['PmaAbsoluteUri']); ?>';
var pma_text_default_tab = '<?php echo PMA_escapeJsString(PMA_getTitleForTarget($GLOBALS['cfg']['DefaultTabTable'])); ?>';
var pma_text_left_default_tab = '<?php echo PMA_escapeJsString(PMA_getTitleForTarget($GLOBALS['cfg']['LeftDefaultTabTable'])); ?>';
var pma_text_default_tab = '<?php echo PMA_escapeJsString(PMA_CommonFunctions::getInstance()->getTitleForTarget($GLOBALS['cfg']['DefaultTabTable'])); ?>';
var pma_text_left_default_tab = '<?php echo PMA_escapeJsString(PMA_CommonFunctions::getInstance()->getTitleForTarget($GLOBALS['cfg']['LeftDefaultTabTable'])); ?>';
// for content and navigation frames

View File

@@ -45,7 +45,7 @@ $(function() {
button_options[PMA_messages['strNo']] = function() { $(this).dialog("close").remove(); }
$form.PMA_confirm(question, $form.attr('action'), function(url) {
PMA_ajaxShowMessage(PMA_messages['strRenamingDatabases']);
PMA_ajaxShowMessage(PMA_messages['strRenamingDatabases'], false);
$.get(url, $("#rename_db_form").serialize() + '&is_js_confirmed=1', function(data) {
if(data.success == true) {
@@ -60,7 +60,7 @@ $(function() {
.end()
.after(data.sql_query);
//Remove the empty notice div generated due to a NULL query passed to PMA_getMessage()
//Remove the empty notice div generated due to a NULL query passed to CommonFunctions::getMessage()
var $notice_class = $("#floating_menubar").next("div").find('.notice');
if ($notice_class.text() == '') {
$notice_class.remove();
@@ -84,7 +84,7 @@ $(function() {
$("#copy_db_form.ajax").live('submit', function(event) {
event.preventDefault();
var $msgbox = PMA_ajaxShowMessage(PMA_messages['strCopyingDatabase']);
PMA_ajaxShowMessage(PMA_messages['strCopyingDatabase'], false);
var $form = $(this);
@@ -94,7 +94,7 @@ $(function() {
// use messages that stay on screen
$('div.success, div.error').fadeOut();
if(data.success == true) {
$('#floating_menubar').after(data.message);
PMA_ajaxShowMessage(data.message);
if( $("#checkbox_switch").is(":checked")) {
window.parent.db = data.newname;
window.parent.refreshMain();
@@ -106,10 +106,8 @@ $(function() {
window.parent.refreshNavigation(true);
}
} else {
$('#floating_menubar').after(data.error);
PMA_ajaxShowMessage(data.error, false);
}
PMA_ajaxRemoveMessage($msgbox);
}) // end $.get
}) // end copy database

View File

@@ -29,7 +29,7 @@ function loadResult(result_path, table_name, link, ajaxEnable)
$(function() {
if(ajaxEnable) {
/** Hides the results shown by the delete criteria */
var $msg = PMA_ajaxShowMessage();
var $msg = PMA_ajaxShowMessage(PMA_messages['strBrowsing'], false);
$('#sqlqueryform').hide();
$('#togglequerybox').hide();
/** Load the browse results to the page */
@@ -81,11 +81,15 @@ function deleteResult(result_path, msg, ajaxEnable)
/** Refresh the search results after the deletion */
document.getElementById('buttonGo').click();
$('#togglequerybox').html(PMA_messages['strHideQueryBox']);
PMA_ajaxRemoveMessage($msg);
/** Show the results of the deletion option */
$('#browse-results').show();
$('#sqlqueryform').show();
$('#togglequerybox').show();
$('html, body')
.animate({
scrollTop: $("#browse-results").offset().top
}, 1000);
PMA_ajaxRemoveMessage($msg);
});
} else {
event.preventDefault();

View File

@@ -558,7 +558,7 @@ $(function() {
var checked = $checkbox.prop('checked');
if (!$(e.target).is(':checkbox, label')) {
checked = !checked;
$checkbox.prop('checked', checked);
$checkbox.prop('checked', checked).trigger('change');
}
if (checked) {
$tr.addClass('marked');
@@ -593,7 +593,8 @@ $(function() {
.slice(start, end + 1)
.removeClass('marked')
.find(':checkbox')
.prop('checked', false);
.prop('checked', false)
.trigger('change');
}
// handle new shift click
@@ -609,7 +610,8 @@ $(function() {
.slice(start, end + 1)
.addClass('marked')
.find(':checkbox')
.prop('checked', true);
.prop('checked', true)
.trigger('change');
// remember the last shift clicked row
last_shift_clicked_row = curr_row;
@@ -617,7 +619,7 @@ $(function() {
});
addDateTimePicker();
/**
* Add attribute to text boxes for iOS devices (based on bugID: 3508912)
*/
@@ -669,6 +671,7 @@ function markAllRows(container_id)
{
$("#" + container_id).find("input:checkbox:enabled").prop('checked', true)
.trigger("change")
.parents("tr").addClass("marked");
return true;
}
@@ -683,6 +686,7 @@ function unMarkAllRows(container_id)
{
$("#" + container_id).find("input:checkbox:enabled").prop('checked', false)
.trigger("change")
.parents("tr").removeClass("marked");
return true;
}
@@ -1520,10 +1524,12 @@ function PMA_ajaxRemoveMessage($this_msgbox)
.stop(true, true)
.fadeOut('medium');
if ($this_msgbox.is('.dismissable')) {
// Here we should destroy the qtip instance, but
// due to a bug in qtip's implementation we can
// only hide it without throwing JS errors.
$this_msgbox.qtip('hide');
if ($('#no_hint').length < 0) {
// Here we should destroy the qtip instance, but
// due to a bug in qtip's implementation we can
// only hide it without throwing JS errors.
$this_msgbox.qtip('hide');
}
} else {
$this_msgbox.remove();
}
@@ -1879,7 +1885,7 @@ function PMA_createProfilingChartJqplot(target, data)
seriesDefaults: {
renderer: $.jqplot.PieRenderer,
rendererOptions: {
showDataLabels: true
showDataLabels: true
}
},
legend: {
@@ -2494,49 +2500,6 @@ $(function() {
}); //end of Drop Database Ajax action
}); // end of $() for Drop Database
/**
* Attach Ajax event handlers for 'Create Database'. Used wherever libraries/
* display_create_database.lib.php is used, ie main.php and server_databases.php
*
* @see $cfg['AjaxEnable']
*/
$(function() {
$('#create_database_form.ajax').live('submit', function(event) {
event.preventDefault();
$form = $(this);
PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
PMA_prepareForAjaxRequest($form);
$.post($form.attr('action'), $form.serialize(), function(data) {
if (data.success == true) {
PMA_ajaxShowMessage(data.message);
//Append database's row to table
$("#tabledatabases")
.find('tbody')
.append(data.new_db_string)
.PMA_sort_table('.name')
.find('#db_summary_row')
.appendTo('#tabledatabases tbody')
.removeClass('odd even');
var $databases_count_object = $('#databases_count');
var databases_count = parseInt($databases_count_object.text()) + 1;
$databases_count_object.text(databases_count);
//Refresh navigation frame as a new database has been added
if (window.parent && window.parent.frame_navigation) {
window.parent.frame_navigation.location.reload();
}
} else {
PMA_ajaxShowMessage(data.error, false);
}
}); // end $.post()
}); // end $().live()
}); // end $() for Create Database
/**
* Validates the password field in a form
*
@@ -2944,7 +2907,7 @@ function checkIndexName(form_id)
/**
* Function to display tooltips that were
* generated on the PHP side by PMA_showHint()
* generated on the PHP side by CommonFunctions::showHint()
*
* @param object $div a div jquery object which specifies the
* domain for searching for tooltips. If we
@@ -3357,7 +3320,7 @@ $(function() {
PMA_init_slider();
/**
* Enables the text generated by PMA_linkOrButton() to be clickable
* Enables the text generated by CommonFunctions::linkOrButton() to be clickable
*/
$('a.formLinkSubmit').live('click', function(e) {
@@ -3825,6 +3788,33 @@ $(document).ready(function () {
}); // end $.live()
});
/**
* Watches checkboxes in a form to set the checkall box accordingly
*/
var checkboxes_sel = "input.checkall:checkbox:enabled";
$(checkboxes_sel).live("change", function () {
var $form = $(this.form);
// total number of checkboxes in current form
var total_boxes = $form.find(checkboxes_sel).length;
// number of checkboxes checked in current form
var checked_boxes = $form.find(checkboxes_sel + ":checked").length;
var $checkall = $form.find("input#checkall");
if (total_boxes == checked_boxes) {
$checkall.prop({checked: true, indeterminate: false});
}
else if (checked_boxes > 0) {
$checkall.prop({checked: true, indeterminate: true});
}
else {
$checkall.prop({checked: false, indeterminate: false});
}
});
$("input#checkall").live("change", function() {
var is_checked = $(this).is(":checked");
$(this.form).find(checkboxes_sel).prop("checked", is_checked)
.parents("tr").toggleClass("marked", is_checked);
});
/**
* Toggles row colors of a set of 'tr' elements starting from a given element
*

View File

@@ -30,7 +30,9 @@ $(function() {
* @var selected_dbs Array containing the names of the checked databases
*/
var selected_dbs = [];
$form.find('input:checkbox:checked').each(function () {
// loop over all checked checkboxes, except the #checkall checkbox
$form.find('input:checkbox:checked:not(#checkall)').each(function () {
$(this).closest('tr').addClass('removeMe');
selected_dbs[selected_dbs.length] = 'DROP DATABASE `' + escapeHtml($(this).val()) + '`;';
});
if (! selected_dbs.length) {
@@ -55,14 +57,65 @@ $(function() {
$.post(url, function(data) {
if(data.success == true) {
PMA_ajaxShowMessage(data.message);
var $rowsToRemove = $form.find('tr.removeMe');
var $databasesCount = $('#databases_count');
var newCount = parseInt($databasesCount.text()) - $rowsToRemove.length;
$databasesCount.text(newCount);
$rowsToRemove.remove();
$form.find('tbody').PMA_sort_table('.name');
if (window.parent && window.parent.frame_navigation) {
window.parent.frame_navigation.location.reload();
}
$('#tableslistcontainer').load('server_databases.php form#dbStatsForm');
} else {
PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + ": " + data.error, false);
$form.find('tr.removeMe').removeClass('removeMe');
PMA_ajaxShowMessage(data.error, false);
}
}); // end $.post()
}); // end $.PMA_confirm()
}) ; //end of Drop Database action
/**
* Attach Ajax event handlers for 'Create Database'.
*
* @see $cfg['AjaxEnable']
*/
$('#create_database_form.ajax').live('submit', function(event) {
event.preventDefault();
$form = $(this);
var newDbNameInput = $form.find('input[name=new_db]');
if (newDbNameInput.val() === '') {
newDbNameInput.focus();
alert(PMA_messages['strFormEmpty']);
return;
}
PMA_ajaxShowMessage(PMA_messages['strProcessingRequest']);
PMA_prepareForAjaxRequest($form);
$.post($form.attr('action'), $form.serialize(), function(data) {
if (data.success == true) {
PMA_ajaxShowMessage(data.message);
//Append database's row to table
$("#tabledatabases")
.find('tbody')
.append(data.new_db_string)
.PMA_sort_table('.name');
var $databases_count_object = $('#databases_count');
var databases_count = parseInt($databases_count_object.text()) + 1;
$databases_count_object.text(databases_count);
//Refresh navigation frame as a new database has been added
if (window.parent && window.parent.frame_navigation) {
window.parent.frame_navigation.location.reload();
}
} else {
PMA_ajaxShowMessage(data.error, false);
}
}); // end $.post()
}); // end $().live()
}); // end $()

View File

@@ -348,7 +348,7 @@ $(function() {
.end()
.after(data.sql_query);
//Remove the empty notice div generated due to a NULL query passed to PMA_getMessage()
//Remove the empty notice div generated due to a NULL query passed to CommonFunctions::getMessage()
var $notice_class = $("#floating_menubar").next("div").find('.notice');
if ($notice_class.text() == '') {
$notice_class.remove();

View File

@@ -437,7 +437,7 @@ function PMA_bytime($num, $precision)
$num = round($num, $precision);
if ($num == 0) {
$num = '<' . pow(10, -$precision);
$num = '<' . PMA_CommonFunctions::getInstance()->pow(10, -$precision);
}
return "$num $per";

File diff suppressed because it is too large Load Diff

View File

@@ -12,7 +12,7 @@ if (! defined('PHPMYADMIN')) {
/**
* Load vendor configuration.
*/
require './libraries/vendor_config.php';
require_once './libraries/vendor_config.php';
/**
* Configuration class

View File

@@ -0,0 +1,513 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Handles Database Search
*
* @package PhpMyAdmin
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* Class to handle database search
*
* @package PhpMyAdmin
*/
class PMA_DbSearch
{
/**
* Database name
*
* @access private
* @var string
*/
private $_db;
/**
* Table Names
*
* @access private
* @var array
*/
private $_tables_names_only;
/**
* Type of search
*
* @access private
* @var array
*/
private $_searchTypes;
/**
* Already set search type
*
* @access private
* @var integer
*/
private $_criteriaSearchType;
/**
* Already set search type's description
*
* @access private
* @var string
*/
private $_searchTypeDescription;
/**
* Search string/regexp
*
* @access private
* @var string
*/
private $_criteriaSearchString;
/**
* Criteria Tables to search in
*
* @access private
* @var array
*/
private $_criteriaTables;
/**
* Restrict the search to this column
*
* @access private
* @var string
*/
private $_criteriaColumnName;
/**
* PMA_CommonFunctions object
*
* @access private
* @var object
*/
private $_common_functions;
/**
* Public Constructor
*
* @param string $db Database name
*
*/
public function __construct($db)
{
$this->_db = $db;
// Sets criteria parameters
$this->_setSearchParams();
}
/**
* Get CommmonFunctions
*
* @return CommonFunctions object
*/
public function getCommonFunctions()
{
if (is_null($this->_common_functions)) {
$this->_common_functions = PMA_CommonFunctions::getInstance();
}
return $this->_common_functions;
}
/**
* Sets search parameters
*
*/
private function _setSearchParams()
{
$this->_tables_names_only = PMA_DBI_get_tables($this->_db);
$this->_searchTypes = array(
'1' => __('at least one of the words'),
'2' => __('all words'),
'3' => __('the exact phrase'),
'4' => __('as regular expression'),
);
if (empty($_REQUEST['criteriaSearchType'])
|| ! is_string($_REQUEST['criteriaSearchType'])
|| ! array_key_exists($_REQUEST['criteriaSearchType'], $this->_searchTypes)
) {
$this->_criteriaSearchType = 1;
unset($_REQUEST['submit_search']);
} else {
$this->_criteriaSearchType = (int) $_REQUEST['criteriaSearchType'];
$this->_searchTypeDescription = $this->_searchTypes[$_REQUEST['criteriaSearchType']];
}
if (empty($_REQUEST['criteriaSearchString'])
|| ! is_string($_REQUEST['criteriaSearchString'])
) {
$this->_criteriaSearchString = '';
unset($_REQUEST['submit_search']);
} else {
$this->_criteriaSearchString = $_REQUEST['criteriaSearchString'];
}
$this->_criteriaTables = array();
if (empty($_REQUEST['criteriaTables']) || ! is_array($_REQUEST['criteriaTables'])) {
unset($_REQUEST['submit_search']);
} elseif (! isset($_REQUEST['selectall']) && ! isset($_REQUEST['unselectall'])) {
$this->_criteriaTables = array_intersect(
$_REQUEST['criteriaTables'], $this->_tables_names_only
);
}
if (isset($_REQUEST['selectall'])) {
$this->_criteriaTables = $this->_tables_names_only;
} elseif (isset($_REQUEST['unselectall'])) {
$this->_criteriaTables = array();
}
if (empty($_REQUEST['criteriaColumnName'])
|| ! is_string($_REQUEST['criteriaColumnName'])
) {
unset($this->_criteriaColumnName);
} else {
$this->_criteriaColumnName = $this->getCommonFunctions()->sqlAddSlashes(
$_REQUEST['criteriaColumnName'], true
);
}
}
/**
* Builds the SQL search query
*
* @param string $table The table name
*
* @return array 3 SQL querys (for count, display and delete results)
*
* @todo can we make use of fulltextsearch IN BOOLEAN MODE for this?
* PMA_backquote
* PMA_DBI_free_result
* PMA_DBI_fetch_assoc
* $GLOBALS['db']
* explode
* count
* strlen
*/
private function _getSearchSqls($table)
{
// Statement types
$sqlstr_select = 'SELECT';
$sqlstr_delete = 'DELETE';
// Table to use
$sqlstr_from = ' FROM '
. $this->getCommonFunctions()->backquote($GLOBALS['db']) . '.'
. $this->getCommonFunctions()->backquote($table);
// Gets where clause for the query
$where_clause = $this->_getWhereClause($table);
// Builds complete queries
$sql['select_columns'] = $sqlstr_select . ' * ' . $sqlstr_from . $where_clause;
// here, I think we need to still use the COUNT clause, even for
// VIEWs, anyway we have a WHERE clause that should limit results
$sql['select_count'] = $sqlstr_select . ' COUNT(*) AS `count`'
. $sqlstr_from . $where_clause;
$sql['delete'] = $sqlstr_delete . $sqlstr_from . $where_clause;
return $sql;
}
/**
* Provides where clause for bulding SQL query
*
* @param string $table The table name
*
* @return string The generated where clause
*/
private function _getWhereClause($table)
{
$where_clause = '';
// Columns to select
$allColumns = PMA_DBI_get_columns($GLOBALS['db'], $table);
$likeClauses = array();
// Based on search type, decide like/regex & '%'/''
$like_or_regex = (($this->_criteriaSearchType == 4) ? 'REGEXP' : 'LIKE');
$automatic_wildcard = (($this->_criteriaSearchType < 3) ? '%' : '');
// For "as regular expression" (search option 4), LIKE won't be used
// Usage example: If user is seaching for a literal $ in a regexp search,
// he should enter \$ as the value.
$this->_criteriaSearchString = $this->getCommonFunctions()->sqlAddSlashes(
$this->_criteriaSearchString, ($this->_criteriaSearchType == 4 ? false : true)
);
// Extract search words or pattern
$search_words = (($this->_criteriaSearchType > 2)
? array($this->_criteriaSearchString) : explode(' ', $this->_criteriaSearchString));
foreach ($search_words as $search_word) {
// Eliminates empty values
if (strlen($search_word) === 0) {
continue;
}
$likeClausesPerColumn = array();
// for each column in the table
foreach ($allColumns as $column) {
if (! isset($this->_criteriaColumnName)
|| strlen($this->_criteriaColumnName) == 0
|| $column['Field'] == $this->_criteriaColumnName
) {
// Drizzle has no CONVERT and all text columns are UTF-8
$column = ((PMA_DRIZZLE)
? $this->getCommonFunctions()->backquote($column['Field'])
: 'CONVERT(' . $this->getCommonFunctions()->backquote($column['Field'])
. ' USING utf8)');
$likeClausesPerColumn[] = $column . ' ' . $like_or_regex . ' '
. "'"
. $automatic_wildcard . $search_word . $automatic_wildcard
. "'";
}
} // end for
if (count($likeClausesPerColumn) > 0) {
$likeClauses[] = implode(' OR ', $likeClausesPerColumn);
}
} // end for
// Use 'OR' if 'at least one word' is to be searched, else use 'AND'
$implode_str = ($this->_criteriaSearchType == 1 ? ' OR ' : ' AND ');
if ( empty($likeClauses)) {
// this could happen when the "inside column" does not exist
// in any selected tables
$where_clause = ' WHERE FALSE';
} else {
$where_clause = ' WHERE ('
. implode(') ' . $implode_str . ' (', $likeClauses)
. ')';
}
return $where_clause;
}
/**
* Displays database search results
*
* @return string HTML for search results
*/
public function getSearchResults()
{
$html_output = '';
// Displays search string
$html_output .= '<br />'
. '<table class="data">'
. '<caption class="tblHeaders">'
. sprintf(
__('Search results for "<i>%s</i>" %s:'),
htmlspecialchars($this->_criteriaSearchString),
$this->_searchTypeDescription
)
. '</caption>';
$num_search_result_total = 0;
$odd_row = true;
// For each table selected as search criteria
foreach ($this->_criteriaTables as $each_table) {
// Gets the SQL statements
$newsearchsqls = $this->_getSearchSqls($each_table);
// Executes the "COUNT" statement
$res_cnt = PMA_DBI_fetch_value($newsearchsqls['select_count']);
$num_search_result_total += $res_cnt;
// Gets the result row's HTML for a table
$html_output .= $this->_getResultsRow(
$each_table, $newsearchsqls, $odd_row
);
$odd_row = ! $odd_row;
} // end for
$html_output .= '</table>';
// Displays total number of matches
if (count($this->_criteriaTables) > 1) {
$html_output .= '<p>';
$html_output .= sprintf(
_ngettext(
'<b>Total:</b> <i>%s</i> match',
'<b>Total:</b> <i>%s</i> matches',
$num_search_result_total
),
$num_search_result_total
);
$html_output .= '</p>';
}
return $html_output;
}
/**
* Provides search results row with browse/delete links.
* (for a table)
*
* @param string $each_table Tables on which search is to be performed
* @param array $newsearchsqls Contains SQL queries
* @param bool $odd_row For displaying contrasting table rows
*
* @return string HTML row
*/
private function _getResultsRow($each_table, $newsearchsqls, $odd_row)
{
$this_url_params = array(
'db' => $GLOBALS['db'],
'goto' => 'db_sql.php',
'pos' => 0,
'is_js_confirmed' => 0,
);
$res_cnt = PMA_DBI_fetch_value($newsearchsqls['select_count']);
// Start forming search results row
$html_output = '<tr class="noclick ' . ($odd_row ? 'odd' : 'even') . '">';
// Displays results count for a table
$html_output .= '<td>';
$html_output .= sprintf(
_ngettext(
'%1$s match in <strong>%2$s</strong>',
'%1$s matches in <strong>%2$s</strong>', $res_cnt
),
$res_cnt, htmlspecialchars($each_table)
);
$html_output .= '</td>';
// Displays browse/delete link if result count > 0
if ($res_cnt > 0) {
$this_url_params['sql_query'] = $newsearchsqls['select_columns'];
$browse_result_path = 'sql.php' . PMA_generate_common_url($this_url_params);
$html_output .= '<td><a name="browse_search" href="'
. $browse_result_path . '" onclick="loadResult(\''
. $browse_result_path . '\',\'' . $each_table . '\',\''
. PMA_generate_common_url($GLOBALS['db'], $each_table) . '\',\''
. ($GLOBALS['cfg']['AjaxEnable']) .'\');return false;" >'
. __('Browse') . '</a></td>';
$this_url_params['sql_query'] = $newsearchsqls['delete'];
$delete_result_path = 'sql.php' . PMA_generate_common_url($this_url_params);
$html_output .= '<td><a name="delete_search" href="'
. $delete_result_path . '" onclick="deleteResult(\''
. $delete_result_path . '\' , \''
. sprintf(
__('Delete the matches for the %s table?'),
htmlspecialchars($each_table)
)
. '\',\'' . ($GLOBALS['cfg']['AjaxEnable']) . '\');return false;">'
. __('Delete') . '</a></td>';
} else {
$html_output .= '<td>&nbsp;</td>'
.'<td>&nbsp;</td>';
}// end if else
$html_output .= '</tr>';
return $html_output;
}
/**
* Provides the main search form's html
*
* @param array $url_params URL parameters
*
* @return string HTML for selection form
*/
public function getSelectionForm($url_params)
{
$html_output = '<a id="db_search"></a>';
$html_output .= '<form id="db_search_form"'
. ($GLOBALS['cfg']['AjaxEnable'] ? ' class="ajax"' : '')
. ' method="post" action="db_search.php" name="db_search">';
$html_output .= PMA_generate_common_hidden_inputs($GLOBALS['db']);
$html_output .= '<fieldset>';
// set legend caption
$html_output .= '<legend>' . __('Search in database') . '</legend>';
$html_output .= '<table class="formlayout">';
// inputbox for search phrase
$html_output .= '<tr>';
$html_output .= '<td>' . __('Words or values to search for (wildcard: "%"):')
. '</td>';
$html_output .= '<td><input type="text" name="criteriaSearchString" size="60"'
. ' value="' . htmlspecialchars($this->_criteriaSearchString) . '" /></td>';
$html_output .= '</tr>';
// choices for types of search
$html_output .= '<tr>';
$html_output .= '<td class="right vtop">' . __('Find:') . '</td>';
$html_output .= '<td>';
$choices = array(
'1' => __('at least one of the words')
. $this->getCommonFunctions()->showHint(
__('Words are separated by a space character (" ").')
),
'2' => __('all words')
. $this->getCommonFunctions()->showHint(
__('Words are separated by a space character (" ").')
),
'3' => __('the exact phrase'),
'4' => __('as regular expression')
. ' ' . $this->getCommonFunctions()->showMySQLDocu('Regexp', 'Regexp')
);
// 4th parameter set to true to add line breaks
// 5th parameter set to false to avoid htmlspecialchars() escaping in the label
// since we have some HTML in some labels
$html_output .= $this->getCommonFunctions()->getRadioFields(
'criteriaSearchType', $choices, $this->_criteriaSearchType, true, false
);
$html_output .= '</td></tr>';
// displays table names as select options
$html_output .= '<tr>';
$html_output .= '<td class="right vtop">' . __('Inside tables:') . '</td>';
$html_output .= '<td rowspan="2">';
$html_output .= '<select name="criteriaTables[]" size="6" multiple="multiple">';
foreach ($this->_tables_names_only as $each_table) {
if (in_array($each_table, $this->_criteriaTables)) {
$is_selected = ' selected="selected"';
} else {
$is_selected = '';
}
$html_output .= '<option value="' . htmlspecialchars($each_table) . '"'
. $is_selected . '>'
. str_replace(' ', '&nbsp;', htmlspecialchars($each_table))
. '</option>';
} // end for
$html_output .= '</select>';
$html_output .= '</td></tr>';
// Displays 'select all' and 'unselect all' links
$alter_select = '<a href="db_search.php'
. PMA_generate_common_url(
array_merge($url_params, array('selectall' => 1))
)
. '#db_search" onclick="setSelectOptions(\'db_search\', \'criteriaTables[]\', true); return false;">'
. __('Select All') . '</a> &nbsp;/&nbsp;';
$alter_select .= '<a href="db_search.php'
. PMA_generate_common_url(
array_merge($url_params, array('unselectall' => 1))
)
. '#db_search" onclick="setSelectOptions(\'db_search\', \'criteriaTables[]\', false); return false;">'
. __('Unselect All') . '</a>';
$html_output .= '<tr><td class="right vbottom">' . $alter_select . '</td></tr>';
// Inputbox for column name entry
$html_output .= '<tr>';
$html_output .= '<td class="right">' . __('Inside column:') . '</td>';
$html_output .= '<td><input type="text" name="criteriaColumnName" size="60"'
. 'value="'
. (! empty($this->_criteriaColumnName) ? htmlspecialchars($this->_criteriaColumnName) : '')
. '" /></td>';
$html_output .= '</tr>';
$html_output .= '</table>';
$html_output .= '</fieldset>';
$html_output .= '<fieldset class="tblFooters">';
$html_output .= '<input type="submit" name="submit_search" value="'
. __('Go') . '" id="buttonGo" />';
$html_output .= '</fieldset>';
$html_output .= '</form>';
$html_output .= $this->_getResultDivs();
return $html_output;
}
/**
* Provides div tags for browsing search results and sql query form.
*
* @return string div tags
*/
private function _getResultDivs()
{
$html_output = '<!-- These two table-image and table-link elements display'
. ' the table name in browse search results -->';
$html_output .= '<div id="table-info">';
$html_output .= '<a class="item" id="table-link" ></a>';
$html_output .= '</div>';
// div for browsing results
$html_output .= '<div id="browse-results">';
$html_output .= '<!-- this browse-results div is used to load the browse'
. ' and delete results in the db search -->';
$html_output .= '</div>';
$html_output .= '<br class="clearfloat" />';
$html_output .= '<div id="sqlqueryform">';
$html_output .= '<!-- this sqlqueryform div is used to load the delete form in'
. ' the db search -->';
$html_output .= '</div>';
$html_output .= '<!-- toggle query box link-->';
$html_output .= '<a id="togglequerybox"></a>';
return $html_output;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -288,7 +288,8 @@ class PMA_Error_Handler
} else {
ob_start();
var_dump($error);
$retval .= ob_end_clean();
$retval .= ob_get_contents();
ob_end_clean();
}
}
} else {

View File

@@ -159,7 +159,8 @@ class PMA_File
/**
* Gets file content
*
* @return string binary file content
* @return mixed the binary file content as a string,
* or false if no content
*
* @access public
*/
@@ -419,7 +420,7 @@ class PMA_File
}
$this->setName(
PMA_userDir($GLOBALS['cfg']['UploadDir']) . PMA_securePath($name)
PMA_CommonFunctions::getInstance()->userDir($GLOBALS['cfg']['UploadDir']) . PMA_securePath($name)
);
if (! $this->isReadable()) {
$this->_error_message = __('File could not be read');

View File

@@ -106,7 +106,7 @@ class PMA_Footer
// set current db, table and sql query in the querywindow
$query = '';
if (strlen($GLOBALS['sql_query']) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
if (isset($GLOBALS['sql_query']) && strlen($GLOBALS['sql_query']) > $GLOBALS['cfg']['MaxCharactersInDisplayedSQL']) {
$query = PMA_escapeJsString($GLOBALS['sql_query']);
}
$this->_scripts->addCode("
@@ -172,7 +172,8 @@ class PMA_Footer
ob_start();
print_r($_SESSION['debug']);
$retval .= ob_end_clean();
$retval .= ob_get_contents();
ob_end_clean();
$retval .= '</pre>';
$retval .= '</div>';
@@ -195,7 +196,7 @@ class PMA_Footer
$retval .= '<a href="index.php' . PMA_generate_common_url($url_params) . '"'
. ' title="' . __('Open new phpMyAdmin window') . '" target="_blank">';
if ($GLOBALS['cfg']['NavigationBarIconic']) {
$retval .= PMA_getImage(
$retval .= PMA_CommonFunctions::getInstance()->getImage(
'window-new.png',
__('Open new phpMyAdmin window')
);
@@ -322,7 +323,8 @@ class PMA_Footer
if (file_exists(CUSTOM_FOOTER_FILE)) {
ob_start();
include CUSTOM_FOOTER_FILE;
$retval .= ob_end_clean();
$retval .= ob_get_contents();
ob_end_clean();
}
} else if (! $this->_isAjax) {
$retval .= "</body></html>";

View File

@@ -168,7 +168,9 @@ class PMA_Header
. urlencode($_SESSION['PMA_Theme']->getId())
);
$this->_scripts->addFile('functions.js');
$this->_scripts->addCode(PMA_getReloadNavigationScript(true));
$this->_scripts->addCode(
PMA_CommonFunctions::getInstance()->getReloadNavigationScript(true)
);
}
/**
@@ -297,7 +299,8 @@ class PMA_Header
if (file_exists(CUSTOM_HEADER_FILE)) {
ob_start();
include CUSTOM_HEADER_FILE;
$retval .= ob_end_clean();
$retval .= ob_get_contents();
ob_end_clean();
}
// offer to load user preferences from localStorage
if ($this->_userprefsOfferImport) {
@@ -334,7 +337,7 @@ class PMA_Header
*/
$GLOBALS['now'] = gmdate('D, d M Y H:i:s') . ' GMT';
/* Prevent against ClickJacking by allowing frames only from same origin */
if (! $GLOBALS['cfg']['AllowThirdPartyFraming']) {
if (! $GLOBALS['cfg']['AllowThirdPartyFraming'] && ! defined('TESTSUITE')) {
header(
'X-Frame-Options: SAMEORIGIN'
);
@@ -350,7 +353,7 @@ class PMA_Header
);
}
PMA_noCacheHeader();
if (! defined('IS_TRANSFORMATION_WRAPPER')) {
if (! defined('IS_TRANSFORMATION_WRAPPER') && ! defined('TESTSUITE')) {
// Define the charset to be used
header('Content-Type: text/html; charset=utf-8');
}
@@ -450,7 +453,7 @@ class PMA_Header
$temp_title = $GLOBALS['cfg']['TitleDefault'];
}
$this->_title = htmlspecialchars(
PMA_expandUserString($temp_title)
PMA_CommonFunctions::getInstance()->expandUserString($temp_title)
);
} else {
$this->_title = 'phpMyAdmin';
@@ -494,7 +497,7 @@ class PMA_Header
}
$retval .= "<noscript>";
$retval .= PMA_message::error(
__("Javascript must be enabled past this point")
__("Javascript must be enabled past this point")
)->getDisplay();
$retval .= "</noscript>";
}

View File

@@ -21,50 +21,50 @@ class PMA_Index
*
* @var array
*/
protected static $_registry = array();
private static $_registry = array();
/**
* @var string The name of the schema
*/
protected $_schema = '';
private $_schema = '';
/**
* @var string The name of the table
*/
protected $_table = '';
private $_table = '';
/**
* @var string The name of the index
*/
protected $_name = '';
private $_name = '';
/**
* Columns in index
*
* @var array
*/
protected $_columns = array();
private $_columns = array();
/**
* The index method used (BTREE, SPATIAL, FULLTEXT, HASH, RTREE).
*
* @var string
*/
protected $_type = '';
private $_type = '';
/**
* The index choice (PRIMARY, UNIQUE, INDEX, SPATIAL, FULLTEXT)
*
* @var string
*/
protected $_choice = '';
private $_choice = '';
/**
* Various remarks.
*
* @var string
*/
protected $_remarks = '';
private $_remarks = '';
/**
* Any comment provided for the index with a COMMENT attribute when the
@@ -72,19 +72,19 @@ class PMA_Index
*
* @var string
*/
protected $_comment = '';
private $_comment = '';
/**
* @var integer 0 if the index cannot contain duplicates, 1 if it can.
*/
protected $_non_unique = 0;
private $_non_unique = 0;
/**
* Indicates how the key is packed. NULL if it is not.
*
* @var string
*/
protected $_packed = null;
private $_packed = null;
/**
* Constructor
@@ -157,7 +157,7 @@ class PMA_Index
*
* @return boolean whether loading was successful
*/
static protected function _loadIndexes($table, $schema)
static private function _loadIndexes($table, $schema)
{
if (isset(PMA_Index::$_registry[$schema][$table])) {
return true;
@@ -202,7 +202,8 @@ class PMA_Index
// $columns[names][]
// $columns[sub_parts][]
foreach ($columns['names'] as $key => $name) {
$sub_part = isset($columns['sub_parts'][$key]) ? $columns['sub_parts'][$key] : '';
$sub_part = isset($columns['sub_parts'][$key])
? $columns['sub_parts'][$key] : '';
$_columns[] = array(
'Column_name' => $name,
'Sub_part' => $sub_part,
@@ -423,6 +424,8 @@ class PMA_Index
*/
static public function getView($table, $schema, $print_mode = false)
{
$common_functions = PMA_CommonFunctions::getInstance();
$indexes = PMA_Index::getFromTable($table, $schema);
$no_indexes_class = count($indexes) > 0 ? ' hide' : '';
@@ -433,7 +436,10 @@ class PMA_Index
if (! $print_mode) {
$r = '<fieldset>';
$r .= '<legend id="index_header">' . __('Indexes');
$r .= PMA_showMySQLDocu('optimization', 'optimizing-database-structure');
$r .= $common_functions->showMySQLDocu(
'optimization', 'optimizing-database-structure'
);
$r .= '</legend>';
$r .= $no_indexes;
if (count($indexes) < 1) {
@@ -480,40 +486,61 @@ class PMA_Index
if ($GLOBALS['cfg']['AjaxEnable']) {
$r .= ' ajax';
}
$r .= '" ' . $row_span . '>'
. ' <a href="tbl_indexes.php' . PMA_generate_common_url($this_params)
. '">' . PMA_getIcon('b_edit.png', __('Edit')) . '</a>'
$r .= '" ' . $row_span . '>' . ' <a href="tbl_indexes.php'
. PMA_generate_common_url($this_params) . '">'
. $common_functions->getIcon('b_edit.png', __('Edit')) . '</a>'
. '</td>' . "\n";
$this_params = $GLOBALS['url_params'];
if ($index->getName() == 'PRIMARY') {
$this_params['sql_query'] = 'ALTER TABLE ' . PMA_backquote($table) . ' DROP PRIMARY KEY;';
$this_params['message_to_show'] = __('The primary key has been dropped');
$js_msg = PMA_jsFormat('ALTER TABLE ' . $table . ' DROP PRIMARY KEY');
$this_params['sql_query'] = 'ALTER TABLE '
. $common_functions->backquote($table)
. ' DROP PRIMARY KEY;';
$this_params['message_to_show']
= __('The primary key has been dropped');
$js_msg = PMA_jsFormat(
'ALTER TABLE ' . $table . ' DROP PRIMARY KEY'
);
} else {
$this_params['sql_query'] = 'ALTER TABLE ' . PMA_backquote($table) . ' DROP INDEX ' . PMA_backquote($index->getName()) . ';';
$this_params['message_to_show'] = sprintf(__('Index %s has been dropped'), $index->getName());
$js_msg = PMA_jsFormat('ALTER TABLE ' . $table . ' DROP INDEX ' . $index->getName()) . ';';
$this_params['sql_query'] = 'ALTER TABLE '
. $common_functions->backquote($table) . ' DROP INDEX '
. $common_functions->backquote($index->getName()) . ';';
$this_params['message_to_show'] = sprintf(
__('Index %s has been dropped'), $index->getName()
);
$js_msg = PMA_jsFormat(
'ALTER TABLE ' . $table . ' DROP INDEX '
. $index->getName() . ';'
);
}
$r .= '<td ' . $row_span . '>';
$r .= '<input type="hidden" class="drop_primary_key_index_msg" value="' . $js_msg . '" />';
$r .= '<input type="hidden" class="drop_primary_key_index_msg"'
. ' value="' . $js_msg . '" />';
$r .= ' <a ';
if ($GLOBALS['cfg']['AjaxEnable']) {
$r .= 'class="drop_primary_key_index_anchor" ';
}
$r .= ' href="sql.php' . PMA_generate_common_url($this_params)
. '" >'
. PMA_getIcon('b_drop.png', __('Drop')) . '</a>'
. $common_functions->getIcon('b_drop.png', __('Drop')) . '</a>'
. '</td>' . "\n";
}
if (! $print_mode) {
$r .= '<th ' . $row_span . '>' . htmlspecialchars($index->getName()) . '</th>';
$r .= '<th ' . $row_span . '>'
. htmlspecialchars($index->getName())
. '</th>';
} else {
$r .= '<td ' . $row_span . '>' . htmlspecialchars($index->getName()) . '</td>';
$r .= '<td ' . $row_span . '>'
. htmlspecialchars($index->getName())
. '</td>';
}
$r .= '<td ' . $row_span . '>' . htmlspecialchars($index->getType()) . '</td>';
$r .= '<td ' . $row_span . '>'
. htmlspecialchars($index->getType())
. '</td>';
$r .= '<td ' . $row_span . '>' . $index->isUnique(true) . '</td>';
$r .= '<td ' . $row_span . '>' . $index->isPacked(true) . '</td>';
@@ -526,9 +553,15 @@ class PMA_Index
$r .= ' (' . $column->getSubPart() . ')';
}
$r .= '</td>';
$r .= '<td>' . htmlspecialchars($column->getCardinality()) . '</td>';
$r .= '<td>' . htmlspecialchars($column->getCollation()) . '</td>';
$r .= '<td>' . htmlspecialchars($column->getNull(true)) . '</td>';
$r .= '<td>'
. htmlspecialchars($column->getCardinality())
. '</td>';
$r .= '<td>'
. htmlspecialchars($column->getCollation())
. '</td>';
$r .= '<td>'
. htmlspecialchars($column->getNull(true))
. '</td>';
if ($column->getSeqInIndex() == 1) {
$r .= '<td ' . $row_span . '>'
@@ -595,7 +628,9 @@ class PMA_Index
// did not find any difference
// so it makes no sense to have this two equal indexes
$message = PMA_Message::notice(__('The indexes %1$s and %2$s seem to be equal and one of them could possibly be removed.'));
$message = PMA_Message::notice(
__('The indexes %1$s and %2$s seem to be equal and one of them could possibly be removed.')
);
$message->addParam($each_index->getName());
$message->addParam($while_index->getName());
$output .= $message->getDisplay();
@@ -617,17 +652,18 @@ class PMA_Index_Column
/**
* @var string The column name
*/
protected $_name = '';
private $_name = '';
/**
* @var integer The column sequence number in the index, starting with 1.
*/
protected $_seq_in_index = 1;
private $_seq_in_index = 1;
/**
* @var string How the column is sorted in the index. “A” (Ascending) or NULL (Not sorted)
* @var string How the column is sorted in the index. “A” (Ascending) or
* NULL (Not sorted)
*/
protected $_collation = null;
private $_collation = null;
/**
* The number of indexed characters if the column is only partly indexed,
@@ -635,7 +671,7 @@ class PMA_Index_Column
*
* @var integer
*/
protected $_sub_part = null;
private $_sub_part = null;
/**
* Contains YES if the column may contain NULL.
@@ -643,7 +679,7 @@ class PMA_Index_Column
*
* @var string
*/
protected $_null = '';
private $_null = '';
/**
* An estimate of the number of unique values in the index. This is updated
@@ -654,7 +690,7 @@ class PMA_Index_Column
*
* @var integer
*/
protected $_cardinality = null;
private $_cardinality = null;
public function __construct($params = array())
{

View File

@@ -205,7 +205,8 @@ class PMA_List_Database extends PMA_List
// thus containing not escaped _ or %
if (! preg_match('/(^|[^\\\\])(_|%)/', $each_only_db)) {
// ... not contains wildcard
$items[] = PMA_unescapeMysqlWildcards($each_only_db);
$items[] = PMA_CommonFunctions::getInstance()
->unescapeMysqlWildcards($each_only_db);
continue;
}
@@ -443,13 +444,16 @@ class PMA_List_Database extends PMA_List
*/
protected function checkAgainstPrivTables()
{
$common_functions = PMA_CommonFunctions::getInstance();
// 1. get allowed dbs from the "mysql.db" table
// User can be blank (anonymous user)
$local_query = "
SELECT DISTINCT `Db` FROM `mysql`.`db`
WHERE `Select_priv` = 'Y'
AND `User`
IN ('" . PMA_sqlAddSlashes($GLOBALS['cfg']['Server']['user']) . "', '')";
IN ('" . $common_functions->sqlAddSlashes($GLOBALS['cfg']['Server']['user']) . "', '')";
$tmp_mydbs = PMA_DBI_fetch_result(
$local_query, null, null, $GLOBALS['controllink']
);
@@ -509,7 +513,7 @@ class PMA_List_Database extends PMA_List
$local_query = 'SELECT DISTINCT `Db` FROM `mysql`.`tables_priv`';
$local_query .= ' WHERE `Table_priv` LIKE \'%Select%\'';
$local_query .= ' AND `User` = \'';
$local_query .= PMA_sqlAddSlashes($GLOBALS['cfg']['Server']['user']) . '\'';
$local_query .= $common_functions->sqlAddSlashes($GLOBALS['cfg']['Server']['user']) . '\'';
$rs = PMA_DBI_try_query($local_query, $GLOBALS['controllink']);
if ($rs && @PMA_DBI_num_rows($rs)) {
while ($row = PMA_DBI_fetch_assoc($rs)) {

View File

@@ -36,7 +36,22 @@ class PMA_Menu
* @access private
* @var string
*/
private $_table;
private $_table;
private $_common_functions;
/**
* Get CommmonFunctions
*
* @return CommonFunctions object
*/
public function getCommonFunctions()
{
if (is_null($this->_common_functions)) {
$this->_common_functions = PMA_CommonFunctions::getInstance();
}
return $this->_common_functions;
}
/**
* Creates a new instance of PMA_Menu
@@ -77,7 +92,7 @@ class PMA_Menu
if (isset($GLOBALS['buffer_message'])) {
$buffer_message = $GLOBALS['buffer_message'];
}
$retval .= PMA_getMessage($GLOBALS['message']);
$retval .= $this->getCommonFunctions()->getMessage($GLOBALS['message']);
unset($GLOBALS['message']);
if (isset($buffer_message)) {
$GLOBALS['buffer_message'] = $buffer_message;
@@ -103,7 +118,7 @@ class PMA_Menu
} else {
$tabs = $this->_getServerTabs();
}
return PMA_generateHtmlTabs($tabs, $url_params);
return $this->getCommonFunctions()->getHtmlTabs($tabs, $url_params);
}
/**
@@ -132,7 +147,7 @@ class PMA_Menu
$retval .= "<div id='floating_menubar'></div>";
$retval .= "<div id='serverinfo'>";
if ($GLOBALS['cfg']['NavigationBarIconic']) {
$retval .= PMA_getImage(
$retval .= $this->getCommonFunctions()->getImage(
's_host.png',
'',
array('class' => 'item')
@@ -149,7 +164,7 @@ class PMA_Menu
if (strlen($this->_db)) {
$retval .= $separator;
if ($GLOBALS['cfg']['NavigationBarIconic']) {
$retval .= PMA_getImage(
$retval .= $this->getCommonFunctions()->getImage(
's_db.png',
'',
array('class' => 'item')
@@ -172,7 +187,7 @@ class PMA_Menu
$retval .= $separator;
if ($GLOBALS['cfg']['NavigationBarIconic']) {
$icon = $tbl_is_view ? 'b_views.png' : 's_tbl.png';
$retval .= PMA_getImage(
$retval .= $this->getCommonFunctions()->getImage(
$icon,
'',
array('class' => 'item')
@@ -238,12 +253,7 @@ class PMA_Menu
{
$db_is_information_schema = PMA_is_system_schema($this->_db);
$tbl_is_view = PMA_Table::isView($this->_db, $this->_table);
$table_status = PMA_Table::sGetStatusInfo($this->_db, $this->_table);
$table_info_num_rows = 0;
if (isset($table_status['Rows'])) {
$table_info_num_rows = $table_status['Rows'];
}
$table_info_num_rows = PMA_Table::countRecords($this->_db, $this->_table);
$tabs = array();
@@ -295,7 +305,7 @@ class PMA_Menu
}
if (! $db_is_information_schema
&& ! PMA_DRIZZLE
&& PMA_currentUserHasPrivilege('TRIGGER', $this->_db, $this->_table)
&& $this->getCommonFunctions()->currentUserHasPrivilege('TRIGGER', $this->_db, $this->_table)
&& ! $tbl_is_view
) {
$tabs['triggers']['link'] = 'tbl_triggers.php';
@@ -391,14 +401,14 @@ class PMA_Menu
}
if (PMA_MYSQL_INT_VERSION >= 50106
&& ! PMA_DRIZZLE
&& PMA_currentUserHasPrivilege('EVENT', $this->_db)
&& $this->getCommonFunctions()->currentUserHasPrivilege('EVENT', $this->_db)
) {
$tabs['events']['link'] = 'db_events.php';
$tabs['events']['text'] = __('Events');
$tabs['events']['icon'] = 'b_events.png';
}
if (! PMA_DRIZZLE
&& PMA_currentUserHasPrivilege('TRIGGER', $this->_db)
&& $this->getCommonFunctions()->currentUserHasPrivilege('TRIGGER', $this->_db)
) {
$tabs['triggers']['link'] = 'db_triggers.php';
$tabs['triggers']['text'] = __('Triggers');
@@ -430,7 +440,7 @@ class PMA_Menu
{
$is_superuser = PMA_isSuperuser();
$binary_logs = null;
if (! PMA_DRIZZLE) {
if (!defined('PMA_DRIZZLE') || (defined('PMA_DRIZZLE') && ! PMA_DRIZZLE)) {
$binary_logs = PMA_DBI_fetch_result(
'SHOW MASTER LOGS',
'Log_name',
@@ -500,7 +510,7 @@ class PMA_Menu
$tabs['charset']['link'] = 'server_collations.php';
$tabs['charset']['text'] = __('Charsets');
if (PMA_DRIZZLE) {
if (defined('PMA_DRIZZLE') && PMA_DRIZZLE) {
$tabs['plugins']['icon'] = 'b_engine.png';
$tabs['plugins']['link'] = 'server_plugins.php';
$tabs['plugins']['text'] = __('Plugins');

View File

@@ -33,7 +33,7 @@
* $hint->addParam('[a@./Documentation.html#cfg_Example@_blank]');
* $hint->addParam('[/a]');
* // add this hint as a tooltip
* $hint = PMA_showHint($hint);
* $hint = showHint($hint);
*
* // add the retrieved tooltip reference to the original message
* $message->addMessage($hint);

View File

@@ -1,7 +1,7 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
*
*
*
* @package PhpMyAdmin
*/
@@ -10,7 +10,7 @@ if (! defined('PHPMYADMIN')) {
}
/**
*
*
*
* @package PhpMyAdmin
*/
@@ -85,7 +85,9 @@ class PMA_OutputBuffering
ob_start('ob_gzhandler');
}
ob_start();
header('X-ob_mode: ' . $this->_mode);
if (! defined('TESTSUITE')) {
header('X-ob_mode: ' . $this->_mode);
}
register_shutdown_function('PMA_OutputBuffering::stop');
$this->_on = true;
}

View File

@@ -48,7 +48,7 @@ class PMA_PDF extends TCPDF
$this->SetY(-15);
$this->SetFont(PMA_PDF_FONT, '', 14);
$this->Cell(0, 6, __('Page number:') . ' ' . $this->getAliasNumPage() . '/' . $this->getAliasNbPages(), 'T', 0, 'C');
$this->Cell(0, 6, PMA_localisedDate(), 0, 1, 'R');
$this->Cell(0, 6, PMA_CommonFunctions::getInstance()->localisedDate(), 0, 1, 'R');
$this->SetY(20);
// set footerset

View File

@@ -47,8 +47,8 @@ class PMA_RecentTable
if (strlen($GLOBALS['cfg']['Server']['pmadb'])
&& strlen($GLOBALS['cfg']['Server']['recent'])
) {
$this->pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) . "."
. PMA_backquote($GLOBALS['cfg']['Server']['recent']);
$this->pma_table = PMA_CommonFunctions::getInstance()->backquote($GLOBALS['cfg']['Server']['pmadb']) . "."
. PMA_CommonFunctions::getInstance()->backquote($GLOBALS['cfg']['Server']['recent']);
}
$server_id = $GLOBALS['server'];
if (! isset($_SESSION['tmp_user_values']['recent_tables'][$server_id])) {
@@ -83,7 +83,7 @@ class PMA_RecentTable
= " SELECT `tables` FROM " . $this->pma_table .
" WHERE `username` = '" . $GLOBALS['cfg']['Server']['user'] . "'";
$row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
$row = PMA_DBI_fetch_array(PMA_queryAsControlUser($sql_query));
if (isset($row[0])) {
return json_decode($row[0], true);
} else {
@@ -101,7 +101,10 @@ class PMA_RecentTable
$username = $GLOBALS['cfg']['Server']['user'];
$sql_query
= " REPLACE INTO " . $this->pma_table . " (`username`, `tables`)" .
" VALUES ('" . $username . "', '" . PMA_sqlAddSlashes(json_encode($this->tables)) . "')";
" VALUES ('" . $username . "', '"
. PMA_CommonFunctions::getInstance()->sqlAddSlashes(
json_encode($this->tables)
) . "')";
$success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);

View File

@@ -153,6 +153,7 @@ class PMA_Scripts
foreach ($this->_files as $file) {
$retval .= $this->_includeFile(
$file['filename'],
$file['timestamp'],
$file['conditional_ie']
);
}

View File

@@ -23,7 +23,8 @@ define('PMA_ENGINE_DETAILS_TYPE_NUMERIC', 2); //Has no effect yet...
define('PMA_ENGINE_DETAILS_TYPE_BOOLEAN', 3); // 'ON' or 'OFF'
/**
* base Storage Engine Class
* Base Storage Engine Class
*
* @package PhpMyAdmin
*/
class PMA_StorageEngine
@@ -75,7 +76,8 @@ class PMA_StorageEngine
AND p.plugin_name NOT IN ('FunctionEngine', 'schema')";
$storage_engines = PMA_DBI_fetch_result($sql, 'Engine');
} else {
$storage_engines = PMA_DBI_fetch_result('SHOW STORAGE ENGINES', 'Engine');
$storage_engines
= PMA_DBI_fetch_result('SHOW STORAGE ENGINES', 'Engine');
}
}
@@ -88,7 +90,8 @@ class PMA_StorageEngine
* @param string $name The name of the select form element
* @param string $id The ID of the form field
* @param string $selected The selected engine
* @param boolean $offerUnavailableEngines Should unavailable storage engines be offered?
* @param boolean $offerUnavailableEngines Should unavailable storage
* engines be offered?
*
* @static
* @return string html selectbox
@@ -116,8 +119,10 @@ class PMA_StorageEngine
$output .= ' <option value="' . htmlspecialchars($key). '"'
. (empty($details['Comment'])
? '' : ' title="' . htmlspecialchars($details['Comment']) . '"')
. (strtolower($key) == $selected || (empty($selected) && $details['Support'] == 'DEFAULT')
? ' selected="selected"' : '') . '>' . "\n"
. (strtolower($key) == $selected
|| (empty($selected) && $details['Support'] == 'DEFAULT')
? ' selected="selected"' : '')
. '>' . "\n"
. ' ' . htmlspecialchars($details['Engine']) . "\n"
. ' </option>' . "\n";
}
@@ -180,7 +185,9 @@ class PMA_StorageEngine
$ret .= '<tr class="' . ($odd_row ? 'odd' : 'even') . '">' . "\n"
. ' <td>' . "\n";
if (! empty($details['desc'])) {
$ret .= ' ' . PMA_showHint($details['desc']) . "\n";
$ret .= ' '
. PMA_CommonFunctions::getInstance()->showHint($details['desc'])
. "\n";
}
$ret .= ' </td>' . "\n"
. ' <th>' . htmlspecialchars($details['title']) . '</th>' . "\n"
@@ -192,7 +199,7 @@ class PMA_StorageEngine
unset($parsed_size);
break;
case PMA_ENGINE_DETAILS_TYPE_NUMERIC:
$ret .= PMA_formatNumber($details['value']) . ' ';
$ret .= PMA_CommonFunctions::getInstance()->formatNumber($details['value']) . ' ';
break;
default:
$ret .= htmlspecialchars($details['value']) . ' ';
@@ -214,7 +221,7 @@ class PMA_StorageEngine
}
/**
* returns the engine specific handling for
* Returns the engine specific handling for
* PMA_ENGINE_DETAILS_TYPE_SIZE type variables.
*
* This function should be overridden when
@@ -225,7 +232,7 @@ class PMA_StorageEngine
*/
function resolveTypeSize($value)
{
return PMA_formatByteDown($value);
return PMA_CommonFunctions::getInstance()->formatByteDown($value);
}
/**

View File

@@ -65,6 +65,21 @@ class PMA_Table
* @var array messages
*/
var $messages = array();
private $_common_functions;
/**
* Get CommmonFunctions
*
* @return CommonFunctions object
*/
public function getCommonFunctions()
{
if (is_null($this->_common_functions)) {
$this->_common_functions = PMA_CommonFunctions::getInstance();
}
return $this->_common_functions;
}
/**
* Constructor
@@ -131,7 +146,7 @@ class PMA_Table
function getName($backquoted = false)
{
if ($backquoted) {
return PMA_backquote($this->name);
return $this->getCommonFunctions()->backquote($this->name);
}
return $this->name;
}
@@ -158,7 +173,7 @@ class PMA_Table
function getDbName($backquoted = false)
{
if ($backquoted) {
return PMA_backquote($this->db_name);
return $this->getCommonFunctions()->backquote($this->db_name);
}
return $this->db_name;
}
@@ -186,6 +201,9 @@ class PMA_Table
*/
static public function isView($db = null, $table = null)
{
$common_functions = PMA_CommonFunctions::getInstance();
if (empty($db) || empty($table)) {
return false;
}
@@ -202,8 +220,8 @@ class PMA_Table
$result = PMA_DBI_fetch_result(
"SELECT TABLE_NAME
FROM information_schema.VIEWS
WHERE TABLE_SCHEMA = '" . PMA_sqlAddSlashes($db) . "'
AND TABLE_NAME = '" . PMA_sqlAddSlashes($table) . "'"
WHERE TABLE_SCHEMA = '" . $common_functions->sqlAddSlashes($db) . "'
AND TABLE_NAME = '" . $common_functions->sqlAddSlashes($table) . "'"
);
return $result ? true : false;
}
@@ -237,49 +255,6 @@ class PMA_Table
return null;
}
/**
* loads structure data
* (this function is work in progress? not yet used)
*
* @return boolean
*/
function loadStructure()
{
$table_info = PMA_DBI_get_tables_full(
$this->getDbName(),
$this->getName()
);
if (false === $table_info) {
return false;
}
$this->settings = $table_info;
if ($this->get('TABLE_ROWS') === null) {
$this->set(
'TABLE_ROWS',
PMA_Table::countRecords(
$this->getDbName(),
$this->getName(),
true
)
);
}
$create_options = explode(' ', $this->get('TABLE_ROWS'));
// export create options by its name as variables into global namespace
// f.e. pack_keys=1 becomes available as $pack_keys with value of '1'
foreach ($create_options as $each_create_option) {
$each_create_option = explode('=', $each_create_option);
if (isset($each_create_option[1])) {
$this->set($$each_create_option[0], $each_create_option[1]);
}
}
return true;
}
/**
* Checks if this is a merge table
*
@@ -403,9 +378,11 @@ class PMA_Table
$default_type = 'USER_DEFINED', $default_value = '', $extra = '',
$comment = '', &$field_primary = null, $move_to = ''
) {
$common_functions = PMA_CommonFunctions::getInstance();
$is_timestamp = strpos(strtoupper($type), 'TIMESTAMP') !== false;
$query = PMA_backquote($name) . ' ' . $type;
$query = $common_functions->backquote($name) . ' ' . $type;
if ($length != ''
&& ! preg_match(
@@ -455,10 +432,10 @@ class PMA_Table
} else {
// Invalid BOOLEAN value
$query .= ' DEFAULT \''
. PMA_sqlAddSlashes($default_value) . '\'';
. $common_functions->sqlAddSlashes($default_value) . '\'';
}
} else {
$query .= ' DEFAULT \'' . PMA_sqlAddSlashes($default_value) . '\'';
$query .= ' DEFAULT \'' . $common_functions->sqlAddSlashes($default_value) . '\'';
}
break;
case 'NULL' :
@@ -508,14 +485,14 @@ class PMA_Table
} // end if (auto_increment)
}
if (!empty($comment)) {
$query .= " COMMENT '" . PMA_sqlAddSlashes($comment) . "'";
$query .= " COMMENT '" . $common_functions->sqlAddSlashes($comment) . "'";
}
// move column
if ($move_to == '-first') { // dash can't appear as part of column name
$query .= ' FIRST';
} elseif ($move_to != '') {
$query .= ' AFTER ' . PMA_backquote($move_to);
$query .= ' AFTER ' . $common_functions->backquote($move_to);
}
return $query;
} // end function
@@ -537,6 +514,9 @@ class PMA_Table
static public function countRecords($db, $table, $force_exact = false,
$is_view = null
) {
$common_functions = PMA_CommonFunctions::getInstance();
if (isset(PMA_Table::$cache[$db][$table]['ExactRows'])) {
$row_count = PMA_Table::$cache[$db][$table]['ExactRows'];
} else {
@@ -569,8 +549,8 @@ class PMA_Table
// fast enough
if (! $is_view || (PMA_DRIZZLE && PMA_is_system_schema($db))) {
$row_count = PMA_DBI_fetch_value(
'SELECT COUNT(*) FROM ' . PMA_backquote($db) . '.'
. PMA_backquote($table)
'SELECT COUNT(*) FROM ' . PMA_CommonFunctions::getInstance()->backquote($db) . '.'
. PMA_CommonFunctions::getInstance()->backquote($table)
);
} else {
// For complex views, even trying to get a partial record
@@ -586,8 +566,8 @@ class PMA_Table
// Use try_query because it can fail (when a VIEW is
// based on a table that no longer exists)
$result = PMA_DBI_try_query(
'SELECT 1 FROM ' . PMA_backquote($db) . '.'
. PMA_backquote($table) . ' LIMIT '
'SELECT 1 FROM ' . $common_functions->backquote($db) . '.'
. $common_functions->backquote($table) . ' LIMIT '
. $GLOBALS['cfg']['MaxExactCountViews'],
null,
PMA_DBI_QUERY_STORE
@@ -633,7 +613,7 @@ class PMA_Table
$attribute, $collation, $null, $default_type, $default_value,
$extra, $comment, &$field_primary, $index, $move_to
) {
return PMA_backquote($oldcol) . ' '
return PMA_CommonFunctions::getInstance()->backquote($oldcol) . ' '
. PMA_Table::generateFieldSpec(
$newcol, $type, $index, $length, $attribute,
$collation, $null, $default_type, $default_value, $extra,
@@ -664,38 +644,40 @@ class PMA_Table
static public function duplicateInfo($work, $pma_table, $get_fields,
$where_fields, $new_fields
) {
$common_functions = PMA_CommonFunctions::getInstance();
$last_id = -1;
if (isset($GLOBALS['cfgRelation']) && $GLOBALS['cfgRelation'][$work]) {
$select_parts = array();
$row_fields = array();
foreach ($get_fields as $get_field) {
$select_parts[] = PMA_backquote($get_field);
$select_parts[] = $common_functions->backquote($get_field);
$row_fields[$get_field] = 'cc';
}
$where_parts = array();
foreach ($where_fields as $_where => $_value) {
$where_parts[] = PMA_backquote($_where) . ' = \''
. PMA_sqlAddSlashes($_value) . '\'';
$where_parts[] = $common_functions->backquote($_where) . ' = \''
. $common_functions->sqlAddSlashes($_value) . '\'';
}
$new_parts = array();
$new_value_parts = array();
foreach ($new_fields as $_where => $_value) {
$new_parts[] = PMA_backquote($_where);
$new_value_parts[] = PMA_sqlAddSlashes($_value);
$new_parts[] = $common_functions->backquote($_where);
$new_value_parts[] = $common_functions->sqlAddSlashes($_value);
}
$table_copy_query = '
SELECT ' . implode(', ', $select_parts) . '
FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.'
. PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
FROM ' . $common_functions->backquote($GLOBALS['cfgRelation']['db']) . '.'
. $common_functions->backquote($GLOBALS['cfgRelation'][$pma_table]) . '
WHERE ' . implode(' AND ', $where_parts);
// must use PMA_DBI_QUERY_STORE here, since we execute another
// query inside the loop
$table_copy_rs = PMA_query_as_controluser(
$table_copy_rs = PMA_queryAsControlUser(
$table_copy_query, true, PMA_DBI_QUERY_STORE
);
@@ -703,20 +685,20 @@ class PMA_Table
$value_parts = array();
foreach ($table_copy_row as $_key => $_val) {
if (isset($row_fields[$_key]) && $row_fields[$_key] == 'cc') {
$value_parts[] = PMA_sqlAddSlashes($_val);
$value_parts[] = $common_functions->sqlAddSlashes($_val);
}
}
$new_table_query = 'INSERT IGNORE INTO '
. PMA_backquote($GLOBALS['cfgRelation']['db'])
. '.' . PMA_backquote($GLOBALS['cfgRelation'][$pma_table]) . '
. $common_functions->backquote($GLOBALS['cfgRelation']['db'])
. '.' . $common_functions->backquote($GLOBALS['cfgRelation'][$pma_table]) . '
(' . implode(', ', $select_parts) . ',
' . implode(', ', $new_parts) . ')
VALUES
(\'' . implode('\', \'', $value_parts) . '\',
\'' . implode('\', \'', $new_value_parts) . '\')';
PMA_query_as_controluser($new_table_query);
PMA_queryAsControlUser($new_table_query);
$last_id = PMA_DBI_insert_id();
} // end while
@@ -745,6 +727,8 @@ class PMA_Table
$target_table, $what, $move, $mode
) {
global $err_url;
$common_functions = PMA_CommonFunctions::getInstance();
/* Try moving table directly */
if ($move && $what == 'data') {
@@ -781,7 +765,7 @@ class PMA_Table
return false;
}
$source = PMA_backquote($source_db) . '.' . PMA_backquote($source_table);
$source = $common_functions->backquote($source_db) . '.' . $common_functions->backquote($source_table);
if (! isset($target_db) || ! strlen($target_db)) {
$target_db = $source_db;
}
@@ -790,16 +774,26 @@ class PMA_Table
// when moving table from replicated one to not replicated one
PMA_DBI_select_db($target_db);
$target = PMA_backquote($target_db) . '.' . PMA_backquote($target_table);
$target = $common_functions->backquote($target_db) . '.' . $common_functions->backquote($target_table);
// do not create the table if dataonly
if ($what != 'dataonly') {
include_once './libraries/export/sql.php';
require_once "libraries/plugin_interface.lib.php";
// get Export SQL instance
$export_sql_plugin = PMA_getPlugin(
"export",
"sql",
'libraries/plugins/export/',
array(
'export_type' => $export_type,
'single_table' => isset($single_table)
)
);
$no_constraints_comments = true;
$GLOBALS['sql_constraints_query'] = '';
$sql_structure = PMA_getTableDef(
$sql_structure = $export_sql_plugin->getTableDef(
$source_db, $source_table, "\n", $err_url, false, false
);
unset($no_constraints_comments);
@@ -808,7 +802,7 @@ class PMA_Table
$i = 0;
if (empty($analyzed_sql[0]['create_table_fields'])) {
// this is not a CREATE TABLE, so find the first VIEW
$target_for_view = PMA_backquote($target_db);
$target_for_view = $common_functions->backquote($target_db);
while (true) {
if ($parsed_sql[$i]['type'] == 'alpha_reservedWord'
&& $parsed_sql[$i]['data'] == 'VIEW'
@@ -842,7 +836,7 @@ class PMA_Table
$i++;
}
/* no need to PMA_backquote() */
/* no need to backquote() */
if (isset($target_for_view)) {
// this a view definition; we just found the first db name
// that follows DEFINER VIEW
@@ -852,7 +846,7 @@ class PMA_Table
// and change them to the target db, ensuring we stay into
// the $parsed_sql limits
$last = $parsed_sql['len'] - 1;
$backquoted_source_db = PMA_backquote($source_db);
$backquoted_source_db = $common_functions->backquote($source_db);
for (++$i; $i <= $last; $i++) {
if ($parsed_sql[$i]['type'] == $table_delimiter
&& $parsed_sql[$i]['data'] == $backquoted_source_db
@@ -878,8 +872,8 @@ class PMA_Table
$drop_query = 'DROP TABLE';
}
$drop_query .= ' IF EXISTS '
. PMA_backquote($target_db) . '.'
. PMA_backquote($target_table);
. $common_functions->backquote($target_db) . '.'
. $common_functions->backquote($target_table);
PMA_DBI_query($drop_query);
$GLOBALS['sql_query'] .= "\n" . $drop_query . ';';
@@ -909,7 +903,7 @@ class PMA_Table
}
// replace it by the target table name, no need
// to PMA_backquote()
// to backquote()
$parsed_sql[$i]['data'] = $target;
// now we must remove all $table_delimiter that follow a
@@ -991,26 +985,26 @@ class PMA_Table
// Get all comments and MIME-Types for current table
$comments_copy_query = 'SELECT
column_name, comment' . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . '
FROM ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info']) . '
FROM ' . $common_functions->backquote($GLOBALS['cfgRelation']['db']) . '.' . $common_functions->backquote($GLOBALS['cfgRelation']['column_info']) . '
WHERE
db_name = \'' . PMA_sqlAddSlashes($source_db) . '\' AND
table_name = \'' . PMA_sqlAddSlashes($source_table) . '\'';
$comments_copy_rs = PMA_query_as_controluser($comments_copy_query);
db_name = \'' . $common_functions->sqlAddSlashes($source_db) . '\' AND
table_name = \'' . $common_functions->sqlAddSlashes($source_table) . '\'';
$comments_copy_rs = PMA_queryAsControlUser($comments_copy_query);
// Write every comment as new copied entry. [MIME]
while ($comments_copy_row = PMA_DBI_fetch_assoc($comments_copy_rs)) {
$new_comment_query = 'REPLACE INTO ' . PMA_backquote($GLOBALS['cfgRelation']['db']) . '.' . PMA_backquote($GLOBALS['cfgRelation']['column_info'])
$new_comment_query = 'REPLACE INTO ' . $common_functions->backquote($GLOBALS['cfgRelation']['db']) . '.' . $common_functions->backquote($GLOBALS['cfgRelation']['column_info'])
. ' (db_name, table_name, column_name, comment' . ($GLOBALS['cfgRelation']['mimework'] ? ', mimetype, transformation, transformation_options' : '') . ') '
. ' VALUES('
. '\'' . PMA_sqlAddSlashes($target_db) . '\','
. '\'' . PMA_sqlAddSlashes($target_table) . '\','
. '\'' . PMA_sqlAddSlashes($comments_copy_row['column_name']) . '\''
. ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . PMA_sqlAddSlashes($comments_copy_row['comment']) . '\','
. '\'' . PMA_sqlAddSlashes($comments_copy_row['mimetype']) . '\','
. '\'' . PMA_sqlAddSlashes($comments_copy_row['transformation']) . '\','
. '\'' . PMA_sqlAddSlashes($comments_copy_row['transformation_options']) . '\'' : '')
. '\'' . $common_functions->sqlAddSlashes($target_db) . '\','
. '\'' . $common_functions->sqlAddSlashes($target_table) . '\','
. '\'' . $common_functions->sqlAddSlashes($comments_copy_row['column_name']) . '\''
. ($GLOBALS['cfgRelation']['mimework'] ? ',\'' . $common_functions->sqlAddSlashes($comments_copy_row['comment']) . '\','
. '\'' . $common_functions->sqlAddSlashes($comments_copy_row['mimetype']) . '\','
. '\'' . $common_functions->sqlAddSlashes($comments_copy_row['transformation']) . '\','
. '\'' . $common_functions->sqlAddSlashes($comments_copy_row['transformation_options']) . '\'' : '')
. ')';
PMA_query_as_controluser($new_comment_query);
PMA_queryAsControlUser($new_comment_query);
} // end while
PMA_DBI_free_result($comments_copy_rs);
unset($comments_copy_rs);
@@ -1214,8 +1208,8 @@ class PMA_Table
$handle_triggers = $this->getDbName() != $new_db && $triggers;
if ($handle_triggers) {
foreach ($triggers as $trigger) {
$sql = 'DROP TRIGGER IF EXISTS ' . PMA_backquote($this->getDbName())
. '.' . PMA_backquote($trigger['name']) . ';';
$sql = 'DROP TRIGGER IF EXISTS ' . $this->getCommonFunctions()->backquote($this->getDbName())
. '.' . $this->getCommonFunctions()->backquote($trigger['name']) . ';';
PMA_DBI_query($sql);
}
}
@@ -1297,7 +1291,7 @@ class PMA_Table
continue;
}
$return[] = $this->getFullName($backquoted) . '.'
. ($backquoted ? PMA_backquote($index[0]) : $index[0]);
. ($backquoted ? $this->getCommonFunctions()->backquote($index[0]) : $index[0]);
}
return $return;
@@ -1327,7 +1321,7 @@ class PMA_Table
$return = array();
foreach ($indexed as $column) {
$return[] = $this->getFullName($backquoted) . '.'
. ($backquoted ? PMA_backquote($column) : $column);
. ($backquoted ? $this->getCommonFunctions()->backquote($column) : $column);
}
return $return;
@@ -1350,7 +1344,7 @@ class PMA_Table
$return = array();
foreach ($indexed as $column) {
$return[] = $this->getFullName($backquoted) . '.'
. ($backquoted ? PMA_backquote($column) : $column);
. ($backquoted ? $this->getCommonFunctions()->backquote($column) : $column);
}
return $return;
@@ -1363,16 +1357,16 @@ class PMA_Table
*/
protected function getUiPrefsFromDb()
{
$pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
PMA_backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
$pma_table = $this->getCommonFunctions()->backquote($GLOBALS['cfg']['Server']['pmadb']) ."."
. $this->getCommonFunctions()->backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
// Read from phpMyAdmin database
$sql_query = " SELECT `prefs` FROM " . $pma_table
. " WHERE `username` = '" . $GLOBALS['cfg']['Server']['user'] . "'"
. " AND `db_name` = '" . PMA_sqlAddSlashes($this->db_name) . "'"
. " AND `table_name` = '" . PMA_sqlAddSlashes($this->name) . "'";
. " AND `db_name` = '" . $this->getCommonFunctions()->sqlAddSlashes($this->db_name) . "'"
. " AND `table_name` = '" . $this->getCommonFunctions()->sqlAddSlashes($this->name) . "'";
$row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
$row = PMA_DBI_fetch_array(PMA_queryAsControlUser($sql_query));
if (isset($row[0])) {
return json_decode($row[0], true);
} else {
@@ -1387,14 +1381,14 @@ class PMA_Table
*/
protected function saveUiPrefsToDb()
{
$pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) . "."
. PMA_backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
$pma_table = $this->getCommonFunctions()->backquote($GLOBALS['cfg']['Server']['pmadb']) . "."
. $this->getCommonFunctions()->backquote($GLOBALS['cfg']['Server']['table_uiprefs']);
$username = $GLOBALS['cfg']['Server']['user'];
$sql_query = " REPLACE INTO " . $pma_table
. " VALUES ('" . $username . "', '" . PMA_sqlAddSlashes($this->db_name)
. "', '" . PMA_sqlAddSlashes($this->name) . "', '"
. PMA_sqlAddSlashes(json_encode($this->uiprefs)) . "', NULL)";
. " VALUES ('" . $username . "', '" . $this->getCommonFunctions()->sqlAddSlashes($this->db_name)
. "', '" . $this->getCommonFunctions()->sqlAddSlashes($this->name) . "', '"
. $this->getCommonFunctions()->sqlAddSlashes(json_encode($this->uiprefs)) . "', NULL)";
$success = PMA_DBI_try_query($sql_query, $GLOBALS['controllink']);
@@ -1424,7 +1418,7 @@ class PMA_Table
$message = PMA_Message::error(
sprintf(
__('Failed to cleanup table UI preferences (see $cfg[\'Servers\'][$i][\'MaxTableUiprefs\'] %s)'),
PMA_showDocu('cfg_Servers_MaxTableUiprefs')
$this->getCommonFunctions()->showDocu('cfg_Servers_MaxTableUiprefs')
)
);
$message->addMessage('<br /><br />');

View File

@@ -80,6 +80,22 @@ class PMA_TableSearch
* @var array
*/
private $_foreigners;
private $_common_functions;
/**
* Get CommmonFunctions
*
* @return CommonFunctions object
*/
public function getCommonFunctions()
{
if (is_null($this->_common_functions)) {
$this->_common_functions = PMA_CommonFunctions::getInstance();
}
return $this->_common_functions;
}
/**
* Public Constructor
@@ -88,7 +104,6 @@ class PMA_TableSearch
* @param string $table Table name
* @param string $searchType Whether normal or zoom search
*
* @return New PMA_TableSearch
*/
public function __construct($db, $table, $searchType)
{
@@ -102,7 +117,7 @@ class PMA_TableSearch
$this->_geomColumnFlag = false;
$this->_foreigners = array();
// Loads table's information
$this->_loadTableInfo($this->_db, $this->_table);
$this->_loadTableInfo();
}
/**
@@ -111,7 +126,7 @@ class PMA_TableSearch
* @return array column names
*/
public function getColumnNames()
{
{
return $this->_columnNames;
}
@@ -119,15 +134,13 @@ class PMA_TableSearch
* Gets all the columns of a table along with their types, collations
* and whether null or not.
*
* @return array Array containing the column list, column types, collations
* and null constraint
*/
private function _loadTableInfo()
{
// Gets the list and number of columns
$columns = PMA_DBI_get_columns($this->_db, $this->_table, null, true);
// Get details about the geometry fucntions
$geom_types = PMA_getGISDatatypes();
$geom_types = $this->getCommonFunctions()->getGISDatatypes();
foreach ($columns as $key => $row) {
// set column name
@@ -231,9 +244,9 @@ class PMA_TableSearch
if ($in_fbs) {
$edit_url = 'gis_data_editor.php?' . PMA_generate_common_url();
$edit_str = PMA_getIcon('b_edit.png', __('Edit/Insert'));
$edit_str = $this->getCommonFunctions()->getIcon('b_edit.png', __('Edit/Insert'));
$html_output .= '<span class="open_search_gis_editor">';
$html_output .= PMA_linkOrButton(
$html_output .= $this->getCommonFunctions()->linkOrButton(
$edit_url, $edit_str, array(), false, false, '_blank'
);
$html_output .= '</span>';
@@ -260,10 +273,10 @@ class PMA_TableSearch
$column_index, $titles, $foreignMaxLimit, $criteriaValues, $column_id,
$in_zoom_search_edit = false
) {
$html_output = '';
$html_output = '';
if (is_array($foreignData['disp_row'])) {
$html_output .= '<select name="criteriaValues[' . $column_index . ']" id="'
. $column_id . $column_index .'">';
$html_output .= '<select name="criteriaValues[' . $column_index . ']"'
. ' id="' . $column_id . $column_index .'">';
$html_output .= PMA_foreignDropdown(
$foreignData['disp_row'], $foreignData['foreign_field'],
$foreignData['foreign_display'], '', $foreignMaxLimit
@@ -329,9 +342,9 @@ EOT;
$html_output .= '<select name="criteriaValues[' . ($column_index)
. '][]" id="' . $column_id . $column_index .'">';
} else {
$html_output .= '<select name="criteriaValues[' . ($column_index)
. '][]" id="' . $column_id . $column_index .'" multiple="multiple" size="'
. min(3, $cnt_value) . '">';
$html_output .= '<select name="criteriaValues[' . $column_index . '][]"'
. ' id="' . $column_id . $column_index . '" multiple="multiple"'
. ' size="' . min(3, $cnt_value) . '">';
}
//Add select options
@@ -366,7 +379,7 @@ EOT;
* @param bool $in_fbs Whether we are in 'function based search'
* @param bool $in_zoom_search_edit Whether we are in zoom search edit
*
* @return string HTML content for viewing foreing data and elements
* @return string HTML content for viewing foreign data and elements
* for search criteria input.
*/
private function _getInputbox($foreignData, $column_name, $column_type,
@@ -377,14 +390,15 @@ EOT;
$column_type = (string)$column_type;
$column_id = ($in_zoom_search_edit) ? 'edit_fieldID_' : 'fieldID_';
//Get inputbox based on different column types (Foreign key, geometrical, enum)
// Get inputbox based on different column types
// (Foreign key, geometrical, enum)
if ($this->_foreigners && isset($this->_foreigners[$column_name])) {
$str .= $this->_getForeignKeyInputBox(
$foreignData, $column_name, $column_index, $titles,
$foreignMaxLimit, $criteriaValues, $column_id
);
} elseif (in_array($column_type, PMA_getGISDatatypes())) {
} elseif (in_array($column_type, $this->getCommonFunctions()->getGISDatatypes())) {
$str .= $this->_getGeometricalInputBox($column_index, $in_fbs);
} elseif (strncasecmp($column_type, 'enum', 4) == 0
@@ -401,7 +415,9 @@ EOT;
if ($column_type == 'date') {
$the_class .= ' datefield';
} elseif ($column_type == 'datetime' || substr($column_type, 0, 9) == 'timestamp') {
} elseif ($column_type == 'datetime'
|| substr($column_type, 0, 9) == 'timestamp'
) {
$the_class .= ' datetimefield';
} elseif (substr($column_type, 0, 3) == 'bit') {
$the_class .= ' bit';
@@ -423,13 +439,14 @@ EOT;
* Return the where clause in case column's type is ENUM.
*
* @param mixed $criteriaValues Search criteria input
* @param string $func_type Search fucntion/operator
* @param string $func_type Search function/operator
*
* @return string part of where clause.
*/
private function _getEnumWhereClause($criteriaValues, $func_type)
{
$where = '';
$common_functions = PMA_CommonFunctions::getInstance();
if (! empty($criteriaValues)) {
if (! is_array($criteriaValues)) {
$criteriaValues = explode(',', $criteriaValues);
@@ -449,10 +466,11 @@ EOT;
$parens_open = '';
$parens_close = '';
}
$enum_where = '\'' . PMA_sqlAddslashes($criteriaValues[0]) . '\'';
$enum_where = '\''
. $common_functions->sqlAddSlashes($criteriaValues[0]) . '\'';
for ($e = 1; $e < $enum_selected_count; $e++) {
$enum_where .= ', \'' . PMA_sqlAddslashes($criteriaValues[$e])
. '\'';
$enum_where .= ', \''
. $common_functions->sqlAddSlashes($criteriaValues[$e]) . '\'';
}
$where = ' ' . $func_type . ' ' . $parens_open
@@ -466,13 +484,14 @@ EOT;
*
* @param mixed $criteriaValues Search criteria input
* @param string $names Name of the column on which search is submitted
* @param string $func_type Search fucntion/operator
* @param string $func_type Search function/operator
* @param bool $geom_func Whether geometry functions should be applied
*
* @return string part of where clause.
*/
private function _getGeomWhereClause($criteriaValues, $names, $func_type, $geom_func = null)
{
private function _getGeomWhereClause($criteriaValues, $names,
$func_type, $geom_func = null
) {
$geom_unary_functions = array(
'IsEmpty' => 1,
'IsSimple' => 1,
@@ -482,28 +501,32 @@ EOT;
$where = '';
// Get details about the geometry fucntions
$geom_funcs = PMA_getGISFunctions($types, true, false);
$geom_funcs = $this->getCommonFunctions()->getGISFunctions($types, true, false);
// New output type is the output type of the function being applied
$types = $geom_funcs[$geom_func]['type'];
// If the function takes a single parameter
if ($geom_funcs[$geom_func]['params'] == 1) {
$backquoted_name = $geom_func . '(' . PMA_backquote($names) . ')';
$backquoted_name = $geom_func . '(' . $this->getCommonFunctions()->backquote($names) . ')';
} else {
// If the function takes two parameters
// create gis data from the criteria input
$gis_data = PMA_createGISData($criteriaValues);
$where = $geom_func . '(' . PMA_backquote($names) . ',' . $gis_data . ')';
$gis_data = $this->getCommonFunctions()->createGISData($criteriaValues);
$where = $geom_func . '(' . $this->getCommonFunctions()->backquote($names) . ',' . $gis_data . ')';
return $where;
}
// If the where clause is something like 'IsEmpty(`spatial_col_name`)'
if (isset($geom_unary_functions[$geom_func]) && trim($criteriaValues) == '') {
if (isset($geom_unary_functions[$geom_func])
&& trim($criteriaValues) == ''
) {
$where = $backquoted_name;
} elseif (in_array($types, PMA_getGISDatatypes()) && ! empty($criteriaValues)) {
} elseif (in_array($types, $this->getCommonFunctions()->getGISDatatypes())
&& ! empty($criteriaValues)
) {
// create gis data from the criteria input
$gis_data = PMA_createGISData($criteriaValues);
$gis_data = $this->getCommonFunctions()->createGISData($criteriaValues);
$where = $backquoted_name . ' ' . $func_type . ' ' . $gis_data;
}
return $where;
@@ -516,7 +539,7 @@ EOT;
* @param string $names Name of the column on which search is submitted
* @param string $types Type of the field
* @param string $collations Field collation
* @param string $func_type Search fucntion/operator
* @param string $func_type Search function/operator
* @param bool $unaryFlag Whether operator unary or not
* @param bool $geom_func Whether geometry functions should be applied
*
@@ -525,12 +548,17 @@ EOT;
private function _getWhereClause($criteriaValues, $names, $types, $collations,
$func_type, $unaryFlag, $geom_func = null
) {
$common_functions = PMA_CommonFunctions::getInstance();
// If geometry function is set
if ($geom_func != null && trim($geom_func) != '') {
return $this->_getGeomWhereClause($criteriaValues, $names, $func_type, $geom_func);
return $this->_getGeomWhereClause(
$criteriaValues, $names, $func_type, $geom_func
);
}
$backquoted_name = PMA_backquote($names);
$backquoted_name = $this->getCommonFunctions()->backquote($names);
$where = '';
if ($unaryFlag) {
$criteriaValues = '';
@@ -541,9 +569,10 @@ EOT;
$where .= $this->_getEnumWhereClause($criteriaValues, $func_type);
} elseif ($criteriaValues != '') {
// For these types we quote the value. Even if it's another type (like INT),
// for a LIKE we always quote the value. MySQL converts strings to numbers
// and numbers to strings as necessary during the comparison
// For these types we quote the value. Even if it's another type
// (like INT), for a LIKE we always quote the value. MySQL converts
// strings to numbers and numbers to strings as necessary
// during the comparison
if (preg_match('@char|binary|blob|text|set|date|time|year@i', $types)
|| strpos(' ' . $func_type, 'LIKE')
) {
@@ -572,7 +601,8 @@ EOT;
// quote values one by one
$values = explode(',', $criteriaValues);
foreach ($values as &$value) {
$value = $quot . PMA_sqlAddslashes(trim($value)) . $quot;
$value = $quot . $common_functions->sqlAddSlashes(trim($value))
. $quot;
}
if ($func_type == 'BETWEEN' || $func_type == 'NOT BETWEEN') {
@@ -584,8 +614,8 @@ EOT;
. ' (' . implode(',', $values) . ')';
}
} else {
$where = $backquoted_name . ' ' . $func_type . ' '
. $quot . PMA_sqlAddslashes($criteriaValues) . $quot;
$where = $backquoted_name . ' ' . $func_type . ' ' . $quot
. $common_functions->sqlAddSlashes($criteriaValues) . $quot;
}
} // end if
@@ -616,16 +646,16 @@ EOT;
$sql_query .= (count($_POST['columnsToDisplay'])
== count($_POST['criteriaColumnNames'])
? '* '
: implode(', ', PMA_backquote($_POST['columnsToDisplay'])));
: implode(', ', $this->getCommonFunctions()->backquote($_POST['columnsToDisplay'])));
} // end if
$sql_query .= ' FROM ' . PMA_backquote($_POST['table']);
$sql_query .= ' FROM ' . $this->getCommonFunctions()->backquote($_POST['table']);
$whereClause = $this->_generateWhereClause();
$sql_query .= $whereClause;
// if the search results are to be ordered
if (isset($_POST['orderByColumn']) && $_POST['orderByColumn'] != '--nil--') {
$sql_query .= ' ORDER BY ' . PMA_backquote($_POST['orderByColumn'])
$sql_query .= ' ORDER BY ' . $this->getCommonFunctions()->backquote($_POST['orderByColumn'])
. ' ' . $_POST['order'];
} // end if
return $sql_query;
@@ -640,7 +670,9 @@ EOT;
{
$fullWhereClause = '';
if (isset($_POST['customWhereClause']) && trim($_POST['customWhereClause']) != '') {
if (isset($_POST['customWhereClause'])
&& trim($_POST['customWhereClause']) != ''
) {
$fullWhereClause .= ' WHERE ' . $_POST['customWhereClause'];
return $fullWhereClause;
}
@@ -665,7 +697,9 @@ EOT;
$_POST['criteriaValues'][$column_index],
$_POST['criteriaColumnNames'][$column_index],
$_POST['criteriaColumnTypes'][$column_index],
$_POST['criteriaColumnCollations'][$column_index], $operator, $unaryFlag,
$_POST['criteriaColumnCollations'][$column_index],
$operator,
$unaryFlag,
$tmp_geom_func
);
@@ -700,15 +734,17 @@ EOT;
* Displays 'Function' column if it is present
*/
$html_output .= '<td>';
$geom_types = PMA_getGISDatatypes();
$geom_types = $this->getCommonFunctions()->getGISDatatypes();
// if a geometry column is present
if (in_array($this->_columnTypes[$column_index], $geom_types)) {
$html_output .= '<select class="geom_func" name="geom_func['
. $column_index . ']">';
// get the relevant list of GIS functions
$funcs = PMA_getGISFunctions($this->_columnTypes[$column_index], true, true);
$funcs = $this->getCommonFunctions()
->getGISFunctions($this->_columnTypes[$column_index], true, true);
/**
* For each function in the list of functions, add an option to select list
* For each function in the list of functions,
* add an option to select list
*/
foreach ($funcs as $func_name => $func) {
$name = isset($func['display']) ? $func['display'] : $func_name;
@@ -731,14 +767,18 @@ EOT;
private function _getOptions()
{
$html_output = '';
$html_output .= PMA_getDivForSliderEffect('searchoptions', __('Options'));
$html_output .= $this->getCommonFunctions()->getDivForSliderEffect(
'searchoptions', __('Options')
);
/**
* Displays columns select list for selecting distinct columns in the search
*/
$html_output .= '<fieldset id="fieldset_select_fields">'
. '<legend>' . __('Select columns (at least one):') . '</legend>'
. '<select name="columnsToDisplay[]" size="' . min(count($this->_columnNames), 10)
. '" multiple="multiple">';
. '<select name="columnsToDisplay[]"'
. ' size="' . min(count($this->_columnNames), 10) . '"'
. ' multiple="multiple">';
// Displays the list of the fields
foreach ($this->_columnNames as $each_field) {
$html_output .= ' '
@@ -756,9 +796,11 @@ EOT;
$html_output .= '<fieldset id="fieldset_search_conditions">'
. '<legend>' . '<em>' . __('Or') . '</em> '
. __('Add search conditions (body of the "where" clause):') . '</legend>';
$html_output .= PMA_showMySQLDocu('SQL-Syntax', 'Functions');
$html_output .= '<input type="text" name="customWhereClause" class="textfield"'
. 'size="64" />';
$html_output .= $this->getCommonFunctions()->showMySQLDocu(
'SQL-Syntax', 'Functions'
);
$html_output .= '<input type="text" name="customWhereClause"'
. ' class="textfield" size="64" />';
$html_output .= '</fieldset>';
/**
@@ -771,7 +813,8 @@ EOT;
. '</fieldset>';
/**
* Displays option for ordering search results by a column value (Asc or Desc)
* Displays option for ordering search results
* by a column value (Asc or Desc)
*/
$html_output .= '<fieldset id="fieldset_display_order">'
. '<legend>' . __('Display order:') . '</legend>'
@@ -786,7 +829,7 @@ EOT;
'ASC' => __('Ascending'),
'DESC' => __('Descending')
);
$html_output .= PMA_getRadioFields(
$html_output .= $this->getCommonFunctions()->getRadioFields(
'order', $choices, 'ASC', false, true, "formelement"
);
unset($choices);
@@ -833,8 +876,9 @@ EOT;
$html_output .= '<td><label for="maxRowPlotLimit">'
. __("Maximum rows to plot") . '</label></td>';
$html_output .= '<td>';
$html_output .= '<input type="text" name="maxPlotLimit" id="maxRowPlotLimit" '
. 'value="' . ((! empty($_POST['maxPlotLimit']))
$html_output .= '<input type="text" name="maxPlotLimit"'
. ' id="maxRowPlotLimit"'
. ' value="' . ((! empty($_POST['maxPlotLimit']))
? htmlspecialchars($_POST['maxPlotLimit'])
: $GLOBALS['cfg']['maxRowPlotLimit'])
. '" />';
@@ -858,7 +902,7 @@ EOT;
? $_POST['criteriaColumnOperators'][$search_index] : '');
$entered_value = (isset($_POST['criteriaValues'])
? $_POST['criteriaValues'] : '');
$titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse foreign values'));
$titles['Browse'] = $this->getCommonFunctions()->getIcon('b_browse.png', __('Browse foreign values'));
//Gets column's type and collation
$type = $this->_columnTypes[$column_index];
$collation = $this->_columnCollations[$column_index];
@@ -902,8 +946,8 @@ EOT;
//If 'Function' column is present
$html_output .= $this->_getGeomFuncHtml($column_index);
//Displays column's name, type, collation and value
$html_output .= '<th>' . htmlspecialchars($this->_columnNames[$column_index])
. '</th>';
$html_output .= '<th>'
. htmlspecialchars($this->_columnNames[$column_index]) . '</th>';
$properties = $this->getColumnProperties($column_index, $column_index);
$html_output .= '<td>' . $properties['type'] . '</td>';
$html_output .= '<td>' . $properties['collation'] . '</td>';
@@ -912,16 +956,19 @@ EOT;
$html_output .= '</tr>';
//Displays hidden fields
$html_output .= '<tr><td>';
$html_output .= '<input type="hidden" name="criteriaColumnNames['
. $column_index . ']" value="'
. htmlspecialchars($this->_columnNames[$column_index]) . '" />';
$html_output .= '<input type="hidden" name="criteriaColumnTypes['
. $column_index . ']" value="' . $this->_columnTypes[$column_index] . '" />';
$html_output .= '<input type="hidden" name="criteriaColumnCollations['
. $column_index . ']" value="' . $this->_columnCollations[$column_index]
. '" /></td></tr>';
$html_output .= '<input type="hidden"'
. ' name="criteriaColumnNames[' . $column_index . ']"'
. ' value="' . htmlspecialchars($this->_columnNames[$column_index])
. '" />';
$html_output .= '<input type="hidden"'
. ' name="criteriaColumnTypes[' . $column_index . ']"'
. ' value="' . $this->_columnTypes[$column_index] . '" />';
$html_output .= '<input type="hidden"'
. ' name="criteriaColumnCollations[' . $column_index . ']"'
. ' value="' . $this->_columnCollations[$column_index] . '" />';
$html_output .= '</td></tr>';
} // end for
return $html_output;
}
@@ -971,7 +1018,10 @@ EOT;
if (isset($_POST['criteriaColumnNames'])
&& $_POST['criteriaColumnNames'][$i] != 'pma_null'
) {
$key = array_search($_POST['criteriaColumnNames'][$i], $this->_columnNames);
$key = array_search(
$_POST['criteriaColumnNames'][$i],
$this->_columnNames
);
$properties = $this->getColumnProperties($i, $key);
$type[$i] = $properties['type'];
$collation[$i] = $properties['collation'];
@@ -983,7 +1033,7 @@ EOT;
//Column Collation
$html_output .= '<td>' . (isset($collation[$i]) ? $collation[$i] : '')
. '</td>';
//Select options for column operators
//Select options for column operators
$html_output .= '<td>' . (isset($func[$i]) ? $func[$i] : '') . '</td>';
//Inputbox for search criteria value
$html_output .= '<td>' . (isset($value[$i]) ? $value[$i] : '') . '</td>';
@@ -1068,7 +1118,7 @@ EOT;
$url_params['db'] = $this->_db;
$url_params['table'] = $this->_table;
$html_output .= PMA_generateHtmlTabs(
$html_output .= $this->getCommonFunctions()->getHtmlTabs(
$this->_getSubTabs(), $url_params, 'topmenu2'
);
$html_output .= $this->_getFormTag($goto);
@@ -1136,7 +1186,7 @@ EOT;
public function getZoomResultsForm($goto, $data)
{
$html_output = '';
$titles['Browse'] = PMA_getIcon('b_browse.png', __('Browse foreign values'));
$titles['Browse'] = $this->getCommonFunctions()->getIcon('b_browse.png', __('Browse foreign values'));
$html_output .= '<form method="post" action="tbl_zoom_select.php"'
. ' name="displayResultForm" id="zoom_display_form"'
. ($GLOBALS['cfg']['AjaxEnable'] ? ' class="ajax"' : '') . '>';
@@ -1192,8 +1242,9 @@ EOT;
//Column's Input box
$html_output .= '<th>';
$html_output .= $this->_getInputbox(
$foreignData, $fieldpopup, $this->_columnTypes[$column_index], $column_index,
$titles, $GLOBALS['cfg']['ForeignKeyMaxLimit'], '', false, true
$foreignData, $fieldpopup, $this->_columnTypes[$column_index],
$column_index, $titles, $GLOBALS['cfg']['ForeignKeyMaxLimit'],
'', false, true
);
$html_output .= '</th></tr>';
}

View File

@@ -82,7 +82,8 @@ class PMA_Tracker
'RENAME TABLE','DROP TABLE','CREATE INDEX','DROP INDEX',
'CREATE VIEW','ALTER VIEW','DROP VIEW'
);
/**
* Initializes settings. See phpMyAdmin/Documentation.html.
*
@@ -92,8 +93,11 @@ class PMA_Tracker
*/
static protected function init()
{
self::$pma_table = PMA_backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
PMA_backquote($GLOBALS['cfg']['Server']['tracking']);
$common_functions = PMA_CommonFunctions::getInstance();
self::$pma_table = $common_functions->backquote($GLOBALS['cfg']['Server']['pmadb']) .".".
$common_functions->backquote($GLOBALS['cfg']['Server']['tracking']);
self::$add_drop_table = $GLOBALS['cfg']['Server']['tracking_add_drop_table'];
@@ -194,6 +198,9 @@ class PMA_Tracker
*/
static public function isTracked($dbname, $tablename)
{
$common_functions = PMA_CommonFunctions::getInstance();
if (! self::$enabled) {
return false;
}
@@ -209,11 +216,11 @@ class PMA_Tracker
}
$sql_query = " SELECT tracking_active FROM " . self::$pma_table .
" WHERE db_name = '" . PMA_sqlAddSlashes($dbname) . "' " .
" AND table_name = '" . PMA_sqlAddSlashes($tablename) . "' " .
" WHERE db_name = '" . $common_functions->sqlAddSlashes($dbname) . "' " .
" AND table_name = '" . $common_functions->sqlAddSlashes($tablename) . "' " .
" ORDER BY version DESC";
$row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
$row = PMA_DBI_fetch_array(PMA_queryAsControlUser($sql_query));
if (isset($row['tracking_active']) && $row['tracking_active'] == 1) {
return true;
@@ -251,13 +258,25 @@ class PMA_Tracker
static public function createVersion($dbname, $tablename, $version,
$tracking_set = '', $is_view = false
) {
global $sql_backquotes;
global $sql_backquotes, $export_type;
$common_functions = PMA_CommonFunctions::getInstance();
if ($tracking_set == '') {
$tracking_set = self::$default_tracking_set;
}
include_once './libraries/export/sql.php';
// get Export SQL instance
require_once "libraries/plugin_interface.lib.php";
$export_sql_plugin = PMA_getPlugin(
"export",
"sql",
'libraries/plugins/export/',
array(
'export_type' => $export_type,
'single_table' => isset($single_table)
)
);
$sql_backquotes = true;
@@ -285,17 +304,17 @@ class PMA_Tracker
if (self::$add_drop_table == true && $is_view == false) {
$create_sql .= self::getLogComment()
. 'DROP TABLE IF EXISTS ' . PMA_backquote($tablename) . ";\n";
. 'DROP TABLE IF EXISTS ' . $common_functions->backquote($tablename) . ";\n";
}
if (self::$add_drop_view == true && $is_view == true) {
$create_sql .= self::getLogComment()
. 'DROP VIEW IF EXISTS ' . PMA_backquote($tablename) . ";\n";
. 'DROP VIEW IF EXISTS ' . $common_functions->backquote($tablename) . ";\n";
}
$create_sql .= self::getLogComment() .
PMA_getTableDef($dbname, $tablename, "\n", "");
$export_sql_plugin->getTableDef($dbname, $tablename, "\n", "");
// Save version
@@ -312,17 +331,17 @@ class PMA_Tracker
"tracking " .
") " .
"values (
'" . PMA_sqlAddSlashes($dbname) . "',
'" . PMA_sqlAddSlashes($tablename) . "',
'" . PMA_sqlAddSlashes($version) . "',
'" . PMA_sqlAddSlashes($date) . "',
'" . PMA_sqlAddSlashes($date) . "',
'" . PMA_sqlAddSlashes($snapshot) . "',
'" . PMA_sqlAddSlashes($create_sql) . "',
'" . PMA_sqlAddSlashes("\n") . "',
'" . PMA_sqlAddSlashes(self::_transformTrackingSet($tracking_set)) . "' )";
'" . $common_functions->sqlAddSlashes($dbname) . "',
'" . $common_functions->sqlAddSlashes($tablename) . "',
'" . $common_functions->sqlAddSlashes($version) . "',
'" . $common_functions->sqlAddSlashes($date) . "',
'" . $common_functions->sqlAddSlashes($date) . "',
'" . $common_functions->sqlAddSlashes($snapshot) . "',
'" . $common_functions->sqlAddSlashes($create_sql) . "',
'" . $common_functions->sqlAddSlashes("\n") . "',
'" . $common_functions->sqlAddSlashes(self::_transformTrackingSet($tracking_set)) . "' )";
$result = PMA_query_as_controluser($sql_query);
$result = PMA_queryAsControlUser($sql_query);
if ($result) {
// Deactivate previous version
@@ -345,10 +364,13 @@ class PMA_Tracker
*/
static public function deleteTracking($dbname, $tablename)
{
$common_functions = PMA_CommonFunctions::getInstance();
$sql_query = "/*NOTRACK*/\n"
. "DELETE FROM " . self::$pma_table
. " WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "'"
. " AND `table_name` = '" . PMA_sqlAddSlashes($tablename) . "'";
. " WHERE `db_name` = '"
. $common_functions->sqlAddSlashes($dbname) . "'"
. " AND `table_name` = '"
. $common_functions->sqlAddSlashes($tablename) . "'";
$result = PMA_query_as_controluser($sql_query);
return $result;
@@ -370,6 +392,8 @@ class PMA_Tracker
static public function createDatabaseVersion($dbname, $version, $query,
$tracking_set = 'CREATE DATABASE,ALTER DATABASE,DROP DATABASE'
) {
$common_functions = PMA_CommonFunctions::getInstance();
$date = date('Y-m-d H:i:s');
if ($tracking_set == '') {
@@ -382,7 +406,7 @@ class PMA_Tracker
if (self::$add_drop_database == true) {
$create_sql .= self::getLogComment()
. 'DROP DATABASE IF EXISTS ' . PMA_backquote($dbname) . ";\n";
. 'DROP DATABASE IF EXISTS ' . $common_functions->backquote($dbname) . ";\n";
}
$create_sql .= self::getLogComment() . $query;
@@ -401,17 +425,17 @@ class PMA_Tracker
"tracking " .
") " .
"values (
'" . PMA_sqlAddSlashes($dbname) . "',
'" . PMA_sqlAddSlashes('') . "',
'" . PMA_sqlAddSlashes($version) . "',
'" . PMA_sqlAddSlashes($date) . "',
'" . PMA_sqlAddSlashes($date) . "',
'" . PMA_sqlAddSlashes('') . "',
'" . PMA_sqlAddSlashes($create_sql) . "',
'" . PMA_sqlAddSlashes("\n") . "',
'" . PMA_sqlAddSlashes(self::_transformTrackingSet($tracking_set)) . "' )";
'" . $common_functions->sqlAddSlashes($dbname) . "',
'" . $common_functions->sqlAddSlashes('') . "',
'" . $common_functions->sqlAddSlashes($version) . "',
'" . $common_functions->sqlAddSlashes($date) . "',
'" . $common_functions->sqlAddSlashes($date) . "',
'" . $common_functions->sqlAddSlashes('') . "',
'" . $common_functions->sqlAddSlashes($create_sql) . "',
'" . $common_functions->sqlAddSlashes("\n") . "',
'" . $common_functions->sqlAddSlashes(self::_transformTrackingSet($tracking_set)) . "' )";
$result = PMA_query_as_controluser($sql_query);
$result = PMA_queryAsControlUser($sql_query);
return $result;
}
@@ -433,13 +457,14 @@ class PMA_Tracker
static private function _changeTracking($dbname, $tablename,
$version, $new_state
) {
$common_functions= PMA_CommonFunctions::getInstance();
$sql_query = " UPDATE " . self::$pma_table .
" SET `tracking_active` = '" . $new_state . "' " .
" WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' " .
" AND `table_name` = '" . PMA_sqlAddSlashes($tablename) . "' " .
" AND `version` = '" . PMA_sqlAddSlashes($version) . "' ";
" WHERE `db_name` = '" . $common_functions->sqlAddSlashes($dbname) . "' " .
" AND `table_name` = '" . $common_functions->sqlAddSlashes($tablename) . "' " .
" AND `version` = '" . $common_functions->sqlAddSlashes($version) . "' ";
$result = PMA_query_as_controluser($sql_query);
$result = PMA_queryAsControlUser($sql_query);
return $result;
}
@@ -460,6 +485,9 @@ class PMA_Tracker
static public function changeTrackingData($dbname, $tablename,
$version, $type, $new_data
) {
$common_functions = PMA_CommonFunctions::getInstance();
if ($type == 'DDL') {
$save_to = 'schema_sql';
} elseif ($type == 'DML') {
@@ -473,7 +501,7 @@ class PMA_Tracker
if (is_array($new_data)) {
foreach ($new_data as $data) {
$new_data_processed .= '# log ' . $date . ' ' . $data['username']
. PMA_sqlAddSlashes($data['statement']) . "\n";
. $common_functions->sqlAddSlashes($data['statement']) . "\n";
}
} else {
$new_data_processed = $new_data;
@@ -481,11 +509,11 @@ class PMA_Tracker
$sql_query = " UPDATE " . self::$pma_table .
" SET `" . $save_to . "` = '" . $new_data_processed . "' " .
" WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' " .
" AND `table_name` = '" . PMA_sqlAddSlashes($tablename) . "' " .
" AND `version` = '" . PMA_sqlAddSlashes($version) . "' ";
" WHERE `db_name` = '" . $common_functions->sqlAddSlashes($dbname) . "' " .
" AND `table_name` = '" . $common_functions->sqlAddSlashes($tablename) . "' " .
" AND `version` = '" . $common_functions->sqlAddSlashes($version) . "' ";
$result = PMA_query_as_controluser($sql_query);
$result = PMA_queryAsControlUser($sql_query);
return $result;
}
@@ -538,16 +566,19 @@ class PMA_Tracker
*/
static public function getVersion($dbname, $tablename, $statement = null)
{
$common_functions = PMA_CommonFunctions::getInstance();
$sql_query = " SELECT MAX(version) FROM " . self::$pma_table .
" WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' " .
" AND `table_name` = '" . PMA_sqlAddSlashes($tablename) . "' ";
" WHERE `db_name` = '" . $common_functions->sqlAddSlashes($dbname) . "' " .
" AND `table_name` = '" . $common_functions->sqlAddSlashes($tablename) . "' ";
if ($statement != "") {
$sql_query .= PMA_DRIZZLE
? ' AND tracking & ' . self::_transformTrackingSet($statement) . ' <> 0'
: " AND FIND_IN_SET('" . $statement . "',tracking) > 0" ;
}
$row = PMA_DBI_fetch_array(PMA_query_as_controluser($sql_query));
$row = PMA_DBI_fetch_array(PMA_queryAsControlUser($sql_query));
return isset($row[0])
? $row[0]
: -1;
@@ -567,19 +598,22 @@ class PMA_Tracker
*/
static public function getTrackedData($dbname, $tablename, $version)
{
$common_functions = PMA_CommonFunctions::getInstance();
if (! isset(self::$pma_table)) {
self::init();
}
$sql_query = " SELECT * FROM " . self::$pma_table .
" WHERE `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' ";
" WHERE `db_name` = '" . $common_functions->sqlAddSlashes($dbname) . "' ";
if (! empty($tablename)) {
$sql_query .= " AND `table_name` = '"
. PMA_sqlAddSlashes($tablename) ."' ";
. $common_functions->sqlAddSlashes($tablename) ."' ";
}
$sql_query .= " AND `version` = '" . PMA_sqlAddSlashes($version) ."' ".
$sql_query .= " AND `version` = '" . $common_functions->sqlAddSlashes($version) ."' ".
" ORDER BY `version` DESC LIMIT 1";
$mixed = PMA_DBI_fetch_assoc(PMA_query_as_controluser($sql_query));
$mixed = PMA_DBI_fetch_assoc(PMA_queryAsControlUser($sql_query));
// Parse log
$log_schema_entries = explode('# log ', $mixed['schema_sql']);
@@ -910,6 +944,9 @@ class PMA_Tracker
*/
static public function handleQuery($query)
{
$common_functions = PMA_CommonFunctions::getInstance();
// If query is marked as untouchable, leave
if (strstr($query, "/*NOTRACK*/")) {
return;
@@ -977,16 +1014,16 @@ class PMA_Tracker
// Mark it as untouchable
$sql_query = " /*NOTRACK*/\n"
. " UPDATE " . self::$pma_table
. " SET " . PMA_backquote($save_to)
. " = CONCAT( " . PMA_backquote($save_to) . ",'\n"
. PMA_sqlAddSlashes($query) . "') ,"
. " SET " . $common_functions->backquote($save_to)
. " = CONCAT( " . $common_functions->backquote($save_to) . ",'\n"
. $common_functions->sqlAddSlashes($query) . "') ,"
. " `date_updated` = '" . $date . "' ";
// If table was renamed we have to change
// the tablename attribute in pma_tracking too
if ($result['identifier'] == 'RENAME TABLE') {
$sql_query .= ', `table_name` = \''
. PMA_sqlAddSlashes($result['tablename_after_rename'])
. $common_functions->sqlAddSlashes($result['tablename_after_rename'])
. '\' ';
}
@@ -997,11 +1034,11 @@ class PMA_Tracker
// we want to track
$sql_query .=
" WHERE FIND_IN_SET('" . $result['identifier'] . "',tracking) > 0" .
" AND `db_name` = '" . PMA_sqlAddSlashes($dbname) . "' " .
" AND `table_name` = '" . PMA_sqlAddSlashes($result['tablename']) . "' " .
" AND `version` = '" . PMA_sqlAddSlashes($version) . "' ";
" AND `db_name` = '" . $common_functions->sqlAddSlashes($dbname) . "' " .
" AND `table_name` = '" . $common_functions->sqlAddSlashes($result['tablename']) . "' " .
" AND `version` = '" . $common_functions->sqlAddSlashes($version) . "' ";
$result = PMA_query_as_controluser($sql_query);
$result = PMA_queryAsControlUser($sql_query);
}
}
}

View File

@@ -1,133 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Set of functions used to run config authentication (ie no authentication).
*
* @package PhpMyAdmin-Auth
* @subpackage Config
*/
/**
* Displays authentication form
*
* @return boolean always true
*
* @access public
*/
function PMA_auth()
{
return true;
} // end of the 'PMA_auth()' function
/**
* Gets advanced authentication settings
*
* @return boolean always true
*
* @access public
*/
function PMA_auth_check()
{
return true;
} // end of the 'PMA_auth_check()' function
/**
* Set the user and password after last checkings if required
*
* @return boolean always true
*
* @access public
*/
function PMA_auth_set_user()
{
return true;
} // end of the 'PMA_auth_set_user()' function
/**
* User is not allowed to login to MySQL -> authentication failed
*
* @global string the MySQL error message PHP returns
* @global string the connection type (persistent or not)
* @global string the MySQL server port to use
* @global string the MySQL socket port to use
* @global array the current server settings
* @global string the font face to use in case of failure
* @global string the default font size to use in case of failure
* @global string the big font size to use in case of failure
* @global boolean tell the "PMA_mysqlDie()" function headers have been
* sent
*
* @return boolean always true (no return indeed)
*
* @access public
*/
function PMA_auth_fails()
{
$conn_error = PMA_DBI_getError();
if (! $conn_error) {
$conn_error = __('Cannot connect: invalid settings.');
}
/* HTML header */
$response = PMA_Response::getInstance();
$response->getFooter()->setMinimal();
$header = $response->getHeader();
$header->setTitle(__('Access denied'));
$header->disableMenu();
?>
<br /><br />
<center>
<h1><?php echo sprintf(__('Welcome to %s'), ' phpMyAdmin '); ?></h1>
</center>
<br />
<table cellpadding="0" cellspacing="3" style="margin: 0 auto" width="80%">
<tr>
<td>
<?php
if (isset($GLOBALS['allowDeny_forbidden']) && $GLOBALS['allowDeny_forbidden']) {
trigger_error(__('Access denied'), E_USER_NOTICE);
} else {
// Check whether user has configured something
if ($GLOBALS['PMA_Config']->source_mtime == 0) {
echo '<p>' . sprintf(__('You probably did not create a configuration file. You might want to use the %1$ssetup script%2$s to create one.'), '<a href="setup/">', '</a>') . '</p>' . "\n";
} elseif (! isset($GLOBALS['errno'])
|| (isset($GLOBALS['errno']) && $GLOBALS['errno'] != 2002)
&& $GLOBALS['errno'] != 2003
) {
// if we display the "Server not responding" error, do not confuse users
// by telling them they have a settings problem
// (note: it's true that they could have a badly typed host name, but
// anyway the current message tells that the server
// rejected the connection, which is not really what happened)
// 2002 is the error given by mysqli
// 2003 is the error given by mysql
trigger_error(__('phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server.'), E_USER_WARNING);
}
PMA_mysqlDie($conn_error, '', true, '', false);
}
$GLOBALS['error_handler']->dispUserErrors();
?>
</td>
</tr>
<?php
if (count($GLOBALS['cfg']['Servers']) > 1) {
// offer a chance to login to other servers if the current one failed
include_once './libraries/select_server.lib.php';
echo '<tr>' . "\n";
echo ' <td>' . "\n";
PMA_select_server(true, true);
echo ' </td>' . "\n";
echo '</tr>' . "\n";
}
echo '</table>' . "\n";
exit;
return true;
} // end of the 'PMA_auth_fails()' function
?>

View File

@@ -1,643 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Set of functions used to run cookie based authentication.
*
* @package PhpMyAdmin-Auth
* @subpackage Cookie
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* Remember where to redirect the user
* in case of an expired session.
*/
if (! empty($_REQUEST['target'])) {
$GLOBALS['target'] = $_REQUEST['target'];
}
/**
* Swekey authentication functions.
*/
require './libraries/auth/swekey/swekey.auth.lib.php';
if (function_exists('mcrypt_encrypt')) {
/**
* Uses faster mcrypt library if available
* (as this is not called from anywhere else, put the code in-line
* for faster execution)
*/
/**
* Initialization
* Store the initialization vector because it will be needed for
* further decryption. I don't think necessary to have one iv
* per server so I don't put the server number in the cookie name.
*/
if (empty($_COOKIE['pma_mcrypt_iv'])
|| false === ($iv = base64_decode($_COOKIE['pma_mcrypt_iv'], true))
) {
srand((double) microtime() * 1000000);
$td = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_CBC, '');
if ($td === false) {
PMA_fatalError(__('Failed to use Blowfish from mcrypt!'));
}
$iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
$GLOBALS['PMA_Config']->setCookie('pma_mcrypt_iv', base64_encode($iv));
}
/**
* Encryption using blowfish algorithm (mcrypt)
*
* @param string $data original data
* @param string $secret the secret
*
* @return string the encrypted result
*
* @access public
*
*/
function PMA_blowfish_encrypt($data, $secret)
{
global $iv;
return base64_encode(
mcrypt_encrypt(MCRYPT_BLOWFISH, $secret, $data, MCRYPT_MODE_CBC, $iv)
);
}
/**
* Decryption using blowfish algorithm (mcrypt)
*
* @param string $encdata encrypted data
* @param string $secret the secret
*
* @return string original data
*
* @access public
*
*/
function PMA_blowfish_decrypt($encdata, $secret)
{
global $iv;
$data = base64_decode($encdata);
$decrypted = mcrypt_decrypt(
MCRYPT_BLOWFISH,
$secret,
$data,
MCRYPT_MODE_CBC,
$iv
);
return trim($decrypted);
}
} else {
include_once './libraries/blowfish.php';
}
/**
* Returns blowfish secret or generates one if needed.
*
* @access public
* @return string
*/
function PMA_get_blowfish_secret()
{
if (empty($GLOBALS['cfg']['blowfish_secret'])) {
if (empty($_SESSION['auto_blowfish_secret'])) {
// this returns 23 characters
$_SESSION['auto_blowfish_secret'] = uniqid('', true);
}
return $_SESSION['auto_blowfish_secret'];
} else {
// apply md5() to work around too long secrets (returns 32 characters)
return md5($GLOBALS['cfg']['blowfish_secret']);
}
}
/**
* Displays authentication form
*
* this function MUST exit/quit the application
*
* @global string the last connection error
*
* @access public
*/
function PMA_auth()
{
global $conn_error;
$response = PMA_Response::getInstance();
if ($response->isAjax()) {
$response->isSuccess(false);
if (! empty($conn_error)) {
$response->addJSON('message', $conn_error);
} else {
$response->addJSON('message', PMA_Message::error(__('Your session has expired. Please login again.')));
}
exit;
}
/* Perform logout to custom URL */
if (! empty($_REQUEST['old_usr'])
&& ! empty($GLOBALS['cfg']['Server']['LogoutURL'])
) {
PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['LogoutURL']);
exit;
}
/* No recall if blowfish secret is not configured as it would produce garbage */
if ($GLOBALS['cfg']['LoginCookieRecall']
&& ! empty($GLOBALS['cfg']['blowfish_secret'])
) {
$default_user = $GLOBALS['PHP_AUTH_USER'];
$default_server = $GLOBALS['pma_auth_server'];
$autocomplete = '';
} else {
$default_user = '';
$default_server = '';
// skip the IE autocomplete feature.
$autocomplete = ' autocomplete="off"';
}
$cell_align = ($GLOBALS['text_dir'] == 'ltr') ? 'left' : 'right';
$response->getFooter()->setMinimal();
$header = $response->getHeader();
$header->setBodyId('loginform');
$header->setTitle('phpMyAdmin');
$header->disableMenu();
$header->disableWarnings();
if (file_exists(CUSTOM_HEADER_FILE)) {
include CUSTOM_HEADER_FILE;
}
?>
<div class="container">
<a href="<?php echo PMA_linkURL('http://www.phpmyadmin.net/'); ?>" target="_blank" class="logo"><?php
$logo_image = $GLOBALS['pmaThemeImage'] . 'logo_right.png';
if (@file_exists($logo_image)) {
echo '<img src="' . $logo_image
. '" id="imLogo" name="imLogo" alt="phpMyAdmin" border="0" />';
} else {
echo '<img name="imLogo" id="imLogo" src="'
. $GLOBALS['pmaThemeImage'] . 'pma_logo.png' . '" '
. 'border="0" width="88" height="31" alt="phpMyAdmin" />';
}
?></a>
<h1>
<?php
echo sprintf(
__('Welcome to %s'),
'<bdo dir="ltr" lang="en">phpMyAdmin</bdo>'
);
?>
</h1>
<?php
// Show error message
if (! empty($conn_error)) {
PMA_Message::rawError($conn_error)->display();
}
echo "<noscript>\n";
PMA_message::error(__("Javascript must be enabled past this point"))->display();
echo "</noscript>\n";
echo "<div class='hide js-show'>";
// Displays the languages form
if (empty($GLOBALS['cfg']['Lang'])) {
include_once './libraries/display_select_lang.lib.php';
// use fieldset, don't show doc link
PMA_select_language(true, false);
}
echo "</div>";
?>
<br />
<!-- Login form -->
<form method="post" action="index.php" name="login_form"<?php echo $autocomplete; ?> target="_top" class="login hide js-show">
<fieldset>
<legend>
<?php
echo __('Log in');
echo PMA_showDocu('');
?>
</legend>
<?php if ($GLOBALS['cfg']['AllowArbitraryServer']) { ?>
<div class="item">
<label for="input_servername" title="<?php echo __('You can enter hostname/IP address and port separated by space.'); ?>"><?php echo __('Server:'); ?></label>
<input type="text" name="pma_servername" id="input_servername" value="<?php echo htmlspecialchars($default_server); ?>" size="24" class="textfield" title="<?php echo __('You can enter hostname/IP address and port separated by space.'); ?>" />
</div>
<?php } ?>
<div class="item">
<label for="input_username"><?php echo __('Username:'); ?></label>
<input type="text" name="pma_username" id="input_username" value="<?php echo htmlspecialchars($default_user); ?>" size="24" class="textfield"/>
</div>
<div class="item">
<label for="input_password"><?php echo __('Password:'); ?></label>
<input type="password" name="pma_password" id="input_password" value="" size="24" class="textfield" />
</div>
<?php
if (count($GLOBALS['cfg']['Servers']) > 1) {
?>
<div class="item">
<label for="select_server"><?php echo __('Server Choice'); ?>:</label>
<select name="server" id="select_server"
<?php
if ($GLOBALS['cfg']['AllowArbitraryServer']) {
echo ' onchange="document.forms[\'login_form\'].elements[\'pma_servername\'].value = \'\'" ';
}
echo '>';
include_once './libraries/select_server.lib.php';
PMA_select_server(false, false);
echo '</select></div>';
} else {
echo ' <input type="hidden" name="server" value="' . $GLOBALS['server'] . '" />';
} // end if (server choice)
?>
</fieldset>
<fieldset class="tblFooters">
<input value="<?php echo __('Go'); ?>" type="submit" id="input_go" />
<?php
$_form_params = array();
if (! empty($GLOBALS['target'])) {
$_form_params['target'] = $GLOBALS['target'];
}
if (! empty($GLOBALS['db'])) {
$_form_params['db'] = $GLOBALS['db'];
}
if (! empty($GLOBALS['table'])) {
$_form_params['table'] = $GLOBALS['table'];
}
// do not generate a "server" hidden field as we want the "server"
// drop-down to have priority
echo PMA_generate_common_hidden_inputs($_form_params, '', 0, 'server');
?>
</fieldset>
</form>
<?php
// BEGIN Swekey Integration
Swekey_login('input_username', 'input_go');
// END Swekey Integration
// show the "Cookies required" message only if cookies are disabled
// (we previously tried to set some cookies)
if (empty($_COOKIE)) {
trigger_error(__('Cookies must be enabled past this point.'), E_USER_NOTICE);
}
if ($GLOBALS['error_handler']->hasDisplayErrors()) {
echo '<div>';
$GLOBALS['error_handler']->dispErrors();
echo '</div>';
}
?>
</div>
<?php
if (file_exists(CUSTOM_FOOTER_FILE)) {
include CUSTOM_FOOTER_FILE;
}
?>
<script type="text/javascript">
//<![CDATA[
// show login form in top frame.
if (top != self || ! $('body#loginform').length) {
window.top.location.href=location;
}
//]]>
</script>
<?php
exit;
} // end of the 'PMA_auth()' function
/**
* Gets advanced authentication settings
*
* this function DOES NOT check authentication - it just checks/provides
* authentication credentials required to connect to the MySQL server
* usually with PMA_DBI_connect()
*
* it returns false if something is missing - which usually leads to
* PMA_auth() which displays login form
*
* it returns true if all seems ok which usually leads to PMA_auth_set_user()
*
* it directly switches to PMA_auth_fails() if user inactivity timout is reached
*
* @todo AllowArbitraryServer on does not imply that the user wants an
* arbitrary server, or? so we should also check if this is filled and
* not only if allowed
*
* @return boolean whether we get authentication settings or not
*
* @access public
*/
function PMA_auth_check()
{
// Initialization
/**
* @global $GLOBALS['pma_auth_server'] the user provided server to connect to
*/
$GLOBALS['pma_auth_server'] = '';
$GLOBALS['PHP_AUTH_USER'] = $GLOBALS['PHP_AUTH_PW'] = '';
$GLOBALS['from_cookie'] = false;
// BEGIN Swekey Integration
if (! Swekey_auth_check()) {
return false;
}
// END Swekey Integration
if (defined('PMA_CLEAR_COOKIES')) {
foreach ($GLOBALS['cfg']['Servers'] as $key => $val) {
$GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $key);
$GLOBALS['PMA_Config']->removeCookie('pmaServer-' . $key);
$GLOBALS['PMA_Config']->removeCookie('pmaUser-' . $key);
}
return false;
}
if (! empty($_REQUEST['old_usr'])) {
// The user wants to be logged out
// -> delete his choices that were stored in session
// according to the PHP manual we should do this before the destroy:
//$_SESSION = array();
session_destroy();
// -> delete password cookie(s)
if ($GLOBALS['cfg']['LoginCookieDeleteAll']) {
foreach ($GLOBALS['cfg']['Servers'] as $key => $val) {
$GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $key);
if (isset($_COOKIE['pmaPass-' . $key])) {
unset($_COOKIE['pmaPass-' . $key]);
}
}
} else {
$GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $GLOBALS['server']);
if (isset($_COOKIE['pmaPass-' . $GLOBALS['server']])) {
unset($_COOKIE['pmaPass-' . $GLOBALS['server']]);
}
}
}
if (! empty($_REQUEST['pma_username'])) {
// The user just logged in
$GLOBALS['PHP_AUTH_USER'] = $_REQUEST['pma_username'];
$GLOBALS['PHP_AUTH_PW'] = empty($_REQUEST['pma_password'])
? ''
: $_REQUEST['pma_password'];
if ($GLOBALS['cfg']['AllowArbitraryServer']
&& isset($_REQUEST['pma_servername'])
) {
$GLOBALS['pma_auth_server'] = $_REQUEST['pma_servername'];
}
return true;
}
// At the end, try to set the $GLOBALS['PHP_AUTH_USER']
// and $GLOBALS['PHP_AUTH_PW'] variables from cookies
// servername
if ($GLOBALS['cfg']['AllowArbitraryServer']
&& ! empty($_COOKIE['pmaServer-' . $GLOBALS['server']])
) {
$GLOBALS['pma_auth_server'] = $_COOKIE['pmaServer-' . $GLOBALS['server']];
}
// username
if (empty($_COOKIE['pmaUser-' . $GLOBALS['server']])) {
return false;
}
$GLOBALS['PHP_AUTH_USER'] = PMA_blowfish_decrypt(
$_COOKIE['pmaUser-' . $GLOBALS['server']],
PMA_get_blowfish_secret()
);
// user was never logged in since session start
if (empty($_SESSION['last_access_time'])) {
return false;
}
// User inactive too long
if ($_SESSION['last_access_time'] < time() - $GLOBALS['cfg']['LoginCookieValidity']) {
PMA_cacheUnset('is_create_db_priv', true);
PMA_cacheUnset('is_process_priv', true);
PMA_cacheUnset('is_reload_priv', true);
PMA_cacheUnset('db_to_create', true);
PMA_cacheUnset('dbs_where_create_table_allowed', true);
$GLOBALS['no_activity'] = true;
PMA_auth_fails();
exit;
}
// password
if (empty($_COOKIE['pmaPass-' . $GLOBALS['server']])) {
return false;
}
$GLOBALS['PHP_AUTH_PW'] = PMA_blowfish_decrypt(
$_COOKIE['pmaPass-' . $GLOBALS['server']],
PMA_get_blowfish_secret()
);
if ($GLOBALS['PHP_AUTH_PW'] == "\xff(blank)") {
$GLOBALS['PHP_AUTH_PW'] = '';
}
$GLOBALS['from_cookie'] = true;
return true;
} // end of the 'PMA_auth_check()' function
/**
* Set the user and password after last checkings if required
*
* @return boolean always true
*
* @access public
*/
function PMA_auth_set_user()
{
global $cfg;
// Ensures valid authentication mode, 'only_db', bookmark database and
// table names and relation table name are used
if ($cfg['Server']['user'] != $GLOBALS['PHP_AUTH_USER']) {
foreach ($cfg['Servers'] as $idx => $current) {
if ($current['host'] == $cfg['Server']['host']
&& $current['port'] == $cfg['Server']['port']
&& $current['socket'] == $cfg['Server']['socket']
&& $current['ssl'] == $cfg['Server']['ssl']
&& $current['connect_type'] == $cfg['Server']['connect_type']
&& $current['user'] == $GLOBALS['PHP_AUTH_USER']
) {
$GLOBALS['server'] = $idx;
$cfg['Server'] = $current;
break;
}
} // end foreach
} // end if
if ($GLOBALS['cfg']['AllowArbitraryServer']
&& ! empty($GLOBALS['pma_auth_server'])
) {
/* Allow to specify 'host port' */
$parts = explode(' ', $GLOBALS['pma_auth_server']);
if (count($parts) == 2) {
$tmp_host = $parts[0];
$tmp_port = $parts[1];
} else {
$tmp_host = $GLOBALS['pma_auth_server'];
$tmp_port = '';
}
if ($cfg['Server']['host'] != $GLOBALS['pma_auth_server']) {
$cfg['Server']['host'] = $tmp_host;
if (! empty($tmp_port)) {
$cfg['Server']['port'] = $tmp_port;
}
}
unset($tmp_host, $tmp_port, $parts);
}
$cfg['Server']['user'] = $GLOBALS['PHP_AUTH_USER'];
$cfg['Server']['password'] = $GLOBALS['PHP_AUTH_PW'];
// Avoid showing the password in phpinfo()'s output
unset($GLOBALS['PHP_AUTH_PW']);
unset($_SERVER['PHP_AUTH_PW']);
$_SESSION['last_access_time'] = time();
// Name and password cookies need to be refreshed each time
// Duration = one month for username
$GLOBALS['PMA_Config']->setCookie(
'pmaUser-' . $GLOBALS['server'],
PMA_blowfish_encrypt(
$cfg['Server']['user'], PMA_get_blowfish_secret()
)
);
// Duration = as configured
$GLOBALS['PMA_Config']->setCookie(
'pmaPass-' . $GLOBALS['server'],
PMA_blowfish_encrypt(
! empty($cfg['Server']['password']) ? $cfg['Server']['password'] : "\xff(blank)",
PMA_get_blowfish_secret()
),
null,
$GLOBALS['cfg']['LoginCookieStore']
);
// Set server cookies if required (once per session) and, in this case, force
// reload to ensure the client accepts cookies
if (! $GLOBALS['from_cookie']) {
if ($GLOBALS['cfg']['AllowArbitraryServer']) {
if (! empty($GLOBALS['pma_auth_server'])) {
// Duration = one month for servername
$GLOBALS['PMA_Config']->setCookie(
'pmaServer-' . $GLOBALS['server'],
$cfg['Server']['host']
);
} else {
// Delete servername cookie
$GLOBALS['PMA_Config']->removeCookie(
'pmaServer-' . $GLOBALS['server']
);
}
}
// URL where to go:
$redirect_url = $cfg['PmaAbsoluteUri'] . 'index.php';
// any parameters to pass?
$url_params = array();
if (strlen($GLOBALS['db'])) {
$url_params['db'] = $GLOBALS['db'];
}
if (strlen($GLOBALS['table'])) {
$url_params['table'] = $GLOBALS['table'];
}
// any target to pass?
if (! empty($GLOBALS['target']) && $GLOBALS['target'] != 'index.php') {
$url_params['target'] = $GLOBALS['target'];
}
/**
* Clear user cache.
*/
PMA_clearUserCache();
PMA_Response::getInstance()->disable();
PMA_sendHeaderLocation(
$redirect_url . PMA_generate_common_url($url_params, '&'),
true
);
exit;
} // end if
return true;
} // end of the 'PMA_auth_set_user()' function
/**
* User is not allowed to login to MySQL -> authentication failed
*
* prepares error message and switches to PMA_auth() which display the error
* and the login form
*
* this function MUST exit/quit the application,
* currently doen by call to PMA_auth()
*
* @access public
*/
function PMA_auth_fails()
{
global $conn_error;
// Deletes password cookie and displays the login form
$GLOBALS['PMA_Config']->removeCookie('pmaPass-' . $GLOBALS['server']);
if (! empty($GLOBALS['login_without_password_is_forbidden'])) {
$conn_error = __('Login without a password is forbidden by configuration (see AllowNoPassword)');
} elseif (! empty($GLOBALS['allowDeny_forbidden'])) {
$conn_error = __('Access denied');
} elseif (! empty($GLOBALS['no_activity'])) {
$conn_error = sprintf(__('No activity within %s seconds; please log in again'), $GLOBALS['cfg']['LoginCookieValidity']);
// Remember where we got timeout to return on same place
if (PMA_getenv('SCRIPT_NAME')) {
$GLOBALS['target'] = basename(PMA_getenv('SCRIPT_NAME'));
// avoid "missing parameter: field" on re-entry
if ('tbl_alter.php' == $GLOBALS['target']) {
$GLOBALS['target'] = 'tbl_structure.php';
}
}
} elseif (PMA_DBI_getError()) {
$conn_error = '#' . $GLOBALS['errno'] . ' '
. __('Cannot log in to the MySQL server');
} else {
$conn_error = __('Cannot log in to the MySQL server');
}
// needed for PHP-CGI (not need for FastCGI or mod-php)
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Pragma: no-cache');
PMA_auth();
} // end of the 'PMA_auth_fails()' function
?>

View File

@@ -1,235 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Set of functions used to run http authentication.
* NOTE: Requires PHP loaded as a Apache module.
*
* @package PhpMyAdmin-Auth
* @subpackage HTTP
*/
/**
* Displays authentication form
*
* @global string the font face to use in case of failure
* @global string the default font size to use in case of failure
* @global string the big font size to use in case of failure
*
* @return boolean always true (no return indeed)
*
* @access public
*/
function PMA_auth()
{
/* Perform logout to custom URL */
if (! empty($_REQUEST['old_usr'])
&& ! empty($GLOBALS['cfg']['Server']['LogoutURL'])
) {
PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['LogoutURL']);
exit;
}
if (empty($GLOBALS['cfg']['Server']['auth_http_realm'])) {
if (empty($GLOBALS['cfg']['Server']['verbose'])) {
$server_message = $GLOBALS['cfg']['Server']['host'];
} else {
$server_message = $GLOBALS['cfg']['Server']['verbose'];
}
$realm_message = 'phpMyAdmin ' . $server_message;
} else {
$realm_message = $GLOBALS['cfg']['Server']['auth_http_realm'];
}
// remove non US-ASCII to respect RFC2616
$realm_message = preg_replace('/[^\x20-\x7e]/i', '', $realm_message);
header('WWW-Authenticate: Basic realm="' . $realm_message . '"');
header('HTTP/1.0 401 Unauthorized');
if (php_sapi_name() !== 'cgi-fcgi') {
header('status: 401 Unauthorized');
}
/* HTML header */
$response = PMA_Response::getInstance();
$response->getFooter()->setMinimal();
$header = $response->getHeader();
$header->setTitle(__('Access denied'));
$header->disableMenu();
?>
<br /><br />
<center>
<h1><?php echo sprintf(__('Welcome to %s'), ' phpMyAdmin'); ?></h1>
</center>
<br />
<?php
PMA_Message::error(__('Wrong username/password. Access denied.'))->display();
if (file_exists(CUSTOM_FOOTER_FILE)) {
include CUSTOM_FOOTER_FILE;
}
exit;
} // end of the 'PMA_auth()' function
/**
* Gets advanced authentication settings
*
* @global string the username if register_globals is on
* @global string the password if register_globals is on
* @global array the array of server variables if register_globals is
* off
* @global array the array of environment variables if register_globals
* is off
* @global string the username for the ? server
* @global string the password for the ? server
* @global string the username for the WebSite Professional server
* @global string the password for the WebSite Professional server
* @global string the username of the user who logs out
*
* @return boolean whether we get authentication settings or not
*
* @access public
*/
function PMA_auth_check()
{
global $PHP_AUTH_USER, $PHP_AUTH_PW;
global $old_usr;
// Grabs the $PHP_AUTH_USER variable whatever are the values of the
// 'register_globals' and the 'variables_order' directives
if (empty($PHP_AUTH_USER)) {
if (PMA_getenv('PHP_AUTH_USER')) {
$PHP_AUTH_USER = PMA_getenv('PHP_AUTH_USER');
} elseif (PMA_getenv('REMOTE_USER')) {
// CGI, might be encoded, see below
$PHP_AUTH_USER = PMA_getenv('REMOTE_USER');
} elseif (PMA_getenv('REDIRECT_REMOTE_USER')) {
// CGI, might be encoded, see below
$PHP_AUTH_USER = PMA_getenv('REDIRECT_REMOTE_USER');
} elseif (PMA_getenv('AUTH_USER')) {
// WebSite Professional
$PHP_AUTH_USER = PMA_getenv('AUTH_USER');
} elseif (PMA_getenv('HTTP_AUTHORIZATION')
&& false === strpos(PMA_getenv('HTTP_AUTHORIZATION'), '<')
) {
// IIS, might be encoded, see below; also prevent XSS
$PHP_AUTH_USER = PMA_getenv('HTTP_AUTHORIZATION');
} elseif (PMA_getenv('Authorization')) {
// FastCGI, might be encoded, see below
$PHP_AUTH_USER = PMA_getenv('Authorization');
}
}
// Grabs the $PHP_AUTH_PW variable whatever are the values of the
// 'register_globals' and the 'variables_order' directives
if (empty($PHP_AUTH_PW)) {
if (PMA_getenv('PHP_AUTH_PW')) {
$PHP_AUTH_PW = PMA_getenv('PHP_AUTH_PW');
} elseif (PMA_getenv('REMOTE_PASSWORD')) {
// Apache/CGI
$PHP_AUTH_PW = PMA_getenv('REMOTE_PASSWORD');
} elseif (PMA_getenv('AUTH_PASSWORD')) {
// WebSite Professional
$PHP_AUTH_PW = PMA_getenv('AUTH_PASSWORD');
}
}
// Decode possibly encoded information (used by IIS/CGI/FastCGI)
// (do not use explode() because a user might have a colon in his password
if (strcmp(substr($PHP_AUTH_USER, 0, 6), 'Basic ') == 0) {
$usr_pass = base64_decode(substr($PHP_AUTH_USER, 6));
if (! empty($usr_pass)) {
$colon = strpos($usr_pass, ':');
if ($colon) {
$PHP_AUTH_USER = substr($usr_pass, 0, $colon);
$PHP_AUTH_PW = substr($usr_pass, $colon + 1);
}
unset($colon);
}
unset($usr_pass);
}
// User logged out -> ensure the new username is not the same
if (!empty($old_usr)
&& (isset($PHP_AUTH_USER) && $old_usr == $PHP_AUTH_USER)
) {
$PHP_AUTH_USER = '';
// -> delete user's choices that were stored in session
session_destroy();
}
// Returns whether we get authentication settings or not
if (empty($PHP_AUTH_USER)) {
return false;
} else {
return true;
}
} // end of the 'PMA_auth_check()' function
/**
* Set the user and password after last checkings if required
*
* @global array the valid servers settings
* @global integer the id of the current server
* @global array the current server settings
* @global string the current username
* @global string the current password
*
* @return boolean always true
*
* @access public
*/
function PMA_auth_set_user()
{
global $cfg, $server;
global $PHP_AUTH_USER, $PHP_AUTH_PW;
// Ensures valid authentication mode, 'only_db', bookmark database and
// table names and relation table name are used
if ($cfg['Server']['user'] != $PHP_AUTH_USER) {
$servers_cnt = count($cfg['Servers']);
for ($i = 1; $i <= $servers_cnt; $i++) {
if (isset($cfg['Servers'][$i])
&& ($cfg['Servers'][$i]['host'] == $cfg['Server']['host']
&& $cfg['Servers'][$i]['user'] == $PHP_AUTH_USER)
) {
$server = $i;
$cfg['Server'] = $cfg['Servers'][$i];
break;
}
} // end for
} // end if
$cfg['Server']['user'] = $PHP_AUTH_USER;
$cfg['Server']['password'] = $PHP_AUTH_PW;
// Avoid showing the password in phpinfo()'s output
unset($GLOBALS['PHP_AUTH_PW']);
unset($_SERVER['PHP_AUTH_PW']);
return true;
} // end of the 'PMA_auth_set_user()' function
/**
* User is not allowed to login to MySQL -> authentication failed
*
* @return boolean always true (no return indeed)
*
* @access public
*/
function PMA_auth_fails()
{
$error = PMA_DBI_getError();
if ($error && $GLOBALS['errno'] != 1045) {
PMA_fatalError($error);
} else {
PMA_auth();
return true;
}
} // end of the 'PMA_auth_fails()' function
?>

View File

@@ -1,259 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Set of functions used to run single signon authentication.
*
* @package PhpMyAdmin-Auth
* @subpackage Signon
*/
/**
* Displays authentication form
*
* @global string the font face to use in case of failure
* @global string the default font size to use in case of failure
* @global string the big font size to use in case of failure
*
* @return boolean always true (no return indeed)
*
* @access public
*/
function PMA_auth()
{
unset($_SESSION['LAST_SIGNON_URL']);
if (empty($GLOBALS['cfg']['Server']['SignonURL'])) {
PMA_fatalError('You must set SignonURL!');
} elseif (! empty($_REQUEST['old_usr'])
&& ! empty($GLOBALS['cfg']['Server']['LogoutURL'])
) {
/* Perform logout to custom URL */
PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['LogoutURL']);
} else {
PMA_sendHeaderLocation($GLOBALS['cfg']['Server']['SignonURL']);
}
exit();
} // end of the 'PMA_auth()' function
/**
* Gets advanced authentication settings
*
* @global string the username if register_globals is on
* @global string the password if register_globals is on
* @global array the array of server variables if register_globals is
* off
* @global array the array of environment variables if register_globals
* is off
* @global string the username for the ? server
* @global string the password for the ? server
* @global string the username for the WebSite Professional server
* @global string the password for the WebSite Professional server
* @global string the username of the user who logs out
*
* @return boolean whether we get authentication settings or not
*
* @access public
*/
function PMA_auth_check()
{
global $PHP_AUTH_USER, $PHP_AUTH_PW;
/* Check if we're using same sigon server */
if (isset($_SESSION['LAST_SIGNON_URL'])
&& $_SESSION['LAST_SIGNON_URL'] != $GLOBALS['cfg']['Server']['SignonURL']
) {
return false;
}
/* Script name */
$script_name = $GLOBALS['cfg']['Server']['SignonScript'];
/* Session name */
$session_name = $GLOBALS['cfg']['Server']['SignonSession'];
/* Login URL */
$signon_url = $GLOBALS['cfg']['Server']['SignonURL'];
/* Current host */
$single_signon_host = $GLOBALS['cfg']['Server']['host'];
/* Current port */
$single_signon_port = $GLOBALS['cfg']['Server']['port'];
/* No configuration updates */
$single_signon_cfgupdate = array();
/* Are we requested to do logout? */
$do_logout = !empty($_REQUEST['old_usr']);
/* Handle script based auth */
if (!empty($script_name)) {
if (! file_exists($script_name)) {
PMA_fatalError(
__('Can not find signon authentication script:') . ' ' . $script_name
);
}
include $script_name;
list ($PHP_AUTH_USER, $PHP_AUTH_PW)
= get_login_credentials($cfg['Server']['user']);
} elseif (isset($_COOKIE[$session_name])) { /* Does session exist? */
/* End current session */
$old_session = session_name();
$old_id = session_id();
session_write_close();
/* Load single signon session */
session_name($session_name);
session_id($_COOKIE[$session_name]);
session_start();
/* Clear error message */
unset($_SESSION['PMA_single_signon_error_message']);
/* Grab credentials if they exist */
if (isset($_SESSION['PMA_single_signon_user'])) {
if ($do_logout) {
$PHP_AUTH_USER = '';
} else {
$PHP_AUTH_USER = $_SESSION['PMA_single_signon_user'];
}
}
if (isset($_SESSION['PMA_single_signon_password'])) {
if ($do_logout) {
$PHP_AUTH_PW = '';
} else {
$PHP_AUTH_PW = $_SESSION['PMA_single_signon_password'];
}
}
if (isset($_SESSION['PMA_single_signon_host'])) {
$single_signon_host = $_SESSION['PMA_single_signon_host'];
}
if (isset($_SESSION['PMA_single_signon_port'])) {
$single_signon_port = $_SESSION['PMA_single_signon_port'];
}
if (isset($_SESSION['PMA_single_signon_cfgupdate'])) {
$single_signon_cfgupdate = $_SESSION['PMA_single_signon_cfgupdate'];
}
/* Also get token as it is needed to access subpages */
if (isset($_SESSION['PMA_single_signon_token'])) {
/* No need to care about token on logout */
$pma_token = $_SESSION['PMA_single_signon_token'];
}
/* End single signon session */
session_write_close();
/* Restart phpMyAdmin session */
session_name($old_session);
if (!empty($old_id)) {
session_id($old_id);
}
session_start();
/* Set the single signon host */
$GLOBALS['cfg']['Server']['host'] = $single_signon_host;
/* Set the single signon port */
$GLOBALS['cfg']['Server']['port'] = $single_signon_port;
/* Configuration update */
$GLOBALS['cfg']['Server'] = array_merge(
$GLOBALS['cfg']['Server'],
$single_signon_cfgupdate
);
/* Restore our token */
if (!empty($pma_token)) {
$_SESSION[' PMA_token '] = $pma_token;
}
/**
* Clear user cache.
*/
PMA_clearUserCache();
}
// Returns whether we get authentication settings or not
if (empty($PHP_AUTH_USER)) {
unset($_SESSION['LAST_SIGNON_URL']);
return false;
} else {
$_SESSION['LAST_SIGNON_URL'] = $GLOBALS['cfg']['Server']['SignonURL'];
return true;
}
} // end of the 'PMA_auth_check()' function
/**
* Set the user and password after last checkings if required
*
* @global array the valid servers settings
* @global integer the id of the current server
* @global array the current server settings
* @global string the current username
* @global string the current password
*
* @return boolean always true
*
* @access public
*/
function PMA_auth_set_user()
{
global $cfg;
global $PHP_AUTH_USER, $PHP_AUTH_PW;
$cfg['Server']['user'] = $PHP_AUTH_USER;
$cfg['Server']['password'] = $PHP_AUTH_PW;
return true;
} // end of the 'PMA_auth_set_user()' function
/**
* User is not allowed to login to MySQL -> authentication failed
*
* @return boolean always true (no return indeed)
*
* @access public
*/
function PMA_auth_fails()
{
/* Session name */
$session_name = $GLOBALS['cfg']['Server']['SignonSession'];
/* Does session exist? */
if (isset($_COOKIE[$session_name])) {
/* End current session */
$old_session = session_name();
$old_id = session_id();
session_write_close();
/* Load single signon session */
session_name($session_name);
session_id($_COOKIE[$session_name]);
session_start();
/* Set error message */
if (! empty($GLOBALS['login_without_password_is_forbidden'])) {
$_SESSION['PMA_single_signon_error_message'] = __('Login without a password is forbidden by configuration (see AllowNoPassword)');
} elseif (! empty($GLOBALS['allowDeny_forbidden'])) {
$_SESSION['PMA_single_signon_error_message'] = __('Access denied');
} elseif (! empty($GLOBALS['no_activity'])) {
$_SESSION['PMA_single_signon_error_message'] = sprintf(__('No activity within %s seconds; please log in again'), $GLOBALS['cfg']['LoginCookieValidity']);
} elseif (PMA_DBI_getError()) {
$_SESSION['PMA_single_signon_error_message'] = PMA_sanitize(PMA_DBI_getError());
} else {
$_SESSION['PMA_single_signon_error_message'] = __('Cannot log in to the MySQL server');
}
}
PMA_auth();
} // end of the 'PMA_auth_fails()' function
?>

View File

@@ -478,59 +478,5 @@ class Horde_Cipher_blowfish
return pack("NN", $R ^ $this->p[0], $L);
}
}
// higher-level functions:
/**
* Encryption using blowfish algorithm
*
* @param string $data original data
* @param string $secret the secret
*
* @return string the encrypted result
*
* @access public
*
*/
function PMA_blowfish_encrypt($data, $secret)
{
$pma_cipher = new Horde_Cipher_blowfish;
$encrypt = '';
$mod = strlen($data) % 8;
if ($mod > 0) {
$data .= str_repeat("\0", 8 - $mod);
}
foreach (str_split($data, 8) as $chunk) {
$encrypt .= $pma_cipher->encryptBlock($chunk, $secret);
}
return base64_encode($encrypt);
}
/**
* Decryption using blowfish algorithm
*
* @param string $encdata encrypted data
* @param string $secret the secret
*
* @return string original data
*
* @access public
*
*/
function PMA_blowfish_decrypt($encdata, $secret)
{
$pma_cipher = new Horde_Cipher_blowfish;
$decrypt = '';
$data = base64_decode($encdata);
foreach (str_split($data, 8) as $chunk) {
$decrypt .= $pma_cipher->decryptBlock($chunk, $secret);
}
return trim($decrypt);
}
?>

View File

@@ -53,25 +53,26 @@ function PMA_Bookmark_getParams()
function PMA_Bookmark_getList($db)
{
global $controllink;
$common_functions = PMA_CommonFunctions::getInstance();
$cfgBookmark = PMA_Bookmark_getParams();
if (empty($cfgBookmark)) {
return array();
}
$query = 'SELECT label, id FROM '. PMA_backquote($cfgBookmark['db'])
. '.' . PMA_backquote($cfgBookmark['table'])
. ' WHERE dbase = \'' . PMA_sqlAddSlashes($db) . '\''
. ' AND user = \'' . PMA_sqlAddSlashes($cfgBookmark['user']) . '\''
$query = 'SELECT label, id FROM '. $common_functions->backquote($cfgBookmark['db'])
. '.' . $common_functions->backquote($cfgBookmark['table'])
. ' WHERE dbase = \'' . $common_functions->sqlAddSlashes($db) . '\''
. ' AND user = \'' . $common_functions->sqlAddSlashes($cfgBookmark['user']) . '\''
. ' ORDER BY label';
$per_user = PMA_DBI_fetch_result(
$query, 'id', 'label', $controllink, PMA_DBI_QUERY_STORE
);
$query = 'SELECT label, id FROM '. PMA_backquote($cfgBookmark['db'])
. '.' . PMA_backquote($cfgBookmark['table'])
. ' WHERE dbase = \'' . PMA_sqlAddSlashes($db) . '\''
$query = 'SELECT label, id FROM '. $common_functions->backquote($cfgBookmark['db'])
. '.' . $common_functions->backquote($cfgBookmark['table'])
. ' WHERE dbase = \'' . $common_functions->sqlAddSlashes($db) . '\''
. ' AND user = \'\''
. ' ORDER BY label';
$global = PMA_DBI_fetch_result(
@@ -112,25 +113,26 @@ function PMA_Bookmark_get($db, $id, $id_field = 'id', $action_bookmark_all = fal
) {
global $controllink;
$common_functions = PMA_CommonFunctions::getInstance();
$cfgBookmark = PMA_Bookmark_getParams();
if (empty($cfgBookmark)) {
return '';
}
$query = 'SELECT query FROM ' . PMA_backquote($cfgBookmark['db'])
. '.' . PMA_backquote($cfgBookmark['table'])
. ' WHERE dbase = \'' . PMA_sqlAddSlashes($db) . '\'';
$query = 'SELECT query FROM ' . $common_functions->backquote($cfgBookmark['db'])
. '.' . $common_functions->backquote($cfgBookmark['table'])
. ' WHERE dbase = \'' . $common_functions->sqlAddSlashes($db) . '\'';
if (!$action_bookmark_all) {
$query .= ' AND (user = \'' . PMA_sqlAddSlashes($cfgBookmark['user']) . '\'';
$query .= ' AND (user = \'' . $common_functions->sqlAddSlashes($cfgBookmark['user']) . '\'';
if (!$exact_user_match) {
$query .= ' OR user = \'\'';
}
$query .= ')';
}
$query .= ' AND ' . PMA_backquote($id_field) . ' = ' . $id;
$query .= ' AND ' . PMA_CommonFunctions::getInstance()->backquote($id_field) . ' = ' . $id;
return PMA_DBI_fetch_value($query, 0, 0, $controllink);
} // end of the 'PMA_Bookmark_get()' function
@@ -152,19 +154,20 @@ function PMA_Bookmark_save($fields, $all_users = false)
{
global $controllink;
$common_functions = PMA_CommonFunctions::getInstance();
$cfgBookmark = PMA_Bookmark_getParams();
if (empty($cfgBookmark)) {
return false;
}
$query = 'INSERT INTO ' . PMA_backquote($cfgBookmark['db'])
. '.' . PMA_backquote($cfgBookmark['table'])
$query = 'INSERT INTO ' . $common_functions->backquote($cfgBookmark['db'])
. '.' . $common_functions->backquote($cfgBookmark['table'])
. ' (id, dbase, user, query, label)'
. ' VALUES (NULL, \'' . PMA_sqlAddSlashes($fields['dbase']) . '\', '
. '\'' . ($all_users ? '' : PMA_sqlAddSlashes($fields['user'])) . '\', '
. '\'' . PMA_sqlAddSlashes(urldecode($fields['query'])) . '\', '
. '\'' . PMA_sqlAddSlashes($fields['label']) . '\')';
. ' VALUES (NULL, \'' . $common_functions->sqlAddSlashes($fields['dbase']) . '\', '
. '\'' . ($all_users ? '' : $common_functions->sqlAddSlashes($fields['user'])) . '\', '
. '\'' . $common_functions->sqlAddSlashes(urldecode($fields['query'])) . '\', '
. '\'' . $common_functions->sqlAddSlashes($fields['label']) . '\')';
return PMA_DBI_query($query, $controllink);
} // end of the 'PMA_Bookmark_save()' function
@@ -185,15 +188,16 @@ function PMA_Bookmark_delete($db, $id)
{
global $controllink;
$common_functions = PMA_CommonFunctions::getInstance();
$cfgBookmark = PMA_Bookmark_getParams();
if (empty($cfgBookmark)) {
return false;
}
$query = 'DELETE FROM ' . PMA_backquote($cfgBookmark['db'])
. '.' . PMA_backquote($cfgBookmark['table'])
. ' WHERE (user = \'' . PMA_sqlAddSlashes($cfgBookmark['user']) . '\''
$query = 'DELETE FROM ' . $common_functions->backquote($cfgBookmark['db'])
. '.' . $common_functions->backquote($cfgBookmark['table'])
. ' WHERE (user = \'' . $common_functions->sqlAddSlashes($cfgBookmark['user']) . '\''
. ' OR user = \'\')'
. ' AND id = ' . $id;
return PMA_DBI_try_query($query, $controllink);

View File

@@ -76,10 +76,11 @@ function PMA_buildHtmlForDb(
$column_order, $replication_types, $replication_info
) {
$common_functions = PMA_CommonFunctions::getInstance();
$out = '';
if ($is_superuser || $GLOBALS['cfg']['AllowUserDropDatabase']) {
$out .= '<td class="tool">';
$out .= '<input type="checkbox" name="selected_dbs[]" '
$out .= '<input type="checkbox" name="selected_dbs[]" class="checkall" '
. 'title="' . htmlspecialchars($current['SCHEMA_NAME']) . '" '
. 'value="' . htmlspecialchars($current['SCHEMA_NAME']) . '" ';
@@ -111,9 +112,13 @@ function PMA_buildHtmlForDb(
$column_order[$stat_name]['footer'] += $current[$stat_name];
}
if ($stat['format'] === 'byte') {
list($value, $unit) = PMA_formatByteDown($current[$stat_name], 3, 1);
list($value, $unit) = $common_functions->formatByteDown(
$current[$stat_name], 3, 1
);
} elseif ($stat['format'] === 'number') {
$value = PMA_formatNumber($current[$stat_name], 0);
$value = $common_functions->formatNumber(
$current[$stat_name], 0
);
} else {
$value = htmlentities($current[$stat_name], 0);
}
@@ -141,7 +146,7 @@ function PMA_buildHtmlForDb(
$replication_info[$type]['Ignore_DB']
);
if (strlen($key) > 0) {
$out .= PMA_getIcon('s_cancel.png', __('Not replicated'));
$out .= $common_functions->getIcon('s_cancel.png', __('Not replicated'));
} else {
$key = array_search(
$current["SCHEMA_NAME"], $replication_info[$type]['Do_DB']
@@ -152,7 +157,7 @@ function PMA_buildHtmlForDb(
&& count($replication_info[$type]['Do_DB']) == 1)
) {
// if ($key != null) did not work for index "0"
$out .= PMA_getIcon('s_success.png', __('Replicated'));
$out .= $common_functions->getIcon('s_success.png', __('Replicated'));
}
}
@@ -174,7 +179,7 @@ function PMA_buildHtmlForDb(
)
. '">'
. ' '
. PMA_getIcon('s_rights.png', __('Check Privileges'))
. $common_functions->getIcon('s_rights.png', __('Check Privileges'))
. '</a></td>';
}
return array($column_order, $out);

View File

@@ -34,13 +34,16 @@ $GLOBALS['is_superuser'] = PMA_isSuperuser();
*/
function PMA_analyseShowGrant()
{
if (PMA_cacheExists('is_create_db_priv', true)) {
$GLOBALS['is_create_db_priv'] = PMA_cacheGet('is_create_db_priv', true);
$GLOBALS['is_process_priv'] = PMA_cacheGet('is_process_priv', true);
$GLOBALS['is_reload_priv'] = PMA_cacheGet('is_reload_priv', true);
$GLOBALS['db_to_create'] = PMA_cacheGet('db_to_create', true);
$common_functions = PMA_CommonFunctions::getInstance();
if ($common_functions->cacheExists('is_create_db_priv', true)) {
$GLOBALS['is_create_db_priv'] = $common_functions->cacheGet('is_create_db_priv', true);
$GLOBALS['is_process_priv'] = $common_functions->cacheGet('is_process_priv', true);
$GLOBALS['is_reload_priv'] = $common_functions->cacheGet('is_reload_priv', true);
$GLOBALS['db_to_create'] = $common_functions->cacheGet('db_to_create', true);
$GLOBALS['dbs_where_create_table_allowed']
= PMA_cacheGet('dbs_where_create_table_allowed', true);
= $common_functions->cacheGet('dbs_where_create_table_allowed', true);
return;
}
@@ -67,7 +70,8 @@ function PMA_analyseShowGrant()
$row[0], $db_name_offset,
strpos($row[0], '.', $db_name_offset) - $db_name_offset
);
$show_grants_dbname = PMA_unQuote($show_grants_dbname, '`');
$show_grants_dbname
= $common_functions->unQuote($show_grants_dbname, '`');
$show_grants_str = substr($row[0], 6, (strpos($row[0], ' ON ') - 6));
if ($show_grants_str == 'RELOAD') {
@@ -96,7 +100,7 @@ function PMA_analyseShowGrant()
// this array may contain wildcards
$GLOBALS['dbs_where_create_table_allowed'][] = $show_grants_dbname;
$dbname_to_test = PMA_backquote($show_grants_dbname);
$dbname_to_test = $common_functions->backquote($show_grants_dbname);
if ($GLOBALS['is_create_db_priv']) {
// no need for any more tests if we already know this
@@ -136,12 +140,13 @@ function PMA_analyseShowGrant()
PMA_DBI_free_result($rs_usr);
// must also PMA_cacheUnset() them in libraries/auth/cookie.auth.lib.php
PMA_cacheSet('is_create_db_priv', $GLOBALS['is_create_db_priv'], true);
PMA_cacheSet('is_process_priv', $GLOBALS['is_process_priv'], true);
PMA_cacheSet('is_reload_priv', $GLOBALS['is_reload_priv'], true);
PMA_cacheSet('db_to_create', $GLOBALS['db_to_create'], true);
PMA_cacheSet(
// must also cacheUnset() them in
// libraries/plugins/auth/AuthenticationCookie.class.php
$common_functions->cacheSet('is_create_db_priv', $GLOBALS['is_create_db_priv'], true);
$common_functions->cacheSet('is_process_priv', $GLOBALS['is_process_priv'], true);
$common_functions->cacheSet('is_reload_priv', $GLOBALS['is_reload_priv'], true);
$common_functions->cacheSet('db_to_create', $GLOBALS['db_to_create'], true);
$common_functions->cacheSet(
'dbs_where_create_table_allowed',
$GLOBALS['dbs_where_create_table_allowed'],
true

View File

@@ -133,7 +133,7 @@ if (! defined('PMA_MINIMUM_COMMON')) {
/**
* common functions
*/
include_once './libraries/common.lib.php';
include_once './libraries/CommonFunctions.class.php';
/**
* JavaScript escaping.
@@ -839,21 +839,28 @@ if (! defined('PMA_MINIMUM_COMMON')) {
// to allow HTTP or http
$cfg['Server']['auth_type'] = strtolower($cfg['Server']['auth_type']);
if (! file_exists('./libraries/auth/' . $cfg['Server']['auth_type'] . '.auth.lib.php')) {
PMA_fatalError(
__('Invalid authentication method set in configuration:') . ' ' . $cfg['Server']['auth_type']
);
}
/**
* the required auth type plugin
*/
include_once './libraries/auth/' . $cfg['Server']['auth_type'] . '.auth.lib.php';
if (! PMA_auth_check()) {
$auth_class = "Authentication" . ucfirst($cfg['Server']['auth_type']);
if (! file_exists('./libraries/plugins/auth/' . $auth_class . '.class.php')) {
PMA_fatalError(
__('Invalid authentication method set in configuration:')
. ' ' . $cfg['Server']['auth_type']
);
}
include_once './libraries/plugins/auth/' . $auth_class . '.class.php';
// todo: add plugin manager
$plugin_manager = null;
$auth_plugin = new $auth_class($plugin_manager);
if (! $auth_plugin->authCheck()) {
/* Force generating of new session on login */
PMA_secureSession();
PMA_auth();
$auth_plugin->auth();
} else {
PMA_auth_set_user();
$auth_plugin->authSetUser();
}
// Check IP-based Allow/Deny rules as soon as possible to reject the
@@ -897,7 +904,7 @@ if (! defined('PMA_MINIMUM_COMMON')) {
// Ejects the user if banished
if ($allowDeny_forbidden) {
PMA_log_user($cfg['Server']['user'], 'allow-denied');
PMA_auth_fails();
$auth_plugin->authFails();
}
} // end if
@@ -905,14 +912,14 @@ if (! defined('PMA_MINIMUM_COMMON')) {
if (!$cfg['Server']['AllowRoot'] && $cfg['Server']['user'] == 'root') {
$allowDeny_forbidden = true;
PMA_log_user($cfg['Server']['user'], 'root-denied');
PMA_auth_fails();
$auth_plugin->authFails();
}
// is a login without password allowed?
if (!$cfg['Server']['AllowNoPassword'] && $cfg['Server']['password'] == '') {
$login_without_password_is_forbidden = true;
PMA_log_user($cfg['Server']['user'], 'empty-denied');
PMA_auth_fails();
$auth_plugin->authFails();
}
// if using TCP socket is not needed
@@ -1017,7 +1024,9 @@ if (! defined('PMA_MINIMUM_COMMON')) {
* check if profiling was requested and remember it
* (note: when $cfg['ServerDefault'] = 0, constant is not defined)
*/
if (isset($_REQUEST['profiling']) && PMA_profilingSupported()) {
if (isset($_REQUEST['profiling'])
&& PMA_CommonFunctions::getInstance()->profilingSupported()
) {
$_SESSION['profiling'] = true;
} elseif (isset($_REQUEST['profiling_form'])) {
// the checkbox was unchecked

File diff suppressed because it is too large Load Diff

View File

@@ -1680,9 +1680,9 @@ $cfg['Export']['pdf_structure_or_data'] = 'data';
/**
*
*
* @global string $cfg['Export']['php_array_structure_or_data']
* @global string $cfg['Export']['phparray_structure_or_data']
*/
$cfg['Export']['php_array_structure_or_data'] = 'data';
$cfg['Export']['phparray_structure_or_data'] = 'data';
/**
*

View File

@@ -151,7 +151,7 @@ function display_input($path, $name, $type, $value, $description = '',
);
if ($is_setup_script) {
// When called from the setup script, we don't have access to the
// sprite-aware PMA_getImage() function because the PMA_theme class
// sprite-aware getImage() function because the PMA_theme class
// has not been loaded, so we generate the img tags manually.
foreach ($icon_init as $k => $v) {
$title = '';
@@ -166,9 +166,11 @@ function display_input($path, $name, $type, $value, $description = '',
);
}
} else {
// In this case we just use PMA_getImage() because it's available
// In this case we just use getImage() because it's available
foreach ($icon_init as $k => $v) {
$icons[$k] = PMA_getImage($v[0], $v[1]);
$icons[$k] = PMA_CommonFunctions::getInstance()->getImage(
$v[0], $v[1]
);
}
}
}

View File

@@ -301,7 +301,7 @@ function PMA_warnMissingExtension($extension, $fatal = false, $extra = '')
function PMA_getTableCount($db)
{
$tables = PMA_DBI_try_query(
'SHOW TABLES FROM ' . PMA_backquote($db) . ';',
'SHOW TABLES FROM ' . PMA_CommonFunctions::getInstance()->backquote($db) . ';',
null, PMA_DBI_QUERY_STORE
);
if ($tables) {
@@ -575,6 +575,9 @@ function PMA_sendHeaderLocation($uri, $use_refresh = false)
*/
function PMA_noCacheHeader()
{
if (defined('TESTSUITE')) {
return;
}
// rfc2616 - Section 14.21
header('Expires: ' . date(DATE_RFC1123));
// HTTP/1.1

View File

@@ -59,7 +59,7 @@ if (! PMA_DBI_checkDbExtension($GLOBALS['cfg']['Server']['extension'])) {
PMA_warnMissingExtension(
$GLOBALS['cfg']['Server']['extension'],
false,
PMA_showDocu('faqmysql')
PMA_CommonFunctions::getInstance()->showDocu('faqmysql')
);
if ($GLOBALS['cfg']['Server']['extension'] === 'mysql') {
@@ -73,7 +73,7 @@ if (! PMA_DBI_checkDbExtension($GLOBALS['cfg']['Server']['extension'])) {
PMA_warnMissingExtension(
$GLOBALS['cfg']['Server']['extension'],
true,
PMA_showDocu('faqmysql')
PMA_CommonFunctions::getInstance()->showDocu('faqmysql')
);
}
@@ -101,7 +101,7 @@ function PMA_DBI_query($query, $link = null, $options = 0,
$cache_affected_rows = true
) {
$res = PMA_DBI_try_query($query, $link, $options, $cache_affected_rows)
or PMA_mysqlDie(PMA_DBI_getError($link), $query);
or PMA_CommonFunctions::getInstance()->mysqlDie(PMA_DBI_getError($link), $query);
return $res;
}
@@ -291,7 +291,7 @@ function PMA_DBI_convert_message($message)
function PMA_DBI_get_tables($database, $link = null)
{
return PMA_DBI_fetch_result(
'SHOW TABLES FROM ' . PMA_backquote($database) . ';',
'SHOW TABLES FROM ' . PMA_CommonFunctions::getInstance()->backquote($database) . ';',
null,
0,
$link,
@@ -363,6 +363,9 @@ function PMA_DBI_get_tables_full($database, $table = false,
$tbl_is_group = false, $link = null, $limit_offset = 0,
$limit_count = false, $sort_by = 'Name', $sort_order = 'ASC'
) {
$common_functions = PMA_CommonFunctions::getInstance();
if (true === $limit_count) {
$limit_count = $GLOBALS['cfg']['MaxTableList'];
}
@@ -380,13 +383,13 @@ function PMA_DBI_get_tables_full($database, $table = false,
if ($table) {
if (true === $tbl_is_group) {
$sql_where_table = 'AND t.`TABLE_NAME` LIKE \''
. PMA_escapeMysqlWildcards(PMA_sqlAddSlashes($table)) . '%\'';
. $common_functions->escapeMysqlWildcards($common_functions->sqlAddSlashes($table)) . '%\'';
} elseif ('comment' === $tbl_is_group) {
$sql_where_table = 'AND t.`TABLE_COMMENT` LIKE \''
. PMA_escapeMysqlWildcards(PMA_sqlAddSlashes($table)) . '%\'';
. $common_functions->escapeMysqlWildcards($common_functions->sqlAddSlashes($table)) . '%\'';
} else {
$sql_where_table = 'AND t.`TABLE_NAME` = \''
. PMA_sqlAddSlashes($table) . '\'';
. $common_functions->sqlAddSlashes($table) . '\'';
}
} else {
$sql_where_table = '';
@@ -399,10 +402,10 @@ function PMA_DBI_get_tables_full($database, $table = false,
// added BINARY in the WHERE clause to force a case sensitive
// comparison (if we are looking for the db Aa we don't want
// to find the db aa)
$this_databases = array_map('PMA_sqlAddSlashes', $databases);
$this_databases = array_map('sqlAddSlashes', $databases);
if (PMA_DRIZZLE) {
$engine_info = PMA_cacheGet('drizzle_engines', true);
$engine_info = $common_functions->cacheGet('drizzle_engines', true);
$stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
if (isset($engine_info['InnoDB'])
&& $engine_info['InnoDB']['module_library'] == 'innobase'
@@ -525,13 +528,13 @@ function PMA_DBI_get_tables_full($database, $table = false,
foreach ($databases as $each_database) {
if ($table || (true === $tbl_is_group)) {
$sql = 'SHOW TABLE STATUS FROM '
. PMA_backquote($each_database)
. $common_functions->backquote($each_database)
.' LIKE \''
. PMA_escapeMysqlWildcards(PMA_sqlAddSlashes($table, true))
. $common_functions->escapeMysqlWildcards($common_functions->sqlAddSlashes($table, true))
. '%\'';
} else {
$sql = 'SHOW TABLE STATUS FROM '
. PMA_backquote($each_database);
. $common_functions->backquote($each_database);
}
$useStatusCache = false;
@@ -660,7 +663,8 @@ function PMA_DBI_get_tables_full($database, $table = false,
$each_tables[$table_name]['TABLE_TYPE'] = 'VIEW';
} else {
/**
* @todo difference between 'TEMPORARY' and 'BASE TABLE' but how to detect?
* @todo difference between 'TEMPORARY' and 'BASE TABLE'
* but how to detect?
*/
$each_tables[$table_name]['TABLE_TYPE'] = 'BASE TABLE';
}
@@ -736,6 +740,8 @@ function PMA_DBI_get_databases_full($database = null, $force_stats = false,
$link = null, $sort_by = 'SCHEMA_NAME', $sort_order = 'ASC',
$limit_offset = 0, $limit_count = false
) {
$common_functions = PMA_CommonFunctions::getInstance();
$sort_order = strtoupper($sort_order);
if (true === $limit_count) {
@@ -764,7 +770,7 @@ function PMA_DBI_get_databases_full($database = null, $force_stats = false,
// get table information from information_schema
if ($database) {
$sql_where_schema = 'WHERE `SCHEMA_NAME` LIKE \''
. PMA_sqlAddSlashes($database) . '\'';
. $common_functions->sqlAddSlashes($database) . '\'';
} else {
$sql_where_schema = '';
}
@@ -785,7 +791,7 @@ function PMA_DBI_get_databases_full($database = null, $force_stats = false,
$sql .= '
FROM data_dictionary.SCHEMAS s';
if ($force_stats) {
$engine_info = PMA_cacheGet('drizzle_engines', true);
$engine_info = $common_functions->cacheGet('drizzle_engines', true);
$stats_join = "LEFT JOIN (SELECT 0 NUM_ROWS) AS stat ON false";
if (isset($engine_info['InnoDB'])
&& $engine_info['InnoDB']['module_library'] == 'innobase'
@@ -802,7 +808,7 @@ function PMA_DBI_get_databases_full($database = null, $force_stats = false,
}
$sql .= $sql_where_schema . '
GROUP BY s.SCHEMA_NAME
ORDER BY ' . PMA_backquote($sort_by) . ' ' . $sort_order
ORDER BY ' . $common_functions->backquote($sort_by) . ' ' . $sort_order
. $limit;
} else {
$sql = 'SELECT
@@ -828,7 +834,7 @@ function PMA_DBI_get_databases_full($database = null, $force_stats = false,
}
$sql .= $sql_where_schema . '
GROUP BY BINARY s.SCHEMA_NAME
ORDER BY BINARY ' . PMA_backquote($sort_by) . ' ' . $sort_order
ORDER BY BINARY ' . $common_functions->backquote($sort_by) . ' ' . $sort_order
. $limit;
}
@@ -836,7 +842,7 @@ function PMA_DBI_get_databases_full($database = null, $force_stats = false,
$mysql_error = PMA_DBI_getError($link);
if (! count($databases) && $GLOBALS['errno']) {
PMA_mysqlDie($mysql_error, $sql);
$common_functions->mysqlDie($mysql_error, $sql);
}
// display only databases also in official database list
@@ -875,7 +881,9 @@ function PMA_DBI_get_databases_full($database = null, $force_stats = false,
$databases[$database_name]['SCHEMA_DATA_FREE'] = 0;
$res = PMA_DBI_query('SHOW TABLE STATUS FROM '
. PMA_backquote($database_name) . ';');
. $common_functions->backquote($database_name) . ';'
);
while ($row = PMA_DBI_fetch_assoc($res)) {
$databases[$database_name]['SCHEMA_TABLES']++;
$databases[$database_name]['SCHEMA_TABLE_ROWS']
@@ -938,6 +946,8 @@ function PMA_DBI_get_databases_full($database = null, $force_stats = false,
function PMA_DBI_get_columns_full($database = null, $table = null,
$column = null, $link = null
) {
$common_functions = PMA_CommonFunctions::getInstance();
$columns = array();
if (! $GLOBALS['cfg']['Server']['DisableIS']) {
@@ -947,19 +957,19 @@ function PMA_DBI_get_columns_full($database = null, $table = null,
// get columns information from information_schema
if (null !== $database) {
$sql_wheres[] = '`TABLE_SCHEMA` = \''
. PMA_sqlAddSlashes($database) . '\' ';
. $common_functions->sqlAddSlashes($database) . '\' ';
} else {
$array_keys[] = 'TABLE_SCHEMA';
}
if (null !== $table) {
$sql_wheres[] = '`TABLE_NAME` = \''
. PMA_sqlAddSlashes($table) . '\' ';
. $common_functions->sqlAddSlashes($table) . '\' ';
} else {
$array_keys[] = 'TABLE_NAME';
}
if (null !== $column) {
$sql_wheres[] = '`COLUMN_NAME` = \''
. PMA_sqlAddSlashes($column) . '\' ';
. $common_functions->sqlAddSlashes($column) . '\' ';
} else {
$array_keys[] = 'COLUMN_NAME';
}
@@ -1032,9 +1042,9 @@ function PMA_DBI_get_columns_full($database = null, $table = null,
}
$sql = 'SHOW FULL COLUMNS FROM '
. PMA_backquote($database) . '.' . PMA_backquote($table);
. $common_functions->backquote($database) . '.' . $common_functions->backquote($table);
if (null !== $column) {
$sql .= " LIKE '" . PMA_sqlAddSlashes($column, true) . "'";
$sql .= " LIKE '" . $common_functions->sqlAddSlashes($column, true) . "'";
}
$columns = PMA_DBI_fetch_result($sql, 'Field', null, $link);
@@ -1111,6 +1121,9 @@ function PMA_DBI_get_columns_full($database = null, $table = null,
*/
function PMA_DBI_get_columns_sql($database, $table, $column = null, $full = false)
{
$common_functions = PMA_CommonFunctions::getInstance();
if (PMA_DRIZZLE) {
// `Key` column:
// * used in primary key => PRI
@@ -1148,15 +1161,15 @@ function PMA_DBI_get_columns_sql($database, $table, $column = null, $full = fals
NULL AS `Privileges`,
column_comment AS `Comment`" : '') . "
FROM data_dictionary.columns
WHERE table_schema = '" . PMA_sqlAddSlashes($database) . "'
AND table_name = '" . PMA_sqlAddSlashes($table) . "'
WHERE table_schema = '" . $common_functions->sqlAddSlashes($database) . "'
AND table_name = '" . $common_functions->sqlAddSlashes($table) . "'
" . (($column != null) ? "
AND column_name = '" . PMA_sqlAddSlashes($column) . "'" : '');
AND column_name = '" . $common_functions->sqlAddSlashes($column) . "'" : '');
// ORDER BY ordinal_position
} else {
$sql = 'SHOW ' . ($full ? 'FULL' : '') . ' COLUMNS
FROM ' . PMA_backquote($database) . '.' . PMA_backquote($table)
. (($column != null) ? "LIKE '" . PMA_sqlAddSlashes($column, true) . "'" : '');
FROM ' . $common_functions->backquote($database) . '.' . $common_functions->backquote($table)
. (($column != null) ? "LIKE '" . $common_functions->sqlAddSlashes($column, true) . "'" : '');
}
return $sql;
}
@@ -1176,6 +1189,8 @@ function PMA_DBI_get_columns_sql($database, $table, $column = null, $full = fals
function PMA_DBI_get_columns($database, $table, $column = null, $full = false,
$link = null
) {
$common_functions = PMA_CommonFunctions::getInstance();
$sql = PMA_DBI_get_columns_sql($database, $table, $column, $full);
$fields = PMA_DBI_fetch_result($sql, 'Field', null, $link);
if (! is_array($fields) || count($fields) == 0) {
@@ -1203,8 +1218,8 @@ function PMA_DBI_get_columns($database, $table, $column = null, $full = false,
FROM data_dictionary.indexes i
JOIN data_dictionary.index_parts p
USING (table_schema, table_name)
WHERE i.table_schema = '" . PMA_sqlAddSlashes($database) . "'
AND i.table_name = '" . PMA_sqlAddSlashes($table) . "'
WHERE i.table_schema = '" . $common_functions->sqlAddSlashes($database) . "'
AND i.table_name = '" . $common_functions->sqlAddSlashes($table) . "'
AND i.is_unique
AND NOT i.is_nullable";
$fs = PMA_DBI_fetch_result($sql, 'index_name', null, $link);
@@ -1250,6 +1265,9 @@ function PMA_DBI_get_column_names($database, $table, $link = null)
*/
function PMA_DBI_get_table_indexes_sql($database, $table, $where = null)
{
$common_functions = PMA_CommonFunctions::getInstance();
if (PMA_DRIZZLE) {
$sql = "SELECT
ip.table_name AS `Table`,
@@ -1270,12 +1288,12 @@ function PMA_DBI_get_table_indexes_sql($database, $table, $where = null)
FROM data_dictionary.index_parts ip
LEFT JOIN data_dictionary.indexes i
USING (table_schema, table_name, index_name)
WHERE table_schema = '" . PMA_sqlAddSlashes($database) . "'
AND table_name = '" . PMA_sqlAddSlashes($table) . "'
WHERE table_schema = '" . $common_functions->sqlAddSlashes($database) . "'
AND table_name = '" . $common_functions->sqlAddSlashes($table) . "'
";
} else {
$sql = 'SHOW INDEXES FROM ' . PMA_backquote($database) . '.'
. PMA_backquote($table);
$sql = 'SHOW INDEXES FROM ' . $common_functions->backquote($database) . '.'
. $common_functions->backquote($table);
}
if ($where) {
$sql .= (PMA_DRIZZLE ? ' AND (' : ' WHERE (') . $where . ')';
@@ -1349,23 +1367,26 @@ function PMA_DBI_get_variable($var, $type = PMA_DBI_GETVAR_SESSION, $link = null
*/
function PMA_DBI_postConnect($link, $is_controluser = false)
{
$common_functions = PMA_CommonFunctions::getInstance();
if (! defined('PMA_MYSQL_INT_VERSION')) {
if (PMA_cacheExists('PMA_MYSQL_INT_VERSION', true)) {
if ($common_functions->cacheExists('PMA_MYSQL_INT_VERSION', true)) {
define(
'PMA_MYSQL_INT_VERSION',
PMA_cacheGet('PMA_MYSQL_INT_VERSION', true)
$common_functions->cacheGet('PMA_MYSQL_INT_VERSION', true)
);
define(
'PMA_MYSQL_MAJOR_VERSION',
PMA_cacheGet('PMA_MYSQL_MAJOR_VERSION', true)
$common_functions->cacheGet('PMA_MYSQL_MAJOR_VERSION', true)
);
define(
'PMA_MYSQL_STR_VERSION',
PMA_cacheGet('PMA_MYSQL_STR_VERSION', true)
$common_functions->cacheGet('PMA_MYSQL_STR_VERSION', true)
);
define(
'PMA_MYSQL_VERSION_COMMENT',
PMA_cacheGet('PMA_MYSQL_VERSION_COMMENT', true)
$common_functions->cacheGet('PMA_MYSQL_VERSION_COMMENT', true)
);
} else {
$version = PMA_DBI_fetch_single_row(
@@ -1391,22 +1412,22 @@ function PMA_DBI_postConnect($link, $is_controluser = false)
define('PMA_MYSQL_STR_VERSION', '5.00.15');
define('PMA_MYSQL_VERSION_COMMENT', '');
}
PMA_cacheSet(
$common_functions->cacheSet(
'PMA_MYSQL_INT_VERSION',
PMA_MYSQL_INT_VERSION,
true
);
PMA_cacheSet(
$common_functions->cacheSet(
'PMA_MYSQL_MAJOR_VERSION',
PMA_MYSQL_MAJOR_VERSION,
true
);
PMA_cacheSet(
$common_functions->cacheSet(
'PMA_MYSQL_STR_VERSION',
PMA_MYSQL_STR_VERSION,
true
);
PMA_cacheSet(
$common_functions->cacheSet(
'PMA_MYSQL_VERSION_COMMENT',
PMA_MYSQL_VERSION_COMMENT,
true
@@ -1421,9 +1442,10 @@ function PMA_DBI_postConnect($link, $is_controluser = false)
if (!PMA_DRIZZLE) {
if (! empty($GLOBALS['collation_connection'])) {
PMA_DBI_query("SET CHARACTER SET 'utf8';", $link, PMA_DBI_QUERY_STORE);
$set_collation_con_query = "SET collation_connection = '"
. $common_functions->sqlAddSlashes($GLOBALS['collation_connection']) . "';";
PMA_DBI_query(
"SET collation_connection = '"
. PMA_sqlAddSlashes($GLOBALS['collation_connection']) . "';",
$set_collation_con_query,
$link,
PMA_DBI_QUERY_STORE
);
@@ -1437,7 +1459,7 @@ function PMA_DBI_postConnect($link, $is_controluser = false)
}
// Cache plugin list for Drizzle
if (PMA_DRIZZLE && !PMA_cacheExists('drizzle_engines', true)) {
if (PMA_DRIZZLE && !$common_functions->cacheExists('drizzle_engines', true)) {
$sql = "SELECT p.plugin_name, m.module_library
FROM data_dictionary.plugins p
JOIN data_dictionary.modules m USING (module_name)
@@ -1445,7 +1467,7 @@ function PMA_DBI_postConnect($link, $is_controluser = false)
AND p.plugin_name NOT IN ('FunctionEngine', 'schema')
AND p.is_active = 'YES'";
$engines = PMA_DBI_fetch_result($sql, 'plugin_name', null, $link);
PMA_cacheSet('drizzle_engines', $engines, true);
$common_functions->cacheSet('drizzle_engines', $engines, true);
}
}
@@ -1748,8 +1770,11 @@ function PMA_DBI_get_warnings($link = null)
*/
function PMA_isSuperuser()
{
if (PMA_cacheExists('is_superuser', true)) {
return PMA_cacheGet('is_superuser', true);
$common_functions = PMA_CommonFunctions::getInstance();
if ($common_functions->cacheExists('is_superuser', true)) {
return $common_functions->cacheGet('is_superuser', true);
}
// when connection failed we don't have a $userlink
@@ -1769,12 +1794,12 @@ function PMA_isSuperuser()
PMA_DBI_QUERY_STORE
);
}
PMA_cacheSet('is_superuser', $r, true);
$common_functions->cacheSet('is_superuser', $r, true);
} else {
PMA_cacheSet('is_superuser', false, true);
$common_functions->cacheSet('is_superuser', false, true);
}
return PMA_cacheGet('is_superuser', true);
return $common_functions->cacheGet('is_superuser', true);
}
/**
@@ -1814,6 +1839,7 @@ function PMA_DBI_get_procedures_or_functions($db, $which, $link = null)
*/
function PMA_DBI_get_definition($db, $which, $name, $link = null)
{
$common_functions = PMA_CommonFunctions::getInstance();
$returned_field = array(
'PROCEDURE' => 'Create Procedure',
'FUNCTION' => 'Create Function',
@@ -1821,7 +1847,8 @@ function PMA_DBI_get_definition($db, $which, $name, $link = null)
'VIEW' => 'Create View'
);
$query = 'SHOW CREATE ' . $which . ' '
. PMA_backquote($db) . '.' . PMA_backquote($name);
. $common_functions->backquote($db) . '.'
. $common_functions->backquote($name);
return(PMA_DBI_fetch_value($query, 0, $returned_field[$which]));
}
@@ -1836,6 +1863,9 @@ function PMA_DBI_get_definition($db, $which, $name, $link = null)
*/
function PMA_DBI_get_triggers($db, $table = '', $delimiter = '//')
{
$common_functions = PMA_CommonFunctions::getInstance();
if (PMA_DRIZZLE) {
// Drizzle doesn't support triggers
return array();
@@ -1850,16 +1880,16 @@ function PMA_DBI_get_triggers($db, $table = '', $delimiter = '//')
. ', EVENT_OBJECT_TABLE, ACTION_TIMING, ACTION_STATEMENT'
. ', EVENT_OBJECT_SCHEMA, EVENT_OBJECT_TABLE, DEFINER'
. ' FROM information_schema.TRIGGERS'
. ' WHERE TRIGGER_SCHEMA= \'' . PMA_sqlAddSlashes($db) . '\'';
. ' WHERE TRIGGER_SCHEMA= \'' . $common_functions->sqlAddSlashes($db) . '\'';
if (! empty($table)) {
$query .= " AND EVENT_OBJECT_TABLE = '"
. PMA_sqlAddSlashes($table) . "';";
. $common_functions->sqlAddSlashes($table) . "';";
}
} else {
$query = "SHOW TRIGGERS FROM " . PMA_backquote($db);
$query = "SHOW TRIGGERS FROM " . $common_functions->backquote($db);
if (! empty($table)) {
$query .= " LIKE '" . PMA_sqlAddSlashes($table, true) . "';";
$query .= " LIKE '" . $common_functions->sqlAddSlashes($table, true) . "';";
}
}
@@ -1883,7 +1913,7 @@ function PMA_DBI_get_triggers($db, $table = '', $delimiter = '//')
// do not prepend the schema name; this way, importing the
// definition into another schema will work
$one_result['full_trigger_name'] = PMA_backquote(
$one_result['full_trigger_name'] = $common_functions->backquote(
$trigger['TRIGGER_NAME']
);
$one_result['drop'] = 'DROP TRIGGER IF EXISTS '
@@ -1892,7 +1922,7 @@ function PMA_DBI_get_triggers($db, $table = '', $delimiter = '//')
. $one_result['full_trigger_name'] . ' '
. $trigger['ACTION_TIMING']. ' '
. $trigger['EVENT_MANIPULATION']
. ' ON ' . PMA_backquote($trigger['EVENT_OBJECT_TABLE'])
. ' ON ' . $common_functions->backquote($trigger['EVENT_OBJECT_TABLE'])
. "\n" . ' FOR EACH ROW '
. $trigger['ACTION_STATEMENT'] . "\n" . $delimiter . "\n";

View File

@@ -14,7 +14,7 @@ if (! defined('PHPMYADMIN')) {
*/
require_once './libraries/bookmark.lib.php';
PMA_checkParameters(array('db'));
PMA_CommonFunctions::getInstance()->checkParameters(array('db'));
$is_show_stats = $cfg['ShowStats'];
@@ -60,7 +60,7 @@ if (! isset($is_db) || ! $is_db) {
*/
if (isset($submitcollation) && !empty($db_collation)) {
list($db_charset) = explode('_', $db_collation);
$sql_query = 'ALTER DATABASE ' . PMA_backquote($db) . ' DEFAULT'
$sql_query = 'ALTER DATABASE ' . PMA_CommonFunctions::getInstance()->backquote($db) . ' DEFAULT'
. PMA_generateCharsetQueryPart($db_collation);
$result = PMA_DBI_query($sql_query);
$message = PMA_Message::success();

View File

@@ -15,6 +15,8 @@ if (! defined('PHPMYADMIN')) {
exit;
}
$common_functions = PMA_CommonFunctions::getInstance();
/**
* limits for table list
*/
@@ -40,6 +42,9 @@ $pos = $_SESSION['tmp_user_values']['table_limit_offset'];
*/
function PMA_fillTooltip(&$tooltip_truename, &$tooltip_aliasname, $table)
{
$common_functions = PMA_CommonFunctions::getInstance();
if (strstr($table['Comment'], '; InnoDB free') === false) {
if (!strstr($table['Comment'], 'InnoDB free') === false) {
// here we have just InnoDB generated part
@@ -74,21 +79,24 @@ function PMA_fillTooltip(&$tooltip_truename, &$tooltip_aliasname, $table)
if (isset($table['Create_time']) && !empty($table['Create_time'])) {
$tooltip_aliasname[$table['Name']] .= ', ' . __('Creation')
. ': ' . PMA_localisedDate(strtotime($table['Create_time']));
. ': '
. $common_functions->localisedDate(strtotime($table['Create_time']));
}
if (! empty($table['Update_time'])) {
$tooltip_aliasname[$table['Name']] .= ', ' . __('Last update')
. ': ' . PMA_localisedDate(strtotime($table['Update_time']));
. ': '
. $common_functions->localisedDate(strtotime($table['Update_time']));
}
if (! empty($table['Check_time'])) {
$tooltip_aliasname[$table['Name']] .= ', ' . __('Last check')
. ': ' . PMA_localisedDate(strtotime($table['Check_time']));
. ': '
. $common_functions->localisedDate(strtotime($table['Check_time']));
}
}
PMA_checkParameters(array('db'));
$common_functions->checkParameters(array('db'));
/**
* @global bool whether to display extended stats
@@ -113,7 +121,9 @@ $tables = array();
// When used in Nested table group mode,
// only show tables matching the given groupname
if (PMA_isValid($tbl_group) && !$cfg['ShowTooltipAliasTB']) {
$tbl_group_sql = ' LIKE "' . PMA_escapeMysqlWildcards($tbl_group) . '%"';
$tbl_group_sql = ' LIKE "'
. $common_functions->escapeMysqlWildcards($tbl_group)
. '%"';
} else {
$tbl_group_sql = '';
}
@@ -126,7 +136,7 @@ if ($cfg['ShowTooltip']) {
// Special speedup for newer MySQL Versions (in 4.0 format changed)
if (true === $cfg['SkipLockedTables']) {
$db_info_result = PMA_DBI_query(
'SHOW OPEN TABLES FROM ' . PMA_backquote($db) . ';'
'SHOW OPEN TABLES FROM ' . $common_functions->backquote($db) . ';'
);
// Blending out tables in use
@@ -141,15 +151,15 @@ if (true === $cfg['SkipLockedTables']) {
if (isset($sot_cache)) {
$db_info_result = PMA_DBI_query(
'SHOW TABLES FROM ' . PMA_backquote($db) . $tbl_group_sql . ';',
'SHOW TABLES FROM ' . $common_functions->backquote($db) . $tbl_group_sql . ';',
null, PMA_DBI_QUERY_STORE
);
if ($db_info_result && PMA_DBI_num_rows($db_info_result) > 0) {
while ($tmp = PMA_DBI_fetch_row($db_info_result)) {
if (! isset($sot_cache[$tmp[0]])) {
$sts_result = PMA_DBI_query(
'SHOW TABLE STATUS FROM ' . PMA_backquote($db)
. ' LIKE \'' . PMA_sqlAddSlashes($tmp[0], true) . '\';'
'SHOW TABLE STATUS FROM ' . $common_functions->backquote($db)
. ' LIKE \'' . $common_functions->sqlAddSlashes($tmp[0], true) . '\';'
);
$sts_tmp = PMA_DBI_fetch_assoc($sts_result);
PMA_DBI_free_result($sts_result);

View File

@@ -40,7 +40,9 @@ function PMA_TableHeader($db_is_information_schema = false, $replication = false
.' </th>'
// larger values are more interesting so default sort order is DESC
.' <th>' . PMA_SortableTableHeader(__('Rows'), 'records', 'DESC')
.PMA_showHint(PMA_sanitize(__('May be approximate. See [a@./Documentation.html#faq3_11@Documentation]FAQ 3.11[/a]'))) . "\n"
. PMA_CommonFunctions::getInstance()->showHint(
PMA_sanitize(__('May be approximate. See [a@./Documentation.html#faq3_11@Documentation]FAQ 3.11[/a]'))
) . "\n"
.' </th>' . "\n";
if (!($GLOBALS['cfg']['PropertiesNumColumns'] > 1)) {
echo ' <th>' . PMA_SortableTableHeader(__('Type'), 'type') . '</th>' . "\n";
@@ -88,6 +90,8 @@ function PMA_TableHeader($db_is_information_schema = false, $replication = false
*/
function PMA_SortableTableHeader($title, $sort, $initial_sort_order = 'ASC')
{
$common_functions = PMA_CommonFunctions::getInstance();
// Set some defaults
$requested_sort = 'table';
$requested_sort_order = $future_sort_order = $initial_sort_order;
@@ -110,8 +114,8 @@ function PMA_SortableTableHeader($title, $sort, $initial_sort_order = 'ASC')
if ($requested_sort_order == 'ASC') {
$future_sort_order = 'DESC';
// current sort order is ASC
$order_img = ' ' . PMA_getImage('s_asc.png', __('Ascending'), array('class' => 'sort_arrow', 'title' => ''));
$order_img .= ' ' . PMA_getImage('s_desc.png', __('Descending'), array('class' => 'sort_arrow hide', 'title' => ''));
$order_img = ' ' . $common_functions->getImage('s_asc.png', __('Ascending'), array('class' => 'sort_arrow', 'title' => ''));
$order_img .= ' ' . $common_functions->getImage('s_desc.png', __('Descending'), array('class' => 'sort_arrow hide', 'title' => ''));
// but on mouse over, show the reverse order (DESC)
$order_link_params['onmouseover'] = "$('.sort_arrow').toggle();";
// on mouse out, show current sort order (ASC)
@@ -119,8 +123,8 @@ function PMA_SortableTableHeader($title, $sort, $initial_sort_order = 'ASC')
} else {
$future_sort_order = 'ASC';
// current sort order is DESC
$order_img = ' ' . PMA_getImage('s_asc.png', __('Ascending'), array('class' => 'sort_arrow hide', 'title' => ''));
$order_img .= ' ' . PMA_getImage('s_desc.png', __('Descending'), array('class' => 'sort_arrow', 'title' => ''));
$order_img = ' ' . $common_functions->getImage('s_asc.png', __('Ascending'), array('class' => 'sort_arrow hide', 'title' => ''));
$order_img .= ' ' . $common_functions->getImage('s_desc.png', __('Descending'), array('class' => 'sort_arrow', 'title' => ''));
// but on mouse over, show the reverse order (ASC)
$order_link_params['onmouseover'] = "$('.sort_arrow').toggle();";
// on mouse out, show current sort order (DESC)
@@ -136,6 +140,8 @@ function PMA_SortableTableHeader($title, $sort, $initial_sort_order = 'ASC')
// We set the position back to 0 every time they sort.
$url .= "&amp;pos=0&amp;sort=$sort&amp;sort_order=$future_sort_order";
return PMA_linkOrButton($url, $title . $order_img, $order_link_params);
return PMA_CommonFunctions::getInstance()->linkOrButton(
$url, $title . $order_img, $order_link_params
);
} // end function PMA_SortableTableHeader()
?>

View File

@@ -50,7 +50,7 @@ if (empty($is_table)
if (! $is_table) {
$_result = PMA_DBI_try_query(
'SHOW TABLES LIKE \'' . PMA_sqlAddSlashes($table, true) . '\';',
'SHOW TABLES LIKE \'' . PMA_CommonFunctions::getInstance()->sqlAddSlashes($table, true) . '\';',
null, PMA_DBI_QUERY_STORE
);
$is_table = @PMA_DBI_num_rows($_result);
@@ -72,7 +72,7 @@ if (empty($is_table)
* only happen if IS_TRANSFORMATION_WRAPPER?
*/
$_result = PMA_DBI_try_query(
'SELECT COUNT(*) FROM ' . PMA_backquote($table) . ';',
'SELECT COUNT(*) FROM ' . PMA_CommonFunctions::getInstance()->backquote($table) . ';',
null,
PMA_DBI_QUERY_STORE
);

View File

@@ -122,7 +122,8 @@ function PMA_DBI_connect($user, $password, $is_controluser = false, $server = nu
// go back to main login if it fails
if (! $auxiliary_connection) {
PMA_log_user($user, 'drizzle-denied');
PMA_auth_fails();
global $auth_plugin;
$auth_plugin->authFails();
} else {
return false;
}

View File

@@ -125,7 +125,8 @@ function PMA_DBI_connect($user, $password, $is_controluser = false, $server = nu
// go back to main login if it fails
if (! $auxiliary_connection) {
PMA_log_user($user, 'mysql-denied');
PMA_auth_fails();
global $auth_plugin;
$auth_plugin->authFails();
} else {
return false;
}

View File

@@ -199,7 +199,8 @@ function PMA_DBI_connect($user, $password, $is_controluser = false, $server = nu
// go back to main login if it fails
if (! $auxiliary_connection) {
PMA_log_user($user, 'mysql-denied');
PMA_auth_fails();
global $auth_plugin;
$auth_plugin->authFails();
} else {
return false;
}

View File

@@ -18,7 +18,7 @@ if ($is_create_db_priv) {
// The user is allowed to create a db
?>
<form method="post" action="db_create.php" id="create_database_form" <?php echo ($GLOBALS['cfg']['AjaxEnable'] ? 'class="ajax" ' : ''); ?>><strong>
<?php echo '<label for="text_create_db">' . __('Create database') . '</label>&nbsp;' . PMA_showMySQLDocu('SQL-Syntax', 'CREATE_DATABASE'); ?></strong><br />
<?php echo '<label for="text_create_db">' . __('Create database') . '</label>&nbsp;' . PMA_CommonFunctions::getInstance()->showMySQLDocu('SQL-Syntax', 'CREATE_DATABASE'); ?></strong><br />
<?php echo PMA_generate_common_hidden_inputs('', '', 5); ?>
<input type="hidden" name="reload" value="1" />
<input type="text" name="new_db" value="<?php echo $db_to_create; ?>" maxlength="64" class="textfield" id="text_create_db"/>
@@ -36,10 +36,10 @@ if ($is_create_db_priv) {
} else {
?>
<!-- db creation no privileges message -->
<strong><?php echo __('Create database') . ':&nbsp;' . PMA_showMySQLDocu('SQL-Syntax', 'CREATE_DATABASE'); ?></strong><br />
<strong><?php echo __('Create database') . ':&nbsp;' . PMA_CommonFunctions::getInstance()->showMySQLDocu('SQL-Syntax', 'CREATE_DATABASE'); ?></strong><br />
<?php
echo '<span class="noPrivileges">'
. PMA_getImage('s_error2.png', '', array('hspace' => 2, 'border' => 0, 'align' => 'middle'))
. PMA_CommonFunctions::getInstance()->getImage('s_error2.png', '', array('hspace' => 2, 'border' => 0, 'align' => 'middle'))
. '' . __('No Privileges') .'</span>';
} // end create db form or message
?>

View File

@@ -41,7 +41,7 @@ $is_create_table_priv = true;
<legend>
<?php
if ($GLOBALS['cfg']['PropertiesIconic']) {
echo PMA_getImage('b_newtbl.png');
echo PMA_CommonFunctions::getInstance()->getImage('b_newtbl.png');
}
echo __('Create table');
?>

View File

@@ -8,6 +8,7 @@ if (! defined('PHPMYADMIN')) {
exit;
}
$common_functions = PMA_CommonFunctions::getInstance();
// Get relations & co. status
$cfgRelation = PMA_getRelationsParam();
@@ -33,11 +34,20 @@ function PMA_exportIsActive($what, $val)
}
/* Scan for plugins */
$export_list = PMA_getPlugins('./libraries/export/', array('export_type' => $export_type, 'single_table' => isset($single_table)));
$export_list = PMA_getPlugins(
"export",
'libraries/plugins/export/',
array(
'export_type' => $export_type,
'single_table' => isset($single_table)
)
);
/* Fail if we didn't find any plugin */
if (empty($export_list)) {
PMA_Message::error(__('Could not load export plugins, please check your installation!'))->display();
PMA_Message::error(__(
'Could not load export plugins, please check your installation!'
))->display();
exit;
}
?>
@@ -79,7 +89,7 @@ if (isset($_GET['sql_query'])) {
<div class="exportoptions" id="header">
<h2>
<?php echo PMA_getImage('b_export.png', __('Export')); ?>
<?php echo $common_functions->getImage('b_export.png', __('Export')); ?>
<?php
if ($export_type == 'server') {
echo __('Exporting databases from the current server');
@@ -183,7 +193,7 @@ if (isset($_GET['sql_query'])) {
id="checkbox_quick_dump_onserver"
<?php PMA_exportCheckboxCheck('quick_export_onserver'); ?> />
<label for="checkbox_quick_dump_onserver">
<?php echo sprintf(__('Save on server in the directory <b>%s</b>'), htmlspecialchars(PMA_userDir($cfg['SaveDir']))); ?>
<?php echo sprintf(__('Save on server in the directory <b>%s</b>'), htmlspecialchars($common_functions->userDir($cfg['SaveDir']))); ?>
</label>
</li>
<li>
@@ -209,7 +219,7 @@ if (isset($_GET['sql_query'])) {
id="checkbox_dump_onserver"
<?php PMA_exportCheckboxCheck('onserver'); ?> />
<label for="checkbox_dump_onserver">
<?php echo sprintf(__('Save on server in the directory <b>%s</b>'), htmlspecialchars(PMA_userDir($cfg['SaveDir']))); ?>
<?php echo sprintf(__('Save on server in the directory <b>%s</b>'), htmlspecialchars($common_functions->userDir($cfg['SaveDir']))); ?>
</label>
</li>
<li>
@@ -243,7 +253,7 @@ if (isset($_GET['sql_query'])) {
$msg->addParam('<a href="Documentation.html#faq6_27" target="documentation">', false);
$msg->addParam('</a>', false);
echo PMA_showHint($msg);
echo $common_functions->showHint($msg);
?>
</label>
<input type="text" name="filename_template" id="filename_template"
@@ -360,7 +370,10 @@ if (isset($_GET['sql_query'])) {
<?php } ?>
<div class="exportoptions" id="submit">
<?php PMA_externalBug(__('SQL compatibility mode'), 'mysql', '50027', '14515'); ?>
<?php echo $common_functions->getExternalBug(
__('SQL compatibility mode'), 'mysql', '50027', '14515'
);
?>
<input type="submit" value="<?php echo __('Go'); ?>" id="buttonGo" />
</div>
</form>

View File

@@ -16,6 +16,9 @@ if (! defined('PHPMYADMIN')) {
*/
function PMA_printGitRevision()
{
$common_functions = PMA_CommonFunctions::getInstance();
if (! $GLOBALS['PMA_Config']->get('PMA_VERSION_GIT')) {
$response = PMA_Response::getInstance();
$response->isSuccess(false);
@@ -65,7 +68,7 @@ function PMA_printGitRevision()
. $branch . ',<br /> '
. sprintf(
__('committed on %1$s by %2$s'),
PMA_localisedDate(strtotime($committer['date'])),
$common_functions->localisedDate(strtotime($committer['date'])),
'<a href="' . PMA_linkURL('mailto:' . $committer['email']) . '">'
. htmlspecialchars($committer['name']) . '</a>'
)
@@ -73,7 +76,7 @@ function PMA_printGitRevision()
? ', <br />'
. sprintf(
__('authored on %1$s by %2$s'),
PMA_localisedDate(strtotime($author['date'])),
$common_functions->localisedDate(strtotime($author['date'])),
'<a href="' . PMA_linkURL('mailto:' . $author['email']) . '">'
. htmlspecialchars($author['name']) . '</a>'
)

View File

@@ -15,12 +15,19 @@ require_once './libraries/file_listing.php';
require_once './libraries/plugin_interface.lib.php';
require_once './libraries/display_import_ajax.lib.php';
$common_functions = PMA_CommonFunctions::getInstance();
/* Scan for plugins */
$import_list = PMA_getPlugins('./libraries/import/', $import_type);
$import_list = PMA_getPlugins(
"import",
'libraries/plugins/import/',
$import_type
);
/* Fail if we didn't find any plugin */
if (empty($import_list)) {
PMA_Message::error(__('Could not load import plugins, please check your installation!'))->display();
PMA_Message::error(__(
'Could not load import plugins, please check your installation!'
))->display();
exit;
}
?>
@@ -38,7 +45,7 @@ if (empty($import_list)) {
$('#upload_form_status').css("display", "inline"); // show progress bar
$('#upload_form_status_info').css("display", "inline"); // - || -
<?php
if ($_SESSION[$SESSION_KEY]["handler"]!="noplugin") {
if ($_SESSION[$SESSION_KEY]["handler"] != "UploadNoplugin") {
?>
var finished = false;
var percent = 0.0;
@@ -130,7 +137,7 @@ if ($_SESSION[$SESSION_KEY]["handler"]!="noplugin") {
<?php
// reload the left sidebar when the import is finished
$GLOBALS['reload'] = true;
echo PMA_getReloadNavigationScript(true);
echo $common_functions->getReloadNavigationScript(true);
?>
} // if finished
@@ -144,7 +151,7 @@ if ($_SESSION[$SESSION_KEY]["handler"]!="noplugin") {
<?php
} else { // no plugin available
?>
$('#upload_form_status_info').html('<img src="<?php echo $GLOBALS['pmaThemeImage'];?>ajax_clock_small.gif" width="16" height="16" alt="ajax clock" /> <?php echo PMA_jsFormat(__('Please be patient, the file is being uploaded. Details about the upload are not available.'), false) . PMA_showDocu('faq2_9'); ?>');
$('#upload_form_status_info').html('<img src="<?php echo $GLOBALS['pmaThemeImage'];?>ajax_clock_small.gif" width="16" height="16" alt="ajax clock" /> <?php echo PMA_jsFormat(__('Please be patient, the file is being uploaded. Details about the upload are not available.'), false) . $common_functions->showDocu('faq2_9'); ?>');
$('#upload_form_status').css("display", "none");
<?php
} // else
@@ -155,10 +162,12 @@ if ($_SESSION[$SESSION_KEY]["handler"]!="noplugin") {
</script>
<form action="import.php" method="post" enctype="multipart/form-data"
name="import"<?php
if ($_SESSION[$SESSION_KEY]["handler"]!="noplugin") {
if ($_SESSION[$SESSION_KEY]["handler"] != "UploadNoplugin") {
echo ' target="import_upload_iframe"';
} ?>>
<input type="hidden" name="<?php echo $ID_KEY; ?>" value="<?php echo $upload_id ; ?>" />
<input type="hidden" name="<?php
echo $_SESSION[$SESSION_KEY]["handler"]::getIdKey();
?>" value="<?php echo $upload_id ; ?>" />
<?php
if ($import_type == 'server') {
echo PMA_generate_common_hidden_inputs('', '', 1);
@@ -172,7 +181,7 @@ echo ' <input type="hidden" name="import_type" value="' . $import_type . '" /
<div class="exportoptions" id="header">
<h2>
<?php echo PMA_getImage('b_import.png', __('Import')); ?>
<?php echo $common_functions->getImage('b_import.png', __('Import')); ?>
<?php
if ($import_type == 'server') {
echo __('Importing into the current server');
@@ -214,21 +223,27 @@ if ($GLOBALS['is_upload'] && !empty($cfg['UploadDir'])) { ?>
<ul>
<li>
<input type="radio" name="file_location" id="radio_import_file" />
<?php PMA_browseUploadFile($max_upload_size); ?>
<?php echo $common_functions->getBrowseUploadFileBlock(
$max_upload_size
);
?>
</li>
<li>
<input type="radio" name="file_location" id="radio_local_import_file" />
<?php PMA_selectUploadFile($import_list, $cfg['UploadDir']); ?>
<?php echo $common_functions->getSelectUploadFileBlock(
$import_list, $cfg['UploadDir']
);
?>
</li>
</ul>
<?php
} elseif ($GLOBALS['is_upload']) {
$uid = uniqid('');
PMA_browseUploadFile($max_upload_size);
echo $common_functions->getBrowseUploadFileBlock($max_upload_size);
} elseif (!$GLOBALS['is_upload']) {
PMA_Message::notice(__('File uploads are not allowed on this server.'))->display();
} elseif (!empty($cfg['UploadDir'])) {
PMA_selectUploadFile($import_list, $cfg['UploadDir']);
echo $common_functions->getSelectUploadFileBlock($import_list, $cfg['UploadDir']);
} // end if (web-server upload directory)
?>
</div>

View File

@@ -5,10 +5,10 @@
*
* @package PhpMyAdmin
*/
if (!defined('PHPMYADMIN')) {
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* constant for differenciating array in $_SESSION variable
*/
@@ -32,7 +32,7 @@ $upload_id = uniqid("");
*/
$plugins = array(
"session",
"uploadprogress",
"progress",
"apc",
"noplugin"
);
@@ -42,8 +42,9 @@ foreach ($plugins as $plugin) {
$check = "PMA_import_" . $plugin . "Check";
if ($check()) {
$_SESSION[$SESSION_KEY]["handler"] = $plugin;
include_once "import/upload/" . $plugin . ".php";
$upload_class = "Upload" . ucwords($plugin);
$_SESSION[$SESSION_KEY]["handler"] = $upload_class;
include_once "plugins/import/upload/" . $upload_class . ".class.php";
break;
}
}
@@ -71,7 +72,7 @@ function PMA_import_apcCheck()
* @return boolean true if UploadProgress extension is available,
* false if it is not
*/
function PMA_import_uploadprogressCheck()
function PMA_import_progressCheck()
{
if (! function_exists("uploadprogress_get_info")
|| ! function_exists('getallheaders')
@@ -83,8 +84,6 @@ function PMA_import_uploadprogressCheck()
/**
* Checks if PHP 5.4 session upload-progress feature is available.
* Due to a bug in PHP 5.4's session upload feature (see /import_status.php),
* we need to check for cURL support.
*
* @return boolean true if PHP 5.4 session upload-progress is available,
* false if it is not
@@ -93,7 +92,6 @@ function PMA_import_sessionCheck()
{
if (PMA_PHP_INT_VERSION < 50400
|| ! ini_get('session.upload_progress.enabled')
|| ! function_exists('curl_exec')
) {
return false;
}
@@ -123,6 +121,8 @@ function PMA_import_nopluginCheck()
function PMA_importAjaxStatus($id)
{
header('Content-type: application/json');
echo json_encode(PMA_getUploadStatus($id));
echo json_encode(
$_SESSION[$GLOBALS['SESSION_KEY']]['handler']::getUploadStatus($id)
);
}
?>

View File

@@ -52,7 +52,7 @@ function PMA_select_language($use_fieldset = false, $show_doc = true)
$language_title = __('Language')
. (__('Language') != 'Language' ? ' - <em>Language</em>' : '');
if ($show_doc) {
$language_title .= PMA_showDocu('faq7_2');
$language_title .= PMA_CommonFunctions::getInstance()->showDocu('faq7_2');
}
if ($use_fieldset) {
echo '<fieldset><legend lang="en" dir="ltr">' . $language_title . '</legend>';

File diff suppressed because it is too large Load Diff

View File

@@ -150,6 +150,9 @@ class PMA_StorageEngine_innodb extends PMA_StorageEngine
*/
function getPageBufferpool()
{
$common_functions = PMA_CommonFunctions::getInstance();
// The following query is only possible because we know
// that we are on MySQL 5 here (checked above)!
// side note: I love MySQL 5 for this. :-)
@@ -160,61 +163,76 @@ class PMA_StorageEngine_innodb extends PMA_StorageEngine
$status = PMA_DBI_fetch_result($sql, 0, 1);
$output = '<table class="data" id="table_innodb_bufferpool_usage">' . "\n"
. ' <caption class="tblHeaders">' . "\n"
. ' ' . __('Buffer Pool Usage') . "\n"
. ' </caption>' . "\n"
. ' <tfoot>' . "\n"
. ' <tr>' . "\n"
. ' <th colspan="2">' . "\n"
. ' ' . __('Total') . "\n"
. ' : ' . PMA_formatNumber($status['Innodb_buffer_pool_pages_total'], 0)
. '&nbsp;' . __('pages')
. ' / '
. join(
'&nbsp;',
PMA_formatByteDown($status['Innodb_buffer_pool_pages_total'] * $status['Innodb_page_size'])
) . "\n"
. ' </th>' . "\n"
. ' </tr>' . "\n"
. ' </tfoot>' . "\n"
. ' <tbody>' . "\n"
. ' <tr class="odd">' . "\n"
. ' <th>' . __('Free pages') . '</th>' . "\n"
. ' <td class="value">'
. PMA_formatNumber($status['Innodb_buffer_pool_pages_free'], 0)
. '</td>' . "\n"
. ' </tr>' . "\n"
. ' <tr class="even">' . "\n"
. ' <th>' . __('Dirty pages') . '</th>' . "\n"
. ' <td class="value">'
. PMA_formatNumber($status['Innodb_buffer_pool_pages_dirty'], 0)
. '</td>' . "\n"
. ' </tr>' . "\n"
. ' <tr class="odd">' . "\n"
. ' <th>' . __('Pages containing data') . '</th>' . "\n"
. ' <td class="value">'
. PMA_formatNumber($status['Innodb_buffer_pool_pages_data'], 0) . "\n"
. '</td>' . "\n"
. ' </tr>' . "\n"
. ' <tr class="even">' . "\n"
. ' <th>' . __('Pages to be flushed') . '</th>' . "\n"
. ' <td class="value">'
. PMA_formatNumber($status['Innodb_buffer_pool_pages_flushed'], 0) . "\n"
. '</td>' . "\n"
. ' </tr>' . "\n"
. ' <tr class="odd">' . "\n"
. ' <th>' . __('Busy pages') . '</th>' . "\n"
. ' <td class="value">'
. PMA_formatNumber($status['Innodb_buffer_pool_pages_misc'], 0) . "\n"
. '</td>' . "\n"
. ' </tr>';
. ' <caption class="tblHeaders">' . "\n"
. ' ' . __('Buffer Pool Usage') . "\n"
. ' </caption>' . "\n"
. ' <tfoot>' . "\n"
. ' <tr>' . "\n"
. ' <th colspan="2">' . "\n"
. ' ' . __('Total') . "\n"
. ' : '
. $common_functions->formatNumber(
$status['Innodb_buffer_pool_pages_total'], 0
)
. '&nbsp;' . __('pages')
. ' / '
. join(
'&nbsp;',
$common_functions->formatByteDown($status['Innodb_buffer_pool_pages_total'] * $status['Innodb_page_size'])
) . "\n"
. ' </th>' . "\n"
. ' </tr>' . "\n"
. ' </tfoot>' . "\n"
. ' <tbody>' . "\n"
. ' <tr class="odd">' . "\n"
. ' <th>' . __('Free pages') . '</th>' . "\n"
. ' <td class="value">'
. $common_functions->formatNumber(
$status['Innodb_buffer_pool_pages_free'], 0
)
. '</td>' . "\n"
. ' </tr>' . "\n"
. ' <tr class="even">' . "\n"
. ' <th>' . __('Dirty pages') . '</th>' . "\n"
. ' <td class="value">'
. $common_functions->formatNumber(
$status['Innodb_buffer_pool_pages_dirty'], 0
)
. '</td>' . "\n"
. ' </tr>' . "\n"
. ' <tr class="odd">' . "\n"
. ' <th>' . __('Pages containing data') . '</th>' . "\n"
. ' <td class="value">'
. $common_functions->formatNumber(
$status['Innodb_buffer_pool_pages_data'], 0
) . "\n"
. '</td>' . "\n"
. ' </tr>' . "\n"
. ' <tr class="even">' . "\n"
. ' <th>' . __('Pages to be flushed') . '</th>' . "\n"
. ' <td class="value">'
. $common_functions->formatNumber(
$status['Innodb_buffer_pool_pages_flushed'], 0
) . "\n"
. '</td>' . "\n"
. ' </tr>' . "\n"
. ' <tr class="odd">' . "\n"
. ' <th>' . __('Busy pages') . '</th>' . "\n"
. ' <td class="value">'
. $common_functions->formatNumber(
$status['Innodb_buffer_pool_pages_misc'], 0
) . "\n"
. '</td>' . "\n"
. ' </tr>';
// not present at least since MySQL 5.1.40
if (isset($status['Innodb_buffer_pool_pages_latched'])) {
$output .= ' <tr class="even">'
. ' <th>' . __('Latched pages') . '</th>'
. ' <td class="value">'
. PMA_formatNumber($status['Innodb_buffer_pool_pages_latched'], 0)
. $common_functions->formatNumber(
$status['Innodb_buffer_pool_pages_latched'], 0
)
. '</td>'
. ' </tr>';
}
@@ -229,25 +247,33 @@ class PMA_StorageEngine_innodb extends PMA_StorageEngine
. ' <tr class="odd">' . "\n"
. ' <th>' . __('Read requests') . '</th>' . "\n"
. ' <td class="value">'
. PMA_formatNumber($status['Innodb_buffer_pool_read_requests'], 0) . "\n"
. $common_functions->formatNumber(
$status['Innodb_buffer_pool_read_requests'], 0
) . "\n"
. '</td>' . "\n"
. ' </tr>' . "\n"
. ' <tr class="even">' . "\n"
. ' <th>' . __('Write requests') . '</th>' . "\n"
. ' <td class="value">'
. PMA_formatNumber($status['Innodb_buffer_pool_write_requests'], 0) . "\n"
. $common_functions->formatNumber(
$status['Innodb_buffer_pool_write_requests'], 0
) . "\n"
. '</td>' . "\n"
. ' </tr>' . "\n"
. ' <tr class="odd">' . "\n"
. ' <th>' . __('Read misses') . '</th>' . "\n"
. ' <td class="value">'
. PMA_formatNumber($status['Innodb_buffer_pool_reads'], 0) . "\n"
. $common_functions->formatNumber(
$status['Innodb_buffer_pool_reads'], 0
) . "\n"
. '</td>' . "\n"
. ' </tr>' . "\n"
. ' <tr class="even">' . "\n"
. ' <th>' . __('Write waits') . '</th>' . "\n"
. ' <td class="value">'
. PMA_formatNumber($status['Innodb_buffer_pool_wait_free'], 0) . "\n"
. $common_functions->formatNumber(
$status['Innodb_buffer_pool_wait_free'], 0
) . "\n"
. '</td>' . "\n"
. ' </tr>' . "\n"
. ' <tr class="odd">' . "\n"
@@ -255,7 +281,7 @@ class PMA_StorageEngine_innodb extends PMA_StorageEngine
. ' <td class="value">'
. ($status['Innodb_buffer_pool_read_requests'] == 0
? '---'
: htmlspecialchars(PMA_formatNumber($status['Innodb_buffer_pool_reads'] * 100 / $status['Innodb_buffer_pool_read_requests'], 3, 2)) . ' %') . "\n"
: htmlspecialchars($common_functions->formatNumber($status['Innodb_buffer_pool_reads'] * 100 / $status['Innodb_buffer_pool_read_requests'], 3, 2)) . ' %') . "\n"
. '</td>' . "\n"
. ' </tr>' . "\n"
. ' <tr class="even">' . "\n"
@@ -263,7 +289,7 @@ class PMA_StorageEngine_innodb extends PMA_StorageEngine
. ' <td class="value">'
. ($status['Innodb_buffer_pool_write_requests'] == 0
? '---'
: htmlspecialchars(PMA_formatNumber($status['Innodb_buffer_pool_wait_free'] * 100 / $status['Innodb_buffer_pool_write_requests'], 3, 2)) . ' %') . "\n"
: htmlspecialchars($common_functions->formatNumber($status['Innodb_buffer_pool_wait_free'] * 100 / $status['Innodb_buffer_pool_write_requests'], 3, 2)) . ' %') . "\n"
. '</td>' . "\n"
. ' </tr>' . "\n"
. ' </tbody>' . "\n"

View File

@@ -97,12 +97,14 @@ class PMA_StorageEngine_pbxt extends PMA_StorageEngine
*/
function resolveTypeSize($formatted_size)
{
$common_functions = PMA_CommonFunctions::getInstance();
if (preg_match('/^[0-9]+[a-zA-Z]+$/', $formatted_size)) {
$value = PMA_extractValueFromFormattedSize($formatted_size);
$value = $common_functions
->extractValueFromFormattedSize($formatted_size);
} else {
$value = $formatted_size;
}
return PMA_formatByteDown($value);
return $common_functions->formatByteDown($value);
}
//--------------------

View File

@@ -14,6 +14,7 @@ if (! defined('TESTSUITE')) {
header('Content-Type: text/html; charset=utf-8');
}
include_once 'libraries/Response.class.php';
PMA_Response::getInstance()->disable();
?>

View File

@@ -1,456 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Set of functions used to build NHibernate dumps of tables
*
* @package PhpMyAdmin-Export
* @subpackage Codegen
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* This gets executed twice so avoid a notice
*/
if (! defined('CG_FORMAT_NHIBERNATE_CS')) {
define("CG_FORMAT_NHIBERNATE_CS", "NHibernate C# DO");
define("CG_FORMAT_NHIBERNATE_XML", "NHibernate XML");
define("CG_HANDLER_NHIBERNATE_CS_BODY", "handleNHibernateCSBody");
define("CG_HANDLER_NHIBERNATE_XML_BODY", "handleNHibernateXMLBody");
}
$CG_FORMATS = array(
CG_FORMAT_NHIBERNATE_CS,
CG_FORMAT_NHIBERNATE_XML
);
$CG_HANDLERS = array(
CG_HANDLER_NHIBERNATE_CS_BODY,
CG_HANDLER_NHIBERNATE_XML_BODY
);
/**
*
*/
if (isset($plugin_list)) {
$plugin_list['codegen'] = array(
'text' => 'CodeGen',
'extension' => 'cs',
'mime_type' => 'text/cs',
'options' => array(),
'options_text' => __('Options')
);
$plugin_list['codegen']['options'] = array(
array(
'type' => 'begin_group',
'name' => 'general_opts'
),
array(
'type' => 'hidden',
'name' => 'structure_or_data'
),
array('type' => 'select',
'name' => 'format',
'text' => __('Format:'),
'values' => $CG_FORMATS
),
array(
'type' => 'end_group'
)
);
} else {
/**
* Set of functions used to build exports of tables
*/
/**
* Outputs export footer
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportFooter()
{
return true;
}
/**
* Outputs export header
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportHeader()
{
return true;
}
/**
* Outputs database header
*
* @param string $db Database name
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportDBHeader($db)
{
return true;
}
/**
* Outputs database footer
*
* @param string $db Database name
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportDBFooter($db)
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportDBCreate($db)
{
return true;
}
/**
* Outputs the content of a table in NHibernate format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $error_url the url to go back in case of error
* @param string $sql_query SQL query for obtaining data
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
{
global $CG_FORMATS, $CG_HANDLERS, $what;
$format = $GLOBALS[$what . '_format'];
if (isset($CG_FORMATS[$format])) {
return PMA_exportOutputHandler(
$CG_HANDLERS[$format]($db, $table, $crlf)
);
}
return PMA_exportOutputHandler(sprintf("%s is not supported.", $format));
}
/**
* TableProperty class
*
* @package PhpMyAdmin-Export
* @subpackage Codegen
*/
class TableProperty
{
public $name;
public $type;
public $nullable;
public $key;
public $defaultValue;
public $ext;
function __construct($row)
{
$this->name = trim($row[0]);
$this->type = trim($row[1]);
$this->nullable = trim($row[2]);
$this->key = trim($row[3]);
$this->defaultValue = trim($row[4]);
$this->ext = trim($row[5]);
}
function getPureType()
{
$pos=strpos($this->type, "(");
if ($pos > 0) {
return substr($this->type, 0, $pos);
}
return $this->type;
}
function isNotNull()
{
return $this->nullable == "NO" ? "true" : "false";
}
function isUnique()
{
return $this->key == "PRI" || $this->key == "UNI" ? "true" : "false";
}
function getDotNetPrimitiveType()
{
if (strpos($this->type, "int") === 0) {
return "int";
}
if (strpos($this->type, "long") === 0) {
return "long";
}
if (strpos($this->type, "char") === 0) {
return "string";
}
if (strpos($this->type, "varchar") === 0) {
return "string";
}
if (strpos($this->type, "text") === 0) {
return "string";
}
if (strpos($this->type, "longtext") === 0) {
return "string";
}
if (strpos($this->type, "tinyint") === 0) {
return "bool";
}
if (strpos($this->type, "datetime") === 0) {
return "DateTime";
}
return "unknown";
}
function getDotNetObjectType()
{
if (strpos($this->type, "int") === 0) {
return "Int32";
}
if (strpos($this->type, "long") === 0) {
return "Long";
}
if (strpos($this->type, "char") === 0) {
return "String";
}
if (strpos($this->type, "varchar") === 0) {
return "String";
}
if (strpos($this->type, "text") === 0) {
return "String";
}
if (strpos($this->type, "longtext") === 0) {
return "String";
}
if (strpos($this->type, "tinyint") === 0) {
return "Boolean";
}
if (strpos($this->type, "datetime") === 0) {
return "DateTime";
}
return "Unknown";
}
function getIndexName()
{
if (strlen($this->key) > 0) {
return "index=\""
. htmlspecialchars($this->name, ENT_COMPAT, 'UTF-8')
. "\"";
}
return "";
}
function isPK()
{
return $this->key=="PRI";
}
function formatCs($text)
{
$text = str_replace(
"#name#",
cgMakeIdentifier($this->name, false),
$text
);
return $this->format($text);
}
function formatXml($text)
{
$text = str_replace(
"#name#",
htmlspecialchars($this->name, ENT_COMPAT, 'UTF-8'),
$text
);
$text = str_replace(
"#indexName#",
$this->getIndexName(),
$text
);
return $this->format($text);
}
function format($text)
{
$text = str_replace(
"#ucfirstName#",
cgMakeIdentifier($this->name),
$text
);
$text = str_replace(
"#dotNetPrimitiveType#",
$this->getDotNetPrimitiveType(),
$text
);
$text = str_replace(
"#dotNetObjectType#",
$this->getDotNetObjectType(),
$text
);
$text = str_replace(
"#type#",
$this->getPureType(),
$text
);
$text = str_replace(
"#notNull#",
$this->isNotNull(),
$text
);
$text = str_replace(
"#unique#",
$this->isUnique(),
$text
);
return $text;
}
}
function cgMakeIdentifier($str, $ucfirst = true)
{
// remove unsafe characters
$str = preg_replace('/[^\p{L}\p{Nl}_]/u', '', $str);
// make sure first character is a letter or _
if (! preg_match('/^\pL/u', $str)) {
$str = '_' . $str;
}
if ($ucfirst) {
$str = ucfirst($str);
}
return $str;
}
function handleNHibernateCSBody($db, $table, $crlf)
{
$lines = array();
$result = PMA_DBI_query(
sprintf('DESC %s.%s', PMA_backquote($db), PMA_backquote($table))
);
if ($result) {
$tableProperties = array();
while ($row = PMA_DBI_fetch_row($result)) {
$tableProperties[] = new TableProperty($row);
}
PMA_DBI_free_result($result);
$lines[] = 'using System;';
$lines[] = 'using System.Collections;';
$lines[] = 'using System.Collections.Generic;';
$lines[] = 'using System.Text;';
$lines[] = 'namespace ' . cgMakeIdentifier($db);
$lines[] = '{';
$lines[] = ' #region ' . cgMakeIdentifier($table);
$lines[] = ' public class ' . cgMakeIdentifier($table);
$lines[] = ' {';
$lines[] = ' #region Member Variables';
foreach ($tableProperties as $tableProperty) {
$lines[] = $tableProperty->formatCs(
' protected #dotNetPrimitiveType# _#name#;'
);
}
$lines[] = ' #endregion';
$lines[] = ' #region Constructors';
$lines[] = ' public ' . cgMakeIdentifier($table).'() { }';
$temp = array();
foreach ($tableProperties as $tableProperty) {
if (! $tableProperty->isPK()) {
$temp[] = $tableProperty->formatCs(
'#dotNetPrimitiveType# #name#'
);
}
}
$lines[] = ' public '
. cgMakeIdentifier($table)
. '('
. implode(', ', $temp)
. ')';
$lines[] = ' {';
foreach ($tableProperties as $tableProperty) {
if (! $tableProperty->isPK()) {
$lines[] = $tableProperty->formatCs(
' this._#name#=#name#;'
);
}
}
$lines[] = ' }';
$lines[] = ' #endregion';
$lines[] = ' #region Public Properties';
foreach ($tableProperties as $tableProperty) {
$lines[] = $tableProperty->formatCs(
' public virtual #dotNetPrimitiveType# #ucfirstName#'
. "\n"
. ' {' . "\n"
. ' get {return _#name#;}' . "\n"
. ' set {_#name#=value;}' . "\n"
. ' }'
);
}
$lines[] = ' #endregion';
$lines[] = ' }';
$lines[] = ' #endregion';
$lines[] = '}';
}
return implode("\n", $lines);
}
function handleNHibernateXMLBody($db, $table, $crlf)
{
$lines = array();
$lines[] = '<?xml version="1.0" encoding="utf-8" ?' . '>';
$lines[] = '<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" '
. 'namespace="' . cgMakeIdentifier($db) . '" '
. 'assembly="' . cgMakeIdentifier($db) . '">';
$lines[] = ' <class '
. 'name="' . cgMakeIdentifier($table) . '" '
. 'table="' . cgMakeIdentifier($table) . '">';
$result = PMA_DBI_query(
sprintf("DESC %s.%s", PMA_backquote($db), PMA_backquote($table))
);
if ($result) {
while ($row = PMA_DBI_fetch_row($result)) {
$tableProperty = new TableProperty($row);
if ($tableProperty->isPK()) {
$lines[] = $tableProperty->formatXml(
' <id name="#ucfirstName#" type="#dotNetObjectType#"'
. ' unsaved-value="0">' . "\n"
. ' <column name="#name#" sql-type="#type#"'
. ' not-null="#notNull#" unique="#unique#"'
. ' index="PRIMARY"/>' . "\n"
. ' <generator class="native" />' . "\n"
. ' </id>'
);
} else {
$lines[] = $tableProperty->formatXml(
' <property name="#ucfirstName#"'
. ' type="#dotNetObjectType#">' . "\n"
. ' <column name="#name#" sql-type="#type#"'
. ' not-null="#notNull#" #indexName#/>' . "\n"
. ' </property>'
);
}
}
PMA_DBI_free_result($result);
}
$lines[] = ' </class>';
$lines[] = '</hibernate-mapping>';
return implode("\n", $lines);
}
}
?>

View File

@@ -1,67 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Set of functions used to build CSV dumps of tables for excel
*
* @package PhpMyAdmin-Export
* @subpackage CSV-Excel
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
*
*/
if (isset($plugin_list)) {
$plugin_list['excel'] = array(
'text' => __('CSV for MS Excel'),
'extension' => 'csv',
'mime_type' => 'text/comma-separated-values',
'options' => array(),
'options_text' => __('Options')
);
$plugin_list['excel']['options'] = array(
array(
'type' => 'begin_group',
'name' => 'general_opts'
),
array(
'type' => 'text',
'name' => 'null',
'text' => __('Replace NULL with:')
),
array(
'type' => 'bool',
'name' => 'removeCRLF',
'text' => __(
'Remove carriage return/line feed characters within columns'
)
),
array(
'type' => 'bool',
'name' => 'columns',
'text' => __('Put columns names in the first row')
),
array(
'type' => 'select',
'name' => 'edition',
'values' => array(
'win' => 'Windows',
'mac_excel2003' => 'Excel 2003 / Macintosh',
'mac_excel2008' => 'Excel 2008 / Macintosh'),
'text' => __('Excel edition:')),
array(
'type' => 'hidden',
'name' => 'structure_or_data'
),
array(
'type' => 'end_group'
)
);
} else {
/* Everything rest is coded in csv plugin */
include './libraries/export/csv.php';
}
?>

View File

@@ -1,334 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Set of functions used to build MediaWiki dumps of tables
*
* @package PhpMyAdmin-Export
* @subpackage MediaWiki
*/
if (! defined('PHPMYADMIN')) {
exit;
}
if (isset($plugin_list)) {
$plugin_list['mediawiki'] = array(
'text' => __('MediaWiki Table'),
'extension' => 'mediawiki',
'mime_type' => 'text/plain',
'options' => array(),
'options_text' => __('Options')
);
// general options
$plugin_list['mediawiki']['options'][] = array(
'type' => 'begin_group',
'name' => 'general_opts'
);
// what to dump (structure/data/both)
$plugin_list['mediawiki']['options'][] = array(
'type' => 'begin_subgroup',
'subgroup_header' => array(
'type' => 'message_only',
'text' => __('Dump table')
)
);
$plugin_list['mediawiki']['options'][] = array(
'type' => 'radio',
'name' => 'structure_or_data',
'values' => array(
'structure' => __('structure'),
'data' => __('data'),
'structure_and_data' => __('structure and data')
)
);
$plugin_list['mediawiki']['options'][] = array(
'type' => 'end_subgroup'
);
// export table name
$plugin_list['mediawiki']['options'][] = array(
'type' => 'bool',
'name' => 'caption',
'text' => __('Export table names')
);
// export table headers
$plugin_list['mediawiki']['options'][] = array(
'type' => 'bool',
'name' => 'headers',
'text' => __('Export table headers')
);
// end general options
$plugin_list['mediawiki']['options'][] = array(
'type' => 'end_group'
);
} else {
/**
* Outputs comments containing info about the exported tables
*
* @param string $text Text of comment
*
* @return string The formatted comment
*
* @access private
*/
function PMA_exportComment($text = '')
{
// see http://www.mediawiki.org/wiki/Help:Formatting
$comment = PMA_exportCRLF();
$comment .= '<!--' . PMA_exportCRLF();
$comment .= $text . PMA_exportCRLF();
$comment .= '-->' . str_repeat(PMA_exportCRLF(), 2);
return $comment;
}
/**
* Outputs CRLF
*
* @return string CRLF
*
* @access private
*/
function PMA_exportCRLF()
{
// The CRLF expected by the mediawiki format is "\n"
return "\n";
}
/**
* Outputs export footer
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportFooter()
{
return true;
}
/**
* Outputs export header
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportHeader()
{
return true;
}
/**
* Outputs database header
*
* @param string $db Database name
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportDBHeader($db)
{
return true;
}
/**
* Outputs database footer
*
* @param string $db Database name
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportDBFooter($db)
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportDBCreate($db)
{
return true;
}
/**
* Outputs table's structure
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $error_url the url to go back in case of error
* @param string $export_mode 'create_table','triggers','create_view',
* 'stand_in'
* @param string $export_type 'server', 'database', 'table'
* @param bool $do_relation whether to include relation comments
* @param bool $do_comments whether to include the pmadb-style column comments
* as comments in the structure; this is deprecated
* but the parameter is left here because export.php
* calls PMA_exportStructure() also for other export
* types which use this parameter
* @param bool $do_mime whether to include mime comments
* @param bool $dates whether to include creation/update/check dates
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportStructure(
$db,
$table,
$crlf,
$error_url,
$export_mode,
$export_type,
$do_relation = false,
$do_comments = false,
$do_mime = false,
$dates = false
) {
switch($export_mode) {
case 'create_table':
$columns = PMA_DBI_get_columns($db, $table);
$columns = array_values($columns);
$row_cnt = count($columns);
// Print structure comment
$output = PMA_exportComment(
"Table structure for "
. PMA_backquote($table)
);
// Begin the table construction
$output .= "{| class=\"wikitable\" style=\"text-align:center;\""
. PMA_exportCRLF();
// Add the table name
if ($GLOBALS['mediawiki_caption']) {
$output .= "|+'''" . $table . "'''" . PMA_exportCRLF();
}
// Add the table headers
if ($GLOBALS['mediawiki_headers']) {
$output .= "|- style=\"background:#ffdead;\"" . PMA_exportCRLF();
$output .= "! style=\"background:#ffffff\" | " . PMA_exportCRLF();
for ($i = 0; $i < $row_cnt; ++$i) {
$output .= " | " . $columns[$i]['Field']. PMA_exportCRLF();
}
}
// Add the table structure
$output .= "|-" . PMA_exportCRLF();
$output .= "! Type" . PMA_exportCRLF();
for ($i = 0; $i < $row_cnt; ++$i) {
$output .= " | " . $columns[$i]['Type'] . PMA_exportCRLF();
}
$output .= "|-" . PMA_exportCRLF();
$output .= "! Null" . PMA_exportCRLF();
for ($i = 0; $i < $row_cnt; ++$i) {
$output .= " | " . $columns[$i]['Null'] . PMA_exportCRLF();
}
$output .= "|-" . PMA_exportCRLF();
$output .= "! Default" . PMA_exportCRLF();
for ($i = 0; $i < $row_cnt; ++$i) {
$output .= " | " . $columns[$i]['Default'] . PMA_exportCRLF();
}
$output .= "|-" . PMA_exportCRLF();
$output .= "! Extra" . PMA_exportCRLF();
for ($i = 0; $i < $row_cnt; ++$i) {
$output .= " | " . $columns[$i]['Extra'] . PMA_exportCRLF();
}
$output .= "|}" . str_repeat(PMA_exportCRLF(), 2);
break;
} // end switch
return PMA_exportOutputHandler($output);
}
/**
* Outputs the content of a table in MediaWiki format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $error_url the url to go back in case of error
* @param string $sql_query SQL query for obtaining data
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportData(
$db,
$table,
$crlf,
$error_url,
$sql_query
) {
// Print data comment
$output = PMA_exportComment("Table data for ". PMA_backquote($table));
// Begin the table construction
// Use the "wikitable" class for style
// Use the "sortable" class for allowing tables to be sorted by column
$output .= "{| class=\"wikitable sortable\" style=\"text-align:center;\""
. PMA_exportCRLF();
// Add the table name
if ($GLOBALS['mediawiki_caption']) {
$output .= "|+'''" . $table . "'''" . PMA_exportCRLF();
}
// Add the table headers
if ($GLOBALS['mediawiki_headers']) {
// Get column names
$column_names = PMA_DBI_get_column_names($db, $table);
// Add column names as table headers
if ( ! is_null($column_names) ) {
// Use '|-' for separating rows
$output .= "|-" . PMA_exportCRLF();
// Use '!' for separating table headers
foreach ($column_names as $column) {
$output .= " ! " . $column . "" . PMA_exportCRLF();
}
}
}
// Get the table data from the database
$result = PMA_DBI_query($sql_query, null, PMA_DBI_QUERY_UNBUFFERED);
$fields_cnt = PMA_DBI_num_fields($result);
while ($row = PMA_DBI_fetch_row($result)) {
$output .= "|-" . PMA_exportCRLF();
// Use '|' for separating table columns
for ($i = 0; $i < $fields_cnt; ++ $i) {
$output .= " | " . $row[$i] . "" . PMA_exportCRLF();
}
}
// End table construction
$output .= "|}" . str_repeat(PMA_exportCRLF(), 2);
return PMA_exportOutputHandler($output);
}
}
?>

View File

@@ -1,520 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Produce a PDF report (export) from a query
*
* @package PhpMyAdmin-Export
* @subpackage PDF
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
*
*/
if (isset($plugin_list)) {
$plugin_list['pdf'] = array(
'text' => __('PDF'),
'extension' => 'pdf',
'mime_type' => 'application/pdf',
'force_file' => true,
'options' => array(),
'options_text' => __('Options')
);
$plugin_list['pdf']['options'] = array(
array(
'type' => 'begin_group',
'name' => 'general_opts'
),
array(
'type' => 'message_only',
'name' => 'explanation',
'text' => __(
'(Generates a report containing the data of a single table)'
)
),
array(
'type' => 'text',
'name' => 'report_title',
'text' => __('Report title:')
),
array(
'type' => 'hidden',
'name' => 'structure_or_data'
),
array(
'type' => 'end_group'
)
);
} else {
include_once './libraries/PDF.class.php';
/**
* Adapted from a LGPL script by Philip Clarke
*
* @package PhpMyAdmin-Export
* @subpackage PDF
*/
class PMA_Export_PDF extends PMA_PDF
{
var $tablewidths;
var $headerset;
function checkPageBreak($h = 0, $y = '', $addpage = true)
{
if ($this->empty_string($y)) {
$y = $this->y;
}
$current_page = $this->page;
if ((($y + $h) > $this->PageBreakTrigger)
AND (! $this->InFooter)
AND ($this->AcceptPageBreak())
) {
if ($addpage) {
//Automatic page break
$x = $this->x;
$this->AddPage($this->CurOrientation);
$this->y = $this->dataY;
$oldpage = $this->page - 1;
$this_page_orm = $this->pagedim[$this->page]['orm'];
$old_page_orm = $this->pagedim[$oldpage]['orm'];
$this_page_olm = $this->pagedim[$this->page]['olm'];
$old_page_olm = $this->pagedim[$oldpage]['olm'];
if ($this->rtl) {
if ($this_page_orm!= $old_page_orm) {
$this->x = $x - ($this_page_orm - $old_page_orm);
} else {
$this->x = $x;
}
} else {
if ($this_page_olm != $old_page_olm) {
$this->x = $x + ($this_page_olm - $old_page_olm);
} else {
$this->x = $x;
}
}
}
return true;
}
if ($current_page != $this->page) {
// account for columns mode
return true;
}
return false;
}
function Header()
{
global $maxY;
// Check if header for this page already exists
if (! isset($this->headerset[$this->page])) {
$fullwidth = 0;
foreach ($this->tablewidths as $width) {
$fullwidth += $width;
}
$this->SetY(($this->tMargin) - ($this->FontSizePt / $this->k) * 5);
$this->cellFontSize = $this->FontSizePt ;
$this->SetFont(
PMA_PDF_FONT,
'',
($this->titleFontSize
? $this->titleFontSize
: $this->FontSizePt)
);
$this->Cell(0, $this->FontSizePt, $this->titleText, 0, 1, 'C');
$this->SetFont(PMA_PDF_FONT, '', $this->cellFontSize);
$this->SetY(($this->tMargin) - ($this->FontSizePt / $this->k) * 2.5);
$this->Cell(
0,
$this->FontSizePt,
__('Database') . ': ' . $this->currentDb . ', '
. __('Table') . ': ' . $this->currentTable,
0, 1, 'L'
);
$l = ($this->lMargin);
foreach ($this->colTitles as $col => $txt) {
$this->SetXY($l, ($this->tMargin));
$this->MultiCell(
$this->tablewidths[$col],
$this->FontSizePt,
$txt
);
$l += $this->tablewidths[$col] ;
$maxY = ($maxY < $this->getY()) ? $this->getY() : $maxY ;
}
$this->SetXY($this->lMargin, $this->tMargin);
$this->setFillColor(200, 200, 200);
$l = ($this->lMargin);
foreach ($this->colTitles as $col => $txt) {
$this->SetXY($l, $this->tMargin);
$this->cell(
$this->tablewidths[$col],
$maxY-($this->tMargin),
'',
1,
0,
'L',
1
);
$this->SetXY($l, $this->tMargin);
$this->MultiCell(
$this->tablewidths[$col],
$this->FontSizePt,
$txt,
0,
'C'
);
$l += $this->tablewidths[$col];
}
$this->setFillColor(255, 255, 255);
// set headerset
$this->headerset[$this->page] = 1;
}
$this->dataY = $maxY;
}
function morepagestable($lineheight=8)
{
// some things to set and 'remember'
$l = $this->lMargin;
$startheight = $h = $this->dataY;
$startpage = $currpage = $this->page;
// calculate the whole width
$fullwidth = 0;
foreach ($this->tablewidths as $width) {
$fullwidth += $width;
}
// Now let's start to write the table
$row = 0;
$tmpheight = array();
$maxpage = $this->page;
while ($data = PMA_DBI_fetch_row($this->results)) {
$this->page = $currpage;
// write the horizontal borders
$this->Line($l, $h, $fullwidth+$l, $h);
// write the content and remember the height of the highest col
foreach ($data as $col => $txt) {
$this->page = $currpage;
$this->SetXY($l, $h);
if ($this->tablewidths[$col] > 0) {
$this->MultiCell(
$this->tablewidths[$col],
$lineheight,
$txt,
0,
$this->colAlign[$col]
);
$l += $this->tablewidths[$col];
}
if (! isset($tmpheight[$row.'-'.$this->page])) {
$tmpheight[$row.'-'.$this->page] = 0;
}
if ($tmpheight[$row.'-'.$this->page] < $this->GetY()) {
$tmpheight[$row.'-'.$this->page] = $this->GetY();
}
if ($this->page > $maxpage) {
$maxpage = $this->page;
}
unset($data[$col]);
}
// get the height we were in the last used page
$h = $tmpheight[$row.'-'.$maxpage];
// set the "pointer" to the left margin
$l = $this->lMargin;
// set the $currpage to the last page
$currpage = $maxpage;
unset($data[$row]);
$row++;
}
// draw the borders
// we start adding a horizontal line on the last page
$this->page = $maxpage;
$this->Line($l, $h, $fullwidth+$l, $h);
// now we start at the top of the document and walk down
for ($i = $startpage; $i <= $maxpage; $i++) {
$this->page = $i;
$l = $this->lMargin;
$t = ($i == $startpage) ? $startheight : $this->tMargin;
$lh = ($i == $maxpage) ? $h : $this->h-$this->bMargin;
$this->Line($l, $t, $l, $lh);
foreach ($this->tablewidths as $width) {
$l += $width;
$this->Line($l, $t, $l, $lh);
}
}
// set it to the last page, if not it'll cause some problems
$this->page = $maxpage;
}
function setAttributes($attr = array())
{
foreach ($attr as $key => $val) {
$this->$key = $val ;
}
}
function setTopMargin($topMargin)
{
$this->tMargin = $topMargin;
}
function mysqlReport($query)
{
unset($this->tablewidths);
unset($this->colTitles);
unset($this->titleWidth);
unset($this->colFits);
unset($this->display_column);
unset($this->colAlign);
/**
* Pass 1 for column widths
*/
$this->results = PMA_DBI_query($query, null, PMA_DBI_QUERY_UNBUFFERED);
$this->numFields = PMA_DBI_num_fields($this->results);
$this->fields = PMA_DBI_get_fields_meta($this->results);
// sColWidth = starting col width (an average size width)
$availableWidth = $this->w - $this->lMargin - $this->rMargin;
$this->sColWidth = $availableWidth / $this->numFields;
$totalTitleWidth = 0;
// loop through results header and set initial
// col widths/ titles/ alignment
// if a col title is less than the starting col width,
// reduce that column size
$colFits = array();
for ($i = 0; $i < $this->numFields; $i++) {
$stringWidth = $this->getstringwidth($this->fields[$i]->name) + 6 ;
// save the real title's width
$titleWidth[$i] = $stringWidth;
$totalTitleWidth += $stringWidth;
// set any column titles less than the start width to
// the column title width
if ($stringWidth < $this->sColWidth) {
$colFits[$i] = $stringWidth ;
}
$this->colTitles[$i] = $this->fields[$i]->name;
$this->display_column[$i] = true;
switch ($this->fields[$i]->type) {
case 'int':
$this->colAlign[$i] = 'R';
break;
case 'blob':
case 'tinyblob':
case 'mediumblob':
case 'longblob':
/**
* @todo do not deactivate completely the display
* but show the field's name and [BLOB]
*/
if (stristr($this->fields[$i]->flags, 'BINARY')) {
$this->display_column[$i] = false;
unset($this->colTitles[$i]);
}
$this->colAlign[$i] = 'L';
break;
default:
$this->colAlign[$i] = 'L';
}
}
// title width verification
if ($totalTitleWidth > $availableWidth) {
$adjustingMode = true;
} else {
$adjustingMode = false;
// we have enough space for all the titles at their
// original width so use the true title's width
foreach ($titleWidth as $key => $val) {
$colFits[$key] = $val;
}
}
// loop through the data; any column whose contents
// is greater than the column size is resized
/**
* @todo force here a LIMIT to avoid reading all rows
*/
while ($row = PMA_DBI_fetch_row($this->results)) {
foreach ($colFits as $key => $val) {
$stringWidth = $this->getstringwidth($row[$key]) + 6 ;
if ($adjustingMode && ($stringWidth > $this->sColWidth)) {
// any column whose data's width is bigger than
// the start width is now discarded
unset($colFits[$key]);
} else {
// if data's width is bigger than the current column width,
// enlarge the column (but avoid enlarging it if the
// data's width is very big)
if ($stringWidth > $val
&& $stringWidth < ($this->sColWidth * 3)
) {
$colFits[$key] = $stringWidth ;
}
}
}
}
$totAlreadyFitted = 0;
foreach ($colFits as $key => $val) {
// set fitted columns to smallest size
$this->tablewidths[$key] = $val;
// to work out how much (if any) space has been freed up
$totAlreadyFitted += $val;
}
if ($adjustingMode) {
$surplus = (sizeof($colFits) * $this->sColWidth) - $totAlreadyFitted;
$surplusToAdd = $surplus / ($this->numFields - sizeof($colFits));
} else {
$surplusToAdd = 0;
}
for ($i = 0; $i < $this->numFields; $i++) {
if (! in_array($i, array_keys($colFits))) {
$this->tablewidths[$i] = $this->sColWidth + $surplusToAdd;
}
if ($this->display_column[$i] == false) {
$this->tablewidths[$i] = 0;
}
}
ksort($this->tablewidths);
PMA_DBI_free_result($this->results);
// Pass 2
$this->results = PMA_DBI_query($query, null, PMA_DBI_QUERY_UNBUFFERED);
$this->setY($this->tMargin);
$this->AddPage();
$this->SetFont(PMA_PDF_FONT, '', 9);
$this->morepagestable($this->FontSizePt);
PMA_DBI_free_result($this->results);
} // end of mysqlReport function
} // end of PMA_Export_PDF class
$pdf = new PMA_Export_PDF('L', 'pt', 'A3');
/**
* Finalize the pdf.
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportFooter()
{
global $pdf;
// instead of $pdf->Output():
if (! PMA_exportOutputHandler($pdf->getPDFData())) {
return false;
}
return true;
}
/**
* Initialize the pdf to export data.
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportHeader()
{
global $pdf_report_title;
global $pdf;
$pdf->Open();
$attr = array('titleFontSize' => 18, 'titleText' => $pdf_report_title);
$pdf->setAttributes($attr);
$pdf->setTopMargin(30);
return true;
}
/**
* Outputs database header
*
* @param string $db Database name
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportDBHeader($db)
{
return true;
}
/**
* Outputs database footer
*
* @param string $db Database name
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportDBFooter($db)
{
return true;
}
/**
* Outputs CREATE DATABASE statement
*
* @param string $db Database name
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportDBCreate($db)
{
return true;
}
/**
* Outputs the content of a table in PDF format
*
* @param string $db database name
* @param string $table table name
* @param string $crlf the end of line sequence
* @param string $error_url the url to go back in case of error
* @param string $sql_query SQL query for obtaining data
*
* @return bool Whether it succeeded
*
* @access public
*/
function PMA_exportData($db, $table, $crlf, $error_url, $sql_query)
{
global $pdf;
$attr = array('currentDb' => $db, 'currentTable' => $table);
$pdf->setAttributes($attr);
$pdf->mysqlReport($sql_query);
return true;
} // end of the 'PMA_exportData()' function
}
?>

View File

@@ -59,7 +59,7 @@ class PMA_GIS_Geometrycollection extends PMA_GIS_Geometry
// Trim to remove leading 'GEOMETRYCOLLECTION(' and trailing ')'
$goem_col = substr($spatial, 19, (strlen($spatial) - 20));
// Split the geometry collection object to get its constituents.
$sub_parts = $this->_explodeGeomCol($goem_col);
@@ -323,7 +323,6 @@ class PMA_GIS_Geometrycollection extends PMA_GIS_Geometry
foreach ($sub_parts as $sub_part) {
$type_pos = stripos($sub_part, '(');
$type = substr($sub_part, 0, $type_pos);
$gis_obj = PMA_GIS_Factory::factory($type);
if (! $gis_obj) {
continue;

View File

@@ -270,26 +270,28 @@ class PMA_GIS_Multilinestring extends PMA_GIS_Geometry
*/
public function generateWkt($gis_data, $index, $empty = '')
{
$no_of_lines = isset($gis_data[$index]['MULTILINESTRING']['no_of_lines'])
? $gis_data[$index]['MULTILINESTRING']['no_of_lines'] : 1;
$data_row = $gis_data[$index]['MULTILINESTRING'];
$no_of_lines = isset($data_row['no_of_lines'])
? $data_row['no_of_lines'] : 1;
if ($no_of_lines < 1) {
$no_of_lines = 1;
}
$wkt = 'MULTILINESTRING(';
for ($i = 0; $i < $no_of_lines; $i++) {
$no_of_points = isset($gis_data[$index]['MULTILINESTRING'][$i]['no_of_points'])
? $gis_data[$index]['MULTILINESTRING'][$i]['no_of_points'] : 2;
$no_of_points = isset($data_row[$i]['no_of_points'])
? $data_row[$i]['no_of_points'] : 2;
if ($no_of_points < 2) {
$no_of_points = 2;
}
$wkt .= '(';
for ($j = 0; $j < $no_of_points; $j++) {
$wkt .= ((isset($gis_data[$index]['MULTILINESTRING'][$i][$j]['x'])
&& trim($gis_data[$index]['MULTILINESTRING'][$i][$j]['x']) != '')
? $gis_data[$index]['MULTILINESTRING'][$i][$j]['x'] : $empty)
. ' ' . ((isset($gis_data[$index]['MULTILINESTRING'][$i][$j]['y'])
&& trim($gis_data[$index]['MULTILINESTRING'][$i][$j]['y']) != '')
? $gis_data[$index]['MULTILINESTRING'][$i][$j]['y'] : $empty) . ',';
$wkt .= ((isset($data_row[$i][$j]['x'])
&& trim($data_row[$i][$j]['x']) != '')
? $data_row[$i][$j]['x'] : $empty)
. ' ' . ((isset($data_row[$i][$j]['y'])
&& trim($data_row[$i][$j]['y']) != '')
? $data_row[$i][$j]['y'] : $empty) . ',';
}
$wkt = substr($wkt, 0, strlen($wkt) - 1);
$wkt .= '),';

View File

@@ -338,33 +338,36 @@ class PMA_GIS_Multipolygon extends PMA_GIS_Geometry
*/
public function generateWkt($gis_data, $index, $empty = '')
{
$no_of_polygons = isset($gis_data[$index]['MULTIPOLYGON']['no_of_polygons'])
? $gis_data[$index]['MULTIPOLYGON']['no_of_polygons'] : 1;
$data_row = $gis_data[$index]['MULTIPOLYGON'];
$no_of_polygons = isset($data_row['no_of_polygons'])
? $data_row['no_of_polygons'] : 1;
if ($no_of_polygons < 1) {
$no_of_polygons = 1;
}
$wkt = 'MULTIPOLYGON(';
for ($k = 0; $k < $no_of_polygons; $k++) {
$no_of_lines = isset($gis_data[$index]['MULTIPOLYGON'][$k]['no_of_lines'])
? $gis_data[$index]['MULTIPOLYGON'][$k]['no_of_lines'] : 1;
$no_of_lines = isset($data_row[$k]['no_of_lines'])
? $data_row[$k]['no_of_lines'] : 1;
if ($no_of_lines < 1) {
$no_of_lines = 1;
}
$wkt .= '(';
for ($i = 0; $i < $no_of_lines; $i++) {
$no_of_points = isset($gis_data[$index]['MULTIPOLYGON'][$k][$i]['no_of_points'])
? $gis_data[$index]['MULTIPOLYGON'][$k][$i]['no_of_points'] : 4;
$no_of_points = isset($data_row[$k][$i]['no_of_points'])
? $data_row[$k][$i]['no_of_points'] : 4;
if ($no_of_points < 4) {
$no_of_points = 4;
}
$wkt .= '(';
for ($j = 0; $j < $no_of_points; $j++) {
$wkt .= ((isset($gis_data[$index]['MULTIPOLYGON'][$k][$i][$j]['x'])
&& trim($gis_data[$index]['MULTIPOLYGON'][$k][$i][$j]['x']) != '')
? $gis_data[$index]['MULTIPOLYGON'][$k][$i][$j]['x'] : $empty)
. ' ' . ((isset($gis_data[$index]['MULTIPOLYGON'][$k][$i][$j]['y'])
&& trim($gis_data[$index]['MULTIPOLYGON'][$k][$i][$j]['y']) != '')
? $gis_data[$index]['MULTIPOLYGON'][$k][$i][$j]['y'] : $empty) .',';
$wkt .= ((isset($data_row[$k][$i][$j]['x'])
&& trim($data_row[$k][$i][$j]['x']) != '')
? $data_row[$k][$i][$j]['x'] : $empty)
. ' ' . ((isset($data_row[$k][$i][$j]['y'])
&& trim($data_row[$k][$i][$j]['y']) != '')
? $data_row[$k][$i][$j]['y'] : $empty) .',';
}
$wkt = substr($wkt, 0, strlen($wkt) - 1);
$wkt .= '),';
@@ -484,32 +487,34 @@ class PMA_GIS_Multipolygon extends PMA_GIS_Geometry
$multipolygon = substr($wkt, 15, (strlen($wkt) - 18));
// Seperate each polygon
$polygons = explode(")),((", $multipolygon);
$params[$index]['MULTIPOLYGON']['no_of_polygons'] = count($polygons);
$param_row =& $params[$index]['MULTIPOLYGON'];
$param_row['no_of_polygons'] = count($polygons);
$k = 0;
foreach ($polygons as $polygon) {
// If the polygon doesnt have an inner polygon
if (strpos($polygon, "),(") === false) {
$params[$index]['MULTIPOLYGON'][$k]['no_of_lines'] = 1;
$param_row[$k]['no_of_lines'] = 1;
$points_arr = $this->extractPoints($polygon, null);
$no_of_points = count($points_arr);
$params[$index]['MULTIPOLYGON'][$k][0]['no_of_points'] = $no_of_points;
$param_row[$k][0]['no_of_points'] = $no_of_points;
for ($i = 0; $i < $no_of_points; $i++) {
$params[$index]['MULTIPOLYGON'][$k][0][$i]['x'] = $points_arr[$i][0];
$params[$index]['MULTIPOLYGON'][$k][0][$i]['y'] = $points_arr[$i][1];
$param_row[$k][0][$i]['x'] = $points_arr[$i][0];
$param_row[$k][0][$i]['y'] = $points_arr[$i][1];
}
} else {
// Seperate outer and inner polygons
$parts = explode("),(", $polygon);
$params[$index]['MULTIPOLYGON'][$k]['no_of_lines'] = count($parts);
$param_row[$k]['no_of_lines'] = count($parts);
$j = 0;
foreach ($parts as $ring) {
$points_arr = $this->extractPoints($ring, null);
$no_of_points = count($points_arr);
$params[$index]['MULTIPOLYGON'][$k][$j]['no_of_points'] = $no_of_points;
$param_row[$k][$j]['no_of_points'] = $no_of_points;
for ($i = 0; $i < $no_of_points; $i++) {
$params[$index]['MULTIPOLYGON'][$k][$j][$i]['x'] = $points_arr[$i][0];
$params[$index]['MULTIPOLYGON'][$k][$j][$i]['y'] = $points_arr[$i][1];
$param_row[$k][$j][$i]['x'] = $points_arr[$i][0];
$param_row[$k][$j][$i]['y'] = $points_arr[$i][1];
}
$j++;
}

View File

@@ -451,6 +451,9 @@ class PMA_GIS_Polygon extends PMA_GIS_Geometry
*/
public static function getPointOnSurface($ring)
{
$common_functions = PMA_CommonFunctions::getInstance();
// Find two consecutive distinct points.
for ($i = 0; $i < count($ring) - 1; $i++) {
if ($ring[$i]['y'] != $ring[$i + 1]['y']) {
@@ -472,7 +475,10 @@ class PMA_GIS_Polygon extends PMA_GIS_Geometry
// Always keep $epsilon < 1 to go with the reduction logic down here
$epsilon = 0.1;
$denominator = sqrt(pow(($y1 - $y0), 2) + pow(($x0 - $x1), 2));
$denominator = sqrt(
$common_functions->pow(($y1 - $y0), 2)
+ $common_functions->pow(($x0 - $x1), 2)
);
$pointA = array(); $pointB = array();
while (true) {
@@ -493,7 +499,7 @@ class PMA_GIS_Polygon extends PMA_GIS_Geometry
} else {
//If both are outside the polygon reduce the epsilon and
//recalculate the points(reduce exponentially for faster convergance)
$epsilon = pow($epsilon, 2);
$epsilon = $common_functions->pow($epsilon, 2);
if ($epsilon == 0) {
return false;
}

View File

@@ -124,7 +124,7 @@ class PMA_GIS_Visualization
*/
private function _sanitizeName($file_name, $ext)
{
$file_name = PMA_sanitize_filename($file_name);
$file_name = PMA_sanitizeFilename($file_name);
// Check if the user already added extension;
// get the substring where the extension would be if it was included
@@ -295,15 +295,19 @@ class PMA_GIS_Visualization
. 'units: "m",'
. 'numZoomLevels: 18,'
. 'maxResolution: 156543.0339,'
. 'maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508),'
. 'restrictedExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508)'
. 'maxExtent: new OpenLayers.Bounds('
. '-20037508, -20037508, 20037508, 20037508),'
. 'restrictedExtent: new OpenLayers.Bounds('
. '-20037508, -20037508, 20037508, 20037508)'
. '};'
. 'var map = new OpenLayers.Map("openlayersmap", options);'
. 'var layerNone = new OpenLayers.Layer.Boxes("None", {isBaseLayer: true});'
. 'var layerNone = new OpenLayers.Layer.Boxes('
. '"None", {isBaseLayer: true});'
. 'var layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");'
. 'var layerOsmarender = new OpenLayers.Layer.OSM.Osmarender("Osmarender");'
. 'var layerOsmarender = new OpenLayers.Layer.OSM.Osmarender('
. '"Osmarender");'
. 'var layerCycleMap = new OpenLayers.Layer.OSM.CycleMap("CycleMap");'
. 'map.addLayers([layerMapnik, layerOsmarender, layerCycleMap, layerNone]);'
. 'map.addLayers([layerMapnik,layerOsmarender,layerCycleMap,layerNone]);'
. 'var vectorLayer = new OpenLayers.Layer.Vector("Data");'
. 'var bound;';
$output .= $this->_prepareDataSet($this->_data, $scale_data, 'ol', '');

View File

@@ -73,7 +73,7 @@ function PMA_GIS_modifyQuery($sql_query, $visualizationSettings)
}
}
}
// If select cluase is *
// If select clause is *
} else {
// If label column is chosen add it to the query
if (isset($visualizationSettings['labelColumn'])

View File

@@ -135,7 +135,7 @@ function PMA_importRunQuery($sql = '', $full = '', $controluser = false)
);
} elseif ($run_query) {
if ($controluser) {
$result = PMA_query_as_controluser(
$result = PMA_queryAsControlUser(
$import_run_buffer['sql']
);
} else {
@@ -243,10 +243,10 @@ function PMA_lookForUse($buffer, $db, $reload)
$db = trim($match[1]);
$db = trim($db, ';'); // for example, USE abc;
// $db must not contain the escape characters generated by PMA_backquote()
// ( used in PMA_buildSQL() as: PMA_backquote($db_name), and then called
// $db must not contain the escape characters generated by backquote()
// ( used in PMA_buildSQL() as: backquote($db_name), and then called
// in PMA_importRunQuery() which in turn calls PMA_lookForUse() )
$db = PMA_unQuote($db);
$db = PMA_CommonFunctions::getInstance()->unQuote($db);
$reload = true;
}
@@ -439,7 +439,7 @@ function PMA_getColumnNumberFromName($name)
// base26 to base10 conversion : multiply each number
// with corresponding value of the position, in this case
// $i=0 : 1; $i=1 : 26; $i=2 : 676; ...
$column_number += $number * pow(26, $i);
$column_number += $number * PMA_CommonFunctions::getInstance()->pow(26, $i);
}
return $column_number;
} else {
@@ -894,6 +894,9 @@ $import_notice = null;
function PMA_buildSQL($db_name, &$tables, &$analyses = null,
&$additional_sql = null, $options = null
) {
$common_functions = PMA_CommonFunctions::getInstance();
/* Take care of the options */
if (isset($options['db_collation'])&& ! is_null($options['db_collation'])) {
$collation = $options['db_collation'];
@@ -918,10 +921,10 @@ function PMA_buildSQL($db_name, &$tables, &$analyses = null,
if ($create_db) {
if (PMA_DRIZZLE) {
$sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_backquote($db_name)
$sql[] = "CREATE DATABASE IF NOT EXISTS " . $common_functions->backquote($db_name)
. " COLLATE " . $collation;
} else {
$sql[] = "CREATE DATABASE IF NOT EXISTS " . PMA_backquote($db_name)
$sql[] = "CREATE DATABASE IF NOT EXISTS " . $common_functions->backquote($db_name)
. " DEFAULT CHARACTER SET " . $charset . " COLLATE " . $collation;
}
}
@@ -930,7 +933,7 @@ function PMA_buildSQL($db_name, &$tables, &$analyses = null,
* The calling plug-in should include this statement,
* if necessary, in the $additional_sql parameter
*
* $sql[] = "USE " . PMA_backquote($db_name);
* $sql[] = "USE " . backquote($db_name);
*/
/* Execute the SQL statements create above */
@@ -995,15 +998,15 @@ function PMA_buildSQL($db_name, &$tables, &$analyses = null,
$num_tables = count($tables);
for ($i = 0; $i < $num_tables; ++$i) {
$num_cols = count($tables[$i][COL_NAMES]);
$tempSQLStr = "CREATE TABLE IF NOT EXISTS " . PMA_backquote($db_name)
. '.' . PMA_backquote($tables[$i][TBL_NAME]) . " (";
$tempSQLStr = "CREATE TABLE IF NOT EXISTS " . $common_functions->backquote($db_name)
. '.' . $common_functions->backquote($tables[$i][TBL_NAME]) . " (";
for ($j = 0; $j < $num_cols; ++$j) {
$size = $analyses[$i][SIZES][$j];
if ((int)$size == 0) {
$size = 10;
}
$tempSQLStr .= PMA_backquote($tables[$i][COL_NAMES][$j]) . " "
$tempSQLStr .= $common_functions->backquote($tables[$i][COL_NAMES][$j]) . " "
. $type_array[$analyses[$i][TYPES][$j]];
if ($analyses[$i][TYPES][$j] != GEOMETRY) {
$tempSQLStr .= "(" . $size . ")";
@@ -1038,11 +1041,11 @@ function PMA_buildSQL($db_name, &$tables, &$analyses = null,
$num_cols = count($tables[$i][COL_NAMES]);
$num_rows = count($tables[$i][ROWS]);
$tempSQLStr = "INSERT INTO " . PMA_backquote($db_name) . '.'
. PMA_backquote($tables[$i][TBL_NAME]) . " (";
$tempSQLStr = "INSERT INTO " . $common_functions->backquote($db_name) . '.'
. $common_functions->backquote($tables[$i][TBL_NAME]) . " (";
for ($m = 0; $m < $num_cols; ++$m) {
$tempSQLStr .= PMA_backquote($tables[$i][COL_NAMES][$m]);
$tempSQLStr .= $common_functions->backquote($tables[$i][COL_NAMES][$m]);
if ($m != ($num_cols - 1)) {
$tempSQLStr .= ", ";
@@ -1075,7 +1078,7 @@ function PMA_buildSQL($db_name, &$tables, &$analyses = null,
}
$tempSQLStr .= (($is_varchar) ? "'" : "");
$tempSQLStr .= PMA_sqlAddSlashes(
$tempSQLStr .= $common_functions->sqlAddSlashes(
(string) $tables[$i][ROWS][$j][$k]
);
$tempSQLStr .= (($is_varchar) ? "'" : "");
@@ -1172,10 +1175,10 @@ function PMA_buildSQL($db_name, &$tables, &$analyses = null,
$message .= sprintf(
'<br /><li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . __('Options') . '</a>)</li>',
$db_url,
sprintf(__('Go to database: %s'), htmlspecialchars(PMA_backquote($db_name))),
sprintf(__('Go to database: %s'), htmlspecialchars($common_functions->backquote($db_name))),
htmlspecialchars($db_name),
$db_ops_url,
sprintf(__('Edit settings for %s'), htmlspecialchars(PMA_backquote($db_name)))
sprintf(__('Edit settings for %s'), htmlspecialchars($common_functions->backquote($db_name)))
);
$message .= '<ul>';
@@ -1198,18 +1201,18 @@ function PMA_buildSQL($db_name, &$tables, &$analyses = null,
$message .= sprintf(
'<li><a href="%s" title="%s">%s</a> (<a href="%s" title="%s">' . __('Structure') . '</a>) (<a href="%s" title="%s">' . __('Options') . '</a>)</li>',
$tbl_url,
sprintf(__('Go to table: %s'), htmlspecialchars(PMA_backquote($tables[$i][TBL_NAME]))),
sprintf(__('Go to table: %s'), htmlspecialchars($common_functions->backquote($tables[$i][TBL_NAME]))),
htmlspecialchars($tables[$i][TBL_NAME]),
$tbl_struct_url,
sprintf(__('Structure of %s'), htmlspecialchars(PMA_backquote($tables[$i][TBL_NAME]))),
sprintf(__('Structure of %s'), htmlspecialchars($common_functions->backquote($tables[$i][TBL_NAME]))),
$tbl_ops_url,
sprintf(__('Edit settings for %s'), htmlspecialchars(PMA_backquote($tables[$i][TBL_NAME])))
sprintf(__('Edit settings for %s'), htmlspecialchars($common_functions->backquote($tables[$i][TBL_NAME])))
);
} else {
$message .= sprintf(
'<li><a href="%s" title="%s">%s</a></li>',
$tbl_url,
sprintf(__('Go to view: %s'), htmlspecialchars(PMA_backquote($tables[$i][TBL_NAME]))),
sprintf(__('Go to view: %s'), htmlspecialchars($common_functions->backquote($tables[$i][TBL_NAME]))),
htmlspecialchars($tables[$i][TBL_NAME])
);
}

View File

@@ -1,41 +0,0 @@
This directory holds import plugins for phpMyAdmin. Plugin should
basically look like following code. Official plugins need to have str*
messages with their definition in language files, if you build some
plugins for your use, you can use directly texts in plugin.
<?php
// vim: expandtab sw=4 ts=4 sts=4 ft=php:
/* Demo import plugin for phpMyAdmin */
if (isset($plugin_list)) {
$plugin_list['name'] = array( // set name of your plugin
'text' => 'strName', // text to be displayed as choice
'extension' => '', // extension this plugin can handle
'options' => array( // array of options for your plugin (optional)
array('type' => '', 'name' => '', 'text' => ''), // type: bool or text, name: form element name, text: description in GUI, size: size of text element (optional). len: maximal size of input (optional)
),
'options_text' => 'strNameImportOptions', // text to describe plugin options (must be set if options are used)
);
} else {
/* We do not define function when plugin is just queried for information above */
$buffer = '';
while (!($finished && $i >= $len) && !$error && !$timeout_passed) {
$data = PMA_importGetNextChunk();
if ($data === false) {
// subtract data we didn't handle yet and stop processing
$offset -= strlen($buffer);
break;
} elseif ($data === true) {
// Handle rest of buffer
} else {
// Append new data to buffer
$buffer .= $data;
}
// PARSE $buffer here, post sql queries using:
PMA_importRunQuery($sql, $verbose_sql_with_comments);
} // End of import loop
// Commit any possible data in buffers
PMA_importRunQuery();
}
?>

View File

@@ -1,529 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* CSV import plugin for phpMyAdmin
*
* @todo add an option for handling NULL values
* @package PhpMyAdmin-Import
* @subpackage CSV
*/
if (! defined('PHPMYADMIN')) {
exit;
}
$analyze = false;
if ($plugin_param !== 'table') {
$analyze = true;
}
if (isset($plugin_list)) {
$plugin_list['csv'] = array(
'text' => __('CSV'),
'extension' => 'csv',
'options' => array(),
'options_text' => __('Options')
);
$plugin_list['csv']['options'] = array(
array(
'type' => 'begin_group',
'name' => 'general_opts'
),
array(
'type' => 'bool',
'name' => 'replace',
'text' => __('Replace table data with file')
),
array(
'type' => 'bool',
'name' => 'ignore',
'text' => __('Do not abort on INSERT error')
),
array(
'type' => 'text',
'name' => 'terminated',
'text' => __('Columns separated with:'),
'size' => 2,
'len' => 2
),
array(
'type' => 'text',
'name' => 'enclosed',
'text' => __('Columns enclosed with:'),
'size' => 2,
'len' => 2
),
array(
'type' => 'text',
'name' => 'escaped',
'text' => __('Columns escaped with:'),
'size' => 2,
'len' => 2
),
array(
'type' => 'text',
'name' => 'new_line',
'text' => __('Lines terminated with:'),
'size' => 2
)
);
if ($plugin_param !== 'table') {
$plugin_list['csv']['options'][] = array(
'type' => 'bool',
'name' => 'col_names',
'text' => __(
'The first line of the file contains the table column names <i>'
. '(if this is unchecked, the first line will become part of the'
. ' data)</i>'
)
);
} else {
$hint = new PMA_Message(
__(
'If the data in each row of the file is not'
. ' in the same order as in the database, list the corresponding'
. ' column names here. Column names must be separated by commas'
. ' and not enclosed in quotations.'
)
);
$plugin_list['csv']['options'][] = array(
'type' => 'text',
'name' => 'columns',
'text' => __('Column names: ') . PMA_showHint($hint)
);
}
$plugin_list['csv']['options'][] = array('type' => 'end_group');
/* We do not define function when plugin is just queried for information above */
return;
}
$replacements = array(
'\\n' => "\n",
'\\t' => "\t",
'\\r' => "\r",
);
$csv_terminated = strtr($csv_terminated, $replacements);
$csv_enclosed = strtr($csv_enclosed, $replacements);
$csv_escaped = strtr($csv_escaped, $replacements);
$csv_new_line = strtr($csv_new_line, $replacements);
$param_error = false;
if (strlen($csv_terminated) != 1) {
$message = PMA_Message::error(__('Invalid parameter for CSV import: %s'));
$message->addParam(__('Columns terminated by'), false);
$error = true;
$param_error = true;
// The default dialog of MS Excel when generating a CSV produces a
// semi-colon-separated file with no chance of specifying the
// enclosing character. Thus, users who want to import this file
// tend to remove the enclosing character on the Import dialog.
// I could not find a test case where having no enclosing characters
// confuses this script.
// But the parser won't work correctly with strings so we allow just
// one character.
} elseif (strlen($csv_enclosed) > 1) {
$message = PMA_Message::error(__('Invalid parameter for CSV import: %s'));
$message->addParam(__('Columns enclosed by'), false);
$error = true;
$param_error = true;
} elseif (strlen($csv_escaped) != 1) {
$message = PMA_Message::error(__('Invalid parameter for CSV import: %s'));
$message->addParam(__('Columns escaped by'), false);
$error = true;
$param_error = true;
} elseif (strlen($csv_new_line) != 1 && $csv_new_line != 'auto') {
$message = PMA_Message::error(__('Invalid parameter for CSV import: %s'));
$message->addParam(__('Lines terminated by'), false);
$error = true;
$param_error = true;
}
// If there is an error in the parameters entered, indicate that immediately.
if ($param_error) {
PMA_mysqlDie($message->getMessage(), '', '', $err_url);
}
$buffer = '';
$required_fields = 0;
if (! $analyze) {
if (isset($csv_replace)) {
$sql_template = 'REPLACE';
} else {
$sql_template = 'INSERT';
if (isset($csv_ignore)) {
$sql_template .= ' IGNORE';
}
}
$sql_template .= ' INTO ' . PMA_backquote($table);
$tmp_fields = PMA_DBI_get_columns($db, $table);
if (empty($csv_columns)) {
$fields = $tmp_fields;
} else {
$sql_template .= ' (';
$fields = array();
$tmp = preg_split('/,( ?)/', $csv_columns);
foreach ($tmp as $key => $val) {
if (count($fields) > 0) {
$sql_template .= ', ';
}
/* Trim also `, if user already included backquoted fields */
$val = trim($val, " \t\r\n\0\x0B`");
$found = false;
foreach ($tmp_fields as $id => $field) {
if ($field['Field'] == $val) {
$found = true;
break;
}
}
if (! $found) {
$message = PMA_Message::error(
__(
'Invalid column (%s) specified! Ensure that columns names'
. ' are spelled correctly, separated by commas, and not'
. ' enclosed in quotes.'
)
);
$message->addParam($val);
$error = true;
break;
}
$fields[] = $field;
$sql_template .= PMA_backquote($val);
}
$sql_template .= ') ';
}
$required_fields = count($fields);
$sql_template .= ' VALUES (';
}
// Defaults for parser
$i = 0;
$len = 0;
$line = 1;
$lasti = -1;
$values = array();
$csv_finish = false;
$tempRow = array();
$rows = array();
$col_names = array();
$tables = array();
$col_count = 0;
$max_cols = 0;
while (! ($finished && $i >= $len) && ! $error && ! $timeout_passed) {
$data = PMA_importGetNextChunk();
if ($data === false) {
// subtract data we didn't handle yet and stop processing
$offset -= strlen($buffer);
break;
} elseif ($data === true) {
// Handle rest of buffer
} else {
// Append new data to buffer
$buffer .= $data;
unset($data);
// Do not parse string when we're not at the end
// and don't have new line inside
if (($csv_new_line == 'auto'
&& strpos($buffer, "\r") === false
&& strpos($buffer, "\n") === false)
|| ($csv_new_line != 'auto'
&& strpos($buffer, $csv_new_line) === false)
) {
continue;
}
}
// Current length of our buffer
$len = strlen($buffer);
// Currently parsed char
$ch = $buffer[$i];
while ($i < $len) {
// Deadlock protection
if ($lasti == $i && $lastlen == $len) {
$message = PMA_Message::error(
__('Invalid format of CSV input on line %d.')
);
$message->addParam($line);
$error = true;
break;
}
$lasti = $i;
$lastlen = $len;
// This can happen with auto EOL and \r at the end of buffer
if (! $csv_finish) {
// Grab empty field
if ($ch == $csv_terminated) {
if ($i == $len - 1) {
break;
}
$values[] = '';
$i++;
$ch = $buffer[$i];
continue;
}
// Grab one field
$fallbacki = $i;
if ($ch == $csv_enclosed) {
if ($i == $len - 1) {
break;
}
$need_end = true;
$i++;
$ch = $buffer[$i];
} else {
$need_end = false;
}
$fail = false;
$value = '';
while (($need_end
&& ( $ch != $csv_enclosed || $csv_enclosed == $csv_escaped ))
|| ( ! $need_end
&& ! ( $ch == $csv_terminated
|| $ch == $csv_new_line
|| ( $csv_new_line == 'auto'
&& ( $ch == "\r" || $ch == "\n" ) ) ) )
) {
if ($ch == $csv_escaped) {
if ($i == $len - 1) {
$fail = true;
break;
}
$i++;
$ch = $buffer[$i];
if ($csv_enclosed == $csv_escaped
&& ($ch == $csv_terminated
|| $ch == $csv_new_line
|| ($csv_new_line == 'auto' && ($ch == "\r" || $ch == "\n")))
) {
break;
}
}
$value .= $ch;
if ($i == $len - 1) {
if (! $finished) {
$fail = true;
}
break;
}
$i++;
$ch = $buffer[$i];
}
// unquoted NULL string
if (false === $need_end && $value === 'NULL') {
$value = null;
}
if ($fail) {
$i = $fallbacki;
$ch = $buffer[$i];
break;
}
// Need to strip trailing enclosing char?
if ($need_end && $ch == $csv_enclosed) {
if ($finished && $i == $len - 1) {
$ch = null;
} elseif ($i == $len - 1) {
$i = $fallbacki;
$ch = $buffer[$i];
break;
} else {
$i++;
$ch = $buffer[$i];
}
}
// Are we at the end?
if ($ch == $csv_new_line
|| ($csv_new_line == 'auto' && ($ch == "\r" || $ch == "\n"))
|| ($finished && $i == $len - 1)
) {
$csv_finish = true;
}
// Go to next char
if ($ch == $csv_terminated) {
if ($i == $len - 1) {
$i = $fallbacki;
$ch = $buffer[$i];
break;
}
$i++;
$ch = $buffer[$i];
}
// If everything went okay, store value
$values[] = $value;
}
// End of line
if ($csv_finish
|| $ch == $csv_new_line
|| ($csv_new_line == 'auto' && ($ch == "\r" || $ch == "\n"))
) {
if ($csv_new_line == 'auto' && $ch == "\r") { // Handle "\r\n"
if ($i >= ($len - 2) && ! $finished) {
break; // We need more data to decide new line
}
if ($buffer[$i + 1] == "\n") {
$i++;
}
}
// We didn't parse value till the end of line, so there was empty one
if (! $csv_finish) {
$values[] = '';
}
if ($analyze) {
foreach ($values as $ley => $val) {
$tempRow[] = $val;
++$col_count;
}
if ($col_count > $max_cols) {
$max_cols = $col_count;
}
$col_count = 0;
$rows[] = $tempRow;
$tempRow = array();
} else {
// Do we have correct count of values?
if (count($values) != $required_fields) {
// Hack for excel
if ($values[count($values) - 1] == ';') {
unset($values[count($values) - 1]);
} else {
$message = PMA_Message::error(
__('Invalid column count in CSV input on line %d.')
);
$message->addParam($line);
$error = true;
break;
}
}
$first = true;
$sql = $sql_template;
foreach ($values as $key => $val) {
if (! $first) {
$sql .= ', ';
}
if ($val === null) {
$sql .= 'NULL';
} else {
$sql .= '\'' . PMA_sqlAddSlashes($val) . '\'';
}
$first = false;
}
$sql .= ')';
/**
* @todo maybe we could add original line to verbose SQL in comment
*/
PMA_importRunQuery($sql, $sql);
}
$line++;
$csv_finish = false;
$values = array();
$buffer = substr($buffer, $i + 1);
$len = strlen($buffer);
$i = 0;
$lasti = -1;
$ch = $buffer[0];
}
} // End of parser loop
} // End of import loop
if ($analyze) {
/* Fill out all rows */
$num_rows = count($rows);
for ($i = 0; $i < $num_rows; ++$i) {
for ($j = count($rows[$i]); $j < $max_cols; ++$j) {
$rows[$i][] = 'NULL';
}
}
if (isset($_REQUEST['csv_col_names'])) {
$col_names = array_splice($rows, 0, 1);
$col_names = $col_names[0];
}
if ((isset($col_names) && count($col_names) != $max_cols)
|| ! isset($col_names)
) {
// Fill out column names
for ($i = 0; $i < $max_cols; ++$i) {
$col_names[] = 'COL '.($i+1);
}
}
if (strlen($db)) {
$result = PMA_DBI_fetch_result('SHOW TABLES');
$tbl_name = 'TABLE '.(count($result) + 1);
} else {
$tbl_name = 'TBL_NAME';
}
$tables[] = array($tbl_name, $col_names, $rows);
/* Obtain the best-fit MySQL types for each column */
$analyses = array();
$analyses[] = PMA_analyzeTable($tables[0]);
/**
* string $db_name (no backquotes)
*
* array $table = array(table_name, array() column_names, array()() rows)
* array $tables = array of "$table"s
*
* array $analysis = array(array() column_types, array() column_sizes)
* array $analyses = array of "$analysis"s
*
* array $create = array of SQL strings
*
* array $options = an associative array of options
*/
/* Set database name to the currently selected one, if applicable */
if (strlen($db)) {
$db_name = $db;
$options = array('create_db' => false);
} else {
$db_name = 'CSV_DB';
$options = null;
}
/* Non-applicable parameters */
$create = null;
/* Created and execute necessary SQL statements from data */
PMA_buildSQL($db_name, $tables, $analyses, $create, $options);
unset($tables);
unset($analyses);
}
// Commit any possible data in buffers
PMA_importRunQuery();
if (count($values) != 0 && ! $error) {
$message = PMA_Message::error(__('Invalid format of CSV input on line %d.'));
$message->addParam($line);
$error = true;
}
?>

View File

@@ -1,97 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* DocSQL import plugin for phpMyAdmin
*
* @package PhpMyAdmin-Import
* @subpackage DocSQL
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* Load relations.
*/
$cfgRelation = PMA_getRelationsParam();
/**
* We need relations enabled and we work only on database
*/
if ($plugin_param !== 'database' || $GLOBALS['num_tables'] < 1
|| ! $cfgRelation['relwork'] || ! $cfgRelation['commwork']
) {
return;
}
if (isset($plugin_list)) {
$plugin_list['docsql'] = array( // set name of your plugin
'text' => __('DocSQL'), // text to be displayed as choice
'extension' => '', // extension this plugin can handle
'options' => array( // array of options for your plugin (optional)
array('type' => 'begin_group', 'name' => 'general_opts'),
array('type' => 'text', 'name' => 'table', 'text' => __('Table name')),
array('type' => 'end_group')
),
'options_text' => __('Options'), // text to describe plugin options (must be set if options are used)
);
/* We do not define function when plugin is just queried for information above */
return;
}
$tab = $_POST['docsql_table'];
$buffer = '';
/* Read whole buffer, we except it is small enough */
while (!$finished && !$error && !$timeout_passed) {
$data = PMA_importGetNextChunk();
if ($data === false) {
// subtract data we didn't handle yet and stop processing
break;
} elseif ($data === true) {
// nothing to read
break;
} else {
// Append new data to buffer
$buffer .= $data;
}
} // End of import loop
/* Process the data */
if ($data === true && !$error && !$timeout_passed) {
$buffer = str_replace("\r\n", "\n", $buffer);
$buffer = str_replace("\r", "\n", $buffer);
$lines = explode("\n", $buffer);
foreach ($lines AS $lkey => $line) {
//echo '<p>' . $line . '</p>';
$inf = explode('|', $line);
if (!empty($inf[1]) && strlen(trim($inf[1])) > 0) {
$qry = '
INSERT INTO
' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['column_info']) . '
(db_name, table_name, column_name, comment)
VALUES (
\'' . PMA_sqlAddSlashes($GLOBALS['db']) . '\',
\'' . PMA_sqlAddSlashes(trim($tab)) . '\',
\'' . PMA_sqlAddSlashes(trim($inf[0])) . '\',
\'' . PMA_sqlAddSlashes(trim($inf[1])) . '\')';
PMA_importRunQuery($qry, $qry . '-- ' . htmlspecialchars($tab) . '.' . htmlspecialchars($inf[0]), true);
} // end inf[1] exists
if (!empty($inf[2]) && strlen(trim($inf[2])) > 0) {
$for = explode('->', $inf[2]);
$qry = '
INSERT INTO
' . PMA_backquote($cfgRelation['db']) . '.' . PMA_backquote($cfgRelation['relation']) . '
(master_db, master_table, master_field, foreign_db, foreign_table, foreign_field)
VALUES (
\'' . PMA_sqlAddSlashes($GLOBALS['db']) . '\',
\'' . PMA_sqlAddSlashes(trim($tab)) . '\',
\'' . PMA_sqlAddSlashes(trim($inf[0])) . '\',
\'' . PMA_sqlAddSlashes($GLOBALS['db']) . '\',
\'' . PMA_sqlAddSlashes(trim($for[0])) . '\',
\'' . PMA_sqlAddSlashes(trim($for[1])) . '\')';
PMA_importRunQuery($qry, $qry . '-- ' . htmlspecialchars($tab) . '.' . htmlspecialchars($inf[0]) . '(' . htmlspecialchars($inf[2]) . ')', true);
} // end inf[2] exists
} // End lines loop
} // End import
// Commit any possible data in buffers
PMA_importRunQuery();
?>

View File

@@ -1,155 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* CSV import plugin for phpMyAdmin using LOAD DATA
*
* @package PhpMyAdmin-Import
* @subpackage LDI
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
*
*/
if ($plugin_param !== 'table') {
return;
}
if (isset($plugin_list)) {
if ($GLOBALS['cfg']['Import']['ldi_local_option'] == 'auto') {
$GLOBALS['cfg']['Import']['ldi_local_option'] = false;
$result = PMA_DBI_try_query('SHOW VARIABLES LIKE \'local\\_infile\';');
if ($result != false && PMA_DBI_num_rows($result) > 0) {
$tmp = PMA_DBI_fetch_row($result);
if ($tmp[1] == 'ON') {
$GLOBALS['cfg']['Import']['ldi_local_option'] = true;
}
}
PMA_DBI_free_result($result);
unset($result);
}
$plugin_list['ldi'] = array(
'text' => __('CSV using LOAD DATA'),
// Following is nonsense, however we want to default to our parser for csv
'extension' => 'ldi',
'options' => array(
array(
'type' => 'begin_group',
'name' => 'general_opts'
),
array(
'type' => 'bool',
'name' => 'replace',
'text' => __('Replace table data with file')
),
array(
'type' => 'bool',
'name' => 'ignore',
'text' => __('Do not abort on INSERT error')
),
array(
'type' => 'text',
'name' => 'terminated',
'text' => __('Columns terminated by'),
'size' => 2,
'len' => 2
),
array(
'type' => 'text',
'name' => 'enclosed',
'text' => __('Columns enclosed by'),
'size' => 2,
'len' => 2
),
array(
'type' => 'text',
'name' => 'escaped',
'text' => __('Columns escaped by'),
'size' => 2,
'len' => 2
),
array(
'type' => 'text',
'name' => 'new_line',
'text' => __('Lines terminated by'),
'size' => 2
),
array(
'type' => 'text',
'name' => 'columns',
'text' => __('Column names')
),
array(
'type' => 'bool',
'name' => 'local_option',
'text' => __('Use LOCAL keyword')
),
array(
'type' => 'end_group'
)
),
'options_text' => __('Options'),
);
/* We do not define function when plugin is just queried for information above */
return;
}
if ($import_file == 'none' || $compression != 'none' || $charset_conversion) {
// We handle only some kind of data!
$message = PMA_Message::error(__('This plugin does not support compressed imports!'));
$error = true;
return;
}
$sql = 'LOAD DATA';
if (isset($ldi_local_option)) {
$sql .= ' LOCAL';
}
$sql .= ' INFILE \'' . PMA_sqlAddSlashes($import_file) . '\'';
if (isset($ldi_replace)) {
$sql .= ' REPLACE';
} elseif (isset($ldi_ignore)) {
$sql .= ' IGNORE';
}
$sql .= ' INTO TABLE ' . PMA_backquote($table);
if (strlen($ldi_terminated) > 0) {
$sql .= ' FIELDS TERMINATED BY \'' . $ldi_terminated . '\'';
}
if (strlen($ldi_enclosed) > 0) {
$sql .= ' ENCLOSED BY \'' . PMA_sqlAddSlashes($ldi_enclosed) . '\'';
}
if (strlen($ldi_escaped) > 0) {
$sql .= ' ESCAPED BY \'' . PMA_sqlAddSlashes($ldi_escaped) . '\'';
}
if (strlen($ldi_new_line) > 0) {
if ($ldi_new_line == 'auto') {
$ldi_new_line = PMA_whichCrlf() == "\n" ? '\n' : '\r\n';
}
$sql .= ' LINES TERMINATED BY \'' . $ldi_new_line . '\'';
}
if ($skip_queries > 0) {
$sql .= ' IGNORE ' . $skip_queries . ' LINES';
$skip_queries = 0;
}
if (strlen($ldi_columns) > 0) {
$sql .= ' (';
$tmp = preg_split('/,( ?)/', $ldi_columns);
$cnt_tmp = count($tmp);
for ($i = 0; $i < $cnt_tmp; $i++) {
if ($i > 0) {
$sql .= ', ';
}
/* Trim also `, if user already included backquoted fields */
$sql .= PMA_backquote(trim($tmp[$i], " \t\r\n\0\x0B`"));
} // end for
$sql .= ')';
}
PMA_importRunQuery($sql, $sql);
PMA_importRunQuery();
$finished = true;
?>

View File

@@ -1,489 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* MediaWiki import plugin for phpMyAdmin
*
* @package PhpMyAdmin-Import
* @subpackage MediaWiki
*/
if (! defined('PHPMYADMIN')) {
exit;
}
$analyze = false;
if ($plugin_param !== 'table') {
$analyze = true;
}
if (isset($plugin_list)) {
$plugin_list['mediawiki'] = array(
'text' => __('MediaWiki Table'),
'extension' => 'txt',
'mime_type' => 'text/plain',
'options' => array(),
'options_text' => __('Options'),
);
// We do not define function when plugin is just
// queried for information above
return;
}
// Defaults for parser
// The buffer that will be used to store chunks read from the imported file
$buffer = '';
// Used as storage for the last part of the current chunk data
// Will be appended to the first line of the next chunk, if there is one
$last_chunk_line = '';
// Remembers whether the current buffer line is part of a comment
$inside_comment = false;
// Remembers whether the current buffer line is part of a data comment
$inside_data_comment = false;
// Remembers whether the current buffer line is part of a structure comment
$inside_structure_comment = false;
// MediaWiki only accepts "\n" as row terminator
$mediawiki_new_line = "\n";
// Initialize the name of the current table
$cur_table_name = "";
while (! $finished && ! $error && ! $timeout_passed ) {
$data = PMA_importGetNextChunk();
if ($data === false) {
// Subtract data we didn't handle yet and stop processing
$offset -= strlen($buffer);
break;
} elseif ($data === true) {
// Handle rest of buffer
} else {
// Append new data to buffer
$buffer = $data;
unset($data);
// Don't parse string if we're not at the end
// and don't have a new line inside
if ( strpos($buffer, $mediawiki_new_line) === false ) {
continue;
}
}
// Because of reading chunk by chunk, the first line from the buffer
// contains only a portion of an actual line from the imported file.
// Therefore, we have to append it to the last line from the previous
// chunk. If we are at the first chunk, $last_chunk_line should be empty.
$buffer = $last_chunk_line . $buffer;
// Process the buffer line by line
$buffer_lines = explode($mediawiki_new_line, $buffer);
$full_buffer_lines_count = count($buffer_lines);
// If the reading is not finalised, the final line of the current chunk
// will not be complete
if (! $finished) {
$full_buffer_lines_count -= 1;
$last_chunk_line = $buffer_lines[$full_buffer_lines_count];
}
for ($line_nr = 0; $line_nr < $full_buffer_lines_count; ++ $line_nr) {
$cur_buffer_line = trim($buffer_lines[$line_nr]);
// If the line is empty, go to the next one
if ( $cur_buffer_line === '' ) {
continue;
}
$first_character = $cur_buffer_line[0];
$matches = array();
// Check beginnning of comment
if (! strcmp(substr($cur_buffer_line, 0, 4), "<!--")) {
$inside_comment = true;
continue;
} elseif ($inside_comment) {
// Check end of comment
if (! strcmp(substr($cur_buffer_line, 0, 4), "-->")) {
// Only data comments are closed. The structure comments will
// be closed when a data comment begins (in order to skip
// structure tables)
if ($inside_data_comment) {
$inside_data_comment = false;
}
// End comments that are not related to table structure
if (! $inside_structure_comment) {
$inside_comment = false;
}
} else {
// Check table name
$match_table_name = array();
if (preg_match(
"/^Table data for `(.*)`$/",
$cur_buffer_line,
$match_table_name
)
) {
$cur_table_name = $match_table_name[1];
$inside_data_comment = true;
// End ignoring structure rows
if ($inside_structure_comment) {
$inside_structure_comment = false;
}
} elseif (preg_match(
"/^Table structure for `(.*)`$/",
$cur_buffer_line,
$match_table_name
)
) {
// The structure comments will be ignored
$inside_structure_comment = true;
}
}
continue;
} elseif (preg_match('/^\{\|(.*)$/', $cur_buffer_line, $matches)) {
// Check start of table
// This will store all the column info on all rows from
// the current table read from the buffer
$cur_temp_table = array();
// Will be used as storage for the current row in the buffer
// Once all its columns are read, it will be added to
// $cur_temp_table and then it will be emptied
$cur_temp_line = array();
// Helps us differentiate the header columns
// from the normal columns
$in_table_header = false;
// End processing because the current line does not
// contain any column information
} elseif (substr($cur_buffer_line, 0, 2) === '|-'
|| substr($cur_buffer_line, 0, 2) === '|+'
|| substr($cur_buffer_line, 0, 2) === '|}'
) {
// Check begin row or end table
// Add current line to the values storage
if (! empty($cur_temp_line)) {
// If the current line contains header cells ( marked with '!' ),
// it will be marked as table header
if ( $in_table_header ) {
// Set the header columns
$cur_temp_table_headers = $cur_temp_line;
} else {
// Normal line, add it to the table
$cur_temp_table [] = $cur_temp_line;
}
}
// Empty the temporary buffer
$cur_temp_line = array();
// No more processing required at the end of the table
if (substr($cur_buffer_line, 0, 2) === '|}') {
$current_table = array(
$cur_table_name,
$cur_temp_table_headers,
$cur_temp_table
);
// Import the current table data into the database
PMA_importDataOneTable($current_table);
// Reset table name
$cur_table_name = "";
}
// What's after the row tag is now only attributes
} elseif (($first_character === '|') || ($first_character === '!')) {
// Check cell elements
// Header cells
if ($first_character === '!') {
// Mark as table header, but treat as normal row
$cur_buffer_line = str_replace('!!', '||', $cur_buffer_line);
// Will be used to set $cur_temp_line as table header
$in_table_header = true;
} else {
$in_table_header = false;
}
// Loop through each table cell
$cells = PMA_explodeMarkup($cur_buffer_line);
foreach ($cells as $cell) {
// A cell could contain both parameters and data
$cell_data = explode('|', $cell, 2);
// A '|' inside an invalid link should not
// be mistaken as delimiting cell parameters
if (strpos($cell_data[0], '[[') === true ) {
if (count($cell_data) == 1) {
$cell = $cell_data[0];
} else {
$cell = $cell_data[1];
}
}
// Delete the beginning of the column, if there is one
$cell = trim($cell);
$col_start_chars = array( "|", "!");
foreach ($col_start_chars as $col_start_char) {
if (strpos($cell, $col_start_char) === 0) {
$cell = trim(substr($cell, 1));
}
}
// Add the cell to the row
$cur_temp_line [] = $cell;
} // foreach $cells
} else {
// If it's none of the above, then the current line has a bad format
$message = PMA_Message::error(
__('Invalid format of mediawiki input on line: <br />%s.')
);
$message->addParam($cur_buffer_line);
$error = true;
}
} // End treating full buffer lines
} // while - finished parsing buffer
/**
* Imports data from a single table
*
* @param array $table containing all table info:
* <code>
* $table[0] - string containing table name
* $table[1] - array[] of table headers
* $table[2] - array[][] of table content rows
* </code>
*
* @global bool $analyze whether to scan for column types
*
* @return void
*/
function PMA_importDataOneTable ($table)
{
global $analyze;
if ($analyze) {
// Set the table name
PMA_setTableName($table[0]);
// Set generic names for table headers if they don't exist
PMA_setTableHeaders($table[1], $table[2][0]);
// Create the tables array to be used in PMA_buildSQL()
$tables = array();
$tables [] = array($table[0], $table[1], $table[2]);
// Obtain the best-fit MySQL types for each column
$analyses = array();
$analyses [] = PMA_analyzeTable($tables[0]);
PMA_executeImportTables($tables, $analyses);
}
// Commit any possible data in buffers
PMA_importRunQuery();
}
/**
* Sets the table name
*
* @param string &$table_name reference to the name of the table
*
* @return void
*/
function PMA_setTableName(&$table_name)
{
if (empty($table_name)) {
$result = PMA_DBI_fetch_result('SHOW TABLES');
// todo check if the name below already exists
$table_name = 'TABLE '.(count($result) + 1);
}
}
/**
* Set generic names for table headers, if they don't exist
*
* @param array &$table_headers reference to the array containing the headers
* of a table
* @param array $table_row array containing the first content row
*
* @return void
*/
function PMA_setTableHeaders(&$table_headers, $table_row)
{
if (empty($table_headers)) {
// The first table row should contain the number of columns
// If they are not set, generic names will be given (COL 1, COL 2, etc)
$num_cols = count($table_row);
for ($i = 0; $i < $num_cols; ++ $i) {
$table_headers [$i] = 'COL '. ($i + 1);
}
}
}
/**
* Sets the database name and additional options and calls PMA_buildSQL()
* Used in PMA_importDataAllTables() and PMA_importDataOneTable()
*
* @param array &$tables structure:
* array(
* array(table_name, array() column_names, array()() rows)
* )
* @param array &$analyses structure:
* $analyses = array(
* array(array() column_types, array() column_sizes)
* )
*
* @global string $db name of the database to import in
*
* @return void
*/
function PMA_executeImportTables(&$tables, &$analyses)
{
global $db;
// $db_name : The currently selected database name, if applicable
// No backquotes
// $options : An associative array of options
if (strlen($db)) {
$db_name = $db;
$options = array('create_db' => false);
} else {
$db_name = 'mediawiki_DB';
$options = null;
}
// Array of SQL strings
// Non-applicable parameters
$create = null;
// Create and execute necessary SQL statements from data
PMA_buildSQL($db_name, $tables, $analyses, $create, $options);
unset($tables);
unset($analyses);
}
/**
* Replaces all instances of the '||' separator between delimiters
* in a given string
*
* @param string $start_delim start delimiter
* @param string $end_delim end delimiter
* @param string $replace the string to be replaced with
* @param string $subject the text to be replaced
*
* @return string with replacements
*/
function PMA_delimiterReplace($start_delim, $end_delim, $replace, $subject)
{
// String that will be returned
$cleaned = "";
// Possible states of current character
$inside_tag = false;
$inside_attribute = false;
// Attributes can be declared with either " or '
$start_attribute_character = false;
// The full separator is "||";
// This rembembers if the previous character was '|'
$partial_separator = false;
// Parse text char by char
for ($i = 0; $i < strlen($subject); $i ++) {
$cur_char = $subject[$i];
// Check for separators
if ($cur_char == '|') {
// If we're not inside a tag, then this is part of a real separator,
// so we append it to the current segment
if (! $inside_attribute) {
$cleaned .= $cur_char;
if ($partial_separator) {
$inside_tag = false;
$inside_attribute = false;
}
} elseif ($partial_separator) {
// If we are inside a tag, we replace the current char with
// the placeholder and append that to the current segment
$cleaned .= $replace;
}
// If the previous character was also '|', then this ends a
// full separator. If not, this may be the beginning of one
$partial_separator = ! $partial_separator;
} else {
// If we're inside a tag attribute and the current character is
// not '|', but the previous one was, it means that the single '|'
// was not appended, so we append it now
if ($partial_separator && $inside_attribute) {
$cleaned .= "|";
}
// If the char is different from "|", no separator can be formed
$partial_separator = false;
// any other character should be appended to the current segment
$cleaned .= $cur_char;
if ($cur_char == '<' && ! $inside_attribute) {
// start of a tag
$inside_tag = true;
} elseif ($cur_char == '>' && ! $inside_attribute) {
// end of a tag
$inside_tag = false;
} elseif (($cur_char == '"' || $cur_char == "'") && $inside_tag) {
// start or end of an attribute
if (! $inside_attribute) {
$inside_attribute = true;
// remember the attribute`s declaration character (" or ')
$start_attribute_character = $cur_char;
} else {
if ($cur_char == $start_attribute_character) {
$inside_attribute = false;
// unset attribute declaration character
$start_attribute_character = false;
}
}
}
}
} // end for each character in $subject
return $cleaned;
}
/**
* Separates a string into items, similarly to explode
* Uses the '||' separator (which is standard in the mediawiki format)
* and ignores any instances of it inside markup tags
* Used in parsing buffer lines containing data cells
*
* @param string $text text to be split
*
* @return array
*/
function PMA_explodeMarkup($text)
{
$separator = "||";
$placeholder = "\x00";
// Remove placeholder instances
$text = str_replace($placeholder, '', $text);
// Replace instances of the separator inside HTML-like
// tags with the placeholder
$cleaned = PMA_delimiterReplace("<", ">", $placeholder, $text);
// Explode, then put the replaced separators back in
$items = explode($separator, $cleaned);
foreach ($items as $i => $str) {
$items[$i] = str_replace($placeholder, $separator, $str);
}
return $items;
}
?>

View File

@@ -1,329 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* OpenDocument Spreadsheet import plugin for phpMyAdmin
*
* @todo Pretty much everything
* @todo Importing of accented characters seems to fail
* @package PhpMyAdmin-Import
* @subpackage ODS
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* We need way to disable external XML entities processing.
*/
if (!function_exists('libxml_disable_entity_loader')) {
return;
}
/**
* The possible scopes for $plugin_param are: 'table', 'database', and 'server'
*/
if (isset($plugin_list)) {
$plugin_list['ods'] = array(
'text' => __('Open Document Spreadsheet'),
'extension' => 'ods',
'options' => array(
array(
'type' => 'begin_group',
'name' => 'general_opts'
),
array(
'type' => 'bool',
'name' => 'col_names',
'text' => __('The first line of the file contains the table column names <i>(if this is unchecked, the first line will become part of the data)</i>')
),
array(
'type' => 'bool',
'name' => 'empty_rows',
'text' => __('Do not import empty rows')
),
array(
'type' => 'bool',
'name' => 'recognize_percentages',
'text' => __('Import percentages as proper decimals <i>(ex. 12.00% to .12)</i>')
),
array(
'type' => 'bool',
'name' => 'recognize_currency',
'text' => __('Import currencies <i>(ex. $5.00 to 5.00)</i>')
),
array('type' => 'end_group')
),
'options_text' => __('Options'),
);
/* We do not define function when plugin is just queried for information above */
return;
}
$i = 0;
$len = 0;
$buffer = "";
/**
* Read in the file via PMA_importGetNextChunk so that
* it can process compressed files
*/
while (! ($finished && $i >= $len) && ! $error && ! $timeout_passed) {
$data = PMA_importGetNextChunk();
if ($data === false) {
/* subtract data we didn't handle yet and stop processing */
$offset -= strlen($buffer);
break;
} elseif ($data === true) {
/* Handle rest of buffer */
} else {
/* Append new data to buffer */
$buffer .= $data;
unset($data);
}
}
unset($data);
/**
* Disable loading of external XML entities.
*/
libxml_disable_entity_loader();
/**
* Load the XML string
*
* The option LIBXML_COMPACT is specified because it can
* result in increased performance without the need to
* alter the code in any way. It's basically a freebee.
*/
$xml = simplexml_load_string($buffer, "SimpleXMLElement", LIBXML_COMPACT);
unset($buffer);
if ($xml === false) {
$sheets = array();
$message = PMA_Message::error(__('The XML file specified was either malformed or incomplete. Please correct the issue and try again.'));
$error = true;
} else {
$sheets = $xml->children('office', true)->{'body'}->{'spreadsheet'}->children('table', true);
}
$tables = array();
$max_cols = 0;
$row_count = 0;
$col_count = 0;
$col_names = array();
$tempRow = array();
$tempRows = array();
$rows = array();
/* Iterate over tables */
foreach ($sheets as $sheet) {
$col_names_in_first_row = isset($_REQUEST['ods_col_names']);
/* Iterate over rows */
foreach ($sheet as $row) {
$type = $row->getName();
if (! strcmp('table-row', $type)) {
/* Iterate over columns */
foreach ($row as $cell) {
$text = $cell->children('text', true);
$cell_attrs = $cell->attributes('office', true);
if (count($text) != 0) {
$attr = $cell->attributes('table', true);
$num_repeat = (int) $attr['number-columns-repeated'];
$num_iterations = $num_repeat ? $num_repeat : 1;
for ($k = 0; $k < $num_iterations; $k++) {
if ($_REQUEST['ods_recognize_percentages']
&& ! strcmp('percentage', $cell_attrs['value-type'])
) {
$value = (double)$cell_attrs['value'];
} elseif ($_REQUEST['ods_recognize_currency']
&& !strcmp('currency', $cell_attrs['value-type'])
) {
$value = (double)$cell_attrs['value'];
} else {
/* We need to concatenate all paragraphs */
$values = array();
foreach ($text as $paragraph) {
$values[] = (string)$paragraph;
}
$value = implode("\n", $values);
}
if (! $col_names_in_first_row) {
$tempRow[] = $value;
} else {
$col_names[] = $value;
}
++$col_count;
}
} else {
/* Number of blank columns repeated */
if ($col_count < count($row->children('table', true)) - 1) {
$attr = $cell->attributes('table', true);
$num_null = (int)$attr['number-columns-repeated'];
if ($num_null) {
if (! $col_names_in_first_row) {
for ($i = 0; $i < $num_null; ++$i) {
$tempRow[] = 'NULL';
++$col_count;
}
} else {
for ($i = 0; $i < $num_null; ++$i) {
$col_names[] = PMA_getColumnAlphaName($col_count + 1);
++$col_count;
}
}
} else {
if (! $col_names_in_first_row) {
$tempRow[] = 'NULL';
} else {
$col_names[] = PMA_getColumnAlphaName($col_count + 1);
}
++$col_count;
}
}
}
}
/* Find the widest row */
if ($col_count > $max_cols) {
$max_cols = $col_count;
}
/* Don't include a row that is full of NULL values */
if (! $col_names_in_first_row) {
if ($_REQUEST['ods_empty_rows']) {
foreach ($tempRow as $cell) {
if (strcmp('NULL', $cell)) {
$tempRows[] = $tempRow;
break;
}
}
} else {
$tempRows[] = $tempRow;
}
}
$col_count = 0;
$col_names_in_first_row = false;
$tempRow = array();
}
}
/* Skip over empty sheets */
if (count($tempRows) == 0 || count($tempRows[0]) == 0) {
$col_names = array();
$tempRow = array();
$tempRows = array();
continue;
}
/**
* Fill out each row as necessary to make
* every one exactly as wide as the widest
* row. This included column names.
*/
/* Fill out column names */
for ($i = count($col_names); $i < $max_cols; ++$i) {
$col_names[] = PMA_getColumnAlphaName($i + 1);
}
/* Fill out all rows */
$num_rows = count($tempRows);
for ($i = 0; $i < $num_rows; ++$i) {
for ($j = count($tempRows[$i]); $j < $max_cols; ++$j) {
$tempRows[$i][] = 'NULL';
}
}
/* Store the table name so we know where to place the row set */
$tbl_attr = $sheet->attributes('table', true);
$tables[] = array((string)$tbl_attr['name']);
/* Store the current sheet in the accumulator */
$rows[] = array((string)$tbl_attr['name'], $col_names, $tempRows);
$tempRows = array();
$col_names = array();
$max_cols = 0;
}
unset($tempRow);
unset($tempRows);
unset($col_names);
unset($sheets);
unset($xml);
/**
* Bring accumulated rows into the corresponding table
*/
$num_tbls = count($tables);
for ($i = 0; $i < $num_tbls; ++$i) {
for ($j = 0; $j < count($rows); ++$j) {
if (! strcmp($tables[$i][TBL_NAME], $rows[$j][TBL_NAME])) {
if (! isset($tables[$i][COL_NAMES])) {
$tables[$i][] = $rows[$j][COL_NAMES];
}
$tables[$i][ROWS] = $rows[$j][ROWS];
}
}
}
/* No longer needed */
unset($rows);
/* Obtain the best-fit MySQL types for each column */
$analyses = array();
$len = count($tables);
for ($i = 0; $i < $len; ++$i) {
$analyses[] = PMA_analyzeTable($tables[$i]);
}
/**
* string $db_name (no backquotes)
*
* array $table = array(table_name, array() column_names, array()() rows)
* array $tables = array of "$table"s
*
* array $analysis = array(array() column_types, array() column_sizes)
* array $analyses = array of "$analysis"s
*
* array $create = array of SQL strings
*
* array $options = an associative array of options
*/
/* Set database name to the currently selected one, if applicable */
if (strlen($db)) {
$db_name = $db;
$options = array('create_db' => false);
} else {
$db_name = 'ODS_DB';
$options = null;
}
/* Non-applicable parameters */
$create = null;
/* Created and execute necessary SQL statements from data */
PMA_buildSQL($db_name, $tables, $analyses, $create, $options);
unset($tables);
unset($analyses);
/* Commit any possible data in buffers */
PMA_importRunQuery();
?>

View File

@@ -1,508 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* ESRI Shape file import plugin for phpMyAdmin
*
* @package PhpMyAdmin-Import
* @subpackage ESRI_Shape
*/
if (! defined('PHPMYADMIN')) {
exit;
}
// Drizzle does not suppost GIS data types
if (PMA_DRIZZLE) {
return;
}
if (isset($plugin_list)) {
$plugin_list['shp'] = array(
'text' => __('ESRI Shape File'),
'extension' => 'shp',
'options' => array(),
'options_text' => __('Options'),
);
} else {
if ((int) ini_get('memory_limit') < 512) {
@ini_set('memory_limit', '512M');
}
@set_time_limit(300);
// Append the bfShapeFiles directory to the include path variable
set_include_path(
get_include_path() . PATH_SEPARATOR . getcwd() . '/libraries/bfShapeFiles/'
);
include_once './libraries/bfShapeFiles/ShapeFile.lib.php';
$GLOBALS['finished'] = false;
$buffer = '';
$eof = false;
// Returns specified number of bytes from the buffer.
// Buffer automatically fetches next chunk of data when the buffer falls short.
// Sets $eof when $GLOBALS['finished'] is set and the buffer falls short.
function readFromBuffer($length)
{
global $buffer, $eof;
if (strlen($buffer) < $length) {
if ($GLOBALS['finished']) {
$eof = true;
} else {
$buffer .= PMA_importGetNextChunk();
}
}
$result = substr($buffer, 0, $length);
$buffer = substr($buffer, $length);
return $result;
}
/**
* This class extends ShapeFile class to cater the following phpMyAdmin
* specific requirements.
* 1) To load data from .dbf file only when the dBase extension is available.
* 2) To use PMA_importGetNextChunk() functionality to read data, rather than
* reading directly from a file. Using readFromBuffer() in place of fread().
* This makes it possible to use compressions.
*
* @package PhpMyAdmin-Import
* @subpackage ESRI_Shape
*/
class PMA_ShapeFile extends ShapeFile
{
/**
* Returns whether the 'dbase' extension is loaded
*
* @return boolean whether the 'dbase' extension is loaded
*/
function _isDbaseLoaded()
{
return extension_loaded('dbase');
}
/**
* Loads ESRI shape data from the imported file
*
* @param string $FileName not used, it's here only to match the method
* signature of the method being overidden
*
* @return void
* @see ShapeFile::loadFromFile()
*/
function loadFromFile($FileName)
{
$this->_loadHeaders();
$this->_loadRecords();
if ($this->_isDbaseLoaded()) {
$this->_closeDBFFile();
}
}
/**
* Loads metadata from the ESRI shape file header
*
* @return void
* @see ShapeFile::_loadHeaders()
*/
function _loadHeaders()
{
readFromBuffer(24);
$this->fileLength = loadData("N", readFromBuffer(4));
readFromBuffer(4);
$this->shapeType = loadData("V", readFromBuffer(4));
$this->boundingBox = array();
$this->boundingBox["xmin"] = loadData("d", readFromBuffer(8));
$this->boundingBox["ymin"] = loadData("d", readFromBuffer(8));
$this->boundingBox["xmax"] = loadData("d", readFromBuffer(8));
$this->boundingBox["ymax"] = loadData("d", readFromBuffer(8));
if ($this->_isDbaseLoaded() && $this->_openDBFFile()) {
$this->DBFHeader = $this->_loadDBFHeader();
}
}
/**
* Loads geometry data from the ESRI shape file
*
* @return void
* @see ShapeFile::_loadRecords()
*/
function _loadRecords()
{
global $eof;
readFromBuffer(32);
while (true) {
$record = new PMA_ShapeRecord(-1);
$record->loadFromFile($this->SHPFile, $this->DBFFile);
if ($record->lastError != "") {
return false;
}
if ($eof) {
break;
}
$this->records[] = $record;
}
}
}
/**
* This class extends ShapeRecord class to cater the following phpMyAdmin
* specific requirements.
* 1) To load data from .dbf file only when the dBase extension is available.
* 2) To use PMA_importGetNextChunk() functionality to read data, rather than
* reading directly from a file. Using readFromBuffer() in place of fread().
* This makes it possible to use compressions.
*
* @package PhpMyAdmin-Import
* @subpackage ESRI_Shape
*/
class PMA_ShapeRecord extends ShapeRecord
{
/**
* Loads a geometry data record from the file
*
* @param object &$SHPFile .shp file
* @param object &$DBFFile .dbf file
*
* @return void
* @see ShapeRecord::loadFromFile()
*/
function loadFromFile(&$SHPFile, &$DBFFile)
{
$this->DBFFile = $DBFFile;
$this->_loadHeaders();
switch ($this->shapeType) {
case 0:
$this->_loadNullRecord();
break;
case 1:
$this->_loadPointRecord();
break;
case 3:
$this->_loadPolyLineRecord();
break;
case 5:
$this->_loadPolygonRecord();
break;
case 8:
$this->_loadMultiPointRecord();
break;
default:
$this->setError(
sprintf(
__("Geometry type '%s' is not supported by MySQL."),
$this->shapeType
)
);
break;
}
if (extension_loaded('dbase') && isset($this->DBFFile)) {
$this->_loadDBFData();
}
}
/**
* Loads metadata from the ESRI shape record header
*
* @return void
* @see ShapeRecord::_loadHeaders()
*/
function _loadHeaders()
{
$this->recordNumber = loadData("N", readFromBuffer(4));
readFromBuffer(4);
$this->shapeType = loadData("V", readFromBuffer(4));
}
/**
* Loads data from a point record
*
* @return void
* @see ShapeRecord::_loadPoint()
*/
function _loadPoint()
{
$data = array();
$data["x"] = loadData("d", readFromBuffer(8));
$data["y"] = loadData("d", readFromBuffer(8));
return $data;
}
/**
* Loads data from a multipoint record
*
* @return void
* @see ShapeRecord::_loadMultiPointRecord()
*/
function _loadMultiPointRecord()
{
$this->SHPData = array();
$this->SHPData["xmin"] = loadData("d", readFromBuffer(8));
$this->SHPData["ymin"] = loadData("d", readFromBuffer(8));
$this->SHPData["xmax"] = loadData("d", readFromBuffer(8));
$this->SHPData["ymax"] = loadData("d", readFromBuffer(8));
$this->SHPData["numpoints"] = loadData("V", readFromBuffer(4));
for ($i = 0; $i <= $this->SHPData["numpoints"]; $i++) {
$this->SHPData["points"][] = $this->_loadPoint();
}
}
/**
* Loads data from a polyline record
*
* @return void
* @see ShapeRecord::_loadPolyLineRecord()
*/
function _loadPolyLineRecord()
{
$this->SHPData = array();
$this->SHPData["xmin"] = loadData("d", readFromBuffer(8));
$this->SHPData["ymin"] = loadData("d", readFromBuffer(8));
$this->SHPData["xmax"] = loadData("d", readFromBuffer(8));
$this->SHPData["ymax"] = loadData("d", readFromBuffer(8));
$this->SHPData["numparts"] = loadData("V", readFromBuffer(4));
$this->SHPData["numpoints"] = loadData("V", readFromBuffer(4));
for ($i = 0; $i < $this->SHPData["numparts"]; $i++) {
$this->SHPData["parts"][$i] = loadData("V", readFromBuffer(4));
}
$readPoints = 0;
reset($this->SHPData["parts"]);
while (list($partIndex, $partData) = each($this->SHPData["parts"])) {
if (! isset($this->SHPData["parts"][$partIndex]["points"])
|| !is_array($this->SHPData["parts"][$partIndex]["points"])
) {
$this->SHPData["parts"][$partIndex] = array();
$this->SHPData["parts"][$partIndex]["points"] = array();
}
while (! in_array($readPoints, $this->SHPData["parts"])
&& ($readPoints < ($this->SHPData["numpoints"]))
) {
$this->SHPData["parts"][$partIndex]["points"][]
= $this->_loadPoint();
$readPoints++;
}
}
}
}
$shp = new PMA_ShapeFile(1);
// If the zip archive has more than one file,
// get the correct content to the buffer from .shp file.
if ($compression == 'application/zip'
&& PMA_getNoOfFilesInZip($import_file) > 1
) {
$zip_content = PMA_getZipContents($import_file, '/^.*\.shp$/i');
$GLOBALS['import_text'] = $zip_content['data'];
}
$temp_dbf_file = false;
// We need dbase extension to handle .dbf file
if (extension_loaded('dbase')) {
// If we can extract the zip archive to 'TempDir'
// and use the files in it for import
if ($compression == 'application/zip'
&& ! empty($cfg['TempDir'])
&& is_writable($cfg['TempDir'])
) {
$dbf_file_name = PMA_findFileFromZipArchive(
'/^.*\.dbf$/i', $import_file
);
// If the corresponding .dbf file is in the zip archive
if ($dbf_file_name) {
// Extract the .dbf file and point to it.
$extracted = PMA_zipExtract(
$import_file,
realpath($cfg['TempDir']),
array($dbf_file_name)
);
if ($extracted) {
$dbf_file_path = realpath($cfg['TempDir'])
. (PMA_IS_WINDOWS ? '\\' : '/') . $dbf_file_name;
$temp_dbf_file = true;
// Replace the .dbf with .*, as required
// by the bsShapeFiles library.
$file_name = substr(
$dbf_file_path, 0, strlen($dbf_file_path) - 4
) . '.*';
$shp->FileName = $file_name;
}
}
} elseif (! empty($local_import_file)
&& ! empty($cfg['UploadDir'])
&& $compression == 'none'
) {
// If file is in UploadDir, use .dbf file in the same UploadDir
// to load extra data.
// Replace the .shp with .*,
// so the bsShapeFiles library correctly locates .dbf file.
$file_name = substr($import_file, 0, strlen($import_file) - 4) . '.*';
$shp->FileName = $file_name;
}
}
// Load data
$shp->loadFromFile('');
if ($shp->lastError != "") {
$error = true;
$message = PMA_Message::error(__('There was an error importing the ESRI shape file: "%s".'));
$message->addParam($shp->lastError);
return;
}
// Delete the .dbf file extracted to 'TempDir'
if ($temp_dbf_file) {
unlink($dbf_file_path);
}
$esri_types = array(
0 => 'Null Shape',
1 => 'Point',
3 => 'PolyLine',
5 => 'Polygon',
8 => 'MultiPoint',
11 => 'PointZ',
13 => 'PolyLineZ',
15 => 'PolygonZ',
18 => 'MultiPointZ',
21 => 'PointM',
23 => 'PolyLineM',
25 => 'PolygonM',
28 => 'MultiPointM',
31 => 'MultiPatch',
);
switch ($shp->shapeType) {
// ESRI Null Shape
case 0:
break;
// ESRI Point
case 1:
$gis_type = 'point';
break;
// ESRI PolyLine
case 3:
$gis_type = 'multilinestring';
break;
// ESRI Polygon
case 5:
$gis_type = 'multipolygon';
break;
// ESRI MultiPoint
case 8:
$gis_type = 'multipoint';
break;
default:
$error = true;
if (! isset($esri_types[$shp->shapeType])) {
$message = PMA_Message::error(__('You tried to import an invalid file or the imported file contains invalid data'));
} else {
$message = PMA_Message::error(__('MySQL Spatial Extension does not support ESRI type "%s".'));
$message->addParam($param);
}
return;
}
if (isset($gis_type)) {
include_once './libraries/gis/pma_gis_factory.php';
$gis_obj = PMA_GIS_Factory::factory($gis_type);
} else {
$gis_obj = null;
}
$num_rows = count($shp->records);
// If .dbf file is loaded, the number of extra data columns
$num_data_cols = isset($shp->DBFHeader) ? count($shp->DBFHeader) : 0;
$rows = array();
$col_names = array();
if ($num_rows != 0) {
foreach ($shp->records as $record) {
$tempRow = array();
if ($gis_obj == null) {
$tempRow[] = null;
} else {
$tempRow[] = "GeomFromText('"
. $gis_obj->getShape($record->SHPData) . "')";
}
if (isset($shp->DBFHeader)) {
foreach ($shp->DBFHeader as $c) {
$cell = trim($record->DBFData[$c[0]]);
if (! strcmp($cell, '')) {
$cell = 'NULL';
}
$tempRow[] = $cell;
}
}
$rows[] = $tempRow;
}
}
if (count($rows) == 0) {
$error = true;
$message = PMA_Message::error(__('The imported file does not contain any data'));
return;
}
// Column names for spatial column and the rest of the columns,
// if they are available
$col_names[] = 'SPATIAL';
for ($n = 0; $n < $num_data_cols; $n++) {
$col_names[] = $shp->DBFHeader[$n][0];
}
// Set table name based on the number of tables
if (strlen($db)) {
$result = PMA_DBI_fetch_result('SHOW TABLES');
$table_name = 'TABLE '.(count($result) + 1);
} else {
$table_name = 'TBL_NAME';
}
$tables = array(array($table_name, $col_names, $rows));
// Use data from shape file to chose best-fit MySQL types for each column
$analyses = array();
$analyses[] = PMA_analyzeTable($tables[0]);
$table_no = 0; $spatial_col = 0;
$analyses[$table_no][TYPES][$spatial_col] = GEOMETRY;
$analyses[$table_no][FORMATTEDSQL][$spatial_col] = true;
// Set database name to the currently selected one, if applicable
if (strlen($db)) {
$db_name = $db;
$options = array('create_db' => false);
} else {
$db_name = 'SHP_DB';
$options = null;
}
// Created and execute necessary SQL statements from data
$null_param = null;
PMA_buildSQL($db_name, $tables, $analyses, $null_param, $options);
unset($tables);
unset($analyses);
$finished = true;
$error = false;
// Commit any possible data in buffers
PMA_importRunQuery();
}
?>

View File

@@ -1,346 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* SQL import plugin for phpMyAdmin
*
* @package PhpMyAdmin-Import
* @subpackage SQL
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
*
*/
if (isset($plugin_list)) {
$plugin_list['sql'] = array(
'text' => __('SQL'),
'extension' => 'sql',
'options_text' => __('Options'),
);
$compats = PMA_DBI_getCompatibilities();
if (count($compats) > 0) {
$values = array();
foreach ($compats as $val) {
$values[$val] = $val;
}
$plugin_list['sql']['options'] = array(
array('type' => 'begin_group', 'name' => 'general_opts'),
array(
'type' => 'select',
'name' => 'compatibility',
'text' => __('SQL compatibility mode:'),
'values' => $values,
'doc' => array(
'manual_MySQL_Database_Administration',
'Server_SQL_mode',
),
),
array(
'type' => 'bool',
'name' => 'no_auto_value_on_zero',
'text' => __('Do not use <code>AUTO_INCREMENT</code> for zero values'),
'doc' => array(
'manual_MySQL_Database_Administration',
'Server_SQL_mode',
'sqlmode_no_auto_value_on_zero'
),
),
array('type' => 'end_group'),
);
}
/* We do not define function when plugin is just queried for information above */
return;
}
$buffer = '';
// Defaults for parser
$sql = '';
$start_pos = 0;
$i = 0;
$len= 0;
$big_value = 2147483647;
$delimiter_keyword = 'DELIMITER '; // include the space because it's mandatory
$length_of_delimiter_keyword = strlen($delimiter_keyword);
if (isset($_POST['sql_delimiter'])) {
$sql_delimiter = $_POST['sql_delimiter'];
} else {
$sql_delimiter = ';';
}
// Handle compatibility options
$sql_modes = array();
if (isset($_REQUEST['sql_compatibility'])
&& 'NONE' != $_REQUEST['sql_compatibility']
) {
$sql_modes[] = $_REQUEST['sql_compatibility'];
}
if (isset($_REQUEST['sql_no_auto_value_on_zero'])) {
$sql_modes[] = 'NO_AUTO_VALUE_ON_ZERO';
}
if (count($sql_modes) > 0) {
PMA_DBI_try_query('SET SQL_MODE="' . implode(',', $sql_modes) . '"');
}
unset($sql_modes);
/**
* will be set in PMA_importGetNextChunk()
*
* @global boolean $GLOBALS['finished']
*/
$GLOBALS['finished'] = false;
while (! ($GLOBALS['finished'] && $i >= $len) && ! $error && ! $timeout_passed) {
$data = PMA_importGetNextChunk();
if ($data === false) {
// subtract data we didn't handle yet and stop processing
$offset -= strlen($buffer);
break;
} elseif ($data === true) {
// Handle rest of buffer
} else {
// Append new data to buffer
$buffer .= $data;
// free memory
unset($data);
// Do not parse string when we're not at the end and don't have ; inside
if ((strpos($buffer, $sql_delimiter, $i) === false)
&& ! $GLOBALS['finished']
) {
continue;
}
}
// Current length of our buffer
$len = strlen($buffer);
// Grab some SQL queries out of it
while ($i < $len) {
$found_delimiter = false;
// Find first interesting character
$old_i = $i;
// this is about 7 times faster that looking for each sequence i
// one by one with strpos()
$match = preg_match(
'/(\'|"|#|-- |\/\*|`|(?i)(?<![A-Z0-9_])' . $delimiter_keyword . ')/',
$buffer,
$matches,
PREG_OFFSET_CAPTURE,
$i
);
if ($match) {
// in $matches, index 0 contains the match for the complete
// expression but we don't use it
$first_position = $matches[1][1];
} else {
$first_position = $big_value;
}
/**
* @todo we should not look for a delimiter that might be
* inside quotes (or even double-quotes)
*/
// the cost of doing this one with preg_match() would be too high
$first_sql_delimiter = strpos($buffer, $sql_delimiter, $i);
if ($first_sql_delimiter === false) {
$first_sql_delimiter = $big_value;
} else {
$found_delimiter = true;
}
// set $i to the position of the first quote,
// comment.start or delimiter found
$i = min($first_position, $first_sql_delimiter);
if ($i == $big_value) {
// none of the above was found in the string
$i = $old_i;
if (!$GLOBALS['finished']) {
break;
}
// at the end there might be some whitespace...
if (trim($buffer) == '') {
$buffer = '';
$len = 0;
break;
}
// We hit end of query, go there!
$i = strlen($buffer) - 1;
}
// Grab current character
$ch = $buffer[$i];
// Quotes
if (strpos('\'"`', $ch) !== false) {
$quote = $ch;
$endq = false;
while (!$endq) {
// Find next quote
$pos = strpos($buffer, $quote, $i + 1);
/*
* Behave same as MySQL and accept end of query as end of backtick.
* I know this is sick, but MySQL behaves like this:
*
* SELECT * FROM `table
*
* is treated like
*
* SELECT * FROM `table`
*/
if ($pos === false && $quote == '`' && $found_delimiter) {
$pos = $first_sql_delimiter - 1;
} elseif ($pos === false) { // No quote? Too short string
// We hit end of string => unclosed quote,
// but we handle it as end of query
if ($GLOBALS['finished']) {
$endq = true;
$i = $len - 1;
}
$found_delimiter = false;
break;
}
// Was not the quote escaped?
$j = $pos - 1;
while ($buffer[$j] == '\\') {
$j--;
}
// Even count means it was not escaped
$endq = (((($pos - 1) - $j) % 2) == 0);
// Skip the string
$i = $pos;
if ($first_sql_delimiter < $pos) {
$found_delimiter = false;
}
}
if (!$endq) {
break;
}
$i++;
// Aren't we at the end?
if ($GLOBALS['finished'] && $i == $len) {
$i--;
} else {
continue;
}
}
// Not enough data to decide
if ((($i == ($len - 1) && ($ch == '-' || $ch == '/'))
|| ($i == ($len - 2) && (($ch == '-' && $buffer[$i + 1] == '-')
|| ($ch == '/' && $buffer[$i + 1] == '*')))) && !$GLOBALS['finished']
) {
break;
}
// Comments
if ($ch == '#'
|| ($i < ($len - 1) && $ch == '-' && $buffer[$i + 1] == '-'
&& (($i < ($len - 2) && $buffer[$i + 2] <= ' ')
|| ($i == ($len - 1) && $GLOBALS['finished'])))
|| ($i < ($len - 1) && $ch == '/' && $buffer[$i + 1] == '*')
) {
// Copy current string to SQL
if ($start_pos != $i) {
$sql .= substr($buffer, $start_pos, $i - $start_pos);
}
// Skip the rest
$start_of_comment = $i;
// do not use PHP_EOL here instead of "\n", because the export
// file might have been produced on a different system
$i = strpos($buffer, $ch == '/' ? '*/' : "\n", $i);
// didn't we hit end of string?
if ($i === false) {
if ($GLOBALS['finished']) {
$i = $len - 1;
} else {
break;
}
}
// Skip *
if ($ch == '/') {
$i++;
}
// Skip last char
$i++;
// We need to send the comment part in case we are defining
// a procedure or function and comments in it are valuable
$sql .= substr($buffer, $start_of_comment, $i - $start_of_comment);
// Next query part will start here
$start_pos = $i;
// Aren't we at the end?
if ($i == $len) {
$i--;
} else {
continue;
}
}
// Change delimiter, if redefined, and skip it (don't send to server!)
if (strtoupper(substr($buffer, $i, $length_of_delimiter_keyword)) == $delimiter_keyword
&& ($i + $length_of_delimiter_keyword < $len)
) {
// look for EOL on the character immediately after 'DELIMITER '
// (see previous comment about PHP_EOL)
$new_line_pos = strpos($buffer, "\n", $i + $length_of_delimiter_keyword);
// it might happen that there is no EOL
if (false === $new_line_pos) {
$new_line_pos = $len;
}
$sql_delimiter = substr(
$buffer,
$i + $length_of_delimiter_keyword,
$new_line_pos - $i - $length_of_delimiter_keyword
);
$i = $new_line_pos + 1;
// Next query part will start here
$start_pos = $i;
continue;
}
// End of SQL
if ($found_delimiter || ($GLOBALS['finished'] && ($i == $len - 1))) {
$tmp_sql = $sql;
if ($start_pos < $len) {
$length_to_grab = $i - $start_pos;
if (! $found_delimiter) {
$length_to_grab++;
}
$tmp_sql .= substr($buffer, $start_pos, $length_to_grab);
unset($length_to_grab);
}
// Do not try to execute empty SQL
if (! preg_match('/^([\s]*;)*$/', trim($tmp_sql))) {
$sql = $tmp_sql;
PMA_importRunQuery(
$sql,
substr($buffer, 0, $i + strlen($sql_delimiter))
);
$buffer = substr($buffer, $i + strlen($sql_delimiter));
// Reset parser:
$len = strlen($buffer);
$sql = '';
$i = 0;
$start_pos = 0;
// Any chance we will get a complete query?
//if ((strpos($buffer, ';') === false) && !$GLOBALS['finished']) {
if (strpos($buffer, $sql_delimiter) === false
&& ! $GLOBALS['finished']
) {
break;
}
} else {
$i++;
$start_pos = $i;
}
}
} // End of parser loop
} // End of import loop
// Commit any possible data in buffers
PMA_importRunQuery('', substr($buffer, 0, $len));
PMA_importRunQuery();
?>

View File

@@ -1,67 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
*
* @package PhpMyAdmin
*/
if (! defined('PHPMYADMIN')) {
exit;
}
$ID_KEY = 'APC_UPLOAD_PROGRESS';
/**
* Returns upload status.
*
* This is implementation for APC extension.
*
* @param string $id
*
* @return array|null
*/
function PMA_getUploadStatus($id)
{
global $SESSION_KEY;
global $ID_KEY;
if (trim($id) == "") {
return null;
}
if (! array_key_exists($id, $_SESSION[$SESSION_KEY])) {
$_SESSION[$SESSION_KEY][$id] = array(
'id' => $id,
'finished' => false,
'percent' => 0,
'total' => 0,
'complete' => 0,
'plugin' => $ID_KEY
);
}
$ret = $_SESSION[$SESSION_KEY][$id];
if (! PMA_import_apcCheck() || $ret['finished']) {
return $ret;
}
$status = apc_fetch('upload_' . $id);
if ($status) {
$ret['finished'] = (bool)$status['done'];
$ret['total'] = $status['total'];
$ret['complete'] = $status['current'];
if ($ret['total'] > 0) {
$ret['percent'] = $ret['complete'] / $ret['total'] * 100;
}
if ($ret['percent'] == 100) {
$ret['finished'] = (bool)true;
}
$_SESSION[$SESSION_KEY][$id] = $ret;
}
return $ret;
}
?>

View File

@@ -1,45 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
*
* @package PhpMyAdmin
*/
if (! defined('PHPMYADMIN')) {
exit;
}
$ID_KEY = 'noplugin';
/**
* Returns upload status.
*
* This is implementation when no webserver support exists,
* so it returns just zeroes.
*
* @param string $id
* @return array|null
*/
function PMA_getUploadStatus($id)
{
global $SESSION_KEY;
global $ID_KEY;
if (trim($id) == "") {
return null;
}
if (! array_key_exists($id, $_SESSION[$SESSION_KEY])) {
$_SESSION[$SESSION_KEY][$id] = array(
'id' => $id,
'finished' => false,
'percent' => 0,
'total' => 0,
'complete' => 0,
'plugin' => $ID_KEY
);
}
$ret = $_SESSION[$SESSION_KEY][$id];
return $ret;
}
?>

View File

@@ -1,77 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
*
* @package PhpMyAdmin
*/
if (! defined('PHPMYADMIN')) {
exit;
}
$ID_KEY = ini_get('session.upload_progress.name');
/**
* Returns upload status.
*
* This is implementation for session.upload_progress in PHP 5.4+.
*
* @param string $id
*
* @return array|null
*/
function PMA_getUploadStatus($id)
{
global $SESSION_KEY;
global $ID_KEY;
if (trim($id) == '') {
return null;
}
if (! array_key_exists($id, $_SESSION[$SESSION_KEY])) {
$_SESSION[$SESSION_KEY][$id] = array(
'id' => $id,
'finished' => false,
'percent' => 0,
'total' => 0,
'complete' => 0,
'plugin' => $ID_KEY
);
}
$ret = $_SESSION[$SESSION_KEY][$id];
if (! PMA_import_sessionCheck() || $ret['finished']) {
return $ret;
}
$status = false;
$sessionkey = ini_get('session.upload_progress.prefix') . $id;
if (isset($_SESSION[$sessionkey])) {
$status = $_SESSION[$sessionkey];
}
if ($status) {
$ret['finished'] = $status['done'];
$ret['total'] = $status['content_length'];
$ret['complete'] = $status['bytes_processed'];
if ($ret['total'] > 0) {
$ret['percent'] = $ret['complete'] / $ret['total'] * 100;
}
} else {
$ret = array(
'id' => $id,
'finished' => true,
'percent' => 100,
'total' => $ret['total'],
'complete' => $ret['total'],
'plugin' => $ID_KEY
);
}
$_SESSION[$SESSION_KEY][$id] = $ret;
return $ret;
}
?>

View File

@@ -1,76 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
*
* @package PhpMyAdmin
*/
if (! defined('PHPMYADMIN')) {
exit;
}
$ID_KEY = "UPLOAD_IDENTIFIER";
/**
* Returns upload status.
*
* This is implementation for uploadprogress extension.
*
* @param string $id
*
* @return array|null
*/
function PMA_getUploadStatus($id)
{
global $SESSION_KEY;
global $ID_KEY;
if (trim($id) == "") {
return null;
}
if (! array_key_exists($id, $_SESSION[$SESSION_KEY])) {
$_SESSION[$SESSION_KEY][$id] = array(
'id' => $id,
'finished' => false,
'percent' => 0,
'total' => 0,
'complete' => 0,
'plugin' => $ID_KEY
);
}
$ret = $_SESSION[$SESSION_KEY][$id];
if (! PMA_import_uploadprogressCheck() || $ret['finished']) {
return $ret;
}
$status = uploadprogress_get_info($id);
if ($status) {
if ($status['bytes_uploaded'] == $status['bytes_total']) {
$ret['finished'] = true;
} else {
$ret['finished'] = false;
}
$ret['total'] = $status['bytes_total'];
$ret['complete'] = $status['bytes_uploaded'];
if ($ret['total'] > 0) {
$ret['percent'] = $ret['complete'] / $ret['total'] * 100;
}
} else {
$ret = array(
'id' => $id,
'finished' => true,
'percent' => 100,
'total' => $ret['total'],
'complete' => $ret['total'],
'plugin' => $ID_KEY
);
}
$_SESSION[$SESSION_KEY][$id] = $ret;
return $ret;
}
?>

View File

@@ -1,318 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* XML import plugin for phpMyAdmin
*
* @todo Improve efficiency
* @package PhpMyAdmin-Import
* @subpackage XML
*/
if (! defined('PHPMYADMIN')) {
exit;
}
/**
* We need way to disable external XML entities processing.
*/
if (!function_exists('libxml_disable_entity_loader')) {
return;
}
/**
* The possible scopes for $plugin_param are: 'table', 'database', and 'server'
*/
if (isset($plugin_list)) {
$plugin_list['xml'] = array(
'text' => __('XML'),
'extension' => 'xml',
'options' => array(
),
'options_text' => __('Options'),
);
/* We do not define function when plugin is just queried for information above */
return;
}
$i = 0;
$len = 0;
$buffer = "";
/**
* Read in the file via PMA_importGetNextChunk so that
* it can process compressed files
*/
while (! ($finished && $i >= $len) && ! $error && ! $timeout_passed) {
$data = PMA_importGetNextChunk();
if ($data === false) {
/* subtract data we didn't handle yet and stop processing */
$offset -= strlen($buffer);
break;
} elseif ($data === true) {
/* Handle rest of buffer */
} else {
/* Append new data to buffer */
$buffer .= $data;
unset($data);
}
}
unset($data);
/**
* Disable loading of external XML entities.
*/
libxml_disable_entity_loader();
/**
* Load the XML string
*
* The option LIBXML_COMPACT is specified because it can
* result in increased performance without the need to
* alter the code in any way. It's basically a freebee.
*/
$xml = simplexml_load_string($buffer, "SimpleXMLElement", LIBXML_COMPACT);
unset($buffer);
/**
* The XML was malformed
*/
if ($xml === false) {
PMA_Message::error(__('The XML file specified was either malformed or incomplete. Please correct the issue and try again.'))->display();
unset($xml);
$GLOBALS['finished'] = false;
return;
}
/**
* Table accumulator
*/
$tables = array();
/**
* Row accumulator
*/
$rows = array();
/**
* Temp arrays
*/
$tempRow = array();
$tempCells = array();
/**
* CREATE code included (by default: no)
*/
$struct_present = false;
/**
* Analyze the data in each table
*/
$namespaces = $xml->getNameSpaces(true);
/**
* Get the database name, collation and charset
*/
$db_attr = $xml->children($namespaces['pma'])->{'structure_schemas'}->{'database'};
if ($db_attr instanceof SimpleXMLElement) {
$db_attr = $db_attr->attributes();
$db_name = (string)$db_attr['name'];
$collation = (string)$db_attr['collation'];
$charset = (string)$db_attr['charset'];
} else {
/**
* If the structure section is not present
* get the database name from the data section
*/
$db_attr = $xml->children()->attributes();
$db_name = (string)$db_attr['name'];
$collation = null;
$charset = null;
}
/**
* The XML was malformed
*/
if ($db_name === null) {
PMA_Message::error(__('The XML file specified was either malformed or incomplete. Please correct the issue and try again.'))->display();
unset($xml);
$GLOBALS['finished'] = false;
return;
}
/**
* Retrieve the structure information
*/
if (isset($namespaces['pma'])) {
/**
* Get structures for all tables
*/
$struct = $xml->children($namespaces['pma']);
$create = array();
foreach ($struct as $tier1 => $val1) {
foreach ($val1 as $tier2 => $val2) {
// Need to select the correct database for the creation of tables,
// views, triggers, etc.
/**
* @todo Generating a USE here blocks importing of a table
* into another database.
*/
$attrs = $val2->attributes();
$create[] = "USE " . PMA_backquote($attrs["name"]);
foreach ($val2 as $val3) {
/**
* Remove the extra cosmetic spacing
*/
$val3 = str_replace(" ", "", (string)$val3);
$create[] = $val3;
}
}
}
$struct_present = true;
}
/**
* Move down the XML tree to the actual data
*/
$xml = $xml->children()->children();
$data_present = false;
/**
* Only attempt to analyze/collect data if there is data present
*/
if ($xml && @$xml->count()) {
$data_present = true;
/**
* Process all database content
*/
foreach ($xml as $k1 => $v1) {
$tbl_attr = $v1->attributes();
$isInTables = false;
for ($i = 0; $i < count($tables); ++$i) {
if (! strcmp($tables[$i][TBL_NAME], (string)$tbl_attr['name'])) {
$isInTables = true;
break;
}
}
if ($isInTables == false) {
$tables[] = array((string)$tbl_attr['name']);
}
foreach ($v1 as $k2 => $v2) {
$row_attr = $v2->attributes();
if (! array_search((string)$row_attr['name'], $tempRow)) {
$tempRow[] = (string)$row_attr['name'];
}
$tempCells[] = (string)$v2;
}
$rows[] = array((string)$tbl_attr['name'], $tempRow, $tempCells);
$tempRow = array();
$tempCells = array();
}
unset($tempRow);
unset($tempCells);
unset($xml);
/**
* Bring accumulated rows into the corresponding table
*/
$num_tbls = count($tables);
for ($i = 0; $i < $num_tbls; ++$i) {
for ($j = 0; $j < count($rows); ++$j) {
if (! strcmp($tables[$i][TBL_NAME], $rows[$j][TBL_NAME])) {
if (! isset($tables[$i][COL_NAMES])) {
$tables[$i][] = $rows[$j][COL_NAMES];
}
$tables[$i][ROWS][] = $rows[$j][ROWS];
}
}
}
unset($rows);
if (! $struct_present) {
$analyses = array();
$len = count($tables);
for ($i = 0; $i < $len; ++$i) {
$analyses[] = PMA_analyzeTable($tables[$i]);
}
}
}
unset($xml);
unset($tempRows);
unset($tempCells);
unset($rows);
/**
* Only build SQL from data if there is data present
*/
if ($data_present) {
/**
* Set values to NULL if they were not present
* to maintain PMA_buildSQL() call integrity
*/
if (! isset($analyses)) {
$analyses = null;
if (! $struct_present) {
$create = null;
}
}
}
/**
* string $db_name (no backquotes)
*
* array $table = array(table_name, array() column_names, array()() rows)
* array $tables = array of "$table"s
*
* array $analysis = array(array() column_types, array() column_sizes)
* array $analyses = array of "$analysis"s
*
* array $create = array of SQL strings
*
* array $options = an associative array of options
*/
/* Set database name to the currently selected one, if applicable */
if (strlen($db)) {
/* Override the database name in the XML file, if one is selected */
$db_name = $db;
$options = array('create_db' => false);
} else {
if ($db_name === null) {
$db_name = 'XML_DB';
}
/* Set database collation/charset */
$options = array(
'db_collation' => $collation,
'db_charset' => $charset,
);
}
/* Created and execute necessary SQL statements from data */
PMA_buildSQL($db_name, $tables, $analyses, $create, $options);
unset($analyses);
unset($tables);
unset($create);
/* Commit any possible data in buffers */
PMA_importRunQuery();
?>

Some files were not shown because too many files have changed in this diff Show More