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

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

Ticket #785 - Resolvendo o problema descrito no ticket em questao

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