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

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

Ticket #931 - 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                   
778                this.finalize();
779                return true;
780                }else  {
781                   
782                    this.finalize();
783                        return false;
784        }
785
786        }
787
788        local_messages.prototype.move_messages = function(new_folder,msgs_number) {
789                this.init_local_messages();
790                var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[new_folder,account_id]);
791                var id_folder = rs.field(0);
792                rs.close();
793                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...
794                this.finalize();
795        }
796       
797        local_messages.prototype.search = function(folders,sFilter) {
798                this.init_local_messages();
799                var filters = sFilter.replace(/^##|##$/g,"").split('##');
800                var friendly_filters = new Array();
801
802                if (sFilter.indexOf('ALL') != -1) { //all filters...
803                    filters[0] = sFilter.replace(/##/g,"");
804                    tmp = filters[0].split("<=>");
805
806                    searchKey = new Array();
807                    searchKey.push("SUBJECT");
808                    searchKey.push(tmp[1]);
809                    friendly_filters.push(searchKey);
810
811                    searchKey = new Array();
812                    searchKey.push("BODY");
813                    searchKey.push(tmp[1]);
814                    friendly_filters.push(searchKey);
815
816                    searchKey = new Array();
817                    searchKey.push("FROM");
818                    searchKey.push(tmp[1]);
819                    friendly_filters.push(searchKey);
820
821                    searchKey = new Array();
822                    searchKey.push("TO");
823                    searchKey.push(tmp[1]);
824                    friendly_filters.push(searchKey);
825
826                    searchKey = new Array();
827                    searchKey.push("CC");
828                    searchKey.push(tmp[1]);
829                    friendly_filters.push(searchKey);
830                }
831                else {
832                    for (var i=0; i<filters.length; i++)
833                    {
834                        if (filters[i] != ""){
835                            //tmp[0] = tmp[0].replace(/^\s+|\s+$/g,"");
836                            //tmp[1] = tmp[1].replace(/^\s+|\s+$/g,"");
837                            friendly_filters.push(filters[i].split("<=>"));
838                        }
839                    }
840                }
841                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 (";
842                for(var fnum in folders) {
843                        sql+="'"+folders[fnum]+"'";
844                        if(fnum<folders.length-1)
845                                sql+=",";
846                }
847                sql += ") and (";
848                for (var z=0;z<friendly_filters.length;z++) {
849                    if (z != 0) {
850                        if (sFilter.indexOf('ALL') != -1)
851                            sql += " or";
852                        else
853                            sql += " and";
854                    }
855                    var cond = friendly_filters[z][0].replace(/^\s+|\s+$/g,"");
856                    if (cond == "SINCE" || cond == "BEFORE" | cond == "ON"){
857
858                        tmpDate = url_decode(friendly_filters[z][1]).split('/');
859
860                        // Date = url_decode(friendly_filters[z][1]);
861                        sql+=" mail.timestamp " + this.aux_convert_filter_field(friendly_filters[z][0], tmpDate);
862                    }
863                    else if (!friendly_filters[z][1])
864                        {
865                            sql+=" mail."+this.aux_convert_filter_field(friendly_filters[z][0]);
866                        }
867                        else
868                            {
869                                sql+=" mail."+this.aux_convert_filter_field(friendly_filters[z][0])+" like '%"+url_decode(friendly_filters[z][1])+"%'";
870                            }
871                }
872                sql += ")";
873                var rs = this.dbGears.execute(sql);
874                var retorno = "";
875                while(rs.isValidRow()) {
876                    var header = connector.unserialize(rs.field(0));
877                    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)+"##";
878                    rs.next();
879                }
880
881                this.finalize();
882                return retorno==""?false:retorno;
883
884        }
885       
886        local_messages.prototype.aux_convert_size = function(size) {
887                var tmp = Math.floor(size/1024);
888                if(tmp >= 1){
889                        return tmp + " kb";     
890                }else{
891                        return size + " b";     
892                }
893               
894        }
895       
896        local_messages.prototype.aux_convert_filter_field = function(filter,date) {
897                if (typeof date != 'undefined'){
898                    var dateObj=new Date();
899                    dateObj.setFullYear(date[2],date[1]-1,date[0]);
900                }
901
902                if((filter=="SUBJECT ") || (filter=="SUBJECT"))
903                        return "subject";
904                else if((filter=="BODY ") || (filter=="BODY"))
905                        return "body";
906                else if((filter=="FROM ") || (filter=="FROM"))
907                        return "ffrom";
908                else if((filter=="TO ") || (filter=="TO"))
909                        return "fto";
910                else if((filter=="CC ") || (filter=="CC"))
911                        return "cc";
912                else if (filter.replace(/^\s+|\s+$/g,"") == "SINCE"){
913                        dateObj.setHours(0, 0, 0, 0);
914                        return ">= " + dateObj.getTime().toString(10).substr(0, 10);
915                }
916                else if (filter.replace(/^\s+|\s+$/g,"") == "BEFORE"){
917                        dateObj.setHours(23, 59, 59, 999);
918                        return "<= " + dateObj.getTime().toString(10).substr(0, 10);
919                }
920                else if (filter.replace(/^\s+|\s+$/g,"") == "ON"){
921                        dateObj.setHours(0, 0, 0, 0);
922                        var ts1 = dateObj.getTime().toString(10).substr(0, 10);
923                        dateObj.setHours(23, 59, 59, 999);
924                        var ts2 = dateObj.getTime().toString(10).substr(0, 10);
925                        return ">= " + ts1 + ") and (timestamp <= " + ts2;
926                }
927                else if (filter.replace(/^\s+|\s+$/g,"") == "FLAGGED")
928                        return "flagged = 1";
929                else if (filter.replace(/^\s+|\s+$/g,"") == "UNFLAGGED")
930                        return "flagged = 0";
931                else if (filter.replace(/^\s+|\s+$/g,"") == "UNSEEN")
932                        return "unseen = 1";
933                else if (filter.replace(/^\s+|\s+$/g,"") == "SEEN")
934                        return "unseen = 0";
935                else if (filter.replace(/^\s+|\s+$/g,"") == "ANSWERED")
936                        return "answered = 1";
937                else if (filter.replace(/^\s+|\s+$/g,"") == "UNANSWERED")
938                        return "answered = 0";
939                else if (filter.replace(/^\s+|\s+$/g,"") == "RECENT")
940                        return "recent = 1";
941                else if (filter.replace(/^\s+|\s+$/g,"") == "OLD")
942                        return "recent = 0";
943
944        }
945       
946        local_messages.prototype.has_local_mails = function() {
947                this.init_local_messages();
948                var rs = this.dbGears.execute("select rowid from folder limit 0,1");
949                var retorno;
950                if(rs.isValidRow())
951                        retorno = true;
952                else
953                        retorno = false;
954                this.finalize();
955                return retorno;
956        }
957
958     //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).
959    local_messages.prototype.get_src = function(url){
960        AJAX = false;
961        if (window.XMLHttpRequest) { // Mozilla, Safari,...
962            AJAX = new XMLHttpRequest();
963            if (AJAX.overrideMimeType) {
964                AJAX.overrideMimeType('text/xml');
965            }
966        } else if (window.ActiveXObject) { // IE
967            try {
968                AJAX = new ActiveXObject("Msxml2.XMLHTTP");
969            } catch (e) {
970                try {
971                AJAX = new ActiveXObject("Microsoft.XMLHTTP");
972                } catch (e) {}
973            }
974        }
975
976        if (!AJAX) {
977            alert('ERRO :(Seu navegador nï¿œo suporta a aplicaᅵᅵo usada neste site');
978            return false;
979        }
980
981        AJAX.onreadystatechange = function() {
982            if (AJAX.readyState == 4) {
983                AJAX.src=AJAX.responseText;
984                if (AJAX.status == 200) {
985                    return AJAX.responseText;
986                    } else {
987                    return false;
988                }
989            }
990        }
991
992        AJAX.open('get', url, false);
993        AJAX.send(null);
994        return AJAX.responseText;
995    };
996
997  //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
998  //para que elas sejam inseridas no imap pela funᅵᅵo  imap_functions.unarchive_mail.
999    local_messages.prototype.unarchive_msgs = function (folder,new_folder,msgs_number){
1000
1001        if(!new_folder)
1002            new_folder='INBOX';
1003        this.init_local_messages();
1004       // alert(folder+new_folder+msgs_number);
1005        var handler_unarchive = function(data)
1006        {
1007            if(data.error == '')
1008                write_msg(get_lang('All messages are successfully unarchived'));
1009            else
1010                alert(data.error);
1011        }
1012        if(msgs_number =='selected' || !msgs_number)
1013        {
1014            msgs_number = get_selected_messages()
1015            if (!msgs_number){
1016                write_msg(get_lang('No selected message.'));
1017                return;
1018            }
1019            var rs = this.dbGears.execute("select mail,timestamp from mail where rowid in ("+msgs_number+")");
1020            var source="";
1021            var timestamp="";
1022            while(rs.isValidRow()) {
1023                mail=connector.unserialize(rs.field(0));
1024                source_tmp=escape(this.get_src(mail.url_export_file));
1025                    source+="#@#@#@"+source_tmp;
1026                    timestamp+="#@#@#@"+rs.field(1);
1027                rs.next();
1028            }
1029            rs.close();
1030            this.finalize();
1031        }
1032        else
1033        {
1034            var rs = this.dbGears.execute("select mail,timestamp from mail where rowid="+msgs_number);
1035            mail=connector.unserialize(rs.field(0));
1036            var source ="";
1037            source = this.get_src(mail.url_export_file);
1038            timestamp=rs.field(1);
1039             rs.close();
1040             this.finalize();
1041        }
1042            params="&folder="+new_folder+"&source="+source+"&timestamp="+timestamp;
1043            cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
1044    }
1045
1046    local_messages.prototype.get_msg_date = function (original_id, is_local){
1047
1048        this.init_local_messages();
1049
1050        if (typeof(is_local) == 'undefined')
1051        {
1052            is_local = false;
1053        }
1054
1055        var rs;
1056
1057        if (is_local)
1058        {
1059            rs = this.dbGears.execute("select mail from mail where rowid="+original_id);
1060        }
1061        else
1062        {
1063            rs = this.dbGears.execute("select mail from mail where original_id="+original_id);
1064        }
1065        var tmp = connector.unserialize(rs.field(0));
1066        var ret = new Array();
1067        ret.fulldate = tmp.fulldate.substr(0,16);
1068        ret.smalldate = tmp.msg_day;
1069        ret.msg_day = tmp.msg_day;
1070        ret.msg_hour = tmp.msg_day;
1071
1072        rs.close();
1073        this.finalize();
1074        return ret;
1075    }
1076
1077
1078    local_messages.prototype.download_all_local_attachments = function(folder,id){
1079        this.init_local_messages();
1080        var rs = this.dbGears.execute("select mail from mail where rowid="+id);
1081        var tmp = connector.unserialize(rs.field(0));
1082        rs.close();
1083        this.finalize();
1084        source = this.get_src(tmp.url_export_file);
1085        source = escape(source);
1086        var handler_source = function(data){
1087            download_attachments(null, null, data, null,null,'anexos.zip');
1088        }
1089        cExecute("$this.imap_functions.download_all_local_attachments",handler_source,"source="+source);
1090    }
1091
1092    /*************************************************************************/
1093/* Funcao usada para exportar mensagens arquivadas localmente.
1094 * Rommel de Brito Cysne (rommel.cysne@serpro.gov.br)
1095 * em 22/12/2008.
1096 */
1097    local_messages.prototype.local_messages_to_export = function(){
1098
1099        if (openTab.type[currentTab] > 1){
1100            var msgs_to_export_id = currentTab.substring(0,currentTab.length-2,currentTab);
1101        }else{
1102            var msgs_to_export_id = get_selected_messages();
1103        }
1104        var handler_local_mesgs_to_export = function(data){
1105            download_attachments(null, null, data, null,null,'mensagens.zip');
1106        }
1107        if(msgs_to_export_id){
1108            this.init_local_messages();
1109            var l_msg = "t";
1110            var mesgs ="";
1111            var subjects ="";
1112            var rs = this.dbGears.execute("select mail,subject from mail where rowid in ("+msgs_to_export_id+")");
1113            while(rs.isValidRow()){
1114                mail = connector.unserialize(rs.field(0));
1115                mail.msg_source?src = mail.msg_source:src = this.get_src(mail.url_export_file);
1116                subject = rs.field(1);
1117                mesgs += src;
1118                mesgs += "@@";
1119                subjects += subject;
1120                subjects += "@@";
1121                rs.next();
1122            }
1123            rs.close();
1124            this.finalize();
1125            mesgs = escape(mesgs);
1126            subjects = escape(subjects);
1127            params = "subjects="+subjects+"&mesgs="+mesgs+"&l_msg="+l_msg+"&msgs_to_export="+msgs_to_export_id;
1128            cExecute ("$this.exporteml.makeAll&", handler_local_mesgs_to_export, params);
1129        }
1130        return true;
1131    }
1132
1133    local_messages.prototype.get_all_local_folder_messages= function(folder_name){
1134
1135
1136         var mesgs = new Array();
1137         var subjects = new Array();
1138         var hoje = new Date();
1139         var msgs_to_export = new Array();
1140         var l_msg="t";
1141
1142        this.init_local_messages();
1143        var query = "select mail,subject,mail.rowid from mail inner join folder on (mail.id_folder=folder.rowid) where folder.folder='" + folder_name + "'";
1144
1145        var rs = this.dbGears.execute(" "+query)
1146
1147            var handler_local_mesgs_to_export = function(data){
1148                    //alert("data - " + data + " - tipo - " + typeof(data));
1149                    download_attachments(null, null, data, null,null,'mensagens.zip');
1150            }
1151        var j=0;
1152        while (rs.isValidRow()){
1153              msgs_to_export[j]=rs.field(2)
1154              mail = connector.unserialize(rs.field(0));
1155                      mail.msg_source?src = mail.msg_source:src = this.get_src(mail.url_export_file);
1156                      subject = rs.field(1);
1157                      mesgs += msg;
1158                      mesgs += "@@";
1159                      subjects += subject;
1160                      subjects += "@@";
1161                      rs.next();
1162              j++;
1163
1164        }
1165           rs.close();
1166           this.finalize();
1167           source = escape(mesgs);
1168           subjects = escape(subjects);
1169           params = "folder="+folder_name+"&subjects="+subjects+"&mesgs="+source+"&l_msg="+l_msg+"&msgs_to_export="+msgs_to_export;
1170           cExecute ("$this.exporteml.makeAll&", handler_local_mesgs_to_export, params);
1171         
1172
1173    }
1174
1175
1176    /*************************************************************************/
1177
1178       
1179/******************************************************************
1180                                        Offline Part
1181 ******************************************************************/
1182
1183        local_messages.prototype.is_offline_installed = function() {
1184                this.init_local_messages();
1185                var check = this.localServer.openManagedStore('expresso-offline');
1186                this.finalize();
1187                if(check==null)
1188                        return false;
1189                else
1190                        return true;
1191               
1192        }
1193        local_messages.prototype.update_offline = function(redirect) {
1194                this.init_local_messages();
1195                var managedStore = this.localServer.openManagedStore('expresso-offline');
1196
1197                if(managedStore!=null){
1198                       
1199                        managedStore.oncomplete = function(details){
1200                                if(redirect!=null)
1201                                        location.href=redirect;
1202                        }
1203                       
1204                        managedStore.checkForUpdate();
1205                } else if(redirect!=null) {
1206                        location.href=redirect;
1207                }
1208                this.finalize();
1209        }
1210       
1211        local_messages.prototype.uninstall_offline = function() {
1212                if (!window.google || !google.gears) {
1213                                temp = confirm(document.getElementById('lang_gears_redirect').value);
1214                                if (temp) {
1215                                        expresso_local_messages.installGears();
1216                                }
1217                                return;
1218
1219                }
1220                this.init_local_messages();
1221                this.localServer.removeManagedStore('expresso-offline');
1222                alert(document.getElementById('lang_offline_uninstalled').value);
1223                //this.dbGears.execute('drop table user');
1224                //this.dbGears.execute('drop table queue');
1225                //this.dbGears.execute('drop table attachments_queue');
1226                this.finalize();
1227        }
1228       
1229        local_messages.prototype.get_folders_to_sync = function() {//Precisa ter visibilidade ao array de linguagens.
1230                this.init_local_messages();
1231                var rs = this.dbGears.execute("select id_folder,folder_name from folders_sync where uid_usuario="+account_id);
1232                var retorno = new Array();
1233                while(rs.isValidRow()) {
1234                        temp = new Array();
1235                        temp[0] = rs.field(0);
1236                        if(temp[0]=='INBOX/Drafts' ||temp[0]=='INBOX/Trash' || temp[0]=='INBOX/Sent') {
1237                                temp[1] = array_lang[rs.field(1).toLowerCase()];
1238                        }
1239                        else {
1240                                temp[1] = rs.field(1); 
1241                        }
1242                       
1243                        retorno.push(temp);
1244                        rs.next();
1245                }
1246                this.finalize();
1247                return retorno;
1248        }
1249       
1250        local_messages.prototype.install_offline = function(urlOffline,urlIcone,uid_usuario,login,pass,redirect) {
1251                if (!window.google || !google.gears) {
1252                                temp = confirm(document.getElementById('lang_gears_redirect').value);
1253                                if (temp) {
1254                                         expresso_local_messages.installGears();
1255                                }
1256                                return;
1257
1258                }
1259               
1260                if(pass.length>0) {
1261                        only_spaces = true;
1262                        for(cont=0;cont<pass.length;cont++) {
1263                                if(pass.charAt(cont)!=" ")
1264                                        only_spaces = false;
1265                        }
1266                        if(only_spaces) {
1267                                alert(document.getElementById('lang_only_spaces_not_allowed').value);
1268                                return false;
1269                        }
1270                }
1271
1272                modal('loading');
1273                var desktop = google.gears.factory.create('beta.desktop');
1274                desktop.createShortcut('ExpressoMail Offline',
1275                        urlOffline,
1276                {'32x32': urlIcone},
1277                'ExpressoMail Offline');
1278
1279
1280                this.init_local_messages();
1281
1282                //user with offline needs to have at least the folder Inbox already created.
1283                tmp_rs = this.dbGears.execute("select rowid from folder where folder='Inbox' and uid_usuario=?",[uid_usuario]);
1284                if(!tmp_rs.isValidRow())
1285                        this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",['Inbox',uid_usuario]);
1286
1287                this.localServer.removeManagedStore('expresso-offline');
1288       
1289                var managedStore = this.localServer.createManagedStore('expresso-offline');
1290                managedStore.manifestUrl = 'js/manifest';
1291
1292                managedStore.onerror = function (error) {
1293                        alert(error);
1294                }
1295               
1296                managedStore.oncomplete = function(details) {
1297                        if (close_lightbox_div) {
1298                                close_lightbox();
1299                                close_lightbox_div = false;
1300                                alert(document.getElementById('lang_offline_installed').value);
1301                                location.href=redirect;
1302                        }
1303                }
1304
1305                //create structure to user in db
1306                this.dbGears.execute('create table if not exists user (uid_usuario int,login text,pass text, logged int,unique(uid_usuario))');
1307                this.dbGears.execute('create table if not exists queue (ffrom text, fto text, cc text, cco text,'+
1308                        'subject text, conf_receipt int, important int,body text,sent int,user int)');
1309                this.dbGears.execute('create table if not exists attachments_queue ('+
1310                        'id_queue int, url_attach text)');
1311                this.dbGears.execute('create table if not exists sent_problems (' +
1312                        'id_queue int,message text)');
1313               
1314                //d = new Date();
1315               
1316                try {
1317                        var rs = this.dbGears.execute("select uid_usuario from user where uid_usuario=?",[uid_usuario]);
1318                        if(!rs.isValidRow())
1319                                this.dbGears.execute("insert into user (uid_usuario,login,pass) values (?,?,?)",[uid_usuario,login,pass]);
1320                        else
1321                                this.dbGears.execute("update user set pass=? where uid_usuario=?",[pass,uid_usuario]);
1322                } catch (error) {
1323                        this.finalize();
1324                        alert(error);
1325                        return false;
1326                }
1327                managedStore.checkForUpdate();
1328                this.capt_url('controller.php?action=$this.db_functions.get_dropdown_contacts_to_cache');
1329               
1330                this.finalize();
1331        }
1332       
1333        /**
1334         * Return all users in an array following the structure below.
1335         *
1336         * key: uid
1337         * value: user login
1338         */
1339        local_messages.prototype.get_all_users = function() {
1340                this.init_local_messages();
1341                var users = new Array();
1342                var rs = this.dbGears.execute("select uid_usuario,login from user");
1343                while(rs.isValidRow()) {
1344                        users[rs.field(0)] = rs.field(1);
1345                        rs.next();
1346                }
1347                this.finalize();
1348                return users;
1349        }
1350       
1351        local_messages.prototype.set_as_logged = function(uid_usuario,pass) {
1352                this.init_local_messages();
1353                var rs = this.dbGears.execute("select pass from user where uid_usuario=?",[uid_usuario]);
1354                if(!rs.isValidRow() || (pass!=rs.field(0) && pass!=MD5(rs.field(0))) ) {
1355                        this.finalize();
1356                        return false;
1357                }
1358                d = new Date();
1359
1360                this.dbGears.execute("update user set logged=null"); //Logoff in everybody
1361                this.dbGears.execute("update user set logged=? where uid_usuario=?",[d.getTime(),uid_usuario]); //Login just in one...
1362                this.finalize();
1363                return true;
1364        }
1365       
1366        local_messages.prototype.unset_as_logged = function() {
1367                this.init_local_messages();
1368                this.dbGears.execute("update user set logged=null"); //Logoff in everybody
1369                this.finalize();
1370        }
1371       
1372        local_messages.prototype.user_logged = function() {
1373                this.init_local_messages();
1374                var user_logged = new Array();
1375                var rs = this.dbGears.execute("select uid_usuario,logged from user where logged is not null");
1376                if(!rs.isValidRow()) {
1377                        this.finalize();
1378                        return null;
1379                }
1380                user_logged[0] = rs.field(0);
1381                user_logged[1] = rs.field(1);
1382                this.finalize();
1383                return user_logged;
1384        }
1385       
1386        local_messages.prototype.send_to_queue = function (form) {
1387                this.init_local_messages();
1388                var mail_values = new Array();
1389               
1390                for (var i=0;i<form.length;i++) {
1391                        if (form.elements[i].name != '') { //I.E made me to do that...
1392                                if(form.elements[i].name=='folder' || form.elements[i].name=='msg_id' || form.elements[i].name=='' || form.elements[i].name==null)
1393                                        continue;
1394                                else if (form.elements[i].name == 'input_return_receipt' )
1395                                        mail_values['conf_receipt'] = form.elements[i].checked ? 1 : 0;
1396                                else if(form.elements[i].name == 'input_important_message')
1397                                        mail_values['important'] = form.elements[i].checked ? 1 : 0;
1398                                else
1399                                        if (form.elements[i].name == 'body')
1400                                                mail_values['body'] = form.elements[i].value;
1401                                        else
1402                                                if (form.elements[i].name == 'input_from')
1403                                                        mail_values['ffrom'] = form.elements[i].value;
1404                                                else
1405                                                        if (form.elements[i].name == 'input_to')
1406                                                                mail_values['fto'] = form.elements[i].value;
1407                                                        else
1408                                                                if (form.elements[i].name == 'input_cc')
1409                                                                        mail_values['cc'] = form.elements[i].value;
1410                                                                else
1411                                                                        if (form.elements[i].name == 'input_cco')
1412                                                                                mail_values['cco'] = form.elements[i].value;
1413                                                                        else
1414                                                                                if (form.elements[i].name == 'input_subject')
1415                                                                                        mail_values['subject'] = form.elements[i].value;
1416                        }
1417                }
1418                //mail_values['fto'] = input_to;
1419                //mail_values['cc'] = input_cc;
1420                //mail_values['cco'] = input_cco;
1421                //mail_values['subject'] = input_subject;
1422                //mail_values['conf_receipt'] = input_return_receipt;
1423                //mail_values['important'] = input_important_message;
1424               
1425                try {
1426                        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]);
1427                        this.send_attach_to_queue(this.dbGears.lastInsertRowId,form);
1428                }catch(error) {
1429                        alert(error);
1430                        return get_lang('Error sending a mail to queue. Verify if you have installed ExpressoMail Offline');
1431                }
1432                this.finalize();
1433                return true;
1434        }
1435       
1436        local_messages.prototype.send_attach_to_queue = function(id_queue,form) {
1437               
1438                for(i=0;i<form.elements.length;i++) {
1439                       
1440                        if(form.elements[i].name.indexOf("file_")!=-1) {
1441                                var tmp_input = form.elements[i];
1442                                var d = new Date();
1443                                var url_local = 'local_attachs/'+d.getTime();
1444                                this.store.captureFile(tmp_input, url_local);
1445                                this.dbGears.execute("insert into attachments_queue (id_queue,url_attach) values (?,?)",[id_queue,url_local]);
1446                        }
1447                        else if(form.elements[i].name.indexOf("offline_forward_")!=-1){
1448                                //alert();
1449                                this.dbGears.execute("insert into attachments_queue (id_queue,url_attach) values (?,?)",[id_queue,form.elements[i].value]);
1450                        }
1451                }
1452        }
1453
1454       
1455        local_messages.prototype.get_num_msgs_to_send = function() {
1456                this.init_local_messages();
1457
1458                var rs = this.dbGears.execute("select count(*) from queue where user=? and sent=0",[account_id]);
1459                var to_return = rs.field(0);
1460
1461                this.finalize();
1462                return to_return;
1463        }
1464       
1465        local_messages.prototype.set_problem_on_sent = function(rowid_message,msg) {
1466                this.init_local_messages();
1467                this.dbGears.execute("update queue set sent = 2 where rowid=?",[rowid_message]);
1468                this.dbGears.execute("insert into sent_problems (id_queue,message) values (?,?)"[rowid_message,msg]);
1469                this.finalize();
1470        }
1471       
1472        local_messages.prototype.set_as_sent = function(rowid_message) {
1473                this.init_local_messages();
1474                this.dbGears.execute("update queue set sent = 1 where rowid=?",[rowid_message]);
1475                this.finalize();
1476        }
1477       
1478        local_messages.prototype.get_form_msg_to_send = function() {
1479                this.init_local_messages();
1480                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]);
1481                if(!rs.isValidRow())
1482                        return false;
1483               
1484                var form = document.createElement('form');
1485                form.method = 'POST';
1486                form.name = 'form_queue_'+rs.field(8);
1487                form.style.display = 'none';
1488                form.onsubmit = function(){return false;}
1489                if(!is_ie)
1490                        form.enctype="multipart/form-data";
1491                else
1492                        form.encoding="multipart/form-data";
1493               
1494                var ffrom = document.createElement('TEXTAREA');
1495                ffrom.name = "input_from";
1496                ffrom.value = rs.field(0);
1497                form.appendChild(ffrom);
1498               
1499                var fto = document.createElement('TEXTAREA');
1500                fto.name = "input_to";
1501                fto.value = rs.field(1);
1502                form.appendChild(fto);
1503               
1504                var cc = document.createElement('TEXTAREA');
1505                cc.name = "input_cc";
1506                cc.value = rs.field(2);
1507                form.appendChild(cc);
1508
1509                var cco = document.createElement('TEXTAREA');
1510                cco.name = "input_cco";
1511                cco.value = rs.field(3);
1512                form.appendChild(cco);
1513               
1514                var subject = document.createElement('TEXTAREA');
1515                subject.name = "input_subject";
1516                subject.value = rs.field(4);
1517                form.appendChild(subject);
1518               
1519                var folder = document.createElement('input');
1520                folder.name='folder';
1521                folder.value=preferences.save_in_folder;
1522                form.appendChild(folder);
1523               
1524                if (rs.field(5) == 1) {
1525                        var conf_receipt = document.createElement('input');
1526                        conf_receipt.type='text';
1527                        conf_receipt.name = "input_return_receipt";
1528                        conf_receipt.value = 'on';
1529                        form.appendChild(conf_receipt);
1530                }
1531               
1532                if (rs.field(6) == 1) {
1533                        var important = document.createElement('input');
1534                        important.type='text';
1535                        important.name = "input_important_message";
1536                        important.value = 'on';
1537                        form.appendChild(important);
1538                }
1539               
1540                var body = document.createElement('TEXTAREA');
1541                body.name = "body";
1542                body.value = rs.field(7);
1543                form.appendChild(body);
1544               
1545                var rowid = document.createElement('input');
1546                rowid.type = 'hidden';
1547                rowid.name = 'rowid';
1548                rowid.value = rs.field(8);
1549                form.appendChild(rowid);
1550               
1551                //Mounting the attachs
1552                var divFiles = document.createElement("div");
1553                divFiles.id = 'divFiles_queue_'+rs.field(8);
1554               
1555                form.appendChild(divFiles);
1556               
1557                document.getElementById('forms_queue').appendChild(form);
1558
1559                var is_local_forward = false;
1560                try {
1561                       
1562                        var rs_attach = this.dbGears.execute('select url_attach from attachments_queue where id_queue=?', [rs.field(8)]);
1563                        while (rs_attach.isValidRow()) {
1564                                if(rs_attach.field(0).indexOf('../tmpLclAtt/')==-1) {
1565                                        tmp_field = addForwardedFile('queue_' + rs.field(8), this.store.getCapturedFileName(rs_attach.field(0)), 'nothing');
1566                                }
1567                                else {
1568                                        var tempNomeArquivo = rs_attach.field(0).split("/");
1569                                        var nomeArquivo = tempNomeArquivo[tempNomeArquivo.length-1];
1570                                        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.
1571                                        is_local_forward = true;
1572                                        tmp_field = addForwardedFile('queue_' + rs.field(8), nomeArquivo, 'nothing');
1573                                }
1574                                fileSubmitter = this.store.createFileSubmitter();
1575                                fileSubmitter.setFileInputElement(tmp_field,rs_attach.field(0));
1576                //              alert(form.innerHTML);
1577                        //      div.appendChild(tmp_field);
1578                                rs_attach.next();
1579                        }
1580                       
1581                        if(is_local_forward) {
1582                                var is_lcl_fw = document.createElement('input');
1583                                is_lcl_fw.type = 'hidden';
1584                                is_lcl_fw.name = 'is_local_forward';
1585                                is_lcl_fw.value = "1";
1586                                form.appendChild(is_lcl_fw);
1587                        }
1588                               
1589                }
1590                catch(exception) {
1591                        alert(exception);
1592                }
1593               
1594                this.finalize();
1595                return form;
1596        }
1597
1598        var expresso_local_messages;
1599        expresso_local_messages = new local_messages();
1600        expresso_local_messages.create_objects();
Note: See TracBrowser for help on using the repository browser.