source: branches/2.1/expressoMail1_2/js/local_messages.js @ 1985

Revision 1985, 54.4 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #888 - Replicando no branch 2.1 a correcao descrita no ticket em questao.

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