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

Revision 4857, 54.9 KB checked in by diogenesduarte, 13 years ago (diff)

Ticket #2100 - utilizando prepared statement para inserir e-mail local.

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
714        this.dbGears.execute("update mail set mail=?,header=?,unseen=? where rowid=?",[connector.serialize(mail),connector.serialize(header),unseen,msgs_to_set[i]]);
715
716    }
717    if(Element('chk_box_select_all_messages'))
718        Element('chk_box_select_all_messages').checked = false;
719    this.finalize();
720        if (!no_errors) {
721                if(one_message)
722                        write_msg(get_lang("this message cant be marked as normal"));
723                else
724                        write_msg(get_lang("At least one of selected message cant be marked as normal"));
725                return false;
726        }
727        return true;
728
729}
730       
731local_messages.prototype.set_message_flag = function(msg_number,flag,func_after_flag_change) {
732    no_errors = this.set_messages_flag(msg_number,flag);
733        if(no_errors && func_after_flag_change)
734                func_after_flag_change(true);
735}
736       
737local_messages.prototype.get_unseen_msgs_number = function() {
738    this.init_local_messages();
739    var rs = this.dbGears.execute("select count(*) from mail where unseen=1");
740    var retorno = rs.field(0);
741    rs.close();
742    this.finalize();
743    return retorno;
744}
745
746local_messages.prototype.create_folder = function(folder) {
747
748    if (folder.indexOf("local_") != -1)
749        return false; //can't create folder with string local_
750
751    this.init_local_messages();
752    try {
753        this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",[folder,account_id]);
754    } catch (error) {
755        this.finalize();
756        return false;
757    }
758    this.finalize();
759    return true;
760}
761
762local_messages.prototype.list_local_folders = function(folder) {
763    this.init_local_messages();
764    var retorno = new Array();
765    var retorno_defaults = new Array();
766    rs = this.dbGears.execute("select folder,rowid from folder where uid_usuario=?",[account_id]);
767//    rs = this.dbGears.execute("select folder.folder,sum(mail.unseen) from folder left join mail on "+
768//      "folder.rowid=mail.id_folder where folder.uid_usuario=? group by folder.folder",[account_id]);
769    var achouInbox = false,achouSent = false ,achouSentConf = false,achouTrash = false,achouDrafts = false;
770    while(rs.isValidRow()) {
771        var temp = new Array();
772        temp[0] = rs.field(0);
773        var rs2 = this.dbGears.execute("select count(*) from mail where id_folder=? and unseen=1",[rs.field(1)]);
774         rs2.field(0)? temp[1] = rs2.field(0):temp[1]=0;
775
776        var rs3 = this.dbGears.execute("select * from folder where folder like ? limit 1",[temp[0]+"/%"]);
777        if(rs3.isValidRow())
778            temp[2] = 1;
779        else
780            temp[2] = 0;
781
782        if(sentfolder ==  preferences.save_in_folder.replace("INBOX/","") || preferences.save_in_folder.replace("INBOX/","") == trashfolder || preferences.save_in_folder.replace("INBOX/","") == draftsfolder)
783            achouSentConf= true;
784
785        switch (temp[0]) {
786            case 'Inbox':
787                retorno_defaults[0] = temp;
788                achouInbox = true;
789                break;
790            case sentfolder :
791                retorno_defaults[1] = temp;
792                achouSent = true;
793                break;
794            case trashfolder:
795                retorno_defaults[3] = temp;
796                achouTrash = true;
797                break;
798            case draftsfolder:
799                retorno_defaults[4] = temp;
800                achouDrafts = true;
801                break;
802            case preferences.save_in_folder.replace("INBOX/",""):
803                retorno_defaults[2] = temp;
804                achouSentConf = true;
805                break;
806            default:
807                retorno.push(temp);
808        }
809
810        rs.next();
811    }
812
813    rs.close();
814    this.finalize();
815
816    if(preferences.auto_create_local=='0' || (achouInbox && achouSent && achouSentConf && achouTrash && achouDrafts)){
817        var retorno_final = retorno_defaults.concat(retorno.sort(charOrdA));
818        return retorno_final;
819    }else{
820        if(!achouInbox)
821            this.create_folder('Inbox');
822        if(!achouSent)
823            this.create_folder(sentfolder);
824        if(!achouTrash)
825            this.create_folder(trashfolder);
826        if(!achouDrafts)
827            this.create_folder(draftsfolder);
828        if(!achouSentConf)
829            this.create_folder(preferences.save_in_folder.replace("INBOX/",""));
830        return this.list_local_folders();
831    }
832
833}
834local_messages.prototype.rename_folder = function(folder,old_folder) {
835    if (folder.indexOf("local_") != -1)
836        return false; //can't create folder with string local_
837    this.init_local_messages();
838    if (old_folder.indexOf("/") != "-1") {
839        final_pos = old_folder.lastIndexOf("/");
840        folder = old_folder.substr(0, final_pos) + "/" + folder;
841    }
842    try {
843        this.dbGears.execute("update folder set folder=? where folder=? and uid_usuario=?",[folder,old_folder,account_id]);
844    } catch (error) {
845        this.finalize();
846        return false;
847    }
848    rs = this.dbGears.execute("select folder from folder where folder like ? and uid_usuario=?",[old_folder+'/%',account_id]);
849    while(rs.isValidRow()) {
850        folder_tmp = rs.field(0);
851        folder_new = folder_tmp.replace(old_folder,folder);
852        this.dbGears.execute("update folder set folder=? where folder=?",[folder_new,folder_tmp]);
853        rs.next();
854    }
855
856
857    this.finalize();
858    return true;
859}
860       
861local_messages.prototype.remove_folder = function(folder) {
862    this.init_local_messages();
863    var rs = this.dbGears.execute("select count(rowid) from folder where folder like ? and uid_usuario=?",[folder+"/%",account_id]);
864    var sons = rs.field(0);
865    rs.close();
866
867    if(sons == 0){
868                var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[folder,account_id]);
869                var folder_id = rs.field(0);
870                rs.close();
871                this.dbGears.execute("delete from folder where rowid=?",[folder_id]);
872                rs = this.dbGears.execute("select rowid,mail from mail where id_folder=?",[folder_id]);
873                while(rs.isValidRow()) {
874                    var rs2 = this.dbGears.execute("select url from anexo where id_mail=?",[rs.field(0)]);
875                    while(rs2.isValidRow()) {
876                        this.store.remove(rs2.field(0));
877                        rs2.next();
878                    }
879                    rs2.close();
880                    this.dbGears.execute("delete from anexo where id_mail=?",[rs.field(0)]);
881                    var mail = connector.unserialize(rs.field(1));
882                    this.store.remove(mail.url_export_file);
883                    rs.next();
884                }
885                rs.close();
886                this.dbGears.execute("delete from mail where id_folder=?",[folder_id]);
887                this.finalize();
888                return true;
889    }else  {
890                this.finalize();
891                return false;
892    }
893
894}
895
896local_messages.prototype.move_messages = function(new_folder,msgs_number) {
897    this.init_local_messages();
898    var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[new_folder,account_id]);
899    var id_folder = rs.field(0);
900    rs.close();
901    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...
902    this.finalize();
903}
904
905local_messages.prototype.setFilter = function(sFilter)
906{
907        this.filterSerch = sFilter;
908}
909
910local_messages.prototype.getFilter = function()
911{
912        return this.filterSerch;
913}
914
915local_messages.prototype.search = function(folders,sFilter) {
916    this.init_local_messages();
917    this.setFilter(sFilter);
918    var filters = sFilter.replace(/^##|##$/g,"").split('##');
919    var friendly_filters = new Array();
920
921    if (sFilter.indexOf('ALL') != -1) { //all filters...
922        filters[0] = sFilter.replace(/##/g,"");
923        tmp = filters[0].split("<=>");
924
925        searchKey = new Array();
926        searchKey.push("SUBJECT");
927        searchKey.push(tmp[1]);
928        friendly_filters.push(searchKey);
929
930        searchKey = new Array();
931        searchKey.push("BODY");
932        searchKey.push(tmp[1]);
933        friendly_filters.push(searchKey);
934
935        searchKey = new Array();
936        searchKey.push("FROM");
937        searchKey.push(tmp[1]);
938        friendly_filters.push(searchKey);
939
940        searchKey = new Array();
941        searchKey.push("TO");
942        searchKey.push(tmp[1]);
943        friendly_filters.push(searchKey);
944
945        searchKey = new Array();
946        searchKey.push("CC");
947        searchKey.push(tmp[1]);
948        friendly_filters.push(searchKey);
949    }
950    else {
951        for (var i=0; i<filters.length; i++)
952        {
953            if (filters[i] != ""){
954                //tmp[0] = tmp[0].replace(/^\s+|\s+$/g,"");
955                //tmp[1] = tmp[1].replace(/^\s+|\s+$/g,"");
956                friendly_filters.push(filters[i].split("<=>"));
957            }
958        }
959    }
960    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 (";
961    for(var fnum in folders) {
962        sql+="'"+folders[fnum]+"'";
963        if(fnum<folders.length-1)
964            sql+=",";
965    }
966    sql += ") and (";
967    for (var z=0;z<friendly_filters.length;z++) {
968        if (z != 0) {
969            if (sFilter.indexOf('ALL') != -1)
970                sql += " or";
971            else
972                sql += " and";
973        }
974        var cond = friendly_filters[z][0].replace(/^\s+|\s+$/g,"");
975        if (cond == "SINCE" || cond == "BEFORE" | cond == "ON"){
976
977            tmpDate = friendly_filters[z][1].replace(/\%2F/g,"/").split('/');
978
979            // Date = url_decode(friendly_filters[z][1]);
980            sql+=" mail.timestamp " + this.aux_convert_filter_field(friendly_filters[z][0], tmpDate);
981        }
982        else if (!friendly_filters[z][1])
983        {
984            sql+=" mail."+this.aux_convert_filter_field(friendly_filters[z][0]);
985        }
986        else
987        {
988            sql+=" mail."+this.aux_convert_filter_field(friendly_filters[z][0])+" like '%"+url_decode(friendly_filters[z][1])+"%'";
989        }
990    }
991    sql += ")";
992    var rs = this.dbGears.execute(sql);
993    var retorno = [];
994    var numRec = 0;
995   
996    while( rs.isValidRow() )
997    {
998                var header                      = connector.unserialize( rs.field(0) );
999                var date_formated       = ( header["udate"] ).toString();
1000                /*
1001                 * Antigamente o udate vinha com o formato de data e foi alterado para vir o timestamp.
1002                 * Nesse caso, e-mails arquivados anteriormente usamos o udate, caso contrario, usamos o smalldate,
1003                 * pois o udate agora vem como timestamp
1004                 * verifica tambem no caso de mensagens antigas que nao exista o smalldate
1005                 * definir
1006                */
1007                if( !date_formated.match(/\d{2}\/\d{2}\/\d{4}/) )
1008                {
1009                        if ( (typeof(header["smalldate"]) != "undefined") && (!header["smalldate"].match(/\d{2}\:\d{2}/) ) ){
1010                                date_formated = header["smalldate"];
1011                        }else{
1012                                var day = new Date();
1013                                day.setTime(header["udate"] * 1000);
1014                                aux_dia = day.getDate() < 10 ? '0' + day.getDate() : day.getDate();
1015                                aux_mes = day.getMonth()+1; // array start with '0..11'
1016                                aux_mes = aux_mes < 10 ? '0' + aux_mes : aux_mes;
1017                                date_formated = aux_dia + '/' +  aux_mes + '/' + day.getFullYear();
1018                        }
1019                }
1020
1021                retorno[ numRec++ ] =
1022                {
1023                        'from'          : header["from"]["name"],
1024                        'subject'       : unescape(header["subject"]),
1025                        'udate'         : date_formated,
1026                        'size'          : rs.field(3),
1027                        'flag'          : header["Unseen"]+header["Recent"]+header["Flagged"]+header["Draft"],
1028                        'boxname'       : "local_"+rs.field(1),
1029                        'uid'           : rs.field(2)
1030                }
1031
1032                rs.next();
1033    }
1034
1035    this.finalize();
1036
1037    return ( retorno.length > 0 ) ? retorno : false ;
1038}
1039       
1040local_messages.prototype.aux_convert_size = function(size) {
1041    var tmp = Math.floor(size/1024);
1042    if(tmp >= 1){
1043        return tmp + " kb";
1044    }else{
1045        return size + " b";
1046    }
1047               
1048}
1049       
1050local_messages.prototype.aux_convert_filter_field = function(filter,date)
1051{
1052        var dateObj;
1053   
1054        if (typeof date != 'undefined')
1055    {
1056        dateObj = new Date(date[2],date[1]-1,date[0]);
1057    }
1058
1059    if((filter=="SUBJECT ") || (filter=="SUBJECT"))
1060        return "subject";
1061    else if((filter=="BODY ") || (filter=="BODY"))
1062        return "body";
1063    else if((filter=="FROM ") || (filter=="FROM"))
1064        return "ffrom";
1065    else if((filter=="TO ") || (filter=="TO"))
1066        return "fto";
1067    else if((filter=="CC ") || (filter=="CC"))
1068        return "cc";
1069    else if (filter.replace(/^\s+|\s+$/g,"") == "SINCE"){
1070        dateObj.setHours(0, 0, 0, 0);
1071        return ">= " + dateObj.getTime().toString(10).substr(0, 10);
1072    }
1073    else if (filter.replace(/^\s+|\s+$/g,"") == "BEFORE"){
1074        dateObj.setHours(23, 59, 59, 999);
1075        return "<= " + dateObj.getTime().toString(10).substr(0, 10);
1076    }
1077    else if (filter.replace(/^\s+|\s+$/g,"") == "ON"){
1078        dateObj.setHours(0, 0, 0, 0);
1079        var ts1 = dateObj.getTime().toString(10).substr(0, 10);
1080        dateObj.setHours(23, 59, 59, 999);
1081        var ts2 = dateObj.getTime().toString(10).substr(0, 10);
1082        return ">= " + ts1 + ") and (timestamp <= " + ts2;
1083    }
1084    else if (filter.replace(/^\s+|\s+$/g,"") == "FLAGGED")
1085        return "flagged = 1";
1086    else if (filter.replace(/^\s+|\s+$/g,"") == "UNFLAGGED")
1087        return "flagged = 0";
1088    else if (filter.replace(/^\s+|\s+$/g,"") == "UNSEEN")
1089        return "unseen = 1";
1090    else if (filter.replace(/^\s+|\s+$/g,"") == "SEEN")
1091        return "unseen = 0";
1092    else if (filter.replace(/^\s+|\s+$/g,"") == "ANSWERED")
1093        return "answered = 1";
1094    else if (filter.replace(/^\s+|\s+$/g,"") == "UNANSWERED")
1095        return "answered = 0";
1096    else if (filter.replace(/^\s+|\s+$/g,"") == "RECENT")
1097        return "recent = 1";
1098    else if (filter.replace(/^\s+|\s+$/g,"") == "OLD")
1099        return "recent = 0";
1100
1101}
1102       
1103local_messages.prototype.has_local_mails = function() {
1104    this.init_local_messages();
1105    var rs = this.dbGears.execute("select rowid from folder limit 0,1");
1106    var retorno;
1107    if(rs.isValidRow())
1108        retorno = true;
1109    else
1110        retorno = false;
1111    this.finalize();
1112    return retorno;
1113}
1114
1115//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Simple AJAX function used to get the RFC822 email source.
1116local_messages.prototype.get_src = function(url){
1117    AJAX = false;
1118    if (window.XMLHttpRequest) { // Mozilla, Safari,...
1119        AJAX = new XMLHttpRequest();
1120        if (AJAX.overrideMimeType) {
1121            AJAX.overrideMimeType('text/xml');
1122        }
1123    } else if (window.ActiveXObject) { // IE
1124        try {
1125            AJAX = new ActiveXObject("Msxml2.XMLHTTP");
1126        } catch (e) {
1127            try {
1128                AJAX = new ActiveXObject("Microsoft.XMLHTTP");
1129            } catch (e) {}
1130        }
1131    }
1132
1133    if (!AJAX) {
1134        alert('ERRO :(Seu navegador não suporta a aplicação usada neste site');
1135        return false;
1136    }
1137
1138    AJAX.onreadystatechange = function() {
1139        if (AJAX.readyState == 4) {
1140            AJAX.src=AJAX.responseText;
1141            if (AJAX.status == 200) {
1142                return AJAX.responseText;
1143            } else {
1144                return false;
1145            }
1146        }
1147    }
1148
1149    AJAX.open('get', url, false);
1150    AJAX.send(null);
1151    return AJAX.responseText;
1152};
1153
1154//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
1155//para que elas sejam inseridas no imap pela função  imap_functions.unarchive_mail.
1156local_messages.prototype.unarchive_msgs = function (folder,new_folder,msgs_number){
1157
1158    if(!new_folder)
1159        new_folder='INBOX';
1160    this.init_local_messages();
1161    // alert(folder+new_folder+msgs_number);
1162    var handler_unarchive = function(data)
1163    {
1164                if(data.error == '')
1165                    write_msg(get_lang('All messages are successfully unarchived'));
1166                else
1167                    alert(data.error);
1168    }
1169
1170        if(currentTab.toString().indexOf("_r") != -1){
1171            msgs_number = currentTab.toString().substr(0,currentTab.toString().indexOf("_r"));
1172    }
1173       
1174    if(msgs_number =='selected' || !msgs_number)
1175    {
1176                msgs_number = get_selected_messages()
1177                if (!msgs_number){
1178                    write_msg(get_lang('No selected message.'));
1179                    return;
1180                }
1181                var rs = this.dbGears.execute("select mail,timestamp from mail where rowid in ("+msgs_number+")");
1182                var source="";
1183                var flags="";
1184                var timestamp="";
1185               
1186                while(rs.isValidRow()) {
1187                        mail=connector.unserialize(rs.field(0));
1188                        mail.msg_source?source_tmp = escape(mail.msg_source):source_tmp = escape(this.get_src(mail.url_export_file));
1189                        flags+="#@#@#@"+mail["Answered"]+":"+mail["Draft"]+":"+mail["Flagged"]+":"+mail["Unseen"];
1190                        source+="#@#@#@"+source_tmp;
1191                        timestamp+="#@#@#@"+rs.field(1);
1192                        rs.next();
1193                }
1194                rs.close();
1195                this.finalize();
1196    }
1197    else
1198    {
1199                var rs = this.dbGears.execute("select mail,timestamp from mail where rowid="+msgs_number);
1200                mail=connector.unserialize(rs.field(0));
1201                var source ="";
1202
1203                mail.msg_source?source = mail.msg_source:source = this.get_src(mail.url_export_file);
1204                flags = mail["Answered"]+":"+mail["Draft"]+":"+mail["Flagged"]+":"+mail["Unseen"];
1205                timestamp=rs.field(1);
1206                rs.close();
1207                this.finalize();
1208    }
1209    params="&folder="+new_folder+"&source="+source+"&timestamp="+timestamp+"&flags="+flags;
1210    cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
1211}
1212
1213local_messages.prototype.get_msg_date = function (original_id, is_local){
1214
1215    this.init_local_messages();
1216
1217    if (typeof(is_local) == 'undefined')
1218    {
1219        is_local = false;
1220    }
1221
1222    var rs;
1223
1224    if (is_local)
1225    {
1226        rs = this.dbGears.execute("select mail from mail where rowid="+original_id);
1227    }
1228    else
1229    {
1230        rs = this.dbGears.execute("select mail from mail where original_id="+original_id);
1231    }
1232    var tmp = connector.unserialize(rs.field(0));
1233    var ret = new Array();
1234    ret.fulldate = tmp.fulldate.substr(0,16);
1235    ret.smalldate = tmp.msg_day;
1236    ret.msg_day = tmp.msg_day;
1237    ret.msg_hour = tmp.msg_day;
1238
1239    rs.close();
1240    this.finalize();
1241    return ret;
1242}
1243
1244
1245local_messages.prototype.download_all_local_attachments = function(folder,id){
1246    this.init_local_messages();
1247    var rs = this.dbGears.execute("select mail from mail where rowid="+id);
1248    var tmp = connector.unserialize(rs.field(0));
1249    rs.close();
1250    this.finalize();
1251    tmp.msg_source?source = tmp.msg_source:source = this.get_src(tmp.url_export_file);
1252    //source = this.get_src(tmp.url_export_file);
1253    source = escape(source);
1254    var handler_source = function(data){
1255        download_attachments(null, null, data, null,null,'anexos.zip');
1256    }
1257    cExecute("$this.imap_functions.download_all_local_attachments",handler_source,"source="+source);
1258}
1259
1260/*************************************************************************/
1261/* Funcao usada para exportar mensagens arquivadas localmente.
1262 * Rommel de Brito Cysne (rommel.cysne@serpro.gov.br)
1263 * em 22/12/2008.
1264 */
1265local_messages.prototype.local_messages_to_export = function(){
1266
1267    if (openTab.type[currentTab] > 1){
1268        var msgs_to_export_id = currentTab.substring(0,currentTab.length-2,currentTab);
1269    }else{
1270        var msgs_to_export_id = get_selected_messages();
1271    }
1272    var handler_local_mesgs_to_export = function(data){
1273        download_attachments(null, null, data, null,null,'mensagens.zip');
1274    }
1275    if(msgs_to_export_id){
1276        this.init_local_messages();
1277        var l_msg = "t";
1278        var mesgs ="";
1279        var subjects ="";
1280        var rs = this.dbGears.execute("select mail,subject from mail where rowid in ("+msgs_to_export_id+")");
1281        while(rs.isValidRow()){
1282            mail = connector.unserialize(rs.field(0));
1283            mail.msg_source?src = mail.msg_source:src = this.get_src(mail.url_export_file);
1284            subject = rs.field(1);
1285            mesgs += src;
1286            mesgs += "@@";
1287            subjects += subject;
1288            subjects += "@@";
1289            rs.next();
1290        }
1291        rs.close();
1292        this.finalize();
1293        mesgs = escape(mesgs);
1294        subjects = escape(subjects);
1295        params = "subjects="+subjects+"&mesgs="+mesgs+"&l_msg="+l_msg+"&msgs_to_export="+msgs_to_export_id;
1296        cExecute ("$this.exporteml.makeAll&", handler_local_mesgs_to_export, params);
1297    }
1298    return true;
1299}
1300
1301local_messages.prototype.get_all_local_folder_messages= function(folder_name){
1302
1303
1304    var mesgs = new Array();
1305    var subjects = new Array();
1306    var hoje = new Date();
1307    var msgs_to_export = new Array();
1308    var l_msg="t";
1309
1310    this.init_local_messages();
1311    var query = "select mail,subject,mail.rowid from mail inner join folder on (mail.id_folder=folder.rowid) where folder.folder='" + folder_name + "'";
1312
1313    var rs = this.dbGears.execute(" "+query)
1314
1315    var handler_local_mesgs_to_export = function(data){
1316        //alert("data - " + data + " - tipo - " + typeof(data));
1317        download_attachments(null, null, data, null,null,'mensagens.zip');
1318    }
1319    var j=0;
1320    while (rs.isValidRow()){
1321        msgs_to_export[j]=rs.field(2)
1322        mail = connector.unserialize(rs.field(0));
1323        mail.msg_source?src = mail.msg_source:src = this.get_src(mail.url_export_file);
1324        subject = rs.field(1);
1325        mesgs += src;
1326        mesgs += "@@";
1327        subjects += subject;
1328        subjects += "@@";
1329        rs.next();
1330        j++;
1331
1332    }
1333    rs.close();
1334    this.finalize();
1335    source = escape(mesgs);
1336    subjects = escape(subjects);
1337    params = "folder="+folder_name+"&subjects="+subjects+"&mesgs="+source+"&l_msg="+l_msg+"&msgs_to_export="+msgs_to_export;
1338    cExecute ("$this.exporteml.makeAll&", handler_local_mesgs_to_export, params);
1339         
1340
1341}
1342
1343
1344/*************************************************************************/
1345
1346       
1347/******************************************************************
1348                                        Offline Part
1349 ******************************************************************/
1350
1351local_messages.prototype.is_offline_installed = function() {
1352    this.init_local_messages();
1353    var check = this.localServer.openManagedStore('expresso-offline');
1354    this.finalize();
1355    if(check==null)
1356        return false;
1357    else
1358        return true;
1359               
1360}
1361local_messages.prototype.update_offline = function(redirect) {
1362    this.init_local_messages();
1363    var managedStore = this.localServer.openManagedStore('expresso-offline');
1364
1365    if(managedStore!=null){
1366                       
1367        managedStore.oncomplete = function(details){
1368            if(redirect!=null)
1369                location.href=redirect;
1370        }
1371                       
1372        managedStore.checkForUpdate();
1373    } else if(redirect!=null) {
1374        location.href=redirect;
1375    }
1376    this.finalize();
1377}
1378       
1379local_messages.prototype.uninstall_offline = function() {
1380    if (!window.google || !google.gears) {
1381        temp = confirm(document.getElementById('lang_gears_redirect').value);
1382        if (temp) {
1383            expresso_local_messages.installGears();
1384        }
1385        return;
1386
1387    }
1388    this.init_local_messages();
1389    this.localServer.removeManagedStore('expresso-offline');
1390    alert(document.getElementById('lang_offline_uninstalled').value);
1391    //this.dbGears.execute('drop table user');
1392    //this.dbGears.execute('drop table queue');
1393    //this.dbGears.execute('drop table attachments_queue');
1394    this.finalize();
1395}
1396       
1397local_messages.prototype.get_folders_to_sync = function() {//Precisa ter visibilidade ao array de linguagens.
1398    this.init_local_messages();
1399    var rs = this.dbGears.execute("select id_folder,folder_name from folders_sync where uid_usuario="+account_id);
1400    var retorno = new Array();
1401    while(rs.isValidRow()) {
1402        temp = new Array();
1403        temp[0] = rs.field(0);
1404        if(temp[0]=='INBOX/Drafts' ||temp[0]=='INBOX/Trash' || temp[0]=='INBOX/Sent') {
1405            temp[1] = array_lang[rs.field(1).toLowerCase()];
1406        }
1407        else {
1408            temp[1] = rs.field(1);
1409        }
1410                       
1411        retorno.push(temp);
1412        rs.next();
1413    }
1414    this.finalize();
1415    return retorno;
1416}
1417       
1418local_messages.prototype.install_offline = function(urlOffline,urlIcone,uid_usuario,login,pass,redirect) {
1419    if (!window.google || !google.gears) {
1420        temp = confirm(document.getElementById('lang_gears_redirect').value);
1421        if (temp) {
1422            expresso_local_messages.installGears();
1423        }
1424        return;
1425
1426    }
1427               
1428    if(pass.length>0) {
1429        only_spaces = true;
1430        for(cont=0;cont<pass.length;cont++) {
1431            if(pass.charAt(cont)!=" ")
1432                only_spaces = false;
1433        }
1434        if(only_spaces) {
1435            alert(document.getElementById('lang_only_spaces_not_allowed').value);
1436            return false;
1437        }
1438    }
1439
1440    modal('loading');
1441    var desktop = google.gears.factory.create('beta.desktop');
1442    desktop.createShortcut('ExpressoMail Offline',
1443        urlOffline,
1444                {'32x32': urlIcone},
1445        'ExpressoMail Offline');
1446
1447
1448    this.init_local_messages();
1449
1450    //user with offline needs to have at least the folder Inbox already created.
1451    tmp_rs = this.dbGears.execute("select rowid from folder where folder='Inbox' and uid_usuario=?",[uid_usuario]);
1452    if(!tmp_rs.isValidRow())
1453        this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",['Inbox',uid_usuario]);
1454
1455    this.localServer.removeManagedStore('expresso-offline');
1456       
1457    var managedStore = this.localServer.createManagedStore('expresso-offline');
1458    managedStore.manifestUrl = 'js/manifest';
1459
1460    managedStore.onerror = function (error) {
1461        alert(error);
1462    }
1463               
1464    managedStore.oncomplete = function(details) {
1465        if (close_lightbox_div) {
1466            close_lightbox();
1467            close_lightbox_div = false;
1468            alert(document.getElementById('lang_offline_installed').value);
1469            location.href=redirect;
1470        }
1471    }
1472
1473    //create structure to user in db
1474    this.dbGears.execute('create table if not exists user (uid_usuario int,login text,pass text, logged int,unique(uid_usuario))');
1475    this.dbGears.execute('create table if not exists queue (ffrom text, fto text, cc text, cco text,'+
1476        'subject text, conf_receipt int, important int,body text,sent int,user int)');
1477    this.dbGears.execute('create table if not exists attachments_queue ('+
1478        'id_queue int, url_attach text)');
1479    this.dbGears.execute('create table if not exists sent_problems (' +
1480        'id_queue int,message text)');
1481               
1482    //d = new Date();
1483               
1484    try {
1485        var rs = this.dbGears.execute("select uid_usuario from user where uid_usuario=?",[uid_usuario]);
1486        if(!rs.isValidRow())
1487            this.dbGears.execute("insert into user (uid_usuario,login,pass) values (?,?,?)",[uid_usuario,login,pass]);
1488        else
1489            this.dbGears.execute("update user set pass=? where uid_usuario=?",[pass,uid_usuario]);
1490    } catch (error) {
1491        this.finalize();
1492        alert(error);
1493        return false;
1494    }
1495    managedStore.checkForUpdate();
1496    this.capt_url('controller.php?action=$this.db_functions.get_dropdown_contacts_to_cache');
1497        setTimeout(function(){
1498        managedStore.complete();
1499    }, 60000);
1500    this.finalize();
1501}
1502       
1503/**
1504         * Return all users in an array following the structure below.
1505         *
1506         * key: uid
1507         * value: user login
1508         */
1509local_messages.prototype.get_all_users = function() {
1510    this.init_local_messages();
1511    var users = new Array();
1512    var rs = this.dbGears.execute("select uid_usuario,login from user");
1513    while(rs.isValidRow()) {
1514        users[rs.field(0)] = rs.field(1);
1515        rs.next();
1516    }
1517    this.finalize();
1518    return users;
1519}
1520       
1521local_messages.prototype.set_as_logged = function(uid_usuario,pass,bypass) {
1522    this.init_local_messages();
1523    if (!bypass) {
1524        var rs = this.dbGears.execute("select pass from user where uid_usuario=?", [uid_usuario]);
1525        if (!rs.isValidRow() || (pass != rs.field(0) && pass != MD5(rs.field(0)))) {
1526            this.finalize();
1527            return false;
1528        }
1529    }
1530    d = new Date();
1531
1532    this.dbGears.execute("update user set logged=null"); //Logoff in everybody
1533    this.dbGears.execute("update user set logged=? where uid_usuario=?",[d.getTime(),uid_usuario]); //Login just in one...
1534    this.finalize();
1535    return true;
1536}
1537       
1538local_messages.prototype.unset_as_logged = function() {
1539    this.init_local_messages();
1540    this.dbGears.execute("update user set logged=null"); //Logoff in everybody
1541    this.finalize();
1542}
1543       
1544local_messages.prototype.user_logged = function() {
1545    this.init_local_messages();
1546    var user_logged = new Array();
1547    var rs = this.dbGears.execute("select uid_usuario,logged from user where logged is not null");
1548    if(!rs.isValidRow()) {
1549        this.finalize();
1550        return null;
1551    }
1552    user_logged[0] = rs.field(0);
1553    user_logged[1] = rs.field(1);
1554    this.finalize();
1555    return user_logged;
1556}
1557       
1558local_messages.prototype.send_to_queue = function (form) {
1559    this.init_local_messages();
1560    var mail_values = new Array();
1561               
1562    for (var i=0;i<form.length;i++) {
1563        if (form.elements[i].name != '') { //I.E made me to do that...
1564            if(form.elements[i].name=='folder' || form.elements[i].name=='msg_id' || form.elements[i].name=='' || form.elements[i].name==null)
1565                continue;
1566            else if (form.elements[i].name == 'input_return_receipt' )
1567                mail_values['conf_receipt'] = form.elements[i].checked ? 1 : 0;
1568            else if(form.elements[i].name == 'input_important_message')
1569                mail_values['important'] = form.elements[i].checked ? 1 : 0;
1570            else
1571            if (form.elements[i].name == 'body')
1572                mail_values['body'] = form.elements[i].value;
1573            else
1574            if (form.elements[i].name == 'input_from')
1575                mail_values['ffrom'] = form.elements[i].value;
1576            else
1577            if (form.elements[i].name == 'input_to')
1578                mail_values['fto'] = form.elements[i].value;
1579            else
1580            if (form.elements[i].name == 'input_cc')
1581                mail_values['cc'] = form.elements[i].value;
1582            else
1583            if (form.elements[i].name == 'input_cco')
1584                mail_values['cco'] = form.elements[i].value;
1585            else
1586            if (form.elements[i].name == 'input_subject')
1587                mail_values['subject'] = form.elements[i].value;
1588        }
1589    }
1590    //mail_values['fto'] = input_to;
1591    //mail_values['cc'] = input_cc;
1592    //mail_values['cco'] = input_cco;
1593    //mail_values['subject'] = input_subject;
1594    //mail_values['conf_receipt'] = input_return_receipt;
1595    //mail_values['important'] = input_important_message;
1596               
1597    try {
1598        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]);
1599        this.send_attach_to_queue(this.dbGears.lastInsertRowId,form);
1600    }catch(error) {
1601        alert(error);
1602        return get_lang('Error sending a mail to queue. Verify if you have installed ExpressoMail Offline');
1603    }
1604    this.finalize();
1605    return true;
1606}
1607       
1608local_messages.prototype.send_attach_to_queue = function(id_queue,form) {
1609               
1610    for(i=0;i<form.elements.length;i++) {
1611                       
1612        if(form.elements[i].name.indexOf("file_")!=-1) {
1613            var tmp_input = form.elements[i];
1614            var d = new Date();
1615            var url_local = 'local_attachs/'+d.getTime();
1616            this.store.captureFile(tmp_input, url_local);
1617            this.dbGears.execute("insert into attachments_queue (id_queue,url_attach) values (?,?)",[id_queue,url_local]);
1618        }
1619        else if(form.elements[i].name.indexOf("offline_forward_")!=-1){
1620            //alert();
1621            this.dbGears.execute("insert into attachments_queue (id_queue,url_attach) values (?,?)",[id_queue,form.elements[i].value]);
1622        }
1623    }
1624}
1625
1626       
1627local_messages.prototype.get_num_msgs_to_send = function() {
1628    this.init_local_messages();
1629
1630    var rs = this.dbGears.execute("select count(*) from queue where user=? and sent=0",[account_id]);
1631    var to_return = rs.field(0);
1632
1633    this.finalize();
1634    return to_return;
1635}
1636       
1637local_messages.prototype.set_problem_on_sent = function(rowid_message,msg) {
1638    this.init_local_messages();
1639    this.dbGears.execute("update queue set sent = 2 where rowid=?",[rowid_message]);
1640    this.dbGears.execute("insert into sent_problems (id_queue,message) values (?,?)"[rowid_message,msg]);
1641    this.finalize();
1642}
1643       
1644local_messages.prototype.set_as_sent = function(rowid_message) {
1645    this.init_local_messages();
1646    this.dbGears.execute("update queue set sent = 1 where rowid=?",[rowid_message]);
1647    this.finalize();
1648}
1649       
1650local_messages.prototype.get_form_msg_to_send = function() {
1651    this.init_local_messages();
1652    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]);
1653    if(!rs.isValidRow())
1654        return false;
1655               
1656    var form = document.createElement('form');
1657    form.method = 'POST';
1658    form.name = 'form_queue_'+rs.field(8);
1659    form.style.display = 'none';
1660                form.onsubmit = function(){return false;}
1661    if(!is_ie)
1662        form.enctype="multipart/form-data";
1663    else
1664        form.encoding="multipart/form-data";
1665               
1666    var ffrom = document.createElement('TEXTAREA');
1667    ffrom.name = "input_from";
1668    ffrom.value = rs.field(0);
1669    form.appendChild(ffrom);
1670               
1671    var fto = document.createElement('TEXTAREA');
1672    fto.name = "input_to";
1673    fto.value = rs.field(1);
1674    form.appendChild(fto);
1675               
1676    var cc = document.createElement('TEXTAREA');
1677    cc.name = "input_cc";
1678    cc.value = rs.field(2);
1679    form.appendChild(cc);
1680
1681    var cco = document.createElement('TEXTAREA');
1682    cco.name = "input_cco";
1683    cco.value = rs.field(3);
1684    form.appendChild(cco);
1685               
1686    var subject = document.createElement('TEXTAREA');
1687    subject.name = "input_subject";
1688    subject.value = rs.field(4);
1689    form.appendChild(subject);
1690               
1691    var folder = document.createElement('input');
1692    folder.name='folder';
1693    folder.value=preferences.save_in_folder;
1694    form.appendChild(folder);
1695               
1696    if (rs.field(5) == 1) {
1697        var conf_receipt = document.createElement('input');
1698        conf_receipt.type='text';
1699        conf_receipt.name = "input_return_receipt";
1700        conf_receipt.value = 'on';
1701        form.appendChild(conf_receipt);
1702    }
1703               
1704    if (rs.field(6) == 1) {
1705        var important = document.createElement('input');
1706        important.type='text';
1707        important.name = "input_important_message";
1708        important.value = 'on';
1709        form.appendChild(important);
1710    }
1711               
1712    var body = document.createElement('TEXTAREA');
1713    body.name = "body";
1714    body.value = rs.field(7);
1715    form.appendChild(body);
1716               
1717    var rowid = document.createElement('input');
1718    rowid.type = 'hidden';
1719    rowid.name = 'rowid';
1720    rowid.value = rs.field(8);
1721    form.appendChild(rowid);
1722               
1723    //Mounting the attachs
1724    var divFiles = document.createElement("div");
1725    divFiles.id = 'divFiles_queue_'+rs.field(8);
1726               
1727    form.appendChild(divFiles);
1728               
1729    document.getElementById('forms_queue').appendChild(form);
1730
1731    var is_local_forward = false;
1732    try {
1733                       
1734        var rs_attach = this.dbGears.execute('select url_attach from attachments_queue where id_queue=?', [rs.field(8)]);
1735        while (rs_attach.isValidRow()) {
1736            if(rs_attach.field(0).indexOf('../tmpLclAtt/')==-1) {
1737                tmp_field = addForwardedFile('queue_' + rs.field(8), this.store.getCapturedFileName(rs_attach.field(0)), 'nothing');
1738            }
1739            else {
1740                var tempNomeArquivo = rs_attach.field(0).split("/");
1741                var nomeArquivo = tempNomeArquivo[tempNomeArquivo.length-1];
1742                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.
1743                is_local_forward = true;
1744                tmp_field = addForwardedFile('queue_' + rs.field(8), nomeArquivo, 'nothing');
1745            }
1746            fileSubmitter = this.store.createFileSubmitter();
1747            fileSubmitter.setFileInputElement(tmp_field,rs_attach.field(0));
1748            //          alert(form.innerHTML);
1749            //  div.appendChild(tmp_field);
1750            rs_attach.next();
1751        }
1752                       
1753        if(is_local_forward) {
1754            var is_lcl_fw = document.createElement('input');
1755            is_lcl_fw.type = 'hidden';
1756            is_lcl_fw.name = 'is_local_forward';
1757            is_lcl_fw.value = "1";
1758            form.appendChild(is_lcl_fw);
1759        }
1760                               
1761    }
1762    catch(exception) {
1763        alert(exception);
1764    }
1765               
1766    this.finalize();
1767    return form;
1768}
1769
1770var expresso_local_messages;
1771expresso_local_messages = new local_messages();
1772//expresso_local_messages.create_objects();
Note: See TracBrowser for help on using the repository browser.