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[1-9])|([1-2][0-9])|(3[0-1])))|((02|04|06|09|11)-((0[1-9])|([1-2][0-9])|30)))$/);
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-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}$/);
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' && $this_function.val().length > 0) {
172 function_selected = true;
175 // check if it is textarea rather than input
176 if ($this_input.length === 0) {
177 $this_input = $("textarea[name='fields[multi_edit][" + multi_edit + "][" +
181 //To generate the textbox that can take the salt
182 var new_salt_box = "<br><input type=text name=salt[multi_edit][" + multi_edit + "][" + urlField + "]" +
183 " id=salt_" + target.id + " placeholder='" + PMA_messages.strEncryptionKey + "'>";
185 //If encrypting or decrypting functions that take salt as input is selected append the new textbox for salt
186 if (target.value === 'AES_ENCRYPT' ||
187 target.value === 'AES_DECRYPT' ||
188 target.value === 'DES_ENCRYPT' ||
189 target.value === 'DES_DECRYPT' ||
190 target.value === 'ENCRYPT') {
191 if (!($("#salt_" + target.id).length)) {
192 $this_input.after(new_salt_box);
195 //Remove the textbox for salt
196 $('#salt_' + target.id).prev('br').remove();
197 $("#salt_" + target.id).remove();
200 if (target.value === 'AES_DECRYPT'
201 || target.value === 'AES_ENCRYPT'
202 || target.value === 'MD5') {
203 $('#' + target.id).rules("add", {
204 validationFunctionForFuns: {
206 depends: function() {
207 return checkForCheckbox(multi_edit);
213 var removeOnclick = 1;
214 if ($("input[name='fields_null[multi_edit][" + multi_edit + "][" + urlField + "]']").length) {
217 // Unchecks the corresponding "NULL" control
218 $("input[name='fields_null[multi_edit][" + multi_edit + "][" + urlField + "]']").prop('checked', false);
220 // Unchecks the Ignore checkbox for the current row
221 $("input[name='insert_ignore_" + multi_edit + "']").prop('checked', false);
223 var charExceptionHandling;
224 if (theType.substring(0,4) === "char") {
225 charExceptionHandling = theType.substring(5,6);
227 else if (theType.substring(0,7) === "varchar") {
228 charExceptionHandling = theType.substring(8,9);
230 if (function_selected) {
231 $this_input.removeAttr('min');
232 $this_input.removeAttr('max');
233 // @todo: put back attributes if corresponding function is deselected
236 // explanation of the last condition:
237 // if a function has been selected in the function drop-down,
238 // do not validate the input field
239 if (target.name && target.name.substring(0, 6) === "fields" && ! function_selected) {
240 //call validate before adding rules
241 $($this_input[0].form).validate();
242 // validate for date time
243 if (theType == "datetime" || theType == "time" || theType == "date" || theType == "timestamp") {
244 $this_input.rules("add", {
245 validationFunctionForDateTime: {
247 depends: function() {
248 return checkForCheckbox(multi_edit);
253 //validation for integer type
254 if ($this_input.data('type') === 'INT') {
255 var mini = parseInt($this_input.attr('min'));
256 var maxi = parseInt($this_input.attr('max'));
257 $this_input.rules("add", {
260 depends: function() {
261 return checkForCheckbox(multi_edit);
266 depends: function() {
267 if (isNaN($this_input.val())) {
270 return checkForCheckbox(multi_edit);
276 depends: function() {
277 if (isNaN($this_input.val())) {
280 return checkForCheckbox(multi_edit);
285 //validation for CHAR types
286 } else if ($this_input.data('type') === 'CHAR') {
287 var maxlen = $this_input.data('maxlength');
288 if (typeof maxlen !== 'undefined') {
290 maxlen=charExceptionHandling;
292 $this_input.rules("add", {
295 depends: function() {
296 return checkForCheckbox(multi_edit);
301 // validate binary & blob types
302 } else if ($this_input.data('type') === 'HEX') {
303 $this_input.rules("add", {
304 validationFunctionForHex: {
306 depends: function() {
307 return checkForCheckbox(multi_edit);
312 if (removeOnclick === 1) {
313 $this_input.removeAttr('onchange');
317 /* End of fields validation*/
320 * Unbind all event handlers before tearing down a page
322 AJAX.registerTeardown('tbl_change.js', function () {
323 $(document).off('click', 'span.open_gis_editor');
324 $(document).off('click', "input[name^='insert_ignore_']");
325 $(document).off('click', "input[name='gis_data[save]']");
326 $(document).off('click', 'input.checkbox_null');
327 $('select[name="submit_type"]').unbind('change');
328 $(document).off('change', "#insert_rows");
332 * Ajax handlers for Change Table page
334 * Actions Ajaxified here:
335 * Submit Data to be inserted into the table.
336 * Restart insertion with 'N' rows.
338 AJAX.registerOnload('tbl_change.js', function () {
340 if($("#insertForm").length) {
341 // validate the comment form when it is submitted
342 $("#insertForm").validate();
343 jQuery.validator.addMethod("validationFunctionForHex", function(value, element) {
344 return value.match(/^[a-f0-9]*$/i) !== null;
347 jQuery.validator.addMethod("validationFunctionForFuns", function(value, element, options) {
348 if (value.substring(0, 3) === "AES" && options.data('type') !== 'HEX') {
352 return !(value.substring(0, 3) === "MD5"
353 && typeof options.data('maxlength') !== 'undefined'
354 && options.data('maxlength') < 32);
357 jQuery.validator.addMethod("validationFunctionForDateTime", function(value, element, options) {
358 var dt_value = value;
359 var theType = options;
360 if (theType == "date") {
361 return isDate(dt_value);
363 } else if (theType == "time") {
364 return isTime(dt_value);
366 } else if (theType == "datetime" || theType == "timestamp") {
368 dt_value = dt_value.trim();
369 if (dt_value == "CURRENT_TIMESTAMP") {
372 if (theType == "timestamp") {
375 if (dt_value == "0000-00-00 00:00:00") {
378 var dv = dt_value.indexOf(" ");
379 if (dv == -1) { // Only the date component, which is valid
380 return isDate(dt_value, tmstmp);
383 return isDate(dt_value.substring(0, dv), tmstmp)
384 && isTime(dt_value.substring(dv + 1));
388 * message extending script must be run
389 * after initiation of functions
391 extendingValidatorMessages();
394 $.datepicker.initialized = false;
396 $(document).on('click', 'span.open_gis_editor', function (event) {
397 event.preventDefault();
401 var value = $span.parent('td').children("input[type='text']").val();
403 var field = $span.parents('tr').children('td:first').find("input[type='hidden']").val();
405 var type = $span.parents('tr').find('span.column_type').text();
406 // Names of input field and null checkbox
407 var input_name = $span.parent('td').children("input[type='text']").attr('name');
409 var token = $("input[name='token']").val();
412 if (!gisEditorLoaded) {
413 loadJSAndGISEditor(value, field, type, input_name, token);
415 loadGISEditor(value, field, type, input_name, token);
420 * Forced validation check of fields
422 $(document).on('click',"input[name^='insert_ignore_']", function (event) {
423 $("#insertForm").valid();
427 * Uncheck the null checkbox as geometry data is placed on the input field
429 $(document).on('click', "input[name='gis_data[save]']", function (event) {
430 var input_name = $('form#gis_data_editor_form').find("input[name='input_name']").val();
431 var $null_checkbox = $("input[name='" + input_name + "']").parents('tr').find('.checkbox_null');
432 $null_checkbox.prop('checked', false);
436 * Handles all current checkboxes for Null; this only takes care of the
437 * checkboxes on currently displayed rows as the rows generated by
438 * "Continue insertion" are handled in the "Continue insertion" code
441 $(document).on('click', 'input.checkbox_null', function (e) {
443 // use hidden fields populated by tbl_change.php
444 $(this).siblings('.nullify_code').val(),
445 $(this).closest('tr').find('input:hidden').first().val(),
446 $(this).siblings('.hashed_field').val(),
447 $(this).siblings('.multi_edit').val()
452 * Reset the auto_increment column to 0 when selecting any of the
453 * insert options in submit_type-dropdown. Only perform the reset
454 * when we are in edit-mode, and not in insert-mode(no previous value
457 $('select[name="submit_type"]').bind('change', function (e) {
458 var thisElemSubmitTypeVal = $(this).val();
459 var $table = $('table.insertRowTable');
460 var auto_increment_column = $table.find('input[name^="auto_increment"]');
461 auto_increment_column.each(function () {
462 var $thisElemAIField = $(this);
463 var thisElemName = $thisElemAIField.attr('name');
465 var prev_value_field = $table.find('input[name="' + thisElemName.replace('auto_increment', 'fields_prev') + '"]');
466 var value_field = $table.find('input[name="' + thisElemName.replace('auto_increment', 'fields') + '"]');
467 var previous_value = $(prev_value_field).val();
468 if (previous_value !== undefined) {
469 if (thisElemSubmitTypeVal == 'insert'
470 || thisElemSubmitTypeVal == 'insertignore'
471 || thisElemSubmitTypeVal == 'showinsert'
473 $(value_field).val(0);
475 $(value_field).val(previous_value);
483 * Continue Insertion form
485 $(document).on('change', "#insert_rows", function (event) {
486 event.preventDefault();
488 * @var columnCount Number of number of columns table has.
490 var columnCount = $("table.insertRowTable:first").find("tr").has("input[name*='fields_name']").length;
492 * @var curr_rows Number of current insert rows already on page
494 var curr_rows = $("table.insertRowTable").length;
496 * @var target_rows Number of rows the user wants
498 var target_rows = $("#insert_rows").val();
500 // remove all datepickers
501 $('input.datefield, input.datetimefield').each(function () {
502 $(this).datepicker('destroy');
505 if (curr_rows < target_rows) {
507 var tempIncrementIndex = function () {
509 var $this_element = $(this);
511 * Extract the index from the name attribute for all input/select fields and increment it
512 * name is of format funcs[multi_edit][10][<long random string of alphanum chars>]
516 * @var this_name String containing name of the input/select elements
518 var this_name = $this_element.attr('name');
519 /** split {@link this_name} at [10], so we have the parts that can be concatenated later */
520 var name_parts = this_name.split(/\[\d+\]/);
521 /** extract the [10] from {@link name_parts} */
522 var old_row_index_string = this_name.match(/\[\d+\]/)[0];
523 /** extract 10 - had to split into two steps to accomodate double digits */
524 var old_row_index = parseInt(old_row_index_string.match(/\d+/)[0], 10);
526 /** calculate next index i.e. 11 */
527 new_row_index = old_row_index + 1;
528 /** generate the new name i.e. funcs[multi_edit][11][foobarbaz] */
529 var new_name = name_parts[0] + '[' + new_row_index + ']' + name_parts[1];
531 var hashed_field = name_parts[1].match(/\[(.+)\]/)[1];
532 $this_element.attr('name', new_name);
534 /** If element is select[name*='funcs'], update id */
535 if ($this_element.is("select[name*='funcs']")) {
536 var this_id = $this_element.attr("id");
537 var id_parts = this_id.split(/\_/);
538 var old_id_index = id_parts[1];
539 var prevSelectedValue = $("#field_" + old_id_index + "_1").val();
540 var new_id_index = parseInt(old_id_index) + columnCount;
541 var new_id = 'field_' + new_id_index + '_1';
542 $this_element.attr('id', new_id);
543 $this_element.find("option").filter(function () {
544 return $(this).text() === prevSelectedValue;
545 }).attr("selected","selected");
547 // If salt field is there then update its id.
548 var nextSaltInput = $this_element.parent().next("td").next("td").find("input[name*='salt']");
549 if (nextSaltInput.length !== 0) {
550 nextSaltInput.attr("id", "salt_" + new_id);
554 // handle input text fields and textareas
555 if ($this_element.is('.textfield') || $this_element.is('.char')) {
556 // do not remove the 'value' attribute for ENUM columns
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 (e) {
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 (e) {
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 $('.control_at_footer')
683 $(this).attr('tabindex', tabindex);
685 } else if (curr_rows > target_rows) {
686 while (curr_rows > target_rows) {
687 $("input[id^=insert_ignore]:last")
688 .nextUntil("fieldset")
694 // Add all the required datepickers back
699 function changeValueFieldType(elem, searchIndex)
701 var fieldsValue = $("select#fieldID_" + searchIndex);
702 if (0 === fieldsValue.size()) {
706 var type = $(elem).val();
707 if ('IN (...)' == type ||
708 'NOT IN (...)' == type ||
710 'NOT BETWEEN' == type
712 $("#fieldID_" + searchIndex).attr('multiple', '');
714 $("#fieldID_" + searchIndex).removeAttr('multiple');