/**
* @author diogenes
*/
function local_messages() {
this.dbGears = null;
this.localServer = null;
this.store = null;
this.fileSubmitter = null;
}
local_messages.prototype.init_local_messages = function(){
if(this.dbGears == null)
this.dbGears = google.gears.factory.create('beta.database');
if(this.localServer==null)
this.localServer = google.gears.factory.create('beta.localserver');
if(this.store==null)
this.store = this.localServer.createStore('test-store');
this.dbGears.open('database-test');
this.dbGears.execute('create table if not exists folder (folder text,uid_usuario int,unique(folder,uid_usuario))');
this.dbGears.execute('create table if not exists mail' +
' (mail blob,original_id int,original_folder text,header blob,timestamp int,uid_usuario int,unseen int,id_folder int,' +
' ffrom text, subject text, fto text, cc text, body text, size int,unique (original_id,original_folder,uid_usuario))');
this.dbGears.execute('create table if not exists anexo' +
' (id_mail int,nome_anexo text,url text,pid int)');
//some people that used old version of local messages could not have the size column. If it's the first version
//with local messages you're using in expresso, this part of code can be removed
try {
this.dbGears.execute('alter table mail add column size int');
}catch(Exception) {
}
var rs = this.dbGears.execute('select rowid,header from mail where size is null');
while(rs.isValidRow()) {
var temp = connector.unserialize(rs.field(1));
this.dbGears.execute('update mail set size='+temp.Size+' where rowid='+rs.field(0));
rs.next();
}
//end of temporary code
}
local_messages.prototype.drop_tables = function() {
this.init_local_messages();
var rs = this.dbGears.execute('select url from anexo');
while(rs.isValidRow()) {
this.store.remove(rs.field(0));
rs.next();
}
this.dbGears.execute('drop table folder');
this.dbGears.execute('drop table mail');
this.dbGears.execute('drop table anexo');
this.finalize();
}
local_messages.prototype.insert_mail = function(msg_info,msg_header,anexos,folder) {
try {
this.init_local_messages();
var unseen = 0;
var login = msg_info.login;
var original_id = msg_info.msg_number;
var original_folder = msg_info.msg_folder;
//This fields needs to be separeted to search.
var from = connector.serialize(msg_info.from);
var subject = msg_info.subject;
var body = msg_info.body;
var to = connector.serialize(msg_info.toaddress2);
var cc = connector.serialize(msg_info.cc);
var size = msg_header.Size;
//do not duplicate this information
msg_info.from = null;
msg_info.subject = null;
msg_info.body = null;
msg_info.to = null;
msg_info.cc = null;
msg_header.Size=null;
//If the mail was archieved in the same date the user received it, the date cames with the time.
//here I solved it
if(msg_header.udate.indexOf(":")!=-1) {
msg_header.udate = msg_header.aux_date;
}
/**
* The importance attribute can be empty, and javascript consider as null causing nullpointer.
*/
if((msg_header.Importance == null) || (msg_header.Importance == ""))
msg_header.Importance = "Normal";
msg_header.aux_date = null;
var mail = connector.serialize(msg_info);
var header = connector.serialize(msg_header);
var timestamp = msg_info.timestamp;
var id_folder;
if((folder==null) || (folder=="local_root"))
folder = "Inbox";
else
folder = folder.substr(6);//take off the word "local_"
var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[folder,account_id]);
if(rs.isValidRow())
id_folder=rs.field(0);
else {
this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",["Inbox",account_id]);
id_folder = this.dbGears.lastInsertRowId;
}
if(msg_info.Unseen=="U")
unseen = 1;
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]);
var call_back = function() {
}
this.store.capture(msg_info.url_export_file,call_back);
var id_mail = this.dbGears.lastInsertRowId;
this.insert_attachments(id_mail,anexos);
this.finalize();
return true;
} catch (error) {
this.finalize();
return false;
}
}
/**
* check if ID is no from main tab, if it's from main returns false, else
* returns an array with all string in position 0, the mail id in position 1
* and the part of string relative to tab in position 2
* @param {Object} id_mail
*/
local_messages.prototype.parse_id_mail = function(id_mail) {
if (this.isInt(id_mail))
return false;
var matches = id_mail.match(/(.+)(_[a-zA-Z0-9]+)/);
return matches;
}
local_messages.prototype.isInt = function(x) {
var y=parseInt(x);
if (isNaN(y)) return false;
return x==y && x.toString()==y.toString();
}
local_messages.prototype.get_local_mail = function(id_mail) {
this.init_local_messages();
var plus_id = '';
var matches = '';
if(matches = this.parse_id_mail(id_mail)) { //Mails coming from other tab.
id_mail = matches[1];
plus_id = matches[2];
}
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);
var retorno = null;
if(rs.isValidRow()) {
retorno = rs.field(1);
}
retorno = connector.unserialize(retorno);
//alert('tipo retorno.source: ' + typeof(retorno.source));
if (typeof(retorno.source) == 'string')
{
retorno.msg_number=rs.field(0)+plus_id;
retorno.original_ID=rs.field(8);
retorno.msg_folder=rs.field(7);
//alert('tipo retorno: '+typeof(retorno))
//show_msg(retorno);
}
else
{
retorno['from'] = connector.unserialize(rs.field(2));
retorno['subject'] = rs.field(3);
retorno['body'] = rs.field(4);
//Codigo que as imagens embutidas em emails (com multipart/related ou multipart/mixed) sejam corretamente mostradas em emails arquivados. Os links do
//tipo "./inc/show_embedded_attach.php?msg_folder=[folder]&msg_num=[msg_num]&msg_part=[part]"
//são substituidos pelos links dos anexos capturados pelo gears.
var thumbs= retorno.thumbs;
var anexos= retorno.array_attach;
for (i in anexos)
{
nomeArquivo = anexos[i]['name'].substring(0,anexos[i]['name'].length - 4);
if(nomeArquivo.match('jpg')||anexos[i]['name'].match('gif')||anexos[i]['name'].match('png'))
{
var er_imagens = new RegExp("\\.\\/inc\\/show_embedded_attach.php\\?msg_folder=[\\w/]+\\&msg_num=[0-9]+\\&msg_part="+anexos[i]['pid']);
var Result_imagens = er_imagens.exec(retorno['body']);
retorno['body'] = retorno['body'].replace(Result_imagens,anexos[i]['url']);
if(thumbs && thumbs[i]){
er_imagens = new RegExp("\\.\\/inc\\/show_thumbs.php\\?file_type=image\\/[\\w]+\\&msg_num=[0-9]+\\&msg_folder=[\\w/%]+\\&msg_part="+anexos[i]['pid']);
Result_imagens = er_imagens.exec(thumbs[i]);
thumbs[i] = thumbs[i].replace(Result_imagens,"'"+anexos[i]['url']+"'");
er_imagens = new RegExp("\\.\\/inc\\/show_img.php\\?msg_num=[0-9]+\\&msg_folder=[\\w/%]+\\&msg_part="+anexos[i]['pid']);
Result_imagens = er_imagens.exec(thumbs[i]);
thumbs[i] = thumbs[i].replace(Result_imagens,"'"+anexos[i]['url']+"'");
thumbs[i] = thumbs[i].replace(/0)
rs2.close();
this.finalize();
return retorno;
}
local_messages.prototype.get_url_anexo = function(msg_number,pid) {
this.init_local_messages();
var matches = '';
if(matches = this.parse_id_mail(msg_number)) {
msg_number = matches[1];
}
var retorno;
var rs = this.dbGears.execute("select url from anexo where id_mail="+msg_number+" and pid = '"+pid+"'");
retorno = rs.field(0)
this.finalize();
return retorno;
}
local_messages.prototype.getInputFileFromAnexo = function (element,url) {
this.init_local_messages();
fileSubmitter = this.store.createFileSubmitter();
fileSubmitter.setFileInputElement(element,url);
this.finalize();
}
local_messages.prototype.finalize = function() {
this.dbGears.close();
this.dbGears = null;
}
local_messages.prototype.delete_msgs = function(msgs_number,border_ID) {
this.init_local_messages();
var rs = this.dbGears.execute("select url from anexo where id_mail in ("+msgs_number+")");
while(rs.isValidRow()) {
this.store.remove(rs.field(0));
rs.next();
}
this.dbGears.execute("delete from anexo where id_mail in ("+msgs_number+")");
this.dbGears.execute("delete from mail where rowid in ("+msgs_number+")");
this.finalize();
if (msgs_number.length == 1)
write_msg(get_lang("The message was deleted."));
else
write_msg(get_lang("The messages were deleted."));
mail_msg = Element("tbody_box");
try {
msgs_exploded = msgs_number.split(",");
}catch(error) {
msgs_exploded = new Array();
msgs_exploded[0] = msgs_number;
}
var msg_to_delete;
for (var i=0; i';
break;
case "forwarded":
header["Draft"]="X";
header["Answered"]="A";
Element("td_message_answered_"+msgs_to_set[i]).innerHTML = '';
break;
}
rs.close();
if(Element("check_box_message_" + msgs_to_set[i]))
Element("check_box_message_" + msgs_to_set[i]).checked = false;
this.dbGears.execute("update mail set header='"+connector.serialize(header)+"',unseen="+unseen+" where rowid="+msgs_to_set[i]);
}
if(Element('chk_box_select_all_messages'))
Element('chk_box_select_all_messages').checked = false;
this.finalize();
}
local_messages.prototype.set_message_flag = function(msg_number,flag) {
this.set_messages_flag(msg_number,flag);
}
local_messages.prototype.get_unseen_msgs_number = function() {
this.init_local_messages();
var rs = this.dbGears.execute("select count(*) from mail where unseen=1");
var retorno = rs.field(0);
rs.close();
this.finalize();
return retorno;
}
local_messages.prototype.create_folder = function(folder) {
if (folder.indexOf("local_") != -1)
return false; //can't create folder with string local_
this.init_local_messages();
try {
this.dbGears.execute("insert into folder (folder,uid_usuario) values (?,?)",[folder,account_id]);
} catch (error) {
this.finalize();
throw error;
return false;
}
this.finalize();
return true;
}
local_messages.prototype.list_local_folders = function(folder) {
this.init_local_messages();
var retorno = new Array();
rs = this.dbGears.execute("select folder.folder,sum(mail.unseen) from folder left join mail on "+
"folder.rowid=mail.id_folder where folder.uid_usuario=? group by folder.folder",[account_id]);
while(rs.isValidRow()) {
var temp = new Array();
temp[0] = rs.field(0);
temp[1] = rs.field(1);
retorno.push(temp);
rs.next();
}
rs.close();
this.finalize();
return retorno;
}
local_messages.prototype.rename_folder = function(folder,old_folder) {
if (folder.indexOf("local_") != -1)
return false; //can't create folder with string local_
this.init_local_messages();
try {
this.dbGears.execute("update folder set folder=? where folder=? and uid_usuario=?",[folder,old_folder,account_id]);
} catch (error) {
this.finalize();
return false;
}
this.finalize();
return true;
}
local_messages.prototype.remove_folder = function(folder) {
this.init_local_messages();
var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[folder,account_id]);
var folder_id = rs.field(0);
rs.close();
this.dbGears.execute("delete from folder where rowid=?",[folder_id]);
rs = this.dbGears.execute("select rowid,mail from mail where id_folder=?",[folder_id]);
while(rs.isValidRow()) {
var rs2 = this.dbGears.execute("select url from anexo where id_mail=?",[rs.field(0)]);
while(rs2.isValidRow()) {
this.store.remove(rs2.field(0));
rs2.next();
}
rs2.close();
this.dbGears.execute("delete from anexo where id_mail=?",[rs.field(0)]);
var mail = connector.unserialize(rs.field(1));
this.store.remove(mail.url_export_file);
rs.next();
}
rs.close();
this.dbGears.execute("delete from mail where id_folder=?",[folder_id]);
this.finalize();
}
local_messages.prototype.move_messages = function(new_folder,msgs_number) {
this.init_local_messages();
var rs = this.dbGears.execute("select rowid from folder where folder=? and uid_usuario=?",[new_folder,account_id]);
var id_folder = rs.field(0);
rs.close();
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...
this.finalize();
}
local_messages.prototype.search = function(folders,filter) {
this.init_local_messages();
var filters = filter.replace(/##/g," ");
filters = filters.replace(/^ +| +$/g,"");
filters = filters.split("<=>");
var friendly_filters = new Array();
if (filters[0].indexOf('ALL') != -1) { //all filters...
friendly_filters.push("SUBJECT");
friendly_filters.push(filters[1]);
friendly_filters.push("BODY");
friendly_filters.push(filters[1]);
friendly_filters.push("FROM");
friendly_filters.push(filters[1]);
friendly_filters.push("TO");
friendly_filters.push(filters[1]);
friendly_filters.push("CC");
friendly_filters.push(filters[1]);
}
else {
friendly_filters[0] = filters[0];
for (var i in filters) {
if (i != 0) {
var temp = filters[i].split(" ");
friendly_filters.push(temp[0]);
friendly_filters.push(temp[1]);
}
}
}
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 (";
for(var fnum in folders) {
sql+="'"+folders[fnum]+"'";
if(fnum= 1){
return tmp + " kb";
}else{
return size + " b";
}
}
local_messages.prototype.aux_convert_filter_field = function(filter) {
if((filter=="SUBJECT ") || (filter=="SUBJECT"))
return "subject";
else if((filter=="BODY ") || (filter=="BODY"))
return "body";
else if((filter=="FROM ") || (filter=="FROM"))
return "ffrom";
else if((filter=="TO ") || (filter=="TO"))
return "fto";
else if((filter=="CC ") || (filter=="CC"))
return "cc";
}
local_messages.prototype.has_local_mails = function() {
this.init_local_messages();
var rs = this.dbGears.execute("select rowid from folder limit 0,1");
var retorno;
if(rs.isValidRow())
retorno = true;
else
retorno = false;
this.finalize();
return retorno;
}
//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).
local_messages.prototype.get_src = function(url){
AJAX = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
AJAX = new XMLHttpRequest();
if (AJAX.overrideMimeType) {
AJAX.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
AJAX = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!AJAX) {
alert('ERRO :(Seu navegador não suporta a aplicação usada neste site');
return false;
}
AJAX.onreadystatechange = function() {
if (AJAX.readyState == 4) {
AJAX.src=AJAX.responseText;
if (AJAX.status == 200) {
return AJAX.responseText;
} else {
return false;
}
}
}
AJAX.open('get', url, false);
AJAX.send(null);
return AJAX.responseText;
};
//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
//para que elas sejam inseridas no imap pela função imap_functions.unarchive_mail.
local_messages.prototype.unarchive_msgs = function (folder,new_folder,msgs_number){
if(!new_folder)
new_folder='INBOX';
this.init_local_messages();
// alert(folder+new_folder+msgs_number);
var handler_unarchive = function(data)
{
if(data.error == '')
write_msg(get_lang('All messages are successfully unarchived'));
else
alert(data.error);
}
if(msgs_number =='selected' || !msgs_number)
{
msgs_number = get_selected_messages()
if (!msgs_number){
write_msg(get_lang('No selected message.'));
return;
}
var rs = this.dbGears.execute("select mail,timestamp from mail where rowid in ("+msgs_number+")");
var source="";
var timestamp="";
while(rs.isValidRow()) {
mail=connector.unserialize(rs.field(0));
source_tmp=escape(this.get_src(mail.url_export_file));
source+="#@#@#@"+source_tmp;
timestamp+="#@#@#@"+rs.field(1);
rs.next();
}
rs.close();
this.finalize();
}
else
{
var rs = this.dbGears.execute("select mail,timestamp from mail where rowid="+msgs_number);
mail=connector.unserialize(rs.field(0));
var source ="";
source = this.get_src(mail.url_export_file);
timestamp=rs.field(1);
rs.close();
this.finalize();
}
params="&folder="+new_folder+"&source="+source+"×tamp="+timestamp;
cExecute ("$this.imap_functions.unarchive_mail&", handler_unarchive, params);
}
local_messages.prototype.get_msg_date = function (original_id, is_local){
this.init_local_messages();
if (typeof(is_local) == 'undefined')
{
is_local = false;
}
var rs;
if (is_local)
{
rs = this.dbGears.execute("select mail from mail where rowid="+original_id);
}
else
{
rs = this.dbGears.execute("select mail from mail where original_id="+original_id);
}
var tmp = connector.unserialize(rs.field(0));
var ret = new Array();
ret.fulldate = tmp.fulldate.substr(0,16);
ret.smalldate = tmp.msg_day;
ret.msg_day = tmp.msg_day;
ret.msg_hour = tmp.msg_day;
rs.close();
this.finalize();
return ret;
}
local_messages.prototype.download_all_local_attachments = function(folder,id){
this.init_local_messages();
var rs = this.dbGears.execute("select mail from mail where rowid="+id);
var tmp = connector.unserialize(rs.field(0));
rs.close();
this.finalize();
source = this.get_src(tmp.url_export_file);
source = escape(source);
var handler_source = function(data){
download_attachments(null, null, data, null,null,'anexos.zip');
}
cExecute("$this.imap_functions.download_all_local_attachments",handler_source,"source="+source);
}
/*************************************************************************/
/* Funcao usada para exportar mensagens arquivadas localmente.
* Rommel de Brito Cysne (rommel.cysne@serpro.gov.br)
* em 22/12/2008.
*/
local_messages.prototype.local_messages_to_export = function(){
if (openTab.type[currentTab] > 1){
var msgs_to_export_id = currentTab.substring(0,currentTab.length-2,currentTab);
}else{
var msgs_to_export_id = get_selected_messages();
}
var handler_local_mesgs_to_export = function(data){
download_attachments(null, null, data, null,null,'mensagens.zip');
}
if(msgs_to_export_id){
this.init_local_messages();
var l_msg = "t";
var mesgs ="";
var subjects ="";
var rs = this.dbGears.execute("select mail,subject from mail where rowid in ("+msgs_to_export_id+")");
while(rs.isValidRow()){
mail = connector.unserialize(rs.field(0));
src = this.get_src(mail.url_export_file);
subject = rs.field(1);
mesgs += src;
mesgs += "@@";
subjects += subject;
subjects += "@@";
rs.next();
}
rs.close();
this.finalize();
mesgs = escape(mesgs);
subjects = escape(subjects);
params = "subjects="+subjects+"&mesgs="+mesgs+"&l_msg="+l_msg+"&msgs_to_export="+msgs_to_export_id;
cExecute ("$this.exporteml.makeAll&", handler_local_mesgs_to_export, params);
}
return true;
}
local_messages.prototype.get_all_local_folder_messages= function(folder_name){
var mesgs = new Array();
var subjects = new Array();
var hoje = new Date();
var msgs_to_export = new Array();
var l_msg="t";
this.init_local_messages();
var query = "select mail,subject,mail.rowid from mail inner join folder on (mail.id_folder=folder.rowid) where folder.folder='" + folder_name + "'";
var rs = this.dbGears.execute(" "+query)
var handler_local_mesgs_to_export = function(data){
//alert("data - " + data + " - tipo - " + typeof(data));
download_attachments(null, null, data, null,null,'mensagens.zip');
}
var j=0;
while (rs.isValidRow()){
msgs_to_export[j]=rs.field(2)
mail = connector.unserialize(rs.field(0));
msg=this.get_src(mail.url_export_file);
subject = rs.field(1);
mesgs += msg;
mesgs += "@@";
subjects += subject;
subjects += "@@";
rs.next();
j++;
}
rs.close();
this.finalize();
source = escape(mesgs);
subjects = escape(subjects);
params = "folder="+folder_name+"&subjects="+subjects+"&mesgs="+source+"&l_msg="+l_msg+"&msgs_to_export="+msgs_to_export;
cExecute ("$this.exporteml.makeAll&", handler_local_mesgs_to_export, params);
}
/*************************************************************************/
/******************************************************************
Offline Part
******************************************************************/
local_messages.prototype.is_offline_installed = function() {
this.init_local_messages();
var check = this.localServer.openManagedStore('expresso-offline');
this.finalize();
if(check==null)
return false;
else
return true;
}
local_messages.prototype.update_offline = function(redirect) {
this.init_local_messages();
var managedStore = this.localServer.openManagedStore('expresso-offline');
if(managedStore!=null){
managedStore.oncomplete = function(details){
if(redirect!=null)
location.href=redirect;
}
managedStore.checkForUpdate();
} else if(redirect!=null) {
location.href=redirect;
}
this.finalize();
}
local_messages.prototype.uninstall_offline = function() {
if (!window.google || !google.gears) {
temp = confirm(document.getElementById('lang_gears_redirect').value);
if (temp) {
location.href = "http://gears.google.com/?action=install&message="+
"Para utilizar o recurso de mensagens locais, instale o google gears&return=" + document.location.href;
}
return;
}
this.init_local_messages();
this.localServer.removeManagedStore('expresso-offline');
alert(document.getElementById('lang_offline_uninstalled').value);
//this.dbGears.execute('drop table user');
//this.dbGears.execute('drop table queue');
//this.dbGears.execute('drop table attachments_queue');
this.finalize();
}
local_messages.prototype.install_offline = function(urlOffline,urlIcone,uid_usuario,login,pass,redirect) {
if (!window.google || !google.gears) {
temp = confirm(document.getElementById('lang_gears_redirect').value);
if (temp) {
location.href = "http://gears.google.com/?action=install&message="+
"Para utilizar o recurso de mensagens locais, instale o google gears&return=" + document.location.href;
}
return;
}
if(pass.length>0) {
only_spaces = true;
for(cont=0;cont