:
+ //
+ // > // Bind an event handler.
+ // > jQuery(window).hashchange( function(e) {
+ // > var hash = location.hash;
+ // > ...
+ // > });
+ // >
+ // > // Manually trigger the event handler.
+ // > jQuery(window).hashchange();
+ //
+ // A more verbose usage that allows for event namespacing:
+ //
+ // > // Bind an event handler.
+ // > jQuery(window).bind( 'hashchange', function(e) {
+ // > var hash = location.hash;
+ // > ...
+ // > });
+ // >
+ // > // Manually trigger the event handler.
+ // > jQuery(window).trigger( 'hashchange' );
+ //
+ // Additional Notes:
+ //
+ // * The polling loop and Iframe are not created until at least one handler
+ // is actually bound to the 'hashchange' event.
+ // * If you need the bound handler(s) to execute immediately, in cases where
+ // a location.hash exists on page load, via bookmark or page refresh for
+ // example, use jQuery(window).hashchange() or the more verbose
+ // jQuery(window).trigger( 'hashchange' ).
+ // * The event can be bound before DOM ready, but since it won't be usable
+ // before then in IE6/7 (due to the necessary Iframe), recommended usage is
+ // to bind it inside a DOM ready handler.
+
+ // Override existing $.event.special.hashchange methods (allowing this plugin
+ // to be defined after jQuery BBQ in BBQ's source code).
+ special[ str_hashchange ] = $.extend( special[ str_hashchange ], {
+
+ // Called only when the first 'hashchange' event is bound to window.
+ setup: function() {
+ // If window.onhashchange is supported natively, there's nothing to do..
+ if ( supports_onhashchange ) { return false; }
+
+ // Otherwise, we need to create our own. And we don't want to call this
+ // until the user binds to the event, just in case they never do, since it
+ // will create a polling loop and possibly even a hidden Iframe.
+ $( fake_onhashchange.start );
+ },
+
+ // Called only when the last 'hashchange' event is unbound from window.
+ teardown: function() {
+ // If window.onhashchange is supported natively, there's nothing to do..
+ if ( supports_onhashchange ) { return false; }
+
+ // Otherwise, we need to stop ours (if possible).
+ $( fake_onhashchange.stop );
+ }
+
+ });
+
+ // fake_onhashchange does all the work of triggering the window.onhashchange
+ // event for browsers that don't natively support it, including creating a
+ // polling loop to watch for hash changes and in IE 6/7 creating a hidden
+ // Iframe to enable back and forward.
+ fake_onhashchange = (function(){
+ var self = {},
+ timeout_id,
+
+ // Remember the initial hash so it doesn't get triggered immediately.
+ last_hash = get_fragment(),
+
+ fn_retval = function(val){ return val; },
+ history_set = fn_retval,
+ history_get = fn_retval;
+
+ // Start the polling loop.
+ self.start = function() {
+ timeout_id || poll();
+ };
+
+ // Stop the polling loop.
+ self.stop = function() {
+ timeout_id && clearTimeout( timeout_id );
+ timeout_id = undefined;
+ };
+
+ // This polling loop checks every $.fn.hashchange.delay milliseconds to see
+ // if location.hash has changed, and triggers the 'hashchange' event on
+ // window when necessary.
+ function poll() {
+ var hash = get_fragment(),
+ history_hash = history_get( last_hash );
+
+ if ( hash !== last_hash ) {
+ history_set( last_hash = hash, history_hash );
+
+ $(window).trigger( str_hashchange );
+
+ } else if ( history_hash !== last_hash ) {
+ location.href = location.href.replace( /#.*/, '' ) + history_hash;
+ }
+
+ timeout_id = setTimeout( poll, $.fn[ str_hashchange ].delay );
+ };
+
+ // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
+ // vvvvvvvvvvvvvvvvvvv REMOVE IF NOT SUPPORTING IE6/7/8 vvvvvvvvvvvvvvvvvvv
+ // vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
+ (window.navigator.userAgent.indexOf("MSIE ") > -1 || !!window.navigator.userAgent.match(/Trident.*rv\:11\./)) && !supports_onhashchange && (function(){
+ // Not only do IE6/7 need the "magical" Iframe treatment, but so does IE8
+ // when running in "IE7 compatibility" mode.
+
+ var iframe,
+ iframe_src;
+
+ // When the event is bound and polling starts in IE 6/7, create a hidden
+ // Iframe for history handling.
+ self.start = function(){
+ if ( !iframe ) {
+ iframe_src = $.fn[ str_hashchange ].src;
+ iframe_src = iframe_src && iframe_src + get_fragment();
+
+ // Create hidden Iframe. Attempt to make Iframe as hidden as possible
+ // by using techniques from http://www.paciellogroup.com/blog/?p=604.
+ iframe = $('').hide()
+
+ // When Iframe has completely loaded, initialize the history and
+ // start polling.
+ .one( 'load', function(){
+ iframe_src || history_set( get_fragment() );
+ poll();
+ })
+
+ // Load Iframe src if specified, otherwise nothing.
+ .attr( 'src', iframe_src || 'javascript:0' )
+
+ // Append Iframe after the end of the body to prevent unnecessary
+ // initial page scrolling (yes, this works).
+ .insertAfter( 'body' )[0].contentWindow;
+
+ // Whenever `document.title` changes, update the Iframe's title to
+ // prettify the back/next history menu entries. Since IE sometimes
+ // errors with "Unspecified error" the very first time this is set
+ // (yes, very useful) wrap this with a try/catch block.
+ doc.onpropertychange = function(){
+ try {
+ if ( event.propertyName === 'title' ) {
+ iframe.document.title = doc.title;
+ }
+ } catch(e) {}
+ };
+
+ }
+ };
+
+ // Override the "stop" method since an IE6/7 Iframe was created. Even
+ // if there are no longer any bound event handlers, the polling loop
+ // is still necessary for back/next to work at all!
+ self.stop = fn_retval;
+
+ // Get history by looking at the hidden Iframe's location.hash.
+ history_get = function() {
+ return get_fragment( iframe.location.href );
+ };
+
+ // Set a new history item by opening and then closing the Iframe
+ // document, *then* setting its location.hash. If document.domain has
+ // been set, update that as well.
+ history_set = function( hash, history_hash ) {
+ var iframe_doc = iframe.document,
+ domain = $.fn[ str_hashchange ].domain;
+
+ if ( hash !== history_hash ) {
+ // Update Iframe with any initial `document.title` that might be set.
+ iframe_doc.title = doc.title;
+
+ // Opening the Iframe's document after it has been closed is what
+ // actually adds a history entry.
+ iframe_doc.open();
+
+ // Set document.domain for the Iframe document as well, if necessary.
+ domain && iframe_doc.write( '' );
+
+ iframe_doc.close();
+
+ // Update the Iframe's hash, for great justice.
+ iframe.location.hash = hash;
+ }
+ };
+
+ })();
+ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ // ^^^^^^^^^^^^^^^^^^^ REMOVE IF NOT SUPPORTING IE6/7/8 ^^^^^^^^^^^^^^^^^^^
+ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+ return self;
+ })();
+
+})(jQuery,window);
diff --git a/js/src/plugins/jquery/jquery.sortableTable.js b/js/src/plugins/jquery/jquery.sortableTable.js
new file mode 100644
index 0000000000..1f4fc91db8
--- /dev/null
+++ b/js/src/plugins/jquery/jquery.sortableTable.js
@@ -0,0 +1,272 @@
+/* vim: set expandtab sw=4 ts=4 sts=4: */
+/**
+ * @fileoverview A jquery plugin that allows drag&drop sorting in tables.
+ * Coded because JQuery UI sortable doesn't support tables. Also it has no animation
+ *
+ * @name Sortable Table JQuery plugin
+ *
+ * @requires jQuery
+ *
+ */
+
+/* Options:
+
+$('table').sortableTable({
+ ignoreRect: { top, left, width, height } - relative coordinates on each element. If the user clicks
+ in this area, it is not seen as a drag&drop request. Useful for toolbars etc.
+ events: {
+ start: callback function when the user starts dragging
+ drop: callback function after an element has been dropped
+ }
+})
+*/
+
+/* Commands:
+
+$('table').sortableTable('init') - equivalent to $('table').sortableTable()
+$('table').sortableTable('refresh') - if the table has been changed, refresh correctly assigns all events again
+$('table').sortableTable('destroy') - removes all events from the table
+
+*/
+
+/* Setup:
+
+ Can be applied on any table, there is just one convention.
+ Each cell (| ) has to contain one and only one element (preferably div or span)
+ which is the actually draggable element.
+*/
+(function($) {
+ jQuery.fn.sortableTable = function(method) {
+
+ var methods = {
+ init : function(options) {
+ var tb = new sortableTableInstance(this, options);
+ tb.init();
+ $(this).data('sortableTable',tb);
+ },
+ refresh : function( ) {
+ $(this).data('sortableTable').refresh();
+ },
+ destroy : function( ) {
+ $(this).data('sortableTable').destroy();
+ }
+ };
+
+ if ( methods[method] ) {
+ return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
+ } else if ( typeof method === 'object' || ! method ) {
+ return methods.init.apply( this, arguments );
+ } else {
+ $.error( 'Method ' + method + ' does not exist on jQuery.sortableTable' );
+ }
+
+ function sortableTableInstance(table, options) {
+ var down = false;
+ var $draggedEl, oldCell, previewMove, id;
+
+ if(!options) options = {};
+
+ /* Mouse handlers on the child elements */
+ var onMouseUp = function(e) {
+ dropAt(e.pageX, e.pageY);
+ }
+
+ var onMouseDown = function(e) {
+ $draggedEl = $(this).children();
+ if($draggedEl.length == 0) return;
+ if(options.ignoreRect && insideRect({x: e.pageX - $draggedEl.offset().left, y: e.pageY - $draggedEl.offset().top}, options.ignoreRect)) return;
+
+ down = true;
+ oldCell = this;
+ //move(e.pageX,e.pageY);
+
+ if(options.events && options.events.start)
+ options.events.start(this);
+
+ return false;
+ }
+
+ var globalMouseMove = function(e) {
+ if(down) {
+ move(e.pageX,e.pageY);
+
+ if(inside($(oldCell), e.pageX, e.pageY)) {
+ if(previewMove != null) {
+ moveTo(previewMove);
+ previewMove = null;
+ }
+ } else
+ $(table).find('td').each(function() {
+ if(inside($(this), e.pageX, e.pageY)) {
+ if($(previewMove).attr('class') != $(this).children().first().attr('class')) {
+ if(previewMove != null) moveTo(previewMove);
+ previewMove = $(this).children().first();
+ if(previewMove.length > 0)
+ moveTo($(previewMove), { pos: {
+ top: $(oldCell).offset().top - $(previewMove).parent().offset().top,
+ left: $(oldCell).offset().left - $(previewMove).parent().offset().left
+ } });
+ }
+
+ return false;
+ }
+ });
+ }
+
+ return false;
+ }
+
+ var globalMouseOut = function() {
+ if(down) {
+ down = false;
+ if(previewMove) moveTo(previewMove);
+ moveTo($draggedEl);
+ previewMove = null;
+ }
+ }
+
+ // Initialize sortable table
+ this.init = function() {
+ id = 1;
+ // Add some required css to each child element in the | s
+ $(table).find('td').children().each(function() {
+ // Remove any old occurences of our added draggable-num class
+ $(this).attr('class',$(this).attr('class').replace(/\s*draggable\-\d+/g,''));
+ $(this).addClass('draggable-' + (id++));
+ });
+
+ // Mouse events
+ $(table).find('td').bind('mouseup',onMouseUp);
+ $(table).find('td').bind('mousedown',onMouseDown);
+
+ $(document).mousemove(globalMouseMove);
+ $(document).bind('mouseleave', globalMouseOut);
+ }
+
+ // Call this when the table has been updated
+ this.refresh = function() {
+ this.destroy();
+ this.init();
+ }
+
+ this.destroy = function() {
+ // Add some required css to each child element in the | s
+ $(table).find('td').children().each(function() {
+ // Remove any old occurences of our added draggable-num class
+ $(this).attr('class',$(this).attr('class').replace(/\s*draggable\-\d+/g,''));
+ });
+
+ // Mouse events
+ $(table).find('td').unbind('mouseup',onMouseUp)
+ $(table).find('td').unbind('mousedown',onMouseDown);
+
+ $(document).unbind('mousemove',globalMouseMove);
+ $(document).unbind('mouseleave',globalMouseOut);
+ }
+
+ function switchElement(drag, dropTo) {
+ var dragPosDiff = {
+ left: $(drag).children().first().offset().left - $(dropTo).offset().left,
+ top: $(drag).children().first().offset().top - $(dropTo).offset().top
+ };
+
+ var dropPosDiff = null;
+ if($(dropTo).children().length > 0) {
+ dropPosDiff = {
+ left: $(dropTo).children().first().offset().left - $(drag).offset().left,
+ top: $(dropTo).children().first().offset().top - $(drag).offset().top
+ };
+ }
+
+ /* I love you append(). It moves the DOM Elements so gracefully <3 */
+ // Put the element in the way to old place
+ $(drag).append($(dropTo).children().first()).children()
+ .stop(true,true)
+ .bind('mouseup',onMouseUp);
+
+ if(dropPosDiff)
+ $(drag).append($(dropTo).children().first()).children()
+ .css('left',dropPosDiff.left + 'px')
+ .css('top',dropPosDiff.top + 'px');
+
+ // Put our dragged element into the space we just freed up
+ $(dropTo).append($(drag).children().first()).children()
+ .bind('mouseup',onMouseUp)
+ .css('left',dragPosDiff.left + 'px')
+ .css('top',dragPosDiff.top + 'px');
+
+ moveTo($(dropTo).children().first(), { duration: 100 });
+ moveTo($(drag).children().first(), { duration: 100 });
+
+ if(options.events && options.events.drop) {
+ // Drop event. The drag child element is moved into the drop element
+ // and vice versa. So the parameters are switched.
+
+ // Calculate row and column index
+ colIdx = $(dropTo).prevAll().length;
+ rowIdx = $(dropTo).parent().prevAll().length;
+
+ options.events.drop(drag,dropTo, { col: colIdx, row: rowIdx });
+ }
+ }
+
+ function move(x,y) {
+ $draggedEl.offset({
+ top: Math.min($(document).height(), Math.max(0, y - $draggedEl.height()/2)),
+ left: Math.min($(document).width(), Math.max(0, x - $draggedEl.width()/2))
+ });
+ }
+
+ function inside($el, x,y) {
+ var off = $el.offset();
+ return y >= off.top && x >= off.left && x < off.left + $el.width() && y < off.top + $el.height();
+ }
+
+ function insideRect(pos, r) {
+ return pos.y > r.top && pos.x > r.left && pos.y < r.top + r.height && pos.x < r.left + r.width;
+ }
+
+ function dropAt(x,y) {
+ if(!down) return;
+ down = false;
+
+ var switched = false;
+
+ $(table).find('td').each(function() {
+ if($(this).children().first().attr('class') != $(oldCell).children().first().attr('class') && inside($(this), x, y)) {
+ switchElement(oldCell, this);
+ switched = true;
+ return;
+ }
+ });
+
+ if(!switched) {
+ if(previewMove) moveTo(previewMove);
+ moveTo($draggedEl);
+ }
+
+ previewMove = null;
+ }
+
+ function moveTo(elem, opts) {
+ if(!opts) opts = {};
+ if(!opts.pos) opts.pos = { left: 0, top: 0 };
+ if(!opts.duration) opts.duration = 200;
+
+ $(elem).css('position','relative');
+ $(elem).animate({ top: opts.pos.top, left: opts.pos.left }, {
+ duration: opts.duration,
+ complete: function() {
+ if(opts.pos.left == 0 && opts.pos.top == 0) {
+ $(elem)
+ .css('position','')
+ .css('left','')
+ .css('top','');
+ }
+ }
+ });
+ }
+ }
+ }
+
+})( jQuery );
\ No newline at end of file
diff --git a/js/src/plugins/jquery/jquery.tablesorter.js b/js/src/plugins/jquery/jquery.tablesorter.js
new file mode 100644
index 0000000000..3ffdf25166
--- /dev/null
+++ b/js/src/plugins/jquery/jquery.tablesorter.js
@@ -0,0 +1,1046 @@
+/*
+ *
+ * TableSorter 2.0 - Client-side table sorting with ease!
+ * Version 2.0.5b
+ * @requires jQuery v1.2.3
+ *
+ * Copyright (c) 2007 Christian Bach
+ * Examples and docs at: http://tablesorter.com
+ * Dual licensed under the MIT and GPL licenses:
+ * http://www.opensource.org/licenses/mit-license.php
+ * http://www.gnu.org/licenses/gpl.html
+ *
+ */
+/**
+ *
+ * @description Create a sortable table with multi-column sorting capabilitys
+ *
+ * @example $('table').tablesorter();
+ * @desc Create a simple tablesorter interface.
+ *
+ * @example $('table').tablesorter({ sortList:[[0,0],[1,0]] });
+ * @desc Create a tablesorter interface and sort on the first and secound column column headers.
+ *
+ * @example $('table').tablesorter({ headers: { 0: { sorter: false}, 1: {sorter: false} } });
+ *
+ * @desc Create a tablesorter interface and disableing the first and second column headers.
+ *
+ *
+ * @example $('table').tablesorter({ headers: { 0: {sorter:"integer"}, 1: {sorter:"currency"} } });
+ *
+ * @desc Create a tablesorter interface and set a column parser for the first
+ * and second column.
+ *
+ *
+ * @param Object
+ * settings An object literal containing key/value pairs to provide
+ * optional settings.
+ *
+ *
+ * @option String cssHeader (optional) A string of the class name to be appended
+ * to sortable tr elements in the thead of the table. Default value:
+ * "header"
+ *
+ * @option String cssAsc (optional) A string of the class name to be appended to
+ * sortable tr elements in the thead on a ascending sort. Default value:
+ * "headerSortUp"
+ *
+ * @option String cssDesc (optional) A string of the class name to be appended
+ * to sortable tr elements in the thead on a descending sort. Default
+ * value: "headerSortDown"
+ *
+ * @option String sortInitialOrder (optional) A string of the inital sorting
+ * order can be asc or desc. Default value: "asc"
+ *
+ * @option String sortMultisortKey (optional) A string of the multi-column sort
+ * key. Default value: "shiftKey"
+ *
+ * @option String textExtraction (optional) A string of the text-extraction
+ * method to use. For complex html structures inside td cell set this
+ * option to "complex", on large tables the complex option can be slow.
+ * Default value: "simple"
+ *
+ * @option Object headers (optional) An object of instructions for per-column
+ * controls in the format: headers: { 0: { option: setting }, ... }. For
+ * example, to disable sorting on the first two columns of a table:
+ * headers: { 0: { sorter: false}, 1: {sorter: false} }.
+ * Default value: null.
+ *
+ * @option Array sortList (optional) An array of instructions for per-column sorting
+ * and direction in the format: [[columnIndex, sortDirection], ... ] where
+ * columnIndex is a zero-based index for your columns left-to-right and
+ * sortDirection is 0 for Ascending and 1 for Descending. A valid argument
+ * that sorts ascending first by column 1 and then column 2 looks like:
+ * [[0,0],[1,0]]. Default value: null.
+ *
+ * @option Array sortForce (optional) An array containing forced sorting rules.
+ * Use to add an additional forced sort that will be appended to the dynamic
+ * selections by the user. For example, can be used to sort people alphabetically
+ * after some other user-selected sort that results in rows with the same value
+ * like dates or money due. It can help prevent data from appearing as though it
+ * has a random secondary sort. Default value: null.
+ *
+ * @option Boolean sortLocaleCompare (optional) Boolean flag indicating whatever
+ * to use String.localeCampare method or not. Default set to true.
+ *
+ *
+ * @option Array sortAppend (optional) An array containing forced sorting rules.
+ * This option let's you specify a default sorting rule, which is
+ * appended to user-selected rules. Default value: null
+ *
+ * @option Boolean widthFixed (optional) Boolean flag indicating if tablesorter
+ * should apply fixed widths to the table columns. This is usefull when
+ * using the pager companion plugin. This options requires the dimension
+ * jquery plugin. Default value: false
+ *
+ * @option Boolean cancelSelection (optional) Boolean flag indicating if
+ * tablesorter should cancel selection of the table headers text.
+ * Default value: true
+ *
+ * @option Boolean debug (optional) Boolean flag indicating if tablesorter
+ * should display debuging information usefull for development.
+ *
+ * @type jQuery
+ *
+ * @name tablesorter
+ *
+ * @cat Plugins/Tablesorter
+ *
+ * @author Christian Bach/christian.bach@polyester.se
+ */
+
+(function ($) {
+ $.extend({
+ tablesorter: new
+ function () {
+
+ var parsers = [],
+ widgets = [];
+
+ this.defaults = {
+ cssHeader: "header",
+ cssAsc: "headerSortUp",
+ cssDesc: "headerSortDown",
+ cssChildRow: "expand-child",
+ sortInitialOrder: "asc",
+ sortMultiSortKey: "shiftKey",
+ sortForce: null,
+ sortAppend: null,
+ sortLocaleCompare: true,
+ textExtraction: "simple",
+ parsers: {}, widgets: [],
+ widgetZebra: {
+ css: ["even", "odd"]
+ }, headers: {}, widthFixed: false,
+ cancelSelection: true,
+ sortList: [],
+ headerList: [],
+ dateFormat: "us",
+ decimal: '/\.|\,/g',
+ onRenderHeader: null,
+ selectorHeaders: 'thead th',
+ debug: false
+ };
+
+ /* debuging utils */
+
+ function benchmark(s, d) {
+ log(s + "," + (new Date().getTime() - d.getTime()) + "ms");
+ }
+
+ this.benchmark = benchmark;
+
+ function log(s) {
+ if (typeof console != "undefined" && typeof console.debug != "undefined") {
+ console.log(s);
+ } else {
+ alert(s);
+ }
+ }
+
+ /* parsers utils */
+
+ function buildParserCache(table, $headers) {
+
+ if (table.config.debug) {
+ var parsersDebug = "";
+ }
+
+ if (table.tBodies.length == 0) return; // In the case of empty tables
+ var rows = table.tBodies[0].rows;
+
+ if (rows[0]) {
+
+ var list = [],
+ cells = rows[0].cells,
+ l = cells.length;
+
+ for (var i = 0; i < l; i++) {
+
+ var p = false;
+
+ if ($.metadata && ($($headers[i]).metadata() && $($headers[i]).metadata().sorter)) {
+
+ p = getParserById($($headers[i]).metadata().sorter);
+
+ } else if ((table.config.headers[i] && table.config.headers[i].sorter)) {
+
+ p = getParserById(table.config.headers[i].sorter);
+ }
+ if (!p) {
+
+ p = detectParserForColumn(table, rows, -1, i);
+ }
+
+ if (table.config.debug) {
+ parsersDebug += "column:" + i + " parser:" + p.id + "\n";
+ }
+
+ list.push(p);
+ }
+ }
+
+ if (table.config.debug) {
+ log(parsersDebug);
+ }
+
+ return list;
+ };
+
+ function detectParserForColumn(table, rows, rowIndex, cellIndex) {
+ var l = parsers.length,
+ node = false,
+ nodeValue = false,
+ keepLooking = true;
+ while (nodeValue == '' && keepLooking) {
+ rowIndex++;
+ if (rows[rowIndex]) {
+ node = getNodeFromRowAndCellIndex(rows, rowIndex, cellIndex);
+ nodeValue = trimAndGetNodeText(table.config, node);
+ if (table.config.debug) {
+ log('Checking if value was empty on row:' + rowIndex);
+ }
+ } else {
+ keepLooking = false;
+ }
+ }
+ for (var i = 1; i < l; i++) {
+ if (parsers[i].is(nodeValue, table, node)) {
+ return parsers[i];
+ }
+ }
+ // 0 is always the generic parser (text)
+ return parsers[0];
+ }
+
+ function getNodeFromRowAndCellIndex(rows, rowIndex, cellIndex) {
+ return rows[rowIndex].cells[cellIndex];
+ }
+
+ function trimAndGetNodeText(config, node) {
+ return $.trim(getElementText(config, node));
+ }
+
+ function getParserById(name) {
+ var l = parsers.length;
+ for (var i = 0; i < l; i++) {
+ if (parsers[i].id.toLowerCase() == name.toLowerCase()) {
+ return parsers[i];
+ }
+ }
+ return false;
+ }
+
+ /* utils */
+
+ function buildCache(table) {
+
+ if (table.config.debug) {
+ var cacheTime = new Date();
+ }
+
+ var totalRows = (table.tBodies[0] && table.tBodies[0].rows.length) || 0,
+ totalCells = (table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length) || 0,
+ parsers = table.config.parsers,
+ cache = {
+ row: [],
+ normalized: []
+ };
+
+ for (var i = 0; i < totalRows; ++i) {
+
+ /** Add the table data to main data array */
+ var c = $(table.tBodies[0].rows[i]),
+ cols = [];
+
+ // if this is a child row, add it to the last row's children and
+ // continue to the next row
+ if (c.hasClass(table.config.cssChildRow)) {
+ cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add(c);
+ // go to the next for loop
+ continue;
+ }
+
+ cache.row.push(c);
+
+ for (var j = 0; j < totalCells; ++j) {
+ cols.push(parsers[j].format(getElementText(table.config, c[0].cells[j]), table, c[0].cells[j]));
+ }
+
+ cols.push(cache.normalized.length); // add position for rowCache
+ cache.normalized.push(cols);
+ cols = null;
+ };
+
+ if (table.config.debug) {
+ benchmark("Building cache for " + totalRows + " rows:", cacheTime);
+ }
+
+ return cache;
+ };
+
+ function getElementText(config, node) {
+
+ if (!node) return "";
+
+ var $node = $(node),
+ data = $node.attr('data-sort-value');
+ if (data !== undefined) return data;
+
+ var text = "";
+
+ if (!config.supportsTextContent) config.supportsTextContent = node.textContent || false;
+
+ if (config.textExtraction == "simple") {
+ if (config.supportsTextContent) {
+ text = node.textContent;
+ } else {
+ if (node.childNodes[0] && node.childNodes[0].hasChildNodes()) {
+ text = node.childNodes[0].innerHTML;
+ } else {
+ text = node.innerHTML;
+ }
+ }
+ } else {
+ if (typeof(config.textExtraction) == "function") {
+ text = config.textExtraction(node);
+ } else {
+ text = $(node).text();
+ }
+ }
+ return text;
+ }
+
+ function appendToTable(table, cache) {
+
+ if (table.config.debug) {
+ var appendTime = new Date()
+ }
+
+ var c = cache,
+ r = c.row,
+ n = c.normalized,
+ totalRows = n.length,
+ checkCell = (n[0].length - 1),
+ tableBody = $(table.tBodies[0]),
+ rows = [];
+
+
+ for (var i = 0; i < totalRows; i++) {
+ var pos = n[i][checkCell];
+
+ rows.push(r[pos]);
+
+ if (!table.config.appender) {
+
+ //var o = ;
+ var l = r[pos].length;
+ for (var j = 0; j < l; j++) {
+ tableBody[0].appendChild(r[pos][j]);
+ }
+
+ //
+ }
+ }
+
+
+
+ if (table.config.appender) {
+
+ table.config.appender(table, rows);
+ }
+
+ rows = null;
+
+ if (table.config.debug) {
+ benchmark("Rebuilt table:", appendTime);
+ }
+
+ // apply table widgets
+ applyWidget(table);
+
+ // trigger sortend
+ setTimeout(function () {
+ $(table).trigger("sortEnd");
+ }, 0);
+
+ };
+
+ function buildHeaders(table) {
+
+ if (table.config.debug) {
+ var time = new Date();
+ }
+
+ var meta = ($.metadata) ? true : false;
+
+ var header_index = computeTableHeaderCellIndexes(table);
+
+ var $tableHeaders = $(table.config.selectorHeaders, table).each(function (index) {
+
+ this.column = header_index[this.parentNode.rowIndex + "-" + this.cellIndex];
+ // this.column = index;
+ this.order = formatSortingOrder(table.config.sortInitialOrder);
+
+
+ this.count = this.order;
+
+ if (checkHeaderMetadata(this) || checkHeaderOptions(table, index)) this.sortDisabled = true;
+ if (checkHeaderOptionsSortingLocked(table, index)) this.order = this.lockedOrder = checkHeaderOptionsSortingLocked(table, index);
+
+ if (!this.sortDisabled) {
+ var $th = $(this).addClass(table.config.cssHeader);
+ if (table.config.onRenderHeader) table.config.onRenderHeader.apply($th);
+ }
+
+ // add cell to headerList
+ table.config.headerList[index] = this;
+ });
+
+ if (table.config.debug) {
+ benchmark("Built headers:", time);
+ log($tableHeaders);
+ }
+
+ return $tableHeaders;
+
+ };
+
+ // from:
+ // http://www.javascripttoolbox.com/lib/table/examples.php
+ // http://www.javascripttoolbox.com/temp/table_cellindex.html
+
+
+ function computeTableHeaderCellIndexes(t) {
+ var matrix = [];
+ var lookup = {};
+ var thead = t.getElementsByTagName('THEAD')[0];
+ var trs = thead.getElementsByTagName('TR');
+
+ for (var i = 0; i < trs.length; i++) {
+ var cells = trs[i].cells;
+ for (var j = 0; j < cells.length; j++) {
+ var c = cells[j];
+
+ var rowIndex = c.parentNode.rowIndex;
+ var cellId = rowIndex + "-" + c.cellIndex;
+ var rowSpan = c.rowSpan || 1;
+ var colSpan = c.colSpan || 1
+ var firstAvailCol;
+ if (typeof(matrix[rowIndex]) == "undefined") {
+ matrix[rowIndex] = [];
+ }
+ // Find first available column in the first row
+ for (var k = 0; k < matrix[rowIndex].length + 1; k++) {
+ if (typeof(matrix[rowIndex][k]) == "undefined") {
+ firstAvailCol = k;
+ break;
+ }
+ }
+ lookup[cellId] = firstAvailCol;
+ for (var k = rowIndex; k < rowIndex + rowSpan; k++) {
+ if (typeof(matrix[k]) == "undefined") {
+ matrix[k] = [];
+ }
+ var matrixrow = matrix[k];
+ for (var l = firstAvailCol; l < firstAvailCol + colSpan; l++) {
+ matrixrow[l] = "x";
+ }
+ }
+ }
+ }
+ return lookup;
+ }
+
+ function checkCellColSpan(table, rows, row) {
+ var arr = [],
+ r = table.tHead.rows,
+ c = r[row].cells;
+
+ for (var i = 0; i < c.length; i++) {
+ var cell = c[i];
+
+ if (cell.colSpan > 1) {
+ arr = arr.concat(checkCellColSpan(table, headerArr, row++));
+ } else {
+ if (table.tHead.length == 1 || (cell.rowSpan > 1 || !r[row + 1])) {
+ arr.push(cell);
+ }
+ // headerArr[row] = (i+row);
+ }
+ }
+ return arr;
+ };
+
+ function checkHeaderMetadata(cell) {
+ if (($.metadata) && ($(cell).metadata().sorter === false)) {
+ return true;
+ };
+ return false;
+ }
+
+ function checkHeaderOptions(table, i) {
+ if ((table.config.headers[i]) && (table.config.headers[i].sorter === false)) {
+ return true;
+ };
+ return false;
+ }
+
+ function checkHeaderOptionsSortingLocked(table, i) {
+ if ((table.config.headers[i]) && (table.config.headers[i].lockedOrder)) return table.config.headers[i].lockedOrder;
+ return false;
+ }
+
+ function applyWidget(table) {
+ var c = table.config.widgets;
+ var l = c.length;
+ for (var i = 0; i < l; i++) {
+
+ getWidgetById(c[i]).format(table);
+ }
+
+ }
+
+ function getWidgetById(name) {
+ var l = widgets.length;
+ for (var i = 0; i < l; i++) {
+ if (widgets[i].id.toLowerCase() == name.toLowerCase()) {
+ return widgets[i];
+ }
+ }
+ };
+
+ function formatSortingOrder(v) {
+ if (typeof(v) != "Number") {
+ return (v.toLowerCase() == "desc") ? 1 : 0;
+ } else {
+ return (v == 1) ? 1 : 0;
+ }
+ }
+
+ function isValueInArray(v, a) {
+ var l = a.length;
+ for (var i = 0; i < l; i++) {
+ if (a[i][0] == v) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ function setHeadersCss(table, $headers, list, css) {
+ // remove all header information
+ $headers.removeClass(css[0]).removeClass(css[1]);
+
+ var h = [];
+ $headers.each(function (offset) {
+ if (!this.sortDisabled) {
+ h[this.column] = $(this);
+ }
+ });
+
+ var l = list.length;
+ for (var i = 0; i < l; i++) {
+ h[list[i][0]].addClass(css[list[i][1]]);
+ }
+ }
+
+ function fixColumnWidth(table, $headers) {
+ var c = table.config;
+ if (c.widthFixed) {
+ var colgroup = $('');
+ $("tr:first td", table.tBodies[0]).each(function () {
+ colgroup.append($('').css('width', $(this).width()));
+ });
+ $(table).prepend(colgroup);
+ };
+ }
+
+ function updateHeaderSortCount(table, sortList) {
+ var c = table.config,
+ l = sortList.length;
+ for (var i = 0; i < l; i++) {
+ var s = sortList[i],
+ o = c.headerList[s[0]];
+ o.count = s[1];
+ o.count++;
+ }
+ }
+
+ /* sorting methods */
+
+ var sortWrapper;
+
+ function multisort(table, sortList, cache) {
+
+ if (table.config.debug) {
+ var sortTime = new Date();
+ }
+
+ var dynamicExp = "sortWrapper = function(a,b) {",
+ l = sortList.length;
+
+ // TODO: inline functions.
+ for (var i = 0; i < l; i++) {
+
+ var c = sortList[i][0];
+ var order = sortList[i][1];
+ // var s = (getCachedSortType(table.config.parsers,c) == "text") ?
+ // ((order == 0) ? "sortText" : "sortTextDesc") : ((order == 0) ?
+ // "sortNumeric" : "sortNumericDesc");
+ // var s = (table.config.parsers[c].type == "text") ? ((order == 0)
+ // ? makeSortText(c) : makeSortTextDesc(c)) : ((order == 0) ?
+ // makeSortNumeric(c) : makeSortNumericDesc(c));
+ var s = (table.config.parsers[c].type == "text") ? ((order == 0) ? makeSortFunction("text", "asc", c) : makeSortFunction("text", "desc", c)) : ((order == 0) ? makeSortFunction("numeric", "asc", c) : makeSortFunction("numeric", "desc", c));
+ var e = "e" + i;
+
+ dynamicExp += "var " + e + " = " + s; // + "(a[" + c + "],b[" + c
+ // + "]); ";
+ dynamicExp += "if(" + e + ") { return " + e + "; } ";
+ dynamicExp += "else { ";
+
+ }
+
+ // if value is the same keep orignal order
+ var orgOrderCol = cache.normalized[0].length - 1;
+ dynamicExp += "return a[" + orgOrderCol + "]-b[" + orgOrderCol + "];";
+
+ for (var i = 0; i < l; i++) {
+ dynamicExp += "}; ";
+ }
+
+ dynamicExp += "return 0; ";
+ dynamicExp += "}; ";
+
+ if (table.config.debug) {
+ benchmark("Evaling expression:" + dynamicExp, new Date());
+ }
+
+ eval(dynamicExp);
+
+ cache.normalized.sort(sortWrapper);
+
+ if (table.config.debug) {
+ benchmark("Sorting on " + sortList.toString() + " and dir " + order + " time:", sortTime);
+ }
+
+ return cache;
+ };
+
+ function makeSortFunction(type, direction, index) {
+ var a = "a[" + index + "]",
+ b = "b[" + index + "]";
+ if (type == 'text' && direction == 'asc') {
+ return "(" + a + " == " + b + " ? 0 : (" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : (" + a + " < " + b + ") ? -1 : 1 )));";
+ } else if (type == 'text' && direction == 'desc') {
+ return "(" + a + " == " + b + " ? 0 : (" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : (" + b + " < " + a + ") ? -1 : 1 )));";
+ } else if (type == 'numeric' && direction == 'asc') {
+ return "(" + a + " === null && " + b + " === null) ? 0 :(" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : " + a + " - " + b + "));";
+ } else if (type == 'numeric' && direction == 'desc') {
+ return "(" + a + " === null && " + b + " === null) ? 0 :(" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : " + b + " - " + a + "));";
+ }
+ };
+
+ function makeSortText(i) {
+ return "((a[" + i + "] < b[" + i + "]) ? -1 : ((a[" + i + "] > b[" + i + "]) ? 1 : 0));";
+ };
+
+ function makeSortTextDesc(i) {
+ return "((b[" + i + "] < a[" + i + "]) ? -1 : ((b[" + i + "] > a[" + i + "]) ? 1 : 0));";
+ };
+
+ function makeSortNumeric(i) {
+ return "a[" + i + "]-b[" + i + "];";
+ };
+
+ function makeSortNumericDesc(i) {
+ return "b[" + i + "]-a[" + i + "];";
+ };
+
+ function sortText(a, b) {
+ if (table.config.sortLocaleCompare) return a.localeCompare(b);
+ return ((a < b) ? -1 : ((a > b) ? 1 : 0));
+ };
+
+ function sortTextDesc(a, b) {
+ if (table.config.sortLocaleCompare) return b.localeCompare(a);
+ return ((b < a) ? -1 : ((b > a) ? 1 : 0));
+ };
+
+ function sortNumeric(a, b) {
+ return a - b;
+ };
+
+ function sortNumericDesc(a, b) {
+ return b - a;
+ };
+
+ function getCachedSortType(parsers, i) {
+ return parsers[i].type;
+ }; /* public methods */
+ this.construct = function (settings) {
+ return this.each(function () {
+ // if no thead or tbody quit.
+ if (!this.tHead || !this.tBodies) return;
+ // declare
+ var $this, $document, $headers, cache, config, shiftDown = 0,
+ sortOrder;
+ // new blank config object
+ this.config = {};
+ // merge and extend.
+ config = $.extend(this.config, $.tablesorter.defaults, settings);
+ // store common expression for speed
+ $this = $(this);
+ // save the settings where they read
+ $.data(this, "tablesorter", config);
+ // build headers
+ $headers = buildHeaders(this);
+ // try to auto detect column type, and store in tables config
+ this.config.parsers = buildParserCache(this, $headers);
+ // build the cache for the tbody cells
+ cache = buildCache(this);
+ // get the css class names, could be done else where.
+ var sortCSS = [config.cssDesc, config.cssAsc];
+ // fixate columns if the users supplies the fixedWidth option
+ fixColumnWidth(this);
+ // apply event handling to headers
+ // this is to big, perhaps break it out?
+ $headers.click(
+
+ function (e) {
+ var totalRows = ($this[0].tBodies[0] && $this[0].tBodies[0].rows.length) || 0;
+ if (!this.sortDisabled && totalRows > 0) {
+ // Only call sortStart if sorting is
+ // enabled.
+ $this.trigger("sortStart");
+ // store exp, for speed
+ var $cell = $(this);
+ // get current column index
+ var i = this.column;
+ // get current column sort order
+ this.order = this.count++ % 2;
+ // always sort on the locked order.
+ if(this.lockedOrder) this.order = this.lockedOrder;
+
+ // user only whants to sort on one
+ // column
+ if (!e[config.sortMultiSortKey]) {
+ // flush the sort list
+ config.sortList = [];
+ if (config.sortForce != null) {
+ var a = config.sortForce;
+ for (var j = 0; j < a.length; j++) {
+ if (a[j][0] != i) {
+ config.sortList.push(a[j]);
+ }
+ }
+ }
+ // add column to sort list
+ config.sortList.push([i, this.order]);
+ // multi column sorting
+ } else {
+ // the user has clicked on an all
+ // ready sortet column.
+ if (isValueInArray(i, config.sortList)) {
+ // revers the sorting direction
+ // for all tables.
+ for (var j = 0; j < config.sortList.length; j++) {
+ var s = config.sortList[j],
+ o = config.headerList[s[0]];
+ if (s[0] == i) {
+ o.count = s[1];
+ o.count++;
+ s[1] = o.count % 2;
+ }
+ }
+ } else {
+ // add column to sort list array
+ config.sortList.push([i, this.order]);
+ }
+ };
+ setTimeout(function () {
+ // set css for headers
+ setHeadersCss($this[0], $headers, config.sortList, sortCSS);
+ appendToTable(
+ $this[0], multisort(
+ $this[0], config.sortList, cache)
+ );
+ }, 1);
+ // stop normal event by returning false
+ return false;
+ }
+ // cancel selection
+ }).mousedown(function () {
+ if (config.cancelSelection) {
+ this.onselectstart = function () {
+ return false
+ };
+ return false;
+ }
+ });
+ // apply easy methods that trigger binded events
+ $this.bind("update", function () {
+ var me = this;
+ setTimeout(function () {
+ // rebuild parsers.
+ me.config.parsers = buildParserCache(
+ me, $headers);
+ // rebuild the cache map
+ cache = buildCache(me);
+ }, 1);
+ }).bind("updateCell", function (e, cell) {
+ var config = this.config;
+ // get position from the dom.
+ var pos = [(cell.parentNode.rowIndex - 1), cell.cellIndex];
+ // update cache
+ cache.normalized[pos[0]][pos[1]] = config.parsers[pos[1]].format(
+ getElementText(config, cell), cell);
+ }).bind("sorton", function (e, list) {
+ $(this).trigger("sortStart");
+ config.sortList = list;
+ // update and store the sortlist
+ var sortList = config.sortList;
+ // update header count index
+ updateHeaderSortCount(this, sortList);
+ // set css for headers
+ setHeadersCss(this, $headers, sortList, sortCSS);
+ // sort the table and append it to the dom
+ appendToTable(this, multisort(this, sortList, cache));
+ }).bind("appendCache", function () {
+ appendToTable(this, cache);
+ }).bind("applyWidgetId", function (e, id) {
+ getWidgetById(id).format(this);
+ }).bind("applyWidgets", function () {
+ // apply widgets
+ applyWidget(this);
+ });
+ if ($.metadata && ($(this).metadata() && $(this).metadata().sortlist)) {
+ config.sortList = $(this).metadata().sortlist;
+ }
+ // if user has supplied a sort list to constructor.
+ if (config.sortList.length > 0) {
+ $this.trigger("sorton", [config.sortList]);
+ }
+ // apply widgets
+ applyWidget(this);
+ });
+ };
+ this.addParser = function (parser) {
+ var l = parsers.length,
+ a = true;
+ for (var i = 0; i < l; i++) {
+ if (parsers[i].id.toLowerCase() == parser.id.toLowerCase()) {
+ a = false;
+ }
+ }
+ if (a) {
+ parsers.push(parser);
+ };
+ };
+ this.addWidget = function (widget) {
+ widgets.push(widget);
+ };
+ this.formatFloat = function (s) {
+ var i = parseFloat(s);
+ return (isNaN(i)) ? 0 : i;
+ };
+ this.formatInt = function (s) {
+ var i = parseInt(s);
+ return (isNaN(i)) ? 0 : i;
+ };
+ this.isDigit = function (s, config) {
+ // replace all an wanted chars and match.
+ return /^[-+]?\d*$/.test($.trim(s.replace(/[,.']/g, '')));
+ };
+ this.clearTableBody = function (table) {
+ if ($.browser.msie) {
+ while (table.tBodies[0].firstChild) {
+ table.tBodies[0].removeChild(table.tBodies[0].firstChild);
+ }
+ } else {
+ table.tBodies[0].innerHTML = "";
+ }
+ };
+ }
+ });
+
+ // extend plugin scope
+ $.fn.extend({
+ tablesorter: $.tablesorter.construct
+ });
+
+ // make shortcut
+ var ts = $.tablesorter;
+
+ // add default parsers
+ ts.addParser({
+ id: "text",
+ is: function (s) {
+ return true;
+ }, format: function (s) {
+ return $.trim(s.toLocaleLowerCase());
+ }, type: "text"
+ });
+
+ ts.addParser({
+ id: "digit",
+ is: function (s, table) {
+ var c = table.config;
+ return $.tablesorter.isDigit(s, c);
+ }, format: function (s) {
+ return $.tablesorter.formatFloat(s);
+ }, type: "numeric"
+ });
+
+ ts.addParser({
+ id: "currency",
+ is: function (s) {
+ return /^[£$€?.]/.test(s);
+ }, format: function (s) {
+ return $.tablesorter.formatFloat(s.replace(new RegExp(/[£$€]/g), ""));
+ }, type: "numeric"
+ });
+
+ ts.addParser({
+ id: "ipAddress",
+ is: function (s) {
+ return /^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);
+ }, format: function (s) {
+ var a = s.split("."),
+ r = "",
+ l = a.length;
+ for (var i = 0; i < l; i++) {
+ var item = a[i];
+ if (item.length == 2) {
+ r += "0" + item;
+ } else {
+ r += item;
+ }
+ }
+ return $.tablesorter.formatFloat(r);
+ }, type: "numeric"
+ });
+
+ ts.addParser({
+ id: "url",
+ is: function (s) {
+ return /^(https?|ftp|file):\/\/$/.test(s);
+ }, format: function (s) {
+ return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//), ''));
+ }, type: "text"
+ });
+
+ ts.addParser({
+ id: "isoDate",
+ is: function (s) {
+ return /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);
+ }, format: function (s) {
+ return $.tablesorter.formatFloat((s != "") ? new Date(s.replace(
+ new RegExp(/-/g), "/")).getTime() : "0");
+ }, type: "numeric"
+ });
+
+ ts.addParser({
+ id: "percent",
+ is: function (s) {
+ return /\%$/.test($.trim(s));
+ }, format: function (s) {
+ return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g), ""));
+ }, type: "numeric"
+ });
+
+ ts.addParser({
+ id: "usLongDate",
+ is: function (s) {
+ return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));
+ }, format: function (s) {
+ return $.tablesorter.formatFloat(new Date(s).getTime());
+ }, type: "numeric"
+ });
+
+ ts.addParser({
+ id: "shortDate",
+ is: function (s) {
+ return /\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);
+ }, format: function (s, table) {
+ var c = table.config;
+ s = s.replace(/\-/g, "/");
+ if (c.dateFormat == "us") {
+ // reformat the string in ISO format
+ s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$1/$2");
+ }
+ if (c.dateFormat == "pt") {
+ s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$2/$1");
+ } else if (c.dateFormat == "uk") {
+ // reformat the string in ISO format
+ s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$2/$1");
+ } else if (c.dateFormat == "dd/mm/yy" || c.dateFormat == "dd-mm-yy") {
+ s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/, "$1/$2/$3");
+ }
+ return $.tablesorter.formatFloat(new Date(s).getTime());
+ }, type: "numeric"
+ });
+ ts.addParser({
+ id: "time",
+ is: function (s) {
+ return /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);
+ }, format: function (s) {
+ return $.tablesorter.formatFloat(new Date("2000/01/01 " + s).getTime());
+ }, type: "numeric"
+ });
+ ts.addParser({
+ id: "metadata",
+ is: function (s) {
+ return false;
+ }, format: function (s, table, cell) {
+ var c = table.config,
+ p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName;
+ return $(cell).metadata()[p];
+ }, type: "numeric"
+ });
+ // add default widgets
+ ts.addWidget({
+ id: "zebra",
+ format: function (table) {
+ if (table.config.debug) {
+ var time = new Date();
+ }
+ var $tr, row = -1,
+ odd;
+ // loop through the visible rows
+ $("tr:visible", table.tBodies[0]).each(function (i) {
+ $tr = $(this);
+ // style children rows the same way the parent
+ // row was styled
+ if (!$tr.hasClass(table.config.cssChildRow)) row++;
+ odd = (row % 2 == 0);
+ $tr.removeClass(
+ table.config.widgetZebra.css[odd ? 0 : 1]).addClass(
+ table.config.widgetZebra.css[odd ? 1 : 0])
+ });
+ if (table.config.debug) {
+ $.tablesorter.benchmark("Applying Zebra widget", time);
+ }
+ }
+ });
+})(jQuery);
diff --git a/js/src/plugins/jquery/jquery.uitablefilter.js b/js/src/plugins/jquery/jquery.uitablefilter.js
new file mode 100644
index 0000000000..d63a74e575
--- /dev/null
+++ b/js/src/plugins/jquery/jquery.uitablefilter.js
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2008 Greg Weber greg at gregweber.info
+ * Dual licensed under the MIT and GPLv2 licenses just as jQuery is:
+ * http://jquery.org/license
+ *
+ * Multi-columns fork by natinusala
+ *
+ * documentation at http://gregweber.info/projects/uitablefilter
+ * https://github.com/natinusala/jquery-uitablefilter
+ *
+ * allows table rows to be filtered (made invisible)
+ *
+ * t = $('table')
+ * $.uiTableFilter( t, phrase )
+ *
+ * arguments:
+ * jQuery object containing table rows
+ * phrase to search for
+ * optional arguments:
+ * array of columns to limit search too (the column title in the table header)
+ * ifHidden - callback to execute if one or more elements was hidden
+ * tdElem - specific element within to be considered for searching or to limit search to,
+ * default:whole | . useful if | has more than one elements inside but want to
+ * limit search within only some of elements or only visible elements. eg tdElem can be "td span"
+ */
+(function($) {
+ $.uiTableFilter = function(jq, phrase, column, ifHidden, tdElem){
+ if(!tdElem) tdElem = "td";
+ var new_hidden = false;
+ if( this.last_phrase === phrase ) return false;
+
+ var phrase_length = phrase.length;
+ var words = phrase.toLowerCase().split(" ");
+
+ // these function pointers may change
+ var matches = function(elem) { elem.show() }
+ var noMatch = function(elem) { elem.hide(); new_hidden = true }
+ var getText = function(elem) { return elem.text() }
+
+ if( column )
+ {
+ if (!$.isArray(column))
+ {
+ column = new Array(column);
+ }
+
+ var index = new Array();
+
+ jq.find("thead > tr:last > th").each(function(i)
+ {
+ for (var j = 0; j < column.length; j++)
+ {
+ if ($.trim($(this).text()) == column[j])
+ {
+ index[j] = i;
+ break;
+ }
+ }
+
+ });
+
+ getText = function(elem) {
+ var selector = "";
+ for (var i = 0; i < index.length; i++)
+ {
+ if (i != 0) {selector += ",";}
+ selector += tdElem + ":eq(" + index[i] + ")";
+ }
+ return $(elem.find((selector))).text();
+ }
+ }
+
+ // if added one letter to last time,
+ // just check newest word and only need to hide
+ if( (words.size > 1) && (phrase.substr(0, phrase_length - 1) ===
+ this.last_phrase) ) {
+
+ if( phrase[-1] === " " )
+ { this.last_phrase = phrase; return false; }
+
+ var words = words[-1]; // just search for the newest word
+
+ // only hide visible rows
+ matches = function(elem) {;}
+ var elems = jq.find("tbody:first > tr:visible")
+ }
+ else {
+ new_hidden = true;
+ var elems = jq.find("tbody:first > tr")
+ }
+
+ elems.each(function(){
+ var elem = $(this);
+ $.uiTableFilter.has_words( getText(elem), words, false ) ?
+ matches(elem) : noMatch(elem);
+ });
+
+ this.last_phrase = phrase;
+ if( ifHidden && new_hidden ) ifHidden();
+ return jq;
+ };
+
+ // caching for speedup
+ $.uiTableFilter.last_phrase = ""
+
+ // not jQuery dependent
+ // "" [""] -> Boolean
+ // "" [""] Boolean -> Boolean
+ $.uiTableFilter.has_words = function( str, words, caseSensitive )
+ {
+ var text = caseSensitive ? str : str.toLowerCase();
+ for (var i=0; i < words.length; i++) {
+ if (text.indexOf(words[i]) === -1) return false;
+ }
+ return true;
+ }
+}) (jQuery);
diff --git a/js/src/server_databases.js b/js/src/server_databases.js
index f29e9f67aa..154b83967b 100644
--- a/js/src/server_databases.js
+++ b/js/src/server_databases.js
@@ -15,10 +15,12 @@ import { PMA_sprintf } from './utils/sprintf';
import './variables/import_variables';
import { PMA_ajaxShowMessage } from './utils/show_ajax_messages';
import { escapeHtml } from './utils/Sanitise';
-import { PMA_Messages as PMA_messages } from './variables/export_variables';
-import { jQuery as $ } from './utils/JqueryExtended';
+import { PMA_Messages as messages } from './variables/export_variables';
+import { $ } from './utils/JqueryExtended';
import { AJAX } from './ajax';
import CommonParams from './variables/common_params';
+import { PMA_reloadNavigation } from './functions/navigation';
+import { getJSConfirmCommonParam } from './functions/Common';
/**
* @package PhpMyAdmin
diff --git a/js/src/server_plugins.js b/js/src/server_plugins.js
index c02c2c4528..01c50e4ea3 100644
--- a/js/src/server_plugins.js
+++ b/js/src/server_plugins.js
@@ -1,5 +1,11 @@
/* vim: set expandtab sw=4 ts=4 sts=4: */
+/**
+ * Module import
+ */
+import { $ } from './utils/JqueryExtended';
+import './plugins/jquery/jquery.tablesorter';
+
/**
* @package PhpMyAdmin
*
diff --git a/js/src/server_privileges.js b/js/src/server_privileges.js
index e1fe4a6728..2c395e8ad3 100644
--- a/js/src/server_privileges.js
+++ b/js/src/server_privileges.js
@@ -16,8 +16,8 @@ import { checkPasswordStrength, displayPasswordGenerateButton } from './utils/pa
import { PMA_Messages as messages } from './variables/export_variables';
import { PMA_ajaxShowMessage, PMA_ajaxRemoveMessage } from './utils/show_ajax_messages';
import CommonParams from './variables/common_params';
-import { jQuery as $ } from './utils/JqueryExtended';
-import { PMA_getSQLEditor } from './utils/sql';
+import { $ } from './utils/JqueryExtended';
+import { PMA_getSQLEditor } from './functions/Sql/SqlEditor';
/**
* @package PhpMyAdmin
diff --git a/js/src/server_status_monitor.js b/js/src/server_status_monitor.js
index ff8e84849c..d47d4de8e3 100644
--- a/js/src/server_status_monitor.js
+++ b/js/src/server_status_monitor.js
@@ -1,4 +1,26 @@
/* vim: set expandtab sw=4 ts=4 sts=4: */
+import { PMA_Messages as messages } from './variables/export_variables';
+import { $ } from './utils/JqueryExtended';
+
+import 'updated-jqplot';
+import './plugins/jquery/jquery.sortableTable';
+
+import 'updated-jqplot/dist/plugins/jqplot.pieRenderer.js';
+import 'updated-jqplot/dist/plugins/jqplot.enhancedPieLegendRenderer.js';
+import 'updated-jqplot/dist/plugins/jqplot.canvasTextRenderer.js';
+import 'updated-jqplot/dist/plugins/jqplot.canvasAxisLabelRenderer.js';
+import 'updated-jqplot/dist/plugins/jqplot.dateAxisRenderer.js';
+import 'updated-jqplot/dist/plugins/jqplot.highlighter.js';
+import 'updated-jqplot/dist/plugins/jqplot.cursor.js';
+import './plugins/jqplot/jqplot.byteFormatter';
+
+import { getOsDetail } from './functions/Server/ServerStatusMonitor';
+import { isStorageSupported } from './functions/config';
+import { createProfilingChart } from './functions/chart';
+import CommonParams from './variables/common_params';
+import { escapeHtml } from './utils/Sanitise';
+import { PMA_getImage } from './functions/get_image';
+
var runtime = {};
var server_time_diff;
var server_os;
@@ -160,9 +182,9 @@ export function onload3 () {
var presetCharts = {
// Query cache efficiency
'qce': {
- title: PMA_messages.strQueryCacheEfficiency,
+ title: messages.strQueryCacheEfficiency,
series: [{
- label: PMA_messages.strQueryCacheEfficiency
+ label: messages.strQueryCacheEfficiency
}],
nodes: [{
dataPoints: [{ type: 'statusvar', name: 'Qcache_hits' }, { type: 'statusvar', name: 'Com_select' }],
@@ -172,9 +194,9 @@ export function onload3 () {
},
// Query cache usage
'qcu': {
- title: PMA_messages.strQueryCacheUsage,
+ title: messages.strQueryCacheUsage,
series: [{
- label: PMA_messages.strQueryCacheUsed
+ label: messages.strQueryCacheUsed
}],
nodes: [{
dataPoints: [{ type: 'statusvar', name: 'Qcache_free_memory' }, { type: 'servervar', name: 'query_cache_size' }],
@@ -188,150 +210,21 @@ export function onload3 () {
var selectionTimeDiff = [];
var selectionStartX;
var selectionStartY;
- var selectionEndX;
- var selectionEndY;
+ // var selectionEndX;
+ // var selectionEndY;
var drawTimeSpan = false;
// chart tooltip
- var tooltipBox;
+ // var tooltipBox;
- /* Add OS specific system info charts to the preset chart list */
- switch (server_os) {
- case 'WINNT':
- $.extend(presetCharts, {
- 'cpu': {
- title: PMA_messages.strSystemCPUUsage,
- series: [{
- label: PMA_messages.strAverageLoad
- }],
- nodes: [{
- dataPoints: [{ type: 'cpu', name: 'loadavg' }]
- }],
- maxYLabel: 100
- },
-
- 'memory': {
- title: PMA_messages.strSystemMemory,
- series: [{
- label: PMA_messages.strTotalMemory,
- fill: true
- }, {
- dataType: 'memory',
- label: PMA_messages.strUsedMemory,
- fill: true
- }],
- nodes: [{ dataPoints: [{ type: 'memory', name: 'MemTotal' }], valueDivisor: 1024 },
- { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 }
- ],
- maxYLabel: 0
- },
-
- 'swap': {
- title: PMA_messages.strSystemSwap,
- series: [{
- label: PMA_messages.strTotalSwap,
- fill: true
- }, {
- label: PMA_messages.strUsedSwap,
- fill: true
- }],
- nodes: [{ dataPoints: [{ type: 'memory', name: 'SwapTotal' }] },
- { dataPoints: [{ type: 'memory', name: 'SwapUsed' }] }
- ],
- maxYLabel: 0
- }
- });
- break;
-
- case 'Linux':
- $.extend(presetCharts, {
- 'cpu': {
- title: PMA_messages.strSystemCPUUsage,
- series: [{
- label: PMA_messages.strAverageLoad
- }],
- nodes: [{ dataPoints: [{ type: 'cpu', name: 'irrelevant' }], transformFn: 'cpu-linux' }],
- maxYLabel: 0
- },
- 'memory': {
- title: PMA_messages.strSystemMemory,
- series: [
- { label: PMA_messages.strBufferedMemory, fill: true },
- { label: PMA_messages.strUsedMemory, fill: true },
- { label: PMA_messages.strCachedMemory, fill: true },
- { label: PMA_messages.strFreeMemory, fill: true }
- ],
- nodes: [
- { dataPoints: [{ type: 'memory', name: 'Buffers' }], valueDivisor: 1024 },
- { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 },
- { dataPoints: [{ type: 'memory', name: 'Cached' }], valueDivisor: 1024 },
- { dataPoints: [{ type: 'memory', name: 'MemFree' }], valueDivisor: 1024 }
- ],
- maxYLabel: 0
- },
- 'swap': {
- title: PMA_messages.strSystemSwap,
- series: [
- { label: PMA_messages.strCachedSwap, fill: true },
- { label: PMA_messages.strUsedSwap, fill: true },
- { label: PMA_messages.strFreeSwap, fill: true }
- ],
- nodes: [
- { dataPoints: [{ type: 'memory', name: 'SwapCached' }], valueDivisor: 1024 },
- { dataPoints: [{ type: 'memory', name: 'SwapUsed' }], valueDivisor: 1024 },
- { dataPoints: [{ type: 'memory', name: 'SwapFree' }], valueDivisor: 1024 }
- ],
- maxYLabel: 0
- }
- });
- break;
-
- case 'SunOS':
- $.extend(presetCharts, {
- 'cpu': {
- title: PMA_messages.strSystemCPUUsage,
- series: [{
- label: PMA_messages.strAverageLoad
- }],
- nodes: [{
- dataPoints: [{ type: 'cpu', name: 'loadavg' }]
- }],
- maxYLabel: 0
- },
- 'memory': {
- title: PMA_messages.strSystemMemory,
- series: [
- { label: PMA_messages.strUsedMemory, fill: true },
- { label: PMA_messages.strFreeMemory, fill: true }
- ],
- nodes: [
- { dataPoints: [{ type: 'memory', name: 'MemUsed' }], valueDivisor: 1024 },
- { dataPoints: [{ type: 'memory', name: 'MemFree' }], valueDivisor: 1024 }
- ],
- maxYLabel: 0
- },
- 'swap': {
- title: PMA_messages.strSystemSwap,
- series: [
- { label: PMA_messages.strUsedSwap, fill: true },
- { label: PMA_messages.strFreeSwap, fill: true }
- ],
- nodes: [
- { dataPoints: [{ type: 'memory', name: 'SwapUsed' }], valueDivisor: 1024 },
- { dataPoints: [{ type: 'memory', name: 'SwapFree' }], valueDivisor: 1024 }
- ],
- maxYLabel: 0
- }
- });
- break;
- }
+ getOsDetail(server_os, presetCharts);
// Default setting for the chart grid
var defaultChartGrid = {
'c0': {
- title: PMA_messages.strQuestions,
+ title: messages.strQuestions,
series: [
- { label: PMA_messages.strQuestions }
+ { label: messages.strQuestions }
],
nodes: [
{ dataPoints: [{ type: 'statusvar', name: 'Questions' }], display: 'differential' }
@@ -339,10 +232,10 @@ export function onload3 () {
maxYLabel: 0
},
'c1': {
- title: PMA_messages.strChartConnectionsTitle,
+ title: messages.strChartConnectionsTitle,
series: [
- { label: PMA_messages.strConnections },
- { label: PMA_messages.strProcesses }
+ { label: messages.strConnections },
+ { label: messages.strProcesses }
],
nodes: [
{ dataPoints: [{ type: 'statusvar', name: 'Connections' }], display: 'differential' },
@@ -351,10 +244,10 @@ export function onload3 () {
maxYLabel: 0
},
'c2': {
- title: PMA_messages.strTraffic,
+ title: messages.strTraffic,
series: [
- { label: PMA_messages.strBytesSent },
- { label: PMA_messages.strBytesReceived }
+ { label: messages.strBytesSent },
+ { label: messages.strBytesReceived }
],
nodes: [
{ dataPoints: [{ type: 'statusvar', name: 'Bytes_sent' }], display: 'differential', valueDivisor: 1024 },
@@ -486,7 +379,7 @@ export function onload3 () {
event.preventDefault();
var dlgButtons = { };
- dlgButtons[PMA_messages.strAddChart] = function () {
+ dlgButtons[messages.strAddChart] = function () {
var type = $('input[name="chartType"]:checked').val();
if (type === 'preset') {
@@ -496,7 +389,7 @@ export function onload3 () {
// each time he adds a series
// So here we only warn if he didn't add a series yet
if (! newChart || ! newChart.nodes || newChart.nodes.length === 0) {
- alert(PMA_messages.strAddOneSeriesWarning);
+ alert(messages.strAddOneSeriesWarning);
return;
}
}
@@ -512,7 +405,7 @@ export function onload3 () {
$(this).dialog('close');
};
- dlgButtons[PMA_messages.strClose] = function () {
+ dlgButtons[messages.strClose] = function () {
newChart = null;
$('span#clearSeriesLink').hide();
$('#seriesPreview').html('');
@@ -553,7 +446,7 @@ export function onload3 () {
buttons: dlgButtons
});
- $('#seriesPreview').html('' + PMA_messages.strNone + '');
+ $('#seriesPreview').html('' + messages.strNone + '');
return false;
});
@@ -580,18 +473,18 @@ export function onload3 () {
$('a[href="#importMonitorConfig"]').on('click', function (event) {
event.preventDefault();
- $('#emptyDialog').dialog({ title: PMA_messages.strImportDialogTitle });
- $('#emptyDialog').html(PMA_messages.strImportDialogMessage + ': ');
var dlgBtns = {};
- dlgBtns[PMA_messages.strImport] = function () {
+ dlgBtns[messages.strImport] = function () {
var input = $('#emptyDialog').find('#import_file')[0];
var reader = new FileReader();
reader.onerror = function (event) {
- alert(PMA_messages.strFailedParsingConfig + '\n' + event.target.error.code);
+ alert(messages.strFailedParsingConfig + '\n' + event.target.error.code);
};
reader.onload = function (e) {
var data = e.target.result;
@@ -600,14 +493,14 @@ export function onload3 () {
try {
json = JSON.parse(data);
} catch (err) {
- alert(PMA_messages.strFailedParsingConfig);
+ alert(messages.strFailedParsingConfig);
$('#emptyDialog').dialog('close');
return;
}
// Basic check, is this a monitor config json?
if (!json || ! json.monitorCharts || ! json.monitorCharts) {
- alert(PMA_messages.strFailedParsingConfig);
+ alert(messages.strFailedParsingConfig);
$('#emptyDialog').dialog('close');
return;
}
@@ -618,8 +511,7 @@ export function onload3 () {
window.localStorage.monitorSettings = JSON.stringify(json.monitorSettings);
rebuildGrid();
} catch (err) {
- console.log(err);
- alert(PMA_messages.strFailedBuildingGrid);
+ alert(messages.strFailedBuildingGrid);
// If an exception is thrown, load default again
if (isStorageSupported('localStorage')) {
window.localStorage.removeItem('monitorCharts');
@@ -633,7 +525,7 @@ export function onload3 () {
reader.readAsText(input.files[0]);
};
- dlgBtns[PMA_messages.strCancel] = function () {
+ dlgBtns[messages.strCancel] = function () {
$(this).dialog('close');
};
@@ -659,9 +551,9 @@ export function onload3 () {
event.preventDefault();
runtime.redrawCharts = ! runtime.redrawCharts;
if (! runtime.redrawCharts) {
- $(this).html(PMA_getImage('play') + PMA_messages.strResumeMonitor);
+ $(this).html(PMA_getImage('play') + messages.strResumeMonitor);
} else {
- $(this).html(PMA_getImage('pause') + PMA_messages.strPauseMonitor);
+ $(this).html(PMA_getImage('pause') + messages.strPauseMonitor);
if (! runtime.charts) {
initGrid();
$('a[href="#settingsPopup"]').show();
@@ -686,7 +578,7 @@ export function onload3 () {
$.extend(vars, getvars);
}
- $.get('server_status_monitor.php' + PMA_commonParams.get('common_query'), vars,
+ $.get('server_status_monitor.php' + CommonParams.get('common_query'), vars,
function (data) {
var logVars;
if (typeof data !== 'undefined' && data.success === true) {
@@ -700,40 +592,40 @@ export function onload3 () {
if (logVars.general_log === 'ON') {
if (logVars.slow_query_log === 'ON') {
- msg = PMA_messages.strBothLogOn;
+ msg = messages.strBothLogOn;
} else {
- msg = PMA_messages.strGenLogOn;
+ msg = messages.strGenLogOn;
}
}
if (msg.length === 0 && logVars.slow_query_log === 'ON') {
- msg = PMA_messages.strSlowLogOn;
+ msg = messages.strSlowLogOn;
}
if (msg.length === 0) {
icon = PMA_getImage('s_error');
- msg = PMA_messages.strBothLogOff;
+ msg = messages.strBothLogOff;
}
- str = '' + PMA_messages.strCurrentSettings + '
';
+ str = ' ' + messages.strCurrentSettings + '';
str += icon + msg + ' ';
if (logVars.log_output !== 'TABLE') {
- str += PMA_getImage('s_error') + ' ' + PMA_messages.strLogOutNotTable + ' ';
+ str += PMA_getImage('s_error') + ' ' + messages.strLogOutNotTable + ' ';
} else {
- str += PMA_getImage('s_success') + ' ' + PMA_messages.strLogOutIsTable + ' ';
+ str += PMA_getImage('s_success') + ' ' + messages.strLogOutIsTable + ' ';
}
if (logVars.slow_query_log === 'ON') {
if (logVars.long_query_time > 2) {
str += PMA_getImage('s_attention') + ' ';
- str += PMA_sprintf(PMA_messages.strSmallerLongQueryTimeAdvice, logVars.long_query_time);
+ str += PMA_sprintf(messages.strSmallerLongQueryTimeAdvice, logVars.long_query_time);
str += ' ';
}
if (logVars.long_query_time < 2) {
str += PMA_getImage('s_success') + ' ';
- str += PMA_sprintf(PMA_messages.strLongQueryTimeSet, logVars.long_query_time);
+ str += PMA_sprintf(messages.strLongQueryTimeSet, logVars.long_query_time);
str += ' ';
}
}
@@ -741,9 +633,9 @@ export function onload3 () {
str += ' ';
if (is_superuser) {
- str += ' ' + PMA_messages.strChangeSettings + '';
+ str += ' ' + messages.strChangeSettings + '';
str += ' ';
- str += PMA_messages.strSettingsAppliedGlobal + ' ';
+ str += messages.strSettingsAppliedGlobal + ' ';
var varValue = 'TABLE';
if (logVars.log_output === 'TABLE') {
@@ -751,26 +643,26 @@ export function onload3 () {
}
str += '- ';
- str += PMA_sprintf(PMA_messages.strSetLogOutput, varValue);
+ str += PMA_sprintf(messages.strSetLogOutput, varValue);
str += ' ';
if (logVars.general_log !== 'ON') {
str += '- ';
- str += PMA_sprintf(PMA_messages.strEnableVar, 'general_log');
+ str += PMA_sprintf(messages.strEnableVar, 'general_log');
str += ' ';
} else {
str += '- ';
- str += PMA_sprintf(PMA_messages.strDisableVar, 'general_log');
+ str += PMA_sprintf(messages.strDisableVar, 'general_log');
str += ' ';
}
if (logVars.slow_query_log !== 'ON') {
str += '- ';
- str += PMA_sprintf(PMA_messages.strEnableVar, 'slow_query_log');
+ str += PMA_sprintf(messages.strEnableVar, 'slow_query_log');
str += ' ';
} else {
str += '- ';
- str += PMA_sprintf(PMA_messages.strDisableVar, 'slow_query_log');
+ str += PMA_sprintf(messages.strDisableVar, 'slow_query_log');
str += ' ';
}
@@ -780,10 +672,10 @@ export function onload3 () {
}
str += '- ';
- str += PMA_sprintf(PMA_messages.setSetLongQueryTime, varValue);
+ str += PMA_sprintf(messages.setSetLongQueryTime, varValue);
str += ' ';
} else {
- str += PMA_messages.strNoSuperUser + ' ';
+ str += messages.strNoSuperUser + ' ';
}
str += ' ';
@@ -812,7 +704,7 @@ export function onload3 () {
$('input[name="chartType"]').on('change', function () {
$('#chartVariableSettings').toggle(this.checked && this.value === 'variable');
var title = $('input[name="chartTitle"]').val();
- if (title === PMA_messages.strChartTitle ||
+ if (title === messages.strChartTitle ||
title === $('label[for="' + $('input[name="chartTitle"]').data('lastRadio') + '"]').text()
) {
$('input[name="chartTitle"]')
@@ -838,7 +730,7 @@ export function onload3 () {
$('a[href="#kibDivisor"]').on('click', function (event) {
event.preventDefault();
$('input[name="valueDivisor"]').val(1024);
- $('input[name="valueUnit"]').val(PMA_messages.strKiB);
+ $('input[name="valueUnit"]').val(messages.strKiB);
$('span.unitInput').toggle(true);
$('input[name="useUnit"]').prop('checked', true);
return false;
@@ -847,7 +739,7 @@ export function onload3 () {
$('a[href="#mibDivisor"]').on('click', function (event) {
event.preventDefault();
$('input[name="valueDivisor"]').val(1024 * 1024);
- $('input[name="valueUnit"]').val(PMA_messages.strMiB);
+ $('input[name="valueUnit"]').val(messages.strMiB);
$('span.unitInput').toggle(true);
$('input[name="useUnit"]').prop('checked', true);
return false;
@@ -855,7 +747,7 @@ export function onload3 () {
$('a[href="#submitClearSeries"]').on('click', function (event) {
event.preventDefault();
- $('#seriesPreview').html(' ' + PMA_messages.strNone + '');
+ $('#seriesPreview').html(' ' + messages.strNone + '');
newChart = null;
$('#clearSeriesLink').hide();
});
@@ -894,9 +786,9 @@ export function onload3 () {
serie.unit = $('input[name="valueUnit"]').val();
}
- var str = serie.display === 'differential' ? ', ' + PMA_messages.strDifferential : '';
- str += serie.valueDivisor ? (', ' + PMA_sprintf(PMA_messages.strDividedBy, serie.valueDivisor)) : '';
- str += serie.unit ? (', ' + PMA_messages.strUnit + ': ' + serie.unit) : '';
+ var str = serie.display === 'differential' ? ', ' + messages.strDifferential : '';
+ str += serie.valueDivisor ? (', ' + PMA_sprintf(messages.strDividedBy, serie.valueDivisor)) : '';
+ str += serie.unit ? (', ' + messages.strUnit + ': ' + serie.unit) : '';
var newSeries = {
label: $('#variableInput').val().replace(/_/g, ' ')
@@ -940,11 +832,11 @@ export function onload3 () {
&& typeof window.localStorage.monitorVersion !== 'undefined'
&& monitorProtocolVersion !== window.localStorage.monitorVersion
) {
- $('#emptyDialog').dialog({ title: PMA_messages.strIncompatibleMonitorConfig });
- $('#emptyDialog').html(PMA_messages.strIncompatibleMonitorConfigDescription);
+ $('#emptyDialog').dialog({ title: messages.strIncompatibleMonitorConfig });
+ $('#emptyDialog').html(messages.strIncompatibleMonitorConfigDescription);
var dlgBtns = {};
- dlgBtns[PMA_messages.strClose] = function () {
+ dlgBtns[messages.strClose] = function () {
$(this).dialog('close');
};
@@ -1092,25 +984,25 @@ export function onload3 () {
}
};
- if (settings.title === PMA_messages.strSystemCPUUsage ||
- settings.title === PMA_messages.strQueryCacheEfficiency
+ if (settings.title === messages.strSystemCPUUsage ||
+ settings.title === messages.strQueryCacheEfficiency
) {
settings.axes.yaxis.tickOptions = {
formatString: '%d %%'
};
- } else if (settings.title === PMA_messages.strSystemMemory ||
- settings.title === PMA_messages.strSystemSwap
+ } else if (settings.title === messages.strSystemMemory ||
+ settings.title === messages.strSystemSwap
) {
settings.stackSeries = true;
settings.axes.yaxis.tickOptions = {
formatter: $.jqplot.byteFormatter(2) // MiB
};
- } else if (settings.title === PMA_messages.strTraffic) {
+ } else if (settings.title === messages.strTraffic) {
settings.axes.yaxis.tickOptions = {
formatter: $.jqplot.byteFormatter(1) // KiB
};
- } else if (settings.title === PMA_messages.strQuestions ||
- settings.title === PMA_messages.strConnections
+ } else if (settings.title === messages.strQuestions ||
+ settings.title === messages.strConnections
) {
settings.axes.yaxis.tickOptions = {
formatter: function (format, val) {
@@ -1306,12 +1198,12 @@ export function onload3 () {
var dlgBtns = { };
- dlgBtns[PMA_messages.strFromSlowLog] = function () {
+ dlgBtns[messages.strFromSlowLog] = function () {
loadLog('slow', min, max);
$(this).dialog('close');
};
- dlgBtns[PMA_messages.strFromGeneralLog] = function () {
+ dlgBtns[messages.strFromGeneralLog] = function () {
loadLog('general', min, max);
$(this).dialog('close');
};
@@ -1352,12 +1244,12 @@ export function onload3 () {
/* 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'), {
+ runtime.refreshRequest = $.post('server_status_monitor.php' + CommonParams.get('common_query'), {
ajax_request: true,
chart_data: 1,
type: 'chartgrid',
requiredData: JSON.stringify(runtime.dataList),
- server: PMA_commonParams.get('server')
+ server: CommonParams.get('server')
}, function (data) {
var chartData;
if (typeof data !== 'undefined' && data.success === true) {
@@ -1448,8 +1340,8 @@ export function onload3 () {
elem.chart.series[j].data.splice(0, elem.chart.series[j].data.length - runtime.gridMaxPoints);
}
}
- if (elem.title === PMA_messages.strSystemMemory ||
- elem.title === PMA_messages.strSystemSwap
+ if (elem.title === messages.strSystemMemory ||
+ elem.title === messages.strSystemSwap
) {
total += value;
}
@@ -1463,15 +1355,15 @@ export function onload3 () {
(runtime.xmax - tickInterval * 3), (runtime.xmax - tickInterval * 2),
(runtime.xmax - tickInterval), runtime.xmax];
- if (elem.title !== PMA_messages.strSystemCPUUsage &&
- elem.title !== PMA_messages.strQueryCacheEfficiency &&
- elem.title !== PMA_messages.strSystemMemory &&
- elem.title !== PMA_messages.strSystemSwap
+ if (elem.title !== messages.strSystemCPUUsage &&
+ elem.title !== messages.strQueryCacheEfficiency &&
+ elem.title !== messages.strSystemMemory &&
+ elem.title !== messages.strSystemSwap
) {
elem.chart.axes.yaxis.max = Math.ceil(elem.maxYLabel * 1.1);
elem.chart.axes.yaxis.tickInterval = Math.ceil(elem.maxYLabel * 1.1 / 5);
- } else if (elem.title === PMA_messages.strSystemMemory ||
- elem.title === PMA_messages.strSystemSwap
+ } else if (elem.title === messages.strSystemMemory ||
+ elem.title === messages.strSystemSwap
) {
elem.chart.axes.yaxis.max = Math.ceil(total * 1.1 / 100) * 100;
elem.chart.axes.yaxis.tickInterval = Math.ceil(total * 1.1 / 5);
@@ -1571,13 +1463,13 @@ export function onload3 () {
opts.limitTypes = false;
}
- $('#emptyDialog').dialog({ title: PMA_messages.strAnalysingLogsTitle });
- $('#emptyDialog').html(PMA_messages.strAnalysingLogs +
+ $('#emptyDialog').dialog({ title: messages.strAnalysingLogsTitle });
+ $('#emptyDialog').html(messages.strAnalysingLogs +
'  ');
var dlgBtns = {};
- dlgBtns[PMA_messages.strCancelRequest] = function () {
+ dlgBtns[messages.strCancelRequest] = function () {
if (logRequest !== null) {
logRequest.abort();
}
@@ -1592,7 +1484,7 @@ export function onload3 () {
});
- logRequest = $.get('server_status_monitor.php' + PMA_commonParams.get('common_query'),
+ logRequest = $.get('server_status_monitor.php' + CommonParams.get('common_query'),
{ ajax_request: true,
log_data: 1,
type: opts.src,
@@ -1611,10 +1503,10 @@ export function onload3 () {
}
if (logData.rows.length === 0) {
- $('#emptyDialog').dialog({ title: PMA_messages.strNoDataFoundTitle });
- $('#emptyDialog').html(' ' + PMA_messages.strNoDataFound + ' ');
+ $('#emptyDialog').dialog({ title: messages.strNoDataFoundTitle });
+ $('#emptyDialog').html(' ' + messages.strNoDataFound + ' ');
- dlgBtns[PMA_messages.strClose] = function () {
+ dlgBtns[messages.strClose] = function () {
$(this).dialog('close');
};
@@ -1625,8 +1517,8 @@ export function onload3 () {
runtime.logDataCols = buildLogTable(logData, opts.removeVariables);
/* Show some stats in the dialog */
- $('#emptyDialog').dialog({ title: PMA_messages.strLoadingLogs });
- $('#emptyDialog').html(' ' + PMA_messages.strLogDataLoaded + ' ');
+ $('#emptyDialog').dialog({ title: messages.strLoadingLogs });
+ $('#emptyDialog').html(' ' + messages.strLogDataLoaded + ' ');
$.each(logData.sum, function (key, value) {
key = key.charAt(0).toUpperCase() + key.slice(1).toLowerCase();
if (key === 'Total') {
@@ -1639,15 +1531,15 @@ export function onload3 () {
if (logData.numRows > 12) {
$('#logTable').prepend(
' ';
}
- explain += '' + PMA_messages.strAffectedRows + ' ' + data.affectedRows;
+ explain += ' ' + messages.strAffectedRows + ' ' + data.affectedRows;
$('#queryAnalyzerDialog').find('div.placeHolder td.explain').append(explain);
@@ -2059,7 +1951,7 @@ export function onload3 () {
if (data.profiling) {
var chartData = [];
- var numberTable = ' | ' + PMA_messages.strStatus + ' | ' + PMA_messages.strTime + ' | ';
+ var numberTable = '| ' + messages.strStatus + ' | ' + messages.strTime + ' | ';
var duration;
var otherTime = 0;
@@ -2083,15 +1975,15 @@ export function onload3 () {
}
if (otherTime > 0) {
- chartData.push([PMA_prettyProfilingNum(otherTime, 2) + ' ' + PMA_messages.strOther, otherTime]);
+ chartData.push([PMA_prettyProfilingNum(otherTime, 2) + ' ' + messages.strOther, otherTime]);
}
- numberTable += '| ' + PMA_messages.strTotalTime + ' | ' + PMA_prettyProfilingNum(totalTime, 2) + ' | ';
+ numberTable += '| ' + messages.strTotalTime + ' | ' + PMA_prettyProfilingNum(totalTime, 2) + ' | ';
numberTable += ' ';
$('#queryAnalyzerDialog').find('div.placeHolder td.chart').append(
- '' + PMA_messages.strProfilingResults + ' ' + $('#profiling_docu').html() + ' ' +
- '(' + PMA_messages.strTable + ', ' + PMA_messages.strChart + ') ' +
+ '' + messages.strProfilingResults + ' ' + $('#profiling_docu').html() + ' ' +
+ '(' + messages.strTable + ', ' + messages.strChart + ') ' +
numberTable + ' ');
$('#queryAnalyzerDialog').find('div.placeHolder a[href="#showNums"]').on('click', function () {
@@ -2106,7 +1998,7 @@ export function onload3 () {
return false;
});
- profilingChart = PMA_createProfilingChart(
+ profilingChart = createProfilingChart(
'queryProfiling',
chartData
);
@@ -2119,7 +2011,6 @@ export function onload3 () {
/* Saves the monitor to localstorage */
function saveMonitor () {
var gridCopy = {};
-
$.each(runtime.charts, function (key, elem) {
gridCopy[key] = {};
gridCopy[key].nodes = elem.nodes;
@@ -2146,13 +2037,13 @@ export function onload4 () {
function serverResponseError () {
var btns = {};
- btns[PMA_messages.strReloadPage] = function () {
+ btns[messages.strReloadPage] = function () {
window.location.reload();
};
- $('#emptyDialog').dialog({ title: PMA_messages.strRefreshFailed });
+ $('#emptyDialog').dialog({ title: messages.strRefreshFailed });
$('#emptyDialog').html(
PMA_getImage('s_attention') +
- PMA_messages.strInvalidResponseExplanation
+ messages.strInvalidResponseExplanation
);
$('#emptyDialog').dialog({ buttons: btns });
}
diff --git a/js/src/server_status_queries.js b/js/src/server_status_queries.js
index f5b151dd96..44f0eca50d 100644
--- a/js/src/server_status_queries.js
+++ b/js/src/server_status_queries.js
@@ -4,8 +4,8 @@
* Module import
*/
import { createProfilingChart } from './functions/chart';
-import { jQuery as $ } from './utils/JqueryExtended';
-import { initTableSorter } from './server_status_sorter';
+import { $ } from './utils/JqueryExtended';
+import { initTableSorter } from './functions/Server/SeverStatusSorter';
/**
* @package PhpMyAdmin
diff --git a/js/src/server_status_sorter.js b/js/src/server_status_sorter.js
index 6171a83f06..ac5cdc4032 100644
--- a/js/src/server_status_sorter.js
+++ b/js/src/server_status_sorter.js
@@ -1,25 +1,11 @@
-import { PMA_Messages as PMA_messages } from './variables/export_variables';
-// TODO: tablesorter shouldn't sort already sorted columns
-export function initTableSorter (tabid) {
- var $table;
- var opts;
- switch (tabid) {
- case 'statustabs_queries':
- $table = $('#serverstatusqueriesdetails');
- opts = {
- sortList: [[3, 1]],
- headers: {
- // 1: { sorter: 'fancyNumber' },
- // 2: { sorter: 'fancyNumber' }
- }
- };
- break;
- }
- $table.tablesorter(opts);
- $table.find('tr:first th')
- .append('')
- .addClass('header');
-}
+/* vim: set expandtab sw=4 ts=4 sts=4: */
+
+/**
+ * Module import
+ */
+import { $ } from './utils/JqueryExtended';
+import './plugins/jquery/jquery.tablesorter';
+import { PMA_Messages as messages } from './variables/export_variables';
$(function () {
$.tablesorter.addParser({
@@ -29,8 +15,8 @@ $(function () {
},
format: function (s) {
var num = $.tablesorter.formatFloat(
- s.replace(PMA_messages.strThousandsSeparator, '')
- .replace(PMA_messages.strDecimalSeparator, '.')
+ s.replace(messages.strThousandsSeparator, '')
+ .replace(messages.strDecimalSeparator, '.')
);
var factor = 1;
diff --git a/js/src/server_user_groups.js b/js/src/server_user_groups.js
index 1c0dec0758..bdc33b2c77 100644
--- a/js/src/server_user_groups.js
+++ b/js/src/server_user_groups.js
@@ -3,7 +3,7 @@
/**
* Module import
*/
-import { PMA_Messages as PMA_messages } from './variables/export_variables';
+import { PMA_Messages as messages } from './variables/export_variables';
import { PMA_sprintf } from './utils/sprintf';
import { escapeHtml } from './utils/Sanitise';
@@ -25,6 +25,7 @@ function teardownServerUserGroups () {
*/
function onloadServerUserGroups () {
// update the checkall checkbox on Edit user group page
+ // console.log($('input.checkall:checkbox:enabled'));
$(checkboxes_sel).trigger('change');
$(document).on('click', 'a.deleteUserGroup.ajax', function (event) {
@@ -32,22 +33,22 @@ function onloadServerUserGroups () {
var $link = $(this);
var groupName = $link.parents('tr').find('td:first').text();
var buttonOptions = {};
- buttonOptions[PMA_messages.strGo] = function () {
+ buttonOptions[messages.strGo] = function () {
$(this).dialog('close');
$link.removeClass('ajax').trigger('click');
};
- buttonOptions[PMA_messages.strClose] = function () {
+ buttonOptions[messages.strClose] = function () {
$(this).dialog('close');
};
$('')
.attr('id', 'confirmUserGroupDeleteDialog')
- .append(PMA_sprintf(PMA_messages.strDropUserGroupWarning, escapeHtml(groupName)))
+ .append(PMA_sprintf(messages.strDropUserGroupWarning, escapeHtml(groupName)))
.dialog({
width: 300,
minWidth: 200,
modal: true,
buttons: buttonOptions,
- title: PMA_messages.strConfirm,
+ title: messages.strConfirm,
close: function () {
$(this).remove();
}
diff --git a/js/src/server_variables.js b/js/src/server_variables.js
index c49fcb29a0..f4ec19bf3d 100644
--- a/js/src/server_variables.js
+++ b/js/src/server_variables.js
@@ -3,6 +3,7 @@
/**
* Module import
*/
+import { $ } from './utils/JqueryExtended';
import { editVariable } from './functions/Server/ServerVariables';
/**
diff --git a/js/src/sql.js b/js/src/sql.js
new file mode 100644
index 0000000000..4d1edefae3
--- /dev/null
+++ b/js/src/sql.js
@@ -0,0 +1,868 @@
+/* vim: set expandtab sw=4 ts=4 sts=4: */
+import { $ } from './utils/JqueryExtended';
+import './plugins/jquery/jquery.uitablefilter';
+import { PMA_Messages as PMA_messages } from './variables/export_variables';
+import PMA_commonParams from './variables/common_params';
+import { PMA_commonActions } from './classes/CommonActions';
+import PMA_MicroHistory from './classes/MicroHistory';
+
+
+import { isStorageSupported } from './functions/config';
+import { PMA_sprintf } from './utils/sprintf';
+import { escapeHtml } from './utils/Sanitise';
+import { PMA_ajaxShowMessage, PMA_ajaxRemoveMessage } from './utils/show_ajax_messages';
+import { initStickyColumns, rearrangeStickyColumns, handleStickyColumns } from './functions/Grid/StickyColumns';
+import { PMA_makegrid } from './utils/makegrid';
+import { AJAX } from './ajax';
+import { initProfilingTables, makeProfilingChart } from './functions/Sql/SqlProfiling';
+import { PMA_highlightSQL } from './utils/sql';
+import { sqlQueryOptions } from './utils/sql';
+import Cookies from 'js-cookie';
+import { printPreview } from './functions/Print';
+
+import {
+ setShowThisQuery, PMA_autosaveSQL, PMA_autosaveSQLSort, PMA_showThisQuery,
+ checkSavedQuery, setQuery, checkSqlQuery, PMA_handleSimulateQueryButton, insertValueQuery
+} from './functions/Sql/SqlQuery';
+
+/**
+ * @fileoverview functions used wherever an sql query form is used
+ *
+ * @requires jQuery
+ * @requires js/functions.js
+ *
+ */
+
+var $data_a;
+
+/**
+ * Unbind all event handlers before tearing down a page
+ */
+export function teardown1 () {
+ $(document).off('click', 'a.delete_row.ajax');
+ $(document).off('submit', '.bookmarkQueryForm');
+ $('input#bkm_label').off('keyup');
+ $(document).off('makegrid', '.sqlqueryresults');
+ $(document).off('stickycolumns', '.sqlqueryresults');
+ $('#togglequerybox').off('click');
+ $(document).off('click', '#button_submit_query');
+ $(document).off('change', '#id_bookmark');
+ $('input[name=\'bookmark_variable\']').off('keypress');
+ $(document).off('submit', '#sqlqueryform.ajax');
+ $(document).off('click', 'input[name=navig].ajax');
+ $(document).off('submit', 'form[name=\'displayOptionsForm\'].ajax');
+ $(document).off('mouseenter', 'th.column_heading.pointer');
+ $(document).off('mouseleave', 'th.column_heading.pointer');
+ $(document).off('click', 'th.column_heading.marker');
+ $(window).off('scroll');
+ $(document).off('keyup', '.filter_rows');
+ $(document).off('click', '#printView');
+ if (sqlQueryOptions.codemirror_editor) {
+ sqlQueryOptions.codemirror_editor.off('change');
+ } else {
+ $('#sqlquery').off('input propertychange');
+ }
+ $('body').off('click', '.navigation .showAllRows');
+ $('body').off('click', 'a.browse_foreign');
+ $('body').off('click', '#simulate_dml');
+ $('body').off('keyup', '#sqlqueryform');
+ $('body').off('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]');
+}
+
+/**
+ * @description Ajax scripts for sql and browse pages
+ *
+ * Actions ajaxified here:
+ *
+ * - Retrieve results of an SQL query
+ * - Paginate the results table
+ * - Sort the results table
+ * - Change table according to display options
+ * - Grid editing of data
+ * - Saving a bookmark
+ *
+ *
+ * @name document.ready
+ * @memberOf jQuery
+ */
+export function onload1 () {
+ if (sqlQueryOptions.codemirror_editor || document.sqlform) {
+ setShowThisQuery();
+ }
+ $(function () {
+ if (sqlQueryOptions.codemirror_editor) {
+ sqlQueryOptions.codemirror_editor.on('change', function () {
+ PMA_autosaveSQL(sqlQueryOptions.codemirror_editor.getValue());
+ });
+ } else {
+ $('#sqlquery').on('input propertychange', function () {
+ PMA_autosaveSQL($('#sqlquery').val());
+ });
+ // Save sql query with sort
+ if ($('#RememberSorting') !== undefined && $('#RememberSorting').is(':checked')) {
+ $('select[name="sql_query"]').on('change', function () {
+ PMA_autosaveSQLSort($('select[name="sql_query"]').val());
+ });
+ } else {
+ if (isStorageSupported('localStorage')
+ && window.localStorage.auto_saved_sql_sort !== undefined
+ ) {
+ window.localStorage.removeItem('auto_saved_sql_sort');
+ } else {
+ Cookies.set('auto_saved_sql_sort', '');
+ }
+ }
+ // If sql query with sort for current table is stored, change sort by key select value
+ var sortStoredQuery = (isStorageSupported('localStorage')
+ && typeof window.localStorage.auto_saved_sql_sort !== 'undefined')
+ ? window.localStorage.auto_saved_sql_sort :
+ Cookies.get('auto_saved_sql_sort');
+ if (typeof sortStoredQuery !== 'undefined'
+ && sortStoredQuery !== $('select[name="sql_query"]').val()
+ && $('select[name="sql_query"] option[value="' + sortStoredQuery + '"]').length !== 0
+ ) {
+ $('select[name="sql_query"]').val(sortStoredQuery).trigger('change');
+ }
+ }
+ });
+
+ // Delete row from SQL results
+ $(document).on('click', 'a.delete_row.ajax', function (e) {
+ e.preventDefault();
+ var question = PMA_sprintf(PMA_messages.strDoYouReally, escapeHtml($(this).closest('td').find('div').text()));
+ var $link = $(this);
+ $link.PMA_confirm(question, $link.attr('href'), function (url) {
+ $msgbox = PMA_ajaxShowMessage();
+ var argsep = PMA_commonParams.get('arg_separator');
+ var params = 'ajax_request=1' + argsep + 'is_js_confirmed=1';
+ var postData = $link.getPostData();
+ if (postData) {
+ params += argsep + postData;
+ }
+ $.post(url, params, function (data) {
+ if (data.success) {
+ PMA_ajaxShowMessage(data.message);
+ $link.closest('tr').remove();
+ } else {
+ PMA_ajaxShowMessage(data.error, false);
+ }
+ });
+ });
+ });
+
+ // Ajaxification for 'Bookmark this SQL query'
+ $(document).on('submit', '.bookmarkQueryForm', function (e) {
+ e.preventDefault();
+ PMA_ajaxShowMessage();
+ var argsep = PMA_commonParams.get('arg_separator');
+ $.post($(this).attr('action'), 'ajax_request=1' + argsep + $(this).serialize(), function (data) {
+ if (data.success) {
+ PMA_ajaxShowMessage(data.message);
+ } else {
+ PMA_ajaxShowMessage(data.error, false);
+ }
+ });
+ });
+
+ /* Hides the bookmarkoptions checkboxes when the bookmark label is empty */
+ $('input#bkm_label').on('keyup', function () {
+ $('input#id_bkm_all_users, input#id_bkm_replace')
+ .parent()
+ .toggle($(this).val().length > 0);
+ }).trigger('keyup');
+
+ /**
+ * Attach Event Handler for 'Copy to clipbpard
+ */
+ $(document).on('click', '#copyToClipBoard', function (event) {
+ event.preventDefault();
+
+ var textArea = document.createElement('textarea');
+
+ //
+ // *** This styling is an extra step which is likely not required. ***
+ //
+ // Why is it here? To ensure:
+ // 1. the element is able to have focus and selection.
+ // 2. if element was to flash render it has minimal visual impact.
+ // 3. less flakyness with selection and copying which **might** occur if
+ // the textarea element is not visible.
+ //
+ // The likelihood is the element won't even render, not even a flash,
+ // so some of these are just precautions. However in IE the element
+ // is visible whilst the popup box asking the user for permission for
+ // the web page to copy to the clipboard.
+ //
+
+ // Place in top-left corner of screen regardless of scroll position.
+ textArea.style.position = 'fixed';
+ textArea.style.top = 0;
+ textArea.style.left = 0;
+
+ // Ensure it has a small width and height. Setting to 1px / 1em
+ // doesn't work as this gives a negative w/h on some browsers.
+ textArea.style.width = '2em';
+ textArea.style.height = '2em';
+
+ // We don't need padding, reducing the size if it does flash render.
+ textArea.style.padding = 0;
+
+ // Clean up any borders.
+ textArea.style.border = 'none';
+ textArea.style.outline = 'none';
+ textArea.style.boxShadow = 'none';
+
+ // Avoid flash of white box if rendered for any reason.
+ textArea.style.background = 'transparent';
+
+ textArea.value = '';
+
+ $('#serverinfo a').each(function () {
+ textArea.value += $(this).text().split(':')[1].trim() + '/';
+ });
+ textArea.value += '\t\t' + window.location.href;
+ textArea.value += '\n';
+ $('.success').each(function () {
+ textArea.value += $(this).text() + '\n\n';
+ });
+
+ $('.sql pre').each(function () {
+ textArea.value += $(this).text() + '\n\n';
+ });
+
+ $('.table_results .column_heading a').each(function () {
+ // Don't copy ordering number text within tag
+ textArea.value += $(this).clone().find('small').remove().end().text() + '\t';
+ });
+
+ textArea.value += '\n';
+ $('.table_results tbody tr').each(function () {
+ $(this).find('.data span').each(function () {
+ textArea.value += $(this).text() + '\t';
+ });
+ textArea.value += '\n';
+ });
+
+ document.body.appendChild(textArea);
+
+ textArea.select();
+
+ try {
+ document.execCommand('copy');
+ } catch (err) {
+ alert('Sorry! Unable to copy');
+ }
+
+ document.body.removeChild(textArea);
+ }); // end of Copy to Clipboard action
+
+ /**
+ * Attach Event Handler for 'Print' link
+ */
+ $(document).on('click', '#printView', function (event) {
+ event.preventDefault();
+
+ // Take to preview mode
+ printPreview();
+ }); // end of 'Print' action
+
+ /**
+ * Attach the {@link makegrid} function to a custom event, which will be
+ * triggered manually everytime the table of results is reloaded
+ * @memberOf jQuery
+ */
+ $(document).on('makegrid', '.sqlqueryresults', function () {
+ $('.table_results').each(function () {
+ PMA_makegrid(this);
+ });
+ });
+
+ /*
+ * Attach a custom event for sticky column headings which will be
+ * triggered manually everytime the table of results is reloaded
+ * @memberOf jQuery
+ */
+ $(document).on('stickycolumns', '.sqlqueryresults', function () {
+ $('.sticky_columns').remove();
+ $('.table_results').each(function () {
+ var $table_results = $(this);
+ // add sticky columns div
+ var $stick_columns = initStickyColumns($table_results);
+ rearrangeStickyColumns($stick_columns, $table_results);
+ // adjust sticky columns on scroll
+ $(window).on('scroll', function () {
+ handleStickyColumns($stick_columns, $table_results);
+ });
+ });
+ });
+
+ /**
+ * Append the "Show/Hide query box" message to the query input form
+ *
+ * @memberOf jQuery
+ * @name appendToggleSpan
+ */
+ // do not add this link more than once
+ if (! $('#sqlqueryform').find('a').is('#togglequerybox')) {
+ $('')
+ .html(PMA_messages.strHideQueryBox)
+ .appendTo('#sqlqueryform')
+ // initially hidden because at this point, nothing else
+ // appears under the link
+ .hide();
+
+ // Attach the toggling of the query box visibility to a click
+ $('#togglequerybox').bind('click', function () {
+ var $link = $(this);
+ $link.siblings().slideToggle('fast');
+ if ($link.text() === PMA_messages.strHideQueryBox) {
+ $link.text(PMA_messages.strShowQueryBox);
+ // cheap trick to add a spacer between the menu tabs
+ // and "Show query box"; feel free to improve!
+ $('#togglequerybox_spacer').remove();
+ $link.before(' ');
+ } else {
+ $link.text(PMA_messages.strHideQueryBox);
+ }
+ // avoid default click action
+ return false;
+ });
+ }
+
+
+ /**
+ * Event handler for sqlqueryform.ajax button_submit_query
+ *
+ * @memberOf jQuery
+ */
+ $(document).on('click', '#button_submit_query', function (event) {
+ $('.success,.error').hide();
+ // hide already existing error or success message
+ var $form = $(this).closest('form');
+ // the Go button related to query submission was clicked,
+ // instead of the one related to Bookmarks, so empty the
+ // id_bookmark selector to avoid misinterpretation in
+ // import.php about what needs to be done
+ $form.find('select[name=id_bookmark]').val('');
+ // let normal event propagation happen
+ if (isStorageSupported('localStorage')) {
+ window.localStorage.removeItem('auto_saved_sql');
+ } else {
+ Cookies.set('auto_saved_sql', '');
+ }
+ var isShowQuery = $('input[name="show_query"').is(':checked');
+ if (isShowQuery) {
+ window.localStorage.show_this_query = '1';
+ var db = $('input[name="db"]').val();
+ var table = $('input[name="table"]').val();
+ var query;
+ if (sqlQueryOptions.codemirror_editor) {
+ query = sqlQueryOptions.codemirror_editor.getValue();
+ } else {
+ query = $('#sqlquery').val();
+ }
+ PMA_showThisQuery(db, table, query);
+ } else {
+ window.localStorage.show_this_query = '0';
+ }
+ });
+
+ /**
+ * Event handler to show appropiate number of variable boxes
+ * based on the bookmarked query
+ */
+ $(document).on('change', '#id_bookmark', function (event) {
+ var varCount = $(this).find('option:selected').data('varcount');
+ if (typeof varCount === 'undefined') {
+ varCount = 0;
+ }
+
+ var $varDiv = $('#bookmark_variables');
+ $varDiv.empty();
+ for (var i = 1; i <= varCount; i++) {
+ $varDiv.append($(''));
+ $varDiv.append($(''));
+ }
+
+ if (varCount === 0) {
+ $varDiv.parent('.formelement').hide();
+ } else {
+ $varDiv.parent('.formelement').show();
+ }
+ });
+
+ /**
+ * Event handler for hitting enter on sqlqueryform bookmark_variable
+ * (the Variable textfield in Bookmarked SQL query section)
+ *
+ * @memberOf jQuery
+ */
+ $('input[name=bookmark_variable]').on('keypress', function (event) {
+ // force the 'Enter Key' to implicitly click the #button_submit_bookmark
+ var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
+ if (keycode === 13) { // keycode for enter key
+ // When you press enter in the sqlqueryform, which
+ // has 2 submit buttons, the default is to run the
+ // #button_submit_query, because of the tabindex
+ // attribute.
+ // This submits #button_submit_bookmark instead,
+ // because when you are in the Bookmarked SQL query
+ // section and hit enter, you expect it to do the
+ // same action as the Go button in that section.
+ $('#button_submit_bookmark').trigger('click');
+ return false;
+ } else {
+ return true;
+ }
+ });
+
+ /**
+ * Ajax Event handler for 'SQL Query Submit'
+ *
+ * @see PMA_ajaxShowMessage()
+ * @memberOf jQuery
+ * @name sqlqueryform_submit
+ */
+ $(document).on('submit', '#sqlqueryform.ajax', function (event) {
+ event.preventDefault();
+
+ var $form = $(this);
+ if (sqlQueryOptions.codemirror_editor) {
+ $form[0].elements.sql_query.value = sqlQueryOptions.codemirror_editor.getValue();
+ }
+ if (! checkSqlQuery($form[0])) {
+ return false;
+ }
+
+ // remove any div containing a previous error message
+ $('div.error').remove();
+
+ var $msgbox = PMA_ajaxShowMessage();
+ var $sqlqueryresultsouter = $('#sqlqueryresultsouter');
+
+ PMA_prepareForAjaxRequest($form);
+
+ var argsep = PMA_commonParams.get('arg_separator');
+ $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_page_request=true', function (data) {
+ if (typeof data !== 'undefined' && data.success === true) {
+ // success happens if the query returns rows or not
+
+ // show a message that stays on screen
+ if (typeof data.action_bookmark !== 'undefined') {
+ // view only
+ if ('1' === data.action_bookmark) {
+ $('#sqlquery').text(data.sql_query);
+ // send to codemirror if possible
+ setQuery(data.sql_query);
+ }
+ // delete
+ if ('2' === data.action_bookmark) {
+ $('#id_bookmark option[value=\'' + data.id_bookmark + '\']').remove();
+ // if there are no bookmarked queries now (only the empty option),
+ // remove the bookmark section
+ if ($('#id_bookmark option').length === 1) {
+ $('#fieldsetBookmarkOptions').hide();
+ $('#fieldsetBookmarkOptionsFooter').hide();
+ }
+ }
+ }
+ $sqlqueryresultsouter
+ .show()
+ .html(data.message);
+ PMA_highlightSQL($sqlqueryresultsouter);
+
+ if (data._menu) {
+ if (history && history.pushState) {
+ history.replaceState({
+ menu : data._menu
+ },
+ 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) {
+ if (! (history && history.pushState)) {
+ PMA_MicroHistory.menus.replace(PMA_MicroHistory.menus.get(data._menuHash));
+ }
+ }
+
+ if (data._params) {
+ PMA_commonParams.setAll(data._params);
+ }
+
+ if (typeof data.ajax_reload !== 'undefined') {
+ if (data.ajax_reload.reload) {
+ if (data.ajax_reload.table_name) {
+ PMA_commonParams.set('table', data.ajax_reload.table_name);
+ PMA_commonActions.refreshMain();
+ } else {
+ PMA_reloadNavigation();
+ }
+ }
+ } else if (typeof data.reload !== 'undefined') {
+ // this happens if a USE or DROP command was typed
+ PMA_commonActions.setDb(data.db);
+ var url;
+ if (data.db) {
+ if (data.table) {
+ url = 'table_sql.php';
+ } else {
+ url = 'db_sql.php';
+ }
+ } else {
+ url = 'server_sql.php';
+ }
+ PMA_commonActions.refreshMain(url, function () {
+ $('#sqlqueryresultsouter')
+ .show()
+ .html(data.message);
+ PMA_highlightSQL($('#sqlqueryresultsouter'));
+ });
+ }
+
+ $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');
+ $('#togglequerybox').show();
+ PMA_init_slider();
+
+ if (typeof data.action_bookmark === 'undefined') {
+ if ($('#sqlqueryform input[name="retain_query_box"]').is(':checked') !== true) {
+ if ($('#togglequerybox').siblings(':visible').length > 0) {
+ $('#togglequerybox').trigger('click');
+ }
+ }
+ }
+ } else if (typeof data !== 'undefined' && data.success === false) {
+ // show an error message that stays on screen
+ $sqlqueryresultsouter
+ .show()
+ .html(data.error);
+ }
+ PMA_ajaxRemoveMessage($msgbox);
+ }); // end $.post()
+ }); // end SQL Query submit
+
+ /**
+ * Ajax Event handler for the display options
+ * @memberOf jQuery
+ * @name displayOptionsForm_submit
+ */
+ $(document).on('submit', 'form[name=\'displayOptionsForm\'].ajax', function (event) {
+ event.preventDefault();
+
+ var $form = $(this);
+
+ var $msgbox = PMA_ajaxShowMessage();
+ var argsep = PMA_commonParams.get('arg_separator');
+ $.post($form.attr('action'), $form.serialize() + argsep + 'ajax_request=true', function (data) {
+ PMA_ajaxRemoveMessage($msgbox);
+ var $sqlqueryresults = $form.parents('.sqlqueryresults');
+ $sqlqueryresults
+ .html(data.message)
+ .trigger('makegrid')
+ .trigger('stickycolumns');
+ PMA_init_slider();
+ PMA_highlightSQL($sqlqueryresults);
+ }); // end $.post()
+ }); // end displayOptionsForm handler
+
+ // Filter row handling. --STARTS--
+ $(document).on('keyup', '.filter_rows', function () {
+ var unique_id = $(this).data('for');
+ var $target_table = $('.table_results[data-uniqueId=\'' + unique_id + '\']');
+ var $header_cells = $target_table.find('th[data-column]');
+ var target_columns = Array();
+ // To handle colspan=4, in case of edit,copy etc options.
+ var dummy_th = ($('.edit_row_anchor').length !== 0 ?
+ ' | | | '
+ : '');
+ // Selecting columns that will be considered for filtering and searching.
+ $header_cells.each(function () {
+ target_columns.push($.trim($(this).text()));
+ });
+
+ var phrase = $(this).val();
+ // Set same value to both Filter rows fields.
+ $('.filter_rows[data-for=\'' + unique_id + '\']').not(this).val(phrase);
+ // Handle colspan.
+ $target_table.find('thead > tr').prepend(dummy_th);
+ $.uiTableFilter($target_table, phrase, target_columns);
+ $target_table.find('th.dummy_th').remove();
+ });
+ // Filter row handling. --ENDS--
+
+ // Prompt to confirm on Show All
+ $('body').on('click', '.navigation .showAllRows', function (e) {
+ e.preventDefault();
+ var $form = $(this).parents('form');
+
+ if (! $(this).is(':checked')) { // already showing all rows
+ submitShowAllForm();
+ } else {
+ $form.PMA_confirm(PMA_messages.strShowAllRowsWarning, $form.attr('action'), function (url) {
+ submitShowAllForm();
+ });
+ }
+
+ function submitShowAllForm () {
+ var argsep = PMA_commonParams.get('arg_separator');
+ var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true';
+ PMA_ajaxShowMessage();
+ AJAX.source = $form;
+ $.post($form.attr('action'), submitData, AJAX.responseHandler);
+ }
+ });
+
+ $('body').on('keyup', '#sqlqueryform', function () {
+ PMA_handleSimulateQueryButton();
+ });
+
+ /**
+ * Ajax event handler for 'Simulate DML'.
+ */
+ $('body').on('click', '#simulate_dml', function () {
+ var $form = $('#sqlqueryform');
+ var query = '';
+ var delimiter = $('#id_sql_delimiter').val();
+ var db_name = $form.find('input[name="db"]').val();
+
+ if (sqlQueryOptions.codemirror_editor) {
+ query = sqlQueryOptions.codemirror_editor.getValue();
+ } else {
+ query = $('#sqlquery').val();
+ }
+
+ if (query.length === 0) {
+ alert(PMA_messages.strFormEmpty);
+ $('#sqlquery').focus();
+ return false;
+ }
+
+ var $msgbox = PMA_ajaxShowMessage();
+ $.ajax({
+ type: 'POST',
+ url: $form.attr('action'),
+ data: {
+ server: PMA_commonParams.get('server'),
+ db: db_name,
+ ajax_request: '1',
+ simulate_dml: '1',
+ sql_query: query,
+ sql_delimiter: delimiter
+ },
+ success: function (response) {
+ PMA_ajaxRemoveMessage($msgbox);
+ if (response.success) {
+ var dialog_content = '';
+ if (response.sql_data) {
+ var len = response.sql_data.length;
+ for (var i = 0; i < len; i++) {
+ dialog_content += ' ' + PMA_messages.strSQLQuery +
+ '' + response.sql_data[i].sql_query +
+ PMA_messages.strMatchedRows +
+ ' ' + response.sql_data[i].matched_rows + '';
+ if (i < len - 1) {
+ dialog_content += '
';
+ }
+ }
+ } else {
+ dialog_content += response.message;
+ }
+ dialog_content += ' ';
+ var $dialog_content = $(dialog_content);
+ var button_options = {};
+ button_options[PMA_messages.strClose] = function () {
+ $(this).dialog('close');
+ };
+ var $response_dialog = $('').append($dialog_content).dialog({
+ minWidth: 540,
+ maxHeight: 400,
+ modal: true,
+ buttons: button_options,
+ title: PMA_messages.strSimulateDML,
+ open: function () {
+ PMA_highlightSQL($(this));
+ },
+ close: function () {
+ $(this).remove();
+ }
+ });
+ } else {
+ PMA_ajaxShowMessage(response.error);
+ }
+ },
+ error: function (response) {
+ PMA_ajaxShowMessage(PMA_messages.strErrorProcessingRequest);
+ }
+ });
+ });
+
+ /**
+ * Handles multi submits of results browsing page such as edit, delete and export
+ */
+ $('body').on('click', 'form[name="resultsForm"].ajax button[name="submit_mult"], form[name="resultsForm"].ajax input[name="submit_mult"]', function (e) {
+ e.preventDefault();
+ var $button = $(this);
+ var $form = $button.closest('form');
+ var argsep = PMA_commonParams.get('arg_separator');
+ var submitData = $form.serialize() + argsep + 'ajax_request=true' + argsep + 'ajax_page_request=true' + argsep + 'submit_mult=' + $button.val();
+ PMA_ajaxShowMessage();
+ AJAX.source = $form;
+ $.post($form.attr('action'), submitData, AJAX.responseHandler);
+ });
+
+ /**
+ * Handles double click table fields to insert into query
+ */
+ $('#tablefields')
+ .on('dblclick', function () {
+ insertValueQuery();
+ });
+
+ /**
+ * Handle click on insert or arrow button to insert table fields in query
+ */
+ $('#tablefieldsSubmitLinkMode,#tablefieldsSubmitNonLinkMode')
+ .on('click', function () {
+ insertValueQuery();
+ });
+} // end $()
+
+/**
+ * Starting from some th, change the class of all td under it.
+ * If isAddClass is specified, it will be used to determine whether to add or remove the class.
+ */
+function PMA_changeClassForColumn ($this_th, newclass, isAddClass) {
+ // index 0 is the th containing the big T
+ var th_index = $this_th.index();
+ var has_big_t = $this_th.closest('tr').children(':first').hasClass('column_action');
+ // .eq() is zero-based
+ if (has_big_t) {
+ th_index--;
+ }
+ var $table = $this_th.parents('.table_results');
+ if (! $table.length) {
+ $table = $this_th.parents('table').siblings('.table_results');
+ }
+ var $tds = $table.find('tbody tr').find('td.data:eq(' + th_index + ')');
+ if (isAddClass === undefined) {
+ $tds.toggleClass(newclass);
+ } else {
+ $tds.toggleClass(newclass, isAddClass);
+ }
+}
+
+/**
+ * Handles browse foreign values modal dialog
+ *
+ * @param object $this_a reference to the browse foreign value link
+ */
+function browseForeignDialog ($this_a) {
+ var formId = '#browse_foreign_form';
+ var showAllId = '#foreign_showAll';
+ var tableId = '#browse_foreign_table';
+ var filterId = '#input_foreign_filter';
+ var $dialog = null;
+ $.get($this_a.attr('href'), { 'ajax_request': true }, function (data) {
+ // Creates browse foreign value dialog
+ $dialog = $('').append(data.message).dialog({
+ title: PMA_messages.strBrowseForeignValues,
+ width: Math.min($(window).width() - 100, 700),
+ maxHeight: $(window).height() - 100,
+ dialogClass: 'browse_foreign_modal',
+ close: function (ev, ui) {
+ // remove event handlers attached to elements related to dialog
+ $(tableId).off('click', 'td a.foreign_value');
+ $(formId).off('click', showAllId);
+ $(formId).off('submit');
+ // remove dialog itself
+ $(this).remove();
+ },
+ modal: true
+ });
+ }).done(function () {
+ var showAll = false;
+ $(tableId).on('click', 'td a.foreign_value', function (e) {
+ e.preventDefault();
+ var $input = $this_a.prev('input[type=text]');
+ // Check if input exists or get CEdit edit_box
+ if ($input.length === 0) {
+ $input = $this_a.closest('.edit_area').prev('.edit_box');
+ }
+ // Set selected value as input value
+ $input.val($(this).data('key'));
+ $dialog.dialog('close');
+ });
+ $(formId).on('click', showAllId, function () {
+ showAll = true;
+ });
+ $(formId).on('submit', function (e) {
+ e.preventDefault();
+ // if filter value is not equal to old value
+ // then reset page number to 1
+ if ($(filterId).val() !== $(filterId).data('old')) {
+ $(formId).find('select[name=pos]').val('0');
+ }
+ var postParams = $(this).serializeArray();
+ // if showAll button was clicked to submit form then
+ // add showAll button parameter to form
+ if (showAll) {
+ postParams.push({
+ name: $(showAllId).attr('name'),
+ value: $(showAllId).val()
+ });
+ }
+ // updates values in dialog
+ $.post($(this).attr('action') + '?ajax_request=1', postParams, function (data) {
+ var $obj = $(' ').html(data.message);
+ $(formId).html($obj.find(formId).html());
+ $(tableId).html($obj.find(tableId).html());
+ });
+ showAll = false;
+ });
+ });
+}
+
+export function onload2 () {
+ $('body').on('click', 'a.browse_foreign', function (e) {
+ e.preventDefault();
+ browseForeignDialog($(this));
+ });
+
+ /**
+ * vertical column highlighting in horizontal mode when hovering over the column header
+ */
+ $(document).on('mouseenter', 'th.column_heading.pointer', function (e) {
+ PMA_changeClassForColumn($(this), 'hover', true);
+ });
+ $(document).on('mouseleave', 'th.column_heading.pointer', function (e) {
+ PMA_changeClassForColumn($(this), 'hover', false);
+ });
+
+ /**
+ * vertical column marking in horizontal mode when clicking the column header
+ */
+ $(document).on('click', 'th.column_heading.marker', function () {
+ PMA_changeClassForColumn($(this), 'marked');
+ });
+
+ /**
+ * create resizable table
+ */
+ $('.sqlqueryresults').trigger('makegrid').trigger('stickycolumns');
+
+ /**
+ * Check if there is any saved query
+ */
+ if (sqlQueryOptions.codemirror_editor || document.sqlform) {
+ checkSavedQuery();
+ }
+}
+
+export function onload4 () {
+ makeProfilingChart();
+ initProfilingTables();
+}
diff --git a/js/src/utils/DateTime.js b/js/src/utils/DateTime.js
new file mode 100644
index 0000000000..ef74c685d6
--- /dev/null
+++ b/js/src/utils/DateTime.js
@@ -0,0 +1,147 @@
+import { PMA_Messages as PMA_messages } from '../variables/export_variables';
+import { PMA_tooltip } from './show_ajax_messages';
+/*
+ * Adds a date/time picker to an element
+ *
+ * @param object $this_element a jQuery object pointing to the element
+ */
+export function PMA_addDatepicker ($this_element, type, options) {
+ var showTimepicker = true;
+ if (type === 'date') {
+ showTimepicker = false;
+ }
+
+ var defaultOptions = {
+ showOn: 'button',
+ buttonImage: themeCalendarImage, // defined in js/messages.php
+ buttonImageOnly: true,
+ stepMinutes: 1,
+ stepHours: 1,
+ showSecond: true,
+ showMillisec: true,
+ showMicrosec: true,
+ showTimepicker: showTimepicker,
+ showButtonPanel: false,
+ dateFormat: 'yy-mm-dd', // yy means year with four digits
+ timeFormat: 'HH:mm:ss.lc',
+ constrainInput: false,
+ altFieldTimeOnly: false,
+ showAnim: '',
+ beforeShow: function (input, inst) {
+ // Remember that we came from the datepicker; this is used
+ // in tbl_change.js by verificationsAfterFieldChange()
+ $this_element.data('comes_from', 'datepicker');
+ if ($(input).closest('.cEdit').length > 0) {
+ setTimeout(function () {
+ inst.dpDiv.css({
+ top: 0,
+ left: 0,
+ position: 'relative'
+ });
+ }, 0);
+ }
+ setTimeout(function () {
+ // Fix wrong timepicker z-index, doesn't work without timeout
+ $('#ui-timepicker-div').css('z-index', $('#ui-datepicker-div').css('z-index'));
+ // Integrate tooltip text into dialog
+ var tooltip = $this_element.tooltip('instance');
+ if (typeof tooltip !== 'undefined') {
+ tooltip.disable();
+ var $note = $(' ');
+ $note.text(tooltip.option('content'));
+ $('div.ui-datepicker').append($note);
+ }
+ }, 0);
+ },
+ onSelect: function () {
+ $this_element.data('datepicker').inline = true;
+ },
+ onClose: function (dateText, dp_inst) {
+ // The value is no more from the date picker
+ $this_element.data('comes_from', '');
+ if (typeof $this_element.data('datepicker') !== 'undefined') {
+ $this_element.data('datepicker').inline = false;
+ }
+ var tooltip = $this_element.tooltip('instance');
+ if (typeof tooltip !== 'undefined') {
+ tooltip.enable();
+ }
+ }
+ };
+ if (type === 'time') {
+ $this_element.timepicker($.extend(defaultOptions, options));
+ // Add a tip regarding entering MySQL allowed-values for TIME data-type
+ PMA_tooltip($this_element, 'input', PMA_messages.strMysqlAllowedValuesTipTime);
+ } else {
+ $this_element.datetimepicker($.extend(defaultOptions, options));
+ }
+}
+
+/**
+ * Add a date/time picker to each element that needs it
+ * (only when jquery-ui-timepicker-addon.js is loaded)
+ */
+function addDateTimePicker () {
+ if ($.timepicker !== undefined) {
+ $('input.timefield, input.datefield, input.datetimefield').each(function () {
+ var decimals = $(this).parent().attr('data-decimals');
+ var type = $(this).parent().attr('data-type');
+
+ var showMillisec = false;
+ var showMicrosec = false;
+ var timeFormat = 'HH:mm:ss';
+ var hourMax = 23;
+ // check for decimal places of seconds
+ if (decimals > 0 && type.indexOf('time') !== -1) {
+ if (decimals > 3) {
+ showMillisec = true;
+ showMicrosec = true;
+ timeFormat = 'HH:mm:ss.lc';
+ } else {
+ showMillisec = true;
+ timeFormat = 'HH:mm:ss.l';
+ }
+ }
+ if (type === 'time') {
+ hourMax = 99;
+ }
+ PMA_addDatepicker($(this), type, {
+ showMillisec: showMillisec,
+ showMicrosec: showMicrosec,
+ timeFormat: timeFormat,
+ hourMax: hourMax
+ });
+ // Add a tip regarding entering MySQL allowed-values
+ // for TIME and DATE data-type
+ if ($(this).hasClass('timefield')) {
+ PMA_tooltip($(this), 'input', PMA_messages.strMysqlAllowedValuesTipTime);
+ } else if ($(this).hasClass('datefield')) {
+ PMA_tooltip($(this), 'input', PMA_messages.strMysqlAllowedValuesTipDate);
+ }
+ });
+ }
+}
+
+/**
+ * Toggle the Datetimepicker UI if the date value entered
+ * by the user in the 'text box' is not going to be accepted
+ * by the Datetimepicker plugin (but is accepted by MySQL)
+ */
+export function toggleDatepickerIfInvalid ($td, $input_field) {
+ // Regex allowed by the Datetimepicker UI
+ var dtexpDate = new RegExp(['^([0-9]{4})',
+ '-(((01|03|05|07|08|10|12)-((0[1-9])|([1-2][0-9])|(3[0-1])))|((02|04|06|09|11)',
+ '-((0[1-9])|([1-2][0-9])|30)))$'].join(''));
+ var dtexpTime = new RegExp(['^(([0-1][0-9])|(2[0-3]))',
+ ':((0[0-9])|([1-5][0-9]))',
+ ':((0[0-9])|([1-5][0-9]))(\.[0-9]{1,6}){0,1}$'].join(''));
+
+ // If key-ed in Time or Date values are unsupported by the UI, close it
+ if ($td.attr('data-type') === 'date' && ! dtexpDate.test($input_field.val())) {
+ $input_field.datepicker('hide');
+ } else if ($td.attr('data-type') === 'time' && ! dtexpTime.test($input_field.val())) {
+ $input_field.datepicker('hide');
+ } else {
+ $input_field.datepicker('show');
+ }
+}
diff --git a/js/src/utils/JqueryExtended.js b/js/src/utils/JqueryExtended.js
index 2e4ccfd477..cf3706db4c 100644
--- a/js/src/utils/JqueryExtended.js
+++ b/js/src/utils/JqueryExtended.js
@@ -15,7 +15,7 @@ import { PMA_Messages as PMA_messages } from '../variables/export_variables';
* Make sure that ajax requests will not be cached
* by appending a random variable to their parameters
*/
-$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
+$.ajaxPrefilter(function (options, originalOptions) {
var nocache = new Date().getTime() + '' + Math.floor(Math.random() * 1000000);
if (typeof options.data === 'string') {
options.data += '&_nocache=' + nocache + '&token=' + encodeURIComponent(PMA_commonParams.get('token'));
@@ -250,4 +250,6 @@ export function extendingValidatorMessages () {
window.jQ = $;
-export const jQuery = $;
+export {
+ $
+};
diff --git a/js/src/utils/Sanitise.js b/js/src/utils/Sanitise.js
index 4431a6e9f0..a16be9289d 100644
--- a/js/src/utils/Sanitise.js
+++ b/js/src/utils/Sanitise.js
@@ -48,10 +48,35 @@ function escapeJsString (unsafe) {
}
}
+/**
+ * decode a string URL_encoded
+ *
+ * @param string str
+ * @return string the URL-decoded string
+ */
+function PMA_urldecode (str) {
+ if (typeof str !== 'undefined') {
+ return decodeURIComponent(str.replace(/\+/g, '%20'));
+ }
+}
+
+/**
+ * endecode a string URL_decoded
+ *
+ * @param string str
+ * @return string the URL-encoded string
+ */
+function PMA_urlencode (str) {
+ if (typeof str !== 'undefined') {
+ return encodeURIComponent(str).replace(/\%20/g, '+');
+ }
+}
+
/**
* Module export
*/
export {
escapeHtml,
- escapeJsString
+ escapeJsString,
+ PMA_urlencode
};
diff --git a/js/src/utils/makegrid.js b/js/src/utils/makegrid.js
new file mode 100644
index 0000000000..393f5eeae3
--- /dev/null
+++ b/js/src/utils/makegrid.js
@@ -0,0 +1,2255 @@
+/* vim: set expandtab sw=4 ts=4 sts=4: */
+
+/**
+ * Module import
+ */
+import { $ } from './JqueryExtended';
+import { PMA_Messages as messages } from '../variables/export_variables';
+import { PMA_ajaxShowMessage, PMA_tooltip } from './show_ajax_messages';
+import { rearrangeStickyColumns } from '../functions/Grid/StickyColumns';
+import { PMA_getCellValue } from '../functions/Grid/Cell';
+import { PMA_updateCode } from '../functions/UpdateCode';
+import CommonParams from '../variables/common_params';
+import { getFieldName } from '../functions/Grid/GetFieldName';
+import { AJAX } from '../ajax';
+import { PMA_addDatepicker, toggleDatepickerIfInvalid } from './DateTime';
+import { escapeHtml, PMA_urlencode } from './Sanitise';
+import { confirmLink } from '../functions/Common';
+import { PMA_highlightSQL } from '../utils/sql';
+/**
+ * Create advanced table (resize, reorder, and show/hide columns; and also grid editing).
+ * This function is designed mainly for table DOM generated from browsing a table in the database.
+ * For using this function in other table DOM, you may need to:
+ * - add "draggable" class in the table header , in order to make it resizable, sortable or hidable
+ * - have at least one non-"draggable" header in the table DOM for placing column visibility drop-down arrow
+ * - pass the value "false" for the parameter "enableGridEdit"
+ * - adjust other parameter value, to select which features that will be enabled
+ *
+ * @param t the table DOM element
+ * @param enableResize Optional, if false, column resizing feature will be disabled
+ * @param enableReorder Optional, if false, column reordering feature will be disabled
+ * @param enableVisib Optional, if false, show/hide column feature will be disabled
+ * @param enableGridEdit Optional, if false, grid editing feature will be disabled
+ */
+function PMA_makegrid (t, enableResize = true, enableReorder = true, enableVisib = true, enableGridEdit = true) {
+ var g = {
+ /** *********
+ * Constant
+ ***********/
+ minColWidth: 15,
+
+
+ /** *********
+ * Variables, assigned with default value, changed later
+ ***********/
+ actionSpan: 5, // number of colspan in Actions header in a table
+ tableCreateTime: null, // table creation time, used for saving column order and visibility to server, only available in "Browse tab"
+
+ // Column reordering variables
+ colOrder: [], // array of column order
+
+ // Column visibility variables
+ colVisib: [], // array of column visibility
+ showAllColText: '', // string, text for "show all" button under column visibility list
+ visibleHeadersCount: 0, // number of visible data headers
+
+ // Table hint variables
+ reorderHint: '', // string, hint for column reordering
+ sortHint: '', // string, hint for column sorting
+ markHint: '', // string, hint for column marking
+ copyHint: '', // string, hint for copy column name
+ showReorderHint: false,
+ showSortHint: false,
+ showMarkHint: false,
+
+ // Grid editing
+ isCellEditActive: false, // true if current focus is in edit cell
+ isEditCellTextEditable: false, // true if current edit cell is editable in the text input box (not textarea)
+ currentEditCell: null, // reference to | that currently being edited
+ cellEditHint: '', // hint shown when doing grid edit
+ gotoLinkText: '', // "Go to link" text
+ wasEditedCellNull: false, // true if last value of the edited cell was NULL
+ maxTruncatedLen: 0, // number of characters that can be displayed in a cell
+ saveCellsAtOnce: false, // $cfg[saveCellsAtOnce]
+ isCellEdited: false, // true if at least one cell has been edited
+ saveCellWarning: '', // string, warning text when user want to leave a page with unsaved edited data
+ lastXHR : null, // last XHR object used in AJAX request
+ isSaving: false, // true when currently saving edited data, used to handle double posting caused by pressing ENTER in grid edit text box in Chrome browser
+ alertNonUnique: '', // string, alert shown when saving edited nonunique table
+
+ // Common hidden inputs
+ token: null,
+ server: null,
+ db: null,
+ table: null,
+
+
+ /** **********
+ * Functions
+ ************/
+
+ /**
+ * Start to resize column. Called when clicking on column separator.
+ *
+ * @param e event
+ * @param obj dragged div object
+ */
+ dragStartRsz: function (e, obj) {
+ var n = $(g.cRsz).find('div').index(obj); // get the index of separator (i.e., column index)
+ $(obj).addClass('colborder_active');
+ g.colRsz = {
+ x0: e.pageX,
+ n: n,
+ obj: obj,
+ objLeft: $(obj).position().left,
+ objWidth: $(g.t).find('th.draggable:visible:eq(' + n + ') span').outerWidth()
+ };
+ $(document.body).css('cursor', 'col-resize').noSelect();
+ if (g.isCellEditActive) {
+ g.hideEditCell();
+ }
+ },
+
+ /**
+ * Start to reorder column. Called when clicking on table header.
+ *
+ * @param e event
+ * @param obj table header object
+ */
+ dragStartReorder: function (e, obj) {
+ // prepare the cCpy (column copy) and cPointer (column pointer) from the dragged column
+ $(g.cCpy).text($(obj).text());
+ var objPos = $(obj).position();
+ $(g.cCpy).css({
+ top: objPos.top + 20,
+ left: objPos.left,
+ height: $(obj).height(),
+ width: $(obj).width()
+ });
+ $(g.cPointer).css({
+ top: objPos.top
+ });
+
+ // get the column index, zero-based
+ var n = g.getHeaderIdx(obj);
+
+ g.colReorder = {
+ x0: e.pageX,
+ y0: e.pageY,
+ n: n,
+ newn: n,
+ obj: obj,
+ objTop: objPos.top,
+ objLeft: objPos.left
+ };
+
+ $(document.body).css('cursor', 'move').noSelect();
+ if (g.isCellEditActive) {
+ g.hideEditCell();
+ }
+ },
+
+ /**
+ * Handle mousemove event when dragging.
+ *
+ * @param e event
+ */
+ dragMove: function (e) {
+ if (g.colRsz) {
+ let dx = e.pageX - g.colRsz.x0;
+ if (g.colRsz.objWidth + dx > g.minColWidth) {
+ $(g.colRsz.obj).css('left', g.colRsz.objLeft + dx + 'px');
+ }
+ } else if (g.colReorder) {
+ // dragged column animation
+ let dx = e.pageX - g.colReorder.x0;
+ $(g.cCpy)
+ .css('left', g.colReorder.objLeft + dx)
+ .show();
+
+ // pointer animation
+ var hoveredCol = g.getHoveredCol(e);
+ if (hoveredCol) {
+ var newn = g.getHeaderIdx(hoveredCol);
+ g.colReorder.newn = newn;
+ if (newn !== g.colReorder.n) {
+ // show the column pointer in the right place
+ var colPos = $(hoveredCol).position();
+ var newleft = newn < g.colReorder.n ?
+ colPos.left :
+ colPos.left + $(hoveredCol).outerWidth();
+ $(g.cPointer)
+ .css({
+ left: newleft,
+ visibility: 'visible'
+ });
+ } else {
+ // no movement to other column, hide the column pointer
+ $(g.cPointer).css('visibility', 'hidden');
+ }
+ }
+ }
+ },
+
+ /**
+ * Stop the dragging action.
+ *
+ * @param e event
+ */
+ dragEnd: function (e) {
+ if (g.colRsz) {
+ var dx = e.pageX - g.colRsz.x0;
+ var nw = g.colRsz.objWidth + dx;
+ if (nw < g.minColWidth) {
+ nw = g.minColWidth;
+ }
+ var n = g.colRsz.n;
+ // do the resizing
+ g.resize(n, nw);
+
+ g.reposRsz();
+ g.reposDrop();
+ g.colRsz = false;
+ $(g.cRsz).find('div').removeClass('colborder_active');
+ rearrangeStickyColumns($(t).prev('.sticky_columns'), $(t));
+ } else if (g.colReorder) {
+ // shift columns
+ if (g.colReorder.newn !== g.colReorder.n) {
+ g.shiftCol(g.colReorder.n, g.colReorder.newn);
+ // assign new position
+ var objPos = $(g.colReorder.obj).position();
+ g.colReorder.objTop = objPos.top;
+ g.colReorder.objLeft = objPos.left;
+ g.colReorder.n = g.colReorder.newn;
+ // send request to server to remember the column order
+ if (g.tableCreateTime) {
+ g.sendColPrefs();
+ }
+ g.refreshRestoreButton();
+ }
+
+ // animate new column position
+ $(g.cCpy).stop(true, true)
+ .animate({
+ top: g.colReorder.objTop,
+ left: g.colReorder.objLeft
+ }, 'fast')
+ .fadeOut();
+ $(g.cPointer).css('visibility', 'hidden');
+
+ g.colReorder = false;
+ rearrangeStickyColumns($(t).prev('.sticky_columns'), $(t));
+ }
+ $(document.body).css('cursor', 'inherit').noSelect(false);
+ },
+
+ /**
+ * Resize column n to new width "nw"
+ *
+ * @param n zero-based column index
+ * @param nw new width of the column in pixel
+ */
+ resize: function (n, nw) {
+ $(g.t).find('tr').each(function () {
+ $(this).find('th.draggable:visible:eq(' + n + ') span,' +
+ 'td:visible:eq(' + (g.actionSpan + n) + ') span')
+ .css('width', nw);
+ });
+ },
+
+ /**
+ * Reposition column resize bars.
+ */
+ reposRsz: function () {
+ $(g.cRsz).find('div').hide();
+ var $firstRowCols = $(g.t).find('tr:first th.draggable:visible');
+ var $resizeHandles = $(g.cRsz).find('div').removeClass('condition');
+ $(g.t).find('table.pma_table').find('thead th:first').removeClass('before-condition');
+ for (var n = 0, l = $firstRowCols.length; n < l; n++) {
+ var $col = $($firstRowCols[n]);
+ var colWidth;
+ if (navigator.userAgent.toLowerCase().indexOf('safari') !== -1) {
+ colWidth = $col.outerWidth();
+ } else {
+ colWidth = $col.outerWidth(true);
+ }
+ $($resizeHandles[n]).css('left', $col.position().left + colWidth)
+ .show();
+ if ($col.hasClass('condition')) {
+ $($resizeHandles[n]).addClass('condition');
+ if (n > 0) {
+ $($resizeHandles[n - 1]).addClass('condition');
+ }
+ }
+ }
+ if ($($resizeHandles[0]).hasClass('condition')) {
+ $(g.t).find('thead th:first').addClass('before-condition');
+ }
+ $(g.cRsz).css('height', $(g.t).height());
+ },
+
+ /**
+ * Shift column from index oldn to newn.
+ *
+ * @param oldn old zero-based column index
+ * @param newn new zero-based column index
+ */
+ shiftCol: function (oldn, newn) {
+ $(g.t).find('tr').each(function () {
+ if (newn < oldn) {
+ $(this).find('th.draggable:eq(' + newn + '),' +
+ 'td:eq(' + (g.actionSpan + newn) + ')')
+ .before($(this).find('th.draggable:eq(' + oldn + '),' +
+ 'td:eq(' + (g.actionSpan + oldn) + ')'));
+ } else {
+ $(this).find('th.draggable:eq(' + newn + '),' +
+ 'td:eq(' + (g.actionSpan + newn) + ')')
+ .after($(this).find('th.draggable:eq(' + oldn + '),' +
+ 'td:eq(' + (g.actionSpan + oldn) + ')'));
+ }
+ });
+ // reposition the column resize bars
+ g.reposRsz();
+
+ // adjust the column visibility list
+ if (newn < oldn) {
+ $(g.cList).find('.lDiv div:eq(' + newn + ')')
+ .before($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
+ } else {
+ $(g.cList).find('.lDiv div:eq(' + newn + ')')
+ .after($(g.cList).find('.lDiv div:eq(' + oldn + ')'));
+ }
+ // adjust the colOrder
+ var tmp = g.colOrder[oldn];
+ g.colOrder.splice(oldn, 1);
+ g.colOrder.splice(newn, 0, tmp);
+ // adjust the colVisib
+ if (g.colVisib.length > 0) {
+ tmp = g.colVisib[oldn];
+ g.colVisib.splice(oldn, 1);
+ g.colVisib.splice(newn, 0, tmp);
+ }
+ },
+
+ /**
+ * Find currently hovered table column's header (excluding actions column).
+ *
+ * @param e event
+ * @return the hovered column's th object or undefined if no hovered column found.
+ */
+ getHoveredCol: function (e) {
+ var hoveredCol;
+ var $headers = $(g.t).find('th.draggable:visible');
+ $headers.each(function () {
+ var left = $(this).offset().left;
+ var right = left + $(this).outerWidth();
+ if (left <= e.pageX && e.pageX <= right) {
+ hoveredCol = this;
+ }
+ });
+ return hoveredCol;
+ },
+
+ /**
+ * Get a zero-based index from a | tag in a table.
+ *
+ * @param obj table header | object
+ * @return zero-based index of the specified table header in the set of table headers (visible or not)
+ */
+ getHeaderIdx: function (obj) {
+ return $(obj).parents('tr').find('th.draggable').index(obj);
+ },
+
+ /**
+ * Reposition the columns back to normal order.
+ */
+ restoreColOrder: function () {
+ // use insertion sort, since we already have shiftCol function
+ for (var i = 1; i < g.colOrder.length; i++) {
+ var x = g.colOrder[i];
+ var j = i - 1;
+ while (j >= 0 && x < g.colOrder[j]) {
+ j--;
+ }
+ if (j !== i - 1) {
+ g.shiftCol(i, j + 1);
+ }
+ }
+ if (g.tableCreateTime) {
+ // send request to server to remember the column order
+ g.sendColPrefs();
+ }
+ g.refreshRestoreButton();
+ },
+
+ /**
+ * Send column preferences (column order and visibility) to the server.
+ */
+ sendColPrefs: function () {
+ if ($(g.t).is('.ajax')) { // only send preferences if ajax class
+ var postParams = {
+ ajax_request: true,
+ db: g.db,
+ table: g.table,
+ token: g.token,
+ server: g.server,
+ set_col_prefs: true,
+ table_create_time: g.tableCreateTime
+ };
+ if (g.colOrder.length > 0) {
+ $.extend(postParams, { col_order: g.colOrder.toString() });
+ }
+ if (g.colVisib.length > 0) {
+ $.extend(postParams, { col_visib: g.colVisib.toString() });
+ }
+ $.post('sql.php', postParams, function (data) {
+ if (data.success !== true) {
+ var $tempDiv = $(document.createElement('div'));
+ $tempDiv.html(data.error);
+ $tempDiv.addClass('error');
+ PMA_ajaxShowMessage($tempDiv, false);
+ }
+ });
+ }
+ },
+
+ /**
+ * Refresh restore button state.
+ * Make restore button disabled if the table is similar with initial state.
+ */
+ refreshRestoreButton: function () {
+ // check if table state is as initial state
+ var isInitial = true;
+ for (var i = 0; i < g.colOrder.length; i++) {
+ if (g.colOrder[i] !== i) {
+ isInitial = false;
+ break;
+ }
+ }
+ // check if only one visible column left
+ var isOneColumn = g.visibleHeadersCount === 1;
+ // enable or disable restore button
+ if (isInitial || isOneColumn) {
+ $(g.o).find('div.restore_column').hide();
+ } else {
+ $(g.o).find('div.restore_column').show();
+ }
+ },
+
+ /**
+ * Update current hint using the boolean values (showReorderHint, showSortHint, etc.).
+ *
+ */
+ updateHint: function () {
+ var text = '';
+ if (!g.colRsz && !g.colReorder) { // if not resizing or dragging
+ if (g.visibleHeadersCount > 1) {
+ g.showReorderHint = true;
+ }
+ if ($(t).find('th.marker').length > 0) {
+ g.showMarkHint = true;
+ }
+ if (g.showSortHint && g.sortHint) {
+ text += text.length > 0 ? ' ' : '';
+ text += '- ' + g.sortHint;
+ }
+ if (g.showMultiSortHint && g.strMultiSortHint) {
+ text += text.length > 0 ? ' ' : '';
+ 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
+ ) {
+ text += text.length > 0 ? ' ' : '';
+ text += '- ' + g.reorderHint;
+ text += text.length > 0 ? ' ' : '';
+ text += '- ' + g.markHint;
+ text += text.length > 0 ? ' ' : '';
+ text += '- ' + g.copyHint;
+ }
+ }
+ return text;
+ },
+
+ /**
+ * Toggle column's visibility.
+ * After calling this function and it returns true, afterToggleCol() must be called.
+ *
+ * @return boolean True if the column is toggled successfully.
+ */
+ toggleCol: function (n) {
+ if (g.colVisib[n]) {
+ // can hide if more than one column is visible
+ if (g.visibleHeadersCount > 1) {
+ $(g.t).find('tr').each(function () {
+ $(this).find('th.draggable:eq(' + n + '),' +
+ 'td:eq(' + (g.actionSpan + n) + ')')
+ .hide();
+ });
+ g.colVisib[n] = 0;
+ $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', false);
+ } else {
+ // cannot hide, force the checkbox to stay checked
+ $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', true);
+ return false;
+ }
+ } else { // column n is not visible
+ $(g.t).find('tr').each(function () {
+ $(this).find('th.draggable:eq(' + n + '),' +
+ 'td:eq(' + (g.actionSpan + n) + ')')
+ .show();
+ });
+ g.colVisib[n] = 1;
+ $(g.cList).find('.lDiv div:eq(' + n + ') input').prop('checked', true);
+ }
+ return true;
+ },
+
+ /**
+ * This must be called if toggleCol() returns is true.
+ *
+ * This function is separated from toggleCol because, sometimes, we want to toggle
+ * some columns together at one time and do just one adjustment after it, e.g. in showAllColumns().
+ */
+ afterToggleCol: function () {
+ // some adjustments after hiding column
+ g.reposRsz();
+ g.reposDrop();
+ g.sendColPrefs();
+
+ // check visible first row headers count
+ g.visibleHeadersCount = $(g.t).find('tr:first th.draggable:visible').length;
+ g.refreshRestoreButton();
+ },
+
+ /**
+ * Show columns' visibility list.
+ *
+ * @param obj The drop down arrow of column visibility list
+ */
+ showColList: function (obj) {
+ // only show when not resizing or reordering
+ if (!g.colRsz && !g.colReorder) {
+ var pos = $(obj).position();
+ // check if the list position is too right
+ if (pos.left + $(g.cList).outerWidth(true) > $(document).width()) {
+ pos.left = $(document).width() - $(g.cList).outerWidth(true);
+ }
+ $(g.cList).css({
+ left: pos.left,
+ top: pos.top + $(obj).outerHeight(true)
+ })
+ .show();
+ $(obj).addClass('coldrop-hover');
+ }
+ },
+
+ /**
+ * Hide columns' visibility list.
+ */
+ hideColList: function () {
+ $(g.cList).hide();
+ $(g.cDrop).find('.coldrop-hover').removeClass('coldrop-hover');
+ },
+
+ /**
+ * Reposition the column visibility drop-down arrow.
+ */
+ reposDrop: function () {
+ var $th = $(t).find('th:not(.draggable)');
+ for (var i = 0; i < $th.length; i++) {
+ var $cd = $(g.cDrop).find('div:eq(' + i + ')'); // column drop-down arrow
+ var pos = $($th[i]).position();
+ $cd.css({
+ left: pos.left + $($th[i]).width() - $cd.width(),
+ top: pos.top
+ });
+ }
+ },
+
+ /**
+ * Show all hidden columns.
+ */
+ showAllColumns: function () {
+ for (var i = 0; i < g.colVisib.length; i++) {
+ if (!g.colVisib[i]) {
+ g.toggleCol(i);
+ }
+ }
+ g.afterToggleCol();
+ },
+
+ /**
+ * Show edit cell, if it can be shown
+ *
+ * @param cell | element to be edited
+ */
+ showEditCell: function (cell) {
+ if ($(cell).is('.grid_edit') &&
+ !g.colRsz && !g.colReorder) {
+ if (!g.isCellEditActive) {
+ var $cell = $(cell);
+
+ if ('string' === $cell.attr('data-type') ||
+ 'blob' === $cell.attr('data-type') ||
+ 'json' === $cell.attr('data-type')
+ ) {
+ g.cEdit = g.cEditTextarea;
+ } else {
+ g.cEdit = g.cEditStd;
+ }
+
+ // remove all edit area and hide it
+ $(g.cEdit).find('.edit_area').empty().hide();
+ // reposition the cEdit element
+ $(g.cEdit).css({
+ top: $cell.position().top,
+ left: $cell.position().left
+ })
+ .show()
+ .find('.edit_box')
+ .css({
+ width: $cell.outerWidth(),
+ height: $cell.outerHeight()
+ });
+ // fill the cell edit with text from |
+ var value = PMA_getCellValue(cell);
+ if ($cell.attr('data-type') === 'json') {
+ value = JSON.stringify(JSON.parse(value), null, 4);
+ }
+ $(g.cEdit).find('.edit_box').val(value);
+
+ g.currentEditCell = cell;
+ $(g.cEdit).find('.edit_box').focus();
+ moveCursorToEnd($(g.cEdit).find('.edit_box'));
+ $(g.cEdit).find('*').prop('disabled', false);
+ }
+ }
+
+ function moveCursorToEnd (input) {
+ var originalValue = input.val();
+ var originallength = originalValue.length;
+ input.val('');
+ input.blur().focus().val(originalValue);
+ input[0].setSelectionRange(originallength, originallength);
+ }
+ },
+
+ /**
+ * Remove edit cell and the edit area, if it is shown.
+ *
+ * @param force Optional, force to hide edit cell without saving edited field.
+ * @param data Optional, data from the POST AJAX request to save the edited field
+ * or just specify "true", if we want to replace the edited field with the new value.
+ * @param field Optional, the edited | . If not specified, the function will
+ * use currently edited | from g.currentEditCell.
+ * @param field Optional, this object contains a boolean named move (true, if called from move* functions)
+ * and a | to which the grid_edit should move
+ */
+ hideEditCell: function (force, data, field, options) {
+ if (g.isCellEditActive && !force) {
+ // cell is being edited, save or post the edited data
+ if (options !== undefined) {
+ g.saveOrPostEditedCell(options);
+ } else {
+ g.saveOrPostEditedCell();
+ }
+ return;
+ }
+
+ // cancel any previous request
+ if (g.lastXHR !== null) {
+ g.lastXHR.abort();
+ g.lastXHR = null;
+ }
+
+ if (data) {
+ if (g.currentEditCell) { // save value of currently edited cell
+ // replace current edited field with the new value
+ var $thisField = $(g.currentEditCell);
+ var isNull = $thisField.data('value') === null;
+ if (isNull) {
+ $thisField.find('span').html('NULL');
+ $thisField.addClass('null');
+ } else {
+ $thisField.removeClass('null');
+ var value = data.isNeedToRecheck
+ ? data.truncatableFieldValue
+ : $thisField.data('value');
+
+ // Truncates the text.
+ $thisField.removeClass('truncated');
+ if (CommonParams.get('pftext') === 'P' && value.length > g.maxTruncatedLen) {
+ $thisField.addClass('truncated');
+ value = value.substring(0, g.maxTruncatedLen) + '...';
+ }
+
+ // Add before carriage return.
+ var newHtml = escapeHtml(value);
+ newHtml = newHtml.replace(/\n/g, ' \n');
+
+ // remove decimal places if column type not supported
+ if (($thisField.attr('data-decimals') === 0) && ($thisField.attr('data-type').indexOf('time') !== -1)) {
+ newHtml = newHtml.substring(0, newHtml.indexOf('.'));
+ }
+
+ // remove addtional decimal places
+ if (($thisField.attr('data-decimals') > 0) && ($thisField.attr('data-type').indexOf('time') !== -1)) {
+ newHtml = newHtml.substring(0, newHtml.length - (6 - $thisField.attr('data-decimals')));
+ }
+
+ var selector = 'span';
+ if ($thisField.hasClass('hex') && $thisField.find('a').length) {
+ selector = 'a';
+ }
+
+ // Updates the code keeping highlighting (if any).
+ var $target = $thisField.find(selector);
+ if (!PMA_updateCode($target, newHtml, value)) {
+ $target.html(newHtml);
+ }
+ }
+ if ($thisField.is('.bit')) {
+ $thisField.find('span').text($thisField.data('value'));
+ }
+ }
+ if (data.transformations !== undefined) {
+ $.each(data.transformations, function (cellIndex, value) {
+ var $thisField = $(g.t).find('.to_be_saved:eq(' + cellIndex + ')');
+ $thisField.find('span').html(value);
+ });
+ }
+ if (data.relations !== undefined) {
+ $.each(data.relations, function (cellIndex, value) {
+ var $thisField = $(g.t).find('.to_be_saved:eq(' + cellIndex + ')');
+ $thisField.find('span').html(value);
+ });
+ }
+
+ // refresh the grid
+ g.reposRsz();
+ g.reposDrop();
+ }
+
+ // hide the cell editing area
+ $(g.cEdit).hide();
+ $(g.cEdit).find('.edit_box').blur();
+ g.isCellEditActive = false;
+ g.currentEditCell = null;
+ // destroy datepicker in edit area, if exist
+ var $dp = $(g.cEdit).find('.hasDatepicker');
+ if ($dp.length > 0) {
+ $(document).bind('mousedown', $.datepicker._checkExternalClick);
+ $dp.datepicker('destroy');
+ // change the cursor in edit box back to normal
+ // (the cursor become a hand pointer when we add datepicker)
+ $(g.cEdit).find('.edit_box').css('cursor', 'inherit');
+ }
+ },
+
+ /**
+ * Show drop-down edit area when edit cell is focused.
+ */
+ showEditArea: function () {
+ if (!g.isCellEditActive) { // make sure the edit area has not been shown
+ g.isCellEditActive = true;
+ g.isEditCellTextEditable = false;
+ /**
+ * @var $td current edited cell
+ */
+ var $td = $(g.currentEditCell);
+ /**
+ * @var $editArea the editing area
+ */
+ var $editArea = $(g.cEdit).find('.edit_area');
+ /**
+ * @var whereClause WHERE clause for the edited cell
+ */
+ var whereClause = $td.parent('tr').find('.where_clause').val();
+ /**
+ * @var fieldName String containing the name of this field.
+ * @see getFieldName()
+ */
+ var fieldName = getFieldName($(t), $td);
+ /**
+ * @var relationCurrValue String current value of the field (for fields that are foreign keyed).
+ */
+ var relationCurrValue = $td.text();
+ /**
+ * @var relationKeyOrDisplayColumn String relational key if in 'Relational display column' mode,
+ * relational display column if in 'Relational key' mode (for fields that are foreign keyed).
+ */
+ var relationKeyOrDisplayColumn = $td.find('a').attr('title');
+ /**
+ * @var currValue String current value of the field (for fields that are of type enum or set).
+ */
+ var currValue = $td.find('span').text();
+
+ // empty all edit area, then rebuild it based on $td classes
+ $editArea.empty();
+
+ // remember this instead of testing more than once
+ var isNull = $td.is('.null');
+
+ // add goto link, if this cell contains a link
+ if ($td.find('a').length > 0) {
+ var gotoLink = document.createElement('div');
+ gotoLink.className = 'goto_link';
+ $(gotoLink).append(g.gotoLinkText + ' ').append($td.find('a').clone());
+ $editArea.append(gotoLink);
+ }
+
+ g.wasEditedCellNull = false;
+ if ($td.is(':not(.not_null)')) {
+ // append a null checkbox
+ $editArea.append('');
+
+ var $checkbox = $editArea.find('.null_div input');
+ // check if current | is NULL
+ if (isNull) {
+ $checkbox.prop('checked', true);
+ g.wasEditedCellNull = true;
+ }
+
+ // if the select/editor is changed un-check the 'checkbox_null__'.
+ if ($td.is('.enum, .set')) {
+ $editArea.on('change', 'select', function () {
+ $checkbox.prop('checked', false);
+ });
+ } else if ($td.is('.relation')) {
+ $editArea.on('change', 'select', function () {
+ $checkbox.prop('checked', false);
+ });
+ $editArea.on('click', '.browse_foreign', function () {
+ $checkbox.prop('checked', false);
+ });
+ } else {
+ $(g.cEdit).on('keypress change paste', '.edit_box', function () {
+ $checkbox.prop('checked', false);
+ });
+ // Capture ctrl+v (on IE and Chrome)
+ $(g.cEdit).on('keydown', '.edit_box', function (e) {
+ if (e.ctrlKey && e.which === 86) {
+ $checkbox.prop('checked', false);
+ }
+ });
+ $editArea.on('keydown', 'textarea', function () {
+ $checkbox.prop('checked', false);
+ });
+ }
+
+ // if null checkbox is clicked empty the corresponding select/editor.
+ $checkbox.click(function () {
+ if ($td.is('.enum')) {
+ $editArea.find('select').val('');
+ } else if ($td.is('.set')) {
+ $editArea.find('select').find('option').each(function () {
+ var $option = $(this);
+ $option.prop('selected', false);
+ });
+ } else if ($td.is('.relation')) {
+ // if the dropdown is there to select the foreign value
+ if ($editArea.find('select').length > 0) {
+ $editArea.find('select').val('');
+ }
+ } else {
+ $editArea.find('textarea').val('');
+ }
+ $(g.cEdit).find('.edit_box').val('');
+ });
+ }
+
+ // reset the position of the edit_area div after closing datetime picker
+ $(g.cEdit).find('.edit_area').css({ 'top' :'0','position':'' });
+
+ if ($td.is('.relation')) {
+ // handle relations
+ $editArea.addClass('edit_area_loading');
+
+ // initialize the original data
+ $td.data('original_data', null);
+
+ /**
+ * @var postParams Object containing parameters for the POST request
+ */
+ let postParams = {
+ 'ajax_request' : true,
+ 'get_relational_values' : true,
+ 'server' : g.server,
+ 'db' : g.db,
+ 'table' : g.table,
+ 'column' : fieldName,
+ 'curr_value' : relationCurrValue,
+ 'relation_key_or_display_column' : relationKeyOrDisplayColumn
+ };
+
+ g.lastXHR = $.post('sql.php', postParams, function (data) {
+ g.lastXHR = null;
+ $editArea.removeClass('edit_area_loading');
+ if ($(data.dropdown).is('select')) {
+ // save original_data
+ var value = $(data.dropdown).val();
+ $td.data('original_data', value);
+ // update the text input field, in case where the "Relational display column" is checked
+ $(g.cEdit).find('.edit_box').val(value);
+ }
+
+ $editArea.append(data.dropdown);
+ $editArea.append(' ' + g.cellEditHint + ' ');
+
+ // for 'Browse foreign values' options,
+ // hide the value next to 'Browse foreign values' link
+ $editArea.find('span.curr_value').hide();
+ // handle update for new values selected from new window
+ $editArea.find('span.curr_value').change(function () {
+ $(g.cEdit).find('.edit_box').val($(this).text());
+ });
+ }); // end $.post()
+
+ $editArea.show();
+ $editArea.on('change', 'select', function () {
+ $(g.cEdit).find('.edit_box').val($(this).val());
+ });
+ g.isEditCellTextEditable = true;
+ } else if ($td.is('.enum')) {
+ // handle enum fields
+ $editArea.addClass('edit_area_loading');
+
+ /**
+ * @var postParams Object containing parameters for the POST request
+ */
+ let postParams = {
+ 'ajax_request' : true,
+ 'get_enum_values' : true,
+ 'server' : g.server,
+ 'db' : g.db,
+ 'table' : g.table,
+ 'column' : fieldName,
+ 'curr_value' : currValue
+ };
+ g.lastXHR = $.post('sql.php', postParams, function (data) {
+ g.lastXHR = null;
+ $editArea.removeClass('edit_area_loading');
+ $editArea.append(data.dropdown);
+ $editArea.append('' + g.cellEditHint + ' ');
+ }); // end $.post()
+
+ $editArea.show();
+ $editArea.on('change', 'select', function () {
+ $(g.cEdit).find('.edit_box').val($(this).val());
+ });
+ } else if ($td.is('.set')) {
+ // handle set fields
+ $editArea.addClass('edit_area_loading');
+
+ /**
+ * @var postParams Object containing parameters for the POST request
+ */
+ let postParams = {
+ 'ajax_request' : true,
+ 'get_set_values' : true,
+ 'server' : g.server,
+ 'db' : g.db,
+ 'table' : g.table,
+ 'column' : fieldName,
+ 'curr_value' : currValue
+ };
+
+ // if the data is truncated, get the full data
+ if ($td.is('.truncated')) {
+ postParams.get_full_values = true;
+ postParams.where_clause = whereClause;
+ }
+
+ g.lastXHR = $.post('sql.php', postParams, function (data) {
+ g.lastXHR = null;
+ $editArea.removeClass('edit_area_loading');
+ $editArea.append(data.select);
+ $td.data('original_data', $(data.select).val().join());
+ $editArea.append('' + g.cellEditHint + ' ');
+ }); // end $.post()
+
+ $editArea.show();
+ $editArea.on('change', 'select', function () {
+ $(g.cEdit).find('.edit_box').val($(this).val());
+ });
+ } else if ($td.is('.truncated, .transformed')) {
+ if ($td.is('.to_be_saved')) { // cell has been edited
+ var value = $td.data('value');
+ $(g.cEdit).find('.edit_box').val(value);
+ $editArea.append('');
+ $editArea.find('textarea').val(value);
+ $editArea
+ .on('keyup', 'textarea', function () {
+ $(g.cEdit).find('.edit_box').val($(this).val());
+ });
+ $(g.cEdit).on('keyup', '.edit_box', function () {
+ $editArea.find('textarea').val($(this).val());
+ });
+ $editArea.append('' + g.cellEditHint + ' ');
+ } else {
+ // handle truncated/transformed values values
+ $editArea.addClass('edit_area_loading');
+
+ // initialize the original data
+ $td.data('original_data', null);
+
+ /**
+ * @var sqlQuery String containing the SQL query used to retrieve value of truncated/transformed data
+ */
+ var sqlQuery = 'SELECT `' + fieldName + '` FROM `' + g.table + '` WHERE ' + whereClause;
+
+ // Make the Ajax call and get the data, wrap it and insert it
+ g.lastXHR = $.post('sql.php', {
+ 'server' : g.server,
+ 'db' : g.db,
+ 'ajax_request' : true,
+ 'sql_query' : sqlQuery,
+ 'grid_edit' : true
+ }, function (data) {
+ g.lastXHR = null;
+ $editArea.removeClass('edit_area_loading');
+ if (typeof data !== 'undefined' && data.success === true) {
+ $td.data('original_data', data.value);
+ $(g.cEdit).find('.edit_box').val(data.value);
+ } else {
+ PMA_ajaxShowMessage(data.error, false);
+ }
+ }); // end $.post()
+ }
+ g.isEditCellTextEditable = true;
+ } else if ($td.is('.timefield, .datefield, .datetimefield, .timestampfield')) {
+ var $inputField = $(g.cEdit).find('.edit_box');
+
+ // remember current datetime value in $input_field, if it is not null
+ var datetimeValue = !isNull ? $inputField.val() : '';
+
+ var showMillisec = false;
+ var showMicrosec = false;
+ var timeFormat = 'HH:mm:ss';
+ // check for decimal places of seconds
+ if (($td.attr('data-decimals') > 0) && ($td.attr('data-type').indexOf('time') !== -1)) {
+ if (datetimeValue && datetimeValue.indexOf('.') === false) {
+ datetimeValue += '.';
+ }
+ if ($td.attr('data-decimals') > 3) {
+ showMillisec = true;
+ showMicrosec = true;
+ timeFormat = 'HH:mm:ss.lc';
+
+ if (datetimeValue) {
+ datetimeValue += '000000';
+ let datetimeValue = datetimeValue.substring(0, datetimeValue.indexOf('.') + 7);
+ $inputField.val(datetimeValue);
+ }
+ } else {
+ showMillisec = true;
+ timeFormat = 'HH:mm:ss.l';
+
+ if (datetimeValue) {
+ datetimeValue += '000';
+ let datetimeValue = datetimeValue.substring(0, datetimeValue.indexOf('.') + 4);
+ $inputField.val(datetimeValue);
+ }
+ }
+ }
+
+ // add datetime picker
+ PMA_addDatepicker($inputField, $td.attr('data-type'), {
+ showMillisec: showMillisec,
+ showMicrosec: showMicrosec,
+ timeFormat: timeFormat
+ });
+
+ $inputField.on('keyup', function (e) {
+ if (e.which === 13) {
+ // post on pressing "Enter"
+ e.preventDefault();
+ e.stopPropagation();
+ g.saveOrPostEditedCell();
+ } else if (e.which === 27) {
+ // Nothing defined for this yet
+ } else {
+ toggleDatepickerIfInvalid($td, $inputField);
+ }
+ });
+
+ $inputField.datepicker('show');
+ toggleDatepickerIfInvalid($td, $inputField);
+
+ // unbind the mousedown event to prevent the problem of
+ // datepicker getting closed, needs to be checked for any
+ // change in names when updating
+ $(document).off('mousedown', $.datepicker._checkExternalClick);
+
+ // move ui-datepicker-div inside cEdit div
+ var datepickerDiv = $('#ui-datepicker-div');
+ datepickerDiv.css({ 'top': 0, 'left': 0, 'position': 'relative' });
+ $(g.cEdit).append(datepickerDiv);
+
+ // cancel any click on the datepicker element
+ $editArea.find('> *').click(function (e) {
+ e.stopPropagation();
+ });
+
+ g.isEditCellTextEditable = true;
+ } else {
+ g.isEditCellTextEditable = true;
+ // only append edit area hint if there is a null checkbox
+ if ($editArea.children().length > 0) {
+ $editArea.append('' + g.cellEditHint + ' ');
+ }
+ }
+ if ($editArea.children().length > 0) {
+ $editArea.show();
+ }
+ }
+ },
+
+ /**
+ * Post the content of edited cell.
+ *
+ * @param field Optional, this object contains a boolean named move (true, if called from move* functions)
+ * and a to which the grid_edit should move
+ */
+ postEditedCell: function (options) {
+ if (g.isSaving) {
+ return;
+ }
+ g.isSaving = true;
+ /**
+ * @var relationFields Array containing the name/value pairs of relational fields
+ */
+ var relationFields = {};
+ /**
+ * @var relationalDisplay string 'K' if relational key, 'D' if relational display column
+ */
+ var relationalDisplay = $(g.o).find('input[nameD]:checked').val();
+ /**
+ * @var transformFields Array containing the name/value pairs for transformed fields
+ */
+ var transformFields = {};
+ /**
+ * @var transformationFields Boolean, if there are any transformed fields in the edited cells
+ */
+ var transformationFields = false;
+ /**
+ * @var fullSqlQuery String containing the complete SQL query to update this table
+ */
+ var fullSqlQuery = '';
+ /**
+ * @var relFieldsList String, url encoded representation of {@link relations_fields}
+ */
+ var relFieldsList = '';
+ /**
+ * @var transformFieldsList String, url encoded representation of {@link transformFields}
+ */
+ var transformFieldsList = '';
+ /**
+ * @var fullWhereClause Array containing where clause for updated fields
+ */
+ var fullWhereClause = [];
+ /**
+ * @var isUnique Boolean, whether the rows in this table is unique or not
+ */
+ var isUnique = $(g.t).find('td.edit_row_anchor').is('.nonunique') ? 0 : 1;
+ /**
+ * multi edit variables
+ */
+ var meFieldsName = [];
+ var meFieldsType = [];
+ var meFields = [];
+ var meFieldsNull = [];
+
+ // alert user if edited table is not unique
+ if (!isUnique) {
+ alert(g.alertNonUnique);
+ }
+
+ // loop each edited row
+ $(g.t).find('td.to_be_saved').parents('tr').each(function () {
+ var $tr = $(this);
+ var whereClause = $tr.find('.where_clause').val();
+ if (typeof whereClause === 'undefined') {
+ whereClause = '';
+ }
+ fullWhereClause.push(whereClause);
+ var conditionArray = JSON.parse($tr.find('.condition_array').val());
+
+ /**
+ * multi edit variables, for current row
+ * @TODO array indices are still not correct, they should be md5 of field's name
+ */
+ var fieldsName = [];
+ var fieldsType = [];
+ var fields = [];
+ var fieldsNull = [];
+
+ // loop each edited cell in a row
+ $tr.find('.to_be_saved').each(function () {
+ /**
+ * @var $thisField Object referring to the td that is being edited
+ */
+ var $thisField = $(this);
+
+ /**
+ * @var fieldName String containing the name of this field.
+ * @see getFieldName()
+ */
+ var fieldName = getFieldName($(g.t), $thisField);
+
+ /**
+ * @var thisFieldParams Array temporary storage for the name/value of current field
+ */
+ var thisFieldParams = {};
+
+ if ($thisField.is('.transformed')) {
+ transformationFields = true;
+ }
+ thisFieldParams[fieldName] = $thisField.data('value');
+
+ /**
+ * @var isNull String capturing whether 'checkbox_null__' is checked.
+ */
+ var isNull = thisFieldParams[fieldName] === null;
+
+ fieldsName.push(fieldName);
+
+ if (isNull) {
+ fieldsNull.push('on');
+ fields.push('');
+ } else {
+ if ($thisField.is('.bit')) {
+ fieldsType.push('bit');
+ } else if ($thisField.hasClass('hex')) {
+ fieldsType.push('hex');
+ }
+ fieldsNull.push('');
+ // Convert \n to \r\n to be consistent with form submitted value.
+ // The internal browser representation has to be just \n
+ // while form submitted value \r\n, see specification:
+ // https://www.w3.org/TR/html5/forms.html#the-textarea-element
+ fields.push($thisField.data('value').replace(/\n/g, '\r\n'));
+
+ var cellIndex = $thisField.index('.to_be_saved');
+ if ($thisField.is(':not(.relation, .enum, .set, .bit)')) {
+ if ($thisField.is('.transformed')) {
+ transformFields[cellIndex] = {};
+ $.extend(transformFields[cellIndex], thisFieldParams);
+ }
+ } else if ($thisField.is('.relation')) {
+ relationFields[cellIndex] = {};
+ $.extend(relationFields[cellIndex], thisFieldParams);
+ }
+ }
+ // check if edited field appears in WHERE clause
+ if (whereClause.indexOf(PMA_urlencode(fieldName)) > -1) {
+ var fieldStr = '`' + g.table + '`.' + '`' + fieldName + '`';
+ for (var field in conditionArray) {
+ if (field.indexOf(fieldStr) > -1) {
+ conditionArray[field] = isNull ? 'IS NULL' : '= \'' + thisFieldParams[fieldName].replace(/'/g, '\'\'') + '\'';
+ break;
+ }
+ }
+ }
+ }); // end of loop for every edited cells in a row
+
+ // save new_clause
+ var newClause = '';
+ for (var field in conditionArray) {
+ newClause += field + ' ' + conditionArray[field] + ' AND ';
+ }
+ newClause = newClause.substring(0, newClause.length - 5); // remove the last AND
+ $tr.data('new_clause', newClause);
+ // save condition_array
+ $tr.find('.condition_array').val(JSON.stringify(conditionArray));
+
+ meFieldsName.push(fieldsName);
+ meFieldsType.push(fieldsType);
+ meFields.push(fields);
+ meFieldsNull.push(fieldsNull);
+ }); // end of loop for every edited rows
+
+ relFieldsList = $.param(relationFields);
+ transformFieldsList = $.param(transformFields);
+
+ // Make the Ajax post after setting all parameters
+ /**
+ * @var postParams Object containing parameters for the POST request
+ */
+ var postParams = { 'ajax_request' : true,
+ 'sql_query' : fullSqlQuery,
+ 'server' : g.server,
+ 'db' : g.db,
+ 'table' : g.table,
+ 'clause_is_unique' : isUnique,
+ 'where_clause' : fullWhereClause,
+ 'fields[multi_edit]' : meFields,
+ 'fields_name[multi_edit]' : meFieldsName,
+ 'fields_type[multi_edit]' : meFieldsType,
+ 'fields_null[multi_edit]' : meFieldsNull,
+ 'rel_fields_list' : relFieldsList,
+ 'do_transformations' : transformationFields,
+ 'transform_fields_list' : transformFieldsList,
+ 'relational_display' : relationalDisplay,
+ 'goto' : 'sql.php',
+ 'submit_type' : 'save'
+ };
+
+ if (!g.saveCellsAtOnce) {
+ $(g.cEdit).find('*').prop('disabled', true);
+ $(g.cEdit).find('.edit_box').addClass('edit_box_posting');
+ } else {
+ $(g.o).find('div.save_edited').addClass('saving_edited_data')
+ .find('input').prop('disabled', true); // disable the save button
+ }
+
+ $.ajax({
+ type: 'POST',
+ url: 'tbl_replace.php',
+ data: postParams,
+ success:
+ function (data) {
+ g.isSaving = false;
+ if (!g.saveCellsAtOnce) {
+ $(g.cEdit).find('*').prop('disabled', false);
+ $(g.cEdit).find('.edit_box').removeClass('edit_box_posting');
+ } else {
+ $(g.o).find('div.save_edited').removeClass('saving_edited_data')
+ .find('input').prop('disabled', false); // enable the save button back
+ }
+ if (typeof data !== 'undefined' && data.success === true) {
+ 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 () {
+ var newClause = $(this).data('new_clause');
+ var $whereClause = $(this).find('.where_clause');
+ var oldClause = $whereClause.val();
+ var decodedOldClause = oldClause;
+ var decodedNewClause = newClause;
+
+ $whereClause.val(newClause);
+ // update Edit, Copy, and Delete links also
+ $(this).find('a').each(function () {
+ $(this).attr('href', $(this).attr('href').replace(oldClause, newClause));
+ // update delete confirmation in Delete link
+ if ($(this).attr('href').indexOf('DELETE') > -1) {
+ $(this).removeAttr('onclick')
+ .off('click')
+ .on('click', function () {
+ return confirmLink(this, 'DELETE FROM `' + g.db + '`.`' + g.table + '` WHERE ' +
+ decodedNewClause + (isUnique ? '' : ' LIMIT 1'));
+ });
+ }
+ });
+ // update the multi edit checkboxes
+ $(this).find('input[type=checkbox]').each(function () {
+ var $checkbox = $(this);
+ var checkboxName = $checkbox.attr('name');
+ var checkboxValue = $checkbox.val();
+
+ $checkbox.attr('name', checkboxName.replace(oldClause, newClause));
+ $checkbox.val(checkboxValue.replace(decodedOldClause, decodedNewClause));
+ });
+ });
+ // update the display of executed SQL query command
+ if (typeof data.sql_query !== 'undefined') {
+ // extract query box
+ var $resultQuery = $($.parseHTML(data.sql_query));
+ var sqlOuter = $resultQuery.find('.sqlOuter').wrap(' ').parent().html();
+ var tools = $resultQuery.find('.tools').wrap(' ').parent().html();
+ // sqlOuter and tools will not be present if 'Show SQL queries' configuration is off
+ if (typeof sqlOuter !== 'undefined' && typeof tools !== 'undefined') {
+ $(g.o).find('.result_query:not(:last)').remove();
+ var $existingQuery = $(g.o).find('.result_query');
+ // If two query box exists update query in second else add a second box
+ if ($existingQuery.find('div.sqlOuter').length > 1) {
+ $existingQuery.children(':nth-child(4)').remove();
+ $existingQuery.children(':nth-child(4)').remove();
+ $existingQuery.append(sqlOuter + tools);
+ } else {
+ $existingQuery.append(sqlOuter + tools);
+ }
+ PMA_highlightSQL($existingQuery);
+ }
+ }
+ // hide and/or update the successfully saved cells
+ g.hideEditCell(true, data);
+
+ // remove the "Save edited cells" button
+ $(g.o).find('div.save_edited').hide();
+ // update saved fields
+ $(g.t).find('.to_be_saved')
+ .removeClass('to_be_saved')
+ .data('value', null)
+ .data('original_data', null);
+
+ g.isCellEdited = false;
+ } else {
+ PMA_ajaxShowMessage(data.error, false);
+ if (!g.saveCellsAtOnce) {
+ $(g.t).find('.to_be_saved')
+ .removeClass('to_be_saved');
+ }
+ }
+ }
+ }).done(function () {
+ if (options !== undefined && options.move) {
+ g.showEditCell(options.cell);
+ }
+ }); // end $.ajax()
+ },
+
+ /**
+ * Save edited cell, so it can be posted later.
+ */
+ saveEditedCell: function () {
+ /**
+ * @var $thisField Object referring to the td that is being edited
+ */
+ var $thisField = $(g.currentEditCell);
+ var $testElement = ''; // to test the presence of a element
+
+ var needToPost = false;
+
+ /**
+ * @var fieldName String containing the name of this field.
+ * @see getFieldName()
+ */
+ var fieldName = getFieldName($(g.t), $thisField);
+
+ /**
+ * @var thisFieldParams Array temporary storage for the name/value of current field
+ */
+ var thisFieldParams = {};
+
+ /**
+ * @var isNull String capturing whether 'checkbox_null__' is checked.
+ */
+ var isNull = $(g.cEdit).find('input:checkbox').is(':checked');
+
+ if ($(g.cEdit).find('.edit_area').is('.edit_area_loading')) {
+ // the edit area is still loading (retrieving cell data), no need to post
+ needToPost = false;
+ } else if (isNull) {
+ if (!g.wasEditedCellNull) {
+ thisFieldParams[fieldName] = null;
+ needToPost = true;
+ }
+ } else {
+ if ($thisField.is('.bit')) {
+ thisFieldParams[fieldName] = $(g.cEdit).find('.edit_box').val();
+ } else if ($thisField.is('.set')) {
+ $testElement = $(g.cEdit).find('select');
+ thisFieldParams[fieldName] = $testElement.map(function () {
+ return $(this).val();
+ }).get().join(',');
+ } else if ($thisField.is('.relation, .enum')) {
+ // for relation and enumeration, take the results from edit box value,
+ // because selected value from drop-down, new window or multiple
+ // selection list will always be updated to the edit box
+ thisFieldParams[fieldName] = $(g.cEdit).find('.edit_box').val();
+ } else if ($thisField.hasClass('hex')) {
+ if ($(g.cEdit).find('.edit_box').val().match(/^(0x)?[a-f0-9]*$/i) !== null) {
+ thisFieldParams[fieldName] = $(g.cEdit).find('.edit_box').val();
+ } else {
+ var hexError = '' + messages.strEnterValidHex + ' ';
+ PMA_ajaxShowMessage(hexError, false);
+ thisFieldParams[fieldName] = PMA_getCellValue(g.currentEditCell);
+ }
+ } else {
+ thisFieldParams[fieldName] = $(g.cEdit).find('.edit_box').val();
+ }
+ if (g.wasEditedCellNull || thisFieldParams[fieldName] !== PMA_getCellValue(g.currentEditCell)) {
+ needToPost = true;
+ }
+ }
+
+ if (needToPost) {
+ $(g.currentEditCell).addClass('to_be_saved')
+ .data('value', thisFieldParams[fieldName]);
+ if (g.saveCellsAtOnce) {
+ $(g.o).find('div.save_edited').show();
+ }
+ g.isCellEdited = true;
+ }
+
+ return needToPost;
+ },
+
+ /**
+ * 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 to which the grid_edit should move
+ */
+ 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) {
+ // 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 {
+ // 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) {
+ // 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 {
+ // 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);
+ }
+ }
+ }
+ },
+
+ /**
+ * Initialize column resize feature.
+ */
+ initColResize: function () {
+ // create column resizer div
+ g.cRsz = document.createElement('div');
+ g.cRsz.className = 'cRsz';
+
+ // get data columns in the first row of the table
+ var $firstRowCols = $(g.t).find('tr:first th.draggable');
+
+ // create column borders
+ $firstRowCols.each(function () {
+ var cb = document.createElement('div'); // column border
+ $(cb).addClass('colborder')
+ .mousedown(function (e) {
+ g.dragStartRsz(e, this);
+ });
+ $(g.cRsz).append(cb);
+ });
+ g.reposRsz();
+
+ // attach to global div
+ $(g.gDiv).prepend(g.cRsz);
+ },
+
+ /**
+ * Initialize column reordering feature.
+ */
+ initColReorder: function () {
+ g.cCpy = document.createElement('div'); // column copy, to store copy of dragged column header
+ g.cPointer = document.createElement('div'); // column pointer, used when reordering column
+
+ // adjust g.cCpy
+ g.cCpy.className = 'cCpy';
+ $(g.cCpy).hide();
+
+ // adjust g.cPointer
+ g.cPointer.className = 'cPointer';
+ $(g.cPointer).css('visibility', 'hidden'); // set visibility to hidden instead of calling hide() to force browsers to cache the image in cPointer class
+
+ // assign column reordering hint
+ g.reorderHint = messages.strColOrderHint;
+
+ // get data columns in the first row of the table
+ var $firstRowCols = $(g.t).find('tr:first th.draggable');
+
+ // initialize column order
+ var $colOrder = $(g.o).find('.col_order'); // check if column order is passed from PHP
+ if ($colOrder.length > 0) {
+ g.colOrder = $colOrder.val().split(',');
+ for (let i = 0; i < g.colOrder.length; i++) {
+ g.colOrder[i] = parseInt(g.colOrder[i], 10);
+ }
+ } else {
+ g.colOrder = [];
+ for (let i = 0; i < $firstRowCols.length; i++) {
+ g.colOrder.push(i);
+ }
+ }
+
+ // register events
+ $(g.t).find('th.draggable')
+ .mousedown(function (e) {
+ $(g.o).addClass('turnOffSelect');
+ if (g.visibleHeadersCount > 1) {
+ g.dragStartReorder(e, this);
+ }
+ })
+ .mouseenter(function () {
+ if (g.visibleHeadersCount > 1) {
+ $(this).css('cursor', 'move');
+ } else {
+ $(this).css('cursor', 'inherit');
+ }
+ })
+ .mouseleave(function () {
+ g.showReorderHint = false;
+ $(this).tooltip('option', {
+ content: g.updateHint()
+ });
+ })
+ .dblclick(function (e) {
+ e.preventDefault();
+ $('')
+ .prop('title', messages.strColNameCopyTitle)
+ .addClass('modal-copy')
+ .text(messages.strColNameCopyText)
+ .append(
+ $('')
+ .prop('readonly', true)
+ .val($(this).data('column'))
+ )
+ .dialog({
+ resizable: false,
+ modal: true
+ })
+ .find('input').focus().select();
+ });
+ $(g.t).find('th.draggable a')
+ .dblclick(function (e) {
+ e.stopPropagation();
+ });
+ // restore column order when the restore button is clicked
+ $(g.o).find('div.restore_column').click(function () {
+ g.restoreColOrder();
+ });
+
+ // attach to global div
+ $(g.gDiv).append(g.cPointer);
+ $(g.gDiv).append(g.cCpy);
+
+ // prevent default "dragstart" event when dragging a link
+ $(g.t).find('th a').on('dragstart', function () {
+ return false;
+ });
+
+ // refresh the restore column button state
+ g.refreshRestoreButton();
+ },
+
+ /**
+ * Initialize column visibility feature.
+ */
+ initColVisib: function () {
+ g.cDrop = document.createElement('div'); // column drop-down arrows
+ g.cList = document.createElement('div'); // column visibility list
+
+ // adjust g.cDrop
+ g.cDrop.className = 'cDrop';
+
+ // adjust g.cList
+ g.cList.className = 'cList';
+ $(g.cList).hide();
+
+ // assign column visibility related hints
+ g.showAllColText = messages.strShowAllCol;
+
+ // 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 $colVisib = $(g.o).find('.col_visib'); // check if column visibility is passed from PHP
+ if ($colVisib.length > 0) {
+ g.colVisib = $colVisib.val().split(',');
+ for (i = 0; i < g.colVisib.length; i++) {
+ g.colVisib[i] = parseInt(g.colVisib[i], 10);
+ }
+ } else {
+ g.colVisib = [];
+ for (i = 0; i < $firstRowCols.length; i++) {
+ g.colVisib.push(1);
+ }
+ }
+
+ // make sure we have more than one column
+ if ($firstRowCols.length > 1) {
+ var $colVisibTh = $(g.t).find('th:not(.draggable)');
+ PMA_tooltip(
+ $colVisibTh,
+ 'th',
+ messages.strColVisibHint
+ );
+
+ // create column visibility drop-down arrow(s)
+ $colVisibTh.each(function () {
+ // var $th = $(this);
+ var cd = document.createElement('div'); // column drop-down arrow
+ // var pos = $th.position();
+ $(cd).addClass('coldrop')
+ .click(function () {
+ if (g.cList.style.display === 'none') {
+ g.showColList(this);
+ } else {
+ g.hideColList();
+ }
+ });
+ $(g.cDrop).append(cd);
+ });
+
+ // add column visibility control
+ g.cList.innerHTML = '';
+ var $listDiv = $(g.cList).find('div');
+
+ var tempClick = function () {
+ if (g.toggleCol($(this).index())) {
+ g.afterToggleCol();
+ }
+ };
+
+ for (i = 0; i < $firstRowCols.length; i++) {
+ var currHeader = $firstRowCols[i];
+ var listElmt = document.createElement('div');
+ $(listElmt).text($(currHeader).text())
+ .prepend('');
+ $listDiv.append(listElmt);
+ // add event on click
+ $(listElmt).click(tempClick);
+ }
+ // add "show all column" button
+ var showAll = document.createElement('div');
+ $(showAll).addClass('showAllColBtn')
+ .text(g.showAllColText);
+ $(g.cList).append(showAll);
+ $(showAll).click(function () {
+ g.showAllColumns();
+ });
+ // prepend "show all column" button at top if the list is too long
+ if ($firstRowCols.length > 10) {
+ var clone = showAll.cloneNode(true);
+ $(g.cList).prepend(clone);
+ $(clone).click(function () {
+ g.showAllColumns();
+ });
+ }
+ }
+
+ // hide column visibility list if we move outside the list
+ $(g.t).find('td, th.draggable').mouseenter(function () {
+ g.hideColList();
+ });
+
+ // attach to global div
+ $(g.gDiv).append(g.cDrop);
+ $(g.gDiv).append(g.cList);
+
+ // some adjustment
+ g.reposDrop();
+ },
+
+ /**
+ * Move currently Editing Cell to Up
+ */
+ moveUp: function (e) {
+ e.preventDefault();
+ var $thisField = $(g.currentEditCell);
+ var fieldName = getFieldName($(g.t), $thisField);
+
+ var whereClause = $thisField.parents('tr').first().find('.where_clause').val();
+ if (typeof whereClause === 'undefined') {
+ whereClause = '';
+ }
+ var found = false;
+ var $prevRow;
+ var $foundRow;
+ // var j = 0;
+
+ $thisField.parents('tr').first().parents('tbody').children().each(function () {
+ if ($(this).find('.where_clause').val() === whereClause) {
+ found = true;
+ $foundRow = $(this);
+ }
+ if (!found) {
+ $prevRow = $(this);
+ }
+ });
+
+ var newCell;
+
+ if (found && $prevRow) {
+ $prevRow.children('td').each(function () {
+ if (getFieldName($(g.t), $(this)) === fieldName) {
+ newCell = this;
+ }
+ });
+ }
+
+ if (newCell) {
+ g.hideEditCell(false, false, false, { move : true, cell : newCell });
+ }
+ },
+
+ /**
+ * Move currently Editing Cell to Down
+ */
+ moveDown: function (e) {
+ e.preventDefault();
+
+ var $thisField = $(g.currentEditCell);
+ var fieldName = getFieldName($(g.t), $thisField);
+
+ var whereClause = $thisField.parents('tr').first().find('.where_clause').val();
+ if (typeof whereClause === 'undefined') {
+ whereClause = '';
+ }
+ var found = false;
+ var $foundRow;
+ var $nextRow;
+ var j = 0;
+ var nextRowFound = false;
+ $thisField.parents('tr').first().parents('tbody').children().each(function () {
+ if ($(this).find('.where_clause').val() === whereClause) {
+ found = true;
+ $foundRow = $(this);
+ }
+ if (found) {
+ if (j >= 1 && ! nextRowFound) {
+ $nextRow = $(this);
+ nextRowFound = true;
+ } else {
+ j++;
+ }
+ }
+ });
+
+ var newCell;
+ if (found && $nextRow) {
+ $nextRow.children('td').each(function () {
+ if (getFieldName($(g.t), $(this)) === fieldName) {
+ newCell = this;
+ }
+ });
+ }
+
+ if (newCell) {
+ g.hideEditCell(false, false, false, { move : true, cell : newCell });
+ }
+ },
+
+ /**
+ * Move currently Editing Cell to Left
+ */
+ moveLeft: function (e) {
+ e.preventDefault();
+
+ var $thisField = $(g.currentEditCell);
+ var fieldName = getFieldName($(g.t), $thisField);
+
+ var whereClause = $thisField.parents('tr').first().find('.where_clause').val();
+ if (typeof whereClause === 'undefined') {
+ whereClause = '';
+ }
+ var found = false;
+ var $foundRow;
+ // var j = 0;
+ $thisField.parents('tr').first().parents('tbody').children().each(function () {
+ if ($(this).find('.where_clause').val() === whereClause) {
+ found = true;
+ $foundRow = $(this);
+ }
+ });
+
+ var leftCell;
+ var cellFound = false;
+ if (found) {
+ $foundRow.children('td.grid_edit').each(function () {
+ if (getFieldName($(g.t), $(this)) === fieldName) {
+ cellFound = true;
+ }
+ if (!cellFound) {
+ leftCell = this;
+ }
+ });
+ }
+
+ if (leftCell) {
+ g.hideEditCell(false, false, false, { move : true, cell : leftCell });
+ }
+ },
+
+ /**
+ * Move currently Editing Cell to Right
+ */
+ moveRight: function (e) {
+ e.preventDefault();
+
+ var $thisField = $(g.currentEditCell);
+ var fieldName = getFieldName($(g.t), $thisField);
+
+ var whereClause = $thisField.parents('tr').first().find('.where_clause').val();
+ if (typeof whereClause === 'undefined') {
+ whereClause = '';
+ }
+ var found = false;
+ var $foundRow;
+ var j = 0;
+ $thisField.parents('tr').first().parents('tbody').children().each(function () {
+ if ($(this).find('.where_clause').val() === whereClause) {
+ found = true;
+ $foundRow = $(this);
+ }
+ });
+
+ var rightCell;
+ var cellFound = false;
+ var nextCellFound = false;
+ if (found) {
+ $foundRow.children('td.grid_edit').each(function () {
+ if (getFieldName($(g.t), $(this)) === fieldName) {
+ cellFound = true;
+ }
+ if (cellFound) {
+ if (j >= 1 && ! nextCellFound) {
+ rightCell = this;
+ nextCellFound = true;
+ } else {
+ j++;
+ }
+ }
+ });
+ }
+
+ if (rightCell) {
+ g.hideEditCell(false, false, false, { move : true, cell : rightCell });
+ }
+ },
+
+ /**
+ * Initialize grid editing feature.
+ */
+ initGridEdit: function () {
+ function startGridEditing (e, cell) {
+ if (g.isCellEditActive) {
+ g.saveOrPostEditedCell();
+ } else {
+ g.showEditCell(cell);
+ }
+ 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;
+ g.cEditTextarea = document.createElement('div');
+
+ // adjust g.cEditStd
+ g.cEditStd.className = 'cEdit';
+ $(g.cEditStd).html('');
+ $(g.cEditStd).hide();
+
+ // adjust g.cEdit
+ g.cEditTextarea.className = 'cEdit';
+ $(g.cEditTextarea).html('');
+ $(g.cEditTextarea).hide();
+
+ // assign cell editing hint
+ g.cellEditHint = messages.strCellEditHint;
+ g.saveCellWarning = messages.strSaveCellWarning;
+ g.alertNonUnique = messages.strAlertNonUnique;
+ g.gotoLinkText = messages.strGoToLink;
+
+ // initialize cell editing configuration
+ g.saveCellsAtOnce = $(g.o).find('.save_cells_at_once').val();
+ g.maxTruncatedLen = CommonParams.get('LimitChars');
+
+ // register events
+ $(g.t).find('td.data.click1')
+ .click(function (e) {
+ startGridEditing(e, this);
+ // prevent default action when clicking on "link" in a table
+ if ($(e.target).is('.grid_edit a')) {
+ e.preventDefault();
+ }
+ });
+
+ $(g.t).find('td.data.click2')
+ .click(function (e) {
+ 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);
+ if ($link.is('.grid_edit.relation a')) {
+ e.preventDefault();
+ // get the click count and increase
+ var clicks = $cell.data('clicks');
+ clicks = (typeof clicks === 'undefined') ? 1 : clicks + 1;
+
+ if (clicks === 1) {
+ // if there are no previous clicks,
+ // start the single click timer
+ 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');
+ AJAX.requestHandler.call($link[0]);
+ $link.addClass('ajax');
+ $cell.data('clicks', 0);
+ }, 700);
+ $cell.data('clicks', clicks);
+ $cell.data('timer', timer);
+ } else {
+ // this is a double click, cancel the single click timer
+ // and make the click count 0
+ clearTimeout($cell.data('timer'));
+ $cell.data('clicks', 0);
+ // start grid-editing
+ startGridEditing(e, this);
+ }
+ }
+ })
+ .dblclick(function (e) {
+ if ($(e.target).is('.grid_edit a')) {
+ e.preventDefault();
+ } else {
+ startGridEditing(e, this);
+ }
+ });
+
+ $(g.cEditStd).on('keydown', 'input.edit_box, select', handleCtrlNavigation);
+
+ $(g.cEditStd).find('.edit_box').focus(function () {
+ g.showEditArea();
+ });
+ $(g.cEditStd).on('keydown', '.edit_box, select', function (e) {
+ if (e.which === 13) {
+ // post on pressing "Enter"
+ e.preventDefault();
+ g.saveOrPostEditedCell();
+ }
+ });
+ $(g.cEditStd).keydown(function (e) {
+ if (!g.isEditCellTextEditable) {
+ // prevent text editing
+ e.preventDefault();
+ }
+ });
+
+ $(g.cEditTextarea).on('keydown', 'textarea.edit_box, select', handleCtrlNavigation);
+
+ $(g.cEditTextarea).find('.edit_box').focus(function () {
+ g.showEditArea();
+ });
+ $(g.cEditTextarea).on('keydown', '.edit_box, select', function (e) {
+ if (e.which === 13 && !e.shiftKey) {
+ // post on pressing "Enter"
+ e.preventDefault();
+ g.saveOrPostEditedCell();
+ }
+ });
+ $(g.cEditTextarea).keydown(function (e) {
+ if (!g.isEditCellTextEditable) {
+ // prevent text editing
+ e.preventDefault();
+ }
+ });
+ $('html').click(function (e) {
+ // hide edit cell if the click is not fromDat edit area
+ if ($(e.target).parents().index($(g.cEdit)) === -1 &&
+ !$(e.target).parents('.ui-datepicker-header').length &&
+ !$('.browse_foreign_modal.ui-dialog:visible').length &&
+ !$(e.target).closest('.dismissable').length
+ ) {
+ g.hideEditCell();
+ }
+ }).keydown(function (e) {
+ if (e.which === 27 && g.isCellEditActive) {
+ // cancel on pressing "Esc"
+ g.hideEditCell(true);
+ }
+ });
+ $(g.o).find('div.save_edited').click(function () {
+ g.hideEditCell();
+ g.postEditedCell();
+ });
+ $(window).on('beforeunload', function () {
+ if (g.isCellEdited) {
+ return g.saveCellWarning;
+ }
+ });
+
+ // attach to global div
+ $(g.gDiv).append(g.cEditStd);
+ $(g.gDiv).append(g.cEditTextarea);
+
+ // add hint for grid editing feature when hovering "Edit" link in each table row
+ if (messages.strGridEditFeatureHint !== undefined) {
+ PMA_tooltip(
+ $(g.t).find('.edit_row_anchor a'),
+ 'a',
+ messages.strGridEditFeatureHint
+ );
+ }
+ }
+ };
+
+ /** ****************
+ * Initialize grid
+ ******************/
+
+ // 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 '';
+ });
+
+ // wrap remaining cells, except actions cell, with span
+ $(t).find('th, td:not(:has(span))')
+ .wrapInner('');
+
+ // create grid elements
+ g.gDiv = document.createElement('div'); // create global div
+
+ // initialize the table variable
+ g.t = t;
+
+ // enclosing .sqlqueryresults div
+ g.o = $(t).parents('.sqlqueryresults');
+
+ // get data columns in the first row of the table
+ var $firstRowCols = $(t).find('tr:first th.draggable');
+
+ // initialize visible headers count
+ g.visibleHeadersCount = $firstRowCols.filter(':visible').length;
+
+ // assign first column (actions) span
+ if (! $(t).find('tr:first th:first').hasClass('draggable')) { // action header exist
+ g.actionSpan = $(t).find('tr:first th:first').prop('colspan');
+ } else {
+ g.actionSpan = 0;
+ }
+
+ // assign table create time
+ // table_create_time will only available if we are in "Browse" tab
+ g.tableCreateTime = $(g.o).find('.table_create_time').val();
+
+ // assign the hints
+ g.sortHint = messages.strSortHint;
+ g.strMultiSortHint = messages.strMultiSortHint;
+ g.markHint = messages.strColMarkHint;
+ g.copyHint = messages.strColNameCopyHint;
+
+ // assign common hidden inputs
+ var $commonHiddenInputs = $(g.o).find('div.common_hidden_inputs');
+ g.server = $commonHiddenInputs.find('input[name=server]').val();
+ g.db = $commonHiddenInputs.find('input[name=db]').val();
+ g.table = $commonHiddenInputs.find('input[name=table]').val();
+
+ // add table class
+ $(t).addClass('pma_table');
+
+ // add relative position to global div so that resize handlers are correctly positioned
+ $(g.gDiv).css('position', 'relative');
+
+ // link the global div
+ $(t).before(g.gDiv);
+ $(g.gDiv).append(t);
+
+ // FEATURES
+ if (enableResize) {
+ g.initColResize();
+ }
+ // disable reordering for result from EXPLAIN or SHOW syntax, which do not have a table navigation panel
+ if (enableReorder &&
+ $(g.o).find('table.navigation').length > 0) {
+ g.initColReorder();
+ }
+ if (enableVisib) {
+ g.initColVisib();
+ }
+ // make sure we have the ajax class
+ if (enableGridEdit &&
+ $(t).is('.ajax')) {
+ g.initGridEdit();
+ }
+
+ // create tooltip for each | with draggable class
+ PMA_tooltip(
+ $(t).find('th.draggable'),
+ 'th',
+ g.updateHint()
+ );
+
+ // register events for hint tooltip (anchors inside draggable th)
+ $(t).find('th.draggable a')
+ .mouseenter(function () {
+ g.showSortHint = true;
+ g.showMultiSortHint = true;
+ $(t).find('th.draggable').tooltip('option', {
+ content: g.updateHint()
+ });
+ })
+ .mouseleave(function () {
+ g.showSortHint = false;
+ g.showMultiSortHint = false;
+ $(t).find('th.draggable').tooltip('option', {
+ content: g.updateHint()
+ });
+ });
+
+ // register events for dragging-related feature
+ if (enableResize || enableReorder) {
+ $(document).mousemove(function (e) {
+ g.dragMove(e);
+ });
+ $(document).mouseup(function (e) {
+ $(g.o).removeClass('turnOffSelect');
+ g.dragEnd(e);
+ });
+ }
+
+ // some adjustment
+ $(t).removeClass('data');
+ $(g.gDiv).addClass('data');
+}
+
+/**
+ * Module export
+ */
+export {
+ PMA_makegrid
+};
diff --git a/js/src/utils/menu_resizer.js b/js/src/utils/menu_resizer.js
index d09a4fc5ea..2435b75e46 100644
--- a/js/src/utils/menu_resizer.js
+++ b/js/src/utils/menu_resizer.js
@@ -1,4 +1,10 @@
/* vim: set expandtab sw=4 ts=4 sts=4: */
+
+/**
+ * Module import
+ */
+import { PMA_getImage } from '../functions/get_image';
+import { PMA_Messages as messages } from '../variables/export_variables';
/**
* Handles the resizing of a menu according to the available screen width
*
@@ -17,7 +23,13 @@
* To restore the menu to a state like before it was initialized:
* $('#myMenu').menuResizer('destroy');
*
- * @package PhpMyAdmin
+ * @access private
+ *
+ * @param {Element} $container
+ *
+ * @param {function} widthCalculator
+ *
+ * @return {void}
*/
function MenuResizer ($container, widthCalculator) {
var self = this;
@@ -45,7 +57,7 @@ function MenuResizer ($container, widthCalculator) {
// create submenu container
var link = $('', { href: '#', 'class': 'tab nowrap' })
- .text(PMA_messages.strMore)
+ .text(messages.strMore)
.on('click', false); // same as event.preventDefault()
var img = $container.find('li img');
if (img.length) {
@@ -80,54 +92,54 @@ MenuResizer.prototype.resize = function () {
var wmax = this.widthCalculator.call(this.$container);
var windowWidth = $(window).width();
var $submenu = this.$container.find('.submenu:last');
- var submenu_w = $submenu.outerWidth(true);
- var $submenu_ul = $submenu.find('ul');
+ var submenuW = $submenu.outerWidth(true);
+ var $submenuUl = $submenu.find('ul');
var $li = this.$container.find('> li');
- var $li2 = $submenu_ul.find('li');
- var more_shown = $li2.length > 0;
+ var $li2 = $submenuUl.find('li');
+ var moreShown = $li2.length > 0;
// Calculate the total width used by all the shown tabs
- var total_len = more_shown ? submenu_w : 0;
+ var totalLen = moreShown ? submenuW : 0;
var l = $li.length - 1;
var i;
for (i = 0; i < l; i++) {
- total_len += $($li[i]).outerWidth(true);
+ totalLen += $($li[i]).outerWidth(true);
}
var hasVScroll = document.body.scrollHeight > document.body.clientHeight;
if (hasVScroll) {
windowWidth += 15;
}
- var navigationwidth = wmax;
+ // var navigationwidth = wmax;
if (windowWidth < 768) {
wmax = 2000;
}
// Now hide menu elements that don't fit into the menubar
var hidden = false; // Whether we have hidden any tabs
- while (total_len >= wmax && --l >= 0) { // Process the tabs backwards
+ while (totalLen >= wmax && --l >= 0) { // Process the tabs backwards
hidden = true;
var el = $($li[l]);
- var el_width = el.outerWidth(true);
- el.data('width', el_width);
- if (! more_shown) {
- total_len -= el_width;
- el.prependTo($submenu_ul);
- total_len += submenu_w;
- more_shown = true;
+ var elWidth = el.outerWidth(true);
+ el.data('width', elWidth);
+ if (! moreShown) {
+ totalLen -= elWidth;
+ el.prependTo($submenuUl);
+ totalLen += submenuW;
+ moreShown = true;
} else {
- total_len -= el_width;
- el.prependTo($submenu_ul);
+ totalLen -= elWidth;
+ el.prependTo($submenuUl);
}
}
// 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 (i = 0, l = $li2.length; i < l; i++) {
- total_len += $($li2[i]).data('width');
+ totalLen += $($li2[i]).data('width');
// item fits or (it is the last item
// and it would fit if More got removed)
- if (total_len < wmax ||
- (i === $li2.length - 1 && total_len - submenu_w < wmax)
+ if (totalLen < wmax ||
+ (i === $li2.length - 1 && totalLen - submenuW < wmax)
) {
$($li2[i]).insertBefore($submenu);
} else {
@@ -143,7 +155,7 @@ MenuResizer.prototype.resize = function () {
} else {
$('.navigationbar').css({ 'width': 'auto' });
$('.navigationbar').css({ 'overflow': 'visible' });
- if ($submenu_ul.find('li').length > 0) {
+ if ($submenuUl.find('li').length > 0) {
$submenu.addClass('shown');
} else {
$submenu.removeClass('shown');
@@ -152,10 +164,10 @@ MenuResizer.prototype.resize = function () {
if (this.$container.find('> li').length === 1) {
// If there is only the "More" tab left, then we need
// to align the submenu to the left edge of the tab
- $submenu_ul.removeClass().addClass('only');
+ $submenuUl.removeClass().addClass('only');
} else {
// Otherwise we align the submenu to the right edge of the tab
- $submenu_ul.removeClass().addClass('notonly');
+ $submenuUl.removeClass().addClass('notonly');
}
if ($submenu.find('.tabactive').length) {
$submenu
diff --git a/js/src/utils/show_ajax_messages.js b/js/src/utils/show_ajax_messages.js
index 4c5afc840f..6a2defcf94 100644
--- a/js/src/utils/show_ajax_messages.js
+++ b/js/src/utils/show_ajax_messages.js
@@ -11,9 +11,9 @@ import { PMA_Messages as messages } from '../variables/export_variables';
import { PMA_highlightSQL } from './sql';
/**
- * @var {int} ajax_message_count Number of AJAX messages shown since page load
+ * @var {int} ajaxMessageCount Number of AJAX messages shown since page load
*/
-let ajax_message_count = 0;
+let ajaxMessageCount = 0;
/**
* Create a jQuery UI tooltip
@@ -129,7 +129,7 @@ const PMA_ajaxShowMessage = (message, timeout, type) => {
.prependTo('#page_content');
}
// Update message count to create distinct message elements every time
- ajax_message_count++;
+ ajaxMessageCount++;
// Remove all old messages, if any
$('span.ajax_notification[id^=ajax_message_num]').remove();
/**
@@ -138,7 +138,7 @@ const PMA_ajaxShowMessage = (message, timeout, type) => {
*/
var $retval = $(
''
)
.hide()
@@ -186,7 +186,7 @@ const PMA_ajaxShowMessage = (message, timeout, type) => {
* @return nothing
*/
function PMA_ajaxRemoveMessage ($thisMsgbox) {
- if ($thisMsgbox !== undefined && $thisMsgbox instanceof jQuery) {
+ if ($thisMsgbox !== undefined && $thisMsgbox instanceof $) {
$thisMsgbox
.stop(true, true)
.fadeOut('medium');
diff --git a/js/src/utils/sql.js b/js/src/utils/sql.js
index b842503792..10b05b2b2b 100644
--- a/js/src/utils/sql.js
+++ b/js/src/utils/sql.js
@@ -1,13 +1,13 @@
import CodeMirror from 'codemirror';
-import '../../../node_modules/codemirror/mode/sql/sql.js';
-import '../../../node_modules/codemirror/addon/runmode/runmode.js';
-import '../../../node_modules/codemirror/addon/hint/show-hint.js';
-import '../../../node_modules/codemirror/addon/hint/sql-hint.js';
-import '../../../node_modules/codemirror/addon/lint/lint.js';
-// import '../../../node_modules/codemirror/addon/lint/sql-lint.js';
+import 'codemirror/mode/sql/sql.js';
+import 'codemirror/addon/runmode/runmode.js';
+import 'codemirror/addon/hint/show-hint.js';
+import 'codemirror/addon/hint/sql-hint.js';
+import 'codemirror/addon/lint/lint.js';
+import '../plugins/codemirror/sql-lint';
import { mysql_doc_builtin, mysql_doc_keyword } from '../consts/doclinks';
-
-window.cm = CodeMirror;
+import CommonParams from '../variables/common_params';
+import { GlobalVariables, PMA_Messages as PMA_messages } from '../variables/export_variables';
/**
* Adds doc link to single highlighted SQL element
@@ -18,7 +18,7 @@ function PMA_doc_add ($elm, params) {
}
var url = PMA_sprintf(
- decodeURIComponent(mysql_doc_template),
+ decodeURIComponent(GlobalVariables.mysql_doc_template),
params[0]
);
if (params.length > 1) {
@@ -106,6 +106,12 @@ export function PMA_highlightSQL ($base) {
let sql_autocomplete_in_progress = false;
let sql_autocomplete = false;
var sql_autocomplete_default_table = '';
+
+export var sqlQueryOptions = {
+ codemirror_editor: false,
+ codemirror_inline_editor: false
+};
+
export function codemirrorAutocompleteOnInputRead (instance) {
if (!sql_autocomplete_in_progress
&& (!instance.options.hintOptions.tables || !sql_autocomplete)) {
@@ -119,8 +125,8 @@ export function codemirrorAutocompleteOnInputRead (instance) {
var href = 'db_sql_autocomplete.php';
var params = {
'ajax_request': true,
- 'server': PMA_commonParams.get('server'),
- 'db': PMA_commonParams.get('db'),
+ 'server': CommonParams.get('server'),
+ 'db': CommonParams.get('db'),
'no_debug': true
};
@@ -140,7 +146,7 @@ export function codemirrorAutocompleteOnInputRead (instance) {
success: function (data) {
if (data.success) {
var tables = JSON.parse(data.tables);
- sql_autocomplete_default_table = PMA_commonParams.get('table');
+ sql_autocomplete_default_table = CommonParams.get('table');
sql_autocomplete = [];
for (var table in tables) {
if (tables.hasOwnProperty(table)) {
@@ -197,76 +203,43 @@ export function codemirrorAutocompleteOnInputRead (instance) {
}
/**
- * Creates an SQL editor which supports auto completing etc.
- *
- * @param $textarea jQuery object wrapping the textarea to be made the editor
- * @param options optional options for CodeMirror
- * @param resize optional resizing ('vertical', 'horizontal', 'both')
- * @param lintOptions additional options for lint
+ * Updates the input fields for the parameters based on the query
*/
-export function PMA_getSQLEditor ($textarea, options, resize, lintOptions) {
- if ($textarea.length > 0 && typeof CodeMirror !== 'undefined') {
- // merge options for CodeMirror
- var defaults = {
- lineNumbers: true,
- matchBrackets: true,
- extraKeys: { 'Ctrl-Space': 'autocomplete' },
- hintOptions: { 'completeSingle': false, 'completeOnSingleClick': true },
- indentUnit: 4,
- mode: 'text/x-mysql',
- lineWrapping: true
- };
+export function updateQueryParameters () {
+ if ($('#parameterized').is(':checked')) {
+ var query = sqlQueryOptions.codemirror_editor
+ ? sqlQueryOptions.codemirror_editor.getValue()
+ : $('#sqlquery').val();
- if (CodeMirror.sqlLint) {
- $.extend(defaults, {
- gutters: ['CodeMirror-lint-markers'],
- lint: {
- 'getAnnotations': CodeMirror.sqlLint,
- 'async': true,
- 'lintOptions': lintOptions
+ var allParameters = query.match(/:[a-zA-Z0-9_]+/g);
+ var parameters = [];
+ // get unique parameters
+ if (allParameters) {
+ $.each(allParameters, function (i, parameter) {
+ if ($.inArray(parameter, parameters) === -1) {
+ parameters.push(parameter);
}
});
+ } else {
+ $('#parametersDiv').text(PMA_messages.strNoParam);
+ return;
}
- $.extend(true, defaults, options);
+ var $temp = $('');
+ $temp.append($('#parametersDiv').children());
+ $('#parametersDiv').empty();
- // create CodeMirror editor
- var codemirrorEditor = CodeMirror.fromTextArea($textarea[0], defaults);
- // allow resizing
- if (! resize) {
- resize = 'vertical';
- }
- var handles = '';
- if (resize === 'vertical') {
- handles = 's';
- }
- if (resize === 'both') {
- handles = 'all';
- }
- if (resize === 'horizontal') {
- handles = 'e, w';
- }
- $(codemirrorEditor.getWrapperElement())
- .css('resize', resize)
- .resizable({
- handles: handles,
- resize: function () {
- codemirrorEditor.setSize($(this).width(), $(this).height());
- }
- });
- // enable autocomplete
- codemirrorEditor.on('inputRead', codemirrorAutocompleteOnInputRead);
-
- // page locking
- codemirrorEditor.on('change', function (e) {
- e.data = {
- value: 3,
- content: codemirrorEditor.isClean(),
- };
- AJAX.lockPageHandler(e);
+ $.each(parameters, function (i, parameter) {
+ var paramName = parameter.substring(1);
+ var $param = $temp.find('#paramSpan_' + paramName);
+ if (! $param.length) {
+ $param = $('');
+ $('').text(parameter).appendTo($param);
+ $('').appendTo($param);
+ }
+ $('#parametersDiv').append($param);
});
-
- return codemirrorEditor;
+ } else {
+ $('#parametersDiv').empty();
}
- return null;
}
diff --git a/js/src/variables/import_variables.js b/js/src/variables/import_variables.js
index 6117b02bb7..8d896f3dfe 100644
--- a/js/src/variables/import_variables.js
+++ b/js/src/variables/import_variables.js
@@ -46,6 +46,12 @@ Variables.setGlobalVars(window.globalVars);
/**
* Importing common parameters like db, table, url etc
*
- * @argument {hash} window.common_params
+ * @argument {hash} window.commonParams
*/
-CommonParams.setAll(window.common_params);
+CommonParams.setAll(window.commonParams);
+
+CommonParams.set('CodemirrorEnable', window.CodemirrorEnable);
+
+CommonParams.set('LintEnable', window.LintEnable);
+
+CommonParams.set('ConsoleEnterExecutes', window.ConsoleEnterExecutes);
diff --git a/libraries/classes/Controllers/Server/ServerPluginsController.php b/libraries/classes/Controllers/Server/ServerPluginsController.php
index 0b8e438e53..fb7583d4fc 100644
--- a/libraries/classes/Controllers/Server/ServerPluginsController.php
+++ b/libraries/classes/Controllers/Server/ServerPluginsController.php
@@ -49,7 +49,6 @@ class ServerPluginsController extends Controller
$header = $this->response->getHeader();
$scripts = $header->getScripts();
- $scripts->addFile('vendor/jquery/jquery.tablesorter.js');
$scripts->addFile('server_plugins');
/**
diff --git a/libraries/classes/Header.php b/libraries/classes/Header.php
index 72b4717e5f..94b5454315 100644
--- a/libraries/classes/Header.php
+++ b/libraries/classes/Header.php
@@ -182,7 +182,6 @@ class Header
// the user preferences have not been merged at this point
$this->_scripts->addFile('messages.php', array('l' => $GLOBALS['lang']));
- $this->_scripts->addFile('common_params.php', array('l' => $GLOBALS['lang']));
$this->_scripts->addFile('vendors~index_new.js');
$this->_scripts->addFile('index_new.js');
$this->_scripts->addFile('keyhandler.js');
@@ -207,6 +206,7 @@ class Header
$this->_scripts->addFile('config');
$this->_scripts->addFile('doclinks.js');
$this->_scripts->addFile('functions.js');
+ $this->_scripts->addFile('functions');
$this->_scripts->addFile('navigation');
$this->_scripts->addFile('navigation.js');
$this->_scripts->addFile('indexes.js');
@@ -220,6 +220,7 @@ class Header
$this->_scripts->addFile('shortcuts_handler');
}
$this->_scripts->addCode($this->getJsParamsCode());
+ $this->_scripts->addCodeNew($this->getJsParamsCode(true));
}
/**
@@ -287,9 +288,11 @@ class Header
* Returns, as a string, a list of parameters
* used on the client side
*
+ * @param bool $flag to check for CommonParams for Modular Code
+ *
* @return string
*/
- public function getJsParamsCode(): string
+ public function getJsParamsCode($flag = false): string
{
$params = $this->getJsParams();
foreach ($params as $key => $value) {
@@ -299,7 +302,11 @@ class Header
$params[$key] = $key . ':"' . Sanitize::escapeJsString($value) . '"';
}
}
- return 'PMA_commonParams.setAll({' . implode(',', $params) . '});';
+ if ($flag) {
+ return 'var commonParams = {' . implode(',', $params) . '};';
+ } else {
+ return 'PMA_commonParams.setAll({' . implode(',', $params) . '});';
+ }
}
/**
@@ -434,6 +441,18 @@ class Header
);
}
}
+ $this->_scripts->addCodeNew(
+ 'CodemirrorEnable='
+ . ($GLOBALS['cfg']['CodemirrorEnable'] ? 'true' : 'false')
+ );
+ $this->_scripts->addCodeNew(
+ 'LintEnable='
+ . ($GLOBALS['cfg']['LintEnable'] ? 'true' : 'false')
+ );
+ $this->_scripts->addCodeNew(
+ 'ConsoleEnterExecutes='
+ . ($GLOBALS['cfg']['ConsoleEnterExecutes'] ? 'true' : 'false')
+ );
$this->_scripts->addCode(
'ConsoleEnterExecutes='
. ($GLOBALS['cfg']['ConsoleEnterExecutes'] ? 'true' : 'false')
diff --git a/libraries/classes/Scripts.php b/libraries/classes/Scripts.php
index 29125bb576..e2e043475b 100644
--- a/libraries/classes/Scripts.php
+++ b/libraries/classes/Scripts.php
@@ -36,6 +36,13 @@ class Scripts
* @var array of strings
*/
private $_code;
+ /**
+ * An array of discrete javascript code snippets for top script
+ *
+ * @access private
+ * @var array of strings
+ */
+ private $_codeNew;
/**
* Returns HTML code to include javascript file.
@@ -157,6 +164,19 @@ class Scripts
$this->_code .= "$code\n";
}
+ /**
+ * Adds a temporary new code snippet to the code to be executed
+ * at the top of the script before other scripts
+ *
+ * @param string $code The JS code to be added
+ *
+ * @return void
+ */
+ public function addCodeNew($code)
+ {
+ $this->_codeNew .= "$code\n";
+ }
+
/**
* Returns a list with filenames and a flag to indicate
* whether to register onload events for this file
@@ -187,6 +207,13 @@ class Scripts
public function getDisplay()
{
$retval = '';
+
+ $retval .= '';
+
if (count($this->_files) > 0) {
$retval .= $this->_includeFiles(
$this->_files
diff --git a/libraries/classes/SqlQueryForm.php b/libraries/classes/SqlQueryForm.php
index 4aa9e4cd78..add65805a6 100644
--- a/libraries/classes/SqlQueryForm.php
+++ b/libraries/classes/SqlQueryForm.php
@@ -278,7 +278,7 @@ class SqlQueryForm
. ''
. ' | | |
| |