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

Revision 3469, 52.1 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #1260 - Caso passado 1 minuto forçamos o fechamento do modal

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