source: trunk/expressoMail1_2/js/connector.js @ 1369

Revision 1369, 16.3 KB checked in by niltonneto, 15 years ago (diff)

Ticket #179 - Corrigido problema do handler do cExecuteForm.

  • Property svn:eol-style set to native
  • Property svn:executable set to *
Line 
1/****************************************** Public variables *************************************************/
2var debug_controller =false;
3var files = new Array();
4var progressBar;
5var handlerExecuteForm = null;
6
7  if (document.all)
8        {
9                navigator.userAgent.toLowerCase().indexOf('msie 5') != -1 ? is_ie5 = true : is_ie5 = false;
10                is_ie = true;
11                is_moz1_6 = false;
12                is_mozilla = false;
13                is_ns4 = false;
14        }
15        else if (document.getElementById)
16        {
17                navigator.userAgent.toLowerCase().match('mozilla.*rv[:]1\.6.*gecko') ? is_moz1_6 = true : is_moz1_6 = false;
18                is_ie = false;
19                is_ie5 = false;
20                is_mozilla = true;
21                is_ns4 = false;
22        }
23        else if (document.layers)
24        {
25                is_ie = false;
26                is_ie5 = false
27                is_moz1_6 = false;
28                is_mozilla = false;
29                is_ns4 = true;
30        }       
31
32/****************************************** Connector Class *************************************************/
33        // Constructor
34        function cConnector()
35        {
36                this.requests = new Array();
37                this.oxmlhttp = null;
38                this.isVisibleBar = false;
39                this.tid = 0;
40                this.progressBar = null;
41                this.oldX = 0;
42                this.oldY = 0;
43                this.updateVersion = "";       
44        }
45       
46        cConnector.prototype.buildBar = function()
47                {                       
48                        var div = document.getElementById('divProgressBar');
49               
50                        if(! div) {                                                                                             
51                                div = document.createElement("DIV");
52                                div.style.visibility    = "hidden";             
53                                div.style.width = "103px";
54                                div.id = 'divProgressBar';
55                                div.align = "center";
56                                div.innerHTML = '&nbsp;&nbsp;<font face="Verdana" size="2" color="WHITE">'+document.getElementById('txt_loading').value+'...</font>&nbsp;';
57                                div.style.background = "#cc4444";
58                                div.style.position = 'fixed';
59                                div.style.top = '0px';
60                                div.style.right = '0px';
61                                document.body.appendChild(div);                                                                                                                         
62                               
63                                if(is_ie) {
64                                        var elem = document.all[div.id];
65                                        elem.style.position="absolute";
66                                        var root = document.body;
67                                        var posX = elem.offsetLeft-root.scrollLeft;
68                                        var posY = elem.offsetTop-root.scrollTop;
69                                        root.onscroll = function() {
70                                                elem.style.right = '0px';
71                                                elem.style.top = (posY + root.scrollTop) + "px";
72                                        };                                     
73                                }
74                               
75                                if(debug_controller) {
76                                        div = document.createElement("DIV");
77                                        div.style.width = "800px";
78                                        div.style.height= "400px";
79                                        div.id = "debug_controller";
80                                        div.align='right';
81                                        document.body.appendChild(div);                                                                                                                         
82                                }
83                        }                                                               
84        }       
85//------------------------------------ BEGIN: Functions for Connector HTTPRequest  -------------------------------------------------// 
86        // Serialize Data Method
87        cConnector.prototype.serialize = function(data)
88        {       var _thisObject = this;         
89                var f = function(data)
90                {
91                        var str_data;
92       
93                        if (data == null ||
94                                (typeof(data) == 'string' && data == ''))
95                        {
96                                str_data = 'N;';
97                        }
98       
99                        else switch(typeof(data))
100                        {
101                                case 'object':
102                                        var arrayCount = 0;
103       
104                                        str_data = '';
105       
106                                        for (i in data)
107                                        {
108                                                if (i == 'length')
109                                                {
110                                                        continue;
111                                                }
112                                               
113                                                arrayCount++;
114                                                switch (typeof(i))
115                                                {
116                                                        case 'number':
117                                                                str_data += 'i:' + i + ';' + _thisObject.serialize(data[i]);
118                                                                break;
119       
120                                                        case 'string':
121                                                                str_data += 's:' + i.length + ':"' + i + '";' + _thisObject.serialize(data[i]);
122                                                                break;
123       
124                                                        default:
125                                                                showMessage(Element('cc_msg_err_serialize_data_unknown').value);
126                                                                break;
127                                                }
128                                        }
129       
130                                        if (!arrayCount)
131                                        {
132                                                str_data = 'N;';       
133                                        }
134                                        else
135                                        {
136                                                str_data = 'a:' + arrayCount + ':{' + str_data + '}';
137                                        }
138                                       
139                                        break;
140                       
141                                case 'string':
142                                        str_data = 's:' + data.length + ':"' + data + '";';
143                                        break;
144                                       
145                                case 'number':
146                                        str_data = 'i:' + data + ';';
147                                        break;
148       
149                                case 'boolean':
150                                        str_data = 'b:' + (data ? '1' : '0') + ';';
151                                        break;
152       
153                                default:
154                                        showMessage(Element('cc_msg_err_serialize_data_unknown').value);
155                                        return null;
156                        }
157
158                        return str_data;
159                }
160       
161                var sdata = f(data);
162                return sdata;
163        }
164        cConnector.prototype.matchBracket = function(strG, iniPosG)
165        {
166                _thisObject = this;
167                var f = function (str, iniPos)
168                {
169                        var nOpen, nClose = iniPos;
170               
171                        do
172                        {
173                                nOpen = str.indexOf('{', nClose+1);
174                                nClose = str.indexOf('}', nClose+1);
175
176                                if (nOpen == -1)
177                                {
178                                        return nClose;
179                                }
180                       
181                                if (nOpen < nClose )
182                                {
183                                        nClose = _thisObject.matchBracket(str, nOpen);
184                                }
185                       
186                        } while (nOpen < nClose);
187
188                        return nClose;
189                }
190
191                return f(strG, iniPosG);
192        }
193       
194               
195        //Unserialize Data Method
196        cConnector.prototype.unserialize = function(str)
197        {
198               
199                _thisObject = this;
200               
201                var f = function (str)
202                {
203                        switch (str.charAt(0))
204                        {
205                                case 'a':
206                                       
207                                        var data = new Array();
208                                        var n = parseInt( str.substring( str.indexOf(':')+1, str.indexOf(':',2) ) );
209                                        var arrayContent = str.substring(str.indexOf('{')+1, str.lastIndexOf('}'));
210                               
211                                        for (var i = 0; i < n; i++)
212                                        {
213                                                var pos = 0;
214       
215                                                /* Process Index */
216                                                var indexStr = arrayContent.substr(pos, arrayContent.indexOf(';')+1);
217                                                var index = _thisObject.unserialize(indexStr);
218                                                pos = arrayContent.indexOf(';', pos)+1;
219                                               
220                                                /* Process Content */
221                                                var part = null;
222                                                switch (arrayContent.charAt(pos))
223                                                {
224                                                        case 'a':
225                                                                var pos_ = _thisObject.matchBracket(arrayContent, arrayContent.indexOf('{', pos))+1;
226                                                                part = arrayContent.substring(pos, pos_);
227                                                                pos = pos_;
228                                                                data[index] = _thisObject.unserialize(part);
229                                                                break;
230                                               
231                                                        case 's':
232                                                                var pval = arrayContent.indexOf(':', pos+2);
233                                                                var val  = parseInt(arrayContent.substring(pos+2, pval));
234                                                                pos = pval + val + 4;
235                                                                data[index] = arrayContent.substr(pval+2, val);
236                                                                break;
237       
238                                                        default:
239                                                                part = arrayContent.substring(pos, arrayContent.indexOf(';', pos)+1);
240                                                                pos = arrayContent.indexOf(';', pos)+1;
241                                                                data[index] = _thisObject.unserialize(part);
242                                                                break;
243                                                }
244                                                arrayContent = arrayContent.substr(pos);
245                                        }
246                                        break;
247                                       
248                                case 's':
249                                        var pos = str.indexOf(':', 2);
250                                        var val = parseInt(str.substring(2,pos));
251                                        var data = str.substr(pos+2, val);
252                                        str = str.substr(pos + 4 + val);
253                                        break;
254       
255                                case 'i':
256                                case 'd':
257                                        var pos = str.indexOf(';');
258                                        var data = parseInt(str.substring(2,pos));
259                                        str = str.substr(pos + 1);
260                                        break;
261                               
262                                case 'N':
263                                        var data = null;
264                                        str = str.substr(str.indexOf(';') + 1);
265                                        break;
266       
267                                case 'b':
268                                        var data = str.charAt(2) == '1' ? true : false;
269                                        break;
270                        }
271                        return data;
272                }
273       
274                return f(str);
275        }
276
277        //Create XMLHTTP object Method
278        cConnector.prototype.createXMLHTTP = function ()
279        {       
280                try
281                {
282                        this.oxmlhttp = new XMLHttpRequest();
283                        this.oxmlhttp.overrideMimeType('text/xml');
284                }
285                catch (e)
286                {
287                        try
288                        {
289                                this.oxmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
290                        }
291                        catch (e1)
292                        {
293                                try
294                                {
295                                        this.oxmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
296                                }
297                                catch (e2)
298                                {
299                                        this.oxmlhttp = null;
300                                }
301                        }
302                }
303       
304        }
305       
306        // Request Constructor Connector       
307        cConnector.prototype.newRequest = function (id, target, method, handler, data)
308        {
309                var params = data;
310                this.tid = id;
311                if (this.requests[id]) {
312                        return false;
313                }
314       
315                this.createXMLHTTP();
316                var oxmlhttp = this.oxmlhttp;
317                var _thisObject = this;         
318               
319                if (! oxmlhttp)         
320                        return false;
321                               
322                this.requests[id] = oxmlhttp;
323                this.buildBar();               
324                this.showProgressBar();
325               
326                var sub_handler = function ()
327                {                       
328                        var progressBar = _thisObject.progressBar;
329                       
330                        try
331                        {
332                                if (oxmlhttp.readyState == 4 )
333                                {
334                                       
335                                        switch (oxmlhttp.status)
336                                        {
337                                               
338                                                case 200:
339                                                        if (typeof(handler) == 'function')
340                                                        {                                                                                                                               
341                                                                _thisObject.hideProgressBar();                                                                                                                         
342                                                                var data = _thisObject.unserialize(oxmlhttp.responseText);
343                                                                if ( typeof data == 'undefined' )
344                                                                        data = oxmlhttp.responseText;
345                                                                if(debug_controller) {
346                                                                        document.getElementById("debug_controller").innerHTML += oxmlhttp.responseText;
347                                                                        document.getElementById("debug_controller").innerHTML += "<br>-------------------------------------------------------------------------------------<br>";
348                                                                }
349                                                                handler(data);
350                                                                addToCache(params?id+"&"+params:id,data);
351                                                                delete _thisObject.requests[id];                                                               
352                                                                _thisObject.requests[id] = null;
353                                                        }
354
355                                                        break;
356
357                                                case 404:
358                                                       
359                                                        alert(get_lang('Page Not Found!'));
360                                                        break;
361
362                                                default:                                                                                               
363                                        }
364                                }
365                        }
366                        catch (e)
367                        {                       
368                                _thisObject.hideProgressBar();
369                                if(debug_controller)
370                                        alert(e+"\n"+oxmlhttp.responseText);
371                                // View Exception in Javascript Console
372                                throw(e);
373                        }
374                                               
375                }
376
377                try
378                {
379                       
380                        if (method == '' || method == 'GET')
381                        {                                                               
382                                oxmlhttp.open("GET",target,true);
383                                if (typeof(handler) == 'function')
384                                {       
385                                        oxmlhttp.onreadystatechange =  sub_handler;                                     
386                                        oxmlhttp.send(null);                                   
387                                }               
388                               
389                        }
390                        else if (method == 'POST')
391                        {
392                                oxmlhttp.open("POST",target, true);
393                                oxmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
394                                if (typeof(handler) == 'function')
395                                {
396                                        oxmlhttp.onreadystatechange = sub_handler;
397                                        oxmlhttp.send(data);
398                                }                               
399                               
400                        }
401                }
402                catch(e)
403                {       
404                        _thisObject.hideProgressBar();
405                        if(debug_controller)
406                                alert(e);
407                        // View Exception in Javascript Console 
408                        throw(e);
409                }
410                                               
411                return true;
412        }
413        // Cancel Request Connector
414        cConnector.prototype.cancelRequest = function (){
415                if (!this.requests[this.tid]){
416                        return false;
417                }
418                this.oxmlhttp.onreadystatechange = null;
419                this.requests[this.tid].abort();
420                this.hideProgressBar();
421        }
422//------------------------------------  END: Functions for Connector HTTPRequest  -------------------------------------------------//
423
424//      ----------------------------------- BEGIN: Functions for build Bar Progress ---------------------------------------------------------//
425        cConnector.prototype.hideProgressBar = function ()
426        {
427                var div = document.getElementById('divProgressBar');
428                div.style.visibility = 'hidden';
429                this.isVisibleBar = false;
430        }
431       
432        cConnector.prototype.showProgressBar = function(){
433                var div = document.getElementById('divProgressBar');
434                div.style.visibility = 'visible';                       
435
436                this.isVisibleBar = true;
437        }
438
439        cConnector.prototype.loadAllScripts = function(scripts) {       
440                for(var i = 0; i < scripts.length; i++){
441                        this.loadScript(scripts[i]);
442                }
443        }
444
445        cConnector.prototype.loadScript = function(scriptPath)  {
446        if (document.getElementById('uploadscript_'+scriptPath)) {
447                return;
448        }
449                var head = document.getElementsByTagName("head")[0];
450                var script = document.createElement("SCRIPT");
451                script.id = 'uploadscript_'+scriptPath;
452                script.type = 'text/javascript';
453               
454                if(is_ie) {
455               
456                        this.oxmlhttp.open("GET", "js/"+scriptPath+".js?"+this.updateVersion, false);
457            this.oxmlhttp.setRequestHeader('Content-Type','text/plain');
458                        this.oxmlhttp.send(null);
459                        if(this.oxmlhttp.status != 0 && this.oxmlhttp.status != 200 ||  this.oxmlhttp.status == 0 && this.oxmlhttp.responseText.length == 0)
460                                throw new Error("Error " + this.oxmlhttp.status + "("+this.oxmlhttp.statusText+") when loading script file '"+scriptPath+"'");
461                        script.text = this.oxmlhttp.responseText;                               
462                }
463                else {
464                        script.src =  "js/"+scriptPath+".js?"+this.updateVersion;
465                }
466
467                head.appendChild(script);
468                return;
469        }
470//------------------------------------  END: Functions for Progress Bar  -------------------------------------------------//
471        // Default Controller File
472        var DEFAULT_URL = 'controller.php?action=';
473        // connector object
474        var connector = new cConnector();
475        var _onmouseup = document.onmouseup;
476        var isExecuteForm = false;
477        var id = null;
478
479        var connectorCache = {
480                'valid' : [],
481                'result' : []
482        };
483        var expurgatedCache = new Array(); // Data to purge from cache
484
485        function queryConnectorCache(url,handler){
486                if (connectorCache.valid[url])
487                {
488                        handler(connectorCache.result[url]);
489                        return true;
490                }
491                else
492                        return false;
493        }
494        function purgeCache(){
495                if (typeof(preferences) == "undefined" || preferences.use_cache != 'True')
496                        return false;
497                var i;
498                for (i=0; i<= expurgatedCache.length; i++)
499                {
500                        connectorCache.valid[expurgatedCache[i]] = false;
501                        try {
502                        delete connectorCache.result[expurgatedCache[i]];
503                        }
504                        catch (e) { };
505                }
506        }
507        function addToCache(id,data){
508                if (typeof(preferences) == "undefined" || preferences.use_cache != 'True')
509                        return false;
510                var func = id.substr(id.lastIndexOf('.')+1);
511                if (func.indexOf('&') > 0)
512                        func = func.substr(0,func.indexOf('&'));
513                switch (func){
514                        // functions that enters in cache
515                        case 'get_info_msg':
516                                data.cacheHit = true;
517                        case 'get_preferences':
518                        case 'getSharedUsersFrom':
519                        case 'get_organizations':
520                        case 'get_catalogs':
521                        case 'get_dropdown_contacts':
522                        case 'get_cc_contacts':
523                        case 'get_cc_groups':
524                        case 'getUsersByEmail':
525                                connectorCache.valid[id] = true;
526                                connectorCache.result[id] = data;
527                                break;
528                        // function that needs expire
529                        case 'get_range_msgs2':
530                        case 'quicksearch':
531                        case 'get_folders_list':
532                        case 'search_msg':
533                        case 'search_for':
534                                connectorCache.valid[id] = true;
535                                connectorCache.result[id] = data;
536                                var i = expurgatedCache.length;
537                                expurgatedCache[i+1] = id;
538                                break;
539                        //functions that expires the cache
540                        case 'move_messages':
541                        case 'delete_msgs':
542                        case 'getReturnExecuteForm':
543                        case 'set_messages_flag':
544                        case 'empty_trash':
545                                purgeCache();
546                        default: // no cache
547                                break;
548                }
549        }
550
551        //      Function executes AJAX
552        //      cExecute (url, handler, params)
553        //      url: 'module.class.method'
554        //  handle: function handle() receive response.
555        //  params: parameters for POST method
556        //      form: form element (for upload files)   
557        function cExecute(url, handler, params, form) {
558                if(isExecuteForm){
559                        isExecuteForm = false;
560                        document.onmouseup = _onmouseup;
561                }
562                if(form) {
563                        cExecuteForm(url, form);
564                        return;
565                }
566
567                url = DEFAULT_URL + url;
568
569                if (queryConnectorCache(params?url+"&"+params:url,handler))
570                        return;
571
572                if(params)
573                        method = "POST";
574                else
575                        method = "GET";
576
577                id = url;
578                connector.newRequest(id, url, method, handler, params);
579        }
580
581// This function executes submit values to Controller (POST)
582        // The return is void.
583        //      cExecuteForm (url, form)
584        //      url: 'module.class.method'
585        //      form: form element (for upload files)   
586        function cExecuteForm(url, form, handler,id){
587                connector.buildBar();
588                isExecuteForm = true;
589               
590                document.onmouseup = alertBut;
591               
592                connector.showProgressBar();
593                if(! (divUpload = document.getElementById('divUpload'))) {
594                        divUpload               = document.createElement('DIV');               
595                        divUpload.id    = 'divUpload';
596                        document.body.appendChild(divUpload);
597                }
598
599                if(! (el = document.getElementById('_action'))) {                       
600                        el                      = document.createElement('input');
601                        el.type = 'hidden';
602                        el.id           = '_action';   
603                        el.name = '_action';
604                        form.appendChild(el);
605                }
606
607                var divFiles = Element("divFiles_"+id);         
608                if (divFiles && divFiles.firstChild) {
609                        el                      = document.createElement('input');
610                        el.type = 'hidden';     
611                        el.name = 'countFiles';
612                        var countDivFiles = 0;
613                        try{
614                                countDivFiles = parseInt(divFiles.lastChild.firstChild.id.split('_')[2]) + 1; // The id of last file
615                                }
616                        catch (e) { var countDivFiles = 0; };
617                        el.value        = countDivFiles ;
618                        form.appendChild(el);                                           
619                }               
620
621                form._action.value = url;
622                // Connector Bug fixing: Encapsulating returned handler function
623                handlerExecuteForm = handler;
624                var form_handler = function (data){
625                        handlerExecuteForm(data);
626                        handlerExecuteForm = null;
627                }
628                divUpload.innerHTML= "<iframe onload=\"cExecute('$this.functions.getReturnExecuteForm',"+form_handler+");\"  style='display:"+(debug_controller ? "" : "none")+";width:"+(debug_controller ? 400 : 0)+";height:"+(debug_controller ? 400 : 0)+";' name='uploadFile'></iframe>";
629                form.action ="controller.php";
630                form.target ="uploadFile";             
631                form.submit();
632                // Connector Bug fixing: Exclude '_action' element after cExecuteForm execution
633                if(el && el.id == '_action'){
634                        el.parentNode.removeChild(el);
635                }
636        }       
637       
638       
639        function alertBut(e) {
640                if(!e)
641                        e = window.event;
642
643            if(_onmouseup)
644                        _onmouseup(e);
645
646                if(isExecuteForm) {
647                if(confirm(get_lang("There's an action processing. Do you want abort it?"))) {
648                        connector.hideProgressBar();
649                        isExecuteForm = false;
650                        delete connector.requests[id];                                                         
651                                connector.requests[id] = null;
652                        stop();                                         
653                        return;
654                }
655                else
656                        return false;
657            }
658        }       
Note: See TracBrowser for help on using the repository browser.