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

Revision 2013, 15.9 KB checked in by amuller, 14 years ago (diff)

Ticket #911 - Correção temporariamente até resolução

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.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                this.connectorCache = {
44                                'valid' : [],
45                                'result' : []
46                };
47                this.expurgatedCache = new Array(); // Data to purge from cache
48
49        }
50
51        cConnector.prototype.buildBar = function()
52                {
53                        var div = document.getElementById('divProgressBar');
54
55                        if(! div) {
56                                div = document.createElement("DIV");
57                                div.style.visibility    = "hidden";
58                                div.style.width = "103px";
59                                div.id = 'divProgressBar';
60                                div.align = "center";
61                                var loadingTitle = document.getElementById('txt_loading');
62                                div.innerHTML = '&nbsp;&nbsp;<font face="Verdana" size="2" color="WHITE">'+loadingTitle.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.toString().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 URL_DEFAULT = '/expresso/controller.php?action=';
469        // connector object
470        var _onmouseup = document.onmouseup;
471        var isExecuteForm = false;
472        var id = null;
473
474        cConnector.prototype.queryConnectorCache = function(url,handler){
475                if (this.connectorCache.valid[url])
476                {
477                        handler(this.connectorCache.result[url]);
478                        return true;
479                }
480                else
481                        return false;
482        }
483        cConnector.prototype.purgeCache= function(){
484                if (typeof(preferences) == "undefined" || preferences.use_cache != 'True')
485                        return false;
486                var i;
487                for (i=0; i<= this.expurgatedCache.length; i++)
488                {
489                        this.connectorCache.valid[this.expurgatedCache[i]] = false;
490                        try {
491                        delete this.connectorCache.result[this.expurgatedCache[i]];
492                        }
493                        catch (e) { };
494                }
495        }
496        cConnector.prototype.addToCache = function(id,data){
497                if (typeof(preferences) == "undefined" || preferences.use_cache != 'True')
498                        return false;
499                var func = id.substr(id.lastIndexOf('.')+1);
500                if (func.indexOf('&') > 0)
501                        func = func.substr(0,func.indexOf('&'));
502                switch (func){
503                        // functions that enters in cache
504                        case 'get_info_msg':
505                                data.cacheHit = true;
506                        case 'get_preferences':
507                        case 'getSharedUsersFrom':
508                        case 'get_organizations':
509                        case 'get_catalogs':
510                        case 'get_dropdown_contacts':
511                        case 'get_cc_contacts':
512                        case 'get_cc_groups':
513                        case 'getUsersByEmail':
514                                this.connectorCache.valid[id] = true;
515                                this.connectorCache.result[id] = data;
516                                break;
517                        // function that needs expire
518                        case 'get_range_msgs2':
519                        case 'quicksearch':
520                        case 'get_folders_list':
521                        case 'search_msg':
522                        case 'search_for':
523                                this.connectorCache.valid[id] = true;
524                                this.connectorCache.result[id] = data;
525                                var i = this.expurgatedCache.length;
526                                this.expurgatedCache[i+1] = id;
527                                break;
528                        //functions that expires the cache
529                        case 'move_messages':
530                        case 'delete_msgs':
531                        case 'getReturnExecuteForm':
532                        case 'set_messages_flag':
533                        case 'empty_trash':
534                                this.purgeCache();
535                        default: // no cache
536                                break;
537                }
538        }
539
540        //      Function executes AJAX
541        //      cExecute (url, handler, params)
542        //      url: 'module.class.method'
543        //  handle: function handle() receive response.
544        //  params: parameters for POST method
545        //      form: form element (for upload files)
546        function cExecute(url, handler, params, form) {
547                if(isExecuteForm){
548                        isExecuteForm = false;
549                        document.onmouseup = _onmouseup;
550                }
551                if(form) {
552                        cExecuteForm(url, form);
553                        return;
554                }
555                url = URL_DEFAULT + url;
556
557                if (expresso.connector.queryConnectorCache(params?url+"&"+params:url,handler))
558                        return;
559
560                if(params)
561                        method = "POST";
562                else
563                        method = "GET";
564
565                id = url;
566                expresso.connector.newRequest(id, url, method, handler, params);
567        }
568
569// This function executes submit values to Controller (POST)
570        // The return is void.
571        //      cExecuteForm (url, form)
572        //      url: 'module.class.method'
573        //      form: form element (for upload files)
574        function cExecuteForm(url, form, handler,id){
575                expresso.connector.buildBar();
576                isExecuteForm = true;
577
578                document.onmouseup = alertBut;
579
580                expresso.connector.showProgressBar();
581                if(! (divUpload = document.getElementById('divUpload'))) {
582                        divUpload               = document.createElement('DIV');
583                        divUpload.id    = 'divUpload';
584                        document.body.appendChild(divUpload);
585                }
586
587                if(! (el = document.getElementById('_action'))) {
588                        el                      = document.createElement('input');
589                        el.type = 'hidden';
590                        el.id           = '_action';
591                        el.name = '_action';
592                        form.appendChild(el);
593                }
594
595                var divFiles = Element("divFiles_"+id);
596                if (divFiles && divFiles.firstChild) {
597                        el                      = document.createElement('input');
598                        el.type = 'hidden';
599                        el.name = 'countFiles';
600                        var countDivFiles = 0;
601                        try{
602                                countDivFiles = parseInt(divFiles.lastChild.firstChild.id.split('_')[2]) + 1; // The id of last file
603                                }
604                        catch (e) { var countDivFiles = 0; };
605                        el.value        = countDivFiles ;
606                        form.appendChild(el);
607                }
608
609                form._action.value = url;
610                // Connector Bug fixing: Encapsulating returned handler function
611                handlerExecuteForm = handler;
612                var form_handler = function (data){
613                        handlerExecuteForm(data);
614                        handlerExecuteForm = null;
615                }
616                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>";
617                form.action ="controller.php";
618                form.target ="uploadFile";
619                form.submit();
620                // Connector Bug fixing: Exclude '_action' element after cExecuteForm execution
621                if(el && el.id == '_action'){
622                        el.parentNode.removeChild(el);
623                }
624        }
625
626
627        function alertBut(e) {
628                if(!e)
629                        e = window.event;
630
631            if(_onmouseup)
632                        _onmouseup(e);
633
634                if(isExecuteForm) {
635                if(confirm(get_lang("There's an action processing. Do you want abort it?"))) {
636                        expresso.connector.hideProgressBar();
637                        isExecuteForm = false;
638                        delete expresso.connector.requests[id];
639                                expresso.connector.requests[id] = null;
640                        stop();
641                        return;
642                }
643                else
644                        return false;
645            }
646        }
647
648function expressoAjax(){
649        this.connector = new cConnector();
650
651}
652expressoAjax.prototype.require = function (module){
653        expresso.connector.loadScript(module);
654}
655var expresso = new expressoAjax();
Note: See TracBrowser for help on using the repository browser.