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

Revision 1666, 52.7 KB checked in by rafaelraymundo, 14 years ago (diff)

Ticket #739 - Na função rename_folder para que as sub pastas não desapareçam.

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                rs = this.dbGears.execute("select folder from folder where folder like ? and uid_usuario=?",[old_folder+'/%',account_id]);
674                while(rs.isValidRow()) {
675                        folder_tmp = rs.field(0);
676                        folder_new = folder_tmp.replace(old_folder,folder);
677                        this.dbGears.execute("update folder set folder=? where folder=?",[folder_new,folder_tmp]);
678                        rs.next();
679                }
680
681
682                this.finalize();
683                return true;
684        }
685       
686        local_messages.prototype.remove_folder = function(folder) {
687                this.init_local_messages();
688                var rs = this.dbGears.execute("select count(rowid) from folder where folder like ? and uid_usuario=?",[folder+"/%",account_id]);
689                var sons = rs.field(0);
690                rs.close();
691
692                if(sons == 0){
693                var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[folder,account_id]);
694                var folder_id = rs.field(0);
695                rs.close();
696                this.dbGears.execute("delete from folder where rowid=?",[folder_id]);
697                rs = this.dbGears.execute("select rowid,mail from mail where id_folder=?",[folder_id]);
698                while(rs.isValidRow()) {
699                        var rs2 = this.dbGears.execute("select url from anexo where id_mail=?",[rs.field(0)]);
700                        while(rs2.isValidRow()) {
701                                this.store.remove(rs2.field(0));
702                                rs2.next();
703                        }
704                        rs2.close();
705                        this.dbGears.execute("delete from anexo where id_mail=?",[rs.field(0)]);
706                        var mail = connector.unserialize(rs.field(1));
707                        this.store.remove(mail.url_export_file);
708                        rs.next();
709                }
710                rs.close();
711                this.dbGears.execute("delete from mail where id_folder=?",[folder_id]);
712                    return true
713                this.finalize();
714                }else  {
715                    return false
716                    this.finalize();
717        }
718
719        }
720
721        local_messages.prototype.move_messages = function(new_folder,msgs_number) {
722                this.init_local_messages();
723                var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[new_folder,account_id]);
724                var id_folder = rs.field(0);
725                rs.close();
726                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...
727                this.finalize();
728        }
729       
730        local_messages.prototype.search = function(folders,sFilter) {
731                this.init_local_messages();
732                var filters = sFilter.replace(/^##|##$/g,"").split('##');
733                var friendly_filters = new Array();
734
735                if (sFilter.indexOf('ALL') != -1) { //all filters...
736                    filters[0] = sFilter.replace(/##/g,"");
737                    tmp = filters[0].split("<=>");
738
739                    searchKey = new Array();
740                    searchKey.push("SUBJECT");
741                    searchKey.push(tmp[1]);
742                    friendly_filters.push(searchKey);
743
744                    searchKey = new Array();
745                    searchKey.push("BODY");
746                    searchKey.push(tmp[1]);
747                    friendly_filters.push(searchKey);
748
749                    searchKey = new Array();
750                    searchKey.push("FROM");
751                    searchKey.push(tmp[1]);
752                    friendly_filters.push(searchKey);
753
754                    searchKey = new Array();
755                    searchKey.push("TO");
756                    searchKey.push(tmp[1]);
757                    friendly_filters.push(searchKey);
758
759                    searchKey = new Array();
760                    searchKey.push("CC");
761                    searchKey.push(tmp[1]);
762                    friendly_filters.push(searchKey);
763                }
764                else {
765                    for (var i=0; i<filters.length; i++)
766                    {
767                        if (filters[i] != ""){
768                            //tmp[0] = tmp[0].replace(/^\s+|\s+$/g,"");
769                            //tmp[1] = tmp[1].replace(/^\s+|\s+$/g,"");
770                            friendly_filters.push(filters[i].split("<=>"));
771                        }
772                    }
773                }
774                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 (";
775                for(var fnum in folders) {
776                        sql+="'"+folders[fnum]+"'";
777                        if(fnum<folders.length-1)
778                                sql+=",";
779                }
780                sql += ") and (";
781                for (var z=0;z<friendly_filters.length-1;z++) {
782                    if (z != 0) {
783                        if (sFilter.indexOf('ALL') != -1)
784                            sql += " or";
785                        else
786                            sql += " and";
787                    }
788                    var cond = friendly_filters[z][0].replace(/^\s+|\s+$/g,"");
789                    if (cond == "SINCE" || cond == "BEFORE" | cond == "ON"){
790
791                        tmpDate = url_decode(friendly_filters[z][1]).split('/');
792
793                        // Date = url_decode(friendly_filters[z][1]);
794                        sql+=" mail.timestamp " + this.aux_convert_filter_field(friendly_filters[z][0], tmpDate);
795                    }
796                    else if (!friendly_filters[z][1])
797                        {
798                            sql+=" mail."+this.aux_convert_filter_field(friendly_filters[z][0]);
799                        }
800                        else
801                            {
802                                sql+=" mail."+this.aux_convert_filter_field(friendly_filters[z][0])+" like '%"+url_decode(friendly_filters[z][1])+"%'";
803                            }
804                }
805                sql += ")";
806                var rs = this.dbGears.execute(sql);
807                var retorno = "";
808                while(rs.isValidRow()) {
809                    var header = connector.unserialize(rs.field(0));
810                    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)+"##";
811                    rs.next();
812                }
813
814                this.finalize();
815                return retorno==""?false:retorno;
816
817        }
818       
819        local_messages.prototype.aux_convert_size = function(size) {
820                var tmp = Math.floor(size/1024);
821                if(tmp >= 1){
822                        return tmp + " kb";     
823                }else{
824                        return size + " b";     
825                }
826               
827        }
828       
829        local_messages.prototype.aux_convert_filter_field = function(filter,date) {
830                if (typeof date != 'undefined'){
831                    var dateObj=new Date();
832                    dateObj.setFullYear(date[2],date[1]-1,date[0]);
833                }
834
835                if((filter=="SUBJECT ") || (filter=="SUBJECT"))
836                        return "subject";
837                else if((filter=="BODY ") || (filter=="BODY"))
838                        return "body";
839                else if((filter=="FROM ") || (filter=="FROM"))
840                        return "ffrom";
841                else if((filter=="TO ") || (filter=="TO"))
842                        return "fto";
843                else if((filter=="CC ") || (filter=="CC"))
844                        return "cc";
845                else if (filter.replace(/^\s+|\s+$/g,"") == "SINCE"){
846                        dateObj.setHours(0, 0, 0, 0);
847                        return ">= " + dateObj.getTime().toString(10).substr(0, 10);
848                }
849                else if (filter.replace(/^\s+|\s+$/g,"") == "BEFORE"){
850                        dateObj.setHours(23, 59, 59, 999);
851                        return "<= " + dateObj.getTime().toString(10).substr(0, 10);
852                }
853                else if (filter.replace(/^\s+|\s+$/g,"") == "ON"){
854                        dateObj.setHours(0, 0, 0, 0);
855                        var ts1 = dateObj.getTime().toString(10).substr(0, 10);
856                        dateObj.setHours(23, 59, 59, 999);
857                        var ts2 = dateObj.getTime().toString(10).substr(0, 10);
858                        return ">= " + ts1 + ") and (timestamp <= " + ts2;
859                }
860                else if (filter.replace(/^\s+|\s+$/g,"") == "FLAGGED")
861                        return "flagged = 1";
862                else if (filter.replace(/^\s+|\s+$/g,"") == "UNFLAGGED")
863                        return "flagged = 0";
864                else if (filter.replace(/^\s+|\s+$/g,"") == "UNSEEN")
865                        return "unseen = 1";
866                else if (filter.replace(/^\s+|\s+$/g,"") == "SEEN")
867                        return "unseen = 0";
868                else if (filter.replace(/^\s+|\s+$/g,"") == "ANSWERED")
869                        return "answered = 1";
870                else if (filter.replace(/^\s+|\s+$/g,"") == "UNANSWERED")
871                        return "answered = 0";
872                else if (filter.replace(/^\s+|\s+$/g,"") == "RECENT")
873                        return "recent = 1";
874                else if (filter.replace(/^\s+|\s+$/g,"") == "OLD")
875                        return "recent = 0";
876
877        }
878       
879        local_messages.prototype.has_local_mails = function() {
880                this.init_local_messages();
881                var rs = this.dbGears.execute("select rowid from folder limit 0,1");
882                var retorno;
883                if(rs.isValidRow())
884                        retorno = true;
885                else
886                        retorno = false;
887                this.finalize();
888                return retorno;
889        }
890
891     //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).
892    local_messages.prototype.get_src = function(url){
893        AJAX = false;
894        if (window.XMLHttpRequest) { // Mozilla, Safari,...
895            AJAX = new XMLHttpRequest();
896            if (AJAX.overrideMimeType) {
897                AJAX.overrideMimeType('text/xml');
898            }
899        } else if (window.ActiveXObject) { // IE
900            try {
901                AJAX = new ActiveXObject("Msxml2.XMLHTTP");
902            } catch (e) {
903                try {
904                AJAX = new ActiveXObject("Microsoft.XMLHTTP");
905                } catch (e) {}
906            }
907        }
908
909        if (!AJAX) {
910            alert('ERRO :(Seu navegador nï¿œo suporta a aplicaᅵᅵo usada neste site');
911            return false;
912        }
913
914        AJAX.onreadystatechange = function() {
915            if (AJAX.readyState == 4) {
916                AJAX.src=AJAX.responseText;
917                if (AJAX.status == 200) {
918                    return AJAX.responseText;
919                    } else {
920                    return false;
921                }
922            }
923        }
924
925        AJAX.open('get', url, false);
926        AJAX.send(null);
927        return AJAX.responseText;
928    };
929
930  //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
931  //para que elas sejam inseridas no imap pela funᅵᅵo  imap_functions.unarchive_mail.
932    local_messages.prototype.unarchive_msgs = function (folder,new_folder,msgs_number){
933
934        if(!new_folder)
935            new_folder='INBOX';
936        this.init_local_messages();
937       // alert(folder+new_folder+msgs_number);
938        var handler_unarchive = function(data)
939        {
940            if(data.error == '')
941                write_msg(get_lang('All messages are successfully unarchived'));
942            else
943                alert(data.error);
944        }
945        if(msgs_number =='selected' || !msgs_number)
946        {
947            msgs_number = get_selected_messages()
948            if (!msgs_number){
949                write_msg(get_lang('No selected message.'));
950                return;
951            }
952            var rs = this.dbGears.execute("select mail,timestamp from mail where rowid in ("+msgs_number+")");
953            var source="";
954            var timestamp="";
955            while(rs.isValidRow()) {
956                mail=connector.unserialize(rs.field(0));
957                source_tmp=escape(this.get_src(mail.url_export_file));
958                    source+="#@#@#@"+source_tmp;
959                    timestamp+="#@#@#@"+rs.field(1);
960                rs.next();
961            }
962            rs.close();
963            this.finalize();
964        }
965        else
966        {
967            var rs = this.dbGears.execute("select mail,timestamp from mail where rowid="+msgs_number);
968            mail=connector.unserialize(rs.field(0));
969            var source ="";
970            source = this.get_src(mail.url_export_file);
971            timestamp=rs.field(1);
972             rs.close();
973             this.finalize();
974        }
975            params="&folder="+new_folder+"&source="+source+"&timestamp="+timestamp;
976            cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
977    }
978
979    local_messages.prototype.get_msg_date = function (original_id, is_local){
980
981        this.init_local_messages();
982
983        if (typeof(is_local) == 'undefined')
984        {
985            is_local = false;
986        }
987
988        var rs;
989
990        if (is_local)
991        {
992            rs = this.dbGears.execute("select mail from mail where rowid="+original_id);
993        }
994        else
995        {
996            rs = this.dbGears.execute("select mail from mail where original_id="+original_id);
997        }
998        var tmp = connector.unserialize(rs.field(0));
999        var ret = new Array();
1000        ret.fulldate = tmp.fulldate.substr(0,16);
1001        ret.smalldate = tmp.msg_day;
1002        ret.msg_day = tmp.msg_day;
1003        ret.msg_hour = tmp.msg_day;
1004
1005        rs.close();
1006        this.finalize();
1007        return ret;
1008    }
1009
1010
1011    local_messages.prototype.download_all_local_attachments = function(folder,id){
1012        this.init_local_messages();
1013        var rs = this.dbGears.execute("select mail from mail where rowid="+id);
1014        var tmp = connector.unserialize(rs.field(0));
1015        rs.close();
1016        this.finalize();
1017        source = this.get_src(tmp.url_export_file);
1018        source = escape(source);
1019        var handler_source = function(data){
1020            download_attachments(null, null, data, null,null,'anexos.zip');
1021        }
1022        cExecute("$this.imap_functions.download_all_local_attachments",handler_source,"source="+source);
1023    }
1024
1025    /*************************************************************************/
1026/* Funcao usada para exportar mensagens arquivadas localmente.
1027 * Rommel de Brito Cysne (rommel.cysne@serpro.gov.br)
1028 * em 22/12/2008.
1029 */
1030    local_messages.prototype.local_messages_to_export = function(){
1031
1032        if (openTab.type[currentTab] > 1){
1033            var msgs_to_export_id = currentTab.substring(0,currentTab.length-2,currentTab);
1034        }else{
1035            var msgs_to_export_id = get_selected_messages();
1036        }
1037        var handler_local_mesgs_to_export = function(data){
1038            download_attachments(null, null, data, null,null,'mensagens.zip');
1039        }
1040        if(msgs_to_export_id){
1041            this.init_local_messages();
1042            var l_msg = "t";
1043            var mesgs ="";
1044            var subjects ="";
1045            var rs = this.dbGears.execute("select mail,subject from mail where rowid in ("+msgs_to_export_id+")");
1046            while(rs.isValidRow()){
1047                mail = connector.unserialize(rs.field(0));
1048                src = this.get_src(mail.url_export_file);
1049                subject = rs.field(1);
1050                mesgs += src;
1051                mesgs += "@@";
1052                subjects += subject;
1053                subjects += "@@";
1054                rs.next();
1055            }
1056            rs.close();
1057            this.finalize();
1058            mesgs = escape(mesgs);
1059            subjects = escape(subjects);
1060            params = "subjects="+subjects+"&mesgs="+mesgs+"&l_msg="+l_msg+"&msgs_to_export="+msgs_to_export_id;
1061            cExecute ("$this.exporteml.makeAll&", handler_local_mesgs_to_export, params);
1062        }
1063        return true;
1064    }
1065
1066    local_messages.prototype.get_all_local_folder_messages= function(folder_name){
1067
1068
1069         var mesgs = new Array();
1070         var subjects = new Array();
1071         var hoje = new Date();
1072         var msgs_to_export = new Array();
1073         var l_msg="t";
1074
1075        this.init_local_messages();
1076        var query = "select mail,subject,mail.rowid from mail inner join folder on (mail.id_folder=folder.rowid) where folder.folder='" + folder_name + "'";
1077
1078        var rs = this.dbGears.execute(" "+query)
1079
1080            var handler_local_mesgs_to_export = function(data){
1081                    //alert("data - " + data + " - tipo - " + typeof(data));
1082                    download_attachments(null, null, data, null,null,'mensagens.zip');
1083            }
1084        var j=0;
1085        while (rs.isValidRow()){
1086              msgs_to_export[j]=rs.field(2)
1087              mail = connector.unserialize(rs.field(0));
1088                      msg=this.get_src(mail.url_export_file);
1089                      subject = rs.field(1);
1090                      mesgs += msg;
1091                      mesgs += "@@";
1092                      subjects += subject;
1093                      subjects += "@@";
1094                      rs.next();
1095              j++;
1096
1097        }
1098           rs.close();
1099           this.finalize();
1100           source = escape(mesgs);
1101           subjects = escape(subjects);
1102           params = "folder="+folder_name+"&subjects="+subjects+"&mesgs="+source+"&l_msg="+l_msg+"&msgs_to_export="+msgs_to_export;
1103           cExecute ("$this.exporteml.makeAll&", handler_local_mesgs_to_export, params);
1104         
1105
1106    }
1107
1108
1109    /*************************************************************************/
1110
1111       
1112/******************************************************************
1113                                        Offline Part
1114 ******************************************************************/
1115
1116        local_messages.prototype.is_offline_installed = function() {
1117                this.init_local_messages();
1118                var check = this.localServer.openManagedStore('expresso-offline');
1119                this.finalize();
1120                if(check==null)
1121                        return false;
1122                else
1123                        return true;
1124               
1125        }
1126        local_messages.prototype.update_offline = function(redirect) {
1127                this.init_local_messages();
1128                var managedStore = this.localServer.openManagedStore('expresso-offline');
1129
1130                if(managedStore!=null){
1131                       
1132                        managedStore.oncomplete = function(details){
1133                                if(redirect!=null)
1134                                        location.href=redirect;
1135                        }
1136                       
1137                        managedStore.checkForUpdate();
1138                } else if(redirect!=null) {
1139                        location.href=redirect;
1140                }
1141                this.finalize();
1142        }
1143       
1144        local_messages.prototype.uninstall_offline = function() {
1145                if (!window.google || !google.gears) {
1146                                temp = confirm(document.getElementById('lang_gears_redirect').value);
1147                                if (temp) {
1148                                        expresso_local_messages.installGears();
1149                                }
1150                                return;
1151
1152                }
1153                this.init_local_messages();
1154                this.localServer.removeManagedStore('expresso-offline');
1155                alert(document.getElementById('lang_offline_uninstalled').value);
1156                //this.dbGears.execute('drop table user');
1157                //this.dbGears.execute('drop table queue');
1158                //this.dbGears.execute('drop table attachments_queue');
1159                this.finalize();
1160        }
1161       
1162        local_messages.prototype.get_folders_to_sync = function() {//Precisa ter visibilidade ao array de linguagens.
1163                this.init_local_messages();
1164                var rs = this.dbGears.execute("select id_folder,folder_name from folders_sync where uid_usuario="+account_id);
1165                var retorno = new Array();
1166                while(rs.isValidRow()) {
1167                        temp = new Array();
1168                        temp[0] = rs.field(0);
1169                        if(temp[0]=='INBOX/Drafts' ||temp[0]=='INBOX/Trash' || temp[0]=='INBOX/Sent') {
1170                                temp[1] = array_lang[rs.field(1).toLowerCase()];
1171                        }
1172                        else {
1173                                temp[1] = rs.field(1); 
1174                        }
1175                       
1176                        retorno.push(temp);
1177                        rs.next();
1178                }
1179                this.finalize();
1180                return retorno;
1181        }
1182       
1183        local_messages.prototype.install_offline = function(urlOffline,urlIcone,uid_usuario,login,pass,redirect) {
1184                if (!window.google || !google.gears) {
1185                                temp = confirm(document.getElementById('lang_gears_redirect').value);
1186                                if (temp) {
1187                                         expresso_local_messages.installGears();
1188                                }
1189                                return;
1190
1191                }
1192               
1193                if(pass.length>0) {
1194                        only_spaces = true;
1195                        for(cont=0;cont<pass.length;cont++) {
1196                                if(pass.charAt(cont)!=" ")
1197                                        only_spaces = false;
1198                        }
1199                        if(only_spaces) {
1200                                alert(document.getElementById('lang_only_spaces_not_allowed').value);
1201                                return false;
1202                        }
1203                }
1204
1205                modal('loading');
1206                var desktop = google.gears.factory.create('beta.desktop');
1207                desktop.createShortcut('ExpressoMail Offline',
1208                        urlOffline,
1209                {'32x32': urlIcone},
1210                'ExpressoMail Offline');
1211
1212
1213                this.init_local_messages();
1214
1215                //user with offline needs to have at least the folder Inbox already created.
1216                tmp_rs = this.dbGears.execute("select rowid from folder where folder='Inbox' and uid_usuario=?",[uid_usuario]);
1217                if(!tmp_rs.isValidRow())
1218                        this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",['Inbox',uid_usuario]);
1219
1220                this.localServer.removeManagedStore('expresso-offline');
1221       
1222                var managedStore = this.localServer.createManagedStore('expresso-offline');
1223                managedStore.manifestUrl = 'js/manifest';
1224
1225                managedStore.onerror = function (error) {
1226                        alert(error);
1227                }
1228               
1229                managedStore.oncomplete = function(details) {
1230                        if (close_lightbox_div) {
1231                                close_lightbox();
1232                                close_lightbox_div = false;
1233                                alert(document.getElementById('lang_offline_installed').value);
1234                                location.href=redirect;
1235                        }
1236                }
1237
1238                //create structure to user in db
1239                this.dbGears.execute('create table if not exists user (uid_usuario int,login text,pass text, logged int,unique(uid_usuario))');
1240                this.dbGears.execute('create table if not exists queue (ffrom text, fto text, cc text, cco text,'+
1241                        'subject text, conf_receipt int, important int,body text,sent int,user int)');
1242                this.dbGears.execute('create table if not exists attachments_queue ('+
1243                        'id_queue int, url_attach text)');
1244                this.dbGears.execute('create table if not exists sent_problems (' +
1245                        'id_queue int,message text)');
1246               
1247                //d = new Date();
1248               
1249                try {
1250                        var rs = this.dbGears.execute("select uid_usuario from user where uid_usuario=?",[uid_usuario]);
1251                        if(!rs.isValidRow())
1252                                this.dbGears.execute("insert into user (uid_usuario,login,pass) values (?,?,?)",[uid_usuario,login,pass]);
1253                        else
1254                                this.dbGears.execute("update user set pass=? where uid_usuario=?",[pass,uid_usuario]);
1255                } catch (error) {
1256                        this.finalize();
1257                        alert(error);
1258                        return false;
1259                }
1260                managedStore.checkForUpdate();
1261               
1262                this.finalize();
1263        }
1264       
1265        /**
1266         * Return all users in an array following the structure below.
1267         *
1268         * key: uid
1269         * value: user login
1270         */
1271        local_messages.prototype.get_all_users = function() {
1272                this.init_local_messages();
1273                var users = new Array();
1274                var rs = this.dbGears.execute("select uid_usuario,login from user");
1275                while(rs.isValidRow()) {
1276                        users[rs.field(0)] = rs.field(1);
1277                        rs.next();
1278                }
1279                this.finalize();
1280                return users;
1281        }
1282       
1283        local_messages.prototype.set_as_logged = function(uid_usuario,pass) {
1284                this.init_local_messages();
1285                var rs = this.dbGears.execute("select pass from user where uid_usuario=?",[uid_usuario]);
1286                if(!rs.isValidRow() || (pass!=rs.field(0) && pass!=MD5(rs.field(0))) ) {
1287                        this.finalize();
1288                        return false;
1289                }
1290                d = new Date();
1291
1292                this.dbGears.execute("update user set logged=null"); //Logoff in everybody
1293                this.dbGears.execute("update user set logged=? where uid_usuario=?",[d.getTime(),uid_usuario]); //Login just in one...
1294                this.finalize();
1295                return true;
1296        }
1297       
1298        local_messages.prototype.unset_as_logged = function() {
1299                this.init_local_messages();
1300                this.dbGears.execute("update user set logged=null"); //Logoff in everybody
1301                this.finalize();
1302        }
1303       
1304        local_messages.prototype.user_logged = function() {
1305                this.init_local_messages();
1306                var user_logged = new Array();
1307                var rs = this.dbGears.execute("select uid_usuario,logged from user where logged is not null");
1308                if(!rs.isValidRow()) {
1309                        this.finalize();
1310                        return null;
1311                }
1312                user_logged[0] = rs.field(0);
1313                user_logged[1] = rs.field(1);
1314                this.finalize();
1315                return user_logged;
1316        }
1317       
1318        local_messages.prototype.send_to_queue = function (form) {
1319                this.init_local_messages();
1320                var mail_values = new Array();
1321               
1322                for (var i=0;i<form.length;i++) {
1323                        if (form.elements[i].name != '') { //I.E made me to do that...
1324                                if(form.elements[i].name=='folder' || form.elements[i].name=='msg_id' || form.elements[i].name=='' || form.elements[i].name==null)
1325                                        continue;
1326                                else if (form.elements[i].name == 'input_return_receipt' )
1327                                        mail_values['conf_receipt'] = form.elements[i].checked ? 1 : 0;
1328                                else if(form.elements[i].name == 'input_important_message')
1329                                        mail_values['important'] = form.elements[i].checked ? 1 : 0;
1330                                else
1331                                        if (form.elements[i].name == 'body')
1332                                                mail_values['body'] = form.elements[i].value;
1333                                        else
1334                                                if (form.elements[i].name == 'input_from')
1335                                                        mail_values['ffrom'] = form.elements[i].value;
1336                                                else
1337                                                        if (form.elements[i].name == 'input_to')
1338                                                                mail_values['fto'] = form.elements[i].value;
1339                                                        else
1340                                                                if (form.elements[i].name == 'input_cc')
1341                                                                        mail_values['cc'] = form.elements[i].value;
1342                                                                else
1343                                                                        if (form.elements[i].name == 'input_cco')
1344                                                                                mail_values['cco'] = form.elements[i].value;
1345                                                                        else
1346                                                                                if (form.elements[i].name == 'input_subject')
1347                                                                                        mail_values['subject'] = form.elements[i].value;
1348                        }
1349                }
1350                //mail_values['fto'] = input_to;
1351                //mail_values['cc'] = input_cc;
1352                //mail_values['cco'] = input_cco;
1353                //mail_values['subject'] = input_subject;
1354                //mail_values['conf_receipt'] = input_return_receipt;
1355                //mail_values['important'] = input_important_message;
1356               
1357                try {
1358                        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]);
1359                        this.send_attach_to_queue(this.dbGears.lastInsertRowId,form);
1360                }catch(error) {
1361                        alert(error);
1362                        return get_lang('Error sending a mail to queue. Verify if you have installed ExpressoMail Offline');
1363                }
1364                this.finalize();
1365                return true;
1366        }
1367       
1368        local_messages.prototype.send_attach_to_queue = function(id_queue,form) {
1369               
1370                for(i=0;i<form.elements.length;i++) {
1371                       
1372                        if(form.elements[i].name.indexOf("file_")!=-1) {
1373                                var tmp_input = form.elements[i];
1374                                var d = new Date();
1375                                var url_local = 'local_attachs/'+d.getTime();
1376                                this.store.captureFile(tmp_input, url_local);
1377                                this.dbGears.execute("insert into attachments_queue (id_queue,url_attach) values (?,?)",[id_queue,url_local]);
1378                        }
1379                        else if(form.elements[i].name.indexOf("offline_forward_")!=-1){
1380                                //alert();
1381                                this.dbGears.execute("insert into attachments_queue (id_queue,url_attach) values (?,?)",[id_queue,form.elements[i].value]);
1382                        }
1383                }
1384        }
1385
1386       
1387        local_messages.prototype.get_num_msgs_to_send = function() {
1388                this.init_local_messages();
1389
1390                var rs = this.dbGears.execute("select count(*) from queue where user=? and sent=0",[account_id]);
1391                var to_return = rs.field(0);
1392
1393                this.finalize();
1394                return to_return;
1395        }
1396       
1397        local_messages.prototype.set_problem_on_sent = function(rowid_message,msg) {
1398                this.init_local_messages();
1399                this.dbGears.execute("update queue set sent = 2 where rowid=?",[rowid_message]);
1400                this.dbGears.execute("insert into sent_problems (id_queue,message) values (?,?)"[rowid_message,msg]);
1401                this.finalize();
1402        }
1403       
1404        local_messages.prototype.set_as_sent = function(rowid_message) {
1405                this.init_local_messages();
1406                this.dbGears.execute("update queue set sent = 1 where rowid=?",[rowid_message]);
1407                this.finalize();
1408        }
1409       
1410        local_messages.prototype.get_form_msg_to_send = function() {
1411                this.init_local_messages();
1412                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]);
1413                if(!rs.isValidRow())
1414                        return false;
1415               
1416                var form = document.createElement('form');
1417                form.method = 'POST';
1418                form.name = 'form_queue_'+rs.field(8);
1419                form.style.display = 'none';
1420                form.onsubmit = function(){return false;}
1421                if(!is_ie)
1422                        form.enctype="multipart/form-data";
1423                else
1424                        form.encoding="multipart/form-data";
1425               
1426                var ffrom = document.createElement('TEXTAREA');
1427                ffrom.name = "input_from";
1428                ffrom.value = rs.field(0);
1429                form.appendChild(ffrom);
1430               
1431                var fto = document.createElement('TEXTAREA');
1432                fto.name = "input_to";
1433                fto.value = rs.field(1);
1434                form.appendChild(fto);
1435               
1436                var cc = document.createElement('TEXTAREA');
1437                cc.name = "input_cc";
1438                cc.value = rs.field(2);
1439                form.appendChild(cc);
1440
1441                var cco = document.createElement('TEXTAREA');
1442                cco.name = "input_cco";
1443                cco.value = rs.field(3);
1444                form.appendChild(cco);
1445               
1446                var subject = document.createElement('TEXTAREA');
1447                subject.name = "input_subject";
1448                subject.value = rs.field(4);
1449                form.appendChild(subject);
1450               
1451                var folder = document.createElement('input');
1452                folder.name='folder';
1453                folder.value=preferences.save_in_folder;
1454                form.appendChild(folder);
1455               
1456                if (rs.field(5) == 1) {
1457                        var conf_receipt = document.createElement('input');
1458                        conf_receipt.type='text';
1459                        conf_receipt.name = "input_return_receipt";
1460                        conf_receipt.value = 'on';
1461                        form.appendChild(conf_receipt);
1462                }
1463               
1464                if (rs.field(6) == 1) {
1465                        var important = document.createElement('input');
1466                        important.type='text';
1467                        important.name = "input_important_message";
1468                        important.value = 'on';
1469                        form.appendChild(important);
1470                }
1471               
1472                var body = document.createElement('TEXTAREA');
1473                body.name = "body";
1474                body.value = rs.field(7);
1475                form.appendChild(body);
1476               
1477                var rowid = document.createElement('input');
1478                rowid.type = 'hidden';
1479                rowid.name = 'rowid';
1480                rowid.value = rs.field(8);
1481                form.appendChild(rowid);
1482               
1483                //Mounting the attachs
1484                var divFiles = document.createElement("div");
1485                divFiles.id = 'divFiles_queue_'+rs.field(8);
1486               
1487                form.appendChild(divFiles);
1488               
1489                document.getElementById('forms_queue').appendChild(form);
1490
1491                var is_local_forward = false;
1492                try {
1493                       
1494                        var rs_attach = this.dbGears.execute('select url_attach from attachments_queue where id_queue=?', [rs.field(8)]);
1495                        while (rs_attach.isValidRow()) {
1496                                if(rs_attach.field(0).indexOf('../tmpLclAtt/')==-1) {
1497                                        tmp_field = addForwardedFile('queue_' + rs.field(8), this.store.getCapturedFileName(rs_attach.field(0)), 'nothing');
1498                                }
1499                                else {
1500                                        var tempNomeArquivo = rs_attach.field(0).split("/");
1501                                        var nomeArquivo = tempNomeArquivo[tempNomeArquivo.length-1];
1502                                        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.
1503                                        is_local_forward = true;
1504                                        tmp_field = addForwardedFile('queue_' + rs.field(8), nomeArquivo, 'nothing');
1505                                }
1506                                fileSubmitter = this.store.createFileSubmitter();
1507                                fileSubmitter.setFileInputElement(tmp_field,rs_attach.field(0));
1508                //              alert(form.innerHTML);
1509                        //      div.appendChild(tmp_field);
1510                                rs_attach.next();
1511                        }
1512                       
1513                        if(is_local_forward) {
1514                                var is_lcl_fw = document.createElement('input');
1515                                is_lcl_fw.type = 'hidden';
1516                                is_lcl_fw.name = 'is_local_forward';
1517                                is_lcl_fw.value = "1";
1518                                form.appendChild(is_lcl_fw);
1519                        }
1520                               
1521                }
1522                catch(exception) {
1523                        alert(exception);
1524                }
1525               
1526                this.finalize();
1527                return form;
1528        }
1529
1530        var expresso_local_messages;
1531        expresso_local_messages = new local_messages();
Note: See TracBrowser for help on using the repository browser.