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

Revision 1939, 53.2 KB checked in by eduardoalex, 14 years ago (diff)

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

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