Merge branch 'QA_3_4'
[phpmyadmin.git] / js / tbl_change.js
blob099dab99b745da8802f49d3305b7a787e87141b6
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     // "SET" field , "ENUM" field with more than 20 characters
30     // or foreign key field (drop-down)
31     if (theType == 1 || theType == 3 || theType == 4) {
32         rowForm.elements['field_' + md5Field + multi_edit + '[]'].selectedIndex = -1;
33     }
34     // Other "ENUM" field
35     else if (theType == 2) {
36         var elts     = rowForm.elements['field_' + md5Field + multi_edit + '[]'];
37         // when there is just one option in ENUM:
38         if (elts.checked) {
39             elts.checked = false;
40         } else {
41             var elts_cnt = elts.length;
42             for (var i = 0; i < elts_cnt; i++ ) {
43                 elts[i].checked = false;
44             } // end for
46         } // end if
47     }
48     // foreign key field (with browsing icon for foreign values)
49     else if (theType == 6) {
50         rowForm.elements['field_' + md5Field + multi_edit + '[]'].value = '';
51     }
52     // Other field types
53     else /*if (theType == 5)*/ {
54         rowForm.elements['fields' + multi_edit + '[' + md5Field + ']'].value = '';
55     } // end if... else if... else
57     return true;
58 } // end of the 'nullify()' function
61 /**
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
65  */
66 //function checks the number of days in febuary
67 function daysInFebruary (year)
69     return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
71 //function to convert single digit to double digit
72 function fractionReplace(num)
74     num = parseInt(num);
75     return num >= 1 && num <= 9 ? '0' + num : '00';
78 /* function to check the validity of date
79 * The following patterns are accepted in this validation (accepted in mysql as well)
80 * 1) 2001-12-23
81 * 2) 2001-1-2
82 * 3) 02-12-23
83 * 4) And instead of using '-' the following punctuations can be used (+,.,*,^,@,/) All these are accepted by mysql as well. Therefore no issues
85 function isDate(val,tmstmp)
87     val=val.replace(/[.|*|^|+|//|@]/g,'-');
88     var arrayVal=val.split("-");
89     for(var a=0;a<arrayVal.length;a++)
90     {
91         if(arrayVal[a].length==1)
92             arrayVal[a]=fractionReplace(arrayVal[a]);
93     }
94     val=arrayVal.join("-");
95     var pos=2;
96             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)))$/);
97         if(val.length==8)
98         {
99             dtexp=new RegExp(/^([0-9]{2})-(((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)))$/);
100             pos=0;
101         }
102         if(dtexp.test(val))
103         {
104             var month=parseInt(val.substring(pos+3,pos+5));
105             var day=parseInt(val.substring(pos+6,pos+8));
106             var year=parseInt(val.substring(0,pos+2));
107             if(month==2&&day>daysInFebruary(year))
108                 return false;
109             if(val.substring(0,pos+2).length==2)
110             {
111                 if(val.substring(0,pos+2).length==2)
112                     year=parseInt("20"+val.substring(0,pos+2));
113                 else
114                     year=parseInt("19"+val.substring(0,pos+2));
115             }
116             if(tmstmp==true)
117             {
118                 if(year<1978) return false;
119                 if(year>2038||(year>2037&&day>19&&month>=1)||(year>2037&&month>1)) return false;
120                 }
121         }
122         else
123             return false;
124         return true;
127 /* function to check the validity of time
128 * The following patterns are accepted in this validation (accepted in mysql as well)
129 * 1) 2:3:4
130 * 2) 2:23:43
132 function isTime(val)
134     var arrayVal=val.split(":");
135     for(var a=0;a<arrayVal.length;a++)
136     {
137         if(arrayVal[a].length==1)
138             arrayVal[a]=fractionReplace(arrayVal[a]);
139     }
140     val=arrayVal.join(":");
141     tmexp=new RegExp(/^(([0-1][0-9])|(2[0-3])):((0[0-9])|([1-5][0-9])):((0[0-9])|([1-5][0-9]))$/);
142         if(!tmexp.test(val))
143             return false;
144         return true;
147 function verificationsAfterFieldChange(urlField, multi_edit, theType)
149     var evt = window.event || arguments.callee.caller.arguments[0];
150     var target = evt.target || evt.srcElement;
152     // Unchecks the corresponding "NULL" control
153     $("input[name='fields_null[multi_edit][" + multi_edit + "][" + urlField + "]']").attr({'checked': false});
155     // Unchecks the Ignore checkbox for the current row
156     $("input[name='insert_ignore_" + multi_edit + "']").attr({'checked': false});
157     var $this_input = $("input[name='fields[multi_edit][" + multi_edit + "][" + urlField + "]']");
159     // Does this field come from datepicker?
160     if ($this_input.data('comes_from') == 'datepicker') {
161         // Yes, so do not validate because the final value is not yet in
162         // the field and hopefully the datepicker returns a valid date+time
163         $this_input.data('comes_from', '');
164         return true;
165     }
167     if(target.name.substring(0,6)=="fields") {
168         // validate for date time
169         if(theType=="datetime"||theType=="time"||theType=="date"||theType=="timestamp") {
170             $this_input.removeClass("invalid_value");
171             var dt_value = $this_input.val();
172             if(theType=="date"){
173                 if (! isDate(dt_value)) {
174                     $this_input.addClass("invalid_value");
175                     return false;
176                 }
177             } else if(theType=="time") {
178                 if (! isTime(dt_value)) {
179                     $this_input.addClass("invalid_value");
180                     return false;
181                 }
182             } else if(theType=="datetime"||theType=="timestamp") {
183                 tmstmp=false;
184                 if(dt_value == "CURRENT_TIMESTAMP") {
185                     return true;
186                 }
187                 if(theType=="timestamp") {
188                     tmstmp=true;
189                 }
190                 if(dt_value=="0000-00-00 00:00:00") {
191                     return true;
192                 }
193                 var dv=dt_value.indexOf(" ");
194                 if(dv==-1) {
195                     $this_input.addClass("invalid_value");
196                     return false;
197                 } else {
198                     if (! (isDate(dt_value.substring(0,dv),tmstmp) && isTime(dt_value.substring(dv+1)))) {
199                         $this_input.addClass("invalid_value");
200                         return false;
201                     }
202                 }
203             }
204         }
205         //validate for integer type
206         if(theType.substring(0,3) == "int"){
207             $this_input.removeClass("invalid_value");
208             if(isNaN($this_input.val())){
209                 $this_input.addClass("invalid_value");
210                 return false;
211             }
212         }
213     }
215  /* End of datetime validation*/
218  * Ajax handlers for Change Table page
220  * Actions Ajaxified here:
221  * Submit Data to be inserted into the table.
222  * Restart insertion with 'N' rows.
223  */
224 $(document).ready(function() {
226     $('.open_gis_editor').live('click', function(event) {
227         event.preventDefault();
229         var $span = $(this);
230         // Current value
231         var value = $span.parent('td').children("input[type='text']").val();
232         // Field name
233         var field = $span.parents('tr').children('td:first').find("input[type='hidden']").val();
234         // Column type
235         var type = $span.parents('tr').find('span.column_type').text();
236         // Names of input field and null checkbox
237         var input_name = $span.parent('td').children("input[type='text']").attr('name');
238         //Token
239         var token = $("input[name='token']").val();
241         openGISEditor();
242         if (!gisEditorLoaded) {
243             loadJSAndGISEditor(value, field, type, input_name, token);
244         } else {
245             loadGISEditor(value, field, type, input_name, token);
246         }
247     });
249     /**
250      * Uncheck the null checkbox as geometry data is placed on the input field
251      */
252     $("input[name='gis_data[save]']").live('click', function(event) {
253         var input_name = $('form#gis_data_editor_form').find("input[name='input_name']").val();   
254         var $null_checkbox = $("input[name='" + input_name + "']").parents('tr').find('.checkbox_null');
255         $null_checkbox.attr('checked', false);
256     });
258     // these were hidden via the "hide" class
259     $('.foreign_values_anchor').show();
261     /**
262      * Handles all current checkboxes for Null; this only takes care of the
263      * checkboxes on currently displayed rows as the rows generated by
264      * "Continue insertion" are handled in the "Continue insertion" code
265      *
266      */
267     $('.checkbox_null').bind('click', function(e) {
268             nullify(
269                 // use hidden fields populated by tbl_change.php
270                 $(this).siblings('.nullify_code').val(),
271                 $(this).closest('tr').find('input:hidden').first().val(),
272                 $(this).siblings('.hashed_field').val(),
273                 $(this).siblings('.multi_edit').val()
274             );
275     });
277     /**
278      * Submission of data to be inserted or updated
279      *
280      * @uses    PMA_ajaxShowMessage()
281      *
282      * This section has been deactivated. Here are the problems that I've
283      * noticed:
284      *
285      * 1. If the form contains a file upload field, the data does not reach
286      *    tbl_replace.php. This is because AJAX does not support file upload.
287      *    As a workaround I tried jquery.form.js version 2.49. The file
288      *    upload worked but afterwards the browser presented a tbl_replace.php
289      *    file and a choice to open or save.
290      *
291      * 2. This code can be called if we are editing or inserting. If editing,
292      *    the "and then" action can be "go back to this page" or "edit next
293      *    row", in which cases it makes sense to use AJAX. But the "go back
294      *    to previous page" and "insert another new row" actions, using AJAX
295      *    has no obvious advantage. If inserting, the "go back to previous"
296      *    action needs a page refresh anyway.
297      */
298     $("#insertFormDEACTIVATED").live('submit', function(event) {
300         /**
301          * @var the_form    Object referring to the insertion form
302          */
303         var $form = $(this);
304         event.preventDefault();
306         PMA_ajaxShowMessage();
307         PMA_prepareForAjaxRequest($form);
309         $.post($form.attr('action'), $form.serialize(), function(data) {
310             if (typeof data.success != 'undefined') {
311                 if(data.success == true) {
312                     PMA_ajaxShowMessage(data.message);
314                     $("#topmenucontainer")
315                     .next('div')
316                     .remove()
317                     .end()
318                     .after(data.sql_query);
320                     //Remove the empty notice div generated due to a NULL query passed to PMA_showMessage()
321                     var $notice_class = $("#topmenucontainer").next("div").find('.notice');
322                     if ($notice_class.text() == '') {
323                         $notice_class.remove();
324                     }
326                     var submit_type = $form.find("select[name='submit_type']").val();
327                     if ('insert' == submit_type || 'insertignore' == submit_type) {
328                         //Clear the data in the forms
329                         $form.find('input:reset').trigger('click');
330                     }
331                 } else {
332                     PMA_ajaxShowMessage(PMA_messages['strErrorProcessingRequest'] + " : "+data.error, "7000");
333                 }
334             } else {
335                 //happens for example when no change was done while editing
336                 $('#insertForm').remove();
337                 $('#topmenucontainer').after('<div id="sqlqueryresults"></div>');
338                 $('#sqlqueryresults').html(data);
339             }
340         })
341     }) // end submission of data to be inserted into table
343     /**
344      * Continue Insertion form
345      */
346     $("#insert_rows").live('change', function(event) {
347         event.preventDefault();
349         /**
350          * @var curr_rows   Number of current insert rows already on page
351          */
352         var curr_rows = $(".insertRowTable").length;
353         /**
354          * @var target_rows Number of rows the user wants
355          */
356         var target_rows = $("#insert_rows").val();
358         // remove all datepickers
359         $('.datefield,.datetimefield').each(function(){
360             $(this).datepicker('destroy');
361         });
363         if(curr_rows < target_rows ) {
364             while( curr_rows < target_rows ) {
366                 /**
367                  * @var $last_row    Object referring to the last row
368                  */
369                 var $last_row = $("#insertForm").find(".insertRowTable:last");
371                 // need to access this at more than one level
372                 // (also needs improvement because it should be calculated
373                 //  just once per cloned row, not once per column)
374                 var new_row_index = 0;
376                 //Clone the insert tables
377                 $last_row
378                 .clone()
379                 .insertBefore("#actions_panel")
380                 .find('input[name*=multi_edit],select[name*=multi_edit],textarea[name*=multi_edit]')
381                 .each(function() {
383                     var $this_element = $(this);
384                     /**
385                      * Extract the index from the name attribute for all input/select fields and increment it
386                      * name is of format funcs[multi_edit][10][<long random string of alphanum chars>]
387                      */
389                     /**
390                      * @var this_name   String containing name of the input/select elements
391                      */
392                     var this_name = $this_element.attr('name');
393                     /** split {@link this_name} at [10], so we have the parts that can be concatenated later */
394                     var name_parts = this_name.split(/\[\d+\]/);
395                     /** extract the [10] from  {@link name_parts} */
396                     var old_row_index_string = this_name.match(/\[\d+\]/)[0];
397                     /** extract 10 - had to split into two steps to accomodate double digits */
398                     var old_row_index = parseInt(old_row_index_string.match(/\d+/)[0]);
400                     /** calculate next index i.e. 11 */
401                     new_row_index = old_row_index + 1;
402                     /** generate the new name i.e. funcs[multi_edit][11][foobarbaz] */
403                     var new_name = name_parts[0] + '[' + new_row_index + ']' + name_parts[1];
405                     var hashed_field = name_parts[1].match(/\[(.+)\]/)[1];
406                     $this_element.attr('name', new_name);
408                     if ($this_element.is('.textfield')) {
409                         // do not remove the 'value' attribute for ENUM columns
410                         if ($this_element.closest('tr').find('span.column_type').html() != 'enum') {
411                             $this_element.attr('value', $this_element.closest('tr').find('span.default_value').html());
412                         }
413                         $this_element
414                         .unbind('change')
415                         // Remove onchange attribute that was placed
416                         // by tbl_change.php; it refers to the wrong row index
417                         .attr('onchange', null)
418                         // Keep these values to be used when the element
419                         // will change
420                         .data('hashed_field', hashed_field)
421                         .data('new_row_index', new_row_index)
422                         .bind('change', function(e) {
423                             var $changed_element = $(this);
424                             verificationsAfterFieldChange(
425                                 $changed_element.data('hashed_field'),
426                                 $changed_element.data('new_row_index'),
427                                 $changed_element.closest('tr').find('span.column_type').html()
428                                 );
429                         });
430                     }
432                     if ($this_element.is('.checkbox_null')) {
433                         $this_element
434                         // this event was bound earlier by jQuery but
435                         // to the original row, not the cloned one, so unbind()
436                         .unbind('click')
437                         // Keep these values to be used when the element
438                         // will be clicked
439                         .data('hashed_field', hashed_field)
440                         .data('new_row_index', new_row_index)
441                         .bind('click', function(e) {
442                                 var $changed_element = $(this);
443                                 nullify(
444                                     $changed_element.siblings('.nullify_code').val(),
445                                     $this_element.closest('tr').find('input:hidden').first().val(),
446                                     $changed_element.data('hashed_field'),
447                                     '[multi_edit][' + $changed_element.data('new_row_index') + ']'
448                                     );
449                         });
450                     }
451                 }) // end each
452                 .end()
453                 .find('.foreign_values_anchor')
454                 .each(function() {
455                         $anchor = $(this);
456                         var new_value = 'rownumber=' + new_row_index;
457                         // needs improvement in case something else inside
458                         // the href contains this pattern
459                         var new_href = $anchor.attr('href').replace(/rownumber=\d+/, new_value);
460                         $anchor.attr('href', new_href );
461                     });
463                 //Insert/Clone the ignore checkboxes
464                 if(curr_rows == 1 ) {
465                     $('<input id="insert_ignore_1" type="checkbox" name="insert_ignore_1" checked="checked" />')
466                     .insertBefore(".insertRowTable:last")
467                     .after('<label for="insert_ignore_1">' + PMA_messages['strIgnore'] + '</label>');
468                 }
469                 else {
471                     /**
472                      * @var last_checkbox   Object reference to the last checkbox in #insertForm
473                      */
474                     var last_checkbox = $("#insertForm").children('input:checkbox:last');
476                     /** name of {@link last_checkbox} */
477                     var last_checkbox_name = $(last_checkbox).attr('name');
478                     /** index of {@link last_checkbox} */
479                     var last_checkbox_index = parseInt(last_checkbox_name.match(/\d+/));
480                     /** name of new {@link last_checkbox} */
481                     var new_name = last_checkbox_name.replace(/\d+/,last_checkbox_index+1);
483                     $(last_checkbox)
484                     .clone()
485                     .attr({'id':new_name, 'name': new_name, 'checked': true})
486                     .add('label[for^=insert_ignore]:last')
487                     .clone()
488                     .attr('for', new_name)
489                     .before('<br />')
490                     .insertBefore(".insertRowTable:last");
491                 }
492                 curr_rows++;
493             }
494         // recompute tabindex for text fields and other controls at footer;
495         // IMO it's not really important to handle the tabindex for
496         // function and Null
497         var tabindex = 0;
498         $('.textfield')
499         .each(function() {
500                 tabindex++;
501                 $(this).attr('tabindex', tabindex);
502                 // update the IDs of textfields to ensure that they are unique
503                 $(this).attr('id', "field_" + tabindex + "_3");
504             });
505         $('.control_at_footer')
506         .each(function() {
507                 tabindex++;
508                 $(this).attr('tabindex', tabindex);
509             });
510         // Add all the required datepickers back
511         $('.datefield,.datetimefield').each(function(){
512             PMA_addDatepicker($(this));
513             });
514         }
515         else if( curr_rows > target_rows) {
516             while(curr_rows > target_rows) {
517                 $("input[id^=insert_ignore]:last")
518                 .nextUntil("fieldset")
519                 .andSelf()
520                 .remove();
521                 curr_rows--;
522             }
523         }
524     })
525 }, 'top.frame_content'); //end $(document).ready()