1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 * @fileoverview function used in table data manipulation pages
7 * @requires js/functions.js
12 * Modify form controls when the "NULL" checkbox is checked
14 * @param theType string the MySQL field type
15 * @param urlField string the urlencoded field name - OBSOLETE
16 * @param md5Field string the md5 hashed field name
17 * @param multi_edit string the multi_edit row sequence number
19 * @return boolean always true
21 function nullify(theType, urlField, md5Field, multi_edit)
23 var rowForm = document.forms.insertForm;
25 if (typeof(rowForm.elements['funcs' + multi_edit + '[' + md5Field + ']']) != 'undefined') {
26 rowForm.elements['funcs' + multi_edit + '[' + md5Field + ']'].selectedIndex = -1;
29 // "ENUM" field with more than 20 characters
31 rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'][1].selectedIndex = -1;
34 else if (theType == 2) {
35 var elts = rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'];
36 // when there is just one option in ENUM:
40 var elts_cnt = elts.length;
41 for (var i = 0; i < elts_cnt; i++) {
42 elts[i].checked = false;
48 else if (theType == 3) {
49 rowForm.elements['fields' + multi_edit + '[' + md5Field + '][]'].selectedIndex = -1;
51 // Foreign key field (drop-down)
52 else if (theType == 4) {
53 rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].selectedIndex = -1;
55 // foreign key field (with browsing icon for foreign values)
56 else if (theType == 6) {
57 rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = '';
60 else /*if (theType == 5)*/ {
61 rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = '';
62 } // end if... else if... else
65 } // end of the 'nullify()' function
69 * javascript DateTime format validation.
70 * its used to prevent adding default (0000-00-00 00:00:00) to database when user enter wrong values
71 * Start of validation part
73 //function checks the number of days in febuary
74 function daysInFebruary(year)
76 return (((year % 4 === 0) && (((year % 100 !== 0)) || (year % 400 === 0))) ? 29 : 28);
78 //function to convert single digit to double digit
79 function fractionReplace(num)
81 num = parseInt(num, 10);
82 return num >= 1 && num <= 9 ? '0' + num : '00';
85 /* function to check the validity of date
86 * The following patterns are accepted in this validation (accepted in mysql as well)
90 * 4) And instead of using '-' the following punctuations can be used (+,.,*,^,@,/) All these are accepted by mysql as well. Therefore no issues
92 function isDate(val, tmstmp)
94 val = val.replace(/[.|*|^|+|//|@]/g, '-');
95 var arrayVal = val.split("-");
96 for (var a = 0; a < arrayVal.length; a++) {
97 if (arrayVal[a].length == 1) {
98 arrayVal[a] = fractionReplace(arrayVal[a]);
101 val = arrayVal.join("-");
103 var dtexp = new RegExp(/^([0-9]{4})-(((01|03|05|07|08|10|12)-((0[0-9])|([1-2][0-9])|(3[0-1])))|((02|04|06|09|11)-((0[0-9])|([1-2][0-9])|30))|((00)-(00)))$/);
104 if (val.length == 8) {
107 if (dtexp.test(val)) {
108 var month = parseInt(val.substring(pos + 3, pos + 5), 10);
109 var day = parseInt(val.substring(pos + 6, pos + 8), 10);
110 var year = parseInt(val.substring(0, pos + 2), 10);
111 if (month == 2 && day > daysInFebruary(year)) {
114 if (val.substring(0, pos + 2).length == 2) {
115 year = parseInt("20" + val.substring(0, pos + 2), 10);
117 if (tmstmp === true) {
121 if (year > 2038 || (year > 2037 && day > 19 && month >= 1) || (year > 2037 && month > 1)) {
131 /* function to check the validity of time
132 * The following patterns are accepted in this validation (accepted in mysql as well)
139 var arrayVal = val.split(":");
140 for (var a = 0, l = arrayVal.length; a < l; a++) {
141 if (arrayVal[a].length == 1) {
142 arrayVal[a] = fractionReplace(arrayVal[a]);
145 val = arrayVal.join(":");
146 var tmexp = new RegExp(/^(-)?(([0-7]?[0-9][0-9])|(8[0-2][0-9])|(83[0-8])):((0[0-9])|([1-5][0-9])):((0[0-9])|([1-5][0-9]))(\.[0-9]{1,6}){0,1}$/);
147 return tmexp.test(val);
151 * To check whether insert section is ignored or not
153 function checkForCheckbox(multi_edit)
155 if($("#insert_ignore_"+multi_edit).length) {
156 return $("#insert_ignore_"+multi_edit).is(":unchecked");
161 function verificationsAfterFieldChange(urlField, multi_edit, theType)
163 var evt = window.event || arguments.callee.caller.arguments[0];
164 var target = evt.target || evt.srcElement;
165 var $this_input = $(":input[name^='fields[multi_edit][" + multi_edit + "][" +
167 // the function drop-down that corresponds to this input field
168 var $this_function = $("select[name='funcs[multi_edit][" + multi_edit + "][" +
170 var function_selected = false;
171 if (typeof $this_function.val() !== 'undefined' &&
172 $this_function.val() !== null &&
173 $this_function.val().length > 0
175 function_selected = true;
178 //To generate the textbox that can take the salt
179 var new_salt_box = "<br><input type=text name=salt[multi_edit][" + multi_edit + "][" + urlField + "]" +
180 " id=salt_" + target.id + " placeholder='" + PMA_messages.strEncryptionKey + "'>";
182 //If encrypting or decrypting functions that take salt as input is selected append the new textbox for salt
183 if (target.value === 'AES_ENCRYPT' ||
184 target.value === 'AES_DECRYPT' ||
185 target.value === 'DES_ENCRYPT' ||
186 target.value === 'DES_DECRYPT' ||
187 target.value === 'ENCRYPT') {
188 if (!($("#salt_" + target.id).length)) {
189 $this_input.after(new_salt_box);
192 //Remove the textbox for salt
193 $('#salt_' + target.id).prev('br').remove();
194 $("#salt_" + target.id).remove();
197 if (target.value === 'AES_DECRYPT'
198 || target.value === 'AES_ENCRYPT'
199 || target.value === 'MD5') {
200 $('#' + target.id).rules("add", {
201 validationFunctionForFuns: {
203 depends: function() {
204 return checkForCheckbox(multi_edit);
210 // Unchecks the corresponding "NULL" control
211 $("input[name='fields_null[multi_edit][" + multi_edit + "][" + urlField + "]']").prop('checked', false);
213 // Unchecks the Ignore checkbox for the current row
214 $("input[name='insert_ignore_" + multi_edit + "']").prop('checked', false);
216 var charExceptionHandling;
217 if (theType.substring(0,4) === "char") {
218 charExceptionHandling = theType.substring(5,6);
220 else if (theType.substring(0,7) === "varchar") {
221 charExceptionHandling = theType.substring(8,9);
223 if (function_selected) {
224 $this_input.removeAttr('min');
225 $this_input.removeAttr('max');
226 // @todo: put back attributes if corresponding function is deselected
229 if ($this_input.data('rulesadded') == null && ! function_selected) {
231 //call validate before adding rules
232 $($this_input[0].form).validate();
233 // validate for date time
234 if (theType == "datetime" || theType == "time" || theType == "date" || theType == "timestamp") {
235 $this_input.rules("add", {
236 validationFunctionForDateTime: {
238 depends: function() {
239 return checkForCheckbox(multi_edit);
244 //validation for integer type
245 if ($this_input.data('type') === 'INT') {
246 var mini = parseInt($this_input.attr('min'));
247 var maxi = parseInt($this_input.attr('max'));
248 $this_input.rules("add", {
251 depends: function() {
252 return checkForCheckbox(multi_edit);
257 depends: function() {
258 if (isNaN($this_input.val())) {
261 return checkForCheckbox(multi_edit);
267 depends: function() {
268 if (isNaN($this_input.val())) {
271 return checkForCheckbox(multi_edit);
276 //validation for CHAR types
277 } else if ($this_input.data('type') === 'CHAR') {
278 var maxlen = $this_input.data('maxlength');
279 if (typeof maxlen !== 'undefined') {
281 maxlen=charExceptionHandling;
283 $this_input.rules("add", {
286 depends: function() {
287 return checkForCheckbox(multi_edit);
292 // validate binary & blob types
293 } else if ($this_input.data('type') === 'HEX') {
294 $this_input.rules("add", {
295 validationFunctionForHex: {
297 depends: function() {
298 return checkForCheckbox(multi_edit);
303 $this_input.data('rulesadded', true);
304 } else if ($this_input.data('rulesadded') == true && function_selected) {
305 // remove any rules added
306 $this_input.rules("remove");
307 // remove any error messages
309 .removeClass('error')
310 .removeAttr('aria-invalid')
313 $this_input.data('rulesadded', null);
316 /* End of fields validation*/
319 * Unbind all event handlers before tearing down a page
321 AJAX.registerTeardown('tbl_change.js', function () {
322 $(document).off('click', 'span.open_gis_editor');
323 $(document).off('click', "input[name^='insert_ignore_']");
324 $(document).off('click', "input[name='gis_data[save]']");
325 $(document).off('click', 'input.checkbox_null');
326 $('select[name="submit_type"]').unbind('change');
327 $(document).off('change', "#insert_rows");
331 * Ajax handlers for Change Table page
333 * Actions Ajaxified here:
334 * Submit Data to be inserted into the table.
335 * Restart insertion with 'N' rows.
337 AJAX.registerOnload('tbl_change.js', function () {
339 if($("#insertForm").length) {
340 // validate the comment form when it is submitted
341 $("#insertForm").validate();
342 jQuery.validator.addMethod("validationFunctionForHex", function(value, element) {
343 return value.match(/^[a-f0-9]*$/i) !== null;
346 jQuery.validator.addMethod("validationFunctionForFuns", function(value, element, options) {
347 if (value.substring(0, 3) === "AES" && options.data('type') !== 'HEX') {
351 return !(value.substring(0, 3) === "MD5" &&
352 typeof options.data('maxlength') !== 'undefined' &&
353 options.data('maxlength') < 32);
356 jQuery.validator.addMethod("validationFunctionForDateTime", function(value, element, options) {
357 var dt_value = value;
358 var theType = options;
359 if (theType == "date") {
360 return isDate(dt_value);
362 } else if (theType == "time") {
363 return isTime(dt_value);
365 } else if (theType == "datetime" || theType == "timestamp") {
367 dt_value = dt_value.trim();
368 if (dt_value == "CURRENT_TIMESTAMP") {
371 if (theType == "timestamp") {
374 if (dt_value == "0000-00-00 00:00:00") {
377 var dv = dt_value.indexOf(" ");
378 if (dv == -1) { // Only the date component, which is valid
379 return isDate(dt_value, tmstmp);
382 return isDate(dt_value.substring(0, dv), tmstmp) &&
383 isTime(dt_value.substring(dv + 1));
387 * message extending script must be run
388 * after initiation of functions
390 extendingValidatorMessages();
393 $.datepicker.initialized = false;
395 $(document).on('click', 'span.open_gis_editor', function (event) {
396 event.preventDefault();
400 var value = $span.parent('td').children("input[type='text']").val();
402 var field = $span.parents('tr').children('td:first').find("input[type='hidden']").val();
404 var type = $span.parents('tr').find('span.column_type').text();
405 // Names of input field and null checkbox
406 var input_name = $span.parent('td').children("input[type='text']").attr('name');
408 var token = $("input[name='token']").val();
411 if (!gisEditorLoaded) {
412 loadJSAndGISEditor(value, field, type, input_name, token);
414 loadGISEditor(value, field, type, input_name, token);
419 * Forced validation check of fields
421 $(document).on('click',"input[name^='insert_ignore_']", function (event) {
422 $("#insertForm").valid();
426 * Uncheck the null checkbox as geometry data is placed on the input field
428 $(document).on('click', "input[name='gis_data[save]']", function (event) {
429 var input_name = $('form#gis_data_editor_form').find("input[name='input_name']").val();
430 var $null_checkbox = $("input[name='" + input_name + "']").parents('tr').find('.checkbox_null');
431 $null_checkbox.prop('checked', false);
435 * Handles all current checkboxes for Null; this only takes care of the
436 * checkboxes on currently displayed rows as the rows generated by
437 * "Continue insertion" are handled in the "Continue insertion" code
440 $(document).on('click', 'input.checkbox_null', function () {
442 // use hidden fields populated by tbl_change.php
443 $(this).siblings('.nullify_code').val(),
444 $(this).closest('tr').find('input:hidden').first().val(),
445 $(this).siblings('.hashed_field').val(),
446 $(this).siblings('.multi_edit').val()
451 * Reset the auto_increment column to 0 when selecting any of the
452 * insert options in submit_type-dropdown. Only perform the reset
453 * when we are in edit-mode, and not in insert-mode(no previous value
456 $('select[name="submit_type"]').bind('change', function () {
457 var thisElemSubmitTypeVal = $(this).val();
458 var $table = $('table.insertRowTable');
459 var auto_increment_column = $table.find('input[name^="auto_increment"]');
460 auto_increment_column.each(function () {
461 var $thisElemAIField = $(this);
462 var thisElemName = $thisElemAIField.attr('name');
464 var prev_value_field = $table.find('input[name="' + thisElemName.replace('auto_increment', 'fields_prev') + '"]');
465 var value_field = $table.find('input[name="' + thisElemName.replace('auto_increment', 'fields') + '"]');
466 var previous_value = $(prev_value_field).val();
467 if (previous_value !== undefined) {
468 if (thisElemSubmitTypeVal == 'insert'
469 || thisElemSubmitTypeVal == 'insertignore'
470 || thisElemSubmitTypeVal == 'showinsert'
472 $(value_field).val(0);
474 $(value_field).val(previous_value);
482 * Continue Insertion form
484 $(document).on('change', "#insert_rows", function (event) {
485 event.preventDefault();
487 * @var columnCount Number of number of columns table has.
489 var columnCount = $("table.insertRowTable:first").find("tr").has("input[name*='fields_name']").length;
491 * @var curr_rows Number of current insert rows already on page
493 var curr_rows = $("table.insertRowTable").length;
495 * @var target_rows Number of rows the user wants
497 var target_rows = $("#insert_rows").val();
499 // remove all datepickers
500 $('input.datefield, input.datetimefield').each(function () {
501 $(this).datepicker('destroy');
504 if (curr_rows < target_rows) {
506 var tempIncrementIndex = function () {
508 var $this_element = $(this);
510 * Extract the index from the name attribute for all input/select fields and increment it
511 * name is of format funcs[multi_edit][10][<long random string of alphanum chars>]
515 * @var this_name String containing name of the input/select elements
517 var this_name = $this_element.attr('name');
518 /** split {@link this_name} at [10], so we have the parts that can be concatenated later */
519 var name_parts = this_name.split(/\[\d+\]/);
520 /** extract the [10] from {@link name_parts} */
521 var old_row_index_string = this_name.match(/\[\d+\]/)[0];
522 /** extract 10 - had to split into two steps to accomodate double digits */
523 var old_row_index = parseInt(old_row_index_string.match(/\d+/)[0], 10);
525 /** calculate next index i.e. 11 */
526 new_row_index = old_row_index + 1;
527 /** generate the new name i.e. funcs[multi_edit][11][foobarbaz] */
528 var new_name = name_parts[0] + '[' + new_row_index + ']' + name_parts[1];
530 var hashed_field = name_parts[1].match(/\[(.+)\]/)[1];
531 $this_element.attr('name', new_name);
533 /** If element is select[name*='funcs'], update id */
534 if ($this_element.is("select[name*='funcs']")) {
535 var this_id = $this_element.attr("id");
536 var id_parts = this_id.split(/\_/);
537 var old_id_index = id_parts[1];
538 var prevSelectedValue = $("#field_" + old_id_index + "_1").val();
539 var new_id_index = parseInt(old_id_index) + columnCount;
540 var new_id = 'field_' + new_id_index + '_1';
541 $this_element.attr('id', new_id);
542 $this_element.find("option").filter(function () {
543 return $(this).text() === prevSelectedValue;
544 }).attr("selected","selected");
546 // If salt field is there then update its id.
547 var nextSaltInput = $this_element.parent().next("td").next("td").find("input[name*='salt']");
548 if (nextSaltInput.length !== 0) {
549 nextSaltInput.attr("id", "salt_" + new_id);
553 // handle input text fields and textareas
554 if ($this_element.is('.textfield') || $this_element.is('.char') || $this_element.is('textarea')) {
555 // do not remove the 'value' attribute for ENUM columns
556 // special handling for radio fields after updating ids to unique - see below
557 if ($this_element.closest('tr').find('span.column_type').html() != 'enum') {
558 $this_element.val($this_element.closest('tr').find('span.default_value').html());
562 // Remove onchange attribute that was placed
563 // by tbl_change.php; it refers to the wrong row index
564 .attr('onchange', null)
565 // Keep these values to be used when the element
567 .data('hashed_field', hashed_field)
568 .data('new_row_index', new_row_index)
569 .bind('change', function () {
570 var $changed_element = $(this);
571 verificationsAfterFieldChange(
572 $changed_element.data('hashed_field'),
573 $changed_element.data('new_row_index'),
574 $changed_element.closest('tr').find('span.column_type').html()
579 if ($this_element.is('.checkbox_null')) {
581 // this event was bound earlier by jQuery but
582 // to the original row, not the cloned one, so unbind()
584 // Keep these values to be used when the element
586 .data('hashed_field', hashed_field)
587 .data('new_row_index', new_row_index)
588 .bind('click', function () {
589 var $changed_element = $(this);
591 $changed_element.siblings('.nullify_code').val(),
592 $this_element.closest('tr').find('input:hidden').first().val(),
593 $changed_element.data('hashed_field'),
594 '[multi_edit][' + $changed_element.data('new_row_index') + ']'
600 var tempReplaceAnchor = function () {
601 var $anchor = $(this);
602 var new_value = 'rownumber=' + new_row_index;
603 // needs improvement in case something else inside
604 // the href contains this pattern
605 var new_href = $anchor.attr('href').replace(/rownumber=\d+/, new_value);
606 $anchor.attr('href', new_href);
609 while (curr_rows < target_rows) {
612 * @var $last_row Object referring to the last row
614 var $last_row = $("#insertForm").find(".insertRowTable:last");
616 // need to access this at more than one level
617 // (also needs improvement because it should be calculated
618 // just once per cloned row, not once per column)
619 var new_row_index = 0;
621 //Clone the insert tables
624 .insertBefore("#actions_panel")
625 .find('input[name*=multi_edit],select[name*=multi_edit],textarea[name*=multi_edit]')
626 .each(tempIncrementIndex)
628 .find('.foreign_values_anchor')
629 .each(tempReplaceAnchor);
631 //Insert/Clone the ignore checkboxes
632 if (curr_rows == 1) {
633 $('<input id="insert_ignore_1" type="checkbox" name="insert_ignore_1" checked="checked" />')
634 .insertBefore("table.insertRowTable:last")
635 .after('<label for="insert_ignore_1">' + PMA_messages.strIgnore + '</label>');
639 * @var $last_checkbox Object reference to the last checkbox in #insertForm
641 var $last_checkbox = $("#insertForm").children('input:checkbox:last');
643 /** name of {@link $last_checkbox} */
644 var last_checkbox_name = $last_checkbox.attr('name');
645 /** index of {@link $last_checkbox} */
646 var last_checkbox_index = parseInt(last_checkbox_name.match(/\d+/), 10);
647 /** name of new {@link $last_checkbox} */
648 var new_name = last_checkbox_name.replace(/\d+/, last_checkbox_index + 1);
650 $('<br/><div class="clearfloat"></div>')
651 .insertBefore("table.insertRowTable:last");
655 .attr({'id': new_name, 'name': new_name})
656 .prop('checked', true)
657 .insertBefore("table.insertRowTable:last");
659 $('label[for^=insert_ignore]:last')
661 .attr('for', new_name)
662 .insertBefore("table.insertRowTable:last");
665 .insertBefore("table.insertRowTable:last");
669 // recompute tabindex for text fields and other controls at footer;
670 // IMO it's not really important to handle the tabindex for
673 $('.textfield, .char, textarea')
676 $(this).attr('tabindex', tabindex);
677 // update the IDs of textfields to ensure that they are unique
678 $(this).attr('id', "field_" + tabindex + "_3");
680 // special handling for radio fields after updating ids to unique
681 if ($(this).closest('tr').find('span.column_type').html() === 'enum') {
682 if ($(this).val() === $(this).closest('tr').find('span.default_value').html()) {
683 $(this).prop('checked', true);
685 $(this).prop('checked', false);
689 $('.control_at_footer')
692 $(this).attr('tabindex', tabindex);
694 } else if (curr_rows > target_rows) {
695 while (curr_rows > target_rows) {
696 $("input[id^=insert_ignore]:last")
697 .nextUntil("fieldset")
703 // Add all the required datepickers back
708 function changeValueFieldType(elem, searchIndex)
710 var fieldsValue = $("select#fieldID_" + searchIndex);
711 if (0 === fieldsValue.size()) {
715 var type = $(elem).val();
716 if ('IN (...)' == type ||
717 'NOT IN (...)' == type ||
719 'NOT BETWEEN' == type
721 $("#fieldID_" + searchIndex).attr('multiple', '');
723 $("#fieldID_" + searchIndex).removeAttr('multiple');