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

Revision 2379, 54.5 KB checked in by eduardoalex, 14 years ago (diff)

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