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

Revision 660, 15.7 KB checked in by niltonneto, 15 years ago (diff)

Resolve #422

  • 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 expurgatedCache = new Array(); // Data to purge from cache
482
483        function queryConnectorCache(url,handler){
484                if (connectorCache.valid[url])
485                {
486                        handler(connectorCache.result[url]);
487                        return true;
488                }
489                else
490                        return false;
491        }
492        function purgeCache(){
493                var i;
494                for (i=0; i<= expurgatedCache.length; i++)
495                {
496                        connectorCache.valid[expurgatedCache[i]] = false;
497                        delete connectorCache.result[expurgatedCache[i]];
498                }
499        }
500        function addToCache(id,data){
501                if (typeof(preferences) == "undefined" || preferences.use_cache != 'True')
502                        return false;
503                var func = id.substr(id.lastIndexOf('.')+1);
504                if (func.indexOf('&') > 0)
505                        func = func.substr(0,func.indexOf('&'));
506                switch (func){
507                        // functions that enters in cache
508                        case 'get_info_msg':
509                                data.cacheHit = true;
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 'getUsersByEmail':
518                        case 'br':
519                        case 'search_for':                     
520                                connectorCache.valid[id] = true;
521                                connectorCache.result[id] = data;
522                                break;
523                        // function that needs expire
524                        case 'get_range_msgs2':
525                        case 'quicksearch':
526                        case 'get_folders_list':
527//                      case 'search_msg':
528                                connectorCache.valid[id] = true;
529                                connectorCache.result[id] = data;
530                                var i = expurgatedCache.length;
531                                expurgatedCache[i+1] = id;
532                                break;
533                        //functions that expires the cache
534                        case 'move_messages':
535                        case 'delete_msgs':
536                        case 'getReturnExecuteForm':
537                        case 'set_messages_flag':
538                        case 'empty_trash':
539                                purgeCache();
540                        default: // no cache
541                                break;
542                }
543        }
544
545        //      Function executes AJAX
546        //      cExecute (url, handler, params)
547        //      url: 'module.class.method'
548        //  handle: function handle() receive response.
549        //  params: parameters for POST method
550        //      form: form element (for upload files)   
551        function cExecute(url, handler, params, form) {
552                if(isExecuteForm){
553                        isExecuteForm = false;
554                        document.onmouseup = _onmouseup;
555                }
556                if(form) {
557                        cExecuteForm(url, form);
558                        return;
559                }
560
561                url = DEFAULT_URL + url;
562
563                if (queryConnectorCache(url,handler))
564                        return;
565
566                if(params)
567                        method = "POST";
568                else
569                        method = "GET";
570
571                id = url;
572                connector.newRequest(id, url, method, handler, params);
573        }
574
575// This function executes submit values to Controller (POST)
576        // The return is void.
577        //      cExecuteForm (url, form)
578        //      url: 'module.class.method'
579        //      form: form element (for upload files)   
580        function cExecuteForm(url, form, handler,id){
581                connector.buildBar();
582                isExecuteForm = true;           
583                document.onmouseup = alertBut;
584
585                connector.showProgressBar();
586                if(! (divUpload = document.getElementById('divUpload'))) {
587                        divUpload               = document.createElement('DIV');               
588                        divUpload.id    = 'divUpload';
589                        document.body.appendChild(divUpload);
590                }
591
592                if(! (el = document.getElementById('_action'))) {                       
593                        el                      = document.createElement('input');
594                        el.type = 'hidden';
595                        el.id           = '_action';   
596                        el.name = '_action';
597                        form.appendChild(el);
598                }
599
600                var divFiles = Element("divFiles_"+id);         
601                if (divFiles && divFiles.firstChild) {
602                        el                      = document.createElement('input');
603                        el.type = 'hidden';     
604                        el.name = 'countFiles';
605                        var countDivFiles = 0;
606                        try{
607                                countDivFiles = parseInt(divFiles.lastChild.firstChild.id.split('_')[2]) + 1; // The id of last file
608                                }
609                        catch (e) { var countDivFiles = 0; };
610                        el.value        = countDivFiles ;
611                        form.appendChild(el);                                           
612                }               
613
614                form._action.value = url;
615                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>";
616                form.action ="controller.php";
617                form.target ="uploadFile";             
618                form.submit();
619        }       
620       
621       
622        function alertBut(e) {
623                if(!e)
624                        e = window.event;
625
626            if(_onmouseup)
627                        _onmouseup(e);
628
629                if(isExecuteForm) {
630                if(confirm(get_lang("There's an action processing. Do you want abort it?"))) {
631                        connector.hideProgressBar();
632                        isExecuteForm = false;
633                        delete connector.requests[id];                                                         
634                                connector.requests[id] = null;
635                        stop();                                         
636                        return;
637                }
638                else
639                        return false;
640            }
641        }       
Note: See TracBrowser for help on using the repository browser.