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

Revision 4846, 55.2 KB checked in by diogenesduarte, 13 years ago (diff)

Ticket #2099 - mudança da variável de controle do for que era o mesmo do for principal.

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