New directory Stucture having modules imported and exported.

This commit needs proper discussion as many of the upcoming changes are based on this commit.
These files contains the working code only.
Right now the code has the functionality to work with both old js files and new js files.
Commeting style is yet to decide
Signed-off-by: Piyush Vijay <piyushvijay.1997@gmail.com>
This commit is contained in:
Piyush Vijay 2018-05-26 23:53:57 +05:30
parent 38cfa4630c
commit c67854e2a3
10 changed files with 1361 additions and 7 deletions

46
js/common_params.php Normal file
View File

@ -0,0 +1,46 @@
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Exporting of translated messages from PHP to Javascript
*
* @package PhpMyAdmin
*/
if (!defined('TESTSUITE')) {
chdir('..');
// Send correct type:
header('Content-Type: text/javascript; charset=UTF-8');
// Cache output in client - the nocache query parameter makes sure that this
// file is reloaded when config changes
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 3600) . ' GMT');
// Avoid loading the full common.inc.php because this would add many
// non-js-compatible stuff like DOCTYPE
define('PMA_MINIMUM_COMMON', true);
define('PMA_PATH_TO_BASEDIR', '../');
require_once './libraries/common.inc.php';
// Close session early as we won't write anything there
session_write_close();
}
// But this one is needed for Sanitize::escapeJsString()
use PhpMyAdmin\Header;
use PhpMyAdmin\Sanitize;
// use PhpMyAdmin\Scripts;
$header = new Header();
// $scripts = new Scripts();
echo "var common_params = new Array();\n";
foreach ($header->getJsParams() as $name => $value) {
Sanitize::printJsValue("common_params['" . $name . "']", $value);
}
// echo "var AJAX_Params = new Array();\n";
// foreach ($header->getDisplay() as $name => $value) {
// Sanitize::printJsValue("AJAX_Params['" . $name . "']", $value);
// }
?>

689
js/src/ajax.js Normal file
View File

