Merge pull request #431 from xmujay/0609_monitor
[phpmyadmin/aamir.git] / js / tbl_change.js
blobef73dacd38e61395359c076c39667c3fb5bd5fa4
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
2 /**
3  * @fileoverview    function used in table data manipulation pages
4  *
5  * @requires    jQuery
6  * @requires    jQueryUI
7  * @requires    js/functions.js
8  *
9  */
11 /**
12  * Modify form controls when the "NULL" checkbox is checked
13  *
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
18  *
19  * @return boolean  always true
20  */
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;
27     }
29     // "ENUM" field with more than 20 characters
30     if (theType == 1) {
31         rowForm.elements['fields' + multi_edit + '[' + md5Field +  ']'][1].selectedIndex = -1;
32     }
33     // Other "ENUM" field
34     else if (theType == 2) {
35         var elts     = rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'];
36         // when there is just one option in ENUM:
37         if (elts.checked) {
38             elts.checked = false;
39         } else {
40             var elts_cnt = elts.length;
41             for (var i = 0; i < elts_cnt; i++) {
42                 elts[i].checked = false;
43             } // end for
45         } // end if
46     }
47     // "SET" field
48     else if (theType == 3) {
49         rowForm.elements['fields' + multi_edit + '[' + md5Field +  '][]'].selectedIndex = -1;
50     }
51     // Foreign key field (drop-down)
52     else if (theType == 4) {
53         rowForm.elements['fields' + multi_edit + '[' + md5Field +  ']'].selectedIndex = -1;
54     }
55     // foreign key field (with browsing icon for foreign values)
56     else if (theType == 6) {
57         rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = '';
58     }
59     // Other field types
60     else /*if (theType == 5)*/ {
61         rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = '';
62     } // end if... else if... else
64     return true;
65 } // end of the 'nullify()' function
68 /**
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
72  */
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)
87 * 1) 2001-12-23
88 * 2) 2001-1-2
89 * 3) 02-12-23
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]);
99         }
100     }
101     val = arrayVal.join("-");
102     var pos = 2;
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) {
105         pos = 0;
106     }
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)) {
112             return false;
113         }
114         if (val.substring(0, pos + 2).length == 2) {
115             year = parseInt("20" + val.substring(0, pos + 2), 10);
116         }
117         if (tmstmp === true) {
118             if (year < 1978) {
119                 return false;
120             }
121             if (year > 2038 || (year > 2037 && day > 19 && month >= 1) || (year > 2037 && month > 1)) {
122                 return false;
123             }
124         }
125     } else {
126         return false;
127     }
128     return true;
131 /* function to check the validity of time
132 * The following patterns are accepted in this validation (accepted in mysql as well)
133 * 1) 2:3:4
134 * 2) 2:23:43
136 function isTime(val)
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]);
142         }
143     }
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);
161     } else {
162         //The value of the select is no longer AES_ENCRYPT, remove the textbox for salt
163         $("#salt_"+target.id).remove();
164     }
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");
178         return true;
179     }
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");
189                     return false;
190                 }
191             } else if (theType == "time") {
192                 if (! isTime(dt_value)) {
193                     $this_input.addClass("invalid_value");
194                     return false;
195                 }
196             } else if (theType == "datetime" || theType == "timestamp") {
197                 var tmstmp = false;
198                 if (dt_value == "CURRENT_TIMESTAMP") {
199                     return true;
200                 }
201                 if (theType == "timestamp") {
202                     tmstmp = true;
203                 }
204                 if (dt_value == "0000-00-00 00:00:00") {
205                     return true;
206                 }
207                 var dv = dt_value.indexOf(" ");
208                 if (dv == -1) {
209                     $this_input.addClass("invalid_value");
210                     return false;
211                 } else {
212                     if (! (isDate(dt_value.substring(0, dv), tmstmp) && isTime(dt_value.substring(dv + 1)))) {
213                         $this_input.addClass("invalid_value");
214                         return false;
215                     }
216                 }
217             }
218         }
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");
224                 return false;
225             }
226         }
227     }
229  /* End of datetime validation*/
233  * Unbind all event handlers before tearing down a page
234  */
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.
249  */
250 AJAX.registerOnload('tbl_change.js', function () {
251     $.datepicker.initialized = false;
253     $('span.open_gis_editor').live('click', function (event) {
254         event.preventDefault();
256         var $span = $(this);
257         // Current value
258         var value = $span.parent('td').children("input[type='text']").val();
259         // Field name
260         var field = $span.parents('tr').children('td:first').find("input[type='hidden']").val();
261         // Column type
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');
265         //Token
266         var token = $("input[name='token']").val();
268         openGISEditor();
269         if (!gisEditorLoaded) {
270             loadJSAndGISEditor(value, field, type, input_name, token);
271         } else {
272             loadGISEditor(value, field, type, input_name, token);
273         }
274     });
276     /**
277      * Uncheck the null checkbox as geometry data is placed on the input field
278      */
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);
283     });
285     /**
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
289      *
290      */
291     $('input.checkbox_null').bind('click', function (e) {
292         nullify(
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()
298         );
299     });
302     /**
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
306      * available).
307      */
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);
318                 } else {
319                     $(value_field).val(previous_value);
320                 }
321             }
322         }
323     });
325     /**
326      * Continue Insertion form
327      */
328     $("#insert_rows").live('change', function (event) {
329         event.preventDefault();
331         /**
332          * @var curr_rows   Number of current insert rows already on page
333          */
334         var curr_rows = $("table.insertRowTable").length;
335         /**
336          * @var target_rows Number of rows the user wants
337          */
338         var target_rows = $("#insert_rows").val();
340         // remove all datepickers
341         $('input.datefield, input.datetimefield').each(function () {
342             $(this).datepicker('destroy');
343         });
345         if (curr_rows < target_rows) {
346             while (curr_rows < target_rows) {
348                 /**
349                  * @var $last_row    Object referring to the last row
350                  */
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
359                 $last_row
360                 .clone()
361                 .insertBefore("#actions_panel")
362                 .find('input[name*=multi_edit],select[name*=multi_edit],textarea[name*=multi_edit]')
363                 .each(function () {
365                     var $this_element = $(this);
366                     /**
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>]
369                      */
371                     /**
372                      * @var this_name   String containing name of the input/select elements
373                      */
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());
394                         }
395                         $this_element
396                         .unbind('change')
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
401                         // will change
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()
410                             );
411                         });
412                     }
414                     if ($this_element.is('.checkbox_null')) {
415                         $this_element
416                         // this event was bound earlier by jQuery but
417                         // to the original row, not the cloned one, so unbind()
418                         .unbind('click')
419                         // Keep these values to be used when the element
420                         // will be clicked
421                         .data('hashed_field', hashed_field)
422                         .data('new_row_index', new_row_index)
423                         .bind('click', function (e) {
424                             var $changed_element = $(this);
425                             nullify(
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') + ']'
430                             );
431                         });
432                     }
433                 }) // end each
434                 .end()
435                 .find('.foreign_values_anchor')
436                 .each(function () {
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);
443                     });
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>');
450                 } else {
452                     /**
453                      * @var $last_checkbox   Object reference to the last checkbox in #insertForm
454                      */
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);
464                     $last_checkbox
465                     .clone()
466                     .attr({'id': new_name, 'name': new_name})
467                     .prop('checked', true)
468                     .add('label[for^=insert_ignore]:last')
469                     .clone()
470                     .attr('for', new_name)
471                     .before('<br />')
472                     .insertBefore("table.insertRowTable:last");
473                 }
474                 curr_rows++;
475             }
476             // recompute tabindex for text fields and other controls at footer;
477             // IMO it's not really important to handle the tabindex for
478             // function and Null
479             var tabindex = 0;
480             $('.textfield')
481             .each(function () {
482                 tabindex++;
483                 $(this).attr('tabindex', tabindex);
484                 // update the IDs of textfields to ensure that they are unique
485                 $(this).attr('id', "field_" + tabindex + "_3");
486             });
487             $('select.control_at_footer')
488             .each(function () {
489                 tabindex++;
490                 $(this).attr('tabindex', tabindex);
491             });
492             // Add all the required datepickers back
493             $('input.datefield, input.datetimefield').each(function () {
494                 PMA_addDatepicker($(this));
495             });
496         } else if (curr_rows > target_rows) {
497             while (curr_rows > target_rows) {
498                 $("input[id^=insert_ignore]:last")
499                 .nextUntil("fieldset")
500                 .andSelf()
501                 .remove();
502                 curr_rows--;
503             }
504         }
505     });