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) {
22 var rowForm = document.forms.insertForm;
24 if (typeof(rowForm.elements['funcs' + multi_edit + '[' + md5Field + ']']) !== 'undefined') {
25 rowForm.elements['funcs' + multi_edit + '[' + md5Field + ']'].selectedIndex = -1;
28 // "ENUM" field with more than 20 characters
30 rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'][1].selectedIndex = -1;
32 } else if (theType === 2) {
33 var elts = rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'];
34 // when there is just one option in ENUM:
38 var elts_cnt = elts.length;
39 for (var i = 0; i < elts_cnt; i++) {
40 elts[i].checked = false;
44 } else if (theType === 3) {
45 rowForm.elements['fields' + multi_edit + '[' + md5Field + '][]'].selectedIndex = -1;
46 // Foreign key field (drop-down)
47 } else if (theType === 4) {
48 rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].selectedIndex = -1;
49 // foreign key field (with browsing icon for foreign values)
50 } else if (theType === 6) {
51 rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = '';
53 } else /* if (theType === 5)*/ {
54 rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = '';
55 } // end if... else if... else
58 } // end of the 'nullify()' function
62 * javascript DateTime format validation.
63 * its used to prevent adding default (0000-00-00 00:00:00) to database when user enter wrong values
64 * Start of validation part
66 // function checks the number of days in febuary
67 function daysInFebruary (year) {
68 return (((year % 4 === 0) && (((year % 100 !== 0)) || (year % 400 === 0))) ? 29 : 28);
70 // function to convert single digit to double digit
71 function fractionReplace (num) {
72 num = parseInt(num, 10);
73 return num >= 1 && num <= 9 ? '0' + num : '00';
76 /* function to check the validity of date
77 * The following patterns are accepted in this validation (accepted in mysql as well)
81 * 4) And instead of using '-' the following punctuations can be used (+,.,*,^,@,/) All these are accepted by mysql as well. Therefore no issues
83 function isDate (val, tmstmp) {
84 val = val.replace(/[.|*|^|+|//|@]/g, '-');
85 var arrayVal = val.split('-');
86 for (var a = 0; a < arrayVal.length; a++) {
87 if (arrayVal[a].length === 1) {
88 arrayVal[a] = fractionReplace(arrayVal[a]);
91 val = arrayVal.join('-');
93 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)))$/);
94 if (val.length === 8) {
97 if (dtexp.test(val)) {
98 var month = parseInt(val.substring(pos + 3, pos + 5), 10);
99 var day = parseInt(val.substring(pos + 6, pos + 8), 10);
100 var year = parseInt(val.substring(0, pos + 2), 10);
101 if (month === 2 && day > daysInFebruary(year)) {
104 if (val.substring(0, pos + 2).length === 2) {
105 year = parseInt('20' + val.substring(0, pos + 2), 10);
107 if (tmstmp === true) {
111 if (year > 2038 || (year > 2037 && day > 19 && month >= 1) || (year > 2037 && month > 1)) {
121 /* function to check the validity of time
122 * The following patterns are accepted in this validation (accepted in mysql as well)
127 function isTime (val) {
128 var arrayVal = val.split(':');
129 for (var a = 0, l = arrayVal.length; a < l; a++) {
130 if (arrayVal[a].length === 1) {
131 arrayVal[a] = fractionReplace(arrayVal[a]);
134 val = arrayVal.join(':');
135 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}$/);
136 return tmexp.test(val);
140 * To check whether insert section is ignored or not
142 function checkForCheckbox (multi_edit) {
143 if ($('#insert_ignore_' + multi_edit).length) {
144 return $('#insert_ignore_' + multi_edit).is(':unchecked');
149 function verificationsAfterFieldChange (urlField, multi_edit, theType) {
150 var evt = window.event || arguments.callee.caller.arguments[0];
151 var target = evt.target || evt.srcElement;
152 var $this_input = $(':input[name^=\'fields[multi_edit][' + multi_edit + '][' +
154 // the function drop-down that corresponds to this input field
155 var $this_function = $('select[name=\'funcs[multi_edit][' + multi_edit + '][' +
157 var function_selected = false;
158 if (typeof $this_function.val() !== 'undefined' &&
159 $this_function.val() !== null &&
160 $this_function.val().length > 0
162 function_selected = true;
165 // To generate the textbox that can take the salt
166 var new_salt_box = '<br><input type=text name=salt[multi_edit][' + multi_edit + '][' + urlField + ']' +
167 ' id=salt_' + target.id + ' placeholder=\'' + PMA_messages.strEncryptionKey + '\'>';
169 // If encrypting or decrypting functions that take salt as input is selected append the new textbox for salt
170 if (target.value === 'AES_ENCRYPT' ||
171 target.value === 'AES_DECRYPT' ||
172 target.value === 'DES_ENCRYPT' ||
173 target.value === 'DES_DECRYPT' ||
174 target.value === 'ENCRYPT') {
175 if (!($('#salt_' + target.id).length)) {
176 $this_input.after(new_salt_box);
179 // Remove the textbox for salt
180 $('#salt_' + target.id).prev('br').remove();
181 $('#salt_' + target.id).remove();
184 if (target.value === 'AES_DECRYPT'
185 || target.value === 'AES_ENCRYPT'
186 || target.value === 'MD5') {
187 $('#' + target.id).rules('add', {
188 validationFunctionForFuns: {
190 depends: function () {
191 return checkForCheckbox(multi_edit);
197 // Unchecks the corresponding "NULL" control
198 $('input[name=\'fields_null[multi_edit][' + multi_edit + '][' + urlField + ']\']').prop('checked', false);
200 // Unchecks the Ignore checkbox for the current row
201 $('input[name=\'insert_ignore_' + multi_edit + '\']').prop('checked', false);
203 var charExceptionHandling;
204 if (theType.substring(0,4) === 'char') {
205 charExceptionHandling = theType.substring(5,6);
206 } else if (theType.substring(0,7) === 'varchar') {
207 charExceptionHandling = theType.substring(8,9);
209 if (function_selected) {
210 $this_input.removeAttr('min');
211 $this_input.removeAttr('max');
212 // @todo: put back attributes if corresponding function is deselected
215 if ($this_input.data('rulesadded') === null && ! function_selected) {
216 // call validate before adding rules
217 $($this_input[0].form).validate();
218 // validate for date time
219 if (theType === 'datetime' || theType === 'time' || theType === 'date' || theType === 'timestamp') {
220 $this_input.rules('add', {
221 validationFunctionForDateTime: {
223 depends: function () {
224 return checkForCheckbox(multi_edit);
229 // validation for integer type
230 if ($this_input.data('type') === 'INT') {
231 var mini = parseInt($this_input.attr('min'));
232 var maxi = parseInt($this_input.attr('max'));
233 $this_input.rules('add', {
236 depends: function () {
237 return checkForCheckbox(multi_edit);
242 depends: function () {
243 if (isNaN($this_input.val())) {
246 return checkForCheckbox(multi_edit);
252 depends: function () {
253 if (isNaN($this_input.val())) {
256 return checkForCheckbox(multi_edit);
261 // validation for CHAR types
262 } else if ($this_input.data('type') === 'CHAR') {
263 var maxlen = $this_input.data('maxlength');
264 if (typeof maxlen !== 'undefined') {
266 maxlen = charExceptionHandling;
268 $this_input.rules('add', {
271 depends: function () {
272 return checkForCheckbox(multi_edit);
277 // validate binary & blob types
278 } else if ($this_input.data('type') === 'HEX') {
279 $this_input.rules('add', {
280 validationFunctionForHex: {
282 depends: function () {
283 return checkForCheckbox(multi_edit);
288 $this_input.data('rulesadded', true);
289 } else if ($this_input.data('rulesadded') === true && function_selected) {
290 // remove any rules added
291 $this_input.rules('remove');
292 // remove any error messages
294 .removeClass('error')
295 .removeAttr('aria-invalid')
298 $this_input.data('rulesadded', null);
301 /* End of fields validation*/
304 * Unbind all event handlers before tearing down a page
306 AJAX.registerTeardown('tbl_change.js', function () {
307 $(document).off('click', 'span.open_gis_editor');
308 $(document).off('click', 'input[name^=\'insert_ignore_\']');
309 $(document).off('click', 'input[name=\'gis_data[save]\']');
310 $(document).off('click', 'input.checkbox_null');
311 $('select[name="submit_type"]').off('change');
312 $(document).off('change', '#insert_rows');
316 * Ajax handlers for Change Table page
318 * Actions Ajaxified here:
319 * Submit Data to be inserted into the table.
320 * Restart insertion with 'N' rows.
322 AJAX.registerOnload('tbl_change.js', function () {
323 if ($('#insertForm').length) {
324 // validate the comment form when it is submitted
325 $('#insertForm').validate();
326 jQuery.validator.addMethod('validationFunctionForHex', function (value, element) {
327 return value.match(/^[a-f0-9]*$/i) !== null;
330 jQuery.validator.addMethod('validationFunctionForFuns', function (value, element, options) {
331 if (value.substring(0, 3) === 'AES' && options.data('type') !== 'HEX') {
335 return !(value.substring(0, 3) === 'MD5' &&
336 typeof options.data('maxlength') !== 'undefined' &&
337 options.data('maxlength') < 32);
340 jQuery.validator.addMethod('validationFunctionForDateTime', function (value, element, options) {
341 var dt_value = value;
342 var theType = options;
343 if (theType === 'date') {
344 return isDate(dt_value);
345 } else if (theType === 'time') {
346 return isTime(dt_value);
347 } else if (theType === 'datetime' || theType === 'timestamp') {
349 dt_value = dt_value.trim();
350 if (dt_value === 'CURRENT_TIMESTAMP' || dt_value === 'current_timestamp()') {
353 if (theType === 'timestamp') {
356 if (dt_value === '0000-00-00 00:00:00') {
359 var dv = dt_value.indexOf(' ');
360 if (dv === -1) { // Only the date component, which is valid
361 return isDate(dt_value, tmstmp);
364 return isDate(dt_value.substring(0, dv), tmstmp) &&
365 isTime(dt_value.substring(dv + 1));
369 * message extending script must be run
370 * after initiation of functions
372 extendingValidatorMessages();
375 $.datepicker.initialized = false;
377 $(document).on('click', 'span.open_gis_editor', function (event) {
378 event.preventDefault();
382 var value = $span.parent('td').children('input[type=\'text\']').val();
384 var field = $span.parents('tr').children('td:first').find('input[type=\'hidden\']').val();
386 var type = $span.parents('tr').find('span.column_type').text();
387 // Names of input field and null checkbox
388 var input_name = $span.parent('td').children('input[type=\'text\']').attr('name');
391 if (!gisEditorLoaded) {
392 loadJSAndGISEditor(value, field, type, input_name);
394 loadGISEditor(value, field, type, input_name);
399 * Forced validation check of fields
401 $(document).on('click','input[name^=\'insert_ignore_\']', function (event) {
402 $('#insertForm').valid();
406 * Uncheck the null checkbox as geometry data is placed on the input field
408 $(document).on('click', 'input[name=\'gis_data[save]\']', function (event) {
409 var input_name = $('form#gis_data_editor_form').find('input[name=\'input_name\']').val();
410 var $null_checkbox = $('input[name=\'' + input_name + '\']').parents('tr').find('.checkbox_null');
411 $null_checkbox.prop('checked', false);
415 * Handles all current checkboxes for Null; this only takes care of the
416 * checkboxes on currently displayed rows as the rows generated by
417 * "Continue insertion" are handled in the "Continue insertion" code
420 $(document).on('click', 'input.checkbox_null', function () {
422 // use hidden fields populated by tbl_change.php
423 $(this).siblings('.nullify_code').val(),
424 $(this).closest('tr').find('input:hidden').first().val(),
425 $(this).siblings('.hashed_field').val(),
426 $(this).siblings('.multi_edit').val()
431 * Reset the auto_increment column to 0 when selecting any of the
432 * insert options in submit_type-dropdown. Only perform the reset
433 * when we are in edit-mode, and not in insert-mode(no previous value
436 $('select[name="submit_type"]').on('change', function () {
437 var thisElemSubmitTypeVal = $(this).val();
438 var $table = $('table.insertRowTable');
439 var auto_increment_column = $table.find('input[name^="auto_increment"]');
440 auto_increment_column.each(function () {
441 var $thisElemAIField = $(this);
442 var thisElemName = $thisElemAIField.attr('name');
444 var prev_value_field = $table.find('input[name="' + thisElemName.replace('auto_increment', 'fields_prev') + '"]');
445 var value_field = $table.find('input[name="' + thisElemName.replace('auto_increment', 'fields') + '"]');
446 var previous_value = $(prev_value_field).val();
447 if (previous_value !== undefined) {
448 if (thisElemSubmitTypeVal === 'insert'
449 || thisElemSubmitTypeVal === 'insertignore'
450 || thisElemSubmitTypeVal === 'showinsert'
452 $(value_field).val(0);
454 $(value_field).val(previous_value);
461 * Continue Insertion form
463 $(document).on('change', '#insert_rows', function (event) {
464 event.preventDefault();
466 * @var columnCount Number of number of columns table has.
468 var columnCount = $('table.insertRowTable:first').find('tr').has('input[name*=\'fields_name\']').length;
470 * @var curr_rows Number of current insert rows already on page
472 var curr_rows = $('table.insertRowTable').length;
474 * @var target_rows Number of rows the user wants
476 var target_rows = $('#insert_rows').val();
478 // remove all datepickers
479 $('input.datefield, input.datetimefield').each(function () {
480 $(this).datepicker('destroy');
483 if (curr_rows < target_rows) {
484 var tempIncrementIndex = function () {
485 var $this_element = $(this);
487 * Extract the index from the name attribute for all input/select fields and increment it
488 * name is of format funcs[multi_edit][10][<long random string of alphanum chars>]
492 * @var this_name String containing name of the input/select elements
494 var this_name = $this_element.attr('name');
495 /** split {@link this_name} at [10], so we have the parts that can be concatenated later */
496 var name_parts = this_name.split(/\[\d+\]/);
497 /** extract the [10] from {@link name_parts} */
498 var old_row_index_string = this_name.match(/\[\d+\]/)[0];
499 /** extract 10 - had to split into two steps to accomodate double digits */
500 var old_row_index = parseInt(old_row_index_string.match(/\d+/)[0], 10);
502 /** calculate next index i.e. 11 */
503 new_row_index = old_row_index + 1;
504 /** generate the new name i.e. funcs[multi_edit][11][foobarbaz] */
505 var new_name = name_parts[0] + '[' + new_row_index + ']' + name_parts[1];
507 var hashed_field = name_parts[1].match(/\[(.+)\]/)[1];
508 $this_element.attr('name', new_name);
510 /** If element is select[name*='funcs'], update id */
511 if ($this_element.is('select[name*=\'funcs\']')) {
512 var this_id = $this_element.attr('id');
513 var id_parts = this_id.split(/\_/);
514 var old_id_index = id_parts[1];
515 var prevSelectedValue = $('#field_' + old_id_index + '_1').val();
516 var new_id_index = parseInt(old_id_index) + columnCount;
517 var new_id = 'field_' + new_id_index + '_1';
518 $this_element.attr('id', new_id);
519 $this_element.find('option').filter(function () {
520 return $(this).text() === prevSelectedValue;
521 }).attr('selected','selected');
523 // If salt field is there then update its id.
524 var nextSaltInput = $this_element.parent().next('td').next('td').find('input[name*=\'salt\']');
525 if (nextSaltInput.length !== 0) {
526 nextSaltInput.attr('id', 'salt_' + new_id);
530 // handle input text fields and textareas
531 if ($this_element.is('.textfield') || $this_element.is('.char') || $this_element.is('textarea')) {
532 // do not remove the 'value' attribute for ENUM columns
533 // special handling for radio fields after updating ids to unique - see below
534 if ($this_element.closest('tr').find('span.column_type').html() !== 'enum') {
535 $this_element.val($this_element.closest('tr').find('span.default_value').html());
539 // Remove onchange attribute that was placed
540 // by tbl_change.php; it refers to the wrong row index
541 .attr('onchange', null)
542 // Keep these values to be used when the element
544 .data('hashed_field', hashed_field)
545 .data('new_row_index', new_row_index)
546 .on('change', function () {
547 var $changed_element = $(this);
548 verificationsAfterFieldChange(
549 $changed_element.data('hashed_field'),
550 $changed_element.data('new_row_index'),
551 $changed_element.closest('tr').find('span.column_type').html()
556 if ($this_element.is('.checkbox_null')) {
558 // this event was bound earlier by jQuery but
559 // to the original row, not the cloned one, so unbind()
561 // Keep these values to be used when the element
563 .data('hashed_field', hashed_field)
564 .data('new_row_index', new_row_index)
565 .on('click', function () {
566 var $changed_element = $(this);
568 $changed_element.siblings('.nullify_code').val(),
569 $this_element.closest('tr').find('input:hidden').first().val(),
570 $changed_element.data('hashed_field'),
571 '[multi_edit][' + $changed_element.data('new_row_index') + ']'
577 var tempReplaceAnchor = function () {
578 var $anchor = $(this);
579 var new_value = 'rownumber=' + new_row_index;
580 // needs improvement in case something else inside
581 // the href contains this pattern
582 var new_href = $anchor.attr('href').replace(/rownumber=\d+/, new_value);
583 $anchor.attr('href', new_href);
586 while (curr_rows < target_rows) {
588 * @var $last_row Object referring to the last row
590 var $last_row = $('#insertForm').find('.insertRowTable:last');
592 // need to access this at more than one level
593 // (also needs improvement because it should be calculated
594 // just once per cloned row, not once per column)
595 var new_row_index = 0;
597 // Clone the insert tables
600 .insertBefore('#actions_panel')
601 .find('input[name*=multi_edit],select[name*=multi_edit],textarea[name*=multi_edit]')
602 .each(tempIncrementIndex)
604 .find('.foreign_values_anchor')
605 .each(tempReplaceAnchor);
607 // Insert/Clone the ignore checkboxes
608 if (curr_rows === 1) {
609 $('<input id="insert_ignore_1" type="checkbox" name="insert_ignore_1" checked="checked" />')
610 .insertBefore('table.insertRowTable:last')
611 .after('<label for="insert_ignore_1">' + PMA_messages.strIgnore + '</label>');
614 * @var $last_checkbox Object reference to the last checkbox in #insertForm
616 var $last_checkbox = $('#insertForm').children('input:checkbox:last');
618 /** name of {@link $last_checkbox} */
619 var last_checkbox_name = $last_checkbox.attr('name');
620 /** index of {@link $last_checkbox} */
621 var last_checkbox_index = parseInt(last_checkbox_name.match(/\d+/), 10);
622 /** name of new {@link $last_checkbox} */
623 var new_name = last_checkbox_name.replace(/\d+/, last_checkbox_index + 1);
625 $('<br/><div class="clearfloat"></div>')
626 .insertBefore('table.insertRowTable:last');
630 .attr({ 'id': new_name, 'name': new_name })
631 .prop('checked', true)
632 .insertBefore('table.insertRowTable:last');
634 $('label[for^=insert_ignore]:last')
636 .attr('for', new_name)
637 .insertBefore('table.insertRowTable:last');
640 .insertBefore('table.insertRowTable:last');
644 // recompute tabindex for text fields and other controls at footer;
645 // IMO it's not really important to handle the tabindex for
648 $('.textfield, .char, textarea')
651 $(this).attr('tabindex', tabindex);
652 // update the IDs of textfields to ensure that they are unique
653 $(this).attr('id', 'field_' + tabindex + '_3');
655 // special handling for radio fields after updating ids to unique
656 if ($(this).closest('tr').find('span.column_type').html() === 'enum') {
657 if ($(this).val() === $(this).closest('tr').find('span.default_value').html()) {
658 $(this).prop('checked', true);
660 $(this).prop('checked', false);
664 $('.control_at_footer')
667 $(this).attr('tabindex', tabindex);
669 } else if (curr_rows > target_rows) {
671 * Displays alert if data loss possible on decrease
674 var checkLock = jQuery.isEmptyObject(AJAX.lockedTargets);
675 if (checkLock || confirm(PMA_messages.strConfirmRowChange) === true) {
676 while (curr_rows > target_rows) {
677 $('input[id^=insert_ignore]:last')
678 .nextUntil('fieldset')
684 document.getElementById('insert_rows').value = curr_rows;
687 // Add all the required datepickers back
692 function changeValueFieldType (elem, searchIndex) {
693 var fieldsValue = $('select#fieldID_' + searchIndex);
694 if (0 === fieldsValue.size()) {
698 var type = $(elem).val();
699 if ('IN (...)' === type ||
700 'NOT IN (...)' === type ||
701 'BETWEEN' === type ||
702 'NOT BETWEEN' === type
704 $('#fieldID_' + searchIndex).attr('multiple', '');
706 $('#fieldID_' + searchIndex).removeAttr('multiple');