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

Revision 2328, 16.6 KB checked in by niltonneto, 14 years ago (diff)

Ticket #926 - Código centralizado para validação de sessão no ExpressoAJAX.

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