source: trunk/expressoMail1_2/js/jscode/local_messages.js @ 2566

Revision 2566, 54.7 KB checked in by amuller, 14 years ago (diff)

Ticket #1036 - Colocando semicolons nos finais das atribuições

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