Revert "Login screen improvements and added favicon (#227)"
[openemr.git] / phpmyadmin / js / common.js
blob4e8545af3fc41acd50901ec27160a08403f22c31
1 /* vim: set expandtab sw=4 ts=4 sts=4: */
3 $(function () {
4     checkNumberOfFields();
5 });
7 /**
8  * Holds common parameters such as server, db, table, etc
9  *
10  * The content for this is normally loaded from Header.class.php or
11  * Response.class.php and executed by ajax.js
12  */
13 var PMA_commonParams = (function () {
14     /**
15      * @var hash params An associative array of key value pairs
16      * @access private
17      */
18     var params = {};
19     // The returned object is the public part of the module
20     return {
21         /**
22          * Saves all the key value pair that
23          * are provided in the input array
24          *
25          * @param obj hash The input array
26          *
27          * @return void
28          */
29         setAll: function (obj) {
30             var reload = false;
31             var updateNavigation = false;
32             for (var i in obj) {
33                 if (params[i] !== undefined && params[i] !== obj[i]) {
34                     if (i == 'db' || i == 'table') {
35                         updateNavigation = true;
36                     }
37                     reload = true;
38                 }
39                 params[i] = obj[i];
40             }
41             if (updateNavigation &&
42                     $('#pma_navigation_tree').hasClass('synced')
43             ) {
44                 PMA_showCurrentNavigation();
45             }
46         },
47         /**
48          * Retrieves a value given its key
49          * Returns empty string for undefined values
50          *
51          * @param name string The key
52          *
53          * @return string
54          */
55         get: function (name) {
56             return params[name] || '';
57         },
58         /**
59          * Saves a single key value pair
60          *
61          * @param name  string The key
62          * @param value string The value
63          *
64          * @return self For chainability
65          */
66         set: function (name, value) {
67             var updateNavigation = false;
68             if (name == 'db' || name == 'table' &&
69                 params[name] !== value
70             ) {
71                 updateNavigation = true;
72             }
73             params[name] = value;
74             if (updateNavigation &&
75                     $('#pma_navigation_tree').hasClass('synced')
76             ) {
77                 PMA_showCurrentNavigation();
78             }
79             return this;
80         },
81         /**
82          * Returns the url query string using the saved parameters
83          *
84          * @return string
85          */
86         getUrlQuery: function () {
87             return PMA_sprintf(
88                 '%s&server=%s&db=%s&table=%s',
89                 this.get('common_query'),
90                 encodeURIComponent(this.get('server')),
91                 encodeURIComponent(this.get('db')),
92                 encodeURIComponent(this.get('table'))
93             );
94         }
95     };
96 })();
98 /**
99  * Holds common parameters such as server, db, table, etc
101  * The content for this is normally loaded from Header.class.php or
102  * Response.class.php and executed by ajax.js
103  */
104 var PMA_commonActions = {
105     /**
106      * Saves the database name when it's changed
107      * and reloads the query window, if necessary
108      *
109      * @param new_db string new_db The name of the new database
110      *
111      * @return void
112      */
113     setDb: function (new_db) {
114         if (new_db != PMA_commonParams.get('db')) {
115             PMA_commonParams.setAll({'db': new_db, 'table': ''});
116         }
117     },
118     /**
119      * Opens a database in the main part of the page
120      *
121      * @param new_db string The name of the new database
122      *
123      * @return void
124      */
125     openDb: function (new_db) {
126         PMA_commonParams
127             .set('db', new_db)
128             .set('table', '');
129         this.refreshMain(
130             PMA_commonParams.get('opendb_url')
131         );
132     },
133     /**
134      * Refreshes the main frame
135      *
136      * @param mixed url Undefined to refresh to the same page
137      *                  String to go to a different page, e.g: 'index.php'
138      *
139      * @return void
140      */
141     refreshMain: function (url, callback) {
142         if (! url) {
143             url = $('#selflink').find('a').attr('href');
144             url = url.substring(0, url.indexOf('?'));
145         }
146         url += PMA_commonParams.getUrlQuery();
147         $('<a />', {href: url})
148             .appendTo('body')
149             .click()
150             .remove();
151         AJAX._callback = callback;
152     }
156  * Class to handle PMA Drag and Drop Import
157  *      feature
158  */
159 PMA_DROP_IMPORT = {
160     /**
161      * @var int, count of total uploads in this view
162      */
163     uploadCount: 0,
164     /**
165      * @var int, count of live uploads
166      */
167     liveUploadCount: 0,
168     /**
169      * @var  string array, allowed extensions
170      */
171     allowedExtensions: ['sql', 'xml', 'ldi', 'mediawiki', 'shp'],
172     /**
173      * @var  string array, allowed extensions for compressed files
174      */
175     allowedCompressedExtensions: ['gz', 'bz2', 'zip'],
176     /**
177      * @var obj array to store message returned by import_status.php
178      */
179     importStatus: [],
180     /**
181      * Checks if any dropped file has valid extension or not
182      *
183      * @param file filename
184      *
185      * @return string, extension for valid extension, '' otherwise
186      */
187     _getExtension: function(file) {
188         var arr = file.split('.');
189         ext = arr[arr.length - 1];
191         //check if compressed
192         if (jQuery.inArray(ext.toLowerCase(),
193             PMA_DROP_IMPORT.allowedCompressedExtensions) !== -1) {
194             ext = arr[arr.length - 2];
195         }
197         //Now check for extension
198         if (jQuery.inArray(ext.toLowerCase(),
199             PMA_DROP_IMPORT.allowedExtensions) !== -1) {
200             return ext;
201         }
202         return '';
203     },
204     /**
205      * Shows upload progress for different sql uploads
206      *
207      * @param: hash (string), hash for specific file upload
208      * @param: percent (float), file upload percentage
209      *
210      * @return void
211      */
212     _setProgress: function(hash, percent) {
213         $('.pma_sql_import_status div li[data-hash="' +hash +'"]')
214             .children('progress').val(percent);
215     },
216     /**
217      * Function to upload the file asynchronously
218      *
219      * @param formData FormData object for a specific file
220      * @param hash hash of the current file upload
221      *
222      * @return void
223      */
224     _sendFileToServer: function(formData, hash) {
225         var uploadURL ="./import.php"; //Upload URL
226         var extraData ={};
227         var jqXHR = $.ajax({
228             xhr: function() {
229                 var xhrobj = $.ajaxSettings.xhr();
230                 if (xhrobj.upload) {
231                     xhrobj.upload.addEventListener('progress', function(event) {
232                         var percent = 0;
233                         var position = event.loaded || event.position;
234                         var total = event.total;
235                         if (event.lengthComputable) {
236                             percent = Math.ceil(position / total * 100);
237                         }
238                         //Set progress
239                         PMA_DROP_IMPORT._setProgress(hash, percent);
240                     }, false);
241                 }
242                 return xhrobj;
243             },
244             url: uploadURL,
245             type: "POST",
246             contentType:false,
247             processData: false,
248             cache: false,
249             data: formData,
250             success: function(data){
251                 PMA_DROP_IMPORT._importFinished(hash, false, data.success);
252                 if (!data.success) {
253                     PMA_DROP_IMPORT.importStatus[PMA_DROP_IMPORT.importStatus.length] = {
254                         hash: hash,
255                         message: data.error
256                     };
257                 }
258             }
259         });
261         // -- provide link to cancel the upload
262         $('.pma_sql_import_status div li[data-hash="' + hash +
263             '"] span.filesize').html('<span hash="' +
264             hash + '" class="pma_drop_file_status" task="cancel">' +
265             PMA_messages.dropImportMessageCancel + '</span>');
267         // -- add event listener to this link to abort upload operation
268         $('.pma_sql_import_status div li[data-hash="' + hash +
269             '"] span.filesize span.pma_drop_file_status')
270             .on('click', function() {
271                 if ($(this).attr('task') === 'cancel') {
272                     jqXHR.abort();
273                     $(this).html('<span>' +PMA_messages.dropImportMessageAborted +'</span>');
274                     PMA_DROP_IMPORT._importFinished(hash, true, false);
275                 } else if ($(this).children("span").html() ===
276                     PMA_messages.dropImportMessageFailed) {
277                     // -- view information
278                     var $this = $(this);
279                     $.each( PMA_DROP_IMPORT.importStatus,
280                     function( key, value ) {
281                         if (value.hash === hash) {
282                             $(".pma_drop_result:visible").remove();
283                             var filename = $this.parent('span').attr('data-filename');
284                             $("body").append('<div class="pma_drop_result"><h2>' +
285                                 PMA_messages.dropImportImportResultHeader + ' - ' +
286                                 filename +'<span class="close">x</span></h2>' +value.message +'</div>');
287                             $(".pma_drop_result").draggable();  //to make this dialog draggable
288                         }
289                     });
290                 }
291             });
292     },
293     /**
294      * Triggered when an object is dragged into the PMA UI
295      *
296      * @param event obj
297      *
298      * @return void
299      */
300     _dragenter : function (event) {
301         event.stopPropagation();
302         event.preventDefault();
303         if (!PMA_DROP_IMPORT._hasFiles(event)) {
304             return;
305         }
306         if (PMA_commonParams.get('db') === '') {
307             $(".pma_drop_handler").html(PMA_messages.dropImportSelectDB);
308         } else {
309             $(".pma_drop_handler").html(PMA_messages.dropImportDropFiles);
310         }
311         $(".pma_drop_handler").fadeIn();
312     },
313     /**
314      * Check if dragged element contains Files
315      *
316      * @param event the event object
317      *
318      * @return bool
319      */
320     _hasFiles: function (event) {
321         return !(typeof event.originalEvent.dataTransfer.types === 'undefined' ||
322             $.inArray('Files', event.originalEvent.dataTransfer.types) < 0 ||
323             $.inArray(
324                 'application/x-moz-nativeimage',
325                 event.originalEvent.dataTransfer.types
326             ) >= 0);
327     },
328     /**
329      * Triggered when dragged file is being dragged over PMA UI
330      *
331      * @param event obj
332      *
333      * @return void
334      */
335     _dragover: function (event) {
336         event.stopPropagation();
337         event.preventDefault();
338         if (!PMA_DROP_IMPORT._hasFiles(event)) {
339             return;
340         }
341         $(".pma_drop_handler").fadeIn();
342     },
343     /**
344      * Triggered when dragged objects are left
345      *
346      * @param event obj
347      *
348      * @return void
349      */
350     _dragleave: function (event) {
351         event.stopPropagation();
352         event.preventDefault();
353         var $pma_drop_handler = $(".pma_drop_handler");
354         $pma_drop_handler.clearQueue().stop();
355         $pma_drop_handler.fadeOut();
356         $pma_drop_handler.html(PMA_messages.dropImportDropFiles);
357     },
358     /**
359      * Called when upload has finished
360      *
361      * @param string, unique hash for a certain upload
362      * @param bool, true if upload was aborted
363      * @param bool, status of sql upload, as sent by server
364      *
365      * @return void
366      */
367     _importFinished: function(hash, aborted, status) {
368         $('.pma_sql_import_status div li[data-hash="' +hash +'"]')
369             .children("progress").hide();
370         var icon = 'icon ic_s_success';
371         // -- provide link to view upload status
372         if (!aborted) {
373             if (status) {
374                 $('.pma_sql_import_status div li[data-hash="' + hash +
375                    '"] span.filesize span.pma_drop_file_status')
376                    .html('<span>' +PMA_messages.dropImportMessageSuccess +'</a>');
377             } else {
378                 $('.pma_sql_import_status div li[data-hash="' + hash +
379                    '"] span.filesize span.pma_drop_file_status')
380                    .html('<span class="underline">' + PMA_messages.dropImportMessageFailed +
381                    '</a>');
382                 icon = 'icon ic_s_error';
383             }
384         } else {
385             icon = 'icon ic_s_notice';
386         }
387         $('.pma_sql_import_status div li[data-hash="' + hash +
388             '"] span.filesize span.pma_drop_file_status')
389             .attr('task', 'info');
391         // Set icon
392         $('.pma_sql_import_status div li[data-hash="' +hash +'"]')
393             .prepend('<img src="./themes/dot.gif" title="finished" class="' +
394             icon +'"> ');
396         // Decrease liveUploadCount by one
397         $('.pma_import_count').html(--PMA_DROP_IMPORT.liveUploadCount);
398         if (!PMA_DROP_IMPORT.liveUploadCount) {
399             $('.pma_sql_import_status h2 .close').fadeIn();
400         }
401     },
402     /**
403      * Triggered when dragged objects are dropped to UI
404      * From this function, the AJAX Upload operation is initiated
405      *
406      * @param event object
407      *
408      * @return void
409      */
410     _drop: function (event) {
411         var dbname = PMA_commonParams.get('db');
412         //if no database is selected -- no
413         if (dbname !== '') {
414             var files = event.originalEvent.dataTransfer.files;
415             if (!files || files.length === 0) {
416                 // No files actually transferred
417                 $(".pma_drop_handler").fadeOut();
418                 event.stopPropagation();
419                 event.preventDefault();
420                 return;
421             }
422             $(".pma_sql_import_status").slideDown();
423             for (var i = 0; i < files.length; i++) {
424                 var ext  = (PMA_DROP_IMPORT._getExtension(files[i].name));
425                 var hash = AJAX.hash(++PMA_DROP_IMPORT.uploadCount);
427                 var $pma_sql_import_status_div = $(".pma_sql_import_status div");
428                 $pma_sql_import_status_div.append('<li data-hash="' +hash +'">' +
429                     ((ext !== '') ? '' : '<img src="./themes/dot.gif" title="invalid format" class="icon ic_s_notice"> ') +
430                     escapeHtml(files[i].name) + '<span class="filesize" data-filename="' +
431                     escapeHtml(files[i].name) +'">' +(files[i].size/1024).toFixed(2) +
432                     ' kb</span></li>');
434                 //scroll the UI to bottom
435                 $pma_sql_import_status_div.scrollTop(
436                     $pma_sql_import_status_div.scrollTop() + 50
437                 );  //50 hardcoded for now
439                 if (ext !== '') {
440                     // Increment liveUploadCount by one
441                     $('.pma_import_count').html(++PMA_DROP_IMPORT.liveUploadCount);
442                     $('.pma_sql_import_status h2 .close').fadeOut();
444                     $('.pma_sql_import_status div li[data-hash="' +hash +'"]')
445                         .append('<br><progress max="100" value="2"></progress>');
447                     //uploading
448                     var fd = new FormData();
449                     fd.append('import_file', files[i]);
450                     // todo: method to find the value below
451                     fd.append('noplugin', '539de66e760ee');
452                     fd.append('db', dbname);
453                     fd.append('token', PMA_commonParams.get('token'));
454                     fd.append('import_type', 'database');
455                     // todo: method to find the value below
456                     fd.append('MAX_FILE_SIZE', '4194304');
457                     // todo: method to find the value below
458                     fd.append('charset_of_file','utf-8');
459                     // todo: method to find the value below
460                     fd.append('allow_interrupt', 'yes');
461                     fd.append('skip_queries', '0');
462                     fd.append('format',ext);
463                     fd.append('sql_compatibility','NONE');
464                     fd.append('sql_no_auto_value_on_zero','something');
465                     fd.append('ajax_request','true');
466                     fd.append('hash', hash);
468                     // init uploading
469                     PMA_DROP_IMPORT._sendFileToServer(fd, hash);
470                 } else if (!PMA_DROP_IMPORT.liveUploadCount) {
471                     $('.pma_sql_import_status h2 .close').fadeIn();
472                 }
473             }
474         }
475         $(".pma_drop_handler").fadeOut();
476         event.stopPropagation();
477         event.preventDefault();
478     }
482  * Called when some user drags, dragover, leave
483  *       a file to the PMA UI
484  * @param object Event data
485  * @return void
486  */
487 $(document).on('dragenter', PMA_DROP_IMPORT._dragenter);
488 $(document).on('dragover', PMA_DROP_IMPORT._dragover);
489 $(document).on('dragleave', '.pma_drop_handler', PMA_DROP_IMPORT._dragleave);
491 //when file is dropped to PMA UI
492 $(document).on('drop', 'body', PMA_DROP_IMPORT._drop);
494 // minimizing-maximising the sql ajax upload status
495 $(document).on('click', '.pma_sql_import_status h2 .minimize', function() {
496     if ($(this).attr('toggle') === 'off') {
497         $('.pma_sql_import_status div').css('height','270px');
498         $(this).attr('toggle','on');
499         $(this).html('-');  // to minimize
500     } else {
501         $('.pma_sql_import_status div').css("height","0px");
502         $(this).attr('toggle','off');
503         $(this).html('+');  // to maximise
504     }
507 // closing sql ajax upload status
508 $(document).on('click', '.pma_sql_import_status h2 .close', function() {
509     $('.pma_sql_import_status').fadeOut(function() {
510         $('.pma_sql_import_status div').html('');
511         PMA_DROP_IMPORT.importStatus = [];  //clear the message array
512     });
515 // Closing the import result box
516 $(document).on('click', '.pma_drop_result h2 .close', function(){
517     $(this).parent('h2').parent('div').remove();