source: trunk/phpgwapi/js/expressoAjax/expressoAjax.js @ 2521

Revision 2521, 16.3 KB checked in by rodsouza, 14 years ago (diff)

Ticket #1009 - Correção de problemas no ExpressoMail? ao carregar imagens.

Line 
1var debug_controller =false;
2var files = new Array();
3var progressBar;
4var handlerExecuteForm = null;
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.hold_session = false;
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.cacheRequest = null;
45                this.connectorCache = {
46                                'valid' : [],
47                                'result' : []
48                };
49                this.expurgatedCache = new Array(); // Data to purge from cache
50
51        }
52        cConnector.prototype.verify_session = function(data) {
53                if(data && data.nosession){
54                        // If hold session is setted, dont reload the page ...
55                        if(expresso.connector.hold_session) {
56                                if(typeof(write_msg) == "function" && typeof(get_lang) == "function")
57                                        write_msg(get_lang("your session could not be verified."));
58                                else
59                                        alert("your session could not be verified.");
60                        }
61                        else
62                                window.location.reload();
63                        return false;
64                }
65                else
66                        return true;
67        }
68        cConnector.prototype.buildBar = function()
69                {
70                        var div = document.getElementById('divProgressBar');
71
72                        if(! div) {
73                                div = document.createElement("DIV");
74                                div.style.visibility    = "hidden";
75                                div.style.width = "103px";
76                                div.id = 'divProgressBar';
77                                div.align = "center";
78                                var loadingTitle = document.getElementById('txt_loading');
79                                div.innerHTML = '&nbsp;&nbsp;<font face="Verdana" size="2" color="WHITE">'+loadingTitle.value+'...</font>&nbsp;';
80                                div.style.background = "#cc4444";
81                                div.style.position = 'fixed';
82                                div.style.top = '0px';
83                                div.style.right = '0px';
84                                document.body.appendChild(div);
85
86                                if(is_ie) {
87                                        var elem = document.all[div.id];
88                                        elem.style.position="absolute";
89                                        var root = document.body;
90                                        var posX = elem.offsetLeft-root.scrollLeft;
91                                        var posY = elem.offsetTop-root.scrollTop;
92                                        root.onscroll = function() {
93                                                elem.style.right = '0px';
94                                                elem.style.top = (posY + root.scrollTop) + "px";
95                                        };
96                                }
97
98                                if(debug_controller) {
99                                        div = document.createElement("DIV");
100                                        div.style.width = "800px";
101                                        div.style.height= "400px";
102                                        div.id = "debug_controller";
103                                        div.align='right';
104                                        document.body.appendChild(div);
105                                }
106                        }
107        }
108//------------------------------------ BEGIN: Functions for Connector HTTPRequest  -------------------------------------------------//
109        // Serialize Data Method
110        cConnector.prototype.serialize = function(data)
111        {       var _thisObject = this;
112                var f = function(data)
113                {
114                        var str_data;
115
116                        if (data == null ||
117                                (typeof(data) == 'string' && data == ''))
118                        {
119                                str_data = 'N;';
120                        }
121
122                        else switch(typeof(data))
123                        {
124                                case 'object':
125                                        var arrayCount = 0;
126
127                                        str_data = '';
128
129                                        for (i in data)
130                                        {
131                                                if (i == 'length')
132                                                {
133                                                        continue;
134                                                }
135
136                                                arrayCount++;
137                                                switch (typeof(i))
138                                                {
139                                                        case 'number':
140                                                                str_data += 'i:' + i + ';' + f(data[i]);
141                                                                break;
142
143                                                        case 'string':
144                                                                str_data += 's:' + i.length + ':"' + i + '";' + f(data[i]);
145                                                                break;
146
147                                                        default:
148                                                                showMessage(Element('cc_msg_err_serialize_data_unknown').value);
149                                                                break;
150                                                }
151                                        }
152
153                                        if (!arrayCount)
154                                        {
155                                                str_data = 'N;';
156                                        }
157                                        else
158                                        {
159                                                str_data = 'a:' + arrayCount + ':{' + str_data + '}';
160                                        }
161
162                                        break;
163
164                                case 'string':
165                                        str_data = 's:' + data.length + ':"' + data + '";';
166                                        break;
167
168                                case 'number':
169                                        str_data = 'i:' + data + ';';
170                                        break;
171
172                                case 'boolean':
173                                        str_data = 'b:' + (data ? '1' : '0') + ';';
174                                        break;
175
176                                default:
177                                        showMessage(Element('cc_msg_err_serialize_data_unknown').value);
178                                        return null;
179                        }
180
181                        return str_data;
182                }
183
184                return f(data);
185        }
186
187
188        //Unserialize Data Method
189        cConnector.prototype.unserialize = function(str)
190        {
191
192                _thisObject = this;
193                var matchB = function (str, iniPos)
194                {
195                        var nOpen, nClose = iniPos;
196                        do
197                        {
198                                nOpen = str.indexOf('{', nClose+1);
199                                nClose = str.indexOf('}', nClose+1);
200
201                                if (nOpen == -1)
202                                {
203                                        return nClose;
204                                }
205                                if (nOpen < nClose )
206                                {
207                                        nClose = matchB(str, nOpen);
208                                }
209                        } while (nOpen < nClose);
210
211                        return nClose;
212                }
213
214                var f = function (str)
215                {
216                        switch (str.toString().charAt(0))
217                        {
218                                case 'a':
219
220                                        var data = new Array();
221                                        var n = parseInt( str.substring( str.indexOf(':')+1, str.indexOf(':',2) ) );
222                                        var arrayContent = str.substring(str.indexOf('{')+1, str.lastIndexOf('}'));
223
224                                        for (var i = 0; i < n; i++)
225                                        {
226                                                var pos = 0;
227
228                                                /* Process Index */
229                                                var indexStr = arrayContent.substr(pos, arrayContent.indexOf(';')+1);
230                                                var index = f(indexStr);
231                                                pos = arrayContent.indexOf(';', pos)+1;
232
233                                                /* Process Content */
234                                                var part = null;
235                                                switch (arrayContent.charAt(pos))
236                                                {
237                                                        case 'a':
238                                                                var pos_ = matchB(arrayContent, arrayContent.indexOf('{', pos))+1;
239                                                                part = arrayContent.substring(pos, pos_);
240                                                                pos = pos_;
241                                                                data[index] = f(part);
242                                                                break;
243
244                                                        case 's':
245                                                                var pval = arrayContent.indexOf(':', pos+2);
246                                                                var val  = parseInt(arrayContent.substring(pos+2, pval));
247                                                                pos = pval + val + 4;
248                                                                data[index] = arrayContent.substr(pval+2, val);
249                                                                break;
250
251                                                        default:
252                                                                part = arrayContent.substring(pos, arrayContent.indexOf(';', pos)+1);
253                                                                pos = arrayContent.indexOf(';', pos)+1;
254                                                                data[index] = f(part);
255                                                                break;
256                                                }
257                                                arrayContent = arrayContent.substr(pos);
258                                        }
259                                        break;
260
261                                case 's':
262                                        var pos = str.indexOf(':', 2);
263                                        var val = parseInt(str.substring(2,pos));
264                                        var data = str.substr(pos+2, val);
265                                        str = str.substr(pos + 4 + val);
266                                        break;
267
268                                case 'i':
269                                case 'd':
270                                        var pos = str.indexOf(';');
271                                        var data = parseInt(str.substring(2,pos));
272                                        str = str.substr(pos + 1);
273                                        break;
274
275                                case 'N':
276                                        var data = null;
277                                        str = str.substr(str.indexOf(';') + 1);
278                                        break;
279
280                                case 'b':
281                                        var data = str.charAt(2) == '1' ? true : false;
282                                        break;
283                        }
284                        return data;
285                }
286
287                return f(str);
288        }
289
290        //Create XMLHTTP object Method
291        cConnector.prototype.createXMLHTTP = function ()
292        {
293                try
294                {
295                        this.oxmlhttp = new XMLHttpRequest();
296                        this.oxmlhttp.overrideMimeType('text/xml');
297                }
298                catch (e)
299                {
300                        try
301                        {
302                                this.oxmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
303                        }
304                        catch (e1)
305                        {
306                                try
307                                {
308                                        this.oxmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
309                                }
310                                catch (e2)
311                                {
312                                        this.oxmlhttp = null;
313                                }
314                        }
315                }
316
317        }
318
319        // Request Constructor Connector
320        cConnector.prototype.newRequest = function (id, target, method, handler, data)
321        {
322                this.tid = id;
323                if (this.requests[id]) {
324                        return false;
325                }
326
327                this.createXMLHTTP();
328                var oxmlhttp = this.oxmlhttp;
329                var _thisObject = this;
330
331                if (! oxmlhttp)
332                        return false;
333
334                this.requests[id] = oxmlhttp;
335                this.buildBar();
336                this.showProgressBar();
337
338                var sub_handler = function ()
339                {
340                        try
341                        {
342                                if (oxmlhttp.readyState == 4 )
343                                {
344
345                                        switch (oxmlhttp.status)
346                                        {
347
348                                                case 200:
349                                                        if (typeof(handler) == 'function')
350                                                        {
351                                                                _thisObject.hideProgressBar();
352                                                                var data = _thisObject.unserialize(oxmlhttp.responseText);
353                                                                if ( typeof data == 'undefined' )
354                                                                        data = oxmlhttp.responseText;
355                                                                // Verify user session
356                                                                if(!_thisObject.verify_session(data)){
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                                                                _thisObject.addToCache(data?id+"&"+data: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", URL_SERVER + "/expressoMail1_2/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 =  URL_SERVER + "/expressoMail1_2/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 URL_DEFAULT = URL_SERVER+'/controller.php?action=';
489        // connector object
490        var _onmouseup = document.onmouseup;
491        var isExecuteForm = false;
492        var id = null;
493
494        cConnector.prototype.queryConnectorCache = function(url,handler){
495                if (this.connectorCache.valid[url])
496                {
497                        handler(this.connectorCache.result[url]);
498                        return true;
499                }
500                else
501                        return false;
502        }
503        cConnector.prototype.purgeCache= function(){
504                if (typeof(preferences) == "undefined" || preferences.use_cache != 'True')
505                        return false;
506                var i;
507                for (i=0; i<= this.expurgatedCache.length; i++)
508                {
509                        this.connectorCache.valid[this.expurgatedCache[i]] = false;
510                        try {
511                        delete this.connectorCache.result[this.expurgatedCache[i]];
512                        }
513                        catch (e) { };
514                }
515        }
516        cConnector.prototype.cacheNextRequest = function(expiration){
517                if (typeof(expiration) == 'undefined')
518                        expiration=0;
519                this.cacheRequest=expiration;
520        }
521
522        cConnector.prototype.addToCache = function(id,data){
523                if (typeof(preferences) == "undefined" || preferences.use_cache != 'True')
524                        return false;
525                var func = id.substr(id.lastIndexOf('.')+1);
526                if (func.indexOf('&') > 0)
527                        func = func.substr(0,func.indexOf('&'));
528                switch (this.cacheRequest){
529                        // functions that enters in cache and never expires
530                        case 0:
531                                data.cacheHit = true;
532                                this.connectorCache.valid[id] = true;
533                                this.connectorCache.result[id] = data;
534                                break;
535                        case 1:
536                        // function that needs expire
537                                this.connectorCache.valid[id] = true;
538                                this.connectorCache.result[id] = data;
539                                var i = this.expurgatedCache.length;
540                                this.expurgatedCache[i+1] = id;
541                                break;
542                        default:
543                        // no cache
544                                break;
545                }
546        }
547
548        //      Function executes AJAX
549        //      cExecute (url, handler, params)
550        //      url: 'module.class.method'
551        //  handle: function handle() receive response.
552        //  params: parameters for POST method
553        //      form: form element (for upload files)
554        function cExecute(url, handler, params, form) {
555                if(isExecuteForm){
556                        isExecuteForm = false;
557                        document.onmouseup = _onmouseup;
558                }
559                if(form) {
560                        cExecuteForm(url, form);
561                        return;
562                }
563                url = URL_DEFAULT + url;
564
565                if (expresso.connector.queryConnectorCache(params?url+"&"+params:url,handler))
566                        return;
567
568                if(params)
569                        method = "POST";
570                else
571                        method = "GET";
572
573                id = url;
574                expresso.connector.newRequest(id, url, method, handler, params);
575        }
576
577// This function executes submit values to Controller (POST)
578        // The return is void.
579        //      cExecuteForm (url, form)
580        //      url: 'module.class.method'
581        //      form: form element (for upload files)
582        function cExecuteForm(url, form, handler,id){
583                expresso.connector.buildBar();
584                isExecuteForm = true;
585
586                document.onmouseup = alertBut;
587
588                expresso.connector.showProgressBar();
589                if(! (divUpload = document.getElementById('divUpload'))) {
590                        divUpload               = document.createElement('DIV');
591                        divUpload.id    = 'divUpload';
592                        document.body.appendChild(divUpload);
593                }
594
595                if(! (el = document.getElementById('_action'))) {
596                        el                      = document.createElement('input');
597                        el.type = 'hidden';
598                        el.id           = '_action';
599                        el.name = '_action';
600                        form.appendChild(el);
601                }
602
603                var divFiles = document.getElementById("divFiles_"+id);
604                if (divFiles && divFiles.firstChild) {
605                        el                      = document.createElement('input');
606                        el.type = 'hidden';
607                        el.name = 'countFiles';
608                        var countDivFiles = 0;
609                        try{
610                                countDivFiles = parseInt(divFiles.lastChild.firstChild.id.split('_')[2]) + 1; // The id of last file
611                                }
612                        catch (e) { var countDivFiles = 0; };
613                        el.value        = countDivFiles ;
614                        form.appendChild(el);
615                }
616
617                form._action.value = url;
618                // Connector Bug fixing: Encapsulating returned handler function
619                handlerExecuteForm = handler;
620                var form_handler = function (data){
621                        handlerExecuteForm(data);
622                        handlerExecuteForm = null;
623                }
624                divUpload.innerHTML= "<iframe onload=\"cExecute('expressoMail1_2.functions.getReturnExecuteForm',"+form_handler+");\"  style='display:"+(debug_controller ? "" : "none")+";width:"+(debug_controller ? 400 : 0)+";height:"+(debug_controller ? 400 : 0)+";' name='uploadFile'></iframe>";
625                form.action = URL_SERVER + "/controller.php";
626                form.target ="uploadFile";
627                form.submit();
628                // Connector Bug fixing: Exclude '_action' element after cExecuteForm execution
629                if(el && el.id == '_action'){
630                        el.parentNode.removeChild(el);
631                }
632        }
633
634
635        function alertBut(e) {
636                if(!e)
637                        e = window.event;
638
639            if(_onmouseup)
640                        _onmouseup(e);
641
642                if(isExecuteForm) {
643                if(confirm(get_lang("There's an action processing. Do you want abort it?"))) {
644                        expresso.connector.hideProgressBar();
645                        isExecuteForm = false;
646                        delete expresso.connector.requests[id];
647                                expresso.connector.requests[id] = null;
648                        stop();
649                        return;
650                }
651                else
652                        return false;
653            }
654        }
655
656function expressoAjax(){
657        this.connector = new cConnector();
658
659}
660expressoAjax.prototype.require = function (module){
661        expresso.connector.loadScript(module);
662}
663var expresso = new expressoAjax();
Note: See TracBrowser for help on using the repository browser.