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

Revision 584, 15.6 KB checked in by niltonneto, 15 years ago (diff)

Correção do connector devido ao cache.

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