source: trunk/expressoMail1_2/js/local_messages.js @ 1982

Revision 1982, 54.3 KB checked in by eduardoalex, 14 years ago (diff)

Ticket #888 - Atualizando a lista de contato apenas se o usuario possui o expresso offline instalado

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