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

Revision 3512, 52.3 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #1322 - Data incorreta nas mensagens na caixa de entrada (local antigas).

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=? order by ';
475               
476    if(sort == 'SORTFROM') {
477        sql += 'order_from ';
478    }
479    if(sort == 'SORTARRIVAL') {
480        sql += 'timestamp ';
481    }
482    if(sort == 'SORTSIZE') {
483        sql += 'size ';
484    }
485    if(sort == 'SORTSUBJECT') {
486        sql += 'UPPER(subject) ';
487    }
488
489
490    sql+= sort_reverse==0?"ASC ":"DESC ";
491    sql +='limit ?,? ';
492
493
494    var rs = this.dbGears.execute(sql,['%'+Element("user_email").value+'%',account_id,folder,msg_range_begin,emails_per_page]);
495    var cont = 0;
496               
497    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]);
498                               
499    while (rs.isValidRow()) {
500        //var email = rs.field(1);
501        var head = rs.field(1);
502        var codigoMail = rs.field(0);
503        var mail = rs.field(6);
504
505        var msg_body = rs.field(5);//recebe o conteudo da coluna "body" do banco de dados;
506
507        var rs2 = this.dbGears.execute('select count(*) from anexo where id_mail = '+codigoMail);
508        var head_unserialized = connector.unserialize(head);
509        var mail_unserialized = connector.unserialize(mail);
510
511      head_unserialized.Size = rs.field(2);
512        if(rs.field(4)==1)
513            head_unserialized.Unseen = 'U';
514                       
515
516        head_unserialized.subject=(head_unserialized.subject==null)?"":head_unserialized.subject;
517
518        //var email_unserialized = connector.unserialize(email);
519        retorno[cont] = head_unserialized;
520        retorno[cont]['msg_number'] = codigoMail;
521        retorno[cont]['msg_day'] = mail_unserialized.msg_day;
522        retorno[cont]['msg_hour'] = mail_unserialized.msg_hour;
523        //declaracao do array() para receber o body de cada mensagem encontrada na busca sql realizada;
524
525        retorno[cont]['msg_sample'] = new Array();
526
527        if( (preview_msg_subject == 0) && (preview_msg_tip == 0) )
528        {
529            retorno[cont]['msg_sample']['body'] = "";
530        }
531        else
532        {
533            msg_body += ">";
534            msg_body=this.strip_tags(msg_body);
535            msg_body=msg_body.replace(/\&nbsp;/ig," ");
536            retorno[cont]['msg_sample']['body'] = " - " + msg_body.substr(2,msg_body.length-1);
537        }
538
539        cont++;
540        rs.next();
541    }
542    retorno['num_msgs'] = rs3.field(0);
543    rs3.close();
544    rs.close();
545    if(cont>0)
546        rs2.close();
547    this.finalize();
548    return retorno;
549}
550       
551local_messages.prototype.get_url_anexo = function(msg_number,pid) {
552    this.init_local_messages();
553    var matches = '';
554    if(matches = this.parse_id_mail(msg_number)) {
555        msg_number = matches[1];
556    }
557               
558    var retorno;
559    var rs = this.dbGears.execute("select url from anexo where id_mail="+msg_number+" and pid = '"+pid+"'");
560    retorno = rs.field(0)
561    this.finalize();
562               
563    return retorno;
564}
565
566local_messages.prototype.getInputFileFromAnexo = function (element,url) {
567    this.init_local_messages();
568    fileSubmitter = this.store.createFileSubmitter();
569    fileSubmitter.setFileInputElement(element,url);
570    this.finalize();
571}
572
573local_messages.prototype.finalize = function() {
574    this.dbGears.close();
575    this.dbGears = null;
576}
577
578local_messages.prototype.delete_msgs = function(msgs_number,border_ID) {
579    this.init_local_messages();
580    var rs = this.dbGears.execute("select url from anexo where id_mail in ("+msgs_number+")");
581    while(rs.isValidRow()) {
582        this.store.remove(rs.field(0));
583        rs.next();
584    }
585    this.dbGears.execute("delete from anexo where id_mail in ("+msgs_number+")");
586    this.dbGears.execute("delete from mail where rowid in ("+msgs_number+")");
587    this.finalize();
588    if (msgs_number.length == 1)
589        write_msg(get_lang("The message was deleted."));
590    else
591        write_msg(get_lang("The messages were deleted."));
592               
593    mail_msg = Element("tbody_box");
594
595    try {
596        msgs_exploded = msgs_number.split(",");
597    }catch(error) {
598        msgs_exploded = new Array();
599        msgs_exploded[0] = msgs_number;
600    }
601    var msg_to_delete;
602    for (var i=0; i<msgs_exploded.length; i++){
603        msg_to_delete = Element(msgs_exploded[i]);
604        if (msg_to_delete){
605            if ( (msg_to_delete.style.backgroundColor != '') && (preferences.use_shortcuts == '1') )
606                select_msg('null', 'down');
607            mail_msg.removeChild(msg_to_delete);
608            decrement_folder_unseen();
609        }
610    }
611    Element('chk_box_select_all_messages').checked = false;
612    if (border_ID != 'null')
613        delete_border(border_ID,'false');
614               
615}
616       
617local_messages.prototype.get_source_msg = function(id_msg) {
618    this.init_local_messages();
619    var rs = this.dbGears.execute("select mail from mail where rowid="+id_msg);
620
621
622    mail = connector.unserialize(rs.field(0));
623    download_local_attachment(mail.url_export_file)
624
625    this.finalize();
626}
627       
628       
629       
630local_messages.prototype.set_messages_flag = function(msgs_number, flag) {
631    this.init_local_messages();
632    var msgs_to_set;
633    if (msgs_number == 'get_selected_messages') {
634        var msgs_to_set = get_selected_messages();
635        msgs_to_set= msgs_to_set.split(",");
636    }
637    else { //Just one message
638        msgs_to_set = new Array();
639        msgs_to_set[0] = msgs_number;
640    }
641    for (var i in msgs_to_set) {
642                       
643        var matches = '';//Messages comming from other tabs.
644        if(matches = this.parse_id_mail(msgs_to_set[i])) {
645            msgs_to_set[i] = matches[1];
646        }
647                       
648        var rs = this.dbGears.execute("select header,unseen from mail where rowid=" + msgs_to_set[i]);
649        header = connector.unserialize(rs.field(0));
650        unseen = rs.field(1);
651        switch(flag) {
652            case "unseen":
653                set_msg_as_unread(msgs_to_set[i]);
654                header["Unseen"] = "U";
655                unseen = 1;
656                break;
657            case "flagged":
658                set_msg_as_flagged(msgs_to_set[i]);
659                header["Flagged"] = "F";
660                break;
661            case "unflagged":
662                if (header["Importance"].indexOf("High") != -1)
663                    write_msg(get_lang("At least one of selected message cant be marked as normal"));
664                else {
665                    set_msg_as_unflagged(msgs_to_set[i]);
666                    header["Flagged"] = "N";
667                }
668                break;
669            case "seen":
670                header["Unseen"] = "N";
671                set_msg_as_read(msgs_to_set[i],true);
672                unseen = 0;
673                break;
674            case "answered":
675                header["Draft"]="";
676                header["Answered"]="A";
677                Element("td_message_answered_"+msgs_to_set[i]).innerHTML = '<img src=templates/default/images/answered.gif title=Respondida>';
678                break;
679            case "forwarded":
680                header["Draft"]="X";
681                header["Answered"]="A";
682                Element("td_message_answered_"+msgs_to_set[i]).innerHTML = '<img src=templates/default/images/forwarded.gif title=Encaminhada>';
683                break;
684        }
685               
686        rs.close();
687                       
688        if(Element("check_box_message_" + msgs_to_set[i]))
689            Element("check_box_message_" + msgs_to_set[i]).checked = false;
690
691        this.dbGears.execute("update mail set header='"+connector.serialize(header)+"',unseen="+unseen+" where rowid="+msgs_to_set[i]);
692    }
693    if(Element('chk_box_select_all_messages'))
694        Element('chk_box_select_all_messages').checked = false;
695    this.finalize();
696
697}
698       
699local_messages.prototype.set_message_flag = function(msg_number,flag) {
700    this.set_messages_flag(msg_number,flag);
701}
702       
703local_messages.prototype.get_unseen_msgs_number = function() {
704    this.init_local_messages();
705    var rs = this.dbGears.execute("select count(*) from mail where unseen=1");
706    var retorno = rs.field(0);
707    rs.close();
708    this.finalize();
709    return retorno;
710}
711
712local_messages.prototype.create_folder = function(folder) {
713
714    if (folder.indexOf("local_") != -1)
715        return false; //can't create folder with string local_
716
717    this.init_local_messages();
718    try {
719        this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",[folder,account_id]);
720    } catch (error) {
721        this.finalize();
722        return false;
723    }
724    this.finalize();
725    return true;
726}
727
728local_messages.prototype.list_local_folders = function(folder) {
729    this.init_local_messages();
730    var retorno = new Array();
731    var retorno_defaults = new Array();
732    rs = this.dbGears.execute("select folder,rowid from folder where uid_usuario=?",[account_id]);
733//    rs = this.dbGears.execute("select folder.folder,sum(mail.unseen) from folder left join mail on "+
734//      "folder.rowid=mail.id_folder where folder.uid_usuario=? group by folder.folder",[account_id]);
735    var achouInbox = false,achouSent = false ,achouSentConf = false,achouTrash = false,achouDrafts = false;
736    while(rs.isValidRow()) {
737        var temp = new Array();
738        temp[0] = rs.field(0);
739        var rs2 = this.dbGears.execute("select count(*) from mail where id_folder=? and unseen=1",[rs.field(1)]);
740         rs2.field(0)? temp[1] = rs2.field(0):temp[1]=0;
741
742        var rs3 = this.dbGears.execute("select * from folder where folder like ? limit 1",[temp[0]+"/%"]);
743        if(rs3.isValidRow())
744            temp[2] = 1;
745        else
746            temp[2] = 0;
747
748        if(sentfolder ==  preferences.save_in_folder.replace("INBOX/","") || preferences.save_in_folder.replace("INBOX/","") == trashfolder || preferences.save_in_folder.replace("INBOX/","") == draftsfolder)
749            achouSentConf= true;
750
751        switch (temp[0]) {
752            case 'Inbox':
753                retorno_defaults[0] = temp;
754                achouInbox = true;
755                break;
756            case sentfolder :
757                retorno_defaults[1] = temp;
758                achouSent = true;
759                break;
760            case trashfolder:
761                retorno_defaults[3] = temp;
762                achouTrash = true;
763                break;
764            case draftsfolder:
765                retorno_defaults[4] = temp;
766                achouDrafts = true;
767                break;
768            case preferences.save_in_folder.replace("INBOX/",""):
769                retorno_defaults[2] = temp;
770                achouSentConf = true;
771                break;
772            default:
773                retorno.push(temp);
774        }
775
776        rs.next();
777    }
778
779    rs.close();
780    this.finalize();
781
782    if(preferences.auto_create_local=='0' || (achouInbox && achouSent && achouSentConf && achouTrash && achouDrafts)){
783        var retorno_final = retorno_defaults.concat(retorno.sort(charOrdA));
784        return retorno_final;
785    }else{
786        if(!achouInbox)
787            this.create_folder('Inbox');
788        if(!achouSent)
789            this.create_folder(sentfolder);
790        if(!achouTrash)
791            this.create_folder(trashfolder);
792        if(!achouDrafts)
793            this.create_folder(draftsfolder);
794        if(!achouSentConf)
795            this.create_folder(preferences.save_in_folder.replace("INBOX/",""));
796        return this.list_local_folders();
797    }
798
799}
800local_messages.prototype.rename_folder = function(folder,old_folder) {
801    if (folder.indexOf("local_") != -1)
802        return false; //can't create folder with string local_
803    this.init_local_messages();
804    if (old_folder.indexOf("/") != "-1") {
805        final_pos = old_folder.lastIndexOf("/");
806        folder = old_folder.substr(0, final_pos) + "/" + folder;
807    }
808    try {
809        this.dbGears.execute("update folder set folder=? where folder=? and uid_usuario=?",[folder,old_folder,account_id]);
810    } catch (error) {
811        this.finalize();
812        return false;
813    }
814    rs = this.dbGears.execute("select folder from folder where folder like ? and uid_usuario=?",[old_folder+'/%',account_id]);
815    while(rs.isValidRow()) {
816        folder_tmp = rs.field(0);
817        folder_new = folder_tmp.replace(old_folder,folder);
818        this.dbGears.execute("update folder set folder=? where folder=?",[folder_new,folder_tmp]);
819        rs.next();
820    }
821
822
823    this.finalize();
824    return true;
825}
826       
827local_messages.prototype.remove_folder = function(folder) {
828    this.init_local_messages();
829    var rs = this.dbGears.execute("select count(rowid) from folder where folder like ? and uid_usuario=?",[folder+"/%",account_id]);
830    var sons = rs.field(0);
831    rs.close();
832
833    if(sons == 0){
834        var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[folder,account_id]);
835        var folder_id = rs.field(0);
836        rs.close();
837        this.dbGears.execute("delete from folder where rowid=?",[folder_id]);
838        rs = this.dbGears.execute("select rowid,mail from mail where id_folder=?",[folder_id]);
839        while(rs.isValidRow()) {
840            var rs2 = this.dbGears.execute("select url from anexo where id_mail=?",[rs.field(0)]);
841            while(rs2.isValidRow()) {
842                this.store.remove(rs2.field(0));
843                rs2.next();
844            }
845            rs2.close();
846            this.dbGears.execute("delete from anexo where id_mail=?",[rs.field(0)]);
847            var mail = connector.unserialize(rs.field(1));
848            this.store.remove(mail.url_export_file);
849            rs.next();
850        }
851        rs.close();
852        this.dbGears.execute("delete from mail where id_folder=?",[folder_id]);
853        return true
854        this.finalize();
855    }else  {
856        return false
857        this.finalize();
858    }
859
860}
861
862local_messages.prototype.move_messages = function(new_folder,msgs_number) {
863    this.init_local_messages();
864    var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[new_folder,account_id]);
865    var id_folder = rs.field(0);
866    rs.close();
867    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...
868    this.finalize();
869}
870       
871local_messages.prototype.search = function(folders,sFilter) {
872    this.init_local_messages();
873    var filters = sFilter.replace(/^##|##$/g,"").split('##');
874    var friendly_filters = new Array();
875
876    if (sFilter.indexOf('ALL') != -1) { //all filters...
877        filters[0] = sFilter.replace(/##/g,"");
878        tmp = filters[0].split("<=>");
879
880        searchKey = new Array();
881        searchKey.push("SUBJECT");
882        searchKey.push(tmp[1]);
883        friendly_filters.push(searchKey);
884
885        searchKey = new Array();
886        searchKey.push("BODY");
887        searchKey.push(tmp[1]);
888        friendly_filters.push(searchKey);
889
890        searchKey = new Array();
891        searchKey.push("FROM");
892        searchKey.push(tmp[1]);
893        friendly_filters.push(searchKey);
894
895        searchKey = new Array();
896        searchKey.push("TO");
897        searchKey.push(tmp[1]);
898        friendly_filters.push(searchKey);
899
900        searchKey = new Array();
901        searchKey.push("CC");
902        searchKey.push(tmp[1]);
903        friendly_filters.push(searchKey);
904    }
905    else {
906        for (var i=0; i<filters.length; i++)
907        {
908            if (filters[i] != ""){
909                //tmp[0] = tmp[0].replace(/^\s+|\s+$/g,"");
910                //tmp[1] = tmp[1].replace(/^\s+|\s+$/g,"");
911                friendly_filters.push(filters[i].split("<=>"));
912            }
913        }
914    }
915    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 (";
916    for(var fnum in folders) {
917        sql+="'"+folders[fnum]+"'";
918        if(fnum<folders.length-1)
919            sql+=",";
920    }
921    sql += ") and (";
922    for (var z=0;z<friendly_filters.length;z++) {
923        if (z != 0) {
924            if (sFilter.indexOf('ALL') != -1)
925                sql += " or";
926            else
927                sql += " and";
928        }
929        var cond = friendly_filters[z][0].replace(/^\s+|\s+$/g,"");
930        if (cond == "SINCE" || cond == "BEFORE" | cond == "ON"){
931
932            tmpDate = friendly_filters[z][1].replace(/\%2F/g,"/").split('/');
933
934            // Date = url_decode(friendly_filters[z][1]);
935            sql+=" mail.timestamp " + this.aux_convert_filter_field(friendly_filters[z][0], tmpDate);
936        }
937        else if (!friendly_filters[z][1])
938        {
939            sql+=" mail."+this.aux_convert_filter_field(friendly_filters[z][0]);
940        }
941        else
942        {
943            sql+=" mail."+this.aux_convert_filter_field(friendly_filters[z][0])+" like '%"+url_decode(friendly_filters[z][1])+"%'";
944        }
945    }
946    sql += ")";
947    var rs = this.dbGears.execute(sql);
948    var retorno = "";
949    while(rs.isValidRow()) {
950        var header = connector.unserialize(rs.field(0));
951        retorno+="##"+"local_"+rs.field(1)+"--"+"local_"+rs.field(1)+"--"+header["from"]["name"]+"--"+header["subject"]+"--"+header["udate"]+"--"+this.aux_convert_size(rs.field(3))+"--"+header["Unseen"]+header["Recent"]+header["Flagged"]+header["Draft"]+"--"+rs.field(2)+"##";
952        rs.next();
953    }
954
955    this.finalize();
956    return retorno==""?false:retorno;
957
958}
959       
960local_messages.prototype.aux_convert_size = function(size) {
961    var tmp = Math.floor(size/1024);
962    if(tmp >= 1){
963        return tmp + " kb";
964    }else{
965        return size + " b";
966    }
967               
968}
969       
970local_messages.prototype.aux_convert_filter_field = function(filter,date) {
971
972var dateObj;
973    if (typeof date != 'undefined'){
974        dateObj=new Date(date[2],date[1]-1,date[0]);
975    }
976
977    if((filter=="SUBJECT ") || (filter=="SUBJECT"))
978        return "subject";
979    else if((filter=="BODY ") || (filter=="BODY"))
980        return "body";
981    else if((filter=="FROM ") || (filter=="FROM"))
982        return "ffrom";
983    else if((filter=="TO ") || (filter=="TO"))
984        return "fto";
985    else if((filter=="CC ") || (filter=="CC"))
986        return "cc";
987    else if (filter.replace(/^\s+|\s+$/g,"") == "SINCE"){
988        dateObj.setHours(0, 0, 0, 0);
989        return ">= " + dateObj.getTime().toString(10).substr(0, 10);
990    }
991    else if (filter.replace(/^\s+|\s+$/g,"") == "BEFORE"){
992        dateObj.setHours(23, 59, 59, 999);
993        return "<= " + dateObj.getTime().toString(10).substr(0, 10);
994    }
995    else if (filter.replace(/^\s+|\s+$/g,"") == "ON"){
996        dateObj.setHours(0, 0, 0, 0);
997        var ts1 = dateObj.getTime().toString(10).substr(0, 10);
998        dateObj.setHours(23, 59, 59, 999);
999        var ts2 = dateObj.getTime().toString(10).substr(0, 10);
1000        return ">= " + ts1 + ") and (timestamp <= " + ts2;
1001    }
1002    else if (filter.replace(/^\s+|\s+$/g,"") == "FLAGGED")
1003        return "flagged = 1";
1004    else if (filter.replace(/^\s+|\s+$/g,"") == "UNFLAGGED")
1005        return "flagged = 0";
1006    else if (filter.replace(/^\s+|\s+$/g,"") == "UNSEEN")
1007        return "unseen = 1";
1008    else if (filter.replace(/^\s+|\s+$/g,"") == "SEEN")
1009        return "unseen = 0";
1010    else if (filter.replace(/^\s+|\s+$/g,"") == "ANSWERED")
1011        return "answered = 1";
1012    else if (filter.replace(/^\s+|\s+$/g,"") == "UNANSWERED")
1013        return "answered = 0";
1014    else if (filter.replace(/^\s+|\s+$/g,"") == "RECENT")
1015        return "recent = 1";
1016    else if (filter.replace(/^\s+|\s+$/g,"") == "OLD")
1017        return "recent = 0";
1018
1019}
1020       
1021local_messages.prototype.has_local_mails = function() {
1022    this.init_local_messages();
1023    var rs = this.dbGears.execute("select rowid from folder limit 0,1");
1024    var retorno;
1025    if(rs.isValidRow())
1026        retorno = true;
1027    else
1028        retorno = false;
1029    this.finalize();
1030    return retorno;
1031}
1032
1033//Por Bruno Costa(bruno.vieira-costa@serpro.gov.br - Simple AJAX function used to get the RFC822 email source.
1034local_messages.prototype.get_src = function(url){
1035    AJAX = false;
1036    if (window.XMLHttpRequest) { // Mozilla, Safari,...
1037        AJAX = new XMLHttpRequest();
1038        if (AJAX.overrideMimeType) {
1039            AJAX.overrideMimeType('text/xml');
1040        }
1041    } else if (window.ActiveXObject) { // IE
1042        try {
1043            AJAX = new ActiveXObject("Msxml2.XMLHTTP");
1044        } catch (e) {
1045            try {
1046                AJAX = new ActiveXObject("Microsoft.XMLHTTP");
1047            } catch (e) {}
1048        }
1049    }
1050
1051    if (!AJAX) {
1052        alert('ERRO :(Seu navegador não suporta a aplicação usada neste site');
1053        return false;
1054    }
1055
1056    AJAX.onreadystatechange = function() {
1057        if (AJAX.readyState == 4) {
1058            AJAX.src=AJAX.responseText;
1059            if (AJAX.status == 200) {
1060                return AJAX.responseText;
1061            } else {
1062                return false;
1063            }
1064        }
1065    }
1066
1067    AJAX.open('get', url, false);
1068    AJAX.send(null);
1069    return AJAX.responseText;
1070};
1071
1072//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
1073//para que elas sejam inseridas no imap pela funᅵᅵo  imap_functions.unarchive_mail.
1074local_messages.prototype.unarchive_msgs = function (folder,new_folder,msgs_number){
1075
1076    if(!new_folder)
1077        new_folder='INBOX';
1078    this.init_local_messages();
1079    // alert(folder+new_folder+msgs_number);
1080    var handler_unarchive = function(data)
1081    {
1082        if(data.error == '')
1083            write_msg(get_lang('All messages are successfully unarchived'));
1084        else
1085            alert(data.error);
1086    }
1087    if(msgs_number =='selected' || !msgs_number)
1088    {
1089        msgs_number = get_selected_messages()
1090        if (!msgs_number){
1091            write_msg(get_lang('No selected message.'));
1092            return;
1093        }
1094        var rs = this.dbGears.execute("select mail,timestamp from mail where rowid in ("+msgs_number+")");
1095        var source="";
1096        var timestamp="";
1097        while(rs.isValidRow()) {
1098            mail=connector.unserialize(rs.field(0));
1099            mail.msg_source?source_tmp = escape(mail.msg_source):source_tmp = escape(this.get_src(mail.url_export_file));
1100//          source_tmp=escape(this.get_src(mail.url_export_file));
1101            source+="#@#@#@"+source_tmp;
1102            timestamp+="#@#@#@"+rs.field(1);
1103            rs.next();
1104        }
1105        rs.close();
1106        this.finalize();
1107    }
1108    else
1109    {
1110        var rs = this.dbGears.execute("select mail,timestamp from mail where rowid="+msgs_number);
1111        mail=connector.unserialize(rs.field(0));
1112        var source ="";
1113//      source = this.get_src(mail.url_export_file);
1114        mail.msg_source?source = mail.msg_source:source = this.get_src(mail.url_export_file);
1115        timestamp=rs.field(1);
1116        rs.close();
1117        this.finalize();
1118    }
1119    params="&folder="+new_folder+"&source="+source+"&timestamp="+timestamp;
1120    cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
1121}
1122
1123local_messages.prototype.get_msg_date = function (original_id, is_local){
1124
1125    this.init_local_messages();
1126
1127    if (typeof(is_local) == 'undefined')
1128    {
1129        is_local = false;
1130    }
1131
1132    var rs;
1133
1134    if (is_local)
1135    {
1136        rs = this.dbGears.execute("select mail from mail where rowid="+original_id);
1137    }
1138    else
1139    {
1140        rs = this.dbGears.execute("select mail from mail where original_id="+original_id);
1141    }
1142    var tmp = connector.unserialize(rs.field(0));
1143    var ret = new Array();
1144    ret.fulldate = tmp.fulldate.substr(0,16);
1145    ret.smalldate = tmp.msg_day;
1146    ret.msg_day = tmp.msg_day;
1147    ret.msg_hour = tmp.msg_day;
1148
1149    rs.close();
1150    this.finalize();
1151    return ret;
1152}
1153
1154
1155local_messages.prototype.download_all_local_attachments = function(folder,id){
1156    this.init_local_messages();
1157    var rs = this.dbGears.execute("select mail from mail where rowid="+id);
1158    var tmp = connector.unserialize(rs.field(0));
1159    rs.close();
1160    this.finalize();
1161    tmp.msg_source?source = tmp.msg_source:source = this.get_src(tmp.url_export_file);
1162    //source = this.get_src(tmp.url_export_file);
1163    source = escape(source);
1164    var handler_source = function(data){
1165        download_attachments(null, null, data, null,null,'anexos.zip');
1166    }
1167    cExecute("$this.imap_functions.download_all_local_attachments",handler_source,"source="+source);
1168}
1169
1170/*************************************************************************/
1171/* Funcao usada para exportar mensagens arquivadas localmente.
1172 * Rommel de Brito Cysne (rommel.cysne@serpro.gov.br)
1173 * em 22/12/2008.
1174 */
1175local_messages.prototype.local_messages_to_export = function(){
1176
1177    if (openTab.type[currentTab] > 1){
1178        var msgs_to_export_id = currentTab.substring(0,currentTab.length-2,currentTab);
1179    }else{
1180        var msgs_to_export_id = get_selected_messages();
1181    }
1182    var handler_local_mesgs_to_export = function(data){
1183        download_attachments(null, null, data, null,null,'mensagens.zip');
1184    }
1185    if(msgs_to_export_id){
1186        this.init_local_messages();
1187        var l_msg = "t";
1188        var mesgs ="";
1189        var subjects ="";
1190        var rs = this.dbGears.execute("select mail,subject from mail where rowid in ("+msgs_to_export_id+")");
1191        while(rs.isValidRow()){
1192            mail = connector.unserialize(rs.field(0));
1193            mail.msg_source?src = mail.msg_source:src = this.get_src(mail.url_export_file);
1194            subject = rs.field(1);
1195            mesgs += src;
1196            mesgs += "@@";
1197            subjects += subject;
1198            subjects += "@@";
1199            rs.next();
1200        }
1201        rs.close();
1202        this.finalize();
1203        mesgs = escape(mesgs);
1204        subjects = escape(subjects);
1205        params = "subjects="+subjects+"&mesgs="+mesgs+"&l_msg="+l_msg+"&msgs_to_export="+msgs_to_export_id;
1206        cExecute ("$this.exporteml.makeAll&", handler_local_mesgs_to_export, params);
1207    }
1208    return true;
1209}
1210
1211local_messages.prototype.get_all_local_folder_messages= function(folder_name){
1212
1213
1214    var mesgs = new Array();
1215    var subjects = new Array();
1216    var hoje = new Date();
1217    var msgs_to_export = new Array();
1218    var l_msg="t";
1219
1220    this.init_local_messages();
1221    var query = "select mail,subject,mail.rowid from mail inner join folder on (mail.id_folder=folder.rowid) where folder.folder='" + folder_name + "'";
1222
1223    var rs = this.dbGears.execute(" "+query)
1224
1225    var handler_local_mesgs_to_export = function(data){
1226        //alert("data - " + data + " - tipo - " + typeof(data));
1227        download_attachments(null, null, data, null,null,'mensagens.zip');
1228    }
1229    var j=0;
1230    while (rs.isValidRow()){
1231        msgs_to_export[j]=rs.field(2)
1232        mail = connector.unserialize(rs.field(0));
1233        mail.msg_source?src = mail.msg_source:src = this.get_src(mail.url_export_file);
1234        subject = rs.field(1);
1235        mesgs += src;
1236        mesgs += "@@";
1237        subjects += subject;
1238        subjects += "@@";
1239        rs.next();
1240        j++;
1241
1242    }
1243    rs.close();
1244    this.finalize();
1245    source = escape(mesgs);
1246    subjects = escape(subjects);
1247    params = "folder="+folder_name+"&subjects="+subjects+"&mesgs="+source+"&l_msg="+l_msg+"&msgs_to_export="+msgs_to_export;
1248    cExecute ("$this.exporteml.makeAll&", handler_local_mesgs_to_export, params);
1249         
1250
1251}
1252
1253
1254/*************************************************************************/
1255
1256       
1257/******************************************************************
1258                                        Offline Part
1259 ******************************************************************/
1260
1261local_messages.prototype.is_offline_installed = function() {
1262    this.init_local_messages();
1263    var check = this.localServer.openManagedStore('expresso-offline');
1264    this.finalize();
1265    if(check==null)
1266        return false;
1267    else
1268        return true;
1269               
1270}
1271local_messages.prototype.update_offline = function(redirect) {
1272    this.init_local_messages();
1273    var managedStore = this.localServer.openManagedStore('expresso-offline');
1274
1275    if(managedStore!=null){
1276                       
1277        managedStore.oncomplete = function(details){
1278            if(redirect!=null)
1279                location.href=redirect;
1280        }
1281                       
1282        managedStore.checkForUpdate();
1283    } else if(redirect!=null) {
1284        location.href=redirect;
1285    }
1286    this.finalize();
1287}
1288       
1289local_messages.prototype.uninstall_offline = function() {
1290    if (!window.google || !google.gears) {
1291        temp = confirm(document.getElementById('lang_gears_redirect').value);
1292        if (temp) {
1293            expresso_local_messages.installGears();
1294        }
1295        return;
1296
1297    }
1298    this.init_local_messages();
1299    this.localServer.removeManagedStore('expresso-offline');
1300    alert(document.getElementById('lang_offline_uninstalled').value);
1301    //this.dbGears.execute('drop table user');
1302    //this.dbGears.execute('drop table queue');
1303    //this.dbGears.execute('drop table attachments_queue');
1304    this.finalize();
1305}
1306       
1307local_messages.prototype.get_folders_to_sync = function() {//Precisa ter visibilidade ao array de linguagens.
1308    this.init_local_messages();
1309    var rs = this.dbGears.execute("select id_folder,folder_name from folders_sync where uid_usuario="+account_id);
1310    var retorno = new Array();
1311    while(rs.isValidRow()) {
1312        temp = new Array();
1313        temp[0] = rs.field(0);
1314        if(temp[0]=='INBOX/Drafts' ||temp[0]=='INBOX/Trash' || temp[0]=='INBOX/Sent') {
1315            temp[1] = array_lang[rs.field(1).toLowerCase()];
1316        }
1317        else {
1318            temp[1] = rs.field(1);
1319        }
1320                       
1321        retorno.push(temp);
1322        rs.next();
1323    }
1324    this.finalize();
1325    return retorno;
1326}
1327       
1328local_messages.prototype.install_offline = function(urlOffline,urlIcone,uid_usuario,login,pass,redirect) {
1329    if (!window.google || !google.gears) {
1330        temp = confirm(document.getElementById('lang_gears_redirect').value);
1331        if (temp) {
1332            expresso_local_messages.installGears();
1333        }
1334        return;
1335
1336    }
1337               
1338    if(pass.length>0) {
1339        only_spaces = true;
1340        for(cont=0;cont<pass.length;cont++) {
1341            if(pass.charAt(cont)!=" ")
1342                only_spaces = false;
1343        }
1344        if(only_spaces) {
1345            alert(document.getElementById('lang_only_spaces_not_allowed').value);
1346            return false;
1347        }
1348    }
1349
1350    modal('loading');
1351    var desktop = google.gears.factory.create('beta.desktop');
1352    desktop.createShortcut('ExpressoMail Offline',
1353        urlOffline,
1354                {'32x32': urlIcone},
1355        'ExpressoMail Offline');
1356
1357
1358    this.init_local_messages();
1359
1360    //user with offline needs to have at least the folder Inbox already created.
1361    tmp_rs = this.dbGears.execute("select rowid from folder where folder='Inbox' and uid_usuario=?",[uid_usuario]);
1362    if(!tmp_rs.isValidRow())
1363        this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",['Inbox',uid_usuario]);
1364
1365    this.localServer.removeManagedStore('expresso-offline');
1366       
1367    var managedStore = this.localServer.createManagedStore('expresso-offline');
1368    managedStore.manifestUrl = 'js/manifest';
1369
1370    managedStore.onerror = function (error) {
1371        alert(error);
1372    }
1373               
1374    managedStore.oncomplete = function(details) {
1375        if (close_lightbox_div) {
1376            close_lightbox();
1377            close_lightbox_div = false;
1378            alert(document.getElementById('lang_offline_installed').value);
1379            location.href=redirect;
1380        }
1381    }
1382
1383    //create structure to user in db
1384    this.dbGears.execute('create table if not exists user (uid_usuario int,login text,pass text, logged int,unique(uid_usuario))');
1385    this.dbGears.execute('create table if not exists queue (ffrom text, fto text, cc text, cco text,'+
1386        'subject text, conf_receipt int, important int,body text,sent int,user int)');
1387    this.dbGears.execute('create table if not exists attachments_queue ('+
1388        'id_queue int, url_attach text)');
1389    this.dbGears.execute('create table if not exists sent_problems (' +
1390        'id_queue int,message text)');
1391               
1392    //d = new Date();
1393               
1394    try {
1395        var rs = this.dbGears.execute("select uid_usuario from user where uid_usuario=?",[uid_usuario]);
1396        if(!rs.isValidRow())
1397            this.dbGears.execute("insert into user (uid_usuario,login,pass) values (?,?,?)",[uid_usuario,login,pass]);
1398        else
1399            this.dbGears.execute("update user set pass=? where uid_usuario=?",[pass,uid_usuario]);
1400    } catch (error) {
1401        this.finalize();
1402        alert(error);
1403        return false;
1404    }
1405    managedStore.checkForUpdate();
1406    this.capt_url('controller.php?action=$this.db_functions.get_dropdown_contacts_to_cache');
1407        setTimeout(function(){
1408        managedStore.complete();
1409    }, 60000);
1410    this.finalize();
1411}
1412       
1413/**
1414         * Return all users in an array following the structure below.
1415         *
1416         * key: uid
1417         * value: user login
1418         */
1419local_messages.prototype.get_all_users = function() {
1420    this.init_local_messages();
1421    var users = new Array();
1422    var rs = this.dbGears.execute("select uid_usuario,login from user");
1423    while(rs.isValidRow()) {
1424        users[rs.field(0)] = rs.field(1);
1425        rs.next();
1426    }
1427    this.finalize();
1428    return users;
1429}
1430       
1431local_messages.prototype.set_as_logged = function(uid_usuario,pass,bypass) {
1432    this.init_local_messages();
1433    if (!bypass) {
1434        var rs = this.dbGears.execute("select pass from user where uid_usuario=?", [uid_usuario]);
1435        if (!rs.isValidRow() || (pass != rs.field(0) && pass != MD5(rs.field(0)))) {
1436            this.finalize();
1437            return false;
1438        }
1439    }
1440    d = new Date();
1441
1442    this.dbGears.execute("update user set logged=null"); //Logoff in everybody
1443    this.dbGears.execute("update user set logged=? where uid_usuario=?",[d.getTime(),uid_usuario]); //Login just in one...
1444    this.finalize();
1445    return true;
1446}
1447       
1448local_messages.prototype.unset_as_logged = function() {
1449    this.init_local_messages();
1450    this.dbGears.execute("update user set logged=null"); //Logoff in everybody
1451    this.finalize();
1452}
1453       
1454local_messages.prototype.user_logged = function() {
1455    this.init_local_messages();
1456    var user_logged = new Array();
1457    var rs = this.dbGears.execute("select uid_usuario,logged from user where logged is not null");
1458    if(!rs.isValidRow()) {
1459        this.finalize();
1460        return null;
1461    }
1462    user_logged[0] = rs.field(0);
1463    user_logged[1] = rs.field(1);
1464    this.finalize();
1465    return user_logged;
1466}
1467       
1468local_messages.prototype.send_to_queue = function (form) {
1469    this.init_local_messages();
1470    var mail_values = new Array();
1471               
1472    for (var i=0;i<form.length;i++) {
1473        if (form.elements[i].name != '') { //I.E made me to do that...
1474            if(form.elements[i].name=='folder' || form.elements[i].name=='msg_id' || form.elements[i].name=='' || form.elements[i].name==null)
1475                continue;
1476            else if (form.elements[i].name == 'input_return_receipt' )
1477                mail_values['conf_receipt'] = form.elements[i].checked ? 1 : 0;
1478            else if(form.elements[i].name == 'input_important_message')
1479                mail_values['important'] = form.elements[i].checked ? 1 : 0;
1480            else
1481            if (form.elements[i].name == 'body')
1482                mail_values['body'] = form.elements[i].value;
1483            else
1484            if (form.elements[i].name == 'input_from')
1485                mail_values['ffrom'] = form.elements[i].value;
1486            else
1487            if (form.elements[i].name == 'input_to')
1488                mail_values['fto'] = form.elements[i].value;
1489            else
1490            if (form.elements[i].name == 'input_cc')
1491                mail_values['cc'] = form.elements[i].value;
1492            else
1493            if (form.elements[i].name == 'input_cco')
1494                mail_values['cco'] = form.elements[i].value;
1495            else
1496            if (form.elements[i].name == 'input_subject')
1497                mail_values['subject'] = form.elements[i].value;
1498        }
1499    }
1500    //mail_values['fto'] = input_to;
1501    //mail_values['cc'] = input_cc;
1502    //mail_values['cco'] = input_cco;
1503    //mail_values['subject'] = input_subject;
1504    //mail_values['conf_receipt'] = input_return_receipt;
1505    //mail_values['important'] = input_important_message;
1506               
1507    try {
1508        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]);
1509        this.send_attach_to_queue(this.dbGears.lastInsertRowId,form);
1510    }catch(error) {
1511        alert(error);
1512        return get_lang('Error sending a mail to queue. Verify if you have installed ExpressoMail Offline');
1513    }
1514    this.finalize();
1515    return true;
1516}
1517       
1518local_messages.prototype.send_attach_to_queue = function(id_queue,form) {
1519               
1520    for(i=0;i<form.elements.length;i++) {
1521                       
1522        if(form.elements[i].name.indexOf("file_")!=-1) {
1523            var tmp_input = form.elements[i];
1524            var d = new Date();
1525            var url_local = 'local_attachs/'+d.getTime();
1526            this.store.captureFile(tmp_input, url_local);
1527            this.dbGears.execute("insert into attachments_queue (id_queue,url_attach) values (?,?)",[id_queue,url_local]);
1528        }
1529        else if(form.elements[i].name.indexOf("offline_forward_")!=-1){
1530            //alert();
1531            this.dbGears.execute("insert into attachments_queue (id_queue,url_attach) values (?,?)",[id_queue,form.elements[i].value]);
1532        }
1533    }
1534}
1535
1536       
1537local_messages.prototype.get_num_msgs_to_send = function() {
1538    this.init_local_messages();
1539
1540    var rs = this.dbGears.execute("select count(*) from queue where user=? and sent=0",[account_id]);
1541    var to_return = rs.field(0);
1542
1543    this.finalize();
1544    return to_return;
1545}
1546       
1547local_messages.prototype.set_problem_on_sent = function(rowid_message,msg) {
1548    this.init_local_messages();
1549    this.dbGears.execute("update queue set sent = 2 where rowid=?",[rowid_message]);
1550    this.dbGears.execute("insert into sent_problems (id_queue,message) values (?,?)"[rowid_message,msg]);
1551    this.finalize();
1552}
1553       
1554local_messages.prototype.set_as_sent = function(rowid_message) {
1555    this.init_local_messages();
1556    this.dbGears.execute("update queue set sent = 1 where rowid=?",[rowid_message]);
1557    this.finalize();
1558}
1559       
1560local_messages.prototype.get_form_msg_to_send = function() {
1561    this.init_local_messages();
1562    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]);
1563    if(!rs.isValidRow())
1564        return false;
1565               
1566    var form = document.createElement('form');
1567    form.method = 'POST';
1568    form.name = 'form_queue_'+rs.field(8);
1569    form.style.display = 'none';
1570                form.onsubmit = function(){return false;}
1571    if(!is_ie)
1572        form.enctype="multipart/form-data";
1573    else
1574        form.encoding="multipart/form-data";
1575               
1576    var ffrom = document.createElement('TEXTAREA');
1577    ffrom.name = "input_from";
1578    ffrom.value = rs.field(0);
1579    form.appendChild(ffrom);
1580               
1581    var fto = document.createElement('TEXTAREA');
1582    fto.name = "input_to";
1583    fto.value = rs.field(1);
1584    form.appendChild(fto);
1585               
1586    var cc = document.createElement('TEXTAREA');
1587    cc.name = "input_cc";
1588    cc.value = rs.field(2);
1589    form.appendChild(cc);
1590
1591    var cco = document.createElement('TEXTAREA');
1592    cco.name = "input_cco";
1593    cco.value = rs.field(3);
1594    form.appendChild(cco);
1595               
1596    var subject = document.createElement('TEXTAREA');
1597    subject.name = "input_subject";
1598    subject.value = rs.field(4);
1599    form.appendChild(subject);
1600               
1601    var folder = document.createElement('input');
1602    folder.name='folder';
1603    folder.value=preferences.save_in_folder;
1604    form.appendChild(folder);
1605               
1606    if (rs.field(5) == 1) {
1607        var conf_receipt = document.createElement('input');
1608        conf_receipt.type='text';
1609        conf_receipt.name = "input_return_receipt";
1610        conf_receipt.value = 'on';
1611        form.appendChild(conf_receipt);
1612    }
1613               
1614    if (rs.field(6) == 1) {
1615        var important = document.createElement('input');
1616        important.type='text';
1617        important.name = "input_important_message";
1618        important.value = 'on';
1619        form.appendChild(important);
1620    }
1621               
1622    var body = document.createElement('TEXTAREA');
1623    body.name = "body";
1624    body.value = rs.field(7);
1625    form.appendChild(body);
1626               
1627    var rowid = document.createElement('input');
1628    rowid.type = 'hidden';
1629    rowid.name = 'rowid';
1630    rowid.value = rs.field(8);
1631    form.appendChild(rowid);
1632               
1633    //Mounting the attachs
1634    var divFiles = document.createElement("div");
1635    divFiles.id = 'divFiles_queue_'+rs.field(8);
1636               
1637    form.appendChild(divFiles);
1638               
1639    document.getElementById('forms_queue').appendChild(form);
1640
1641    var is_local_forward = false;
1642    try {
1643                       
1644        var rs_attach = this.dbGears.execute('select url_attach from attachments_queue where id_queue=?', [rs.field(8)]);
1645        while (rs_attach.isValidRow()) {
1646            if(rs_attach.field(0).indexOf('../tmpLclAtt/')==-1) {
1647                tmp_field = addForwardedFile('queue_' + rs.field(8), this.store.getCapturedFileName(rs_attach.field(0)), 'nothing');
1648            }
1649            else {
1650                var tempNomeArquivo = rs_attach.field(0).split("/");
1651                var nomeArquivo = tempNomeArquivo[tempNomeArquivo.length-1];
1652                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.
1653                is_local_forward = true;
1654                tmp_field = addForwardedFile('queue_' + rs.field(8), nomeArquivo, 'nothing');
1655            }
1656            fileSubmitter = this.store.createFileSubmitter();
1657            fileSubmitter.setFileInputElement(tmp_field,rs_attach.field(0));
1658            //          alert(form.innerHTML);
1659            //  div.appendChild(tmp_field);
1660            rs_attach.next();
1661        }
1662                       
1663        if(is_local_forward) {
1664            var is_lcl_fw = document.createElement('input');
1665            is_lcl_fw.type = 'hidden';
1666            is_lcl_fw.name = 'is_local_forward';
1667            is_lcl_fw.value = "1";
1668            form.appendChild(is_lcl_fw);
1669        }
1670                               
1671    }
1672    catch(exception) {
1673        alert(exception);
1674    }
1675               
1676    this.finalize();
1677    return form;
1678}
1679
1680var expresso_local_messages;
1681expresso_local_messages = new local_messages();
1682//expresso_local_messages.create_objects();
Note: See TracBrowser for help on using the repository browser.