source: trunk/expressoMail1_2/js/jscode/local_messages.js @ 2519

Revision 2519, 54.7 KB checked in by rodsouza, 14 years ago (diff)

Ticket #1009 - Permitindo que o ExpressoMail? não realize reload de página.

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