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

Revision 1752, 53.3 KB checked in by rafaelraymundo, 15 years ago (diff)

Ticket #703 - Preview das mensagens configuravel. Por tool-tip e coluna de assunto

RevLine 
[670]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        }
[1622]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       
[1466]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        }
[670]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)
[1121]126                        this.store = this.localServer.createStore('test-store');                       
[1518]127               
128                var db_in_other_use = true;
[1595]129                var start_trying = new Date().getTime();
[1518]130                while (db_in_other_use) {
131                        try {
132                                this.dbGears.open('database-test');
133                                db_in_other_use = false;
134                        }
135                        catch (ex) {
[1595]136                                if(new Date.getTime()-start_trying>10000) { //too much time trying, throw an exception
137                                        throw ex;
138                                }
[1518]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');
[670]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)');
[1518]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)');
[670]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
[1622]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
[670]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]);
[1000]279                        if(rs.isValidRow())
[670]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;
[1622]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()]);
[670]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();
[1035]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);
[670]315                var retorno = null;
316                if(rs.isValidRow()) {
317                         retorno = rs.field(1);
318                }
319                retorno = connector.unserialize(retorno);
[1000]320
[1035]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]"
[1666]339            //sï¿œo substituidos pelos links dos anexos capturados pelo gears.
[1035]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"');
[1000]359                        }
[1035]360                    }
361            }
[1000]362
[1035]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();
[670]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);
[1752]447
448                        var msg_body = rs.field(5);//recebe o conteudo da coluna "body" do banco de dados;
449
[670]450                        var rs2 = this.dbGears.execute('select count(*) from anexo where id_mail = '+codigoMail);
451                        var head_unserialized = connector.unserialize(head);
452                        head_unserialized.Size = rs.field(2);
453                        if(rs.field(4)==1)
454                                head_unserialized.Unseen = 'U';         
455                       
[1752]456
457                        head_unserialized.subject=(head_unserialized.subject==null)?"":head_unserialized.subject;
458
[670]459                        //var email_unserialized = connector.unserialize(email);
460                        retorno[cont] = head_unserialized;
461                        retorno[cont]['msg_number'] = codigoMail;
462                       
[1752]463                        //declaracao do array() para receber o body de cada mensagem encontrada na busca sql realizada;
464                        msg_body=this.strip_tags(msg_body);
465                        msg_body=msg_body.replace(/\&nbsp;/ig," ");
466                        retorno[cont]['msg_sample'] = new Array();
467
468                        if( (preview_msg_subject == 0) && (preview_msg_tip == 0) )
469                        {
470                                retorno[cont]['msg_sample']['body'] = "";
471                        }
472                        else
473                        {
474                                retorno[cont]['msg_sample']['body'] = " - " + msg_body.substr(3,300);
475                        }
476
[670]477                        cont++;
478                        rs.next();
479                }
480                retorno['num_msgs'] = rs3.field(0);
481                rs3.close();
482                rs.close();
483                if(cont>0)
484                        rs2.close();
485                this.finalize();
486                return retorno;
487        }
488       
489        local_messages.prototype.get_url_anexo = function(msg_number,pid) {
490                this.init_local_messages();
491
492                var retorno;
493                var rs = this.dbGears.execute("select url from anexo where id_mail="+msg_number+" and pid = '"+pid+"'");
494                retorno = rs.field(0)
495                this.finalize();
496               
497                return retorno;
498        }
499
500        local_messages.prototype.getInputFileFromAnexo = function (element,url) {
501                this.init_local_messages();
[1121]502                fileSubmitter = this.store.createFileSubmitter();
503                fileSubmitter.setFileInputElement(element,url);
[670]504                this.finalize();
505        }
506
507        local_messages.prototype.finalize = function() {
508                this.dbGears.close();
509                this.dbGears = null;
510        }
511
512        local_messages.prototype.delete_msgs = function(msgs_number,border_ID) {
513                this.init_local_messages();
514                var rs = this.dbGears.execute("select url from anexo where id_mail in ("+msgs_number+")");
515                while(rs.isValidRow()) {
516                        this.store.remove(rs.field(0));
517                        rs.next();
518                }
519                this.dbGears.execute("delete from anexo where id_mail in ("+msgs_number+")");
520                this.dbGears.execute("delete from mail where rowid in ("+msgs_number+")");
521                this.finalize();
522                if (msgs_number.length == 1)
523                        write_msg(get_lang("The message was deleted."));
524                else
525                        write_msg(get_lang("The messages were deleted."));
526               
527                mail_msg = Element("tbody_box");
528
529                try {
530                        msgs_exploded = msgs_number.split(",");
531                }catch(error) {
532                        msgs_exploded = new Array();
533                        msgs_exploded[0] = msgs_number;
534                }
535                var msg_to_delete;
536                for (var i=0; i<msgs_exploded.length; i++){
537                        msg_to_delete = Element(msgs_exploded[i]);
538                        if (msg_to_delete){
539                                if ( (msg_to_delete.style.backgroundColor != '') && (preferences.use_shortcuts == '1') )
540                                        select_msg('null', 'down');
541                                mail_msg.removeChild(msg_to_delete);
[1381]542                                decrement_folder_unseen();
[670]543                        }
544                }
545                Element('chk_box_select_all_messages').checked = false;
546                if (border_ID != 'null')
547                        delete_border(border_ID,'false');
548               
549        }
550       
551        local_messages.prototype.get_source_msg = function(id_msg) {
552                this.init_local_messages();
553                var rs = this.dbGears.execute("select mail from mail where rowid="+id_msg);
554
555
556                mail = connector.unserialize(rs.field(0));             
557                download_local_attachment(mail.url_export_file)
558
559                this.finalize();
560        }
561       
562        local_messages.prototype.set_messages_flag = function(msgs_number, flag) {
563                this.init_local_messages();
564                var msgs_to_set;
565                if (msgs_number == 'get_selected_messages') {
566                        var msgs_to_set = get_selected_messages();
567                        msgs_to_set= msgs_to_set.split(",");
568                }
569                else { //Just one message
570                        msgs_to_set = new Array();
571                        msgs_to_set[0] = msgs_number;
572                }
573                for (var i in msgs_to_set) {
574               
575                        var rs = this.dbGears.execute("select header,unseen from mail where rowid=" + msgs_to_set[i]);
576                        header = connector.unserialize(rs.field(0));
577                        unseen = rs.field(1);
[1121]578                        switch(flag) {
579                                case "unseen":
580                                        set_msg_as_unread(msgs_to_set[i]);
581                                        header["Unseen"] = "U";
582                                        unseen = 1;
583                                        break;
584                                case "flagged":
[670]585                                        set_msg_as_flagged(msgs_to_set[i]);
586                                        header["Flagged"] = "F";
[1121]587                                        break;
588                                case "unflagged":
589                                        if (header["Importance"].indexOf("High") != -1)
590                                                write_msg(get_lang("At least one of selected message cant be marked as normal"));
591                                        else {
592                                                set_msg_as_unflagged(msgs_to_set[i]);
593                                                header["Flagged"] = "N";
594                                        }
595                                        break;
596                                case "seen":
597                                        header["Unseen"] = "N";
598                                        set_msg_as_read(msgs_to_set[i],true);
599                                        unseen = 0;
600                                        break;
601                                case "answered":
602                                        header["Draft"]="";
603                                        header["Answered"]="A";
604                                        Element("td_message_answered_"+msgs_to_set[i]).innerHTML = '<img src=templates/default/images/answered.gif title=Respondida>';
605                                        break;
606                                case "forwarded":
607                                        header["Draft"]="X";
608                                        header["Answered"]="A";
609                                        Element("td_message_answered_"+msgs_to_set[i]).innerHTML = '<img src=templates/default/images/forwarded.gif title=Encaminhada>';
610                                        break;
611                        }
612               
[670]613                        rs.close();
614                       
615                        if(Element("check_box_message_" + msgs_to_set[i]))
616                                Element("check_box_message_" + msgs_to_set[i]).checked = false;
617
618                        this.dbGears.execute("update mail set header='"+connector.serialize(header)+"',unseen="+unseen+" where rowid="+msgs_to_set[i]);                 
619                }
620                if(Element('chk_box_select_all_messages'))
621                        Element('chk_box_select_all_messages').checked = false;
622                this.finalize();
623
624        }
625       
[1121]626        local_messages.prototype.set_message_flag = function(msg_number,flag) {
627                this.set_messages_flag(msg_number,flag);
628        }
629       
[670]630        local_messages.prototype.get_unseen_msgs_number = function() {
631                this.init_local_messages();
632                var rs = this.dbGears.execute("select count(*) from mail where unseen=1");
633                var retorno = rs.field(0);
634                rs.close();
635                this.finalize();
636                return retorno;
637        }
638
639        local_messages.prototype.create_folder = function(folder) {
640
641                if (folder.indexOf("local_") != -1)
642                        return false; //can't create folder with string local_
643
644                this.init_local_messages();
645                try {
646                        this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",[folder,account_id]);
647                } catch (error) {
648                        this.finalize();
649                        throw error;
650                        return false;
651                }
652                this.finalize();
653                return true;
654        }
655
656        local_messages.prototype.list_local_folders = function(folder) {
657                this.init_local_messages();
658                var retorno = new Array();
659                rs = this.dbGears.execute("select folder.folder,sum(mail.unseen) from folder left join mail on "+
660                                "folder.rowid=mail.id_folder where folder.uid_usuario=? group by folder.folder",[account_id]);
661                while(rs.isValidRow()) {
662                        var temp = new Array();
663                        temp[0] = rs.field(0);
664                        temp[1] = rs.field(1);
[1477]665                        var rs2 = this.dbGears.execute("select * from folder where folder like ?",["%"+temp[0]+"/%"]);
666                        if(rs2.isValidRow())
667                                temp[2] = 1;
668                        else
669                                temp[2] = 0;
[670]670                        retorno.push(temp);
671                        rs.next();
672                }
673               
674                rs.close();
675                this.finalize();
676                return retorno;
677        }
678
679        local_messages.prototype.rename_folder = function(folder,old_folder) {
680                if (folder.indexOf("local_") != -1)
681                        return false; //can't create folder with string local_
682                this.init_local_messages();
[1477]683                if (old_folder.indexOf("/") != "-1") {
684                        final_pos = old_folder.lastIndexOf("/");
685                        folder = old_folder.substr(0, final_pos) + "/" + folder;
686                }
[670]687                try {
688                        this.dbGears.execute("update folder set folder=? where folder=? and uid_usuario=?",[folder,old_folder,account_id]);
689                } catch (error) {
690                        this.finalize();
691                        return false;
692                }
[1666]693                rs = this.dbGears.execute("select folder from folder where folder like ? and uid_usuario=?",[old_folder+'/%',account_id]);
694                while(rs.isValidRow()) {
695                        folder_tmp = rs.field(0);
696                        folder_new = folder_tmp.replace(old_folder,folder);
697                        this.dbGears.execute("update folder set folder=? where folder=?",[folder_new,folder_tmp]);
698                        rs.next();
699                }
700
701
[670]702                this.finalize();
703                return true;
704        }
705       
706        local_messages.prototype.remove_folder = function(folder) {
707                this.init_local_messages();
[1666]708                var rs = this.dbGears.execute("select count(rowid) from folder where folder like ? and uid_usuario=?",[folder+"/%",account_id]);
709                var sons = rs.field(0);
710                rs.close();
711
712                if(sons == 0){
[670]713                var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[folder,account_id]);
714                var folder_id = rs.field(0);
715                rs.close();
716                this.dbGears.execute("delete from folder where rowid=?",[folder_id]);
717                rs = this.dbGears.execute("select rowid,mail from mail where id_folder=?",[folder_id]);
718                while(rs.isValidRow()) {
719                        var rs2 = this.dbGears.execute("select url from anexo where id_mail=?",[rs.field(0)]);
720                        while(rs2.isValidRow()) {
721                                this.store.remove(rs2.field(0));
722                                rs2.next();
723                        }
724                        rs2.close();
725                        this.dbGears.execute("delete from anexo where id_mail=?",[rs.field(0)]);
726                        var mail = connector.unserialize(rs.field(1));
727                        this.store.remove(mail.url_export_file);
728                        rs.next();
729                }
730                rs.close();
731                this.dbGears.execute("delete from mail where id_folder=?",[folder_id]);
[1666]732                    return true
[670]733                this.finalize();
[1666]734                }else  {
735                    return false
736                    this.finalize();
[670]737        }
738
[1666]739        }
740
[670]741        local_messages.prototype.move_messages = function(new_folder,msgs_number) {
742                this.init_local_messages();
743                var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[new_folder,account_id]);
744                var id_folder = rs.field(0);
745                rs.close();
746                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...
747                this.finalize();
748        }
749       
[1622]750        local_messages.prototype.search = function(folders,sFilter) {
[670]751                this.init_local_messages();
[1622]752                var filters = sFilter.replace(/^##|##$/g,"").split('##');
[670]753                var friendly_filters = new Array();
[1622]754
755                if (sFilter.indexOf('ALL') != -1) { //all filters...
756                    filters[0] = sFilter.replace(/##/g,"");
757                    tmp = filters[0].split("<=>");
758
759                    searchKey = new Array();
760                    searchKey.push("SUBJECT");
761                    searchKey.push(tmp[1]);
762                    friendly_filters.push(searchKey);
763
764                    searchKey = new Array();
765                    searchKey.push("BODY");
766                    searchKey.push(tmp[1]);
767                    friendly_filters.push(searchKey);
768
769                    searchKey = new Array();
770                    searchKey.push("FROM");
771                    searchKey.push(tmp[1]);
772                    friendly_filters.push(searchKey);
773
774                    searchKey = new Array();
775                    searchKey.push("TO");
776                    searchKey.push(tmp[1]);
777                    friendly_filters.push(searchKey);
778
779                    searchKey = new Array();
780                    searchKey.push("CC");
781                    searchKey.push(tmp[1]);
782                    friendly_filters.push(searchKey);
[670]783                }
784                else {
[1622]785                    for (var i=0; i<filters.length; i++)
786                    {
787                        if (filters[i] != ""){
788                            //tmp[0] = tmp[0].replace(/^\s+|\s+$/g,"");
789                            //tmp[1] = tmp[1].replace(/^\s+|\s+$/g,"");
790                            friendly_filters.push(filters[i].split("<=>"));
791                        }
792                    }
[670]793                }
794                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 (";
795                for(var fnum in folders) {
796                        sql+="'"+folders[fnum]+"'";
797                        if(fnum<folders.length-1)
798                                sql+=",";
799                }
800                sql += ") and (";
[1747]801                for (var z=0;z<friendly_filters.length;z++) {
[1622]802                    if (z != 0) {
803                        if (sFilter.indexOf('ALL') != -1)
804                            sql += " or";
805                        else
806                            sql += " and";
807                    }
808                    var cond = friendly_filters[z][0].replace(/^\s+|\s+$/g,"");
809                    if (cond == "SINCE" || cond == "BEFORE" | cond == "ON"){
810
811                        tmpDate = url_decode(friendly_filters[z][1]).split('/');
812
813                        // Date = url_decode(friendly_filters[z][1]);
814                        sql+=" mail.timestamp " + this.aux_convert_filter_field(friendly_filters[z][0], tmpDate);
815                    }
816                    else if (!friendly_filters[z][1])
817                        {
818                            sql+=" mail."+this.aux_convert_filter_field(friendly_filters[z][0]);
819                        }
820                        else
821                            {
822                                sql+=" mail."+this.aux_convert_filter_field(friendly_filters[z][0])+" like '%"+url_decode(friendly_filters[z][1])+"%'";
823                            }
[670]824                }
825                sql += ")";
826                var rs = this.dbGears.execute(sql);
827                var retorno = "";
828                while(rs.isValidRow()) {
[1622]829                    var header = connector.unserialize(rs.field(0));
[1747]830                    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)+"##";
[1622]831                    rs.next();
[670]832                }
833
834                this.finalize();
835                return retorno==""?false:retorno;
836
837        }
838       
839        local_messages.prototype.aux_convert_size = function(size) {
840                var tmp = Math.floor(size/1024);
841                if(tmp >= 1){
842                        return tmp + " kb";     
843                }else{
844                        return size + " b";     
845                }
846               
847        }
848       
[1622]849        local_messages.prototype.aux_convert_filter_field = function(filter,date) {
850                if (typeof date != 'undefined'){
851                    var dateObj=new Date();
852                    dateObj.setFullYear(date[2],date[1]-1,date[0]);
853                }
854
[670]855                if((filter=="SUBJECT ") || (filter=="SUBJECT"))
856                        return "subject";
857                else if((filter=="BODY ") || (filter=="BODY"))
858                        return "body";
859                else if((filter=="FROM ") || (filter=="FROM"))
860                        return "ffrom";
861                else if((filter=="TO ") || (filter=="TO"))
862                        return "fto";
863                else if((filter=="CC ") || (filter=="CC"))
864                        return "cc";
[1622]865                else if (filter.replace(/^\s+|\s+$/g,"") == "SINCE"){
866                        dateObj.setHours(0, 0, 0, 0);
867                        return ">= " + dateObj.getTime().toString(10).substr(0, 10);
868                }
869                else if (filter.replace(/^\s+|\s+$/g,"") == "BEFORE"){
870                        dateObj.setHours(23, 59, 59, 999);
871                        return "<= " + dateObj.getTime().toString(10).substr(0, 10);
872                }
873                else if (filter.replace(/^\s+|\s+$/g,"") == "ON"){
874                        dateObj.setHours(0, 0, 0, 0);
875                        var ts1 = dateObj.getTime().toString(10).substr(0, 10);
876                        dateObj.setHours(23, 59, 59, 999);
877                        var ts2 = dateObj.getTime().toString(10).substr(0, 10);
878                        return ">= " + ts1 + ") and (timestamp <= " + ts2;
879                }
880                else if (filter.replace(/^\s+|\s+$/g,"") == "FLAGGED")
881                        return "flagged = 1";
882                else if (filter.replace(/^\s+|\s+$/g,"") == "UNFLAGGED")
883                        return "flagged = 0";
884                else if (filter.replace(/^\s+|\s+$/g,"") == "UNSEEN")
885                        return "unseen = 1";
886                else if (filter.replace(/^\s+|\s+$/g,"") == "SEEN")
887                        return "unseen = 0";
888                else if (filter.replace(/^\s+|\s+$/g,"") == "ANSWERED")
889                        return "answered = 1";
890                else if (filter.replace(/^\s+|\s+$/g,"") == "UNANSWERED")
891                        return "answered = 0";
892                else if (filter.replace(/^\s+|\s+$/g,"") == "RECENT")
893                        return "recent = 1";
894                else if (filter.replace(/^\s+|\s+$/g,"") == "OLD")
895                        return "recent = 0";
896
[670]897        }
898       
899        local_messages.prototype.has_local_mails = function() {
900                this.init_local_messages();
901                var rs = this.dbGears.execute("select rowid from folder limit 0,1");
902                var retorno;
903                if(rs.isValidRow())
904                        retorno = true;
905                else
906                        retorno = false;
907                this.finalize();
908                return retorno;
909        }
[1000]910
[1666]911     //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).
[1000]912    local_messages.prototype.get_src = function(url){
913        AJAX = false;
914        if (window.XMLHttpRequest) { // Mozilla, Safari,...
915            AJAX = new XMLHttpRequest();
916            if (AJAX.overrideMimeType) {
917                AJAX.overrideMimeType('text/xml');
918            }
919        } else if (window.ActiveXObject) { // IE
920            try {
921                AJAX = new ActiveXObject("Msxml2.XMLHTTP");
922            } catch (e) {
923                try {
924                AJAX = new ActiveXObject("Microsoft.XMLHTTP");
925                } catch (e) {}
926            }
927        }
928
929        if (!AJAX) {
[1666]930            alert('ERRO :(Seu navegador nï¿œo suporta a aplicaᅵᅵo usada neste site');
[1000]931            return false;
932        }
933
934        AJAX.onreadystatechange = function() {
935            if (AJAX.readyState == 4) {
936                AJAX.src=AJAX.responseText;
937                if (AJAX.status == 200) {
938                    return AJAX.responseText;
939                    } else {
940                    return false;
941                }
942            }
943        }
944
945        AJAX.open('get', url, false);
946        AJAX.send(null);
947        return AJAX.responseText;
948    };
949
950  //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
[1666]951  //para que elas sejam inseridas no imap pela funᅵᅵo  imap_functions.unarchive_mail.
[1000]952    local_messages.prototype.unarchive_msgs = function (folder,new_folder,msgs_number){
953
954        if(!new_folder)
955            new_folder='INBOX';
956        this.init_local_messages();
957       // alert(folder+new_folder+msgs_number);
958        var handler_unarchive = function(data)
959        {
960            if(data.error == '')
961                write_msg(get_lang('All messages are successfully unarchived'));
962            else
963                alert(data.error);
964        }
965        if(msgs_number =='selected' || !msgs_number)
966        {
967            msgs_number = get_selected_messages()
968            if (!msgs_number){
969                write_msg(get_lang('No selected message.'));
970                return;
971            }
972            var rs = this.dbGears.execute("select mail,timestamp from mail where rowid in ("+msgs_number+")");
973            var source="";
974            var timestamp="";
975            while(rs.isValidRow()) {
976                mail=connector.unserialize(rs.field(0));
977                source_tmp=escape(this.get_src(mail.url_export_file));
978                    source+="#@#@#@"+source_tmp;
979                    timestamp+="#@#@#@"+rs.field(1);
980                rs.next();
981            }
982            rs.close();
983            this.finalize();
984        }
985        else
986        {
987            var rs = this.dbGears.execute("select mail,timestamp from mail where rowid="+msgs_number);
988            mail=connector.unserialize(rs.field(0));
989            var source ="";
990            source = this.get_src(mail.url_export_file);
991            timestamp=rs.field(1);
992             rs.close();
993             this.finalize();
994        }
995            params="&folder="+new_folder+"&source="+source+"&timestamp="+timestamp;
996            cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
997    }
998
[1340]999    local_messages.prototype.get_msg_date = function (original_id, is_local){
[1000]1000
[1035]1001        this.init_local_messages();
1002
[1340]1003        if (typeof(is_local) == 'undefined')
1004        {
1005            is_local = false;
1006        }
1007
1008        var rs;
1009
1010        if (is_local)
1011        {
1012            rs = this.dbGears.execute("select mail from mail where rowid="+original_id);
1013        }
1014        else
1015        {
1016            rs = this.dbGears.execute("select mail from mail where original_id="+original_id);
1017        }
[1035]1018        var tmp = connector.unserialize(rs.field(0));
1019        var ret = new Array();
1020        ret.fulldate = tmp.fulldate.substr(0,16);
1021        ret.smalldate = tmp.msg_day;
1022        ret.msg_day = tmp.msg_day;
1023        ret.msg_hour = tmp.msg_day;
1024
1025        rs.close();
1026        this.finalize();
1027        return ret;
1028    }
1029
1030
[1000]1031    local_messages.prototype.download_all_local_attachments = function(folder,id){
1032        this.init_local_messages();
1033        var rs = this.dbGears.execute("select mail from mail where rowid="+id);
1034        var tmp = connector.unserialize(rs.field(0));
1035        rs.close();
1036        this.finalize();
1037        source = this.get_src(tmp.url_export_file);
1038        source = escape(source);
1039        var handler_source = function(data){
1040            download_attachments(null, null, data, null,null,'anexos.zip');
1041        }
1042        cExecute("$this.imap_functions.download_all_local_attachments",handler_source,"source="+source);
1043    }
1044
1045    /*************************************************************************/
1046/* Funcao usada para exportar mensagens arquivadas localmente.
1047 * Rommel de Brito Cysne (rommel.cysne@serpro.gov.br)
1048 * em 22/12/2008.
1049 */
1050    local_messages.prototype.local_messages_to_export = function(){
1051
1052        if (openTab.type[currentTab] > 1){
1053            var msgs_to_export_id = currentTab.substring(0,currentTab.length-2,currentTab);
1054        }else{
1055            var msgs_to_export_id = get_selected_messages();
1056        }
1057        var handler_local_mesgs_to_export = function(data){
1058            download_attachments(null, null, data, null,null,'mensagens.zip');
1059        }
1060        if(msgs_to_export_id){
1061            this.init_local_messages();
1062            var l_msg = "t";
1063            var mesgs ="";
1064            var subjects ="";
1065            var rs = this.dbGears.execute("select mail,subject from mail where rowid in ("+msgs_to_export_id+")");
1066            while(rs.isValidRow()){
1067                mail = connector.unserialize(rs.field(0));
[1752]1068                mail.msg_source?src = mail.msg_source:src = this.get_src(mail.url_export_file);
[1000]1069                subject = rs.field(1);
1070                mesgs += src;
1071                mesgs += "@@";
1072                subjects += subject;
1073                subjects += "@@";
1074                rs.next();
1075            }
1076            rs.close();
1077            this.finalize();
1078            mesgs = escape(mesgs);
1079            subjects = escape(subjects);
1080            params = "subjects="+subjects+"&mesgs="+mesgs+"&l_msg="+l_msg+"&msgs_to_export="+msgs_to_export_id;
1081            cExecute ("$this.exporteml.makeAll&", handler_local_mesgs_to_export, params);
1082        }
1083        return true;
1084    }
1085
1086    local_messages.prototype.get_all_local_folder_messages= function(folder_name){
1087
1088
1089         var mesgs = new Array();
1090         var subjects = new Array();
1091         var hoje = new Date();
1092         var msgs_to_export = new Array();
1093         var l_msg="t";
1094
1095        this.init_local_messages();
1096        var query = "select mail,subject,mail.rowid from mail inner join folder on (mail.id_folder=folder.rowid) where folder.folder='" + folder_name + "'";
1097
1098        var rs = this.dbGears.execute(" "+query)
1099
1100            var handler_local_mesgs_to_export = function(data){
1101                    //alert("data - " + data + " - tipo - " + typeof(data));
1102                    download_attachments(null, null, data, null,null,'mensagens.zip');
1103            }
1104        var j=0;
1105        while (rs.isValidRow()){
1106              msgs_to_export[j]=rs.field(2)
1107              mail = connector.unserialize(rs.field(0));
[1752]1108                      mail.msg_source?src = mail.msg_source:src = this.get_src(mail.url_export_file);
[1000]1109                      subject = rs.field(1);
1110                      mesgs += msg;
1111                      mesgs += "@@";
1112                      subjects += subject;
1113                      subjects += "@@";
1114                      rs.next();
1115              j++;
1116
1117        }
1118           rs.close();
1119           this.finalize();
1120           source = escape(mesgs);
1121           subjects = escape(subjects);
1122           params = "folder="+folder_name+"&subjects="+subjects+"&mesgs="+source+"&l_msg="+l_msg+"&msgs_to_export="+msgs_to_export;
1123           cExecute ("$this.exporteml.makeAll&", handler_local_mesgs_to_export, params);
1124         
1125
1126    }
1127
1128
1129    /*************************************************************************/
1130
[670]1131       
[1121]1132/******************************************************************
1133                                        Offline Part
1134 ******************************************************************/
1135
1136        local_messages.prototype.is_offline_installed = function() {
1137                this.init_local_messages();
1138                var check = this.localServer.openManagedStore('expresso-offline');
1139                this.finalize();
1140                if(check==null)
1141                        return false;
1142                else
1143                        return true;
1144               
1145        }
1146        local_messages.prototype.update_offline = function(redirect) {
1147                this.init_local_messages();
1148                var managedStore = this.localServer.openManagedStore('expresso-offline');
1149
1150                if(managedStore!=null){
1151                       
1152                        managedStore.oncomplete = function(details){
1153                                if(redirect!=null)
1154                                        location.href=redirect;
1155                        }
1156                       
1157                        managedStore.checkForUpdate();
1158                } else if(redirect!=null) {
1159                        location.href=redirect;
1160                }
1161                this.finalize();
1162        }
1163       
1164        local_messages.prototype.uninstall_offline = function() {
1165                if (!window.google || !google.gears) {
1166                                temp = confirm(document.getElementById('lang_gears_redirect').value);
1167                                if (temp) {
[1466]1168                                        expresso_local_messages.installGears();
[1121]1169                                }
1170                                return;
1171
1172                }
1173                this.init_local_messages();
1174                this.localServer.removeManagedStore('expresso-offline');
1175                alert(document.getElementById('lang_offline_uninstalled').value);
1176                //this.dbGears.execute('drop table user');
1177                //this.dbGears.execute('drop table queue');
1178                //this.dbGears.execute('drop table attachments_queue');
1179                this.finalize();
1180        }
1181       
[1595]1182        local_messages.prototype.get_folders_to_sync = function() {//Precisa ter visibilidade ao array de linguagens.
[1518]1183                this.init_local_messages();
1184                var rs = this.dbGears.execute("select id_folder,folder_name from folders_sync where uid_usuario="+account_id);
1185                var retorno = new Array();
1186                while(rs.isValidRow()) {
1187                        temp = new Array();
1188                        temp[0] = rs.field(0);
[1595]1189                        if(temp[0]=='INBOX/Drafts' ||temp[0]=='INBOX/Trash' || temp[0]=='INBOX/Sent') {
1190                                temp[1] = array_lang[rs.field(1).toLowerCase()];
1191                        }
1192                        else {
1193                                temp[1] = rs.field(1); 
1194                        }
1195                       
[1518]1196                        retorno.push(temp);
1197                        rs.next();
1198                }
1199                this.finalize();
1200                return retorno;
1201        }
1202       
[1121]1203        local_messages.prototype.install_offline = function(urlOffline,urlIcone,uid_usuario,login,pass,redirect) {
1204                if (!window.google || !google.gears) {
1205                                temp = confirm(document.getElementById('lang_gears_redirect').value);
1206                                if (temp) {
[1466]1207                                         expresso_local_messages.installGears();
[1121]1208                                }
1209                                return;
1210
1211                }
1212               
1213                if(pass.length>0) {
1214                        only_spaces = true;
1215                        for(cont=0;cont<pass.length;cont++) {
1216                                if(pass.charAt(cont)!=" ")
1217                                        only_spaces = false;
1218                        }
1219                        if(only_spaces) {
1220                                alert(document.getElementById('lang_only_spaces_not_allowed').value);
1221                                return false;
1222                        }
1223                }
1224
1225                modal('loading');
1226                var desktop = google.gears.factory.create('beta.desktop');
1227                desktop.createShortcut('ExpressoMail Offline',
1228                        urlOffline,
1229                {'32x32': urlIcone},
1230                'ExpressoMail Offline');
1231
1232
1233                this.init_local_messages();
1234
1235                //user with offline needs to have at least the folder Inbox already created.
1236                tmp_rs = this.dbGears.execute("select rowid from folder where folder='Inbox' and uid_usuario=?",[uid_usuario]);
1237                if(!tmp_rs.isValidRow())
1238                        this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",['Inbox',uid_usuario]);
1239
1240                this.localServer.removeManagedStore('expresso-offline');
1241       
1242                var managedStore = this.localServer.createManagedStore('expresso-offline');
1243                managedStore.manifestUrl = 'js/manifest';
1244
1245                managedStore.onerror = function (error) {
1246                        alert(error);
1247                }
1248               
1249                managedStore.oncomplete = function(details) {
1250                        if (close_lightbox_div) {
1251                                close_lightbox();
1252                                close_lightbox_div = false;
1253                                alert(document.getElementById('lang_offline_installed').value);
1254                                location.href=redirect;
1255                        }
1256                }
1257
1258                //create structure to user in db
1259                this.dbGears.execute('create table if not exists user (uid_usuario int,login text,pass text, logged int,unique(uid_usuario))');
1260                this.dbGears.execute('create table if not exists queue (ffrom text, fto text, cc text, cco text,'+
1261                        'subject text, conf_receipt int, important int,body text,sent int,user int)');
1262                this.dbGears.execute('create table if not exists attachments_queue ('+
1263                        'id_queue int, url_attach text)');
1264                this.dbGears.execute('create table if not exists sent_problems (' +
1265                        'id_queue int,message text)');
1266               
1267                //d = new Date();
1268               
1269                try {
1270                        var rs = this.dbGears.execute("select uid_usuario from user where uid_usuario=?",[uid_usuario]);
1271                        if(!rs.isValidRow())
1272                                this.dbGears.execute("insert into user (uid_usuario,login,pass) values (?,?,?)",[uid_usuario,login,pass]);
1273                        else
1274                                this.dbGears.execute("update user set pass=? where uid_usuario=?",[pass,uid_usuario]);
1275                } catch (error) {
1276                        this.finalize();
1277                        alert(error);
1278                        return false;
1279                }
1280                managedStore.checkForUpdate();
1281               
1282                this.finalize();
1283        }
1284       
1285        /**
1286         * Return all users in an array following the structure below.
1287         *
1288         * key: uid
1289         * value: user login
1290         */
1291        local_messages.prototype.get_all_users = function() {
1292                this.init_local_messages();
1293                var users = new Array();
1294                var rs = this.dbGears.execute("select uid_usuario,login from user");
1295                while(rs.isValidRow()) {
1296                        users[rs.field(0)] = rs.field(1);
1297                        rs.next();
1298                }
1299                this.finalize();
1300                return users;
1301        }
1302       
1303        local_messages.prototype.set_as_logged = function(uid_usuario,pass) {
1304                this.init_local_messages();
1305                var rs = this.dbGears.execute("select pass from user where uid_usuario=?",[uid_usuario]);
1306                if(!rs.isValidRow() || (pass!=rs.field(0) && pass!=MD5(rs.field(0))) ) {
1307                        this.finalize();
1308                        return false;
1309                }
1310                d = new Date();
1311
1312                this.dbGears.execute("update user set logged=null"); //Logoff in everybody
1313                this.dbGears.execute("update user set logged=? where uid_usuario=?",[d.getTime(),uid_usuario]); //Login just in one...
1314                this.finalize();
1315                return true;
1316        }
1317       
1318        local_messages.prototype.unset_as_logged = function() {
1319                this.init_local_messages();
1320                this.dbGears.execute("update user set logged=null"); //Logoff in everybody
1321                this.finalize();
1322        }
1323       
1324        local_messages.prototype.user_logged = function() {
1325                this.init_local_messages();
1326                var user_logged = new Array();
1327                var rs = this.dbGears.execute("select uid_usuario,logged from user where logged is not null");
1328                if(!rs.isValidRow()) {
1329                        this.finalize();
1330                        return null;
1331                }
1332                user_logged[0] = rs.field(0);
1333                user_logged[1] = rs.field(1);
1334                this.finalize();
1335                return user_logged;
1336        }
1337       
1338        local_messages.prototype.send_to_queue = function (form) {
1339                this.init_local_messages();
1340                var mail_values = new Array();
1341               
1342                for (var i=0;i<form.length;i++) {
1343                        if (form.elements[i].name != '') { //I.E made me to do that...
1344                                if(form.elements[i].name=='folder' || form.elements[i].name=='msg_id' || form.elements[i].name=='' || form.elements[i].name==null)
1345                                        continue;
1346                                else if (form.elements[i].name == 'input_return_receipt' )
1347                                        mail_values['conf_receipt'] = form.elements[i].checked ? 1 : 0;
1348                                else if(form.elements[i].name == 'input_important_message')
1349                                        mail_values['important'] = form.elements[i].checked ? 1 : 0;
1350                                else
1351                                        if (form.elements[i].name == 'body')
1352                                                mail_values['body'] = form.elements[i].value;
1353                                        else
1354                                                if (form.elements[i].name == 'input_from')
1355                                                        mail_values['ffrom'] = form.elements[i].value;
1356                                                else
1357                                                        if (form.elements[i].name == 'input_to')
1358                                                                mail_values['fto'] = form.elements[i].value;
1359                                                        else
1360                                                                if (form.elements[i].name == 'input_cc')
1361                                                                        mail_values['cc'] = form.elements[i].value;
1362                                                                else
1363                                                                        if (form.elements[i].name == 'input_cco')
1364                                                                                mail_values['cco'] = form.elements[i].value;
1365                                                                        else
1366                                                                                if (form.elements[i].name == 'input_subject')
1367                                                                                        mail_values['subject'] = form.elements[i].value;
1368                        }
1369                }
1370                //mail_values['fto'] = input_to;
1371                //mail_values['cc'] = input_cc;
1372                //mail_values['cco'] = input_cco;
1373                //mail_values['subject'] = input_subject;
1374                //mail_values['conf_receipt'] = input_return_receipt;
1375                //mail_values['important'] = input_important_message;
1376               
1377                try {
1378                        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]);
1379                        this.send_attach_to_queue(this.dbGears.lastInsertRowId,form);
1380                }catch(error) {
1381                        alert(error);
1382                        return get_lang('Error sending a mail to queue. Verify if you have installed ExpressoMail Offline');
1383                }
1384                this.finalize();
1385                return true;
1386        }
1387       
1388        local_messages.prototype.send_attach_to_queue = function(id_queue,form) {
1389               
1390                for(i=0;i<form.elements.length;i++) {
1391                       
1392                        if(form.elements[i].name.indexOf("file_")!=-1) {
1393                                var tmp_input = form.elements[i];
1394                                var d = new Date();
1395                                var url_local = 'local_attachs/'+d.getTime();
1396                                this.store.captureFile(tmp_input, url_local);
1397                                this.dbGears.execute("insert into attachments_queue (id_queue,url_attach) values (?,?)",[id_queue,url_local]);
1398                        }
1399                        else if(form.elements[i].name.indexOf("offline_forward_")!=-1){
1400                                //alert();
1401                                this.dbGears.execute("insert into attachments_queue (id_queue,url_attach) values (?,?)",[id_queue,form.elements[i].value]);
1402                        }
1403                }
1404        }
1405
1406       
1407        local_messages.prototype.get_num_msgs_to_send = function() {
1408                this.init_local_messages();
1409
1410                var rs = this.dbGears.execute("select count(*) from queue where user=? and sent=0",[account_id]);
1411                var to_return = rs.field(0);
1412
1413                this.finalize();
1414                return to_return;
1415        }
1416       
1417        local_messages.prototype.set_problem_on_sent = function(rowid_message,msg) {
1418                this.init_local_messages();
1419                this.dbGears.execute("update queue set sent = 2 where rowid=?",[rowid_message]);
1420                this.dbGears.execute("insert into sent_problems (id_queue,message) values (?,?)"[rowid_message,msg]);
1421                this.finalize();
1422        }
1423       
1424        local_messages.prototype.set_as_sent = function(rowid_message) {
1425                this.init_local_messages();
1426                this.dbGears.execute("update queue set sent = 1 where rowid=?",[rowid_message]);
1427                this.finalize();
1428        }
1429       
1430        local_messages.prototype.get_form_msg_to_send = function() {
1431                this.init_local_messages();
1432                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]);
1433                if(!rs.isValidRow())
1434                        return false;
1435               
1436                var form = document.createElement('form');
1437                form.method = 'POST';
1438                form.name = 'form_queue_'+rs.field(8);
1439                form.style.display = 'none';
1440                form.onsubmit = function(){return false;}
1441                if(!is_ie)
1442                        form.enctype="multipart/form-data";
1443                else
1444                        form.encoding="multipart/form-data";
1445               
1446                var ffrom = document.createElement('TEXTAREA');
1447                ffrom.name = "input_from";
1448                ffrom.value = rs.field(0);
1449                form.appendChild(ffrom);
1450               
1451                var fto = document.createElement('TEXTAREA');
1452                fto.name = "input_to";
1453                fto.value = rs.field(1);
1454                form.appendChild(fto);
1455               
1456                var cc = document.createElement('TEXTAREA');
1457                cc.name = "input_cc";
1458                cc.value = rs.field(2);
1459                form.appendChild(cc);
1460
1461                var cco = document.createElement('TEXTAREA');
1462                cco.name = "input_cco";
1463                cco.value = rs.field(3);
1464                form.appendChild(cco);
1465               
1466                var subject = document.createElement('TEXTAREA');
1467                subject.name = "input_subject";
1468                subject.value = rs.field(4);
1469                form.appendChild(subject);
1470               
1471                var folder = document.createElement('input');
1472                folder.name='folder';
1473                folder.value=preferences.save_in_folder;
1474                form.appendChild(folder);
1475               
1476                if (rs.field(5) == 1) {
1477                        var conf_receipt = document.createElement('input');
1478                        conf_receipt.type='text';
1479                        conf_receipt.name = "input_return_receipt";
1480                        conf_receipt.value = 'on';
1481                        form.appendChild(conf_receipt);
1482                }
1483               
1484                if (rs.field(6) == 1) {
1485                        var important = document.createElement('input');
1486                        important.type='text';
1487                        important.name = "input_important_message";
1488                        important.value = 'on';
1489                        form.appendChild(important);
1490                }
1491               
1492                var body = document.createElement('TEXTAREA');
1493                body.name = "body";
1494                body.value = rs.field(7);
1495                form.appendChild(body);
1496               
1497                var rowid = document.createElement('input');
1498                rowid.type = 'hidden';
1499                rowid.name = 'rowid';
1500                rowid.value = rs.field(8);
1501                form.appendChild(rowid);
1502               
1503                //Mounting the attachs
1504                var divFiles = document.createElement("div");
1505                divFiles.id = 'divFiles_queue_'+rs.field(8);
1506               
1507                form.appendChild(divFiles);
1508               
1509                document.getElementById('forms_queue').appendChild(form);
1510
1511                var is_local_forward = false;
1512                try {
1513                       
1514                        var rs_attach = this.dbGears.execute('select url_attach from attachments_queue where id_queue=?', [rs.field(8)]);
1515                        while (rs_attach.isValidRow()) {
1516                                if(rs_attach.field(0).indexOf('../tmpLclAtt/')==-1) {
1517                                        tmp_field = addForwardedFile('queue_' + rs.field(8), this.store.getCapturedFileName(rs_attach.field(0)), 'nothing');
1518                                }
1519                                else {
1520                                        var tempNomeArquivo = rs_attach.field(0).split("/");
1521                                        var nomeArquivo = tempNomeArquivo[tempNomeArquivo.length-1];
[1666]1522                                        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.
[1121]1523                                        is_local_forward = true;
1524                                        tmp_field = addForwardedFile('queue_' + rs.field(8), nomeArquivo, 'nothing');
1525                                }
1526                                fileSubmitter = this.store.createFileSubmitter();
1527                                fileSubmitter.setFileInputElement(tmp_field,rs_attach.field(0));
1528                //              alert(form.innerHTML);
1529                        //      div.appendChild(tmp_field);
1530                                rs_attach.next();
1531                        }
1532                       
1533                        if(is_local_forward) {
1534                                var is_lcl_fw = document.createElement('input');
1535                                is_lcl_fw.type = 'hidden';
1536                                is_lcl_fw.name = 'is_local_forward';
1537                                is_lcl_fw.value = "1";
1538                                form.appendChild(is_lcl_fw);
1539                        }
1540                               
1541                }
1542                catch(exception) {
1543                        alert(exception);
1544                }
1545               
1546                this.finalize();
1547                return form;
1548        }
1549
[670]1550        var expresso_local_messages;
1551        expresso_local_messages = new local_messages();
Note: See TracBrowser for help on using the repository browser.