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

Revision 3806, 53.9 KB checked in by eduardoalex, 13 years ago (diff)

Ticket #1570 - Resolvendo o problema de marcar mensagem enviada como importante, como normal

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