Merge branch 'MAINT_4_5_0' into STABLE

This commit is contained in:
Marc Delisle 2015-09-23 06:14:04 -04:00
commit 3050932bf2
1068 changed files with 502131 additions and 381312 deletions

3
.gitignore vendored
View File

@ -45,3 +45,6 @@ phpunit.xml
/.pydevproject
# Ant cache
cache.properties
# Composer
composer.lock
/vendor/

View File

@ -6,10 +6,9 @@
language: php
php:
- "7.0"
- "5.6"
- "5.5"
- "5.4"
- "5.3"
- hhvm
- nightly
@ -61,6 +60,8 @@ matrix:
env: PHPUNIT_ARGS="--exclude-group selenium"
- php: nightly
env: PHPUNIT_ARGS="--exclude-group selenium"
- php: "7.0"
env: PHPUNIT_ARGS="--exclude-group selenium"
fast_finish: true
include:
- php: 5.6

View File

@ -4,6 +4,15 @@ As an open source project, phpMyAdmin welcomes contributions of many forms.
## Bug reporting
We appreciate your effort to improve phpMyAdmin by submitting a bug report. Before doing so, please check the following things:
1. Check whether the bug you face **hasn't been already reported**. Duplicate reports takes us time, that we could be used to fix other bugs or make improvements.
2. Specify the phpMyAdmin, server, PHP, MySQL and browser information that may be helpful to fix the problem, especially exact **version numbers**.
3. If you got some error, please **describe what happened** and add error message. Reports like "I get error when I clicked on some link." are useless.
4. Provide easy steps to reproduce and if possible include your table structure (``SHOW CREATE TABLE `tbl_name```); if your problem implies specific data, attach a small export file for sample rows.
5. **Security problems** should not be reported here. See [our security page](https://www.phpmyadmin.net/security/).
Thanks for your help!
Please report [bugs on GitHub][1].
[1]: https://github.com/phpmyadmin/phpmyadmin/issues/new

111
ChangeLog
View File

@ -1,7 +1,107 @@
phpMyAdmin - ChangeLog
======================
4.4.15.0 (2015-09-20)
4.5.0.0 (2015-09-23)
+ rfe Pagination for GIS visualization
+ issue #6207 Usability improvements for console
+ issue #6310 Access to Add columns text-box and Go button when creating table
+ issue #6007 Add lock tables, disable keys options
+ issue #6306 Additional page locking
+ issue #6314 Support MySQL 5.7 syntax for password change
+ issue #6319 Display/edit index name
+ issue #6318 Toggle autocomplete of table and column names
+ issue #5633 Manage multiple variable in bookmarked query
+ issue #5642 Show edit/delete also when there is calculated column
+ issue #6313 Show databases as list instead of as dropdown when no database is selected
+ rfe Optional dark theme for the console
+ issue #5053 PDF schema sort options
+ issue #5543 Structure in PDF export
+ issue #6327 Have ZeroConf create phpmyadmin DB if possible
+ issue #5462 Warning before silent data conversion/truncation
+ issue #6338 Support a default page in designer
+ issue #6339 Allow copying mutiple rows
+ issue #6334 No SQL query for loading data
+ issue #6341 New data validation feature and datetime type
+ issue #6324 Importing and exporting pMA meta-data
+ issue #6330 Add grouping to stored procedures in the navigation tree
+ issue #6275 Support IPv6 browser transformation
+ rfe Option groups for 'With selected' dropdown in database structure page
+ issue #6347 Support CHECKSUM TABLE operation
+ issue #6088 Support for Paramaters with raw SQL
+ issue #5844 Show original size of truncated columns
+ issue #6114 Explain analyzer
+ issue #6186 Add "Drop partition" option to partition tools
+ issue #6354 Procedures window shift-click should select multiple rows
+ issue #6355 Designer: "Sticky" menu option
+ issue #6357 Directly show table comments in structure view
+ issue #6259 Page-related settings
+ issue #5356 Alter privileges when renaming or copying a database
- issue #11256 Slowness due to large number of routines
- issue #11258 GROUP_CONCAT shown as GROUPBY_CONCAT in CodeMirror autocomplete
+ issue #5946 Work with --skip-grant-tables
- issue #11266 "Sort by key" drop-down value is lost
+ issue #6287 Browse: improve display of right-aligned data
- issue #11265 Textarea rows settings ignored Features > Text fields
+ issue #6358 MIME types should be lower case
- issue #11226 Drop table doesn't remove the table name from navigation bar
+ issue #6360 MySQL and MariaDB functions INET6_ATON and INET6_NTOA
- bug Link to get real row counts of all the views in a db, at once
- issue #11275 Drizzle version numbers
+ issue #5400 Rewrite print view using CSS; fixes print view failures on multi-query statements
+ issue #6362 Support spatial indexes in table create form
+ issue #6068 Use CTRL or ALT plus arrow keys for navigation in grid editor
+ rfe Remove support for Shift + Click on function name to apply to all rows in insert/edit page
+ issue #6326 Don't group tables in tree if the result has only one group
- issue #11287 When hide table structure actions is false, action should be in a row
+ issue #5425 Batch changing the collation of each column in a table
- issue #10918 QBE generates wrong query
+ issue #6292 Use plain English descriptors instead of script names for icon link destinations
+ issue #6239 Disable foreign key checks for some operations
- issue #11296 "With selected" links doesn't work in table browse
- issue #11166 Query builder: missing joint for the intermediary table
+ issue #6251 Integrate SQL debugging into console
- issue #11061 Improve/restore non-unique index row editing
- issue #11301 MySQL errors are not shown when DebugSQL is enabled
+ issue #5037 One file per table and one file per database export option
+ issue #5759 Designer settings should be part of saved state
+ issue #6257 Option to remove functions, procedures, etc., from navigation tree
+ issue #5388 Column privileges and update
+ issue #6231 Cant use external config file
+ issue #6252 CSV import: Allow "Columns escaped with" to be optional
+ issue #6262 Being able to use multiple servers at the same time when using cookie auth
+ issue #6301 select structure or data for each table when exporting
- issue #11261 Autocomplete completes the original table name when joining multiple aliased tables
+ rfe Remove configuration storage data related to a user upon deleting the user
+ issue #6298 Improved processlist for mariadb
+ issue #6300 Warn about "Any user" potential problem
+ issue #6368 Hide/disable edit links for read-only variables
+ issue #6365 Human readable/writable URLs (html5 api)
+ rfe Support virtual columns in MySQL 5.7.5+
+ issue #6215 Support for virtual/persistent columns in MariaDB
- issue #11314 Undefined <feature>work upon upgrade to new version
- issue #1817 Creating configuration storage tables fail in MySQL 5.7
- issue #6118 Parser does not handle nested selects
- issue #5437 Support SELECT ... FROM DUAL
- issue #4962 Support UNION
- issue #11322 Missing null checkbox when grid editing a null cell
+ Upgrade TCPDF to version 6.2.9
+ issue #6102 Add SHA256 security password support
- issue #10250 Displayed git revision info is not set
+ Improved schema SVG export
- issue #10726 Do not try to set port 80 for https requests
+ issue #11394 Export/import Designer view
+ Partition support in table Structure
+ issue #11414 Unclear export options / organization / hierarchy
Set minimum required PHP version to 5.5 (older versions are EOL)
- issue #11407 ALTER TABLE failing on import when table exists
- issue Do not export `sys` database when exporting server
- issue #11436 CREATE DATABASE should be enabled by default on server exports
- issue #11442 MySQL 5.7 and SHOW VARIABLES
- issue #11445 MySQL 5.7 and Status page for an unprivileged user
- issue #11448 Clarify doc about the MemoryLimit directive
- issue #11489 Cannot copy a database under certain conditions
4.4.15.0 (not yet released)
- issue #11411 Undefined "replace" function on numeric scalar
- issue #11421 Stored-proc / routine - broken parameter parsing
- issue Missing name for configuration read_as_multibytes
@ -12,8 +112,6 @@ phpMyAdmin - ChangeLog
- issue #11458 Invalid UTF-8 sequence in argument
- issue #11457 Request URI too large
- issue Invalid argument supplied for foreach()
- issue #11461 Foreign key constraints for InnoDB tables with upper-case letters disabled
- issue #11487 Warning when entering Query page
4.4.14.1 (2015-09-08)
- issue [security] reCaptcha bypass
@ -149,8 +247,8 @@ phpMyAdmin - ChangeLog
4.4.3.0 (2015-04-20)
- bug #4851 PHP errors in login dialogue
- bug #4845 White screen (Cloudflare)
- bug #4207 json_encode error due to strftime returning non utf8 chars in Windows 8.1 Chinese version
- bug #4845 White screen (Cloudflare)
- bug #4794 Server error viewing table content
- bug Fix issues related to number of decimal places in time
- bug #4853 Relation view between 1600 and 1780 px
@ -289,10 +387,7 @@ explanation
4.3.11.1 (2015-03-04)
- bug [security] Risk of BREACH attack, see PMASA-2015-1
4.3.11.1 (not yet released)
- bug [security] Risk of BREACH attack, see PMASA-2015-1
4.3.11.0 (not yet released)
4.3.11.0 (2015-03-02)
- bug #4774 SQL links are completely wrong
- bug #4768 MariaDB: version mismatch
- bug #4777 Some images are missing in Designer for original theme

39
LICENSE
View File

@ -1,12 +1,12 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
@ -15,7 +15,7 @@ software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
@ -55,8 +55,8 @@ patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
@ -110,7 +110,7 @@ above, provided that you also meet all of these conditions:
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
@ -168,7 +168,7 @@ access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
@ -225,7 +225,7 @@ impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
@ -255,7 +255,7 @@ make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
@ -277,9 +277,9 @@ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
@ -303,10 +303,9 @@ the "copyright" line and a pointer to where the full notice is found.
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
@ -336,5 +335,5 @@ necessary. Here is a sample; alter the names:
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

View File

@ -76,5 +76,3 @@ class PMAStandard_Sniffs_Files_SpacesAroundConcatSniff implements PHP_CodeSniffe
}//end class
// }}}
?>

View File

@ -9,12 +9,6 @@
<exclude name="PEAR.Commenting.FunctionComment" />
<exclude name="Generic.Commenting.DocComment" />
</rule>
<rule ref="Generic.Files.LineLength">
<properties>
<property name="lineLimit" value="85"/>
<property name="absoluteLineLimit" value="0"/>
</properties>
</rule>
<rule ref="Generic.Metrics.NestingLevel" />
<!-- There MUST NOT be trailing whitespace at the end of lines. -->
<rule ref="Squiz.WhiteSpace.SuperfluousWhitespace" />

2
README
View File

@ -1,7 +1,7 @@
phpMyAdmin - Readme
===================
Version 4.4.15
Version 4.5.0
A set of PHP-scripts to manage MySQL over the web.

View File

@ -58,4 +58,3 @@ $html = PMA_getHtmlForRelationalFieldSelection(
);
$response->addHtml($html);
?>

View File

@ -55,7 +55,7 @@
<arg line="${source_comma_sep}
xml
codesize,design,naming,unusedcode
--exclude test,build,tcpdf,php-gettext,bfShapeFiles,PMAStandard,phpseclib,recaptchalib.php,swekey.php,vendor
--exclude test,build,tcpdf,php-gettext,bfShapeFiles,PMAStandard,phpseclib,recaptchalib.php,swekey.php,vendor,sql-parser
--reportfile '${basedir}/build/logs/pmd.xml'" />
</exec>
</target>
@ -71,8 +71,9 @@
--exclude libraries/php-gettext
--exclude libraries/bfShapeFiles
--exclude libraries/phpseclib
--exclude libraries/plugins/auth/recaptchalib.php
--exclude libraries/plugins/auth/recaptcha/recaptchalib.php
--exclude libraries/plugins/auth/swekey/swekey.php
--exclude libraries/sql-parser
${source}" />
</exec>
</target>
@ -88,8 +89,9 @@
--exclude libraries/php-gettext
--exclude libraries/bfShapeFiles
--exclude libraries/phpseclib
--exclude libraries/plugins/auth/recaptchalib.php
--exclude libraries/plugins/auth/recaptcha/recaptchalib.php
--exclude libraries/plugins/auth/swekey/swekey.php
--exclude libraries/sql-parser
${source}" />
</exec>
</target>
@ -97,7 +99,7 @@
<target name="phpcs" description="Generate checkstyle.xml using PHP_CodeSniffer excluding third party libraries">
<exec executable="phpcs">
<arg line="
--ignore=*/php-gettext/*,*/vendor/*,*/tcpdf/*,*/canvg/*,*/codemirror/*,*/openlayers/*,*/jquery/*,*/jqplot/*,*/build/*,*/bfShapeFiles/*,*/PMAStandard/*,*/phpseclib/*,*/recaptchalib.php,*/swekey.php
--ignore=*/php-gettext/*,*/vendor/*,*/tcpdf/*,*/canvg/*,*/codemirror/*,*/openlayers/*,*/jquery/*,*/jqplot/*,*/build/*,*/bfShapeFiles/*,*/PMAStandard/*,*/phpseclib/*,*/recaptcha/*,*/swekey/*,*/sql-parser/*
--report=checkstyle
--extensions=php
--report-file='${basedir}/build/logs/checkstyle.xml'

View File

@ -33,7 +33,10 @@ if (is_readable($filename)) {
}
} else {
printf(
__('The %s file is not available on this system, please visit www.phpmyadmin.net for more information.'),
__(
'The %s file is not available on this system, please visit '
. 'www.phpmyadmin.net for more information.'
),
$filename
);
exit;

View File

@ -8,8 +8,15 @@
require_once 'libraries/common.inc.php';
// If request for creating all PMA tables.
// If request for creating the pmadb
if (isset($_REQUEST['create_pmadb'])) {
if (PMA_createPMADatabase()) {
PMA_fixPMATables('phpmyadmin');
}
}
// If request for creating all PMA tables.
if (isset($_REQUEST['fixall_pmadb'])) {
PMA_fixPMATables($GLOBALS['db']);
}
@ -23,5 +30,3 @@ $response = PMA_Response::getInstance();
$response->addHTML(
PMA_getRelationsParamDiagnostic($cfgRelation)
);
?>

View File

@ -8,7 +8,7 @@
"authors": [
{
"name": "The phpMyAdmin Team",
"email": "phpmyadmin-devel@lists.sourceforge.net",
"email": "developers@phpmyadmin.net",
"homepage": "https://www.phpmyadmin.net/team/"
}
],
@ -23,7 +23,14 @@
},
"require-dev": {
"satooshi/php-coveralls": ">=0.6",
"phpunit/phpunit": "<4.2",
"phpunit/phpunit-selenium": ">=1.2"
}
"phpunit/phpunit": ">=3.7",
"phpunit/phpunit-selenium": ">=1.2",
"squizlabs/php_codesniffer": "2.*"
},
"repositories": [
{
"type": "composer",
"url": "https://www.phpmyadmin.net"
}
]
}

View File

@ -10,18 +10,18 @@
* @package PhpMyAdmin
*/
/*
/**
* This is needed for cookie based authentication to encrypt password in
* cookie
*/
$cfg['blowfish_secret'] = ''; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */
/*
/**
* Servers configuration
*/
$i = 0;
/*
/**
* First server
*/
$i++;
@ -33,7 +33,7 @@ $cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = false;
/*
/**
* phpMyAdmin configuration storage settings.
*/
@ -62,14 +62,16 @@ $cfg['Servers'][$i]['AllowNoPassword'] = false;
// $cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
// $cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
// $cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
// $cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
// $cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
/* Contrib / Swekey authentication */
// $cfg['Servers'][$i]['auth_swekey_config'] = '/etc/swekey-pma.conf';
/*
/**
* End of servers configuration
*/
/*
/**
* Directories for saving/loading files from server
*/
$cfg['UploadDir'] = '';
@ -78,8 +80,9 @@ $cfg['SaveDir'] = '';
/**
* Whether to display icons or text or both icons and text in table row
* action segment. Value can be either of 'icons', 'text' or 'both'.
* default = 'both'
*/
//$cfg['RowActionType'] = 'both';
//$cfg['RowActionType'] = 'icons';
/**
* Defines whether a user should be displayed a "show all (records)"
@ -91,20 +94,21 @@ $cfg['SaveDir'] = '';
/**
* Number of rows displayed when browsing a result set. If the result
* set contains more rows, "Previous" and "Next".
* default = 30
* Possible values: 25, 50, 100, 250, 500
* default = 25
*/
//$cfg['MaxRows'] = 50;
/**
* disallow editing of binary fields
* Disallow editing of binary fields
* valid values are:
* false allow editing
* 'blob' allow editing except for BLOB fields
* 'noblob' disallow editing except for BLOB fields
* 'all' disallow editing
* default = blob
* default = 'blob'
*/
//$cfg['ProtectBinary'] = 'false';
//$cfg['ProtectBinary'] = false;
/**
* Default language to use, if not browser-defined or user-defined
@ -133,20 +137,21 @@ $cfg['SaveDir'] = '';
/**
* When using DB-based query history, how many entries should be kept?
*
* default = 25
*/
//$cfg['QueryHistoryMax'] = 100;
/**
* Should error reporting be enabled for JavaScript errors
* Whether or not to query the user before sending the error report to
* the phpMyAdmin team when a JavaScript error occurs
*
* Available options
* ('ask' | 'always' | 'never')
* default = 'ask'
*/
//$cfg['SendErrorReports'] = 'ask';
//$cfg['SendErrorReports'] = 'always';
/*
/**
* You can find more configuration options in the documentation
* in the doc/ folder or at <http://docs.phpmyadmin.net/>.
*/
?>

View File

@ -10,7 +10,6 @@
* Gets some core libraries
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/tbl_columns_definition_form.lib.php';
require_once 'libraries/central_columns.lib.php';
if (isset($_POST['edit_save']) || isset($_POST['add_new_column'])) {
@ -22,7 +21,7 @@ if (isset($_POST['edit_save']) || isset($_POST['add_new_column'])) {
if ($col_default == 'NONE' && $_POST['col_default_sel'] != 'USER_DEFINED') {
$col_default = "";
}
$col_extra = $_POST['col_extra'];
$col_extra = isset($_POST['col_extra']) ? $_POST['col_extra'] : '';
$col_isNull = isset($_POST['col_isNull'])?1:0;
$col_length = $_POST['col_length'];
$col_attribute = $_POST['col_attribute'];
@ -30,13 +29,13 @@ if (isset($_POST['edit_save']) || isset($_POST['add_new_column'])) {
$collation = $_POST['collation'];
if (isset($orig_col_name) && $orig_col_name) {
echo PMA_updateOneColumn(
$db, $orig_col_name, $col_name, $col_type,$col_attribute,
$db, $orig_col_name, $col_name, $col_type, $col_attribute,
$col_length, $col_isNull, $collation, $col_extra, $col_default
);
exit;
} else {
$tmp_msg = PMA_updateOneColumn(
$db, "", $col_name, $col_type,$col_attribute,
$db, "", $col_name, $col_type, $col_attribute,
$col_length, $col_isNull, $collation, $col_extra, $col_default
);
}
@ -66,10 +65,27 @@ $cfgCentralColumns = PMA_centralColumnsGetParams();
$pmadb = $cfgCentralColumns['db'];
$pmatable = $cfgCentralColumns['table'];
$max_rows = $GLOBALS['cfg']['MaxRows'];
if (isset($_REQUEST['edit_central_columns_page'])) {
$selected_fld = $_REQUEST['selected_fld'];
$selected_db = $_REQUEST['db'];
$edit_central_column_page = PMA_getHTMLforEditingPage(
$selected_fld, $selected_db
);
$response->addHTML($edit_central_column_page);
exit;
}
if (isset($_POST['multi_edit_central_column_save'])) {
$message = PMA_updateMultipleColumn();
if (!is_bool($message)) {
$response->isSuccess(false);
$response->addJSON('message', $message);
}
}
if (isset($_POST['delete_save'])) {
$col_name = array();
$col_name[] = $_REQUEST['col_name'];
$tmp_msg = PMA_deleteColumnsFromList($col_name, false);
parse_str($_POST['col_name'], $col_name);
$tmp_msg = PMA_deleteColumnsFromList($col_name['selected_fld'], false);
}
if (isset($_REQUEST['total_rows']) && $_REQUEST['total_rows']) {
$total_rows = $_REQUEST['total_rows'];
@ -106,6 +122,7 @@ $deleteRowForm = '<form method="post" id="del_form" action="db_central_columns.p
. '<input type="hidden" name="delete_save" value="delete"></form>';
$response->addHTML($deleteRowForm);
$table_struct = '<div id="tableslistcontainer">'
. '<form name="tableslistcontainer">'
. '<table id="table_columns" class="tablesorter" '
. 'style="min-width:100%" class="data">';
$response->addHTML($table_struct);
@ -115,7 +132,7 @@ $tableheader = PMA_getCentralColumnsTableHeader(
$response->addHTML($tableheader);
$result = PMA_getColumnsList($db, $pos, $max_rows);
$odd_row = true;
$row_num=0;
$row_num = 0;
foreach ($result as $row) {
$tableHtmlRow = PMA_getHTMLforCentralColumnsTableRow(
$row, $odd_row, $row_num, $db
@ -124,11 +141,13 @@ foreach ($result as $row) {
$odd_row = !$odd_row;
$row_num++;
}
$response->addHTML('</table></div>');
$response->addHTML('</table>');
$tablefooter = PMA_getCentralColumnsTableFooter($pmaThemeImage, $text_dir);
$response->addHTML($tablefooter);
$response->addHTML('</form></div>');
$message = PMA_Message::success(
sprintf(__('Showing rows %1$s - %2$s.'), ($pos + 1), ($pos + count($result)))
);
if (isset($tmp_msg) && $tmp_msg !== true) {
$message = $tmp_msg;
}
?>

View File

@ -130,7 +130,10 @@ if (! $result) {
)
);
$response->addJSON(
'url_query', $GLOBALS['cfg']['DefaultTabDatabase']
'url_query',
PMA_Util::getScriptNameForOption(
$GLOBALS['cfg']['DefaultTabDatabase'], 'database'
)
. $url_query . '&amp;db='
. urlencode($current['SCHEMA_NAME'])
);
@ -138,4 +141,3 @@ if (! $result) {
include_once '' . $cfg['DefaultTabDatabase'];
}
}
?>

View File

@ -13,7 +13,17 @@ require_once 'libraries/common.inc.php';
if (! isset($selected_tbl)) {
include 'libraries/db_common.inc.php';
include 'libraries/db_info.inc.php';
list(
$tables,
$num_tables,
$total_num_tables,
$sub_part,
$is_show_stats,
$db_is_system_schema,
$tooltip_truename,
$tooltip_aliasname,
$pos
) = PMA_Util::getDbInfo($db, isset($sub_part) ? $sub_part : '');
}
$response = PMA_Response::getInstance();
@ -45,8 +55,8 @@ if ($cfgRelation['commwork']) {
* Displays DB comment
*/
if ($comment) {
echo '<p>' . __('Database comment:')
. ' <i>' . htmlspecialchars($comment) . '</i></p>';
echo '<p>' . __('Database comment')
. '<br /><i>' . htmlspecialchars($comment) . '</i></p>';
} // end if
}
@ -65,9 +75,10 @@ foreach ($tables as $table) {
echo '<h2>' . htmlspecialchars($table) . '</h2>' . "\n";
/**
* Gets table informations
* Gets table information
*/
$show_comment = PMA_Table::sGetStatusInfo($db, $table, 'TABLE_COMMENT');
$show_comment = $GLOBALS['dbi']->getTable($db, $table)
->getStatusInfo('TABLE_COMMENT');
/**
* Gets table keys and retains them
@ -123,14 +134,7 @@ foreach ($tables as $table) {
// reformat mysql query output
// set or enum types: slashes single quotes inside options
if ('set' == $extracted_columnspec['type']
|| 'enum' == $extracted_columnspec['type']
) {
$type_nowrap = '';
} else {
$type_nowrap = ' class="nowrap"';
}
$type = htmlspecialchars($extracted_columnspec['print_type']);
$attribute = $extracted_columnspec['attribute'];
if (! isset($row['Default'])) {
@ -152,7 +156,12 @@ foreach ($tables as $table) {
echo ' <em>(' . __('Primary') . ')</em>';
}
echo '</td>';
echo '<td' . $type_nowrap . ' lang="en" dir="ltr">' . $type . '</td>';
echo '<td'
. PMA_Util::getClassForType(
$extracted_columnspec['type']
)
. ' lang="en" dir="ltr">' . $type . '</td>';
echo '<td>';
echo (($row['Null'] == 'NO') ? __('No') : __('Yes'));
echo '</td>';
@ -195,7 +204,7 @@ foreach ($tables as $table) {
echo '</table>';
// display indexes information
if (count(PMA_Index::getFromTable($table, $db)) > 0) {
echo PMA_Index::getView($table, $db, true);
echo PMA_Index::getHtmlForIndexes($table, $db, true);
}
echo '</div>';
} //ends main while
@ -204,5 +213,3 @@ foreach ($tables as $table) {
* Displays the footer
*/
echo PMA_Util::getButton();
?>

View File

@ -36,12 +36,8 @@ if (isset($_REQUEST['dialog'])) {
if (isset($_REQUEST['operation'])) {
if ($_REQUEST['operation'] == 'deletePage') {
$result = PMA_deletePage($_REQUEST['selected_page']);
if ($result) {
$response->isSuccess(true);
} else {
$response->isSuccess(false);
}
$success = PMA_deletePage($_REQUEST['selected_page']);
$response->isSuccess($success);
} elseif ($_REQUEST['operation'] == 'savePage') {
if ($_REQUEST['save_page'] == 'same') {
$page = $_REQUEST['selected_page'];
@ -49,11 +45,8 @@ if (isset($_REQUEST['operation'])) {
$page = PMA_createNewPage($_REQUEST['selected_value'], $GLOBALS['db']);
$response->addJSON('id', $page);
}
if (PMA_saveTablePositions($page)) {
$response->isSuccess(true);
} else {
$response->isSuccess(false);
}
$success = PMA_saveTablePositions($page);
$response->isSuccess($success);
} elseif ($_REQUEST['operation'] == 'setDisplayField') {
PMA_saveDisplayField(
$_REQUEST['db'], $_REQUEST['table'], $_REQUEST['field']
@ -80,7 +73,11 @@ if (isset($_REQUEST['operation'])) {
);
$response->isSuccess($success);
$response->addJSON('message', $message);
} elseif ($_REQUEST['operation'] == 'save_setting_value') {
$success = PMA_saveDesignerSetting($_REQUEST['index'], $_REQUEST['value']);
$response->isSuccess($success);
}
return;
}
@ -89,15 +86,18 @@ $tab_column = PMA_getColumnsInfo();
$script_tables = PMA_getScriptTabs();
$tables_pk_or_unique_keys = PMA_getPKOrUniqueKeys();
$tables_all_keys = PMA_getAllKeys();
$classes_side_menu = PMA_returnClassNamesFromMenuButtons();
$display_page = -1;
$selected_page = null;
if (! isset($_REQUEST['query'])) {
if (isset($_REQUEST['query'])) {
$display_page = PMA_getDefaultPage($_REQUEST['db']);
} else {
if (! empty($_REQUEST['page'])) {
$display_page = $_REQUEST['page'];
} else {
$display_page = PMA_getFirstPage($_REQUEST['db']);
$display_page = PMA_getLoadingPage($_REQUEST['db']);
}
}
if ($display_page != -1) {
@ -127,7 +127,18 @@ $scripts->addFile('pmd/iecanvas.js', true);
$scripts->addFile('pmd/init.js');
require 'libraries/db_common.inc.php';
require 'libraries/db_info.inc.php';
list(
$tables,
$num_tables,
$total_num_tables,
$sub_part,
$is_show_stats,
$db_is_system_schema,
$tooltip_truename,
$tooltip_aliasname,
$pos
) = PMA_Util::getDbInfo($db, isset($sub_part) ? $sub_part : '');
// Embed some data into HTML, later it will be read
// by pmd/init.js and converted to JS variables.
@ -137,11 +148,15 @@ $response->addHTML(
)
);
$response->addHTML(
PMA_getDesignerPageMenu(isset($_REQUEST['query']), $selected_page)
PMA_getDesignerPageMenu(isset($_REQUEST['query']), $selected_page, $classes_side_menu)
);
$response->addHTML('<div id="canvas_outer">');
$response->addHTML('<form action="" id="container-form" method="post" name="form1">');
$response->addHTML(
'<form action="" id="container-form" method="post" name="form1">'
);
$response->addHTML(PMA_getHTMLCanvas());
$response->addHTML(PMA_getHTMLTableList($tab_pos, $display_page));
@ -169,5 +184,4 @@ if (isset($_REQUEST['query'])) {
$response->addHTML(PMA_getQueryDetails());
}
$response->addHTML(PMA_getCacheImages());
?>
$response->addHTML('<div id="PMA_disable_floating_menubar"></div>');

View File

@ -22,5 +22,3 @@ require_once 'libraries/rte/rte_events.lib.php';
*/
$_PMA_RTE = 'EVN';
require_once 'libraries/rte/rte_main.inc.php';
?>

View File

@ -10,18 +10,33 @@
* Gets some core libraries
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/config/page_settings.class.php';
require_once 'libraries/export.lib.php';
PMA_PageSettings::showGroup('Export');
$response = PMA_Response::getInstance();
$header = $response->getHeader();
$scripts = $header->getScripts();
$scripts->addFile('export.js');
// $sub_part is also used in db_info.inc.php to see if we are coming from
// $sub_part is used in PMA_Util::getDbInfo() to see if we are coming from
// db_export.php, in which case we don't obey $cfg['MaxTableList']
$sub_part = '_export';
require_once 'libraries/db_common.inc.php';
$url_query .= '&amp;goto=db_export.php';
require_once 'libraries/db_info.inc.php';
list(
$tables,
$num_tables,
$total_num_tables,
$sub_part,
$is_show_stats,
$db_is_system_schema,
$tooltip_truename,
$tooltip_aliasname,
$pos
) = PMA_Util::getDbInfo($db, isset($sub_part) ? $sub_part : '');
/**
* Displays the form
@ -34,21 +49,28 @@ if ($num_tables < 1) {
exit;
} // end if
$multi_values = '<div>';
$multi_values .= '<a href="#"';
$multi_values .= ' onclick="setSelectOptions(\'dump\', \'table_select[]\', true);'
. ' return false;">';
$multi_values .= __('Select All');
$multi_values .= '</a>';
$multi_values .= ' / ';
$multi_values .= '<a href="#"';
$multi_values .= ' onclick="setSelectOptions(\'dump\', \'table_select[]\', false);'
. ' return false;">';
$multi_values .= __('Unselect All');
$multi_values .= '</a><br />';
$multi_values .= '<select name="table_select[]" id="table_select" size="10"'
. ' multiple="multiple">';
$multi_values = '<div class="export_table_list_container">';
if (isset($_GET['structure_or_data_forced'])) {
$force_val = htmlspecialchars($_GET['structure_or_data_forced']);
} else {
$force_val = 0;
}
$multi_values .= '<input type="hidden" name="structure_or_data_forced" value="'
. $force_val . '">';
$multi_values .= '<table class="export_table_select">'
. '<thead><tr><th></th>'
. '<th>' . __('Tables') . '</th>'
. '<th class="export_structure">' . __('Structure') . '</th>'
. '<th class="export_data">' . __('Data') . '</th>'
. '</tr><tr>'
. '<td></td>'
. '<td class="export_table_name all">' . __('Select all') . '</td>'
. '<td class="export_structure all">'
. '<input type="checkbox" id="table_structure_all" /></td>'
. '<td class="export_data all"><input type="checkbox" id="table_data_all" />'
. '</td>'
. '</tr></thead>'
. '<tbody>';
$multi_values .= "\n";
// when called by libraries/mult_submits.inc.php
@ -58,37 +80,56 @@ if (!empty($_POST['selected_tbl']) && empty($table_select)) {
// Check if the selected tables are defined in $_GET
// (from clicking Back button on export.php)
if (isset($_GET['table_select'])) {
$_GET['table_select'] = urldecode($_GET['table_select']);
$_GET['table_select'] = explode(",", $_GET['table_select']);
foreach (array('table_select', 'table_structure', 'table_data') as $one_key) {
if (isset($_GET[$one_key])) {
$_GET[$one_key] = urldecode($_GET[$one_key]);
$_GET[$one_key] = explode(",", $_GET[$one_key]);
}
}
foreach ($tables as $each_table) {
if (isset($_GET['table_select'])) {
if (in_array($each_table['Name'], $_GET['table_select'])) {
$is_selected = ' selected="selected"';
} else {
$is_selected = '';
}
$is_checked = PMA_getCheckedClause(
$each_table['Name'], $_GET['table_select']
);
} elseif (isset($table_select)) {
if (in_array($each_table['Name'], $table_select)) {
$is_selected = ' selected="selected"';
} else {
$is_selected = '';
}
$is_checked = PMA_getCheckedClause(
$each_table['Name'], $table_select
);
} else {
$is_selected = ' selected="selected"';
$is_checked = ' checked="checked"';
}
if (isset($_GET['table_structure'])) {
$structure_checked = PMA_getCheckedClause(
$each_table['Name'], $_GET['table_structure']
);
} else {
$structure_checked = $is_checked;
}
if (isset($_GET['table_data'])) {
$data_checked = PMA_getCheckedClause(
$each_table['Name'], $_GET['table_data']
);
} else {
$data_checked = $is_checked;
}
$table_html = htmlspecialchars($each_table['Name']);
$multi_values .= ' <option value="' . $table_html . '"'
. $is_selected . '>'
. str_replace(' ', '&nbsp;', $table_html) . '</option>' . "\n";
$multi_values .= '<tr>';
$multi_values .= '<td><input type="checkbox" name="table_select[]"'
. ' value="' . $table_html . '"' . $is_checked . ' /></td>';
$multi_values .= '<td class="export_table_name">'
. str_replace(' ', '&nbsp;', $table_html) . '</td>';
$multi_values .= '<td class="export_structure">'
. '<input type="checkbox" name="table_structure[]"'
. ' value="' . $table_html . '"' . $structure_checked . ' /></td>';
$multi_values .= '<td class="export_data">'
. '<input type="checkbox" name="table_data[]"'
. ' value="' . $table_html . '"' . $data_checked . ' /></td>';
$multi_values .= '</tr>';
} // end for
$multi_values .= "\n";
$multi_values .= '</select></div>';
$multi_values .= '</tbody></table></div>';
$export_type = 'database';
require_once 'libraries/display_export.inc.php';
?>

View File

@ -7,6 +7,9 @@
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/config/page_settings.class.php';
PMA_PageSettings::showGroup('Import');
$response = PMA_Response::getInstance();
$header = $response->getHeader();
@ -17,9 +20,23 @@ $scripts->addFile('import.js');
* Gets tables information and displays top links
*/
require 'libraries/db_common.inc.php';
require 'libraries/db_info.inc.php';
$import_type = 'database';
require 'libraries/display_import.inc.php';
list(
$tables,
$num_tables,
$total_num_tables,
$sub_part,
$is_show_stats,
$db_is_system_schema,
$tooltip_truename,
$tooltip_aliasname,
$pos
) = PMA_Util::getDbInfo($db, isset($sub_part) ? $sub_part : '');
?>
require 'libraries/display_import.lib.php';
$response = PMA_Response::getInstance();
$response->addHTML(
PMA_getImportDisplay(
'database', $db, $table, $max_upload_size
)
);

View File

@ -17,10 +17,12 @@
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/mysql_charsets.inc.php';
require_once 'libraries/display_create_table.lib.php';
/**
* functions implementation for this script
*/
require_once 'libraries/check_user_privileges.lib.php';
require_once 'libraries/operations.lib.php';
// add a javascript file for jQuery functions to handle Ajax actions
@ -70,6 +72,7 @@ if (/*overload*/mb_strlen($GLOBALS['db'])
include_once "libraries/plugin_interface.lib.php";
// remove all foreign key constraints, otherwise we can get errors
/* @var $export_sql_plugin ExportSql */
$export_sql_plugin = PMA_getPlugin(
"export",
"sql",
@ -116,6 +119,12 @@ if (/*overload*/mb_strlen($GLOBALS['db'])
PMA_duplicateBookmarks($_error, $GLOBALS['db']);
if (! $_error && $move) {
if (isset($_REQUEST['adjust_privileges'])
&& ! empty($_REQUEST['adjust_privileges'])
) {
PMA_AdjustPrivileges_moveDB($GLOBALS['db'], $_REQUEST['newname']);
}
/**
* cleanup pmadb stuff for this db
*/
@ -134,6 +143,12 @@ if (/*overload*/mb_strlen($GLOBALS['db'])
$message->addParam($GLOBALS['db']);
$message->addParam($_REQUEST['newname']);
} elseif (! $_error) {
if (isset($_REQUEST['adjust_privileges'])
&& ! empty($_REQUEST['adjust_privileges'])
) {
PMA_AdjustPrivileges_copyDB($GLOBALS['db'], $_REQUEST['newname']);
}
$message = PMA_Message::success(
__('Database %1$s has been copied to %2$s.')
);
@ -196,7 +211,19 @@ $url_query .= '&amp;goto=db_operations.php';
// Gets the database structure
$sub_part = '_structure';
require 'libraries/db_info.inc.php';
list(
$tables,
$num_tables,
$total_num_tables,
$sub_part,
$is_show_stats,
$db_is_system_schema,
$tooltip_truename,
$tooltip_aliasname,
$pos
) = PMA_Util::getDbInfo($db, isset($sub_part) ? $sub_part : '');
echo "\n";
if (isset($message)) {
@ -218,11 +245,7 @@ if (!$is_information_schema) {
}
$response->addHTML('<div class="operations_half_width">');
ob_start();
include 'libraries/display_create_table.lib.php';
$content = ob_get_contents();
ob_end_clean();
$response->addHTML($content);
$response->addHTML(PMA_getHtmlForCreateTable($db));
$response->addHTML('</div>');
/**
@ -256,7 +279,10 @@ if (!$is_information_schema) {
&& $cfg['PmaNoRelation_DisableWarning'] == false
) {
$message = PMA_Message::notice(
__('The phpMyAdmin configuration storage has been deactivated. %sFind out why%s.')
__(
'The phpMyAdmin configuration storage has been deactivated. ' .
'%sFind out why%s.'
)
);
$message->addParam(
'<a href="' . $cfg['PmaAbsoluteUri']
@ -287,5 +313,3 @@ if ($cfgRelation['pdfwork'] && $num_tables > 0) {
PMA_DatabaseInterface::QUERY_STORE
);
} // end if
?>

View File

@ -1,175 +0,0 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Print view of a database
*
* @package PhpMyAdmin
*/
/**
*
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/db_printview.lib.php';
$response = PMA_Response::getInstance();
$header = $response->getHeader();
$header->enablePrintView();
PMA_Util::checkParameters(array('db'));
/**
* Defines the url to return to in case of error in a sql statement
*/
$err_url = 'db_sql.php' . PMA_URL_getCommon(array('db' => $db));
/**
* Settings for relations stuff
*/
$cfgRelation = PMA_getRelationsParam();
/**
* If there is at least one table, displays the printer friendly view, else
* an error message
*/
$tables = $GLOBALS['dbi']->getTablesFull($db);
$num_tables = count($tables);
echo '<br />';
// 1. No table
if ($num_tables == 0) {
echo __('No tables found in database.');
} else {
// 2. Shows table information
echo '<table>';
echo '<thead>';
echo '<tr>';
echo '<th>' . __('Table') . '</th>';
echo '<th>' . __('Rows') . '</th>';
echo '<th>' . __('Type') . '</th>';
if ($cfg['ShowStats']) {
echo '<th>' . __('Size') . '</th>';
}
echo '<th>' . __('Comments') . '</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
$sum_entries = $sum_size = 0;
$odd_row = true;
foreach ($tables as $sts_data) {
if (PMA_Table::isMerge($db, $sts_data['TABLE_NAME'])
|| /*overload*/mb_strtoupper($sts_data['ENGINE']) == 'FEDERATED'
) {
$merged_size = true;
} else {
$merged_size = false;
}
$sum_entries += $sts_data['TABLE_ROWS'];
echo '<tr class="' . ($odd_row ? 'odd' : 'even') . '">';
echo '<th>';
echo htmlspecialchars($sts_data['TABLE_NAME']);
echo '</th>';
if (isset($sts_data['TABLE_ROWS'])) {
echo '<td class="right">';
if ($merged_size) {
echo '<i>';
echo PMA_Util::formatNumber($sts_data['TABLE_ROWS'], 0);
echo '</i>';
} else {
echo PMA_Util::formatNumber($sts_data['TABLE_ROWS'], 0);
}
echo '</td>';
echo '<td class="nowrap">';
echo $sts_data['ENGINE'];
echo '</td>';
if ($cfg['ShowStats']) {
$tblsize = $sts_data['Data_length'] + $sts_data['Index_length'];
$sum_size += $tblsize;
list($formated_size, $unit)
= PMA_Util::formatByteDown($tblsize, 3, 1);
echo '<td class="right nowrap">';
echo $formated_size . ' ' . $unit;
echo '</td>';
} // end if
} else {
echo '<td colspan="3" class="center">';
if (! PMA_Table::isView($db, $sts_data['TABLE_NAME'])) {
echo __('in use');
}
echo '</td>';
}
echo '<td>';
if (! empty($sts_data['Comment'])) {
echo htmlspecialchars($sts_data['Comment']);
$needs_break = '<br />';
} else {
$needs_break = '';
}
if (! empty($sts_data['Create_time'])
|| ! empty($sts_data['Update_time'])
|| ! empty($sts_data['Check_time'])
) {
echo $needs_break;
echo '<table width="100%">';
if (! empty($sts_data['Create_time'])) {
echo PMA_getHtmlForOneDate(
__('Creation:'),
$sts_data['Create_time']
);
}
if (! empty($sts_data['Update_time'])) {
echo PMA_getHtmlForOneDate(
__('Last update:'),
$sts_data['Update_time']
);
}
if (! empty($sts_data['Check_time'])) {
echo PMA_getHtmlForOneDate(
__('Last check:'),
$sts_data['Check_time']
);
}
echo '</table>';
}
echo '</td>';
echo '</tr>';
}
echo '<tr>';
echo '<th class="center">';
printf(
_ngettext('%s table', '%s tables', $num_tables),
PMA_Util::formatNumber($num_tables, 0)
);
echo '</th>';
echo '<th class="right nowrap">';
echo PMA_Util::formatNumber($sum_entries, 0);
echo '</th>';
echo '<th class="center">';
echo '--';
echo '</th>';
if ($cfg['ShowStats']) {
list($sum_formated, $unit)
= PMA_Util::formatByteDown($sum_size, 3, 1);
echo '<th class="right nowrap">';
echo $sum_formated . ' ' . $unit;
echo '</th>';
}
echo '<th></th>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
}
/**
* Displays the footer
*/
echo PMA_Util::getButton();
echo "<div id='PMA_disable_floating_menubar'></div>\n";
?>

View File

@ -22,7 +22,7 @@ $cfgRelation = PMA_getRelationsParam();
$savedSearchList = array();
$savedSearch = null;
$currentSearchId = null;
if (isset($cfgRelation['savedsearcheswork']) && $cfgRelation['savedsearcheswork']) {
if ($cfgRelation['savedsearcheswork']) {
include 'libraries/SavedSearches.class.php';
$header = $response->getHeader();
$scripts = $header->getScripts();
@ -80,15 +80,30 @@ if (isset($_REQUEST['submit_sql']) && ! empty($sql_query)) {
if (! preg_match('@^SELECT@i', $sql_query)) {
$message_to_display = true;
} else {
$goto = 'db_sql.php';
$goto = 'db_sql.php';
// Parse and analyze the query
include_once 'libraries/parse_analyze.inc.php';
PMA_executeQueryAndSendQueryResponse(
$analyzed_sql_results, false, $_REQUEST['db'], null, false, null, null,
false, null, null, null, $goto, $pmaThemeImage, null, null, null,
$sql_query, null, null
$analyzed_sql_results, // analyzed_sql_results
false, // is_gotofile
$_REQUEST['db'], // db
null, // table
false, // find_real_end
null, // sql_query_for_bookmark
null, // extra_data
null, // message_to_show
null, // message
null, // sql_data
$goto, // goto
$pmaThemeImage, // pmaThemeImage
null, // disp_query
null, // disp_message
null, // query_type
$sql_query, // sql_query
null, // selectedTables
null // complete_query
);
}
}
@ -97,7 +112,18 @@ $sub_part = '_qbe';
require 'libraries/db_common.inc.php';
$url_query .= '&amp;goto=db_qbe.php';
$url_params['goto'] = 'db_qbe.php';
require 'libraries/db_info.inc.php';
list(
$tables,
$num_tables,
$total_num_tables,
$sub_part,
$is_show_stats,
$db_is_system_schema,
$tooltip_truename,
$tooltip_aliasname,
$pos
) = PMA_Util::getDbInfo($db, isset($sub_part) ? $sub_part : '');
if ($message_to_display) {
PMA_Message::error(__('You have to choose at least one column to display!'))
@ -106,7 +132,7 @@ if ($message_to_display) {
unset($message_to_display);
// create new qbe search instance
$db_qbe = new PMA_DBQbe($GLOBALS['db'], $savedSearchList, $savedSearch);
$db_qbe = new PMA_DbQbe($GLOBALS['db'], $savedSearchList, $savedSearch);
$url = 'db_designer.php' . PMA_URL_getCommon(
array_merge(
@ -128,4 +154,3 @@ $response->addHTML(
* Displays the Query by example form
*/
$response->addHTML($db_qbe->getSelectionForm());
?>

View File

@ -16,6 +16,7 @@ require_once 'libraries/mysql_charsets.inc.php';
/**
* Include all other files
*/
require_once 'libraries/check_user_privileges.lib.php';
require_once 'libraries/rte/rte_routines.lib.php';
/**
@ -23,5 +24,3 @@ require_once 'libraries/rte/rte_routines.lib.php';
*/
$_PMA_RTE = 'RTN';
require_once 'libraries/rte/rte_main.inc.php';
?>

View File

@ -24,7 +24,7 @@ $scripts->addFile('jquery/jquery-ui-timepicker-addon.js');
require 'libraries/db_common.inc.php';
// If config variable $GLOBALS['cfg']['Usedbsearch'] is on false : exit.
// If config variable $GLOBALS['cfg']['UseDbSearch'] is on false : exit.
if (! $GLOBALS['cfg']['UseDbSearch']) {
PMA_Util::mysqlDie(
__('Access denied!'), '', false, $err_url
@ -37,8 +37,18 @@ $url_params['goto'] = 'db_search.php';
$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';
if ($GLOBALS['is_ajax_request'] != true) {
list(
$tables,
$num_tables,
$total_num_tables,
$sub_part,
$is_show_stats,
$db_is_system_schema,
$tooltip_truename,
$tooltip_aliasname,
$pos
) = PMA_Util::getDbInfo($db, isset($sub_part) ? $sub_part : '');
}
// Main search form has been submitted, get results
@ -60,4 +70,3 @@ $response->addHTML(
);
$response->addHTML($db_search->getSelectionForm());
$response->addHTML($db_search->getResultDivs());
?>

View File

@ -10,6 +10,9 @@
*
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/config/page_settings.class.php';
PMA_PageSettings::showGroup('Sql_queries');
/**
* Runs common work
@ -41,5 +44,3 @@ $response->addHTML(
: ';'
)
);
?>

View File

@ -8,17 +8,19 @@
require_once 'libraries/common.inc.php';
$db = isset($_POST['db']) ? $_POST['db'] : $GLOBALS['db'];
$sql_autocomplete = array();
if ($db) {
$tableNames = $GLOBALS['dbi']->getTables($db);
foreach ($tableNames as $tableName) {
$sql_autocomplete[$tableName] = $GLOBALS['dbi']->getColumns(
$db, $tableName
);
if ($GLOBALS['cfg']['EnableAutocompleteForTablesAndColumns']) {
$db = isset($_POST['db']) ? $_POST['db'] : $GLOBALS['db'];
$sql_autocomplete = array();
if ($db) {
$tableNames = $GLOBALS['dbi']->getTables($db);
foreach ($tableNames as $tableName) {
$sql_autocomplete[$tableName] = $GLOBALS['dbi']->getColumns(
$db, $tableName
);
}
}
} else {
$sql_autocomplete = true;
}
$response = PMA_Response::getInstance();
$response->addJSON("tables", json_encode($sql_autocomplete));

View File

@ -6,13 +6,15 @@
* @package PhpMyAdmin
*/
/**
* Loading common files. Used to check for authorization, localization and to
* load the parsing library.
*/
require_once 'libraries/common.inc.php';
require_once 'libraries/sql-formatter/lib/SqlFormatter.php';
$query = isset($_POST['sql']) ? $_POST['sql'] : '';
$query = !empty($_POST['sql']) ? $_POST['sql'] : '';
SqlFormatter::$tab = "\t";
$query = SqlFormatter::format($query, false);
$query = SqlParser\Utils\Formatter::format($query);
$response = PMA_Response::getInstance();
$response->addJSON("sql", $query);

View File

@ -6,340 +6,49 @@
* @package PhpMyAdmin
*/
/**
*
*/
namespace PMA;
use PMA_Response;
require_once 'libraries/common.inc.php';
require_once 'libraries/db_common.inc.php';
/**
* Function implementations for this script
*/
require_once 'libraries/structure.lib.php';
list(
$tables,
$num_tables,
$total_num_tables,
$sub_part,
$is_show_stats,
$db_is_system_schema,
$tooltip_truename,
$tooltip_aliasname,
$pos
) = \PMA_Util::getDbInfo($GLOBALS['db'], isset($sub_part) ? $sub_part : '');
// Add/Remove favorite tables using Ajax request.
if ($GLOBALS['is_ajax_request'] && ! empty($_REQUEST['favorite_table'])) {
PMA_addRemoveFavoriteTables($db);
exit;
}
require_once 'libraries/di/Container.class.php';
require_once 'libraries/controllers/DatabaseStructureController.class.php';
require_once 'libraries/Response.class.php';
$response = PMA_Response::getInstance();
$header = $response->getHeader();
$scripts = $header->getScripts();
$scripts->addFile('db_structure.js');
$scripts->addFile('tbl_change.js');
$scripts->addFile('jquery/jquery-ui-timepicker-addon.js');
$container = DI\Container::getDefaultContainer();
$container->factory('PMA\Controllers\DatabaseStructureController');
$container->alias(
'DatabaseStructureController', 'PMA\Controllers\DatabaseStructureController'
);
$container->set('PMA_Response', PMA_Response::getInstance());
$container->alias('response', 'PMA_Response');
// Drops/deletes/etc. multiple tables if required
if ((!empty($_POST['submit_mult']) && isset($_POST['selected_tbl']))
|| isset($_POST['mult_btn'])
) {
$action = 'db_structure.php';
$err_url = 'db_structure.php' . PMA_URL_getCommon(array('db' => $db));
// see bug #2794840; in this case, code path is:
// db_structure.php -> libraries/mult_submits.inc.php -> sql.php
// -> db_structure.php and if we got an error on the multi submit,
// we must display it here and not call again mult_submits.inc.php
if (! isset($_POST['error']) || false === $_POST['error']) {
include 'libraries/mult_submits.inc.php';
}
if (empty($_POST['message'])) {
$_POST['message'] = PMA_Message::success();
}
}
require 'libraries/db_common.inc.php';
$url_query .= '&amp;goto=db_structure.php';
// Gets the database structure
$sub_part = '_structure';
require 'libraries/db_info.inc.php';
// If there is an Ajax request for real row count of a table.
if ($GLOBALS['is_ajax_request']
&& isset($_REQUEST['real_row_count'])
&& $_REQUEST['real_row_count'] == true
) {
PMA_handleRealRowCountRequest();
exit;
}
if (!PMA_DRIZZLE) {
include_once 'libraries/replication.inc.php';
} else {
$GLOBALS['replication_info']['slave']['status'] = false;
}
require_once 'libraries/bookmark.lib.php';
require_once 'libraries/mysql_charsets.inc.php';
$db_collation = PMA_getDbCollation($db);
$titles = PMA_Util::buildActionTitles();
// 1. No tables
if ($num_tables == 0) {
$response->addHTML(
PMA_message::notice(__('No tables found in database.'))
);
PMA_possiblyShowCreateTableDialog($db, $db_is_system_schema, $response);
exit;
}
// else
// 2. Shows table informations
/**
* Displays the tables list
*/
$response->addHTML('<div id="tableslistcontainer">');
$_url_params = array(
global $db, $pos, $db_is_system_schema, $total_num_tables, $tables, $num_tables;
/* Define dependencies for the concerned controller */
$dependency_definitions = array(
'db' => $db,
'url_query' => &$GLOBALS['url_query'],
'pos' => $pos,
'db' => $db);
// Add the sort options if they exists
if (isset($_REQUEST['sort'])) {
$_url_params['sort'] = $_REQUEST['sort'];
}
if (isset($_REQUEST['sort_order'])) {
$_url_params['sort_order'] = $_REQUEST['sort_order'];
}
$response->addHTML(
PMA_Util::getListNavigator(
$total_num_tables, $pos, $_url_params, 'db_structure.php',
'frame_content', $GLOBALS['cfg']['MaxTableList']
)
'db_is_system_schema' => $db_is_system_schema,
'num_tables' => $num_tables,
'total_num_tables' => $total_num_tables,
'tables' => $tables,
);
// tables form
$response->addHTML(
'<form method="post" action="db_structure.php" '
. 'name="tablesForm" id="tablesForm">'
);
$response->addHTML(PMA_URL_getHiddenInputs($db));
$response->addHTML(
PMA_tableHeader(
$db_is_system_schema, $GLOBALS['replication_info']['slave']['status']
)
);
$i = $sum_entries = 0;
$overhead_check = '';
$create_time_all = '';
$update_time_all = '';
$check_time_all = '';
$num_columns = $cfg['PropertiesNumColumns'] > 1
? ceil($num_tables / $cfg['PropertiesNumColumns']) + 1
: 0;
$row_count = 0;
$sum_size = (double) 0;
$overhead_size = (double) 0;
$hidden_fields = array();
$odd_row = true;
// Instance of PMA_RecentFavoriteTable class.
$fav_instance = PMA_RecentFavoriteTable::getInstance('favorite');
foreach ($tables as $keyname => $current_table) {
// Get valid statistics whatever is the table type
$drop_query = '';
$drop_message = '';
$already_favorite = false;
$overhead = '';
$table_is_view = false;
$table_encoded = urlencode($current_table['TABLE_NAME']);
// Sets parameters for links
$tbl_url_query = $url_query . '&amp;table=' . $table_encoded;
// do not list the previous table's size info for a view
list($current_table, $formatted_size, $unit, $formatted_overhead,
$overhead_unit, $overhead_size, $table_is_view, $sum_size)
= PMA_getStuffForEngineTypeTable(
$current_table, $db_is_system_schema,
$is_show_stats, $table_is_view, $sum_size, $overhead_size
);
if (! PMA_Table::isMerge($db, $current_table['TABLE_NAME'])) {
$sum_entries += $current_table['TABLE_ROWS'];
}
if (isset($current_table['Collation'])) {
$collation = '<dfn title="'
. PMA_getCollationDescr($current_table['Collation']) . '">'
. $current_table['Collation'] . '</dfn>';
} else {
$collation = '---';
}
if ($is_show_stats) {
if ($formatted_overhead != '') {
$overhead = '<a href="tbl_structure.php'
. $tbl_url_query . '#showusage">'
. '<span>' . $formatted_overhead . '</span>&nbsp;'
. '<span class="unit">' . $overhead_unit . '</span>'
. '</a>' . "\n";
$overhead_check .=
"markAllRows('row_tbl_" . ($i + 1) . "');";
} else {
$overhead = '-';
}
} // end if
unset($showtable);
if ($GLOBALS['cfg']['ShowDbStructureCreation']) {
list($create_time, $create_time_all) = PMA_getTimeForCreateUpdateCheck(
$current_table, 'Create_time', $create_time_all
);
}
if ($GLOBALS['cfg']['ShowDbStructureLastUpdate']) {
// $showtable might already be set from ShowDbStructureCreation, see above
list($update_time, $update_time_all) = PMA_getTimeForCreateUpdateCheck(
$current_table, 'Update_time', $update_time_all
);
}
if ($GLOBALS['cfg']['ShowDbStructureLastCheck']) {
// $showtable might already be set from ShowDbStructureCreation, see above
list($check_time, $check_time_all) = PMA_getTimeForCreateUpdateCheck(
$current_table, 'Check_time', $check_time_all
);
}
list($alias, $truename) = PMA_getAliasAndTrueName(
$tooltip_aliasname, $current_table, $tooltip_truename
);
$i++;
$row_count++;
if ($table_is_view) {
$hidden_fields[] = '<input type="hidden" name="views[]" value="'
. htmlspecialchars($current_table['TABLE_NAME']) . '" />';
}
/*
* Always activate links for Browse, Search and Empty, even if
* the icons are greyed, because
* 1. for views, we don't know the number of rows at this point
* 2. for tables, another source could have populated them since the
* page was generated
*
* I could have used the PHP ternary conditional operator but I find
* the code easier to read without this operator.
*/
list($browse_table, $search_table, $browse_table_label, $empty_table,
$tracking_icon) = PMA_getHtmlForActionLinks(
$current_table, $table_is_view, $tbl_url_query,
$titles, $truename, $db_is_system_schema, $url_query
);
if (! $db_is_system_schema) {
list($drop_query, $drop_message)
= PMA_getTableDropQueryAndMessage($table_is_view, $current_table);
}
if ($num_columns > 0
&& $num_tables > $num_columns
&& ($row_count % $num_columns) == 0
) {
$row_count = 1;
$odd_row = true;
$response->addHTML(
'</tr></tbody></table>'
);
$response->addHTML(
PMA_tableHeader(false, $GLOBALS['replication_info']['slave']['status'])
);
}
list($do, $ignored) = PMA_getServerSlaveStatus(
$GLOBALS['replication_info']['slave']['status'], $truename
);
// Handle favorite table list. ----START----
$already_favorite = PMA_checkFavoriteTable($db, $current_table['TABLE_NAME']);
if (isset($_REQUEST['remove_favorite'])) {
if ($already_favorite) {
// If already in favorite list, remove it.
$favorite_table = $_REQUEST['favorite_table'];
$fav_instance->remove($db, $favorite_table);
}
}
if (isset($_REQUEST['add_favorite'])) {
if (!$already_favorite) {
// Otherwise add to favorite list.
$favorite_table = $_REQUEST['favorite_table'];
$fav_instance->add($db, $favorite_table);
}
} // Handle favorite table list. ----ENDS----
list($html_output, $odd_row, $approx_rows) = PMA_getHtmlForStructureTableRow(
$i, $odd_row, $table_is_view, $current_table,
$browse_table_label, $tracking_icon,
$GLOBALS['replication_info']['slave']['status'],
$browse_table, $tbl_url_query, $search_table, $db_is_system_schema,
$titles, $empty_table, $drop_query, $drop_message, $collation,
$formatted_size, $unit, $overhead,
(isset ($create_time) ? $create_time : ''),
(isset ($update_time) ? $update_time : ''),
(isset ($check_time) ? $check_time : ''),
$is_show_stats, $ignored, $do, $colspan_for_structure
);
$response->addHTML($html_output);
} // end foreach
// Show Summary
$response->addHTML('</tbody>');
$response->addHTML(
PMA_getHtmlBodyForTableSummary(
$num_tables, $GLOBALS['replication_info']['slave']['status'],
$db_is_system_schema, $sum_entries, $db_collation, $is_show_stats, $sum_size,
$overhead_size, $create_time_all, $update_time_all, $check_time_all,
isset($approx_rows) ? $approx_rows : false
)
);
$response->addHTML('</table>');
//check all
$response->addHTML(
PMA_getHtmlForCheckAllTables(
$pmaThemeImage, $text_dir, $overhead_check,
$db_is_system_schema, $hidden_fields
)
);
$response->addHTML('</form>'); //end of form
// display again the table list navigator
$response->addHTML(
PMA_Util::getListNavigator(
$total_num_tables, $pos, $_url_params, 'db_structure.php',
'frame_content', $GLOBALS['cfg']['MaxTableList']
)
);
$response->addHTML('</div><hr />');
/**
* Work on the database
*/
/* DATABASE WORK */
/* Printable view of a table */
$response->addHTML(
PMA_getHtmlForTablePrintViewLink($url_query)
. PMA_getHtmlForDataDictionaryLink($url_query)
);
PMA_possiblyShowCreateTableDialog($db, $db_is_system_schema, $response);
?>
/** @var Controllers\DatabaseStructureController $controller */
$controller = $container->get('DatabaseStructureController', $dependency_definitions);
$controller->indexAction();

View File

@ -12,6 +12,7 @@
require_once 'libraries/common.inc.php';
require_once './libraries/tracking.lib.php';
require_once 'libraries/display_create_table.lib.php';
//Get some js files needed for Ajax requests
$response = PMA_Response::getInstance();
@ -28,7 +29,18 @@ $url_query .= '&amp;goto=tbl_tracking.php&amp;back=db_tracking.php';
// Get the database structure
$sub_part = '_structure';
require 'libraries/db_info.inc.php';
list(
$tables,
$num_tables,
$total_num_tables,
$sub_part,
$is_show_stats,
$db_is_system_schema,
$tooltip_truename,
$tooltip_aliasname,
$pos
) = PMA_Util::getDbInfo($db, isset($sub_part) ? $sub_part : '');
// Work to do?
// (here, do not use $_REQUEST['db] as it can be crafted)
@ -89,7 +101,7 @@ if ($num_tables == 0 && count($data['ddlog']) == 0) {
echo '<p>' . __('No tables found in database.') . '</p>' . "\n";
if (empty($db_is_system_schema)) {
include 'libraries/display_create_table.lib.php';
echo PMA_getHtmlForCreateTable($db);
}
exit;
}
@ -108,234 +120,20 @@ $all_tables_query = ' SELECT table_name, MAX(version) as version FROM ' .
$all_tables_result = PMA_queryAsControlUser($all_tables_query);
// If a HEAD version exists
if ($GLOBALS['dbi']->numRows($all_tables_result) > 0) {
?>
<div id="tracked_tables">
<h3><?php echo __('Tracked tables');?></h3>
<form method="post" action="db_tracking.php" name="trackedForm"
id="trackedForm" class="ajax">
<?php
echo PMA_URL_getHiddenInputs($GLOBALS['db'])
?>
<table id="versions" class="data">
<thead>
<tr>
<th></th>
<th><?php echo __('Table');?></th>
<th><?php echo __('Last version');?></th>
<th><?php echo __('Created');?></th>
<th><?php echo __('Updated');?></th>
<th><?php echo __('Status');?></th>
<th><?php echo __('Action');?></th>
<th><?php echo __('Show');?></th>
</tr>
</thead>
<tbody>
<?php
// Print out information about versions
$delete = PMA_Util::getIcon('b_drop.png', __('Delete tracking'));
$versions = PMA_Util::getIcon('b_versions.png', __('Versions'));
$report = PMA_Util::getIcon('b_report.png', __('Tracking report'));
$structure = PMA_Util::getIcon('b_props.png', __('Structure snapshot'));
$style = 'odd';
while ($one_result = $GLOBALS['dbi']->fetchArray($all_tables_result)) {
list($table_name, $version_number) = $one_result;
$table_query = ' SELECT * FROM ' .
PMA_Util::backquote($cfgRelation['db']) . '.' .
PMA_Util::backquote($cfgRelation['tracking']) .
' WHERE `db_name` = \'' . PMA_Util::sqlAddSlashes($_REQUEST['db'])
. '\' AND `table_name` = \'' . PMA_Util::sqlAddSlashes($table_name)
. '\' AND `version` = \'' . $version_number . '\'';
$table_result = PMA_queryAsControlUser($table_query);
$version_data = $GLOBALS['dbi']->fetchArray($table_result);
$tmp_link = 'tbl_tracking.php' . $url_query . '&amp;table='
. htmlspecialchars($version_data['table_name']);
$delete_link = 'db_tracking.php' . $url_query . '&amp;table='
. htmlspecialchars($version_data['table_name'])
. '&amp;delete_tracking=true&amp';
$checkbox_id = "selected_tbl_"
. htmlspecialchars($version_data['table_name']);
?>
<tr class="noclick <?php echo $style;?>">
<td class="center">
<input type="checkbox" name="selected_tbl[]"
class="checkall" id="<?php echo $checkbox_id;?>"
value="<?php echo htmlspecialchars($version_data['table_name']);?>"/>
</td>
<th>
<label for="<?php echo $checkbox_id;?>">
<?php echo htmlspecialchars($version_data['table_name']);?>
</label>
</th>
<td class="right"><?php echo $version_data['version'];?></td>
<td><?php echo $version_data['date_created'];?></td>
<td><?php echo $version_data['date_updated'];?></td>
<td>
<?php
$state = PMA_getVersionStatus($version_data);
$options = array(
0 => array(
'label' => __('not active'),
'value' => 'deactivate_now',
'selected' => ($state != 'active')
),
1 => array(
'label' => __('active'),
'value' => 'activate_now',
'selected' => ($state == 'active')
)
);
echo PMA_Util::toggleButton(
$tmp_link . '&amp;version=' . $version_data['version'],
'toggle_activation',
$options,
null
);
?>
</td>
<td>
<a class="delete_tracking_anchor ajax" href="<?php echo $delete_link;?>" >
<?php echo $delete; ?></a>
<?php
echo '</td>'
. '<td>'
. '<a href="' . $tmp_link . '">' . $versions . '</a>'
. '&nbsp;&nbsp;'
. '<a href="' . $tmp_link . '&amp;report=true&amp;version='
. $version_data['version'] . '">' . $report . '</a>'
. '&nbsp;&nbsp;'
. '<a href="' . $tmp_link . '&amp;snapshot=true&amp;version='
. $version_data['version'] . '">' . $structure . '</a>'
. '</td>'
. '</tr>';
if ($style == 'even') {
$style = 'odd';
} else {
$style = 'even';
}
}
unset($tmp_link);
?>
</tbody>
</table>
<?php
echo PMA_Util::getWithSelected($pmaThemeImage, $text_dir, "trackedForm");
echo PMA_Util::getButtonOrImage(
'submit_mult', 'mult_submit', 'submit_mult_delete_tracking',
__('Delete tracking'), 'b_drop.png', 'delete_tracking'
if (is_object($all_tables_result) && $GLOBALS['dbi']->numRows($all_tables_result) > 0) {
PMA_displayTrackedTables(
$GLOBALS['db'], $all_tables_result, $url_query, $pmaThemeImage,
$text_dir, $cfgRelation
);
?>
</form>
</div>
<?php
}
$sep = $GLOBALS['cfg']['NavigationTreeTableSeparator'];
// Get list of tables
$table_list = PMA_Util::getTableList($GLOBALS['db']);
$my_tables = array();
// For each table try to get the tracking version
foreach ($table_list as $key => $value) {
// If $value is a table group.
if (array_key_exists(('is' . $sep . 'group'), $value)
&& $value['is' . $sep . 'group']
) {
foreach ($value as $temp_table) {
// If $temp_table is a table with the value for 'Name' is set,
// rather than a property of the table group.
if (is_array($temp_table)
&& array_key_exists('Name', $temp_table)
) {
$tracking_version = PMA_Tracker::getVersion(
$GLOBALS['db'],
$temp_table['Name']
);
if ($tracking_version == -1) {
$my_tables[] = $temp_table['Name'];
}
}
}
} else { // If $value is a table.
if (PMA_Tracker::getVersion($GLOBALS['db'], $value['Name']) == -1) {
$my_tables[] = $value['Name'];
}
}
}
$untracked_tables = PMA_getUntrackedTables($GLOBALS['db']);
// If untracked tables exist
if (count($my_tables) > 0) {
?>
<h3><?php echo __('Untracked tables');?></h3>
<form method="post" action="db_tracking.php" name="untrackedForm"
id="untrackedForm" class="ajax">
<?php
echo PMA_URL_getHiddenInputs($GLOBALS['db'])
?>
<table id="noversions" class="data">
<thead>
<tr>
<th></th>
<th style="width: 300px"><?php echo __('Table');?></th>
<th><?php echo __('Action');?></th>
</tr>
</thead>
<tbody>
<?php
// Print out list of untracked tables
$style = 'odd';
foreach ($my_tables as $key => $tablename) {
$checkbox_id = "selected_tbl_"
. htmlspecialchars($tablename);
if (PMA_Tracker::getVersion($GLOBALS['db'], $tablename) == -1) {
$my_link = '<a href="tbl_tracking.php' . $url_query
. '&amp;table=' . htmlspecialchars($tablename) . '">';
$my_link .= PMA_Util::getIcon('eye.png', __('Track table'));
$my_link .= '</a>';
?>
<tr class="noclick <?php echo $style;?>">
<td class="center">
<input type="checkbox" name="selected_tbl[]"
class="checkall" id="<?php echo $checkbox_id;?>"
value="<?php echo htmlspecialchars($tablename);?>"/>
</td>
<th>
<label for="<?php echo $checkbox_id;?>">
<?php echo htmlspecialchars($tablename);?>
</label>
</th>
<td><?php echo $my_link;?></td>
</tr>
<?php
if ($style == 'even') {
$style = 'odd';
} else {
$style = 'even';
}
}
}
?>
</tbody>
</table>
<?php
echo PMA_Util::getWithSelected($pmaThemeImage, $text_dir, "untrackedForm");
echo PMA_Util::getButtonOrImage(
'submit_mult', 'mult_submit', 'submit_mult_track',
__('Track table'), 'eye.png', 'track'
if (count($untracked_tables) > 0) {
PMA_displayUntrackedTables(
$GLOBALS['db'], $untracked_tables, $url_query, $pmaThemeImage, $text_dir
);
?>
</form>
<?php
}
// If available print out database log
if (count($data['ddlog']) > 0) {
@ -346,5 +144,3 @@ if (count($data['ddlog']) > 0) {
}
echo PMA_Util::getMessage(__('Database Log'), $log);
}
?>

View File

@ -21,5 +21,3 @@ require_once 'libraries/rte/rte_triggers.lib.php';
*/
$_PMA_RTE = 'TRI';
require_once 'libraries/rte/rte_main.inc.php';
?>

View File

@ -179,7 +179,7 @@ class ConfigFileDomain(Domain):
labelid, contnode)
def get_objects(self):
for (type, name), info in self.data['objects'].iteritems():
for (type, name), info in self.data['objects'].items():
yield (name, name, type, info[0], info[1],
self.object_types[type].attrs['searchprio'])

View File

@ -51,7 +51,7 @@ copyright = u'2012 - 2014, The phpMyAdmin devel team'
# built documents.
#
# The short X.Y version.
version = '4.4.15'
version = '4.5.0'
# The full version, including alpha/beta/rc tags.
release = version
@ -127,7 +127,7 @@ html_theme = 'default'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
#html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied

View File

@ -144,6 +144,17 @@ Basic settings
set, and the :config:option:`$cfg['UserprefsDisallow']` directive should
contain ``'SendErrorReports'`` in one of its array values.
.. config:option:: $cfg['ConsoleEnterExecutes']
:type: boolean
:default: false
Setting this to ``true`` allows the user to execute queries by pressing Enter
instead of Ctrl+Enter. A new line can be inserted by pressing Shift + Enter.
The behaviour of the console can be temporarily changed using console's
settings interface.
.. config:option:: $cfg['AllowThirdPartyFraming']
:type: boolean
@ -159,7 +170,7 @@ Server connection settings
.. config:option:: $cfg['Servers']
:type: array
:default: one server array with settings listed bellow
:default: one server array with settings listed below
Since version 1.4.2, phpMyAdmin supports the administration of multiple
MySQL servers. Therefore, a :config:option:`$cfg['Servers']`-array has been
@ -771,6 +782,22 @@ Server connection settings
* put the table name in :config:option:`$cfg['Servers'][$i]['central_columns']` (e.g.
``pma__central_columns``)
.. _designer_settings:
.. config:option:: $cfg['Servers'][$i]['designer_settings']
:type: string
:default: ``''``
Since release 4.5.0 your designer settings can be remembered.
Your choice regarding 'Angular/Direct Links', 'Snap to Grid', 'Toggle Relation Lines',
'Small/Big All', 'Move Menu' and 'Pin Text' can be remembered persistently.
To allow the usage of this functionality:
* set up :config:option:`$cfg['Servers'][$i]['pmadb']` and the phpMyAdmin configuration storage
* put the table name in :config:option:`$cfg['Servers'][$i]['designer_settings']` (e.g.
``pma__designer_settings``)
.. _savedsearches:
.. config:option:: $cfg['Servers'][$i]['savedsearches']
@ -785,6 +812,20 @@ Server connection settings
* put the table name in :config:option:`$cfg['Servers'][$i]['savedsearches']` (e.g.
``pma__savedsearches``)
.. _export_templates:
.. config:option:: $cfg['Servers'][$i]['export_templates']
:type: string
:default: ``''``
Since release 4.5.0 you can save and load export templates.
To allow the usage of this functionality:
* set up :config:option:`$cfg['Servers'][$i]['pmadb']` and the phpMyAdmin configuration storage
* put the table name in :config:option:`$cfg['Servers'][$i]['export_templates']` (e.g.
``pma__export_templates``)
.. _tracking:
.. config:option:: $cfg['Servers'][$i]['tracking']
@ -1100,8 +1141,8 @@ Generic settings
:type: boolean
:default: true
Enables check for latest versions using javascript on main phpMyAdmin
page.
Enables check for latest versions using JavaScript on the main phpMyAdmin
page or by directly accessing :file:`version_check.php`.
.. note::
@ -1149,8 +1190,7 @@ Generic settings
:default: 250
The maximum number of table names to be displayed in the main panel's
list (except on the Export page). This limit is also enforced in the
navigation panel when in Light mode.
list (except on the Export page).
.. config:option:: $cfg['ShowHint']
@ -1223,10 +1263,12 @@ Generic settings
:default: ``'-1'``
Set the number of bytes a script is allowed to allocate. If set to
``'-1'``, no limit is imposed.
``'-1'``, no limit is imposed. If set to ``'0'``, no change of the
memory limit is attempted and the :file:`php.ini` ``memory_limit`` is
used.
This setting is used while importing/exporting dump files and at some other
places in phpMyAdmin so you definitely don't want to put here a too low
This setting is used while importing/exporting dump files
so you definitely don't want to put here a too low
value. It has no effect when PHP is running in safe mode.
You can also use any string as in :file:`php.ini`, eg. '16M'. Ensure you
@ -1266,6 +1308,16 @@ Generic settings
middle-clicking for pasting the clipboard contents in some Linux
distributions (such as Ubuntu) is not supported by all browsers.
.. config:option:: $cfg['DefaultForeignKeyChecks']
:type: string
:default: ``'default'``
Default value of the checkbox for foreign key checks, to disable/enable
foreign key checks for certain queries. The possible values are ``'default'``,
``'enable'`` or ``'disable'``. If set to ``'default'``, the value of the
MySQL variable ``FOREIGN_KEY_CHECKS`` is used.
.. config:option:: $cfg['AllowUserDropDatabase']
:type: boolean
@ -1524,9 +1576,9 @@ Navigation panel setup
:type: string
:default: ``'index.php'``
Enter :term:`URL` where logo in the navigation panel will point to.
Enter :term:`URL` where logo in the navigation panel will point to.
For use especially with self made theme which changes this.
For external :term:`URL`s, you should include URL scheme as well.
For external URLs, you should include URL scheme as well.
.. config:option:: $cfg['NavigationLogoLinkWindow']
@ -1578,16 +1630,17 @@ Navigation panel setup
.. config:option:: $cfg['NavigationTreeDefaultTabTable']
:type: string
:default: ``'tbl_structure.php'``
:default: ``'structure'``
Defines the tab displayed by default when clicking the small icon next
to each table name in the navigation panel. Possible values:
to each table name in the navigation panel. The possible values are the
localized equivalent of:
* ``tbl_structure.php``
* ``tbl_sql.php``
* ``tbl_select.php``
* ``tbl_change.php``
* ``sql.php``
* ``structure``
* ``sql``
* ``search``
* ``insert``
* ``browse``
.. config:option:: $cfg['NavigationTreeDefaultTabTable2']
@ -1595,14 +1648,15 @@ Navigation panel setup
:default: null
Defines the tab displayed by default when clicking the second small icon next
to each table name in the navigation panel. Possible values:
to each table name in the navigation panel. The possible values are the
localized equivalent of:
* ``(empty)``
* ``tbl_structure.php``
* ``tbl_sql.php``
* ``tbl_select.php``
* ``tbl_change.php``
* ``sql.php``
* ``structure``
* ``sql``
* ``search``
* ``insert``
* ``browse``
.. config:option:: $cfg['NavigationTreeEnableExpansion']
@ -1611,6 +1665,42 @@ Navigation panel setup
Whether to offer the possibility of tree expansion in the navigation panel.
.. config:option:: $cfg['NavigationTreeShowTables']
:type: boolean
:default: true
Whether to show tables under database in the navigation panel.
.. config:option:: $cfg['NavigationTreeShowViews']
:type: boolean
:default: true
Whether to show views under database in the navigation panel.
.. config:option:: $cfg['NavigationTreeShowFunctions']
:type: boolean
:default: true
Whether to show functions under database in the navigation panel.
.. config:option:: $cfg['NavigationTreeShowProcedures']
:type: boolean
:default: true
Whether to show procedures under database in the navigation panel.
.. config:option:: $cfg['NavigationTreeShowEvents']
:type: boolean
:default: true
Whether to show events under database in the navigation panel.
Main panel
----------
@ -1665,6 +1755,23 @@ Main panel
in the configuration file, end users can't be allowed to change their
passwords.
.. config:option:: $cfg['ShowGitRevision']
:type: boolean
:default: true
Defines whether to display informations about the current Git revision (if
applicable) on the main panel.
.. config:option:: $cfg['MysqlMinVersion']
:type: array
Defines the minimum supported MySQL version. The default is chosen
by the phpMyAdmin team; however this directive was asked by a developer
of the Plesk control panel to ease integration with older MySQL servers
(where most of the phpMyAdmin features work).
Database structure
------------------
@ -1929,40 +2036,41 @@ Tabs display settings
.. config:option:: $cfg['DefaultTabServer']
:type: string
:default: ``'index.php'``
:default: ``'welcome'``
Defines the tab displayed by default on server view. Possible values:
* ``main.php`` (recommended for multi-user setups)
* ``server_databases.php``,
* ``server_status.php``
* ``server_variables.php``
* ``server_privileges.php``
* ``welcome`` (recommended for multi-user setups)
* ``databases``,
* ``status``
* ``variables``
* ``privileges``
.. config:option:: $cfg['DefaultTabDatabase']
:type: string
:default: ``'db_structure.php'``
:default: ``'structure'``
Defines the tab displayed by default on database view. Possible
values:
* ``db_structure.php``
* ``db_sql.php``
* ``db_search.php``.
* ``structure``
* ``sql``
* ``search``
* ``operations``
.. config:option:: $cfg['DefaultTabTable']
:type: string
:default: ``'sql.php'``
:default: ``'browse'``
Defines the tab displayed by default on table view. Possible values:
* ``tbl_structure.php``
* ``tbl_sql.php``
* ``tbl_select.php``
* ``tbl_change.php``
* ``sql.php``
* ``structure``
* ``sql``
* ``search``
* ``insert``
* ``browse``
PDF Options
-----------
@ -2002,8 +2110,8 @@ Languages
:default: ``'utf8_general_ci'``
Defines the default connection collation to use, if not user-defined.
See the `MySQL documentation for charsets
<http://dev.mysql.com/doc/mysql/en/charset-charsets.html>`_
See the `MySQL documentation for charsets
<http://dev.mysql.com/doc/mysql/en/charset-charsets.html>`_
for list of possible values. This setting is
ignored when connected to Drizzle server.
@ -2142,7 +2250,7 @@ Web server settings
Additional string to include in allowed script and image sources in Content
Security Policy header.
This can be useful when you want to include some external javascript files
This can be useful when you want to include some external JavaScript files
in :file:`config.footer.inc.php` or :file:`config.header.inc.php`, which
would be normally not allowed by Content Security Policy.
@ -2336,6 +2444,16 @@ Design customization
put when tables contents are displayed (you may have them displayed at
the left side, right side, both sides or nowhere).
.. config:option:: $cfg['RowActionLinksWithoutUnique']
:type: boolean
:default: false
Defines whether to show row links (Edit, Copy, Delete) and checkboxes
for multiple row operations even when the selection does not have a unique key.
Using row actions in the absence of a unique key may result in different/more
rows being affected since there is no guaranteed way to select the exact row(s).
.. config:option:: $cfg['RememberSorting']
:type: boolean
@ -2445,6 +2563,14 @@ Text fields
Defines if the whole textarea of the query box will be selected on
click.
.. config:option:: $cfg['EnableAutocompleteForTablesAndColumns']
:type: boolean
:default: true
Whether to enable autocomplete for table and column names in any
SQL query box.
SQL query box settings
----------------------
@ -2783,7 +2909,7 @@ Developer
:default: false
Enable logging queries and execution times to be
displayed in the bottom of main page (right frame).
displayed in the console's Debug SQL tab.
.. config:option:: $cfg['DBG']['demo']
@ -2792,4 +2918,3 @@ Developer
Enable to let server present itself as demo server.
This is used for <http://demo.phpmyadmin.net/>.

View File

@ -37,7 +37,7 @@ Credits, in chronological order
* Loïc Chapeaux <lolo\_at\_phpheaven.net>
* rewrote and optimized javascript, DHTML and DOM stuff
* rewrote and optimized JavaScript, DHTML and DOM stuff
* rewrote the scripts so they fit the :term:`PEAR` coding standards and
generate XHTML1.0 and CSS2 compliant codes
@ -402,6 +402,18 @@ Credits, in chronological order
* Export with table/column name changes
* Dan Ungureanu (Google Summer of Code 2015)
* New parser and analyzer
* Nisarg Jhaveri (Google Summer of Code 2015)
* Page-related settings
* SQL debugging integration to the Console
* Other UI improvements
And also to the following people who have contributed minor changes,
enhancements, bugfixes or support for a new language since version
2.1.0:

View File

@ -385,8 +385,7 @@ MMCache but upgrading MMCache to version 2.3.21 solves the problem.
Yes.
Since release 4.1 phpMyAdmin supports only PHP 5.3 and newer. For PHP 5.2 you
can use 4.0.x releases.
Since release 4.5, phpMyAdmin supports only PHP 5.5 and newer. Since release 4.1 phpMyAdmin supports only PHP 5.3 and newer. For PHP 5.2 you can use 4.0.x releases.
.. _faq1_32:
@ -1593,8 +1592,8 @@ mimetypes by heart so he/she can enter it at will?
.. _faqbookmark:
6.18 Bookmarks: Where can I store bookmarks? Why can't I see any bookmarks below the query box? What is this variable for?
--------------------------------------------------------------------------------------------------------------------------
6.18 Bookmarks: Where can I store bookmarks? Why can't I see any bookmarks below the query box? What are these variables for?
-----------------------------------------------------------------------------------------------------------------------------
Any query you have executed can be stored as a bookmark on the page
where the results are displayed. You will find a button labeled
@ -1603,39 +1602,38 @@ stored a bookmark, it is related to the database you run the query on.
You can now access a bookmark dropdown on each page, the query box
appears on for that database.
You can also have, inside the query, a placeholder for a variable.
This is done by inserting into the query a SQL comment between ``/*`` and
``*/``. Inside the comment, the special string ``[VARIABLE]`` is used.
Be aware that the whole query minus the SQL comment must be
You can also have, inside the query, placeholders for variables.
This is done by inserting into the query SQL comments between ``/*`` and
``*/``. Inside the comments, the special strings ``[VARIABLE{variable-number}]`` is used.
Be aware that the whole query minus the SQL comments must be
valid by itself, otherwise you won't be able to store it as a bookmark.
When you execute the bookmark, everything typed into the *value*
input box on the query box page will replace the string ``/*[VARIABLE]*/`` in
When you execute the bookmark, everything typed into the *Variables*
input boxes on the query box page will replace the strings ``/*[VARIABLE{variable-number}]*/`` in
your stored query.
Also remember, that everything else inside the ``/*[VARIABLE]*/`` string for
Also remember, that everything else inside the ``/*[VARIABLE{variable-number}]*/`` string for
your query will remain the way it is, but will be stripped of the ``/**/``
chars. So you can use:
.. code-block:: mysql
/*, [VARIABLE] AS myname */
/*, [VARIABLE1] AS myname */
which will be expanded to
.. code-block:: mysql
, VARIABLE as myname
, VARIABLE1 as myname
in your query, where VARIABLE is the string you entered in the input box. If an
empty string is provided, no replacements are made.
in your query, where VARIABLE1 is the string you entered in the Variable 1 input box.
A more complex example. Say you have stored
this query:
.. code-block:: mysql
SELECT Name, Address FROM addresses WHERE 1 /* AND Name LIKE '%[VARIABLE]%' */
SELECT Name, Address FROM addresses WHERE 1 /* AND Name LIKE '%[VARIABLE1]%' */
Say, you now enter "phpMyAdmin" as the variable for the stored query, the full
query will be:
@ -1644,18 +1642,11 @@ query will be:
SELECT Name, Address FROM addresses WHERE 1 AND Name LIKE '%phpMyAdmin%'
You can use multiple occurrences of ``/*[VARIABLE]*/`` in a single query
(that is, multiple occurrences of the *same* variable).
**NOTE THE ABSENCE OF SPACES** inside the ``/**/`` construct. Any spaces
inserted there will be later also inserted as spaces in your query and may lead
to unexpected results especially when using the variable expansion inside of a
"LIKE ''" expression.
Your initial query which is going to be stored as a bookmark has to yield at
least one result row so you can store the bookmark. You may have that to work
around using well positioned ``/**/`` comments.
.. _faq6_19:
6.19 How can I create simple LATEX document to include exported table?
@ -2011,6 +2002,78 @@ Which says, OwnerEmail depends on OwnerLastName and OwnerFirstName.
OwnerPhone depends on OwnerLastName and OwnerFirstName.
PetType depends on PetBreed.
.. _faq6_38:
6.38 How can I reassign auto-incremented values?
------------------------------------------------
Some users prefer their AUTO_INCREMENT values to be consecutive; this is not
always the case after row deletion.
Here are the steps to accomplish this. These are manual steps because they
involve a manual verification at one point.
* Ensure that you have exclusive access to the table to rearrange
* On your primary key column (i.e. id), remove the AUTO_INCREMENT setting
* Delete your primary key in Structure > indexes
* Create a new column future_id as primary key, AUTO_INCREMENT
* Browse your table and verify that the new increments correspond to what
you're expecting
* Drop your old id column
* Rename the future_id column to id
* Move the new id column via Structure > Move columns
.. _faq6_39:
6.39 What is the "Adjust privileges" option when renaming, copying, or moving a database, table, column, or procedure?
----------------------------------------------------------------------------------------------------------------------
When renaming/copying/moving a database/table/column/procedure,
MySQL does not adjust the original privileges relating to these objects
on its own. By selecting this option, phpMyAdmin will adjust the privilege
table so that users have the same privileges on the new items.
For example: A user 'bob'@'localhost' has a 'SELECT' privilege on a
column named 'id'. Now, if this column is renamed to 'id_new'; MySQL,
on its own, would **not** adjust the column privileges to the new column name.
phpMyAdmin can make this adjustment for you automatically.
Notes:
* While adjusting privileges for a database, the privileges of all
database-related elements (tables, columns and procedures) are also adjusted
to the database's new name.
* Similarly, while adjusting privileges for a table, the privileges of all
the columns inside the new table are also adjusted.
* While adjusting privileges, the user performing the operation **must** have the following
privileges:
* SELECT, INSERT, UPDATE, DELETE privileges on following tables:
`mysql`.`db`, `mysql`.`columns_priv`, `mysql`.`tables_priv`, `mysql`.`procs_priv`
* FLUSH privilege (GLOBAL)
Thus, if you want to replicate the database/table/column/procedure as it is
while renaming/copying/moving these objects, make sure you have checked this option.
.. _faq6_40:
6.40 I see "Bind parameters" checkbox in the "SQL" page. How do I write parameterized SQL queries?
--------------------------------------------------------------------------------------------------
From version 4.5, phpMyAdmin allows users to execute parameterized queries in the "SQL" page.
Parameters should be prefixed with a colon(:) and when the "Bind parameters" checkbox is checked
these parameters will be identified and input fields for these parameters will be presented.
Values entered in these field will be substituted in the query before being executed.
.. _faqproject:
phpMyAdmin project

View File

@ -6,13 +6,13 @@ Requirements
Web server
----------
Since, phpMyAdmin's interface is based entirely in your browser, you'll need a
web server (such as Apache, :term:`IIS`) to install phpMyAdmin's files into.
Since phpMyAdmin's interface is based entirely in your browser, you'll need a
web server (such as Apache, nginx, :term:`IIS`) to install phpMyAdmin's files into.
PHP
---
* You need PHP 5.3.7 or newer, with ``session`` support, the Standard PHP Library
* You need PHP 5.5.0 or newer, with ``session`` support, the Standard PHP Library
(SPL) extension, JSON support, and the ``mbstring`` extension.
* To support uploading of ZIP files, you need the PHP ``zip`` extension.
@ -49,6 +49,6 @@ phpMyAdmin supports MySQL-compatible databases.
Web browser
-----------
To access phpMyAdmin you need a web browser with cookies and javascript
To access phpMyAdmin you need a web browser with cookies and JavaScript
enabled.

View File

@ -96,6 +96,7 @@ Quick Install
Downloads page. Some kits contain only the English messages, others
contain all languages. We'll assume you chose a kit whose name
looks like ``phpMyAdmin-x.x.x -all-languages.tar.gz``.
#. Ensure you have downloaded a genuine archive, see :ref:`verify`.
#. Untar or unzip the distribution (be sure to unzip the subdirectories):
``tar -xzvf phpMyAdmin_x.x.x-all-languages.tar.gz`` in your
webserver's document root. If you don't have direct access to your
@ -245,6 +246,97 @@ options which the setup script does not provide.
webserver or limit access by web server configuration, see
:ref:`faq1_42`.
.. _verify:
Verifying phpMyAdmin releases
+++++++++++++++++++++++++++++
Since July 2015 all phpMyAdmin releases are cryptographically signed by the
releasing developer, who is currently Marc Delisle. His key id is
0x81AF644A, his PGP fingerprint is:
.. code-block:: console
436F F188 4B1A 0C3F DCBF 0D79 FEFC 65D1 81AF 644A
and you can get more identification information from `https://keybase.io/lem9 <https://keybase.io/lem9>`_. You should verify that the signature matches
the archive you have downloaded. This way you can be sure that you are using
the same code that was released.
Each archive is accompanied with ``.asc`` files which contains the PGP signature
for it. Once you have both of them in the same folder, you can verify the signature:
.. code-block:: console
$ gpg --verify phpMyAdmin-4.4.9-all-languages.zip.asc
gpg: Signature made Fri Jun 12 13:09:58 2015 CEST using RSA key ID 81AF644A
gpg: Can't check signature: No public key
As you can see gpg complains that it does not know the public key. At this
point you should do one of the following steps:
* Download the keyring from `our download server <https://files.phpmyadmin.net/phpmyadmin.keyring>`_, then import it with:
.. code-block:: console
$ gpg --import phpmyadmin.keyring
* Download and import the key from one of the key servers:
.. code-block:: console
$ gpg --keyserver hkp://pgp.mit.edu --recv-keys 81AF644A
gpg: requesting key 81AF644A from hkp server pgp.mit.edu
gpg: key 81AF644A: public key "Marc Delisle <marc@infomarc.info>" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg: imported: 1 (RSA: 1)
This will improve the situation a bit - at this point you can verify that the
signature from the given key is correct but you still can not trust the name used
in the key:
.. code-block:: console
$ gpg --verify phpMyAdmin-4.4.9-all-languages.zip.asc
gpg: Signature made Fri Jun 12 13:09:58 2015 CEST using RSA key ID 81AF644A
gpg: Good signature from "Marc Delisle <marc@infomarc.info>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
Primary key fingerprint: 436F F188 4B1A 0C3F DCBF 0D79 FEFC 65D1 81AF 644A
The problem here is that anybody could issue the key with this name. You need to
ensure that the key is actually owned by the mentioned person. The GNU Privacy
Handbook covers this topic in the chapter `Validating other keys on your public
keyring`_. The most reliable method is to meet the developer in person and
exchange key fingerprints, however you can also rely on the web of trust. This way
you can trust the key transitively though signatures of others, who have met
the developer in person. For example you can see how `Marc's key links to
Linus's key`_.
Once the key is trusted, the warning will not occur:
.. code-block:: console
$ gpg --verify phpMyAdmin-4.4.9-all-languages.zip.asc
gpg: Signature made Fri Jun 12 13:09:58 2015 CEST using RSA key ID 81AF644A
gpg: Good signature from "Marc Delisle <marc@infomarc.info>" [full]
Should the signature be invalid (the archive has been changed), you would get a
clear error regardless of the fact that the key is trusted or not:
.. code-block:: console
$ gpg --verify phpMyAdmin-4.4.9-all-languages.zip.asc
gpg: Signature made Fri Jun 12 13:09:58 2015 CEST using RSA key ID 81AF644A
gpg: BAD signature from "Marc Delisle <marc@infomarc.info>" [unknown]
.. _Validating other keys on your public keyring: https://www.gnupg.org/gph/en/manual.html#AEN335
.. _Marc's key links to Linus's key: http://pgp.cs.uu.nl/mk_path.cgi?FROM=00411886&TO=81AF644A
.. index::
single: Configuration storage
single: phpMyAdmin configuration storage
@ -351,6 +443,9 @@ newer (<= 4.2.x) and if you use the phpMyAdmin configuration storage, you
should run the :term:`SQL` script found in
:file:`sql/upgrade_column_info_4_3_0+.sql`.
Do not forget to clear the browser cache and to empty the old session by
logging out and logging in again.
.. index:: Authentication mode
.. _authentication_modes:
@ -537,7 +632,23 @@ are always ways to make your installation more secure:
phpMyAdmin, you can use :config:option:`$cfg['Servers'][$i]['AllowDeny']['rules']` to limit them.
* Consider hiding phpMyAdmin behind an authentication proxy, so that
users need to authenticate prior to providing MySQL credentials
to phpMyAdmin.
to phpMyAdmin. You can achieve this by configuring your web server to request
HTTP authentication. For example in Apache this can be done with:
.. code-block:: apache
AuthType Basic
AuthName "Restricted Access"
AuthUserFile /usr/share/phpmyadmin/passwd
Require valid-user
Once you have changed configuration, you need to create list of users which
can authenticate. This can be done using the :program:`htpasswd` utility:
.. code-block:: sh
htpasswd -c /usr/share/phpmyadmin/passwd username
* If you are afraid of automated attacks, enabling Captcha by
:config:option:`$cfg['CaptchaLoginPublicKey']` and
:config:option:`$cfg['CaptchaLoginPrivateKey']` might be an option.

View File

@ -127,4 +127,3 @@ if (isset($_REQUEST['send_error_report'])
$GLOBALS['error_handler']->savePreviousErrors();
}
}
?>

View File

@ -48,4 +48,6 @@ foreach ($hosts as $host) {
$cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
$cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
$cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
$cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
$cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
}

View File

@ -33,5 +33,3 @@ function get_login_credentials($user)
return $credentials;
}
?>

View File

@ -49,15 +49,19 @@ if (!defined('TESTSUITE')) {
'quick_or_custom',
'db_select',
'table_select',
'table_structure',
'table_data',
'limit_to',
'limit_from',
'allrows',
'lock_tables',
'output_format',
'filename_template',
'maxsize',
'remember_template',
'charset_of_file',
'charset',
'compression',
'as_separate_files',
'knjenc',
'xkana',
'htmlword_structure_or_data',
@ -85,6 +89,7 @@ if (!defined('TESTSUITE')) {
'ods_structure_or_data',
'ods_columns',
'json_structure_or_data',
'json_pretty_print',
'xml_structure_or_data',
'xml_export_events',
'xml_export_functions',
@ -109,7 +114,6 @@ if (!defined('TESTSUITE')) {
'sql_create_database',
'sql_drop_table',
'sql_procedure_function',
'sql_create_table_statements',
'sql_create_table',
'sql_create_view',
'sql_create_trigger',
@ -126,6 +130,7 @@ if (!defined('TESTSUITE')) {
'sql_utc_time',
'sql_drop_database',
'sql_views_as_tables',
'sql_metadata',
'csv_separator',
'csv_enclosed',
'csv_escaped',
@ -164,6 +169,7 @@ if (!defined('TESTSUITE')) {
PMA_Util::checkParameters(array('what', 'export_type'));
// export class instance, not array of properties, as before
/* @var $export_plugin ExportPlugin */
$export_plugin = PMA_getPlugin(
"export",
$what,
@ -178,15 +184,10 @@ if (!defined('TESTSUITE')) {
$type = $what;
// Check export type
if (! isset($export_plugin)) {
if (empty($export_plugin)) {
PMA_fatalError(__('Bad type!'));
}
// Avoid warning from PHP Analyzer
if (is_null($export_plugin)) {
$export_plugin = new stdClass();
}
/**
* valid compression methods
*/
@ -207,6 +208,7 @@ if (!defined('TESTSUITE')) {
$file_handle = '';
$err_url = '';
$filename = '';
$separate_files = '';
// Is it a quick or custom export?
if ($_REQUEST['quick_or_custom'] == 'quick') {
@ -219,6 +221,16 @@ if (!defined('TESTSUITE')) {
$asfile = false;
} else {
$asfile = true;
if (isset($_REQUEST['as_separate_files'])
&& ! empty($_REQUEST['as_separate_files'])
) {
if (isset($_REQUEST['compression'])
&& ! empty($_REQUEST['compression'])
&& $_REQUEST['compression'] == 'zip'
) {
$separate_files = $_REQUEST['as_separate_files'];
}
}
if (in_array($_REQUEST['compression'], $compression_methods)) {
$compression = $_REQUEST['compression'];
$buffer_needed = true;
@ -266,14 +278,20 @@ if (!defined('TESTSUITE')) {
// Merge SQL Query aliases with Export aliases from
// export page, Export page aliases are given more
// preference over SQL Query aliases.
if (!empty($_REQUEST['aliases'])) {
$aliases = PMA_mergeAliases(
PMA_SQP_getAliasesFromQuery($sql_query, $db),
$_REQUEST['aliases']
);
$_SESSION['tmpval']['aliases'] = $_REQUEST['aliases'];
} else {
$aliases = PMA_SQP_getAliasesFromQuery($sql_query, $db);
$parser = new SqlParser\Parser($sql_query);
$aliases = array();
if ((!empty($parser->statements[0]))
&& ($parser->statements[0] instanceof SqlParser\Statements\SelectStatement)
) {
if (!empty($_REQUEST['aliases'])) {
$aliases = PMA_mergeAliases(
SqlParser\Utils\Misc::getAliases($parser->statements[0], $db),
$_REQUEST['aliases']
);
$_SESSION['tmpval']['aliases'] = $_REQUEST['aliases'];
} else {
$aliases = SqlParser\Utils\Misc::getAliases($parser->statements[0], $db);
}
}
/**
@ -288,6 +306,9 @@ if (!defined('TESTSUITE')) {
$dump_buffer = '';
$dump_buffer_len = 0;
// Array of dump_buffers - used in separate file exports
$dump_buffer_objects = array();
// We send fake headers to avoid browser timeout when buffering
$time_start = time();
@ -305,7 +326,7 @@ if (!defined('TESTSUITE')) {
// Do we need to convert charset?
$output_charset_conversion = $asfile
&& $GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE
&& isset($charset_of_file) && $charset_of_file != 'utf-8'
&& isset($charset) && $charset != 'utf-8'
&& $type != 'xls';
// Use on the fly compression?
@ -377,9 +398,12 @@ if (!defined('TESTSUITE')) {
do {
// Add possibly some comments to export
if (! $export_plugin->exportHeader($db)) {
if (! $export_plugin->exportHeader()) {
break;
}
// Re - initialize
$dump_buffer = '';
$dump_buffer_len = 0;
// Will we need relation & co. setup?
$do_relation = isset($GLOBALS[$what . '_relation']);
@ -408,14 +432,40 @@ if (!defined('TESTSUITE')) {
PMA_exportServer(
$db_select, $whatStrucOrData, $export_plugin, $crlf, $err_url,
$export_type, $do_relation, $do_comments, $do_mime, $do_dates,
$aliases
$aliases, $separate_files
);
} elseif ($export_type == 'database') {
PMA_exportDatabase(
$db, $tables, $whatStrucOrData, $export_plugin, $crlf, $err_url,
$export_type, $do_relation, $do_comments, $do_mime, $do_dates,
$aliases
);
if (!isset($table_structure) || !is_array($table_structure)) {
$table_structure = array();
}
if (!isset($table_data) || !is_array($table_data)) {
$table_data = array();
}
if (!empty($_REQUEST['structure_or_data_forced'])) {
$table_structure = $tables;
$table_data = $tables;
}
if (isset($lock_tables)) {
PMA_lockTables($db, $tables, "READ");
try {
PMA_exportDatabase(
$db, $tables, $whatStrucOrData, $table_structure,
$table_data, $export_plugin, $crlf, $err_url, $export_type,
$do_relation, $do_comments, $do_mime, $do_dates, $aliases,
$separate_files
);
PMA_unlockTables();
} catch (Exception $e) { // TODO use finally when PHP version is 5.5
PMA_unlockTables();
throw $e;
}
} else {
PMA_exportDatabase(
$db, $tables, $whatStrucOrData, $table_structure, $table_data,
$export_plugin, $crlf, $err_url, $export_type, $do_relation,
$do_comments, $do_mime, $do_dates, $aliases, $separate_files
);
}
} else {
// We export just one table
// $allrows comes from the form when "Dump all rows" has been selected
@ -428,11 +478,27 @@ if (!defined('TESTSUITE')) {
if (! isset($limit_from)) {
$limit_from = 0;
}
PMA_exportTable(
$db, $table, $whatStrucOrData, $export_plugin, $crlf, $err_url,
$export_type, $do_relation, $do_comments, $do_mime, $do_dates,
$allrows, $limit_to, $limit_from, $sql_query, $aliases
);
if (isset($lock_tables)) {
try {
PMA_lockTables($db, array($table), "READ");
PMA_exportTable(
$db, $table, $whatStrucOrData, $export_plugin, $crlf,
$err_url, $export_type, $do_relation, $do_comments,
$do_mime, $do_dates, $allrows, $limit_to, $limit_from,
$sql_query, $aliases
);
PMA_unlockTables();
} catch (Exception $e) { // TODO use finally when PHP version is 5.5
PMA_unlockTables();
throw $e;
}
} else {
PMA_exportTable(
$db, $table, $whatStrucOrData, $export_plugin, $crlf, $err_url,
$export_type, $do_relation, $do_comments, $do_mime, $do_dates,
$allrows, $limit_to, $limit_from, $sql_query, $aliases
);
}
}
if (! $export_plugin->exportFooter()) {
break;
@ -448,33 +514,39 @@ if (!defined('TESTSUITE')) {
/**
* Send the dump as a file...
*/
if (! empty($asfile)) {
// Convert the charset if required.
if ($output_charset_conversion) {
$dump_buffer = PMA_convertString(
'utf-8',
$GLOBALS['charset_of_file'],
$dump_buffer
);
}
// Compression needed?
if ($compression) {
$dump_buffer
= PMA_compressExport($dump_buffer, $compression, $filename);
}
/* If we saved on server, we have to close file now */
if ($save_on_server) {
$message = PMA_closeExportFile(
$file_handle, $dump_buffer, $save_filename
);
PMA_showExportPage($db, $table, $export_type);
} else {
echo $dump_buffer;
}
} else {
if (empty($asfile)) {
echo PMA_getHtmlForDisplayedExportFooter($back_button);
return;
} // end if
// Convert the charset if required.
if ($output_charset_conversion) {
$dump_buffer = PMA_convertString(
'utf-8',
$GLOBALS['charset'],
$dump_buffer
);
}
// Compression needed?
if ($compression) {
if (! empty($separate_files)) {
$dump_buffer = PMA_compressExport(
$dump_buffer_objects, $compression, $filename
);
} else {
$dump_buffer = PMA_compressExport($dump_buffer, $compression, $filename);
}
}
/* If we saved on server, we have to close file now */
if ($save_on_server) {
$message = PMA_closeExportFile(
$file_handle, $dump_buffer, $save_filename
);
PMA_showExportPage($db, $table, $export_type);
} else {
echo $dump_buffer;
}
}
?>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 22 KiB

View File

@ -78,4 +78,3 @@ if (isset($_REQUEST['filename']) && isset($_REQUEST['image'])) {
}
echo file_get_contents($_FILES['file']['tmp_name']);
}
?>

View File

@ -22,7 +22,6 @@ function escape($variable)
require_once 'libraries/common.inc.php';
require_once 'libraries/gis/GIS_Factory.class.php';
require_once 'libraries/gis/GIS_Visualization.class.php';
require_once 'libraries/tbl_gis_visualization.lib.php';
// Get data if any posted
$gis_data = array();
@ -89,10 +88,11 @@ $visualizationSettings = array(
'spatialColumn' => 'wkt'
);
$data = array(array('wkt' => $wkt_with_zero, 'srid' => $srid));
$visualization = PMA_GIS_visualizationResults(
$data, $visualizationSettings, $format
);
$open_layers = PMA_GIS_visualizationResults($data, $visualizationSettings, 'ol');
$visualization = PMA_GIS_Visualization::getByData($data, $visualizationSettings)
->toImage($format);
$open_layers = PMA_GIS_Visualization::getByData($data, $visualizationSettings)
->asOl();
// If the call is to update the WKT and visualization make an AJAX response
if (isset($_REQUEST['generate']) && $_REQUEST['generate'] == true) {
@ -301,7 +301,7 @@ for ($a = 0; $a < $geom_count; $a++) {
echo '<label for="y">' . __("Y") . '</label>';
echo '<input type="text" name="gis_data[' . $a . '][' . $type . ']['
. $i . '][' . $j . '][y]"' . ' value="'
. escape($gis_data[$a][$type][$i][$j]['x']) . '" />';
. escape($gis_data[$a][$type][$i][$j]['y']) . '" />';
}
echo '<input type="submit" name="gis_data[' . $a . '][' . $type . ']['
. $i . '][add_point]"'
@ -426,4 +426,3 @@ echo '</form>';
PMA_Response::getInstance()->addJSON('gis_editor', ob_get_contents());
ob_end_clean();
?>

View File

@ -68,7 +68,6 @@ if (isset($_REQUEST['console_bookmark_add'])) {
* Sets globals from $_POST
*/
$post_params = array(
'bkm_label',
'charset_of_file',
'format',
'import_type',
@ -76,7 +75,6 @@ $post_params = array(
'MAX_FILE_SIZE',
'message_to_show',
'noplugin',
'skip',
'skip_queries',
'local_import_file'
);
@ -100,9 +98,31 @@ if (!isset($_SESSION['is_multi_query'])) {
$_SESSION['is_multi_query'] = false;
}
$ajax_reload = array();
// Are we just executing plain query or sql file?
// (eg. non import, but query box/window run)
if (! empty($sql_query)) {
// apply values for parameters
if (! empty($_REQUEST['parameterized'])) {
$parameters = $_REQUEST['parameters'];
foreach ($parameters as $parameter => $replacement) {
$quoted = preg_quote($parameter);
// making sure that :param does not apply values to :param1
$sql_query = preg_replace(
'/' . $quoted . '([^a-zA-Z0-9_])/',
PMA_Util::sqlAddSlashes($replacement) . '${1}',
$sql_query
);
// for parameters the appear at the end of the string
$sql_query = preg_replace(
'/' . $quoted . '$/',
PMA_Util::sqlAddSlashes($replacement),
$sql_query
);
}
}
// run SQL query
$import_text = $sql_query;
$import_type = 'query';
@ -117,6 +137,7 @@ if (! empty($sql_query)) {
// refresh navigation and main panels
if (preg_match('/^(DROP)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i', $sql_query)) {
$GLOBALS['reload'] = true;
$ajax_reload['reload'] = true;
}
// refresh navigation panel only
@ -124,7 +145,7 @@ if (! empty($sql_query)) {
'/^(CREATE|ALTER)\s+(VIEW|TABLE|DATABASE|SCHEMA)\s+/i',
$sql_query
)) {
$ajax_reload = array('reload' => true);
$ajax_reload['reload'] = true;
}
// do a dynamic reload if table is RENAMED
@ -134,17 +155,11 @@ if (! empty($sql_query)) {
$sql_query,
$rename_table_names
)) {
$ajax_reload = array('reload' => true);
$ajax_reload['reload'] = true;
$ajax_reload['table_name'] = PMA_Util::unQuote($rename_table_names[2]);
}
$sql_query = '';
} elseif (! empty($sql_localfile)) {
// run SQL file on server
$local_import_file = $sql_localfile;
$import_type = 'queryfile';
$format = 'sql';
unset($sql_localfile);
} elseif (! empty($sql_file)) {
// run uploaded SQL file
$import_file = $sql_file;
@ -161,7 +176,10 @@ if (! empty($sql_query)) {
// upload limit has been reached, let's assume the second possibility.
if ($_POST == array() && $_GET == array()) {
$message = PMA_Message::error(
__('You probably tried to upload a file that is too large. Please refer to %sdocumentation%s for a workaround for this limit.')
__(
'You probably tried to upload a file that is too large. Please refer ' .
'to %sdocumentation%s for a workaround for this limit.'
)
);
$message->addParam('[doc@faq1-16]');
$message->addParam('[/doc]');
@ -311,9 +329,7 @@ if (! empty($_REQUEST['id_bookmark'])) {
isset($_REQUEST['action_bookmark_all'])
);
if (! empty($_REQUEST['bookmark_variable'])) {
$import_text = preg_replace(
'|/\*(.*)\[VARIABLE\](.*)\*/|imsU',
'${1}' . PMA_Util::sqlAddSlashes($_REQUEST['bookmark_variable']) . '${2}',
$import_text = PMA_Bookmark_applyVariables(
$import_text
);
}
@ -324,6 +340,7 @@ if (! empty($_REQUEST['id_bookmark'])) {
$import_text
)) {
$GLOBALS['reload'] = true;
$ajax_reload['reload'] = true;
}
// refresh navigation panel only
@ -332,9 +349,6 @@ if (! empty($_REQUEST['id_bookmark'])) {
$import_text
)
) {
if (! isset($ajax_reload)) {
$ajax_reload = array();
}
$ajax_reload['reload'] = true;
}
break;
@ -452,7 +466,11 @@ if ($import_file != 'none' && ! $error) {
// instead.
$message = PMA_Message::error(
__('Uploaded file cannot be moved, because the server has open_basedir enabled without access to the %s directory (for temporary files).')
__(
'Uploaded file cannot be moved, because the server has ' .
'open_basedir enabled without access to the %s directory ' .
'(for temporary files).'
)
);
$message->addParam($tmp_subdir);
PMA_stopImport($message);
@ -475,7 +493,11 @@ if ($import_file != 'none' && ! $error) {
$import_handle = @bzopen($import_file, 'r');
} else {
$message = PMA_Message::error(
__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
__(
'You attempted to load file with unsupported compression ' .
'(%s). Either support for it is not implemented or disabled ' .
'by your configuration.'
)
);
$message->addParam($compression);
PMA_stopImport($message);
@ -486,7 +508,11 @@ if ($import_file != 'none' && ! $error) {
$import_handle = @gzopen($import_file, 'r');
} else {
$message = PMA_Message::error(
__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
__(
'You attempted to load file with unsupported compression ' .
'(%s). Either support for it is not implemented or disabled ' .
'by your configuration.'
)
);
$message->addParam($compression);
PMA_stopImport($message);
@ -507,7 +533,11 @@ if ($import_file != 'none' && ! $error) {
}
} else {
$message = PMA_Message::error(
__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
__(
'You attempted to load file with unsupported compression ' .
'(%s). Either support for it is not implemented or disabled ' .
'by your configuration.'
)
);
$message->addParam($compression);
PMA_stopImport($message);
@ -518,7 +548,11 @@ if ($import_file != 'none' && ! $error) {
break;
default:
$message = PMA_Message::error(
__('You attempted to load file with unsupported compression (%s). Either support for it is not implemented or disabled by your configuration.')
__(
'You attempted to load file with unsupported compression (%s). ' .
'Either support for it is not implemented or disabled by your ' .
'configuration.'
)
);
$message->addParam($compression);
PMA_stopImport($message);
@ -532,7 +566,11 @@ if ($import_file != 'none' && ! $error) {
} elseif (! $error) {
if (! isset($import_text) || empty($import_text)) {
$message = PMA_Message::error(
__('No data was received to import. Either no file name was submitted, or the file size exceeded the maximum size permitted by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].')
__(
'No data was received to import. Either no file name was ' .
'submitted, or the file size exceeded the maximum size permitted ' .
'by your PHP configuration. See [doc@faq1-16]FAQ 1.16[/doc].'
)
);
PMA_stopImport($message);
}
@ -565,9 +603,9 @@ if ($GLOBALS['PMA_recoding_engine'] != PMA_CHARSET_NONE && isset($charset_of_fil
}
}
// Something to skip?
if (! $error && isset($skip)) {
$original_skip = $skip;
// Something to skip? (because timeout has passed)
if (! $error && isset($_POST['skip'])) {
$original_skip = $skip = $_POST['skip'];
while ($skip > 0) {
PMA_importGetNextChunk($skip < $read_limit ? $skip : $read_limit);
// Disable read progressivity, otherwise we eat all memory!
@ -584,6 +622,7 @@ $sql_data = array('valid_sql' => array(), 'valid_queries' => 0);
if (! $error) {
// Check for file existence
include_once "libraries/plugin_interface.lib.php";
/* @var $import_plugin ImportPlugin */
$import_plugin = PMA_getPlugin(
"import",
$format,
@ -597,7 +636,14 @@ if (! $error) {
PMA_stopImport($message);
} else {
// Do the real import
$import_plugin->doImport($sql_data);
try {
$default_fk_check = PMA_Util::handleDisableFKCheckInit();
$import_plugin->doImport($sql_data);
PMA_Util::handleDisableFKCheckCleanup($default_fk_check);
} catch (Exception $e) {
PMA_Util::handleDisableFKCheckCleanup($default_fk_check);
throw $e;
}
}
}
@ -628,7 +674,7 @@ if (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 2) {
} elseif ($bookmark_created) {
$special_message = '[br]' . sprintf(
__('Bookmark %s has been created.'),
htmlspecialchars($bkm_label)
htmlspecialchars($_POST['bkm_label'])
);
} elseif ($finished && ! $error) {
if ($import_type == 'query') {
@ -656,7 +702,9 @@ if (! empty($id_bookmark) && $_REQUEST['action_bookmark'] == 2) {
// Did we hit timeout? Tell it user.
if ($timeout_passed) {
$importUrl = $err_url .= '&timeout_passed=1&offset=' . urlencode($GLOBALS['offset']);
$importUrl = $err_url .= '&timeout_passed=1&offset=' . urlencode(
$GLOBALS['offset']
);
if (isset($local_import_file)) {
$importUrl .= '&local_import_file=' . urlencode($local_import_file);
}
@ -718,19 +766,27 @@ if ($go_sql) {
include 'libraries/parse_analyze.inc.php';
$html_output .= PMA_executeQueryAndGetQueryResponse(
$analyzed_sql_results, false, $db, $table, null,
$sql_query, null, $analyzed_sql_results['is_affected'],
null, null, null, $goto, $pmaThemeImage,
null, null, null, $sql_query, null, null
$analyzed_sql_results, // analyzed_sql_results
false, // is_gotofile
$db, // db
$table, // table
null, // find_real_end
$sql_query, // sql_query_for_bookmark
null, // extra_data
null, // message_to_show
null, // message
null, // sql_data
$goto, // goto
$pmaThemeImage, // pmaThemeImage
null, // disp_query
null, // disp_message
null, // query_type
$sql_query, // sql_query
null, // selectedTables
null // complete_query
);
}
if (!isset($ajax_reload)) {
$ajax_reload = array();
}
if (isset($table)) {
$ajax_reload['table_name'] = $table;
}
$response = PMA_Response::getInstance();
$response->addJSON('ajax_reload', $ajax_reload);
$response->addHTML($html_output);
@ -767,4 +823,3 @@ if ($go_sql) {
if (isset($_REQUEST['rollback_query'])) {
$GLOBALS['dbi']->query('ROLLBACK');
}
?>

View File

@ -115,4 +115,3 @@ if (isset($_GET["message"]) && $_GET["message"]) {
} else {
PMA_importAjaxStatus($_GET["id"]);
}
?>

104
index.php
View File

@ -15,6 +15,7 @@ require_once 'libraries/common.inc.php';
* display Git revision if requested
*/
require_once 'libraries/display_git_revision.lib.php';
require_once 'libraries/Template.class.php';
/**
* pass variables to child pages
@ -38,9 +39,9 @@ unset($drops, $each_drop);
* Such scripts must not be loaded on home page.
*
*/
$target_blacklist = array (
$target_blacklist = array (
'import.php', 'export.php'
);
);
// If we have a valid target, let's load that script instead
if (! empty($_REQUEST['target'])
@ -61,9 +62,13 @@ if (isset($_REQUEST['ajax_request']) && ! empty($_REQUEST['access_time'])) {
if (! empty($_REQUEST['db'])) {
$page = null;
if (! empty($_REQUEST['table'])) {
$page = $GLOBALS['cfg']['DefaultTabTable'];
$page = PMA_Util::getScriptNameForOption(
$GLOBALS['cfg']['DefaultTabTable'], 'table'
);
} else {
$page = $GLOBALS['cfg']['DefaultTabDatabase'];
$page = PMA_Util::getScriptNameForOption(
$GLOBALS['cfg']['DefaultTabDatabase'], 'database'
);
}
include $page;
exit;
@ -155,7 +160,7 @@ if ($server > 0 || count($cfg['Servers']) > 1
echo '</div>';
}
echo '<div class="group">';
echo '<h2>' . __('General Settings') . '</h2>';
echo '<h2>' . __('General settings') . '</h2>';
echo '<ul>';
/**
@ -183,7 +188,7 @@ if ($server > 0 || count($cfg['Servers']) > 1
if ($cfg['ShowChgPassword']) {
$conditional_class = 'ajax';
PMA_printListItem(
PMA_Util::getImage('s_passwd.png') . " " . __('Change password'),
PMA_Util::getImage('s_passwd.png') . "&nbsp;" . __('Change password'),
'li_change_password',
'user_password.php' . $common_url_query,
null,
@ -198,7 +203,7 @@ if ($server > 0 || count($cfg['Servers']) > 1
echo ' <form method="post" action="index.php">' . "\n"
. PMA_URL_getHiddenInputs(null, null, 4, 'collation_connection')
. ' <label for="select_collation_connection">' . "\n"
. ' ' . PMA_Util::getImage('s_asci.png') . " "
. ' ' . PMA_Util::getImage('s_asci.png') . "&nbsp;"
. __('Server connection collation') . "\n"
// put the doc link in the form so that it appears on the same line
. PMA_Util::showMySQLDocu('Charset-connection')
@ -221,7 +226,7 @@ if ($server > 0 || count($cfg['Servers']) > 1
}
echo '<div class="group">';
echo '<h2>' . __('Appearance Settings') . '</h2>';
echo '<h2>' . __('Appearance settings') . '</h2>';
echo ' <ul>';
// Displays language selection combo
@ -251,7 +256,7 @@ echo '</ul>';
if ($server > 0) {
echo '<ul>';
PMA_printListItem(
PMA_Util::getImage('b_tblops.png') . " " . __('More settings'),
PMA_Util::getImage('b_tblops.png') . "&nbsp;" . __('More settings'),
'li_user_preferences',
'prefs_manage.php' . $common_url_query,
null,
@ -492,7 +497,13 @@ if ($cfg['LoginCookieValidityDisableWarning'] == false) {
$gc_time = (int)@ini_get('session.gc_maxlifetime');
if ($gc_time < $GLOBALS['cfg']['LoginCookieValidity'] ) {
trigger_error(
__('Your PHP parameter [a@http://php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime@_blank]session.gc_maxlifetime[/a] is lower than cookie validity configured in phpMyAdmin, because of this, your login might expire sooner than configured in phpMyAdmin.'),
__(
'Your PHP parameter [a@http://php.net/manual/en/session.' .
'configuration.php#ini.session.gc-maxlifetime@_blank]session.' .
'gc_maxlifetime[/a] is lower than cookie validity configured ' .
'in phpMyAdmin, because of this, your login might expire sooner ' .
'than configured in phpMyAdmin.'
),
E_USER_WARNING
);
}
@ -505,7 +516,11 @@ if ($GLOBALS['cfg']['LoginCookieStore'] != 0
&& $GLOBALS['cfg']['LoginCookieStore'] < $GLOBALS['cfg']['LoginCookieValidity']
) {
trigger_error(
__('Login cookie store is lower than cookie validity configured in phpMyAdmin, because of this, your login will expire sooner than configured in phpMyAdmin.'),
__(
'Login cookie store is lower than cookie validity configured in ' .
'phpMyAdmin, because of this, your login will expire sooner than ' .
'configured in phpMyAdmin.'
),
E_USER_WARNING
);
}
@ -517,7 +532,9 @@ if (! empty($_SESSION['encryption_key'])
&& empty($GLOBALS['cfg']['blowfish_secret'])
) {
trigger_error(
__('The configuration file now needs a secret passphrase (blowfish_secret).'),
__(
'The configuration file now needs a secret passphrase (blowfish_secret).'
),
E_USER_WARNING
);
}
@ -528,7 +545,13 @@ if (! empty($_SESSION['encryption_key'])
*/
if (file_exists('config')) {
trigger_error(
__('Directory [code]config[/code], which is used by the setup script, still exists in your phpMyAdmin directory. It is strongly recommended to remove it once phpMyAdmin has been configured. Otherwise the security of your server may be compromised by unauthorized people downloading your configuration.'),
__(
'Directory [code]config[/code], which is used by the setup script, ' .
'still exists in your phpMyAdmin directory. It is strongly ' .
'recommended to remove it once phpMyAdmin has been configured. ' .
'Otherwise the security of your server may be compromised by ' .
'unauthorized people downloading your configuration.'
),
E_USER_WARNING
);
}
@ -594,7 +617,11 @@ if (isset($GLOBALS['dbi'])
trigger_error(
PMA_sanitize(
sprintf(
__('Your PHP MySQL library version %s differs from your MySQL server version %s. This may cause unpredictable behavior.'),
__(
'Your PHP MySQL library version %s differs from your ' .
'MySQL server version %s. This may cause unpredictable ' .
'behavior.'
),
$_client_info,
substr(
PMA_MYSQL_STR_VERSION,
@ -618,7 +645,10 @@ if ($cfg['SuhosinDisableWarning'] == false
) {
trigger_error(
sprintf(
__('Server running with Suhosin. Please refer to %sdocumentation%s for possible issues.'),
__(
'Server running with Suhosin. Please refer to %sdocumentation%s ' .
'for possible issues.'
),
'[doc@faq1-38]',
'[/doc]'
),
@ -669,33 +699,19 @@ function PMA_printListItem($name, $listId = null, $url = null,
$mysql_help_page = null, $target = null, $a_id = null, $class = null,
$a_class = null
) {
echo '<li id="' . $listId . '"';
if (null !== $class) {
echo ' class="' . $class . '"';
}
echo '>';
if (null !== $url) {
echo '<a href="' . $url . '"';
if (null !== $target) {
echo ' target="' . $target . '"';
}
if (null != $a_id) {
echo ' id="' . $a_id . '"';
}
if (null != $a_class) {
echo ' class="' . $a_class . '"';
}
echo '>';
}
echo $name;
if (null !== $url) {
echo '</a>' . "\n";
}
if (null !== $mysql_help_page) {
echo PMA_Util::showMySQLDocu($mysql_help_page);
}
echo '</li>';
echo PMA\Template::get('list/item')
->render(
array(
'content' => $name,
'id' => $listId,
'class' => $class,
'url' => array(
'href' => $url,
'target' => $target,
'id' => $a_id,
'class' => $a_class,
),
'mysql_help_page' => $mysql_help_page,
)
);
}
?>

View File

@ -153,7 +153,12 @@ var AJAX = {
* @todo Fix Code mirror does not give correct full value (query)
* in textarea, it returns only the change in content.
*/
var newHash = AJAX.hash($(this).val());
var newHash = null;
if (event.data.value == 1) {
newHash = AJAX.hash($(this).val());
} else {
newHash = AJAX.hash($(this).is(":checked"));
}
var oldHash = $(this).data('val-hash');
// Set lock if old value != new value
// otherwise release lock
@ -179,6 +184,15 @@ var AJAX = {
AJAX.lockedTargets = {};
$('#lock_page_icon').html('');
},
handleMenu: {
replace: function (content) {
$('#floating_menubar').html(content)
// Remove duplicate wrapper
// TODO: don't send it in the response
.children().first().remove();
$('#topmenu').menuResizer(PMA_mainMenuResizerCallback);
}
},
/**
* Event handler for clicks on links and form submissions
*
@ -226,6 +240,8 @@ var AJAX = {
return false;
}
AJAX.resetLock();
var isLink = !! href || false;
var previousLinkAborted = false;
if (AJAX.active === true) {
// Cancel the old request if abortable, when the user requests
@ -239,6 +255,7 @@ var AJAX = {
AJAX.$msgbox = PMA_ajaxShowMessage(PMA_messages.strAbortedRequest);
AJAX.active = false;
AJAX.xhr = null;
previousLinkAborted = true;
} else {
//If can't abort
return false;
@ -253,14 +270,15 @@ var AJAX = {
$('html, body').animate({scrollTop: 0}, 'fast');
var isLink = !! href || false;
var url = isLink ? href : $(this).attr('action');
var params = 'ajax_request=true&ajax_page_request=true';
if (! isLink) {
params += '&' + $(this).serialize();
}
// Add a list of menu hashes that we have in the cache to the request
params += AJAX.cache.menus.getRequestParam();
if (! (history && history.pushState)) {
// Add a list of menu hashes that we have in the cache to the request
params += PMA_MicroHistory.menus.getRequestParam();
}
if (AJAX._debug) {
console.log("Loading: " + url); // no need to translate
@ -271,6 +289,18 @@ var AJAX = {
AJAX.$msgbox = PMA_ajaxShowMessage();
//Save reference for the new link request
AJAX.xhr = $.get(url, params, AJAX.responseHandler);
if (history && history.pushState) {
var state = {
url : href
};
if (previousLinkAborted) {
//hack: there is already an aborted entry on stack
//so just modify the aborted one
history.replaceState(state, null, href);
} else {
history.pushState(state, null, href);
}
}
} else {
/**
* Manually fire the onsubmit event for the form, if any.
@ -305,7 +335,6 @@ var AJAX = {
return;
}
if (typeof data.success != 'undefined' && data.success) {
$table_clone = false;
$('html, body').animate({scrollTop: 0}, 'fast');
PMA_ajaxRemoveMessage(AJAX.$msgbox);
@ -324,10 +353,27 @@ var AJAX = {
$('title').replaceWith(data._title);
}
if (data._menu) {
AJAX.cache.menus.replace(data._menu);
AJAX.cache.menus.add(data._menuHash, data._menu);
if (history && history.pushState) {
var state = {
url : data._selflink,
menu : data._menu
};
history.replaceState(state, null);
AJAX.handleMenu.replace(data._menu);
} else {
PMA_MicroHistory.menus.replace(data._menu);
PMA_MicroHistory.menus.add(data._menuHash, data._menu);
}
} else if (data._menuHash) {
AJAX.cache.menus.replace(AJAX.cache.menus.get(data._menuHash));
if (! (history && history.pushState)) {
PMA_MicroHistory.menus.replace(PMA_MicroHistory.menus.get(data._menuHash));
}
}
if (data._disableNaviSettings) {
PMA_disableNaviSettings();
}
else {
PMA_ensureNaviSettings(data._selflink);
}
// Remove all containers that may have
@ -335,15 +381,14 @@ var AJAX = {
$('body').children()
.not('#pma_navigation')
.not('#floating_menubar')
.not('#goto_pagetop')
.not('#lock_page_icon')
.not('#page_nav_icons')
.not('#page_content')
.not('#selflink')
.not('#session_debug')
.not('#pma_header')
.not('#pma_footer')
.not('#pma_demo')
.not('#pma_console_container')
.not('#prefs_autoload')
.remove();
// Replace #page_content with new content
if (data.message && data.message.length > 0) {
@ -355,29 +400,35 @@ var AJAX = {
}
if (data._selflink) {
var source = data._selflink.split('?')[0];
//Check for faulty links
if (source == "import.php") {
var replacement = "tbl_sql.php";
data._selflink = data._selflink.replace(source,replacement);
$selflink_replace = {
"import.php": "tbl_sql.php",
"tbl_chart.php": "sql.php",
"tbl_gis_visualization.php": "sql.php"
};
if ($selflink_replace[source]) {
var replacement = $selflink_replace[source];
data._selflink = data._selflink.replace(source, replacement);
}
$('#selflink > a').attr('href', data._selflink);
$('#selflink').find('> a').attr('href', data._selflink);
}
if (data._params) {
PMA_commonParams.setAll(data._params);
}
if (data._scripts) {
AJAX.scriptHandler.load(data._scripts);
}
if (data._selflink && data._scripts && data._menuHash && data._params) {
AJAX.cache.add(
data._selflink,
data._scripts,
data._menuHash,
data._params,
AJAX.source.attr('rel')
);
}
if (data._params) {
PMA_commonParams.setAll(data._params);
if (! (history && history.pushState)) {
PMA_MicroHistory.add(
data._selflink,
data._scripts,
data._menuHash,
data._params,
AJAX.source.attr('rel')
);
}
}
if (data._displayMessage) {
$('#page_content').prepend(data._displayMessage);
@ -390,18 +441,17 @@ var AJAX = {
if(data._errSubmitMsg){
msg = data._errSubmitMsg;
}
if (data._debug) {
$('#session_debug').replaceWith(data._debug);
}
if (data._errors) {
$('<div/>', {id : 'pma_errors'})
.insertAfter('#selflink')
.append(data._errors);
// bind for php error reporting forms (bottom)
$("#pma_ignore_errors_bottom").bind("click", function() {
$("#pma_ignore_errors_bottom").bind("click", function(e) {
e.preventDefault();
PMA_ignorePhpErrors();
});
$("#pma_ignore_all_errors_bottom").bind("click", function() {
$("#pma_ignore_all_errors_bottom").bind("click", function(e) {
e.preventDefault();
PMA_ignorePhpErrors(false);
});
// In case of 'sendErrorReport'='always'
@ -433,6 +483,7 @@ var AJAX = {
}
AJAX._callback = function () {};
});
} else {
PMA_ajaxShowMessage(data.error, false);
AJAX.active = false;
@ -462,6 +513,11 @@ var AJAX = {
* @var array _scripts The list of files already downloaded
*/
_scripts: [],
/**
* @var string _scriptsVersion version of phpMyAdmin from which the
* scripts have been loaded
*/
_scriptsVersion: null,
/**
* @var array _scriptsToBeLoaded The list of files that
* need to be downloaded
@ -497,8 +553,16 @@ var AJAX = {
*
* @return void
*/
load: function (files) {
load: function (files, callback) {
var self = this;
// Clear loaded scripts if they are from another version of phpMyAdmin.
// Depends on common params being set before loading scripts in responseHandler
if (self._scriptsVersion == null) {
self._scriptsVersion = PMA_commonParams.get('PMA_VERSION');
} else if (self._scriptsVersion != PMA_commonParams.get('PMA_VERSION')) {
self._scripts = [];
self._scriptsVersion = PMA_commonParams.get('PMA_VERSION');
}
self._scriptsToBeLoaded = [];
self._scriptsToBeFired = [];
for (var i in files) {
@ -520,11 +584,12 @@ var AJAX = {
}
}
request.push("call_done=1");
request.push("v=" + encodeURIComponent(PMA_commonParams.get('PMA_VERSION')));
// Download the composite js file, if necessary
if (needRequest) {
this.appendScript("js/get_scripts.js.php?" + request.join("&"));
} else {
self.done();
self.done(callback);
}
},
/**
@ -532,7 +597,10 @@ var AJAX = {
*
* @return void
*/
done: function () {
done: function (callback) {
if($.isFunction(callback)) {
callback();
}
if (typeof ErrorReport !== 'undefined') {
ErrorReport.wrap_global_functions();
}
@ -573,7 +641,9 @@ var AJAX = {
*/
$(document).off('click', 'a').on('click', 'a', AJAX.requestHandler);
$(document).off('submit', 'form').on('submit', 'form', AJAX.requestHandler);
AJAX.cache.update();
if (! (history && history.pushState)) {
PMA_MicroHistory.update();
}
callback();
}
}
@ -596,11 +666,12 @@ AJAX.registerOnload('functions.js', function () {
}
});
var $page_content = $('#page_content');
/**
* Workaround for passing submit button name,value on ajax form submit
* by appending hidden element with submit button name and value.
*/
$("#page_content").on('click', 'form input[type=submit]', function() {
$page_content.on('click', 'form input[type=submit]', function() {
var buttonName = $(this).attr('name');
if (typeof buttonName === 'undefined') {
return;
@ -614,12 +685,22 @@ AJAX.registerOnload('functions.js', function () {
/**
* Attach event listener to events when user modify visible
* Input or Textarea fields to make changes in forms
* Input,Textarea and select fields to make changes in forms
*/
$('#page_content').on(
$page_content.on(
'keyup change',
'form.lock-page textarea, ' +
'form.lock-page input[type="text"]',
'form.lock-page input[type="text"], ' +
'form.lock-page input[type="number"], ' +
'form.lock-page select',
{value:1},
AJAX.lockPageHandler
);
$page_content.on(
'change',
'form.lock-page input[type="checkbox"], ' +
'form.lock-page input[type="radio"]',
{value:2},
AJAX.lockPageHandler
);
/**
@ -632,375 +713,68 @@ AJAX.registerOnload('functions.js', function () {
});
});
/**
* Unbind all event handlers before tearing down a page
*/
AJAX.registerTeardown('functions.js', function () {
$('#page_content').off('keyup change',
'form.lock-page textarea, ' +
'form.lock-page input[type="text"]'
);
$('form.lock-page').off('reset');
});
/**
* An implementation of a client-side page cache.
* This object also uses the cache to provide a simple microhistory,
* that is the ability to use the back and forward buttons in the browser
*/
AJAX.cache = {
/**
* @var int The maximum number of pages to keep in the cache
*/
MAX: 6,
/**
* @var object A hash used to prime the cache with data about the initially
* loaded page. This is set in the footer, and then loaded
* by a double-queued event further down this file.
*/
primer: {},
/**
* @var array Stores the content of the cached pages
*/
pages: [],
/**
* @var int The index of the currently loaded page
* This is used to know at which point in the history we are
*/
current: 0,
/**
* Saves a new page in the cache
*
* @param string hash The hash part of the url that is being loaded
* @param array scripts A list of scripts that is required for the page
* @param string menu A hash that links to a menu stored
* in a dedicated menu cache
* @param array params A list of parameters used by PMA_commonParams()
* @param string rel A relationship to the current page:
* 'samepage': Forces the response to be treated as
* the same page as the current one
* 'newpage': Forces the response to be treated as
* a new page
* undefined: Default behaviour, 'samepage' if the
* selflinks of the two pages are the same.
* 'newpage' otherwise
*
* @return void
*/
add: function (hash, scripts, menu, params, rel) {
if (this.pages.length > AJAX.cache.MAX) {
// Trim the cache, to the maximum number of allowed entries
// This way we will have a cached menu for every page
for (var i = 0; i < this.pages.length - this.MAX; i++) {
delete this.pages[i];
}
}
while (this.current < this.pages.length) {
// trim the cache if we went back in the history
// and are now going forward again
this.pages.pop();
}
if (rel === 'newpage' ||
(
typeof rel === 'undefined' && (
typeof this.pages[this.current - 1] === 'undefined' ||
this.pages[this.current - 1].hash !== hash
)
)
) {
this.pages.push({
hash: hash,
content: $('#page_content').html(),
scripts: scripts,
selflink: $('#selflink').html(),
menu: menu,
params: params
});
AJAX.setUrlHash(this.current, hash);
this.current++;
}
},
/**
* Restores a page from the cache. This is called when the hash
* part of the url changes and it's structure appears to be valid
*
* @param string index Which page from the history to load
*
* @return void
*/
navigate: function (index) {
if (typeof this.pages[index] === 'undefined' ||
typeof this.pages[index].content === 'undefined' ||
typeof this.pages[index].menu === 'undefined' ||
! AJAX.cache.menus.get(this.pages[index].menu)
) {
PMA_ajaxShowMessage(
'<div class="error">' + PMA_messages.strInvalidPage + '</div>',
false
);
} else {
AJAX.active = true;
var record = this.pages[index];
AJAX.scriptHandler.reset(function () {
$('#page_content').html(record.content);
$('#selflink').html(record.selflink);
AJAX.cache.menus.replace(AJAX.cache.menus.get(record.menu));
PMA_commonParams.setAll(record.params);
AJAX.scriptHandler.load(record.scripts);
AJAX.cache.current = ++index;
});
}
},
/**
* Resaves the content of the current page in the cache.
* Necessary in order not to show the user some outdated version of the page
*
* @return void
*/
update: function () {
var page = this.pages[this.current - 1];
if (page) {
page.content = $('#page_content').html();
}
},
/**
* @var object Dedicated menu cache
*/
menus: {
/**
* Returns the number of items in an associative array
*
* @return int
*/
size: function (obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
size++;
}
}
return size;
},
/**
* @var hash Stores the content of the cached menus
*/
data: {},
/**
* Saves a new menu in the cache
*
* @param string hash The hash (trimmed md5) of the menu to be saved
* @param string content The HTML code of the menu to be saved
*
* @return void
*/
add: function (hash, content) {
if (this.size(this.data) > AJAX.cache.MAX) {
// when the cache grows, we remove the oldest entry
var oldest, key, init = 0;
for (var i in this.data) {
if (this.data[i]) {
if (! init || this.data[i].timestamp.getTime() < oldest.getTime()) {
oldest = this.data[i].timestamp;
key = i;
init = 1;
}
}
}
delete this.data[key];
}
this.data[hash] = {
content: content,
timestamp: new Date()
};
},
/**
* Retrieves a menu given its hash
*
* @param string hash The hash of the menu to be retrieved
*
* @return string
*/
get: function (hash) {
if (this.data[hash]) {
return this.data[hash].content;
} else {
// This should never happen as long as the number of stored menus
// is larger or equal to the number of pages in the page cache
return '';
}
},
/**
* Prepares part of the parameter string used during page requests,
* this is necessary to tell the server which menus we have in the cache
*
* @return string
*/
getRequestParam: function () {
var param = '';
var menuHashes = [];
for (var i in this.data) {
menuHashes.push(i);
}
var menuHashesParam = menuHashes.join('-');
if (menuHashesParam) {
param = '&menuHashes=' + menuHashesParam;
}
return param;
},
/**
* Replaces the menu with new content
*
* @return void
*/
replace: function (content) {
$('#floating_menubar').html(content)
// Remove duplicate wrapper
// TODO: don't send it in the response
.children().first().remove();
$('#topmenu').menuResizer(PMA_mainMenuResizerCallback);
}
}
};
/**
* URL hash management module.
* Allows direct bookmarking and microhistory.
*/
AJAX.setUrlHash = (function (jQuery, window) {
"use strict";
/**
* Indictaes whether we have already completed
* the initialisation of the hash
*
* @access private
*/
var ready = false;
/**
* Stores a hash that needed to be set when we were not ready
*
* @access private
*/
var savedHash = "";
/**
* Flag to indicate if the change of hash was triggered
* by a user pressing the back/forward button or if
* the change was triggered internally
*
* @access private
*/
var userChange = true;
// Fix favicon disappearing in Firefox when setting location.hash
function resetFavicon() {
if (navigator.userAgent.indexOf('Firefox') > -1) {
// Move the link tags for the favicon to the bottom
// of the head element to force a reload of the favicon
$('head > link[href=favicon\\.ico]').appendTo('head');
}
}
/**
* Sets the hash part of the URL
*
* @access public
*/
function setUrlHash(index, hash) {
/*
* Known problem:
* Setting hash leads to reload in webkit:
* http://www.quirksmode.org/bugreports/archives/2005/05/Safari_13_visual_anomaly_with_windowlocationhref.html
*
* so we expect that users are not running an ancient Safari version
*/
userChange = false;
if (ready) {
window.location.hash = "PMAURL-" + index + ":" + hash;
resetFavicon();
} else {
savedHash = "PMAURL-" + index + ":" + hash;
}
}
/**
* Start initialisation
*/
if (window.location.hash.substring(0, 8) == '#PMAURL-') {
// We have a valid hash, let's redirect the user
// to the page that it's pointing to
var colon_position = window.location.hash.indexOf(':');
var questionmark_position = window.location.hash.indexOf('?');
if (colon_position != -1 && questionmark_position != -1 && colon_position < questionmark_position) {
var hash_url = window.location.hash.substring(colon_position + 1, questionmark_position);
if (PMA_gotoWhitelist.indexOf(hash_url) != -1) {
window.location = window.location.hash.substring(
colon_position + 1
);
}
}
} else {
// We don't have a valid hash, so we'll set it up
// when the page finishes loading
jQuery(function () {
/* Check if we should set URL */
if (savedHash !== "") {
window.location.hash = savedHash;
savedHash = "";
resetFavicon();
}
// Indicate that we're done initialising
ready = true;
});
}
/**
* Register an event handler for when the url hash changes
*/
jQuery(function () {
jQuery(window).hashchange(function () {
if (userChange === false) {
// Ignore internally triggered hash changes
userChange = true;
} else if (/^#PMAURL-\d+:/.test(window.location.hash)) {
// Change page if the hash changed was triggered by a user action
var index = window.location.hash.substring(
8, window.location.hash.indexOf(':')
);
AJAX.cache.navigate(index);
}
});
});
/**
* Publicly exposes a reference to the otherwise private setUrlHash function
*/
return setUrlHash;
})(jQuery, window);
/**
* Page load event handler
*/
$(function () {
// Add the menu from the initial page into the cache
// The cache primer is set by the footer class
if (AJAX.cache.primer.url) {
AJAX.cache.menus.add(
AJAX.cache.primer.menuHash,
$('<div></div>')
.append('<div></div>')
.append($('#serverinfo').clone())
.append($('#topmenucontainer').clone())
.html()
);
var menuContent = $('<div></div>')
.append($('#serverinfo').clone())
.append($('#topmenucontainer').clone())
.html();
if (history && history.pushState) {
//set initial state reload
var initState = ('state' in window.history && window.history.state !== null);
var initURL = $('#selflink').find('> a').attr('href') || location.href;
var state = {
url : initURL,
menu : menuContent
};
history.replaceState(state, null);
$(window).on('popstate', function(event) {
var initPop = (! initState && location.href == initURL);
initState = true;
//check if popstate fired on first page itself
if (initPop) {
return;
}
var state = event.originalEvent.state;
if (state && state.menu) {
AJAX.$msgbox = PMA_ajaxShowMessage();
var params = 'ajax_request=true&ajax_page_request=true';
var url = state.url || location.href;
$.get(url, params, AJAX.responseHandler);
//TODO: Check if sometimes menu is not retrieved from server,
// Not sure but it seems menu was missing only for printview which
// been removed lately, so if it's right some dead menu checks/fallbacks
// may need to be removed from this file and Header.class.php
//AJAX.handleMenu.replace(event.originalEvent.state.menu);
}
});
} else {
// Fallback to microhistory mechanism
AJAX.scriptHandler
.load([{'name' : 'microhistory.js', 'fire' : 1}], function () {
// The cache primer is set by the footer class
if (PMA_MicroHistory.primer.url) {
PMA_MicroHistory.menus.add(
PMA_MicroHistory.primer.menuHash,
menuContent
);
}
$(function () {
// Queue up this event twice to make sure that we get a copy
// of the page after all other onload events have been fired
if (PMA_MicroHistory.primer.url) {
PMA_MicroHistory.add(
PMA_MicroHistory.primer.url,
PMA_MicroHistory.primer.scripts,
PMA_MicroHistory.primer.menuHash
);
}
});
});
}
$(function () {
// Queue up this event twice to make sure that we get a copy
// of the page after all other onload events have been fired
if (AJAX.cache.primer.url) {
AJAX.cache.add(
AJAX.cache.primer.url,
AJAX.cache.primer.scripts,
AJAX.cache.primer.menuHash
);
}
});
});
/**

View File

@ -1,4 +1,4 @@
Copyright (C) 2014 by Marijn Haverbeke <marijnh@gmail.com> and others
Copyright (C) 2015 by Marijn Haverbeke <marijnh@gmail.com> and others
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

38
js/codemirror/addon/hint/show-hint.css vendored Normal file
View File

@ -0,0 +1,38 @@
.CodeMirror-hints {
position: absolute;
z-index: 10;
overflow: hidden;
list-style: none;
margin: 0;
padding: 2px;
-webkit-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
-moz-box-shadow: 2px 3px 5px rgba(0,0,0,.2);
box-shadow: 2px 3px 5px rgba(0,0,0,.2);
border-radius: 3px;
border: 1px solid silver;
background: white;
font-size: 90%;
font-family: monospace;
max-height: 20em;
overflow-y: auto;
}
.CodeMirror-hint {
margin: 0;
padding: 0 4px;
border-radius: 2px;
max-width: 19em;
overflow: hidden;
white-space: pre;
color: black;
cursor: pointer;
}
li.CodeMirror-hint-active {
background: #08f;
color: white;
}

View File

@ -24,44 +24,45 @@
return cm.showHint(newOpts);
};
var asyncRunID = 0;
function retrieveHints(getter, cm, options, then) {
if (getter.async) {
var id = ++asyncRunID;
getter(cm, function(hints) {
if (asyncRunID == id) then(hints);
}, options);
} else {
then(getter(cm, options));
}
}
CodeMirror.defineExtension("showHint", function(options) {
// We want a single cursor position.
if (this.listSelections().length > 1 || this.somethingSelected()) return;
if (this.state.completionActive) this.state.completionActive.close();
var completion = this.state.completionActive = new Completion(this, options);
var getHints = completion.options.hint;
if (!getHints) return;
if (!completion.options.hint) return;
CodeMirror.signal(this, "startCompletion", this);
return retrieveHints(getHints, this, completion.options, function(hints) { completion.showHints(hints); });
completion.update(true);
});
function Completion(cm, options) {
this.cm = cm;
this.options = this.buildOptions(options);
this.widget = this.onClose = null;
this.widget = null;
this.debounce = 0;
this.tick = 0;
this.startPos = this.cm.getCursor();
this.startLen = this.cm.getLine(this.startPos.line).length;
var self = this;
cm.on("cursorActivity", this.activityFunc = function() { self.cursorActivity(); });
}
var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
return setTimeout(fn, 1000/60);
};
var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
Completion.prototype = {
close: function() {
if (!this.active()) return;
this.cm.state.completionActive = null;
this.tick = null;
this.cm.off("cursorActivity", this.activityFunc);
if (this.widget && this.data) CodeMirror.signal(this.data, "close");
if (this.widget) this.widget.close();
if (this.onClose) this.onClose();
CodeMirror.signal(this.cm, "endCompletion", this.cm);
},
@ -78,70 +79,50 @@
this.close();
},
showHints: function(data) {
if (!data || !data.list.length || !this.active()) return this.close();
cursorActivity: function() {
if (this.debounce) {
cancelAnimationFrame(this.debounce);
this.debounce = 0;
}
if (this.options.completeSingle && data.list.length == 1)
this.pick(data, 0);
else
this.showWidget(data);
var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line);
if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch ||
pos.ch < this.startPos.ch || this.cm.somethingSelected() ||
(pos.ch && this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) {
this.close();
} else {
var self = this;
this.debounce = requestAnimationFrame(function() {self.update();});
if (this.widget) this.widget.disable();
}
},
showWidget: function(data) {
this.widget = new Widget(this, data);
CodeMirror.signal(data, "shown");
var debounce = 0, completion = this, finished;
var closeOn = this.options.closeCharacters;
var startPos = this.cm.getCursor(), startLen = this.cm.getLine(startPos.line).length;
var requestAnimationFrame = window.requestAnimationFrame || function(fn) {
return setTimeout(fn, 1000/60);
};
var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout;
function done() {
if (finished) return;
finished = true;
completion.close();
completion.cm.off("cursorActivity", activity);
if (data) CodeMirror.signal(data, "close");
update: function(first) {
if (this.tick == null) return;
if (this.data) CodeMirror.signal(this.data, "update");
if (!this.options.hint.async) {
this.finishUpdate(this.options.hint(this.cm, this.options), first);
} else {
var myTick = ++this.tick, self = this;
this.options.hint(this.cm, function(data) {
if (self.tick == myTick) self.finishUpdate(data, first);
}, this.options);
}
},
function update() {
if (finished) return;
CodeMirror.signal(data, "update");
retrieveHints(completion.options.hint, completion.cm, completion.options, finishUpdate);
}
function finishUpdate(data_) {
data = data_;
if (finished) return;
if (!data || !data.list.length) return done();
if (completion.widget) completion.widget.close();
completion.widget = new Widget(completion, data);
}
finishUpdate: function(data, first) {
this.data = data;
function clearDebounce() {
if (debounce) {
cancelAnimationFrame(debounce);
debounce = 0;
}
}
function activity() {
clearDebounce();
var pos = completion.cm.getCursor(), line = completion.cm.getLine(pos.line);
if (pos.line != startPos.line || line.length - pos.ch != startLen - startPos.ch ||
pos.ch < startPos.ch || completion.cm.somethingSelected() ||
(pos.ch && closeOn.test(line.charAt(pos.ch - 1)))) {
completion.close();
var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle);
if (this.widget) this.widget.close();
if (data && data.list.length) {
if (picked && data.list.length == 1) {
this.pick(data, 0);
} else {
debounce = requestAnimationFrame(update);
if (completion.widget) completion.widget.close();
this.widget = new Widget(this, data);
CodeMirror.signal(data, "shown");
}
}
this.cm.on("cursorActivity", activity);
this.onClose = done;
},
buildOptions: function(options) {
@ -206,6 +187,7 @@
function Widget(completion, data) {
this.completion = completion;
this.data = data;
this.picked = false;
var widget = this, cm = completion.cm;
var hints = this.hints = document.createElement("ul");
@ -320,6 +302,13 @@
cm.off("scroll", this.onScroll);
},
disable: function() {
this.completion.cm.removeKeyMap(this.keyMap);
var widget = this;
this.keyMap = {Enter: function() { widget.picked = true; }};
this.completion.cm.addKeyMap(this.keyMap);
},
pick: function() {
this.completion.pick(this.data, this.selectedHint);
},

View File

@ -52,12 +52,9 @@
function addMatches(result, search, wordlist, formatter) {
for (var word in wordlist) {
if (!wordlist.hasOwnProperty(word)) continue;
if (Array.isArray(wordlist)) {
word = wordlist[word];
}
if (match(search, word)) {
result.push(formatter(word));
}
if (wordlist.slice) word = wordlist[word];
if (match(search, word)) result.push(formatter(word));
}
}
@ -115,21 +112,28 @@
string = nameParts.pop();
var table = nameParts.join(".");
var alias = false;
var aliasTable = table;
// Check if table is available. If not, find table by Alias
if (!getItem(tables, table))
if (!getItem(tables, table)) {
var oldTable = table;
table = findTableByAlias(table, editor);
if (table !== oldTable) alias = true;
}
var columns = getItem(tables, table);
if (columns && Array.isArray(tables) && columns.columns)
if (columns && columns.columns)
columns = columns.columns;
if (columns) {
addMatches(result, string, columns, function(w) {
var tableInsert = table;
if (alias == true) tableInsert = aliasTable;
if (typeof w == "string") {
w = table + "." + w;
w = tableInsert + "." + w;
} else {
w = shallowClone(w);
w.text = table + "." + w.text;
w.text = tableInsert + "." + w.text;
}
return useBacktick ? insertBackticks(w) : w;
});
@ -208,6 +212,7 @@
CodeMirror.registerHelper("hint", "sql", function(editor, options) {
tables = (options && options.tables) || {};
var defaultTableName = options && options.defaultTable;
var disableKeywords = options && options.disableKeywords;
defaultTable = defaultTableName && getItem(tables, defaultTableName);
keywords = keywords || getKeywords(editor);
@ -216,7 +221,7 @@
defaultTable = defaultTable || [];
if (Array.isArray(tables) && defaultTable.columns)
if (defaultTable.columns)
defaultTable = defaultTable.columns;
var cur = editor.getCursor();
@ -240,7 +245,8 @@
} else {
addMatches(result, search, tables, function(w) {return w;});
addMatches(result, search, defaultTable, function(w) {return w;});
addMatches(result, search, keywords, function(w) {return w.toUpperCase();});
if (!disableKeywords)
addMatches(result, search, keywords, function(w) {return w.toUpperCase();});
}
return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)};

77
js/codemirror/addon/lint/lint.css vendored Normal file
View File

@ -0,0 +1,77 @@
/* The lint marker gutter */
.CodeMirror-lint-markers {
width: 16px;
}
.CodeMirror-lint-tooltip {
background-color: infobackground;
border: 1px solid black;
border-radius: 4px 4px 4px 4px;
color: infotext;
font-size: 10pt;
overflow: hidden;
padding: 2px 5px;
position: fixed;
white-space: pre;
white-space: pre-wrap;
z-index: 100;
max-width: 600px;
opacity: 0;
transition: opacity .4s;
-moz-transition: opacity .4s;
-webkit-transition: opacity .4s;
-o-transition: opacity .4s;
-ms-transition: opacity .4s;
}
.CodeMirror-lint-tooltip code {
font-family: monospace;
font-weight: bold;
}
.CodeMirror-lint-mark-error, .CodeMirror-lint-mark-warning {
background-position: left bottom;
background-repeat: repeat-x;
}
.CodeMirror-lint-mark-error {
background-image:
url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJDw4cOCW1/KIAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAHElEQVQI12NggIL/DAz/GdA5/xkY/qPKMDAwAADLZwf5rvm+LQAAAABJRU5ErkJggg==")
;
}
.CodeMirror-lint-mark-warning {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAADCAYAAAC09K7GAAAAAXNSR0IArs4c6QAAAAZiS0dEAP8A/wD/oL2nkwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9sJFhQXEbhTg7YAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAMklEQVQI12NkgIIvJ3QXMjAwdDN+OaEbysDA4MPAwNDNwMCwiOHLCd1zX07o6kBVGQEAKBANtobskNMAAAAASUVORK5CYII=");
}
.CodeMirror-lint-marker-error, .CodeMirror-lint-marker-warning {
background-position: center center;
background-repeat: no-repeat;
cursor: pointer;
display: inline-block;
height: 16px;
width: 16px;
vertical-align: middle;
position: relative;
}
.CodeMirror-lint-message-error, .CodeMirror-lint-message-warning {
padding-left: 18px;
background-position: top left;
background-repeat: no-repeat;
}
.CodeMirror-lint-marker-error, .CodeMirror-lint-message-error {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAHlBMVEW7AAC7AACxAAC7AAC7AAAAAAC4AAC5AAD///+7AAAUdclpAAAABnRSTlMXnORSiwCK0ZKSAAAATUlEQVR42mWPOQ7AQAgDuQLx/z8csYRmPRIFIwRGnosRrpamvkKi0FTIiMASR3hhKW+hAN6/tIWhu9PDWiTGNEkTtIOucA5Oyr9ckPgAWm0GPBog6v4AAAAASUVORK5CYII=");
}
.CodeMirror-lint-marker-warning, .CodeMirror-lint-message-warning {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAANlBMVEX/uwDvrwD/uwD/uwD/uwD/uwD/uwD/uwD/uwD6twD/uwAAAADurwD2tQD7uAD+ugAAAAD/uwDhmeTRAAAADHRSTlMJ8mN1EYcbmiixgACm7WbuAAAAVklEQVR42n3PUQqAIBBFUU1LLc3u/jdbOJoW1P08DA9Gba8+YWJ6gNJoNYIBzAA2chBth5kLmG9YUoG0NHAUwFXwO9LuBQL1giCQb8gC9Oro2vp5rncCIY8L8uEx5ZkAAAAASUVORK5CYII=");
}
.CodeMirror-lint-marker-multiple {
background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAMAAADzjKfhAAAACVBMVEUAAAAAAAC/v7914kyHAAAAAXRSTlMAQObYZgAAACNJREFUeNo1ioEJAAAIwmz/H90iFFSGJgFMe3gaLZ0od+9/AQZ0ADosbYraAAAAAElFTkSuQmCC");
background-repeat: no-repeat;
background-position: right bottom;
width: 100%; height: 100%;
}

209
js/codemirror/addon/lint/lint.js vendored Normal file
View File

@ -0,0 +1,209 @@
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../../lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["../../lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var GUTTER_ID = "CodeMirror-lint-markers";
function showTooltip(e, content) {
var tt = document.createElement("div");
tt.className = "CodeMirror-lint-tooltip";
tt.appendChild(content.cloneNode(true));
document.body.appendChild(tt);
function position(e) {
if (!tt.parentNode) return CodeMirror.off(document, "mousemove", position);
tt.style.top = Math.max(0, e.clientY - tt.offsetHeight - 5) + "px";
tt.style.left = (e.clientX + 5) + "px";
}
CodeMirror.on(document, "mousemove", position);
position(e);
if (tt.style.opacity != null) tt.style.opacity = 1;
return tt;
}
function rm(elt) {
if (elt.parentNode) elt.parentNode.removeChild(elt);
}
function hideTooltip(tt) {
if (!tt.parentNode) return;
if (tt.style.opacity == null) rm(tt);
tt.style.opacity = 0;
setTimeout(function() { rm(tt); }, 600);
}
function showTooltipFor(e, content, node) {
var tooltip = showTooltip(e, content);
function hide() {
CodeMirror.off(node, "mouseout", hide);
if (tooltip) { hideTooltip(tooltip); tooltip = null; }
}
var poll = setInterval(function() {
if (tooltip) for (var n = node;; n = n.parentNode) {
if (n && n.nodeType == 11) n = n.host;
if (n == document.body) return;
if (!n) { hide(); break; }
}
if (!tooltip) return clearInterval(poll);
}, 400);
CodeMirror.on(node, "mouseout", hide);
}
function LintState(cm, options, hasGutter) {
this.marked = [];
this.options = options;
this.timeout = null;
this.hasGutter = hasGutter;
this.onMouseOver = function(e) { onMouseOver(cm, e); };
}
function parseOptions(_cm, options) {
if (options instanceof Function) return {getAnnotations: options};
if (!options || options === true) options = {};
return options;
}
function clearMarks(cm) {
var state = cm.state.lint;
if (state.hasGutter) cm.clearGutter(GUTTER_ID);
for (var i = 0; i < state.marked.length; ++i)
state.marked[i].clear();
state.marked.length = 0;
}
function makeMarker(labels, severity, multiple, tooltips) {
var marker = document.createElement("div"), inner = marker;
marker.className = "CodeMirror-lint-marker-" + severity;
if (multiple) {
inner = marker.appendChild(document.createElement("div"));
inner.className = "CodeMirror-lint-marker-multiple";
}
if (tooltips != false) CodeMirror.on(inner, "mouseover", function(e) {
showTooltipFor(e, labels, inner);
});
return marker;
}
function getMaxSeverity(a, b) {
if (a == "error") return a;
else return b;
}
function groupByLine(annotations) {
var lines = [];
for (var i = 0; i < annotations.length; ++i) {
var ann = annotations[i], line = ann.from.line;
(lines[line] || (lines[line] = [])).push(ann);
}
return lines;
}
function annotationTooltip(ann) {
var severity = ann.severity;
if (!severity) severity = "error";
var tip = document.createElement("div");
tip.className = "CodeMirror-lint-message-" + severity;
tip.appendChild(document.createTextNode(ann.message));
// Unescaping only the <code> tag.
tip.innerHTML = tip.innerHTML.replace("&lt;code&gt;", "<code>")
.replace("&lt;/code&gt;", "</code>");
return tip;
}
function startLinting(cm) {
var state = cm.state.lint, options = state.options;
var passOptions = options.options || options; // Support deprecated passing of `options` property in options
var getAnnotations = options.getAnnotations || cm.getHelper(CodeMirror.Pos(0, 0), "lint");
if (!getAnnotations) return;
if (options.async || getAnnotations.async)
getAnnotations(cm.getValue(), updateLinting, passOptions, cm);
else
updateLinting(cm, getAnnotations(cm.getValue(), passOptions, cm));
}
function updateLinting(cm, annotationsNotSorted) {
clearMarks(cm);
var state = cm.state.lint, options = state.options;
var annotations = groupByLine(annotationsNotSorted);
for (var line = 0; line < annotations.length; ++line) {
var anns = annotations[line];
if (!anns) continue;
var maxSeverity = null;
var tipLabel = state.hasGutter && document.createDocumentFragment();
for (var i = 0; i < anns.length; ++i) {
var ann = anns[i];
var severity = ann.severity;
if (!severity) severity = "error";
maxSeverity = getMaxSeverity(maxSeverity, severity);
if (options.formatAnnotation) ann = options.formatAnnotation(ann);
if (state.hasGutter) tipLabel.appendChild(annotationTooltip(ann));
if (ann.to) state.marked.push(cm.markText(ann.from, ann.to, {
className: "CodeMirror-lint-mark-" + severity,
__annotation: ann
}));
}
if (state.hasGutter)
cm.setGutterMarker(line, GUTTER_ID, makeMarker(tipLabel, maxSeverity, anns.length > 1,
state.options.tooltips));
}
if (options.onUpdateLinting) options.onUpdateLinting(annotationsNotSorted, annotations, cm);
}
function onChange(cm) {
var state = cm.state.lint;
if (!state) return;
clearTimeout(state.timeout);
state.timeout = setTimeout(function(){startLinting(cm);}, state.options.delay || 500);
}
function popupSpanTooltip(ann, e) {
var target = e.target || e.srcElement;
showTooltipFor(e, annotationTooltip(ann), target);
}
function onMouseOver(cm, e) {
var target = e.target || e.srcElement;
if (!/\bCodeMirror-lint-mark-/.test(target.className)) return;
var box = target.getBoundingClientRect(), x = (box.left + box.right) / 2, y = (box.top + box.bottom) / 2;
var spans = cm.findMarksAt(cm.coordsChar({left: x, top: y}, "client"));
for (var i = 0; i < spans.length; ++i) {
var ann = spans[i].__annotation;
if (ann) return popupSpanTooltip(ann, e);
}
}
CodeMirror.defineOption("lint", false, function(cm, val, old) {
if (old && old != CodeMirror.Init) {
clearMarks(cm);
cm.off("change", onChange);
CodeMirror.off(cm.getWrapperElement(), "mouseover", cm.state.lint.onMouseOver);
clearTimeout(cm.state.lint.timeout);
delete cm.state.lint;
}
if (val) {
var gutters = cm.getOption("gutters"), hasLintGutter = false;
for (var i = 0; i < gutters.length; ++i) if (gutters[i] == GUTTER_ID) hasLintGutter = true;
var state = cm.state.lint = new LintState(cm, parseOptions(cm, val), hasLintGutter);
cm.on("change", onChange);
if (state.options.tooltips != false)
CodeMirror.on(cm.getWrapperElement(), "mouseover", state.onMouseOver);
startLinting(cm);
}
});
});

39
js/codemirror/addon/lint/sql-lint.js vendored Normal file
View File

@ -0,0 +1,39 @@
CodeMirror.sqlLint = function(text, updateLinting, options, cm) {
// Skipping check if text box is empty.
if(text.trim() == "") {
updateLinting(cm, []);
return;
}
function handleResponse(json) {
response = JSON.parse(json);
var found = [];
for (var idx in response) {
found.push({
from: CodeMirror.Pos(
response[idx].fromLine, response[idx].fromColumn
),
to: CodeMirror.Pos(
response[idx].toLine, response[idx].toColumn
),
message: response[idx].message,
severity : response[idx].severity
});
}
updateLinting(cm, found);
}
$.ajax({
method: "POST",
url: "lint.php",
data: {
sql_query: text,
token: PMA_commonParams.get('token'),
server: PMA_commonParams.get('server')
},
success: handleResponse
});
}

325
js/codemirror/lib/codemirror.css vendored Normal file
View File

@ -0,0 +1,325 @@
/* BASICS */
.CodeMirror {
/* Set height, width, borders, and global font properties here */
font-family: monospace;
height: 300px;
color: black;
}
/* PADDING */
.CodeMirror-lines {
padding: 4px 0; /* Vertical padding around content */
}
.CodeMirror pre {
padding: 0 4px; /* Horizontal padding of content */
}
.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
background-color: white; /* The little square between H and V scrollbars */
}
/* GUTTER */
.CodeMirror-gutters {
border-right: 1px solid #ddd;
background-color: #f7f7f7;
white-space: nowrap;
}
.CodeMirror-linenumbers {}
.CodeMirror-linenumber {
padding: 0 3px 0 5px;
min-width: 20px;
text-align: right;
color: #999;
white-space: nowrap;
}
.CodeMirror-guttermarker { color: black; }
.CodeMirror-guttermarker-subtle { color: #999; }
/* CURSOR */
.CodeMirror div.CodeMirror-cursor {
border-left: 1px solid black;
}
/* Shown when moving in bi-directional text */
.CodeMirror div.CodeMirror-secondarycursor {
border-left: 1px solid silver;
}
.CodeMirror.cm-fat-cursor div.CodeMirror-cursor {
width: auto;
border: 0;
background: #7e7;
}
.CodeMirror.cm-fat-cursor div.CodeMirror-cursors {
z-index: 1;
}
.cm-animate-fat-cursor {
width: auto;
border: 0;
-webkit-animation: blink 1.06s steps(1) infinite;
-moz-animation: blink 1.06s steps(1) infinite;
animation: blink 1.06s steps(1) infinite;
}
@-moz-keyframes blink {
0% { background: #7e7; }
50% { background: none; }
100% { background: #7e7; }
}
@-webkit-keyframes blink {
0% { background: #7e7; }
50% { background: none; }
100% { background: #7e7; }
}
@keyframes blink {
0% { background: #7e7; }
50% { background: none; }
100% { background: #7e7; }
}
/* Can style cursor different in overwrite (non-insert) mode */
div.CodeMirror-overwrite div.CodeMirror-cursor {}
.cm-tab { display: inline-block; text-decoration: inherit; }
.CodeMirror-ruler {
border-left: 1px solid #ccc;
position: absolute;
}
/* DEFAULT THEME */
.cm-s-default .cm-header {color: blue;}
.cm-s-default .cm-quote {color: #090;}
.cm-negative {color: #d44;}
.cm-positive {color: #292;}
.cm-header, .cm-strong {font-weight: bold;}
.cm-em {font-style: italic;}
.cm-link {text-decoration: underline;}
.cm-strikethrough {text-decoration: line-through;}
.cm-s-default .cm-keyword {color: #708;}
.cm-s-default .cm-atom {color: #219;}
.cm-s-default .cm-number {color: #164;}
.cm-s-default .cm-def {color: #00f;}
.cm-s-default .cm-variable,
.cm-s-default .cm-punctuation,
.cm-s-default .cm-property,
.cm-s-default .cm-operator {}
.cm-s-default .cm-variable-2 {color: #05a;}
.cm-s-default .cm-variable-3 {color: #085;}
.cm-s-default .cm-comment {color: #a50;}
.cm-s-default .cm-string {color: #a11;}
.cm-s-default .cm-string-2 {color: #f50;}
.cm-s-default .cm-meta {color: #555;}
.cm-s-default .cm-qualifier {color: #555;}
.cm-s-default .cm-builtin {color: #30a;}
.cm-s-default .cm-bracket {color: #997;}
.cm-s-default .cm-tag {color: #170;}
.cm-s-default .cm-attribute {color: #00c;}
.cm-s-default .cm-hr {color: #999;}
.cm-s-default .cm-link {color: #00c;}
.cm-s-default .cm-error {color: #f00;}
.cm-invalidchar {color: #f00;}
.CodeMirror-composing { border-bottom: 2px solid; }
/* Default styles for common addons */
div.CodeMirror span.CodeMirror-matchingbracket {color: #0f0;}
div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #f22;}
.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
.CodeMirror-activeline-background {background: #e8f2ff;}
/* STOP */
/* The rest of this file contains styles related to the mechanics of
the editor. You probably shouldn't touch them. */
.CodeMirror {
position: relative;
overflow: hidden;
background: white;
}
.CodeMirror-scroll {
overflow: scroll !important; /* Things will break if this is overridden */
/* 30px is the magic margin used to hide the element's real scrollbars */
/* See overflow: hidden in .CodeMirror */
margin-bottom: -30px; margin-right: -30px;
padding-bottom: 30px;
height: 100%;
outline: none; /* Prevent dragging from highlighting the element */
position: relative;
}
.CodeMirror-sizer {
position: relative;
border-right: 30px solid transparent;
}
/* The fake, visible scrollbars. Used to force redraw during scrolling
before actuall scrolling happens, thus preventing shaking and
flickering artifacts. */
.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
position: absolute;
z-index: 6;
display: none;
}
.CodeMirror-vscrollbar {
right: 0; top: 0;
overflow-x: hidden;
overflow-y: scroll;
}
.CodeMirror-hscrollbar {
bottom: 0; left: 0;
overflow-y: hidden;
overflow-x: scroll;
}
.CodeMirror-scrollbar-filler {
right: 0; bottom: 0;
}
.CodeMirror-gutter-filler {
left: 0; bottom: 0;
}
.CodeMirror-gutters {
position: absolute; left: 0; top: 0;
z-index: 3;
}
.CodeMirror-gutter {
white-space: normal;
height: 100%;
display: inline-block;
margin-bottom: -30px;
/* Hack to make IE7 behave */
*zoom:1;
*display:inline;
}
.CodeMirror-gutter-wrapper {
position: absolute;
z-index: 4;
height: 100%;
}
.CodeMirror-gutter-elt {
position: absolute;
cursor: default;
z-index: 4;
}
.CodeMirror-gutter-wrapper {
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
.CodeMirror-lines {
cursor: text;
min-height: 1px; /* prevents collapsing before first draw */
}
.CodeMirror pre {
/* Reset some styles that the rest of the page might have set */
-moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
border-width: 0;
background: transparent;
font-family: inherit;
font-size: inherit;
margin: 0;
white-space: pre;
word-wrap: normal;
line-height: inherit;
color: inherit;
z-index: 2;
position: relative;
overflow: visible;
-webkit-tap-highlight-color: transparent;
}
.CodeMirror-wrap pre {
word-wrap: break-word;
white-space: pre-wrap;
word-break: normal;
}
.CodeMirror-linebackground {
position: absolute;
left: 0; right: 0; top: 0; bottom: 0;
z-index: 0;
}
.CodeMirror-linewidget {
position: relative;
z-index: 2;
overflow: auto;
}
.CodeMirror-widget {}
.CodeMirror-code {
outline: none;
}
/* Force content-box sizing for the elements where we expect it */
.CodeMirror-scroll,
.CodeMirror-sizer,
.CodeMirror-gutter,
.CodeMirror-gutters,
.CodeMirror-linenumber {
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.CodeMirror-measure {
position: absolute;
width: 100%;
height: 0;
overflow: hidden;
visibility: hidden;
}
.CodeMirror-measure pre { position: static; }
.CodeMirror div.CodeMirror-cursor {
position: absolute;
border-right: none;
width: 0;
}
div.CodeMirror-cursors {
visibility: hidden;
position: relative;
z-index: 3;
}
.CodeMirror-focused div.CodeMirror-cursors {
visibility: visible;
}
.CodeMirror-selected { background: #d9d9d9; }
.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
.CodeMirror-crosshair { cursor: crosshair; }
.CodeMirror ::selection { background: #d7d4f0; }
.CodeMirror ::-moz-selection { background: #d7d4f0; }
.cm-searching {
background: #ffa;
background: rgba(255, 255, 0, .4);
}
/* IE7 hack to prevent it from returning funny offsetTops on the spans */
.CodeMirror span { *vertical-align: text-bottom; }
/* Used to force a border model for a node */
.cm-force-border { padding-right: .1px; }
@media print {
/* Hide the cursor when printing */
.CodeMirror div.CodeMirror-cursors {
visibility: hidden;
}
}
/* See issue #2901 */
.cm-tab-wrap-hack:after { content: ''; }
/* Help users use markselection to safely style text background */
span.CodeMirror-selectedtext { background: none; }

View File

@ -82,12 +82,15 @@
keyMaps: [], // stores maps added by addKeyMap
overlays: [], // highlighting overlays, as added by addOverlay
modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info
overwrite: false, focused: false,
overwrite: false,
delayingBlurEvent: false,
focused: false,
suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll
draggingText: false,
highlight: new Delayed(), // stores highlight worker timeout
keySeq: null // Unfinished key sequence
keySeq: null, // Unfinished key sequence
specialChars: null
};
var cm = this;
@ -591,7 +594,7 @@
"CodeMirror-linenumber CodeMirror-gutter-elt"));
var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW;
display.lineGutter.style.width = "";
display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding);
display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1;
display.lineNumWidth = display.lineNumInnerWidth + padding;
display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
display.lineGutter.style.width = display.lineNumWidth + "px";
@ -725,12 +728,9 @@
}
function postUpdateDisplay(cm, update) {
var force = update.force, viewport = update.viewport;
var viewport = update.viewport;
for (var first = true;; first = false) {
if (first && cm.options.lineWrapping && update.oldDisplayWidth != displayWidth(cm)) {
force = true;
} else {
force = false;
if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
// Clip forced viewport to actual scrollable area.
if (viewport && viewport.top != null)
viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};
@ -1076,14 +1076,15 @@
// was made out of.
var lastCopied = null;
function applyTextInput(cm, inserted, deleted, sel) {
function applyTextInput(cm, inserted, deleted, sel, origin) {
var doc = cm.doc;
cm.display.shift = false;
if (!sel) sel = doc.sel;
var paste = cm.state.pasteIncoming || origin == "paste";
var textLines = splitLines(inserted), multiPaste = null;
// When pasing N lines into N selections, insert one line per selection
if (cm.state.pasteIncoming && sel.ranges.length > 1) {
if (paste && sel.ranges.length > 1) {
if (lastCopied && lastCopied.join("\n") == inserted)
multiPaste = sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines);
else if (textLines.length == sel.ranges.length)
@ -1097,38 +1098,57 @@
if (range.empty()) {
if (deleted && deleted > 0) // Handle deletion
from = Pos(from.line, from.ch - deleted);
else if (cm.state.overwrite && !cm.state.pasteIncoming) // Handle overwrite
else if (cm.state.overwrite && !paste) // Handle overwrite
to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));
}
var updateInput = cm.curOp.updateInput;
var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines,
origin: cm.state.pasteIncoming ? "paste" : cm.state.cutIncoming ? "cut" : "+input"};
origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")};
makeChange(cm.doc, changeEvent);
signalLater(cm, "inputRead", cm, changeEvent);
// When an 'electric' character is inserted, immediately trigger a reindent
if (inserted && !cm.state.pasteIncoming && cm.options.electricChars &&
cm.options.smartIndent && range.head.ch < 100 &&
(!i || sel.ranges[i - 1].head.line != range.head.line)) {
var mode = cm.getModeAt(range.head);
var end = changeEnd(changeEvent);
if (mode.electricChars) {
for (var j = 0; j < mode.electricChars.length; j++)
if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
indentLine(cm, end.line, "smart");
break;
}
} else if (mode.electricInput) {
if (mode.electricInput.test(getLine(doc, end.line).text.slice(0, end.ch)))
indentLine(cm, end.line, "smart");
}
}
}
if (inserted && !paste)
triggerElectric(cm, inserted);
ensureCursorVisible(cm);
cm.curOp.updateInput = updateInput;
cm.curOp.typing = true;
cm.state.pasteIncoming = cm.state.cutIncoming = false;
}
function handlePaste(e, cm) {
var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
if (pasted) {
e.preventDefault();
runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); });
return true;
}
}
function triggerElectric(cm, inserted) {
// When an 'electric' character is inserted, immediately trigger a reindent
if (!cm.options.electricChars || !cm.options.smartIndent) return;
var sel = cm.doc.sel;
for (var i = sel.ranges.length - 1; i >= 0; i--) {
var range = sel.ranges[i];
if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue;
var mode = cm.getModeAt(range.head);
var indented = false;
if (mode.electricChars) {
for (var j = 0; j < mode.electricChars.length; j++)
if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
indented = indentLine(cm, range.head.line, "smart");
break;
}
} else if (mode.electricInput) {
if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
indented = indentLine(cm, range.head.line, "smart");
}
if (indented) signalLater(cm, "electricInput", cm, range.head.line);
}
}
function copyableRanges(cm) {
var text = [], ranges = [];
for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
@ -1164,6 +1184,7 @@
this.inaccurateSelection = false;
// Used to work around IE issue with selection being forgotten when focus moves away from textarea
this.hasSelection = false;
this.composing = null;
};
function hiddenTextarea() {
@ -1200,21 +1221,9 @@
input.poll();
});
on(te, "paste", function() {
// Workaround for webkit bug https://bugs.webkit.org/show_bug.cgi?id=90206
// Add a char to the end of textarea before paste occur so that
// selection doesn't span to the end of textarea.
if (webkit && !cm.state.fakedLastChar && !(new Date - cm.state.lastMiddleDown < 200)) {
var start = te.selectionStart, end = te.selectionEnd;
te.value += "$";
// The selection end needs to be set before the start, otherwise there
// can be an intermediate non-empty selection between the two, which
// can override the middle-click paste buffer on linux and cause the
// wrong thing to get pasted.
te.selectionEnd = end;
te.selectionStart = start;
cm.state.fakedLastChar = true;
}
on(te, "paste", function(e) {
if (handlePaste(e, cm)) return true;
cm.state.pasteIncoming = true;
input.fastPoll();
});
@ -1228,6 +1237,8 @@
te.value = lastCopied.join("\n");
selectInput(te);
}
} else if (!cm.options.lineWiseCopyCut) {
return;
} else {
var ranges = copyableRanges(cm);
lastCopied = ranges.text;
@ -1254,6 +1265,21 @@
on(display.lineSpace, "selectstart", function(e) {
if (!eventInWidget(display, e)) e_preventDefault(e);
});
on(te, "compositionstart", function() {
var start = cm.getCursor("from");
input.composing = {
start: start,
range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
};
});
on(te, "compositionend", function() {
if (input.composing) {
input.poll();
input.composing.range.clear();
input.composing = null;
}
});
},
prepareSelection: function() {
@ -1361,14 +1387,11 @@
// possible when it is clear that nothing happened. hasSelection
// will be the case when there is a lot of text in the textarea,
// in which case reading its value would be expensive.
if (!cm.state.focused || (hasSelection(input) && !prevInput) ||
if (this.contextMenuPending || !cm.state.focused ||
(hasSelection(input) && !prevInput) ||
isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq)
return false;
// See paste handler for more on the fakedLastChar kludge
if (cm.state.pasteIncoming && cm.state.fakedLastChar) {
input.value = input.value.substring(0, input.value.length - 1);
cm.state.fakedLastChar = false;
}
var text = input.value;
// If nothing changed, bail.
if (text == prevInput && !cm.somethingSelected()) return false;
@ -1381,19 +1404,29 @@
return false;
}
if (text.charCodeAt(0) == 0x200b && cm.doc.sel == cm.display.selForContextMenu && !prevInput)
prevInput = "\u200b";
if (cm.doc.sel == cm.display.selForContextMenu) {
var first = text.charCodeAt(0);
if (first == 0x200b && !prevInput) prevInput = "\u200b";
if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); }
}
// Find the part of the input that is actually new
var same = 0, l = Math.min(prevInput.length, text.length);
while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same;
var self = this;
runInOp(cm, function() {
applyTextInput(cm, text.slice(same), prevInput.length - same);
applyTextInput(cm, text.slice(same), prevInput.length - same,
null, self.composing ? "*compose" : null);
// Don't leave long text in the textarea, since it makes further polling slow
if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = "";
else self.prevInput = text;
if (self.composing) {
self.composing.range.clear();
self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"),
{className: "CodeMirror-composing"});
}
});
return true;
},
@ -1440,7 +1473,9 @@
function prepareSelectAllHack() {
if (te.selectionStart != null) {
var selected = cm.somethingSelected();
var extval = te.value = "\u200b" + (selected ? te.value : "");
var extval = "\u200b" + (selected ? te.value : "");
te.value = "\u21da"; // Used to catch context-menu undo
te.value = extval;
input.prevInput = selected ? "" : "\u200b";
te.selectionStart = 1; te.selectionEnd = extval.length;
// Re-set this, in case some other handler touched the
@ -1458,7 +1493,8 @@
if (te.selectionStart != null) {
if (!ie || (ie && ie_version < 9)) prepareSelectAllHack();
var i = 0, poll = function() {
if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0)
if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
te.selectionEnd > 0 && input.prevInput == "\u200b")
operation(cm, commands.selectAll)(cm);
else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500);
else display.input.reset();
@ -1491,6 +1527,7 @@
this.cm = cm;
this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
this.polling = new Delayed();
this.gracePeriod = false;
}
ContentEditableInput.prototype = copyObj({
@ -1500,13 +1537,7 @@
div.contentEditable = "true";
disableBrowserMagic(div);
on(div, "paste", function(e) {
var pasted = e.clipboardData && e.clipboardData.getData("text/plain");
if (pasted) {
e.preventDefault();
cm.replaceSelection(pasted, null, "paste");
}
});
on(div, "paste", function(e) { handlePaste(e, cm); })
on(div, "compositionstart", function(e) {
var data = e.data;
@ -1552,6 +1583,8 @@
if (cm.somethingSelected()) {
lastCopied = cm.getSelections();
if (e.type == "cut") cm.replaceSelection("", null, "cut");
} else if (!cm.options.lineWiseCopyCut) {
return;
} else {
var ranges = copyableRanges(cm);
lastCopied = ranges.text;
@ -1625,10 +1658,21 @@
sel.removeAllRanges();
sel.addRange(rng);
if (old && sel.anchorNode == null) sel.addRange(old);
else if (gecko) this.startGracePeriod();
}
this.rememberSelection();
},
startGracePeriod: function() {
var input = this;
clearTimeout(this.gracePeriod);
this.gracePeriod = setTimeout(function() {
input.gracePeriod = false;
if (input.selectionChanged())
input.cm.operation(function() { input.cm.curOp.selectionChanged = true; });
}, 20);
},
showMultipleSelections: function(info) {
removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
@ -1671,12 +1715,15 @@
this.polling.set(this.cm.options.pollInterval, poll);
},
pollSelection: function() {
if (this.composing) return;
selectionChanged: function() {
var sel = window.getSelection();
return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset;
},
var sel = window.getSelection(), cm = this.cm;
if (sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset) {
pollSelection: function() {
if (!this.composing && !this.gracePeriod && this.selectionChanged()) {
var sel = window.getSelection(), cm = this.cm;
this.rememberSelection();
var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
var head = domToPos(cm, sel.focusNode, sel.focusOffset);
@ -1703,7 +1750,7 @@
var toIndex = findViewIndex(cm, to.line);
if (toIndex == display.view.length - 1) {
var toLine = display.viewTo - 1;
var toNode = display.view[toIndex].node;
var toNode = display.lineDiv.lastChild;
} else {
var toLine = lineNo(display.view[toIndex + 1].line) - 1;
var toNode = display.view[toIndex + 1].node.previousSibling;
@ -1783,7 +1830,7 @@
var partPos = getBidiPartAt(order, pos.ch);
side = partPos % 2 ? "right" : "left";
}
var result = nodeAndOffsetInLineMap(info.map, pos.ch, "left");
var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
result.offset = result.collapse == "right" ? result.end : result.start;
return result;
}
@ -2895,6 +2942,7 @@
updateMaxLine: false, // Set when the widest line needs to be determined anew
scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet
scrollToPos: null, // Used to scroll to a specific position
focus: false,
id: ++nextOpId // Unique ID
};
if (operationGroup) {
@ -3012,6 +3060,7 @@
if (cm.state.focused && op.updateInput)
cm.display.input.reset(op.typing);
if (op.focus && op.focus == activeElt()) ensureFocus(op.cm);
}
function endOperation_finish(op) {
@ -3376,15 +3425,11 @@
// Prevent wrapper from ever scrolling
on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
function drag_(e) {
if (!signalDOMEvent(cm, e)) e_stop(e);
}
if (cm.options.dragDrop) {
on(d.scroller, "dragstart", function(e){onDragStart(cm, e);});
on(d.scroller, "dragenter", drag_);
on(d.scroller, "dragover", drag_);
on(d.scroller, "drop", operation(cm, onDrop));
}
d.dragFunctions = {
simple: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);},
start: function(e){onDragStart(cm, e);},
drop: operation(cm, onDrop)
};
var inp = d.input.getField();
on(inp, "keyup", function(e) { onKeyUp.call(cm, e); });
@ -3394,6 +3439,18 @@
on(inp, "blur", bind(onBlur, cm));
}
function dragDropChanged(cm, value, old) {
var wasOn = old && old != CodeMirror.Init;
if (!value != !wasOn) {
var funcs = cm.display.dragFunctions;
var toggle = value ? on : off;
toggle(cm.display.scroller, "dragstart", funcs.start);
toggle(cm.display.scroller, "dragenter", funcs.simple);
toggle(cm.display.scroller, "dragover", funcs.simple);
toggle(cm.display.scroller, "drop", funcs.drop);
}
}
// Called when the window resizes
function onResize(cm) {
var d = cm.display;
@ -3475,6 +3532,7 @@
break;
case 3:
if (captureRightClick) onContextMenu(cm, e);
else delayBlurEvent(cm);
break;
}
}
@ -3482,7 +3540,7 @@
var lastClick, lastDoubleClick;
function leftButtonDown(cm, e, start) {
if (ie) setTimeout(bind(ensureFocus, cm), 0);
else ensureFocus(cm);
else cm.curOp.focus = activeElt();
var now = +new Date, type;
if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) {
@ -3498,7 +3556,8 @@
var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained;
if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) &&
type == "single" && (contained = sel.contains(start)) > -1 &&
!sel.ranges[contained].empty())
(cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) &&
(cmp(contained.to(), start) > 0 || start.xRel < 0))
leftButtonStartDrag(cm, e, start, modifier);
else
leftButtonSelect(cm, e, start, type, modifier);
@ -3507,7 +3566,7 @@
// Start a text drag. When it ends, see if any dragging actually
// happen, and treat as a click if it didn't.
function leftButtonStartDrag(cm, e, start, modifier) {
var display = cm.display;
var display = cm.display, startTime = +new Date;
var dragEnd = operation(cm, function(e2) {
if (webkit) display.scroller.draggable = false;
cm.state.draggingText = false;
@ -3515,12 +3574,13 @@
off(display.scroller, "drop", dragEnd);
if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) {
e_preventDefault(e2);
if (!modifier)
if (!modifier && +new Date - 200 < startTime)
extendSelection(cm.doc, start);
display.input.focus();
// Work around unexplainable focus problem in IE9 (#2127)
if (ie && ie_version == 9)
// Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
if (webkit || ie && ie_version == 9)
setTimeout(function() {document.body.focus(); display.input.focus();}, 20);
else
display.input.focus();
}
});
// Let the drag handler handle this.
@ -3546,6 +3606,7 @@
ourRange = new Range(start, start);
} else {
ourRange = doc.sel.primary();
ourIndex = doc.sel.primIndex;
}
if (e.altKey) {
@ -3577,7 +3638,7 @@
ourIndex = ranges.length;
setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex),
{scroll: false, origin: "*mouse"});
} else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single") {
} else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) {
setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0));
startSel = doc.sel;
} else {
@ -3640,7 +3701,7 @@
var cur = posFromMouse(cm, e, true, type == "rect");
if (!cur) return;
if (cmp(cur, lastPos) != 0) {
ensureFocus(cm);
cm.curOp.focus = activeElt();
extendTo(cur);
var visible = visibleLines(display, doc);
if (cur.line >= visible.to || cur.line < visible.from)
@ -3743,7 +3804,7 @@
try {
var text = e.dataTransfer.getData("Text");
if (text) {
if (cm.state.draggingText && !(mac ? e.metaKey : e.ctrlKey))
if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey))
var selected = cm.listSelections();
setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
if (selected) for (var i = 0; i < selected.length; ++i)
@ -3998,7 +4059,7 @@
var lastStoppedKey = null;
function onKeyDown(e) {
var cm = this;
ensureFocus(cm);
cm.curOp.focus = activeElt();
if (signalDOMEvent(cm, e)) return;
// IE does strange things with escape.
if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false;
@ -4050,7 +4111,19 @@
// FOCUS/BLUR EVENTS
function delayBlurEvent(cm) {
cm.state.delayingBlurEvent = true;
setTimeout(function() {
if (cm.state.delayingBlurEvent) {
cm.state.delayingBlurEvent = false;
onBlur(cm);
}
}, 100);
}
function onFocus(cm) {
if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false;
if (cm.options.readOnly == "nocursor") return;
if (!cm.state.focused) {
signal(cm, "focus", cm);
@ -4068,6 +4141,8 @@
restartBlink(cm);
}
function onBlur(cm) {
if (cm.state.delayingBlurEvent) return;
if (cm.state.focused) {
signal(cm, "blur", cm);
cm.state.focused = false;
@ -4572,6 +4647,8 @@
if (indentString != curSpaceString) {
replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
line.stateAfter = null;
return true;
} else {
// Ensure that, if the cursor was in the whitespace at the start
// of the line, it is moved to the end of that space.
@ -4584,7 +4661,6 @@
}
}
}
line.stateAfter = null;
}
// Utility for applying a change to a line by handle or number,
@ -4824,7 +4900,7 @@
getHelpers: function(pos, type) {
var found = [];
if (!helpers.hasOwnProperty(type)) return helpers;
if (!helpers.hasOwnProperty(type)) return found;
var help = helpers[type], mode = this.getModeAt(pos);
if (typeof mode[type] == "string") {
if (help[mode[type]]) found.push(help[mode[type]]);
@ -4874,10 +4950,15 @@
return lineAtHeight(this.doc, height + this.display.viewOffset);
},
heightAtLine: function(line, mode) {
var end = false, last = this.doc.first + this.doc.size - 1;
if (line < this.doc.first) line = this.doc.first;
else if (line > last) { line = last; end = true; }
var lineObj = getLine(this.doc, line);
var end = false, lineObj;
if (typeof line == "number") {
var last = this.doc.first + this.doc.size - 1;
if (line < this.doc.first) line = this.doc.first;
else if (line > last) { line = last; end = true; }
lineObj = getLine(this.doc, line);
} else {
lineObj = line;
}
return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top +
(end ? this.doc.height - heightAtLine(lineObj) : 0);
},
@ -4906,12 +4987,6 @@
});
}),
addLineWidget: methodOp(function(handle, node, options) {
return addLineWidget(this, handle, node, options);
}),
removeLineWidget: function(widget) { widget.clear(); },
lineInfo: function(line) {
if (typeof line == "number") {
if (!isLine(this.doc, line)) return null;
@ -4973,6 +5048,8 @@
return commands[cmd](this);
},
triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
findPosH: function(from, amount, unit, visually) {
var dir = 1;
if (amount < 0) { dir = -1; amount = -amount; }
@ -5186,10 +5263,10 @@
clearCaches(cm);
regChange(cm);
}, true);
option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val) {
cm.options.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
cm.refresh();
}, true);
option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) {
cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
if (old != CodeMirror.Init) cm.refresh();
});
option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true);
option("electricChars", true);
option("inputStyle", mobile ? "contenteditable" : "textarea", function() {
@ -5235,6 +5312,7 @@
option("showCursorWhenSelecting", false, updateSelection, true);
option("resetSelectionOnContextMenu", true);
option("lineWiseCopyCut", true);
option("readOnly", false, function(cm, val) {
if (val == "nocursor") {
@ -5247,7 +5325,7 @@
}
});
option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true);
option("dragDrop", true);
option("dragDrop", true, dragDropChanged);
option("cursorBlinkRate", 530);
option("cursorScrollMargin", 0);
@ -5639,7 +5717,7 @@
for (var i = 0; i < keys.length; i++) {
var val, name;
if (i == keys.length - 1) {
name = keyname;
name = keys.join(" ");
val = value;
} else {
name = keys.slice(0, i + 1).join(" ");
@ -6431,10 +6509,10 @@
// Line widgets are block elements displayed above or below a line.
var LineWidget = CodeMirror.LineWidget = function(cm, node, options) {
var LineWidget = CodeMirror.LineWidget = function(doc, node, options) {
if (options) for (var opt in options) if (options.hasOwnProperty(opt))
this[opt] = options[opt];
this.cm = cm;
this.doc = doc;
this.node = node;
};
eventMixin(LineWidget);
@ -6445,52 +6523,55 @@
}
LineWidget.prototype.clear = function() {
var cm = this.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line);
if (no == null || !ws) return;
for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1);
if (!ws.length) line.widgets = null;
var height = widgetHeight(this);
runInOp(cm, function() {
updateLineHeight(line, Math.max(0, line.height - height));
if (cm) runInOp(cm, function() {
adjustScrollWhenAboveVisible(cm, line, -height);
regLineChange(cm, no, "widget");
updateLineHeight(line, Math.max(0, line.height - height));
});
};
LineWidget.prototype.changed = function() {
var oldH = this.height, cm = this.cm, line = this.line;
var oldH = this.height, cm = this.doc.cm, line = this.line;
this.height = null;
var diff = widgetHeight(this) - oldH;
if (!diff) return;
runInOp(cm, function() {
updateLineHeight(line, line.height + diff);
if (cm) runInOp(cm, function() {
cm.curOp.forceUpdate = true;
adjustScrollWhenAboveVisible(cm, line, diff);
updateLineHeight(line, line.height + diff);
});
};
function widgetHeight(widget) {
if (widget.height != null) return widget.height;
var cm = widget.doc.cm;
if (!cm) return 0;
if (!contains(document.body, widget.node)) {
var parentStyle = "position: relative;";
if (widget.coverGutter)
parentStyle += "margin-left: -" + widget.cm.display.gutters.offsetWidth + "px;";
parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";
if (widget.noHScroll)
parentStyle += "width: " + widget.cm.display.wrapper.clientWidth + "px;";
removeChildrenAndAdd(widget.cm.display.measure, elt("div", [widget.node], null, parentStyle));
parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";
removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
}
return widget.height = widget.node.offsetHeight;
}
function addLineWidget(cm, handle, node, options) {
var widget = new LineWidget(cm, node, options);
if (widget.noHScroll) cm.display.alignWidgets = true;
changeLine(cm.doc, handle, "widget", function(line) {
function addLineWidget(doc, handle, node, options) {
var widget = new LineWidget(doc, node, options);
var cm = doc.cm;
if (cm && widget.noHScroll) cm.display.alignWidgets = true;
changeLine(doc, handle, "widget", function(line) {
var widgets = line.widgets || (line.widgets = []);
if (widget.insertAt == null) widgets.push(widget);
else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget);
widget.line = line;
if (!lineIsHidden(cm.doc, line)) {
var aboveVisible = heightAtLine(line) < cm.doc.scrollTop;
if (cm && !lineIsHidden(doc, line)) {
var aboveVisible = heightAtLine(line) < doc.scrollTop;
updateLineHeight(line, line.height + widgetHeight(widget));
if (aboveVisible) addToScrollPos(cm, null, widget.height);
cm.curOp.forceUpdate = true;
@ -6710,7 +6791,9 @@
// is needed on Webkit to be able to get line-level bounding
// rectangles for it (in measureChar).
var content = elt("span", null, null, webkit ? "padding-right: .1px" : null);
var builder = {pre: elt("pre", [content]), content: content, col: 0, pos: 0, cm: cm};
var builder = {pre: elt("pre", [content]), content: content,
col: 0, pos: 0, cm: cm,
splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")};
lineView.measure = {};
// Iterate over the logical lines that make up this visual line.
@ -6720,8 +6803,6 @@
builder.addToken = buildToken;
// Optionally wire in some hacks into the token-rendering
// algorithm, to deal with browser quirks.
if ((ie || webkit) && cm.getOption("lineWrapping"))
builder.addToken = buildTokenSplitSpaces(builder.addToken);
if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line)))
builder.addToken = buildTokenBadBidi(builder.addToken, order);
builder.map = [];
@ -6770,10 +6851,11 @@
// the line map. Takes care to render special characters separately.
function buildToken(builder, text, style, startStyle, endStyle, title, css) {
if (!text) return;
var special = builder.cm.options.specialChars, mustWrap = false;
var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text;
var special = builder.cm.state.specialChars, mustWrap = false;
if (!special.test(text)) {
builder.col += text.length;
var content = document.createTextNode(text);
var content = document.createTextNode(displayText);
builder.map.push(builder.pos, builder.pos + text.length, content);
if (ie && ie_version < 9) mustWrap = true;
builder.pos += text.length;
@ -6784,7 +6866,7 @@
var m = special.exec(text);
var skipped = m ? m.index - pos : text.length - pos;
if (skipped) {
var txt = document.createTextNode(text.slice(pos, pos + skipped));
var txt = document.createTextNode(displayText.slice(pos, pos + skipped));
if (ie && ie_version < 9) content.appendChild(elt("span", [txt]));
else content.appendChild(txt);
builder.map.push(builder.pos, builder.pos + skipped, txt);
@ -6821,22 +6903,17 @@
builder.content.appendChild(content);
}
function buildTokenSplitSpaces(inner) {
function split(old) {
var out = " ";
for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
out += " ";
return out;
}
return function(builder, text, style, startStyle, endStyle, title) {
inner(builder, text.replace(/ {3,}/g, split), style, startStyle, endStyle, title);
};
function splitSpaces(old) {
var out = " ";
for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0";
out += " ";
return out;
}
// Work around nonsense dimensions being reported for stretches of
// right-to-left text.
function buildTokenBadBidi(inner, order) {
return function(builder, text, style, startStyle, endStyle, title) {
return function(builder, text, style, startStyle, endStyle, title, css) {
style = style ? style + " cm-force-border" : "cm-force-border";
var start = builder.pos, end = start + text.length;
for (;;) {
@ -6845,8 +6922,8 @@
var part = order[i];
if (part.to > start && part.from <= start) break;
}
if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title);
inner(builder, text.slice(0, part.to - start), style, startStyle, null, title);
if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css);
inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css);
startStyle = null;
text = text.slice(part.to - start);
start = part.to;
@ -6888,8 +6965,13 @@
var foundBookmarks = [];
for (var j = 0; j < spans.length; ++j) {
var sp = spans[j], m = sp.marker;
if (sp.from <= pos && (sp.to == null || sp.to > pos)) {
if (sp.to != null && nextChange > sp.to) { nextChange = sp.to; spanEndStyle = ""; }
if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
foundBookmarks.push(m);
} else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
if (sp.to != null && sp.to != pos && nextChange > sp.to) {
nextChange = sp.to;
spanEndStyle = "";
}
if (m.className) spanStyle += " " + m.className;
if (m.css) css = m.css;
if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle;
@ -6900,12 +6982,12 @@
} else if (sp.from > pos && nextChange > sp.from) {
nextChange = sp.from;
}
if (m.type == "bookmark" && sp.from == pos && m.widgetNode) foundBookmarks.push(m);
}
if (collapsed && (collapsed.from || 0) == pos) {
buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos,
collapsed.marker, collapsed.from == null);
if (collapsed.to == null) return;
if (collapsed.to == pos) collapsed = false;
}
if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j)
buildCollapsedSpan(builder, 0, foundBookmarks[j]);
@ -7368,13 +7450,19 @@
});
}),
addLineWidget: docMethodOp(function(handle, node, options) {
return addLineWidget(this, handle, node, options);
}),
removeLineWidget: function(widget) { widget.clear(); },
markText: function(from, to, options) {
return markText(this, clipPos(this, from), clipPos(this, to), options, "range");
},
setBookmark: function(pos, options) {
var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options),
insertLeft: options && options.insertLeft,
clearWhenEmpty: false, shared: options && options.shared};
clearWhenEmpty: false, shared: options && options.shared,
handleMouseEvents: options && options.handleMouseEvents};
pos = clipPos(this, pos);
return markText(this, pos, pos, realOpts, "bookmark");
},
@ -7489,7 +7577,7 @@
Doc.prototype.eachLine = Doc.prototype.iter;
// Set up methods on CodeMirror's prototype to redirect to the editor's document.
var dontDelegate = "iter insert remove copy getEditor".split(" ");
var dontDelegate = "iter insert remove copy getEditor constructor".split(" ");
for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0)
CodeMirror.prototype[prop] = (function(method) {
return function() {return method.apply(this.doc, arguments);};
@ -8108,7 +8196,7 @@
return function(){return f.apply(null, args);};
}
var nonASCIISingleCaseWordChar = /[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
var isWordCharBasic = CodeMirror.isWordChar = function(ch) {
return /\w/.test(ch) || ch > "\x80" &&
(ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch));
@ -8630,6 +8718,8 @@
lst(order).to -= m[0].length;
order.push(new BidiSpan(0, len - m[0].length, len));
}
if (order[0].level == 2)
order.unshift(new BidiSpan(1, order[0].to, order[0].to));
if (order[0].level != lst(order).level)
order.push(new BidiSpan(order[0].level, len, len));
@ -8639,7 +8729,7 @@
// THE END
CodeMirror.version = "5.0.1";
CodeMirror.version = "5.4.0";
return CodeMirror;
});

View File

@ -482,8 +482,11 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
function maybetype(type) {
if (isTS && type == ":") return cont(typedef);
}
function maybedefault(_, value) {
if (value == "=") return cont(expressionNoComma);
}
function typedef(type) {
if (type == "variable"){cx.marked = "variable-3"; return cont();}
if (type == "variable") {cx.marked = "variable-3"; return cont();}
}
function vardef() {
return pass(pattern, maybetype, maybeAssign, vardefCont);
@ -538,7 +541,7 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
}
function funarg(type) {
if (type == "spread") return cont(funarg);
return pass(pattern, maybetype);
return pass(pattern, maybetype, maybedefault);
}
function className(type, value) {
if (type == "variable") {register(value); return cont(classNameAfter);}
@ -549,6 +552,10 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
}
function classBody(type, value) {
if (type == "variable" || cx.style == "keyword") {
if (value == "static") {
cx.marked = "keyword";
return cont(classBody);
}
cx.marked = "property";
if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody);
return cont(functiondef, classBody);
@ -581,7 +588,11 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
function importSpec(type, value) {
if (type == "{") return contCommasep(importSpec, "}");
if (type == "variable") register(value);
return cont();
if (value == "*") cx.marked = "keyword";
return cont(maybeAs);
}
function maybeAs(_type, value) {
if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
}
function maybeFrom(_type, value) {
if (value == "from") { cx.marked = "keyword"; return cont(expression); }
@ -669,6 +680,7 @@ CodeMirror.defineMode("javascript", function(config, parserConfig) {
blockCommentEnd: jsonMode ? null : "*/",
lineComment: jsonMode ? null : "//",
fold: "brace",
closeBrackets: "()[]{}''\"\"``",
helperType: jsonMode ? "json" : "javascript",
jsonldMode: jsonldMode,

View File

@ -257,7 +257,7 @@ CodeMirror.defineMode("sql", function(config, parserConfig) {
}
// these keywords are used by all SQL dialects (however, a mode can still overwrite it)
var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from having in insert into is join like not on or order select set table union update values where ";
var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where ";
// turn a space-separated list into an array
function set(str) {
@ -280,7 +280,7 @@ CodeMirror.defineMode("sql", function(config, parserConfig) {
CodeMirror.defineMIME("text/x-mssql", {
name: "sql",
client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
keywords: set(sqlKeywords + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered"),
keywords: set(sqlKeywords + "begin trigger proc view index for add constraint key primary foreign collate clustered nonclustered declare"),
builtin: set("bigint numeric bit smallint decimal smallmoney int tinyint money float real char varchar text nchar nvarchar ntext binary varbinary image cursor timestamp hierarchyid uniqueidentifier sql_variant xml table "),
atoms: set("false true null unknown"),
operatorChars: /^[*+\-%<>!=]/,
@ -293,7 +293,7 @@ CodeMirror.defineMode("sql", function(config, parserConfig) {
CodeMirror.defineMIME("text/x-mysql", {
name: "sql",
client: set("charset clear connect edit ego exit go help nopager notee nowarning pager print prompt quit rehash source status system tee"),
keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group groupby_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
keywords: set(sqlKeywords + "accessible action add after algorithm all analyze asensitive at authors auto_increment autocommit avg avg_row_length before binary binlog both btree cache call cascade cascaded case catalog_name chain change changed character check checkpoint checksum class_origin client_statistics close coalesce code collate collation collations column columns comment commit committed completion concurrent condition connection consistent constraint contains continue contributors convert cross current current_date current_time current_timestamp current_user cursor data database databases day_hour day_microsecond day_minute day_second deallocate dec declare default delay_key_write delayed delimiter des_key_file describe deterministic dev_pop dev_samp deviance diagnostics directory disable discard distinctrow div dual dumpfile each elseif enable enclosed end ends engine engines enum errors escape escaped even event events every execute exists exit explain extended fast fetch field fields first flush for force foreign found_rows full fulltext function general get global grant grants group group_concat handler hash help high_priority hosts hour_microsecond hour_minute hour_second if ignore ignore_server_ids import index index_statistics infile inner innodb inout insensitive insert_method install interval invoker isolation iterate key keys kill language last leading leave left level limit linear lines list load local localtime localtimestamp lock logs low_priority master master_heartbeat_period master_ssl_verify_server_cert masters match max max_rows maxvalue message_text middleint migrate min min_rows minute_microsecond minute_second mod mode modifies modify mutex mysql_errno natural next no no_write_to_binlog offline offset one online open optimize option optionally out outer outfile pack_keys parser partition partitions password phase plugin plugins prepare preserve prev primary privileges procedure processlist profile profiles purge query quick range read read_write reads real rebuild recover references regexp relaylog release remove rename reorganize repair repeatable replace require resignal restrict resume return returns revoke right rlike rollback rollup row row_format rtree savepoint schedule schema schema_name schemas second_microsecond security sensitive separator serializable server session share show signal slave slow smallint snapshot soname spatial specific sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache sql_small_result sqlexception sqlstate sqlwarning ssl start starting starts status std stddev stddev_pop stddev_samp storage straight_join subclass_origin sum suspend table_name table_statistics tables tablespace temporary terminated to trailing transaction trigger triggers truncate uncommitted undo uninstall unique unlock upgrade usage use use_frm user user_resources user_statistics using utc_date utc_time utc_timestamp value variables varying view views warnings when while with work write xa xor year_month zerofill begin do then else loop repeat"),
builtin: set("bool boolean bit blob decimal double float long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision date datetime year unsigned signed numeric"),
atoms: set("false true null unknown"),
operatorChars: /^[*+\-%<>!=&|^]/,
@ -327,9 +327,9 @@ CodeMirror.defineMode("sql", function(config, parserConfig) {
CodeMirror.defineMIME("text/x-cassandra", {
name: "sql",
client: { },
keywords: set("use select from using consistency where limit first reversed first and in insert into values using consistency ttl update set delete truncate begin batch apply create keyspace with columnfamily primary key index on drop alter type add any one quorum all local_quorum each_quorum"),
builtin: set("ascii bigint blob boolean counter decimal double float int text timestamp uuid varchar varint"),
atoms: set("false true"),
keywords: set("add all allow alter and any apply as asc authorize batch begin by clustering columnfamily compact consistency count create custom delete desc distinct drop each_quorum exists filtering from grant if in index insert into key keyspace keyspaces level limit local_one local_quorum modify nan norecursive nosuperuser not of on one order password permission permissions primary quorum rename revoke schema select set storage superuser table three to token truncate ttl two type unlogged update use user users using values where with writetime"),
builtin: set("ascii bigint blob boolean counter decimal double float frozen inet int list map static text timestamp timeuuid tuple uuid varchar varint"),
atoms: set("false true infinity NaN"),
operatorChars: /^[<>=]/,
dateSQL: { },
support: set("commentSlashSlash decimallessFloat"),

View File

@ -140,7 +140,7 @@ var PMA_commonActions = {
*/
refreshMain: function (url, callback) {
if (! url) {
url = $('#selflink a').attr('href');
url = $('#selflink').find('a').attr('href');
url = url.substring(0, url.indexOf('?'));
}
url += PMA_commonParams.getUrlQuery();
@ -350,9 +350,10 @@ PMA_DROP_IMPORT = {
_dragleave: function (event) {
event.stopPropagation();
event.preventDefault();
$(".pma_drop_handler").clearQueue().stop();
$(".pma_drop_handler").fadeOut();
$(".pma_drop_handler").html(PMA_messages.dropImportDropFiles);
var $pma_drop_handler = $(".pma_drop_handler");
$pma_drop_handler.clearQueue().stop();
$pma_drop_handler.fadeOut();
$pma_drop_handler.html(PMA_messages.dropImportDropFiles);
},
/**
* Called when upload has finished
@ -423,15 +424,17 @@ PMA_DROP_IMPORT = {
var ext = (PMA_DROP_IMPORT._getExtension(files[i].name));
var hash = AJAX.hash(++PMA_DROP_IMPORT.uploadCount);
$(".pma_sql_import_status div").append('<li data-hash="' +hash +'">' +
var $pma_sql_import_status_div = $(".pma_sql_import_status div");
$pma_sql_import_status_div.append('<li data-hash="' +hash +'">' +
((ext !== '') ? '' : '<img src="./themes/dot.gif" title="invalid format" class="icon ic_s_notice"> ') +
escapeHtml(files[i].name) + '<span class="filesize" data-filename="' +
escapeHtml(files[i].name) +'">' +(files[i].size/1024).toFixed(2) +
' kb</span></li>');
//scroll the UI to bottom
$(".pma_sql_import_status div").scrollTop(
$(".pma_sql_import_status div").scrollTop() + 50); //50 hardcoded for now
$pma_sql_import_status_div.scrollTop(
$pma_sql_import_status_div.scrollTop() + 50
); //50 hardcoded for now
if (ext !== '') {
// Increment liveUploadCount by one

View File

@ -7,8 +7,8 @@
* Unbind all event handlers before tearing down a page
*/
AJAX.registerTeardown('config.js', function () {
$('input[id], select[id], textarea[id]').unbind('change').unbind('keyup');
$('input[type=button][name=submit_reset]').unbind('click');
$('.optbox input[id], .optbox select[id], .optbox textarea[id]').unbind('change').unbind('keyup');
$('.optbox input[type=button][name=submit_reset]').unbind('click');
$('div.tabs_contents').undelegate();
$('#import_local_storage, #export_local_storage').unbind('click');
$('form.prefs-form').unbind('change').unbind('submit');
@ -17,8 +17,9 @@ AJAX.registerTeardown('config.js', function () {
});
AJAX.registerOnload('config.js', function () {
$('#topmenu2').find('li.active a').attr('rel', 'samepage');
$('#topmenu2').find('li:not(.active) a').attr('rel', 'newpage');
var $topmenu_upt = $('#topmenu2.user_prefs_tabs');
$topmenu_upt.find('li.active a').attr('rel', 'samepage');
$topmenu_upt.find('li:not(.active) a').attr('rel', 'newpage');
});
// default values for fields
@ -43,6 +44,35 @@ function getFieldType(field)
return '';
}
/**
* Enables or disables the "restore default value" button
*
* @param {Element} field
* @param {boolean} display
*/
function setRestoreDefaultBtn(field, display)
{
var $el = $(field).closest('td').find('.restore-default img');
$el[display ? 'show' : 'hide']();
}
/**
* Marks field depending on its value (system default or custom)
*
* @param {Element} field
*/
function markField(field)
{
var $field = $(field);
var type = getFieldType($field);
var isDefault = checkFieldDefault($field, type);
// checkboxes uses parent <span> for marking
var $fieldMarker = (type == 'checkbox') ? $field.parent() : $field;
setRestoreDefaultBtn($field, !isDefault);
$fieldMarker[isDefault ? 'removeClass' : 'addClass']('custom');
}
/**
* Sets field value
*
@ -299,7 +329,7 @@ function validateField(id, type, onKeyUp, params)
function getFieldValidators(field_id, onKeyUpOnly)
{
// look for field bound validator
var name = field_id.match(/[^-]+$/)[0];
var name = field_id && field_id.match(/[^-]+$/)[0];
if (typeof validators._field[name] != 'undefined') {
return [[validators._field[name], null]];
}
@ -423,7 +453,7 @@ function validate_field(field, isKeyUp, errors)
args = [];
}
args.unshift(isKeyUp);
result = functions[i][0].apply(field[0], args);
result = functions[i][0].apply($field[0], args);
if (result !== true) {
if (typeof result == 'string') {
result = [result];
@ -444,43 +474,30 @@ function validate_field_and_fieldset(field, isKeyUp)
var $field = $(field);
var errors = {};
validate_field($field, isKeyUp, errors);
validate_fieldset($field.closest('fieldset'), isKeyUp, errors);
validate_fieldset($field.closest('fieldset.optbox'), isKeyUp, errors);
displayErrors(errors);
}
/**
* Marks field depending on its value (system default or custom)
*
* @param {Element} field
*/
function markField(field)
{
var $field = $(field);
var type = getFieldType($field);
var isDefault = checkFieldDefault($field, type);
// checkboxes uses parent <span> for marking
var $fieldMarker = (type == 'checkbox') ? $field.parent() : $field;
setRestoreDefaultBtn($field, !isDefault);
$fieldMarker[isDefault ? 'removeClass' : 'addClass']('custom');
function loadInlineConfig() {
if (!Array.isArray(configInlineParams)) {
return;
}
for (var i = 0; i < configInlineParams.length; ++i) {
if (typeof configInlineParams[i] === 'function') {
configInlineParams[i]();
}
}
}
/**
* Enables or disables the "restore default value" button
*
* @param {Element} field
* @param {boolean} display
*/
function setRestoreDefaultBtn(field, display)
{
var $el = $(field).closest('td').find('.restore-default img');
$el[display ? 'show' : 'hide']();
}
AJAX.registerOnload('config.js', function () {
function setupValidation() {
validate = {};
configScriptLoaded = true;
if (configScriptLoaded && typeof configInlineParams !== "undefined") {
loadInlineConfig();
}
// register validators and mark custom values
var $elements = $('input[id], select[id], textarea[id]');
$('input[id], select[id], textarea[id]').each(function () {
var $elements = $('.optbox input[id], .optbox select[id], .optbox textarea[id]');
$elements.each(function () {
markField(this);
var $el = $(this);
$el.bind('change', function () {
@ -511,7 +528,7 @@ AJAX.registerOnload('config.js', function () {
validate_field($elements[i], false, errors);
}
// run all fieldset validators
$('fieldset').each(function () {
$('fieldset.optbox').each(function () {
validate_fieldset(this, false, errors);
});
@ -519,6 +536,10 @@ AJAX.registerOnload('config.js', function () {
} else if ($check_page_refresh) {
$check_page_refresh.val('1');
}
}
AJAX.registerOnload('config.js', function () {
setupValidation();
});
//
@ -536,27 +557,42 @@ AJAX.registerOnload('config.js', function () {
*/
function setTab(tab_id)
{
$('ul.tabs li').removeClass('active').find('a[href=#' + tab_id + ']').parent().addClass('active');
$('div.tabs_contents fieldset').hide().filter('#' + tab_id).show();
location.hash = 'tab_' + tab_id;
$('form.config-form input[name=tab_hash]').val(location.hash);
$('ul.tabs').each(function() {
var $this = $(this);
if (!$this.find('li a[href=#' + tab_id + ']').length) {
return;
}
$this.find('li').removeClass('active').find('a[href=#' + tab_id + ']').parent().addClass('active');
$this.parent().find('div.tabs_contents fieldset').hide().filter('#' + tab_id).show();
location.hash = 'tab_' + tab_id;
$this.parent().find('input[name=tab_hash]').val(location.hash);
});
}
function setupConfigTabs() {
var forms = $('form.config-form');
forms.each(function() {
var $this = $(this);
var $tabs = $this.find('ul.tabs');
if (!$tabs.length) {
return;
}
// add tabs events and activate one tab (the first one or indicated by location hash)
$tabs.find('li').removeClass('active');
$tabs.find('a')
.click(function (e) {
e.preventDefault();
setTab($(this).attr('href').substr(1));
})
.filter(':first')
.parent()
.addClass('active');
$this.find('div.tabs_contents fieldset').hide().filter(':first').show();
});
}
AJAX.registerOnload('config.js', function () {
var $tabs = $('ul.tabs');
if (!$tabs.length) {
return;
}
// add tabs events and activate one tab (the first one or indicated by location hash)
$tabs.find('a')
.click(function (e) {
e.preventDefault();
setTab($(this).attr('href').substr(1));
})
.filter(':first')
.parent()
.addClass('active');
$('div.tabs_contents fieldset').hide().filter(':first').show();
setupConfigTabs();
// tab links handling, check each 200ms
// (works with history in FF, further browser support here would be an overkill)
@ -582,7 +618,7 @@ AJAX.registerOnload('config.js', function () {
//
AJAX.registerOnload('config.js', function () {
$('input[type=button][name=submit_reset]').click(function () {
$('.optbox input[type=button][name=submit_reset]').click(function () {
var fields = $(this).closest('fieldset').find('input, select, textarea');
for (var i = 0, imax = fields.length; i < imax; i++) {
setFieldValue(fields[i], getFieldType(fields[i]));
@ -612,7 +648,7 @@ function restoreField(field_id)
setFieldValue($field, getFieldType($field), defaultValues[field_id]);
}
AJAX.registerOnload('config.js', function () {
function setupRestoreField() {
$('div.tabs_contents')
.delegate('.restore-default, .set-value', 'mouseenter', function () {
$(this).css('opacity', 1);
@ -637,6 +673,10 @@ AJAX.registerOnload('config.js', function () {
.find('.restore-default, .set-value')
// inline-block for IE so opacity inheritance works
.css({display: 'inline-block', opacity: 0.25});
}
AJAX.registerOnload('config.js', function () {
setupRestoreField();
});
//
@ -763,7 +803,7 @@ function updatePrefsDate()
'@DATE@',
PMA_formatDateTime(d)
);
$('#opts_import_local_storage div.localStorage-exists').html(msg);
$('#opts_import_local_storage').find('div.localStorage-exists').html(msg);
}
/**

File diff suppressed because it is too large Load Diff

View File

@ -12,6 +12,7 @@
* Actions ajaxified here:
* Inline Edit and save of a result row
* Delete a row
* Multiple edit and delete option
*
*/
@ -24,14 +25,19 @@ AJAX.registerTeardown('db_central_columns.js', function () {
$('.edit_cancel_form').unbind('click');
$('#table-select').unbind('change');
$('#column-select').unbind('change');
$("#add_col_div>a").unbind('click');
$("#add_col_div").find(">a").unbind('click');
$('#add_new').unbind('submit');
$('#multi_edit_central_columns').unbind('submit');
$("select.default_type").unbind('change');
$("button[name='delete_central_columns']").unbind('click');
$("button[name='edit_central_columns']").unbind('click');
});
AJAX.registerOnload('db_central_columns.js', function () {
$('#tableslistcontainer input,#tableslistcontainer select,.default_value,.open_enum_editor').hide();
if ($('#table_columns tbody tr').length > 0) {
$('#tableslistcontainer input,#tableslistcontainer select,#tableslistcontainer .default_value,#tableslistcontainer .open_enum_editor').hide();
$('#tableslistcontainer').find('.checkall').show();
$('#tableslistcontainer').find('.checkall_box').show();
if ($('#table_columns').find('tbody tr').length > 0) {
$("#table_columns").tablesorter({
headers: {
0: {sorter: false},
@ -40,12 +46,43 @@ AJAX.registerOnload('db_central_columns.js', function () {
}
});
}
$('#add_new td').each(function(){
$('#tableslistcontainer').find('button[name="delete_central_columns"]').click(function(event){
event.preventDefault();
var multi_delete_columns = $('.checkall:checkbox:checked').serialize();
if(multi_delete_columns === ''){
PMA_ajaxShowMessage(PMA_messages.strRadioUnchecked);
return false;
}
PMA_ajaxShowMessage();
$("#del_col_name").val(multi_delete_columns);
$("#del_form").submit();
});
$('#tableslistcontainer').find('button[name="edit_central_columns"]').click(function(event){
event.preventDefault();
var editColumnList = $('.checkall:checkbox:checked').serialize();
if(editColumnList === ''){
PMA_ajaxShowMessage(PMA_messages.strRadioUnchecked);
return false;
}
var editColumnData = editColumnList+ '&edit_central_columns_page=true&ajax_request=true&ajax_page_request=true&token='+PMA_commonParams.get('token')+'&db='+PMA_commonParams.get('db');
PMA_ajaxShowMessage();
AJAX.source = $(this);
$.get('db_central_columns.php', editColumnData, AJAX.responseHandler);
});
$('#multi_edit_central_columns').submit(function(event){
event.preventDefault();
event.stopPropagation();
var multi_column_edit_data = $("#multi_edit_central_columns").serialize()+'&multi_edit_central_column_save=true&ajax_request=true&ajax_page_request=true&token='+PMA_commonParams.get('token')+'&db='+PMA_commonParams.get('db');
PMA_ajaxShowMessage();
AJAX.source = $(this);
$.post('db_central_columns.php', multi_column_edit_data, AJAX.responseHandler);
});
$('#add_new').find('td').each(function(){
if ($(this).attr('name') !== 'undefined') {
$(this).find('input,select:first').attr('name', $(this).attr('name'));
}
});
$("#add_new #field_0_0").attr('required','required');
$("#field_0_0").attr('required','required');
$('#add_new input[type="text"], #add_new input[type="number"], #add_new select')
.css({
'width' : '10em',
@ -60,15 +97,13 @@ AJAX.registerOnload('db_central_columns.js', function () {
$.uiTableFilter($("#table_columns"), $(this).val(), cols, null, "td span");
});
$('.edit').click(function() {
rownum = $(this).parent().data('rownum');
var rownum = $(this).parent().data('rownum');
$('#save_' + rownum).show();
$(this).hide();
$('#f_' + rownum + ' td span').hide();
$('#f_' + rownum + ' input, #f_' + rownum + ' select, #f_' + rownum + ' .open_enum_editor').show();
var extra_val = $('#f_' + rownum + ' td[name=col_extra] span').html();
var attribute_val = $('#f_' + rownum + ' td[name=col_attribute] span').html();
$('#f_' + rownum + ' select[name=field_attribute\\['+ rownum +'\\] ] option[value="' + attribute_val + '"]').attr("selected","selected");
$('#f_' + rownum + ' select[name=col_extra] option[value="' + extra_val + '"]').attr("selected","selected");
if($('#f_' + rownum + ' .default_type').val() === 'USER_DEFINED') {
$('#f_' + rownum + ' .default_type').siblings('.default_value').show();
} else {
@ -78,28 +113,29 @@ AJAX.registerOnload('db_central_columns.js', function () {
$(".del_row").click(function (event) {
event.preventDefault();
event.stopPropagation();
$td = $(this);
var $td = $(this);
var question = PMA_messages.strDeleteCentralColumnWarning;
$td.PMA_confirm(question, null, function (url) {
rownum = $td.data('rownum');
$("#del_col_name").val($('#f_' + rownum + ' td[name=col_name] span').html());
var rownum = $td.data('rownum');
$("#del_col_name").val("selected_fld%5B%5D="+$('#checkbox_row_' + rownum ).val());
$("#del_form").submit();
});
});
$('.edit_cancel_form').click(function(event) {
event.preventDefault();
event.stopPropagation();
rownum = $(this).data('rownum');
var rownum = $(this).data('rownum');
$('#save_' + rownum).hide();
$('#edit_' + rownum).show();
$('#f_' + rownum + ' td span').show();
$('#f_' + rownum + ' input, #f_' + rownum + ' select,#f_'+rownum+' .default_value, #f_' + rownum + ' .open_enum_editor').hide();
$('#tableslistcontainer').find('.checkall').show();
});
$('.edit_save_form').click(function(event) {
//alert(1);
event.preventDefault();
event.stopPropagation();
rownum = $(this).data('rownum');
var rownum = $(this).data('rownum');
$('#f_' + rownum + ' td').each(function() {
if ($(this).attr('name') !== 'undefined') {
$(this).find(':input[type!="hidden"],select:first')
@ -133,14 +169,15 @@ AJAX.registerOnload('db_central_columns.js', function () {
$('#f_' + rownum + ' td[name=col_length] span').text($('#f_' + rownum + ' input[name=col_length]').val()).html();
$('#f_' + rownum + ' td[name=collation] span').text($('#f_' + rownum + ' select[name=collation]').val()).html();
$('#f_' + rownum + ' td[name=col_attribute] span').text($('#f_' + rownum + ' select[name=col_attribute]').val()).html();
$('#f_' + rownum + ' td[name=col_isNull] span').text($('#f_' + rownum + ' input[name=col_isNull]').val()).html();
$('#f_' + rownum + ' td[name=col_extra] span').text($('#f_' + rownum + ' select[name=col_extra]').val()).html();
$('#f_' + rownum + ' td[name=col_isNull] span').text($('#f_' + rownum +' input[name=col_isNull]').is(":checked")?"Yes":"No").html();
$('#f_' + rownum + ' td[name=col_extra] span').text($('#f_' + rownum + ' input[name=col_extra]').is(":checked") ? "auto_increment" : "").html();
$('#f_' + rownum + ' td[name=col_default] span').text($('#f_' + rownum + ' :input[name=col_default]').val()).html();
}
$('#save_' + rownum).hide();
$('#edit_' + rownum).show();
$('#f_' + rownum + ' td span').show();
$('#f_' + rownum + ' input, #f_' + rownum + ' select,#f_' + rownum + ' .default_value, #f_' + rownum + ' .open_enum_editor').hide();
$('#tableslistcontainer').find('.checkall').show();
},
error: function() {
PMA_ajaxShowMessage(
@ -154,7 +191,7 @@ AJAX.registerOnload('db_central_columns.js', function () {
});
$('#table-select').change(function(e) {
var selectvalue = $(this).val();
var default_column_select = $('#column-select option:first');
var default_column_select = $('#column-select').find('option:first');
var href = "db_central_columns.php";
var params = {
'ajax_request' : true,
@ -178,18 +215,19 @@ AJAX.registerOnload('db_central_columns.js', function () {
$("#add_column").submit();
}
});
$("#add_col_div>a").click(function(event){
$("#add_col_div").find(">a").click(function(event){
$('#add_new').slideToggle("slow");
if($("#add_col_div>a span").html() === '+') {
$("#add_col_div>a span").html('-');
var $addColDivLinkSpan = $("#add_col_div").find(">a span");
if($addColDivLinkSpan.html() === '+') {
$addColDivLinkSpan.html('-');
} else {
$("#add_col_div>a span").html('+');
$addColDivLinkSpan.html('+');
}
});
$('#add_new').submit(function(event){
$('#add_new').toggle();
});
$("select.default_type").change(function () {
$("#tableslistcontainer").find("select.default_type").change(function () {
if ($(this).val() === 'USER_DEFINED') {
$(this).siblings('.default_value').attr('name','col_default');
$(this).attr('name','col_default_sel');

View File

@ -20,6 +20,7 @@
* Unbind all event handlers before tearing down a page
*/
AJAX.registerTeardown('db_qbe.js', function () {
$(document).off('change', 'select[name^=criteriaColumn]');
$(document).off('change', "#searchId");
$(document).off('click', "#saveSearch");
$(document).off('click', "#updateSearch");
@ -28,6 +29,18 @@ AJAX.registerTeardown('db_qbe.js', function () {
AJAX.registerOnload('db_qbe.js', function () {
PMA_getSQLEditor($('#textSqlquery'), {}, 'both');
/**
* Ajax handler to check the corresponding 'show' checkbox when column is selected
*/
$(document).on('change', 'select[name^=criteriaColumn]', function (event) {
if ($(this).val()) {
var index = (/\d+/).exec($(this).attr('name'));
$('input[name=criteriaShow\\[' + index + '\\]]').prop('checked', true);
}
});
/**
* Ajax event handlers for 'Select saved search'
*/
@ -39,7 +52,7 @@ AJAX.registerOnload('db_qbe.js', function () {
/**
* Ajax event handlers for 'Create bookmark'
*/
$(document).on('click', "#saveSearch", function (event) {
$(document).on('click', "#saveSearch", function () {
$('#action').val('create');
});
@ -54,11 +67,11 @@ AJAX.registerOnload('db_qbe.js', function () {
* Ajax event handlers for 'Delete bookmark'
*/
$(document).on('click', "#deleteSearch", function (event) {
var question = PMA_sprintf(PMA_messages.strConfirmDeleteQBESearch, $("#searchId option:selected").text());
var question = PMA_sprintf(PMA_messages.strConfirmDeleteQBESearch, $("#searchId").find("option:selected").text());
if (!confirm(question)) {
return false;
}
$('#action').val('delete');
});
});
});

View File

@ -26,6 +26,7 @@ AJAX.registerTeardown('db_structure.js', function () {
$(document).off('click', "a.drop_table_anchor.ajax");
$(document).off('click', '#real_end_input');
$(document).off('click', "a.favorite_table_anchor.ajax");
$(document).off('click', '#printView');
$('a.real_row_count').off('click');
$('a.row_count_sum').off('click');
$('select[name=submit_mult]').unbind('change');
@ -48,7 +49,7 @@ function PMA_adjustTotals() {
/**
* @var $allTr jQuery object that references all the rows in the list of tables
*/
var $allTr = $("#tablesForm table.data tbody:first tr");
var $allTr = $("#tablesForm").find("table.data tbody:first tr");
// New summary values for the table
var tableSum = $allTr.size();
var rowsSum = 0;
@ -126,7 +127,11 @@ function PMA_adjustTotals() {
// Update summary with new data
var $summary = $("#tbl_summary_row");
$summary.find('.tbl_num').text(PMA_sprintf(PMA_messages.strNTables, tableSum));
$summary.find('.row_count_sum').text(strRowSum);
if (rowSumApproximated) {
$summary.find('.row_count_sum').text(strRowSum);
} else {
$summary.find('.tbl_rows').text(strRowSum);
}
$summary.find('.tbl_size').text(sizeSum + " " + byteUnits[size_magnitude]);
$summary.find('.tbl_overhead').text(overheadSum + " " + byteUnits[overhead_magnitude]);
}
@ -137,7 +142,7 @@ function PMA_adjustTotals() {
*/
function PMA_fetchRealRowCount($target)
{
var $throbber = $('#pma_navigation .throbber')
var $throbber = $('#pma_navigation').find('.throbber')
.first()
.clone()
.css({visibility: 'visible', display: 'inline-block'})
@ -178,31 +183,6 @@ function PMA_fetchRealRowCount($target)
}
AJAX.registerOnload('db_structure.js', function () {
/**
* Handler for the print view multisubmit.
* All other multi submits can be handled via ajax, but this one needs
* special treatment as the results need to open in another browser window
*/
$('#tablesForm').submit(function (event) {
var $form = $(this);
if ($form.find('select[name=submit_mult]').val() === 'print') {
event.preventDefault();
event.stopPropagation();
$('form#clone').remove();
var $clone = $form
.clone()
.hide()
.appendTo('body');
$clone
.find('select[name=submit_mult]')
.val('print');
$clone
.attr('target', 'printview')
.attr('id', 'clone')
.submit();
}
});
/**
* function to open the confirmation dialog for making table consistent with central list
*
@ -264,13 +244,16 @@ AJAX.registerOnload('db_structure.js', function () {
* @var question String containing the question to be asked for confirmation
*/
var question = PMA_messages.strTruncateTableStrongWarning + ' ' +
PMA_sprintf(PMA_messages.strDoYouReally, 'TRUNCATE ' + escapeHtml(curr_table_name));
PMA_sprintf(PMA_messages.strDoYouReally, 'TRUNCATE ' + escapeHtml(curr_table_name)) +
getForeignKeyCheckboxLoader();
$this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) {
PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
$.get(url, {'is_js_confirmed' : 1, 'ajax_request' : true}, function (data) {
var params = getJSConfirmCommonParam(this);
$.get(url, params, function (data) {
if (typeof data !== 'undefined' && data.success === true) {
PMA_ajaxShowMessage(data.message);
// Adjust table statistics
@ -290,7 +273,7 @@ AJAX.registerOnload('db_structure.js', function () {
PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
}
}); // end $.get()
}); //end $.PMA_confirm()
}, loadForeignKeyCheckbox); //end $.PMA_confirm()
}); //end of Truncate Table Ajax action
/**
@ -325,12 +308,15 @@ AJAX.registerOnload('db_structure.js', function () {
question =
PMA_sprintf(PMA_messages.strDoYouReally, 'DROP VIEW ' + escapeHtml(curr_table_name));
}
question += getForeignKeyCheckboxLoader();
$this_anchor.PMA_confirm(question, $this_anchor.attr('href'), function (url) {
var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
$.get(url, {'is_js_confirmed' : 1, 'ajax_request' : true}, function (data) {
var params = getJSConfirmCommonParam(this);
$.get(url, params, function (data) {
if (typeof data !== 'undefined' && data.success === true) {
PMA_ajaxShowMessage(data.message);
toggleRowColors($curr_row.next());
@ -342,9 +328,19 @@ AJAX.registerOnload('db_structure.js', function () {
PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest + " : " + data.error, false);
}
}); // end $.get()
}); // end $.PMA_confirm()
}, loadForeignKeyCheckbox); // end $.PMA_confirm()
}); //end of Drop Table Ajax action
/**
* Attach Event Handler for 'Print View'
*/
$(document).on('click', "#printView", function (event) {
event.preventDefault();
// Print the page
printPage();
}); //end of Print View action
//Calculate Real End for InnoDB
/**
* Ajax Event handler for calculating the real end for a InnoDB table
@ -364,11 +360,6 @@ AJAX.registerOnload('db_structure.js', function () {
return false;
}); //end Calculate Real End for InnoDB
PMA_tooltip(
$("select[name*='funcs']"),
'select',
PMA_messages.strFunctionHint
);
// Add tooltip to favorite icons.
$(".favorite_table_anchor").each(function () {
PMA_tooltip(

View File

@ -12,8 +12,9 @@ AJAX.registerTeardown('db_tracking.js', function () {
*/
AJAX.registerOnload('db_tracking.js', function () {
$('#versions tr:first th').append($('<div class="sorticon"></div>'));
$('#versions').tablesorter({
var $versions = $('#versions');
$versions.find('tr:first th').append($('<div class="sorticon"></div>'));
$versions.tablesorter({
sortList: [[1, 0]],
headers: {
0: {sorter: false},
@ -24,8 +25,9 @@ AJAX.registerOnload('db_tracking.js', function () {
}
});
$('#noversions tr:first th').append($('<div class="sorticon"></div>'));
$('#noversions').tablesorter({
var $noVersions = $('#noversions');
$noVersions.find('tr:first th').append($('<div class="sorticon"></div>'));
$noVersions.tablesorter({
sortList: [[1, 0]],
headers: {
0: {sorter: false},
@ -33,10 +35,12 @@ AJAX.registerOnload('db_tracking.js', function () {
}
});
var $body = $('body');
/**
* Handles multi submit for tracked tables
*/
$('body').on('click', '#trackedForm.ajax button[name="submit_mult"], #trackedForm.ajax input[name="submit_mult"]', function (e) {
$body.on('click', '#trackedForm.ajax button[name="submit_mult"], #trackedForm.ajax input[name="submit_mult"]', function (e) {
e.preventDefault();
var $button = $(this);
var $form = $button.parent('form');
@ -59,7 +63,7 @@ AJAX.registerOnload('db_tracking.js', function () {
/**
* Handles multi submit for untracked tables
*/
$('body').on('click', '#untrackedForm.ajax button[name="submit_mult"], #untrackedForm.ajax input[name="submit_mult"]', function (e) {
$body.on('click', '#untrackedForm.ajax button[name="submit_mult"], #untrackedForm.ajax input[name="submit_mult"]', function (e) {
e.preventDefault();
var $button = $(this);
var $form = $button.parent('form');
@ -72,7 +76,7 @@ AJAX.registerOnload('db_tracking.js', function () {
/**
* Ajax Event handler for 'Delete tracking'
*/
$('body').on('click', 'a.delete_tracking_anchor.ajax', function (e) {
$body.on('click', 'a.delete_tracking_anchor.ajax', function (e) {
e.preventDefault();
var $anchor = $(this);
var question = PMA_messages.strDeleteTrackingData;

View File

@ -68,8 +68,8 @@ var ErrorReport = {
var button_options = {};
button_options[PMA_messages.strSendErrorReport] = function () {
$dialog = $(this);
post_data = $.extend(report_data, {
var $dialog = $(this);
var post_data = $.extend(report_data, {
send_error_report: true,
description: $("#report_description").val(),
always_send: $("#always_send_checkbox")[0].checked
@ -117,16 +117,16 @@ var ErrorReport = {
_showErrorNotification: function () {
ErrorReport._removeErrorNotification();
$div = $(
var $div = $(
'<div style="position:fixed;bottom:0;left:0;right:0;margin:0;' +
'z-index:1000" class="error" id="error_notification"></div>'
).append(
PMA_getImage("s_error.png") + PMA_messages.strErrorOccurred
);
$buttons = $('<div style="float:right"></div>');
var $buttons = $('<div class="floatright"></div>');
button_html = '<button id="show_error_report">';
var button_html = '<button id="show_error_report">';
button_html += PMA_messages.strShowReportDetails;
button_html += '</button>';
@ -187,35 +187,6 @@ var ErrorReport = {
ErrorReport._removeErrorNotification();
ErrorReport._showReportDialog(ErrorReport._last_exception);
},
/**
* Returns the needed info about stored microhistory
*
* @return object
*/
_get_microhistory: function () {
cached_pages = AJAX.cache.pages.slice(-7);
remove = ["common_query", "table", "db", "token", "pma_absolute_uri"];
return {
pages: cached_pages.map(function (page) {
simplepage = {
hash: page.hash
};
if (page.params) {
simplepage.params = $.extend({}, page.params);
$.each(simplepage.params, function (param) {
if ($.inArray(param, remove) != -1) {
delete simplepage.params[param];
}
});
}
return simplepage;
}),
current_index: AJAX.cache.current -
(AJAX.cache.pages.length - cached_pages.length)
};
},
/**
* Redirects to the settings page containing error report
* preferences
@ -238,11 +209,10 @@ var ErrorReport = {
"token": PMA_commonParams.get('token'),
"exception": exception,
"current_url": window.location.href,
"microhistory": ErrorReport._get_microhistory(),
"exception_type": 'js'
};
if (typeof AJAX.cache.pages[AJAX.cache.current - 1] !== 'undefined') {
report_data.scripts = AJAX.cache.pages[AJAX.cache.current - 1].scripts.map(
if (AJAX.scriptHandler._scripts.length > 0) {
report_data.scripts = AJAX.scriptHandler._scripts.map(
function (script) {
return script.name;
}

View File

@ -26,35 +26,266 @@ function enable_dump_some_rows_sub_options()
$("input[type='text'][name='limit_from']").prop('disabled', '');
}
/**
* Return template data as a json object
*
* @returns template data
*/
function getTemplateData()
{
var $form = $('form[name="dump"]');
var blacklist = ['token', 'server', 'db', 'table', 'single_table',
'export_type', 'export_method', 'sql_query', 'template_id'];
var obj = {};
var arr = $form.serializeArray();
$.each(arr, function () {
if ($.inArray(this.name, blacklist) < 0) {
if (obj[this.name] !== undefined) {
if (! obj[this.name].push) {
obj[this.name] = [obj[this.name]];
}
obj[this.name].push(this.value || '');
} else {
obj[this.name] = this.value || '';
}
}
});
// include unchecked checboxes (which are ignored by serializeArray()) with null
// to uncheck them when loading the template
$form.find('input[type="checkbox"]:not(:checked)').each(function () {
if (obj[this.name] === undefined) {
obj[this.name] = null;
}
});
// include empty multiselects
$form.find('select').each(function () {
if ($(this).find('option:selected').length == 0) {
obj[this.name] = [];
}
});
return obj;
}
/**
* Create a template with selected options
*
* @param name name of the template
*/
function createTemplate(name)
{
var templateData = getTemplateData();
var params = {
ajax_request : true,
token : PMA_commonParams.get('token'),
server : PMA_commonParams.get('server'),
db : PMA_commonParams.get('db'),
table : PMA_commonParams.get('table'),
exportType : $('input[name="export_type"]').val(),
templateAction : 'create',
templateName : name,
templateData : JSON.stringify(templateData)
};
PMA_ajaxShowMessage();
$.post('tbl_export.php', params, function (response) {
if (response.success === true) {
$('#templateName').val('');
$('#template').html(response.data);
$("#template").find("option").each(function() {
if ($(this).text() == name) {
$(this).prop('selected', true);
}
});
PMA_ajaxShowMessage(PMA_messages.strTemplateCreated);
} else {
PMA_ajaxShowMessage(response.error, false);
}
});
}
/**
* Loads a template
*
* @param id ID of the template to load
*/
function loadTemplate(id)
{
var params = {
ajax_request : true,
token : PMA_commonParams.get('token'),
server : PMA_commonParams.get('server'),
db : PMA_commonParams.get('db'),
table : PMA_commonParams.get('table'),
exportType : $('input[name="export_type"]').val(),
templateAction : 'load',
templateId : id,
};
PMA_ajaxShowMessage();
$.post('tbl_export.php', params, function (response) {
if (response.success === true) {
var $form = $('form[name="dump"]');
var options = $.parseJSON(response.data);
$.each(options, function (key, value) {
var $element = $form.find('[name="' + key + '"]');
if ($element.length) {
if (($element.is('input') && $element.attr('type') == 'checkbox') && value === null) {
$element.prop('checked', false);
} else {
if (($element.is('input') && $element.attr('type') == 'checkbox') ||
($element.is('input') && $element.attr('type') == 'radio') ||
($element.is('select') && $element.attr('multiple') == 'multiple')) {
if (! value.push) {
value = [value];
}
}
$element.val(value);
}
$element.trigger('change');
}
});
$('input[name="template_id"]').val(id);
PMA_ajaxShowMessage(PMA_messages.strTemplateLoaded);
} else {
PMA_ajaxShowMessage(response.error, false);
}
});
}
/**
* Updates an existing template with current options
*
* @param id ID of the template to update
*/
function updateTemplate(id)
{
var templateData = getTemplateData();
var params = {
ajax_request : true,
token : PMA_commonParams.get('token'),
server : PMA_commonParams.get('server'),
db : PMA_commonParams.get('db'),
table : PMA_commonParams.get('table'),
exportType : $('input[name="export_type"]').val(),
templateAction : 'update',
templateId : id,
templateData : JSON.stringify(templateData)
};
PMA_ajaxShowMessage();
$.post('tbl_export.php', params, function (response) {
if (response.success === true) {
PMA_ajaxShowMessage(PMA_messages.strTemplateUpdated);
} else {
PMA_ajaxShowMessage(response.error, false);
}
});
}
/**
* Delete a template
*
* @param id ID of the template to delete
*/
function deleteTemplate(id)
{
var params = {
ajax_request : true,
token : PMA_commonParams.get('token'),
server : PMA_commonParams.get('server'),
db : PMA_commonParams.get('db'),
table : PMA_commonParams.get('table'),
exportType : $('input[name="export_type"]').val(),
templateAction : 'delete',
templateId : id,
};
PMA_ajaxShowMessage();
$.post('tbl_export.php', params, function (response) {
if (response.success === true) {
$('#template').find('option[value="' + id + '"]').remove();
PMA_ajaxShowMessage(PMA_messages.strTemplateDeleted);
} else {
PMA_ajaxShowMessage(response.error, false);
}
});
}
/**
* Unbind all event handlers before tearing down a page
*/
AJAX.registerTeardown('export.js', function () {
$("#plugins").unbind('change');
$("input[type='radio'][name='sql_structure_or_data']").unbind('change');
$("input[type='radio'][name='latex_structure_or_data']").unbind('change');
$("input[type='radio'][name='odt_structure_or_data']").unbind('change');
$("input[type='radio'][name='texytext_structure_or_data']").unbind('change');
$("input[type='radio'][name='htmlword_structure_or_data']").unbind('change');
$("input[type='radio'][name='sql_structure_or_data']").unbind('change');
$("input[type='radio'][name$='_structure_or_data']").off('change');
$("input[type='radio'][name='output_format']").unbind('change');
$("#checkbox_sql_include_comments").unbind('change');
$("#plugins").unbind('change');
$("input[type='radio'][name='quick_or_custom']").unbind('change');
$("input[type='radio'][name='allrows']").unbind('change');
$('#btn_alias_config').off('click');
$('#db_alias_select').off('change');
$('.table_alias_select').off('change');
$('input[name="table_select[]"]').off('change');
$('input[name="table_structure[]"]').off('change');
$('input[name="table_data[]"]').off('change');
$('#table_structure_all').off('change');
$('#table_data_all').off('change');
$('input[name="createTemplate"]').off('click');
$('select[name="template"]').off('change');
$('input[name="updateTemplate"]').off('click');
$('input[name="deleteTemplate"]').off('click');
});
AJAX.registerOnload('export.js', function () {
/**
* Export template handling code
*/
// create a new template
$('input[name="createTemplate"]').on('click', function (e) {
e.preventDefault();
var name = $('input[name="templateName"]').val();
if (name.length) {
createTemplate(name);
}
});
// load an existing template
$('select[name="template"]').on('change', function (e) {
e.preventDefault();
var id = $(this).val();
if (id.length) {
loadTemplate(id);
}
});
// udpate an existing template with new criteria
$('input[name="updateTemplate"]').on('click', function (e) {
e.preventDefault();
var id = $('select[name="template"]').val();
if (id.length) {
updateTemplate(id);
}
});
// delete an existing template
$('input[name="deleteTemplate"]').on('click', function (e) {
e.preventDefault();
var id = $('select[name="template"]').val();
if (id.length) {
deleteTemplate(id);
}
});
/**
* Toggles the hiding and showing of each plugin's options
* according to the currently selected plugin from the dropdown list
*/
$("#plugins").change(function () {
$("#format_specific_opts div.format_specific_options").hide();
var selected_plugin_name = $("#plugins option:selected").val();
$("#format_specific_opts").find("div.format_specific_options").hide();
var selected_plugin_name = $("#plugins").find("option:selected").val();
$("#" + selected_plugin_name + "_options").show();
});
@ -86,15 +317,79 @@ AJAX.registerOnload('export.js', function () {
$("#checkbox_sql_auto_increment").removeProp('disabled').parent().fadeTo('fast', 1);
}
});
// For separate-file exports only ZIP compression is allowed
$('input[type="checkbox"][name="as_separate_files"]').change(function(){
if (! $(this).attr('checked')) {
$('#compression').val('zip');
}
});
$('#compression').change(function(){
if ($('option:selected').val() !== 'zip') {
$('input[type="checkbox"][name="as_separate_files"]').attr('checked', false);
}
});
});
function setup_table_structure_or_data() {
if ($("input[name='export_type']").val() != 'database') {
return;
}
var pluginName = $("#plugins").find("option:selected").val();
var formElemName = pluginName + "_structure_or_data";
var force_structure_or_data = !($("input[name='" + formElemName + "_default']").length);
if (force_structure_or_data === true) {
$('input[name="structure_or_data_forced"]').val(1);
$('.export_structure input[type="checkbox"], .export_data input[type="checkbox"]')
.prop('disabled', true);
$('.export_structure, .export_data').fadeTo('fast', 0.4);
} else {
$('input[name="structure_or_data_forced"]').val(0);
$('.export_structure input[type="checkbox"], .export_data input[type="checkbox"]')
.removeProp('disabled');
$('.export_structure, .export_data').fadeTo('fast', 1);
var structure_or_data = $('input[name="' + formElemName + '_default"]').val();
if (structure_or_data == 'structure') {
$('.export_data input[type="checkbox"]')
.prop('checked', false);
} else if (structure_or_data == 'data') {
$('.export_structure input[type="checkbox"]')
.prop('checked', false);
}
if (structure_or_data == 'structure' || structure_or_data == 'structure_and_data') {
if (!$('.export_structure input[type="checkbox"]:checked').length) {
$('input[name="table_select[]"]:checked')
.closest('tr')
.find('.export_structure input[type="checkbox"]')
.prop('checked', true);
}
}
if (structure_or_data == 'data' || structure_or_data == 'structure_and_data') {
if (!$('.export_data input[type="checkbox"]:checked').length) {
$('input[name="table_select[]"]:checked')
.closest('tr')
.find('.export_data input[type="checkbox"]')
.prop('checked', true);
}
}
check_selected_tables();
check_table_select_all();
}
}
/**
* Toggles the hiding and showing of plugin structure-specific and data-specific
* options
*/
function toggle_structure_data_opts(pluginName)
function toggle_structure_data_opts()
{
var pluginName = $("select#plugins").val();
var radioFormName = pluginName + "_structure_or_data";
var dataDiv = "#" + pluginName + "_data";
var structureDiv = "#" + pluginName + "_structure";
@ -112,37 +407,20 @@ function toggle_structure_data_opts(pluginName)
}
}
AJAX.registerOnload('export.js', function () {
$("input[type='radio'][name='latex_structure_or_data']").change(function () {
toggle_structure_data_opts("latex");
});
$("input[type='radio'][name='odt_structure_or_data']").change(function () {
toggle_structure_data_opts("odt");
});
$("input[type='radio'][name='texytext_structure_or_data']").change(function () {
toggle_structure_data_opts("texytext");
});
$("input[type='radio'][name='htmlword_structure_or_data']").change(function () {
toggle_structure_data_opts("htmlword");
});
$("input[type='radio'][name='sql_structure_or_data']").change(function () {
toggle_structure_data_opts("sql");
});
});
/**
* Toggles the disabling of the "save to file" options
*/
function toggle_save_to_file()
{
var $ulSaveAsfile = $("#ul_save_asfile");
if (!$("#radio_dump_asfile").prop("checked")) {
$("#ul_save_asfile > li").fadeTo('fast', 0.4);
$("#ul_save_asfile > li > input").prop('disabled', true);
$("#ul_save_asfile > li> select").prop('disabled', true);
$ulSaveAsfile.find("> li").fadeTo('fast', 0.4);
$ulSaveAsfile.find("> li > input").prop('disabled', true);
$ulSaveAsfile.find("> li > select").prop('disabled', true);
} else {
$("#ul_save_asfile > li").fadeTo('fast', 1);
$("#ul_save_asfile > li > input").prop('disabled', false);
$("#ul_save_asfile > li> select").prop('disabled', false);
$ulSaveAsfile.find("> li").fadeTo('fast', 1);
$ulSaveAsfile.find("> li > input").prop('disabled', false);
$ulSaveAsfile.find("> li > select").prop('disabled', false);
}
}
@ -157,27 +435,117 @@ AJAX.registerOnload('export.js', function () {
function toggle_sql_include_comments()
{
$("#checkbox_sql_include_comments").change(function () {
var $ulIncludeComments = $("#ul_include_comments");
if (!$("#checkbox_sql_include_comments").prop("checked")) {
$("#ul_include_comments > li").fadeTo('fast', 0.4);
$("#ul_include_comments > li > input").prop('disabled', true);
$ulIncludeComments.find("> li").fadeTo('fast', 0.4);
$ulIncludeComments.find("> li > input").prop('disabled', true);
} else {
// If structure is not being exported, the comment options for structure should not be enabled
if ($("#radio_sql_structure_or_data_data").prop("checked")) {
$("#text_sql_header_comment").removeProp('disabled').parent("li").fadeTo('fast', 1);
} else {
$("#ul_include_comments > li").fadeTo('fast', 1);
$("#ul_include_comments > li > input").removeProp('disabled');
$ulIncludeComments.find("> li").fadeTo('fast', 1);
$ulIncludeComments.find("> li > input").removeProp('disabled');
}
}
});
}
function check_table_select_all() {
var total = $('input[name="table_select[]"]').length;
var str_checked = $('input[name="table_structure[]"]:checked').length;
var data_checked = $('input[name="table_data[]"]:checked').length;
var str_all = $('#table_structure_all');
var data_all = $('#table_data_all');
if (str_checked == total) {
str_all
.prop("indeterminate", false)
.prop('checked', true);
} else if (str_checked === 0) {
str_all
.prop("indeterminate", false)
.prop('checked', false);
} else {
str_all
.prop("indeterminate", true)
.prop('checked', false);
}
if (data_checked == total) {
data_all
.prop("indeterminate", false)
.prop('checked', true);
} else if (data_checked === 0) {
data_all
.prop("indeterminate", false)
.prop('checked', false);
} else {
data_all
.prop("indeterminate", true)
.prop('checked', false);
}
}
function toggle_table_select_all_str() {
var str_all = $('#table_structure_all').is(':checked');
if (str_all) {
$('input[name="table_structure[]"]').prop('checked', true);
} else {
$('input[name="table_structure[]"]').prop('checked', false);
}
}
function toggle_table_select_all_data() {
var data_all = $('#table_data_all').is(':checked');
if (data_all) {
$('input[name="table_data[]"]').prop('checked', true);
} else {
$('input[name="table_data[]"]').prop('checked', false);
}
}
function check_selected_tables(argument) {
$('.export_table_select tbody tr').each(function() {
check_table_selected(this);
});
}
function check_table_selected(row) {
var $row = $(row);
var table_select = $row.find('input[name="table_select[]"]');
var str_check = $row.find('input[name="table_structure[]"]');
var data_check = $row.find('input[name="table_data[]"]');
var data = data_check.is(':checked:not(:disabled)');
var structure = str_check.is(':checked:not(:disabled)');
if (data && structure) {
table_select.prop({checked: true, indeterminate: false});
} else if (data || structure) {
table_select.prop({checked: true, indeterminate: true});
} else {
table_select.prop({checked: false, indeterminate: false});
}
}
function toggle_table_select(row) {
var $row = $(row);
var table_selected = $row.find('input[name="table_select[]"]').is(':checked');
if (table_selected) {
$row.find('input[type="checkbox"]:not(:disabled)').prop('checked', true);
} else {
$row.find('input[type="checkbox"]:not(:disabled)').prop('checked', false);
}
}
AJAX.registerOnload('export.js', function () {
/**
* For SQL plugin, if "CREATE TABLE options" is checked/unchecked, check/uncheck each of its sub-options
*/
var $create = $("#checkbox_sql_create_table_statements");
var $create_options = $("#ul_create_table_statements input");
var $create_options = $("#ul_create_table_statements").find("input");
$create.change(function () {
$create_options.prop('checked', $(this).prop("checked"));
});
@ -191,7 +559,7 @@ AJAX.registerOnload('export.js', function () {
* Disables the view output as text option if the output must be saved as a file
*/
$("#plugins").change(function () {
var active_plugin = $("#plugins option:selected").val();
var active_plugin = $("#plugins").find("option:selected").val();
var force_file = $("#force_file_" + active_plugin).val();
if (force_file == "true") {
if ($("#radio_dump_asfile").prop('checked') !== true) {
@ -203,6 +571,78 @@ AJAX.registerOnload('export.js', function () {
$("#radio_view_as_text").prop('disabled', false).parent().fadeTo('fast', 1);
}
});
$("input[type='radio'][name$='_structure_or_data']").on('change', function () {
toggle_structure_data_opts();
});
$('input[name="table_select[]"]').on('change', function() {
toggle_table_select($(this).closest('tr'));
check_table_select_all();
});
$('input[name="table_structure[]"]').on('change', function() {
check_table_selected($(this).closest('tr'));
check_table_select_all();
});
$('input[name="table_data[]"]').on('change', function() {
check_table_selected($(this).closest('tr'));
check_table_select_all();
});
$('#table_structure_all').on('change', function() {
toggle_table_select_all_str();
check_selected_tables();
});
$('#table_data_all').on('change', function() {
toggle_table_select_all_data();
check_selected_tables();
});
if ($("input[name='export_type']").val() == 'database') {
// Hide structure or data radio buttons
$("input[type='radio'][name$='_structure_or_data']").each(function() {
var $this = $(this);
var name = $this.prop('name');
var val = $('input[name="' + name + '"]:checked').val();
var name_default = name + '_default';
if (!$('input[name="' + name_default + '"]').length) {
$this
.after(
$('<input type="hidden" name="' + name_default + '" value="' + val + '" disabled>')
)
.after(
$('<input type="hidden" name="' + name + '" value="structure_and_data">')
);
$this.parent().find('label').remove();
} else {
$this.parent().remove();
}
});
$("input[type='radio'][name$='_structure_or_data']").remove();
// Disable CREATE table checkbox for sql
var createTableCheckbox = $('#checkbox_sql_create_table');
createTableCheckbox.prop('checked', true);
var dummyCreateTable = $('#checkbox_sql_create_table')
.clone()
.removeAttr('id')
.attr('type', 'hidden');
createTableCheckbox
.prop('disabled', true)
.after(dummyCreateTable)
.parent()
.fadeTo('fast', 0.4);
setup_table_structure_or_data();
}
/**
* Handle force structure_or_data
*/
$("#plugins").change(setup_table_structure_or_data);
});
/**
@ -218,7 +658,7 @@ function toggle_quick_or_custom()
$("#output").show();
$("#format_specific_opts").show();
$("#output_quick_export").hide();
var selected_plugin_name = $("#plugins option:selected").val();
var selected_plugin_name = $("#plugins").find("option:selected").val();
$("#" + selected_plugin_name + "_options").show();
} else { // quick
$("#databases_and_tables").hide();
@ -320,7 +760,7 @@ function createAliasModal(event) {
});
$('#alias_modal').parent().appendTo($('form[name="dump"]'));
};
$('#alias_modal input[type="text"]').prop('disabled', false);
$('#alias_modal').find('input[type="text"]').prop('disabled', false);
$('#alias_modal').dialog({
width: Math.min($(window).width() - 100, 700),
maxHeight: $(window).height(),
@ -353,17 +793,17 @@ AJAX.registerOnload('export.js', function () {
$("input[type='radio'][name='quick_or_custom']").change(toggle_quick_or_custom);
$("#scroll_to_options_msg").hide();
$("#format_specific_opts div.format_specific_options")
.hide()
.css({
"border": 0,
"margin": 0,
"padding": 0
})
.find("h3")
.remove();
$("#format_specific_opts").find("div.format_specific_options")
.hide()
.css({
"border": 0,
"margin": 0,
"padding": 0
})
.find("h3")
.remove();
toggle_quick_or_custom();
toggle_structure_data_opts($("select#plugins").val());
toggle_structure_data_opts();
toggle_sql_include_comments();
/**

File diff suppressed because it is too large Load Diff

View File

@ -20,9 +20,11 @@ require_once './libraries/common.inc.php';
require_once './libraries/OutputBuffering.class.php';
$buffer = PMA_OutputBuffering::getInstance();
$buffer->start();
register_shutdown_function(function() {
echo PMA_OutputBuffering::getInstance()->getContents();
});
register_shutdown_function(
function () {
echo PMA_OutputBuffering::getInstance()->getContents();
}
);
// Get the data for the sprites, if it's available
if (is_readable($_SESSION['PMA_Theme']->getPath() . '/sprites.lib.php')) {
@ -136,7 +138,9 @@ function PMA_getImage(image, alternate, attributes) {
if (i == 'src') {
// do not allow to override the 'src' attribute
continue;
} else if (i == 'class') {
}
if (i == 'class') {
retval.attr(i, retval.attr('class') + ' ' + attributes[i]);
} else {
retval.attr(i, attributes[i]);

View File

@ -26,12 +26,14 @@ $_GET['scripts'] = json_encode($_GET['scripts']);
define('PMA_MINIMUM_COMMON', true);
require_once './libraries/common.inc.php';
include_once './libraries/OutputBuffering.class.php';
require_once './libraries/OutputBuffering.class.php';
$buffer = PMA_OutputBuffering::getInstance();
$buffer->start();
register_shutdown_function(function() {
echo PMA_OutputBuffering::getInstance()->getContents();
});
register_shutdown_function(
function () {
echo PMA_OutputBuffering::getInstance()->getContents();
}
);
$_GET['scripts'] = json_decode($_GET['scripts']);
if (! empty($_GET['scripts']) && is_array($_GET['scripts'])) {
@ -59,4 +61,3 @@ if (! empty($_GET['scripts']) && is_array($_GET['scripts'])) {
if (isset($_GET['call_done'])) {
echo "AJAX.scriptHandler.done();";
}
?>

View File

@ -19,11 +19,11 @@ function closeGISEditor() {
}
/**
* Prepares the HTML recieved via AJAX.
* Prepares the HTML received via AJAX.
*/
function prepareJSVersion() {
// Change the text on the submit button
$("#gis_editor input[name='gis_data[save]']")
$("#gis_editor").find("input[name='gis_data[save]']")
.val(PMA_messages.strCopy)
.insertAfter($('#gis_data_textarea'))
.before('<br/><br/>');
@ -37,7 +37,7 @@ function prepareJSVersion() {
$('div#gis_data_output p').remove();
// Remove 'add' buttons and add links
$('#gis_editor input.add').each(function (e) {
$('#gis_editor').find('input.add').each(function (e) {
var $button = $(this);
$button.addClass('addJs').removeClass('add');
var classes = $button.attr('class');

View File

@ -11,10 +11,10 @@
*/
function changePluginOpts()
{
$("#format_specific_opts div.format_specific_options").each(function () {
$("#format_specific_opts").find("div.format_specific_options").each(function () {
$(this).hide();
});
var selected_plugin_name = $("#plugins option:selected").val();
var selected_plugin_name = $("#plugins").find("option:selected").val();
$("#" + selected_plugin_name + "_options").fadeIn('slow');
if (selected_plugin_name == "csv") {
$("#import_notification").text(PMA_messages.strImportCSV);
@ -141,7 +141,7 @@ AJAX.registerOnload('import.js', function () {
* Javascript-disabled browsers
*/
$("#scroll_to_options_msg").hide();
$("#format_specific_opts div.format_specific_options")
$("#format_specific_opts").find("div.format_specific_options")
.css({
"border": 0,
"margin": 0,

View File

@ -17,27 +17,27 @@ function checkIndexType()
/**
* @var Object Dropdown to select the index choice.
*/
$select_index_choice = $('#select_index_choice');
var $select_index_choice = $('#select_index_choice');
/**
* @var Object Dropdown to select the index type.
*/
$select_index_type = $('#select_index_type');
var $select_index_type = $('#select_index_type');
/**
* @var Object Table header for the size column.
*/
$size_header = $('#index_columns thead tr th:nth-child(2)');
var $size_header = $('#index_columns').find('thead tr th:nth-child(2)');
/**
* @var Object Inputs to specify the columns for the index.
*/
$column_inputs = $('select[name="index[columns][names][]"]');
var $column_inputs = $('select[name="index[columns][names][]"]');
/**
* @var Object Inputs to specify sizes for columns of the index.
*/
$size_inputs = $('input[name="index[columns][sub_parts][]"]');
var $size_inputs = $('input[name="index[columns][sub_parts][]"]');
/**
* @var Object Footer containg the controllers to add more columns
*/
$add_more = $('#index_frm .add_more');
var $add_more = $('#index_frm').find('.add_more');
if ($select_index_choice.val() == 'SPATIAL') {
// Disable and hide the size column
@ -122,20 +122,8 @@ function PMA_removeColumnFromIndex(col_index)
.attr('data-index');
if (previous_index.length) {
previous_index = previous_index.split(',');
switch (previous_index[0].toLowerCase()) {
case 'primary':
source_array = primary_indexes;
break;
case 'unique':
source_array = unique_indexes;
break;
case 'index':
source_array = indexes;
break;
case 'fulltext':
source_array = fulltext_indexes;
break;
default:
var source_array = PMA_getIndexArray(previous_index[0]);
if (source_array == null) {
return;
}
@ -171,15 +159,17 @@ function PMA_removeColumnFromIndex(col_index)
*/
function PMA_addColumnToIndex(source_array, array_index, index_choice, col_index)
{
// Remove column from other indexes (if any).
PMA_removeColumnFromIndex(col_index);
if (col_index >= 0) {
// Remove column from other indexes (if any).
PMA_removeColumnFromIndex(col_index);
}
var index_name = $('input[name="index[Key_name]"]').val();
var index_comment = $('input[name="index[Index_comment]"]').val();
var key_block_size = $('input[name="index[Key_block_size]"]').val();
var parser = $('input[name="index[Parser]"]').val();
var index_type = $('select[name="index[Index_type]"]').val();
var columns = [];
$('#index_columns tbody').find('tr').each(function () {
$('#index_columns').find('tbody').find('tr').each(function () {
// Get columns in particular order.
var col_index = $(this).find('select[name="index[columns][names][]"]').val();
var size = $(this).find('input[name="index[columns][sub_parts][]"]').val();
@ -200,9 +190,31 @@ function PMA_addColumnToIndex(source_array, array_index, index_choice, col_index
'columns': columns
};
// Update index details on form.
$('select[name="field_key[' + col_index + ']"]')
.attr('data-index', index_choice + ',' + array_index);
// Display index name (or column list)
var displayName = index_name;
if (displayName == '') {
var columnNames = [];
$.each(columns, function () {
columnNames.push($('input[name="field_name[' + this.col_index + ']"]').val());
});
displayName = '[' + columnNames.join(', ') + ']';
}
$.each(columns, function () {
var id = 'index_name_' + this.col_index + '_8';
var $name = $('#' + id);
if ($name.length == 0) {
$name = $('<a id="' + id + '" href="#" class="ajax show_index_dialog"></a>');
$name.insertAfter($('select[name="field_key[' + this.col_index + ']"]'));
}
var $text = $('<small>').text(displayName);
$name.html($text);
});
if (col_index >= 0) {
// Update index details on form.
$('select[name="field_key[' + col_index + ']"]')
.attr('data-index', index_choice + ',' + array_index);
}
PMA_setIndexFormParameters(source_array, index_choice.toLowerCase());
}
@ -292,7 +304,7 @@ function PMA_showAddIndexDialog(source_array, array_index, target_columns, col_i
}
post_data.columns = JSON.stringify(columns);
button_options = {};
var button_options = {};
button_options[PMA_messages.strGo] = function () {
var is_missing_value = false;
$('select[name="index[columns][names][]"]').each(function () {
@ -321,14 +333,16 @@ function PMA_showAddIndexDialog(source_array, array_index, target_columns, col_i
$(this).dialog('close');
};
button_options[PMA_messages.strCancel] = function () {
// Handle state on 'Cancel'.
var $select_list = $('select[name="field_key[' + col_index + ']"]');
if (! $select_list.attr('data-index').length) {
$select_list.find('option[value*="none"]').attr('selected', 'selected');
} else {
var previous_index = $select_list.attr('data-index').split(',');
$select_list.find('option[value*="' + previous_index[0].toLowerCase() + '"]')
.attr('selected', 'selected');
if (col_index >= 0) {
// Handle state on 'Cancel'.
var $select_list = $('select[name="field_key[' + col_index + ']"]');
if (! $select_list.attr('data-index').length) {
$select_list.find('option[value*="none"]').attr('selected', 'selected');
} else {
var previous_index = $select_list.attr('data-index').split(',');
$select_list.find('option[value*="' + previous_index[0].toLowerCase() + '"]')
.attr('selected', 'selected');
}
}
$(this).dialog('close');
};
@ -340,7 +354,7 @@ function PMA_showAddIndexDialog(source_array, array_index, target_columns, col_i
} else {
PMA_ajaxRemoveMessage($msgbox);
// Show dialog if the request was successful
$div = $('<div/>');
var $div = $('<div/>');
$div
.append(data.message)
.dialog({
@ -351,12 +365,12 @@ function PMA_showAddIndexDialog(source_array, array_index, target_columns, col_i
checkIndexName("index_frm");
PMA_showHints($div);
PMA_init_slider();
$('#index_columns td').each(function () {
$('#index_columns').find('td').each(function () {
$(this).css("width", $(this).width() + 'px');
});
$('#index_columns tbody').sortable({
$('#index_columns').find('tbody').sortable({
axis: 'y',
containment: $("#index_columns tbody"),
containment: $("#index_columns").find("tbody"),
tolerance: 'pointer'
});
// We dont need the slider at this moment.
@ -476,6 +490,38 @@ function PMA_indexTypeSelectionDialog(source_array, index_choice, col_index)
});
}
/**
* Returns the array of indexes based on the index choice
*
* @param index_choice index choice
*/
function PMA_getIndexArray(index_choice)
{
var source_array = null;
switch (index_choice.toLowerCase()) {
case 'primary':
source_array = primary_indexes;
break;
case 'unique':
source_array = unique_indexes;
break;
case 'index':
source_array = indexes;
break;
case 'fulltext':
source_array = fulltext_indexes;
break;
case 'spatial':
source_array = spatial_indexes;
break;
default:
return null;
}
return source_array;
}
/**
* Unbind all event handlers before tearing down a page
*/
@ -487,6 +533,7 @@ AJAX.registerTeardown('indexes.js', function () {
$(document).off('click', "#table_index tbody tr td.edit_index.ajax, #indexes .add_index.ajax");
$(document).off('click', '#index_frm input[type=submit]');
$('body').off('change', 'select[name*="field_key"]');
$(document).off('click', '.show_index_dialog');
});
/**
@ -504,6 +551,7 @@ AJAX.registerOnload('indexes.js', function () {
unique_indexes = [];
indexes = [];
fulltext_indexes = [];
spatial_indexes = [];
// for table creation form
var $engine_selector = $('.create_table_form select[name=tbl_storage_engine]');
@ -655,19 +703,9 @@ AJAX.registerOnload('indexes.js', function () {
}
// Select a source array.
switch (index_choice) {
case 'primary':
source_array = primary_indexes;
break;
case 'unique':
source_array = unique_indexes;
break;
case 'index':
source_array = indexes;
break;
case 'fulltext':
source_array = fulltext_indexes;
break;
var source_array = PMA_getIndexArray(index_choice);
if (source_array == null) {
return;
}
if (source_array.length === 0) {
@ -694,4 +732,26 @@ AJAX.registerOnload('indexes.js', function () {
}
}
});
$(document).on('click', '.show_index_dialog', function (e) {
e.preventDefault();
// Get index details.
var previous_index = $(this).prev('select')
.attr('data-index')
.split(',');
var index_choice = previous_index[0];
var array_index = previous_index[1];
var source_array = PMA_getIndexArray(index_choice);
var source_length = source_array[array_index].columns.length;
var target_columns = [];
for (var i = 0; i < source_length; i++) {
target_columns.push(source_array[array_index].columns[i].col_index);
}
PMA_showAddIndexDialog(source_array, array_index, target_columns, -1, source_array[array_index]);
})
});

940
js/jquery/additional-methods.js vendored Normal file
View File

@ -0,0 +1,940 @@
/*!
* jQuery Validation Plugin v1.13.1
*
* http://jqueryvalidation.org/
*
* Copyright (c) 2014 Jörn Zaefferer
* Released under the MIT license
*/
(function( factory ) {
if ( typeof define === "function" && define.amd ) {
define( ["jquery", "./jquery.validate"], factory );
} else {
factory( jQuery );
}
}(function( $ ) {
(function() {
function stripHtml(value) {
// remove html tags and space chars
return value.replace(/<.[^<>]*?>/g, " ").replace(/&nbsp;|&#160;/gi, " ")
// remove punctuation
.replace(/[.(),;:!?%#$'\"_+=\/\-“”’]*/g, "");
}
$.validator.addMethod("maxWords", function(value, element, params) {
return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length <= params;
}, $.validator.format("Please enter {0} words or less."));
$.validator.addMethod("minWords", function(value, element, params) {
return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length >= params;
}, $.validator.format("Please enter at least {0} words."));
$.validator.addMethod("rangeWords", function(value, element, params) {
var valueStripped = stripHtml(value),
regex = /\b\w+\b/g;
return this.optional(element) || valueStripped.match(regex).length >= params[0] && valueStripped.match(regex).length <= params[1];
}, $.validator.format("Please enter between {0} and {1} words."));
}());
// Accept a value from a file input based on a required mimetype
$.validator.addMethod("accept", function(value, element, param) {
// Split mime on commas in case we have multiple types we can accept
var typeParam = typeof param === "string" ? param.replace(/\s/g, "").replace(/,/g, "|") : "image/*",
optionalValue = this.optional(element),
i, file;
// Element is optional
if (optionalValue) {
return optionalValue;
}
if ($(element).attr("type") === "file") {
// If we are using a wildcard, make it regex friendly
typeParam = typeParam.replace(/\*/g, ".*");
// Check if the element has a FileList before checking each file
if (element.files && element.files.length) {
for (i = 0; i < element.files.length; i++) {
file = element.files[i];
// Grab the mimetype from the loaded file, verify it matches
if (!file.type.match(new RegExp( ".?(" + typeParam + ")$", "i"))) {
return false;
}
}
}
}
// Either return true because we've validated each file, or because the
// browser does not support element.files and the FileList feature
return true;
}, $.validator.format("Please enter a value with a valid mimetype."));
$.validator.addMethod("alphanumeric", function(value, element) {
return this.optional(element) || /^\w+$/i.test(value);
}, "Letters, numbers, and underscores only please");
/*
* Dutch bank account numbers (not 'giro' numbers) have 9 digits
* and pass the '11 check'.
* We accept the notation with spaces, as that is common.
* acceptable: 123456789 or 12 34 56 789
*/
$.validator.addMethod("bankaccountNL", function(value, element) {
if (this.optional(element)) {
return true;
}
if (!(/^[0-9]{9}|([0-9]{2} ){3}[0-9]{3}$/.test(value))) {
return false;
}
// now '11 check'
var account = value.replace(/ /g, ""), // remove spaces
sum = 0,
len = account.length,
pos, factor, digit;
for ( pos = 0; pos < len; pos++ ) {
factor = len - pos;
digit = account.substring(pos, pos + 1);
sum = sum + factor * digit;
}
return sum % 11 === 0;
}, "Please specify a valid bank account number");
$.validator.addMethod("bankorgiroaccountNL", function(value, element) {
return this.optional(element) ||
($.validator.methods.bankaccountNL.call(this, value, element)) ||
($.validator.methods.giroaccountNL.call(this, value, element));
}, "Please specify a valid bank or giro account number");
/**
* BIC is the business identifier code (ISO 9362). This BIC check is not a guarantee for authenticity.
*
* BIC pattern: BBBBCCLLbbb (8 or 11 characters long; bbb is optional)
*
* BIC definition in detail:
* - First 4 characters - bank code (only letters)
* - Next 2 characters - ISO 3166-1 alpha-2 country code (only letters)
* - Next 2 characters - location code (letters and digits)
* a. shall not start with '0' or '1'
* b. second character must be a letter ('O' is not allowed) or one of the following digits ('0' for test (therefore not allowed), '1' for passive participant and '2' for active participant)
* - Last 3 characters - branch code, optional (shall not start with 'X' except in case of 'XXX' for primary office) (letters and digits)
*/
$.validator.addMethod("bic", function(value, element) {
return this.optional( element ) || /^([A-Z]{6}[A-Z2-9][A-NP-Z1-2])(X{3}|[A-WY-Z0-9][A-Z0-9]{2})?$/.test( value );
}, "Please specify a valid BIC code");
/*
* Código de identificación fiscal ( CIF ) is the tax identification code for Spanish legal entities
* Further rules can be found in Spanish on http://es.wikipedia.org/wiki/C%C3%B3digo_de_identificaci%C3%B3n_fiscal
*/
$.validator.addMethod( "cifES", function( value ) {
"use strict";
var num = [],
controlDigit, sum, i, count, tmp, secondDigit;
value = value.toUpperCase();
// Quick format test
if ( !value.match( "((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)" ) ) {
return false;
}
for ( i = 0; i < 9; i++ ) {
num[ i ] = parseInt( value.charAt( i ), 10 );
}
// Algorithm for checking CIF codes
sum = num[ 2 ] + num[ 4 ] + num[ 6 ];
for ( count = 1; count < 8; count += 2 ) {
tmp = ( 2 * num[ count ] ).toString();
secondDigit = tmp.charAt( 1 );
sum += parseInt( tmp.charAt( 0 ), 10 ) + ( secondDigit === "" ? 0 : parseInt( secondDigit, 10 ) );
}
/* The first (position 1) is a letter following the following criteria:
* A. Corporations
* B. LLCs
* C. General partnerships
* D. Companies limited partnerships
* E. Communities of goods
* F. Cooperative Societies
* G. Associations
* H. Communities of homeowners in horizontal property regime
* J. Civil Societies
* K. Old format
* L. Old format
* M. Old format
* N. Nonresident entities
* P. Local authorities
* Q. Autonomous bodies, state or not, and the like, and congregations and religious institutions
* R. Congregations and religious institutions (since 2008 ORDER EHA/451/2008)
* S. Organs of State Administration and regions
* V. Agrarian Transformation
* W. Permanent establishments of non-resident in Spain
*/
if ( /^[ABCDEFGHJNPQRSUVW]{1}/.test( value ) ) {
sum += "";
controlDigit = 10 - parseInt( sum.charAt( sum.length - 1 ), 10 );
value += controlDigit;
return ( num[ 8 ].toString() === String.fromCharCode( 64 + controlDigit ) || num[ 8 ].toString() === value.charAt( value.length - 1 ) );
}
return false;
}, "Please specify a valid CIF number." );
/* NOTICE: Modified version of Castle.Components.Validator.CreditCardValidator
* Redistributed under the the Apache License 2.0 at http://www.apache.org/licenses/LICENSE-2.0
* Valid Types: mastercard, visa, amex, dinersclub, enroute, discover, jcb, unknown, all (overrides all other settings)
*/
$.validator.addMethod("creditcardtypes", function(value, element, param) {
if (/[^0-9\-]+/.test(value)) {
return false;
}
value = value.replace(/\D/g, "");
var validTypes = 0x0000;
if (param.mastercard) {
validTypes |= 0x0001;
}
if (param.visa) {
validTypes |= 0x0002;
}
if (param.amex) {
validTypes |= 0x0004;
}
if (param.dinersclub) {
validTypes |= 0x0008;
}
if (param.enroute) {
validTypes |= 0x0010;
}
if (param.discover) {
validTypes |= 0x0020;
}
if (param.jcb) {
validTypes |= 0x0040;
}
if (param.unknown) {
validTypes |= 0x0080;
}
if (param.all) {
validTypes = 0x0001 | 0x0002 | 0x0004 | 0x0008 | 0x0010 | 0x0020 | 0x0040 | 0x0080;
}
if (validTypes & 0x0001 && /^(5[12345])/.test(value)) { //mastercard
return value.length === 16;
}
if (validTypes & 0x0002 && /^(4)/.test(value)) { //visa
return value.length === 16;
}
if (validTypes & 0x0004 && /^(3[47])/.test(value)) { //amex
return value.length === 15;
}
if (validTypes & 0x0008 && /^(3(0[012345]|[68]))/.test(value)) { //dinersclub
return value.length === 14;
}
if (validTypes & 0x0010 && /^(2(014|149))/.test(value)) { //enroute
return value.length === 15;
}
if (validTypes & 0x0020 && /^(6011)/.test(value)) { //discover
return value.length === 16;
}
if (validTypes & 0x0040 && /^(3)/.test(value)) { //jcb
return value.length === 16;
}
if (validTypes & 0x0040 && /^(2131|1800)/.test(value)) { //jcb
return value.length === 15;
}
if (validTypes & 0x0080) { //unknown
return true;
}
return false;
}, "Please enter a valid credit card number.");
/**
* Validates currencies with any given symbols by @jameslouiz
* Symbols can be optional or required. Symbols required by default
*
* Usage examples:
* currency: ["£", false] - Use false for soft currency validation
* currency: ["$", false]
* currency: ["RM", false] - also works with text based symbols such as "RM" - Malaysia Ringgit etc
*
* <input class="currencyInput" name="currencyInput">
*
* Soft symbol checking
* currencyInput: {
* currency: ["$", false]
* }
*
* Strict symbol checking (default)
* currencyInput: {
* currency: "$"
* //OR
* currency: ["$", true]
* }
*
* Multiple Symbols
* currencyInput: {
* currency: "$,£,¢"
* }
*/
$.validator.addMethod("currency", function(value, element, param) {
var isParamString = typeof param === "string",
symbol = isParamString ? param : param[0],
soft = isParamString ? true : param[1],
regex;
symbol = symbol.replace(/,/g, "");
symbol = soft ? symbol + "]" : symbol + "]?";
regex = "^[" + symbol + "([1-9]{1}[0-9]{0,2}(\\,[0-9]{3})*(\\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\\.[0-9]{0,2})?|0(\\.[0-9]{0,2})?|(\\.[0-9]{1,2})?)$";
regex = new RegExp(regex);
return this.optional(element) || regex.test(value);
}, "Please specify a valid currency");
$.validator.addMethod("dateFA", function(value, element) {
return this.optional(element) || /^[1-4]\d{3}\/((0?[1-6]\/((3[0-1])|([1-2][0-9])|(0?[1-9])))|((1[0-2]|(0?[7-9]))\/(30|([1-2][0-9])|(0?[1-9]))))$/.test(value);
}, "Please enter a correct date");
/**
* Return true, if the value is a valid date, also making this formal check dd/mm/yyyy.
*
* @example $.validator.methods.date("01/01/1900")
* @result true
*
* @example $.validator.methods.date("01/13/1990")
* @result false
*
* @example $.validator.methods.date("01.01.1900")
* @result false
*
* @example <input name="pippo" class="{dateITA:true}" />
* @desc Declares an optional input element whose value must be a valid date.
*
* @name $.validator.methods.dateITA
* @type Boolean
* @cat Plugins/Validate/Methods
*/
$.validator.addMethod("dateITA", function(value, element) {
var check = false,
re = /^\d{1,2}\/\d{1,2}\/\d{4}$/,
adata, gg, mm, aaaa, xdata;
if ( re.test(value)) {
adata = value.split("/");
gg = parseInt(adata[0], 10);
mm = parseInt(adata[1], 10);
aaaa = parseInt(adata[2], 10);
xdata = new Date(aaaa, mm - 1, gg, 12, 0, 0, 0);
if ( ( xdata.getUTCFullYear() === aaaa ) && ( xdata.getUTCMonth () === mm - 1 ) && ( xdata.getUTCDate() === gg ) ) {
check = true;
} else {
check = false;
}
} else {
check = false;
}
return this.optional(element) || check;
}, "Please enter a correct date");
$.validator.addMethod("dateNL", function(value, element) {
return this.optional(element) || /^(0?[1-9]|[12]\d|3[01])[\.\/\-](0?[1-9]|1[012])[\.\/\-]([12]\d)?(\d\d)$/.test(value);
}, "Please enter a correct date");
// Older "accept" file extension method. Old docs: http://docs.jquery.com/Plugins/Validation/Methods/accept
$.validator.addMethod("extension", function(value, element, param) {
param = typeof param === "string" ? param.replace(/,/g, "|") : "png|jpe?g|gif";
return this.optional(element) || value.match(new RegExp(".(" + param + ")$", "i"));
}, $.validator.format("Please enter a value with a valid extension."));
/**
* Dutch giro account numbers (not bank numbers) have max 7 digits
*/
$.validator.addMethod("giroaccountNL", function(value, element) {
return this.optional(element) || /^[0-9]{1,7}$/.test(value);
}, "Please specify a valid giro account number");
/**
* IBAN is the international bank account number.
* It has a country - specific format, that is checked here too
*/
$.validator.addMethod("iban", function(value, element) {
// some quick simple tests to prevent needless work
if (this.optional(element)) {
return true;
}
// remove spaces and to upper case
var iban = value.replace(/ /g, "").toUpperCase(),
ibancheckdigits = "",
leadingZeroes = true,
cRest = "",
cOperator = "",
countrycode, ibancheck, charAt, cChar, bbanpattern, bbancountrypatterns, ibanregexp, i, p;
if (!(/^([a-zA-Z0-9]{4} ){2,8}[a-zA-Z0-9]{1,4}|[a-zA-Z0-9]{12,34}$/.test(iban))) {
return false;
}
// check the country code and find the country specific format
countrycode = iban.substring(0, 2);
bbancountrypatterns = {
"AL": "\\d{8}[\\dA-Z]{16}",
"AD": "\\d{8}[\\dA-Z]{12}",
"AT": "\\d{16}",
"AZ": "[\\dA-Z]{4}\\d{20}",
"BE": "\\d{12}",
"BH": "[A-Z]{4}[\\dA-Z]{14}",
"BA": "\\d{16}",
"BR": "\\d{23}[A-Z][\\dA-Z]",
"BG": "[A-Z]{4}\\d{6}[\\dA-Z]{8}",
"CR": "\\d{17}",
"HR": "\\d{17}",
"CY": "\\d{8}[\\dA-Z]{16}",
"CZ": "\\d{20}",
"DK": "\\d{14}",
"DO": "[A-Z]{4}\\d{20}",
"EE": "\\d{16}",
"FO": "\\d{14}",
"FI": "\\d{14}",
"FR": "\\d{10}[\\dA-Z]{11}\\d{2}",
"GE": "[\\dA-Z]{2}\\d{16}",
"DE": "\\d{18}",
"GI": "[A-Z]{4}[\\dA-Z]{15}",
"GR": "\\d{7}[\\dA-Z]{16}",
"GL": "\\d{14}",
"GT": "[\\dA-Z]{4}[\\dA-Z]{20}",
"HU": "\\d{24}",
"IS": "\\d{22}",
"IE": "[\\dA-Z]{4}\\d{14}",
"IL": "\\d{19}",
"IT": "[A-Z]\\d{10}[\\dA-Z]{12}",
"KZ": "\\d{3}[\\dA-Z]{13}",
"KW": "[A-Z]{4}[\\dA-Z]{22}",
"LV": "[A-Z]{4}[\\dA-Z]{13}",
"LB": "\\d{4}[\\dA-Z]{20}",
"LI": "\\d{5}[\\dA-Z]{12}",
"LT": "\\d{16}",
"LU": "\\d{3}[\\dA-Z]{13}",
"MK": "\\d{3}[\\dA-Z]{10}\\d{2}",
"MT": "[A-Z]{4}\\d{5}[\\dA-Z]{18}",
"MR": "\\d{23}",
"MU": "[A-Z]{4}\\d{19}[A-Z]{3}",
"MC": "\\d{10}[\\dA-Z]{11}\\d{2}",
"MD": "[\\dA-Z]{2}\\d{18}",
"ME": "\\d{18}",
"NL": "[A-Z]{4}\\d{10}",
"NO": "\\d{11}",
"PK": "[\\dA-Z]{4}\\d{16}",
"PS": "[\\dA-Z]{4}\\d{21}",
"PL": "\\d{24}",
"PT": "\\d{21}",
"RO": "[A-Z]{4}[\\dA-Z]{16}",
"SM": "[A-Z]\\d{10}[\\dA-Z]{12}",
"SA": "\\d{2}[\\dA-Z]{18}",
"RS": "\\d{18}",
"SK": "\\d{20}",
"SI": "\\d{15}",
"ES": "\\d{20}",
"SE": "\\d{20}",
"CH": "\\d{5}[\\dA-Z]{12}",
"TN": "\\d{20}",
"TR": "\\d{5}[\\dA-Z]{17}",
"AE": "\\d{3}\\d{16}",
"GB": "[A-Z]{4}\\d{14}",
"VG": "[\\dA-Z]{4}\\d{16}"
};
bbanpattern = bbancountrypatterns[countrycode];
// As new countries will start using IBAN in the
// future, we only check if the countrycode is known.
// This prevents false negatives, while almost all
// false positives introduced by this, will be caught
// by the checksum validation below anyway.
// Strict checking should return FALSE for unknown
// countries.
if (typeof bbanpattern !== "undefined") {
ibanregexp = new RegExp("^[A-Z]{2}\\d{2}" + bbanpattern + "$", "");
if (!(ibanregexp.test(iban))) {
return false; // invalid country specific format
}
}
// now check the checksum, first convert to digits
ibancheck = iban.substring(4, iban.length) + iban.substring(0, 4);
for (i = 0; i < ibancheck.length; i++) {
charAt = ibancheck.charAt(i);
if (charAt !== "0") {
leadingZeroes = false;
}
if (!leadingZeroes) {
ibancheckdigits += "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf(charAt);
}
}
// calculate the result of: ibancheckdigits % 97
for (p = 0; p < ibancheckdigits.length; p++) {
cChar = ibancheckdigits.charAt(p);
cOperator = "" + cRest + "" + cChar;
cRest = cOperator % 97;
}
return cRest === 1;
}, "Please specify a valid IBAN");
$.validator.addMethod("integer", function(value, element) {
return this.optional(element) || /^-?\d+$/.test(value);
}, "A positive or negative non-decimal number please");
$.validator.addMethod("ipv4", function(value, element) {
return this.optional(element) || /^(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)\.(25[0-5]|2[0-4]\d|[01]?\d\d?)$/i.test(value);
}, "Please enter a valid IP v4 address.");
$.validator.addMethod("ipv6", function(value, element) {
return this.optional(element) || /^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}:([0-9A-Fa-f]{1,4}:)?[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){4}:([0-9A-Fa-f]{1,4}:){0,2}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){3}:([0-9A-Fa-f]{1,4}:){0,3}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){2}:([0-9A-Fa-f]{1,4}:){0,4}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){6}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(([0-9A-Fa-f]{1,4}:){0,5}:((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|(::([0-9A-Fa-f]{1,4}:){0,5}((\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b)\.){3}(\b((25[0-5])|(1\d{2})|(2[0-4]\d)|(\d{1,2}))\b))|([0-9A-Fa-f]{1,4}::([0-9A-Fa-f]{1,4}:){0,5}[0-9A-Fa-f]{1,4})|(::([0-9A-Fa-f]{1,4}:){0,6}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:))$/i.test(value);
}, "Please enter a valid IP v6 address.");
$.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
$.validator.addMethod("letterswithbasicpunc", function(value, element) {
return this.optional(element) || /^[a-z\-.,()'"\s]+$/i.test(value);
}, "Letters or punctuation only please");
$.validator.addMethod("mobileNL", function(value, element) {
return this.optional(element) || /^((\+|00(\s|\s?\-\s?)?)31(\s|\s?\-\s?)?(\(0\)[\-\s]?)?|0)6((\s|\s?\-\s?)?[0-9]){8}$/.test(value);
}, "Please specify a valid mobile number");
/* For UK phone functions, do the following server side processing:
* Compare original input with this RegEx pattern:
* ^\(?(?:(?:00\)?[\s\-]?\(?|\+)(44)\)?[\s\-]?\(?(?:0\)?[\s\-]?\(?)?|0)([1-9]\d{1,4}\)?[\s\d\-]+)$
* Extract $1 and set $prefix to '+44<space>' if $1 is '44', otherwise set $prefix to '0'
* Extract $2 and remove hyphens, spaces and parentheses. Phone number is combined $prefix and $2.
* A number of very detailed GB telephone number RegEx patterns can also be found at:
* http://www.aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validating_and_Formatting_GB_Telephone_Numbers
*/
$.validator.addMethod("mobileUK", function(phone_number, element) {
phone_number = phone_number.replace(/\(|\)|\s+|-/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(?:(?:(?:00\s?|\+)44\s?|0)7(?:[1345789]\d{2}|624)\s?\d{3}\s?\d{3})$/);
}, "Please specify a valid mobile number");
/*
* The número de identidad de extranjero ( NIE )is a code used to identify the non-nationals in Spain
*/
$.validator.addMethod( "nieES", function( value ) {
"use strict";
value = value.toUpperCase();
// Basic format test
if ( !value.match( "((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)" ) ) {
return false;
}
// Test NIE
//T
if ( /^[T]{1}/.test( value ) ) {
return ( value[ 8 ] === /^[T]{1}[A-Z0-9]{8}$/.test( value ) );
}
//XYZ
if ( /^[XYZ]{1}/.test( value ) ) {
return (
value[ 8 ] === "TRWAGMYFPDXBNJZSQVHLCKE".charAt(
value.replace( "X", "0" )
.replace( "Y", "1" )
.replace( "Z", "2" )
.substring( 0, 8 ) % 23
)
);
}
return false;
}, "Please specify a valid NIE number." );
/*
* The Número de Identificación Fiscal ( NIF ) is the way tax identification used in Spain for individuals
*/
$.validator.addMethod( "nifES", function( value ) {
"use strict";
value = value.toUpperCase();
// Basic format test
if ( !value.match("((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)") ) {
return false;
}
// Test NIF
if ( /^[0-9]{8}[A-Z]{1}$/.test( value ) ) {
return ( "TRWAGMYFPDXBNJZSQVHLCKE".charAt( value.substring( 8, 0 ) % 23 ) === value.charAt( 8 ) );
}
// Test specials NIF (starts with K, L or M)
if ( /^[KLM]{1}/.test( value ) ) {
return ( value[ 8 ] === String.fromCharCode( 64 ) );
}
return false;
}, "Please specify a valid NIF number." );
$.validator.addMethod("nowhitespace", function(value, element) {
return this.optional(element) || /^\S+$/i.test(value);
}, "No white space please");
/**
* Return true if the field value matches the given format RegExp
*
* @example $.validator.methods.pattern("AR1004",element,/^AR\d{4}$/)
* @result true
*
* @example $.validator.methods.pattern("BR1004",element,/^AR\d{4}$/)
* @result false
*
* @name $.validator.methods.pattern
* @type Boolean
* @cat Plugins/Validate/Methods
*/
$.validator.addMethod("pattern", function(value, element, param) {
if (this.optional(element)) {
return true;
}
if (typeof param === "string") {
param = new RegExp("^(?:" + param + ")$");
}
return param.test(value);
}, "Invalid format.");
/**
* Dutch phone numbers have 10 digits (or 11 and start with +31).
*/
$.validator.addMethod("phoneNL", function(value, element) {
return this.optional(element) || /^((\+|00(\s|\s?\-\s?)?)31(\s|\s?\-\s?)?(\(0\)[\-\s]?)?|0)[1-9]((\s|\s?\-\s?)?[0-9]){8}$/.test(value);
}, "Please specify a valid phone number.");
/* For UK phone functions, do the following server side processing:
* Compare original input with this RegEx pattern:
* ^\(?(?:(?:00\)?[\s\-]?\(?|\+)(44)\)?[\s\-]?\(?(?:0\)?[\s\-]?\(?)?|0)([1-9]\d{1,4}\)?[\s\d\-]+)$
* Extract $1 and set $prefix to '+44<space>' if $1 is '44', otherwise set $prefix to '0'
* Extract $2 and remove hyphens, spaces and parentheses. Phone number is combined $prefix and $2.
* A number of very detailed GB telephone number RegEx patterns can also be found at:
* http://www.aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validating_and_Formatting_GB_Telephone_Numbers
*/
$.validator.addMethod("phoneUK", function(phone_number, element) {
phone_number = phone_number.replace(/\(|\)|\s+|-/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(?:(?:(?:00\s?|\+)44\s?)|(?:\(?0))(?:\d{2}\)?\s?\d{4}\s?\d{4}|\d{3}\)?\s?\d{3}\s?\d{3,4}|\d{4}\)?\s?(?:\d{5}|\d{3}\s?\d{3})|\d{5}\)?\s?\d{4,5})$/);
}, "Please specify a valid phone number");
/**
* matches US phone number format
*
* where the area code may not start with 1 and the prefix may not start with 1
* allows '-' or ' ' as a separator and allows parens around area code
* some people may want to put a '1' in front of their number
*
* 1(212)-999-2345 or
* 212 999 2344 or
* 212-999-0983
*
* but not
* 111-123-5434
* and not
* 212 123 4567
*/
$.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(\+?1-?)?(\([2-9]([02-9]\d|1[02-9])\)|[2-9]([02-9]\d|1[02-9]))-?[2-9]([02-9]\d|1[02-9])-?\d{4}$/);
}, "Please specify a valid phone number");
/* For UK phone functions, do the following server side processing:
* Compare original input with this RegEx pattern:
* ^\(?(?:(?:00\)?[\s\-]?\(?|\+)(44)\)?[\s\-]?\(?(?:0\)?[\s\-]?\(?)?|0)([1-9]\d{1,4}\)?[\s\d\-]+)$
* Extract $1 and set $prefix to '+44<space>' if $1 is '44', otherwise set $prefix to '0'
* Extract $2 and remove hyphens, spaces and parentheses. Phone number is combined $prefix and $2.
* A number of very detailed GB telephone number RegEx patterns can also be found at:
* http://www.aa-asterisk.org.uk/index.php/Regular_Expressions_for_Validating_and_Formatting_GB_Telephone_Numbers
*/
//Matches UK landline + mobile, accepting only 01-3 for landline or 07 for mobile to exclude many premium numbers
$.validator.addMethod("phonesUK", function(phone_number, element) {
phone_number = phone_number.replace(/\(|\)|\s+|-/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(?:(?:(?:00\s?|\+)44\s?|0)(?:1\d{8,9}|[23]\d{9}|7(?:[1345789]\d{8}|624\d{6})))$/);
}, "Please specify a valid uk phone number");
/**
* Matches a valid Canadian Postal Code
*
* @example jQuery.validator.methods.postalCodeCA( "H0H 0H0", element )
* @result true
*
* @example jQuery.validator.methods.postalCodeCA( "H0H0H0", element )
* @result false
*
* @name jQuery.validator.methods.postalCodeCA
* @type Boolean
* @cat Plugins/Validate/Methods
*/
$.validator.addMethod( "postalCodeCA", function( value, element ) {
return this.optional( element ) || /^[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d$/.test( value );
}, "Please specify a valid postal code" );
/*
* Valida CEPs do brasileiros:
*
* Formatos aceitos:
* 99999-999
* 99.999-999
* 99999999
*/
$.validator.addMethod("postalcodeBR", function(cep_value, element) {
return this.optional(element) || /^\d{2}.\d{3}-\d{3}?$|^\d{5}-?\d{3}?$/.test( cep_value );
}, "Informe um CEP válido.");
/* Matches Italian postcode (CAP) */
$.validator.addMethod("postalcodeIT", function(value, element) {
return this.optional(element) || /^\d{5}$/.test(value);
}, "Please specify a valid postal code");
$.validator.addMethod("postalcodeNL", function(value, element) {
return this.optional(element) || /^[1-9][0-9]{3}\s?[a-zA-Z]{2}$/.test(value);
}, "Please specify a valid postal code");
// Matches UK postcode. Does not match to UK Channel Islands that have their own postcodes (non standard UK)
$.validator.addMethod("postcodeUK", function(value, element) {
return this.optional(element) || /^((([A-PR-UWYZ][0-9])|([A-PR-UWYZ][0-9][0-9])|([A-PR-UWYZ][A-HK-Y][0-9])|([A-PR-UWYZ][A-HK-Y][0-9][0-9])|([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRVWXY]))\s?([0-9][ABD-HJLNP-UW-Z]{2})|(GIR)\s?(0AA))$/i.test(value);
}, "Please specify a valid UK postcode");
/*
* Lets you say "at least X inputs that match selector Y must be filled."
*
* The end result is that neither of these inputs:
*
* <input class="productinfo" name="partnumber">
* <input class="productinfo" name="description">
*
* ...will validate unless at least one of them is filled.
*
* partnumber: {require_from_group: [1,".productinfo"]},
* description: {require_from_group: [1,".productinfo"]}
*
* options[0]: number of fields that must be filled in the group
* options[1]: CSS selector that defines the group of conditionally required fields
*/
$.validator.addMethod("require_from_group", function(value, element, options) {
var $fields = $(options[1], element.form),
$fieldsFirst = $fields.eq(0),
validator = $fieldsFirst.data("valid_req_grp") ? $fieldsFirst.data("valid_req_grp") : $.extend({}, this),
isValid = $fields.filter(function() {
return validator.elementValue(this);
}).length >= options[0];
// Store the cloned validator for future validation
$fieldsFirst.data("valid_req_grp", validator);
// If element isn't being validated, run each require_from_group field's validation rules
if (!$(element).data("being_validated")) {
$fields.data("being_validated", true);
$fields.each(function() {
validator.element(this);
});
$fields.data("being_validated", false);
}
return isValid;
}, $.validator.format("Please fill at least {0} of these fields."));
/*
* Lets you say "either at least X inputs that match selector Y must be filled,
* OR they must all be skipped (left blank)."
*
* The end result, is that none of these inputs:
*
* <input class="productinfo" name="partnumber">
* <input class="productinfo" name="description">
* <input class="productinfo" name="color">
*
* ...will validate unless either at least two of them are filled,
* OR none of them are.
*
* partnumber: {skip_or_fill_minimum: [2,".productinfo"]},
* description: {skip_or_fill_minimum: [2,".productinfo"]},
* color: {skip_or_fill_minimum: [2,".productinfo"]}
*
* options[0]: number of fields that must be filled in the group
* options[1]: CSS selector that defines the group of conditionally required fields
*
*/
$.validator.addMethod("skip_or_fill_minimum", function(value, element, options) {
var $fields = $(options[1], element.form),
$fieldsFirst = $fields.eq(0),
validator = $fieldsFirst.data("valid_skip") ? $fieldsFirst.data("valid_skip") : $.extend({}, this),
numberFilled = $fields.filter(function() {
return validator.elementValue(this);
}).length,
isValid = numberFilled === 0 || numberFilled >= options[0];
// Store the cloned validator for future validation
$fieldsFirst.data("valid_skip", validator);
// If element isn't being validated, run each skip_or_fill_minimum field's validation rules
if (!$(element).data("being_validated")) {
$fields.data("being_validated", true);
$fields.each(function() {
validator.element(this);
});
$fields.data("being_validated", false);
}
return isValid;
}, $.validator.format("Please either skip these fields or fill at least {0} of them."));
/* Validates US States and/or Territories by @jdforsythe
* Can be case insensitive or require capitalization - default is case insensitive
* Can include US Territories or not - default does not
* Can include US Military postal abbreviations (AA, AE, AP) - default does not
*
* Note: "States" always includes DC (District of Colombia)
*
* Usage examples:
*
* This is the default - case insensitive, no territories, no military zones
* stateInput: {
* caseSensitive: false,
* includeTerritories: false,
* includeMilitary: false
* }
*
* Only allow capital letters, no territories, no military zones
* stateInput: {
* caseSensitive: false
* }
*
* Case insensitive, include territories but not military zones
* stateInput: {
* includeTerritories: true
* }
*
* Only allow capital letters, include territories and military zones
* stateInput: {
* caseSensitive: true,
* includeTerritories: true,
* includeMilitary: true
* }
*
*
*
*/
jQuery.validator.addMethod("stateUS", function(value, element, options) {
var isDefault = typeof options === "undefined",
caseSensitive = ( isDefault || typeof options.caseSensitive === "undefined" ) ? false : options.caseSensitive,
includeTerritories = ( isDefault || typeof options.includeTerritories === "undefined" ) ? false : options.includeTerritories,
includeMilitary = ( isDefault || typeof options.includeMilitary === "undefined" ) ? false : options.includeMilitary,
regex;
if (!includeTerritories && !includeMilitary) {
regex = "^(A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])$";
} else if (includeTerritories && includeMilitary) {
regex = "^(A[AEKLPRSZ]|C[AOT]|D[CE]|FL|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEINOPST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$";
} else if (includeTerritories) {
regex = "^(A[KLRSZ]|C[AOT]|D[CE]|FL|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEINOPST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$";
} else {
regex = "^(A[AEKLPRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|PA|RI|S[CD]|T[NX]|UT|V[AT]|W[AIVY])$";
}
regex = caseSensitive ? new RegExp(regex) : new RegExp(regex, "i");
return this.optional(element) || regex.test(value);
},
"Please specify a valid state");
// TODO check if value starts with <, otherwise don't try stripping anything
$.validator.addMethod("strippedminlength", function(value, element, param) {
return $(value).text().length >= param;
}, $.validator.format("Please enter at least {0} characters"));
$.validator.addMethod("time", function(value, element) {
return this.optional(element) || /^([01]\d|2[0-3])(:[0-5]\d){1,2}$/.test(value);
}, "Please enter a valid time, between 00:00 and 23:59");
$.validator.addMethod("time12h", function(value, element) {
return this.optional(element) || /^((0?[1-9]|1[012])(:[0-5]\d){1,2}(\ ?[AP]M))$/i.test(value);
}, "Please enter a valid time in 12-hour am/pm format");
// same as url, but TLD is optional
$.validator.addMethod("url2", function(value, element) {
return this.optional(element) || /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)*(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
}, $.validator.messages.url);
/**
* Return true, if the value is a valid vehicle identification number (VIN).
*
* Works with all kind of text inputs.
*
* @example <input type="text" size="20" name="VehicleID" class="{required:true,vinUS:true}" />
* @desc Declares a required input element whose value must be a valid vehicle identification number.
*
* @name $.validator.methods.vinUS
* @type Boolean
* @cat Plugins/Validate/Methods
*/
$.validator.addMethod("vinUS", function(v) {
if (v.length !== 17) {
return false;
}
var LL = [ "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" ],
VL = [ 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 7, 9, 2, 3, 4, 5, 6, 7, 8, 9 ],
FL = [ 8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2 ],
rs = 0,
i, n, d, f, cd, cdv;
for (i = 0; i < 17; i++) {
f = FL[i];
d = v.slice(i, i + 1);
if (i === 8) {
cdv = d;
}
if (!isNaN(d)) {
d *= f;
} else {
for (n = 0; n < LL.length; n++) {
if (d.toUpperCase() === LL[n]) {
d = VL[n];
d *= f;
if (isNaN(cdv) && n === 8) {
cdv = LL[n];
}
break;
}
}
}
rs += d;
}
cd = rs % 11;
if (cd === 10) {
cd = "X";
}
if (cd === cdv) {
return true;
}
return false;
}, "The specified vehicle identification number (VIN) is invalid.");
$.validator.addMethod("zipcodeUS", function(value, element) {
return this.optional(element) || /^\d{5}(-\d{4})?$/.test(value);
}, "The specified US ZIP Code is invalid");
$.validator.addMethod("ziprange", function(value, element) {
return this.optional(element) || /^90[2-5]\d\{2\}-\d{4}$/.test(value);
}, "Your ZIP-code must be in the range 902xx-xxxx to 905xx-xxxx");
}));

1365
js/jquery/jquery.validate.js vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -440,9 +440,11 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
text += text.length > 0 ? '<br />' : '';
text += '- ' + g.strMultiSortHint;
}
if (g.showMarkHint && g.markHint
&& !g.showSortHint // we do not show mark hint, when sort hint is shown
&& g.showReorderHint && g.reorderHint
if (g.showMarkHint &&
g.markHint &&
! g.showSortHint && // we do not show mark hint, when sort hint is shown
g.showReorderHint &&
g.reorderHint
) {
text += text.length > 0 ? '<br />' : '';
text += '- ' + g.reorderHint;
@ -575,9 +577,8 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
if (!g.isCellEditActive) {
var $cell = $(cell);
if (
'string' === $cell.attr('data-type')
|| 'blob' === $cell.attr('data-type')
if ('string' === $cell.attr('data-type') ||
'blob' === $cell.attr('data-type')
) {
g.cEdit = g.cEditTextarea;
} else {
@ -603,9 +604,18 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
g.currentEditCell = cell;
$(g.cEdit).find('.edit_box').focus();
moveCursorToEnd($(g.cEdit).find('.edit_box'));
$(g.cEdit).find('*').removeProp('disabled');
}
}
function moveCursorToEnd(input) {
var originalValue = input.val();
var originallength = originalValue.length;
input.val('');
input.blur().focus().val(originalValue);
input[0].setSelectionRange(originallength, originallength);
}
},
/**
@ -616,11 +626,17 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
* or just specify "true", if we want to replace the edited field with the new value.
* @param field Optional, the edited <td>. If not specified, the function will
* use currently edited <td> from g.currentEditCell.
* @param field Optional, this object contains a boolean named move (true, if called from move* functions)
* and a <td> to which the grid_edit should move
*/
hideEditCell: function (force, data, field) {
hideEditCell: function (force, data, field, options) {
if (g.isCellEditActive && !force) {
// cell is being edited, save or post the edited data
g.saveOrPostEditedCell();
if (options !== undefined) {
g.saveOrPostEditedCell(options);
} else {
g.saveOrPostEditedCell();
}
return;
}
@ -1040,10 +1056,6 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
datepicker_div.css({'top': 0, 'left': 0, 'position': 'relative'});
$(g.cEdit).append(datepicker_div);
if (is_null){
$(g.cEdit).find('.edit_area').hide();
}
// cancel any click on the datepicker element
$editArea.find('> *').click(function (e) {
e.stopPropagation();
@ -1057,7 +1069,7 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
$editArea.append('<div class="cell_edit_hint">' + g.cellEditHint + '</div>');
}
}
if ($editArea.children().length > 0 && !is_null) {
if ($editArea.children().length > 0) {
$editArea.show();
}
}
@ -1065,8 +1077,11 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
/**
* Post the content of edited cell.
*
* @param field Optional, this object contains a boolean named move (true, if called from move* functions)
* and a <td> to which the grid_edit should move
*/
postEditedCell: function () {
postEditedCell: function (options) {
if (g.isSaving) {
return;
}
@ -1273,7 +1288,9 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
.find('input').removeProp('disabled'); // enable the save button back
}
if (typeof data !== 'undefined' && data.success === true) {
PMA_ajaxShowMessage(data.message);
if (typeof options === 'undefined' || ! options.move) {
PMA_ajaxShowMessage(data.message);
}
// update where_clause related data in each edited row
$(g.t).find('td.to_be_saved').parents('tr').each(function () {
@ -1315,7 +1332,7 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
var tools = $result_query.find('.tools').wrap('<p>').parent().html();
// sqlOuter and tools will not be present if 'Show SQL queries' configuration is off
if (typeof sqlOuter != 'undefined' && typeof tools != 'undefined') {
$existing_query = $(g.o).find('.result_query');
var $existing_query = $(g.o).find('.result_query');
// If two query box exists update query in second else add a second box
if ($existing_query.find('div.sqlOuter').length > 1) {
$existing_query.children(":nth-child(4)").remove();
@ -1347,6 +1364,10 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
}
}
}
}).done(function(){
if (options !== undefined && options.move) {
g.showEditCell(options.cell);
}
}); // end $.ajax()
},
@ -1430,20 +1451,54 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
/**
* Save or post currently edited cell, depending on the "saveCellsAtOnce" configuration.
*
* @param field Optional, this object contains a boolean named move (true, if called from move* functions)
* and a <td> to which the grid_edit should move
*/
saveOrPostEditedCell: function () {
saveOrPostEditedCell: function (options) {
var saved = g.saveEditedCell();
// Check if $cfg['SaveCellsAtOnce'] is false
if (!g.saveCellsAtOnce) {
// Check if need_to_post is true
if (saved) {
g.postEditedCell();
// Check if this function called from 'move' functions
if (options !== undefined && options.move) {
g.postEditedCell(options);
} else {
g.postEditedCell();
}
// need_to_post is false
} else {
g.hideEditCell(true);
// Check if this function called from 'move' functions
if (options !== undefined && options.move) {
g.hideEditCell(true);
g.showEditCell(options.cell);
// NOT called from 'move' functions
} else {
g.hideEditCell(true);
}
}
// $cfg['SaveCellsAtOnce'] is true
} else {
// If need_to_post
if (saved) {
g.hideEditCell(true, true);
// If this function called from 'move' functions
if (options !== undefined && options.move) {
g.hideEditCell(true, true, false, options);
g.showEditCell(options.cell);
// NOT called from 'move' functions
} else {
g.hideEditCell(true, true);
}
} else {
g.hideEditCell(true);
// If this function called from 'move' functions
if (options !== undefined && options.move) {
g.hideEditCell(true, false, false, options);
g.showEditCell(options.cell);
// NOT called from 'move' functions
} else {
g.hideEditCell(true);
}
}
}
},
@ -1589,16 +1644,17 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
// get data columns in the first row of the table
var $firstRowCols = $(g.t).find('tr:first th.draggable');
var i;
// initialize column visibility
var $col_visib = $(g.o).find('.col_visib'); // check if column visibility is passed from PHP
if ($col_visib.length > 0) {
g.colVisib = $col_visib.val().split(',');
for (var i = 0; i < g.colVisib.length; i++) {
for (i = 0; i < g.colVisib.length; i++) {
g.colVisib[i] = parseInt(g.colVisib[i], 10);
}
} else {
g.colVisib = [];
for (var i = 0; i < $firstRowCols.length; i++) {
for (i = 0; i < $firstRowCols.length; i++) {
g.colVisib.push(1);
}
}
@ -1638,7 +1694,7 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
}
};
for (var i = 0; i < $firstRowCols.length; i++) {
for (i = 0; i < $firstRowCols.length; i++) {
var currHeader = $firstRowCols[i];
var listElmt = document.createElement('div');
$(listElmt).text($(currHeader).text())
@ -1678,6 +1734,187 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
g.reposDrop();
},
/**
* Move currently Editing Cell to Up
*/
moveUp: function(e) {
e.preventDefault();
var $this_field = $(g.currentEditCell);
var field_name = getFieldName($(g.t), $this_field);
var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
if (typeof where_clause === 'undefined') {
where_clause = '';
}
where_clause = PMA_urldecode(where_clause);
var found = false;
var $found_row;
var $prev_row;
var j = 0;
$this_field.parents('tr').first().parents('tbody').children().each(function(){
if (PMA_urldecode($(this).find('.where_clause').val()) == where_clause) {
found = true;
$found_row = $(this);
}
if (!found) {
$prev_row = $(this);
}
});
var new_cell;
if (found && $prev_row) {
$prev_row.children('td').each(function(){
if (getFieldName($(g.t), $(this)) == field_name) {
new_cell = this;
}
});
}
if (new_cell) {
g.hideEditCell(false, false, false, {move : true, cell : new_cell});
}
},
/**
* Move currently Editing Cell to Down
*/
moveDown: function(e) {
e.preventDefault();
var $this_field = $(g.currentEditCell);
var field_name = getFieldName($(g.t), $this_field);
var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
if (typeof where_clause === 'undefined') {
where_clause = '';
}
where_clause = PMA_urldecode(where_clause);
var found = false;
var $found_row;
var $next_row;
var j = 0;
var next_row_found = false;
$this_field.parents('tr').first().parents('tbody').children().each(function(){
if (PMA_urldecode($(this).find('.where_clause').val()) == where_clause) {
found = true;
$found_row = $(this);
}
if (found) {
if (j >= 1 && ! next_row_found) {
$next_row = $(this);
next_row_found = true;
} else {
j++;
}
}
});
var new_cell;
if (found && $next_row) {
$next_row.children('td').each(function(){
if (getFieldName($(g.t), $(this)) == field_name) {
new_cell = this;
}
});
}
if (new_cell) {
g.hideEditCell(false, false, false, {move : true, cell : new_cell});
}
},
/**
* Move currently Editing Cell to Left
*/
moveLeft: function(e) {
e.preventDefault();
var $this_field = $(g.currentEditCell);
var field_name = getFieldName($(g.t), $this_field);
var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
if (typeof where_clause === 'undefined') {
where_clause = '';
}
where_clause = PMA_urldecode(where_clause);
var found = false;
var $found_row;
var j = 0;
$this_field.parents('tr').first().parents('tbody').children().each(function(){
if (PMA_urldecode($(this).find('.where_clause').val()) == where_clause) {
found = true;
$found_row = $(this);
}
});
var left_cell;
var cell_found = false;
if (found) {
$found_row.children('td.grid_edit').each(function(){
if (getFieldName($(g.t), $(this)) === field_name) {
cell_found = true;
}
if (!cell_found) {
left_cell = this;
}
});
}
if (left_cell) {
g.hideEditCell(false, false, false, {move : true, cell : left_cell});
}
},
/**
* Move currently Editing Cell to Right
*/
moveRight: function(e) {
e.preventDefault();
var $this_field = $(g.currentEditCell);
var field_name = getFieldName($(g.t), $this_field);
var where_clause = $this_field.parents('tr').first().find('.where_clause').val();
if (typeof where_clause === 'undefined') {
where_clause = '';
}
where_clause = PMA_urldecode(where_clause);
var found = false;
var $found_row;
var j = 0;
$this_field.parents('tr').first().parents('tbody').children().each(function(){
if (PMA_urldecode($(this).find('.where_clause').val()) == where_clause) {
found = true;
$found_row = $(this);
}
});
var right_cell;
var cell_found = false;
var next_cell_found = false;
if (found) {
$found_row.children('td.grid_edit').each(function(){
if (getFieldName($(g.t), $(this)) === field_name) {
cell_found = true;
}
if (cell_found) {
if (j >= 1 && ! next_cell_found) {
right_cell = this;
next_cell_found = true;
} else {
j++;
}
}
});
}
if (right_cell) {
g.hideEditCell(false, false, false, {move : true, cell : right_cell});
}
},
/**
* Initialize grid editing feature.
*/
@ -1692,6 +1929,18 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
e.stopPropagation();
}
function handleCtrlNavigation(e) {
if ((e.ctrlKey && e.which == 38 ) || (e.altKey && e.which == 38)) {
g.moveUp(e);
} else if ((e.ctrlKey && e.which == 40) || (e.altKey && e.which == 40)) {
g.moveDown(e);
} else if ((e.ctrlKey && e.which == 37 ) || (e.altKey && e.which == 37)) {
g.moveLeft(e);
} else if ((e.ctrlKey && e.which == 39) || (e.altKey && e.which == 39)) {
g.moveRight(e);
}
}
// create cell edit wrapper element
g.cEditStd = document.createElement('div');
g.cEdit = g.cEditStd;
@ -1729,7 +1978,7 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
$(g.t).find('td.data.click2')
.click(function (e) {
$cell = $(this);
var $cell = $(this);
// In the case of relational link, We want single click on the link
// to goto the link and double click to start grid-editing.
var $link = $(e.target);
@ -1742,7 +1991,7 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
if (clicks == 1) {
// if there are no previous clicks,
// start the single click timer
timer = setTimeout(function () {
var timer = setTimeout(function () {
// temporarily remove ajax class so the page loader will not handle it,
// submit and then add it back
$link.removeClass('ajax');
@ -1770,6 +2019,8 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
}
});
$(g.cEditStd).on('keydown', 'input.edit_box, select', handleCtrlNavigation);
$(g.cEditStd).find('.edit_box').focus(function (e) {
g.showEditArea();
});
@ -1786,6 +2037,9 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
e.preventDefault();
}
});
$(g.cEditTextarea).on('keydown', 'textarea.edit_box, select', handleCtrlNavigation);
$(g.cEditTextarea).find('.edit_box').focus(function (e) {
g.showEditArea();
});
@ -1846,7 +2100,15 @@ function PMA_makegrid(t, enableResize, enableReorder, enableVisib, enableGridEdi
* Initialize grid
******************/
// wrap all data cells, except actions cell, with span
// wrap all truncated data cells with span indicating the original length
// todo update the original length after a grid edit
$(t).find('td.data.truncated:not(:has(span))')
.wrapInner(function() {
return '<span title="' + PMA_messages.strOriginalLength + ' ' +
$(this).data('originallength') + '"></span>';
});
// wrap remaining cells, except actions cell, with span
$(t).find('th, td:not(:has(span))')
.wrapInner('<span />');

View File

@ -68,7 +68,8 @@
// Calculate the total width used by all the shown tabs
var total_len = more_shown ? submenu_w : 0;
var l = $li.length - 1;
for (var i = 0; i < l; i++) {
var i;
for (i = 0; i < l; i++) {
total_len += $($li[i]).outerWidth(true);
}
// Now hide menu elements that don't fit into the menubar
@ -91,7 +92,7 @@
// If we didn't hide any tabs, then there might be some space to show some
if (! hidden) {
// Show menu elements that do fit into the menubar
for (var i = 0, l = $li2.length; i < l; i++) {
for (i = 0, l = $li2.length; i < l; i++) {
total_len += $($li2[i]).data('width');
// item fits or (it is the last item
// and it would fit if More got removed)

View File

@ -29,9 +29,11 @@ require_once './libraries/Util.class.php';
require_once './libraries/OutputBuffering.class.php';
$buffer = PMA_OutputBuffering::getInstance();
$buffer->start();
register_shutdown_function(function() {
echo PMA_OutputBuffering::getInstance()->getContents();
});
register_shutdown_function(
function () {
echo PMA_OutputBuffering::getInstance()->getContents();
}
);
$js_messages['strNoDropDatabases'] = __('"DROP DATABASE" statements are disabled.');
if ($cfg['AllowUserDropDatabase']) {
@ -58,19 +60,42 @@ $js_messages['strConfirmDeleteQBESearch'] = __('Do you really want to delete the
$js_messages['strConfirmNavigation'] = __('You have unsaved changes; are you sure you want to leave this page?');
$js_messages['strDropUserWarning'] = __('Do you really want to revoke the selected user(s) ?');
$js_messages['strDeleteCentralColumnWarning'] = __('Do you really want to delete this central column?');
$js_messages['strDropRTEitems'] = __('Do you really want to delete the selected items?');
$js_messages['strDropPartitionWarning'] = __('Do you really want to DROP the selected partition(s)? This will also DELETE the data related to the selected partition(s)!');
$js_messages['strTruncatePartitionWarning'] = __('Do you really want to TRUNCATE the selected partition(s)?');
$js_messages['strChangeColumnCollation'] = __(
'This operation will attempt to convert your data to the new collation. In '
. 'rare cases, especially where a character doesn\'t exist in the new '
. 'collation, this process could cause the data to appear incorrectly under '
. 'the new collation; in this case we suggest you revert to the original '
. 'collation and refer to the tips at '
)
. '<a href="%s" target="garbled_data_wiki">' . __('Garbled Data') . '</a>.'
. '<br/><br/>'
. __('Are you sure you wish to change the collation and convert the data?');
$js_messages['strChangeAllColumnCollationsWarning'] = __(
'Through this operation, MySQL attempts to map the data values between collations. '
. 'If the character sets are incompatible, '
. 'there may be data loss and this lost data may <b>NOT</b> be recoverable simply '
. 'by changing back the column collation(s).'
. '<b> To convert existing data, it is suggested to use the column(s) editing feature '
. '(the "Change" Link) on the table structure page. </b>'
)
. '<br/><br/>'
. __('Are you sure you wish to change all the column collations and convert the data?');
/* For modal dialog buttons */
$js_messages['strSaveAndClose'] = __('Save & Close');
$js_messages['strSaveAndClose'] = __('Save & close');
$js_messages['strReset'] = __('Reset');
$js_messages['strResetAll'] = __('Reset All');
$js_messages['strResetAll'] = __('Reset all');
/* For indexes */
$js_messages['strFormEmpty'] = __('Missing value in the form!');
$js_messages['strRadioUnchecked'] = __('Select at least one of the options!');
$js_messages['strEnterValidNumber'] = __('Please enter a valid number!');
$js_messages['strEnterValidLength'] = __('Please enter a valid length!');
$js_messages['strAddIndex'] = __('Add Index');
$js_messages['strEditIndex'] = __('Edit Index');
$js_messages['strAddIndex'] = __('Add index');
$js_messages['strEditIndex'] = __('Edit index');
$js_messages['strAddToIndex'] = __('Add %s column(s) to index');
$js_messages['strCreateSingleColumnIndex'] = __('Create single-column index');
$js_messages['strCreateCompositeIndex'] = __('Create composite index');
@ -90,7 +115,7 @@ $js_messages['strSQLQuery'] = __('SQL query:');
/* Charts */
/* l10n: Default label for the y-Axis of Charts */
$js_messages['strYValues'] = __('Y Values');
$js_messages['strYValues'] = __('Y values');
/* For server_privileges.js */
$js_messages['strHostEmpty'] = __('The host name is empty!');
@ -100,6 +125,12 @@ $js_messages['strPasswordNotSame'] = __('The passwords aren\'t the same!');
$js_messages['strRemovingSelectedUsers'] = __('Removing Selected Users');
$js_messages['strClose'] = __('Close');
/* For export.js */
$js_messages['strTemplateCreated'] = __('Template was created.');
$js_messages['strTemplateLoaded'] = __('Template was loaded.');
$js_messages['strTemplateUpdated'] = __('Template was updated.');
$js_messages['strTemplateDeleted'] = __('Template was deleted.');
/* l10n: Other, small valued, queries */
$js_messages['strOther'] = __('Other');
/* l10n: Thousands separator */
@ -117,7 +148,7 @@ $js_messages['strQueryCacheEfficiency'] = __('Query cache efficiency');
$js_messages['strQueryCacheUsage'] = __('Query cache usage');
$js_messages['strQueryCacheUsed'] = __('Query cache used');
$js_messages['strSystemCPUUsage'] = __('System CPU Usage');
$js_messages['strSystemCPUUsage'] = __('System CPU usage');
$js_messages['strSystemMemory'] = __('System memory');
$js_messages['strSystemSwap'] = __('System swap');
@ -128,10 +159,10 @@ $js_messages['strBufferedMemory'] = __('Buffered memory');
$js_messages['strFreeMemory'] = __('Free memory');
$js_messages['strUsedMemory'] = __('Used memory');
$js_messages['strTotalSwap'] = __('Total Swap');
$js_messages['strCachedSwap'] = __('Cached Swap');
$js_messages['strUsedSwap'] = __('Used Swap');
$js_messages['strFreeSwap'] = __('Free Swap');
$js_messages['strTotalSwap'] = __('Total swap');
$js_messages['strCachedSwap'] = __('Cached swap');
$js_messages['strUsedSwap'] = __('Used swap');
$js_messages['strFreeSwap'] = __('Free swap');
$js_messages['strBytesSent'] = __('Bytes sent');
$js_messages['strBytesReceived'] = __('Bytes received');
@ -185,7 +216,7 @@ $js_messages['strNoSuperUser'] = __(
$js_messages['strChangeSettings'] = __('Change settings');
$js_messages['strCurrentSettings'] = __('Current settings');
$js_messages['strChartTitle'] = __('Chart Title');
$js_messages['strChartTitle'] = __('Chart title');
/* l10n: As in differential values */
$js_messages['strDifferential'] = __('Differential');
$js_messages['strDividedBy'] = __('Divided by %s');
@ -241,7 +272,7 @@ $js_messages['strImportDialogTitle'] = __('Import monitor configuration');
$js_messages['strImportDialogMessage'] = __('Please select the file you want to import.');
$js_messages['strNoImportFile'] = __('No files available on server for import!');
$js_messages['strAnalyzeQuery'] = __('Analyse Query');
$js_messages['strAnalyzeQuery'] = __('Analyse query');
/* Server status advisor */
@ -255,36 +286,40 @@ $js_messages['strFormula'] = __('Used variable / formula');
$js_messages['strTest'] = __('Test');
/* For query editor */
$js_messages['strFormatting'] = __('Formatting SQL...');
$js_messages['strFormatting'] = __('Formatting SQL');
/* For inline query editing */
$js_messages['strGo'] = __('Go');
$js_messages['strCancel'] = __('Cancel');
/* For page-related settings */
$js_messages['strPageSettings'] = _('Page-related settings');
$js_messages['strApply'] = _('Apply');
/* For Ajax Notifications */
$js_messages['strLoading'] = __('Loading…');
$js_messages['strAbortedRequest'] = __('Request Aborted!!');
$js_messages['strProcessingRequest'] = __('Processing Request');
$js_messages['strRequestFailed'] = __('Request Failed!!');
$js_messages['strErrorProcessingRequest'] = __('Error in Processing Request');
$js_messages['strAbortedRequest'] = __('Request aborted!!');
$js_messages['strProcessingRequest'] = __('Processing request');
$js_messages['strRequestFailed'] = __('Request failed!!');
$js_messages['strErrorProcessingRequest'] = __('Error in processing request');
$js_messages['strErrorCode'] = __('Error code: %s');
$js_messages['strErrorText'] = __('Error text: %s');
$js_messages['strNoDatabasesSelected'] = __('No databases selected.');
$js_messages['strDroppingColumn'] = __('Dropping Column');
$js_messages['strAddingPrimaryKey'] = __('Adding Primary Key');
$js_messages['strDroppingColumn'] = __('Dropping column');
$js_messages['strAddingPrimaryKey'] = __('Adding primary key');
$js_messages['strOK'] = __('OK');
$js_messages['strDismiss'] = __('Click to dismiss this notification');
/* For db_operations.js */
$js_messages['strRenamingDatabases'] = __('Renaming Databases');
$js_messages['strCopyingDatabase'] = __('Copying Database');
$js_messages['strChangingCharset'] = __('Changing Charset');
$js_messages['strRenamingDatabases'] = __('Renaming databases');
$js_messages['strCopyingDatabase'] = __('Copying database');
$js_messages['strChangingCharset'] = __('Changing charset');
$js_messages['strNo'] = __('No');
/* For Foreign key checks */
$js_messages['strForeignKeyCheck'] = __('Enable foreign key checks');
/* For db_stucture.js */
$js_messages['strForeignKeyCheck'] = __('Foreign key check:');
$js_messages['strForeignKeyCheckEnabled'] = __('(Enabled)');
$js_messages['strForeignKeyCheckDisabled'] = __('(Disabled)');
$js_messages['strErrorRealRowCount'] = __('Failed to get real row count.');
/* For db_search.js */
@ -296,6 +331,7 @@ $js_messages['strDeleting'] = __('Deleting');
/* For db_routines.js */
$js_messages['MissingReturn'] = __('The definition of a stored function must contain a RETURN statement!');
$js_messages['strExport'] = __('Export');
/* For ENUM/SET editor*/
$js_messages['enum_editor'] = __('ENUM/SET editor');
@ -311,9 +347,11 @@ $js_messages['strImportCSV'] = __('Note: If the file contains multiple tables, t
$js_messages['strHideQueryBox'] = __('Hide query box');
$js_messages['strShowQueryBox'] = __('Show query box');
$js_messages['strEdit'] = __('Edit');
$js_messages['strDelete'] = __('Delete');
$js_messages['strNotValidRowNumber'] = __('%d is not valid row number.');
$js_messages['strBrowseForeignValues'] = __('Browse foreign values');
$js_messages['strNoAutoSavedQuery'] = __('No auto-saved query');
$js_messages['strBookmarkVariable'] = __('Variable %d:');
/* For Central list of columns */
$js_messages['pickColumn'] = __('Pick');
@ -382,6 +420,7 @@ $js_messages['strDisplayHelp'] = '<ul><li>'
. '</li><li>'
. __('The plot can be resized by dragging it along the bottom right corner.')
. '</li></ul>';
$js_messages['strHelpTitle'] = 'Zoom search instructions';
$js_messages['strInputNull'] = '<strong>' . __('Select two columns') . '</strong>';
$js_messages['strSameInputs'] = '<strong>'
. __('Select two different columns')
@ -398,11 +437,10 @@ $js_messages['strPointN'] = __('Point %d');
$js_messages['strLineString'] = __('Linestring');
$js_messages['strPolygon'] = __('Polygon');
$js_messages['strGeometry'] = __('Geometry');
$js_messages['strInnerRing'] = __('Inner Ring');
$js_messages['strOuterRing'] = __('Outer Ring');
$js_messages['strInnerRing'] = __('Inner ring');
$js_messages['strOuterRing'] = __('Outer ring');
$js_messages['strAddPoint'] = __('Add a point');
$js_messages['strAddInnerRing'] = __('Add an inner ring');
$js_messages['strFunctionHint'] = __('Shift + Click on function name to apply to all rows.');
$js_messages['strYes'] = __('Yes');
$js_messages['strCopyEncryptionKey'] = __('Do you want to copy encryption key?');
$js_messages['strEncryptionKey'] = __('Encryption key');
@ -424,6 +462,7 @@ $js_messages['strLeavingDesigner'] = __(
);
$js_messages['strPageName'] = __('Page name');
$js_messages['strSavePage'] = __('Save page');
$js_messages['strSavePageAs'] = __('Save page as');
$js_messages['strOpenPage'] = __('Open page');
$js_messages['strDeletePage'] = __('Delete page');
$js_messages['strUntitled'] = __('Untitled');
@ -437,6 +476,7 @@ $js_messages['strModificationSaved'] = __('Modifications have been saved');
/* Visual query builder (js/pmd/move.js) */
$js_messages['strAddOption'] = __('Add an option for column "%s".');
$js_messages['strObjectsCreated'] = __('%d object(s) created.');
$js_messages['strSubmit'] = __('Submit');
/* For makegrid.js (column reordering, show/hide column, grid editing) */
$js_messages['strCellEditHint'] = __('Press escape to cancel editing.');
@ -453,6 +493,7 @@ $js_messages['strShowAllCol'] = __('Show all');
$js_messages['strAlertNonUnique'] = __('This table does not contain a unique column. Features related to the grid edit, checkbox, Edit, Copy and Delete links may not work after saving.');
$js_messages['strEnterValidHex'] = __('Please enter a valid hexadecimal string. Valid characters are 0-9, A-F.');
$js_messages['strShowAllRowsWarning'] = __('Do you really want to see all of the rows? For a big table this could crash the browser.');
$js_messages['strOriginalLength'] = __('Original length');
/** Drag & Drop sql import messages */
$js_messages['dropImportMessageCancel'] = __('cancel');
@ -481,14 +522,14 @@ $js_messages['strColNameCopyText'] = __('Right-click the column name to copy it
/* password generation */
$js_messages['strGeneratePassword'] = __('Generate password');
$js_messages['strGenerate'] = __('Generate');
$js_messages['strChangePassword'] = __('Change Password');
$js_messages['strChangePassword'] = __('Change password');
/* navigation tabs */
$js_messages['strMore'] = __('More');
/* navigation panel */
$js_messages['strShowPanel'] = __('Show Panel');
$js_messages['strHidePanel'] = __('Hide Panel');
$js_messages['strShowPanel'] = __('Show panel');
$js_messages['strHidePanel'] = __('Hide panel');
$js_messages['strUnhideNavItem'] = __('Show hidden navigation tree items.');
$js_messages['linkWithMain'] = __('Link with main panel');
$js_messages['unlinkWithMain'] = __('Unlink from main panel');
@ -512,13 +553,13 @@ $js_messages['strUpToDate'] = __('up to date');
$js_messages['strCreateView'] = __('Create view');
/* Error Reporting */
$js_messages['strSendErrorReport'] = __("Send Error Report");
$js_messages['strSubmitErrorReport'] = __("Submit Error Report");
$js_messages['strSendErrorReport'] = __("Send error report");
$js_messages['strSubmitErrorReport'] = __("Submit error report");
$js_messages['strErrorOccurred'] = __(
"A fatal JavaScript error has occurred. Would you like to send an error report?"
);
$js_messages['strChangeReportSettings'] = __("Change Report Settings");
$js_messages['strShowReportDetails'] = __("Show Report Details");
$js_messages['strChangeReportSettings'] = __("Change report settings");
$js_messages['strShowReportDetails'] = __("Show report details");
$js_messages['strIgnore'] = __("Ignore");
$js_messages['strTimeOutError'] = __(
"Your export is incomplete, due to a low execution time limit at the PHP level!"
@ -532,14 +573,15 @@ $js_messages['strTooManyInputs'] = __(
$js_messages['phpErrorsFound'] = '<div class="error">'
. __('Some errors have been detected on the server!')
. '<div>'
. '<br/>'
. __('Please look at the bottom of this window.')
. '<div>'
. '<input id="pma_ignore_errors_popup" type="submit" value="'
. __('Ignore')
. '" style="float: right; margin: 20px;">'
. '" class="floatright" style="margin-top: 20px;">'
. '<input id="pma_ignore_all_errors_popup" type="submit" value="'
. __('Ignore All')
. '" style="float: right; margin: 20px;">'
. '" class="floatright" style="margin-top: 20px;">'
. '</div></div>';
$js_messages['phpErrorsBeingSubmitted'] = '<div class="error">'
@ -552,8 +594,15 @@ $js_messages['phpErrorsBeingSubmitted'] = '<div class="error">'
. '" width="16" height="16" alt="ajax clock"/>'
. '</div>';
// For console
$js_messages['strConsoleRequeryConfirm'] = __('Execute this query again?');
$js_messages['strConsoleDeleteBookmarkConfirm'] = __('Do you really want to delete this bookmark?');
$js_messages['strConsoleDebugError'] = __('Some error occurred while getting SQL debug info.');
$js_messages['strConsoleDebugSummary'] = __('%s queries executed %s times in %s seconds.');
$js_messages['strConsoleDebugArgsSummary'] = __('%s argument(s) passed');
$js_messages['strConsoleDebugShowArgs'] = __('Show arguments');
$js_messages['strConsoleDebugHideArgs'] = __('Hide arguments');
$js_messages['strConsoleDebugTimeTaken'] = __('Time taken:');
$js_messages['strNoLocalStorage'] = __('Your web browser does not support local storage of settings or the quota limit has been reached, some features may not work properly for you. In Safari, such problem is commonly caused by "Private Mode Browsing".');
echo "var PMA_messages = new Array();\n";
@ -611,29 +660,29 @@ PMA_printJsValue(
PMA_printJsValue(
"$.datepicker.regional['']['monthNamesShort']",
array(
/* l10n: Short month name */
/* l10n: Short month name */
__('Jan'),
/* l10n: Short month name */
/* l10n: Short month name */
__('Feb'),
/* l10n: Short month name */
/* l10n: Short month name */
__('Mar'),
/* l10n: Short month name */
/* l10n: Short month name */
__('Apr'),
/* l10n: Short month name */
/* l10n: Short month name */
_pgettext('Short month name', 'May'),
/* l10n: Short month name */
/* l10n: Short month name */
__('Jun'),
/* l10n: Short month name */
/* l10n: Short month name */
__('Jul'),
/* l10n: Short month name */
/* l10n: Short month name */
__('Aug'),
/* l10n: Short month name */
/* l10n: Short month name */
__('Sep'),
/* l10n: Short month name */
/* l10n: Short month name */
__('Oct'),
/* l10n: Short month name */
/* l10n: Short month name */
__('Nov'),
/* l10n: Short month name */
/* l10n: Short month name */
__('Dec')
)
);
@ -652,38 +701,38 @@ PMA_printJsValue(
PMA_printJsValue(
"$.datepicker.regional['']['dayNamesShort']",
array(
/* l10n: Short week day name */
/* l10n: Short week day name */
__('Sun'),
/* l10n: Short week day name */
/* l10n: Short week day name */
__('Mon'),
/* l10n: Short week day name */
/* l10n: Short week day name */
__('Tue'),
/* l10n: Short week day name */
/* l10n: Short week day name */
__('Wed'),
/* l10n: Short week day name */
/* l10n: Short week day name */
__('Thu'),
/* l10n: Short week day name */
/* l10n: Short week day name */
__('Fri'),
/* l10n: Short week day name */
/* l10n: Short week day name */
__('Sat')
)
);
PMA_printJsValue(
"$.datepicker.regional['']['dayNamesMin']",
array(
/* l10n: Minimal week day name */
/* l10n: Minimal week day name */
__('Su'),
/* l10n: Minimal week day name */
/* l10n: Minimal week day name */
__('Mo'),
/* l10n: Minimal week day name */
/* l10n: Minimal week day name */
__('Tu'),
/* l10n: Minimal week day name */
/* l10n: Minimal week day name */
__('We'),
/* l10n: Minimal week day name */
/* l10n: Minimal week day name */
__('Th'),
/* l10n: Minimal week day name */
/* l10n: Minimal week day name */
__('Fr'),
/* l10n: Minimal week day name */
/* l10n: Minimal week day name */
__('Sa')
)
);
@ -716,3 +765,33 @@ PMA_printJsValue("$.timepicker.regional['']['secondText']", __('Second'));
?>
$.extend($.timepicker._defaults, $.timepicker.regional['']);
} /* if ($.timepicker) */
<?php
/* Form validation */
echo "function extendingValidatorMessages() {\n";
echo "$.extend($.validator.messages, {\n";
/* Default validation functions */
PMA_printJsValueForFormValidation('required', __('This field is required'));
PMA_printJsValueForFormValidation('remote', __('Please fix this field'));
PMA_printJsValueForFormValidation('email', __('Please enter a valid email address'));
PMA_printJsValueForFormValidation('url', __('Please enter a valid URL'));
PMA_printJsValueForFormValidation('date', __('Please enter a valid date'));
PMA_printJsValueForFormValidation('dateISO', __('Please enter a valid date ( ISO )'));
PMA_printJsValueForFormValidation('number', __('Please enter a valid number'));
PMA_printJsValueForFormValidation('creditcard', __('Please enter a valid credit card number'));
PMA_printJsValueForFormValidation('digits', __('Please enter only digits'));
PMA_printJsValueForFormValidation('equalTo', __('Please enter the same value again'));
PMA_printJsValueForFormValidation('maxlength', __('Please enter no more than {0} characters'), true);
PMA_printJsValueForFormValidation('minlength', __('Please enter at least {0} characters'), true);
PMA_printJsValueForFormValidation('rangelength', __('Please enter a value between {0} and {1} characters long'), true);
PMA_printJsValueForFormValidation('range', __('Please enter a value between {0} and {1}'), true);
PMA_printJsValueForFormValidation('max', __('Please enter a value less than or equal to {0}'), true);
PMA_printJsValueForFormValidation('min', __('Please enter a value greater than or equal to {0}'), true);
/* customed functions */
PMA_printJsValueForFormValidation('validationFunctionForDateTime', __('Please enter a valid date or time'), true);
PMA_printJsValueForFormValidation('validationFunctionForHex', __('Please enter a valid HEX input'), true);
PMA_printJsValueForFormValidation('validationFunctionForFuns', __('Error'), true, false);
echo "\n});";
echo "\n} /* if ($.validator) */";
?>

331
js/microhistory.js Normal file
View File

@ -0,0 +1,331 @@
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* An implementation of a client-side page cache.
* This object also uses the cache to provide a simple microhistory,
* that is the ability to use the back and forward buttons in the browser
*/
PMA_MicroHistory = {
/**
* @var int The maximum number of pages to keep in the cache
*/
MAX: 6,
/**
* @var object A hash used to prime the cache with data about the initially
* loaded page. This is set in the footer, and then loaded
* by a double-queued event further down this file.
*/
primer: {},
/**
* @var array Stores the content of the cached pages
*/
pages: [],
/**
* @var int The index of the currently loaded page
* This is used to know at which point in the history we are
*/
current: 0,
/**
* Saves a new page in the cache
*
* @param string hash The hash part of the url that is being loaded
* @param array scripts A list of scripts that is required for the page
* @param string menu A hash that links to a menu stored
* in a dedicated menu cache
* @param array params A list of parameters used by PMA_commonParams()
* @param string rel A relationship to the current page:
* 'samepage': Forces the response to be treated as
* the same page as the current one
* 'newpage': Forces the response to be treated as
* a new page
* undefined: Default behaviour, 'samepage' if the
* selflinks of the two pages are the same.
* 'newpage' otherwise
*
* @return void
*/
add: function (hash, scripts, menu, params, rel) {
if (this.pages.length > PMA_MicroHistory.MAX) {
// Trim the cache, to the maximum number of allowed entries
// This way we will have a cached menu for every page
for (var i = 0; i < this.pages.length - this.MAX; i++) {
delete this.pages[i];
}
}
while (this.current < this.pages.length) {
// trim the cache if we went back in the history
// and are now going forward again
this.pages.pop();
}
if (rel === 'newpage' ||
(
typeof rel === 'undefined' && (
typeof this.pages[this.current - 1] === 'undefined' ||
this.pages[this.current - 1].hash !== hash
)
)
) {
this.pages.push({
hash: hash,
content: $('#page_content').html(),
scripts: scripts,
selflink: $('#selflink').html(),
menu: menu,
params: params
});
PMA_SetUrlHash(this.current, hash);
this.current++;
}
},
/**
* Restores a page from the cache. This is called when the hash
* part of the url changes and it's structure appears to be valid
*
* @param string index Which page from the history to load
*
* @return void
*/
navigate: function (index) {
if (typeof this.pages[index] === 'undefined' ||
typeof this.pages[index].content === 'undefined' ||
typeof this.pages[index].menu === 'undefined' ||
! PMA_MicroHistory.menus.get(this.pages[index].menu)
) {
PMA_ajaxShowMessage(
'<div class="error">' + PMA_messages.strInvalidPage + '</div>',
false
);
} else {
AJAX.active = true;
var record = this.pages[index];
AJAX.scriptHandler.reset(function () {
$('#page_content').html(record.content);
$('#selflink').html(record.selflink);
PMA_MicroHistory.menus.replace(PMA_MicroHistory.menus.get(record.menu));
PMA_commonParams.setAll(record.params);
AJAX.scriptHandler.load(record.scripts);
PMA_MicroHistory.current = ++index;
});
}
},
/**
* Resaves the content of the current page in the cache.
* Necessary in order not to show the user some outdated version of the page
*
* @return void
*/
update: function () {
var page = this.pages[this.current - 1];
if (page) {
page.content = $('#page_content').html();
}
},
/**
* @var object Dedicated menu cache
*/
menus: {
/**
* Returns the number of items in an associative array
*
* @return int
*/
size: function (obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
size++;
}
}
return size;
},
/**
* @var hash Stores the content of the cached menus
*/
data: {},
/**
* Saves a new menu in the cache
*
* @param string hash The hash (trimmed md5) of the menu to be saved
* @param string content The HTML code of the menu to be saved
*
* @return void
*/
add: function (hash, content) {
if (this.size(this.data) > PMA_MicroHistory.MAX) {
// when the cache grows, we remove the oldest entry
var oldest, key, init = 0;
for (var i in this.data) {
if (this.data[i]) {
if (! init || this.data[i].timestamp.getTime() < oldest.getTime()) {
oldest = this.data[i].timestamp;
key = i;
init = 1;
}
}
}
delete this.data[key];
}
this.data[hash] = {
content: content,
timestamp: new Date()
};
},
/**
* Retrieves a menu given its hash
*
* @param string hash The hash of the menu to be retrieved
*
* @return string
*/
get: function (hash) {
if (this.data[hash]) {
return this.data[hash].content;
} else {
// This should never happen as long as the number of stored menus
// is larger or equal to the number of pages in the page cache
return '';
}
},
/**
* Prepares part of the parameter string used during page requests,
* this is necessary to tell the server which menus we have in the cache
*
* @return string
*/
getRequestParam: function () {
var param = '';
var menuHashes = [];
for (var i in this.data) {
menuHashes.push(i);
}
var menuHashesParam = menuHashes.join('-');
if (menuHashesParam) {
param = '&menuHashes=' + menuHashesParam;
}
return param;
},
/**
* Replaces the menu with new content
*
* @return void
*/
replace: function (content) {
$('#floating_menubar').html(content)
// Remove duplicate wrapper
// TODO: don't send it in the response
.children().first().remove();
$('#topmenu').menuResizer(PMA_mainMenuResizerCallback);
}
}
};
/**
* URL hash management module.
* Allows direct bookmarking and microhistory.
*/
PMA_SetUrlHash = (function (jQuery, window) {
"use strict";
/**
* Indictaes whether we have already completed
* the initialisation of the hash
*
* @access private
*/
var ready = false;
/**
* Stores a hash that needed to be set when we were not ready
*
* @access private
*/
var savedHash = "";
/**
* Flag to indicate if the change of hash was triggered
* by a user pressing the back/forward button or if
* the change was triggered internally
*
* @access private
*/
var userChange = true;
// Fix favicon disappearing in Firefox when setting location.hash
function resetFavicon() {
if (navigator.userAgent.indexOf('Firefox') > -1) {
// Move the link tags for the favicon to the bottom
// of the head element to force a reload of the favicon
$('head > link[href=favicon\\.ico]').appendTo('head');
}
}
/**
* Sets the hash part of the URL
*
* @access public
*/
function setUrlHash(index, hash) {
/*
* Known problem:
* Setting hash leads to reload in webkit:
* http://www.quirksmode.org/bugreports/archives/2005/05/Safari_13_visual_anomaly_with_windowlocationhref.html
*
* so we expect that users are not running an ancient Safari version
*/
userChange = false;
if (ready) {
window.location.hash = "PMAURL-" + index + ":" + hash;
resetFavicon();
} else {
savedHash = "PMAURL-" + index + ":" + hash;
}
}
/**
* Start initialisation
*/
if (window.location.hash.substring(0, 8) == '#PMAURL-') {
// We have a valid hash, let's redirect the user
// to the page that it's pointing to
var colon_position = window.location.hash.indexOf(':');
var questionmark_position = window.location.hash.indexOf('?');
if (colon_position != -1 && questionmark_position != -1 && colon_position < questionmark_position) {
var hash_url = window.location.hash.substring(colon_position + 1, questionmark_position);
if (PMA_gotoWhitelist.indexOf(hash_url) != -1) {
window.location = window.location.hash.substring(
colon_position + 1
);
}
}
} else {
// We don't have a valid hash, so we'll set it up
// when the page finishes loading
jQuery(function () {
/* Check if we should set URL */
if (savedHash !== "") {
window.location.hash = savedHash;
savedHash = "";
resetFavicon();
}
// Indicate that we're done initialising
ready = true;
});
}
/**
* Register an event handler for when the url hash changes
*/
jQuery(function () {
jQuery(window).hashchange(function () {
if (userChange === false) {
// Ignore internally triggered hash changes
userChange = true;
} else if (/^#PMAURL-\d+:/.test(window.location.hash)) {
// Change page if the hash changed was triggered by a user action
var index = window.location.hash.substring(
8, window.location.hash.indexOf(':')
);
PMA_MicroHistory.navigate(index);
}
});
});
/**
* Publicly exposes a reference to the otherwise private setUrlHash function
*/
return setUrlHash;
})(jQuery, window);

View File

@ -68,11 +68,8 @@ function loadChildNodes(isNode, $expandElem, callback) {
})
.slideDown('slow');
}
if (data._debug){
$('#session_debug').replaceWith(data._debug);
}
if (data._errors) {
$errors = $(data._errors);
var $errors = $(data._errors);
if ($errors.children().length > 0) {
$('#pma_errors').replaceWith(data._errors);
}
@ -86,7 +83,7 @@ function loadChildNodes(isNode, $expandElem, callback) {
} else {
var $throbber = $expandElem.find('img.throbber');
$throbber.hide();
$icon = $expandElem.find('img.ic_b_plus');
var $icon = $expandElem.find('img.ic_b_plus');
$icon.show();
PMA_ajaxShowMessage(data.error, false);
}
@ -122,7 +119,7 @@ function collapseTreeNode($expandElem) {
*/
function traverseNavigationForPaths() {
var params = {
pos: $('#pma_navigation_tree div.dbselector select').val()
pos: $('#pma_navigation_tree').find('div.dbselector select').val()
};
if ($('#navi_db_select').length) {
return params;
@ -204,7 +201,7 @@ $(function () {
// reload icon object
var $icon = $(this).find('img');
// source of the hidden throbber icon
var icon_throbber_src = $('#pma_navigation .throbber').attr('src');
var icon_throbber_src = $('#pma_navigation').find('.throbber').attr('src');
// source of the reload icon
var icon_reload_src = $icon.attr('src');
// replace the source of the reload icon with the one for throbber
@ -217,6 +214,10 @@ $(function () {
});
$(document).on("change", '#navi_db_select', function (event) {
if (! $(this).val()) {
PMA_commonParams.set('db', '');
PMA_reloadNavigation();
}
$(this).closest('form').trigger('submit');
});
@ -226,7 +227,7 @@ $(function () {
*/
$(document).on('click', '#pma_navigation_collapse', function (event) {
event.preventDefault();
$('#pma_navigation_tree a.expander').each(function() {
$('#pma_navigation_tree').find('a.expander').each(function() {
var $icon = $(this).find('img');
if ($icon.is('.ic_b_minus')) {
$(this).click();
@ -347,13 +348,12 @@ $(function () {
dialog.editorDialog(1, $(this));
});
/** Execute Routines */
/** Edit Routines, Triggers or Events */
$(document).on('click', 'li.procedure > a.ajax, li.function > a.ajax', function (event) {
event.preventDefault();
var dialog = new RTE.object('routine');
dialog.executeDialog($(this));
dialog.editorDialog(0, $(this));
});
/** Edit Triggers and Events */
$(document).on('click', 'li.trigger > a.ajax', function (event) {
event.preventDefault();
var dialog = new RTE.object('trigger');
@ -365,15 +365,16 @@ $(function () {
dialog.editorDialog(0, $(this));
});
/** Edit Routines */
/** Execute Routines */
$(document).on('click', 'li.procedure div a.ajax img,' +
' li.function div a.ajax img', function (event) {
event.preventDefault();
var dialog = new RTE.object('routine');
dialog.editorDialog(0, $(this).parent());
dialog.executeDialog($(this).parent());
});
/** Export Triggers and Events */
$(document).on('click', 'li.trigger div:eq(1) a.ajax img, li.event div:eq(1) a.ajax img', function (event) {
$(document).on('click', 'li.trigger div:eq(1) a.ajax img,' +
' li.event div:eq(1) a.ajax img', function (event) {
event.preventDefault();
var dialog = new RTE.object();
dialog.exportDialog($(this).parent());
@ -487,7 +488,7 @@ $(function () {
cache: false,
type: 'POST',
data: {
favorite_tables: (isStorageSupported('localStorage'))
favorite_tables: (isStorageSupported('localStorage') && typeof window.localStorage.favorite_tables !== 'undefined')
? window.localStorage.favorite_tables
: ''
},
@ -519,8 +520,8 @@ $(function () {
storage.removeItem('navTreePaths');
});
// Initialize if no previous state is defined
if ($('#pma_navigation_tree_content').length
&& typeof storage.navTreePaths === 'undefined'
if ($('#pma_navigation_tree_content').length &&
typeof storage.navTreePaths === 'undefined'
) {
navTreeStateUpdate();
} else if (PMA_commonParams.get('server') === storage.server &&
@ -578,7 +579,7 @@ function expandTreeNode($expandElem, callback) {
}
$children.promise().done(navTreeStateUpdate);
} else {
var $throbber = $('#pma_navigation .throbber')
var $throbber = $('#pma_navigation').find('.throbber')
.first()
.clone()
.css({visibility: 'visible', display: 'block'})
@ -648,9 +649,27 @@ function PMA_showCurrentNavigation() {
.removeClass('selected');
if (db) {
var $dbItem = findLoadedItem(
$('#pma_navigation_tree > div'), db, 'database', !table
$('#pma_navigation_tree').find('> div'), db, 'database', !table
);
if ($dbItem) {
if ($('#navi_db_select').length &&
$('option:selected', $('#navi_db_select')).length
) {
if (! PMA_selectCurrentDb()) {
return;
}
// If loaded database in navigation is not same as current one
if ($('#pma_navigation_tree_content').find('span.loaded_db:first').text()
!== $('#navi_db_select').val()
) {
loadChildNodes(false, $('option:selected', $('#navi_db_select')), function (data) {
handleTableOrDb(table, $('#pma_navigation_tree_content'));
var $children = $('#pma_navigation_tree_content').children('div.list_container');
$children.promise().done(navTreeStateUpdate);
});
} else {
handleTableOrDb(table, $('#pma_navigation_tree_content'));
}
} else if ($dbItem) {
var $expander = $dbItem.children('div:first').children('a.expander');
// if not loaded or loaded but collapsed
if (! $expander.hasClass('loaded') ||
@ -662,25 +681,9 @@ function PMA_showCurrentNavigation() {
} else {
handleTableOrDb(table, $dbItem);
}
} else if ($('#navi_db_select').length
&& $('option:selected', $('#navi_db_select')).length
) {
if (! PMA_selectCurrentDb()) {
return;
}
// If loaded database in navigation is not same as current one
if ( $('#pma_navigation_tree_content span.loaded_db:first').text()
!== $('#navi_db_select').val()
) {
loadChildNodes(false, $('option:selected', $('#navi_db_select')), function (data) {
handleTableOrDb(table, $('#pma_navigation_tree_content'));
var $children = $('#pma_navigation_tree_content').children('div.list_container');
$children.promise().done(navTreeStateUpdate);
});
} else {
handleTableOrDb(table, $('#pma_navigation_tree_content'));
}
}
} else if ($('#navi_db_select').length && $('#navi_db_select').val()) {
$('#navi_db_select').val('').hide().trigger('change');
}
PMA_showFullName($('#pma_navigation_tree'));
@ -725,7 +728,7 @@ function PMA_showCurrentNavigation() {
}
// taverse up and expand and parent navigation groups
$li.parents('.navGroup').each(function () {
$cont = $(this).children('div.list_container');
var $cont = $(this).children('div.list_container');
if (! $cont.is(':visible')) {
$(this)
.children('div:first')
@ -769,7 +772,7 @@ function PMA_showCurrentNavigation() {
.children('div:first')
.children('a.expander');
if (! $expander.hasClass('loaded')) {
loadAndShowTableOrView($expander, $containers[index], itemName);
loadAndShowTableOrView($expander, $containers[index], itemName);
}
});
// else if no subContainers
@ -778,7 +781,7 @@ function PMA_showCurrentNavigation() {
.children('div:first')
.children('a.expander');
if (! $expander.hasClass('loaded')) {
loadAndShowTableOrView($expander, $dbItem, itemName);
loadAndShowTableOrView($expander, $dbItem, itemName);
}
}
}
@ -819,6 +822,46 @@ function PMA_showCurrentNavigation() {
}
}
/**
* Disable navigation panel settings
*
* @return void
*/
function PMA_disableNaviSettings() {
$('#pma_navigation_settings_icon').addClass('hide');
$('#pma_navigation_settings').remove();
}
/**
* Ensure that navigation panel settings is properly setup.
* If not, set it up
*
* @return void
*/
function PMA_ensureNaviSettings(selflink) {
$('#pma_navigation_settings_icon').removeClass('hide');
if (!$('#pma_navigation_settings').length) {
var params = {
getNaviSettings: true
};
var url = $('#pma_navigation').find('a.navigation_url').attr('href');
$.post(url, params, function (data) {
if (typeof data !== 'undefined' && data.success) {
$('#pma_navi_settings_container').html(data.message);
setupRestoreField();
setupValidation();
setupConfigTabs();
$('#pma_navigation_settings').find('form').attr('action', selflink);
} else {
PMA_ajaxShowMessage(data.error);
}
});
} else {
$('#pma_navigation_settings').find('form').attr('action', selflink);
}
}
/**
* Reloads the whole navigation tree while preserving its state
*
@ -829,7 +872,8 @@ function PMA_showCurrentNavigation() {
*/
function PMA_reloadNavigation(callback, paths) {
var params = {
reload: true
reload: true,
no_debug: true
};
paths = paths || traverseNavigationForPaths();
$.extend(params, paths);
@ -862,13 +906,19 @@ function PMA_reloadNavigation(callback, paths) {
}
function PMA_selectCurrentDb() {
if ($('#navi_db_select').length) {
$('#navi_db_select').val(PMA_commonParams.get('db'));
if ($('#navi_db_select').val() !== PMA_commonParams.get('db')) {
return false;
}
return true;
var $naviDbSelect = $('#navi_db_select');
if (!$naviDbSelect.length) {
return false;
}
if (PMA_commonParams.get('db')) { // db selected
$naviDbSelect.show();
}
$naviDbSelect.val(PMA_commonParams.get('db'));
return $naviDbSelect.val() === PMA_commonParams.get('db');
}
/**

View File

@ -13,6 +13,7 @@
var normalizeto = '1nf';
var primary_key;
var data_parsed = null;
function appendHtmlColumnsList()
{
$.get(
@ -45,21 +46,21 @@ function goTo3NFStep1(newTables)
"tables": newTables,
"step": '3.1'
}, function(data) {
$("#page_content h3").html(PMA_messages.str3NFNormalization);
$("#mainContent legend").html(data.legendText);
$("#mainContent h4").html(data.headText);
$("#mainContent p").html(data.subText);
$("#mainContent #extra").html(data.extra);
$("#extra form").each(function() {
form_id = $(this).attr('id');
colname = $(this).data('colname');
$("#"+form_id+" input[value='"+colname+"']").next().remove();
$("#"+form_id+" input[value='"+colname+"']").remove();
$("#page_content").find("h3").html(PMA_messages.str3NFNormalization);
$("#mainContent").find("legend").html(data.legendText);
$("#mainContent").find("h4").html(data.headText);
$("#mainContent").find("p").html(data.subText);
$("#mainContent").find("#extra").html(data.extra);
$("#extra").find("form").each(function() {
var form_id = $(this).attr('id');
var colname = $(this).data('colname');
$("#" + form_id + " input[value='" + colname + "']").next().remove();
$("#" + form_id + " input[value='" + colname + "']").remove();
});
$("#mainContent #newCols").html('');
$("#mainContent").find("#newCols").html('');
$('.tblFooters').html('');
if (data.subText !== "") {
$('.tblFooters').html('<input type="button" onClick="processDependencies(\'\', true);" value="'+PMA_messages.strDone+'"/>');
$('.tblFooters').html('<input type="button" onClick="processDependencies(\'\', true);" value="' + PMA_messages.strDone + '"/>');
}
}
);
@ -81,7 +82,7 @@ function goTo2NFStep1() {
$("#mainContent #extra").html(data.extra);
$("#mainContent #newCols").html('');
if (data.subText !== '') {
$('.tblFooters').html('<input type="submit" value="'+PMA_messages.strDone+'" onclick="processDependencies(\''+data.primary_key+'\');">');
$('.tblFooters').html('<input type="submit" value="' + PMA_messages.strDone + '" onclick="processDependencies(\'' + data.primary_key + '\');">');
} else {
if (normalizeto === '3nf') {
$("#mainContent #newCols").html(PMA_messages.strToNextStep);
@ -127,7 +128,7 @@ function goToStep4()
$("#mainContent #newCols").html('');
$('.tblFooters').html('');
for(var pk in primary_key) {
$("#extra input[value='"+primary_key[pk]+"']").attr("disabled","disabled");
$("#extra input[value='" + primary_key[pk] + "']").attr("disabled","disabled");
}
}
);
@ -152,7 +153,7 @@ function goToStep3()
$('.tblFooters').html('');
primary_key = $.parseJSON(data.primary_key);
for(var pk in primary_key) {
$("#extra input[value='"+primary_key[pk]+"']").attr("disabled","disabled");
$("#extra input[value='" + primary_key[pk] + "']").attr("disabled","disabled");
}
}
);
@ -198,7 +199,7 @@ function goTo2NFFinish(pd)
{
var tables = {};
for (var dependson in pd) {
tables[dependson] = $('#extra input[name="'+dependson+'"]').val();
tables[dependson] = $('#extra input[name="' + dependson + '"]').val();
}
datastring = {"token": PMA_commonParams.get('token'),
"ajax_request": true,
@ -240,7 +241,7 @@ function goTo3NFFinish(newTables)
{
for (var table in newTables) {
for (var newtbl in newTables[table]) {
updatedname = $('#extra input[name="'+newtbl+'"]').val();
var updatedname = $('#extra input[name="' + newtbl + '"]').val();
newTables[table][updatedname] = newTables[table][newtbl];
if (updatedname !== newtbl) {
delete newTables[table][newtbl];
@ -279,7 +280,7 @@ var backup = '';
function goTo2NFStep2(pd, primary_key)
{
$("#newCols").html('');
$("#mainContent legend").html(PMA_messages.strStep+' 2.2 '+PMA_messages.strConfirmPd);
$("#mainContent legend").html(PMA_messages.strStep + ' 2.2 ' + PMA_messages.strConfirmPd);
$("#mainContent h4").html(PMA_messages.strSelectedPd);
$("#mainContent p").html(PMA_messages.strPdHintNote);
var extra = '<div class="dependencies_box">';
@ -287,11 +288,11 @@ function goTo2NFStep2(pd, primary_key)
for (var dependson in pd) {
if (dependson !== primary_key) {
pdFound = true;
extra += '<p class="displayblock desc">'+escapeHtml(dependson) +" -> "+escapeHtml(pd[dependson].toString())+'</p>';
extra += '<p class="displayblock desc">' + escapeHtml(dependson) + " -> " + escapeHtml(pd[dependson].toString()) + '</p>';
}
}
if(!pdFound) {
extra += '<p class="displayblock desc">'+PMA_messages.strNoPdSelected+'</p>';
extra += '<p class="displayblock desc">' + PMA_messages.strNoPdSelected + '</p>';
extra += '</div>';
} else {
extra += '</div>';
@ -316,7 +317,7 @@ function goTo2NFStep2(pd, primary_key)
});
}
$("#mainContent #extra").html(extra);
$('.tblFooters').html('<input type="button" value="'+PMA_messages.strBack+'" id="backEditPd"/><input type="button" id="goTo2NFFinish" value="'+PMA_messages.strGo+'"/>');
$('.tblFooters').html('<input type="button" value="' + PMA_messages.strBack + '" id="backEditPd"/><input type="button" id="goTo2NFFinish" value="' + PMA_messages.strGo + '"/>');
$("#goTo2NFFinish").click(function(){
goTo2NFFinish(pd);
});
@ -325,7 +326,7 @@ function goTo2NFStep2(pd, primary_key)
function goTo3NFStep2(pd, tablesTds)
{
$("#newCols").html('');
$("#mainContent legend").html(PMA_messages.strStep+' 3.2 '+PMA_messages.strConfirmTd);
$("#mainContent legend").html(PMA_messages.strStep + ' 3.2 ' + PMA_messages.strConfirmTd);
$("#mainContent h4").html(PMA_messages.strSelectedTd);
$("#mainContent p").html(PMA_messages.strPdHintNote);
var extra = '<div class="dependencies_box">';
@ -335,12 +336,12 @@ function goTo3NFStep2(pd, tablesTds)
dependson = tablesTds[table][i];
if (dependson !== '' && dependson !== table) {
pdFound = true;
extra += '<p class="displayblock desc">'+escapeHtml(dependson) +" -> "+escapeHtml(pd[dependson].toString())+'</p>';
extra += '<p class="displayblock desc">' + escapeHtml(dependson) + " -> " + escapeHtml(pd[dependson].toString()) + '</p>';
}
}
}
if(!pdFound) {
extra += '<p class="displayblock desc">'+PMA_messages.strNoTdSelected+'</p>';
extra += '<p class="displayblock desc">' + PMA_messages.strNoTdSelected + '</p>';
extra += '</div>';
} else {
extra += '</div>';
@ -366,7 +367,7 @@ function goTo3NFStep2(pd, tablesTds)
});
}
$("#mainContent #extra").html(extra);
$('.tblFooters').html('<input type="button" value="'+PMA_messages.strBack+'" id="backEditPd"/><input type="button" id="goTo3NFFinish" value="'+PMA_messages.strGo+'"/>');
$('.tblFooters').html('<input type="button" value="' + PMA_messages.strBack + '" id="backEditPd"/><input type="button" id="goTo3NFFinish" value="' + PMA_messages.strGo + '"/>');
$("#goTo3NFFinish").click(function(){
if (!pdFound) {
goTo3NFFinish([]);
@ -382,6 +383,7 @@ function processDependencies(primary_key, isTransitive)
var dependsOn;
pd[primary_key] = [];
$("#extra form").each(function() {
var tblname;
if (isTransitive === true) {
tblname = $(this).data('tablename');
primary_key = tblname;
@ -390,11 +392,11 @@ function processDependencies(primary_key, isTransitive)
}
tablesTds[tblname].push(primary_key);
}
form_id = $(this).attr('id');
$('#'+form_id+' input[type=checkbox]:not(:checked)').removeAttr('checked');
var form_id = $(this).attr('id');
$('#' + form_id + ' input[type=checkbox]:not(:checked)').removeAttr('checked');
dependsOn = '';
$('#'+form_id+' input[type=checkbox]:checked').each(function(){
dependsOn += $(this).val()+', ';
$('#' + form_id + ' input[type=checkbox]:checked').each(function(){
dependsOn += $(this).val() + ', ';
$(this).attr("checked","checked");
});
if (dependsOn === '') {
@ -425,8 +427,8 @@ function processDependencies(primary_key, isTransitive)
}
function moveRepeatingGroup(repeatingCols) {
newTable = $("input[name=repeatGroupTable]").val();
newColumn = $("input[name=repeatGroupColumn]").val();
var newTable = $("input[name=repeatGroupTable]").val();
var newColumn = $("input[name=repeatGroupColumn]").val();
if (!newTable) {
$("input[name=repeatGroupTable]").focus();
return false;
@ -506,8 +508,8 @@ AJAX.registerOnload('normalization.js', function() {
$('#newCols').html(data.message);
$('.default_value').hide();
$('.enum_notice').hide();
$('.tblFooters').html("<input type='submit' id='saveSplit' value='"+PMA_messages.strSave+"'/>" +
"<input type='submit' id='cancelSplit' value='"+PMA_messages.strCancel+"' "+
$('.tblFooters').html("<input type='submit' id='saveSplit' value='" + PMA_messages.strSave + "'/>" +
"<input type='submit' id='cancelSplit' value='" + PMA_messages.strCancel + "' " +
"onclick=\"$('#newCols').html('');$(this).parent().html('')\"/>");
}
}
@ -532,6 +534,7 @@ AJAX.registerOnload('normalization.js', function() {
"db": PMA_commonParams.get('db'),
"table": PMA_commonParams.get('table'),
"dropped_column": selectedCol,
"purge" : 1,
"sql_query": 'ALTER TABLE `' + PMA_commonParams.get('table') + '` DROP `' + selectedCol + '`;',
"is_js_confirmed": 1
},
@ -567,8 +570,8 @@ AJAX.registerOnload('normalization.js', function() {
$('#newCols').html(data.message);
$('.default_value').hide();
$('.enum_notice').hide();
$('.tblFooters').html("<input type='submit' id='saveNewPrimary' value='"+PMA_messages.strSave+"'/>" +
"<input type='submit' id='cancelSplit' value='"+PMA_messages.strCancel+"' "+
$('.tblFooters').html("<input type='submit' id='saveNewPrimary' value='" + PMA_messages.strSave + "'/>" +
"<input type='submit' id='cancelSplit' value='" + PMA_messages.strCancel + "' " +
"onclick=\"$('#newCols').html('');$(this).parent().html('')\"/>");
} else {
PMA_ajaxShowMessage(data.error, false);
@ -578,7 +581,7 @@ AJAX.registerOnload('normalization.js', function() {
return false;
});
$(".tblFooters").on("click", "#saveNewPrimary", function() {
datastring = $('#newCols :input').serialize();
var datastring = $('#newCols :input').serialize();
datastring += "&field_key[0]=primary_0&ajax_request=1&do_save_data=1&field_where=last";
$.post("tbl_addfield.php", datastring, function(data) {
if (data.success === true) {
@ -627,15 +630,15 @@ AJAX.registerOnload('normalization.js', function() {
});
if (repeatingCols !== '') {
newColName = $("#extra input[type=checkbox]:checked:first").val();
var newColName = $("#extra input[type=checkbox]:checked:first").val();
repeatingCols = repeatingCols.slice(0, -2);
confirmStr = PMA_sprintf(PMA_messages.strMoveRepeatingGroup, escapeHtml(repeatingCols), escapeHtml(PMA_commonParams.get('table')));
confirmStr += '<input type="text" name="repeatGroupTable" placeholder="'+PMA_messages.strNewTablePlaceholder+'"/>'+
'( '+escapeHtml(primary_key.toString())+', <input type="text" name="repeatGroupColumn" placeholder="'+PMA_messages.strNewColumnPlaceholder+'" value="'+escapeHtml(newColName)+'">)'+
var confirmStr = PMA_sprintf(PMA_messages.strMoveRepeatingGroup, escapeHtml(repeatingCols), escapeHtml(PMA_commonParams.get('table')));
confirmStr += '<input type="text" name="repeatGroupTable" placeholder="' + PMA_messages.strNewTablePlaceholder + '"/>' +
'( ' + escapeHtml(primary_key.toString()) + ', <input type="text" name="repeatGroupColumn" placeholder="' + PMA_messages.strNewColumnPlaceholder + '" value="' + escapeHtml(newColName) + '">)' +
'</ol>';
$("#newCols").html(confirmStr);
$('.tblFooters').html('<input type="submit" value="'+PMA_messages.strCancel+'" onclick="$(\'#newCols\').html(\'\');$(\'#extra input[type=checkbox]\').removeAttr(\'checked\')"/>'+
'<input type="submit" value="'+PMA_messages.strGo+'" onclick="moveRepeatingGroup(\''+repeatingCols+'\')"/>');
$('.tblFooters').html('<input type="submit" value="' + PMA_messages.strCancel + '" onclick="$(\'#newCols\').html(\'\');$(\'#extra input[type=checkbox]\').removeAttr(\'checked\')"/>' +
'<input type="submit" value="' + PMA_messages.strGo + '" onclick="moveRepeatingGroup(\'' + repeatingCols + '\')"/>');
}
});
$("#mainContent p").on("click", "#createPrimaryKey", function(event) {
@ -665,19 +668,19 @@ AJAX.registerOnload('normalization.js', function() {
});
$("#mainContent").on("click", "#showPossiblePd", function(){
if($(this).hasClass('hideList')) {
$(this).html('+ '+PMA_messages.strShowPossiblePd);
$(this).html('+ ' + PMA_messages.strShowPossiblePd);
$(this).removeClass('hideList');
$("#newCols").slideToggle("slow");
return false;
}
if($("#newCols").html() !== '') {
$("#showPossiblePd").html('- '+PMA_messages.strHidePd);
$("#showPossiblePd").html('- ' + PMA_messages.strHidePd);
$("#showPossiblePd").addClass('hideList');
$("#newCols").slideToggle("slow");
return false;
}
$("#newCols").insertAfter("#mainContent h4");
$("#newCols").html('<div class="center">'+PMA_messages.strLoading+'<br/>'+PMA_messages.strWaitForPd+'</div>');
$("#newCols").html('<div class="center">' + PMA_messages.strLoading + '<br/>' + PMA_messages.strWaitForPd + '</div>');
$.post(
"normalization.php",
{
@ -687,7 +690,7 @@ AJAX.registerOnload('normalization.js', function() {
"table": PMA_commonParams.get('table'),
"findPdl": true
}, function(data) {
$("#showPossiblePd").html('- '+PMA_messages.strHidePd);
$("#showPossiblePd").html('- ' + PMA_messages.strHidePd);
$("#showPossiblePd").addClass('hideList');
$("#newCols").html(data.message);
});
@ -698,9 +701,9 @@ AJAX.registerOnload('normalization.js', function() {
var strColsRight = $(this).next().next().html();
var colsRight = strColsRight.split(',');
for (var i in colsRight) {
$('form[data-colname="'+colsRight[i].trim()+'"] input[type="checkbox"]').prop('checked', false);
$('form[data-colname="' + colsRight[i].trim() + '"] input[type="checkbox"]').prop('checked', false);
for (var j in colsLeft) {
$('form[data-colname="'+colsRight[i].trim()+'"] input[value="'+colsLeft[j].trim()+'"]').prop('checked', true);
$('form[data-colname="' + colsRight[i].trim() + '"] input[value="' + colsLeft[j].trim() + '"]').prop('checked', true);
}
}
});

59
js/page_settings.js Normal file
View File

@ -0,0 +1,59 @@
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* @fileoverview function used for page-related settings
* @name Page-related settings
*
* @requires jQuery
* @requires jQueryUI
* @required js/functions.js
*/
function showSettings(selector) {
var buttons = {};
buttons[PMA_messages.strApply] = function() {
$('.config-form').submit();
};
buttons[PMA_messages.strCancel] = function () {
$(this).dialog('close');
};
// Keeping a clone to restore in case the user cancels the operation
var $clone = $(selector + ' .page_settings').clone(true);
$(selector)
.dialog({
title: PMA_messages.strPageSettings,
width: 700,
minHeight: 250,
modal: true,
open: function() {
$(this).dialog('option', 'maxHeight', $(window).height() - $(this).offset().top);
},
close: function() {
$(selector + ' .page_settings').replaceWith($clone);
},
buttons: buttons
});
}
function showPageSettings() {
showSettings('#page_settings_modal');
}
function showNaviSettings() {
showSettings('#pma_navigation_settings');
}
AJAX.registerTeardown('page_settings.js', function () {
$('#page_settings_icon').css('display', 'none');
$('#page_settings_icon').unbind('click');
$('#pma_navigation_settings_icon').unbind('click');
});
AJAX.registerOnload('page_settings.js', function () {
if ($('#page_settings_modal').length) {
$('#page_settings_icon').css('display', 'inline');
$('#page_settings_icon').bind('click', showPageSettings);
}
$('#pma_navigation_settings_icon').bind('click', showNaviSettings);
});

View File

@ -91,19 +91,27 @@ function Delete_page(page_id, callback)
function Load_first_page(db, callback)
{
DesignerOfflineDB.loadAllObjects('pdf_pages', function (pages) {
var firstPage = null;
for (var i = 0; i < pages.length; i++) {
var page = pages[i];
if (page.db_name == db) {
callback(page);
return;
// give preference to a page having same name as the db
if (page.page_descr == db) {
callback(page);
return;
}
if (firstPage == null) {
firstPage = page;
}
}
}
callback(firstPage);
});
}
function Show_new_page_tables(check)
{
var all_tables = $("#id_scroll_tab td input:checkbox");
var all_tables = $("#id_scroll_tab").find("td input:checkbox");
all_tables.prop('checked', check);
for (var tab = 0; tab < all_tables.length; tab++) {
var input = all_tables[tab];
@ -115,7 +123,7 @@ function Show_new_page_tables(check)
}
}
selected_page = -1;
$("#name-panel #page_name").text(PMA_messages.strUntitled);
$("#page_name").text(PMA_messages.strUntitled);
MarkUnsaved();
}
@ -123,7 +131,7 @@ function Load_HTML_for_page(page_id)
{
Show_new_page_tables(false);
Load_page_objects(page_id, function (page, tbl_cords) {
$("#name-panel #page_name").text(page.page_descr);
$("#name-panel").find("#page_name").text(page.page_descr);
MarkSaved();
for (var t = 0; t < tbl_cords.length; t++) {
var tb_id = db + '.' + tbl_cords[t].table_name;

View File

@ -10,22 +10,7 @@
var history_array = []; // Global array to store history objects
var select_field = []; // Global array to store informaation for columns which are used in select clause
var g_index;
/**
* function for panel, hides and shows toggle_container <div>,which is for history elements uses {@link JQuery}.
*
* @param index has value 1 or 0,decides wheter to hide toggle_container on load.
**/
function panel(index)
{
if (!index) {
$(".toggle_container").hide();
}
$("h2.tiger").click(function () {
$(this).toggleClass("active").next().slideToggle("slow");
});
}
var vqb_editor = null;
/**
* To display details of objects(where,rename,Having,aggregate,groupby,orderby,having)
@ -51,7 +36,7 @@ function detail(index)
str = 'GroupBy ' + history_array[index].get_column_name();
}
if (type == "OrderBy") {
str = 'OrderBy ' + history_array[index].get_column_name();
str = 'OrderBy ' + history_array[index].get_column_name() + ' ' + history_array[index].get_obj().get_order();
}
if (type == "Having") {
str = 'Having ';
@ -97,7 +82,7 @@ function display(init, finit)
str = ''; // string to store Html code for history tab
for (i = 0; i < history_array.length; i++) {
temp = history_array[i].get_tab(); //+ '.' + history_array[i].get_obj_no(); for Self JOIN
str += '<h2 class="tiger"><a href="#">' + temp + '</a></h2>';
str += '<h3 class="tiger"><a href="#">' + temp + '</a></h3>';
str += '<div class="toggle_container">\n';
while ((history_array[i].get_tab()) == temp) { //+ '.' + history_array[i].get_obj_no()) == temp) {
str += '<div class="block"> <table width ="250">';
@ -107,20 +92,27 @@ function display(init, finit)
} else {
str += '<img src="' + pmaThemeImage + 'pmd/and_icon.png" onclick="and_or(' + i + ')" title="AND"/></td>';
}
str += '<td style="padding-left: 5px;" class="right">' + PMA_getImage('b_sbrowse.png', 'column name') + '</td><td width="175" style="padding-left: 5px">' + history_array[i].get_column_name();
str += '<td style="padding-left: 5px;" class="right">' + PMA_getImage('b_sbrowse.png', 'column name') + '</td>' +
'<td width="175" style="padding-left: 5px">' + history_array[i].get_column_name() + '<td>';
if (history_array[i].get_type() == "GroupBy" || history_array[i].get_type() == "OrderBy") {
str += '</td><td class="center">' + PMA_getImage('s_info.png', detail(i)) + '<td title="' + detail(i) + '">' + history_array[i].get_type() + '</td></td><td onmouseover="this.className=\'history_table\';" onmouseout="this.className=\'history_table2\'" onclick=history_delete(' + i + ')>' + PMA_getImage('b_drop.png', 'Delete') + '</td></tr></thead>';
str += '<td class="center">' + PMA_getImage('s_info.png', detail(i)) + '</td>' +
'<td title="' + detail(i) + '">' + history_array[i].get_type() + '</td>' +
'<td onmouseover="this.className=\'history_table\';" onmouseout="this.className=\'history_table2\'" onclick=history_delete(' + i + ')>' + PMA_getImage('b_drop.png', PMA_messages.strDelete) + '</td>';
} else {
str += '</td><td class="center">' + PMA_getImage('s_info.png', detail(i)) + '</td><td title="' + detail(i) + '">' + history_array[i].get_type() + '</td><td <td onmouseover="this.className=\'history_table\';" onmouseout="this.className=\'history_table2\'" onclick=history_edit(' + i + ')>' + PMA_getImage('b_edit.png', PMA_messages.strEdit) + '</td><td onmouseover="this.className=\'history_table\';" onmouseout="this.className=\'history_table2\'" onclick=history_delete(' + i + ')><img src="themes/original/img/b_drop.png" title="Delete"></td></tr></thead>';
str += '<td class="center">' + PMA_getImage('s_info.png', detail(i)) + '</td>' +
'<td title="' + detail(i) + '">' + history_array[i].get_type() + '</td>' +
'<td onmouseover="this.className=\'history_table\';" onmouseout="this.className=\'history_table2\'" onclick=history_edit(' + i + ')>' + PMA_getImage('b_edit.png', PMA_messages.strEdit) + '</td>' +
'<td onmouseover="this.className=\'history_table\';" onmouseout="this.className=\'history_table2\'" onclick=history_delete(' + i + ')>' + PMA_getImage('b_drop.png', PMA_messages.strDelete) + '</td>';
}
str += '</tr></thead>';
i++;
if (i >= history_array.length) {
break;
}
str += '</table></div><br/>';
str += '</table></div>';
}
i--;
str += '</div><br/>';
str += '</div>';
}
return str;
}
@ -142,7 +134,7 @@ function and_or(index)
}
var existingDiv = document.getElementById('ab');
existingDiv.innerHTML = display(0, 0);
panel(1);
$('#ab').accordion("refresh");
}
/**
@ -163,7 +155,7 @@ function history_delete(index)
history_array.splice(index, 1);
var existingDiv = document.getElementById('ab');
existingDiv.innerHTML = display(0, 0);
panel(1);
$('#ab').accordion("refresh");
}
/**
@ -258,7 +250,7 @@ function edit(type)
}
var existingDiv = document.getElementById('ab');
existingDiv.innerHTML = display(0, 0);
panel(1);
$('#ab').accordion("refresh");
}
/**
@ -272,7 +264,7 @@ function edit(type)
*
**/
function history(ncolumn_name, nobj, ntab, nobj_no, ntype)
function history_obj(ncolumn_name, nobj, ntab, nobj_no, ntype)
{
var and_or;
var obj;
@ -355,6 +347,21 @@ var where = function (nrelation_operator, nquery) {
this.setrelation_operator(nrelation_operator);
};
/**
* Orderby object closure
*
* @param norder order, ASC or DESC
*/
var orderby = function(norder) {
var order;
this.set_order = function(norder) {
order = norder;
};
this.get_order = function() {
return order;
};
this.set_order(norder);
};
/**
* Having object closure, makes an object with all information of where
@ -510,10 +517,10 @@ function query_groupby()
var str = "";
for (i = 0; i < history_array.length;i++) {
if (history_array[i].get_type() == "GroupBy") {
str += history_array[i].get_column_name() + ", ";
str += '`' + history_array[i].get_column_name() + "`, ";
}
}
str = str.substr(0, str.length - 1);
str = str.substr(0, str.length - 2);
return str;
}
@ -529,10 +536,10 @@ function query_having()
for (i = 0; i < history_array.length;i++) {
if (history_array[i].get_type() == "Having") {
if (history_array[i].get_obj().get_operator() != 'None') {
and += history_array[i].get_obj().get_operator() + "(" + history_array[i].get_column_name() + " ) " + history_array[i].get_obj().getrelation_operator();
and += history_array[i].get_obj().get_operator() + "(`" + history_array[i].get_column_name() + "`) " + history_array[i].get_obj().getrelation_operator();
and += " " + history_array[i].get_obj().getquery() + ", ";
} else {
and += history_array[i].get_column_name() + " " + history_array[i].get_obj().getrelation_operator() + " " + history_array[i].get_obj().getquery() + ", ";
and += "`" + history_array[i].get_column_name() + "` " + history_array[i].get_obj().getrelation_operator() + " " + history_array[i].get_obj().getquery() + ", ";
}
}
}
@ -555,9 +562,12 @@ function query_orderby()
var i;
var str = "";
for (i = 0; i < history_array.length;i++) {
if (history_array[i].get_type() == "OrderBy") { str += history_array[i].get_column_name() + " , "; }
if (history_array[i].get_type() == "OrderBy") {
str += "`" + history_array[i].get_column_name() + "` " +
history_array[i].get_obj().get_order() + ", ";
}
}
str = str.substr(0, str.length - 1);
str = str.substr(0, str.length - 2);
return str;
}
@ -575,10 +585,10 @@ function query_where()
for (i = 0; i < history_array.length;i++) {
if (history_array[i].get_type() == "Where") {
if (history_array[i].get_and_or() === 0) {
and += "( " + history_array[i].get_column_name() + " " + history_array[i].get_obj().getrelation_operator() + " " + history_array[i].get_obj().getquery() + ")";
and += "( `" + history_array[i].get_column_name() + "` " + history_array[i].get_obj().getrelation_operator() + " " + history_array[i].get_obj().getquery() + ")";
and += " AND ";
} else {
or += "( " + history_array[i].get_column_name() + " " + history_array[i].get_obj().getrelation_operator() + " " + history_array[i].get_obj().getquery() + ")";
or += "( `" + history_array[i].get_column_name() + "` " + history_array[i].get_obj().getrelation_operator() + " " + history_array[i].get_obj().getquery() + ")";
or += " OR ";
}
}
@ -623,26 +633,6 @@ function check_rename(id_this)
return "";
}
function gradient(id, level)
{
var box = document.getElementById(id);
box.style.opacity = level;
box.style.MozOpacity = level;
box.style.KhtmlOpacity = level;
box.style.filter = "alpha(opacity=" + level * 100 + ")";
box.style.display = "block";
}
function fadein(id)
{
var level = 0;
while (level <= 1) {
setTimeout("gradient('" + id + "'," + level + ")", (level * 1000) + 10);
level += 0.01;
}
}
/**
* This function builds from clause of query
* makes automatic joins.
@ -674,7 +664,7 @@ function query_from()
from_array = unique(from_array);
tab_left = from_array;
temp = tab_left.shift();
quer = temp;
quer = '`' + temp + '`';
tab_used.push(temp);
// if master table (key2) matches with tab used get all keys and check if tab_left matches
// after this check if master table (key2) matches with tab left then check if any foreign matches with master .
@ -688,7 +678,7 @@ function query_from()
parts1 = contr[K][key][key2][key3][0].split(".");
if (found(tab_left, parts1[1]) > 0) {
query += "\n" + 'LEFT JOIN ';
query += '`' + parts1[0] + '`.`' + parts1[1] + '` ON ';
query += '`' + parts1[1] + '` ON ';
query += '`' + parts[1] + '`.`' + key3 + '` = ';
query += '`' + parts1[1] + '`.`' + contr[K][key][key2][key3][1] + '` ';
t_tab_left.push(parts1[1]);
@ -712,7 +702,7 @@ function query_from()
parts1 = contr[K][key][key2][key3][0].split(".");
if (found(tab_used, parts1[1]) > 0) {
query += "\n" + 'LEFT JOIN ';
query += '`' + parts[0] + '`.`' + parts[1] + '` ON ';
query += '`' + parts[1] + '` ON ';
query += '`' + parts1[1] + '`.`' + contr[K][key][key2][key3][1] + '` = ';
query += '`' + parts[1] + '`.`' + key3 + '` ';
t_tab_left.push(parts[1]);
@ -752,46 +742,91 @@ function build_query(formtitle, fadin)
{
var q_select = "SELECT ";
var temp;
for (var i = 0;i < select_field.length; i++) {
temp = check_aggregate(select_field[i]);
if (temp !== "") {
q_select += temp;
temp = check_rename(select_field[i]);
q_select += temp + ",";
} else {
temp = check_rename(select_field[i]);
q_select += select_field[i] + temp + ",";
if (select_field.length > 0) {
for (var i = 0; i < select_field.length; i++) {
temp = check_aggregate(select_field[i]);
if (temp !== "") {
q_select += temp;
temp = check_rename(select_field[i]);
q_select += temp + ", ";
} else {
temp = check_rename(select_field[i]);
q_select += select_field[i] + temp + ", ";
}
}
}
q_select = q_select.substring(0, q_select.length - 1);
q_select += " FROM " + query_from();
if (query_where() !== "") {
q_select += "\n WHERE";
q_select += query_where();
}
if (query_groupby() !== "") { q_select += "\nGROUP BY " + query_groupby(); }
if (query_having() !== "") { q_select += "\nHAVING " + query_having(); }
if (query_orderby() !== "") { q_select += "\nORDER BY " + query_orderby(); }
var box = document.getElementById('box');
document.getElementById('filter').style.display = 'block';
var btitle = document.getElementById('boxtitle');
btitle.innerHTML = 'SELECT';//formtitle;
if (fadin) {
gradient("box", 0);
fadein("box");
q_select = q_select.substring(0, q_select.length - 2);
} else {
box.style.display = 'block';
q_select += "* ";
}
document.getElementById('textSqlquery').innerHTML = q_select;
}
function closebox()
{
document.getElementById('box').style.display = 'none';
document.getElementById('filter').style.display = 'none';
q_select += "\nFROM " + query_from();
var q_where = query_where();
if (q_where !== "") {
q_select += "\nWHERE " + q_where;
}
var q_groupby = query_groupby();
if (q_groupby !== "") {
q_select += "\nGROUP BY " + q_groupby;
}
var q_having = query_having();
if (q_having !== "") {
q_select += "\nHAVING " + q_having;
}
var q_orderby = query_orderby();
if (q_orderby !== "") {
q_select += "\nORDER BY " + q_orderby;
}
/**
* @var button_options Object containing options
* for jQueryUI dialog buttons
*/
var button_options = {};
button_options[PMA_messages.strClose] = function () {
$(this).dialog("close");
};
button_options[PMA_messages.strSubmit] = function () {
if (vqb_editor) {
var $elm = $ajaxDialog.find('textarea');
vqb_editor.save();
$elm.val(vqb_editor.getValue());
}
$('#vqb_form').submit();
};
var $ajaxDialog = $('#box').dialog({
appendTo: '#page_content',
width: 500,
buttons: button_options,
modal: true,
title: 'SELECT'
});
// Attach syntax highlighted editor to query dialog
/**
* @var $elm jQuery object containing the reference
* to the query textarea.
*/
var $elm = $ajaxDialog.find('textarea');
if (! vqb_editor) {
vqb_editor = PMA_getSQLEditor($elm);
}
if (vqb_editor) {
vqb_editor.setValue(q_select);
vqb_editor.focus();
} else {
$elm.val(q_select);
$elm.focus();
}
}
AJAX.registerTeardown('pmd/history.js', function () {
vqb_editor = null;
history_array = [];
select_field = [];
$("#ok_edit_rename").unbind('click');
$("#ok_edit_having").unbind('click');
$("#ok_edit_Aggr").unbind('click');
@ -811,4 +846,5 @@ AJAX.registerOnload('pmd/history.js', function () {
$("#ok_edit_where").click(function() {
edit('Where');
});
});
$('#ab').accordion({collapsible : true, active : 'none'});
});

View File

@ -16,10 +16,10 @@ if (! isCanvasSupported()) {
el.parentNode.replaceChild(newEl, el);
el = newEl;
el.getContext = function () {
if (this.cont) {
return this.cont;
if (! this.cont) {
this.cont = new PMD_2D(this);
}
return this.cont = new PMD_2D(this);
return this.cont;
};
el.style.width = el.attributes.width.nodeValue + "px";

View File

@ -3,7 +3,7 @@
* Initialises the data required to run PMD, then fires it up.
*/
var j_tabs, h_tabs, contr, server, db, token, selected_page, pmd_tables_enabled;
var j_tabs, h_tabs, contr, display_field, server, db, token, selected_page, pmd_tables_enabled;
AJAX.registerTeardown('pmd/init.js', function () {
$(".trigger").unbind('click');
@ -13,6 +13,7 @@ AJAX.registerOnload('pmd/init.js', function () {
$(".trigger").click(function () {
$(".panel").toggle("fast");
$(this).toggleClass("active");
$('#ab').accordion("refresh");
return false;
});
var tables_data = $.parseJSON($("#script_tables").html());

View File

@ -17,6 +17,8 @@ AJAX.registerTeardown('pmd/move.js', function () {
if ($.FullScreen.supported) {
$(document).unbind($.FullScreen.prefix + 'fullscreenchange');
}
$('#selflink').show();
});
AJAX.registerOnload('pmd/move.js', function () {
@ -26,15 +28,18 @@ AJAX.registerOnload('pmd/move.js', function () {
if (! $.FullScreen.isFullScreen()) {
$('#page_content').removeClass('content_fullscreen')
.css({'width': 'auto', 'height': 'auto'});
var $img = $('#toggleFullscreen img');
$img.attr('src', $img.data('enter'));
var $img = $('#toggleFullscreen').find('img');
var $span = $img.siblings('span');
$span.text($span.data('enter'));
$img.attr('src', $img.data('enter'))
.attr('title', $span.data('enter'));
}
});
} else {
$('#toggleFullscreen').hide();
}
$('#selflink').hide();
});
// Below is the function to bind onbeforeunload events with the content_frame as well as the top window.
@ -177,7 +182,7 @@ function MouseMove(e)
if (ON_grid) {
new_x = parseInt(new_x / grid_size) * grid_size;
new_y = parseInt(new_y / grid_size) * grid_size;
};
}
$cur_click.css('left', new_x + 'px');
$cur_click.css('top', new_y + 'px');
@ -190,14 +195,15 @@ function MouseMove(e)
if (menu_moved) {
delta_x = -delta_x;
}
var new_width = $('#layer_menu').width() + delta_x;
var $layer_menu = $('#layer_menu');
var new_width = $layer_menu.width() + delta_x;
if (new_width < 150) {
new_width = 150;
}
else {
dx = e.pageX;
}
$('#layer_menu').width(new_width);
$layer_menu.width(new_width);
}
if (ON_relation || ON_display_field) {
@ -244,6 +250,52 @@ function Osn_tab_pos()
osn_tab_height = parseInt(document.getElementById('osn_tab').style.height, 10);
}
function setDefaultValuesFromSavedState()
{
if ($('#angular_direct_button').attr('class') === 'M_butt') {
ON_angular_direct = 0;
} else {
ON_angular_direct = 1;
}
Angular_direct();
if ($('#grid_button').attr('class') === 'M_butt') {
ON_grid = 1;
} else {
ON_grid = 0;
}
Grid();
var $relLineInvert = $('#relLineInvert');
if ($relLineInvert.attr('class') === 'M_butt') {
show_relation_lines = false;
$relLineInvert.attr('class', 'M_butt');
} else {
show_relation_lines = true;
$relLineInvert.attr('class', 'M_butt_Selected_down');
}
Relation_lines_invert();
if ($('#pin_Text').attr('class') === 'M_butt_Selected_down') {
always_show_text = true;
Show_text();
} else {
always_show_text = false;
}
var $key_SB_all = $('#key_SB_all');
if ($key_SB_all.attr('class') === 'M_butt_Selected_down') {
$key_SB_all.click();
$key_SB_all.toggleClass('M_butt_Selected_down');
$key_SB_all.toggleClass('M_butt');
}
var $key_Left_Right = $('#key_Left_Right');
if ($key_Left_Right.attr('class') === 'M_butt_Selected_down') {
$key_Left_Right.click();
}
}
function Main()
{
@ -257,6 +309,7 @@ function Main()
Canvas_pos();
Small_tab_refresh();
Re_load();
setDefaultValuesFromSavedState();
id_hint = document.getElementById('pmd_hint');
if (isIE) {
General_scroll();
@ -374,8 +427,8 @@ function Re_load()
row_offset_top = 0;
tab_hide_button = document.getElementById('id_hide_tbody_' + contr[K][key][key2][key3][0]);
if (tab_hide_button.innerHTML == 'v') {
var toColumn = document.getElementById(contr[K][key][key2][key3][0]
+ '.' + contr[K][key][key2][key3][1]);
var toColumn = document.getElementById(contr[K][key][key2][key3][0] +
'.' + contr[K][key][key2][key3][1]);
if (toColumn) {
row_offset_top = toColumn.offsetTop;
} else {
@ -533,19 +586,24 @@ function Rect(x1, y1, w, h, color)
//--------------------------- FULLSCREEN -------------------------------------
function Toggle_fullscreen()
{
var $img = $('#toggleFullscreen img');
var value_sent = '';
var $img = $('#toggleFullscreen').find('img');
var $span = $img.siblings('span');
if (! $.FullScreen.isFullScreen()) {
$img.attr('src', $img.data('exit'))
.attr('title', $span.data('exit'));
$span.text($span.data('exit'));
$('#page_content')
.addClass('content_fullscreen')
.css({'width': screen.width - 5, 'height': screen.height - 5})
.requestFullScreen();
value_sent = 'on';
}
if ($.FullScreen.isFullScreen()) {
$.FullScreen.cancelFullScreen();
value_sent = 'off';
}
saveValueInConfig('full_screen', value_sent);
}
// ------------------------------ NEW ------------------------------------------
@ -728,7 +786,7 @@ function Edit_pages()
if (! pmd_tables_enabled) {
Create_page_list(db, function (options) {
$("#page_edit_dialog #selected_page").append(options);
$("#selected_page").append(options);
});
}
$('<div id="page_edit_dialog"></div>')
@ -808,7 +866,7 @@ function Delete_pages()
if (! pmd_tables_enabled) {
Create_page_list(db, function (options) {
$("#page_delete_dialog #selected_page").append(options);
$("#selected_page").append(options);
});
}
@ -907,7 +965,7 @@ function Save_as()
if (! pmd_tables_enabled) {
Create_page_list(db, function (options) {
$("#page_save_as_dialog #selected_page").append(options);
$("#selected_page").append(options);
});
}
@ -915,7 +973,7 @@ function Save_as()
.append(data.message)
.dialog({
appendTo: '#page_content',
title: "Save table coordinates",
title: PMA_messages.strSavePageAs,
width: 450,
modal: true,
buttons: button_options,
@ -1033,26 +1091,45 @@ function Load_page(page) {
function Grid()
{
var value_sent = '';
if (!ON_grid) {
ON_grid = 1;
value_sent = 'on';
document.getElementById('grid_button').className = 'M_butt_Selected_down';
} else {
document.getElementById('grid_button').className = 'M_butt';
ON_grid = 0;
value_sent = 'off';
}
saveValueInConfig('snap_to_grid', value_sent);
}
function Angular_direct()
{
var value_sent = '';
if (ON_angular_direct) {
ON_angular_direct = 0;
value_sent = 'angular';
document.getElementById('angular_direct_button').className = 'M_butt_Selected_down';
} else {
ON_angular_direct = 1;
value_sent = 'direct';
document.getElementById('angular_direct_button').className = 'M_butt';
}
saveValueInConfig('angular_direct', value_sent);
Re_load();
}
function saveValueInConfig(index_sent, value_sent) {
$.post('db_designer.php',
{operation: 'save_setting_value', index: index_sent, ajax_request: true, server: server, token: token, value: value_sent},
function (data) {
if (data.success === false) {
PMA_ajaxShowMessage(data.error, false);
}
});
}
//++++++++++++++++++++++++++++++ RELATION ++++++++++++++++++++++++++++++++++++++
function Start_relation()
{
@ -1181,6 +1258,7 @@ function Small_tab_all(id_this) // max/min all tables
{
var icon = id_this.childNodes[0];
var key;
var value_sent = '';
if (icon.alt == "v") {
for (key in j_tabs) {
if (document.getElementById('id_hide_tbody_' + key).innerHTML == "v") {
@ -1189,6 +1267,7 @@ function Small_tab_all(id_this) // max/min all tables
}
icon.alt = ">";
icon.src = icon.dataset.right;
value_sent = 'v';
} else {
for (key in j_tabs) {
if (document.getElementById('id_hide_tbody_' + key).innerHTML != "v") {
@ -1197,7 +1276,11 @@ function Small_tab_all(id_this) // max/min all tables
}
icon.alt = "v";
icon.src = icon.dataset.down;
value_sent = '>';
}
saveValueInConfig('small_big_all', value_sent);
$('#key_SB_all').toggleClass('M_butt_Selected_down');
$('#key_SB_all').toggleClass('M_butt');
Re_load();
}
@ -1212,6 +1295,9 @@ function Small_tab_invert() // invert max/min all tables
function Relation_lines_invert()
{
show_relation_lines = ! show_relation_lines;
saveValueInConfig('relation_lines', show_relation_lines);
$('#relLineInvert').toggleClass('M_butt_Selected_down');
$('#relLineInvert').toggleClass('M_butt');
Re_load();
}
@ -1450,7 +1536,7 @@ function No_have_constr(id_this)
if (id_this.alt == 'v') {
id_this.alt = '>';
id_this.src = id_this.dataset.right;;
id_this.src = id_this.dataset.right;
} else {
id_this.alt = 'v';
id_this.src = id_this.dataset.down;
@ -1540,19 +1626,24 @@ function Side_menu_right(id_this)
icon.attr('src', icon.attr('data-right'));
icon.attr('data-right', current);
menu_moved = !menu_moved;
saveValueInConfig('side_menu', $('#side_menu').hasClass('right'));
$('#key_Left_Right').toggleClass('M_butt_Selected_down');
$('#key_Left_Right').toggleClass('M_butt');
}
//------------------------------------------------------------------------------
function Show_text () {
$('#side_menu .hidable').show();
$('#side_menu').find('.hidable').show();
}
function Hide_text () {
if (!always_show_text) {
$('#side_menu .hidable').hide();
$('#side_menu').find('.hidable').hide();
}
}
function Pin_text () {
always_show_text = !always_show_text;
$('#pin_Text').toggleClass('M_butt_Selected_down');
$('#pin_Text').toggleClass('M_butt');
saveValueInConfig('pin_text', always_show_text);
}
//------------------------------------------------------------------------------
function Start_display_field()
@ -1739,26 +1830,26 @@ function add_object()
}
p = document.getElementById('Query');
where_obj = new where(rel.value, p.value);//make where object
history_array.push(new history(col_name, where_obj, tab_name, h_tabs[downer + '.' + tab_name], "Where"));
history_array.push(new history_obj(col_name, where_obj, tab_name, h_tabs[downer + '.' + tab_name], "Where"));
sum = sum + 1;
rel.value = '--';
p.value = "";
}
if (document.getElementById('new_name').value !== "") {
var rename_obj = new rename(document.getElementById('new_name').value);//make Rename object
history_array.push(new history(col_name, rename_obj, tab_name, h_tabs[downer + '.' + tab_name], "Rename"));
history_array.push(new history_obj(col_name, rename_obj, tab_name, h_tabs[downer + '.' + tab_name], "Rename"));
sum = sum + 1;
document.getElementById('new_name').value = "";
}
if (document.getElementById('operator').value != '---') {
var aggregate_obj = new aggregate(document.getElementById('operator').value);
history_array.push(new history(col_name, aggregate_obj, tab_name, h_tabs[downer + '.' + tab_name], "Aggregate"));
history_array.push(new history_obj(col_name, aggregate_obj, tab_name, h_tabs[downer + '.' + tab_name], "Aggregate"));
sum = sum + 1;
document.getElementById('operator').value = '---';
//make aggregate operator
}
if (document.getElementById('groupby').checked === true) {
history_array.push(new history(col_name, 'GroupBy', tab_name, h_tabs[downer + '.' + tab_name], "GroupBy"));
history_array.push(new history_obj(col_name, 'GroupBy', tab_name, h_tabs[downer + '.' + tab_name], "GroupBy"));
sum = sum + 1;
document.getElementById('groupby').checked = false;
//make groupby
@ -1775,16 +1866,17 @@ function add_object()
p.value,
document.getElementById('h_operator').value
);//make where object
history_array.push(new history(col_name, where_obj, tab_name, h_tabs[downer + '.' + tab_name], "Having"));
history_array.push(new history_obj(col_name, where_obj, tab_name, h_tabs[downer + '.' + tab_name], "Having"));
sum = sum + 1;
document.getElementById('h_rel_opt').value = '--';
document.getElementById('h_operator').value = '---';
p.value = ""; //make having
}
if (document.getElementById('orderby').checked === true) {
history_array.push(new history(col_name, 'OrderBy', tab_name, h_tabs[downer + '.' + tab_name], "OrderBy"));
if (document.getElementById('orderby').value != '---') {
var oderby_obj = new orderby(document.getElementById('orderby').value);
history_array.push(new history_obj(col_name, oderby_obj, tab_name, h_tabs[downer + '.' + tab_name], "OrderBy"));
sum = sum + 1;
document.getElementById('orderby').checked = false;
document.getElementById('orderby').value = '---';
//make orderby
}
PMA_ajaxShowMessage(PMA_sprintf(PMA_messages.strObjectsCreated, sum));
@ -1792,7 +1884,7 @@ function add_object()
var existingDiv = document.getElementById('ab');
existingDiv.innerHTML = display(init, history_array.length);
Close_option();
panel(0);
$('#ab').accordion("refresh");
}
AJAX.registerTeardown('pmd/move.js', function () {
@ -1823,7 +1915,7 @@ AJAX.registerTeardown('pmd/move.js', function () {
$("#key_HS").unbind('click');
$('.scroll_tab_struct').unbind('click');
$('.scroll_tab_checkbox').unbind('click');
$('#id_scroll_tab tr').off('click', '.pmd_Tabs2,.pmd_Tabs');
$('#id_scroll_tab').find('tr').off('click', '.pmd_Tabs2,.pmd_Tabs');
$('.pmd_tab').off('click', '.select_all_1');
$('.pmd_tab').off('click', '.small_tab,.small_tab2');
$('.pmd_tab').off('click', '.small_tab_pref_1');
@ -1945,7 +2037,7 @@ AJAX.registerOnload('pmd/move.js', function () {
$('.scroll_tab_checkbox').click(function() {
VisibleTab(this,$(this).val());
});
$('#id_scroll_tab tr').on('click', '.pmd_Tabs2,.pmd_Tabs', function() {
$('#id_scroll_tab').find('tr').on('click', '.pmd_Tabs2,.pmd_Tabs', function() {
Select_tab($(this).attr('pmd_url_table_name'));
});
$('.pmd_tab').on('click', '.select_all_1', function() {

View File

@ -41,6 +41,7 @@ AJAX.registerTeardown('replication.js', function () {
$('#slave_errormanagement_href').unbind('click');
$('#slave_synchronization_href').unbind('click');
$('#db_reset_href').unbind('click');
$('#db_select_href').unbind('click');
});
AJAX.registerOnload('replication.js', function () {
@ -70,4 +71,8 @@ AJAX.registerOnload('replication.js', function () {
$('#db_select option:selected').prop('selected', false);
$('#db_select').trigger('change');
});
$('#db_select_href').click(function () {
$('#db_select option').prop('selected', true);
$('#db_select').trigger('change');
});
});

175
js/rte.js
View File

@ -110,8 +110,41 @@ RTE.COMMON = {
exportDialog: function ($this) {
var $msg = PMA_ajaxShowMessage();
// Fire the ajax request straight away
$.get($this.attr('href'), {'ajax_request': true}, function (data) {
if ($this.hasClass('mult_submit')) {
var combined = {
success: true,
title: PMA_messages.strExport,
message: '',
error: ''
};
// export anchors of all selected rows
var export_anchors = $('input.checkall:checked').parents('tr').find('.export_anchor');
var count = export_anchors.length;
var returnCount = 0;
export_anchors.each(function () {
$.get($(this).attr('href'), {'ajax_request': true}, function (data) {
returnCount++;
if (data.success === true) {
combined.message += "\n" + data.message + "\n";
if (returnCount == count) {
showExport(combined);
}
} else {
// complain even if one export is failing
combined.success = false;
combined.error += "\n" + data.error + "\n";
if (returnCount == count) {
showExport(combined);
}
}
});
});
} else {
$.get($this.attr('href'), {'ajax_request': true}, showExport);
}
function showExport(data) {
if (data.success === true) {
PMA_ajaxRemoveMessage($msg);
/**
@ -125,6 +158,7 @@ RTE.COMMON = {
/**
* Display the dialog to the user
*/
data.message = '<textarea cols="40" rows="15" style="width: 100%;">' + data.message + '</textarea>';
var $ajaxDialog = $('<div>' + data.message + '</div>').dialog({
width: 500,
buttons: button_options,
@ -136,24 +170,11 @@ RTE.COMMON = {
* to the Export textarea.
*/
var $elm = $ajaxDialog.find('textarea');
/**
* @var opts Options to pass to the codemirror editor
*/
var opts = {
lineNumbers: true,
matchBrackets: true,
extraKeys: {"Ctrl-Space": "autocomplete"},
hintOptions: {"completeSingle": false, "completeOnSingleClick": true},
indentUnit: 4,
mode: "text/x-mysql",
lineWrapping: true
};
CodeMirror.fromTextArea($elm[0], opts)
.on("inputRead", codemirrorAutocompleteOnInputRead);
PMA_getSQLEditor($elm);
} else {
PMA_ajaxShowMessage(data.error, false);
}
}); // end $.get()
} // end showExport()
}, // end exportDialog()
editorDialog: function (is_new, $this) {
var that = this;
@ -339,22 +360,8 @@ RTE.COMMON = {
* the Definition textarea.
*/
var $elm = $('textarea[name=item_definition]').last();
/**
* @var opts Options to pass to the codemirror editor
*/
var opts = {
lineNumbers: true,
matchBrackets: true,
extraKeys: {"Ctrl-Space": "autocomplete"},
hintOptions: {"completeSingle": false, "completeOnSingleClick": true},
indentUnit: 4,
mode: "text/x-mysql",
lineWrapping: true
};
if (typeof CodeMirror != 'undefined') {
that.syntaxHiglighter = CodeMirror.fromTextArea($elm[0], opts);
that.syntaxHiglighter.on("inputRead", codemirrorAutocompleteOnInputRead);
}
that.syntaxHiglighter = PMA_getSQLEditor($elm);
// Execute item-specific code
that.postDialogShow(data);
} else {
@ -364,7 +371,7 @@ RTE.COMMON = {
},
dropDialog: function ($this) {
/**
/**
* @var $curr_row Object containing reference to the current row
*/
var $curr_row = $this.parents('tr');
@ -397,6 +404,7 @@ RTE.COMMON = {
// nothing to show in the table, so we hide it.
$table.hide("slow", function () {
$(this).find('tr.even, tr.odd').remove();
$('.withSelected').remove();
$('#nothing2display').show("slow");
});
} else {
@ -415,7 +423,7 @@ RTE.COMMON = {
*/
var rowclass = '';
$table.find('tr').has('td').each(function () {
rowclass = (ct % 2 === 0) ? 'odd' : 'even';
rowclass = (ct % 2 === 1) ? 'odd' : 'even';
$(this).removeClass().addClass(rowclass);
ct++;
});
@ -431,6 +439,89 @@ RTE.COMMON = {
}
}); // end $.get()
}); // end $.PMA_confirm()
},
dropMultipleDialog: function ($this) {
// We ask for confirmation here
$this.PMA_confirm(PMA_messages.strDropRTEitems, '', function (url) {
/**
* @var msg jQuery object containing the reference to
* the AJAX message shown to the user
*/
var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
// drop anchors of all selected rows
var drop_anchors = $('input.checkall:checked').parents('tr').find('.drop_anchor');
var success = true;
var count = drop_anchors.length;
var returnCount = 0;
drop_anchors.each(function () {
var $anchor = $(this);
/**
* @var $curr_row Object containing reference to the current row
*/
var $curr_row = $anchor.parents('tr');
$.get($anchor.attr('href'), {'is_js_confirmed': 1, 'ajax_request': true}, function (data) {
returnCount++;
if (data.success === true) {
/**
* @var $table Object containing reference
* to the main list of elements
*/
var $table = $curr_row.parent();
// Check how many rows will be left after we remove
// the one that the user has requested us to remove
if ($table.find('tr').length === 3) {
// If there are two rows left, it means that they are
// the header of the table and the rows that we are
// about to remove, so after the removal there will be
// nothing to show in the table, so we hide it.
$table.hide("slow", function () {
$(this).find('tr.even, tr.odd').remove();
$('.withSelected').remove();
$('#nothing2display').show("slow");
});
} else {
$curr_row.hide("fast", function () {
$(this).remove();
// Now we have removed the row from the list, but maybe
// some row classes are wrong now. So we will itirate
// throught all rows and assign correct classes to them.
/**
* @var ct Count of processed rows
*/
var ct = 0;
/**
* @var rowclass Class to be attached to the row
* that is being processed
*/
var rowclass = '';
$table.find('tr').has('td').each(function () {
rowclass = (ct % 2 === 1) ? 'odd' : 'even';
$(this).removeClass().addClass(rowclass);
ct++;
});
});
}
if (returnCount == count) {
if (success) {
// Get rid of the "Loading" message
PMA_ajaxRemoveMessage($msg);
$('#rteListForm_checkall').prop({checked: false, indeterminate: false});
}
PMA_reloadNavigation();
}
} else {
PMA_ajaxShowMessage(data.error, false);
success = false;
if (returnCount == count) {
PMA_reloadNavigation();
}
}
}); // end $.get()
}); // end drop_anchors.each()
}); // end $.PMA_confirm()
}
}; // end RTE namespace
@ -711,7 +802,7 @@ RTE.ROUTINE = {
/**
* Display the dialog to the user
*/
$ajaxDialog = $('<div>' + data.message + '</div>').dialog({
var $ajaxDialog = $('<div>' + data.message + '</div>').dialog({
width: 650,
buttons: that.buttonOptions,
title: data.title,
@ -806,6 +897,12 @@ $(function () {
dialog.exportDialog($(this));
}); // end $(document).on()
$(document).on('click', '#rteListForm.ajax .mult_submit[value="export"]', function (event) {
event.preventDefault();
var dialog = new RTE.object();
dialog.exportDialog($(this));
}); // end $(document).on()
/**
* Attach Ajax event handlers for Drop functionality
* of Routines, Triggers and Events.
@ -816,6 +913,12 @@ $(function () {
dialog.dropDialog($(this));
}); // end $(document).on()
$(document).on('click', '#rteListForm.ajax .mult_submit[value="drop"]', function (event) {
event.preventDefault();
var dialog = new RTE.object();
dialog.dropMultipleDialog($(this));
}); // end $(document).on()
/**
* Attach Ajax event handlers for the "Change event/routine type"
* functionality in the events editor, so that the correct

View File

@ -127,7 +127,9 @@ AJAX.registerOnload('server_databases.js', function () {
var dbStruct_url = data.url_query;
dbStruct_url = dbStruct_url.replace(/amp;/ig, '');
var params = 'ajax_request=true&ajax_page_request=true';
params += AJAX.cache.menus.getRequestParam();
if (! (history && history.pushState)) {
params += PMA_Microhistory.menus.getRequestParam();
}
$.get(dbStruct_url, params, AJAX.responseHandler);
} else {
PMA_ajaxShowMessage(data.error, false);

View File

@ -2,24 +2,8 @@
/**
* Functions used in server plugins pages
*/
var pma_theme_image; // filled in server_plugins.php
AJAX.registerOnload('server_plugins.js', function () {
// Add tabs
$('#pluginsTabs').tabs({
// Tab persistence
cookie: { name: 'pma_serverStatusTabs', expires: 1 },
show: function (event, ui) {
// Fixes line break in the menu bar when the page overflows and scrollbar appears
$('#topmenu').menuResizer('resize');
// 'Plugins' tab is too high due to hiding of 'Modules' by negative left position,
// hide tabs by changing display to fix it
$(ui.panel).closest('.ui-tabs').find('> div').not(ui.panel).css('display', 'none');
$(ui.panel).css('display', 'block');
}
});
// Make columns sortable, but only for tables with more than 1 data row
// Make columns sortable, but only for tables with more than 1 data row
var $tables = $('#plugins_plugins table:has(tbody tr + tr)');
$tables.tablesorter({
sortList: [[0, 0]],

View File

@ -61,6 +61,7 @@ AJAX.registerTeardown('server_privileges.js', function () {
$(document).off("click", ".checkall_box");
$(document).off('change', '#checkbox_SSL_priv');
$(document).off('change', 'input[name="ssl_type"]');
$(document).off('change', '#select_authentication_plugin');
});
AJAX.registerOnload('server_privileges.js', function () {
@ -91,6 +92,18 @@ AJAX.registerOnload('server_privileges.js', function () {
}
});
/**
* Display a notice if sha256_password is selected
*/
$(document).on("change", "#select_authentication_plugin", function () {
var selected_plugin = $(this).val();
if (selected_plugin === 'sha256_password') {
$('#ssl_reqd_warning').show();
} else {
$('#ssl_reqd_warning').hide();
}
});
/**
* AJAX handler for 'Revoke User'
*
@ -106,7 +119,7 @@ AJAX.registerOnload('server_privileges.js', function () {
$thisButton.PMA_confirm(PMA_messages.strDropUserWarning, $form.attr('action'), function (url) {
$drop_users_db_checkbox = $("#checkbox_drop_users_db");
var $drop_users_db_checkbox = $("#checkbox_drop_users_db");
if ($drop_users_db_checkbox.is(':checked')) {
var is_confirmed = confirm(PMA_messages.strDropDatabaseStrongWarning + '\n' + PMA_sprintf(PMA_messages.strDoYouReally, 'DROP DATABASE'));
if (! is_confirmed) {
@ -259,18 +272,7 @@ AJAX.registerOnload('server_privileges.js', function () {
});
PMA_ajaxRemoveMessage($msgbox);
// Attach syntax highlighted editor to export dialog
if (typeof CodeMirror != 'undefined') {
CodeMirror.fromTextArea(
$ajaxDialog.find('textarea')[0],
{
lineNumbers: true,
matchBrackets: true,
indentUnit: 4,
mode: "text/x-mysql",
lineWrapping: true
}
);
}
PMA_getSQLEditor($ajaxDialog.find('textarea'));
} else {
PMA_ajaxShowMessage(data.error, false);
}
@ -278,18 +280,7 @@ AJAX.registerOnload('server_privileges.js', function () {
); //end $.post
});
// if exporting non-ajax, highlight anyways
if ($("textarea.export").length > 0 && typeof CodeMirror != 'undefined') {
CodeMirror.fromTextArea(
$('textarea.export')[0],
{
lineNumbers: true,
matchBrackets: true,
indentUnit: 4,
mode: "text/x-mysql",
lineWrapping: true
}
);
}
PMA_getSQLEditor($('textarea.export'));
$(document).on('click', "a.export_user_anchor.ajax", function (event) {
event.preventDefault();
@ -315,18 +306,7 @@ AJAX.registerOnload('server_privileges.js', function () {
});
PMA_ajaxRemoveMessage($msgbox);
// Attach syntax highlighted editor to export dialog
if (typeof CodeMirror != 'undefined') {
CodeMirror.fromTextArea(
$ajaxDialog.find('textarea')[0],
{
lineNumbers: true,
matchBrackets: true,
indentUnit: 4,
mode: "text/x-mysql",
lineWrapping: true
}
);
}
PMA_getSQLEditor($ajaxDialog.find('textarea'));
} else {
PMA_ajaxShowMessage(data.error, false);
}

View File

@ -16,6 +16,12 @@ AJAX.registerTeardown('server_status_advisor.js', function () {
});
AJAX.registerOnload('server_status_advisor.js', function () {
// if no advisor is loaded
if ($('#advisorData').length == 0) {
return;
}
/**** Server config advisor ****/
var $dialog = $('<div />').attr('id', 'advisorDialog');
var $instructionsDialog = $('<div />')

View File

@ -103,7 +103,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
}
// Timepicker is loaded on demand so we need to initialize
// datetime fields from the 'load log' dialog
$('#logAnalyseDialog .datetimefield').each(function () {
$('#logAnalyseDialog').find('.datetimefield').each(function () {
PMA_addDatepicker($(this));
});
@ -403,15 +403,15 @@ AJAX.registerOnload('server_status_monitor.js', function () {
calculateChartSize();
// Empty cells should keep their size so you can drop onto them
$('#chartGrid tr td').css('width', chartSize.width + 'px');
$('#chartGrid .monitorChart').css({
$('#chartGrid').find('tr td').css('width', chartSize.width + 'px');
$('#chartGrid').find('.monitorChart').css({
width: chartSize.width + 'px',
height: chartSize.height + 'px'
});
/* Reorder all charts that it fills all column cells */
var numColumns;
var $tr = $('#chartGrid tr:first');
var $tr = $('#chartGrid').find('tr:first');
var row = 0;
var tempManageCols = function () {
@ -488,7 +488,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
var type = $('input[name="chartType"]:checked').val();
if (type == 'preset') {
newChart = presetCharts[$('#addChartDialog select[name="presetCharts"]').prop('value')];
newChart = presetCharts[$('#addChartDialog').find('select[name="presetCharts"]').prop('value')];
} else {
// If user builds his own chart, it's being set/updated
// each time he adds a series
@ -517,7 +517,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
$(this).dialog("close");
};
var $presetList = $('#addChartDialog select[name="presetCharts"]');
var $presetList = $('#addChartDialog').find('select[name="presetCharts"]');
if ($presetList.html().length === 0) {
$.each(presetCharts, function (key, value) {
$presetList.append('<option value="' + key + '">' + value.title + '</option>');
@ -551,7 +551,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
buttons: dlgButtons
});
$('#addChartDialog #seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');
$('#seriesPreview').html('<i>' + PMA_messages.strNone + '</i>');
return false;
});
@ -984,10 +984,10 @@ AJAX.registerOnload('server_status_monitor.js', function () {
/* Calculate how much spacing there is between each chart */
$('#chartGrid').html('<tr><td></td><td></td></tr><tr><td></td><td></td></tr>');
chartSpacing = {
width: $('#chartGrid td:nth-child(2)').offset().left -
$('#chartGrid td:nth-child(1)').offset().left,
height: $('#chartGrid tr:nth-child(2) td:nth-child(2)').offset().top -
$('#chartGrid tr:nth-child(1) td:nth-child(1)').offset().top
width: $('#chartGrid').find('td:nth-child(2)').offset().left -
$('#chartGrid').find('td:nth-child(1)').offset().left,
height: $('#chartGrid').find('tr:nth-child(2) td:nth-child(2)').offset().top -
$('#chartGrid').find('tr:nth-child(1) td:nth-child(1)').offset().top
};
$('#chartGrid').html('');
@ -1002,15 +1002,15 @@ AJAX.registerOnload('server_status_monitor.js', function () {
}
/* Fill in missing cells */
var numCharts = $('#chartGrid .monitorChart').length;
var numCharts = $('#chartGrid').find('.monitorChart').length;
var numMissingCells = (monitorSettings.columns - numCharts % monitorSettings.columns) % monitorSettings.columns;
for (i = 0; i < numMissingCells; i++) {
$('#chartGrid tr:last').append('<td></td>');
$('#chartGrid').find('tr:last').append('<td></td>');
}
// Empty cells should keep their size so you can drop onto them
calculateChartSize();
$('#chartGrid tr td').css('width', chartSize.width + 'px');
$('#chartGrid').find('tr td').css('width', chartSize.width + 'px');
buildRequiredDataList();
refreshChartGrid();
@ -1130,7 +1130,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
settings.series = chartObj.series;
if ($('#' + 'gridchart' + runtime.chartAI).length === 0) {
var numCharts = $('#chartGrid .monitorChart').length;
var numCharts = $('#chartGrid').find('.monitorChart').length;
if (numCharts === 0 || (numCharts % monitorSettings.columns === 0)) {
$('#chartGrid').append('<tr></tr>');
@ -1139,7 +1139,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
if (!chartSize) {
calculateChartSize();
}
$('#chartGrid tr:last').append(
$('#chartGrid').find('tr:last').append(
'<td><div id="gridChartContainer' + runtime.chartAI + '" class="">' +
'<div class="ui-state-default monitorChart"' +
' id="gridchart' + runtime.chartAI + '"' +
@ -1238,7 +1238,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
if ($('#selection_box').length) {
$('#selection_box').remove();
}
selectionBox = $('<div id="selection_box" style="z-index:1000;height:250px;position:absolute;background-color:#87CEEB;opacity:0.4;filter:alpha(opacity=40);pointer-events:none;">');
var selectionBox = $('<div id="selection_box" style="z-index:1000;height:205px;position:absolute;background-color:#87CEEB;opacity:0.4;filter:alpha(opacity=40);pointer-events:none;">');
$(document.body).append(selectionBox);
selectionStartX = ev.pageX;
selectionStartY = ev.pageY;
@ -1289,19 +1289,20 @@ AJAX.registerOnload('server_status_monitor.js', function () {
$(document.body).mouseup(function () {
if ($('#selection_box').length) {
selectionBox.remove();
$('#selection_box').remove();
}
});
// Edit, Print icon only in edit mode
$('#chartGrid div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode);
$('#chartGrid').find('div svg').find('*[zIndex=20], *[zIndex=21], *[zIndex=19]').toggle(editMode);
runtime.chartAI++;
}
function PMA_getLogAnalyseDialog(min, max) {
var $dateStart = $('#logAnalyseDialog input[name="dateStart"]');
var $dateEnd = $('#logAnalyseDialog input[name="dateEnd"]');
var $logAnalyseDialog = $('#logAnalyseDialog');
var $dateStart = $logAnalyseDialog.find('input[name="dateStart"]');
var $dateEnd = $logAnalyseDialog.find('input[name="dateEnd"]');
$dateStart.prop("readonly", true);
$dateEnd.prop("readonly", true);
@ -1317,7 +1318,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
$(this).dialog("close");
};
$('#logAnalyseDialog').dialog({
$logAnalyseDialog.dialog({
width: 'auto',
height: 'auto',
buttons: dlgBtns
@ -1333,13 +1334,13 @@ AJAX.registerOnload('server_status_monitor.js', function () {
showMicrosec: false,
timeFormat: 'HH:mm:ss'
});
$('#logAnalyseDialog input[name="dateStart"]').datepicker('setDate', min);
$('#logAnalyseDialog input[name="dateEnd"]').datepicker('setDate', max);
$dateStart.datepicker('setDate', min);
$dateEnd.datepicker('setDate', max);
}
function loadLog(type, min, max) {
var dateStart = Date.parse($('#logAnalyseDialog input[name="dateStart"]').datepicker('getDate')) || min;
var dateEnd = Date.parse($('#logAnalyseDialog input[name="dateEnd"]').datepicker('getDate')) || max;
var dateStart = Date.parse($('#logAnalyseDialog').find('input[name="dateStart"]').datepicker('getDate')) || min;
var dateEnd = Date.parse($('#logAnalyseDialog').find('input[name="dateEnd"]').datepicker('getDate')) || max;
loadLogStatistics({
src: type,
@ -1350,7 +1351,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
});
}
/* Called in regular intervalls, this function updates the values of each chart in the grid */
/* Called in regular intervals, this function updates the values of each chart in the grid */
function refreshChartGrid() {
/* Send to server */
runtime.refreshRequest = $.post('server_status_monitor.php' + PMA_commonParams.get('common_query'), {
@ -1610,57 +1611,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
return serverResponseError();
}
if (logData.rows.length !== 0) {
runtime.logDataCols = buildLogTable(logData, opts.removeVariables);
/* Show some stats in the dialog */
$('#emptyDialog').dialog({title: PMA_messages.strLoadingLogs});
$('#emptyDialog').html('<p>' + PMA_messages.strLogDataLoaded + '</p>');
$.each(logData.sum, function (key, value) {
key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
if (key == 'Total') {
key = '<b>' + key + '</b>';
}
$('#emptyDialog').append(key + ': ' + value + '<br/>');
});
/* Add filter options if more than a bunch of rows there to filter */
if (logData.numRows > 12) {
$('#logTable').prepend(
'<fieldset id="logDataFilter">' +
' <legend>' + PMA_messages.strFiltersForLogTable + '</legend>' +
' <div class="formelement">' +
' <label for="filterQueryText">' + PMA_messages.strFilterByWordRegexp + '</label>' +
' <input name="filterQueryText" type="text" id="filterQueryText" style="vertical-align: baseline;" />' +
' </div>' +
((logData.numRows > 250) ? ' <div class="formelement"><button name="startFilterQueryText" id="startFilterQueryText">' + PMA_messages.strFilter + '</button></div>' : '') +
' <div class="formelement">' +
' <input type="checkbox" id="noWHEREData" name="noWHEREData" value="1" /> ' +
' <label for="noWHEREData"> ' + PMA_messages.strIgnoreWhereAndGroup + '</label>' +
' </div' +
'</fieldset>'
);
$('#logTable #noWHEREData').change(function () {
filterQueries(true);
});
if (logData.numRows > 250) {
$('#logTable #startFilterQueryText').click(filterQueries);
} else {
$('#logTable #filterQueryText').keyup(filterQueries);
}
}
dlgBtns[PMA_messages.strJumpToTable] = function () {
$(this).dialog("close");
$(document).scrollTop($('#logTable').offset().top);
};
$('#emptyDialog').dialog("option", "buttons", dlgBtns);
} else {
if (logData.rows.length === 0) {
$('#emptyDialog').dialog({title: PMA_messages.strNoDataFoundTitle});
$('#emptyDialog').html('<p>' + PMA_messages.strNoDataFound + '</p>');
@ -1669,7 +1620,57 @@ AJAX.registerOnload('server_status_monitor.js', function () {
};
$('#emptyDialog').dialog("option", "buttons", dlgBtns);
return;
}
runtime.logDataCols = buildLogTable(logData, opts.removeVariables);
/* Show some stats in the dialog */
$('#emptyDialog').dialog({title: PMA_messages.strLoadingLogs});
$('#emptyDialog').html('<p>' + PMA_messages.strLogDataLoaded + '</p>');
$.each(logData.sum, function (key, value) {
key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
if (key == 'Total') {
key = '<b>' + key + '</b>';
}
$('#emptyDialog').append(key + ': ' + value + '<br/>');
});
/* Add filter options if more than a bunch of rows there to filter */
if (logData.numRows > 12) {
$('#logTable').prepend(
'<fieldset id="logDataFilter">' +
' <legend>' + PMA_messages.strFiltersForLogTable + '</legend>' +
' <div class="formelement">' +
' <label for="filterQueryText">' + PMA_messages.strFilterByWordRegexp + '</label>' +
' <input name="filterQueryText" type="text" id="filterQueryText" style="vertical-align: baseline;" />' +
' </div>' +
((logData.numRows > 250) ? ' <div class="formelement"><button name="startFilterQueryText" id="startFilterQueryText">' + PMA_messages.strFilter + '</button></div>' : '') +
' <div class="formelement">' +
' <input type="checkbox" id="noWHEREData" name="noWHEREData" value="1" /> ' +
' <label for="noWHEREData"> ' + PMA_messages.strIgnoreWhereAndGroup + '</label>' +
' </div' +
'</fieldset>'
);
$('#noWHEREData').change(function () {
filterQueries(true);
});
if (logData.numRows > 250) {
$('#startFilterQueryText').click(filterQueries);
} else {
$('#filterQueryText').keyup(filterQueries);
}
}
dlgBtns[PMA_messages.strJumpToTable] = function () {
$(this).dialog("close");
$(document).scrollTop($('#logTable').offset().top);
};
$('#emptyDialog').dialog("option", "buttons", dlgBtns);
}
);
@ -1682,7 +1683,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
*/
function filterQueries(varFilterChange) {
var odd_row = false, cell, textFilter;
var val = $('#logTable #filterQueryText').val();
var val = $('#filterQueryText').val();
if (val.length === 0) {
textFilter = null;
@ -1691,7 +1692,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
}
var rowSum = 0, totalSum = 0, i = 0, q;
var noVars = $('#logTable #noWHEREData').prop('checked');
var noVars = $('#noWHEREData').prop('checked');
var equalsFilter = /([^=]+)=(\d+|((\'|"|).*?[^\\])\4((\s+)|$))/gi;
var functionFilter = /([a-z0-9_]+)\(.+?\)/gi;
var filteredQueries = {}, filteredQueriesLines = {};
@ -1717,7 +1718,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
};
// We just assume the sql text is always in the second last column, and that the total count is right of it
$('#logTable table tbody tr td:nth-child(' + (runtime.logDataCols.length - 1) + ')').each(function () {
$('#logTable').find('table tbody tr td:nth-child(' + (runtime.logDataCols.length - 1) + ')').each(function () {
var $t = $(this);
// If query is a SELECT and user enabled or disabled to group
// queries ignoring data in where statements, we
@ -1793,7 +1794,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
// We finished summarizing counts => Update count values of all grouped entries
if (varFilterChange) {
if (noVars) {
var numCol, row, $table = $('#logTable table tbody');
var numCol, row, $table = $('#logTable').find('table tbody');
$.each(filteredQueriesLines, function (key, value) {
if (filteredQueries[key] <= 1) {
return;
@ -1812,16 +1813,16 @@ AJAX.registerOnload('server_status_monitor.js', function () {
});
}
$('#logTable table').trigger("update");
$('#logTable').find('table').trigger("update");
setTimeout(function () {
$('#logTable table').trigger('sorton', [[[runtime.logDataCols.length - 1, 1]]]);
$('#logTable').find('table').trigger('sorton', [[[runtime.logDataCols.length - 1, 1]]]);
}, 0);
}
// Display some stats at the bottom of the table
$('#logTable table tfoot tr')
$('#logTable').find('table tfoot tr')
.html('<th colspan="' + (runtime.logDataCols.length - 1) + '">' +
PMA_messages.strSumRows + ' ' + rowSum + '<span style="float:right">' +
PMA_messages.strSumRows + ' ' + rowSum + '<span class="floatright">' +
PMA_messages.strTotal + '</span></th><th class="right">' + totalSum + '</th>');
}
}
@ -1900,12 +1901,12 @@ AJAX.registerOnload('server_status_monitor.js', function () {
$table.append('<tfoot>' +
'<tr><th colspan="' + (cols.length - 1) + '">' + PMA_messages.strSumRows +
' ' + data.numRows + '<span style="float:right">' + PMA_messages.strTotal +
' ' + data.numRows + '<span class="floatright">' + PMA_messages.strTotal +
'</span></th><th class="right">' + data.sum.TOTAL + '</th></tr></tfoot>');
// Append a tooltip to the count column, if there exist one
if ($('#logTable tr:first th:last').text().indexOf("#") > -1) {
$('#logTable tr:first th:last').append('&nbsp;' + PMA_getImage('b_help.png', '', {'class': 'qroupedQueryInfoIcon'}));
if ($('#logTable').find('tr:first th:last').text().indexOf("#") > -1) {
$('#logTable').find('tr:first th:last').append('&nbsp;' + PMA_getImage('b_help.png', '', {'class': 'qroupedQueryInfoIcon'}));
var tooltipContent = PMA_messages.strCountColumnExplanation;
if (groupInserts) {
@ -1919,12 +1920,12 @@ AJAX.registerOnload('server_status_monitor.js', function () {
);
}
$('#logTable table').tablesorter({
$('#logTable').find('table').tablesorter({
sortList: [[cols.length - 1, 1]],
widgets: ['fast-zebra']
});
$('#logTable table thead th')
$('#logTable').find('table thead th')
.append('<div class="sorticon"></div>');
return cols;
@ -1968,7 +1969,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
if (profilingChart !== null) {
profilingChart.destroy();
}
$('#queryAnalyzerDialog div.placeHolder').html('');
$('#queryAnalyzerDialog').find('div.placeHolder').html('');
if (codemirror_editor) {
codemirror_editor.setValue('');
} else {
@ -1982,7 +1983,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
function loadQueryAnalysis(rowData) {
var db = rowData.db || '';
$('#queryAnalyzerDialog div.placeHolder').html(
$('#queryAnalyzerDialog').find('div.placeHolder').html(
PMA_messages.strAnalyzing + ' <img class="ajaxIcon" src="' +
pmaThemeImage + 'ajax_clock_small.gif" alt="">');
@ -1992,7 +1993,7 @@ AJAX.registerOnload('server_status_monitor.js', function () {
query: codemirror_editor ? codemirror_editor.getValue() : $('#sqlquery').val(),
database: db
}, function (data) {
var i;
var i, l;
if (typeof data !== 'undefined' && data.success === true) {
data = data.message;
}
@ -2000,12 +2001,12 @@ AJAX.registerOnload('server_status_monitor.js', function () {
if (data.error.indexOf('1146') != -1 || data.error.indexOf('1046') != -1) {
data.error = PMA_messages.strServerLogError;
}
$('#queryAnalyzerDialog div.placeHolder').html('<div class="error">' + data.error + '</div>');
$('#queryAnalyzerDialog').find('div.placeHolder').html('<div class="error">' + data.error + '</div>');
return;
}
var totalTime = 0;
// Float sux, I'll use table :(
$('#queryAnalyzerDialog div.placeHolder')
$('#queryAnalyzerDialog').find('div.placeHolder')
.html('<table width="100%" border="0"><tr><td class="explain"></td><td class="chart"></td></tr></table>');
var explain = '<b>' + PMA_messages.strExplainOutput + '</b> ' + $('#explain_docu').html();
@ -2041,9 +2042,9 @@ AJAX.registerOnload('server_status_monitor.js', function () {
explain += '<p><b>' + PMA_messages.strAffectedRows + '</b> ' + data.affectedRows;
$('#queryAnalyzerDialog div.placeHolder td.explain').append(explain);
$('#queryAnalyzerDialog').find('div.placeHolder td.explain').append(explain);
$('#queryAnalyzerDialog div.placeHolder a[href*="#showExplain"]').click(function () {
$('#queryAnalyzerDialog').find('div.placeHolder a[href*="#showExplain"]').click(function () {
var id = $(this).attr('href').split('-')[1];
$(this).parent().find('div[class*="explain"]').hide();
$(this).parent().find('div[class*="explain-' + id + '"]').show();
@ -2081,26 +2082,26 @@ AJAX.registerOnload('server_status_monitor.js', function () {
numberTable += '<tr><td><b>' + PMA_messages.strTotalTime + '</b></td><td>' + PMA_prettyProfilingNum(totalTime, 2) + '</td></tr>';
numberTable += '</tbody></table>';
$('#queryAnalyzerDialog div.placeHolder td.chart').append(
$('#queryAnalyzerDialog').find('div.placeHolder td.chart').append(
'<b>' + PMA_messages.strProfilingResults + ' ' + $('#profiling_docu').html() + '</b> ' +
'(<a href="#showNums">' + PMA_messages.strTable + '</a>, <a href="#showChart">' + PMA_messages.strChart + '</a>)<br/>' +
numberTable + ' <div id="queryProfiling"></div>');
$('#queryAnalyzerDialog div.placeHolder a[href="#showNums"]').click(function () {
$('#queryAnalyzerDialog #queryProfiling').hide();
$('#queryAnalyzerDialog table.queryNums').show();
$('#queryAnalyzerDialog').find('div.placeHolder a[href="#showNums"]').click(function () {
$('#queryAnalyzerDialog').find('#queryProfiling').hide();
$('#queryAnalyzerDialog').find('table.queryNums').show();
return false;
});
$('#queryAnalyzerDialog div.placeHolder a[href="#showChart"]').click(function () {
$('#queryAnalyzerDialog #queryProfiling').show();
$('#queryAnalyzerDialog table.queryNums').hide();
$('#queryAnalyzerDialog').find('div.placeHolder a[href="#showChart"]').click(function () {
$('#queryAnalyzerDialog').find('#queryProfiling').show();
$('#queryAnalyzerDialog').find('table.queryNums').hide();
return false;
});
profilingChart = PMA_createProfilingChartJqplot(
'queryProfiling',
chartData
'queryProfiling',
chartData
);
//$('#queryProfiling').resizable();

View File

@ -57,10 +57,9 @@ var processList = {
$tr.remove();
// As we just removed a row, reapply odd-even classes
// to keep table stripes consistent
$('#tableprocesslist > tbody > tr').filter(':even')
.removeClass('odd').addClass('even');
$('#tableprocesslist > tbody > tr').filter(':odd')
.removeClass('even').addClass('odd');
var $tableProcessListTr = $('#tableprocesslist').find('> tbody > tr');
$tableProcessListTr.filter(':even').removeClass('odd').addClass('even');
$tableProcessListTr.filter(':odd').removeClass('even').addClass('odd');
// Show process killed message
PMA_ajaxShowMessage(data.message, false);
} else {

View File

@ -72,18 +72,12 @@ $(function () {
$.tablesorter.addWidget({
id: "fast-zebra",
format: function (table) {
if (table.config.debug) {
var time = new Date();
}
$("tr:even", table.tBodies[0])
.removeClass(table.config.widgetZebra.css[0])
.addClass(table.config.widgetZebra.css[1]);
$("tr:odd", table.tBodies[0])
.removeClass(table.config.widgetZebra.css[1])
.addClass(table.config.widgetZebra.css[0]);
if (table.config.debug) {
$.tablesorter.benchmark("Applying Fast-Zebra widget", time);
}
}
});
});

View File

@ -38,8 +38,8 @@ AJAX.registerOnload('server_status_variables.js', function () {
$('#dontFormat').change(function () {
// Hiding the table while changing values speeds up the process a lot
$('#serverstatusvariables').hide();
$('#serverstatusvariables td.value span.original').toggle(this.checked);
$('#serverstatusvariables td.value span.formatted').toggle(! this.checked);
$('#serverstatusvariables').find('td.value span.original').toggle(this.checked);
$('#serverstatusvariables').find('td.value span.formatted').toggle(! this.checked);
$('#serverstatusvariables').show();
}).trigger('change');
@ -64,7 +64,7 @@ AJAX.registerOnload('server_status_variables.js', function () {
}
if (section.length > 1) {
$('#linkSuggestions span').each(function () {
$('#linkSuggestions').find('span').each(function () {
if ($(this).attr('class').indexOf('status_' + section) != -1) {
useful_links++;
$(this).css('display', '');
@ -81,7 +81,7 @@ AJAX.registerOnload('server_status_variables.js', function () {
}
odd_row = false;
$('#serverstatusvariables th.name').each(function () {
$('#serverstatusvariables').find('th.name').each(function () {
if ((textFilter === null || textFilter.exec($(this).text())) &&
(! alertFilter || $(this).next().find('span.attention').length > 0) &&
(categoryFilter.length === 0 || $(this).parent().hasClass('s_' + categoryFilter))

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