source: branches/2.5/expressoMail1_2/js/connector.js @ 7919

Revision 7919, 17.9 KB checked in by douglas, 11 years ago (diff)

Ticket #3360 - Verificar inconsistência na exibição de alertas

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