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

Revision 3018, 54.3 KB checked in by amuller, 14 years ago (diff)

Ticket #1135 - Aplicando alterações do branches 2.0 no branches 2.2

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