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

Revision 1444, 16.1 KB checked in by amuller, 15 years ago (diff)

Ticket #653 - Melhoria de performance do serialize e unserialize

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