source: branches/2.2/expressoMail1_2/js/local_messages.js @ 3236

Revision 3236, 54.4 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #1262 - Imagem quebrada na previsualização de msg no arquivamento local.

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