source: branches/2.0/expressoMail1_2/js/connector.js @ 2391

Revision 2391, 16.8 KB checked in by niltonneto, 14 years ago (diff)

Ticket #1018 - Corrigido validação de sessão em requisições AJAX.

  • 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                                                                // Verify user session
346                                                                if(data && data.nosession){
347                                                                // If hold session is setted, dont reload the page ...
348                                                                        if(hold_session) {
349                                                                                if(typeof(write_msg) == "function" && typeof(get_lang) == "function")
350                                                                                        write_msg(get_lang("your session could not be verified."));
351                                                                                else
352                                                                                        alert("your session could not be verified.");
353                                                                        }
354                                                                        else
355                                                                                window.location.reload();
356
357                                                                        delete _thisObject.requests[id];
358                                                                        _thisObject.requests[id] = null;
359                                                                        return false;
360                                                                }
361                                                                if(debug_controller) {
362                                                                        document.getElementById("debug_controller").innerHTML += oxmlhttp.responseText;
363                                                                        document.getElementById("debug_controller").innerHTML += "<br>-------------------------------------------------------------------------------------<br>";
364                                                                }
365                                                                handler(data);
366                                                                addToCache(params?id+"&"+params:id,data);
367                                                                delete _thisObject.requests[id];                                                               
368                                                                _thisObject.requests[id] = null;
369                                                        }
370
371                                                        break;
372
373                                                case 404:
374                                                       
375                                                        alert(get_lang('Page Not Found!'));
376                                                        break;
377
378                                                default:                                                                                               
379                                        }
380                                }
381                        }
382                        catch (e)
383                        {                       
384                                _thisObject.hideProgressBar();
385                                if(debug_controller)
386                                        alert(e+"\n"+oxmlhttp.responseText);
387                                // View Exception in Javascript Console
388                                throw(e);
389                        }
390                                               
391                }
392
393                try
394                {
395                       
396                        if (method == '' || method == 'GET')
397                        {                                                               
398                                oxmlhttp.open("GET",target,true);
399                                if (typeof(handler) == 'function')
400                                {       
401                                        oxmlhttp.onreadystatechange =  sub_handler;                                     
402                                        oxmlhttp.send(null);                                   
403                                }               
404                               
405                        }
406                        else if (method == 'POST')
407                        {
408                                oxmlhttp.open("POST",target, true);
409                                oxmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
410                                if (typeof(handler) == 'function')
411                                {
412                                        oxmlhttp.onreadystatechange = sub_handler;
413                                        oxmlhttp.send(data);
414                                }                               
415                               
416                        }
417                }
418                catch(e)
419                {       
420                        _thisObject.hideProgressBar();
421                        if(debug_controller)
422                                alert(e);
423                        // View Exception in Javascript Console 
424                        throw(e);
425                }
426                                               
427                return true;
428        }
429        // Cancel Request Connector
430        cConnector.prototype.cancelRequest = function (){
431                if (!this.requests[this.tid]){
432                        return false;
433                }
434                this.oxmlhttp.onreadystatechange = null;
435                this.requests[this.tid].abort();
436                this.hideProgressBar();
437        }
438//------------------------------------  END: Functions for Connector HTTPRequest  -------------------------------------------------//
439
440//      ----------------------------------- BEGIN: Functions for build Bar Progress ---------------------------------------------------------//
441        cConnector.prototype.hideProgressBar = function ()
442        {
443                var div = document.getElementById('divProgressBar');
444                div.style.visibility = 'hidden';
445                this.isVisibleBar = false;
446        }
447       
448        cConnector.prototype.showProgressBar = function(){
449                var div = document.getElementById('divProgressBar');
450                div.style.visibility = 'visible';                       
451
452                this.isVisibleBar = true;
453        }
454
455        cConnector.prototype.loadAllScripts = function(scripts) {       
456                for(var i = 0; i < scripts.length; i++){
457                        this.loadScript(scripts[i]);
458                }
459        }
460
461        cConnector.prototype.loadScript = function(scriptPath)  {
462        if (document.getElementById('uploadscript_'+scriptPath)) {
463                return;
464        }
465                var head = document.getElementsByTagName("head")[0];
466                var script = document.createElement("SCRIPT");
467                script.id = 'uploadscript_'+scriptPath;
468                script.type = 'text/javascript';
469               
470                if(is_ie) {
471               
472                        this.oxmlhttp.open("GET", "js/"+scriptPath+".js?"+this.updateVersion, false);
473            this.oxmlhttp.setRequestHeader('Content-Type','text/plain');
474                        this.oxmlhttp.send(null);
475                        if(this.oxmlhttp.status != 0 && this.oxmlhttp.status != 200 ||  this.oxmlhttp.status == 0 && this.oxmlhttp.responseText.length == 0)
476                                throw new Error("Error " + this.oxmlhttp.status + "("+this.oxmlhttp.statusText+") when loading script file '"+scriptPath+"'");
477                        script.text = this.oxmlhttp.responseText;                               
478                }
479                else {
480                        script.src =  "js/"+scriptPath+".js?"+this.updateVersion;
481                }
482
483                head.appendChild(script);
484                return;
485        }
486//------------------------------------  END: Functions for Progress Bar  -------------------------------------------------//
487        // Default Controller File
488        var DEFAULT_URL = 'controller.php?action=';
489        // connector object
490        var connector = new cConnector();
491        var _onmouseup = document.onmouseup;
492        var isExecuteForm = false;
493        var id = null;
494
495        var connectorCache = {
496                'valid' : [],
497                'result' : []
498        };
499        var expurgatedCache = new Array(); // Data to purge from cache
500
501        function queryConnectorCache(url,handler){
502                if (connectorCache.valid[url])
503                {
504                        handler(connectorCache.result[url]);
505                        return true;
506                }
507                else
508                        return false;
509        }
510        function purgeCache(){
511                if (typeof(preferences) == "undefined" || preferences.use_cache != 'True')
512                        return false;
513                var i;
514                for (i=0; i<= expurgatedCache.length; i++)
515                {
516                        connectorCache.valid[expurgatedCache[i]] = false;
517                        try {
518                        delete connectorCache.result[expurgatedCache[i]];
519                        }
520                        catch (e) { };
521                }
522        }
523        function addToCache(id,data){
524                if (typeof(preferences) == "undefined" || preferences.use_cache != 'True')
525                        return false;
526                var func = id.substr(id.lastIndexOf('.')+1);
527                if (func.indexOf('&') > 0)
528                        func = func.substr(0,func.indexOf('&'));
529                switch (func){
530                        // functions that enters in cache
531                        case 'get_info_msg':
532                                data.cacheHit = true;
533                        case 'get_preferences':
534                        case 'getSharedUsersFrom':
535                        case 'get_organizations':
536                        case 'get_catalogs':
537                        case 'get_dropdown_contacts':
538                        case 'get_cc_contacts':
539                        case 'get_cc_groups':
540                        case 'getUsersByEmail':
541                                connectorCache.valid[id] = true;
542                                connectorCache.result[id] = data;
543                                break;
544                        // function that needs expire
545                        case 'get_range_msgs2':
546                        case 'quicksearch':
547                        case 'get_folders_list':
548                        case 'search_msg':
549                        case 'search_for':
550                                connectorCache.valid[id] = true;
551                                connectorCache.result[id] = data;
552                                var i = expurgatedCache.length;
553                                expurgatedCache[i+1] = id;
554                                break;
555                        //functions that expires the cache
556                        case 'move_messages':
557                        case 'delete_msgs':
558                        case 'getReturnExecuteForm':
559                        case 'set_messages_flag':
560                        case 'empty_trash':
561                                purgeCache();
562                        default: // no cache
563                                break;
564                }
565        }
566
567        //      Function executes AJAX
568        //      cExecute (url, handler, params)
569        //      url: 'module.class.method'
570        //  handle: function handle() receive response.
571        //  params: parameters for POST method
572        //      form: form element (for upload files)   
573        function cExecute(url, handler, params, form) {
574                if(isExecuteForm){
575                        isExecuteForm = false;
576                        document.onmouseup = _onmouseup;
577                }
578                if(form) {
579                        cExecuteForm(url, form);
580                        return;
581                }
582
583                url = DEFAULT_URL + url;
584
585                if (queryConnectorCache(params?url+"&"+params:url,handler))
586                        return;
587
588                if(params)
589                        method = "POST";
590                else
591                        method = "GET";
592
593                id = url;
594                connector.newRequest(id, url, method, handler, params);
595        }
596
597// This function executes submit values to Controller (POST)
598        // The return is void.
599        //      cExecuteForm (url, form)
600        //      url: 'module.class.method'
601        //      form: form element (for upload files)   
602        function cExecuteForm(url, form, handler,id){
603                connector.buildBar();
604                isExecuteForm = true;
605               
606                document.onmouseup = alertBut;
607               
608                connector.showProgressBar();
609                if(! (divUpload = document.getElementById('divUpload'))) {
610                        divUpload               = document.createElement('DIV');               
611                        divUpload.id    = 'divUpload';
612                        document.body.appendChild(divUpload);
613                }
614
615                if(! (el = document.getElementById('_action'))) {                       
616                        el                      = document.createElement('input');
617                        el.type = 'hidden';
618                        el.id           = '_action';   
619                        el.name = '_action';
620                        form.appendChild(el);
621                }
622
623                var divFiles = Element("divFiles_"+id);         
624                if (divFiles && divFiles.firstChild) {
625                        el                      = document.createElement('input');
626                        el.type = 'hidden';     
627                        el.name = 'countFiles';
628                        var countDivFiles = 0;
629                        try{
630                                countDivFiles = parseInt(divFiles.lastChild.firstChild.id.split('_')[2]) + 1; // The id of last file
631                                }
632                        catch (e) { var countDivFiles = 0; };
633                        el.value        = countDivFiles ;
634                        form.appendChild(el);                                           
635                }               
636
637                form._action.value = url;
638                // Connector Bug fixing: Encapsulating returned handler function
639                handlerExecuteForm = handler;
640                var form_handler = function (data){
641                        handlerExecuteForm(data);
642                        handlerExecuteForm = null;
643                }
644                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>";
645                form.action ="controller.php";
646                form.target ="uploadFile";             
647                form.submit();
648                // Connector Bug fixing: Exclude '_action' element after cExecuteForm execution
649                if(el && el.id == '_action'){
650                        el.parentNode.removeChild(el);
651                }
652        }       
653       
654       
655        function alertBut(e) {
656                if(!e)
657                        e = window.event;
658
659            if(_onmouseup)
660                        _onmouseup(e);
661
662                if(isExecuteForm) {
663                if(confirm(get_lang("There's an action processing. Do you want abort it?"))) {
664                        connector.hideProgressBar();
665                        isExecuteForm = false;
666                        delete connector.requests[id];                                                         
667                                connector.requests[id] = null;
668                        stop();                                         
669                        return;
670                }
671                else
672                        return false;
673            }
674        }       
Note: See TracBrowser for help on using the repository browser.