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)))$/);
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)
138 var arrayVal = val.split(":");
139 for (var a = 0, l = arrayVal.length; a < l; a++) {
140 if (arrayVal[a].length == 1) {
141 arrayVal[a] = fractionReplace(arrayVal[a]);
144 val = arrayVal.join(":");
145 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]))$/);
146 return tmexp.test(val);
149 function verificationsAfterFieldChange(urlField, multi_edit, theType)
151 var evt = window.event || arguments.callee.caller.arguments[0];
152 var target = evt.target || evt.srcElement;
154 //To generate the textbox that can take the salt
155 var new_salt_box = "<br><input type=text name=salt[multi_edit][" + multi_edit + "][" + urlField + "]"
156 +" id=salt_"+target.id+" placeholder='enter Salt'>";
158 //If AES_ENCRYPT is Selected then append the new textbox for salt
159 if (target.value == "AES_ENCRYPT" && !($("#salt_"+target.id).length)) {
160 $("input[name='fields[multi_edit][" + multi_edit + "][" + urlField + "]']").after(new_salt_box);
162 //The value of the select is no longer AES_ENCRYPT, remove the textbox for salt
163 $("#salt_"+target.id).remove();
166 // Unchecks the corresponding "NULL" control
167 $("input[name='fields_null[multi_edit][" + multi_edit + "][" + urlField + "]']").prop('checked', false);
169 // Unchecks the Ignore checkbox for the current row
170 $("input[name='insert_ignore_" + multi_edit + "']").prop('checked', false);
171 var $this_input = $("input[name='fields[multi_edit][" + multi_edit + "][" + urlField + "]']");
173 // Does this field come from datepicker?
174 if ($this_input.data('comes_from') == 'datepicker') {
175 // Yes, so do not validate because the final value is not yet in
176 // the field and hopefully the datepicker returns a valid date+time
177 $this_input.removeClass("invalid_value");
181 if (target.name.substring(0, 6) == "fields") {
182 // validate for date time
183 if (theType == "datetime" || theType == "time" || theType == "date" || theType == "timestamp") {
184 $this_input.removeClass("invalid_value");
185 var dt_value = $this_input.val();
186 if (theType == "date") {
187 if (! isDate(dt_value)) {
188 $this_input.addClass("invalid_value");
191 } else if (theType == "time") {
192 if (! isTime(dt_value)) {
193 $this_input.addClass("invalid_value");
196 } else if (theType == "datetime" || theType == "timestamp") {
198 if (dt_value == "CURRENT_TIMESTAMP") {
201 if (theType == "timestamp") {
204 if (dt_value == "0000-00-00 00:00:00") {
207 var dv = dt_value.indexOf(" ");
209 $this_input.addClass("invalid_value");
212 if (! (isDate(dt_value.substring(0, dv), tmstmp) && isTime(dt_value.substring(dv + 1)))) {
213 $this_input.addClass("invalid_value");
219 //validate for integer type
220 if (theType.substring(0, 3) == "int") {
221 $this_input.removeClass("invalid_value");
222 if (isNaN($this_input.val())) {
223 $this_input.addClass("invalid_value");
229 /* End of datetime validation*/
233 * Unbind all event handlers before tearing down a page
235 AJAX.registerTeardown('tbl_change.js', function () {
236 $('span.open_gis_editor').die('click');
237 $("input[name='gis_data[save]']").die('click');
238 $('input.checkbox_null').unbind('click');
239 $('select[name="submit_type"]').unbind('change');
240 $("#insert_rows").die('change');
244 * Ajax handlers for Change Table page
246 * Actions Ajaxified here:
247 * Submit Data to be inserted into the table.
248 * Restart insertion with 'N' rows.
250 AJAX.registerOnload('tbl_change.js', function () {
251 $.datepicker.initialized = false;
253 $('span.open_gis_editor').live('click', function (event) {
254 event.preventDefault();
258 var value = $span.parent('td').children("input[type='text']").val();
260 var field = $span.parents('tr').children('td:first').find("input[type='hidden']").val();
262 var type = $span.parents('tr').find('span.column_type').text();
263 // Names of input field and null checkbox
264 var input_name = $span.parent('td').children("input[type='text']").attr('name');
266 var token = $("input[name='token']").val();
269 if (!gisEditorLoaded) {
270 loadJSAndGISEditor(value, field, type, input_name, token);
272 loadGISEditor(value, field, type, input_name, token);
277 * Uncheck the null checkbox as geometry data is placed on the input field
279 $("input[name='gis_data[save]']").live('click', function (event) {
280 var input_name = $('form#gis_data_editor_form').find("input[name='input_name']").val();
281 var $null_checkbox = $("input[name='" + input_name + "']").parents('tr').find('.checkbox_null');
282 $null_checkbox.prop('checked', false);
286 * Handles all current checkboxes for Null; this only takes care of the
287 * checkboxes on currently displayed rows as the rows generated by
288 * "Continue insertion" are handled in the "Continue insertion" code
291 $('input.checkbox_null').bind('click', function (e) {
293 // use hidden fields populated by tbl_change.php
294 $(this).siblings('.nullify_code').val(),
295 $(this).closest('tr').find('input:hidden').first().val(),
296 $(this).siblings('.hashed_field').val(),
297 $(this).siblings('.multi_edit').val()
303 * Reset the auto_increment column to 0 when selecting any of the
304 * insert options in submit_type-dropdown. Only perform the reset
305 * when we are in edit-mode, and not in insert-mode(no previous value
308 $('select[name="submit_type"]').bind('change', function (e) {
309 var $table = $('table.insertRowTable');
310 var auto_increment_column = $table.find('input[name^="auto_increment"]').attr('name');
311 if (auto_increment_column) {
312 var prev_value_field = $table.find('input[name="' + auto_increment_column.replace('auto_increment', 'fields_prev') + '"]');
313 var value_field = $table.find('input[name="' + auto_increment_column.replace('auto_increment', 'fields') + '"]');
314 var previous_value = $(prev_value_field).val();
315 if (previous_value !== undefined) {
316 if ($(this).val() == 'insert' || $(this).val() == 'insertignore' || $(this).val() == 'showinsert') {
317 $(value_field).val(0);
319 $(value_field).val(previous_value);
326 * Continue Insertion form
328 $("#insert_rows").live('change', function (event) {
329 event.preventDefault();
332 * @var curr_rows Number of current insert rows already on page
334 var curr_rows = $("table.insertRowTable").length;
336 * @var target_rows Number of rows the user wants
338 var target_rows = $("#insert_rows").val();
340 // remove all datepickers
341 $('input.datefield, input.datetimefield').each(function () {
342 $(this).datepicker('destroy');
345 if (curr_rows < target_rows) {
346 while (curr_rows < target_rows) {
349 * @var $last_row Object referring to the last row
351 var $last_row = $("#insertForm").find(".insertRowTable:last");
353 // need to access this at more than one level
354 // (also needs improvement because it should be calculated
355 // just once per cloned row, not once per column)
356 var new_row_index = 0;
358 //Clone the insert tables
361 .insertBefore("#actions_panel")
362 .find('input[name*=multi_edit],select[name*=multi_edit],textarea[name*=multi_edit]')
365 var $this_element = $(this);
367 * Extract the index from the name attribute for all input/select fields and increment it
368 * name is of format funcs[multi_edit][10][<long random string of alphanum chars>]
372 * @var this_name String containing name of the input/select elements
374 var this_name = $this_element.attr('name');
375 /** split {@link this_name} at [10], so we have the parts that can be concatenated later */
376 var name_parts = this_name.split(/\[\d+\]/);
377 /** extract the [10] from {@link name_parts} */
378 var old_row_index_string = this_name.match(/\[\d+\]/)[0];
379 /** extract 10 - had to split into two steps to accomodate double digits */
380 var old_row_index = parseInt(old_row_index_string.match(/\d+/)[0], 10);
382 /** calculate next index i.e. 11 */
383 new_row_index = old_row_index + 1;
384 /** generate the new name i.e. funcs[multi_edit][11][foobarbaz] */
385 var new_name = name_parts[0] + '[' + new_row_index + ']' + name_parts[1];
387 var hashed_field = name_parts[1].match(/\[(.+)\]/)[1];
388 $this_element.attr('name', new_name);
390 if ($this_element.is('.textfield')) {
391 // do not remove the 'value' attribute for ENUM columns
392 if ($this_element.closest('tr').find('span.column_type').html() != 'enum') {
393 $this_element.val($this_element.closest('tr').find('span.default_value').html());
397 // Remove onchange attribute that was placed
398 // by tbl_change.php; it refers to the wrong row index
399 .attr('onchange', null)
400 // Keep these values to be used when the element
402 .data('hashed_field', hashed_field)
403 .data('new_row_index', new_row_index)
404 .bind('change', function (e) {
405 var $changed_element = $(this);
406 verificationsAfterFieldChange(
407 $changed_element.data('hashed_field'),
408 $changed_element.data('new_row_index'),
409 $changed_element.closest('tr').find('span.column_type').html()
414 if ($this_element.is('.checkbox_null')) {
416 // this event was bound earlier by jQuery but
417 // to the original row, not the cloned one, so unbind()
419 // Keep these values to be used when the element
421 .data('hashed_field', hashed_field)
422 .data('new_row_index', new_row_index)
423 .bind('click', function (e) {
424 var $changed_element = $(this);
426 $changed_element.siblings('.nullify_code').val(),
427 $this_element.closest('tr').find('input:hidden').first().val(),
428 $changed_element.data('hashed_field'),
429 '[multi_edit][' + $changed_element.data('new_row_index') + ']'
435 .find('.foreign_values_anchor')
437 var $anchor = $(this);
438 var new_value = 'rownumber=' + new_row_index;
439 // needs improvement in case something else inside
440 // the href contains this pattern
441 var new_href = $anchor.attr('href').replace(/rownumber=\d+/, new_value);
442 $anchor.attr('href', new_href);
445 //Insert/Clone the ignore checkboxes
446 if (curr_rows == 1) {
447 $('<input id="insert_ignore_1" type="checkbox" name="insert_ignore_1" checked="checked" />')
448 .insertBefore("table.insertRowTable:last")
449 .after('<label for="insert_ignore_1">' + PMA_messages.strIgnore + '</label>');
453 * @var $last_checkbox Object reference to the last checkbox in #insertForm
455 var $last_checkbox = $("#insertForm").children('input:checkbox:last');
457 /** name of {@link $last_checkbox} */
458 var last_checkbox_name = $last_checkbox.attr('name');
459 /** index of {@link $last_checkbox} */
460 var last_checkbox_index = parseInt(last_checkbox_name.match(/\d+/), 10);
461 /** name of new {@link $last_checkbox} */
462 var new_name = last_checkbox_name.replace(/\d+/, last_checkbox_index + 1);
466 .attr({'id': new_name, 'name': new_name})
467 .prop('checked', true)
468 .add('label[for^=insert_ignore]:last')
470 .attr('for', new_name)
472 .insertBefore("table.insertRowTable:last");
476 // recompute tabindex for text fields and other controls at footer;
477 // IMO it's not really important to handle the tabindex for
483 $(this).attr('tabindex', tabindex);
484 // update the IDs of textfields to ensure that they are unique
485 $(this).attr('id', "field_" + tabindex + "_3");
487 $('select.control_at_footer')
490 $(this).attr('tabindex', tabindex);
492 // Add all the required datepickers back
493 $('input.datefield, input.datetimefield').each(function () {
494 PMA_addDatepicker($(this));
496 } else if (curr_rows > target_rows) {
497 while (curr_rows > target_rows) {
498 $("input[id^=insert_ignore]:last")
499 .nextUntil("fieldset")