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

Revision 2402, 16.4 KB checked in by amuller, 14 years ago (diff)

Ticket #1022 - Mudando critérios de req. ao entrar na cache/

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