source: trunk/expressoMail1_2/js/local_messages.js @ 2096

Revision 2096, 54.6 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #933 - Correção do problema descrito no ticket em questão.

Line 
1/**
2 * @author diogenes
3 */
4
5        function local_messages() {
6                this.dbGears = null;
7                this.localServer = null;
8                this.store = null;
9        }
10
11        function HeaderFlags()
12        {
13            this.Answered = 0;
14            //this.Draft = 0;
15            this.Flagged = 0;
16            this.Recent = 0;
17        }
18
19        HeaderFlags.prototype.getAnswered = function()
20        {
21            return this.Answered;
22        }
23
24        HeaderFlags.prototype.setAnswered = function(answered)
25        {
26            this.Answered = answered;
27        }
28
29        //HeaderFlags.prototype.getDraft = function()
30        //{
31        //    return this.Draft;
32        //}
33
34        HeaderFlags.prototype.setDraft = function(draft)
35        {
36            this.Draft = draft;
37        }
38
39        HeaderFlags.prototype.getFlagged = function()
40        {
41            return this.Flagged;
42        }
43
44        HeaderFlags.prototype.setFlagged = function(flagged)
45        {
46            this.Flagged = flagged;
47        }
48
49        HeaderFlags.prototype.getRecent = function()
50        {
51            return this.Recent;
52        }
53
54        HeaderFlags.prototype.setRecent = function(recent)
55        {
56            this.Recent = recent;
57        }
58
59        function FlagsParser(headerObj)
60        {
61            this.Header = headerObj;
62        }
63
64        FlagsParser.prototype.parse = function()
65        {
66            var tmp = null;
67            if (typeof this.Header == 'string')
68            {
69                tmp = expresso.connector.unserialize(this.Header);
70            }
71            else
72            {
73                tmp = this.Header;
74            }
75
76            flags = new HeaderFlags();
77
78            if (tmp.Answered && tmp.Answered.match(/^A$/))
79            {
80                flags.setAnswered(1);
81                //if (tmp.Draft && tmp.Draft.match(/^X$/))
82                //{
83                //    flags.setDraft(1);
84                //}
85            }
86
87            if (tmp.Flagged && tmp.Flagged.match(/^F$/)){
88                flags.setFlagged(1);
89            }
90
91            if (tmp.Forwarded && tmp.Forwarded.match(/^F$/)){
92                flags.setAnswered(1);
93                //flags.setDraft(1);
94            }
95
96            if (tmp.Recent && tmp.Recent.match(/^R$/)){
97                flags.setRecent(1);
98            }
99
100            return flags;
101
102        }
103       
104        local_messages.prototype.installGears = function (){
105                temp = confirm(get_lang("To use local messages you have to install google gears. Would you like to install it now?"));
106                if (temp && typeof(preferences.googlegears_url) != 'undefined'){
107                        if (is_ie)
108                                location.href = preferences.googlegears_url + "/gears.exe";
109                        else
110                                location.href = preferences.googlegears_url + "/gears.xpi";
111                        return false;
112                }
113                if (temp) {
114                        location.href = "http://gears.google.com/?action=install&message="+
115                                get_lang("To use local messages, install Google Gears")+"&return=" + document.location.href;
116                }
117                else return false;
118        }
119
120        local_messages.prototype.create_objects = function() {
121                try {
122                        if(this.dbGears == null)
123                                this.dbGears = google.gears.factory.create('beta.database');
124                        if(this.localServer == null)
125                                this.localServer = google.gears.factory.create('beta.localserver');
126                        if(this.store == null)
127                                this.store = this.localServer.createStore('test-store');
128                }
129                catch(e){}
130        }
131
132        local_messages.prototype.init_local_messages = function(){ //starts only database operations
133               
134                if(this.dbGears==null || this.localServer==null || this.store == null)
135                        this.create_objects();
136               
137                var db_in_other_use = true;
138                var start_trying = new Date().getTime();
139                while (db_in_other_use) {
140                        try {
141                                this.dbGears.open('database-test');
142                                db_in_other_use = false;
143                        }
144                        catch (ex) {
145                                if(new Date().getTime()-start_trying>10000) { //too much time trying, throw an exception
146                                        throw ex;
147                                }
148                        }
149                }
150                       
151//              this.dbGears.open('database-test');
152                this.dbGears.execute('create table if not exists folder (folder text,uid_usuario int,unique(folder,uid_usuario))');
153                this.dbGears.execute('create table if not exists mail' +
154                ' (mail blob,original_id int,original_folder text,header blob,timestamp int,uid_usuario int,unseen int,id_folder int,' +
155                ' ffrom text, subject text, fto text, cc text, body text, size int,unique (original_id,original_folder,uid_usuario))');
156                this.dbGears.execute('create table if not exists anexo' +
157                ' (id_mail int,nome_anexo text,url text,pid int)');
158                this.dbGears.execute('create table if not exists folders_sync' +
159                ' (id_folder text,folder_name text,uid_usuario int)');
160                this.dbGears.execute('create table if not exists msgs_to_remove (id_msg int,folder text,uid_usuario int)');
161                this.dbGears.execute('create index if not exists idx_user3 on mail (id_folder,uid_usuario,timestamp)');
162
163                //some people that used old version of local messages could not have the size column. If it's the first version
164                //with local messages you're using in expresso, this part of code can be removed
165                try {
166                        this.dbGears.execute('alter table mail add column size int');
167                }catch(Exception) {
168                       
169                }
170                var rs = this.dbGears.execute('select rowid,header from mail where size is null');
171                while(rs.isValidRow()) {
172                        var temp = expresso.connector.unserialize(rs.field(1));
173                       
174                        this.dbGears.execute('update mail set size='+temp.Size+' where rowid='+rs.field(0));
175                        rs.next();
176                }
177                //end of temporary code
178
179                try {
180                    this.dbGears.execute('begin transaction');
181                    this.dbGears.execute('alter table mail add column answered int');
182                    //this.dbGears.execute('alter table mail add column draft int');
183                    this.dbGears.execute('alter table mail add column flagged int');
184                    this.dbGears.execute('alter table mail add column recent int');
185                    //this.dbGears.execute('commit transaction');
186                    //transaction_ended = true;
187                    //if (transaction_ended){
188                    rs = null;
189                    rs = this.dbGears.execute('select rowid,header from mail');
190
191                    // Popular os valores das novas colunas.
192                    var tmp = null;
193                    //this.dbGears.execute('begin transaction');
194                    while(rs.isValidRow()) {
195                        //tmp = expresso.connector.unserialize(rs.field(1));
196                        parser = new FlagsParser(rs.field(1));
197                        flags = parser.parse();
198
199                        this.dbGears.execute('update mail set answered='+flags.getAnswered()+
200                            ',flagged='+flags.getFlagged()+',recent='+flags.getRecent()+
201                            //',draft='+flags.getDraft()+' where rowid='+rs.field(0));
202                            ' where rowid='+rs.field(0));
203
204                        rs.next();
205                    }
206                    this.dbGears.execute('commit transaction');
207
208                    //tmp = null;
209
210                }catch(Exception) {
211                    this.dbGears.execute('rollback transaction');
212                }
213
214        }
215       
216        local_messages.prototype.drop_tables = function() {
217                this.init_local_messages();
218                var rs = this.dbGears.execute('select url from anexo');
219                while(rs.isValidRow()) {
220                        this.store.remove(rs.field(0));
221                        rs.next();
222                }
223                this.dbGears.execute('drop table folder');
224                this.dbGears.execute('drop table mail');
225                this.dbGears.execute('drop table anexo');
226                this.finalize();
227        }
228       
229        local_messages.prototype.insert_mail = function(msg_info,msg_header,anexos,folder) {
230                try {
231                        this.init_local_messages();
232                        var unseen = 0;
233                        var login = msg_info.login;
234                        var original_id = msg_info.msg_number;
235                        var original_folder = msg_info.msg_folder;
236                       
237                        //This fields needs to be separeted to search.
238                        var from = expresso.connector.serialize(msg_info.from);
239                        var subject = msg_info.subject;
240                        var body = msg_info.body;
241                        var to = expresso.connector.serialize(msg_info.toaddress2);
242                        var cc = expresso.connector.serialize(msg_info.cc);
243                        var size = msg_header.Size;
244       
245                        //do not duplicate this information
246                        msg_info.from = null;
247                        msg_info.subject = null;
248                        msg_info.body = null;
249                        msg_info.to = null;
250                        msg_info.cc = null;
251                        msg_header.Size=null;
252                        //If the mail was archieved in the same date the user received it, the date cames with the time.
253                        //here I solved it
254                        if(msg_header.udate.indexOf(":")!=-1) {
255                                msg_header.udate = msg_header.aux_date;
256                        }
257                       
258                        /**
259                         * The importance attribute can be empty, and javascript consider as null causing nullpointer.
260                         */
261                        if((msg_header.Importance == null) ||  (msg_header.Importance == ""))
262                                msg_header.Importance = "Normal";
263                       
264                        msg_header.aux_date = null;
265                       
266                        var mail = expresso.connector.serialize(msg_info);
267                        var header = expresso.connector.serialize(msg_header);
268       
269                        var timestamp = msg_info.timestamp;
270                        var id_folder;
271       
272                        if((folder==null) || (folder=="local_root"))
273                                folder = "Inbox";
274                        else
275                                folder = folder.substr(6);//take off the word "local_"
276                       
277                        var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[folder,account_id]);
278                        if(rs.isValidRow())
279                                id_folder=rs.field(0);
280                        else {
281                                this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",["Inbox",account_id]);
282                                id_folder = this.dbGears.lastInsertRowId;
283                        }
284                       
285                        if(msg_info.Unseen=="U")
286                                unseen = 1;
287
288                        //parse header
289                        parser = new FlagsParser(msg_header);
290                        flags = parser.parse();
291
292                        //insere o e-mail
293                        //this.dbGears.execute("insert into mail (mail,original_id,original_folder,header,timestamp,uid_usuario,unseen,id_folder,ffrom,subject,fto,cc,body,size) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[mail,original_id,original_folder,header,timestamp,login,unseen,id_folder,from,subject,to,cc,body,size]);
294                        this.dbGears.execute("insert into mail (mail,original_id,original_folder,header,timestamp,uid_usuario,unseen,id_folder,ffrom,subject,fto,cc,body,size,answered,flagged,recent) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",[mail,original_id,original_folder,header,timestamp,login,unseen,id_folder,from,subject,to,cc,body,size,flags.getAnswered(),flags.getFlagged(),flags.getRecent()]);
295                        var call_back = function() {
296                        }
297                        this.store.capture(msg_info.url_export_file,call_back);
298                        var id_mail = this.dbGears.lastInsertRowId;
299       
300                        this.insert_attachments(id_mail,anexos);
301                        this.finalize();
302                        return true;
303                } catch (error) {
304                        this.finalize();
305                        return false;
306                }
307
308
309        }
310       
311        /**
312         * check if ID is no from main tab, if it's from main returns false, else
313         * returns an array with all string in position 0, the mail id in position 1
314         * and the part of string relative to tab in position 2
315         * @param {Object} id_mail
316         */
317        local_messages.prototype.parse_id_mail = function(id_mail) {
318                if (this.isInt(id_mail))
319                        return false;
320               
321                var matches = id_mail.match(/(.+)(_[a-zA-Z0-9]+)/);
322                return matches;
323        }
324       
325        local_messages.prototype.isInt = function(x) {
326                var y=parseInt(x);
327                if (isNaN(y)) return false;
328                return x==y && x.toString()==y.toString();
329        }
330       
331        local_messages.prototype.get_local_mail = function(id_mail) {
332                this.init_local_messages();
333
334                var plus_id = '';
335                var matches = '';
336                if(matches = this.parse_id_mail(id_mail)) { //Mails coming from other tab.
337                        id_mail = matches[1];
338                        plus_id = matches[2];
339                }
340               
341                var rs = this.dbGears.execute("select mail.rowid,mail.mail,mail.ffrom,mail.subject,mail.body,mail.fto,mail.cc,folder.folder,mail.original_id from mail inner join folder on mail.id_folder=folder.rowid  where mail.rowid="+id_mail);
342                var retorno = null;
343                if(rs.isValidRow()) {
344                         retorno = rs.field(1);
345                }
346                retorno = expresso.connector.unserialize(retorno);
347
348        //alert('tipo retorno.source: ' + typeof(retorno.source));
349
350        if (typeof(retorno.source) == 'string')
351        {
352            retorno.msg_number=rs.field(0)+plus_id;
353            retorno.original_ID=rs.field(8);
354            retorno.msg_folder=rs.field(7);
355
356            //alert('tipo retorno: '+typeof(retorno))
357            //show_msg(retorno);
358        }
359                else
360        {
361            retorno['from'] = expresso.connector.unserialize(rs.field(2));
362            retorno['subject'] = rs.field(3);
363            retorno['body'] = rs.field(4);
364            //Codigo que as imagens embutidas em emails (com multipart/related ou multipart/mixed) sejam corretamente mostradas em emails arquivados. Os links do
365            //tipo "./inc/show_embedded_attach.php?msg_folder=[folder]&msg_num=[msg_num]&msg_part=[part]"
366            //sï¿œo substituidos pelos links dos anexos capturados pelo gears.
367
368            var thumbs= retorno.thumbs;
369            var anexos= retorno.array_attach;
370            for (i in anexos)
371            {
372                nomeArquivo = anexos[i]['name'].substring(0,anexos[i]['name'].length - 4);
373                if(nomeArquivo.match('jpg')||anexos[i]['name'].match('gif')||anexos[i]['name'].match('png'))
374                    {
375                        var er_imagens = new RegExp("\\.\\/inc\\/show_embedded_attach.php\\?msg_folder=[\\w/]+\\&msg_num=[0-9]+\\&msg_part="+anexos[i]['pid']);
376                        var Result_imagens = er_imagens.exec(retorno['body']);
377                        retorno['body'] = retorno['body'].replace(Result_imagens,anexos[i]['url']);
378                        if(thumbs && thumbs[i]){
379                            er_imagens = new RegExp("\\.\\/inc\\/show_thumbs.php\\?file_type=image\\/[\\w]+\\&msg_num=[0-9]+\\&msg_folder=[\\w/%]+\\&msg_part="+anexos[i]['pid']);
380                            Result_imagens = er_imagens.exec(thumbs[i]);
381                            thumbs[i] = thumbs[i].replace(Result_imagens,"'"+anexos[i]['url']+"'");
382                            er_imagens = new RegExp("\\.\\/inc\\/show_img.php\\?msg_num=[0-9]+\\&msg_folder=[\\w/%]+\\&msg_part="+anexos[i]['pid']);
383                            Result_imagens = er_imagens.exec(thumbs[i]);
384                            thumbs[i] = thumbs[i].replace(Result_imagens,"'"+anexos[i]['url']+"'");
385                            thumbs[i] = thumbs[i].replace(/<IMG/i,'<img width="120"');
386                        }
387                    }
388            }
389
390            retorno['to'] = expresso.connector.unserialize(rs.field(5));
391            retorno['cc'] = expresso.connector.unserialize(rs.field(6));
392
393            retorno['local_message'] = true;
394            retorno['msg_folder'] = "local_"+rs.field(7); //Now it's a local folder
395            retorno['msg_number'] = rs.field(0)+plus_id; //the message number is the rowid
396
397        }
398
399        rs.close();
400                this.finalize();
401                return retorno;
402        }
403
404        local_messages.prototype.insert_attachments = function(id_msg,anexos) {
405                //insert_mail already close and open gears.
406                for (var i = 0; i < anexos.length; i++) {
407                        this.dbGears.execute("insert into anexo (id_mail,nome_anexo,url,pid) values (?,?,?,?)", [id_msg, anexos[i]['name'],anexos[i]['url'],anexos[i]['pid']]);
408                        this.capt_url(anexos[i]['url']);
409                }
410        }
411
412        local_messages.prototype.capt_url = function (url) {
413                //insert_mail already close and open gears.
414                var call_back = function(url,success,captureId) {
415                                //alert("Capturado: " + url);
416                        }
417                //alert(url);
418                this.store.capture(url,call_back);
419        }
420
421        local_messages.prototype.strip_tags = function (str) {
422                return str.replace(/<\/?[^>]+>/gi, '');
423        }
424
425        local_messages.prototype.get_local_range_msgs = function(folder,msg_range_begin,emails_per_page,sort,sort_reverse,search,preview_msg_subject,preview_msg_tip) {
426
427                this.init_local_messages();
428                var retorno = new Array();
429                msg_range_begin--;
430               
431                filter = " ";
432                if(search=="FLAGGED") {
433                        filter = "and (header like '%\"Flagged\";s:1:\"F%' or header like '%\"Importance\";s:5:\"High%') ";
434                }
435                if(search=="UNSEEN") {
436                        filter = "and unseen = 1 ";
437                }
438                if(search=="SEEN") {
439                        filter = "and unseen = 0 ";
440                }
441                if (search=="ANSWERED") {
442                        filter = "and header like '%\"Answered\";s:1:\"A%' ";
443                }
444               
445                sql = 'select mail.rowid as rowid,mail.header as header,mail.size as size,mail.timestamp as timestamp,mail.unseen as unseen,mail.body as body,case when lower(mail.ffrom) like ? then ltrim(ltrim(substr(UPPER(ffrom),21,length(ffrom)),\':\'),\'"\') else ltrim(ltrim(substr(UPPER(fto),7,length(fto)),\':\'),\'"\') end as order_from,mail.subject from mail inner join folder on mail.id_folder=folder.rowid where mail.uid_usuario=? and folder.folder=? order by '
446               
447                if(sort == 'SORTFROM') {
448                        sql += 'order_from ';
449                }
450                if(sort == 'SORTARRIVAL') {
451                        sql += 'timestamp ';
452                }
453                if(sort == 'SORTSIZE') {
454                        sql += 'size ';
455                }
456                if(sort == 'SORTSUBJECT') {
457                        sql += 'UPPER(subject) ';
458                }
459
460
461                sql+= sort_reverse==0?"ASC ":"DESC ";
462                sql +='limit ?,? ';
463
464
465                var rs = this.dbGears.execute(sql,['%'+Element("user_email").value+'%',account_id,folder,msg_range_begin,emails_per_page]);
466                var cont = 0;
467               
468                var rs3 = this.dbGears.execute('select count(*) from mail inner join folder on mail.id_folder=folder.rowid where mail.uid_usuario=? and folder.folder=?'+filter,[account_id,folder]);
469                               
470                while (rs.isValidRow()) {
471                        //var email = rs.field(1);
472                        var head = rs.field(1);
473                        var codigoMail = rs.field(0);
474
475                        var msg_body = rs.field(5);//recebe o conteudo da coluna "body" do banco de dados;
476
477                        var rs2 = this.dbGears.execute('select count(*) from anexo where id_mail = '+codigoMail);
478                        var head_unserialized = expresso.connector.unserialize(head);
479                        head_unserialized.Size = rs.field(2);
480                        if(rs.field(4)==1)
481                                head_unserialized.Unseen = 'U';         
482                       
483
484                        head_unserialized.subject=(head_unserialized.subject==null)?"":head_unserialized.subject;
485
486                        //var email_unserialized = expresso.connector.unserialize(email);
487                        retorno[cont] = head_unserialized;
488                        retorno[cont]['msg_number'] = codigoMail;
489                       
490                        //declaracao do array() para receber o body de cada mensagem encontrada na busca sql realizada;
491                        msg_body=this.strip_tags(msg_body);
492                        msg_body=msg_body.replace(/\&nbsp;/ig," ");
493                        retorno[cont]['msg_sample'] = new Array();
494
495                        if( (preview_msg_subject == 0) && (preview_msg_tip == 0) )
496                        {
497                                retorno[cont]['msg_sample']['body'] = "";
498                        }
499                        else
500                        {
501                                retorno[cont]['msg_sample']['body'] = " - " + msg_body.substr(2,300);
502                        }
503
504                        cont++;
505                        rs.next();
506                }
507                retorno['num_msgs'] = rs3.field(0);
508                rs3.close();
509                rs.close();
510                if(cont>0)
511                        rs2.close();
512                this.finalize();
513                return retorno;
514        }
515       
516        local_messages.prototype.get_url_anexo = function(msg_number,pid) {
517                this.init_local_messages();
518                var matches = '';
519                if(matches = this.parse_id_mail(msg_number)) {
520                        msg_number = matches[1];
521                }
522               
523                var retorno;
524                var rs = this.dbGears.execute("select url from anexo where id_mail="+msg_number+" and pid = '"+pid+"'");
525                retorno = rs.field(0)
526                this.finalize();
527               
528                return retorno;
529        }
530
531        local_messages.prototype.getInputFileFromAnexo = function (element,url) {
532                this.init_local_messages();
533                fileSubmitter = this.store.createFileSubmitter();
534                fileSubmitter.setFileInputElement(element,url);
535                this.finalize();
536        }
537
538        local_messages.prototype.finalize = function() {
539                this.dbGears.close();
540                this.dbGears = null;
541        }
542
543        local_messages.prototype.delete_msgs = function(msgs_number,border_ID) {
544                this.init_local_messages();
545                var rs = this.dbGears.execute("select url from anexo where id_mail in ("+msgs_number+")");
546                while(rs.isValidRow()) {
547                        this.store.remove(rs.field(0));
548                        rs.next();
549                }
550                this.dbGears.execute("delete from anexo where id_mail in ("+msgs_number+")");
551                this.dbGears.execute("delete from mail where rowid in ("+msgs_number+")");
552                this.finalize();
553                if (msgs_number.length == 1)
554                        write_msg(get_lang("The message was deleted."));
555                else
556                        write_msg(get_lang("The messages were deleted."));
557               
558                mail_msg = Element("tbody_box");
559
560                try {
561                        msgs_exploded = msgs_number.split(",");
562                }catch(error) {
563                        msgs_exploded = new Array();
564                        msgs_exploded[0] = msgs_number;
565                }
566                var msg_to_delete;
567                for (var i=0; i<msgs_exploded.length; i++){
568                        msg_to_delete = Element(msgs_exploded[i]);
569                        if (msg_to_delete){
570                                if ( (msg_to_delete.style.backgroundColor != '') && (preferences.use_shortcuts == '1') )
571                                        select_msg('null', 'down');
572                                mail_msg.removeChild(msg_to_delete);
573                                decrement_folder_unseen();
574                        }
575                }
576                Element('chk_box_select_all_messages').checked = false;
577                if (border_ID != 'null')
578                        delete_border(border_ID,'false');
579               
580        }
581       
582        local_messages.prototype.get_source_msg = function(id_msg) {
583                this.init_local_messages();
584                var rs = this.dbGears.execute("select mail from mail where rowid="+id_msg);
585
586
587                mail = expresso.connector.unserialize(rs.field(0));             
588                download_local_attachment(mail.url_export_file)
589
590                this.finalize();
591        }
592       
593       
594       
595        local_messages.prototype.set_messages_flag = function(msgs_number, flag) {
596                this.init_local_messages();
597                var msgs_to_set;
598                if (msgs_number == 'get_selected_messages') {
599                        var msgs_to_set = get_selected_messages();
600                        msgs_to_set= msgs_to_set.split(",");
601                }
602                else { //Just one message
603                        msgs_to_set = new Array();
604                        msgs_to_set[0] = msgs_number;
605                }
606                for (var i in msgs_to_set) {
607                       
608                        var matches = '';//Messages comming from other tabs.
609                        if(matches = this.parse_id_mail(msgs_to_set[i])) {
610                                msgs_to_set[i] = matches[1];
611                        }
612                       
613                        var rs = this.dbGears.execute("select header,unseen from mail where rowid=" + msgs_to_set[i]);
614                        header = expresso.connector.unserialize(rs.field(0));
615                        unseen = rs.field(1);
616                        switch(flag) {
617                                case "unseen":
618                                        set_msg_as_unread(msgs_to_set[i]);
619                                        header["Unseen"] = "U";
620                                        unseen = 1;
621                                        break;
622                                case "flagged":
623                                        set_msg_as_flagged(msgs_to_set[i]);
624                                        header["Flagged"] = "F";
625                                        break;
626                                case "unflagged":
627                                        if (header["Importance"].indexOf("High") != -1)
628                                                write_msg(get_lang("At least one of selected message cant be marked as normal"));
629                                        else {
630                                                set_msg_as_unflagged(msgs_to_set[i]);
631                                                header["Flagged"] = "N";
632                                        }
633                                        break;
634                                case "seen":
635                                        header["Unseen"] = "N";
636                                        set_msg_as_read(msgs_to_set[i],true);
637                                        unseen = 0;
638                                        break;
639                                case "answered":
640                                        header["Draft"]="";
641                                        header["Answered"]="A";
642                                        Element("td_message_answered_"+msgs_to_set[i]).innerHTML = '<img src=templates/default/images/answered.gif title=Respondida>';
643                                        break;
644                                case "forwarded":
645                                        header["Draft"]="X";
646                                        header["Answered"]="A";
647                                        Element("td_message_answered_"+msgs_to_set[i]).innerHTML = '<img src=templates/default/images/forwarded.gif title=Encaminhada>';
648                                        break;
649                        }
650               
651                        rs.close();
652                       
653                        if(Element("check_box_message_" + msgs_to_set[i]))
654                                Element("check_box_message_" + msgs_to_set[i]).checked = false;
655
656                        this.dbGears.execute("update mail set header='"+expresso.connector.serialize(header)+"',unseen="+unseen+" where rowid="+msgs_to_set[i]);                       
657                }
658                if(Element('chk_box_select_all_messages'))
659                        Element('chk_box_select_all_messages').checked = false;
660                this.finalize();
661
662        }
663       
664        local_messages.prototype.set_message_flag = function(msg_number,flag) {
665                this.set_messages_flag(msg_number,flag);
666        }
667       
668        local_messages.prototype.get_unseen_msgs_number = function() {
669                this.init_local_messages();
670                var rs = this.dbGears.execute("select count(*) from mail where unseen=1");
671                var retorno = rs.field(0);
672                rs.close();
673                this.finalize();
674                return retorno;
675        }
676
677        local_messages.prototype.create_folder = function(folder) {
678
679                if (folder.indexOf("local_") != -1)
680                        return false; //can't create folder with string local_
681
682                this.init_local_messages();
683                try {
684                        this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",[folder,account_id]);
685                } catch (error) {
686                        this.finalize();
687                        throw error;
688                        return false;
689                }
690                this.finalize();
691                return true;
692        }
693
694        local_messages.prototype.list_local_folders = function(folder) {
695                this.init_local_messages();
696                var retorno = new Array();
697                rs = this.dbGears.execute("select folder,rowid from folder where uid_usuario=?",[account_id]);
698                while(rs.isValidRow()) {
699                        var temp = new Array();
700                        temp[0] = rs.field(0);
701                       
702                        var rs2 = this.dbGears.execute("select count(*) from mail where id_folder=? and unseen=1",[rs.field(1)]);
703                        temp[1] = rs2.field(0);                 
704
705                        var rs3 = this.dbGears.execute("select * from folder where folder like ? limit 1",[temp[0]+"/%"]);
706                        if(rs3.isValidRow())
707                                temp[2] = 1;
708                        else
709                                temp[2] = 0;
710                        retorno.push(temp);
711                        rs.next();
712                }
713               
714                rs.close();
715                this.finalize();
716                return retorno;
717        }
718
719        local_messages.prototype.rename_folder = function(folder,old_folder) {
720                if (folder.indexOf("local_") != -1)
721                        return false; //can't create folder with string local_
722                this.init_local_messages();
723                if (old_folder.indexOf("/") != "-1") {
724                        final_pos = old_folder.lastIndexOf("/");
725                        folder = old_folder.substr(0, final_pos) + "/" + folder;
726                }
727                try {
728                        this.dbGears.execute("update folder set folder=? where folder=? and uid_usuario=?",[folder,old_folder,account_id]);
729                } catch (error) {
730                        this.finalize();
731                        return false;
732                }
733                rs = this.dbGears.execute("select folder from folder where folder like ? and uid_usuario=?",[old_folder+'/%',account_id]);
734                while(rs.isValidRow()) {
735                        folder_tmp = rs.field(0);
736                        folder_new = folder_tmp.replace(old_folder,folder);
737                        this.dbGears.execute("update folder set folder=? where folder=?",[folder_new,folder_tmp]);
738                        rs.next();
739                }
740
741
742                this.finalize();
743                return true;
744        }
745       
746        local_messages.prototype.remove_folder = function(folder) {
747                this.init_local_messages();
748                var rs = this.dbGears.execute("select count(rowid) from folder where folder like ? and uid_usuario=?",[folder+"/%",account_id]);
749                var sons = rs.field(0);
750                rs.close();
751
752                if(sons == 0){
753                var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[folder,account_id]);
754                var folder_id = rs.field(0);
755                rs.close();
756                this.dbGears.execute("delete from folder where rowid=?",[folder_id]);
757                rs = this.dbGears.execute("select rowid,mail from mail where id_folder=?",[folder_id]);
758                while(rs.isValidRow()) {
759                        var rs2 = this.dbGears.execute("select url from anexo where id_mail=?",[rs.field(0)]);
760                        while(rs2.isValidRow()) {
761                                this.store.remove(rs2.field(0));
762                                rs2.next();
763                        }
764                        rs2.close();
765                        this.dbGears.execute("delete from anexo where id_mail=?",[rs.field(0)]);
766                        var mail = expresso.connector.unserialize(rs.field(1));
767                        this.store.remove(mail.url_export_file);
768                        rs.next();
769                }
770                rs.close();
771                this.dbGears.execute("delete from mail where id_folder=?",[folder_id]);
772                this.finalize();
773                return true;
774                }else  {
775                    this.finalize();
776                        return false;
777        }
778
779        }
780
781        local_messages.prototype.move_messages = function(new_folder,msgs_number) {
782                this.init_local_messages();
783                var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[new_folder,account_id]);
784                var id_folder = rs.field(0);
785                rs.close();
786                this.dbGears.execute("update mail set id_folder="+id_folder+" where rowid in ("+msgs_number.toString()+")"); //usando statement nï¿œo tava funcionando quando tinha mais de um email...
787                this.finalize();
788        }
789       
790        local_messages.prototype.search = function(folders,sFilter) {
791                this.init_local_messages();
792                var filters = sFilter.replace(/^##|##$/g,"").split('##');
793                var friendly_filters = new Array();
794
795                if (sFilter.indexOf('ALL') != -1) { //all filters...
796                    filters[0] = sFilter.replace(/##/g,"");
797                    tmp = filters[0].split("<=>");
798
799                    searchKey = new Array();
800                    searchKey.push("SUBJECT");
801                    searchKey.push(tmp[1]);
802                    friendly_filters.push(searchKey);
803
804                    searchKey = new Array();
805                    searchKey.push("BODY");
806                    searchKey.push(tmp[1]);
807                    friendly_filters.push(searchKey);
808
809                    searchKey = new Array();
810                    searchKey.push("FROM");
811                    searchKey.push(tmp[1]);
812                    friendly_filters.push(searchKey);
813
814                    searchKey = new Array();
815                    searchKey.push("TO");
816                    searchKey.push(tmp[1]);
817                    friendly_filters.push(searchKey);
818
819                    searchKey = new Array();
820                    searchKey.push("CC");
821                    searchKey.push(tmp[1]);
822                    friendly_filters.push(searchKey);
823                }
824                else {
825                    for (var i=0; i<filters.length; i++)
826                    {
827                        if (filters[i] != ""){
828                            //tmp[0] = tmp[0].replace(/^\s+|\s+$/g,"");
829                            //tmp[1] = tmp[1].replace(/^\s+|\s+$/g,"");
830                            friendly_filters.push(filters[i].split("<=>"));
831                        }
832                    }
833                }
834                var sql = "select mail.header,folder.folder,mail.rowid,size from mail inner join folder on mail.id_folder=folder.rowid where mail.uid_usuario="+account_id + " and folder.folder in (";
835                for(var fnum in folders) {
836                        sql+="'"+folders[fnum]+"'";
837                        if(fnum<folders.length-1)
838                                sql+=",";
839                }
840                sql += ") and (";
841                for (var z=0;z<friendly_filters.length;z++) {
842                    if (z != 0) {
843                        if (sFilter.indexOf('ALL') != -1)
844                            sql += " or";
845                        else
846                            sql += " and";
847                    }
848                    var cond = friendly_filters[z][0].replace(/^\s+|\s+$/g,"");
849                    if (cond == "SINCE" || cond == "BEFORE" | cond == "ON"){
850
851                        tmpDate = url_decode(friendly_filters[z][1]).split('/');
852
853                        // Date = url_decode(friendly_filters[z][1]);
854                        sql+=" mail.timestamp " + this.aux_convert_filter_field(friendly_filters[z][0], tmpDate);
855                    }
856                    else if (!friendly_filters[z][1])
857                        {
858                            sql+=" mail."+this.aux_convert_filter_field(friendly_filters[z][0]);
859                        }
860                        else
861                            {
862                                sql+=" mail."+this.aux_convert_filter_field(friendly_filters[z][0])+" like '%"+url_decode(friendly_filters[z][1])+"%'";
863                            }
864                }
865                sql += ")";
866                var rs = this.dbGears.execute(sql);
867                var retorno = "";
868                while(rs.isValidRow()) {
869                    var header = expresso.connector.unserialize(rs.field(0));
870                    retorno+="##"+"local_"+rs.field(1)+"--"+header["from"]["name"]+"--"+header["subject"]+"--"+header["udate"]+"--"+this.aux_convert_size(rs.field(3))+"--"+header["Unseen"]+header["Recent"]+header["Flagged"]+header["Draft"]+"--"+rs.field(2)+"##";
871                    rs.next();
872                }
873
874                this.finalize();
875                return retorno==""?false:retorno;
876
877        }
878       
879        local_messages.prototype.aux_convert_size = function(size) {
880                var tmp = Math.floor(size/1024);
881                if(tmp >= 1){
882                        return tmp + " kb";     
883                }else{
884                        return size + " b";     
885                }
886               
887        }
888       
889        local_messages.prototype.aux_convert_filter_field = function(filter,date) {
890                if (typeof date != 'undefined'){
891                    var dateObj=new Date();
892                    dateObj.setFullYear(date[2],date[1]-1,date[0]);
893                }
894
895                if((filter=="SUBJECT ") || (filter=="SUBJECT"))
896                        return "subject";
897                else if((filter=="BODY ") || (filter=="BODY"))
898                        return "body";
899                else if((filter=="FROM ") || (filter=="FROM"))
900                        return "ffrom";
901                else if((filter=="TO ") || (filter=="TO"))
902                        return "fto";
903                else if((filter=="CC ") || (filter=="CC"))
904                        return "cc";
905                else if (filter.replace(/^\s+|\s+$/g,"") == "SINCE"){
906                        dateObj.setHours(0, 0, 0, 0);
907                        return ">= " + dateObj.getTime().toString(10).substr(0, 10);
908                }
909                else if (filter.replace(/^\s+|\s+$/g,"") == "BEFORE"){
910                        dateObj.setHours(23, 59, 59, 999);
911                        return "<= " + dateObj.getTime().toString(10).substr(0, 10);
912                }
913                else if (filter.replace(/^\s+|\s+$/g,"") == "ON"){
914                        dateObj.setHours(0, 0, 0, 0);
915                        var ts1 = dateObj.getTime().toString(10).substr(0, 10);
916                        dateObj.setHours(23, 59, 59, 999);
917                        var ts2 = dateObj.getTime().toString(10).substr(0, 10);
918                        return ">= " + ts1 + ") and (timestamp <= " + ts2;
919                }
920                else if (filter.replace(/^\s+|\s+$/g,"") == "FLAGGED")
921                        return "flagged = 1";
922                else if (filter.replace(/^\s+|\s+$/g,"") == "UNFLAGGED")
923                        return "flagged = 0";
924                else if (filter.replace(/^\s+|\s+$/g,"") == "UNSEEN")
925                        return "unseen = 1";
926                else if (filter.replace(/^\s+|\s+$/g,"") == "SEEN")
927                        return "unseen = 0";
928                else if (filter.replace(/^\s+|\s+$/g,"") == "ANSWERED")
929                        return "answered = 1";
930                else if (filter.replace(/^\s+|\s+$/g,"") == "UNANSWERED")
931                        return "answered = 0";
932                else if (filter.replace(/^\s+|\s+$/g,"") == "RECENT")
933                        return "recent = 1";
934                else if (filter.replace(/^\s+|\s+$/g,"") == "OLD")
935                        return "recent = 0";
936
937        }
938       
939        local_messages.prototype.has_local_mails = function() {
940                this.init_local_messages();
941                var rs = this.dbGears.execute("select rowid from folder limit 0,1");
942                var retorno;
943                if(rs.isValidRow())
944                        retorno = true;
945                else
946                        retorno = false;
947                this.finalize();
948                return retorno;
949        }
950
951     //Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Essa funᅵᅵo ï¿œ um AJAX simples que serve apenas para pegar o fonte de uma msg local (no formato RFC 822).
952    local_messages.prototype.get_src = function(url){
953        AJAX = false;
954        if (window.XMLHttpRequest) { // Mozilla, Safari,...
955            AJAX = new XMLHttpRequest();
956            if (AJAX.overrideMimeType) {
957                AJAX.overrideMimeType('text/xml');
958            }
959        } else if (window.ActiveXObject) { // IE
960            try {
961                AJAX = new ActiveXObject("Msxml2.XMLHTTP");
962            } catch (e) {
963                try {
964                AJAX = new ActiveXObject("Microsoft.XMLHTTP");
965                } catch (e) {}
966            }
967        }
968
969        if (!AJAX) {
970            alert('ERRO :(Seu navegador nï¿œo suporta a aplicaᅵᅵo usada neste site');
971            return false;
972        }
973
974        AJAX.onreadystatechange = function() {
975            if (AJAX.readyState == 4) {
976                AJAX.src=AJAX.responseText;
977                if (AJAX.status == 200) {
978                    return AJAX.responseText;
979                    } else {
980                    return false;
981                }
982            }
983        }
984
985        AJAX.open('get', url, false);
986        AJAX.send(null);
987        return AJAX.responseText;
988    };
989
990  //Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Dessarquiva msgs locais pegando o codigo fonte das mesmas e mandando via POST para o servidor
991  //para que elas sejam inseridas no imap pela funᅵᅵo  imap_functions.unarchive_mail.
992    local_messages.prototype.unarchive_msgs = function (folder,new_folder,msgs_number){
993
994        if(!new_folder)
995            new_folder='INBOX';
996        this.init_local_messages();
997       // alert(folder+new_folder+msgs_number);
998        var handler_unarchive = function(data)
999        {
1000            if(data.error == '')
1001                write_msg(get_lang('All messages are successfully unarchived'));
1002            else
1003                alert(data.error);
1004        }
1005        if(msgs_number =='selected' || !msgs_number)
1006        {
1007            msgs_number = get_selected_messages()
1008            if (!msgs_number){
1009                write_msg(get_lang('No selected message.'));
1010                return;
1011            }
1012            var rs = this.dbGears.execute("select mail,timestamp from mail where rowid in ("+msgs_number+")");
1013            var source="";
1014            var timestamp="";
1015            while(rs.isValidRow()) {
1016                mail=expresso.connector.unserialize(rs.field(0));
1017                source_tmp=escape(this.get_src(mail.url_export_file));
1018                    source+="#@#@#@"+source_tmp;
1019                    timestamp+="#@#@#@"+rs.field(1);
1020                rs.next();
1021            }
1022            rs.close();
1023            this.finalize();
1024        }
1025        else
1026        {
1027            var rs = this.dbGears.execute("select mail,timestamp from mail where rowid="+msgs_number);
1028            mail=expresso.connector.unserialize(rs.field(0));
1029            var source ="";
1030            source = this.get_src(mail.url_export_file);
1031            timestamp=rs.field(1);
1032             rs.close();
1033             this.finalize();
1034        }
1035            params="&folder="+new_folder+"&source="+source+"&timestamp="+timestamp;
1036            cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
1037    }
1038
1039    local_messages.prototype.get_msg_date = function (original_id, is_local){
1040
1041        this.init_local_messages();
1042
1043        if (typeof(is_local) == 'undefined')
1044        {
1045            is_local = false;
1046        }
1047
1048        var rs;
1049
1050        if (is_local)
1051        {
1052            rs = this.dbGears.execute("select mail from mail where rowid="+original_id);
1053        }
1054        else
1055        {
1056            rs = this.dbGears.execute("select mail from mail where original_id="+original_id);
1057        }
1058        var tmp = expresso.connector.unserialize(rs.field(0));
1059        var ret = new Array();
1060        ret.fulldate = tmp.fulldate.substr(0,16);
1061        ret.smalldate = tmp.msg_day;
1062        ret.msg_day = tmp.msg_day;
1063        ret.msg_hour = tmp.msg_day;
1064
1065        rs.close();
1066        this.finalize();
1067        return ret;
1068    }
1069
1070
1071    local_messages.prototype.download_all_local_attachments = function(folder,id){
1072        this.init_local_messages();
1073        var rs = this.dbGears.execute("select mail from mail where rowid="+id);
1074        var tmp = expresso.connector.unserialize(rs.field(0));
1075        rs.close();
1076        this.finalize();
1077        source = this.get_src(tmp.url_export_file);
1078        source = escape(source);
1079        var handler_source = function(data){
1080            download_attachments(null, null, data, null,null,'anexos.zip');
1081        }
1082        cExecute("$this.imap_functions.download_all_local_attachments",handler_source,"source="+source);
1083    }
1084
1085    /*************************************************************************/
1086/* Funcao usada para exportar mensagens arquivadas localmente.
1087 * Rommel de Brito Cysne (rommel.cysne@serpro.gov.br)
1088 * em 22/12/2008.
1089 */
1090    local_messages.prototype.local_messages_to_export = function(){
1091
1092        if (openTab.type[currentTab] > 1){
1093            var msgs_to_export_id = currentTab.substring(0,currentTab.length-2,currentTab);
1094        }else{
1095            var msgs_to_export_id = get_selected_messages();
1096        }
1097        var handler_local_mesgs_to_export = function(data){
1098            download_attachments(null, null, data, null,null,'mensagens.zip');
1099        }
1100        if(msgs_to_export_id){
1101            this.init_local_messages();
1102            var l_msg = "t";
1103            var mesgs ="";
1104            var subjects ="";
1105            var rs = this.dbGears.execute("select mail,subject from mail where rowid in ("+msgs_to_export_id+")");
1106            while(rs.isValidRow()){
1107                mail = expresso.connector.unserialize(rs.field(0));
1108                mail.msg_source?src = mail.msg_source:src = this.get_src(mail.url_export_file);
1109                subject = rs.field(1);
1110                mesgs += src;
1111                mesgs += "@@";
1112                subjects += subject;
1113                subjects += "@@";
1114                rs.next();
1115            }
1116            rs.close();
1117            this.finalize();
1118            mesgs = escape(mesgs);
1119            subjects = escape(subjects);
1120            params = "subjects="+subjects+"&mesgs="+mesgs+"&l_msg="+l_msg+"&msgs_to_export="+msgs_to_export_id;
1121            cExecute ("$this.exporteml.makeAll&", handler_local_mesgs_to_export, params);
1122        }
1123        return true;
1124    }
1125
1126    local_messages.prototype.get_all_local_folder_messages= function(folder_name){
1127
1128
1129         var mesgs = new Array();
1130         var subjects = new Array();
1131         var hoje = new Date();
1132         var msgs_to_export = new Array();
1133         var l_msg="t";
1134
1135        this.init_local_messages();
1136        var query = "select mail,subject,mail.rowid from mail inner join folder on (mail.id_folder=folder.rowid) where folder.folder='" + folder_name + "'";
1137
1138        var rs = this.dbGears.execute(" "+query)
1139
1140            var handler_local_mesgs_to_export = function(data){
1141                    //alert("data - " + data + " - tipo - " + typeof(data));
1142                    download_attachments(null, null, data, null,null,'mensagens.zip');
1143            }
1144        var j=0;
1145        while (rs.isValidRow()){
1146              msgs_to_export[j]=rs.field(2)
1147              mail = expresso.connector.unserialize(rs.field(0));
1148                      mail.msg_source?src = mail.msg_source:src = this.get_src(mail.url_export_file);
1149                      subject = rs.field(1);
1150                      mesgs += msg;
1151                      mesgs += "@@";
1152                      subjects += subject;
1153                      subjects += "@@";
1154                      rs.next();
1155              j++;
1156
1157        }
1158           rs.close();
1159           this.finalize();
1160           source = escape(mesgs);
1161           subjects = escape(subjects);
1162           params = "folder="+folder_name+"&subjects="+subjects+"&mesgs="+source+"&l_msg="+l_msg+"&msgs_to_export="+msgs_to_export;
1163           cExecute ("$this.exporteml.makeAll&", handler_local_mesgs_to_export, params);
1164         
1165
1166    }
1167
1168
1169    /*************************************************************************/
1170
1171       
1172/******************************************************************
1173                                        Offline Part
1174 ******************************************************************/
1175
1176        local_messages.prototype.is_offline_installed = function() {
1177                this.init_local_messages();
1178                var check = this.localServer.openManagedStore('expresso-offline');
1179                this.finalize();
1180                if(check==null)
1181                        return false;
1182                else
1183                        return true;
1184               
1185        }
1186        local_messages.prototype.update_offline = function(redirect) {
1187                this.init_local_messages();
1188                var managedStore = this.localServer.openManagedStore('expresso-offline');
1189
1190                if(managedStore!=null){
1191                       
1192                        managedStore.oncomplete = function(details){
1193                                if(redirect!=null)
1194                                        location.href=redirect;
1195                        }
1196                       
1197                        managedStore.checkForUpdate();
1198                } else if(redirect!=null) {
1199                        location.href=redirect;
1200                }
1201                this.finalize();
1202        }
1203       
1204        local_messages.prototype.uninstall_offline = function() {
1205                if (!window.google || !google.gears) {
1206                                temp = confirm(document.getElementById('lang_gears_redirect').value);
1207                                if (temp) {
1208                                        expresso_local_messages.installGears();
1209                                }
1210                                return;
1211
1212                }
1213                this.init_local_messages();
1214                this.localServer.removeManagedStore('expresso-offline');
1215                alert(document.getElementById('lang_offline_uninstalled').value);
1216                //this.dbGears.execute('drop table user');
1217                //this.dbGears.execute('drop table queue');
1218                //this.dbGears.execute('drop table attachments_queue');
1219                this.finalize();
1220        }
1221       
1222        local_messages.prototype.get_folders_to_sync = function() {//Precisa ter visibilidade ao array de linguagens.
1223                this.init_local_messages();
1224                var rs = this.dbGears.execute("select id_folder,folder_name from folders_sync where uid_usuario="+account_id);
1225                var retorno = new Array();
1226                while(rs.isValidRow()) {
1227                        temp = new Array();
1228                        temp[0] = rs.field(0);
1229                        if(temp[0]=='INBOX/Drafts' ||temp[0]=='INBOX/Trash' || temp[0]=='INBOX/Sent') {
1230                                temp[1] = array_lang[rs.field(1).toLowerCase()];
1231                        }
1232                        else {
1233                                temp[1] = rs.field(1); 
1234                        }
1235                       
1236                        retorno.push(temp);
1237                        rs.next();
1238                }
1239                this.finalize();
1240                return retorno;
1241        }
1242       
1243        local_messages.prototype.install_offline = function(urlOffline,urlIcone,uid_usuario,login,pass,redirect) {
1244                if (!window.google || !google.gears) {
1245                                temp = confirm(document.getElementById('lang_gears_redirect').value);
1246                                if (temp) {
1247                                         expresso_local_messages.installGears();
1248                                }
1249                                return;
1250
1251                }
1252               
1253                if(pass.length>0) {
1254                        only_spaces = true;
1255                        for(cont=0;cont<pass.length;cont++) {
1256                                if(pass.charAt(cont)!=" ")
1257                                        only_spaces = false;
1258                        }
1259                        if(only_spaces) {
1260                                alert(document.getElementById('lang_only_spaces_not_allowed').value);
1261                                return false;
1262                        }
1263                }
1264
1265                modal('loading');
1266                var desktop = google.gears.factory.create('beta.desktop');
1267                desktop.createShortcut('ExpressoMail Offline',
1268                        urlOffline,
1269                {'32x32': urlIcone},
1270                'ExpressoMail Offline');
1271
1272
1273                this.init_local_messages();
1274
1275                //user with offline needs to have at least the folder Inbox already created.
1276                tmp_rs = this.dbGears.execute("select rowid from folder where folder='Inbox' and uid_usuario=?",[uid_usuario]);
1277                if(!tmp_rs.isValidRow())
1278                        this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",['Inbox',uid_usuario]);
1279
1280                this.localServer.removeManagedStore('expresso-offline');
1281       
1282                var managedStore = this.localServer.createManagedStore('expresso-offline');
1283                managedStore.manifestUrl = 'js/manifest';
1284
1285                managedStore.onerror = function (error) {
1286                        alert(error);
1287                }
1288               
1289                managedStore.oncomplete = function(details) {
1290                        if (close_lightbox_div) {
1291                                close_lightbox();
1292                                close_lightbox_div = false;
1293                                alert(document.getElementById('lang_offline_installed').value);
1294                                location.href=redirect;
1295                        }
1296                }
1297
1298                //create structure to user in db
1299                this.dbGears.execute('create table if not exists user (uid_usuario int,login text,pass text, logged int,unique(uid_usuario))');
1300                this.dbGears.execute('create table if not exists queue (ffrom text, fto text, cc text, cco text,'+
1301                        'subject text, conf_receipt int, important int,body text,sent int,user int)');
1302                this.dbGears.execute('create table if not exists attachments_queue ('+
1303                        'id_queue int, url_attach text)');
1304                this.dbGears.execute('create table if not exists sent_problems (' +
1305                        'id_queue int,message text)');
1306               
1307                //d = new Date();
1308               
1309                try {
1310                        var rs = this.dbGears.execute("select uid_usuario from user where uid_usuario=?",[uid_usuario]);
1311                        if(!rs.isValidRow())
1312                                this.dbGears.execute("insert into user (uid_usuario,login,pass) values (?,?,?)",[uid_usuario,login,pass]);
1313                        else
1314                                this.dbGears.execute("update user set pass=? where uid_usuario=?",[pass,uid_usuario]);
1315                } catch (error) {
1316                        this.finalize();
1317                        alert(error);
1318                        return false;
1319                }
1320                managedStore.checkForUpdate();
1321                this.capt_url('controller.php?action=$this.db_functions.get_dropdown_contacts_to_cache');
1322               
1323                this.finalize();
1324        }
1325       
1326        /**
1327         * Return all users in an array following the structure below.
1328         *
1329         * key: uid
1330         * value: user login
1331         */
1332        local_messages.prototype.get_all_users = function() {
1333                this.init_local_messages();
1334                var users = new Array();
1335                var rs = this.dbGears.execute("select uid_usuario,login from user");
1336                while(rs.isValidRow()) {
1337                        users[rs.field(0)] = rs.field(1);
1338                        rs.next();
1339                }
1340                this.finalize();
1341                return users;
1342        }
1343       
1344        local_messages.prototype.set_as_logged = function(uid_usuario,pass,bypass) {
1345                this.init_local_messages();
1346                if (!bypass) {
1347                        var rs = this.dbGears.execute("select pass from user where uid_usuario=?", [uid_usuario]);
1348                        if (!rs.isValidRow() || (pass != rs.field(0) && pass != MD5(rs.field(0)))) {
1349                                this.finalize();
1350                                return false;
1351                        }
1352                }
1353                d = new Date();
1354
1355                this.dbGears.execute("update user set logged=null"); //Logoff in everybody
1356                this.dbGears.execute("update user set logged=? where uid_usuario=?",[d.getTime(),uid_usuario]); //Login just in one...
1357                this.finalize();
1358                return true;
1359        }
1360       
1361        local_messages.prototype.unset_as_logged = function() {
1362                this.init_local_messages();
1363                this.dbGears.execute("update user set logged=null"); //Logoff in everybody
1364                this.finalize();
1365        }
1366       
1367        local_messages.prototype.user_logged = function() {
1368                this.init_local_messages();
1369                var user_logged = new Array();
1370                var rs = this.dbGears.execute("select uid_usuario,logged from user where logged is not null");
1371                if(!rs.isValidRow()) {
1372                        this.finalize();
1373                        return null;
1374                }
1375                user_logged[0] = rs.field(0);
1376                user_logged[1] = rs.field(1);
1377                this.finalize();
1378                return user_logged;
1379        }
1380       
1381        local_messages.prototype.send_to_queue = function (form) {
1382                this.init_local_messages();
1383                var mail_values = new Array();
1384               
1385                for (var i=0;i<form.length;i++) {
1386                        if (form.elements[i].name != '') { //I.E made me to do that...
1387                                if(form.elements[i].name=='folder' || form.elements[i].name=='msg_id' || form.elements[i].name=='' || form.elements[i].name==null)
1388                                        continue;
1389                                else if (form.elements[i].name == 'input_return_receipt' )
1390                                        mail_values['conf_receipt'] = form.elements[i].checked ? 1 : 0;
1391                                else if(form.elements[i].name == 'input_important_message')
1392                                        mail_values['important'] = form.elements[i].checked ? 1 : 0;
1393                                else
1394                                        if (form.elements[i].name == 'body')
1395                                                mail_values['body'] = form.elements[i].value;
1396                                        else
1397                                                if (form.elements[i].name == 'input_from')
1398                                                        mail_values['ffrom'] = form.elements[i].value;
1399                                                else
1400                                                        if (form.elements[i].name == 'input_to')
1401                                                                mail_values['fto'] = form.elements[i].value;
1402                                                        else
1403                                                                if (form.elements[i].name == 'input_cc')
1404                                                                        mail_values['cc'] = form.elements[i].value;
1405                                                                else
1406                                                                        if (form.elements[i].name == 'input_cco')
1407                                                                                mail_values['cco'] = form.elements[i].value;
1408                                                                        else
1409                                                                                if (form.elements[i].name == 'input_subject')
1410                                                                                        mail_values['subject'] = form.elements[i].value;
1411                        }
1412                }
1413                //mail_values['fto'] = input_to;
1414                //mail_values['cc'] = input_cc;
1415                //mail_values['cco'] = input_cco;
1416                //mail_values['subject'] = input_subject;
1417                //mail_values['conf_receipt'] = input_return_receipt;
1418                //mail_values['important'] = input_important_message;
1419               
1420                try {
1421                        this.dbGears.execute("insert into queue (ffrom,fto,cc,cco,subject,conf_receipt,important,body,sent,user) values (?,?,?,?,?,?,?,?,0,?)", [mail_values['ffrom'], mail_values['fto'], mail_values['cc'], mail_values['cco'], mail_values['subject'], mail_values['conf_receipt'], mail_values['important'], mail_values['body'], account_id]);
1422                        this.send_attach_to_queue(this.dbGears.lastInsertRowId,form);
1423                }catch(error) {
1424                        alert(error);
1425                        return get_lang('Error sending a mail to queue. Verify if you have installed ExpressoMail Offline');
1426                }
1427                this.finalize();
1428                return true;
1429        }
1430       
1431        local_messages.prototype.send_attach_to_queue = function(id_queue,form) {
1432               
1433                for(i=0;i<form.elements.length;i++) {
1434                       
1435                        if(form.elements[i].name.indexOf("file_")!=-1) {
1436                                var tmp_input = form.elements[i];
1437                                var d = new Date();
1438                                var url_local = 'local_attachs/'+d.getTime();
1439                                this.store.captureFile(tmp_input, url_local);
1440                                this.dbGears.execute("insert into attachments_queue (id_queue,url_attach) values (?,?)",[id_queue,url_local]);
1441                        }
1442                        else if(form.elements[i].name.indexOf("offline_forward_")!=-1){
1443                                //alert();
1444                                this.dbGears.execute("insert into attachments_queue (id_queue,url_attach) values (?,?)",[id_queue,form.elements[i].value]);
1445                        }
1446                }
1447        }
1448
1449       
1450        local_messages.prototype.get_num_msgs_to_send = function() {
1451                this.init_local_messages();
1452
1453                var rs = this.dbGears.execute("select count(*) from queue where user=? and sent=0",[account_id]);
1454                var to_return = rs.field(0);
1455
1456                this.finalize();
1457                return to_return;
1458        }
1459       
1460        local_messages.prototype.set_problem_on_sent = function(rowid_message,msg) {
1461                this.init_local_messages();
1462                this.dbGears.execute("update queue set sent = 2 where rowid=?",[rowid_message]);
1463                this.dbGears.execute("insert into sent_problems (id_queue,message) values (?,?)"[rowid_message,msg]);
1464                this.finalize();
1465        }
1466       
1467        local_messages.prototype.set_as_sent = function(rowid_message) {
1468                this.init_local_messages();
1469                this.dbGears.execute("update queue set sent = 1 where rowid=?",[rowid_message]);
1470                this.finalize();
1471        }
1472       
1473        local_messages.prototype.get_form_msg_to_send = function() {
1474                this.init_local_messages();
1475                var rs = this.dbGears.execute('select ffrom,fto,cc,cco,subject,conf_receipt,important,body,rowid from queue where sent=0 and user = ? limit 0,1',[account_id]);
1476                if(!rs.isValidRow())
1477                        return false;
1478               
1479                var form = document.createElement('form');
1480                form.method = 'POST';
1481                form.name = 'form_queue_'+rs.field(8);
1482                form.style.display = 'none';
1483                form.onsubmit = function(){return false;}
1484                if(!is_ie)
1485                        form.enctype="multipart/form-data";
1486                else
1487                        form.encoding="multipart/form-data";
1488               
1489                var ffrom = document.createElement('TEXTAREA');
1490                ffrom.name = "input_from";
1491                ffrom.value = rs.field(0);
1492                form.appendChild(ffrom);
1493               
1494                var fto = document.createElement('TEXTAREA');
1495                fto.name = "input_to";
1496                fto.value = rs.field(1);
1497                form.appendChild(fto);
1498               
1499                var cc = document.createElement('TEXTAREA');
1500                cc.name = "input_cc";
1501                cc.value = rs.field(2);
1502                form.appendChild(cc);
1503
1504                var cco = document.createElement('TEXTAREA');
1505                cco.name = "input_cco";
1506                cco.value = rs.field(3);
1507                form.appendChild(cco);
1508               
1509                var subject = document.createElement('TEXTAREA');
1510                subject.name = "input_subject";
1511                subject.value = rs.field(4);
1512                form.appendChild(subject);
1513               
1514                var folder = document.createElement('input');
1515                folder.name='folder';
1516                folder.value=preferences.save_in_folder;
1517                form.appendChild(folder);
1518               
1519                if (rs.field(5) == 1) {
1520                        var conf_receipt = document.createElement('input');
1521                        conf_receipt.type='text';
1522                        conf_receipt.name = "input_return_receipt";
1523                        conf_receipt.value = 'on';
1524                        form.appendChild(conf_receipt);
1525                }
1526               
1527                if (rs.field(6) == 1) {
1528                        var important = document.createElement('input');
1529                        important.type='text';
1530                        important.name = "input_important_message";
1531                        important.value = 'on';
1532                        form.appendChild(important);
1533                }
1534               
1535                var body = document.createElement('TEXTAREA');
1536                body.name = "body";
1537                body.value = rs.field(7);
1538                form.appendChild(body);
1539               
1540                var rowid = document.createElement('input');
1541                rowid.type = 'hidden';
1542                rowid.name = 'rowid';
1543                rowid.value = rs.field(8);
1544                form.appendChild(rowid);
1545               
1546                //Mounting the attachs
1547                var divFiles = document.createElement("div");
1548                divFiles.id = 'divFiles_queue_'+rs.field(8);
1549               
1550                form.appendChild(divFiles);
1551               
1552                document.getElementById('forms_queue').appendChild(form);
1553
1554                var is_local_forward = false;
1555                try {
1556                       
1557                        var rs_attach = this.dbGears.execute('select url_attach from attachments_queue where id_queue=?', [rs.field(8)]);
1558                        while (rs_attach.isValidRow()) {
1559                                if(rs_attach.field(0).indexOf('../tmpLclAtt/')==-1) {
1560                                        tmp_field = addForwardedFile('queue_' + rs.field(8), this.store.getCapturedFileName(rs_attach.field(0)), 'nothing');
1561                                }
1562                                else {
1563                                        var tempNomeArquivo = rs_attach.field(0).split("/");
1564                                        var nomeArquivo = tempNomeArquivo[tempNomeArquivo.length-1];
1565                                        nomeArquivo = nomeArquivo.substring(0,nomeArquivo.length - 4); //Anexos no gears sï¿œo todos com extensï¿œo .php. tenho que tirar a extensï¿œo para ficar o nome real do arquivo.
1566                                        is_local_forward = true;
1567                                        tmp_field = addForwardedFile('queue_' + rs.field(8), nomeArquivo, 'nothing');
1568                                }
1569                                fileSubmitter = this.store.createFileSubmitter();
1570                                fileSubmitter.setFileInputElement(tmp_field,rs_attach.field(0));
1571                //              alert(form.innerHTML);
1572                        //      div.appendChild(tmp_field);
1573                                rs_attach.next();
1574                        }
1575                       
1576                        if(is_local_forward) {
1577                                var is_lcl_fw = document.createElement('input');
1578                                is_lcl_fw.type = 'hidden';
1579                                is_lcl_fw.name = 'is_local_forward';
1580                                is_lcl_fw.value = "1";
1581                                form.appendChild(is_lcl_fw);
1582                        }
1583                               
1584                }
1585                catch(exception) {
1586                        alert(exception);
1587                }
1588               
1589                this.finalize();
1590                return form;
1591        }
1592
1593        var expresso_local_messages;
1594        expresso_local_messages = new local_messages();
1595        expresso_local_messages.create_objects();
Note: See TracBrowser for help on using the repository browser.