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

Revision 1622, 52.0 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #722 - Implementação da pesquisa avançada no expressoMail.

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