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 //To generate the textbox that can take the salt
176 var new_salt_box = "<br><input type=text name=salt[multi_edit][" + multi_edit + "][" + urlField + "]" +
177 " id=salt_" + target.id + " placeholder='" + PMA_messages.strEncryptionKey + "'>";
179 //If encrypting or decrypting functions that take salt as input is selected append the new textbox for salt
180 if (target.value === 'AES_ENCRYPT' ||
181 target.value === 'AES_DECRYPT' ||
182 target.value === 'DES_ENCRYPT' ||
183 target.value === 'DES_DECRYPT' ||
184 target.value === 'ENCRYPT') {
185 if (!($("#salt_" + target.id).length)) {
186 $this_input.after(new_salt_box);
189 //Remove the textbox for salt
190 $('#salt_' + target.id).prev('br').remove();
191 $("#salt_" + target.id).remove();
194 if (target.value === 'AES_DECRYPT'
195 || target.value === 'AES_ENCRYPT'
196 || target.value === 'MD5') {
197 $('#' + target.id).rules("add", {
198 validationFunctionForFuns: {
200 depends: function() {
201 return checkForCheckbox(multi_edit);
207 // Unchecks the corresponding "NULL" control
208 $("input[name='fields_null[multi_edit][" + multi_edit + "][" + urlField + "]']").prop('checked', false);
210 // Unchecks the Ignore checkbox for the current row
211 $("input[name='insert_ignore_" + multi_edit + "']").prop('checked', false);
213 var charExceptionHandling;
214 if (theType.substring(0,4) === "char") {
215 charExceptionHandling = theType.substring(5,6);
217 else if (theType.substring(0,7) === "varchar") {
218 charExceptionHandling = theType.substring(8,9);
220 if (function_selected) {
221 $this_input.removeAttr('min');
222 $this_input.removeAttr('max');
223 // @todo: put back attributes if corresponding function is deselected
226 if ($this_input.data('rulesadded') == null && ! function_selected) {
228 //call validate before adding rules
229 $($this_input[0].form).validate();
230 // validate for date time
231 if (theType == "datetime" || theType == "time" || theType == "date" || theType == "timestamp") {
232 $this_input.rules("add", {
233 validationFunctionForDateTime: {
235 depends: function() {
236 return checkForCheckbox(multi_edit);
241 //validation for integer type
242 if ($this_input.data('type') === 'INT') {
243 var mini = parseInt($this_input.attr('min'));
244 var maxi = parseInt($this_input.attr('max'));
245 $this_input.rules("add", {
248 depends: function() {
249 return checkForCheckbox(multi_edit);
254 depends: function() {
255 if (isNaN($this_input.val())) {
258 return checkForCheckbox(multi_edit);
264 depends: function() {
265 if (isNaN($this_input.val())) {
268 return checkForCheckbox(multi_edit);
273 //validation for CHAR types
274 } else if ($this_input.data('type') === 'CHAR') {
275 var maxlen = $this_input.data('maxlength');
276 if (typeof maxlen !== 'undefined') {
278 maxlen=charExceptionHandling;
280 $this_input.rules("add", {
283 depends: function() {
284 return checkForCheckbox(multi_edit);
289 // validate binary & blob types
290 } else if ($this_input.data('type') === 'HEX') {
291 $this_input.rules("add", {
292 validationFunctionForHex: {
294 depends: function() {
295 return checkForCheckbox(multi_edit);
300 $this_input.data('rulesadded', true);
301 } else if ($this_input.data('rulesadded') == true && function_selected) {
302 // remove any rules added
303 $this_input.rules("remove");
304 // remove any error messages
306 .removeClass('error')
307 .removeAttr('aria-invalid')
310 $this_input.data('rulesadded', null);
313 /* End of fields validation*/
316 * Unbind all event handlers before tearing down a page
318 AJAX.registerTeardown('tbl_change.js', function () {
319 $(document).off('click', 'span.open_gis_editor');
320 $(document).off('click', "input[name^='insert_ignore_']");
321 $(document).off('click', "input[name='gis_data[save]']");
322 $(document).off('click', 'input.checkbox_null');
323 $('select[name="submit_type"]').unbind('change');
324 $(document).off('change', "#insert_rows");
328 * Ajax handlers for Change Table page
330 * Actions Ajaxified here:
331 * Submit Data to be inserted into the table.
332 * Restart insertion with 'N' rows.
334 AJAX.registerOnload('tbl_change.js', function () {
336 if($("#insertForm").length) {
337 // validate the comment form when it is submitted
338 $("#insertForm").validate();
339 jQuery.validator.addMethod("validationFunctionForHex", function(value, element) {
340 return value.match(/^[a-f0-9]*$/i) !== null;
343 jQuery.validator.addMethod("validationFunctionForFuns", function(value, element, options) {
344 if (value.substring(0, 3) === "AES" && options.data('type') !== 'HEX') {
348 return !(value.substring(0, 3) === "MD5"
349 && typeof options.data('maxlength') !== 'undefined'
350 && options.data('maxlength') < 32);
353 jQuery.validator.addMethod("validationFunctionForDateTime", function(value, element, options) {
354 var dt_value = value;
355 var theType = options;
356 if (theType == "date") {
357 return isDate(dt_value);
359 } else if (theType == "time") {
360 return isTime(dt_value);
362 } else if (theType == "datetime" || theType == "timestamp") {
364 dt_value = dt_value.trim();
365 if (dt_value == "CURRENT_TIMESTAMP") {
368 if (theType == "timestamp") {
371 if (dt_value == "0000-00-00 00:00:00") {
374 var dv = dt_value.indexOf(" ");
375 if (dv == -1) { // Only the date component, which is valid
376 return isDate(dt_value, tmstmp);
379 return isDate(dt_value.substring(0, dv), tmstmp)
380 && isTime(dt_value.substring(dv + 1));
384 * message extending script must be run
385 * after initiation of functions
387 extendingValidatorMessages();
390 $.datepicker.initialized = false;
392 $(document).on('click', 'span.open_gis_editor', function (event) {
393 event.preventDefault();
397 var value = $span.parent('td').children("input[type='text']").val();
399 var field = $span.parents('tr').children('td:first').find("input[type='hidden']").val();
401 var type = $span.parents('tr').find('span.column_type').text();
402 // Names of input field and null checkbox
403 var input_name = $span.parent('td').children("input[type='text']").attr('name');
405 var token = $("input[name='token']").val();
408 if (!gisEditorLoaded) {
409 loadJSAndGISEditor(value, field, type, input_name, token);
411 loadGISEditor(value, field, type, input_name, token);
416 * Forced validation check of fields
418 $(document).on('click',"input[name^='insert_ignore_']", function (event) {
419 $("#insertForm").valid();
423 * Uncheck the null checkbox as geometry data is placed on the input field
425 $(document).on('click', "input[name='gis_data[save]']", function (event) {
426 var input_name = $('form#gis_data_editor_form').find("input[name='input_name']").val();
427 var $null_checkbox = $("input[name='" + input_name + "']").parents('tr').find('.checkbox_null');
428 $null_checkbox.prop('checked', false);
432 * Handles all current checkboxes for Null; this only takes care of the
433 * checkboxes on currently displayed rows as the rows generated by
434 * "Continue insertion" are handled in the "Continue insertion" code
437 $(document).on('click', 'input.checkbox_null', function (e) {
439 // use hidden fields populated by tbl_change.php
440 $(this).siblings('.nullify_code').val(),
441 $(this).closest('tr').find('input:hidden').first().val(),
442 $(this).siblings('.hashed_field').val(),
443 $(this).siblings('.multi_edit').val()
448 * Reset the auto_increment column to 0 when selecting any of the
449 * insert options in submit_type-dropdown. Only perform the reset
450 * when we are in edit-mode, and not in insert-mode(no previous value
453 $('select[name="submit_type"]').bind('change', function (e) {
454 var thisElemSubmitTypeVal = $(this).val();
455 var $table = $('table.insertRowTable');
456 var auto_increment_column = $table.find('input[name^="auto_increment"]');
457 auto_increment_column.each(function () {
458 var $thisElemAIField = $(this);
459 var thisElemName = $thisElemAIField.attr('name');
461 var prev_value_field = $table.find('input[name="' + thisElemName.replace('auto_increment', 'fields_prev') + '"]');
462 var value_field = $table.find('input[name="' + thisElemName.replace('auto_increment', 'fields') + '"]');
463 var previous_value = $(prev_value_field).val();
464 if (previous_value !== undefined) {
465 if (thisElemSubmitTypeVal == 'insert'
466 || thisElemSubmitTypeVal == 'insertignore'
467 || thisElemSubmitTypeVal == 'showinsert'
469 $(value_field).val(0);
471 $(value_field).val(previous_value);
479 * Continue Insertion form
481 $(document).on('change', "#insert_rows", function (event) {
482 event.preventDefault();
484 * @var columnCount Number of number of columns table has.
486 var columnCount = $("table.insertRowTable:first").find("tr").has("input[name*='fields_name']").length;
488 * @var curr_rows Number of current insert rows already on page
490 var curr_rows = $("table.insertRowTable").length;
492 * @var target_rows Number of rows the user wants
494 var target_rows = $("#insert_rows").val();
496 // remove all datepickers
497 $('input.datefield, input.datetimefield').each(function () {
498 $(this).datepicker('destroy');
501 if (curr_rows < target_rows) {
503 var tempIncrementIndex = function () {
505 var $this_element = $(this);
507 * Extract the index from the name attribute for all input/select fields and increment it
508 * name is of format funcs[multi_edit][10][<long random string of alphanum chars>]
512 * @var this_name String containing name of the input/select elements
514 var this_name = $this_element.attr('name');
515 /** split {@link this_name} at [10], so we have the parts that can be concatenated later */
516 var name_parts = this_name.split(/\[\d+\]/);
517 /** extract the [10] from {@link name_parts} */
518 var old_row_index_string = this_name.match(/\[\d+\]/)[0];
519 /** extract 10 - had to split into two steps to accomodate double digits */
520 var old_row_index = parseInt(old_row_index_string.match(/\d+/)[0], 10);
522 /** calculate next index i.e. 11 */
523 new_row_index = old_row_index + 1;
524 /** generate the new name i.e. funcs[multi_edit][11][foobarbaz] */
525 var new_name = name_parts[0] + '[' + new_row_index + ']' + name_parts[1];
527 var hashed_field = name_parts[1].match(/\[(.+)\]/)[1];
528 $this_element.attr('name', new_name);
530 /** If element is select[name*='funcs'], update id */
531 if ($this_element.is("select[name*='funcs']")) {
532 var this_id = $this_element.attr("id");
533 var id_parts = this_id.split(/\_/);
534 var old_id_index = id_parts[1];
535 var prevSelectedValue = $("#field_" + old_id_index + "_1").val();
536 var new_id_index = parseInt(old_id_index) + columnCount;
537 var new_id = 'field_' + new_id_index + '_1';
538 $this_element.attr('id', new_id);
539 $this_element.find("option").filter(function () {
540 return $(this).text() === prevSelectedValue;
541 }).attr("selected","selected");
543 // If salt field is there then update its id.
544 var nextSaltInput = $this_element.parent().next("td").next("td").find("input[name*='salt']");
545 if (nextSaltInput.length !== 0) {
546 nextSaltInput.attr("id", "salt_" + new_id);
550 // handle input text fields and textareas
551 if ($this_element.is('.textfield') || $this_element.is('.char')) {
552 // do not remove the 'value' attribute for ENUM columns
553 if ($this_element.closest('tr').find('span.column_type').html() != 'enum') {
554 $this_element.val($this_element.closest('tr').find('span.default_value').html());
558 // Remove onchange attribute that was placed
559 // by tbl_change.php; it refers to the wrong row index
560 .attr('onchange', null)
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 .bind('change', function (e) {
566 var $changed_element = $(this);
567 verificationsAfterFieldChange(
568 $changed_element.data('hashed_field'),
569 $changed_element.data('new_row_index'),
570 $changed_element.closest('tr').find('span.column_type').html()
575 if ($this_element.is('.checkbox_null')) {
577 // this event was bound earlier by jQuery but
578 // to the original row, not the cloned one, so unbind()
580 // Keep these values to be used when the element
582 .data('hashed_field', hashed_field)
583 .data('new_row_index', new_row_index)
584 .bind('click', function (e) {
585 var $changed_element = $(this);
587 $changed_element.siblings('.nullify_code').val(),
588 $this_element.closest('tr').find('input:hidden').first().val(),
589 $changed_element.data('hashed_field'),
590 '[multi_edit][' + $changed_element.data('new_row_index') + ']'
596 var tempReplaceAnchor = function () {
597 var $anchor = $(this);
598 var new_value = 'rownumber=' + new_row_index;
599 // needs improvement in case something else inside
600 // the href contains this pattern
601 var new_href = $anchor.attr('href').replace(/rownumber=\d+/, new_value);
602 $anchor.attr('href', new_href);
605 while (curr_rows < target_rows) {
608 * @var $last_row Object referring to the last row
610 var $last_row = $("#insertForm").find(".insertRowTable:last");
612 // need to access this at more than one level
613 // (also needs improvement because it should be calculated
614 // just once per cloned row, not once per column)
615 var new_row_index = 0;
617 //Clone the insert tables
620 .insertBefore("#actions_panel")
621 .find('input[name*=multi_edit],select[name*=multi_edit],textarea[name*=multi_edit]')
622 .each(tempIncrementIndex)
624 .find('.foreign_values_anchor')
625 .each(tempReplaceAnchor);
627 //Insert/Clone the ignore checkboxes
628 if (curr_rows == 1) {
629 $('<input id="insert_ignore_1" type="checkbox" name="insert_ignore_1" checked="checked" />')
630 .insertBefore("table.insertRowTable:last")
631 .after('<label for="insert_ignore_1">' + PMA_messages.strIgnore + '</label>');
635 * @var $last_checkbox Object reference to the last checkbox in #insertForm
637 var $last_checkbox = $("#insertForm").children('input:checkbox:last');
639 /** name of {@link $last_checkbox} */
640 var last_checkbox_name = $last_checkbox.attr('name');
641 /** index of {@link $last_checkbox} */
642 var last_checkbox_index = parseInt(last_checkbox_name.match(/\d+/), 10);
643 /** name of new {@link $last_checkbox} */
644 var new_name = last_checkbox_name.replace(/\d+/, last_checkbox_index + 1);
646 $('<br/><div class="clearfloat"></div>')
647 .insertBefore("table.insertRowTable:last");
651 .attr({'id': new_name, 'name': new_name})
652 .prop('checked', true)
653 .insertBefore("table.insertRowTable:last");
655 $('label[for^=insert_ignore]:last')
657 .attr('for', new_name)
658 .insertBefore("table.insertRowTable:last");
661 .insertBefore("table.insertRowTable:last");
665 // recompute tabindex for text fields and other controls at footer;
666 // IMO it's not really important to handle the tabindex for
669 $('.textfield, .char, textarea')
672 $(this).attr('tabindex', tabindex);
673 // update the IDs of textfields to ensure that they are unique
674 $(this).attr('id', "field_" + tabindex + "_3");
676 $('.control_at_footer')
679 $(this).attr('tabindex', tabindex);
681 } else if (curr_rows > target_rows) {
682 while (curr_rows > target_rows) {
683 $("input[id^=insert_ignore]:last")
684 .nextUntil("fieldset")
690 // Add all the required datepickers back
695 function changeValueFieldType(elem, searchIndex)
697 var fieldsValue = $("select#fieldID_" + searchIndex);
698 if (0 === fieldsValue.size()) {
702 var type = $(elem).val();
703 if ('IN (...)' == type ||
704 'NOT IN (...)' == type ||
706 'NOT BETWEEN' == type
708 $("#fieldID_" + searchIndex).attr('multiple', '');
710 $("#fieldID_" + searchIndex).removeAttr('multiple');