@ -0,0 +1,689 @@
/**
* This object handles ajax requests for pages. It also
* handles the reloading of the main menu and scripts.
*/
export var AJAX = {
/**
* @var bool active Whether we are busy
*/
active: false,
/**
* @var object source The object whose event initialized the request
*/
source: null,
/**
* @var object xhr A reference to the ajax request that is currently running
*/
xhr: null,
/**
* @var object lockedTargets, list of locked targets
*/
lockedTargets: {},
/**
* @var function Callback to execute after a successful request
* Used by PMA_commonFunctions from common.js
*/
_callback: function () {},
/**
* @var bool _debug Makes noise in your Firebug console
*/
_debug: false,
/**
* @var object $msgbox A reference to a jQuery object that links to a message
* box that is generated by PMA_ajaxShowMessage()
*/
$msgbox: null,
/**
* Given the filename of a script, returns a hash to be
* used to refer to all the events registered for the file
*
* @param key string key The filename for which to get the event name
*
* @return int
*/
hash: function (key) {
/* http://burtleburtle.net/bob/hash/doobs.html#one */
key += '';
var len = key.length;
var hash = 0;
var i = 0;
for (; i < len; ++i) {
hash += key.charCodeAt(i);
hash += (hash << 10);
hash ^= (hash >> 6);
}
hash += (hash << 3);
hash ^= (hash >> 11);
hash += (hash << 15);
return Math.abs(hash);
},
/**
* Registers an onload event for a file
*
* @param file string file The filename for which to register the event
* @param func function func The function to execute when the page is ready
*
* @return self For chaining
*/
registerOnload: function (file, func) {
var eventName = 'onload_' + AJAX.hash(file);
$(document).on(eventName, func);
if (this._debug) {
console.log(
// no need to translate
'Registered event ' + eventName + ' for file ' + file
);
}
return this;
},
/**
* Registers a teardown event for a file. This is useful to execute functions
* that unbind events for page elements that are about to be removed.
*
* @param string file The filename for which to register the event
* @param function func The function to execute when
* the page is about to be torn down
*
* @return self For chaining
*/
registerTeardown: function (file, func) {
var eventName = 'teardown_' + AJAX.hash(file);
$(document).on(eventName, func);
if (this._debug) {
console.log(
// no need to translate
'Registered event ' + eventName + ' for file ' + file
);
}
return this;
},
/**
* Called when a page has finished loading, once for every
* file that registered to the onload event of that file.
*
* @param string file The filename for which to fire the event
*
* @return void
*/
fireOnload: function (file) {
var eventName = 'onload_' + AJAX.hash(file);
$(document).trigger(eventName);
if (this._debug) {
console.log(
// no need to translate
'Fired event ' + eventName + ' for file ' + file
);
}
},
/**
* Called just before a page is torn down, once for every
* file that registered to the teardown event of that file.
*
* @param string file The filename for which to fire the event
*
* @return void
*/
fireTeardown: function (file) {
var eventName = 'teardown_' + AJAX.hash(file);
$(document).triggerHandler(eventName);
if (this._debug) {
console.log(
// no need to translate
'Fired event ' + eventName + ' for file ' + file
);
}
},
/**
* function to handle lock page mechanism
*
* @param event the event object
*
* @return void
*/
lockPageHandler: function (event) {
var newHash = null;
var oldHash = null;
var lockId;
// CodeMirror lock
if (event.data.value === 3) {
newHash = event.data.content;
oldHash = true;
lockId = 'cm';
} else {
// Don't lock on enter.
if (0 === event.charCode) {
return;
}
lockId = $(this).data('lock-id');
if (typeof lockId === 'undefined') {
return;
}
/*
* @todo Fix Code mirror does not give correct full value (query)
* in textarea, it returns only the change in content.
*/
if (event.data.value === 1) {
newHash = AJAX.hash($(this).val());
} else {
newHash = AJAX.hash($(this).is(':checked'));
}
oldHash = $(this).data('val-hash');
}
// Set lock if old value !== new value
// otherwise release lock
if (oldHash !== newHash) {
AJAX.lockedTargets[lockId] = true;
} else {
delete AJAX.lockedTargets[lockId];
}
// Show lock icon if locked targets is not empty.
// otherwise remove lock icon
if (!jQuery.isEmptyObject(AJAX.lockedTargets)) {
$('#lock_page_icon').html(PMA_getImage('s_lock', PMA_messages.strLockToolTip).toString());
} else {
$('#lock_page_icon').html('');
}
},
/**
* resets the lock
*
* @return void
*/
resetLock: function () {
AJAX.lockedTargets = {};
$('#lock_page_icon').html('');
},
handleMenu: {
replace: function (content) {
$('#floating_menubar').html(content)
// Remove duplicate wrapper
// TODO: don't send it in the response
.children().first().remove();
$('#topmenu').menuResizer(PMA_mainMenuResizerCallback);
}
},
/**
* Event handler for clicks on links and form submissions
*
* @param object e Event data
*
* @return void
*/
requestHandler: function (event) {
// In some cases we don't want to handle the request here and either
// leave the browser deal with it natively (e.g: file download)
// or leave an existing ajax event handler present elsewhere deal with it
var href = $(this).attr('href');
if (typeof event !== 'undefined' && (event.shiftKey || event.ctrlKey)) {
return true;
} else if ($(this).attr('target')) {
return true;
} else if ($(this).hasClass('ajax') || $(this).hasClass('disableAjax')) {
// reset the lockedTargets object, as specified AJAX operation has finished
AJAX.resetLock();
return true;
} else if (href && href.match(/^#/)) {
return true;
} else if (href && href.match(/^mailto/)) {
return true;
} else if ($(this).hasClass('ui-datepicker-next') ||
$(this).hasClass('ui-datepicker-prev')
) {
return true;
}
if (typeof event !== 'undefined') {
event.preventDefault();
event.stopImmediatePropagation();
}
// triggers a confirm dialog if:
// the user has performed some operations on loaded page
// the user clicks on some link, (won't trigger for buttons)
// the click event is not triggered by script
if (typeof event !== 'undefined' && event.type === 'click' &&
event.isTrigger !== true &&
!jQuery.isEmptyObject(AJAX.lockedTargets)
) {
if (confirm(PMA_messages.strConfirmNavigation) === false) {
return false;
} else {
if (isStorageSupported('localStorage')) {
window.localStorage.removeItem('auto_saved_sql');
} else {
Cookies.set('auto_saved_sql', '');
}
}
}
AJAX.resetLock();
var isLink = !! href || false;
var previousLinkAborted = false;
if (AJAX.active === true) {
// Cancel the old request if abortable, when the user requests
// something else. Otherwise silently bail out, as there is already
// a request well in progress.
if (AJAX.xhr) {
// In case of a link request, attempt aborting
AJAX.xhr.abort();
if (AJAX.xhr.status === 0 && AJAX.xhr.statusText === 'abort') {
// If aborted
AJAX.$msgbox = PMA_ajaxShowMessage(PMA_messages.strAbortedRequest);
AJAX.active = false;
AJAX.xhr = null;
previousLinkAborted = true;
} else {
// If can't abort
return false;
}
} else {
// In case submitting a form, don't attempt aborting
return false;
}
}
AJAX.source = $(this);
$('html, body').animate({ scrollTop: 0 }, 'fast');
var url = isLink ? href : $(this).attr('action');
var argsep = PMA_commonParams.get('arg_separator');
var params = 'ajax_request=true' + argsep + 'ajax_page_request=true';
var dataPost = AJAX.source.getPostData();
if (! isLink) {
params += argsep + $(this).serialize();
} else if (dataPost) {
params += argsep + dataPost;
isLink = false;
}
if (! (history && history.pushState)) {
// Add a list of menu hashes that we have in the cache to the request
params += PMA_MicroHistory.menus.getRequestParam();
}
if (AJAX._debug) {
console.log('Loading: ' + url); // no need to translate
}
if (isLink) {
AJAX.active = true;
AJAX.$msgbox = PMA_ajaxShowMessage();
// Save reference for the new link request
AJAX.xhr = $.get(url, params, AJAX.responseHandler);
if (history && history.pushState) {
var state = {
url : href
};
if (previousLinkAborted) {
// hack: there is already an aborted entry on stack
// so just modify the aborted one
history.replaceState(state, null, href);
} else {
history.pushState(state, null, href);
}
}
} else {
/**
* Manually fire the onsubmit event for the form, if any.
* The event was saved in the jQuery data object by an onload
* handler defined below. Workaround for bug #3583316
*/
var onsubmit = $(this).data('onsubmit');
// Submit the request if there is no onsubmit handler
// or if it returns a value that evaluates to true
if (typeof onsubmit !== 'function' || onsubmit.apply(this, [event])) {
AJAX.active = true;
AJAX.$msgbox = PMA_ajaxShowMessage();
$.post(url, params, AJAX.responseHandler);
}
}
},
/**
* Called after the request that was initiated by this.requestHandler()
* has completed successfully or with a caught error. For completely
* failed requests or requests with uncaught errors, see the .ajaxError
* handler at the bottom of this file.
*
* To refer to self use 'AJAX', instead of 'this' as this function
* is called in the jQuery context.
*
* @param object e Event data
*
* @return void
*/
responseHandler: function (data) {
if (typeof data === 'undefined' || data === null) {
return;
}
if (typeof data.success !== 'undefined' && data.success) {
$('html, body').animate({ scrollTop: 0 }, 'fast');
PMA_ajaxRemoveMessage(AJAX.$msgbox);
if (data._redirect) {
PMA_ajaxShowMessage(data._redirect, false);
AJAX.active = false;
AJAX.xhr = null;
return;
}
AJAX.scriptHandler.reset(function () {
if (data._reloadNavigation) {
PMA_reloadNavigation();
}
if (data._title) {
$('title').replaceWith(data._title);
}
if (data._menu) {
if (history && history.pushState) {
var state = {
url : data._selflink,
menu : data._menu
};
history.replaceState(state, null);
AJAX.handleMenu.replace(data._menu);
} else {
PMA_MicroHistory.menus.replace(data._menu);
PMA_MicroHistory.menus.add(data._menuHash, data._menu);
}
} else if (data._menuHash) {
if (! (history && history.pushState)) {
PMA_MicroHistory.menus.replace(PMA_MicroHistory.menus.get(data._menuHash));
}
}
if (data._disableNaviSettings) {
PMA_disableNaviSettings();
} else {
PMA_ensureNaviSettings(data._selflink);
}
// Remove all containers that may have
// been added outside of #page_content
$('body').children()
.not('#pma_navigation')
.not('#floating_menubar')
.not('#page_nav_icons')
.not('#page_content')
.not('#selflink')
.not('#pma_header')
.not('#pma_footer')
.not('#pma_demo')
.not('#pma_console_container')
.not('#prefs_autoload')
.remove();
// Replace #page_content with new content
if (data.message && data.message.length > 0) {
$('#page_content').replaceWith(
'<div id=\'page_content\'>' + data.message + '</div>'
);
PMA_highlightSQL($('#page_content'));
checkNumberOfFields();
}
if (data._selflink) {
var source = data._selflink.split('?')[0];
// Check for faulty links
$selflink_replace = {
'import.php': 'tbl_sql.php',
'tbl_chart.php': 'sql.php',
'tbl_gis_visualization.php': 'sql.php'
};
if ($selflink_replace[source]) {
var replacement = $selflink_replace[source];
data._selflink = data._selflink.replace(source, replacement);
}
$('#selflink').find('> a').attr('href', data._selflink);
}
if (data._params) {
PMA_commonParams.setAll(data._params);
}
if (data._scripts) {
AJAX.scriptHandler.load(data._scripts);
}
if (data._selflink && data._scripts && data._menuHash && data._params) {
if (! (history && history.pushState)) {
PMA_MicroHistory.add(
data._selflink,
data._scripts,
data._menuHash,
data._params,
AJAX.source.attr('rel')
);
}
}
if (data._displayMessage) {
$('#page_content').prepend(data._displayMessage);
PMA_highlightSQL($('#page_content'));
}
$('#pma_errors').remove();
var msg = '';
if (data._errSubmitMsg) {
msg = data._errSubmitMsg;
}
if (data._errors) {
$('<div/>', { id : 'pma_errors', class : 'clearfloat' })
.insertAfter('#selflink')
.append(data._errors);
// bind for php error reporting forms (bottom)
$('#pma_ignore_errors_bottom').on('click', function (e) {
e.preventDefault();
PMA_ignorePhpErrors();
});
$('#pma_ignore_all_errors_bottom').on('click', function (e) {
e.preventDefault();
PMA_ignorePhpErrors(false);
});
// In case of 'sendErrorReport'='always'
// submit the hidden error reporting form.
if (data._sendErrorAlways === '1' &&
data._stopErrorReportLoop !== '1'
) {
$('#pma_report_errors_form').submit();
PMA_ajaxShowMessage(PMA_messages.phpErrorsBeingSubmitted, false);
$('html, body').animate({ scrollTop:$(document).height() }, 'slow');
} else if (data._promptPhpErrors) {
// otherwise just prompt user if it is set so.
msg = msg + PMA_messages.phpErrorsFound;
// scroll to bottom where all the errors are displayed.
$('html, body').animate({ scrollTop:$(document).height() }, 'slow');
}
}
PMA_ajaxShowMessage(msg, false);
// bind for php error reporting forms (popup)
$('#pma_ignore_errors_popup').on('click', function () {
PMA_ignorePhpErrors();
});
$('#pma_ignore_all_errors_popup').on('click', function () {
PMA_ignorePhpErrors(false);
});
if (typeof AJAX._callback === 'function') {
AJAX._callback.call();
}
AJAX._callback = function () {};
});
} else {
PMA_ajaxShowMessage(data.error, false);
AJAX.active = false;
AJAX.xhr = null;
PMA_handleRedirectAndReload(data);
if (data.fieldWithError) {
$(':input.error').removeClass('error');
$('#' + data.fieldWithError).addClass('error');
}
}
},
/**
* This object is in charge of downloading scripts,
* keeping track of what's downloaded and firing
* the onload event for them when the page is ready.
*/
scriptHandler: {
/**
* @var array _scripts The list of files already downloaded
*/
_scripts: [],
/**
* @var string _scriptsVersion version of phpMyAdmin from which the
* scripts have been loaded
*/
_scriptsVersion: null,
/**
* @var array _scriptsToBeLoaded The list of files that
* need to be downloaded
*/
_scriptsToBeLoaded: [],
/**
* @var array _scriptsToBeFired The list of files for which
* to fire the onload and unload events
*/
_scriptsToBeFired: [],
_scriptsCompleted: false,
/**
* Records that a file has been downloaded
*
* @param string file The filename
* @param string fire Whether this file will be registering
* onload/teardown events
*
* @return self For chaining
*/
add: function (file, fire) {
this._scripts.push(file);
if (fire) {
// Record whether to fire any events for the file
// This is necessary to correctly tear down the initial page
this._scriptsToBeFired.push(file);
}
return this;
},
/**
* Download a list of js files in one request
*
* @param array files An array of filenames and flags
*
* @return void
*/
load: function (files, callback) {
var self = this;
var i;
// Clear loaded scripts if they are from another version of phpMyAdmin.
// Depends on common params being set before loading scripts in responseHandler
if (self._scriptsVersion === null) {
self._scriptsVersion = PMA_commonParams.get('PMA_VERSION');
} else if (self._scriptsVersion !== PMA_commonParams.get('PMA_VERSION')) {
self._scripts = [];
self._scriptsVersion = PMA_commonParams.get('PMA_VERSION');
}
self._scriptsCompleted = false;
self._scriptsToBeFired = [];
// We need to first complete list of files to load
// as next loop will directly fire requests to load them
// and that triggers removal of them from
// self._scriptsToBeLoaded
for (i in files) {
self._scriptsToBeLoaded.push(files[i].name);
if (files[i].fire) {
self._scriptsToBeFired.push(files[i].name);
}
}
for (i in files) {
var script = files[i].name;
// Only for scripts that we don't already have
if ($.inArray(script, self._scripts) === -1) {
this.add(script);
this.appendScript(script, callback);
} else {
self.done(script, callback);
}
}
// Trigger callback if there is nothing else to load
self.done(null, callback);
},
/**
* Called whenever all files are loaded
*
* @return void
*/
done: function (script, callback) {
if (typeof ErrorReport !== 'undefined') {
ErrorReport.wrap_global_functions();
}
if ($.inArray(script, this._scriptsToBeFired)) {
AJAX.fireOnload(script);
}
if ($.inArray(script, this._scriptsToBeLoaded)) {
this._scriptsToBeLoaded.splice($.inArray(script, this._scriptsToBeLoaded), 1);
}
if (script === null) {
this._scriptsCompleted = true;
}
/* We need to wait for last signal (with null) or last script load */
AJAX.active = (this._scriptsToBeLoaded.length > 0) || ! this._scriptsCompleted;
/* Run callback on last script */
if (! AJAX.active && $.isFunction(callback)) {
callback();
}
},
/**
* Appends a script element to the head to load the scripts
*
* @return void
*/
appendScript: function (name, callback) {
var head = document.head || document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var self = this;
script.type = 'text/javascript';
/**
* This piece of code is for appending the new revamped files into the
* DOM so that both new and old files can be used simultaneously
* It checks whether the file contains new in its name or not
*/
var check = name.split('_');
if (check[check.length - 1] === 'new.js') {
var script_src = '';
if (PMA_commonParams.get('environment') === 'development') {
script_src += 'http://localhost:' + PMA_commonParams.get('webpack_port') + '/js/dist/';
} else if (PMA_commonParams.get('environment') === 'production') {
script_src = 'js/dist/';
}
script.src = script_src + name + '?' + 'v=' + encodeURIComponent(PMA_commonParams.get('PMA_VERSION'));
} else {
script.src = 'js/' + name + '?' + 'v=' + encodeURIComponent(PMA_commonParams.get('PMA_VERSION'));
}
script.async = false;
script.onload = function () {
self.done(name, callback);
};
head.appendChild(script);
},
/**
* Fires all the teardown event handlers for the current page
* and rebinds all forms and links to the request handler
*
* @param function callback The callback to call after resetting
*
* @return void
*/
reset: function (callback) {
for (var i in this._scriptsToBeFired) {
AJAX.fireTeardown(this._scriptsToBeFired[i]);
}
this._scriptsToBeFired = [];
/**
* Re-attach a generic event handler to clicks
* on pages and submissions of forms
*/
$(document).off('click', 'a').on('click', 'a', AJAX.requestHandler);
$(document).off('submit', 'form').on('submit', 'form', AJAX.requestHandler);
if (! (history && history.pushState)) {
PMA_MicroHistory.update();
}
callback();
}
}
}

View File

@ -0,0 +1,157 @@
/**
* Expand the navigation and highlight the current database or table/view
*
* @returns void
*/
export function PMA_showCurrentNavigation() {
var db = PMA_commonParams.get('db');
var table = PMA_commonParams.get('table');
$('#pma_navigation_tree').find('li.selected').removeClass('selected');
if (db) {
var $dbItem = findLoadedItem($('#pma_navigation_tree').find('> div'), db, 'database', !table);
if ($('#navi_db_select').length && $('option:selected', $('#navi_db_select')).length) {
if (!PMA_selectCurrentDb()) {
return;
}
// If loaded database in navigation is not same as current one
if ($('#pma_navigation_tree_content').find('span.loaded_db:first').text() !== $('#navi_db_select').val()) {
loadChildNodes(false, $('option:selected', $('#navi_db_select')), function (data) {
handleTableOrDb(table, $('#pma_navigation_tree_content'));
var $children = $('#pma_navigation_tree_content').children('div.list_container');
$children.promise().done(navTreeStateUpdate);
});
} else {
handleTableOrDb(table, $('#pma_navigation_tree_content'));
}
} else if ($dbItem) {
var $expander = $dbItem.children('div:first').children('a.expander');
// if not loaded or loaded but collapsed
if (!$expander.hasClass('loaded') || $expander.find('img').is('.ic_b_plus')) {
expandTreeNode($expander, function () {
handleTableOrDb(table, $dbItem);
});
} else {
handleTableOrDb(table, $dbItem);
}
}
} else if ($('#navi_db_select').length && $('#navi_db_select').val()) {
$('#navi_db_select').val('').hide().trigger('change');
}
PMA_showFullName($('#pma_navigation_tree'));
function handleTableOrDb (table, $dbItem) {
if (table) {
loadAndHighlightTableOrView($dbItem, table);
} else {
var $container = $dbItem.children('div.list_container');
var $tableContainer = $container.children('ul').children('li.tableContainer');
if ($tableContainer.length > 0) {
var $expander = $tableContainer.children('div:first').children('a.expander');
$tableContainer.addClass('selected');
expandTreeNode($expander, function () {
scrollToView($dbItem, true);
});
} else {
scrollToView($dbItem, true);
}
}
}
function findLoadedItem ($container, name, clazz, doSelect) {
var ret = false;
$container.children('ul').children('li').each(function () {
var $li = $(this);
// this is a navigation group, recurse
if ($li.is('.navGroup')) {
var $container = $li.children('div.list_container');
var $childRet = findLoadedItem($container, name, clazz, doSelect);
if ($childRet) {
ret = $childRet;
return false;
}
} else {
// this is a real navigation item
// name and class matches
if ((clazz && $li.is('.' + clazz) || !clazz) && $li.children('a').text() === name) {
if (doSelect) {
$li.addClass('selected');
}
// taverse up and expand and parent navigation groups
$li.parents('.navGroup').each(function () {
var $cont = $(this).children('div.list_container');
if (!$cont.is(':visible')) {
$(this).children('div:first').children('a.expander').click();
}
});
ret = $li;
return false;
}
}
});
return ret;
}
function loadAndHighlightTableOrView ($dbItem, itemName) {
var $container = $dbItem.children('div.list_container');
var $expander;
var $whichItem = isItemInContainer($container, itemName, 'li.table, li.view');
// If item already there in some container
if ($whichItem) {
// get the relevant container while may also be a subcontainer
var $relatedContainer = $whichItem.closest('li.subContainer').length ? $whichItem.closest('li.subContainer') : $dbItem;
$whichItem = findLoadedItem($relatedContainer.children('div.list_container'), itemName, null, true);
// Show directly
showTableOrView($whichItem, $relatedContainer.children('div:first').children('a.expander'));
// else if item not there, try loading once
} else {
var $sub_containers = $dbItem.find('.subContainer');
// If there are subContainers i.e. tableContainer or viewContainer
if ($sub_containers.length > 0) {
var $containers = [];
$sub_containers.each(function (index) {
$containers[index] = $(this);
$expander = $containers[index].children('div:first').children('a.expander');
if (!$expander.hasClass('loaded')) {
loadAndShowTableOrView($expander, $containers[index], itemName);
}
});
// else if no subContainers
} else {
$expander = $dbItem.children('div:first').children('a.expander');
if (!$expander.hasClass('loaded')) {
loadAndShowTableOrView($expander, $dbItem, itemName);
}
}
}
}
function loadAndShowTableOrView ($expander, $relatedContainer, itemName) {
loadChildNodes(true, $expander, function (data) {
var $whichItem = findLoadedItem($relatedContainer.children('div.list_container'), itemName, null, true);
if ($whichItem) {
showTableOrView($whichItem, $expander);
}
});
}
function showTableOrView ($whichItem, $expander) {
expandTreeNode($expander, function (data) {
if ($whichItem) {
scrollToView($whichItem, false);
}
});
}
function isItemInContainer ($container, name, clazz) {
var $whichItem = null;
$items = $container.find(clazz);
var found = false;
$items.each(function () {
if ($(this).children('a').text() === name) {
$whichItem = $(this);
return false;
}
});
return $whichItem;
}
}

View File

@ -0,0 +1,102 @@
import zxcvbn from 'zxcvbn';
import { PMA_Messages as PMA_messages } from '../variables/export_variables';
/**
* Validates the password field in a form
*
* @see PMA_messages.strPasswordEmpty
* @see PMA_messages.strPasswordNotSame
* @param object $the_form The form to be validated
* @return bool
*/
function PMA_checkPassword ($the_form) {
// Did the user select 'no password'?
if ($the_form.find('#nopass_1').is(':checked')) {
return true;
} else {
var $pred = $the_form.find('#select_pred_password');
if ($pred.length && ($pred.val() === 'none' || $pred.val() === 'keep')) {
return true;
}
}
var $password = $the_form.find('input[name=pma_pw]');
var $password_repeat = $the_form.find('input[name=pma_pw2]');
var alert_msg = false;
if ($password.val() === '') {
alert_msg = PMA_messages.strPasswordEmpty;
} else if ($password.val() !== $password_repeat.val()) {
alert_msg = PMA_messages.strPasswordNotSame;
}
if (alert_msg) {
alert(alert_msg);
$password.val('');
$password_repeat.val('');
$password.focus();
return false;
}
return true;
}
/**
* Validates the "add a user" form
*
* @return {boolean} whether the form is validated or not
*/
export function checkAddUser (the_form) {
if (the_form.elements.pred_hostname.value === 'userdefined' && the_form.elements.hostname.value === '') {
alert(PMA_messages.strHostEmpty);
the_form.elements.hostname.focus();
return false;
}
if (the_form.elements.pred_username.value === 'userdefined' && the_form.elements.username.value === '') {
alert(PMA_messages.strUserEmpty);
the_form.elements.username.focus();
return false;
}
return PMA_checkPassword($(the_form));
} // end of the 'checkAddUser()' function
/**
* Function to check the password strength
*
* @param {string} value Passworrd string
* @param {object} meter_obj jQuery object to show strength in meter
* @param {object} meter_object_label jQuery object to show text of password strnegth
* @param {string} username Username string
*
* @returns {void}
*/
export function checkPasswordStrength (value, meter_obj, meter_object_label, username) {
// List of words we don't want to appear in the password
var customDict = [
'phpmyadmin',
'mariadb',
'mysql',
'php',
'my',
'admin',
];
if (username !== null) {
customDict.push(username);
}
var zxcvbn_obj = zxcvbn(value, customDict);
var strength = zxcvbn_obj.score;
strength = parseInt(strength);
meter_obj.val(strength);
switch (strength) {
case 0: meter_object_label.html(PMA_messages.strExtrWeak);
break;
case 1: meter_object_label.html(PMA_messages.strVeryWeak);
break;
case 2: meter_object_label.html(PMA_messages.strWeak);
break;
case 3: meter_object_label.html(PMA_messages.strGood);
break;
case 4: meter_object_label.html(PMA_messages.strStrong);
}
}

View File

@ -0,0 +1,6 @@
import $ from 'jquery';
import 'jquery-ui-bundle';
window.jQ = $;
export const jQuery = $;

View File

@ -0,0 +1,208 @@
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Functions for adding and removing ajax messages
*/
/**
* Module imports
*/
import sprintf from 'sprintf-js';
import { PMA_Messages as PMA_messages } from '../variables/export_variables';
/**
* @var int ajax_message_count Number of AJAX messages shown since page load
*/
let ajax_message_count = 0;
/**
* Create a jQuery UI tooltip
*
* @param $elements jQuery object representing the elements
* @param item the item
* (see https://api.jqueryui.com/tooltip/#option-items)
* @param myContent content of the tooltip
* @param additionalOptions to override the default options
*
*/
export function PMA_tooltip ($elements, item, myContent, additionalOptions) {
if ($('#no_hint').length > 0) {
return;
}
var defaultOptions = {
content: myContent,
items: item,
tooltipClass: 'tooltip',
track: true,
show: false,
hide: false
};
$elements.tooltip($.extend(true, defaultOptions, additionalOptions));
}
/**
* @param string string message to display
*
* @return string A concated string of aguments passed
*/
export function PMA_sprintf () {
/**
* This package can be implemented in two ways
*
* 1) sprintf.sprintf("A %s is %s", "string", "string");
*
* 2) sprintf.vsprintf("A %s is %s", ["string", "string"]);
*/
return sprintf.sprintf(...arguments);
}
/**
* Show a message on the top of the page for an Ajax request
*
* Sample usage:
*
* 1) var $msg = PMA_ajaxShowMessage();
* This will show a message that reads "Loading...". Such a message will not
* disappear automatically and cannot be dismissed by the user. To remove this
* message either the PMA_ajaxRemoveMessage($msg) function must be called or
* another message must be show with PMA_ajaxShowMessage() function.
*
* 2) var $msg = PMA_ajaxShowMessage(PMA_messages.strProcessingRequest);
* This is a special case. The behaviour is same as above,
* just with a different message
*
* 3) var $msg = PMA_ajaxShowMessage('The operation was successful');
* This will show a message that will disappear automatically and it can also
* be dismissed by the user.
*
* 4) var $msg = PMA_ajaxShowMessage('Some error', false);
* This will show a message that will not disappear automatically, but it
* can be dismissed by the user after he has finished reading it.
*
* @param string message string containing the message to be shown.
* optional, defaults to 'Loading...'
* @param mixed timeout number of milliseconds for the message to be visible
* optional, defaults to 5000. If set to 'false', the
* notification will never disappear
* @param string type string to dictate the type of message shown.
* optional, defaults to normal notification.
* If set to 'error', the notification will show message
* with red background.
* If set to 'success', the notification will show with
* a green background.
* @return jQuery object jQuery Element that holds the message div
* this object can be passed to PMA_ajaxRemoveMessage()
* to remove the notification
*/
export const PMA_ajaxShowMessage = (message, timeout, type) => {
/**
* @var self_closing Whether the notification will automatically disappear
*/
var self_closing = true;
/**
* @var dismissable Whether the user will be able to remove
* the notification by clicking on it
*/
var dismissable = true;
// Handle the case when a empty data.message is passed.
// We don't want the empty message
if (message === '') {
return true;
} else if (! message) {
// If the message is undefined, show the default
message = PMA_messages.strLoading;
dismissable = false;
self_closing = false;
} else if (message === PMA_messages.strProcessingRequest) {
// This is another case where the message should not disappear
dismissable = false;
self_closing = false;
}
// Figure out whether (or after how long) to remove the notification
if (timeout === undefined) {
timeout = 5000;
} else if (timeout === false) {
self_closing = false;
}
// Determine type of message, add styling as required
if (type === 'error') {
message = '<div class="error">' + message + '</div>';
} else if (type === 'success') {
message = '<div class="success">' + message + '</div>';
}
// Create a parent element for the AJAX messages, if necessary
if ($('#loading_parent').length === 0) {
$('<div id="loading_parent"></div>')
.prependTo('#page_content');
}
// Update message count to create distinct message elements every time
ajax_message_count++;
// Remove all old messages, if any
$('span.ajax_notification[id^=ajax_message_num]').remove();
/**
* @var $retval a jQuery object containing the reference
* to the created AJAX message
*/
var $retval = $(
'<span class="ajax_notification" id="ajax_message_num_' +
ajax_message_count +
'"></span>'
)
.hide()
.appendTo('#loading_parent')
.html(message)
.show();
// If the notification is self-closing we should create a callback to remove it
if (self_closing) {
$retval
.delay(timeout)
.fadeOut('medium', function () {
if ($(this).is(':data(tooltip)')) {
$(this).tooltip('destroy');
}
// Remove the notification
$(this).remove();
});
}
// If the notification is dismissable we need to add the relevant class to it
// and add a tooltip so that the users know that it can be removed
if (dismissable) {
$retval.addClass('dismissable').css('cursor', 'pointer');
/**
* Add a tooltip to the notification to let the user know that (s)he
* can dismiss the ajax notification by clicking on it.
*/
PMA_tooltip(
$retval,
'span',
PMA_messages.strDismiss
);
}
PMA_highlightSQL($retval);
return $retval;
};
/**
* Removes the message shown for an Ajax operation when it's completed
*
* @param jQuery object jQuery Element that holds the notification
*
* @return nothing
*/
export function PMA_ajaxRemoveMessage ($this_msgbox) {
if ($this_msgbox !== undefined && $this_msgbox instanceof jQuery) {
$this_msgbox
.stop(true, true)
.fadeOut('medium');
if ($this_msgbox.is(':data(tooltip)')) {
$this_msgbox.tooltip('destroy');
} else {
$this_msgbox.remove();
}
}
}

View File

@ -0,0 +1,35 @@
/**
* HTML escaping
*/
export function escapeHtml (unsafe) {
if (typeof(unsafe) !== 'undefined') {
return unsafe
.toString()
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
} else {
return false;
}
}
export function escapeJsString (unsafe) {
if (typeof(unsafe) !== 'undefined') {
return unsafe
.toString()
.replace('\x00', '')
.replace('\\', '\\\\')
.replace('\'', '\\\'')
.replace('&#039;', '\\\&#039;')
.replace('"', '\"')
.replace('&quot;', '\&quot;')
.replace('\n', '\n')
.replace('\r', '\r')
.replace(/<\/script/gi, '</\' + \'script');
} else {
return false;
}
}

View File

@ -0,0 +1,99 @@
import { PMA_sprintf } from '../utils/show_ajax_messages';
import { PMA_showCurrentNavigation } from '../functions/navigation';
/**
* Holds common parameters such as server, db, table, etc
*
* The content for this is normally loaded from Header.php or
* Response.php and executed by ajax.js
*/
export const PMA_commonParams = (function () {
/**
* @var hash params An associative array of key value pairs
* @access private
*/
var params = {};
// The returned object is the public part of the module
return {
/**
* Saves all the key value pair that
* are provided in the input array
*
* @param obj hash The input array
*
* @return void
*/
setAll: function (obj) {
var reload = false;
var updateNavigation = false;
for (var i in obj) {
if (params[i] !== undefined && params[i] !== obj[i]) {
if (i === 'db' || i === 'table') {
updateNavigation = true;
}
reload = true;
}
params[i] = obj[i];
}
if (updateNavigation &&
$('#pma_navigation_tree').hasClass('synced')
) {
PMA_showCurrentNavigation();
}
},
/**
* Retrieves a value given its key
* Returns empty string for undefined values
*
* @param name string The key
*
* @return string
*/
get: function (name) {
return params[name];
},
/**
* Saves a single key value pair
*
* @param name string The key
* @param value string The value
*
* @return self For chainability
*/
set: function (name, value) {
var updateNavigation = false;
if (name === 'db' || name === 'table' &&
params[name] !== value
) {
updateNavigation = true;
}
params[name] = value;
if (updateNavigation &&
$('#pma_navigation_tree').hasClass('synced')
) {
PMA_showCurrentNavigation();
}
return this;
},
/**
* Returns the url query string using the saved parameters
*
* @return string
*/
getUrlQuery: function () {
var common = this.get('common_query');
var separator = '?';
var argsep = PMA_commonParams.get('arg_separator');
if (common.length > 0) {
separator = argsep;
}
return PMA_sprintf(
'%s%sserver=%s' + argsep + 'db=%s' + argsep + 'table=%s',
this.get('common_query'),
separator,
encodeURIComponent(this.get('server')),
encodeURIComponent(this.get('db')),
encodeURIComponent(this.get('table'))
);
}
};
}());

View File

@ -0,0 +1,12 @@
import { Variables } from './global_variables';
import { PMA_commonParams } from './common_params';
Variables.setAllMessages(window.PMA_messages);
/**
* This statement to be placed in the file going to be
* executed firstly like functions.js
*/
PMA_commonParams.setAll(window.common_params);
export const PMA_Messages = Variables.getMessages();

View File

@ -5,20 +5,20 @@
* jquery-ui-timepicker edits using global functions
*/
export const PMA_messages = (function () {
export const Variables = (function () {
/**
* @var obj params An associate array having key value pairs
* of messages to show in js files.
*
* @access private
*/
let messages = new Array();
let pmaMessages = new Array();
/**
* @var obj params Associative array having global configurations
*
* @access private
*/
let globalVars = new Array();
let globalVariables = new Array();
/**
* @var obj params Associative array having timepicker edits
*
@ -37,7 +37,7 @@ export const PMA_messages = (function () {
* @return array
*/
getMessages: () => {
return messages;
return pmaMessages;
},
/**
* Retrieves the globalVars array
@ -45,7 +45,7 @@ export const PMA_messages = (function () {
* @return array
*/
getGlobalVars: () => {
return globalVars;
return globalVariables;
},
/**
* Retrieves the timePickerVars array
@ -72,7 +72,7 @@ export const PMA_messages = (function () {
*/
setAllMessages: (obj) => {
for (var i in obj) {
messages[i] = obj[i];
pmaMessages[i] = obj[i];
}
},
/**
@ -84,7 +84,7 @@ export const PMA_messages = (function () {
*/
setGlobalVars: (obj) => {
for (var i in obj) {
globalVars[i] = obj[i];
globalVariables[i] = obj[i];
}
},
/**