Index: /branches/2.2/listAdmin/setup/phpgw_es-es.lang
===================================================================
--- /branches/2.2/listAdmin/setup/phpgw_es-es.lang	(revision 3514)
+++ /branches/2.2/listAdmin/setup/phpgw_es-es.lang	(revision 3514)
@@ -0,0 +1,2 @@
+Global Configuration	common	es-es	Configuración global
+Managers	common	es-es	Encargados
Index: /branches/2.2/listAdmin/setup/phpgw_pt-br.lang
===================================================================
--- /branches/2.2/listAdmin/setup/phpgw_pt-br.lang	(revision 3514)
+++ /branches/2.2/listAdmin/setup/phpgw_pt-br.lang	(revision 3514)
@@ -0,0 +1,214 @@
+listAdmin	common	pt-br	Mailman Admin
+listAdmin	listAdmin	pt-br	Mailman Admin
+Global Configuration	common	pt-br	Configurações Globais
+User Accounts	listAdmin	pt-br	Contas de usuários
+User Groups	listAdmin	pt-br	Grupos de usuários
+Email Lists	listAdmin	pt-br	Listas de Emails
+Computers	listAdmin	pt-br	Computadores
+Sectors	listAdmin	pt-br	Setores
+Show Sessions	listAdmin	pt-br	Exibir Sessões
+Logs	listAdmin	pt-br	Logs
+Create User	listAdmin	pt-br	Criar Usuário
+Context	listAdmin	pt-br	Contexto
+Organizations	listAdmin	pt-br	Organizações
+Login ID	listAdmin	pt-br	Login
+Re-Password	listAdmin	pt-br	Re-Senha
+Change password	listAdmin	pt-br	Usuário pode alterar a própria senha?
+Account Active	listAdmin	pt-br	A Conta ExpressoLivre está ativa?
+General Information	listAdmin	pt-br	Informações Gerais
+Email Config	listAdmin	pt-br	Configurações de E-mail
+Groups Permission	listAdmin	pt-br	Grupos
+Aplication Permission	listAdmin	pt-br	Aplicações
+Samba Config	listAdmin	pt-br	Configurações do SAMBA
+Active email account	listAdmin	pt-br	Conta de E-mail ativa
+Alias email	listAdmin	pt-br	E-mail alternativo
+Forwarding email	listAdmin	pt-br	E-mail de encaminhamento
+Only forwarding	listAdmin	pt-br	Somente encaminhar
+Email quota in MB	listAdmin	pt-br	Cota (em MB)
+Quota used in MB	listAdmin	pt-br	Cota utilizada (em MB)
+ListGroups	listAdmin	pt-br	O usuário participa destes Grupos:
+Primary Group	listAdmin	pt-br	Grupo primário
+partici lists	listAdmin	pt-br	O usuário participa destas Listas de E-mail:
+Edit User	listAdmin	pt-br	Edição de Usuário
+Delete user	listAdmin	pt-br	Excluir Usuário
+AcctFlags	listAdmin	pt-br	Tipo de Conta
+Logon Script	listAdmin	pt-br	Script de Logon
+Computer	listAdmin	pt-br	Computador
+Home Directory	listAdmin	pt-br	Diretório Home
+Samba User Desactive	listAdmin	pt-br	Usuário Samba Desabilitado
+Samba User Active	listAdmin	pt-br	Usuário Samba Ativo
+Groups Names	listAdmin	pt-br	Nome do Grupo
+No matches found	listAdmin	pt-br	Nenhum resultado encontrado
+Add Groups	listAdmin	pt-br	Criar Grupos
+Groups Names	listAdmin	pt-br	Nome dos Grupos
+Group users	listAdmin	pt-br	Usuários do Grupo
+Applications	listAdmin	pt-br	Aplicações
+Add User	listAdmin	pt-br	Adicionar Usuário
+Remove User	listAdmin	pt-br	Remover Usuário
+Add Email Lists	listAdmin	pt-br	Criar Listas de E-mail
+Email Lists Logins	listAdmin	pt-br	Login da Lista
+Email Lists Names	listAdmin	pt-br	Nome da Lista
+Email List active	listAdmin	pt-br	A lista de e-mail está ativa?
+Users in Email List	listAdmin	pt-br	Usuários na Lista de Email
+Create Computers	listAdmin	pt-br	Criar computadores
+Edit computers	listAdmin	pt-br	Editar computadores
+Delete computers	listAdmin	pt-br	Deletar computadores
+Computer UID	listAdmin	pt-br	UID do Computador
+Computer Type	listAdmin	pt-br	Tipo do Computador
+WorkStation Active	listAdmin	pt-br	Estação de Trabalho (ATIVO)
+WorkStation Desactive	listAdmin	pt-br	Estação de Trabalho (INATIVO)
+Trust Account	listAdmin	pt-br	Conta de TRUST
+Server	listAdmin	pt-br	Servidor
+Add Sectors	listAdmin	pt-br	Criar Setor
+Sector name	listAdmin	pt-br	Nome do Setor/Organização
+Add Sub-Sectors	listAdmin	pt-br	Criar Sub-Setores
+Do you realy want delete this sector?	listAdmin	pt-br	Você realmente quer DELETAR este setor?
+All users, groups and sub-sectors of this sector will be DELETED!	listAdmin	pt-br	Todos os usuários, grupos, listas e sub-setores SERÃo DELETADOS!
+Content the folling users	listAdmin	pt-br	Contêm os seguintes usuários
+Content the folling groups	listAdmin	pt-br	Contêm os seguintes grupos
+Content the folling sectors	listAdmin	pt-br	Contêm os seguintes setores
+Do you realy want delete this group?	listAdmin	pt-br	Você realmente quer DELETAR este grupo?
+Delete Group	listAdmin	pt-br	Deletar Grupo
+Do you realy want delete this Email List?	listAdmin	pt-br	Você realmente quer DELETAR esta Lista de E-mail?
+Manager Login	listAdmin	pt-br	Login do Gerente
+Hour	listAdmin	pt-br	Hora
+Context	listAdmin	pt-br	Contexto
+Contexto	listAdmin	pt-br	Contexto
+Manager LID	listAdmin	pt-br	Login do Gerente
+Add Manager	listAdmin	pt-br	Adicionar Gerente
+List Managers	listAdmin	pt-br	Lista de Gerentes
+Add Managers	listAdmin	pt-br	Adicionar Gerentes
+Add users	listAdmin	pt-br	Adicionar usuários
+Edit users	listAdmin	pt-br	Editar usuários
+Delete users	listAdmin	pt-br	Deletar usuários
+View user	listAdmin	pt-br	Exibir usuário
+View users	listAdmin	pt-br	Exibir usuários
+Add groups	listAdmin	pt-br	Adicionar grupos
+Edit groups	listAdmin	pt-br	Editar grupos
+Delete groups	listAdmin	pt-br	Deletar grupos
+Change users password	listAdmin	pt-br	Alterar senhas dos usuários
+Add email lists	listAdmin	pt-br	Adicionar listas de emails
+Edit email lists	listAdmin	pt-br	Editar listas de emails
+Delete email lists	listAdmin	pt-br	Deletar listas de emails
+View email lists	listAdmin	pt-br	Exibir listas de emails
+Create Sectors	listAdmin	pt-br	Criar setores
+Edit Sectors	listAdmin	pt-br	Editar setores
+Delete Sectors	listAdmin	pt-br	Deletar setores
+View sessions (local)	listAdmin	pt-br	Exibir sessões (local)
+View sessions (global)	listAdmin	pt-br	Exibir sessões (global)
+View logs	listAdmin	pt-br	Exibir Logs
+Edit Managers	listAdmin	pt-br	Editar Gerentes
+Email Lists	listAdmin	pt-br	Listas de Email Mailman
+Sectors	listAdmin	pt-br	Setores
+Show Sessions - Local	listAdmin	pt-br	Exibir Sessões - Local
+Show Session - Global	listAdmin	pt-br	Exibir Sessões - Global
+No matches found	listAdmin	pt-br	Nenhum registro encontrado
+Logs	listAdmin	pt-br	Logs
+Add User	listAdmin	pt-br	Adicionar Usuários
+Organizations	listAdmin	pt-br	Organizações
+Login ID	listAdmin	pt-br	Login
+Re-Password	listAdmin	pt-br	Re-Senha
+Change password	listAdmin	pt-br	Alterar senha
+Anonymous	listAdmin	pt-br	Anônimo
+Account Active	listAdmin	pt-br	Conta Ativa
+Expire	listAdmin	pt-br	Expira
+General Information	listAdmin	pt-br	Informações Gerais
+Email Config	listAdmin	pt-br	Configuração de Email
+Active email account	listAdmin	pt-br	Conta de email ativa
+Alias email	listAdmin	pt-br	E-mail alternativo
+Forwarding email	listAdmin	pt-br	E-mail de encaminhamento
+Email quota in MB	listAdmin	pt-br	Cota de e-mail em MB
+Quota used in MB	listAdmin	pt-br	Cota de e-mail usada em MB
+Groups Permission	listAdmin	pt-br	Grupos
+ListGroups	listAdmin	pt-br	Lista de Grupos
+Primary Group	listAdmin	pt-br	Grupo Primário
+Remove	listAdmin	pt-br	Remover
+Aplication Permission	listAdmin	pt-br	Aplicações
+Create User	listAdmin	pt-br	Criar Usuário
+Groups Names	listAdmin	pt-br	Nome dos Grupos
+Users for inclusion	listAdmin	pt-br	Usuários para inclusão
+Remove Users	listAdmin	pt-br	Remover Usuários
+Applications for this group	listAdmin	pt-br	Aplicações para este grupo
+Email Lists Names	listAdmin	pt-br	Nome das Listas de E-mails
+Email List name	listAdmin	pt-br	Nome da Lista de E-mail
+Email List active	listAdmin	pt-br	Lista de Email ativa
+Users in Email List	listAdmin	pt-br	Usuários da Lista de Email
+Add Sectores	listAdmin	pt-br	Adicionar Setores
+Add Sub-Sectors	listAdmin	pt-br	Adicionar Sub-Setores
+Sector Name	listAdmin	pt-br	Nome do Setor
+Create Sector	listAdmin	pt-br	Criar Setor
+List of current users	listAdmin	pt-br	Lista de Usuários Conectados
+totalsessions	listAdmin	pt-br	Total de Sessões
+Manager Login	listAdmin	pt-br	Login do Gerente
+Hour	listAdmin	pt-br	Hora
+Only forwarding	listAdmin	pt-br	Somente encaminhar mensagens
+View Log	listAdmin	pt-br	Exibir Log
+User Info	listAdmin	pt-br	Info sobre usuário
+Group Info	listAdmin	pt-br	Info sobre grupos
+App Info	listAdmin	pt-br	Info sobre aplicações
+Edit Group	listAdmin	pt-br	Editar Grupos
+Remove User	listAdmin	pt-br	Remover Usuários
+Add Sectors	listAdmin	pt-br	Adicionar Setores
+Edit Sector	listAdmin	pt-br	Editar Setores
+Do you realy want delete this sector?	listAdmin	pt-br	Você realmente deseja excluir este setor?
+All users, groups and sub-sectors of this sector will be DELETED!	listAdmin	pt-br	Todos os usuários, grupos e sub-setores deste setor irão ser DELETADOS!
+Content the folling users	listAdmin	pt-br	Contêm os seguintes usuários
+Content the folling groups	listAdmin	pt-br	Contêm os seguintes grupos
+Content the folling sectors	listAdmin	pt-br	Contêm os seguintes setores
+You dont have access to this module.	listAdmin	pt-br	Você não tem acesso a este módulo.
+User email alredy exist.	listAdmin	pt-br	E-mail do usuário já cadastrado.
+User login alredy exist.	listAdmin	pt-br	Login do usuário já cadastrado.
+Password and Re-Password doesnt are equal.	listAdmin	pt-br	Senha e Re-Senha não são iguais.
+Edit User	listAdmin	pt-br	Editar Usuário
+Email Lists Logins	listAdmin	pt-br	Login das Listas
+partici lists	listAdmin	pt-br	Participante das Listas
+Rel Lists	listAdmin	pt-br	Relação de Listas
+Error in OpenLDAP.	listAdmin	pt-br	Erro no OpenLDAP.
+Account Invisible	listAdmin	pt-br	Ocultar esta conta das pesquisas e do Catálogo Geral?
+Total Sessions	listAdmin	pt-br	Total de Sessões
+totalsessions	listAdmin	pt-br	Total de Sessões
+View User	listAdmin	pt-br	Exibir Usuários
+Total Sessions	listAdmin	pt-br	Total de Sessões
+totalsessions	listAdmin	pt-br	Total de Sessões
+Sector	listAdmin	pt-br	Setor
+Phone	listAdmin	pt-br	Telefone
+Photo	listAdmin	pt-br	Foto
+Maillist login	listAdmin	pt-br	Login da Lista de Email
+Maillist Mail	listAdmin	pt-br	E-Mail da Lista de Email
+Maillist name	listAdmin	pt-br	Nome da Lista de Email
+Maillist users	listAdmin	pt-br	Usuários da Lista de Email
+Create Email List	listAdmin	pt-br	Criar Lista de Email
+Create Group	listAdmin	pt-br	Criar Grupo de Usuários
+Edit Group	listAdmin	pt-br	Editar Grupo de Usuários
+Edit Email Lists	listAdmin	pt-br	Editar Lista de Email
+Manager name	listAdmin	pt-br	Nome do Gerente
+Rename users	listAdmin	pt-br	Renomear usuários
+Change users quote	listAdmin	pt-br	Alterar  cota dos usuários
+Set default users password	listAdmin	pt-br	Setar senha padrão
+Create Organizations	listAdmin	pt-br	Criar organizações
+Edit Organizations	listAdmin	pt-br	Editar organizações
+Delete Organizations	listAdmin	pt-br	Deletar organizações
+Select users from all sub-organizations	listAdmin	pt-br	Selecionar usuários de todas as sub-organizações
+scl	listAdmin	pt-br	scl
+Show users from all sub-organizations	listAdmin	pt-br	Exibir usuários de todas as sub-organizações
+Edit Sending Control List	listAdmin	pt-br	Editar Lista de Controle de Envio
+Samba Domains	listAdmin	pt-br	Dominios Samba
+Samba domains name	listAdmin	pt-br	Nome dos domínios Samba
+Samba domain name	listAdmin	pt-br	Nome do domínio Samba
+Samba domain SID	listAdmin	pt-br	SID do domínio Samba
+sambaSID	listAdmin	pt-br	sambaSID
+Add Samba Domains	listAdmin	pt-br	Criar domínios Samba
+Add Samba Domain	listAdmin	pt-br	Criar domínio Samba
+Samba domains name is empty	listAdmin	pt-br	O nome do domínio samba está vazio
+Samba SID is empty	listAdmin	pt-br	O SID do domínio samba está vazio
+Samba domain name or SID already exist	listAdmin	pt-br	O nome do domínio samba ou sambaSID já existe
+Use samba attributes	listAdmin	pt-br	Usar atributos samba
+Occult Sector	listAdmin	pt-br	Ocultar setor
+Edit email attribute from the groups	listAdmin	pt-br	Editar campo e-mail do grupo
+Adm	listAdmin	pt_br	Adm
+scl	listAdmin	pt_br	Scl
+maillist adm	listAdmin	pt_br	Gerentes da Lista
+admin lists	listAdmin	pt_br	Editar Gerentes de Listas
+adm email lists	listAdmin	pt_br	Administrar Listas de Email
+Maillist description	listAdmin	pt-br	Descrição da Lista de Email
+Search argument too short	listAdmin	pt-br	Argumento de busca muito pequeno. Mínimo 4 caracteres.
Index: /branches/2.2/listAdmin/setup/tables_current.inc.php
===================================================================
--- /branches/2.2/listAdmin/setup/tables_current.inc.php	(revision 3514)
+++ /branches/2.2/listAdmin/setup/tables_current.inc.php	(revision 3514)
@@ -0,0 +1,35 @@
+<?php
+	/*******************************************************************************\
+	*  This program is free software; you can redistribute it and/or modify it	*
+	*  under the terms of the GNU General Public License as published by the	*
+	*  Free Software Foundation; either version 2 of the License, or (at your	*
+	*  option) any later version.							*
+	\*******************************************************************************/
+
+	$phpgw_baseline = array(
+		'phpgw_expressoadmin' => array(
+			'fd' => array(
+				'manager_lid'	=> array('type' => 'varchar','precision' => 50,'nullable' => false),
+				'context'		=> array('type' => 'varchar','precision' => 255,'nullable' => false),
+				'acl'			=> array('type' => 'int','precision' => 8,'nullable' => false)
+			),
+			'pk' => array(),
+			'fk' => array(),
+			'ix' => array(),
+			'uc' => array()
+		),
+		
+		'phpgw_expressoadmin_apps' => array(
+			'fd' => array(
+				'manager_lid'	=> array('type' => 'varchar','precision' => 50,'nullable' => false),
+				'context'		=> array('type' => 'varchar','precision' => 255,'nullable' => false),
+				'app'			=> array('type' => 'varchar','precision' => 100,'nullable' => false)
+			),
+			'pk' => array(),
+			'fk' => array(),
+			'ix' => array(),
+			'uc' => array()
+		),
+
+	);
+?>
Index: /branches/2.2/listAdmin/setup/tables_update.inc.php
===================================================================
--- /branches/2.2/listAdmin/setup/tables_update.inc.php	(revision 3514)
+++ /branches/2.2/listAdmin/setup/tables_update.inc.php	(revision 3514)
@@ -0,0 +1,18 @@
+<?php
+	/**************************************************************************\
+	* phpGroupWare - Setup                                                     *
+	* http://www.phpgroupware.org                                              *
+	* --------------------------------------------                             *
+	* This program is free software; you can redistribute it and/or modify it  *
+	* under the terms of the GNU General Public License as published by the    *
+	* Free Software Foundation; either version 2 of the License, or (at your   *
+	* option) any later version.                                               *
+	\**************************************************************************/	
+	$test[] = '1.0.0';
+	function listAdmin_upgrade1_0_0()
+	{
+		
+		$GLOBALS['setup_info']['listAdmin']['currentver'] = '2.0.0';
+		return $GLOBALS['setup_info']['listAdmin']['currentver'];
+	}
+?>
Index: /branches/2.2/listAdmin/setup/setup.inc.php
===================================================================
--- /branches/2.2/listAdmin/setup/setup.inc.php	(revision 3514)
+++ /branches/2.2/listAdmin/setup/setup.inc.php	(revision 3514)
@@ -0,0 +1,33 @@
+<?php
+	/***********************************************************************************\
+	*  This program is free software; you can redistribute it and/or modify it		   *
+	*  under the terms of the GNU General Public License as published by the		   *
+	*  Free Software Foundation; either version 2 of the License, or (at your		   *
+	*  option) any later version.													   *
+	\***********************************************************************************/
+
+	$setup_info['listAdmin']['name'] = 'listAdmin';
+	$setup_info['listAdmin']['version'] = '2.0.0';
+	$setup_info['listAdmin']['app_order'] = 10;
+	$setup_info['listAdmin']['enable'] = 1;
+
+	$setup_info['listAdmin']['author'] = 'Rommel de Brito Cysne (rommel.cysne@serpro.gov.br)';
+	$setup_info['listAdmin']['license']  = 'GPL';
+	$setup_info['listAdmin']['description'] = 'Interface de administracao de listas de e-mail do Mailman.';
+	$setup_info['listAdmin']['note'] = '';
+	$setup_info['listAdmin']['maintainer'] = array(
+		'name'  => 'Rommel Cysne',
+		'email' => 'rommel.cysne@serpro.gov.br'
+	);
+
+
+	/* The hooks this app includes, needed for hooks registration */
+	$setup_info['listAdmin']['hooks'][] = 'admin';
+
+
+	/* Dependencies for this app to work */
+	$setup_info['listAdmin']['depends'][] = array(
+		'appname' => 'phpgwapi',
+		'versions' => Array('2.0','2.1')
+	);
+?>
Index: /branches/2.2/listAdmin/docs/manageheader.tpl
===================================================================
--- /branches/2.2/listAdmin/docs/manageheader.tpl	(revision 3514)
+++ /branches/2.2/listAdmin/docs/manageheader.tpl	(revision 3514)
@@ -0,0 +1,245 @@
+<!-- BEGIN manageheader -->
+
+<script language="JavaScript" type="text/javascript">
+<!--
+  {js_default_db_ports}
+  function setDefaultDBPort(selectBox,portField)
+  {
+	//alert("select: " + selectBox + "; portField: " + portField);
+    if(selectBox.selectedIndex != -1 && selectBox.options[selectBox.selectedIndex].value)
+	{
+		//alert("value = " + selectBox.options[selectBox.selectedIndex].value);
+		portField.value = default_db_ports[selectBox.options[selectBox.selectedIndex].value];
+	}
+    return false;
+  }
+
+/***** INICIO BLOCO MAILMAN *****/
+
+	function ocultar(zdiv)
+	{
+		var xdiv = document.getElementById(zdiv);
+		if(xdiv.id == "certificado") {
+			xdiv.style.display='none';
+			var xdiv = document.getElementById('cert_0');
+			xdiv.checked = true;
+		}
+		if(xdiv.id == "conf_mailman") {
+			xdiv.style.display='none';
+			document.getElementById('use_mail_0').checked = true;
+		}
+		if(xdiv.id == "badlogin") {
+			xdiv.style.display='none';
+			var xdiv = document.getElementById('badlogintxt');
+			xdiv.value='0';
+		}
+	}
+
+	function exibir(zdiv)
+	{
+		var xdiv = document.getElementById(zdiv);
+		xdiv.style.display='';
+	}
+
+/***** FIM BLOCO MAILMAN *****/
+
+//-->
+</script>
+
+<table border="0" width="90%" cellspacing="0" cellpadding="0" align="center">
+<tbody><tr><td>
+
+{detected}
+
+	<tr class="th">
+    <th colspan="2">{lang_settings}</th>
+  </tr>
+   <form name="domain_settings" action="manageheader.php" method="post">
+    <input type="hidden" name="setting[write_config]" value="true">
+  <tr>
+    <td colspan="2"><b>{lang_serverroot}</b>
+      <br><input type="text" name="setting[server_root]" size="80" value="{server_root}">
+    </td>
+  </tr>
+  <tr>
+    <td colspan="2"><b>{lang_includeroot}</b><br><input type="text" name="setting[include_root]" size="80" value="{include_root}"></td>
+  </tr>
+  <tr>
+    <td colspan="2"><b>{lang_adminuser}</b><br><input type="text" name="setting[HEADER_ADMIN_USER]" size="30" value="{header_admin_user}"></td>
+  </tr>
+  <tr>
+    <td colspan="2"><b>{lang_adminpass}</b><br><input type="password" name="setting[HEADER_ADMIN_PASSWORD]" size="30" value="{header_admin_password}"><input type="hidden" name="setting[HEADER_ADMIN_PASS]" value="{header_admin_pass}"></td>
+  </tr>
+  <tr>
+    <td colspan="2"><b>{lang_setup_acl}</b><br><input type="text" name="setting[setup_acl]" size="30" value="{setup_acl}"></td>
+  </tr>
+  <tr>
+    <td><b>{lang_persist}</b><br>
+      <select type="checkbox" name="setting[db_persistent]">
+        <option value="True"{db_persistent_yes}>{lang_Yes}</option>
+        <option value="False"{db_persistent_no}>{lang_No}</option>
+      </select>
+    </td>
+    <td>{lang_persistdescr}</td>
+  </tr>
+  <tr>
+    <td><b>{lang_sesstype}</b><br>
+      <select name="setting[sessions_type]">
+{session_options}
+      </select>
+    </td>
+    <td>{lang_sesstypedescr}</td>
+  </tr>
+  <tr>
+    <td><b>{lang_enablemcrypt}</b><br>
+      <select name="setting[enable_mcrypt]">
+        <option value="True"{mcrypt_enabled_yes}>{lang_Yes}</option>
+        <option value="False"{mcrypt_enabled_no}>{lang_No}</option>
+      </select>
+    </td>
+    <td>{lang_mcrypt_warning}</td>
+  </tr>
+  <tr>
+    <td><b>{lang_mcryptversion}</b><br><input type="text" name="setting[mcrypt_version]" value="{mcrypt}"></td>
+    <td>{lang_mcryptversiondescr}</td>
+  </tr>
+  <tr>
+    <td><b>{lang_mcryptiv}</b><br><input type="text" name="setting[mcrypt_iv]" value="{mcrypt_iv}" size="30"></td>
+    <td>{lang_mcryptivdescr}</td>
+  </tr>
+  <tr>
+    <td><b>{lang_domselect}</b><br>
+      <select name="setting[domain_selectbox]">
+        <option value="True"{domain_selectbox_yes}>{lang_Yes}</option>
+        <option value="False"{domain_selectbox_no}>{lang_No}</option>
+      </select></td><td>&nbsp;
+    </td>
+  </tr>
+{domains}{comment_l}
+  <tr class="th">
+    <td colspan="2"><input type="submit" name="adddomain" value="{lang_adddomain}"></td>
+  </tr>{comment_r}
+  
+	<!-- INICIO configurações exclusivas para o ExpressoLivre -->
+	<tr><td><br></td></tr>
+	<th colspan="2" class="th">ExpressoLivre</th>
+	
+	<tr><td colspan="2"><b>Usar HTTPS?</b></td></tr>
+  	<tr><td colspan="2">
+	  	<font color='red'>Obs.: Apenas use https no site, caso o apache esteja configurado para isto. A porta 443 DEVE estar acessível.</font><br>
+		<INPUT type="radio"{use_https_0} name="setting[use_https]" value="0">NÃO Usar HTTPS no site.<BR>
+		<INPUT type="radio"{use_https_1} name="setting[use_https]" value="1">Usar HTTPS apenas no Login.<BR>
+		<INPUT type="radio"{use_https_2} name="setting[use_https]" value="2">Usar HTTPS no Site inteiro.<BR>	
+  	</td></tr>
+
+<!-- INICIO BLOCO MAILMAN -->
+
+	<tr><td colspan="2">
+	<fieldset><legend>Mailman</legend>
+	<table>
+		<tr><td colspan="2"><b>Usar Mailman?</b></td></tr>
+		<tr><td colspan="2">
+			<INPUT id="use_mail_0" type="radio" {use_mailman_0} name="setting[use_mailman]" value="0" onclick="javascript:ocultar('conf_mailman')" />NAO usar listas no Mailman.<BR>
+			<INPUT id="use_mail_1" type="radio" {use_mailman_1} name="setting[use_mailman]" value="1" onclick="javascript:exibir('conf_mailman')" />Usar listas no Mailman.<BR>
+		</td></tr>
+	</table>
+	<table id="conf_mailman" {div_mailman} >
+		<tr><td colspan="2"><b>Digite o DN usado pelas listas. (Ex.: ou=listas,dc=company,dc=com,dc=br)</b></td></tr>
+		<tr><td colspan="2">
+			<INPUT size="50" name="setting[dn_listas]" value="{dn_listas}" />
+		</td></tr>
+		<tr><td colspan="2"><b>Digite o dominio usado pelas listas. (Ex.: dominio.com.br)</b></td></tr>
+		<tr><td colspan="2">
+			<INPUT size="50" name="setting[dominio_listas]" value="{dominio_listas}" />
+		</td></tr>
+		<tr><td colspan="2"><b>Digite a porta utilizada pelo Mailman. (Ex: 80)</b></td></tr>
+		<tr><td colspan="2">
+			<INPUT size="50" name="setting[porta_mailman]" value="{porta_mailman}" onkeypress="return soNumero(this, event);"/>
+		</td></tr>
+		<tr><td colspan="2"><b>Digite o endereco IP do servidor Mailman. (Ex.: 192.168.0.1)</b></td></tr>
+		<tr><td colspan="2">
+			<INPUT size="50" name="setting[host_mailman]" value="{host_mailman}" />
+		</td></tr>
+		<tr><td colspan="2"><b>Digite o caminho do programa de sincronizacao do Mailman.</b></td></tr>
+		<tr><td colspan="2">
+			<INPUT size="50" name="setting[url_mailman]" value="{url_mailman}" />
+		</td></tr>
+	</table>
+
+<!-- FIM BLOCO MAILMAN -->
+
+	<tr><td colspan="2"><b>Digite os endereços de emails, separados por vírgula, que devem receber as sugestões enviados pelos usuários.</b></td></tr>
+	<tr><td colspan="2"><INPUT size="50" name="setting[sugestoes_email_to]" value="{sugestoes_email_to}"></td></tr>
+	
+	<tr><td colspan="2"><b>Digite parte do seu domínio. Esta parte de domínio será concatenado a organização do usuário para formar o domínio do usuário. Ex.: usuario@organizacao.dominio -> joao@celepar.pr.gov.br, o pr.gov.br é a parte do domínio.</b></td></tr>
+	<tr><td colspan="2"><INPUT size="50" name="setting[domain_name]" value="{domain_name}"></td></tr>
+	
+	<th colspan="2" class="th">&nbsp;</th>
+  	<!-- FIM configurações exclusivas para o ExpressoLivre -->
+
+  <tr>
+    <td colspan="2">{errors}</td>
+  </tr>
+{formend}
+  <tr>
+    <td colspan="3">
+ <form action="index.php" method="post">
+  <br>{lang_finaldescr}<br>
+  <input type="hidden" name="FormLogout"  value="header">
+  <input type="hidden" name="ConfigLogin" value="Login">
+  <input type="hidden" name="FormUser"    value="{FormUser}">
+  <input type="hidden" name="FormPW"      value="{FormPW}">
+  <input type="hidden" name="FormDomain"  value="{FormDomain}">
+  <input type="submit" name="junk"        value="{lang_continue}">
+ </form>
+    </td>
+  </tr>
+  <tr class="banner">
+    <td colspan="3">&nbsp;</td>
+  </tr>
+</table>
+</body>
+</html>
+<!-- END manageheader -->
+
+<!-- BEGIN domain -->
+  <tr class="th">
+    <td>{lang_domain}:</td>&nbsp;<td><input name="domains[{db_domain}]" value="{db_domain}">&nbsp;&nbsp;<input type="checkbox" name="deletedomain[{db_domain}]">&nbsp;<font color="fefefe">{lang_delete}</font></td>
+  </tr>
+  <tr>
+    <td><b>{lang_dbtype}</b><br>
+      <select name="setting_{db_domain}[db_type]" onchange="setDefaultDBPort(this,this.form['setting_{db_domain}[db_port]']);">
+{dbtype_options}
+      </select>
+    </td>
+    <td>{lang_whichdb}</td>
+  </tr>
+  <tr>
+    <td><b>{lang_dbhost}</b><br><input type="text" name="setting_{db_domain}[db_host]" value="{db_host}"></td><td>{lang_dbhostdescr}</td>
+  </tr>
+  <tr>
+  <tr>
+    <td><b>{lang_dbport}</b><br><input type="text" name="setting_{db_domain}[db_port]" value="{db_port}"></td><td>{lang_dbportdescr}</td>
+  </tr>
+  <tr>
+    <td><b>{lang_dbname}</b><br><input type="text" name="setting_{db_domain}[db_name]" value="{db_name}"></td><td>{lang_dbnamedescr}</td>
+  </tr>
+  <tr>
+    <td><b>{lang_dbuser}</b><br><input type="text" name="setting_{db_domain}[db_user]" value="{db_user}"></td><td>{lang_dbuserdescr}</td>
+  </tr>
+  <tr>
+    <td><b>{lang_dbpass}</b><br><input type="password" name="setting_{db_domain}[db_pass]" value="{db_pass}"></td><td>{lang_dbpassdescr}</td>
+  </tr>
+  <tr>
+    <td><b>{lang_configuser}</b><br><input type="text" name="setting_{db_domain}[config_user]" value="{config_user}"></td>
+  </tr>
+  <tr>
+    <td><b>{lang_configpass}</b><br><input type="password" name="setting_{db_domain}[config_pass]" value="{config_pass}"><input type="hidden" name="setting_{db_domain}[config_password]" value="{config_password}"></td>
+    <td>{lang_passforconfig}</td>
+  </tr>
+<!-- END domain -->
+
+</td></tr>
+</tbody>
+
+</table>
Index: /branches/2.2/listAdmin/docs/header.inc.php.template
===================================================================
--- /branches/2.2/listAdmin/docs/header.inc.php.template	(revision 3514)
+++ /branches/2.2/listAdmin/docs/header.inc.php.template	(revision 3514)
@@ -0,0 +1,148 @@
+<?php
+	/**************************************************************************\
+	* eGroupWare                                                               *
+	* http://www.egroupware.org                                                *
+	* This file was originaly written by Dan Kuykendall                        *
+	* --------------------------------------------                             *
+	*  This program is free software; you can redistribute it and/or modify it *
+	*  under the terms of the GNU General Public License as published by the   *
+	*  Free Software Foundation; either version 2 of the License, or (at your  *
+	*  option) any later version.                                              *
+	\**************************************************************************/
+	/* $Id: header.inc.php.template,v 1.55.2.1 2004/08/03 14:05:35 reinerj Exp $ */
+
+	/**************************************************************************\
+	* !!!!!!! EDIT THESE LINES !!!!!!!!                                        *
+	* This setting allows you to easily move the include directory and the     *
+	* base of the eGroupWare install. Simple edit the following 2 lines with   *
+	* the absolute path to fit your site, and you should be up and running.    *
+	\**************************************************************************/
+
+	define('PHPGW_SERVER_ROOT','{SERVER_ROOT}');
+	define('PHPGW_INCLUDE_ROOT','{INCLUDE_ROOT}');
+	$GLOBALS['phpgw_info']['server']['header_admin_user'] = '{HEADER_ADMIN_USER}';
+	$GLOBALS['phpgw_info']['server']['header_admin_password'] = '{HEADER_ADMIN_PASSWORD}';
+	$GLOBALS['phpgw_info']['server']['setup_acl'] = '{SETUP_ACL}';
+
+	// Opcoes exlusivas para o Expresso Livre
+	$GLOBALS['phpgw_info']['server']['use_https'] = {USE_HTTPS};
+	$GLOBALS['phpgw_info']['server']['sugestoes_email_to'] = '{SUGESTOES_EMAIL_TO}';
+	$GLOBALS['phpgw_info']['server']['domain_name'] = '{DOMAIN_NAME}';
+	$GLOBALS['phpgw_info']['server']['use_prefix_organization'] = {USE_PREFIX_ORGANIZATION};
+
+/********** INICIO BLOCO MAILMAN ************/
+
+	// Opcoes usadas com servidor de listas Mailman
+	$GLOBALS['phpgw_info']['server']['use_mailman'] = '{USE_MAILMAN}';
+	$GLOBALS['phpgw_info']['server']['dn_listas'] = '{DN_LISTAS}';
+	$GLOBALS['phpgw_info']['server']['dominio_listas'] = '{DOMINIO_LISTAS}';
+	$GLOBALS['phpgw_info']['server']['porta_mailman'] = '{PORTA_MAILMAN}';
+	$GLOBALS['phpgw_info']['server']['host_mailman'] = '{HOST_MAILMAN}';
+	$GLOBALS['phpgw_info']['server']['url_mailman'] = '{URL_MAILMAN}';
+
+/********** FIM BLOCO MAILMAN ***************/
+
+	// If you want to identify your App Server (recommended for multiple servers):
+	//$GLOBALS['phpgw_info']['server']['use_frontend_id']   = 1024;
+	//$GLOBALS['phpgw_info']['server']['use_frontend_name'] = '01';
+			
+	/* eGroupWare domain-specific db settings */{domains}
+	/*
+	** If you want to have your domains in a select box, change to True
+	** If not, users will have to login as user@domain
+	** Note: This is only for virtual domain support, default domain users can login only using
+	** there loginid.
+	*/
+	$GLOBALS['phpgw_info']['server']['show_domain_selectbox'] = {DOMAIN_SELECTBOX};
+
+	$GLOBALS['phpgw_info']['server']['db_persistent'] = {DB_PERSISTENT};
+
+	/*
+	** eGroupWare can handle session management using the database or 
+	** the session support built into PHP4 which usually gives better
+	** performance. 
+	** Your choices are 'db' or 'php4'
+	*/
+	$GLOBALS['phpgw_info']['server']['sessions_type'] = '{SESSIONS_TYPE}';
+
+	/* Select which login template set you want, most people will use default */
+	$GLOBALS['phpgw_info']['login_template_set'] = 'celepar';
+
+	/* This is used to control mcrypt's use */
+	$GLOBALS['phpgw_info']['server']['mcrypt_enabled'] = {ENABLE_MCRYPT};
+	/* Set this to 'old' for versions < 2.4, otherwise the exact mcrypt version you use. */
+	$GLOBALS['phpgw_info']['server']['versions']['mcrypt'] = '{MCRYPT_VERSION}';
+
+	/*
+	** This is a random string used as the initialization vector for mcrypt
+	** feel free to change it when setting up eGrouWare on a clean database,
+	** but you must not change it after that point!
+	** It should be around 30 bytes in length.
+	*/
+	$GLOBALS['phpgw_info']['server']['mcrypt_iv'] = '{MCRYPT_IV}';
+
+	if(!isset($GLOBALS['phpgw_info']['flags']['nocachecontrol']) || !$GLOBALS['phpgw_info']['flags']['nocachecontrol'])
+	{
+		header('Cache-Control: no-cache, must-revalidate');  // HTTP/1.1
+		header('Pragma: no-cache');                          // HTTP/1.0
+	}
+	else
+	{
+		// allow caching by browser
+		session_cache_limiter(PHP_VERSION >= 4.2 ? 'private_no_expire' : 'private');
+	}
+
+	/* debugging settings */
+	define('DEBUG_APP',  False);
+	define('DEBUG_API',  False);
+	define('DEBUG_DATATYPES',  True);
+	define('DEBUG_LEVEL',  3);
+	define('DEBUG_OUTPUT', 2); /* 1 = screen,  2 = DB. For both use 3. */
+	define('DEBUG_TIMER', False);
+
+	function perfgetmicrotime()
+	{
+		list($usec, $sec) = explode(' ',microtime());
+		return ((float)$usec + (float)$sec);
+	}
+
+	if (DEBUG_TIMER)
+	{
+		$GLOBALS['debug_timer_start'] = perfgetmicrotime();
+	}
+
+	/**************************************************************************\
+	* Do not edit these lines                                                  *
+	\**************************************************************************/
+	define('PHPGW_API_INC',PHPGW_INCLUDE_ROOT.'/phpgwapi/inc');
+	include(PHPGW_SERVER_ROOT.'/phpgwapi/setup/setup.inc.php');
+	$GLOBALS['phpgw_info']['server']['versions']['phpgwapi'] = $setup_info['phpgwapi']['version'];
+	$GLOBALS['phpgw_info']['server']['versions']['current_header'] = $setup_info['phpgwapi']['versions']['current_header'];
+	unset($setup_info);
+	$GLOBALS['phpgw_info']['server']['versions']['header'] = '1.27';
+	/* This is a fix for NT */
+	if(!isset($GLOBALS['phpgw_info']['flags']['noapi']) || !$GLOBALS['phpgw_info']['flags']['noapi'] == True)
+	{
+		include(PHPGW_API_INC . '/functions.inc.php');
+		include(PHPGW_API_INC . '/xml_functions.inc.php');
+		include(PHPGW_API_INC . '/soap_functions.inc.php');
+	}
+
+	/*
+	  Leave off the final php closing tag, some editors will add
+	  a \n or space after which will mess up cookies later on
+	*/<!-- BEGIN domain -->
+	$GLOBALS['phpgw_domain']['{DB_DOMAIN}'] = array(
+		'db_host' => '{DB_HOST}',
+		'db_port' => '{DB_PORT}',
+		'db_name' => '{DB_NAME}',
+		'db_user' => '{DB_USER}',
+		'db_pass' => '{DB_PASS}',
+		// Look at the README file
+		'db_type' => '{DB_TYPE}',
+		// This will limit who is allowed to make configuration modifications
+		'config_user'   => '{CONFIG_USER}',
+		'config_passwd' => '{CONFIG_PASS}'
+	);
+
+<!-- END domain -->
Index: /branches/2.2/listAdmin/docs/manageheader.php
===================================================================
--- /branches/2.2/listAdmin/docs/manageheader.php	(revision 3514)
+++ /branches/2.2/listAdmin/docs/manageheader.php	(revision 3514)
@@ -0,0 +1,738 @@
+<?php
+  /**************************************************************************\
+  * eGroupWare                                                               *
+  * http://www.egroupware.org                                                *
+  * --------------------------------------------                             *
+  *  This program is free software; you can redistribute it and/or modify it *
+  *  under the terms of the GNU General Public License as published by the   *
+  *  Free Software Foundation; either version 2 of the License, or (at your  *
+  *  option) any later version.                                              *
+  \**************************************************************************/
+
+
+	$phpgw_info = array();
+	$GLOBALS['phpgw_info']['flags'] = array(
+		'nocachecontrol' => True,
+		'noheader' => True,
+		'nonavbar' => True,
+		'currentapp' => 'home',
+		'noapi' => True
+	);
+	include('./inc/functions.inc.php');
+
+	$GLOBALS['phpgw_info']['server']['versions']['current_header'] = $setup_info['phpgwapi']['versions']['current_header'];
+	$GLOBALS['phpgw_info']['server']['versions']['phpgwapi'] = $setup_info['phpgwapi']['version'];
+	unset($setup_info);
+
+	/* Fetch the current real path.
+	 * If this is in the server document root, then it is probably ok.
+	 * Otherwise, don't guess, just show the usual instructive default.
+	 */
+	$realpath = realpath('..');
+	if(!ereg('^' . $_SERVER['DOCUMENT_ROOT'],$realpath))
+	{
+		if(PHP_OS == 'Windows')
+		{
+			$realpath = 'Drive:\\\\Path';
+		}
+		else
+		{
+			$realpath = '/path/to/egroupware';
+		}
+	}
+
+	$adddomain = get_var('adddomain',Array('POST'));
+
+	$db_fullnames = array(
+		'pgsql'  => 'PostgreSQL',
+		'mysql'  => 'MySQL',
+		'mssql'  => 'MS SQL Server',
+		'oracle' => 'Oracle'
+	);
+
+	$default_db_ports = array(
+		'pgsql'  => 5432,
+		'mysql'  => 3306,
+		'mssql'  => 1433,
+		'oracle' => 1521
+	);
+
+	function check_form_values()
+	{
+		// PHP will automatically replace any dots in incoming
+		// variable names with underscores.
+
+		$errors = '';
+		$domains = get_var('domains',Array('POST'));
+		@reset($domains);
+		while(list($k,$v) = @each($domains))
+		{
+			$variableName = str_replace('.','_',$k);
+			$deletedomain = get_var('deletedomain',Array('POST'));
+			if(isset($deletedomain[$variableName]))
+			{
+				continue;
+			}
+			$dom = get_var('setting_'.$variableName,Array('POST'));
+			if(!$dom['config_pass'] && !$dom['config_password'])
+			{
+				$errors .= '<br>' . lang("You didn't enter a config password for domain %1",$v);
+			}
+			if(!$dom['config_user'])
+			{
+				$errors .= '<br>' . lang("You didn't enter a config username for domain %1",$v);
+			}
+		}
+
+		$setting = get_var('setting',Array('POST'));
+		
+		if(!$setting['HEADER_ADMIN_PASSWORD'] && !$setting['HEADER_ADMIN_PASS'])
+		{
+			$errors .= '<br>' . lang("You didn't enter a header admin password");
+		}
+		if(!$setting['HEADER_ADMIN_USER'])
+		{
+			$errors .= '<br>' . lang("You didn't enter a header admin username");
+		}
+
+		if($errors)
+		{
+			$GLOBALS['phpgw_setup']->html->show_header('Error',True);
+			echo $errors;
+			echo '<p><input type="submit" value="'.lang('Back to the previous screen').'" onClick="history.back()"></p>';
+			exit;
+		}
+	}
+
+	/* authentication phase */
+	$GLOBALS['phpgw_info']['setup']['stage']['header'] = $GLOBALS['phpgw_setup']->detection->check_header();
+
+	// added these to let the app work, need to templatize still
+	$tpl_root = $GLOBALS['phpgw_setup']->html->setup_tpl_dir('setup');
+	$setup_tpl = CreateObject('setup.Template',$tpl_root);
+	$setup_tpl->set_file(array(
+		'T_head' => 'head.tpl',
+		'T_footer' => 'footer.tpl',
+		'T_alert_msg' => 'msg_alert_msg.tpl',
+		'T_login_main' => 'login_main.tpl',
+		'T_login_stage_header' => 'login_stage_header.tpl',
+		'T_setup_manage' => 'manageheader.tpl'
+	));
+	$setup_tpl->set_block('T_login_stage_header','B_multi_domain','V_multi_domain');
+	$setup_tpl->set_block('T_login_stage_header','B_single_domain','V_single_domain');
+	$setup_tpl->set_block('T_setup_manage','manageheader','manageheader');
+	$setup_tpl->set_block('T_setup_manage','domain','domain');
+
+	/* Detect current mode */
+	switch($GLOBALS['phpgw_info']['setup']['stage']['header'])
+	{
+		case '1':
+			$GLOBALS['phpgw_info']['setup']['HeaderFormMSG'] = lang('Create your header.inc.php');
+			$GLOBALS['phpgw_info']['setup']['PageMSG'] = lang('You have not created your header.inc.php yet!<br> You can create it now.');
+			break;
+		case '2':
+			$GLOBALS['phpgw_info']['setup']['HeaderFormMSG'] = lang('Your header admin password is NOT set. Please set it now!');
+			$GLOBALS['phpgw_info']['setup']['PageMSG'] = lang('Your header admin password is NOT set. Please set it now!');
+			break;
+		case '3':
+			$GLOBALS['phpgw_info']['setup']['HeaderFormMSG'] = lang('You need to add some domains to your header.inc.php.');
+			$GLOBALS['phpgw_info']['setup']['PageMSG'] = lang('You need to add some domains to your header.inc.php.');
+			$GLOBALS['phpgw_info']['setup']['HeaderLoginMSG'] = lang('You need to add some domains to your header.inc.php.');
+			if(!$GLOBALS['phpgw_setup']->auth('Header'))
+			{
+				$GLOBALS['phpgw_setup']->html->show_header('Please login',True);
+				$GLOBALS['phpgw_setup']->html->login_form();
+				$GLOBALS['phpgw_setup']->html->show_footer();
+				exit;
+			}
+			break;
+		case '4':
+			$GLOBALS['phpgw_info']['setup']['HeaderFormMSG'] = lang('Your header.inc.php needs upgrading.');
+			$GLOBALS['phpgw_info']['setup']['PageMSG'] = lang('Your header.inc.php needs upgrading.<br><blink><b class="msg">WARNING!</b></blink><br><b>MAKE BACKUPS!</b>');
+			$GLOBALS['phpgw_info']['setup']['HeaderLoginMSG'] = lang('Your header.inc.php needs upgrading.');
+			if(!$GLOBALS['phpgw_setup']->auth('Header'))
+			{
+				$GLOBALS['phpgw_setup']->html->show_header('Please login',True);
+				$GLOBALS['phpgw_setup']->html->login_form();
+				$GLOBALS['phpgw_setup']->html->show_footer();
+				exit;
+			}
+			break;
+		case '10':
+			if(!$GLOBALS['phpgw_setup']->auth('Header'))
+			{
+				$GLOBALS['phpgw_setup']->html->show_header('Please login',True);
+				$GLOBALS['phpgw_setup']->html->login_form();
+				$GLOBALS['phpgw_setup']->html->show_footer();
+				exit;
+			}
+			$GLOBALS['phpgw_info']['setup']['HeaderFormMSG'] = lang('Edit your header.inc.php');
+			$GLOBALS['phpgw_info']['setup']['PageMSG'] = lang('Edit your existing header.inc.php');
+			break;
+	}
+
+	$action = @get_var('action',Array('POST'));
+	list($action) = @each($action);
+	switch($action)
+	{
+		case 'download':
+			check_form_values();
+			$header_template = CreateObject('setup.Template','../');
+			$b = CreateObject('phpgwapi.browser');
+			$b->content_header('header.inc.php','application/octet-stream');
+			/*
+			header('Content-disposition: attachment; filename="header.inc.php"');
+			header('Content-type: application/octet-stream');
+			header('Pragma: no-cache');
+			header('Expires: 0');
+			*/
+			$newheader = $GLOBALS['phpgw_setup']->html->generate_header();
+			echo $newheader;
+			break;
+		case 'view':
+			check_form_values();
+			$header_template = CreateObject('setup.Template','../');
+			$GLOBALS['phpgw_setup']->html->show_header('Generated header.inc.php', False, 'header');
+			echo '<table width="90%"><tr><td>';
+			echo '<br>' . lang('Save this text as contents of your header.inc.php') . '<br><hr>';
+			$newheader = $GLOBALS['phpgw_setup']->html->generate_header();
+			echo '<pre>';
+			echo htmlentities($newheader);
+			echo '</pre><hr>';
+			echo '<form action="index.php" method="post">';
+			echo '<br>' . lang('After retrieving the file, put it into place as the header.inc.php.  Then, click "continue".') . '<br>';
+			echo '<input type="hidden" name="FormLogout" value="header">';
+			echo '<input type="submit" name="junk" value="'.lang('Continue').'">';
+			echo '</form>';
+			echo '</td></tr></table>';
+			$GLOBALS['phpgw_setup']->html->show_footer();
+			break;
+		case 'write':
+			check_form_values();
+			$header_template = CreateObject('setup.Template','../');
+			if(is_writeable('../header.inc.php') || (!file_exists('../header.inc.php') && is_writeable('../')))
+			{
+				$newheader = $GLOBALS['phpgw_setup']->html->generate_header();
+				$fsetup = fopen('../header.inc.php','wb');
+				fwrite($fsetup,$newheader);
+				fclose($fsetup);
+				$GLOBALS['phpgw_setup']->html->show_header('Saved header.inc.php', False, 'header');
+				echo '<form action="index.php" method="post">';
+ 				echo '<br>' . lang('Created header.inc.php!');
+				echo '<input type="hidden" name="FormLogout" value="header">';
+				echo '<input type="submit" name="junk" value="'.lang('Continue').'">';
+				echo '</form>';
+				echo '</body></html>';
+				break;
+			}
+			else
+			{
+				$GLOBALS['phpgw_setup']->html->show_header('Error generating header.inc.php', False, 'header');
+				echo lang('Could not open header.inc.php for writing!') . '<br>' . "\n";
+				echo lang('Please check read/write permissions on directories, or back up and use another option.') . '<br>';
+				echo '</td></tr></table></body></html>';
+			}
+			break;
+		default:
+			$GLOBALS['phpgw_setup']->html->show_header($GLOBALS['phpgw_info']['setup']['HeaderFormMSG'], False, 'header');
+			
+			$detected = '';
+
+			if(!get_var('ConfigLang',array('POST','COOKIE')))
+			{
+				$detected .= '<br><form action="manageheader.php" method="Post">Please Select your language '.lang_select(True,'en')."</form>\n";
+			}
+
+			$detected .= '<table border="0" width="100%" cellspacing="0" cellpadding="0">' . "\n";
+
+			$detected .= '<tr><td colspan="2"><p>' . $GLOBALS['phpgw_info']['setup']['PageMSG'] . '<br />&nbsp;</p></td></tr>';
+			
+			$detected .= '<tr class="th"><td colspan="2">' . lang('Analysis') . '</td></tr><tr><td colspan="2">'. "\n";
+
+			$supported_db = array();
+			if(extension_loaded('pgsql') || function_exists('pg_connect'))
+			{
+				$detected .= lang('You appear to have PostgreSQL support enabled') . '<br>' . "\n";
+				$supported_db[]  = 'pgsql';
+			}
+			else
+			{
+				$detected .= lang('No PostgreSQL support found. Disabling') . '<br>' . "\n";
+			}
+			if(extension_loaded('mysql') || function_exists('mysql_connect'))
+			{
+				$detected .= lang('You appear to have MySQL support enabled') . '<br>' . "\n";
+				$supported_db[] = 'mysql';
+			}
+			else
+			{
+				$detected .= lang('No MySQL support found. Disabling') . '<br>' . "\n";
+			}
+			if(extension_loaded('mssql') || function_exists('mssql_connect'))
+			{
+				$detected .= lang('You appear to have Microsoft SQL Server support enabled') . '<br>' . "\n";
+				$supported_db[] = 'mssql';
+			}
+			else
+			{
+				$detected .= lang('No Microsoft SQL Server support found. Disabling') . '<br>' . "\n";
+			}
+/*
+			if(extension_loaded('oci8'))
+			{
+				$detected .= lang('You appear to have Oracle V8 (OCI) support enabled') . '<br>' . "\n";
+				$supported_db[] = 'oracle';
+			}
+			else
+			{
+				if(extension_loaded('oracle'))
+				{
+					$detected .= lang('You appear to have Oracle support enabled') . '<br>' . "\n";
+					$supported_db[] = 'oracle';
+				}
+				else
+				{
+					$detected .= lang('No Oracle-DB support found. Disabling') . '<br>' . "\n";
+				}
+			}
+*/
+			if(!count($supported_db))
+			{
+				$detected .= '<b><p align="center" class="msg">'
+					. lang('Did not find any valid DB support!')
+					. "<br>\n"
+					. lang('Try to configure your php to support one of the above mentioned DBMS, or install eGroupWare by hand.')
+					. '</p></b><td></tr></table></body></html>';
+				echo $detected;
+				exit;
+			}
+
+			if(!function_exists('version_compare'))
+			{
+				$detected .= '<b><p align="center" class="msg">'
+					. lang('You appear to be using PHP earlier than 4.1.0. eGroupWare now requires 4.1.0 or later'). "\n"
+					. '</p></b><td></tr></table></body></html>';
+				echo $detected;
+				exit;
+			}
+			else
+			{
+				$detected .= lang('You appear to be using PHP4. Enabling PHP4 sessions support') . '<br>' . "\n";
+				$supported_sessions_type[] = 'php4';	// makeing php4 sessions the default
+				$supported_sessions_type[] = 'db';
+			}
+
+			@reset($default_db_ports);
+			$js_default_db_ports = 'var default_db_ports = new Array();'."\n";
+			while(list($k,$v) = @each($default_db_ports))
+			{
+				$js_default_db_ports .= '  default_db_ports["'.$k.'"]="'.$v.'";'."\n";
+			}
+			$setup_tpl->set_var('js_default_db_ports',$js_default_db_ports);
+
+			/*
+			if(extension_loaded('xml') || function_exists('xml_parser_create'))
+			{
+				$detected .= lang('You appear to have XML support enabled') . '<br>' . "\n";
+				$xml_enabled = 'True';
+			}
+			else
+			{
+				$detected .= lang('No XML support found. Disabling') . '<br>' . "\n";
+			}
+			*/
+
+			$no_guess = False;
+			if(file_exists('../header.inc.php') && is_file('../header.inc.php') && is_readable('../header.inc.php'))
+			{
+				$detected .= lang('Found existing configuration file. Loading settings from the file...') . '<br>' . "\n";
+				$GLOBALS['phpgw_info']['flags']['noapi'] = True;
+				$no_guess = true;
+				/* This code makes sure the newer multi-domain supporting header.inc.php is being used */
+				if(!isset($GLOBALS['phpgw_domain']))
+				{
+					$detected .= lang('You need to add some domains to your header.inc.php.') . '<br>' . "\n";
+					$GLOBALS['phpgw_domain']['default'] = array();
+					$setup_tpl->set_var('lang_domain',lang('Domain'));
+					$setup_tpl->set_var('lang_delete',lang('Delete'));
+					$setup_tpl->set_var('db_domain','default');
+					$setup_tpl->set_var('db_host','localhost');
+					$setup_tpl->set_var('db_name','expresso');
+					$setup_tpl->set_var('db_user','postgres');
+					$setup_tpl->set_var('db_pass','');
+					$setup_tpl->set_var('config_user','changeme');
+					$setup_tpl->set_var('config_pass','');
+					while(list($k,$v) = @each($supported_db))
+					{
+						$dbtype_options .= '<option value="' . $v . '">' . $db_fullnames[$v] . "\n";
+						if (!isset($default_port))
+							$default_port = $default_db_ports[$v];
+					}
+					$setup_tpl->set_var('dbtype_options',$dbtype_options);
+					$setup_tpl->set_var('db_port',$default_port);
+					$setup_tpl->parse('domains','domain',True);
+				}
+				else
+				{
+					if(@$GLOBALS['phpgw_info']['server']['header_version'] != @$GLOBALS['phpgw_info']['server']['current_header_version'])
+					{
+						$detected .= lang("You're using an old header.inc.php version...") . '<br>' . "\n";
+						$detected .= lang('Importing old settings into the new format....') . '<br>' . "\n";
+					}
+					reset($GLOBALS['phpgw_domain']);
+					$default_domain = each($GLOBALS['phpgw_domain']);
+					$GLOBALS['phpgw_info']['server']['default_domain'] = $default_domain[0];
+					unset($default_domain); // we kill this for security reasons
+					$GLOBALS['phpgw_info']['server']['config_passwd'] = $GLOBALS['phpgw_domain'][$GLOBALS['phpgw_info']['server']['default_domain']]['config_passwd'];
+					$GLOBALS['phpgw_info']['server']['config_user'] = $GLOBALS['phpgw_domain'][$GLOBALS['phpgw_info']['server']['default_domain']]['config_user'];
+
+					if(@$adddomain)
+					{
+						$GLOBALS['phpgw_domain'][lang('new')] = array();
+					}
+
+					reset($GLOBALS['phpgw_domain']);
+					while(list($key,$val) = each($GLOBALS['phpgw_domain']))
+					{
+						$setup_tpl->set_var('lang_domain',lang('Domain'));
+						$setup_tpl->set_var('lang_delete',lang('Delete'));
+						$setup_tpl->set_var('db_domain',$key);
+						$setup_tpl->set_var('db_host',$GLOBALS['phpgw_domain'][$key]['db_host']);
+						/* Set default here if the admin didn't set a port yet */
+						$setup_tpl->set_var('db_port',$GLOBALS['phpgw_domain'][$key]['db_port']
+							? $GLOBALS['phpgw_domain'][$key]['db_port']
+							: @$default_db_ports[$GLOBALS['phpgw_domain'][$key]['db_type']]
+						);
+						$setup_tpl->set_var('db_name',$GLOBALS['phpgw_domain'][$key]['db_name']);
+						$setup_tpl->set_var('db_user',$GLOBALS['phpgw_domain'][$key]['db_user']);
+						$setup_tpl->set_var('db_pass',$GLOBALS['phpgw_domain'][$key]['db_pass']);
+						$setup_tpl->set_var('db_type',$GLOBALS['phpgw_domain'][$key]['db_type']);
+						if(!@isset($GLOBALS['phpgw_domain'][$key]['config_user']))
+						{
+							$setup_tpl->set_var('config_user','admin');
+						}
+						else
+						{
+							$setup_tpl->set_var('config_user',$GLOBALS['phpgw_domain'][$key]['config_user']);
+						}
+						$setup_tpl->set_var('config_pass','');
+						$setup_tpl->set_var('config_password',$GLOBALS['phpgw_domain'][$key]['config_passwd']);
+
+						$selected = '';
+						$dbtype_options = '';
+						$found_dbtype = False;
+						@reset($supported_db);
+						while(list($k,$v) = @each($supported_db))
+						{
+							if($v == $GLOBALS['phpgw_domain'][$key]['db_type'])
+							{
+								$selected = ' selected ';
+								$found_dbtype = true;
+							}
+							else
+							{
+								$selected = '';
+							}
+							$dbtype_options .= '<option ' . $selected . 'value="' . $v . '">' . $db_fullnames[$v] . "\n";
+						}
+						$setup_tpl->set_var('dbtype_options',$dbtype_options);
+
+						$setup_tpl->parse('domains','domain',True);
+					}
+					$setup_tpl->set_var('domain','');
+				}
+				if(defined('PHPGW_SERVER_ROOT'))
+				{
+					$GLOBALS['phpgw_info']['server']['server_root']  = (PHPGW_SERVER_ROOT  == '..') ? $realpath : PHPGW_SERVER_ROOT;
+					$GLOBALS['phpgw_info']['server']['include_root'] = (PHPGW_INCLUDE_ROOT == '..') ? $realpath : PHPGW_SERVER_ROOT;
+				}
+				elseif(!@isset($GLOBALS['phpgw_info']['server']['include_root']) && @$GLOBALS['phpgw_info']['server']['header_version'] <= 1.6)
+				{
+					$GLOBALS['phpgw_info']['server']['include_root'] = @$GLOBALS['phpgw_info']['server']['server_root'];
+				}
+				elseif(!@isset($GLOBALS['phpgw_info']['server']['header_version']) && @$GLOBALS['phpgw_info']['server']['header_version'] <= 1.6)
+				{
+					$GLOBALS['phpgw_info']['server']['include_root'] = @$GLOBALS['phpgw_info']['server']['server_root'];
+				}
+			}
+			else
+			{
+				$detected .= lang('Sample configuration not found. using built in defaults') . '<br>' . "\n";
+				$GLOBALS['phpgw_info']['server']['server_root']  = $realpath;
+				$GLOBALS['phpgw_info']['server']['include_root'] = $realpath;
+				/* This is the basic include needed on each page for eGroupWare application compliance */
+				$GLOBALS['phpgw_info']['flags']['htmlcompliant'] = True;
+
+				/* These are the settings for the database system */
+				$setup_tpl->set_var('lang_domain',lang('Domain'));
+				$setup_tpl->set_var('lang_delete',lang('Delete'));
+				$setup_tpl->set_var('db_domain','default');
+				$setup_tpl->set_var('db_host','localhost');
+				$setup_tpl->set_var('db_name','expresso');
+				$setup_tpl->set_var('db_user','postgres');
+				$setup_tpl->set_var('db_pass','');
+				$setup_tpl->set_var('config_user','admin');
+				$setup_tpl->set_var('config_pass','');
+				$setup_tpl->set_var('use_https_0',' checked');
+
+				while(list($k,$v) = each($supported_db))
+				{
+					$dbtype_options .= '<option value="' . $v . '">' . $db_fullnames[$v] . "\n";
+					if (!isset($default_port))
+						$default_port = $default_db_ports[$v];
+				}
+				$setup_tpl->set_var('db_port',$default_port);
+				$setup_tpl->set_var('dbtype_options',$dbtype_options);
+
+				$setup_tpl->parse('domains','domain',True);
+				$setup_tpl->set_var('domain','');
+
+				$setup_tpl->set_var('comment_l','<!-- ');
+				$setup_tpl->set_var('comment_r',' -->');
+
+				/* These are a few of the advanced settings */
+				$GLOBALS['phpgw_info']['server']['db_persistent'] = True;
+				$GLOBALS['phpgw_info']['server']['mcrypt_enabled'] = extension_loaded('mcrypt');
+				$GLOBALS['phpgw_info']['server']['versions']['mcrypt'] = '';
+
+				srand((double)microtime()*1000000);
+				$random_char = array(
+					'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f',
+					'g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v',
+					'w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L',
+					'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
+				);
+
+				for($i=0; $i<30; $i++)
+				{
+					$GLOBALS['phpgw_info']['server']['mcrypt_iv'] .= $random_char[rand(1,count($random_char))];
+				}
+			}
+
+			// now guessing better settings then the default ones 
+			if(!$no_guess)
+			{
+				$detected .= lang('Now guessing better values for defaults...') . '<br>' . "\n";
+				$this_dir = dirname($_SERVER['SCRIPT_FILENAME']);
+				$updir    = str_replace('/setup','',$this_dir);
+				$GLOBALS['phpgw_info']['server']['server_root'] = $updir; 
+				$GLOBALS['phpgw_info']['server']['include_root'] = $updir; 
+			}
+
+			$setup_tpl->set_var('detected',$detected);
+			/* End of detected settings, now display the form with the detected or prior values */
+
+			$setup_tpl->set_var('server_root',@$GLOBALS['phpgw_info']['server']['server_root']);
+			$setup_tpl->set_var('include_root',@$GLOBALS['phpgw_info']['server']['include_root']);
+			if(!@isset($GLOBALS['phpgw_info']['server']['header_admin_user']))
+			{
+				$setup_tpl->set_var('header_admin_user','admin');
+			}
+			else
+			{
+				$setup_tpl->set_var('header_admin_user',@$GLOBALS['phpgw_info']['server']['header_admin_user']);
+			}
+			$setup_tpl->set_var('header_admin_pass',@$GLOBALS['phpgw_info']['server']['header_admin_password']);
+			$setup_tpl->set_var('header_admin_password','');
+
+
+			if(@$GLOBALS['phpgw_info']['server']['db_persistent'])
+			{
+				$setup_tpl->set_var('db_persistent_yes',' selected');
+			}
+			else
+			{
+				$setup_tpl->set_var('db_persistent_no',' selected');
+			}
+
+			$selected = '';
+			$session_options = '';
+			while(list($k,$v) = each($supported_sessions_type))
+			{
+				if($v == @$GLOBALS['phpgw_info']['server']['sessions_type'])
+				{
+					$selected = ' selected ';
+				}
+				else
+				{
+					$selected = '';
+				}
+				$session_options .= '<option ' . $selected . 'value="' . $v . '">' . $v . "\n";
+			}
+			$setup_tpl->set_var('session_options',$session_options);
+
+			if(@$GLOBALS['phpgw_info']['server']['mcrypt_enabled'])
+			{
+				$setup_tpl->set_var('mcrypt_enabled_yes',' selected');
+			}
+			else
+			{
+				$setup_tpl->set_var('mcrypt_enabled_no',' selected');
+			}
+
+			$setup_tpl->set_var('mcrypt',$GLOBALS['phpgw_info']['server']['versions']['mcrypt']);
+			$setup_tpl->set_var('mcrypt_iv',$GLOBALS['phpgw_info']['server']['mcrypt_iv']);
+
+			$setup_tpl->set_var('lang_setup_acl',lang('Limit access to setup to the following addresses, networks or hostnames (e.g. 127.0.0.1,10.1.1,myhost.dnydns.org)'));
+			$setup_tpl->set_var('setup_acl',$GLOBALS['phpgw_info']['server']['setup_acl']);
+
+			if(@$GLOBALS['phpgw_info']['server']['show_domain_selectbox'])
+			{
+				$setup_tpl->set_var('domain_selectbox_yes',' selected');
+			}
+			else
+			{
+				$setup_tpl->set_var('domain_selectbox_no',' selected');
+			}
+
+			// ExpressoLivre
+			switch($GLOBALS['phpgw_info']['server']['use_https'])
+			{
+				case '0':
+					$setup_tpl->set_var('use_https_0',' checked');
+					break;
+				case '1':
+					$setup_tpl->set_var('use_https_1',' checked');
+					break;
+				case '2':
+					$setup_tpl->set_var('use_https_2',' checked');
+					break;
+			}
+
+/********************* INICIO BLOCO MAILMAN **************************/
+
+			switch($GLOBALS['phpgw_info']['server']['use_mailman'])
+			{
+				case '0':
+					$setup_tpl->set_var('use_mailman_0',' checked');
+					$setup_tpl->set_var('div_mailman',' style="display: none;" ');
+					break;
+				case '1':
+					$setup_tpl->set_var('use_mailman_1',' checked');
+					$setup_tpl->set_var('div_mailman','');
+					break;
+				default:
+					$setup_tpl->set_var('use_mailman_0',' checked');
+					$setup_tpl->set_var('div_mailman',' style="display: none;" ');
+			}
+			if($GLOBALS['phpgw_info']['server']['contexto_geral'])
+			{
+				$setup_tpl->set_var('contexto_geral',$GLOBALS['phpgw_info']['server']['contexto_geral']);
+			}
+			if($GLOBALS['phpgw_info']['server']['dn_listas'])
+			{
+				$setup_tpl->set_var('dn_listas',$GLOBALS['phpgw_info']['server']['dn_listas']);
+			}
+			if($GLOBALS['phpgw_info']['server']['dominio_listas'])
+			{
+				$setup_tpl->set_var('dominio_listas',$GLOBALS['phpgw_info']['server']['dominio_listas']);
+			}
+			if($GLOBALS['phpgw_info']['server']['porta_mailman'])
+			{
+				$setup_tpl->set_var('porta_mailman',$GLOBALS['phpgw_info']['server']['porta_mailman']);
+			}
+			if($GLOBALS['phpgw_info']['server']['host_mailman'])
+			{
+				$setup_tpl->set_var('host_mailman',$GLOBALS['phpgw_info']['server']['host_mailman']);
+			}
+			if($GLOBALS['phpgw_info']['server']['url_mailman'])
+			{
+				$setup_tpl->set_var('url_mailman',$GLOBALS['phpgw_info']['server']['url_mailman']);
+			}
+
+/********************* FIM BLOCO MAILMAN **************************/
+
+			if(@$GLOBALS['phpgw_info']['server']['sugestoes_email_to'])
+			{
+				$setup_tpl->set_var('sugestoes_email_to',$GLOBALS['phpgw_info']['server']['sugestoes_email_to']);
+			}
+
+			if(@$GLOBALS['phpgw_info']['server']['domain_name'])
+			{
+				$setup_tpl->set_var('domain_name',$GLOBALS['phpgw_info']['server']['domain_name']);
+			}
+
+			if(@$GLOBALS['phpgw_info']['server']['use_prefix_organization'])
+			{
+				$setup_tpl->set_var('use_prefix_organization_checked',' checked');
+			}
+	 		
+			$errors = '';
+			if(!$found_dbtype)
+			{
+				/*
+				$errors .= '<br><font color="red">' . lang('Warning!') . '<br>'
+					. lang('The db_type in defaults (%1) is not supported on this server. using first supported type.',$GLOBALS['phpgw_info']['server']['db_type'])
+					. '</font>';
+				*/
+			}
+
+			if(is_writeable('../header.inc.php') ||
+				(!file_exists('../header.inc.php') && is_writeable('../')))
+			{
+				$errors .= '<br><input type="submit" name="action[write]" value="'.lang('Write config').'">&nbsp;'
+					. lang('or') . '&nbsp;<input type="submit" name="action[download]" value="'.lang('Download').'">&nbsp;'
+					. lang('or') . '&nbsp;<input type=submit name="action[view]" value="'.lang('View').'"> '.lang('the file').'.</form>';
+			}
+			else
+			{
+				$errors .= '<br>'
+					. lang('Cannot create the header.inc.php due to file permission restrictions.<br> Instead you can %1 the file.',
+					'<input type="submit" name="action[download]" value="'.lang('Download').'">' . lang('or') . '&nbsp;<input type="submit" name="action[view]" value="'.lang('View').'">')
+					. '</form>';
+			}
+			// set domain and password for the continue button
+			@reset($GLOBALS['phpgw_domain']);
+			list($firstDomain) = @each($GLOBALS['phpgw_domain']);
+			$setup_tpl->set_var(array(
+				'FormDomain' => $firstDomain,
+				'FormUser'   => $GLOBALS['phpgw_domain'][$firstDomain]['config_user'],
+				'FormPW'     => $GLOBALS['phpgw_domain'][$firstDomain]['config_passwd']
+			));
+			$setup_tpl->set_var('errors',$errors);
+
+			$setup_tpl->set_var('lang_settings',lang('Settings'));
+			$setup_tpl->set_var('lang_adddomain',lang('Add a domain'));
+			$setup_tpl->set_var('lang_serverroot',lang('Server Root'));
+			$setup_tpl->set_var('lang_includeroot',lang('Include Root (this should be the same as Server Root unless you know what you are doing)'));
+			$setup_tpl->set_var('lang_adminuser',lang('Admin user for header manager'));
+			$setup_tpl->set_var('lang_adminpass',lang('Admin password to header manager'));
+			$setup_tpl->set_var('lang_dbhost',lang('DB Host'));
+			$setup_tpl->set_var('lang_dbhostdescr',lang('Hostname/IP of database server'));
+			$setup_tpl->set_var('lang_dbport',lang('DB Port'));
+			$setup_tpl->set_var('lang_dbportdescr',lang('TCP port number of database server'));
+			$setup_tpl->set_var('lang_dbname',lang('DB Name'));
+			$setup_tpl->set_var('lang_dbnamedescr',lang('Name of database'));
+			$setup_tpl->set_var('lang_dbuser',lang('DB User'));
+			$setup_tpl->set_var('lang_dbuserdescr',lang('Name of db user eGroupWare uses to connect'));
+			$setup_tpl->set_var('lang_dbpass',lang('DB Password'));
+			$setup_tpl->set_var('lang_dbpassdescr',lang('Password of db user'));
+			$setup_tpl->set_var('lang_dbtype',lang('DB Type'));
+			$setup_tpl->set_var('lang_whichdb',lang('Which database type do you want to use with eGroupWare?'));
+			$setup_tpl->set_var('lang_configuser',lang('Configuration User'));
+			$setup_tpl->set_var('lang_configpass',lang('Configuration Password'));
+			$setup_tpl->set_var('lang_passforconfig',lang('Password needed for configuration'));
+			$setup_tpl->set_var('lang_persist',lang('Persistent connections'));
+			$setup_tpl->set_var('lang_persistdescr',lang('Do you want persistent connections (higher performance, but consumes more resources)'));
+			$setup_tpl->set_var('lang_sesstype',lang('Sessions Type'));
+			$setup_tpl->set_var('lang_sesstypedescr',lang('What type of sessions management do you want to use (PHP4 session management may perform better)?'));
+			$setup_tpl->set_var('lang_enablemcrypt',lang('Enable MCrypt'));
+			$setup_tpl->set_var('lang_mcrypt_warning',lang('Not all mcrypt algorithms and modes work with eGroupWare. If you experience problems try switching it off.'));
+			$setup_tpl->set_var('lang_mcryptversion',lang('MCrypt version'));
+			$setup_tpl->set_var('lang_mcryptversiondescr',lang('Set this to "old" for versions &lt; 2.4, otherwise the exact mcrypt version you use.'));
+			$setup_tpl->set_var('lang_mcryptiv',lang('MCrypt initialization vector'));
+			$setup_tpl->set_var('lang_mcryptivdescr',lang('This should be around 30 bytes in length.<br>Note: The default has been randomly generated.'));
+			$setup_tpl->set_var('lang_domselect',lang('Domain select box on login'));
+			$setup_tpl->set_var('lang_finaldescr',lang('After retrieving the file, put it into place as the header.inc.php.  Then, click "continue".'));
+			$setup_tpl->set_var('lang_continue',lang('Continue'));
+			$setup_tpl->set_var('lang_Yes',lang('Yes'));
+			$setup_tpl->set_var('lang_No',lang('No'));
+
+
+			$setup_tpl->pfp('out','manageheader');
+
+			$GLOBALS['phpgw_setup']->html->show_footer();
+
+			break; // ending the switch default
+	}
+?>
Index: /branches/2.2/listAdmin/controller.php
===================================================================
--- /branches/2.2/listAdmin/controller.php	(revision 3514)
+++ /branches/2.2/listAdmin/controller.php	(revision 3514)
@@ -0,0 +1,79 @@
+<?php
+if(!isset($GLOBALS['phpgw_info'])){
+        $GLOBALS['phpgw_info']['flags'] = array(
+                'currentapp' => 'listAdmin',
+                'nonavbar'   => true,
+                'noheader'   => true
+        );
+}
+require_once '../header.session.inc.php';
+
+	//	Explode action from cExecuteForm function
+	$cExecuteFormReturn = false;
+ 	if($_POST['_action']) { 		
+ 		if($_FILES) {
+ 			$count_files = $_POST['countFiles'];
+			$array_files = array(); 		
+ 			for($idx = 1; $idx <= $count_files; $idx++) { 		
+ 				if($_FILES['file_'.$idx] && !$_FILES['file_'.$idx]['error'])
+ 					$array_files[] = $_FILES['file_'.$idx]; 					 
+ 			}
+ 			$_POST['FILES'] = $array_files;
+ 		} 		  		
+ 		list($app,$class,$method) = explode('.',@$_POST['_action']);
+ 		$cExecuteFormReturn = true;
+ 	}
+ 	//	Explode action from cExecute function
+ 	else if($_GET['action'])
+		list($app,$class,$method) = explode('.',@$_GET['action']);
+	// NO ACTION
+	else
+		return $_SESSION['response'] = 'false';
+	
+	// Load dinamically class file.
+	if($app == '$this')
+		$filename = 'inc/class.'.$class.'.inc.php';
+	else if( strpos($app, '$this/') !== false)
+	{
+		$filename = str_replace('$this/','',$app) . '.php';
+		include_once($filename);
+		exit;
+	}
+	else
+		$filename = '../'.$app.'/inc/class.'.$class.'.inc.php';
+
+	include_once($filename);	
+	
+	// Create new Object  (class loaded).	
+	$obj = new $class;
+	
+	// Prepare parameters for execution.	
+	$params = array();
+	
+	// If array $_POST is not null , the submit method is POST. 
+	if($_POST) {
+		$params = $_POST;
+	}
+	// If array $_POST is null , and the array $_GET > 1, the submit method is GET.
+	else if(count($_GET) > 1)	{		
+		array_shift($_GET);
+		$params = $_GET;
+	}
+
+	$result = array();
+	
+	
+	// if params is not empty, then class method with parameters.	
+	if($params)
+		$result = $obj -> $method($params);
+	else 		
+		$result = $obj -> $method();
+		
+	// Return result serialized.	
+	
+
+	if(!$cExecuteFormReturn)
+		echo serialize($result);
+	else
+		$_SESSION['response'] = $result;
+?>
Index: /branches/2.2/listAdmin/inc/access_denied.php
===================================================================
--- /branches/2.2/listAdmin/inc/access_denied.php	(revision 3514)
+++ /branches/2.2/listAdmin/inc/access_denied.php	(revision 3514)
@@ -0,0 +1,30 @@
+<?php
+	/************************************************************************************\
+	* Expresso Administração                 			                                 *
+	* by Joao Alfredo Knopik Junior (joao.alfredo@gmail.com, jakjr@celepar.pr.gov.br)  	 *
+	* -----------------------------------------------------------------------------------*
+	*  This program is free software; you can redistribute it and/or modify it			 *
+	*  under the terms of the GNU General Public License as published by the			 *
+	*  Free Software Foundation; either version 2 of the License, or (at your			 *
+	*  option) any later version.														 *
+	\************************************************************************************/
+
+	$GLOBALS['phpgw_info'] = array();
+	$GLOBALS['phpgw_info']['flags']['currentapp'] = 'listAdmin';
+	include('../../header.inc.php');
+
+	$template = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
+	$template->set_file(Array('expressoadmin' => 'access_denied.tpl'));
+	
+	$template->set_block('expressoadmin','main');
+	
+	$var = Array(
+		'lang_access_denied' => lang('You dont have access to this module.'),
+		'lang_back'	=> lang('Back'),
+		'back_url'	=> $GLOBALS['phpgw']->link('/listAdmin/index.php')
+	);
+	$template->set_var($var);
+	
+	$template->pfp('out','main');
+	$GLOBALS['phpgw']->common->phpgw_footer();	
+?>
Index: /branches/2.2/listAdmin/inc/class.db_functions.inc.php
===================================================================
--- /branches/2.2/listAdmin/inc/class.db_functions.inc.php	(revision 3514)
+++ /branches/2.2/listAdmin/inc/class.db_functions.inc.php	(revision 3514)
@@ -0,0 +1,596 @@
+<?php
+define('PHPGW_INCLUDE_ROOT','../');	
+define('PHPGW_API_INC','../phpgwapi/inc');
+include_once(PHPGW_API_INC.'/class.db.inc.php');
+
+class db_functions
+{	
+	var $db;
+	var $user_id;
+	
+	function db_functions(){
+		
+		if (is_array($_SESSION['phpgw_info']['expresso']['server']))
+			$GLOBALS['phpgw_info']['server'] = $_SESSION['phpgw_info']['expresso']['server'];
+		else
+			$_SESSION['phpgw_info']['expresso']['server'] = $GLOBALS['phpgw_info']['server'];
+		
+		$this->db = new db();
+		$this->db->Halt_On_Error = 'no';
+		$this->db->connect(
+				$_SESSION['phpgw_info']['expresso']['server']['db_name'], 
+				$_SESSION['phpgw_info']['expresso']['server']['db_host'],
+				$_SESSION['phpgw_info']['expresso']['server']['db_port'],
+				$_SESSION['phpgw_info']['expresso']['server']['db_user'],
+				$_SESSION['phpgw_info']['expresso']['server']['db_pass'],
+				$_SESSION['phpgw_info']['expresso']['server']['db_type']
+		);		
+		$this->user_id = $_SESSION['phpgw_info']['expresso']['user']['account_id'];	
+	}
+
+	// BEGIN of functions.
+	function read_acl($account_lid)
+	{
+		$query = "SELECT * FROM phpgw_expressoadmin WHERE manager_lid = '" . $account_lid . "'"; 
+		$this->db->query($query);
+		while($this->db->next_record())
+			$result[] = $this->db->row();
+		return $result;
+	}
+	
+	/*
+	function get_sectors($params)
+	{
+		$organization = strtolower($params['organization']);
+		
+		$result = array();
+		// Pesquisa no BD os nomes setores no tabela phpgw_expressoadmin_sectors.
+ 		$query = "SELECT sector FROM phpgw_expressoadmin_sectors WHERE organization='$organization' ORDER by sector ASC";
+
+        if (!$this->db->query($query))
+        	return 'Erro em get_sectors:' . pg_last_error();
+
+		while($this->db->next_record())
+			$result[] = $this->db->row();
+
+		return $result;
+	}
+	*/
+	
+	function get_next_id()
+	{
+		// Busco o ID dos accounts
+		$query_accounts = "SELECT id FROM phpgw_nextid WHERE appname = 'accounts'";
+        if (!$this->db->query($query_accounts))
+        	return 'Erro em get_next_id:' . pg_last_error();
+		while($this->db->next_record())
+			$result_accounts[] = $this->db->row();
+		$accounts_id = $result_accounts[0]['id'];
+		
+		// Busco o ID dos groups
+		$query_groups = "SELECT id FROM phpgw_nextid WHERE appname = 'groups'";
+        if (!$this->db->query($query_groups))
+        	return 'Erro em get_next_id:' . pg_last_error();
+		while($this->db->next_record())
+			$result_groups[] = $this->db->row();
+		$groups_id = $result_groups[0]['id'];
+		
+		//Retorna o maior dos ID's
+		if ($accounts_id >= $groups_id)
+			return $accounts_id;
+		else
+			return $groups_id;
+		}
+	
+	function increment_id($id, $type)
+	{
+		$sql = "UPDATE phpgw_nextid set id = '".$id."' WHERE appname = '" . $type . "'";
+		if (!$this->db->query($sql))
+			return 'Erro em increment_id:' . pg_last_error();
+		else
+			return true;
+	}
+	
+	function add_user2group($gidnumber, $uidnumber)
+	{
+		$query = "SELECT acl_location FROM phpgw_acl WHERE acl_appname = 'phpgw_group' AND acl_location = '" . $gidnumber . "' AND acl_account = '" . $uidnumber . "'";
+		if (!$this->db->query($query))
+		{
+			$result['status'] = false;
+			$result['msg'] = 'Erro em add_user2group:' . pg_last_error();
+			return $result;
+		}
+		while($this->db->next_record())
+			$user_in_group[] = $this->db->row();
+		
+		if (count($user_in_group) == 0)
+		{
+			$sql = "INSERT INTO phpgw_acl (acl_appname, acl_location, acl_account, acl_rights) "
+			. "VALUES('phpgw_group','" . $gidnumber . "','" . $uidnumber . "','1')";
+			if (!$this->db->query($sql))
+			{
+				$result['status'] = false;
+				$result['msg'] = 'Erro em add_user2group:' . pg_last_error();
+				return $result;
+			}
+		}
+		$result['status'] = true;
+		return $result;
+	}
+
+	function remove_user2group($gidnumber, $uidnumber)
+	{
+		$query = "SELECT acl_location FROM phpgw_acl WHERE acl_appname = 'phpgw_group' AND acl_location = '" . $gidnumber . "' AND acl_account = '" . $uidnumber . "'";
+		if (!$this->db->query($query))
+		{
+			$result['status'] = false;
+			$result['msg'] = 'Erro em add_user2group:' . pg_last_error();
+			return $result;
+		}
+		while($this->db->next_record())
+			$user_in_group[] = $this->db->row();
+		
+		if (count($user_in_group) > 0)
+		{
+			$sql = "DELETE FROM phpgw_acl WHERE acl_appname = 'phpgw_group' AND acl_location = '" . $gidnumber . "' AND acl_account = '".$uidnumber."'";
+			if (!$this->db->query($sql))
+			{
+				$result['status'] = false;
+				$result['msg'] = 'Erro em add_user2group:' . pg_last_error();
+				return $result;
+			}
+		}
+		$result['status'] = true;
+		return $result;
+	}
+
+	function add_pref_changepassword($uidnumber)
+	{
+		$query = "SELECT * FROM phpgw_acl WHERE acl_appname = 'preferences' AND acl_location = 'changepassword' AND acl_account = '" . $uidnumber . "'";
+		if (!$this->db->query($query))
+		{
+			$result['status'] = false;
+			$result['msg'] = 'Erro em add_pref_changepassword:' . pg_last_error();
+			return $result;
+		}
+		while($this->db->next_record())
+			$user_pref_changepassword[] = $this->db->row();
+		
+		if (count($user_pref_changepassword) == 0)
+		{
+			$sql = "INSERT INTO phpgw_acl (acl_appname, acl_location, acl_account, acl_rights) "
+			. "VALUES('preferences','changepassword','" . $uidnumber . "','1')";
+			if (!$this->db->query($sql))
+			{
+				$result['status'] = false;
+				$result['msg'] = 'Erro em add_pref_changepassword:' . pg_last_error();
+				return $result;
+			}
+		}
+		$result['status'] = true;
+		return $result;
+	}	
+
+	function remove_pref_changepassword($uidnumber)
+	{
+		$query = "SELECT * FROM phpgw_acl WHERE acl_appname = 'preferences' AND acl_location = 'changepassword' AND acl_account = '" . $uidnumber . "'";
+		if (!$this->db->query($query))
+		{
+			$result['status'] = false;
+			$result['msg'] = 'Erro em add_pref_changepassword:' . pg_last_error();
+			return $result;
+		}
+		while($this->db->next_record())
+			$user_pref_changepassword[] = $this->db->row();
+		
+		if (count($user_pref_changepassword) != 0)
+		{
+			$sql = "DELETE FROM phpgw_acl WHERE acl_appname = 'preferences' AND acl_location = 'changepassword' AND acl_account = '".$uidnumber."'";
+			if (!$this->db->query($sql))
+			{
+				$result['status'] = false;
+				$result['msg'] = 'Erro em remove_pref_changepassword:' . pg_last_error();
+				return $result;
+			}
+		}
+		$result['status'] = true;
+		return $result;
+	}	
+	
+	function add_id2apps($id, $apps)
+	{
+		$result['status'] = true;
+		if ($apps)
+		{
+			foreach($apps as $app => $value)
+			{
+				$query = "SELECT * FROM phpgw_acl WHERE acl_appname = '".$app."' AND acl_location = 'run' AND acl_account = '" . $id . "'";
+				if (!$this->db->query($query))
+				{
+					$result['status'] = false;
+					$result['msg'] = 'Erro em add_id2apps: ' . pg_last_error();
+					return $result;
+				}
+				
+				while($this->db->next_record())
+					$user_app[] = $this->db->row();
+					
+				if (count($user_app) == 0)
+				{
+					$sql = "INSERT INTO phpgw_acl (acl_appname, acl_location, acl_account, acl_rights) "
+					. "VALUES('".$app."','run','" . $id . "','1')";
+						
+					if (!$this->db->query($sql))
+					{
+						$result['status'] = false;
+						$result['msg'] = 'Erro em add_id2apps: ' . pg_last_error();
+						return $result;
+					}
+					else
+					{
+						$this->write_log("Adicionado aplicativo $app ao id",$id,'','','');	
+					}
+				}
+			}
+		}
+		return $result;
+	}
+
+	function remove_id2apps($id, $apps)
+	{
+		$result['status'] = true;
+		if ($apps)
+		{
+			foreach($apps as $app => $value)
+			{
+				$query = "SELECT acl_location FROM phpgw_acl WHERE acl_appname = '" . $app . "' AND acl_location = 'run' AND acl_account = '" . $id . "'";
+				
+				if (!$this->db->query($query))
+				{
+					$result['status'] = false;
+					$result['msg'] = 'Erro em remove_id2apps:' . pg_last_error();
+					return $result;
+				}
+				while($this->db->next_record())
+					$user_in_group[] = $this->db->row();
+				
+				if (count($user_in_group) > 0)
+				{
+					$sql = "DELETE FROM phpgw_acl WHERE acl_appname = '" . $app . "' AND acl_location = 'run' AND acl_account = '".$id."'";
+					if (!$this->db->query($sql))
+					{
+						$result['status'] = false;
+						$result['msg'] = 'Erro em remove_id2apps:' . pg_last_error();
+						return $result;
+					}
+					else
+					{
+						$this->write_log("Removido aplicativo $app do id",$id,'','','');	
+					}
+				}
+			}
+		}
+		return $result;
+	}
+
+
+	function get_user_info($uidnumber)
+	{
+		// Groups
+		$query = "SELECT acl_location FROM phpgw_acl WHERE acl_appname = 'phpgw_group' AND acl_account = '".$uidnumber."'";
+		$this->db->query($query);
+		while($this->db->next_record())
+			$user_app[] = $this->db->row();
+		
+		for ($i=0; $i<count($user_app); $i++)
+			$return['groups'][] = $user_app[$i]['acl_location'];
+		
+		// ChangePassword
+		$query = "SELECT acl_rights FROM phpgw_acl WHERE acl_appname = 'preferences' AND acl_location = 'changepassword' AND acl_account = '".$uidnumber."'";
+		$this->db->query($query);
+		while($this->db->next_record())
+			$changepassword[] = $this->db->row();
+		$return['changepassword'] = $changepassword[0]['acl_rights'];
+		
+		// Apps
+		$query = "SELECT acl_appname FROM phpgw_acl WHERE acl_account = '".$uidnumber."' AND acl_location = 'run'";
+		$this->db->query($query);
+		while($this->db->next_record())
+			$user_apps[] = $this->db->row();
+			
+		if ($user_apps)
+		{			
+			foreach ($user_apps as $app)
+			{
+				$return['apps'][$app['acl_appname']] = '1';
+			}
+		}
+		
+		return $return;
+	}
+	
+	function get_group_info($gidnumber)
+	{
+		// Apps
+		$query = "SELECT acl_appname FROM phpgw_acl WHERE acl_account = '".$gidnumber."' AND acl_location = 'run'";
+		$this->db->query($query);
+		while($this->db->next_record())
+			$group_apps[] = $this->db->row();
+		
+		if ($group_apps)
+		{			
+			foreach ($group_apps as $app)
+			{
+				$return['apps'][$app['acl_appname']] = '1';
+			}
+		}
+		
+		// Members
+		$query = "SELECT acl_account FROM phpgw_acl WHERE acl_appname = 'phpgw_group' AND acl_location = '" . $gidnumber . "'";
+		
+		$this->db->query($query);
+		while($this->db->next_record())
+			$group_members[] = $this->db->row();
+
+		if ($group_members)
+		{
+			foreach ($group_members as $member)
+			{
+				$return['members'][] = $member['acl_account'];
+			}
+		}
+		else
+			$return['members'] = array();
+
+		return $return;
+	}
+	
+	function default_user_password_is_set($uid)
+	{
+		$query = "SELECT uid FROM phpgw_expressoadmin_passwords WHERE uid = '" . $uid . "'";
+		$this->db->query($query);
+		while($this->db->next_record())
+		{
+			$userPassword[] = $this->db->row();
+		}
+		if (count($userPassword) == 0)
+			return false;
+		else
+			return true;
+	}
+	
+	function set_user_password($uid, $password)
+	{
+		$query = "SELECT uid FROM phpgw_expressoadmin_passwords WHERE uid = '" . $uid . "'";
+		$this->db->query($query);
+		while($this->db->next_record())
+		{
+			$user[] = $this->db->row();
+		}
+		if (count($user) == 0)
+		{
+			$sql = "INSERT INTO phpgw_expressoadmin_passwords (uid, password) VALUES('".$uid."','".$password."')";
+
+			if (!$this->db->query($sql))
+			{
+				$result['status'] = false;
+				$result['msg'] = 'Erro em set_user_password: ' . pg_last_error();
+				return $result;
+			}
+		}
+		return true;
+	}
+	
+	function get_user_password($uid)
+	{
+		$query = "SELECT password FROM phpgw_expressoadmin_passwords WHERE uid = '" . $uid . "'";
+		$this->db->query($query);
+		while($this->db->next_record())
+		{
+			$userPassword[] = $this->db->row();
+		}
+		
+		if (count($userPassword) == 1)
+		{
+			$sql = "DELETE FROM phpgw_expressoadmin_passwords WHERE uid = '" . $uid . "'";
+			$this->db->query($sql);
+			return $userPassword[0]['password'];
+		}
+		else
+			return false;
+	}
+	
+	function delete_user($uidnumber)
+	{
+		// AGENDA
+		$this->db->query('SELECT cal_id FROM phpgw_cal WHERE owner ='.$uidnumber);
+		while($this->db->next_record())
+		{
+			$ids[] = $this->db->row();
+		}
+		if (count($ids))
+		{
+			foreach($ids as $i => $id)
+			{
+				$this->db->query('DELETE FROM phpgw_cal WHERE cal_id='.$id['cal_id']);
+				$this->db->query('DELETE FROM phpgw_cal_user WHERE cal_id='.$id['cal_id']);
+				$this->db->query('DELETE FROM phpgw_cal_repeats WHERE cal_id='.$id['cal_id']);
+				$this->db->query('DELETE FROM phpgw_cal_extra WHERE cal_id='.$id['cal_id']);
+			}
+		}
+			
+		// CONATOS pessoais e grupos.
+		$this->db->query('SELECT id_contact FROM phpgw_cc_contact WHERE id_owner ='.$uidnumber);
+		while($this->db->next_record())
+		{
+			$ids[] = $this->db->row();
+		}
+
+		if (count($ids))
+		{
+			foreach($ids as $i => $id_contact)
+			{
+				$this->db->query('SELECT id_connection FROM phpgw_cc_contact_conns WHERE id_contact='.$id_contact['id_contact']);
+				while($this->db->next_record())
+				{
+					$id_conns[] = $this->db->row();
+				}
+				if (count($id_conns))
+				{
+					foreach($id_conns as $j => $id_conn)
+					{
+						$this->db->query('DELETE FROM phpgw_cc_connections WHERE id_connection='.$id_conn['id_connection']);
+						$this->db->query('DELETE FROM phpgw_cc_contact_grps WHERE id_connection='.$id_conn['id_connection']);
+					}
+				}
+					
+				$this->db->query('SELECT id_address FROM phpgw_cc_contact_addrs WHERE id_contact='.$id_contact['id_contact']);
+				while($this->db->next_record())
+				{
+					$id_addresses[] = $$this->db->row();
+				}
+				if (count($id_addresses))
+				{
+					foreach($id_addresses as $j => $id_addrs)
+					{
+						$this->db->query('DELETE FROM phpgw_cc_addresses WHERE id_address='.$id_addrs['id_address']);
+					}
+				}
+				$this->db->query('DELETE FROM phpgw_cc_contact WHERE id_contact='.$id_contact['id_contact']);
+				$this->db->query('DELETE FROM phpgw_cc_contact_conns WHERE id_contact='.$id_contact['id_contact']);
+				$this->db->query('DELETE FROM phpgw_cc_contact_addrs WHERE id_contact='.$id_contact['id_contact']);
+			}
+		}
+		$this->db->query('DELETE FROM phpgw_cc_groups WHERE owner='.$uidnumber);
+			
+		// PREFERENCIAS
+		$this->db->query('DELETE FROM phpgw_preferences WHERE preference_owner='.$uidnumber);
+			
+		// ACL
+		$this->db->query('DELETE FROM phpgw_acl WHERE acl_account='.$uidnumber);
+		
+		// Corrigir
+		$return['status'] = true;
+		return $return;
+	}
+
+	function delete_group($gidnumber)
+	{
+		// ACL
+		$this->db->query('DELETE FROM phpgw_acl WHERE acl_location='.$gidnumber);
+		$this->db->query('DELETE FROM phpgw_acl WHERE acl_account='.$gidnumber);
+		
+		// Corrigir
+		$return['status'] = true;
+		return $return;
+	}
+	
+	function write_log($action, $groupinfo='', $userinfo='', $appinfo='', $msg_log='')
+	{
+		$sql = "INSERT INTO phpgw_expressoadmin_log (date, manager, action, groupinfo, userinfo, appinfo, msg) "
+		. "VALUES('now','" . $_SESSION['phpgw_info']['expresso']['user']['account_lid'] . "','" . strtolower($action) . "','" . strtolower($groupinfo) . "','" . strtolower($userinfo) . "','" . strtolower($appinfo) . "','" .strtolower($msg_log) . "')";
+		$this->db->query($sql);
+		return;
+	}
+	
+	function get_sieve_info()
+	{
+		$this->db->query('SELECT profileID,imapenablesieve,imapsieveserver,imapsieveport FROM phpgw_emailadmin');
+		
+		$i=0;
+		while($this->db->next_record())
+		{
+			$serverList[$i]['profileID']		= $this->db->f(0);
+			$serverList[$i]['imapenablesieve']	= $this->db->f(1);
+			$serverList[$i]['imapsieveserver']	= $this->db->f(2);
+			$serverList[$i]['imapsieveport']	= $this->db->f(3);
+			$i++;
+		}
+		
+		return $serverList;
+	}
+	
+	function get_apps($account_lid)
+	{
+		$this->db->query("SELECT * FROM phpgw_expressoadmin_apps WHERE manager_lid = '".$account_lid."'");
+		
+		while($this->db->next_record())
+		{
+			$tmp = $this->db->row();
+			$availableApps[$tmp['app']] = 'run'; 
+		}
+			
+		return $availableApps;
+	}
+	
+	function get_sambadomains_list()
+	{
+		$query = "SELECT * FROM phpgw_expressoadmin_samba ORDER by samba_domain_name ASC"; 
+		$this->db->query($query);
+		while($this->db->next_record())
+			$result[] = $this->db->row();
+		return $result;
+	}
+	
+	function exist_domain_name_sid($sambadomainname, $sambasid)
+	{
+		$query = "SELECT * FROM phpgw_expressoadmin_samba WHERE samba_domain_name='$sambadomainname' OR samba_domain_sid='$sambasid'"; 
+		$this->db->query($query);
+		while($this->db->next_record())
+			$result[] = $this->db->row();
+		
+		if (count($result) > 0)
+			return true;
+		else
+			return false;
+	}
+	
+	function delete_sambadomain($sambadomainname)
+	{
+		$this->db->query("DELETE FROM phpgw_expressoadmin_samba WHERE samba_domain_name='$sambadomainname'");
+		return;
+	}
+	
+	function add_sambadomain($sambadomainname, $sambasid)
+	{
+		$sql = "INSERT INTO phpgw_expressoadmin_samba (samba_domain_name, samba_domain_sid) VALUES('$sambadomainname','$sambasid')";
+		$this->db->query($sql);
+		return;
+	}
+
+        function add_edit_user_data($edit_user)
+	        {
+		$query = "SELECT 'uidnumber' FROM phpgw_ldap_users WHERE uidnumber='".$edit_user['uidnumber']."'";
+		$this->db->query($query);
+		if($this->db->next_record())
+			{
+			$sql = "UPDATE phpgw_ldap_users SET uid='".$edit_user['uid']."',uidnumber='".$edit_user['uidnumber']."',givenname='".$edit_user['givenname']."',sn='".$edit_user['sn']."',cn='".$edit_user['cn']."',mail='".$edit_user['mail']."',mailalternateaddress='".$edit_user['mailalternateaddress']."' WHERE uid='".$edit_user['uid']."'";
+			$this->db->query($sql);
+                	}
+			else
+			{
+			$sql = "INSERT INTO phpgw_ldap_users VALUES('".$edit_user['uid']."','".$edit_user['uidnumber']."','".$edit_user['sn']."','".$edit_user['cn']."','".$edit_user['givenname']."','".$edit_user['mail']."','".$edit_user['mailalternateaddress']."')";
+			$this->db->query($sql);
+			}
+                return true;
+	        }
+/*        function get_user_list($search)
+                {
+		$users_ldap="";
+                $query = "SELECT * FROM phpgw_ldap_users WHERE uidnumber LIKE '%".$search."%' OR uid LIKE '%".$search."%' OR cn LIKE '%".$search."%' OR sn LIKE '%".$search."%' OR givenname LIKE '%".$search."%' OR mail LIKE '%".$search."%' OR mailalternateaddress LIKE '%".$search."%'";
+                $this->db->query($query);
+		$i=0;
+                while($this->db->next_record()) 
+			{
+			$users_ldap[$i]['uid']            	= $this->db->f(0);
+			$users_ldap[$i]['uidnumber']      	= $this->db->f(1);
+			$users_ldap[$i]['cn']        		= $this->db->f(3);
+			$users_ldap[$i]['mail']        		= $this->db->f(5);
+			$i++;
+			}	     
+		return $users_ldap;
+                }
+*/
+
+}
+?>
Index: /branches/2.2/listAdmin/inc/class.imap_functions.inc.php
===================================================================
--- /branches/2.2/listAdmin/inc/class.imap_functions.inc.php	(revision 3514)
+++ /branches/2.2/listAdmin/inc/class.imap_functions.inc.php	(revision 3514)
@@ -0,0 +1,119 @@
+<?php
+
+class imap_functions
+{
+	var $imap;
+	var $imapDelimiter;
+	var $imap_admin;
+	var $imap_passwd;
+	var $imap_server;
+	var $imap_port;
+	
+	function imap_functions(){
+		$this->imap_admin	= $_SESSION['phpgw_info']['expresso']['email_server']['imapAdminUsername'];
+		$this->imap_passwd	= $_SESSION['phpgw_info']['expresso']['email_server']['imapAdminPW'];
+		$this->imap_server	= $_SESSION['phpgw_info']['expresso']['email_server']['imapServer'];
+		$this->imap_port	= $_SESSION['phpgw_info']['expresso']['email_server']['imapPort'];
+		$this->imapDelimiter= $_SESSION['phpgw_info']['expresso']['email_server']['imapDelimiter'];
+		$this->imap 		= imap_open('{'.$this->imap_server.':'.$this->imap_port.'/novalidate-cert}', $this->imap_admin, $this->imap_passwd, OP_HALFOPEN);
+	}
+	
+	function create($uid, $mailquota)
+	{
+		if (!imap_createmailbox($this->imap, '{'.$this->imap_server.'}' . "user" . $this->imapDelimiter . $uid))
+		{
+			$error = imap_errors();
+			$result['status'] = false;
+			$result['msg'] = 'Erro na funcao imap_function->create(INBOX): ' . $error[0];
+			$result['error'] = $error[0];
+			return $result;
+		}
+		if (!imap_createmailbox($this->imap, '{'.$this->imap_server.'}' . "user" . $this->imapDelimiter . $uid . $this->imapDelimiter . "Sent"))
+		{
+			$error = imap_errors();
+			$result['status'] = false;
+			$result['msg'] = 'Erro na funcao imap_function->create(Enviados): ' . $error[0];
+			return $result;
+		}
+		if (!imap_createmailbox($this->imap, '{'.$this->imap_server.'}' . "user" . $this->imapDelimiter . $uid . $this->imapDelimiter . "Drafts"))
+		{
+			$error = imap_errors();
+			$result['status'] = false;
+			$result['msg'] = 'Erro na funcao imap_function->create(Rascunho): ' . $error[0];
+			return $result;
+		}
+		if (!imap_createmailbox($this->imap, '{'.$this->imap_server.'}' . "user" . $this->imapDelimiter . $uid . $this->imapDelimiter . "Trash"))
+		{
+			$error = imap_errors();
+			$result['status'] = false;
+			$result['msg'] = 'Erro na funcao imap_function->create(Lixeira): ' . $error[0];
+			return $result;
+		}
+		if (!imap_set_quota($this->imap,"user" . $this->imapDelimiter . $uid, ($mailquota*1024))) 
+		{
+			$error = imap_errors();
+			$result['status'] = false;
+			$result['msg'] = 'Erro na funcao imap_function->create(set_quota): ' . $error[0];
+			return $result;
+		}
+		
+		$result['status'] = true;
+		return $result;
+	}
+	
+	function get_user_info($uid)
+	{
+		$get_quota = @imap_get_quotaroot($this->imap,"user" . $this->imapDelimiter . $uid);
+		
+		if (count($get_quota) == 0)
+		{
+			$quota['mailquota'] = '-1';
+			$quota['mailquota_used'] = '-1';
+		}	
+		else
+		{
+			$quota['mailquota'] = ($get_quota['limit'] / 1024);
+			$quota['mailquota_used'] = ($get_quota['usage'] / 1024);
+		}
+			
+		return $quota;
+	}
+	
+	function change_user_quota($uid, $quota)
+	{
+		$set_quota = imap_set_quota($this->imap,"user" . $this->imapDelimiter . $uid, ($quota*1024));
+		return true;
+	}
+	
+	function delete_user($uid)
+	{
+		$result['status'] = true;
+		
+		//Seta acl imap para poder deletar o user.
+		// Esta sem tratamento de erro, pois o retorno da funcao deve ter um bug.
+		imap_setacl($this->imap, "user" . $this->imapDelimiter . $uid, $this->imap_admin, 'c');
+		
+		if (!imap_deletemailbox($this->imap, '{'.$this->imap_server.'}' . "user" . $this->imapDelimiter . $uid))
+		{
+			$result['status'] = false;
+			$result['msg'] = "Erro na funcao imap_function->delete_user.\nRetorno do servidor: " . imap_last_error();
+		}
+		
+		return $result;
+	}
+	
+	function rename_mailbox($old_mailbox, $new_mailbox)
+	{
+		$result['status'] = true;		
+		$result_rename = imap_renamemailbox($this->imap,
+						'{'.$this->imap_server.':'.$this->imap_port.'}user' . $this->imapDelimiter . $old_mailbox,
+						'{'.$this->imap_server.':'.$this->imap_port.'}user' . $this->imapDelimiter . $new_mailbox);
+		
+		if (!$result_rename)
+		{
+			$result['status'] = false;
+			$result['msg'] = "Erro na funcao imap_function->rename_mailbox.\nRetorno do servidor: " . imap_last_error();
+		}
+		return $result;
+	}
+}
Index: /branches/2.2/listAdmin/inc/class.maillist.inc.php
===================================================================
--- /branches/2.2/listAdmin/inc/class.maillist.inc.php	(revision 3514)
+++ /branches/2.2/listAdmin/inc/class.maillist.inc.php	(revision 3514)
@@ -0,0 +1,727 @@
+<?php
+	/**********************************************************************************\
+	* Expresso Administraï¿œï¿œo                 									      *
+	* by Joao Alfredo Knopik Junior (joao.alfredo@gmail.com, jakjr@celepar.pr.gov.br) *
+	* --------------------------------------------------------------------------------*
+	*  This program is free software; you can redistribute it and/or modify it		  *
+	*  under the terms of the GNU General Public License as published by the		  *
+	*  Free Software Foundation; either version 2 of the License, or (at your		  *
+	*  option) any later version.													  *
+	\**********************************************************************************/
+	
+	include_once('class.ldap_functions.inc.php');
+	include_once('class.db_functions.inc.php');
+	include_once('class.functions.inc.php');
+	
+	class maillist
+	{
+		var $ldap_functions;
+		var $db_functions;
+		var $functions;
+		var $current_config;
+		
+		
+		function maillist()
+		{
+			$this->ldap_functions = new ldap_functions;
+			$this->db_functions = new db_functions;
+			$this->functions = new functions;
+			$this->current_config = $_SESSION['phpgw_info']['expresso']['listAdmin']; 
+		}
+		
+		function validate_fields($params)
+		{
+			return $this->ldap_functions->validate_fields_maillist($params);
+		}
+		
+		function create($params)
+		{
+			// Verifica o acesso do gerente
+	/*		if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'add_maillists'))
+			{
+				$return['status'] = false;
+				$return['msg'] = 'Vocï¿œ nï¿œo tem acesso para adicionar listas de email.';
+				return $return;
+			}
+	*/		
+
+			$return['status'] = true;
+			
+			//Retira os uids duplicados se existir
+			$array_tmp = array();
+			$array_tmp = array_unique($params['members']);
+			$params['members'] = $array_tmp;
+			
+				// Pega ID do BD e incrementa de 1 (vai ser o uidnumber da lista)
+			$id = (($this->db_functions->get_next_id()) + 1);
+			
+			// Incrementa o id no BD.
+			$this->db_functions->increment_id($id,'accounts');
+
+			//DN do repositorio das listas de e-mail; usado para gravacao de listas manuais
+			$dnListas = $this->current_config['dn_listas'];
+			//Dominio do servidor de listas; usado na composicao do endereco de e-mail das listas
+			$dominioListas = $this->current_config['dominio_listas'];
+
+			// Cria array para incluir no LDAP
+			//$dn = 'uid=' . $params['uid'] . ',' . $params['context'];
+			$dn = 'uid=' . $params['uid'] . ',' . $dnListas;
+			
+			$maillist_info = array();
+			$maillist_info['uid']					= $params['uid'];  
+			$maillist_info['givenName']				= 'MailList';
+			$maillist_info['sn']					= $params['uid'];
+			$maillist_info['cn']					= $params['uid'];
+			
+			$maillist_info['homeDirectory']				= '/home/false';
+			$maillist_info['loginShell']				= '/bin/false';
+			$maillist_info['mail']					= $params['uid'] . "@" . $dominioListas;
+			$maillist_info['description']				= $params['description'];
+			
+			$expressoAdmin 						= $GLOBALS['phpgw_info']['server']['header_admin_user'];
+			//Obtem uidnumber baseado no uid do usuario expresso-admin
+			$admUidnumber						= $this->ldap_functions->uid2uidnumber($expressoAdmin);
+			//Obten email baseado no uidnumber do usuario expresso-admin
+			$adminlista						= $this->ldap_functions->uidnumber2mail($admUidnumber);
+
+			//Pega o id do usuario atual da sessao
+			$usuarioAtual 						= $_SESSION['phpgw_info']['expresso']['user']['account_lid'];
+			//Pega o uidnumber do usuario atual
+			$uidUsuarioAtual 					= $this->ldap_functions->uid2uidnumber($usuarioAtual);
+			//Pega o email do usuario atual
+			$mailUsuarioAtual 					= $this->ldap_functions->uidnumber2mail($uidUsuarioAtual);
+
+			//adiciona o expresso-admin como administrador padrao da lista no campo admlista 
+			$adm_info['admlista'][0] 				= $adminlista;
+//			system('echo "admlista: '.$GLOBALS['phpgw_info']['server']['header_admin_user'].'">>/tmp/teste.log');
+			//adiciona o usuario corrente como administrador da lista
+			$adm_info['admlista'][1] 				= $mailUsuarioAtual;
+
+			//verifica se o usuario logado (corrente) eh igual ao administrador padrao (expresso-admin)
+			if($adm_info['admlista'][0] == $adm_info['admlista'][1]) {
+				$maillist_info['admlista'][0] = $adm_info['admlista'][0];
+			}else {
+				$maillist_info['admlista'][0] = $adm_info['admlista'][0];
+				$maillist_info['admlista'][1] = $adm_info['admlista'][1];
+			}
+
+
+			//Modifica a geracao de senha pro mailman
+			$senhaCripto                                            = $params['listPass'];
+                        $maillist_info['listPass']				= $senhaCripto;
+//			system('echo "listPass: '.$senhaCripto.'">>/tmp/teste.log');
+                        //$maillist_info['listPass']				= 'senha';
+			$maillist_info['objectClass'][0]			= 'posixAccount';
+			$maillist_info['objectClass'][1]			= 'inetOrgPerson';
+			$maillist_info['objectClass'][2]			= 'shadowAccount';
+			//$maillist_info['objectClass'][3]			= 'qmailuser';
+			$maillist_info['objectClass'][3]			= 'phpgwAccount';
+			$maillist_info['objectClass'][4]			= 'top';
+			$maillist_info['objectClass'][5]			= 'person';
+			$maillist_info['objectClass'][6]			= 'organizationalPerson';		
+			$maillist_info['objectClass'][7]                        = 'mailman';		
+			//$maillist_info['phpgwAccountExpires']		        = '-1';
+			//$maillist_info[$GLOBALS['phpgw_info']['server']['atributoexpiracao']] = '-1';
+			if(isset($GLOBALS['phpgw_info']['server']['atributoexpiracao']))
+					{
+					$maillist_info[$GLOBALS['phpgw_info']['server']['atributoexpiracao']] = '-1';
+					}
+				else
+					{
+					$maillist_info['phpgwaccountexpires'] = '-1';
+					}
+			$maillist_info['phpgwAccountType']			= 'l';
+			$maillist_info['phpgwAccountStatus']			= 'A';
+			$maillist_info['uidnumber']				= $id;
+			$maillist_info['gidnumber']				= '0';
+			$maillist_info['deliveryMode']				= 'forwardOnly';
+			
+			if ($params['accountStatus'] == 'on')
+				$maillist_info['accountStatus'] = 'active';
+			
+			if ($params['phpgwAccountVisible'] == 'on')
+				$maillist_info['phpgwAccountVisible'] = '-1';
+
+			if ($params['defaultMemberModeration'] == 'on')
+                                $maillist_info['defaultMemberModeration'] = '1';
+
+			foreach($params['members'] as $index=>$uidnumber)
+			{
+				$this->db_functions->write_log($params['context'],",",$params['cn']);
+				$mail = $this->ldap_functions->uidnumber2mail($uidnumber);
+
+				//Este if foi adicionado para tratar a situacao de uma lista ser criada com usuario(s) externo(s)
+				if($mail == '')
+				{
+					//adiciona ao vetor o(s) usuario(s) externo(s)
+					$maillist_info['mailForwardingAddress'][] = $uidnumber;
+				} else{	
+					//adiciona ao vetor o(s) usuario(s) exitente(s) no RHDS
+					$maillist_info['mailForwardingAddress'][] = $mail;
+				}
+
+				//$maillist_info['mailForwardingAddress'][] = $mail;
+				$this->db_functions->write_log("Adicionado usuario $mail a lista ".$params['cn']." no momento da criaï¿œï¿œo",$dn,$uidnumber,'','');
+			}
+			$result = $this->ldap_functions->ldap_add_entry($dn, $maillist_info);			
+
+			if (!$result['status'])
+			{
+				$return['status'] = false;
+				$return['msg'] .= $result['msg'];
+			}
+			
+			if ($return['status'] == true)
+			{
+				$this->db_functions->write_log('Criado lista de email','',$dn,'','');
+			}
+			
+			$opts = null;
+			$obj = null;
+			return $return;
+		}
+		
+		function save($new_values)
+		{
+			// Verifica o acesso do gerente
+	/*		if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'edit_maillists'))
+			{
+				$return['status'] = false;
+				$return['msg'] = 'Vocï¿œ nï¿œo tem acesso para editar listas de email.';
+				return $return;
+			}
+*/
+			if ($params['accountAdm'] == 'on'){
+                                $teste = 'A';
+				$return['msg'] = '$teste';
+                        }
+
+			$return['status'] = true;
+			
+			//Retira os uids duplicados se existir
+			$array_tmp = array();
+			$array_tmp = array_unique($new_values['members']);
+			$new_values['members'] = $array_tmp;
+	                
+			$old_values = $this->get_info($new_values['uidnumber'], $new_values['manager_context']);
+			$diff = array_diff($new_values, $old_values);
+			
+			$dn = 'uid=' . $old_values['uid'] . ',' . $old_values['context'];
+			////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+			// RENAME
+/*			if ($diff['context'] || $diff['uid'])
+			{
+				$newrdn = 'uid=' . $new_values['uid'];
+				$newparent = $new_values['context'];
+				$result =  $this->ldap_functions->change_user_context($dn, $newrdn, $newparent);
+				if (!$result['status'])
+				{
+					$return['status'] = false;
+					$return['msg'] .= $result['msg'];
+				}
+				else
+				{
+					$dn = $newrdn . ',' . $newparent;
+					$old_dn = $old_values['uid'];
+					$this->db_functions->write_log("Renomeado login da lista de $old_dn para $dn",'',$dn,$old_values['uid'],'');
+				}
+			}*/
+			
+			////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+			// REPLACE MAIL || CN || SN
+			if ($new_values['mail'] != $old_values['mail'])
+			{
+				$ldap_mod_replace['mail'] = $new_values['mail'];
+				$this->db_functions->write_log('Modificado email da lista para ' . $new_values['mail'],'',$dn,'','');
+			}
+
+			if ($new_values['listPass'] != $old_values['listPass'])
+                        {
+//                              $tmpPassword     = '{md5}' . base64_encode(pack("H*",md5($new_values['userPassword'])));
+				$senhaCripto     = $new_values['listPass'];
+                                $tmpPassword     = encriptar($senhaCripto);
+				$ldap_mod_replace['listPass'] = $tmpPassword;
+                                $this->db_functions->write_log('Modificado senha da lista para ' . $tmpPassword ,'',$dn,'','');
+                        }
+
+			if ($new_values['cn'] != $old_values['cn'])
+			//if ($diff['uid'])
+			{
+				$ldap_mod_replace['cn'] = $new_values['uid'];
+				$ldap_mod_replace['sn'] = $new_values['uid'];
+		//		$ldap_mod_replace['uid'] = $new_values['uid'];
+				$this->db_functions->write_log("Modificado common name da lista $dn",'',$dn,'','');
+			}
+			
+	/*		if ($diff['sn'])
+			{
+				$ldap_mod_replace['uid'] = $new_values['uid'];
+			}
+	*/		
+			if (count($ldap_mod_replace))
+			{
+				$result = $this->ldap_functions->replace_user_attributes($dn, $ldap_mod_replace);
+				if (!$result['status'])
+				{
+					$return['status'] = false;
+					$return['msg'] .= $result['msg'];
+				}
+			}
+			
+			//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+			// REMOVE ATTRS
+			if (($old_values['accountStatus'] == 'active') && ($new_values['accountStatus'] != 'on'))
+				$ldap_remove['accountStatus']	= array();
+			
+			if (($old_values['defaultMemberModeration'] == '1') && ($new_values['defaultMemberModeration'] != 'on'))
+                                $ldap_remove['defaultMemberModeration']   = array();		
+
+				
+			if (($old_values['phpgwAccountVisible'] == '-1') && ($new_values['phpgwAccountVisible'] != 'on'))
+				$ldap_remove['phpgwAccountVisible']	= array();
+			
+			if (count($ldap_remove))
+			{
+				$result = $this->ldap_functions->remove_user_attributes($dn, $ldap_remove);
+				if (!$result['status'])
+				{
+					$return['status'] = false;
+					$return['msg'] .= $result['msg'];
+				}
+			}
+			
+			//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+			// ADD ATTRS
+			if (($old_values['accountStatus'] != 'active') && ($new_values['accountStatus'] == 'on'))
+				$ldap_add['accountStatus']	= 'active';
+
+			if (($old_values['defaultMemberModeration'] != '1') && ($new_values['defaultMemberModeration'] == 'on'))
+                                $ldap_add['defaultMemberModeration']      = '1';	
+			
+		
+			if (($old_values['phpgwAccountVisible'] != '-1') && ($new_values['phpgwAccountVisible'] == 'on'))
+				$ldap_add['phpgwAccountVisible'] = '-1';
+			
+			if (count($ldap_add))
+			{
+				$result = $this->ldap_functions->add_user_attributes($dn, $ldap_add);
+				if (!$result['status'])
+				{
+					$return['status'] = false;
+					$return['msg'] .= $result['msg'];
+				}
+			}
+			
+			////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+			// USERS
+
+			if (!$new_values['members'])
+				$new_values['members'] = array();
+			if (!$old_values['members'])
+				$old_values['members'] = array();
+
+			$add_users = array_diff($new_values['members'], $old_values['members']);
+
+			$remove_users = array_diff($old_values['members'], $new_values['members']);
+			
+			if (count($add_users)>0)
+			{
+				$array_emails_add = array();
+				foreach($add_users as $uidnumber)
+				{
+					$mail = $this->ldap_functions->uidnumber2mail($uidnumber);
+					usleep(100000);
+
+					//caso nao exista o e-mail do usuario informado (usuario externo);
+					if(empty($mail)){
+						$mail = $uidnumber;
+					}
+
+					$array_emails_add[] = $mail;
+					$this->db_functions->write_log("Adicionado usuario $mail $teste a lista",$dn,$uidnumber,'','');
+				}
+					$this->ldap_functions->add_user2maillist($new_values['uidnumber'], $array_emails_add);
+			}
+			if (count($remove_users)>0)
+			{
+				$array_emails_remove = array();
+				foreach($remove_users as $uidnumber)
+				{
+					$mail = $this->ldap_functions->uidnumber2mail($uidnumber);
+					
+					//caso nao exista o e-mail do usuario informado (usuario externo);
+					if (empty($mail))
+						$mail = $uidnumber;
+					
+					$array_emails_remove[] = $mail;
+					$this->db_functions->write_log("Removido usuario $mail da lista",$dn,$uidnumber,'','');
+				}
+				$this->ldap_functions->remove_user2maillist($new_values['uidnumber'], $array_emails_remove);
+				//$this->ldap_functions->remove_user2maillist_adm($new_values['uidnumber'], $array_emails_remove);
+
+			}
+			
+			return $return;
+		}
+
+		function save_adm($new_values) // Funcao usada para salvar alteracoes de administradores de listas
+		{
+			// Verifica o acesso do gerente
+	/*			if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'adm_maillists'))
+			{
+				$return['status'] = false;
+				$return['msg'] = 'Vocï¿œ nï¿œo tem acesso para editar listas de email.';
+				return $return;
+			}
+*/
+			$return['status'] = true;
+			
+			//Retira os uids duplicados se existir
+			$array_tmp = array();
+			$array_tmp = array_unique($new_values['members']);
+			$new_values['members'] = $array_tmp;
+	                
+			$old_values = $this->get_adm_info($new_values['uidnumber'], $new_values['manager_context']);
+			$diff = array_diff($new_values, $old_values);
+			
+			$dn = 'uid=' . $old_values['uid'] . ',' . $old_values['context'];
+			//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+			// ADD ATTRS
+			if (($old_values['accountStatus'] != 'active') && ($new_values['accountStatus'] == 'on'))
+				$ldap_add['accountStatus']	= 'active';
+			
+			if (($old_values['phpgwAccountVisible'] != '-1') && ($new_values['phpgwAccountVisible'] == 'on'))
+				$ldap_add['phpgwAccountVisible'] = '-1';
+			
+			if (count($ldap_add))
+			{
+				$result = $this->ldap_functions->add_user_attributes($dn, $ldap_add);
+				if (!$result['status'])
+				{
+					$return['status'] = false;
+					$return['msg'] .= $result['msg'];
+				}
+			}
+			
+			////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+			// USERS
+
+			if (!$new_values['members'])
+				$new_values['members'] = array();
+			if (!$old_values['members'])
+				$old_values['members'] = array();
+
+			$add_users = array_diff($new_values['members'], $old_values['members']);
+
+			$remove_users = array_diff($old_values['members'], $new_values['members']);
+			
+			if (count($add_users)>0)
+			{
+				$array_emails_add = array();
+				foreach($add_users as $uidnumber)
+				{
+					$mail = $this->ldap_functions->uidnumber2mail($uidnumber);
+					$array_emails_add[] = $mail;
+					$this->db_functions->write_log("Adicionado usuario $mail $teste a lista",$dn,$uidnumber,'','');
+				}
+					$this->ldap_functions->add_user2maillist_adm($new_values['uidnumber'], $array_emails_add);
+			}
+			if (count($remove_users)>0)
+			{
+				$array_emails_remove = array();
+				foreach($remove_users as $uidnumber)
+				{
+					$mail = $this->ldap_functions->uidnumber2mail($uidnumber);
+					
+					// Nï¿œo achei o email do usuï¿œrio no ldap.
+					if (empty($mail))
+						$mail = $uidnumber;
+					
+					$array_emails_remove[] = $mail;
+					$this->db_functions->write_log("Removido usuario $mail da lista",$dn,$uidnumber,'','');
+				}
+				$this->ldap_functions->remove_user2maillist_adm($new_values['uidnumber'], $array_emails_remove);
+
+			}
+			
+			return $return;
+		}		
+
+		
+		function save_scl($new_values)
+		{
+			// Verifica o acesso do gerente
+	/*		if (!$this->functions->check_acl($_SESSION['phpgw_info']['expresso']['user']['account_lid'], 'edit_maillists'))
+			{
+				$return['status'] = false;
+				$return['msg'] = 'Vocï¿œ nï¿œo tem acesso para editar listas de email.';
+				return $return;
+			}
+	*/		
+			$return['status'] = true;
+
+			//Retira os uids duplicados se existir
+			$array_tmp = array();
+			$array_tmp = array_unique($new_values['members']);
+			$new_values['members'] = $array_tmp;
+			
+			$old_values = $this->get_scl_info($new_values['uidnumber'], $new_values['manager_context']);
+			$diff = array_diff($new_values, $old_values);
+			$dn = $old_values['dn'];
+			
+			////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+			// ADD ATTRS
+			if (($new_values['participantCanSendMail'] == 'on') && ($old_values['participantCanSendMail'] == ''))
+			{
+				$ldap_add['participantCanSendMail'] = "TRUE";
+				$this->db_functions->write_log("Ativado participantCanSendMail da SCL da lista de email " . $new_values['mail'],'','','','');
+			}
+			if (($new_values['accountRestrictive'] == 'on') && ($old_values['accountRestrictive'] == ''))
+			{
+				$ldap_add['accountRestrictive'] = "mailListRestriction";
+				$ldap_add['accountDeliveryMessage']	= 'OK';
+				$this->db_functions->write_log("Ativado mailListRestriction da SCL da lista de email " . $new_values['mail'],'','','','');
+			}
+			if (count($ldap_add))
+			{
+				$result = $this->ldap_functions->add_user_attributes($dn, $ldap_add);
+				if (!$result['status'])
+				{
+					$return['status'] = false;
+					$return['msg'] .= $result['msg'];
+				}
+			}
+			
+			//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+			// REMOVE ATTRS
+			if (($new_values['participantCanSendMail'] != 'on') && ($old_values['participantCanSendMail'] == 'TRUE'))
+			{
+				$ldap_remove['participantCanSendMail']	= array();
+				$this->db_functions->write_log("Desativado participantCanSendMail da SCL da lista de email " . $new_values['mail'],'','','','');
+			}
+			if (($new_values['accountRestrictive'] != 'on') && ($old_values['accountRestrictive'] == 'mailListRestriction'))
+			{
+				$ldap_remove['accountRestrictive']	= array();
+				$ldap_remove['accountDeliveryMessage']	= array();
+				$this->db_functions->write_log("Desativado restriï¿œï¿œo (mailListRestriction) da SCL da lista de email " . $new_values['mail'],'','','','');
+			}
+			if (count($ldap_remove))
+			{
+				$result = $this->ldap_functions->remove_user_attributes($dn, $ldap_remove);
+				if (!$result['status'])
+				{
+					$return['status'] = false;
+					$return['msg'] .= $result['msg'];
+				}
+			}
+			
+			////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+			// USERS
+
+			if (!$new_values['members'])
+				$new_values['members'] = array();
+			if (!$old_values['members'])
+				$old_values['members'] = array();
+
+			$add_users = array_diff($new_values['members'], $old_values['members']);
+			$remove_users = array_diff($old_values['members'], $new_values['members']);
+			
+			if (count($add_users)>0)
+			{
+				$array_emails_add = array();
+				foreach($add_users as $uidnumber)
+				{
+					$mail = $this->ldap_functions->uidnumber2mail($uidnumber);
+					$array_emails_add[] = $mail;
+					$this->db_functions->write_log("Adicionado usuario $mail a SCL da lista $dn",'',$uidnumber,'','');
+				}
+				$result = $this->ldap_functions->add_user2maillist_scl($dn, $array_emails_add);
+				if (!$result['status'])
+				{
+					$return['status'] = false;
+					$return['msg'] .= $result['msg'];
+				}
+				
+			}
+			
+			if (count($remove_users)>0)
+			{
+				$array_emails_remove = array();
+				foreach($remove_users as $uidnumber)
+				{
+					$mail = $this->ldap_functions->uidnumber2mail($uidnumber);
+					$array_emails_remove[] = $mail;
+					$this->db_functions->write_log("Removido usuario $mail da SCP da lista $dn",'',$uidnumber,'','');
+				}
+				$result = $this->ldap_functions->remove_user2maillist_scl($dn, $array_emails_remove);
+				if (!$result['status'])
+				{
+					$return['status'] = false;
+					$return['msg'] .= $result['msg'];
+				}
+			}
+			
+			return $return;
+		}				
+		
+		function get_info($uidnumber, $context)
+		{
+			$maillist_info_ldap = $this->ldap_functions->get_maillist_info($uidnumber, $context);
+			return $maillist_info_ldap;
+		}
+
+		function get_adm_info($uidnumber, $context) //Funcao que usa get_adm_maillist_info para trazer dados dos administradores
+							    // de listas;
+		{
+			$maillist_info_ldap = $this->ldap_functions->get_adm_maillist_info($uidnumber, $context);
+			return $maillist_info_ldap;
+		}
+
+
+		function get_scl_info($uidnumber, $context)
+		{
+			$maillist_info_ldap = $this->ldap_functions->get_maillist_scl_info($uidnumber, $context);
+			return $maillist_info_ldap;
+		}
+		
+		function delete($params)
+		{
+			// Verifica se usuario atual pertence ao grupo de administradores
+			// de listas para ter permissao de excluir a lista de email
+			$usuarioAtual = $_SESSION['phpgw_info']['expresso']['user']['account_lid'];
+			if ($this->ldap_functions->is_user_listAdmin($usuarioAtual) != 1)
+			{
+				$return['status'] = false;
+				$return['msg'] .= 'Vocï¿œ nï¿œo tem acesso para excluir listas de email.';
+				$return['msg'] .= ' - oi';
+				return $return;
+			}
+
+			$return['status'] = true;
+
+			$uidnumber = $params['uidnumber'];
+			$uid = $this->ldap_functions->uidnumber2uid($uidnumber);
+
+			//LDAP
+			$result_ldap = $this->ldap_functions->delete_maillist($uidnumber);
+			if (!$result_ldap['status'])
+			{
+				$return['status'] = false;
+				$return['msg'] .= $result_ldap['msg'];
+			}
+			
+			if ($return['status'] == true)
+			{
+				$this->db_functions->write_log('Deletado lista de email','',$uid,'','');
+			}
+			
+			return $return;	
+		}		
+		
+		//Rotina que visa atualizar o Mailman com base na criaï¿œï¿œo de nova lista no RHDS, em tempo real
+		//Utiliza socket para disparar um HTTP Post remoto
+		function synchronize_mailman($dados_lista){
+			//porta do servidor de acesso via rede
+			$porta_mailman = $this->current_config['porta_mailman']; //$GLOBALS['phpgw_info']['server']['porta_mailman'];
+			//endereï¿œo IP do servidor mailman
+			$host_mailman = $this->current_config['host_mailman']; //$GLOBALS['phpgw_info']['server']['host_mailman'];
+			//endereco da URL para o script PHP que faz a atualizacao no recurso remoto
+			//$url_mailman = '/servidor-listas/mailman_request.php';
+			$url_mailman = $this->current_config['url_mailman']; //$GLOBALS['phpgw_info']['server']['url_mailman'];
+			//o nome da lista passado como parametro no array associativo (algo tipo "uid=lista-X")
+			$lista_mailman = $dados_lista['uid'];
+			$op_mailman = $dados_lista['op'];
+			
+			if(strlen($lista_mailman) <= 0){
+				$msg_socket = "[ERROSOCKET00] " . date("d/m/Y-G:i:s") . " -[".$_SERVER['REMOTE_ADDR']."]"."-[".$_SERVER['REQUEST_URI']."]"."-[".$_SERVER['SCRIPT_NAME']."]:"." Sincronismo MailMan-RHDS falhou ao adicionar nova lista: Motivo= nome da lista(\"$lista_mailman\") invalido.";
+				$retorno['status'] = false;
+				$retorno['msg'] = $msg_socket; 
+				//Grava no logger o erro
+				$log = `/usr/bin/logger -p local5.notice -t Sinc-Listas-Mailman-RHDS '$msg_socket'`;
+    			return $retorno;				
+			}
+			
+			//Cria o socket TCP/IP
+			$socket = socket_create(AF_INET, SOCK_STREAM, 0);
+			
+			$retorno['status'] = true;
+			
+			//Em caso de erro, retorna um vetor serializado contendo (falso, string erro)
+			if ($socket < 0) {
+				$msg_socket = "[ERROSOCKET01] " . date("d/m/Y-G:i:s") . " -[".$_SERVER['REMOTE_ADDR']."]"."-[".$_SERVER['REQUEST_URI']."]"."-[".$_SERVER['SCRIPT_NAME']."]:"." Sincronismo MailMan-RHDS falhou ao adicionar nova lista: php socket_create() falhou. Motivo= " . socket_strerror($socket);;
+				$retorno['status'] = false;
+				$retorno['msg'] = $msg_socket; 
+				//Grava no logger o erro
+				$log = `/usr/bin/logger -p local5.notice -t Sinc-Listas-Mailman-RHDS '$msg_socket'`;
+    			return $retorno;
+			}
+			
+			//Estabelece a conexï¿œo com o recurso
+			$resultado = socket_connect($socket, $host_mailman, $porta_mailman);
+			
+			//Em caso de erro, retorna um vetor serializado contendo (falso, string erro)
+			if ($resultado < 0) {
+				$msg_socket = "[ERROSOCKET02] " .date("d/m/Y-G:i:s") . " -[".$_SERVER['REMOTE_ADDR']."]"."-[".$_SERVER['REQUEST_URI']."]"."-[".$_SERVER['SCRIPT_NAME']."]:"." Sincronismo MailMan-RHDS falhou ao adicionar nova lista: php socket_connect() [$resultado] falhou. Motivo=  " . socket_strerror($resultado);
+				$retorno['status'] = false;
+				$retorno['msg'] = $msg_socket; 
+				//Grava no logger o erro
+				$log = `/usr/bin/logger -p local5.notice -t Sinc-Listas-Mailman-RHDS '$msg_socket'`;
+    			return $retorno;				
+			}			
+			
+			//Envia o dado "lid", contendo o nome da lista recebido como parametro da funcao, e "op=1" (nova lista)
+			$post_lista = "uid=".$lista_mailman."&op=".$op_mailman;
+			
+			//Define o tipo de mensagem que vai ser disparada via socket: no caso, um HTTP Post
+			$dados_envio_socket = "POST $url_mailman HTTP/1.0\r\n";
+			$dados_envio_socket .= "Host: $host_mailman\r\n";
+			$dados_envio_socket .= "Accept: text/xml,application/xml,application/xhtml+xml,text/html,text/plain;\r\n";
+			$dados_envio_socket .= "Accept-Charset: ISO-8859-1,utf-8;\r\n";
+			$dados_envio_socket .= "Accept-Language: pt-br,en-us,en;\r\n";
+			$dados_envio_socket .= "Content-Type: application/x-www-form-urlencoded\r\n";
+			$dados_envio_socket .= "Connection: close\r\n";
+			$dados_envio_socket .= "Content-Length: " . strlen($post_lista) . "\r\n";
+			$dados_envio_socket .= "\r\n";
+			$dados_envio_socket .= "$post_lista\r\n";
+			
+			//String que contï¿œm a saï¿œda do processamento remoto
+			$dados_saida_socket = '';
+			
+			//Efetiva os dados de entrada para o processamento no socket remoto
+			if (socket_write ($socket, $dados_envio_socket, strlen($dados_envio_socket))){
+				while ($leitura_socket  = socket_read($socket, 2048)) {
+    				$dados_saida_socket .= $leitura_socket;
+				}
+			}
+			else{
+				$msg_socket = "[ERROSOCKET03] " .date("d/m/Y-G:i:s") . " -[".$_SERVER['REMOTE_ADDR']."]"."-[".$_SERVER['REQUEST_URI']."]"."-[".$_SERVER['SCRIPT_NAME']."]:"." Sincronismo MailMan-RHDS falhou ao adicionar nova lista: php socket_write() [$dados_envio_socket] falhou. Motivo=  " . socket_strerror(socket_last_error());
+				$retorno['status'] = false;
+				$retorno['msg'] = $msg_socket; 
+				//Grava no logger o erro
+				$log = `/usr/bin/logger -p local5.notice -t Sinc-Listas-Mailman-RHDS '$msg_socket'`;
+    			return $retorno;					
+			}
+			
+			//Captura a partir da string total da resposta do socket, a secï¿œï¿œo serializada a ser tratada
+			$vet_dados_saida = explode('@@', $dados_saida_socket);
+			if(count($vet_dados_saida[1]) > 0){
+				$dados_serializados_saida = unserialize($vet_dados_saida[1]);
+			}
+			else{
+				$msg_socket = "[ERROSOCKET04] " .date("d/m/Y-G:i:s") . " -[".$_SERVER['REMOTE_ADDR']."]"."-[".$_SERVER['REQUEST_URI']."]"."-[".$_SERVER['SCRIPT_NAME']."]:"." Sincronismo MailMan-RHDS falhou ao adicionar nova lista: php resposta do socket nula/invalida. Conteudo=  " . $dados_saida_socket; 
+				$retorno['status'] = false;
+				$retorno['msg'] = $msg_socket;
+				//Grava no logger o erro
+				$log = `/usr/bin/logger -p local5.notice -t Sinc-Listas-Mailman-RHDS '$msg_socket'`;
+				return $retorno;
+			}
+
+			//Encerra a conexï¿œo com o recurso remoto
+			socket_close($socket);	
+			
+			//Retorna um array contendo (true, dados serializados de processamento remoto)
+			return $dados_serializados_saida;		
+		}
+		//Usada para fazer rebind em caso de escrita em slave (quando volta uma referral)
+	}
+?>
Index: /branches/2.2/listAdmin/inc/class.uimaillists.inc.php
===================================================================
--- /branches/2.2/listAdmin/inc/class.uimaillists.inc.php	(revision 3514)
+++ /branches/2.2/listAdmin/inc/class.uimaillists.inc.php	(revision 3514)
@@ -0,0 +1,615 @@
+<?php
+	/*************************************************************************************\
+	* Expresso Administração                 										     *
+	* by Joao Alfredo Knopik Junior (joao.alfredo@gmail.com, jakjr@celepar.pr.gov.br)  	 *
+	* -----------------------------------------------------------------------------------*
+	*  This program is free software; you can redistribute it and/or modify it			 *
+	*  under the terms of the GNU General Public License as published by the			 *
+	*  Free Software Foundation; either version 2 of the License, or (at your			 *
+	*  option) any later version.														 *
+	\*************************************************************************************/
+
+	class uimaillists
+	{
+		var $public_functions = array
+		(
+			'list_maillists'	=> True,
+			'add_maillists'		=> True,
+			'edit_maillists'	=> True,
+			'scl_maillists'		=> True,
+			'adm_maillists'		=> True,
+			'css'			=> True
+		);
+
+		var $nextmatchs;
+		var $functions;
+			
+		function uimaillists()
+		{
+			$this->maillist		= CreateObject('listAdmin.maillist');
+			$this->functions	= CreateObject('listAdmin.functions');
+			$this->ldap_functions   = CreateObject('listAdmin.ldap_functions');
+			$this->nextmatchs	= CreateObject('phpgwapi.nextmatchs');
+
+			$c = CreateObject('phpgwapi.config','listAdmin');
+			$c->read_repository();
+			$this->current_config = $c->config_data;
+
+			if(!@is_object($GLOBALS['phpgw']->js))
+			{
+				$GLOBALS['phpgw']->js = CreateObject('phpgwapi.javascript');
+			}
+			$GLOBALS['phpgw']->js->validate_file('jscode','connector','listAdmin');#diretorio, arquivo.js, aplicacao
+			$GLOBALS['phpgw']->js->validate_file('jscode','expressoadmin','listAdmin');
+			$GLOBALS['phpgw']->js->validate_file('jscode','maillists','listAdmin');
+		}
+		
+		function list_maillists()
+		{
+			$account_lid = $GLOBALS['phpgw']->accounts->data['account_lid'];
+			//$acl = $this->functions->read_acl($account_lid);
+			$context = $GLOBALS['phpgw_info']['server']['ldap_context']; //$acl[0]['context'];
+			$context_display = ldap_dn2ufn($GLOBALS['phpgw_info']['server']['ldap_context']); //$acl[0]['context_display'];
+			
+			if(isset($_POST['query']))
+			{
+				// limit query to limit characters
+				if(eregi('^[a-z_0-9_%-].+$',$_POST['query'])) 
+					$GLOBALS['query'] = $_POST['query'];
+			}
+
+			unset($GLOBALS['phpgw_info']['flags']['noheader']);
+			unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
+			
+			$GLOBALS['phpgw_info']['flags']['app_header'] = $GLOBALS['phpgw_info']['apps']['listAdmin']['title'].' - '.lang('Email Lists');
+			$GLOBALS['phpgw']->common->phpgw_header();
+
+			$p = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
+			$p->set_file(array('maillists'   => 'maillists.tpl'));
+			$p->set_block('maillists','list','list');
+			$p->set_block('maillists','row','row');
+			$p->set_block('maillists','row_empty','row_empty');
+
+
+			//Pega o id do usuario atual da sessao
+			$usuarioAtual=$_SESSION['phpgw_info']['expresso']['user']['account_lid'];
+			//Pega o uidnumber do usuario atual
+			$admUidnumber = $this->ldap_functions->uid2uidnumber($usuarioAtual);
+
+			//Pega o email do usuario atual
+			$admlista = $this->ldap_functions->uidnumber2mail($admUidnumber);
+
+			$desabilitado = 'disabled';
+
+			if($this->ldap_functions->is_user_listAdmin($usuarioAtual) == 1)
+			{
+				$desabilitado = '';
+				$can_edit = True;
+				$can_delete = True;
+			}
+			else
+			{
+				$can_edit = True;
+				$can_delete = False;
+			}
+
+
+			// Seta as variaveis padroes.
+			$var = Array(
+				'th_bg'					=> $GLOBALS['phpgw_info']['theme']['th_bg'],
+				'back_url'				=> $GLOBALS['phpgw']->link('/listAdmin/index.php'),
+				'add_action'				=> $GLOBALS['phpgw']->link('/index.php','menuaction=listAdmin.uimaillists.add_maillists'),
+				'add_email_lists_disabled'		=> $this->functions->check_acl($account_lid,'add_maillists') ? '' : 'disabled',
+				'context'				=> $context,
+				'context_display'			=> $context_display,
+				'desabilitado'				=> $desabilitado,
+				'lang_email_lists_uid'			=> lang('Email Lists Logins'),
+				'lang_email_lists_names'		=> lang('Email Lists Names'),
+				'lang_add_email_lists'			=> lang('Add Email Lists'),
+				'lang_edit'  				=> lang('Edit'),
+				'lang_scl'  				=> 'SCL',
+				'lang_adm'  				=> 'ADM',
+				'lang_delete'				=> 'Excluir',
+				'lang_view'				=> lang('View'),
+				'lang_back'				=> lang('back'),
+				'lang_context'				=> lang('context'),
+				'lang_email'				=> lang('E-mail'),
+				'lang_search'				=> lang('search')
+			);
+			$p->set_var($var);
+
+			// Save query
+			$p->set_var('query', $GLOBALS['query']);
+
+			//Variavel recebe o contexto onde estao gravadas as listas no sistema;
+			$contextoListas = $this->current_config['dn_listas'];
+
+			$auto_list = $this->current_config['mm_ldap_query_automatic'];
+			if( ($auto_list == "true") && ($GLOBALS['query'] == '') )
+			{
+				//Retorna todas as listas que o usuario conectado administra
+				$maillists_info = $this->functions->auto_list('maillists', $contextoListas, $admlista);
+			}else {
+			//Admin make a search
+				if( ($GLOBALS['query'] != '') && (strlen($GLOBALS['query']) < 4) ) {
+					$p->set_var('message',lang('Search argument too short'));
+				}else if ($GLOBALS['query'] != ''){
+					//Retorna as listas que o usuario conectado administra, de acordo com o argumento de busca
+					$maillists_info = $this->functions->get_list('maillists', $GLOBALS['query'], $contextoListas, $admlista);
+				}
+			}
+
+			$total = count($maillists_info);
+
+
+			if (!count($total) && $GLOBALS['query'] != '')
+			{
+				$p->set_var('message',lang('No matches found'));
+			}
+			else if ($total)
+			{
+
+				foreach($maillists_info as $maillist)
+				{
+					$tr_color = $this->nextmatchs->alternate_row_color($tr_color);
+					$var = array(
+						'tr_color'		=> $tr_color,
+						'row_uid'		=> $maillist['uid'],
+						'row_name'		=> $maillist['name'],
+						'row_email'		=> $maillist['email']
+					);
+					$p->set_var($var);
+
+					if ($can_edit)
+					{
+						$p->set_var('edit_link',$this->row_action('edit','maillists',$maillist['uidnumber'],$maillist['uid']));
+						$p->set_var('scl_link',$this->row_action('scl','maillists',$maillist['uidnumber'],$maillist['uid']));
+						$p->set_var('adm_link',$this->row_action('adm','maillists',$maillist['uidnumber'],$maillist['uid']));
+					}
+					else
+					{
+						$p->set_var('edit_link','&nbsp;');
+						$p->set_var('scl_link','&nbsp;');
+						$p->set_var('adm_link','&nbsp;');
+					}
+
+					if ($can_delete)
+					{
+						$p->set_var('delete_link',"<a href='#' onClick='javascript:delete_maillist(\"".$maillist['uid']."\",\"".$maillist['uidnumber']."\",\"".$context."\");'>Excluir</a>");
+					}
+					else
+					{
+						$p->set_var('delete_link','&nbsp;');
+					}
+					
+					$p->fp('rows','row',True);
+				}
+			}
+			$p->parse('rows','row_empty',True);
+			$p->set_var($var);
+			$p->pfp('out','list');
+
+		}
+		
+		function add_maillists()
+		{
+			//$GLOBALS['phpgw']->js->set_onload('get_available_users(document.forms[0].org_context.value, document.forms[0].ea_check_allUsers.checked);');
+			
+			$account_lid = $GLOBALS['phpgw']->accounts->data['account_lid'];
+			//$acl = $this->functions->read_acl($account_lid);
+			//$context = $acl[0]['context'];
+			$context = $GLOBALS['phpgw_info']['server']['ldap_context']; //$acl[0]['context'];
+			//$context_display = ldap_dn2ufn($GLOBALS['phpgw_info']['server']['ldap_context']); //$acl[0]['context_display'];
+			
+			unset($GLOBALS['phpgw_info']['flags']['noheader']);
+			unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
+			$GLOBALS['phpgw_info']['flags']['app_header'] = $GLOBALS['phpgw_info']['apps']['listAdmin']['title'].' - '.lang('Create Email List');
+			$GLOBALS['phpgw']->common->phpgw_header();
+			
+			// Set o template
+			$p = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
+			$p->set_file(Array('create_maillist' => 'maillists_form.tpl'));
+
+			// Pega combo das organizações.
+			$org = $this->functions->get_organizations($context, '');
+
+			// Seta variaveis utilizadas pelo tpl.
+			$var = Array(
+				'color_bg1'					=> "#E8F0F0",
+				'color_bg2'					=> "#D3DCE3",
+				'type'						=> 'create_maillist',
+				'ldap_context'					=> $GLOBALS['phpgw_info']['server']['ldap_context'],
+				'uid'						=> 'lista-',
+				'exibir_div'					=> ' style="display: none;" ',
+				'accountStatus_checked'				=> 'CHECKED',
+//				'defaultMemberModeration_checked'		=> 'CHECKED',	
+				'accountAdm_checked'				=> 'CHECKED',
+				'restrictionsOnEmailLists'			=> $this->current_config['expressoAdmin_restrictionsOnEmailLists'],
+				'lang_back'					=> lang('Back'),
+				'lang_save'					=> lang('save'),
+				'lang_org'					=> lang('Organizations'),
+				'lang_maillist_uid'				=> lang('Maillist login'),
+				'lang_maillist_mail'				=> lang('Maillist Mail'),
+				'lang_maillist_name'				=> lang('Maillist name'),
+				'lang_maillist_description'			=> lang('Maillist description'),
+				'lang_maillist_users'				=> lang('Maillist users'),
+				'lang_add_user'					=> lang('Add User'),
+				'lang_rem_user'					=> lang('Remove User'),
+				'lang_all_users'				=> lang('Show users from all sub-organizations'),
+				'back_url'					=> $GLOBALS['phpgw']->link('/index.php','menuaction=listAdmin.uimaillists.list_maillists'),
+				'combo_org'					=> $org,
+				'ea_select_usersInMaillist'			=> $ea_select_usersInMaillist
+			);
+			$p->set_var($var);
+			
+			$p->pfp('out','create_maillist');
+		}
+		
+		
+		function edit_maillists()
+		{
+	
+			$GLOBALS['phpgw']->js->set_onload('get_available_users(document.forms[0].org_context.value, document.forms[0].ea_check_allUsers.checked);');
+			
+			$account_lid = $GLOBALS['phpgw']->accounts->data['account_lid'];
+			//$acl = $this->functions->read_acl($account_lid);
+			//$manager_context = $acl[0]['context'];
+			$manager_context = $GLOBALS['phpgw_info']['server']['ldap_context']; //$acl[0]['context'];
+			//$context_display = ldap_dn2ufn($GLOBALS['phpgw_info']['server']['ldap_context']); //$acl[0]['context_display'];
+			
+
+			//Teste o tipo de lista que esta sendo editada (corporativa ou funcional);
+			$uid_lista = $_GET['maillist_uid']; //recebe o uid da lista selecionada;
+			$str = explode("-", $uid_lista); //separa pelo "-";
+			$str = $str[0]; //pega o primeiro elemento, que neste caso e o que indica o tipo de lista
+
+			$somente_leitura = "";
+			$desabilitado = "";
+			if(($str == "listacorp") || ($str == "listafunc")) {
+				$somente_leitura = "readonly"; //se lista for corp ou func, a variavel recebe readonly - sera usada em todos os input do form de edicao de listas;
+				$desabilitado = "disabled";
+			}
+
+			//Pega o id do administrador do Expresso (expresso-admin)
+			$expressoAdmin 						= $GLOBALS['phpgw_info']['server']['header_admin_user'];
+
+			//Pega o id do usuario atual da sessao
+			$usuarioAtual 						= $_SESSION['phpgw_info']['expresso']['user']['account_lid'];
+
+			if($expressoAdmin != $usuarioAtual) {
+
+				$soAdminLe = "readonly"; //se usuarioAtual for diferente de expressoAdmin, a variavel recebe readonly - sera usada nos input com uid, mail e cn da lista;
+
+			}
+
+
+
+
+			// GET all infomations about the group.
+			$maillist_info = $this->maillist->get_info($_GET['uidnumber'], $manager_context);
+			// debug_array($maillist_info);
+					
+	
+			unset($GLOBALS['phpgw_info']['flags']['noheader']);
+			unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
+			$GLOBALS['phpgw_info']['flags']['app_header'] = $GLOBALS['phpgw_info']['apps']['listAdmin']['title'].' - '.lang('Edit Email Lists');
+			$GLOBALS['phpgw']->common->phpgw_header();
+
+			// Set o template
+			$p = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
+			$p->set_file(Array('edit_maillist' => 'maillists_form.tpl'));
+
+			// Pega combo das organizações e seleciona a org da lista.
+			$org = $this->functions->get_organizations($manager_context, trim(strtolower($maillist_info['context'])));
+
+			// Usuarios da lista.
+			if (count($maillist_info['members_info']) > 0)
+			{
+				foreach ($maillist_info['members_info'] as $uidnumber=>$userinfo)
+				{
+					$array_users[$uidnumber] = $userinfo['cn'];
+					$array_users_uid[$uidnumber] = $userinfo['uid'];
+					$array_users_type[$uidnumber] = $userinfo['type'];
+				}
+				natcasesort($array_users);
+				foreach ($array_users as $uidnumber=>$cn)
+				{
+					if ($array_users_type[$uidnumber] == 'u')
+					{
+						//$users .= "<option value=" . $uidnumber . ">" . $cn .  " [" . $array_users_uid[$uidnumber] . "]</option>";
+						$users .= "<option value=" . $uidnumber . ">" . $cn .  " [" . $maillist_info['members_info'][$uidnumber]['mail'] . "]</option>";
+					}
+					elseif ($array_users_type[$uidnumber] == 'l')
+					{
+						$lists .= "<option value=" . $uidnumber . ">" . $cn .  " [" . $array_users_uid[$uidnumber] . "]</option>";
+					}
+					else
+					{
+						$unknow .= "<option value=" . $uidnumber . ">" . $cn .  " [" . $array_users_uid[$uidnumber] . "]</option>";
+					}
+				}
+				
+				if ($unknow != '')
+				{
+					//$opt_tmp_unknow = '<option  value="-1" disabled>--------------------&nbsp;&nbsp;&nbsp;&nbsp;E-mails não encontrados&nbsp;&nbsp;&nbsp;&nbsp;------------------ </option>'."\n";
+					$opt_tmp_unknow = '<option  value="-1" disabled>-----------&nbsp;&nbsp;&nbsp;Usu&aacute;rios n&atilde;o pertencentes ou n&atilde;o criados no Expresso&nbsp;&nbsp;&nbsp;---------- </option>'."\n";
+					$ea_select_usersInMaillist .= $opt_tmp_unknow . $unknow;
+				}
+				if ($lists != '')
+				{
+					$opt_tmp_lists  = '<option  value="-1" disabled>------------------------------&nbsp;&nbsp;&nbsp;&nbsp;Listas&nbsp;&nbsp;&nbsp;&nbsp;------------------------------ </option>'."\n";
+					$ea_select_usersInMaillist .= $opt_tmp_lists . $lists;
+				}
+				$opt_tmp_users  = '<option  value="-1" disabled>-----------------------------&nbsp;&nbsp;&nbsp;&nbsp;Usuários&nbsp;&nbsp;&nbsp;&nbsp;---------------------------- </option>'."\n";
+				$ea_select_usersInMaillist .= $opt_tmp_users . $users;
+			}
+
+			// Seta variaveis utilizadas pelo tpl.
+			$var = Array(
+				'color_bg1'					=> "#E8F0F0",
+				'color_bg2'					=> "#D3DCE3",
+				'type'						=> 'edit_maillist',
+				'ldap_context'					=> $GLOBALS['phpgw_info']['server']['ldap_context'],
+				'lang_back'					=> lang('Back'),
+				'lang_save'					=> lang('save'),
+				'lang_org'					=> lang('Organizations'),
+				'lang_maillist_uid'				=> lang('Maillist login'),
+				'lang_maillist_mail'				=> lang('Maillist Mail'),
+				'lang_maillist_name'				=> lang('Maillist name'),
+				'lang_maillist_users'				=> lang('Maillist users'),
+				'lang_maillist_description'			=> lang('Maillist description'),
+				'lang_add_user'					=> lang('Add User'),
+				'lang_rem_user'					=> lang('Remove User'),
+				'lang_all_users'				=> lang('Select users from all sub-organizations'),
+				'back_url'					=> $GLOBALS['phpgw']->link('/index.php','menuaction=listAdmin.uimaillists.list_maillists'),
+//				'back_url'					=> $GLOBALS['phpgw']->link('/index.php','menuaction=listAdmin.uimaillists.list_maillists'),
+				'combo_org'					=> $org,
+				'manager_context'				=> $manager_context,
+				'somente_leitura'				=> $somente_leitura, //recebe a variavel testada acima;
+				'desabilitado'					=> $desabilitado, //recebe a variavel testada acima;
+				'soAdminLe'					=> $soAdminLe, //recebe a variavel testada acima;
+				'uidnumber'					=> $_GET['uidnumber'],
+				'uid'						=> $maillist_info['uid'],
+				'defaultMemberModeration'			=> $maillist_info['defaultMemberModeration'],
+				'admlista'					=> $maillist_info['admlista'],
+				'listPass'					=> $maillist_info['listPass'],
+				'exibir_div'					=> '',
+				'mail'						=> $maillist_info['mail'],
+				'description'					=> $maillist_info['description'],
+				'cn'						=> $maillist_info['cn'],
+				'accountStatus_checked'				=> $maillist_info['accountStatus'] == 'active' ? 'CHECKED' : '',
+				'accountAdm_checked'            		=> $maillist_info['accountAdm'] == 'active' ? 'CHECKED' : '',
+
+				'phpgwAccountVisible_checked'			=> $maillist_info['phpgwAccountVisible'] == '-1' ? 'CHECKED' : '',
+				'defaultMemberModeration_checked'               => $maillist_info['defaultMemberModeration'] == '1' ? 'CHECKED' : '',
+				'ea_select_usersInMaillist'			=> $ea_select_usersInMaillist
+			);
+			$p->set_var($var);
+			
+			$p->pfp('out','edit_maillist');
+		}
+		
+		function adm_maillists() //Funcao que trata do modulo/template de administradores de listas
+		{
+	
+//			$GLOBALS['phpgw']->js->set_onload('get_available_users_only(document.forms[0].org_context.value, document.forms[0].ea_check_allUsers.checked);');
+			
+			$account_lid = $GLOBALS['phpgw']->accounts->data['account_lid'];
+			//$acl = $this->functions->read_acl($account_lid);
+			//$manager_context = $acl[0]['context'];
+			$manager_context = $GLOBALS['phpgw_info']['server']['ldap_context']; //$acl[0]['context'];
+			//$context_display = ldap_dn2ufn($GLOBALS['phpgw_info']['server']['ldap_context']); //$acl[0]['context_display'];
+			
+			//Teste o tipo de lista que esta sendo editada (corporativa ou funcional);
+			$uid_lista = $_GET['maillist_uid']; //recebe o uid da lista selecionada;
+			$str = explode("-", $uid_lista); //separa pelo "-";
+			$str = $str[0]; //pega o primeiro elemento, que neste caso e o que indica o tipo de lista
+
+			$somente_leitura = "";
+			$desabilitado = "";
+			if(($str == "listacorp") || ($str == "listafunc")) {
+				$somente_leitura = "readonly"; //se lista for corp ou func, a variavel recebe readonly - sera usada nos input com uid, mail e cn da lista;
+				$desabilitado = "disabled";
+			}
+
+
+			// GET all infomations about the group.
+			$maillist_info = $this->maillist->get_adm_info($_GET['uidnumber'], $manager_context);
+			// debug_array($maillist_info);
+					
+	
+			unset($GLOBALS['phpgw_info']['flags']['noheader']);
+			unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
+			$GLOBALS['phpgw_info']['flags']['app_header'] = $GLOBALS['phpgw_info']['apps']['listAdmin']['title'].' - '.lang('Admin Lists');
+			$GLOBALS['phpgw']->common->phpgw_header();
+
+			// Set o template
+			$p = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
+			$p->set_file(Array('adm_maillist' => 'maillists_adm.tpl'));
+
+			// Pega combo das organizações e seleciona a org da lista.
+			$org = $this->functions->get_organizations($manager_context, trim(strtolower($maillist_info['context'])));
+
+			// Usuarios da lista.
+			if (count($maillist_info['members_info']) > 0)
+			{
+				foreach ($maillist_info['members_info'] as $uidnumber=>$userinfo)
+				{
+					$array_users[$uidnumber] = $userinfo['cn'];
+					$array_users_uid[$uidnumber] = $userinfo['uid'];
+					$array_users_type[$uidnumber] = $userinfo['type'];
+				}
+				natcasesort($array_users);
+				foreach ($array_users as $uidnumber=>$cn)
+				{
+					if ($array_users_type[$uidnumber] == 'u')
+					{
+//						$users .= "<option value=" . $uidnumber . ">" . $cn .  " [" . $array_users_uid[$uidnumber] . "]</option>";
+						$users .= "<option value=" . $uidnumber . ">" . $cn .  " [" . $maillist_info['members_info'][$uidnumber]['mail'] . "]</option>";
+					}
+					else
+					{
+						$unknow .= "<option value=" . $uidnumber . ">" . $cn .  " [" . $array_users_uid[$uidnumber] . "]</option>";
+					}
+				}
+				
+				if ($unknow != '')
+				{
+					//$opt_tmp_unknow = '<option  value="-1" disabled>--------------------&nbsp;&nbsp;&nbsp;&nbsp;E-mails não encontrados&nbsp;&nbsp;&nbsp;&nbsp;------------------ </option>'."\n";
+					$opt_tmp_unknow = '<option  value="-1" disabled>-----------&nbsp;&nbsp;&nbsp;Usu&aacute;rios n&atilde;o pertencentes ou n&atilde;o criados no Expresso&nbsp;&nbsp;&nbsp;---------- </option>'."\n";
+					$ea_select_ADM_Maillist .= $opt_tmp_unknow . $unknow;
+				}
+				$opt_tmp_users  = '<option  value="-1" disabled>-----------------------------&nbsp;&nbsp;&nbsp;&nbsp;Usuários&nbsp;&nbsp;&nbsp;&nbsp;---------------------------- </option>'."\n";
+				$ea_select_ADM_Maillist .= $opt_tmp_users . $users;
+			}
+
+			// Seta variaveis utilizadas pelo tpl.
+			$var = Array(
+				'color_bg1'					=> "#E8F0F0",
+				'color_bg2'					=> "#D3DCE3",
+				'type'						=> 'adm_maillist',
+				'ldap_context'					=> $GLOBALS['phpgw_info']['server']['ldap_context'],
+				'dn_listas'					=> $GLOBALS['phpgw_info']['server']['dn_listas'],
+				'lang_back'					=> lang('Back'),
+				'lang_save'					=> lang('save'),
+				'lang_org'					=> lang('Organizations'),
+				'lang_maillist_uid'				=> lang('Maillist login'),
+				'lang_maillist_mail'				=> lang('Maillist Mail'),
+				'lang_maillist_name'				=> lang('Maillist name'),
+				'lang_maillist_description'			=> lang('Maillist description'),
+				'lang_maillist_users'				=> lang('Maillist users'),
+				'lang_maillist_adm'				=> lang('Maillist adm'),
+				'lang_add_user'					=> lang('Add User'),
+				'lang_rem_user'					=> lang('Remove User'),
+				'lang_all_users'				=> lang('Select users from all sub-organizations'),
+				'back_url'					=> $GLOBALS['phpgw']->link('/index.php','menuaction=listAdmin.uimaillists.list_maillists'),
+				'combo_org'					=> $org,
+				'teste'						=> $maillist_info['context'],
+				'manager_context'				=> $manager_context,
+				'uidnumber'					=> $_GET['uidnumber'],
+				'uid'						=> $maillist_info['uid'],
+				'admlista'					=> $maillist_info['admlista'],
+				'somente_leitura'				=> $somente_leitura, //recebe a variavel testada acima;
+				'desabilitado'					=> $desabilitado, //recebe a variavel testada acima;
+				'mail'						=> $maillist_info['mail'],
+				'cn'						=> $maillist_info['cn'],
+				'description'					=> $maillist_info['description'],
+				'accountStatus_checked'				=> $maillist_info['accountStatus'] == 'active' ? 'CHECKED' : '',
+				'accountAdm_checked'            		=> $maillist_info['accountAdm'] == 'active' ? 'CHECKED' : '',
+
+				'phpgwAccountVisible_checked'			=> $maillist_info['phpgwAccountVisible'] == '-1' ? 'CHECKED' : '',
+				'ea_select_ADM_Maillist'			=> $ea_select_ADM_Maillist
+			);
+
+			$p->set_var($var);
+			
+			$p->pfp('out','adm_maillist');
+		}
+
+		function scl_maillists()
+		{
+			$GLOBALS['phpgw']->js->set_onload('get_available_users(document.forms[0].org_context.value, document.forms[0].ea_check_allUsers.checked);');
+			
+			$account_lid = $GLOBALS['phpgw']->accounts->data['account_lid'];
+			//$acl = $this->functions->read_acl($account_lid);
+			//$manager_context = $acl[0]['context'];
+			$manager_context = $GLOBALS['phpgw_info']['server']['ldap_context']; //$acl[0]['context'];
+			//$context_display = ldap_dn2ufn($GLOBALS['phpgw_info']['server']['ldap_context']); //$acl[0]['context_display'];
+			
+			//Teste o tipo de lista que esta sendo editada (corporativa ou funcional);
+			$uid_lista = $_GET['maillist_uid']; //recebe o uid da lista selecionada;
+			$str = explode("-", $uid_lista); //separa pelo "-";
+			$str = $str[0]; //pega o primeiro elemento, que neste caso e o que indica o tipo de lista
+
+			$somente_leitura = "";
+			$desabilitado = "";
+			if(($str == "listacorp") || ($str == "listafunc")) {
+				$somente_leitura = "readonly"; //se lista for corp ou func, a variavel recebe readonly - sera usada nos input com uid, mail e cn da lista;
+				$desabilitado = "disabled";
+			}
+
+			// GET all infomations about the group.
+			$maillist_info = $this->maillist->get_scl_info($_GET['uidnumber'], $manager_context);
+			//_debug_array($maillist_info);
+			
+			unset($GLOBALS['phpgw_info']['flags']['noheader']);
+			unset($GLOBALS['phpgw_info']['flags']['nonavbar']);
+			$GLOBALS['phpgw_info']['flags']['app_header'] = $GLOBALS['phpgw_info']['apps']['listAdmin']['title'].' - '.lang('Edit Sending Control List');
+			$GLOBALS['phpgw']->common->phpgw_header();
+
+			// Set o template
+			$p = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
+			$p->set_file(Array('sql_maillist' => 'maillists_scl.tpl'));
+
+			// Pega combo das organizações e seleciona a org da lista.
+			$org = $this->functions->get_organizations($manager_context, trim(strtolower($maillist_info['context'])));
+
+			// Usuarios de senders.
+			if (count($maillist_info['senders_info']) > 0)
+			{
+				foreach ($maillist_info['senders_info'] as $uidnumber=>$senderinfo)
+				{
+					$array_senders[$uidnumber] = $senderinfo['cn'];
+				}
+				natcasesort($array_senders);
+				foreach ($array_senders as $uidnumber=>$cn)
+				{
+					$ea_select_users_SCL_Maillist .= "<option value=" . $uidnumber . ">" . $cn . " [" . $maillist_info['senders_info'][$uidnumber]['mail'] . "]</option>";
+				}
+			}
+
+			// Seta variaveis utilizadas pelo tpl.
+			$var = Array(
+				'color_bg1'					=> "#E8F0F0",
+				'color_bg2'					=> "#D3DCE3",
+				'type'						=> 'edit_maillist',
+				'ldap_context'					=> $GLOBALS['phpgw_info']['server']['ldap_context'],
+				'dn'						=> $maillist_info['dn'],
+				'lang_back'					=> lang('Back'),
+				'lang_save'					=> lang('save'),
+				'lang_org'					=> lang('Organizations'),
+				'lang_maillist_uid'				=> lang('Maillist login'),
+				'lang_maillist_mail'				=> lang('Maillist Mail'),
+				'lang_maillist_name'				=> lang('Maillist name'),
+				'lang_maillist_description'			=> lang('Maillist description'),
+				'lang_maillist_users'				=> lang('Maillist users'),
+				'lang_add_user'					=> lang('Add User'),
+				'lang_rem_user'					=> lang('Remove User'),
+				'lang_all_users'				=> lang('Show users from all sub-organizations'),
+				'back_url'					=> $GLOBALS['phpgw']->link('/index.php','menuaction=listAdmin.uimaillists.list_maillists'),
+				'combo_org'					=> $org,
+				'manager_context'				=> $manager_context,
+				'uidnumber'					=> $_GET['uidnumber'],
+				'uid'						=> $maillist_info['uid'],
+				'mail'						=> $maillist_info['mail'],
+				'cn'						=> $maillist_info['cn'],
+				'description'					=> $maillist_info['description'],
+				'admlista'					=> $maillist_info['admlista'],
+				'somente_leitura'				=> $somente_leitura, //recebe a variavel testada acima;
+				'desabilitado'					=> $desabilitado, //recebe a variavel testada acima;
+				'listPass'					=> $maillist_info['listPass'],
+				'accountRestrictive_checked'			=> $maillist_info['accountRestrictive'] == 'mailListRestriction' ? 'CHECKED' : '',
+				'participantCanSendMail_checked'		=> $maillist_info['participantCanSendMail'] == 'TRUE' ? 'CHECKED' : '',
+				'ea_select_users_SCL_Maillist'			=> $ea_select_users_SCL_Maillist
+			);
+			$p->set_var($var);
+			
+			$p->pfp('out','sql_maillist');
+		}
+	
+		function row_action($action,$type,$uidnumber,$maillist_uid)
+		{
+			return '<a href="'.$GLOBALS['phpgw']->link('/index.php',Array(
+				'menuaction'					=> 'listAdmin.uimaillists.'.$action.'_'.$type,
+				'uidnumber'					=> $uidnumber,
+				'maillist_uid'					=> $maillist_uid
+				)).'"> '.lang($action).' </a>';
+		}
+		
+		function css()
+		{
+			$appCSS = '';
+			return $appCSS;
+		}
+	}
+?>
Index: /branches/2.2/listAdmin/inc/hook_admin.inc.php
===================================================================
--- /branches/2.2/listAdmin/inc/hook_admin.inc.php	(revision 3514)
+++ /branches/2.2/listAdmin/inc/hook_admin.inc.php	(revision 3514)
@@ -0,0 +1,25 @@
+<?php
+  /***************************************************************************\
+  * eGroupWare - Contacts Center                                              *
+  * http://www.egroupware.org                                                 *
+  * Written by:                                                               *
+  *  - Raphael Derosso Pereira <raphaelpereira@users.sourceforge.net>         *
+  *  sponsored by Thyamad - http://www.thyamad.com
+  * ------------------------------------------------------------------------- *
+  *  This program is free software; you can redistribute it and/or modify it  *
+  *  under the terms of the GNU General Public License as published by the    *
+  *  Free Software Foundation; either version 2 of the License, or (at your   *
+  *  option) any later version.                                               *
+  \***************************************************************************/
+
+	// Only Modify the $file and $title variables.....
+	$title = $appname;
+	$file = Array(
+		'Global Configuration' => $GLOBALS['phpgw']->link('/index.php','menuaction=admin.uiconfig.index&appname=' . $appname),
+		//'Edit custom fields' => $GLOBALS['phpgw']->link('/index.php','menuaction=addressbook.uifields.index'),
+		//'Global Categories' => $GLOBALS['phpgw']->link('/index.php','menuaction=admin.uicategories.index&appname=addressbook')
+	);
+	//Do not modify below this line
+	display_section($appname,$file);
+
+?>
Index: /branches/2.2/listAdmin/inc/class.functions.inc.php
===================================================================
--- /branches/2.2/listAdmin/inc/class.functions.inc.php	(revision 3514)
+++ /branches/2.2/listAdmin/inc/class.functions.inc.php	(revision 3514)
@@ -0,0 +1,845 @@
+<?php
+	/**********************************************************************************\
+	* Expresso Administraï¿œï¿œo                 									      *
+	* by Joao Alfredo Knopik Junior (joao.alfredo@gmail.com, jakjr@celepar.pr.gov.br) *
+	* --------------------------------------------------------------------------------*
+	*  This program is free software; you can redistribute it and/or modify it		  *
+	*  under the terms of the GNU General Public License as published by the		  *
+	*  Free Software Foundation; either version 2 of the License, or (at your		  *
+	*  option) any later version.													  *
+	\**********************************************************************************/
+	
+	include_once('class.db_functions.inc.php');
+
+	class functions
+	{
+		
+		var $public_functions = array
+		(
+			'make_array_acl' 	=> True,
+			'check_acl'		=> True,
+			'read_acl'		=> True,
+			'exist_account_lid'	=> True,
+			'exist_email'		=> True,
+			'array_invert'		=> True
+		);
+		
+		var $nextmatchs;
+		var $sectors_list = array();
+		
+		function functions()
+		{
+			$this->db_functions = new db_functions;
+		}
+	
+
+		// Account and type of access. Return: Have access ? (true/false)
+		function check_acl($account_lid, $access)
+		{
+			$acl = $this->read_acl($account_lid);
+			$array_acl = $this->make_array_acl($acl[0][acl]);
+			
+			//What access ?? In the IF, verify if have access.
+			switch($access)
+			{
+				case list_users:
+					if ($array_acl[add_users] || $array_acl[edit_users] || $array_acl[delete_users] || $array_acl[change_users_password] || $array_acl[change_users_quote] || $array_acl[edit_sambausers_attributes] || $array_acl[view_users])
+						return true;
+					break;
+				case add_users:
+					if ($array_acl[add_users])
+						return true;
+					break;
+				case edit_users:
+					if ($array_acl[edit_users])
+						return true;
+					break;
+				case delete_users:
+					if ($array_acl[delete_users])
+						return true;
+					break;
+				case rename_users:
+					if ($array_acl[rename_users])
+						return true;
+					break;
+				case view_users:
+					if ($array_acl[view_users])
+						return true;
+					break;
+				case change_users_password:
+					if ($array_acl[change_users_password])
+						return true;
+					break;
+				case change_users_quote:
+					if ($array_acl[change_users_quote])
+						return true;
+					break;
+				case set_user_default_password:
+					if ($array_acl[set_user_default_password])
+						return true;
+					break;
+				case edit_sambausers_attributes:
+					if ($array_acl[edit_sambausers_attributes])
+						return true;
+					break;
+				case edit_sambadomains:
+					if ($array_acl[edit_sambadomains])
+						return true;
+					break;
+				
+				case list_groups:
+					if ($array_acl[add_groups] || $array_acl[edit_groups] || $array_acl[delete_groups])
+						return true;
+					break;
+				case add_groups:
+					if ($array_acl[add_groups])
+						return true;
+					break;
+				case edit_groups:
+					if ($array_acl[edit_groups])
+						return true;
+					break;
+				case delete_groups:
+					if ($array_acl[delete_groups])
+						return true;
+					break;
+				case edit_email_groups:
+					if ($array_acl[edit_email_groups])
+						return true;
+					break;
+				
+				case list_maillists:
+					if ($array_acl[add_maillists] || $array_acl[edit_maillists] || $array_acl[adm_maillists] || $array_acl[delete_maillists])
+						return true;
+					break;
+				case add_maillists:
+					if ($array_acl[add_maillists])
+						return true;
+					break;
+				case edit_maillists:
+					if ($array_acl[edit_maillists])
+						return true;
+					break;
+				case adm_maillists:
+					if ($array_acl[adm_maillists])
+						return true;
+					break;
+				case delete_maillists:
+					if ($array_acl[delete_maillists])
+						return true;
+					break;
+
+				case list_sectors:
+					if ($array_acl[create_sectors] || $array_acl[edit_sectors] || $array_acl[delete_sectors])
+						return true;
+					break;
+				case create_sectors:
+					if ($array_acl[create_sectors])
+						return true;
+					break;
+				case edit_sectors:
+					if ($array_acl[edit_sectors])
+						return true;
+					break;
+				case delete_sectors:
+					if ($array_acl[delete_sectors])
+						return true;
+					break;
+
+				case view_global_sessions:
+					if ($array_acl[view_global_sessions])
+						return true;
+					break;
+
+				case list_computers:
+					if ($array_acl[create_computers] || $array_acl[edit_computers] || $array_acl[delete_computers])
+						return true;
+					break;
+				case create_computers:
+					if ($array_acl[create_computers])
+						return true;
+					break;
+				case edit_computers:
+					if ($array_acl[edit_computers])
+						return true;
+					break;
+				case delete_computers:
+					if ($array_acl[delete_computers])
+						return true;
+					break;
+
+				case view_logs:
+					if ($array_acl[view_logs])
+						return true;
+					break;
+
+				default:
+					return false; 	
+			}
+			
+			return false;
+		}
+		
+		// Read acl from db
+		function read_acl($account_lid)
+		{ 
+			$result = $this->db_functions->read_acl($account_lid);
+			$context_array = ldap_explode_dn($result[0]['context'], 1);
+			$result[0]['context_display'] = ldap_dn2ufn ( $result[0]['context'] );
+			return $result;
+		}
+		
+		// Make a array read humam
+		// Last acl:	33.554.432, 67.108.864
+		function make_array_acl($acl)
+		{
+			$array_acl['add_users'] = $acl & 1;
+			$array_acl['edit_users'] = $acl & 2;
+			$array_acl['delete_users'] = $acl & 4;
+			$array_acl['rename_users'] = $acl & 8388608;
+			$array_acl['view_users'] = $acl & 33554432;
+			$array_acl['add_groups'] = $acl & 16;
+			$array_acl['edit_groups'] = $acl & 32;
+			$array_acl['delete_groups'] = $acl & 64;
+			$array_acl['edit_email_groups'] = $acl & 67108864;
+			$array_acl['change_users_password'] = $acl & 128;
+			$array_acl['change_users_quote'] = $acl & 262144;
+			$array_acl['set_user_default_password'] = $acl & 524288;
+			$array_acl['edit_sambausers_attributes'] = $acl & 32768;
+			$array_acl['edit_sambadomains'] = $acl & 16777216;
+			$array_acl['add_maillists'] = $acl & 256;
+			$array_acl['edit_maillists'] = $acl & 512;
+			$array_acl['delete_maillists'] = $acl & 1024;
+			$array_acl['adm_maillists'] = $acl & 2048;
+			$array_acl['create_sectors'] = $acl & 4096;
+			$array_acl['edit_sectors'] = $acl & 8192;
+			$array_acl['delete_sectors'] = $acl & 16384;
+			$array_acl['view_global_sessions'] = $acl & 65536;
+			$array_acl['view_logs'] = $acl & 131072;
+			$array_acl['create_computers'] = $acl & 1048576;
+			$array_acl['edit_computers'] = $acl & 2097152;
+			$array_acl['delete_computers'] = $acl & 4194304;
+			return $array_acl;
+		}
+
+		function auto_list($type, $context, $admlista)
+		{
+			$common = new common();
+			$ldap_conn = $GLOBALS['phpgw']->common->ldapConnect();
+
+			if ($type == 'maillists')
+			{
+				
+				//filtro de busca das listas de e-mail, busca apenas as listas permitidas ao usuario conectado;
+				//$context = $GLOBALS['phpgw_info']['server']['ldap_context'];
+				$filter="(&(phpgwAccountType=l)(admlista=$admlista)(|(cn=*)(uid=*)))";
+				$justthese = array("uidnumber", "cn", "uid", "mail");
+				$search=ldap_search($ldap_conn, $context, $filter, $justthese);
+				ldap_sort($ldap_conn, $search, "uid");
+				$info = ldap_get_entries($ldap_conn, $search);
+				ldap_close($ldap_conn);
+
+				$i = 0;
+				$tmp = array();
+				for ($i=0; $i < $info['count']; $i++)
+				{
+					$tmp[$i]['uid'] 		= $info[$i]['uid'][0];
+					$tmp[$i]['name'] 		= $info[$i]['cn'][0];
+					$tmp[$i]['uidnumber']		= $info[$i]['uidnumber'][0];
+					$tmp[$i]['email']		= $info[$i]['mail'][0];
+				}
+				return $tmp;
+			}
+		}
+
+		function get_list($type, $query, $context, $admlista)
+		{
+			$common = new common();
+			$ldap_conn = $GLOBALS['phpgw']->common->ldapConnect();//$common->ldapConnect();
+			if ($type == 'accounts')
+			{
+				$justthese = array("uidnumber", "uid", "cn", "mail", "objectclass");
+				//$filter="(&(phpgwAccountType=u)(|(uid=*".$query."*)(sn=*".$query."*)(cn=*".$query."*)(givenName=*".$query."*)(mail=$query*)(mailAlternateAddress=$query*)))";
+				//$filter="(&(objectclass=".$GLOBALS['phpgw_info']['server']['atributousuarios'].")(|(uid=*".$query."*)(sn=*".$query."*)(cn=*".$query."*)(givenName=*".$query."*)(mail=$query*)))";
+				$filter="(&(objectclass=".$GLOBALS['phpgw_info']['server']['atributousuarios'].")(|(uid=*".$query."*)(sn=*".$query."*)(cn=*".$query."*)(givenName=*".$query."*)(mail=$query*)))";
+				$search=ldap_search($ldap_conn, $context, $filter, $justthese);
+				ldap_sort($ldap_conn, $search, "cn");
+				$info = ldap_get_entries($ldap_conn, $search);
+				ldap_close($ldap_conn);
+				
+				$i = 0;
+				$tmp = array();
+				$ldap_found=false;
+				for ($i=0; $i < $info['count']; $i++)
+					{
+					$tmp[$i][account_id]			= $info[$i]['uidnumber'][0]; 
+					$tmp[$i][account_lid] 			= $info[$i]['uid'][0];
+					$tmp[$i][account_cn] 			= $info[$i]['cn'][0];
+					$tmp[$i][account_mail] 			= $info[$i]['mail'][0];
+					$tmp[$i][account_expresso] 		= false;
+					$tmp[$i][account_deleted] 		= false;
+					$ldap_found=true;
+					foreach ($info[$i]['objectclass'] as $objectclass)
+						{
+						if (strcasecmp($objectclass, 'phpgwaccount') == 0)
+							{
+							$tmp[$i][account_expresso] = true;
+							}
+						}
+					//$tmp[$i][account_expresso] = true;
+					}
+				// fazendo a pesquisa tambem no banco de dados
+				// eh cpf?
+				if ((strlen($query) == 11)and(!$ldap_found))
+					{
+					// inferindo o uidnumber
+					$uidnumber=substr($query,0,strlen($query)-2);
+					while (strpos($uidnumber,'0')===0)
+						{
+						$uidnumber=substr($uidnumber,1);
+						}
+					// consulta pelo uidnumber na tabela das acls					
+					$sql="SELECT DISTINCT acl_account FROM phpgw_acl WHERE acl_account='".$uidnumber."'";
+					$GLOBALS['phpgw']->db->query($sql);
+                        		while($GLOBALS['phpgw']->db->next_record())
+						{
+						$find=false;
+						foreach ($tmp as $ldap)
+							{
+							if ($ldap[account_id] == $GLOBALS['phpgw']->db->f(0))
+								{
+								$find=true;
+								}
+							}
+						if (!$find)
+							{
+							$tmp[$i][account_id]                    = $GLOBALS['phpgw']->db->f(0);
+				                	$tmp[$i][account_lid]                   = $query;
+				                	$tmp[$i][account_cn]                    = "Nao encontrado no RHDS";
+				                	$tmp[$i][account_mail]                  = "Nao encontrado no RHDS";
+							$tmp[$i][account_expresso]              = false;
+					                $tmp[$i][account_deleted]               = true;
+							++$i;
+							}
+						}
+					}
+                        							
+				return $tmp;
+			}
+			elseif($type == 'groups')
+			{
+				$filter="(&(phpgwAccountType=g)(cn=*".$query."*))";
+				$justthese = array("gidnumber", "cn", "description");
+				$search=ldap_search($ldap_conn, $context, $filter, $justthese);
+				ldap_sort($ldap_conn, $search, "cn");
+				$info = ldap_get_entries($ldap_conn, $search);				
+				ldap_close($ldap_conn);
+				
+				$i = 0;
+				$tmp = array();
+				for ($i=0; $i < $info['count']; $i++)
+				{
+					$tmp[$i][cn] 			= $info[$i][cn][0];
+					$tmp[$i][description]	= $info[$i][description][0];
+					$tmp[$i][gidnumber]		= $info[$i][gidnumber][0];
+				}
+				return $tmp;
+			}
+			elseif($type == 'maillists')
+			{
+
+//				$filter="(&(phpgwAccountType=l)(|(cn=*".$query."*)(uid=*".$query."*)(mail=*".$query."*)))";
+//				$filter="(&(phpgwAccountType=l)(|(cn=*".$query."*)(uid=*".$query."*)(mail=*".$query."*)(admlista=$admlista)))";
+
+				//filtro de busca das listas de e-mail, busca apenas as listas permitidas ao usuario conectado;
+				$context = $GLOBALS['phpgw_info']['server']['ldap_context'];
+				$filter="(&(phpgwAccountType=l)(admlista=$admlista)(|(cn=*".$query."*)(uid=*".$query."*)))";
+				$justthese = array("uidnumber", "cn", "uid", "mail");
+				$search=ldap_search($ldap_conn, $context, $filter, $justthese);
+				ldap_sort($ldap_conn, $search, "uid");
+				$info = ldap_get_entries($ldap_conn, $search);
+				ldap_close($ldap_conn);
+
+				$i = 0;
+				$tmp = array();
+				for ($i=0; $i < $info['count']; $i++)
+				{
+					$tmp[$i]['uid'] 		= $info[$i]['uid'][0];
+					$tmp[$i]['name'] 		= $info[$i]['cn'][0];
+					$tmp[$i]['uidnumber']		= $info[$i]['uidnumber'][0];
+					$tmp[$i]['email']		= $info[$i]['mail'][0];
+				}
+				return $tmp;
+			}
+			elseif($type == 'computers')
+			{
+				$filter="(&(objectClass=sambaSAMAccount)(|(sambaAcctFlags=[W          ])(sambaAcctFlags=[DW         ])(sambaAcctFlags=[I          ])(sambaAcctFlags=[S          ]))(cn=*".$query."*))";
+				$justthese = array("cn","uidNumber","description");
+				$search=ldap_search($ldap_conn, $context, $filter, $justthese);
+				ldap_sort($ldap_conn, $search, "cn");
+				$info = ldap_get_entries($ldap_conn, $search);
+				ldap_close($ldap_conn);
+				$tmp = array();
+				for ($i=0; $i < $info['count']; $i++)
+				{
+					$tmp[$i]['cn'] 			= $info[$i]['cn'][0];
+					$tmp[$i]['uidNumber']		= $info[$i]['uidnumber'][0];
+					$tmp[$i]['description'] 	= utf8_decode($info[$i]['description'][0]);
+				}
+				return $tmp;
+			}
+		}
+		
+		//Criado nova funï¿œï¿œo bem mais eficiente!
+		/*
+		function get_organizations($context, $selected='')
+		{
+			//echo $selected;
+			
+			$first_sector_ufn = ldap_dn2ufn($context);
+			$first_sector_string = split(",", $first_sector_ufn);
+			
+			$s = CreateObject('phpgwapi.sector_search_ldap');
+			$sectors_info = $s->sector_search($context);
+			
+			$sector_select = "";
+			$sector_select .= "<option value='" .$context . "'";
+			$sector_select .= ">".strtoupper($first_sector_string[0])."</option>\n";
+			
+			foreach($sectors_info as $sector)
+			{
+				if ($sector->sector_level == 1)
+				{
+					$sector->sector_name = '+ '.$sector->sector_name;
+				}
+				else
+				{
+					$sector_space = '';
+					for ($i=1; $i < $sector->sector_level; $i++)
+						$sector_space = '---'.$sector_space;
+					$sector->sector_name = $sector_space.' '.$sector->sector_name;
+				}
+				$sector_select .= '<option value="' . strtolower($sector->sector_context) . '"';
+				
+				if (trim(strtolower($sector->sector_context)) == $selected)
+					$sector_select .= ' selected>' . $sector->sector_name . "</option>\n";
+				else
+					$sector_select .= '>' . $sector->sector_name . "</option>\n";
+			}
+			//$sector_select .= "</select>";
+			return $sector_select;	
+		}
+		*/
+		
+		/*
+		function get_organizations($context, $selected='', $show_invisible_ou=false)
+		{
+			$dn			= $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
+			$passwd		= $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
+			$ldap_conn	= ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
+			
+			ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
+			ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
+			ldap_bind($ldap_conn,$dn,$passwd);
+			
+			$justthese = array("dn");
+			$filter = $show_invisible_ou ? "(ou=*)" : "(& (ou=*) (!(phpgwAccountVisible=-1)) )";
+			$search=ldap_search($ldap_conn, $context, $filter, $justthese);
+        	
+        	ldap_sort($ldap_conn, $search, "ou");
+        	$info = ldap_get_entries($ldap_conn, $search);
+			ldap_close($ldap_conn);
+
+			// Retiro o count do array info e inverto o array para ordenaï¿œï¿œo.
+	        for ($i=0; $i<$info["count"]; $i++)
+    	    {
+				$dn = $info[$i]["dn"];
+				
+				// Necessï¿œrio, pq em uma busca com ldapsearch ou=*, traz tb o prï¿œprio ou. 
+				if (strtolower($dn) == $context)
+					continue;
+
+				$array_dn = ldap_explode_dn ( $dn, 1 );
+
+                $array_dn_reverse  = array_reverse ( $array_dn, true );
+
+				array_pop ( $array_dn_reverse );
+
+				$inverted_dn[$dn] = implode ( ".", $array_dn_reverse );
+			}
+
+			// Ordenaï¿œï¿œo
+			natcasesort($inverted_dn);
+			
+			// Construï¿œï¿œo do select
+			$level = 0;
+			foreach ($inverted_dn as $dn=>$invert_ufn)
+			{
+                $display = '';
+
+                $array_dn_reverse = explode ( ".", $invert_ufn );
+                $array_dn  = array_reverse ( $array_dn_reverse, true );
+
+                $level = count( $array_dn ) - 4;
+
+                if ($level == 0)
+                        $display .= '+';
+                else {
+                        for ($i=0; $i<$level; $i++)
+                                $display .= '---';
+                }
+
+                reset ( $array_dn );
+                $display .= ' ' . (current ( $array_dn ) );
+				
+				$dn = trim(strtolower($dn));
+				if ( $dn == $selected )
+					$select = ' selected';
+				else
+					$select = '';
+                $options .= "<option value='$dn'$select>$display</option>";
+        	}
+
+			// Cria a primeira entrada na combo 
+			$first_sector_ufn = ldap_dn2ufn($context);
+			$first_sector_string = split(",", $first_sector_ufn);
+			$options = "<option value='$context'>" . strtoupper($first_sector_string[0]) . "</option>" . $options;
+
+    	    return $options;
+		}
+		*/
+		
+		function get_organizations($context, $selected='', $referral=false, $show_invisible_ou=true)
+		{
+			$s = CreateObject('phpgwapi.sector_search_ldap');
+			$sectors_info = $s->get_organizations($context, $selected, $referral, $show_invisible_ou);
+			return $sectors_info;
+		}		
+		
+		function get_sectors($selected='', $referral=false, $show_invisible_ou=true)
+		{
+			$s = CreateObject('phpgwapi.sector_search_ldap');
+			$sectors_info = $s->get_sectors($selected, $referral, $show_invisible_ou);
+			return $sectors_info;
+		}		
+ 
+		/*
+		function get_sectors($context, $selected='')
+		{
+			$query = "SELECT sector FROM phpgw_expressoadmin_sectors WHERE organization = '" . $context . "'";
+			$GLOBALS['phpgw']->db->query($query);
+			while($GLOBALS['phpgw']->db->next_record())
+			{
+				$query_result[] = $GLOBALS['phpgw']->db->row();
+			}
+			
+			if (count($query_result) > 0)
+			{
+				foreach ($query_result as $index=>$tmp)
+				{
+					$sector = $tmp['sector'];
+					if ($sector == $selected)
+						$sector_options .= "<option value='$sector' selected>$sector</option>";
+					else
+						$sector_options .= "<option value='$sector'>$sector</option>";
+				}
+				return $sector_options;
+			}
+			else
+				return false;
+		}
+		*/
+		
+		// Get list of all levels, this function is used for sectors module.
+		/*
+		function get_sectors_list($context)
+		{
+			$connection = $GLOBALS['phpgw']->common->ldapConnect();
+			ldap_set_option($connection, LDAP_OPT_PROTOCOL_VERSION, 3);
+			ldap_set_option($connection, LDAP_OPT_REFERRALS, 0);
+	
+			if ($connection)
+			{				
+				$bind=ldap_bind($connection);
+				$filter="ou=*";
+				$justthese = array("ou");
+				$search=ldap_list($connection, $context, $filter, $justthese);
+				ldap_sort($connection, $search, "ou");
+				$info = ldap_get_entries($connection, $search);
+				for ($i=0; $i<$info["count"]; $i++)
+				{
+					$this->level++;
+					$next_context[$i] = 'ou='.$info[$i]["ou"][0].','.$context;
+					$obj = new sectors_object($info[$i]["ou"][0], $next_context[$i], $this->level, 'False');
+					array_push($this->sectors_list, $obj);
+					$this->get_sectors_list($next_context[$i]);
+				}
+			}
+			ldap_close($connection);
+			$this->level--;
+			return $this->sectors_list;
+		}
+		*/
+		
+		// Get list of all levels, this function is used for sectors module.
+		function get_sectors_list($context, $selected='', $referral=false ,$show_invisible_ou=false)
+		{
+			$dn			= $GLOBALS['phpgw_info']['server']['ldap_root_dn'];
+			$passwd		= $GLOBALS['phpgw_info']['server']['ldap_root_pw'];
+			$ldap_conn	= ldap_connect($GLOBALS['phpgw_info']['server']['ldap_host']);
+			
+			ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3);
+			
+			if ($referral)
+				ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 1);
+			else
+				ldap_set_option($ldap_conn, LDAP_OPT_REFERRALS, 0);
+			
+			ldap_bind($ldap_conn,$dn,$passwd);
+			
+			$justthese = array("dn");
+			$filter = "(ou=*)";
+			$search=ldap_search($ldap_conn, $context, $filter, $justthese);
+        	
+        	ldap_sort($ldap_conn, $search, "ou");
+        	$info = ldap_get_entries($ldap_conn, $search);
+			ldap_close($ldap_conn);
+
+			// Retiro o count do array info e inverto o array para ordenaï¿œï¿œo.
+	        for ($i=0; $i<$info["count"]; $i++)
+    	    {
+				$dn = $info[$i]["dn"];
+				
+				// Necessï¿œrio, pq em uma busca com ldapsearch ou=*, traz tb o prï¿œprio ou. 
+				if (strtolower($dn) == $context)
+					continue;
+
+				$array_dn = ldap_explode_dn ( $dn, 1 );
+
+                $array_dn_reverse  = array_reverse ( $array_dn, true );
+
+				// Retirar o indice count do array.
+				array_pop ( $array_dn_reverse );
+
+				$inverted_dn[$dn] = implode ( "#", $array_dn_reverse );
+			}
+
+			// Ordenaï¿œï¿œo
+			natcasesort($inverted_dn);
+			
+			// Construï¿œï¿œo do select
+			$level = 0;
+			$options = array();
+			foreach ($inverted_dn as $dn=>$invert_ufn)
+			{
+                $display = '';
+
+                $array_dn_reverse = explode ( "#", $invert_ufn );
+                $array_dn  = array_reverse ( $array_dn_reverse, true );
+
+                $level = count( $array_dn ) - (int)(count(explode(",", $GLOBALS['phpgw_info']['server']['ldap_context'])) + 1);
+
+                if ($level == 0)
+                        $display .= '+';
+                else 
+                {
+					for ($i=0; $i<$level; $i++)
+						$display .= '---';
+                }
+
+                reset ( $array_dn );
+                $display .= ' ' . (current ( $array_dn ) );
+				
+				$dn = trim(strtolower($dn));
+				$options[$dn] = $display;
+        	}
+    	    return $options;
+		}
+		
+		function exist_account_lid($account_lid)
+		{
+			$conection = $GLOBALS['phpgw']->common->ldapConnect();
+			$sri = ldap_search($conection, $GLOBALS['phpgw_info']['server']['ldap_context'], "uid=" . $account_lid);
+			$result = ldap_get_entries($conection, $sri);
+			return $result['count'];
+		}
+		
+		function exist_email($mail)
+		{
+			$conection = $GLOBALS['phpgw']->common->ldapConnect();
+			$sri = ldap_search($conection, $GLOBALS['phpgw_info']['server']['ldap_context'], "mail=" . $mail);
+			$result = ldap_get_entries($conection, $sri);
+			ldap_close($conection);
+			
+			if ($result['count'] == 0)
+				return false;
+			else
+				return true;
+		}
+		
+		function array_invert($array)
+		{
+			$result[] = end($array);
+			while ($item = prev($array))
+				$result[] = $item;
+			return $result; 
+		}
+		
+		function get_next_id()
+		{
+			// Busco o ID dos accounts
+			$query_accounts = "SELECT id FROM phpgw_nextid WHERE appname = 'accounts'";
+			$GLOBALS['phpgw']->db->query($query_accounts);
+			while($GLOBALS['phpgw']->db->next_record())
+			{
+				$result_accounts[] = $GLOBALS['phpgw']->db->row();
+			}			
+			$accounts_id = $result_accounts[0]['id'];
+			
+			// Busco o ID dos groups
+			$query_groups = "SELECT id FROM phpgw_nextid WHERE appname = 'groups'";
+			$GLOBALS['phpgw']->db->query($query_groups);
+			while($GLOBALS['phpgw']->db->next_record())
+			{
+				$result_groups[] = $GLOBALS['phpgw']->db->row();
+			}			
+			$groups_id = $result_groups[0]['id'];
+			
+			//Retorna o maior dos ID's
+			if ($accounts_id >= $groups_id)
+				return $accounts_id;
+			else
+				return $groups_id;
+		}
+		
+		function increment_id($id, $type)
+		{
+			$sql = "UPDATE phpgw_nextid set id = '".$id."' WHERE appname = '" . $type . "'"; 
+			$GLOBALS['phpgw']->db->query($sql);
+		}
+		
+		function make_list_app($account_lid, $context, $user_applications, $disabled='')
+		{
+			// create list of ALL available apps
+			$availableAppsGLOBALS = $GLOBALS['phpgw_info']['apps'];
+			
+			// create list of available apps for the user
+			$query = "SELECT * FROM phpgw_expressoadmin_apps WHERE manager_lid = '".$account_lid."' AND context = '".$context."'";
+			$GLOBALS['phpgw']->db->query($query);
+			while($GLOBALS['phpgw']->db->next_record())
+			{
+				$availableApps[] = $GLOBALS['phpgw']->db->row();
+			}
+			
+			// Retira alguns modulos
+			if (count($availableApps))
+			{
+				foreach ($availableApps as $key => $value)
+				{
+					if ($value['app'] != 'phpgwapi')
+						$tmp[] = $availableApps[$key];
+				}
+			}
+			$availableApps = $tmp;
+			
+			// Cria um array com as aplicacoes disponiveis para o manager, com as atributos das aplicacoes.
+			$availableAppsUser = array();
+			if (count($availableApps))
+			{
+				foreach($availableApps as $app => $title)
+				{
+					if ($availableAppsGLOBALS[$title['app']])
+						$availableAppsUser[$title['app']] = $availableAppsGLOBALS[$title['app']];
+				}
+			}
+			
+			// Loop para criar dinamicamente uma tabela com 3 colunas, cada coluna com um aplicativo e um check box.
+			$applications_list = '';
+			$app_col1 = '';
+			$app_col2 = '';
+			$app_col3 = '';
+			$total_apps = count($availableAppsUser);
+			$i = 0;
+			foreach($availableAppsUser as $app => $data)
+			{
+				// 1 coluna 
+				if (($i +1) % 3 == 1)
+				{
+					$checked = $user_applications[$app] ? 'CHECKED' : '';
+					$app_col1 = sprintf("<td>%s</td><td width='10'><input type='checkbox' name='apps[%s]' value='1' %s %s></td>\n",
+					$data['title'],$app,$checked, $disabled);
+					if ($i == ($total_apps-1))
+						$applications_list .= sprintf('<tr bgcolor="%s">%s</tr>','#DDDDDD', $app_col1);
+				}
+				
+				// 2 coluna
+				if (($i +1) % 3 == 2)
+				{
+					$checked = $user_applications[$app] ? 'CHECKED' : '';
+					$app_col2 = sprintf("<td>%s</td><td width='10'><input type='checkbox' name='apps[%s]' value='1' %s %s></td>\n",
+					$data['title'],$app,$checked, $disabled);
+					
+					if ($i == ($total_apps-1))
+						$applications_list .= sprintf('<tr bgcolor="%s">%s%s</tr>','#DDDDDD', $app_col1,$app_col2);
+				}
+				// 3 coluna 
+				if (($i +1) % 3 == 0)
+				{
+					$checked = $user_applications[$app] ? 'CHECKED' : '';
+					$app_col3 = sprintf("<td>%s</td><td width='10'><input type='checkbox' name='apps[%s]' value='1' %s %s></td>\n",
+					$data['title'],$app,$checked, $disabled);
+					
+					// Cria nova linha
+					$applications_list .= sprintf('<tr bgcolor="%s">%s%s%s</tr>','#DDDDDD', $app_col1, $app_col2, $app_col3);					
+				}
+				$i++;
+			}
+			return $applications_list;
+		}
+		
+		function exist_attribute_in_ldap($dn, $attribute, $value)
+		{
+			$connection = $GLOBALS['phpgw']->common->ldapConnect();
+			$search = ldap_search($connection, $dn, $attribute. "=" . $value);
+			$result = ldap_get_entries($connection, $search);
+			ldap_close($connection);
+			//_debug_array($result);
+			if ($result['count'] == 0)
+				return false;
+			else
+				return true;	
+		}
+		
+		function getReturnExecuteForm(){
+			$response = $_SESSION['response'];
+			$_SESSION['response'] = null;
+			return $response;
+		}
+
+		function write_log2($action, $groupinfo='', $userinfo='', $appinfo='', $msg_log='')
+		{
+			$sql = "INSERT INTO phpgw_expressoadmin_log (date, manager, action, groupinfo, userinfo, appinfo, msg) "
+			. "VALUES('now','" . $_SESSION['phpgw_info']['expresso']['user']['account_lid'] . "','" . strtolower($action) . "','" . strtolower($groupinfo) . "','" . strtolower($userinfo) . "','" . strtolower($appinfo) . "','" .strtolower($msg_log) . "')";
+			$GLOBALS['phpgw']->db->query($sql);
+			return;
+		}
+		
+	}
+	
+	class sectors_object
+	{
+		var $sector_name;
+		var $sector_context;
+		var $sector_level;
+		var $sector_leaf;
+		var $sectors_list = array();
+		var $level;
+		
+		function sectors_object($sector_name, $sector_context, $sector_level, $sector_leaf)
+		{
+			$this->sector_name = $sector_name;
+			$this->sector_context = $sector_context;
+			$this->sector_level = $sector_level;
+			$this->sector_leaf = $sector_leaf;
+		}
+	}
Index: /branches/2.2/listAdmin/inc/class.ldap_functions.inc.php
===================================================================
--- /branches/2.2/listAdmin/inc/class.ldap_functions.inc.php	(revision 3514)
+++ /branches/2.2/listAdmin/inc/class.ldap_functions.inc.php	(revision 3514)
@@ -0,0 +1,1642 @@
+<?php
+define('PHPGW_INCLUDE_ROOT','../');
+define('PHPGW_API_INC','../phpgwapi/inc');	
+include_once(PHPGW_API_INC.'/class.common.inc.php');
+
+class ldap_functions
+{
+	var $ldap;
+	var $ldap_write;
+	var $current_config;
+	
+	function ldap_functions()
+		{
+		$GLOBALS['phpgw_info']['server'] = $_SESSION['phpgw_info']['expresso']['server'];
+		$this->current_config = $_SESSION['phpgw_info']['expresso']['listAdmin'];
+		$common = new common();
+		$this->ldap = $common->ldapConnect();
+		//Para haver escrita em diretorio escravo eh necessario que se faca login na api com a opcao de seguir referrals. Foi feita aqui a divisao entre escrita e leitura pois a leitura ldap fica bem mais lenta quando configurada para seguir referrals.
+                /*
+		if($GLOBALS['phpgw_info']['server']['diretorioescravo'])
+			{
+			$this->ldap_write = $common->ldapConnect("","","",true);
+			}
+			else
+			{
+			$this->ldap_write = $this->ldap;
+			}
+
+                 *
+                 */
+                if ( (!empty($GLOBALS['phpgw_info']['server']['ldap_master_host'])) &&
+			 (!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_dn'])) &&
+			 (!empty($GLOBALS['phpgw_info']['server']['ldap_master_root_pw'])) )
+                        {
+                            $this->ldap_write = $common->ldapConnect($GLOBALS['phpgw_info']['server']['ldap_master_host'],
+											   $GLOBALS['phpgw_info']['server']['ldap_master_root_dn'],
+											   $GLOBALS['phpgw_info']['server']['ldap_master_root_pw']);
+                        }
+                        else
+                        {
+                            $this->ldap_write = $common->ldapConnect();
+                        }
+
+                 }
+	function validate_fields($params)
+	{
+		$params = unserialize($params['attributes']);
+		$type = $params['type'];
+		$context = $GLOBALS['phpgw_info']['server']['ldap_context'];
+		$uid = $params['uid'];
+		$mail = $params['mail'];
+		$mailalternateaddress = $params['mailalternateaddress'];
+
+		$result['status'] = true;
+		
+		if ($_SESSION['phpgw_info']['expresso']['global_denied_users'][$uid])
+		{
+			$result['status'] = false;
+			$result['msg'] = 'Este LOGIN nï¿œo pode ser usado pois ï¿œ uma conta de sistema.';
+			return $result;
+		}
+		
+		if (($type == 'create_user') || ($type == 'rename_user')) 
+		{
+			// UID
+			$filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uid=$uid))";
+			$justthese = array("uid");
+			$search = ldap_search($this->ldap, $context, $filter, $justthese);
+			$count_entries = ldap_count_entries($this->ldap,$search);
+			if ($count_entries > 0)
+			{
+				$result['status'] = false;
+				$result['msg'] = 'LOGIN jï¿œ esta sendo usado.';
+				return $result;
+			}
+
+			// GRUPOS
+			$filter = "(&(phpgwAccountType=g)(cn=$uid))";
+			$justthese = array("cn");
+			$search = ldap_search($this->ldap, $context, $filter, $justthese);
+			$count_entries = ldap_count_entries($this->ldap,$search);
+			if ($count_entries > 0)
+			{
+				$result['status'] = false;
+				$result['msg'] = 'LOGIN do usuï¿œrio jï¿œ esta sendo usado por um grupo.';
+				return $result;
+			}
+		
+			// UID em outras organizaï¿œï¿œes
+			//Quando tento retirar as organizaï¿œï¿œes pelo expressoAdmin dï¿œ este erro.
+			$filter = "(ou=*)";
+			$justthese = array("ou");
+			$search = ldap_list($this->ldap, $context, $filter, $justthese);
+			$entries = ldap_get_entries($this->ldap,$search);
+			foreach ($entries as $index=>$org)
+			{
+				$organization = $org['ou'][0];
+				$organization = strtolower($organization);
+				
+				$filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uid=$organization-$uid))";
+				$justthese = array("uid");
+				$search = ldap_search($this->ldap, $context, $filter, $justthese);
+				$count_entries = ldap_count_entries($this->ldap,$search);
+				if ($count_entries > 0)
+				{
+					$result['status'] = false;
+					$result['msg'] = 'LOGIN jï¿œ esta sendo usado por outro usuï¿œrio em outra organizaï¿œï¿œo.';
+					return $result;
+				}
+			}
+		}
+		
+		if ($type == 'rename_user')
+		{
+			return $result;
+		}
+		
+		// MAIL
+		$filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|(mail=$mail)(mailalternateaddress=$mail)))";
+		$justthese = array("mail", "uid");
+		$search = ldap_search($this->ldap, $context, $filter, $justthese);
+		$entries = ldap_get_entries($this->ldap,$search);
+		if ($entries['count'] == 1){
+			if ($entries[0]['uid'][0] != $uid){
+				$result['status'] = false;
+				$result['msg'] = 'E-MAIL estï¿œ sendo usado por 1 usuï¿œrio: ' . $entries[0]['uid'][0];
+				//ldap_close($this->ldap);
+				return $result;
+			}
+		}
+		else if ($entries['count'] > 1){
+			$result['status'] = false;
+			$result['msg'] = 'E-MAIL estï¿œ sendo usado por de 2 ou mais usuï¿œrios.';
+			//ldap_close($this->ldap);
+			return $result;
+		}
+		
+		// MAILAlternateAddress
+		$filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|(mail=$mailalternateaddress)(mailalternateaddress=$mailalternateaddress)))";
+		$justthese = array("mail", "uid");
+		$search = ldap_search($this->ldap, $context, $filter, $justthese);
+		$entries = ldap_get_entries($this->ldap,$search);
+		if ($entries['count'] == 1){
+			if ($entries[0]['uid'][0] != $uid){
+				$result['status'] = false;
+				$result['msg'] = "E-MAIL alternativo estï¿œ sendo usado por 1 usuï¿œrio: " . $entries[0]['uid'][0];
+				//ldap_close($this->ldap);
+				return $result;
+			}
+		}
+		else if ($entries['count'] > 1){
+			$result['status'] = false;
+			$result['msg'] = 'E-MAIL alternativo estï¿œ sendo usado por 2 ou mais usuï¿œrios.';
+			return $result;
+		}
+
+		return $result;
+	}
+	
+	function validate_fields_maillist($params)
+	{
+		$context = $GLOBALS['phpgw_info']['server']['ldap_context'];
+		$uid = $params['uid'];
+		$mail = $params['mail'];
+		$result['status'] = true;
+		
+		if ($_SESSION['phpgw_info']['expresso']['global_denied_users'][$uid])
+		{
+			$result['status'] = false;
+			$result['msg'] = 'Este LOGIN nï¿œo pode ser usado pois ï¿œ uma conta de sistema.';
+			return $result;
+		}
+		
+		// UID
+		$filter = "(&(phpgwAccountType=l)(uid=$uid))";
+		$justthese = array("uid");
+		$search = ldap_search($this->ldap, $context, $filter, $justthese);
+		$count_entries = ldap_count_entries($this->ldap,$search);
+		if ($count_entries > 0)
+		{
+			$result['status'] = false;
+			$result['msg'] = 'LOGIN da lista jï¿œ estï¿œ sendo usado.';
+			return $result;
+		}
+		
+		// MAIL
+		/*
+		$filter = "(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|(mail=$mail)(mailalternateaddress=$mail)))";
+		$justthese = array("mail");
+		$search = ldap_search($this->ldap, $context, $filter, $justthese);
+		$count_entries = ldap_count_entries($this->ldap,$search);
+		if ($count_entries > 0)
+		{
+			$result['status'] = false;
+			$result['msg'] = 'E-MAIL da lista jï¿œ estï¿œ sendo usado.';
+			return $result;
+		}*/
+		
+		return $result;	
+	}
+
+	//Busca usuï¿œrios de um contexto e jï¿œ retorna as options do select;
+	function get_available_users($params)
+	{
+		$context = $params['context'];
+		$recursive = $params['recursive'];
+		$justthese = array("cn", "uidNumber");
+		$filter="(phpgwAccountType=u)";
+		
+		if ($recursive == 'true')
+			$groups_list=ldap_search($this->ldap, $context, $filter, $justthese);
+		else
+    		$groups_list=ldap_list($this->ldap, $context, $filter, $justthese);
+    	
+    	$entries = ldap_get_entries($this->ldap, $groups_list);
+    	
+		for ($i=0; $i<$entries["count"]; $i++){
+			$u_tmp[$entries[$i]["uidnumber"][0]] = $entries[$i]["cn"][0];
+		}
+			
+		if (count($u_tmp))
+			natcasesort($u_tmp);
+
+		$i = 0;
+		$users = array();
+			
+		if (count($u_tmp))
+		{
+			foreach ($u_tmp as $uidnumber => $cn)
+			{
+				$options .= "<option value=$uidnumber>$cn</option>";
+			}
+			unset($u_tmp);
+		}
+
+    	return $options;
+	}
+
+	//Busca usuï¿œrios e listas de um contexto e jï¿œ retorna as options do select;
+	function get_available_users_and_maillist($params)
+	{
+
+		$context = $params['context'];
+		$recursive = $params['recursive'];
+		
+		//Usado para retirar a prï¿œpria lista das possibilidades de inclusï¿œo.
+		$denied_uidnumber = $params['denied_uidnumber'];
+		
+		$justthese = array("cn", "uidNumber");
+		$users_filter="(phpgwAccountType=u)";
+		$lists_filter = $denied_uidnumber == '' ? "(phpgwAccountType=l)" : "(&(phpgwAccountType=l)(!(uidnumber=$denied_uidnumber)))";
+		
+		$users = Array();
+		$lists = Array();		
+
+		if ($recursive == 'true')
+		{
+			$lists_search = ldap_search($this->ldap, $context, $lists_filter, $justthese);
+			$users_search = ldap_search($this->ldap, $context, $users_filter, $justthese);
+		}
+		else
+		{
+			$lists_search = ldap_list($this->ldap, $context, $lists_filter, $justthese);
+			$users_search = ldap_list($this->ldap, $context, $users_filter, $justthese);
+		}
+		
+		$lists_entries = ldap_get_entries($this->ldap, $lists_search);
+		for ($i=0; $i<$lists_entries["count"]; $i++)
+		{
+			$l_tmp[$lists_entries[$i]["uidnumber"][0]] = $lists_entries[$i]["cn"][0];
+		}
+			
+		if (count($l_tmp))
+			natcasesort($l_tmp);
+			
+		$i = 0;
+		$lists = array();
+		
+		$options .= '<option  value="-1" disabled>------------------------------&nbsp;&nbsp;&nbsp;&nbsp;Listas&nbsp;&nbsp;&nbsp;&nbsp;------------------------------ </option>'."\n";	
+		if (count($l_tmp))
+		{
+			foreach ($l_tmp as $uidnumber => $cn)
+			{
+				$options .= "<option value=$uidnumber>$cn</option>";
+			}
+			unset($l_tmp);
+		}
+		
+		$users_entries = ldap_get_entries($this->ldap, $users_search);
+		for ($i=0; $i<$users_entries["count"]; $i++)
+		{
+			$u_tmp[$users_entries[$i]["uidnumber"][0]] = $users_entries[$i]["cn"][0];
+		}
+			
+		if (count($u_tmp))
+			natcasesort($u_tmp);
+			
+		$i = 0;
+		$users = array();
+		
+		$options .= '<option  value="-1" disabled>-----------------------------&nbsp;&nbsp;&nbsp;&nbsp;Usuarios&nbsp;&nbsp;&nbsp;&nbsp;---------------------------- </option>'."\n";	
+		if (count($u_tmp))
+		{
+			foreach ($u_tmp as $uidnumber => $cn)
+			{
+				$options .= "<option value=$uidnumber class='line-above'>$cn</option>";
+			}
+			unset($u_tmp);
+		}
+			
+   		return $options;
+	}
+
+	//Funcao que busca apenas os usuarios de um contexto e ja retorna as options do select;
+	function get_available_users_only($params)
+	{
+
+		$context = $params['context'];
+		$recursive = $params['recursive'];
+		$filtro = $params['filtro'];
+		
+		$justthese = array("cn", "uidNumber");
+//		$users_filter="(phpgwAccountType=u)";
+$users_filter="(&(phpgwAccountType=u)(cn=*$filtro*))";
+		
+		$users = Array();
+
+		if ($recursive == 'true')
+		{
+			$users_search = ldap_search($this->ldap, $context, $users_filter, $justthese);
+		}
+		else
+		{
+			$users_search = ldap_list($this->ldap, $context, $users_filter, $justthese);
+		}
+		
+		$users_entries = ldap_get_entries($this->ldap, $users_search);
+		for ($i=0; $i<$users_entries["count"]; $i++)
+		{
+			$u_tmp[$users_entries[$i]["uidnumber"][0]] = $users_entries[$i]["cn"][0];
+		}
+			
+		if (count($u_tmp))
+			natcasesort($u_tmp);
+			
+		$i = 0;
+		$users = array();
+		
+		$options .= '<option  value="-1" disabled>-----------------------------&nbsp;&nbsp;&nbsp;&nbsp;Usuarios&nbsp;&nbsp;&nbsp;&nbsp;---------------------------- </option>'."\n";	
+		if (count($u_tmp))
+		{
+			foreach ($u_tmp as $uidnumber => $cn)
+			{
+				$options .= "<option value=$uidnumber class='line-above'>$cn</option>";
+			}
+			unset($u_tmp);
+		}
+			
+   		return $options;
+	}
+
+
+	function is_user_listAdmin($uid)
+	{
+		$cn_listadmin = $this->current_config['name_listadmin'];
+		$justthese = array("memberUid");
+		//$filter = "(&(phpgwAccountType=g)(cn=listadmin)(memberuid=$uid))";
+		$filter = "(&(phpgwAccountType=g)(cn=$cn_listadmin)(memberuid=$uid))";
+		$dn = $this->current_config['dn_listadmin'];
+		$search = ldap_search($this->ldap,$dn,$filter, $justthese);
+		$entry = ldap_get_entries($this->ldap, $search);
+		$i = 0;
+		for($i = 0; $i <= $entry[0]['memberuid']['count']; $i++)
+		{
+			if($entry[0]['memberuid'][$i] == $uid)
+			{
+				$return = 1;
+			}
+		}
+		return $return;
+	}
+
+
+
+
+
+	function search_users_only($params)
+	{
+
+		$context = $GLOBALS['phpgw_info']['server']['ldap_context']; //$params['context'];
+		$filtro = $params['filtro'];
+		$tipo = $params['tipo'];
+		//      $recursive = $params['recursive'];
+
+		$justthese = array("cn", "uidNumber", "mail");
+
+		if($tipo == "adm_maillist")
+		{
+			$users_filter="(&(phpgwAccountType=u)(phpgwAccountStatus=A)(|(cn=*$filtro*)(mail=*$filtro*)))";
+		}
+		else
+		{
+			$users_filter="(&(phpgwAccountStatus=A)(|(cn=*$filtro*)(mail=*$filtro*)))";
+		}
+
+		$users = Array();
+
+	//      if ($recursive == 'true')
+	//      {
+		$users_search = ldap_search($this->ldap, $context, $users_filter, $justthese);
+	//      }
+	//      else
+	//      {
+	//              $users_search = ldap_list($this->ldap, $context, $users_filter, $justthese);
+	//      }
+
+		$users_entries = ldap_get_entries($this->ldap, $users_search);
+		for ($i=0; $i<$users_entries["count"]; $i++)
+		{
+				$u_tmp[$users_entries[$i]["uidnumber"][0]] = $users_entries[$i]["cn"][0] . " [" .$users_entries[$i]["mail"][0] . "]";
+		}
+
+		if(count($u_tmp) == 0) {
+			$options .= '<option  value="-1" disabled>------&nbsp;&nbsp;&nbsp;USUARIO INVALIDO OU NAO CRIADO NO EXPRESSO&nbsp;&nbsp;&nbsp;------</option>'."\n";
+		}
+
+		if (count($u_tmp))
+			natcasesort($u_tmp);
+
+		$i = 0;
+		$users = array();
+
+		$options .= '<option  value="-1" disabled>-----------------------------&nbsp;&nbsp;&nbsp;&nbsp;Usuarios&nbsp;&nbsp;&nbsp;&nbsp;---------------------------- </option>'."\n";
+		if (count($u_tmp))
+		{
+			foreach ($u_tmp as $uidnumber => $cn)
+			{
+				$options .= "<option value=$uidnumber class='line-above'>$cn</option>";
+			}
+
+			unset($u_tmp);
+		}
+
+		return $options;
+	}
+
+
+	function get_available_groups($params)
+	{
+	$context = $params['context'];
+	$justthese = array("cn", "gidNumber");
+    	$groups_list=ldap_search($this->ldap, $context, ("(phpgwAccountType=g)"), $justthese);
+    	ldap_sort($this->ldap, $groups_list, "cn");
+    	$entries = ldap_get_entries($this->ldap, $groups_list);
+	$options = '';
+	for ($i=0; $i<$entries['count']; $i++)
+		{
+		$options .= "<option value=" . $entries[$i]['gidnumber'][0] . ">" . $entries[$i]['cn'][0] . "</option>";
+		}
+    	return $options;		
+	}
+	
+	function get_available_maillists($params)
+	{
+		$context = $params['context'];
+		$justthese = array("uid","mail","uidNumber");
+    	$maillists=ldap_search($this->ldap, $context, ("(phpgwAccountType=l)"), $justthese);
+    	ldap_sort($this->ldap, $maillists, "uid");
+    	
+    	$entries = ldap_get_entries($this->ldap, $maillists);
+    	
+		$options = '';			
+		for ($i=0; $i<$entries['count']; $i++)
+		{
+			$options .= "<option value=" . $entries[$i]['uidnumber'][0] . ">" . $entries[$i]['uid'][0] . " </option>";
+		}
+    	return $options;		
+	}
+	
+	function ldap_add_entry($dn, $entry)
+	{
+		$result = array();
+		if (!@ldap_add ($this->ldap_write, $dn, $entry ))
+		{
+			$result['status'] = false;
+			$result['msg'] = "Erro na funcao ldap_functions->ldap_add_entry ($dn).\nRetorno do servidor:" . ldap_error($this->ldap_write);
+		}
+		else
+			$result['status'] = true;
+		return $result;
+	}
+	
+	function ldap_save_photo($dn, $pathphoto, $photo_exist=false)
+	{
+		$fd = fopen($pathphoto, "r");
+		$fsize = filesize($pathphoto);
+		$jpegStr = fread($fd, $fsize);
+		fclose ($fd);
+		$attrs['jpegPhoto'] = $jpegStr;
+			
+		if ($photo_exist)
+			$res = @ldap_mod_replace($this->ldap_write, $dn, $attrs);
+		else
+			$res = @ldap_mod_add($this->ldap_write, $dn, $attrs);
+			
+		if ($res)
+		{
+			$result['status'] = true;
+		}
+		else
+		{
+			$result['status'] = false;
+			$result['msg'] = "Erro na funcao ldap_functions->ldap_save_photo ($dn).\nRetorno do servidor:" . ldap_error($this->ldap_write);
+		}
+		return $result;
+	}
+	
+	function ldap_remove_photo($dn)
+	{
+		$attrs['jpegPhoto'] = array();
+		$res = ldap_mod_del($this->ldap_write, $dn, $attrs);
+		if ($res)
+		{
+			$result['status'] = true;
+		}
+		else
+		{
+			$result['status'] = false;
+			$result['msg'] = "Erro na funcao ldap_functions->ldap_remove_photo ($dn).\nRetorno do servidor:" . ldap_error($this->ldap_write);
+		}
+		return $result;
+	}	
+	
+	// Pode receber tanto um ï¿œnico memberUid quanto um array de memberUid's
+	function add_user2group($gidNumber, $memberUid)
+	{
+		$filter = "(&(phpgwAccountType=g)(gidNumber=$gidNumber))";
+		$justthese = array("dn");
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+		$entry = ldap_get_entries($this->ldap_write, $search);
+		$group_dn = $entry[0]['dn'];
+		$attrs['memberUid'] = $memberUid;
+		
+		$res = @ldap_mod_add($this->ldap_write, $group_dn, $attrs);
+		
+		if ($res)
+		{
+			$result['status'] = true;
+		}
+		else
+		{
+			$result['status'] = false;
+			$result['msg'] = "Erro na funcao ldap_functions->add_user2group ($memberUid).\nRetorno do servidor:" . ldap_error($this->ldap_write);
+		}
+		return $result;
+	}
+	
+	function remove_user2group($gidNumber, $memberUid)
+	{
+		$filter = "(&(phpgwAccountType=g)(gidNumber=$gidNumber))";
+		$justthese = array("dn");
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+		$entry = ldap_get_entries($this->ldap_write, $search);
+		$group_dn = $entry[0]['dn'];
+		$attrs['memberUid'] = $memberUid;
+		$res = @ldap_mod_del($this->ldap_write, $group_dn, $attrs);
+		
+		/*echo 'usuarios recebidos para remocao no ldap';
+		echo '<pre>';
+		print_r($memberUid);*/
+		
+		if ($res)
+		{
+			$result['status'] = true;
+		}
+		else
+		{
+			$result['status'] = false;
+			$result['msg'] = "Erro na funcao ldap_functions->remove_user2group ($memberUid).\nRetorno do servidor:" . ldap_error($this->ldap_write);
+		}
+		return $result;
+	}
+	
+	function add_user2maillist($uidNumber, $mail)
+	{
+		$filter = "(&(phpgwAccountType=l)(uidNumber=$uidNumber))";
+		$justthese = array("dn");
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+		$entry = ldap_get_entries($this->ldap_write, $search);
+		$group_dn = $entry[0]['dn'];
+		echo "teste...";
+
+		$attrs['mailForwardingAddress'] = $mail;
+		$res = ldap_mod_add($this->ldap_write, $group_dn, $attrs);
+                
+		if ($res)
+		{
+			$result['status'] = true;
+		}
+		else
+		{
+			$result['status'] = false;
+			$result['msg'] = "Erro na funcao ldap_functions->add_user2maillist ($mail).\nRetorno do servidor:" . ldap_error($this->ldap_write);
+		}
+		return $result;
+	}
+	
+	function add_user2maillist_adm($uidNumber, $mail)
+        {
+		$result['msg'] = "Entre adiciona adm";
+		$filter = "(&(phpgwAccountType=l)(uidNumber=$uidNumber))";
+		$justthese = array("dn");
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+		$entry = ldap_get_entries($this->ldap_write, $search);
+		$group_dn = $entry[0]['dn'];
+
+		$attrs['admlista'] = $mail;
+		$res = ldap_mod_add($this->ldap_write, $group_dn, $attrs);
+
+		if ($res)
+		{
+				$result['status'] = true;
+		}
+		else
+		{
+				$result['status'] = false;
+				$result['msg'] = "Erro na funcao ldap_functions->add_user2maillist ($mail).\nRetorno do servidor:" . ldap_error($this->ldap_write);
+		}
+		return $result;
+        }
+
+
+	
+	function add_user2maillist_scl($dn, $array_emails)
+	{
+		$attrs['naomoderado'] = $array_emails;
+		$res = @ldap_mod_add($this->ldap_write, $dn, $attrs);
+		if ($res)
+		{
+			$result['status'] = true;
+		}
+		else
+		{
+			$result['status'] = false;
+			$result['msg'] = "Erro na funcao ldap_functions->add_user2maillist_scl ($dn).\n\nRetorno do servidor:" . ldap_error($this->ldap_write);
+		}
+		return $result;
+	}
+
+	function remove_user2maillist($uidNumber, $mail)
+	{
+		$filter = "(&(phpgwAccountType=l)(uidNumber=$uidNumber))";
+		$justthese = array("dn");
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+		$entry = ldap_get_entries($this->ldap_write, $search);
+		$group_dn = $entry[0]['dn'];
+		$attrs['mailForwardingAddress'] = $mail;
+		$res = @ldap_mod_del($this->ldap_write, $group_dn, $attrs);
+		
+		if ($res)
+		{
+			$result['status'] = true;
+		}
+		else
+		{
+			$result['status'] = false;
+			$result['msg'] = "Erro na funcao ldap_functions->remove_user2maillist ($mail).\n\nRetorno do servidor:" . ldap_error($this->ldap_write);
+		}
+		return $result;
+	}
+	
+	function remove_user2maillist_adm($uidNumber, $mail)
+        {
+		$filter = "(&(phpgwAccountType=l)(uidNumber=$uidNumber))";
+		$justthese = array("dn");
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+		$entry = ldap_get_entries($this->ldap_write, $search);
+		$group_dn = $entry[0]['dn'];
+		$attrsAdm['admlista'] = $mail;
+		$res = @ldap_mod_del($this->ldap_write, $group_dn, $attrsAdm);
+		if ($res)
+		{
+				$result['status'] = true;
+		}
+		else
+		{
+				$result['status'] = false;
+				$result['msg'] = "Erro na funcao ldap_functions->remove_user2maillist ($mail).\n\nRetorno do servidor:" . ldap_error($this->ldap_write);
+		}
+		return $result;
+        }
+
+	function remove_user2maillist_scl($dn, $array_emails)
+	{
+		$attrs['naomoderado'] = $array_emails;
+		$res = @ldap_mod_del($this->ldap_write, $dn, $attrs);
+		
+		if ($res)
+		{
+			$result['status'] = true;
+		}
+		else
+		{
+			$result['status'] = false;
+			$result['msg'] = "Erro na funcao ldap_functions->remove_user2maillist_scp ($dn).\n\nRetorno do servidor:" . ldap_error($this->ldap_write);
+		}
+		return $result;
+	}
+
+	function replace_user2maillists($new_mail, $old_mail)
+	{
+		$filter = "(&(phpgwAccountType=l)(mailforwardingaddress=$old_mail))";
+		$justthese = array("dn");
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+		$entries = ldap_get_entries($this->ldap_write, $search);
+		$result['status'] = true;
+		for ($i=0; $i<$entries['count']; $i++)
+		{
+			$attrs['mailforwardingaddress'] = $old_mail;
+			$res1 = @ldap_mod_del($this->ldap_write, $entries[$i]['dn'], $attrs);
+			$attrs['mailforwardingaddress'] = $new_mail;
+			$res2 = @ldap_mod_add($this->ldap_write, $entries[$i]['dn'], $attrs);
+		
+			if ((!$res1) || (!$res2))
+			{
+				$result['status'] = false;
+				$result['msg'] = "Erro na funcao ldap_functions->replace_user2maillists ($old_mail).\nRetorno do servidor:" . ldap_error($this->ldap_write);
+			}
+		}
+		return $result;
+	}
+	
+	function get_user_info($uidnumber, $context, $serpro=false)
+	{
+		if ($serpro)
+			$filter="(&(objectclass=".$GLOBALS['phpgw_info']['server']['atributousuarios'].")(uidNumber=".$uidnumber."))";
+			else
+			$filter="(&(phpgwAccountType=u)(uidNumber=".$uidnumber."))";
+		//Precisa identificar cada atributo, pois em alguns ldaps os atributos nao sao devolvidos se nao fores explicitamente identificados na pesquisa
+		$justthese = array("dn","ou","uid","uidnumber","gidnumber","departmentnumber","givenname","sn","telephonenumber","mobile","phpgwaccountstatus","phpgwaccountvisible","accountstatus","mail","defaultmembermoderation","admlista","listPass","listPass","mailalternateaddress","mailforwardingaddress","deliverymode","userpasswordrfc2617","cn","objectclass",$GLOBALS['phpgw_info']['server']['atributoexpiracao']);
+		$search = ldap_search($this->ldap, $context, $filter, $justthese);
+		//$search = ldap_search($this->ldap, $context, $filter);
+		$entry = ldap_get_entries($this->ldap, $search);
+
+		//Pega o dn do setor do usuario.
+		$entry[0]['dn'] = strtolower($entry[0]['dn']);
+		$sector_dn_array = explode(",", $entry[0]['dn']);
+		for($i=1; $i<count($sector_dn_array); $i++)
+			$sector_dn .= $sector_dn_array[$i] . ',';
+		//Retira ultimo pipe.
+		$sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
+	
+	    $result['dn']               = $entry[0]['dn'];
+	    $result['ou']               = $entry[0]['ou'][0];
+		$result['context']			= $sector_dn;
+		$result['uid']				= $entry[0]['uid'][0];
+		$result['uidnumber']		= $entry[0]['uidnumber'][0];
+		$result['gidnumber']		= $entry[0]['gidnumber'][0];
+		$result['departmentnumber']	= $entry[0]['departmentnumber'][0];
+		$result['givenname']		= $entry[0]['givenname'][0];
+		$result['sn']				= $entry[0]['sn'][0];
+		$result['telephonenumber']	= $entry[0]['telephonenumber'][0];
+                $result['mobile']	= $entry[0]['mobile'][0];
+		$result['phpgwaccountstatus']	= $entry[0]['phpgwaccountstatus'][0];
+		$result['phpgwaccountvisible']	= $entry[0]['phpgwaccountvisible'][0];
+		$result['accountstatus']	= $entry[0]['accountstatus'][0];
+		$result['mail']				= $entry[0]['mail'][0];
+		$result['defaultMemberModeration']   = $entry[0]['defaultmembermoderation'][0];
+		$result['admlista']                  = $entry[0]['admlista'][0];
+		$result['listPass']			= $entry[0]['listPass'][0];
+		$result['mailalternateaddress']	= $entry[0]['mailalternateaddress'][0];
+		$result['mailforwardingaddress']= $entry[0]['mailforwardingaddress'][0];
+		$result['deliverymode']		= $entry[0]['deliverymode'][0];
+		$result['userPasswordRFC2617']	= $entry[0]['userpasswordrfc2617'][0];
+		$result['cn']				= $entry[0]['cn'][0];
+		$result['phpgwaccount']		= false;
+		if(isset($GLOBALS['phpgw_info']['server']['atributoexpiracao']))
+			$result[$GLOBALS['phpgw_info']['server']['atributoexpiracao']]	= $entry[0][$GLOBALS['phpgw_info']['server']['atributoexpiracao']][0];
+			else
+			$result['phpgwaccountexpires'] = $entry[0]['phpgwaccountexpires'][0];
+		//objectclass phpgwaccount
+		foreach ($entry[0]['objectclass'] as $objectclass)
+			{
+			if  (strcasecmp($objectclass, 'phpgwaccount') == 0)
+				$result['phpgwaccount']  = true;
+			}
+		//Photo
+		if ($entry[0]['jpegphoto']['count'] == 1)
+			$result['photo_exist'] = 'true';
+		
+		// Samba
+		for ($i=0; $i<$entry[0]['objectclass']['count']; $i++)
+		{
+			if ($entry[0]['objectclass'][$i] == 'sambaSamAccount')
+				$result['sambaUser'] = true;
+		}		 
+		if (($this->current_config['expressoAdmin_samba_support'] == 'true') && ($result['sambaUser']))
+		{
+			$result['sambaaccflags'] = $entry[0]['sambaacctflags'][0];
+			$result['sambalogonscript'] = $entry[0]['sambalogonscript'][0];
+			$result['homedirectory'] = $entry[0]['homedirectory'][0];
+			$a_tmp = explode("-", $entry[0]['sambasid'][0]);
+			array_pop($a_tmp);
+			$result['sambasid'] = implode("-", $a_tmp);
+		}
+		
+		// MailLists
+		$justthese = array("uid","mail","uidnumber");
+		$filter="(&(phpgwAccountType=l)(mailforwardingaddress=".$result['mail']."))";
+		$search = ldap_search($this->ldap, $context, $filter, $justthese);
+    	ldap_sort($this->ldap, $search, "uid");
+    	$entries = ldap_get_entries($this->ldap, $search);
+
+    	for ($i=0; $i<$entries['count']; $i++)
+    	{
+    		$result['maillists_info'][$i]['uidnumber'] = $entries[$i]['uidnumber'][0];
+    		$result['maillists_info'][$i]['uid'] = $entries[$i]['uid'][0];
+    		$result['maillists_info'][$i]['mail'] = $entries[$i]['mail'][0];
+    		$result['maillists'][] = $entries[$i]['uidnumber'][0];
+    	}
+    	
+    	// Groups
+		$justthese = array("gidnumber","cn");
+		$filter="(&(phpgwAccountType=g)(memberuid=".$result['uid']."))";
+		$search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+    	ldap_sort($this->ldap, $search, "cn");
+    	$entries = ldap_get_entries($this->ldap, $search);
+    	for ($i=0; $i<$entries['count']; $i++)
+    	{
+    		$result['groups_ldap'][ $entries[$i]['gidnumber'][0] ] = $entries[$i]['cn'][0];
+		$result['groups'][ $entries[$i]['gidnumber'][0] ] = $entries[$i]['gidnumber'][0];
+		$result['groups_info'][ $entries[$i]['gidnumber'][0] ] = $entries[$i]['gidnumber'][0];
+    	}
+		return $result;		
+	}
+	
+	function get_group_info($gidnumber, $context)
+	{
+		$filter="(&(phpgwAccountType=g)(gidNumber=".$gidnumber."))";
+		$search = ldap_search($this->ldap, $context, $filter);
+		$entry = ldap_get_entries($this->ldap, $search);
+
+		//Pega o dn do setor do grupo.
+		$entry[0]['dn'] = strtolower($entry[0]['dn']);
+		$sector_dn_array = explode(",", $entry[0]['dn']);
+		for($i=1; $i<count($sector_dn_array); $i++)
+			$sector_dn .= $sector_dn_array[$i] . ',';
+		//Retira ultimo pipe.
+		$sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
+		
+		$result['context']				= $sector_dn;
+		$result['cn']					= $entry[0]['cn'][0];
+		$result['description']			= $entry[0]['description'][0];
+		$result['gidnumber']			= $entry[0]['gidnumber'][0];
+		$result['phpgwaccountvisible']	= $entry[0]['phpgwaccountvisible'][0];
+		$result['email']				= $entry[0]['mail'][0];
+		
+		//MemberUid
+		for ($i=0; $i<$entry[0]['memberuid']['count']; $i++)
+		{
+			$justthese = array("cn","uid","uidnumber");
+			
+			// Montagem dinamica do filtro
+			$filter="(&(phpgwAccountType=u)(|";
+			for ($k=0; (($k<10) && ($i<$entry[0]['memberuid']['count'])); $k++)
+			{
+				$filter .= "(uid=".$entry[0]['memberuid'][$i].")";
+				$i++;
+			}
+			$i--;
+			$filter .= "))";
+			
+			$search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+			$user_entry = ldap_get_entries($this->ldap, $search);
+
+			for ($j=0; $j<$user_entry['count']; $j++)
+			{
+				$result['memberuid_info'][$user_entry[$j]['uid'][0]]['cn'] = $user_entry[$j]['cn'][0];
+				$result['memberuid_info'][$user_entry[$j]['uid'][0]]['uidnumber'] = $user_entry[$j]['uidnumber'][0];
+				$result['memberuid_info'][$user_entry[$j]['uid'][0]]['type'] = 'u';
+			}
+		}
+		
+		// Retira o count do array
+		array_shift($entry[0]['memberuid']);
+		
+		// Checamos e-mails que nï¿œo fazem parte do expresso.
+		// Criamos um array temporario
+		$tmp_array = array();
+		foreach ($result['memberuid_info'] as $uid => $user_data)
+		{
+			$tmp_array[] = $uid;
+		}
+
+		// Vemos a diferenï¿œa
+		$array_diff = array_diff($entry[0]['memberuid'], $tmp_array);
+		
+		// Incluimos no resultado
+		foreach ($array_diff as $index=>$uid)
+		{
+			$result['memberuid_info'][$uid]['cn'] = $uid;
+		}
+		
+		// Samba
+		for ($i=0; $i<$entry[0]['objectclass']['count']; $i++)
+		{
+			if ($entry[0]['objectclass'][$i] == 'sambaGroupMapping')
+				$result['sambaGroup'] = true;
+
+			$a_tmp = explode("-", $entry[0]['sambasid'][0]);
+			array_pop($a_tmp);
+			$result['sambasid'] = implode("-", $a_tmp);
+		}
+
+		return $result;
+	}	
+	
+	function get_maillist_info($uidnumber, $context)
+	{
+		$filter="(&(phpgwAccountType=l)(uidNumber=".$uidnumber."))";
+		$search = ldap_search($this->ldap, $context, $filter);
+		$entry = ldap_get_entries($this->ldap, $search);
+	
+		//Pega o dn do setor do usuario.
+		$entry[0]['dn'] = strtolower($entry[0]['dn']);
+		$sector_dn_array = explode(",", $entry[0]['dn']);
+		for($i=1; $i<count($sector_dn_array); $i++)
+			$sector_dn .= $sector_dn_array[$i] . ',';
+		//Retira ultimo pipe.
+		$sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
+
+		$result['context']			= $sector_dn;
+		$result['uidnumber']			= $entry[0]['uidnumber'][0];
+		$result['uid']				= $entry[0]['uid'][0];
+		$result['cn']				= $entry[0]['cn'][0];
+		$result['admlista']			= $entry[0]['admlista'][0];
+		$result['defaultMemberModeration']      = $entry[0]['defaultmembermoderation'][0];
+		$result['listPass']			= $entry[0]['listPass'][0];
+		$result['mail']				= $entry[0]['mail'][0];
+		$result['accountStatus']		= $entry[0]['accountstatus'][0];
+		$result['accountAdm']                	= $entry[0]['accountAdm'][0];
+		$result['phpgwAccountVisible']		= $entry[0]['phpgwaccountvisible'][0];
+		$result['description']			= $entry[0]['description'][0];
+			
+		//Members
+		for ($i=0; $i<$entry[0]['mailforwardingaddress']['count']; $i++)
+		{
+			$justthese = array("cn", "uidnumber", "uid", "phpgwaccounttype", "mail");
+				
+			// Montagem dinamica do filtro
+			$filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|";
+			for ($k=0; (($k<10) && ($i<$entry[0]['mailforwardingaddress']['count'])); $k++)
+			{
+				$filter .= "(mail=".$entry[0]['mailforwardingaddress'][$i].")";
+				$i++;
+			}
+			$i--;
+			$filter .= "))";
+				
+			$search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+			$user_entry = ldap_get_entries($this->ldap, $search);
+				
+			for ($j=0; $j<$user_entry['count']; $j++)
+			{
+				$result['members_info'][$user_entry[$j]['uidnumber'][0]]['uid'] = $user_entry[$j]['uid'][0];
+				$result['members_info'][$user_entry[$j]['uidnumber'][0]]['cn'] = $user_entry[$j]['cn'][0];
+				$result['members_info'][$user_entry[$j]['uidnumber'][0]]['type'] = $user_entry[$j]['phpgwaccounttype'][0];
+				$result['members_info'][$user_entry[$j]['uidnumber'][0]]['mail'] = $user_entry[$j]['mail'][0];
+				$result['members'][] = $user_entry[$j]['uidnumber'][0];
+			}
+		}
+
+		// Retira o count do array
+		array_shift($entry[0]['mailforwardingaddress']);
+
+		// Checamos e-mails que nï¿œo fazem parte do expresso.
+		// Criamos um array temporario
+		$tmp_array = array();
+		foreach ($result['members_info'] as $uid => $user_data)
+		{
+			$tmp_array[] = $user_data['mail'];
+		}
+
+		// Vemos a diferenï¿œa
+		$array_diff = array_diff($entry[0]['mailforwardingaddress'], $tmp_array);
+
+		// Incluimos no resultado
+		foreach ($array_diff as $index=>$mailforwardingaddress)
+		{
+			$result['members_info'][$mailforwardingaddress]['uid'] = $mailforwardingaddress;
+			//$result['members_info'][$mailforwardingaddress]['cn'] = 'E-Mail nao encontrado';
+			$result['members_info'][$mailforwardingaddress]['cn'] = '';
+			$result['members_info'][$mailforwardingaddress]['mailforwardingaddress'] = $mailforwardingaddress;
+			$result['members'][] = $mailforwardingaddress;
+		}
+		return $result;	
+	}	
+
+	function get_adm_maillist_info($uidnumber, $context) // Funcao que coleta as informacoes dos administradores de listas no LDAP
+	{
+		$filter="(&(phpgwAccountType=l)(uidNumber=".$uidnumber."))";
+		$search = ldap_search($this->ldap, $context, $filter);
+		$entry = ldap_get_entries($this->ldap, $search);
+	
+		//Pega o dn do setor do usuario.
+		$entry[0]['dn'] = strtolower($entry[0]['dn']);
+		$sector_dn_array = explode(",", $entry[0]['dn']);
+		for($i=1; $i<count($sector_dn_array); $i++)
+			$sector_dn .= $sector_dn_array[$i] . ',';
+		//Retira ultimo pipe.
+		$sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
+			
+		$result['context']			= $sector_dn;
+		$result['uidnumber']			= $entry[0]['uidnumber'][0];
+		$result['uid']				= $entry[0]['uid'][0];
+		$result['cn']				= $entry[0]['cn'][0];
+		$result['listPass']			= $entry[0]['listPass'][0];
+		$result['mail']				= $entry[0]['mail'][0];
+		$result['accountStatus']		= $entry[0]['accountstatus'][0];
+		$result['accountAdm']                	= $entry[0]['accountAdm'][0];
+		$result['phpgwAccountVisible']		= $entry[0]['phpgwaccountvisible'][0];
+		$result['description']			= $entry[0]['description'][0];
+
+		//Members
+		for ($i=0; $i<$entry[0]['admlista']['count']; $i++)
+		{
+			$justthese = array("cn", "uidnumber", "uid", "phpgwaccounttype", "mail", "admlista");
+				
+			// Montagem dinamica do filtro
+			$filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(|";
+			for ($k=0; (($k<10) && ($i<$entry[0]['admlista']['count'])); $k++)
+			{
+				$filter .= "(mail=".$entry[0]['admlista'][$i].")";
+				$i++;
+			}
+			$i--;
+			$filter .= "))";
+				
+			$search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+			$user_entry = ldap_get_entries($this->ldap, $search);
+				
+			for ($j=0; $j<$user_entry['count']; $j++)
+			{
+				$result['members_info'][$user_entry[$j]['uidnumber'][0]]['uid'] = $user_entry[$j]['uid'][0];
+				$result['members_info'][$user_entry[$j]['uidnumber'][0]]['cn'] = $user_entry[$j]['cn'][0];
+				$result['members_info'][$user_entry[$j]['uidnumber'][0]]['type'] = $user_entry[$j]['phpgwaccounttype'][0];
+				$result['members_info'][$user_entry[$j]['uidnumber'][0]]['mail'] = $user_entry[$j]['mail'][0];
+				$result['members'][] = $user_entry[$j]['uidnumber'][0];
+			}
+		}
+
+		// Retira o count do array
+		array_shift($entry[0]['admlista']);
+
+		// Checamos e-mails que nï¿œo fazem parte do expresso.
+		// Criamos um array temporario
+		$tmp_array = array();
+		foreach ($result['members_info'] as $uid => $user_data)
+		{
+			$tmp_array[] = $user_data['mail'];
+		}
+
+		// Vemos a diferenï¿œa
+		$array_diff = array_diff($entry[0]['admlista'], $tmp_array);
+
+		// Incluimos no resultado
+		foreach ($array_diff as $index=>$admlista)
+		{
+			$result['members_info'][$admlista]['uid'] = $admlista;
+			//$result['members_info'][$admlista]['cn'] = 'E-Mail nao encontrado';
+			$result['members_info'][$admlista]['cn'] = '';
+			$result['members_info'][$admlista]['admlista'] = $admlista;
+			$result['members'][] = $admlista;
+		}
+		return $result;	
+	}	
+
+
+	function get_maillist_scl_info($uidnumber, $context)
+	{
+		$filter="(&(phpgwAccountType=l)(uidNumber=".$uidnumber."))";
+		$search = ldap_search($this->ldap, $context, $filter);
+		$entry = ldap_get_entries($this->ldap, $search);
+
+		//Pega o dn do setor do usuario.
+		$entry[0]['dn'] = strtolower($entry[0]['dn']);
+		$sector_dn_array = explode(",", $entry[0]['dn']);
+		for($i=1; $i<count($sector_dn_array); $i++)
+			$sector_dn .= $sector_dn_array[$i] . ',';
+		//Retira ultimo pipe.
+		$sector_dn = substr($sector_dn,0,(strlen($sector_dn) - 1));
+		
+		$result['dn']				= $entry[0]['dn'];
+		$result['context']			= $sector_dn;
+		$result['uidnumber']		        = $entry[0]['uidnumber'][0];
+		$result['uid']				= $entry[0]['uid'][0];
+		$result['cn']				= $entry[0]['cn'][0];
+		$result['mail']				= $entry[0]['mail'][0];
+		$result['accountStatus']	        = $entry[0]['accountstatus'][0];
+		$result['accountAdm']                   = $entry[0]['accountAdm'][0];
+		$result['phpgwAccountVisible']		= $entry[0]['phpgwaccountvisible'][0];
+		$result['accountRestrictive']		= $entry[0]['accountrestrictive'][0];
+		$result['participantCanSendMail']	= $entry[0]['participantcansendmail'][0];
+		$result['description']			= $entry[0]['description'][0];
+		
+		//Senders
+		//for ($i=0; $i<$entry[0]['mailsenderaddress']['count']; $i++)
+		//Recupera a relacao de usuario nao moderados no Mailman (podem enviar e-mails para uma lista de e-mail sem precisar da
+		//autorizacao do moderador;
+		for ($i=0; $i<$entry[0]['naomoderado']['count']; $i++)
+		{
+			$justthese = array("cn", "uidnumber", "uid", "mail");
+			$filter="(&(phpgwAccountType=u)(mail=".$entry[0]['naomoderado'][$i]."))";
+			$search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+			$user_entry = ldap_get_entries($this->ldap, $search);
+			
+			$result['senders_info'][$user_entry[0]['uidnumber'][0]]['uid'] = $user_entry[0]['uid'][0];
+			$result['senders_info'][$user_entry[0]['uidnumber'][0]]['cn'] = $user_entry[0]['cn'][0];
+			$result['senders_info'][$user_entry[0]['uidnumber'][0]]['mail'] = $user_entry[0]['mail'][0];
+			$result['members'][] = $user_entry[0]['uidnumber'][0];
+		}
+
+		return $result;
+	}	
+
+	function group_exist($gidnumber)
+	{
+		$justthese = array("cn");
+		$filter="(&(phpgwAccountType=g)(gidNumber=".$gidnumber."))";
+		$search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+				
+		$entry = ldap_get_entries($this->ldap, $search);
+		if ($entry['count'] == 0)
+			return false;
+		else
+			return true;
+	}
+
+	function gidnumbers2cn($gidnumbers, $context)
+	{
+		$result = array();
+		if (count($gidnumbers))
+		{
+			$justthese = array("cn");
+			$i = 0;
+			foreach ($gidnumbers as $gidnumber)
+			{
+				$filter="(&(phpgwAccountType=g)(gidNumber=".$gidnumber."))";
+				$search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+				
+				$entry = ldap_get_entries($this->ldap, $search);
+				if ($entry['count'] == 0)
+					$result['groups_info'][$i]['cn'] = '_Grupo existe no BD mas nï¿œo no LDAP';
+				else
+					$result['groups_info'][$i]['cn'] = $entry[0]['cn'][0];
+				$result['groups_info'][$i]['gidnumber'] = $gidnumber;
+				
+				if (!strpos(strtolower($entry[0]['dn']), strtolower($context)))
+					$result['groups_info'][$i]['group_disabled'] = 'true';
+				else
+					$result['groups_info'][$i]['group_disabled'] = 'false';
+				
+				$i++;
+			}
+		}
+		return $result;
+	}
+
+	function uidnumber2uid($uidnumber)
+	{
+		$justthese = array("uid");
+		$filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uidNumber=".$uidnumber."))";
+		$search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+		$entry = ldap_get_entries($this->ldap, $search);
+		return $entry[0]['uid'][0];
+	}
+
+	function uid2uidnumber($uid)
+	{
+	       $justthese = array("uidnumber");
+	       $filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uid=".$uid."))";
+	       $search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+	       $entry = ldap_get_entries($this->ldap, $search);
+	       return $entry[0]['uidnumber'][0];
+	}
+
+	function uidnumber2mail($uidnumber)
+	{
+		$justthese = array("mail");
+		$filter="(&(|(phpgwAccountType=u)(phpgwAccountType=l))(uidNumber=".$uidnumber."))";
+		$search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+		$entry = ldap_get_entries($this->ldap, $search);
+		return $entry[0]['mail'][0];
+	}
+
+	
+	function change_user_context($dn, $newrdn, $newparent)
+	{
+		if (!ldap_rename ( $this->ldap_write, $dn, $newrdn, $newparent, true ))
+		{
+			$return['status'] = false;
+			$return['msg'] = 'Erro em ldap_funcitons->change_user_context: ' . ldap_error($this->ldap_write);
+		}
+		else
+			$return['status'] = true;
+		return $return;
+	}
+	
+	function replace_user_attributes($dn, $ldap_mod_replace)
+	{
+		if (!@ldap_mod_replace ( $this->ldap_write, $dn, $ldap_mod_replace ))
+		{
+			$return['status'] = false;
+			$return['msg'] = 'Erro em ldap_funcitons->replace_user_attributes: ' . ldap_error($this->ldap_write);
+		}
+		else
+			$return['status'] = true;
+		return $return;
+	}
+	
+	function add_user_attributes($dn, $ldap_add)
+	{
+		if (!@ldap_mod_add ( $this->ldap_write, $dn, $ldap_add ))
+		{
+			$return['status'] = false;
+			$return['msg'] = 'Erro em ldap_funcitons->add_user_attributes: ' . ldap_error($this->ldap_write);
+		}
+		else
+			$return['status'] = true;
+		
+		return $return;
+	}
+	
+	function remove_user_attributes($dn, $ldap_remove)
+	{
+		if (!@ldap_mod_del ( $this->ldap_write, $dn, $ldap_remove ))
+		{
+			$return['status'] = false;
+			$return['msg'] = 'Erro em ldap_funcitons->remove_user_attributes: ' . ldap_error($this->ldap_write);
+		}
+		else
+			$return['status'] = true;
+		
+		return $return;
+	}
+	
+	function set_user_password($uid, $password)
+	{
+		$justthese = array("userPassword");
+		$filter="(&(phpgwAccountType=u)(uid=".$uid."))";
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+		$entry = ldap_get_entries($this->ldap_write, $search);
+		$dn = $entry[0]['dn'];
+		$userPassword = $entry[0]['userpassword'][0];
+		$ldap_mod_replace['userPassword'] = $password;
+		$this->replace_user_attributes($dn, $ldap_mod_replace);
+		return $userPassword;
+	}
+
+	function set_user_expires($uid, $expires)
+	{
+		$justthese = array(" ");
+		$filter="(&(phpgwAccountType=u)(uid=".$uid."))";
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+		$entry = ldap_get_entries($this->ldap_write, $search);
+		$dn = $entry[0]['dn'];
+		if(isset($GLOBALS['phpgw_info']['server']['atributoexpiracao']))
+			{
+			if(substr($GLOBALS['phpgw_info']['server']['atributoexpiracao'],-1,1)=="Z")
+				{
+				###quando a data de expiracao estah no formato yyyymmddhhmmssZ
+				$ldap_mod_replace[$GLOBALS['phpgw_info']['server']['atributoexpiracao']] = strftime("%Y%m%d%H%M%SZ", $expires);
+				}
+				else
+				{
+				###Outro atributo ldap que, assim como o phpgwaccounttype, tambem contem hora em formato unix
+				$ldap_mod_replace[$GLOBALS['phpgw_info']['server']['atributoexpiracao']] = $expires;
+				}
+			}
+		else
+			{
+			$ldap_mod_replace['phpgwaccountexpires'] = $expires;
+			}
+		//$ldap_mod_replace['phpgwaccountexpires'] = $expires;
+		$this->replace_user_attributes($dn, $ldap_mod_replace);
+		return true;
+	}
+	
+	function delete_user($user_info)
+	{
+		$return['status'] = true;
+		
+		// GROUPS
+		$attrs = array();
+		$attrs['memberUid'] = $user_info['uid'];
+		if (count($user_info['groups_info']))
+		{
+			foreach ($user_info['groups_info'] as $group_info)
+			{
+				$gidnumber = $group_info['gidnumber'];
+				$justthese = array("dn");
+				$filter="(&(phpgwAccountType=g)(gidnumber=".$gidnumber."))";
+				$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+	    		$entry = ldap_get_entries($this->ldap_write, $search);
+				$dn = $entry[0]['dn'];
+			
+				if (!@ldap_mod_del($this->ldap_write, $dn, $attrs))
+				{
+					$return['status'] = false;
+					$return['msg'] .= 'Erro em ldap_funcitons->delete_user, grupos: ' . ldap_error($this->ldap_write);
+				}
+			}
+		}
+			
+		// MAILLISTS
+		$attrs = array();
+		$attrs['mailForwardingAddress'] = $user_info['mail'];
+		if (count($user_info['maillists_info']))
+		{
+			foreach ($user_info['maillists_info'] as $maillists_info)
+			{
+				$uidnumber = $maillists_info['uidnumber'];
+				$justthese = array("dn");
+				$filter="(&(phpgwAccountType=l)(uidnumber=".$uidnumber."))";
+				$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+	    		$entry = ldap_get_entries($this->ldap_write, $search);
+				$dn = $entry[0]['dn'];
+			
+				if (!@ldap_mod_del($this->ldap_write, $dn, $attrs))
+				{
+					$return['status'] = false;
+					$return['msg'] .= 'Erro em ldap_funcitons->delete_user, listas de email: ' . ldap_error($this->ldap_write);
+				}
+			}
+		}
+			
+		// UID
+		$dn = "uid=" . $user_info['uid'] . "," . $user_info['context'];
+		if (!@ldap_delete($this->ldap_write, $dn))
+		{
+			$return['status'] = false;
+			$return['msg'] .= 'Erro em ldap_funcitons->delete_user, listas de email: ' . ldap_error($this->ldap_write);
+		}
+		
+		return $return;
+	}
+function delete_user_group($user,$groups)
+        {
+        $return['status'] = true;
+        $attrs = array();
+        $attrs['memberUid'] = $user['uid'];
+	if ($groups['groups'])
+		{
+                foreach ($groups['groups'] as $gidnumber)
+                         {
+	                 $justthese = array("dn");
+	                 $filter="(&(phpgwAccountType=g)(gidnumber=".$gidnumber."))";
+	                 $search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+                         $entry = ldap_get_entries($this->ldap_write, $search);
+                         $dn = $entry[0]['dn'];
+                         if (!@ldap_mod_del($this->ldap_write, $dn, $attrs))
+                                {
+                                $return['status'] = false;
+	                        $return['msg'] .= 'Erro em ldap_funcitons->delete_user, grupos: ' . ldap_error($this->ldap_write);
+	                        }
+              		}
+		}
+        return $return;
+        }
+function delete_maillist($uidnumber)
+	{
+		$return['status'] = true;
+		
+		$justthese = array("dn");
+		$filter="(&(phpgwAccountType=l)(uidnumber=".$uidnumber."))";
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+   		$entry = ldap_get_entries($this->ldap_write, $search);
+		$dn = $entry[0]['dn'];
+		
+		if (!@ldap_delete($this->ldap_write, $dn))
+		{
+			$return['status'] = false;
+			$return['msg'] .= 'Erro em ldap_funcitons->delete_maillist, listas de email: ' . ldap_error($this->ldap_write);
+		}
+		
+		return $return;
+	}
+
+	function delete_group($gidnumber)
+	{
+		$return['status'] = true;
+		
+		$justthese = array("dn");
+		$filter="(&(phpgwAccountType=g)(gidnumber=".$gidnumber."))";
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+   		$entry = ldap_get_entries($this->ldap_write, $search);
+		$dn = $entry[0]['dn'];
+		
+		if (!@ldap_delete($this->ldap_write, $dn))
+		{
+			$return['status'] = false;
+			$return['msg'] .= 'Erro em ldap_funcitons->delete_maillist, listas de email: ' . ldap_error($this->ldap_write);
+		}
+		
+		return $return;
+	}
+
+	
+	function rename_uid($uid, $new_uid)
+	{
+		$return['status'] = true;
+		
+		$justthese = array("dn");
+		$filter="(&(phpgwAccountType=u)(uid=".$uid."))";
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+	    $entry = ldap_get_entries($this->ldap_write, $search);
+		$dn = $entry[0]['dn'];
+		
+		$explode_dn = ldap_explode_dn($dn, 0);
+		$rdn = "uid=" . $new_uid;
+
+		$parent = array();
+		for ($j=1; $j<(count($explode_dn)-1); $j++)
+			$parent[] = $explode_dn[$j];
+		$parent = implode(",", $parent);
+		
+		$return['new_dn'] = $rdn . ',' . $parent;
+			
+		if (!@ldap_rename($this->ldap_write, $dn, $rdn, $parent, false))
+		{
+			$return['status'] = false;
+			$return['msg'] .= 'Erro em ldap_funcitons->rename_uid: ' . ldap_error($this->ldap_write);
+		}
+		
+		//Grupos
+		$justthese = array("dn");
+		$filter="(&(phpgwAccountType=g)(memberuid=".$uid."))";
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+	    $entry = ldap_get_entries($this->ldap_write, $search);
+    	$array_mod_add['memberUid'] = $new_uid;
+    	$array_mod_del['memberUid'] = $uid;
+
+	    for ($i=0; $i<=$entry['count']; $i++)
+	    {
+	    	$dn = $entry[$i]['dn'];
+	    	@ldap_mod_add ( $this->ldap_write, $dn,  $array_mod_add);
+	    	@ldap_mod_del ( $this->ldap_write, $dn,  $array_mod_del);
+	    }
+		return $return;
+	}
+
+	function rename_cn($cn, $new_cn)
+	{
+		$return['status'] = true;
+		
+		$justthese = array("dn");
+		$filter="(&(phpgwAccountType=g)(uid=".$cn."))";
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+	    $entry = ldap_get_entries($this->ldap_write, $search);
+		$dn = $entry[0]['dn'];
+		
+		$explode_dn = ldap_explode_dn($dn, 0);
+		$rdn = "cn=" . $new_cn;
+
+		$parent = array();
+		for ($j=1; $j<(count($explode_dn)-1); $j++)
+			$parent[] = $explode_dn[$j];
+		$parent = implode(",", $parent);
+		
+		$return['new_dn'] = $rdn . ',' . $parent;
+			
+		if (!@ldap_rename($this->ldap_write, $dn, $rdn, $parent, false))
+		{
+			$return['status'] = false;
+		}
+		
+		return $return;
+	}
+/*
+	function rename_departmentnumber($old_dp, $new_dp)
+	{
+		$return['status'] = true;
+		
+		$justthese = array("dn");
+		$filter="(&(phpgwAccountType=u)(departmentnumber=".$old_dp."))";
+		$search = ldap_search($this->ldap, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter, $justthese);
+	    $entry = ldap_get_entries($this->ldap, $search);
+		
+	    for ($i=0; $i<=$entry['count']; $i++)
+	    {
+	    	$dn = strtolower($entry[$i]['dn']);
+	    	$ldap_mod_replace = array();
+	    	$ldap_mod_replace['departmentnumber'] = $new_dp;
+	    	@ldap_mod_replace ( $this->ldap, $dn,  $ldap_mod_replace);
+			//if (!@ldap_mod_replace ( $this->ldap, $dn,  $ldap_mod_replace))
+			//{
+			//	$return['status'] = false;
+			//	$return['msg'] .= 'Erro em ldap_funcitons->rename_departmentnumber: ' . ldap_error($this->ldap);
+			//}
+	    }
+		return $return;
+	}
+*/
+/*
+	function get_sambadomains($context)
+	{
+		$return['status'] = true;
+		$return['sambaDomains'] = array();
+		
+		$justthese = array("sambaSID","sambaDomainName");
+		$filter="(objectClass=sambaDomain)";
+		$search = ldap_search($this->ldap, $context, $filter, $justthese);
+	    $entry = ldap_get_entries($this->ldap, $search);
+		
+	    for ($i=0; $i<$entry['count']; $i++)
+	    {
+			$return['sambaDomains'][$i]['samba_domain_sid'] = $entry[$i]['sambasid'][0];
+			$return['sambaDomains'][$i]['samba_domain_name'] = $entry[$i]['sambadomainname'][0];
+			$return['sambaDomains'][$i]['samba_domain_dn'] = $entry[$i]['dn'];
+	    }
+	    
+		return $return;
+	}
+*/
+	function exist_sambadomains($context, $sambaDomainName)
+	{
+		$justthese = array("dn");
+		$filter="(&(objectClass=sambaDomain)(sambaDomainName=$sambaDomainName))";
+		$search = ldap_search($this->ldap_write, $context, $filter, $justthese);
+	    $entry = ldap_get_entries($this->ldap_write, $search);
+	    
+		if ($entry['count'])
+			return true;
+		else
+			return false;
+	}
+	
+	// Primeiro nilvel de organizaï¿œï¿œo.
+	function exist_sambadomains_in_context($params)
+	{
+		$dn = $GLOBALS['phpgw_info']['server']['ldap_context'];
+		$array_dn = ldap_explode_dn ( $dn, 0 );
+		
+		$context = $params['context'];
+		$array_context = ldap_explode_dn ( $context, 0 );
+		
+		// Pego o setor no caso do contexto ser um sub-setor.
+		if (($array_dn['count']+1) < ($array_context['count']))
+		{
+			// inverto o array_dn para poder retirar o count
+			$array_dn_reverse  = array_reverse ( $array_dn, false );
+			
+			//retiro o count
+			array_pop($array_dn_reverse);
+			
+			//incluo o setor no dn
+			array_push ( $array_dn_reverse,  $array_context[ $array_context['count'] - 1 - $array_dn['count']]);
+			
+			// Volto a ordem natural
+			$array_dn  = array_reverse ( $array_dn_reverse, false );
+			
+			// Implodo
+			$context = implode ( ",", $array_dn );
+		}
+		
+		$justthese = array("dn","sambaDomainName");
+		$filter="(objectClass=sambaDomain)";
+		$search = ldap_list($this->ldap_write, $context, $filter, $justthese);
+	    $entry = ldap_get_entries($this->ldap_write, $search);
+	    
+   	    for ($i=0; $i<$entry['count']; $i++)
+	    {
+			$return['sambaDomains'][$i] = $entry[$i]['sambadomainname'][0];
+	    }
+	    
+		if ($entry['count'])
+			$return['status'] = true;
+		else
+			$return['status'] = false;
+			
+		return $return;
+	}
+	
+	function add_sambadomain($sambadomainname, $sambasid, $context)
+	{
+		$result = array();
+		
+		$dn 								= "sambaDomainName=$sambadomainname,$context";
+		$entry['sambaSID'] 					= $sambasid;
+		$entry['objectClass'] 				= 'sambaDomain';
+		$entry['sambaAlgorithmicRidBase']	= '1000';
+		$entry['sambaDomainName']			= $sambadomainname;
+		
+		if (!@ldap_add ( $this->ldap_write, $dn, $entry ))
+		{
+			$return['status'] = false;
+			$return['msg'] = "Erro na funcao ldap_functions->add_sambadomain ($dn).\nRetorno do servidor: " . ldap_error($this->ldap_write);
+		}
+		else
+			$return['status'] = true;
+		
+		return $return;
+	}
+	
+	function delete_sambadomain($sambadomainname)
+	{
+		$return['status'] = true;
+		$filter="(sambaDomainName=$sambadomainname)";
+		$search = ldap_search($this->ldap_write, $GLOBALS['phpgw_info']['server']['ldap_context'], $filter);
+	    $entry = ldap_get_entries($this->ldap_write, $search);
+	 
+	 	if ($entry['count'] != 0)
+	    {
+			$dn = $entry[0]['dn'];
+			
+			if (!@ldap_delete($this->ldap_write, $dn))
+			{
+				$return['status'] = false;
+				$return['msg'] .= "Erro em ldap_functions->delete_sambadomain ($sambadomainname).\nRetorno do servidor: " . ldap_error($this->ldap_write);
+			}
+	    }
+	    
+		return $return;
+	}
+}
+//Geracao de senha criptografada pro Mailman
+
+	function encriptar($string)
+		{
+		$key='expresso-livre';
+		$result = '';
+		for($i=1; $i<=strlen($string); $i++)
+		{
+			$char = substr($string, $i-1, 1);
+			$keychar = substr($key, ($i % strlen($key))-1, 1);
+			$char = chr(ord($char)+ord($keychar));
+			$result.=$char;
+		}
+		return $result;
+		}
+
+?>
Index: /branches/2.2/listAdmin/inc/sieve-php.lib.php
===================================================================
--- /branches/2.2/listAdmin/inc/sieve-php.lib.php	(revision 3514)
+++ /branches/2.2/listAdmin/inc/sieve-php.lib.php	(revision 3514)
@@ -0,0 +1,905 @@
+<?php
+/**
+ * sieve-php.lib.php
+ *
+ * $Id$ 
+ *
+ * Copyright 2001-2003 Dan Ellis <danellis@rushmore.com>
+ *
+ * This program is released under the GNU Public License.  See the enclosed
+ * file COPYING for license information. If you did not receive this file, see
+ * http://www.fsf.org/copyleft/gpl.html.
+ *
+ * You should have received a copy of the GNU Public License along with this
+ * package; if not, write to the Free Software Foundation, Inc., 59 Temple
+ * Place - Suite 330, Boston, MA 02111-1307, USA.        
+ *
+ * See CHANGES for updates since last release
+ *
+ * @author Dan Ellis
+ * @package sieve-php
+ * @copyright Copyright 2002-2003, Dan Ellis, All Rights Reserved.  
+ * @version 0.1.0
+ */
+
+/**
+ * Constants
+ */
+define ("F_NO", 0);		
+define ("F_OK", 1);
+define ("F_DATA", 2);
+define ("F_HEAD", 3);
+
+define ("EC_NOT_LOGGED_IN", 0);
+define ("EC_QUOTA", 10);
+define ("EC_NOSCRIPTS", 20);
+define ("EC_UNKNOWN", 255);
+
+/**
+ * SIEVE class - A Class that implements MANAGESIEVE in PHP4|5.
+ *
+ * This program provides a handy interface into the Cyrus timsieved server
+ * under php4.  It is tested with Sieve server included in Cyrus 2.0, but it
+ * has been upgraded (not tested) to work with older Sieve server versions.
+ *
+ * All functions will return either true or false and will fill in
+ * $sieve->error with a defined error code like EC_QUOTA, raw server errors in
+ * $sieve->error_raw, and successful responses in $sieve->responses.
+ *
+ * NOTE: a major change since version (0.0.5) is the inclusion of a standard
+ * method to retrieve  server responses.  All functions will return either true
+ * or false and will fill in $sieve->error with a defined error code like
+ * EC_QUOTA, raw server errors in $sieve->error_raw, and successful responses
+ * in $sieve->responses.
+ *
+ * Usage is pretty simple.  The basics is login, do what you need and logout.
+ * There are two sample files (which suck) test.php and testsieve.php.
+ * test.php allows you to create/delete/view scripts and testsieve.php is a
+ * very basic sieve server test.
+ *
+ * Please let us know of any bugs, problems or ideas at sieve-php development
+ * list:  sieve-php-devel@lists.sourceforge.net. A web interface to subscribe
+ * to this list is available at:
+ * https://lists.sourceforge.net/mailman/listinfo/sieve-php-devel
+ *
+ * @author Dan Ellis
+ * @example simple_example.php A simple example that shows usage of sieve-php
+ * class.
+ * @example vacationset-sieve.php A more elaborate example of vacation script
+ * handling.
+ * @version 0.1.0
+ * @package sieve-php
+ * @todo Maybe add the NOOP function.
+ * @todo Have timing mechanism when port problems arise.
+ * @todo Provide better error diagnostics. 
+ */
+class sieve {
+  var $host;
+  var $port;
+  var $user;
+  var $pass;
+  /**
+   * a comma seperated list of allowed auth types, in order of preference
+   */
+  var $auth_types;
+  /**
+   * type of authentication attempted
+   */
+  var $auth_in_use;
+  
+  var $line;
+  var $fp;
+  var $retval;
+  var $tmpfile;
+  var $fh;
+  var $len;
+  var $script;
+
+  var $loggedin;
+  var $capabilities;
+  var $error;
+  var $error_raw;
+  var $responses;
+
+  //maybe we should add an errorlvl that the user will pass to new sieve = sieve(,,,,E_WARN)
+  //so we can decide how to handle certain errors?!?
+
+  /**
+   * get response
+   */
+  function get_response()
+  {
+    if($this->loggedin == false or feof($this->fp)){
+        $this->error = EC_NOT_LOGGED_IN;
+        $this->error_raw = "You are not logged in.";
+        return false;
+    }
+
+    unset($this->response);
+    unset($this->error);
+    unset($this->error_raw);
+
+    $this->line=fgets($this->fp,1024);
+    $this->token = split(" ", $this->line, 2);
+
+    if($this->token[0] == "NO"){
+        /* we need to try and extract the error code from here.  There are two possibilites: one, that it will take the form of:
+           NO ("yyyyy") "zzzzzzz" or, two, NO {yyyyy} "zzzzzzzzzzz" */
+        $this->x = 0;
+        list($this->ltoken, $this->mtoken, $this->rtoken) = split(" ", $this->line." ", 3);
+        if($this->mtoken[0] == "{"){
+            while($this->mtoken[$this->x] != "}" or $this->err_len < 1){
+                $this->err_len = substr($this->mtoken, 1, $this->x);
+                $this->x++;    
+            }
+            //print "<br>Trying to receive $this->err_len bytes for result<br>";
+            $this->line = fgets($this->fp,$this->err_len);
+            $this->error_raw[]=substr($this->line, 0, strlen($this->line) -2);    //we want to be nice and strip crlf's
+            $this->err_recv = strlen($this->line);
+
+            while($this->err_recv < $this->err_len){
+                //print "<br>Trying to receive ".($this->err_len-$this->err_recv)." bytes for result<br>";
+                $this->line = fgets($this->fp, ($this->err_len-$this->err_recv));
+                $this->error_raw[]=substr($this->line, 0, strlen($this->line) -2);    //we want to be nice and strip crlf's
+                $this->err_recv += strlen($this->line);
+            } /* end while */
+            $this->line = fgets($this->fp, 1024);	//we need to grab the last crlf, i think.  this may be a bug...
+            $this->error=EC_UNKNOWN;
+      
+        } /* end if */
+        elseif($this->mtoken[0] == "("){
+            switch($this->mtoken){
+                case "(\"QUOTA\")":
+                    $this->error = EC_QUOTA;
+                    $this->error_raw=$this->rtoken;
+                    break;
+                default:
+                    $this->error = EC_UNKNOWN;
+                    $this->error_raw=$this->rtoken;
+                    break;
+            } /* end switch */
+        } /* end elseif */
+        else{
+            $this->error = EC_UNKNOWN;
+            $this->error_raw = $this->line;
+        }     
+        return false;
+
+    } /* end if */
+    elseif(substr($this->token[0],0,2) == "OK"){
+         return true;
+    } /* end elseif */
+    elseif($this->token[0][0] == "{"){
+        
+        /* Unable wild assumption:  that the only function that gets here is the get_script(), doesn't really matter though */       
+
+        /* the first line is the len field {xx}, which we don't care about at this point */
+        $this->line = fgets($this->fp,1024);
+        while(substr($this->line,0,2) != "OK" and substr($this->line,0,2) != "NO"){
+            $this->response[]=$this->line;
+            $this->line = fgets($this->fp, 1024);
+        }
+        if(substr($this->line,0,2) == "OK")
+            return true;
+        else
+            return false;
+    } /* end elseif */
+    elseif($this->token[0][0] == "\""){
+
+        /* I'm going under the _assumption_ that the only function that will get here is the listscripts().
+           I could very well be mistaken here, if I am, this part needs some rework */
+
+        $this->found_script=false;        
+
+        while(substr($this->line,0,2) != "OK" and substr($this->line,0,2) != "NO"){
+            $this->found_script=true;
+            list($this->ltoken, $this->rtoken) = explode(" ", $this->line." ",2);
+		//hmmm, a bug in php, if there is no space on explode line, a warning is generated...
+           
+            if(strcmp(rtrim($this->rtoken), "ACTIVE")==0){
+                $this->response["ACTIVE"] = substr(rtrim($this->ltoken),1,-1);  
+            }
+            else
+                $this->response[] = substr(rtrim($this->ltoken),1,-1);
+            $this->line = fgets($this->fp, 1024);
+        } /* end while */
+        
+        return true;
+        
+    } /* end elseif */
+    else{
+            $this->error = EC_UNKNOWN;
+            $this->error_raw = $this->line;
+	    print '<b><i>UNKNOWN ERROR (Please report this line to <a
+	    href="mailto:sieve-php-devel@lists.sourceforge.net">sieve-php-devel
+	    Mailing List</a> to include in future releases):
+	    '.$this->line.'</i></b><br>';
+
+            return false;
+    } /* end else */   
+  } /* end get_response() */
+
+  /**
+   * Initialization of the SIEVE class.
+   * 
+   * It will return
+   * false if it fails, true if all is well.  This also loads some arrays up
+   * with some handy information:
+   *
+   * @param $host string hostname to connect to. Usually the IMAP server where
+   * a SIEVE daemon, such as timsieved, is listening.
+   *
+   * @param $port string Numeric port to connect to. SIEVE daemons usually
+   * listen to port 2000.
+   *
+   * @param $user string is a super-user or proxy-user that has ACL rights to
+   * login on behalf of the $auth.
+   *
+   * @param $pass string password to use for authentication
+   *
+   * @param $auth string is the authorized user identity for which the SIEVE
+   * scripts will be managed.
+   *
+   * @param $auth_types string a string containing all the allowed
+   * authentication types allowed in order of preference, seperated by spaces.
+   * (ex.  "PLAIN DIGEST-MD5 CRAM-MD5"  The method the library will try first
+   * is PLAIN.) The default for this value is PLAIN.
+   *
+   * Note: $user, if included, is the account name (and $pass will be the
+   * password) of an administrator account that can act on behalf of the user.
+   * If you are using Cyrus, you must make sure that the admin account has
+   * rights to admin the user.  This is to allow admins to edit/view users
+   * scripts without having to know the user's password.  Very handy.
+   */
+  function sieve($host, $port, $user, $pass, $auth="", $auth_types='PLAIN') {
+    $this->host=$host;
+    $this->port=$port;
+    $this->user=$user;
+    $this->pass=$pass;
+    if(!strcmp($auth, ""))		/* If there is no auth user, we deem the user itself to be the auth'd user */
+        $this->auth = $this->user;
+    else
+        $this->auth = $auth;
+    $this->auth_types=$auth_types;	/* Allowed authentication types */
+    $this->fp=0;
+    $this->line="";
+    $this->retval="";
+    $this->tmpfile="";
+    $this->fh=0;
+    $this->len=0;
+    $this->capabilities="";
+    $this->loggedin=false;
+    $this->error= "";
+    $this->error_raw="";
+  }
+
+   /**
+    * Tokenize a line of input by quote marks and return them as an array
+    *
+    * @param $string string Input line to parse for quotes
+    * @return array Array of broken by quotes parts of original string
+    */
+  function parse_for_quotes($string) {
+
+      $start = -1;
+      $index = 0;
+
+      for($ptr = 0; $ptr < strlen($string); $ptr++){
+          if($string[$ptr] == '"' and $string[$ptr] != '\\'){
+              if($start == -1){
+                  $start = $ptr;
+              } /* end if */
+              else{
+                  $token[$index++] = substr($string, $start + 1, $ptr - $start - 1);
+                  $found = true;
+                  $start = -1;
+              } /* end else */
+
+          } /* end if */  
+
+      } /* end for */
+
+      if(isset($token))
+          return $token;
+      else
+          return false;
+  } /* end function */            
+
+  /**
+   * Parser for status responses.
+   *
+   * This should probably be replaced by a smarter parser.
+   *
+   * @param $string string Input that contains status responses.
+   * @todo remove this function and dependencies
+   */
+  function status($string) {
+
+      /*  Need to remove this and all dependencies from the class */
+
+      switch (substr($string, 0,2)){
+          case "NO":
+              return F_NO;		//there should be some function to extract the error code from this line
+					//NO ("quota") "You are oly allowed x number of scripts"
+              break;
+          case "OK":
+              return F_OK;
+              break;
+          default:
+              switch ($string[0]){
+                  case "{":
+                      //do parse here for curly braces - maybe modify
+                      //parse_for_quotes to handle any parse delimiter?
+                      return F_HEAD;
+                      break;
+                  default:
+                      return F_DATA;
+                      break;
+              }
+        }
+  }
+  
+  /**
+   * Attemp to log in to the sieve server.
+   * 
+   * It will return false if it fails, true if all is well.  This also loads
+   * some arrays up with some handy information:
+   *
+   * capabilities["implementation"] contains the sieve version information
+   * 
+   * capabilities["auth"] contains the supported authentication modes by the
+   * SIEVE server.
+   * 
+   * capabilities["modules"] contains the built in modules like "reject",
+   * "redirect", etc.
+   * 
+   * capabilities["starttls"] , if is set and equal to true, will show that the
+   * server supports the STARTTLS extension.
+   * 
+   * capabilities["unknown"] contains miscellaneous/extraneous header info sieve
+   * may have sent
+   *
+   * @return boolean
+   */
+  function sieve_login() {
+    $this->fp=fsockopen($this->host,$this->port);
+    if($this->fp == false)
+        return false;
+
+    $this->line=fgets($this->fp,1024);
+    //Hack for older versions of Sieve Server.  They do not respond with the Cyrus v2. standard
+    //response.  They repsond as follows: "Cyrus timsieved v1.0.0" "SASL={PLAIN,........}"
+    //So, if we see IMLEMENTATION in the first line, then we are done.
+
+    if(ereg("IMPLEMENTATION",$this->line))
+    {
+      //we're on the Cyrus V2 sieve server
+      while(sieve::status($this->line) == F_DATA){
+
+          $this->item = sieve::parse_for_quotes($this->line);
+
+          if(strcmp($this->item[0], "IMPLEMENTATION") == 0)
+              $this->capabilities["implementation"] = $this->item[1];
+        
+          elseif(strcmp($this->item[0], "SIEVE") == 0 or strcmp($this->item[0], "SASL") == 0){
+
+              if(strcmp($this->item[0], "SIEVE") == 0)
+                  $this->cap_type="modules";
+              else
+                  $this->cap_type="auth";            
+
+              $this->modules = split(" ", $this->item[1]);
+              if(is_array($this->modules)){
+                  foreach($this->modules as $this->module)
+                      $this->capabilities[$this->cap_type][$this->module]=true;
+              } /* end if */
+              elseif(is_string($this->modules))
+                  $this->capabilites[$this->cap_type][$this->modules]=true;
+          }    
+          elseif(strcmp($this->item[0], "STARTTLS") == 0) {
+	          $this->capabilities['starttls'] = true;
+	  
+          }
+	  else{ 
+              $this->capabilities["unknown"][]=$this->line;
+          }    
+      $this->line=fgets($this->fp,1024);
+       }// end while
+    }
+    else
+    {
+        //we're on the older Cyrus V1. server  
+        //this version does not support module reporting.  We only have auth types.
+        $this->cap_type="auth";
+       
+        //break apart at the "Cyrus timsieve...." "SASL={......}"
+        $this->item = sieve::parse_for_quotes($this->line);
+
+        $this->capabilities["implementation"] = $this->item[0];
+
+        //we should have "SASL={..........}" now.  Break out the {xx,yyy,zzzz}
+        $this->modules = substr($this->item[1], strpos($this->item[1], "{"),strlen($this->item[1])-1);
+
+        //then split again at the ", " stuff.
+        $this->modules = split($this->modules, ", ");
+ 
+        //fill up our $this->modules property
+        if(is_array($this->modules)){
+            foreach($this->modules as $this->module)
+                $this->capabilities[$this->cap_type][$this->module]=true;
+        } /* end if */
+        elseif(is_string($this->modules))
+            $this->capabilites[$this->cap_type][$this->module]=true;
+    }
+
+
+
+
+    if(sieve::status($this->line) == F_NO){		//here we should do some returning of error codes?
+        $this->error=EC_UNKNOWN;
+        $this->error_raw = "Server not allowing connections.";
+        return false;
+    }
+
+    /* decision login to decide what type of authentication to use... */
+
+
+     /* Loop through each allowed authentication type and see if the server allows the type */
+     foreach(explode(" ", $this->auth_types) as $auth_type)
+     {
+        if ($this->capabilities["auth"][$auth_type])
+        {
+            /* We found an auth type that is allowed. */
+            $this->auth_in_use = $auth_type;
+        }
+     }
+    
+     /* call our authentication program */
+   
+    return sieve::authenticate();
+
+  }
+
+  /**
+   * Log out of the sieve server.
+   *
+   * @return boolean Always returns true at this point.
+   */
+  function sieve_logout() {
+    if($this->loggedin==false)
+        return false;
+
+    fputs($this->fp,"LOGOUT\r\n");
+    fclose($this->fp);
+    $this->loggedin=false;
+    return true;
+  }
+
+  /**
+   * Send the script contained in $script to the server.
+   *
+   * It will return any error results it finds (in $sieve->error and
+   * $sieve->error_raw), and return true if it is successfully sent.  The
+   * function does _not_ automatically make the script the active script.
+   *
+   * @param $scriptname string The name of the SIEVE script.
+   * @param $script The script to be uploaded.
+   * @return boolean Returns true if script has been successfully uploaded.
+   */
+  function sieve_sendscript($scriptname, $script) {
+    if($this->loggedin==false)
+        return false;
+    $this->script=stripslashes($script);
+    $len=strlen($this->script);
+    
+    //fputs($this->fp, "PUTSCRIPT \"$scriptname\" \{$len+}\r\n");
+    
+    fputs($this->fp, 'PUTSCRIPT "' . $scriptname . '" {' . $len . '+}' . "\r\n");
+    fputs($this->fp, "$this->script\r\n");
+  
+    return sieve::get_response();
+
+  }  
+  
+  /**
+   * Check if there is enough space for a script to be uploaded. 
+   *
+   * This function returns true or false based on whether the sieve server will
+   * allow your script to be sent and your quota has not been exceeded.  This
+   * function does not currently work due to a believed bug in timsieved.  It
+   * could be my code too.
+   *
+   * It appears the timsieved does not honor the NUMBER type.  see lex.c in
+   * timsieved src.  don't expect this function to work yet.  I might have
+   * messed something up here, too.
+   *
+   * @param $scriptname string The name of the SIEVE script.
+   * @param $scriptsize integer The size of the SIEVE script.
+   * @return boolean
+   * @todo Does not work; bug fix and test.
+   */
+  function sieve_havespace($scriptname, $scriptsize)   {
+    if($this->loggedin==false)
+        return false;
+    fputs($this->fp, "HAVESPACE \"$scriptname\" $scriptsize\r\n");
+    return sieve::get_response();
+  }  
+
+  /**
+   * Set the script active on the sieve server.
+   *
+   * @param $scriptname string The name of the SIEVE script.
+   * @return boolean
+   */
+  function sieve_setactivescript($scriptname)   {
+    if($this->loggedin==false)
+        return false;
+
+    fputs($this->fp, "SETACTIVE \"$scriptname\"\r\n");   
+    return sieve::get_response();
+
+  }
+  
+  /**
+   * Return the contents of the requested script.
+   * 
+   * If you want to display the script, you will need to change all CrLf to
+   * '.'.
+   *
+   * @param $scriptname string The name of the SIEVE script.
+   * @return arr SIEVE script data.
+   */
+  function sieve_getscript($scriptname) {
+    unset($this->script);
+    if($this->loggedin==false)
+        return false;
+
+    fputs($this->fp, "GETSCRIPT \"$scriptname\"\r\n");
+    return sieve::get_response();
+  }
+
+  /**
+   * Attempt to delete the script requested.
+   *
+   * If the script is currently active, the server will not have any active
+   * script after the deletion.
+   *
+   * @param $scriptname string The name of the SIEVE script.
+   * @return mixed
+   */
+  function sieve_deletescript($scriptname)   {
+    if($this->loggedin==false)
+        return false;
+
+    fputs($this->fp, "DELETESCRIPT \"$scriptname\"\r\n");    
+
+    return sieve::get_response();
+  }
+
+  
+  /**
+   * List available scripts on the SIEVE server.
+   *
+   * This function returns true or false.  $sieve->response will be filled
+   * with the names of the scripts found.  If a script is active, the
+   * $sieve->response["ACTIVE"] will contain the name of the active script.
+   *
+   * @return boolean
+   */
+  function sieve_listscripts() { 
+     fputs($this->fp, "LISTSCRIPTS\r\n"); 
+     sieve::get_response();		//should always return true, even if there are no scripts...
+     if(isset($this->found_script) and $this->found_script)
+         return true;
+     else{
+         $this->error=EC_NOSCRIPTS;	//sieve::getresponse has no way of telling wether a script was found...
+         $this->error_raw="No scripts found for this account.";
+         return false;
+     }
+   }
+
+
+  /**
+   * Check availability of connection to the SIEVE server.
+   *
+   * This function returns true or false based on whether the connection to the
+   * sieve server is still alive.
+   *
+   * @return boolean
+   */
+  function sieve_alive()   {
+      if(!isset($this->fp) or $this->fp==0){
+          $this->error = EC_NOT_LOGGED_IN;
+          return false;
+      }
+      elseif(feof($this->fp)){			
+          $this->error = EC_NOT_LOGGED_IN;
+          return false;
+      }
+      else
+          return true;
+  }
+
+  /**
+   * Perform SASL authentication to SIEVE server.
+   *
+   * Attempts to authenticate to SIEVE, using some SASL authentication method
+   * such as PLAIN or DIGEST-MD5.
+   *
+   */
+  function authenticate() {
+    switch ($this->auth_in_use) {
+
+        case "PLAIN":
+            $auth=base64_encode("$this->auth\0$this->user\0$this->pass");
+            $this->len=strlen($auth);
+			
+            fputs($this->fp, 'AUTHENTICATE "PLAIN" {' . $this->len . '+}' . "\r\n");
+            fputs($this->fp, "$auth\r\n");
+
+            $this->line=fgets($this->fp,1024);
+            while(sieve::status($this->line) == F_DATA)
+               $this->line=fgets($this->fp,1024);
+
+             if(sieve::status($this->line) == F_NO)
+               return false;
+             $this->loggedin=true;
+               return true;    
+	    break;
+	
+        case "DIGEST-MD5":
+	     // SASL DIGEST-MD5 support works with timsieved 1.1.0
+	     // follows rfc2831 for generating the $response to $challenge
+	     fputs($this->fp, "AUTHENTICATE \"DIGEST-MD5\"\r\n");
+	     // $clen is length of server challenge, we ignore it. 
+	     $clen = fgets($this->fp, 1024);
+	     // read for 2048, rfc2831 max length allowed
+	     $challenge = fgets($this->fp, 2048);
+	     // vars used when building $response_value and $response
+	     $cnonce = base64_encode(bin2hex(hmac_md5(microtime())));
+	     $ncount = "00000001";
+	     $qop_value = "auth"; 
+	     $digest_uri_value = "sieve/$this->host";
+	     // decode the challenge string
+	     $result = decode_challenge($challenge);
+	     // verify server supports qop=auth 
+	     $qop = explode(",",$result['qop']);
+	     if (!in_array($qop_value, $qop)) {
+	        // rfc2831: client MUST fail if no qop methods supported
+	        return false;
+	     }
+	     // build the $response_value
+	     $string_a1 = utf8_encode($this->user).":";
+	     $string_a1 .= utf8_encode($result['realm']).":";
+	     $string_a1 .= utf8_encode($this->pass);
+	     $string_a1 = hmac_md5($string_a1);
+	     $A1 = $string_a1.":".$result['nonce'].":".$cnonce.":".utf8_encode($this->auth);
+	     $A1 = bin2hex(hmac_md5($A1));
+	     $A2 = bin2hex(hmac_md5("AUTHENTICATE:$digest_uri_value"));
+	     $string_response = $result['nonce'].":".$ncount.":".$cnonce.":".$qop_value;
+	     $response_value = bin2hex(hmac_md5($A1.":".$string_response.":".$A2));
+	     // build the challenge $response
+	     $reply = "charset=utf-8,username=\"".$this->user."\",realm=\"".$result['realm']."\",";
+	     $reply .= "nonce=\"".$result['nonce']."\",nc=$ncount,cnonce=\"$cnonce\",";
+	     $reply .= "digest-uri=\"$digest_uri_value\",response=$response_value,";
+	     $reply .= "qop=$qop_value,authzid=\"".utf8_encode($this->auth)."\"";
+	     $response = base64_encode($reply);
+	     fputs($this->fp, "\"$response\"\r\n");
+ 	
+             $this->line = fgets($this->fp, 1024);
+             while(sieve::status($this->line) == F_DATA)
+                $this->line = fgets($this->fp,1024);
+
+             if(sieve::status($this->line) == F_NO)
+               return false;
+             $this->loggedin = TRUE;
+               return TRUE;    
+             break;
+	
+        case "CRAM-MD5":
+  	     // SASL CRAM-MD5 support works with timsieved 1.1.0
+	     // follows rfc2195 for generating the $response to $challenge
+	     // CRAM-MD5 does not support proxy of $auth by $user
+	     // requires php mhash extension
+	     fputs($this->fp, "AUTHENTICATE \"CRAM-MD5\"\r\n");
+	     // $clen is the length of the challenge line the server gives us
+	     $clen = fgets($this->fp, 1024);
+	     // read for 1024, should be long enough?
+	     $challenge = fgets($this->fp, 1024);
+	     // build a response to the challenge
+	     $hash = bin2hex(hmac_md5(base64_decode($challenge), $this->pass));
+	     $response = base64_encode($this->user." ".$hash);
+	     // respond to the challenge string
+	     fputs($this->fp, "\"$response\"\r\n");
+	     
+             $this->line = fgets($this->fp, 1024);		
+             while(sieve::status($this->line) == F_DATA)
+                $this->line = fgets($this->fp,1024);
+
+             if(sieve::status($this->line) == F_NO)
+               return false;
+             $this->loggedin = TRUE;
+               return TRUE;    
+             break;
+
+	case "LOGIN":
+ 	     $login=base64_encode($this->user);
+ 	     $pass=base64_encode($this->pass);
+ 	
+ 	     fputs($this->fp, "AUTHENTICATE \"LOGIN\"\r\n");
+ 	     fputs($this->fp, "{".strlen($login)."+}\r\n");
+ 	     fputs($this->fp, "$login\r\n");
+ 	     fputs($this->fp, "{".strlen($pass)."+}\r\n");
+ 	     fputs($this->fp, "$pass\r\n");
+ 
+	     $this->line=fgets($this->fp,1024);
+ 	     while(sieve::status($this->line) == F_HEAD ||
+ 	           sieve::status($this->line) == F_DATA)
+ 	         $this->line=fgets($this->fp,1024);
+ 	
+ 	     if(sieve::status($this->line) == F_NO)
+ 	         return false;
+ 	     $this->loggedin=true;
+ 	     return true;
+ 	     break;
+
+        default:
+            echo 'default';
+            return false;
+            break;
+
+    }//end switch
+  }
+
+  /**
+   * Return an array of available capabilities.
+   *
+   * @return array
+   */
+  function sieve_get_capability() {
+    if($this->loggedin==false)
+        return false;
+    fputs($this->fp, "CAPABILITY\r\n"); 
+    $this->line=fgets($this->fp,1024);
+
+    //Hack for older versions of Sieve Server.  They do not respond with the Cyrus v2. standard
+    //response.  They repsond as follows: "Cyrus timsieved v1.0.0" "SASL={PLAIN,........}"
+    //So, if we see IMLEMENTATION in the first line, then we are done.
+
+    if(ereg("IMPLEMENTATION",$this->line))
+    {
+      //we're on the Cyrus V2 sieve server
+      while(sieve::status($this->line) == F_DATA){
+
+          $this->item = sieve::parse_for_quotes($this->line);
+
+          if(strcmp($this->item[0], "IMPLEMENTATION") == 0)
+              $this->capabilities["implementation"] = $this->item[1];
+        
+          elseif(strcmp($this->item[0], "SIEVE") == 0 or strcmp($this->item[0], "SASL") == 0){
+
+              if(strcmp($this->item[0], "SIEVE") == 0)
+                  $this->cap_type="modules";
+              else
+                  $this->cap_type="auth";            
+
+              $this->modules = split(" ", $this->item[1]);
+              if(is_array($this->modules)){
+                  foreach($this->modules as $this->module)
+                      $this->capabilities[$this->cap_type][$this->module]=true;
+              } /* end if */
+              elseif(is_string($this->modules))
+                  $this->capabilites[$this->cap_type][$this->modules]=true;
+          }    
+          else{ 
+              $this->capabilities["unknown"][]=$this->line;
+          }    
+      $this->line=fgets($this->fp,1024);
+
+       }// end while
+    }
+    else
+    {
+        //we're on the older Cyrus V1. server  
+        //this version does not support module reporting.  We only have auth types.
+        $this->cap_type="auth";
+       
+        //break apart at the "Cyrus timsieve...." "SASL={......}"
+        $this->item = sieve::parse_for_quotes($this->line);
+
+        $this->capabilities["implementation"] = $this->item[0];
+
+        //we should have "SASL={..........}" now.  Break out the {xx,yyy,zzzz}
+        $this->modules = substr($this->item[1], strpos($this->item[1], "{"),strlen($this->item[1])-1);
+
+        //then split again at the ", " stuff.
+        $this->modules = split($this->modules, ", ");
+ 
+        //fill up our $this->modules property
+        if(is_array($this->modules)){
+            foreach($this->modules as $this->module)
+                $this->capabilities[$this->cap_type][$this->module]=true;
+        } /* end if */
+        elseif(is_string($this->modules))
+            $this->capabilites[$this->cap_type][$this->module]=true;
+    }
+
+    return $this->modules;
+  }
+
+}
+
+
+/**
+ * The following functions are support functions and might be handy to the
+ * sieve class.
+ */
+
+if(!function_exists('hmac_md5')) {
+
+/**
+ * Creates a HMAC digest that can be used for auth purposes.
+ * See RFCs 2104, 2617, 2831
+ * Uses mhash() extension if available
+ *
+ * Squirrelmail has this function in functions/auth.php, and it might have been
+ * included already. However, it helps remove the dependancy on mhash.so PHP
+ * extension, for some sites. If mhash.so _is_ available, it is used for its
+ * speed.
+ *
+ * This function is Copyright (c) 1999-2003 The SquirrelMail Project Team
+ * Licensed under the GNU GPL. For full terms see the file COPYING.
+ *
+ * @param string $data Data to apply hash function to.
+ * @param string $key Optional key, which, if supplied, will be used to
+ * calculate data's HMAC.
+ * @return string HMAC Digest string
+ */
+function hmac_md5($data, $key='') {
+    // See RFCs 2104, 2617, 2831
+    // Uses mhash() extension if available
+    if (extension_loaded('mhash')) {
+      if ($key== '') {
+        $mhash=mhash(MHASH_MD5,$data);
+      } else {
+        $mhash=mhash(MHASH_MD5,$data,$key);
+      }
+      return $mhash;
+    }
+    if (!$key) {
+         return pack('H*',md5($data));
+    }
+    $key = str_pad($key,64,chr(0x00));
+    if (strlen($key) > 64) {
+        $key = pack("H*",md5($key));
+    }
+    $k_ipad =  $key ^ str_repeat(chr(0x36), 64) ;
+    $k_opad =  $key ^ str_repeat(chr(0x5c), 64) ;
+    /* Heh, let's get recursive. */
+    $hmac=hmac_md5($k_opad . pack("H*",md5($k_ipad . $data)) );
+    return $hmac;
+}
+}
+
+/**
+ * A hack to decode the challenge from timsieved 1.1.0.
+ * 
+ * This function may not work with other versions and most certainly won't work
+ * with other DIGEST-MD5 implentations
+ *
+ * @param $input string Challenge supplied by timsieved.
+ */
+function decode_challenge ($input) {
+    $input = base64_decode($input);
+    preg_match("/nonce=\"(.*)\"/U",$input, $matches);
+    $resp['nonce'] = $matches[1];
+    preg_match("/realm=\"(.*)\"/U",$input, $matches);
+    $resp['realm'] = $matches[1];
+    preg_match("/qop=\"(.*)\"/U",$input, $matches);
+    $resp['qop'] = $matches[1];
+    return $resp;
+}
+
+// vim:ts=4:et:ft=php
+
+?>
Index: /branches/2.2/listAdmin/js/jscode/listadmin.js
===================================================================
--- /branches/2.2/listAdmin/js/jscode/listadmin.js	(revision 3514)
+++ /branches/2.2/listAdmin/js/jscode/listadmin.js	(revision 3514)
@@ -0,0 +1,66 @@
+	/************************************************************************************\
+	* Expresso Administração                 										    *
+	* by Joao Alfredo Knopik Junior (joao.alfredo@gmail.com, jakjr@celepar.pr.gov.br)   *
+	* ----------------------------------------------------------------------------------*
+	*  This program is free software; you can redistribute it and/or modify it			*
+	*  under the terms of the GNU General Public License as published by the			*
+	*  Free Software Foundation; either version 2 of the License, or (at your			*
+	*  option) any later version.														*
+	\************************************************************************************/
+
+function emailSuggestion_expressoadmin(use_suggestion_in_logon_script, concatenateDomain)
+{
+	if (concatenateDomain == 'true')
+	{
+		domain_name = document.forms[0].defaultDomain.value;
+		document.forms[0].mail1.value = document.forms[0].uid.value + '@' + domain_name;
+	}
+	else
+	{
+		document.forms[0].mail1.value = document.forms[0].uid.value;
+	}
+
+	if (use_suggestion_in_logon_script == 'true')
+		document.forms[0].sambalogonscript.value = document.forms[0].uid.value+'.bat';
+	document.forms[0].sambahomedirectory.value = '/home/'+document.forms[0].uid.value+'/';
+	var re_cpf = /^([0-9])+$/;
+	if ((document.forms[0].uid.value.length == 11)&&(re_cpf.test(document.forms[0].uid.value))&&(validarCPF(document.forms[0].uid.value)))
+		{
+		document.forms[0].corporative_information_cpf.value=document.forms[0].uid.value;
+		return;
+		}
+}
+
+function FormataValor(event, campo)
+{
+	separador1 = '(';
+	separador2 = ')';
+	separador3 = '-';
+
+	vr = campo.value;
+	tam = vr.length;
+
+	if ((tam == 1) && (( event.keyCode != 8 ) || ( event.keyCode != 46 )))
+		campo.value = '';
+
+	if ((tam == 3) && (( event.keyCode != 8 ) || ( event.keyCode != 46 )))
+		campo.value = vr.substr( 0, tam - 1 );
+
+	if (( tam <= 1 ) && ( event.keyCode != 8 ) && ( event.keyCode != 46 ))
+ 		campo.value = separador1 + vr;
+
+	if (( tam == 3 ) && ( event.keyCode != 8 ) && ( event.keyCode != 46 ))
+		campo.value = vr + separador2;
+
+	if (( tam == 8 ) && (( event.keyCode != 8 ) && ( event.keyCode != 46 )))
+		campo.value = vr + separador3;
+
+	if ((( tam == 9 ) || ( tam == 8 )) && (( event.keyCode == 8 ) || ( event.keyCode == 46 )))
+		campo.value = vr.substr( 0, tam - 1 );
+}
+function emailGenerate()
+{
+     document.forms[0].mail.value=document.forms[0].mail1.value;
+     document.forms[0].mailalternateaddress.value=document.forms[0].uid.value + '@mail.' + document.forms[0].defaultDomain.value;
+     //document.forms[0].mailalteraddress[].value=document.forms[0].uid.value + '@mail.' + document.forms[0].defaultDomain.value;
+}
Index: /branches/2.2/listAdmin/js/jscode/connector.js
===================================================================
--- /branches/2.2/listAdmin/js/jscode/connector.js	(revision 3514)
+++ /branches/2.2/listAdmin/js/jscode/connector.js	(revision 3514)
@@ -0,0 +1,552 @@
+/****************************************** Public variables *************************************************/
+var debug_controller = false;
+var files = new Array();
+var progressBar;
+
+  if (document.all)
+	{
+		navigator.userAgent.toLowerCase().indexOf('msie 5') != -1 ? is_ie5 = true : is_ie5 = false;
+		is_ie = true;
+		is_moz1_6 = false;
+		is_mozilla = false;
+		is_ns4 = false;
+	}
+	else if (document.getElementById)
+	{
+		navigator.userAgent.toLowerCase().match('mozilla.*rv[:]1\.6.*gecko') ? is_moz1_6 = true : is_moz1_6 = false;
+		is_ie = false;
+		is_ie5 = false;
+		is_mozilla = true;
+		is_ns4 = false;
+	}
+	else if (document.layers)
+	{
+		is_ie = false;
+		is_ie5 = false
+		is_moz1_6 = false;
+		is_mozilla = false;
+		is_ns4 = true;
+	}	
+
+/****************************************** Connector Class *************************************************/
+	// Constructor
+	function cConnector()
+	{
+		this.requests = new Array();
+		this.oxmlhttp = null;
+		this.isVisibleBar = false;
+		this.tid = 0;
+		this.progressBar = null;
+		this.oldX = 0;
+		this.oldY = 0;
+	}
+	
+	cConnector.prototype.buildBar = function()
+		{			
+			var div = document.getElementById('divProgressBar');
+		
+			if(! div) {												
+				div = document.createElement("DIV");
+				div.style.visibility	= "hidden";		
+				div.style.width = "103px";
+				div.id = 'divProgressBar';
+				div.align = "center";
+				div.innerHTML = '&nbsp;&nbsp;<font face="Verdana" size="2" color="WHITE">Carregando...</font>&nbsp;';
+				div.style.background = "#cc4444";
+				div.style.position = 'fixed';
+				div.style.top = '0px';
+				div.style.right = '0px';
+				document.body.appendChild(div);																
+				
+				if(is_ie) {
+					var elem = document.all[div.id]; 
+					elem.style.position="absolute";
+					var root = document.body;
+					var posX = elem.offsetLeft-root.scrollLeft;
+					var posY = elem.offsetTop-root.scrollTop;
+					root.onscroll = function() {
+						elem.style.right = '0px';
+						elem.style.top = (posY + root.scrollTop) + "px";
+					};					
+				}
+				
+				if(debug_controller) {
+					div = document.createElement("DIV");
+					div.style.width	= "800px";
+					div.style.height= "400px";
+					div.id = "debug_controller";
+					div.align='right';
+					document.body.appendChild(div);																
+				}
+			}								
+	}	
+//------------------------------------ BEGIN: Functions for Connector HTTPRequest  -------------------------------------------------//	
+	// Serialize Data Method
+	cConnector.prototype.serialize = function(data)
+	{	var _thisObject = this;		
+		var f = function(data)
+		{
+			var str_data;
+	
+			if (data == null || 
+				(typeof(data) == 'string' && data == ''))
+			{
+				str_data = 'N;';
+			}
+	
+			else switch(typeof(data))
+			{
+				case 'object':
+					var arrayCount = 0;
+	
+					str_data = '';
+	
+					for (i in data)
+					{
+						if (i == 'length')
+						{
+							continue;
+						}
+						
+						arrayCount++;
+						switch (typeof(i))
+						{
+							case 'number':
+								str_data += 'i:' + i + ';' + _thisObject.serialize(data[i]);
+								break;
+	
+							case 'string':
+								str_data += 's:' + i.length + ':"' + i + '";' + _thisObject.serialize(data[i]);
+								break;
+	
+							default:
+								showMessage(Element('cc_msg_err_serialize_data_unknown').value);
+								break;
+						}
+					}
+	
+					if (!arrayCount)
+					{
+						str_data = 'N;';	
+					}
+					else
+					{
+						str_data = 'a:' + arrayCount + ':{' + str_data + '}';
+					}
+					
+					break;
+			
+				case 'string':
+					str_data = 's:' + data.length + ':"' + data + '";';
+					break;
+					
+				case 'number':
+					str_data = 'i:' + data + ';';
+					break;
+	
+				case 'boolean':
+					str_data = 'b:' + (data ? '1' : '0') + ';';
+					break;
+	
+				default:
+					showMessage(Element('cc_msg_err_serialize_data_unknown').value);
+					return null;
+			}
+	
+			return str_data;
+		}
+	
+		var sdata = f(data);
+		return sdata;
+	}
+	cConnector.prototype.matchBracket = function(strG, iniPosG)
+	{
+		_thisObject = this;
+		var f = function (str, iniPos)
+		{
+			var nOpen, nClose = iniPos;
+		
+			do 
+			{
+				nOpen = str.indexOf('{', nClose+1);
+				nClose = str.indexOf('}', nClose+1);
+
+				if (nOpen == -1)
+				{
+					return nClose;
+				}
+			
+				if (nOpen < nClose )
+				{
+					nClose = _thisObject.matchBracket(str, nOpen);
+				}
+			
+			} while (nOpen < nClose);
+
+			return nClose;
+		}
+
+		return f(strG, iniPosG);
+	}
+	
+		
+	//Unserialize Data Method
+	cConnector.prototype.unserialize = function(str)
+	{
+		
+		_thisObject = this;
+		
+		var f = function (str)
+		{
+			switch (str.charAt(0))
+			{
+				case 'a':
+					
+					var data = new Array();
+					var n = parseInt( str.substring( str.indexOf(':')+1, str.indexOf(':',2) ) );
+					var arrayContent = str.substring(str.indexOf('{')+1, str.lastIndexOf('}'));
+				
+					for (var i = 0; i < n; i++)
+					{
+						var pos = 0;
+	
+						/* Process Index */
+						var indexStr = arrayContent.substr(pos, arrayContent.indexOf(';')+1);
+						var index = _thisObject.unserialize(indexStr);
+						pos = arrayContent.indexOf(';', pos)+1;
+						
+						/* Process Content */
+						var part = null;
+						switch (arrayContent.charAt(pos))
+						{
+							case 'a':
+								var pos_ = _thisObject.matchBracket(arrayContent, arrayContent.indexOf('{', pos))+1;
+								part = arrayContent.substring(pos, pos_);
+								pos = pos_;
+								data[index] = _thisObject.unserialize(part);
+								break;
+						
+							case 's':
+								var pval = arrayContent.indexOf(':', pos+2);
+								var val  = parseInt(arrayContent.substring(pos+2, pval));
+								pos = pval + val + 4;
+								data[index] = arrayContent.substr(pval+2, val);
+								break;
+	
+							default:
+								part = arrayContent.substring(pos, arrayContent.indexOf(';', pos)+1);
+								pos = arrayContent.indexOf(';', pos)+1;
+								data[index] = _thisObject.unserialize(part);
+								break;
+						}
+						arrayContent = arrayContent.substr(pos);
+					}
+					break;
+					
+				case 's':
+					var pos = str.indexOf(':', 2);
+					var val = parseInt(str.substring(2,pos));
+					var data = str.substr(pos+2, val);
+					str = str.substr(pos + 4 + val);
+					break;
+	
+				case 'i':
+				case 'd':
+					var pos = str.indexOf(';');
+					var data = parseInt(str.substring(2,pos));
+					str = str.substr(pos + 1);
+					break;
+				
+				case 'N':
+					var data = null;
+					str = str.substr(str.indexOf(';') + 1);
+					break;
+	
+				case 'b':
+					var data = str.charAt(2) == '1' ? true : false;
+					break;
+			}
+			
+			return data;
+		}
+	
+		return f(str);
+	}
+
+	//Create XMLHTTP object Method
+	cConnector.prototype.createXMLHTTP = function ()
+	{	
+		try
+		{ 
+			this.oxmlhttp = new XMLHttpRequest();
+			this.oxmlhttp.overrideMimeType('text/xml');
+		}
+		catch (e)
+		{ 
+			try
+			{
+				this.oxmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
+			}
+			catch (e1)
+			{ 
+				try
+				{
+					this.oxmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
+				}
+				catch (e2)
+				{
+					this.oxmlhttp = null;
+				}
+			}
+		}
+	
+	}
+	
+	// Request Constructor Connector	
+	cConnector.prototype.newRequest = function (id, target, method, handler, data)
+	{
+		this.tid = id;
+		if (this.requests[id]) {
+			return false;
+		}
+	
+		this.createXMLHTTP();
+		var oxmlhttp = this.oxmlhttp;
+		var _thisObject = this;		
+		
+		if (! oxmlhttp)		
+			return false;
+				
+		this.requests[id] = oxmlhttp;
+		this.buildBar();		
+		this.showProgressBar();
+		
+		var sub_handler = function ()
+		{			
+			var progressBar = _thisObject.progressBar;
+			
+			try
+			{
+				if (oxmlhttp.readyState == 4 )
+				{
+					
+					switch (oxmlhttp.status)
+					{
+					
+						case 200:
+							if (typeof(handler) == 'function')
+							{																
+								_thisObject.hideProgressBar();																
+								var data = _thisObject.unserialize(oxmlhttp.responseText);
+								if(debug_controller) {
+									document.getElementById("debug_controller").innerHTML += oxmlhttp.responseText;
+									document.getElementById("debug_controller").innerHTML += "<br>-------------------------------------------------------------------------------------<br>";
+								}									
+								handler(data);
+								delete _thisObject.requests[id];								
+								_thisObject.requests[id] = null;
+							}
+
+							break;
+
+						case 404:
+							
+							alert('Page Not Found!');
+							break;
+
+						default:												
+					}
+				}
+			}
+			catch (e)
+			{
+				_thisObject.hideProgressBar();
+				if(debug_controller)
+					alert(e+"\n"+oxmlhttp.responseText);
+				// View Exception in Javascript Console
+				throw(e);
+			}
+						
+		}
+
+		try
+		{ 
+			
+			if (method == '' || method == 'GET')
+			{								
+				oxmlhttp.open("GET",target,true);
+				if (typeof(handler) == 'function')
+				{	
+					oxmlhttp.onreadystatechange =  sub_handler;					
+					oxmlhttp.send(null);					
+				}		
+				
+			}
+			else if (method == 'POST')
+			{
+				oxmlhttp.open("POST",target, true);
+				oxmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
+				if (typeof(handler) == 'function')
+				{
+					oxmlhttp.onreadystatechange = sub_handler;
+					oxmlhttp.send(data);
+				}				
+				
+			}
+		}
+		catch(e)
+		{	
+			_thisObject.hideProgressBar();
+			if(debug_controller)
+				alert(e);
+			// View Exception in Javascript Console	 
+			throw(e);
+		}
+						
+		return true;
+	}
+	// Cancel Request Connector
+	cConnector.prototype.cancelRequest = function (){
+		if (!this.requests[this.tid]){
+			return false;
+		}
+		this.oxmlhttp.onreadystatechange = null;
+		this.requests[this.tid].abort();
+		this.hideProgressBar();
+	}
+//------------------------------------  END: Functions for Connector HTTPRequest  -------------------------------------------------//
+
+//	----------------------------------- BEGIN: Functions for build Bar Progress ---------------------------------------------------------//
+	cConnector.prototype.hideProgressBar = function ()
+	{
+		div = document.getElementById('divProgressBar');
+		div.style.visibility = 'hidden';
+		this.isVisibleBar = false;
+	}
+	
+	cConnector.prototype.showProgressBar = function()
+	{
+	div = document.getElementById('divProgressBar');
+		div.style.visibility = 'visible';
+		this.isVisibleBar = true;
+	}
+
+	cConnector.prototype.loadScript = function(scriptPath)	{
+      	if (document.getElementById('uploadscript_'+scriptPath)) {
+      		return;
+      	}
+  	
+		this.oxmlhttp.open("GET", "js/"+scriptPath+".js", false);
+        this.oxmlhttp.setRequestHeader('Content-Type','text/plain');
+		this.oxmlhttp.send(null);
+		if(this.oxmlhttp.status != 0 && this.oxmlhttp.status != 200 || 	this.oxmlhttp.status == 0 && this.oxmlhttp.responseText.length == 0)
+			throw new Error("Error " + this.oxmlhttp.status + "("+this.oxmlhttp.statusText+") when loading script file '"+scriptPath+"'");
+		
+		var head = document.getElementsByTagName("head")[0];
+		var script = document.createElement("SCRIPT");
+		script.id = 'uploadscript_'+scriptPath;
+		script.type = 'text/javascript';		
+		script.text = this.oxmlhttp.responseText;
+		head.appendChild(script);
+		return;	
+	}
+//------------------------------------  END: Functions for Progress Bar  -------------------------------------------------//
+	// Default Controller File
+	var DEFAULT_URL = 'listAdmin/controller.php?action=';
+	// connector object
+	var connector = new cConnector();
+	var _onmouseup = document.onmouseup;
+	var isExecuteForm = false;
+	var id = null;
+
+	// 	Function executes AJAX
+	// 	cExecute (url, handler, params)
+	//	url: 'module.class.method'
+	//  handle: function handle() receive response.
+	//  params: parameters for POST method
+	//	form: form element (for upload files)	
+	function cExecute(url, handler, params, form) {
+		if(isExecuteForm){
+			isExecuteForm = false;
+			document.onmouseup = _onmouseup;
+		}
+		if(form) {
+			cExecuteForm(url, form);
+			return;
+		}
+		
+		url = DEFAULT_URL + url;
+			
+		if(params)		 
+			method = "POST";
+			 	
+		 else 
+			method = "GET";
+			 
+		id = url;
+		connector.newRequest(id, url, method, handler, params);
+	}
+	
+	// This function executes submit values to Controller (POST)
+	// The return is void.
+	// 	cExecuteForm (url, form)
+	//	url: 'module.class.method'
+	//	form: form element (for upload files)	
+	function cExecuteForm(url, form, handler){
+		connector.buildBar();
+		isExecuteForm = true;		
+		document.onmouseup = alertBut;
+		
+		connector.showProgressBar();
+		if(! (divUpload = document.getElementById('divUpload'))) {
+			divUpload		= document.createElement('DIV');		
+			divUpload.id	= 'divUpload';
+			document.body.appendChild(divUpload);
+		}
+		
+		if(! (el = document.getElementById('_action'))) {			
+			el			= document.createElement('input');
+			el.type	= 'hidden';
+			el.id		= '_action';	
+			el.name	= '_action';
+			form.appendChild(el);
+		}
+		
+		if(countFiles) {			
+			el			= document.createElement('input');
+			el.type	= 'hidden';	
+			el.name	= 'countFiles';
+			el.value 	= countFiles;
+			form.appendChild(el);						
+		}		
+		
+		form._action.value = url;
+		divUpload.innerHTML= "<iframe onload=\"cExecute('$this.functions.getReturnExecuteForm',"+handler+");\"  style='display:"+(debug_controller ? "" : "none")+";width:"+(debug_controller ? 800 : 0)+";height:"+(debug_controller ? 800 : 0)+";' name='uploadFile'></iframe>";
+
+		form.action ="listAdmin/controller.php";
+		form.target ="uploadFile";
+		
+		form.submit();
+	}	
+	
+	
+	function alertBut(e) {
+	   	if(!e)
+			e = window.event;
+
+	    if(_onmouseup)
+			_onmouseup(e);
+
+		if(isExecuteForm) {
+	    	if(confirm("There's an action processing. Do you want abort it?")) {
+		    	connector.hideProgressBar();
+		    	isExecuteForm = false;
+		    	delete connector.requests[id];								
+				connector.requests[id] = null;
+	    		stop();		    		    		
+	    		return;
+	    	}
+    		else
+    			return false;
+	    }
+	}	
Index: /branches/2.2/listAdmin/js/jscode/maillists.js
===================================================================
--- /branches/2.2/listAdmin/js/jscode/maillists.js	(revision 3514)
+++ /branches/2.2/listAdmin/js/jscode/maillists.js	(revision 3514)
@@ -0,0 +1,799 @@
+countFiles = 0;
+function validate_fields(type)
+{
+	document.forms[0].uid.value = document.forms[0].uid.value.toLowerCase();
+	document.forms[0].old_uid.value = document.forms[0].old_uid.value.toLowerCase();
+	
+	if (document.forms[0].uid.value == ''){
+		alert('Campo LOGIN da lista está vazio.');
+		return;
+	}
+
+/*	if (document.forms[0].cn.value == ''){
+		alert('Campo NOME da lista está vazio.');
+		return;
+	}*/
+	
+	if (document.forms[0].restrictionsOnEmailLists.value == 'true')
+	{
+		uid_tmp = document.forms[0].uid.value.split("-");
+		if ((uid_tmp.length < 3) || (uid_tmp[0] != 'lista')){
+			alert(
+				'O campo LOGIN da lista está incompleto.\n' +
+				'O nome da lista deve ser formado assim:\n' +
+				'lista-ORGANIZACAO-NOME_DA_LISTA.\n' +
+				'Ex: lista-serpro-rh.');
+			return;
+		}
+	}
+		
+	if (document.forms[0].uid.value.split(" ").length > 1){
+		alert('Campo LOGIN comtém espaços.');
+		document.forms[0].uid.focus();
+		return;
+	}
+
+	//Verifica se a pagina de origem e a de edicao ou criacao de lista, pois o atributo listPass e usado apenas nestas paginas;
+	if((type == 'edit_maillist') || (type == 'create_maillist')) {
+		if (document.forms[0].listPass.value == ''){
+			alert('Campo SENHA da lista está vazio.');
+			document.forms[0].listPass.focus();
+			return;
+		}
+	}
+	
+/*	if (document.forms[0].mail.value == ''){
+		alert('Campo E-MAIL da lista está vazio.');
+		document.forms[0].mail.focus();
+		return;
+	}
+	var reEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
+	if(!reEmail.test(document.forms[0].mail.value)){
+		alert("Campo E-mail não é válido.");
+		return false;
+	}
+*/
+// Alteracao para saber de onde vem a chamada do save() - se da pagina de edicao de lista ou da pagina de administrador da lista
+	if((type == 'edit_maillist') || (type == 'create_maillist')) { // pagina de edicao da lista
+		select_userInMaillist = document.getElementById('ea_select_usersInMaillist');
+		if (select_userInMaillist.options.length == 0){
+			alert('Nenhum usuário faz parte da lista.');
+			return;
+		}
+		
+	/*}else if(type == 'adm_maillist') { // pagina de administador da lista
+		select_ADM_Maillist = document.getElementById('ea_select_ADM_Maillist');
+		if (select_ADM_Maillist.options.length == 0){
+			alert('Nenhum usuário faz parte da lista.');
+			return;
+		}
+	*/	
+	}
+
+/* Codigo original preservado, em caso de necessidade
+
+	select_userInMaillist = document.getElementById('ea_select_usersInMaillist');
+	if (select_userInMaillist.options.length == 0){
+		alert('Nenhum usuário faz parte da lista.');
+		return;
+	}
+
+*/
+	var handler_validate_fields = function(data)
+	{
+		if (!data.status)
+			alert(data.msg);
+		else
+		{
+			if (type == 'create_maillist')
+				cExecuteForm ("$this.maillist.create", document.forms[0], handler_create);
+			else if (type == 'edit_maillist')
+				cExecuteForm ("$this.maillist.save", document.forms[0], handler_save);
+			//else if (type == 'adm_maillist')
+			//	cExecuteForm ("$this.maillist.save_adm", document.forms[0], handler_save);
+		}
+	}
+
+// Alteracao semelhante a descrita acima
+	if((type == 'edit_maillist') || (type == 'create_maillist')) {
+		for(var i=0; i<select_userInMaillist.options.length; i++)
+			select_userInMaillist.options[i].selected = true;
+
+	/*}else if(type == 'adm_maillist') {
+		for(var i=0; i<select_ADM_Maillist.options.length; i++)
+			select_ADM_Maillist.options[i].selected = true;
+*/
+	}
+
+/* Codigo original preservado, em caso de necessidade
+
+	// Needed select all options from select
+	for(var i=0; i<select_userInMaillist.options.length; i++)
+		select_userInMaillist.options[i].selected = true;
+*/
+
+	// O UID da lista foi alterado ou é uma nova lista.
+	if ((document.forms[0].old_uid.value != document.forms[0].uid.value) || (type == 'create_maillist')){
+		cExecute ('$this.maillist.validate_fields&uid='+document.forms[0].uid.value, handler_validate_fields);
+	}
+	else if (type == 'edit_maillist')
+	{
+		cExecuteForm ("$this.maillist.save", document.forms[0], handler_save);
+	}
+	//else if (type == 'adm_maillist')
+	//{
+	//	cExecuteForm ("$this.maillist.save_adm", document.forms[0], handler_save);
+	//}
+}
+
+// HANDLER CREATE
+// É necessário 2 funcões de retorno por causa do cExecuteForm.
+function handler_create(data)
+{
+	return_handler_create(data);
+}
+function return_handler_create(data)
+{
+	if (!data.status)
+		alert(data.msg);
+	else{
+		//Rotina alterada em 08/10/2007, para contemplar a sincronização Mailman/RHDS
+		//Faz a chamada do script que atualiza as listas no Mailman/RHDS
+		window.setTimeout("cExecute('$this.maillist.synchronize_mailman&uid='+document.forms[0].uid.value+'&op=1', handler_sync_mailman)", 10);
+		//A nova lista foi criada com sucesso
+		//alert('Lista de emails criada com êxito!');
+	}
+	return;
+}
+
+//Manipulador ascrescentado em 08/10/2007: para tratar da sincronização em tempo real do Mailman com o RHDS
+function handler_sync_mailman(data){
+	//Converte os dados do vetor oriundo de um script PHP para um vetor JavaScript
+	var dados_serializados = eval(data);
+	return_handler_sync_mailman(dados_serializados);
+}
+
+function return_handler_sync_mailman(data){
+	//Depois de processar a sincronização do Mailman com o RHDS, redireciona o usuário para a tela inicial
+	//Mesmo que não tenha tido êxito, segue o comportamento default da aplicação, redirecionando o usuário
+	//EM CASO DE ERRO NA SINCRONIZAÇÃO: CONFERIR O LOG "expresso_sincronizacao_mailmanrhds.log" em "/tmp"
+	//alert("Retorno do socket:\nSTATUS=" + data['status'] +'\nMSG=' + data['msg']);
+	alert('Lista de emails criada com êxito!');
+	location.href="./index.php?menuaction=listAdmin.uimaillists.list_maillists";		
+//	alert('Teste debug!'+ data["msg"]);
+}
+
+// HANDLER SAVE
+// É necessário 2 funcões de retorno por causa do cExecuteForm.
+function handler_save(data)
+{
+	return_handler_save(data);
+}
+function return_handler_save(data)
+{
+	if (!data.status)
+		alert(data.msg);
+	else{
+
+		//Alterado em 28/04/2008. Linha abaixo foi incluida para sincronizacao do Mailman com o RHDS, apos alteracao de uma
+		//caracteristica nas abas Editar e Adm, em uma lista existente;
+		window.setTimeout("cExecute('$this.maillist.synchronize_mailman&uid='+document.forms[0].uid.value+'&op=1', handler_sync_mailman)", 10);
+	//	alert('Lista de emails salva com êxito!!');
+	//	location.href="./index.php?menuaction=listAdmin.uimaillists.list_maillists";
+	}
+	return;
+}
+
+function save_adm()
+{
+	select_users_ADM_Maillist = document.getElementById('ea_select_ADM_Maillist');
+	for(var i=0; i<select_users_ADM_Maillist.options.length; i++)
+		select_users_ADM_Maillist.options[i].selected = true;
+
+	cExecuteForm ("$this.maillist.save_adm", document.forms[0], handler_save_adm);
+}
+function handler_save_adm(data)
+{
+	return_handler_save_adm(data);
+}
+
+function return_handler_save_adm(data)
+{
+	if (!data.status)
+		alert(data.msg);
+	else
+
+		//Alterado em 28/04/2008. Linha abaixo foi incluida para sincronizacao do Mailman com o RHDS, apos alteracao de uma
+		//caracteristica na aba ADM, em uma lista existente;
+		window.setTimeout("cExecute('$this.maillist.synchronize_mailman&uid='+document.forms[0].uid.value+'&op=1', handler_sync_mailman)", 10);
+	//	alert('Sending Control List salva com êxito!!');
+	//	location.href="./index.php?menuaction=listAdmin.uimaillists.list_maillists";
+	return;
+}
+
+function save_scl()
+{
+	select_users_SCL_Maillist = document.getElementById('ea_select_users_SCL_Maillist');
+	// Needed select all options from select
+	for(var i=0; i<select_users_SCL_Maillist.options.length; i++)
+		select_users_SCL_Maillist.options[i].selected = true;
+
+	cExecuteForm ("$this.maillist.save_scl", document.forms[0], handler_save_scl);
+}
+function handler_save_scl(data)
+{
+	return_handler_save_scl(data);
+}
+
+function return_handler_save_scl(data)
+{
+	if (!data.status)
+		alert(data.msg);
+	else
+
+		//Alterado em 28/04/2008. Linha abaixo foi incluida para sincronizacao do Mailman com o RHDS, apos alteracao de uma
+		//caracteristica na aba SCL, em uma lista existente;
+		window.setTimeout("cExecute('$this.maillist.synchronize_mailman&uid='+document.forms[0].uid.value+'&op=1', handler_sync_mailman)", 10);
+	//	alert('Sending Control List salva com êxito!!');
+	//	location.href="./index.php?menuaction=listAdmin.uimaillists.list_maillists";
+	return;
+}
+
+function sinc_combos_org(context, recursive)
+{
+	combo_org_maillists = document.getElementById('ea_combo_org_maillists');
+
+	for (i=0; i<combo_org_maillists.length; i++)
+	{
+		if (combo_org_maillists.options[i].value == context)
+		{
+			combo_org_maillists.options[i].selected = true;
+			get_available_users(context, recursive);
+			break;
+		}
+	}
+}
+
+function get_available_users(context, recursive)
+{
+	var handler_get_available_users = function(data)
+	{
+		select_available_users = document.getElementById('ea_select_available_users');
+		
+		//Limpa o select
+		for(var i=0; i<select_available_users.options.length; i++)
+		{
+			select_available_users.options[i] = null;
+			i--;
+		}
+
+		if ((data) && (data.length > 0))
+		{
+			// Necessario, pois o IE6 tem um bug que retira o primeiro options se o innerHTML estiver vazio.
+			select_available_users.innerHTML = 'lixo' + data;
+			select_available_users.outerHTML = select_available_users.outerHTML;
+			
+			select_available_users.disabled = false;
+			select_available_users_clone = document.getElementById('ea_select_available_users').cloneNode(true);
+			document.getElementById('ea_input_searchUser').value = '';
+		}
+	}
+	
+	//Impede chamada recursiva na raiz das organizações
+	if ((recursive) && (document.forms[0].ldap_context.value == document.getElementById('ea_combo_org_maillists').value))
+	{
+		alert('Nao é possível selecionar todos os usuários da organização raiz.')
+		document.getElementById('ea_check_allUsers').checked = false;
+		
+		// Limpa select
+		select_available_users = document.getElementById('ea_select_available_users');
+		select_available_users.innerHTML = 'lixo';
+		select_available_users.outerHTML = select_available_users.outerHTML;
+		return;
+	}
+		cExecute ('$this.ldap_functions.get_available_users_and_maillist&context='+context+'&recursive='+recursive+'&denied_uidnumber='+document.forms[0].uidnumber.value, handler_get_available_users);
+}
+
+
+function get_available_users_only(context, recursive) // Funcao que busca os usuarios apenas, sem as listas
+{
+
+	itemBusca = document.getElementById('ea_input_searchUser').value;
+
+
+	var handler_get_available_users = function(data)
+	{
+		select_available_users = document.getElementById('ea_select_available_users');
+		
+		//Limpa o select
+		for(var i=0; i<select_available_users.options.length; i++)
+		{
+			select_available_users.options[i] = null;
+			i--;
+		}
+
+		if ((data) && (data.length > 0))
+		{
+			// Necessario, pois o IE6 tem um bug que retira o primeiro options se o innerHTML estiver vazio.
+			select_available_users.innerHTML = 'lixo' + data;
+			select_available_users.outerHTML = select_available_users.outerHTML;
+			
+			select_available_users.disabled = false;
+//			select_available_users_clone = document.getElementById('ea_select_available_users').cloneNode(true);
+			document.getElementById('ea_input_searchUser').value = '';
+		}
+	}
+
+	//Impede chamada recursiva na raiz das organizações
+	if ((recursive) && (document.forms[0].ldap_context.value == document.getElementById('ea_combo_org_maillists').value))
+	{
+		alert('Nao é possível selecionar todos os usuários da organização raiz.')
+		document.getElementById('ea_check_allUsers').checked = false;
+		
+		// Limpa select
+		select_available_users = document.getElementById('ea_select_available_users');
+		select_available_users.innerHTML = 'lixo';
+		select_available_users.outerHTML = select_available_users.outerHTML;
+		return;
+	}
+
+		cExecute ('$this.ldap_functions.get_available_users_only&context='+context+'&filtro='+itemBusca+'&recursive='+recursive+'&denied_uidnumber='+document.forms[0].uidnumber.value, handler_get_available_users);
+}
+
+
+function search_users() // Funcao que busca apenas os usuarios, sem as listas
+{
+
+//	dnSearch = document.getElementById("ea_combo_org_maillists").value; //Recebe o dn para busca do usuario;
+	users = document.getElementById('ea_input_searchUser').value; //Recebe qual usuario deve ser buscado;
+	tipoTpl = document.forms[0].tipo.value; //Recebe a opcao de administracao de lista a partir da qual esta sendo feita a busca (Edit, Scl ou Adm);
+
+	//Exige que o argumento de busca tenha, no minimo, 4 caracteres;
+	if(users.length < 4) {
+
+		alert('Argumento de busca deve ter no mínimo 4 caracteres.');
+		return;
+	}
+
+	var handler_search_users = function(data)
+	{
+
+		select_available_users = document.getElementById('ea_select_available_users');
+
+		//Limpa o select
+		for(var i=0; i<select_available_users.options.length; i++)
+		{
+			select_available_users.options[i] = null;
+			i--;
+		}
+
+		if ((data) && (data.length > 0))
+		{
+			// Necessario, pois o IE6 tem um bug que retira o primeiro options se o innerHTML estiver vazio.
+			select_available_users.innerHTML = 'lixo' + data;
+			select_available_users.outerHTML = select_available_users.outerHTML;
+
+			select_available_users.disabled = false;
+			select_available_users_clone = document.getElementById('ea_select_available_users').cloneNode(true);
+			document.getElementById('ea_input_searchUser').value = '';
+		}
+	}
+
+	cExecute ('$this.ldap_functions.search_users_only&&filtro='+users+'&tipo='+tipoTpl+'&denied_uidnumber='+document.forms[0].uidnumber.value, handler_search_users);
+
+}
+
+function add_externalUser2maillist()
+{
+	input_externalUsers = document.getElementById('ea_input_externalUser').value;
+	select_usersInMaillist = document.getElementById('ea_select_usersInMaillist');
+
+	var count_externalUsers = input_externalUsers.length;
+	var count_usersInMaillist = select_usersInMaillist.options.length;
+	var new_options = '';
+
+	var teste = ''; //Variavel que ira receber mensagem de alerta ao usuario;
+	var alerta = new Boolean(0); //Variavel que sera usada para verificar se o alerta ao usuario sera exibido ou nao;
+	teste += "Usuário(os) já pertence(m) à lista:\n"; //Inicio da mensagem de alerta ao usuario;
+
+
+	//Laco abaixo compara se o valor escolhido em select_available_users ja existe em select_usersInMaillist
+	//se existir, adiciona o valor em teste e muda a variavel alerta para true; teste sera exibido em tela
+	//apenas de alerta  true; ver if no fim da funcao;
+	for(j = 0; j < count_usersInMaillist; j++)
+	{
+		var tmp = select_usersInMaillist.options[j].text
+
+		if(tmp.match(input_externalUsers))
+		{
+			teste += input_externalUsers + "\n";
+			alerta = new Boolean(1);
+		}
+	}
+
+	if(alerta != true)
+	{
+		if(document.all)
+		{
+			if ( (select_usersInMaillist.innerHTML.indexOf('value='+input_externalUsers)) == '-1' )
+			{
+				new_options +=  "<option value="
+							+ input_externalUsers
+							+ ">"
+							+ input_extenalUsers
+							+ "</options>";
+			}
+		}
+		else
+		{		
+			if ( (select_usersInMaillist.innerHTML.indexOf('value="'+input_externalUsers+'"')) == '-1' )
+			{
+				new_options +=  "<option value="
+							+ input_externalUsers
+							+ ">"
+							+ input_externalUsers
+							+ "</options>";
+			}
+		}
+	}
+
+	//Se alerta for true, exibe na tela o valor de teste;
+	if(alerta == true)
+	{
+		alert(teste);
+	}
+
+
+	if (new_options != '')
+	{
+		select_usersInMaillist.innerHTML = 'lixo' + new_options + select_usersInMaillist.innerHTML;
+		select_usersInMaillist.outerHTML = select_usersInMaillist.outerHTML;
+	}
+
+	document.getElementById('ea_input_externalUser').value = '';
+
+}
+
+
+
+function add_user2maillist()
+{
+	select_available_users = document.getElementById('ea_select_available_users');
+	select_usersInMaillist = document.getElementById('ea_select_usersInMaillist');
+
+	var count_available_users = select_available_users.length;
+	var count_usersInMailList = select_usersInMaillist.options.length;
+	var new_options = '';
+
+	var teste = ''; //Variavel que ira receber mensagem de alerta ao usuario;
+	var alerta = new Boolean(0); //Variavel que sera usada para verificar se o alerta ao usuario sera exibido ou nao;
+	teste += "Usuário(os) já pertence(m) à lista:\n"; //Inicio da mensagem de alerta ao usuario;
+
+	for (i = 0 ; i < count_available_users ; i++)
+	{
+		if (select_available_users.options[i].selected)
+		{
+
+
+			//Laco abaixo compara se o valor escolhido em select_available_users ja existe em select_usersInMaillist
+			//se existir, adiciona o valor em teste e muda a variavel alerta para true; teste sera exibido em tela
+			//apenas de alerta  true; ver if no fim da funcao;
+			for(j = 0; j < count_usersInMailList; j++)
+			{
+				if(select_usersInMaillist.options[j].text == select_available_users.options[i].text)
+				{
+					teste += select_available_users.options[i].text + "\n";
+					alerta = new Boolean(1);
+				}
+			}
+
+
+			if(document.all)
+			{
+				if ( (select_usersInMaillist.innerHTML.indexOf('value='+select_available_users.options[i].value)) == '-1' )
+				{
+					new_options +=  "<option value="
+								+ select_available_users.options[i].value
+								+ ">"
+								+ select_available_users.options[i].text
+								+ "</options>";
+				}
+			}
+			else
+			{		
+				if ( (select_usersInMaillist.innerHTML.indexOf('value="'+select_available_users.options[i].value+'"')) == '-1' )
+				{
+					new_options +=  "<option value="
+								+ select_available_users.options[i].value
+								+ ">"
+								+ select_available_users.options[i].text
+								+ "</options>";
+				}
+			}
+		}
+	}
+
+	//Se alerta for true, exibe na tela o valor de teste;
+	if(alerta == true)
+	{
+		alert(teste);
+	}
+
+
+	if (new_options != '')
+	{
+		select_usersInMaillist.innerHTML = 'lixo' + new_options + select_usersInMaillist.innerHTML;
+		select_usersInMaillist.outerHTML = select_usersInMaillist.outerHTML;
+	}
+}
+
+function remove_user2maillist()
+{
+	select_usersInMaillist = document.getElementById('ea_select_usersInMaillist');
+	
+	for(var i = 0;i < select_usersInMaillist.options.length; i++)
+		if(select_usersInMaillist.options[i].selected)
+			select_usersInMaillist.options[i--] = null;
+}
+
+function add_user2adm_maillist()
+{
+	select_available_users = document.getElementById('ea_select_available_users');
+	select_ADM_Maillist = document.getElementById('ea_select_ADM_Maillist');
+
+	var count_available_users = select_available_users.length;
+	var count_ADM_MailList = select_ADM_Maillist.options.length;
+	var new_options = '';
+
+
+	var teste = ''; //Variavel que ira receber mensagem de alerta ao usuario;
+	var alerta = new Boolean(0); //Variavel que sera usada para verificar se o alerta ao usuario sera exibido ou nao;
+	teste += "Usuário(os) já pertence(m) à lista:\n"; //Inicio da mensagem de alerta ao usuario;
+
+
+	for (i = 0 ; i < count_available_users ; i++)
+	{
+		if (select_available_users.options[i].selected)
+		{
+
+
+			//Laco abaixo compara se o valor escolhido em select_available_users ja existe em select_ADM_Maillist
+			//se existir, adiciona o valor em teste e muda a variavel alerta para true; teste sera exibido em tela
+			//apenas de alerta  true; ver if no fim da funcao;
+			for(j = 0; j < count_ADM_MailList; j++)
+			{
+				if(select_ADM_Maillist.options[j].text == select_available_users.options[i].text)
+				{
+					teste += select_available_users.options[i].text + "\n";
+					alerta = new Boolean(1);
+				}
+			}
+
+
+			if(document.all)
+			{
+				if ( (select_ADM_Maillist.innerHTML.indexOf('value='+select_available_users.options[i].value)) == '-1' )
+				{
+					new_options +=  "<option value="
+								+ select_available_users.options[i].value
+								+ ">"
+								+ select_available_users.options[i].text
+								+ "</options>";
+				}
+			}
+			else
+			{		
+				if ( (select_ADM_Maillist.innerHTML.indexOf('value="'+select_available_users.options[i].value+'"')) == '-1' )
+				{
+					new_options +=  "<option value="
+								+ select_available_users.options[i].value
+								+ ">"
+								+ select_available_users.options[i].text
+								+ "</options>";
+				}
+			}
+		}
+	}
+
+
+	//Se alerta for true, exibe na tela o valor de teste;
+	if(alerta == true)
+	{
+		alert(teste);
+	}
+
+	if (new_options != '')
+	{
+		select_ADM_Maillist.innerHTML = 'lixo' + new_options + select_ADM_Maillist.innerHTML;
+		select_ADM_Maillist.outerHTML = select_ADM_Maillist.outerHTML;
+	//	select_AdminInMaillist.outerHTML = select_AdminInMaillist.outerHTML;
+	}
+}
+
+function remove_user2adm_maillist()
+{
+	select_ADM_Maillist = document.getElementById('ea_select_ADM_Maillist');
+	
+	for(var i = 0;i < select_ADM_Maillist.options.length; i++)
+		if(select_ADM_Maillist.options[i].selected)
+			select_ADM_Maillist.options[i--] = null;
+}
+
+
+function add_user2scl_maillist()
+{
+	select_available_users = document.getElementById('ea_select_available_users');
+	select_usersInMaillist = document.getElementById('ea_select_users_SCL_Maillist');
+
+	var count_available_users = select_available_users.length;
+	var count_usersInMailList = select_usersInMaillist.options.length;
+	var new_options = '';
+
+
+	var teste = ''; //Variavel que ira receber mensagem de alerta ao usuario;
+	var alerta = new Boolean(0); //Variavel que sera usada para verificar se o alerta ao usuario sera exibido ou nao;
+	teste += "Usuário(os) já pertence(m) à lista:\n"; //Inicio da mensagem de alerta ao usuario;
+
+
+	for (i = 0 ; i < count_available_users ; i++)
+	{
+		if (select_available_users.options[i].selected)
+		{
+
+
+			//Laco abaixo compara se o valor escolhido em select_available_users ja existe em select_usersInMaillist
+			//se existir, adiciona o valor em teste e muda a variavel alerta para true; teste sera exibido em tela
+			//apenas de alerta  true; ver if no fim da funcao;
+			for(j = 0; j < count_usersInMailList; j++)
+			{
+				if(select_usersInMaillist.options[j].text == select_available_users.options[i].text)
+				{
+					teste += select_available_users.options[i].text + "\n";
+					alerta = new Boolean(1);
+				}
+			}
+
+
+			if(document.all)
+			{
+				if ( (select_usersInMaillist.innerHTML.indexOf('value='+select_available_users.options[i].value)) == '-1' )
+				{
+					new_options +=  "<option value="
+								+ select_available_users.options[i].value
+								+ ">"
+								+ select_available_users.options[i].text
+								+ "</options>";
+				}
+			}
+			else
+			{		
+				if ( (select_usersInMaillist.innerHTML.indexOf('value="'+select_available_users.options[i].value+'"')) == '-1' )
+				{
+					new_options +=  "<option value="
+								+ select_available_users.options[i].value
+								+ ">"
+								+ select_available_users.options[i].text
+								+ "</options>";
+				}
+			}
+		}
+	}
+
+
+	//Se alerta for true, exibe na tela o valor de teste;
+	if(alerta == true)
+	{
+		alert(teste);
+	}
+
+	if (new_options != '')
+	{
+		select_usersInMaillist.innerHTML = '#' + new_options + select_usersInMaillist.innerHTML;
+		select_usersInMaillist.outerHTML = select_usersInMaillist.outerHTML;
+	}
+}
+
+function remove_user2scl_maillist()
+{
+	select_usersInMaillist = document.getElementById('ea_select_users_SCL_Maillist');
+	
+	for(var i = 0;i < select_usersInMaillist.options.length; i++)
+		if(select_usersInMaillist.options[i].selected)
+			select_usersInMaillist.options[i--] = null;
+}
+
+
+// Variaveis Locais 
+if (document.getElementById('ea_select_available_users'))
+{
+	var select_available_users  = document.getElementById('ea_select_available_users');
+	var select_available_users_clone = select_available_users.cloneNode(true);
+}
+else
+{
+	var select_available_users  = '';
+	var select_available_users_clone = '';
+}
+var finderTimeout = '';
+
+// Funcoes											
+function optionFinderTimeout(obj)
+{
+	clearTimeout(finderTimeout);	
+	var oWait = document.getElementById("ea_span_searching");
+	oWait.innerHTML = 'Buscando...';
+	finderTimeout = setTimeout("optionFinder('"+obj.id+"')",500);
+}
+function optionFinder(id) {
+	var oWait = document.getElementById("ea_span_searching");
+	var oText = document.getElementById(id);
+		
+	//Limpa todo o select
+if(oText.length < 4) {
+	var select_available_users_tmp = document.getElementById('ea_select_available_users');
+
+	for(var i = 0;i < select_available_users_tmp.options.length; i++)
+		select_available_users_tmp.options[i--] = null;
+}
+if(oText.length >= 4) {
+
+get_available_users(oText.value);
+
+                        var select_available_users_tmp = document.getElementById('ea_select_available_users');
+                        for(var i = 0;i < select_available_users_tmp.options.length; i++)
+                                select_available_users_tmp.options[i--] = null;
+	var RegExp_name = new RegExp("\\b"+oText.value, "i");
+	
+	//Inclui usuário começando com a pesquisa
+/*	for(i = 0; i < select_available_users_clone.length; i++){
+		if ( RegExp_name.test(select_available_users_clone[i].text) || (select_available_users_clone[i].value == -1) )
+		{
+			sel = select_available_users_tmp.options;
+			option = new Option(select_available_users_clone[i].text,select_available_users_clone[i].value);
+
+			if (select_available_users_clone[i].value == -1)
+				option.disabled = true;
+
+			sel[sel.length] = option;
+		}
+	}*/
+	oWait.innerHTML = '&nbsp;';
+}
+}			
+
+function delete_maillist(uid, uidnumber)
+{
+	if (confirm("Realmente deletar Lista " + uid + " ??"))
+	{
+		var handler_delete_maillist = function(data)
+		{
+			if (!data.status)
+				alert(data.msg);
+			else
+				//alert('Lista de email deletada com êxito!!');
+				window.setTimeout("cExecute('$this.maillist.synchronize_mailman&uid=" + uid + "&op=0', handler_delete_maillist_sync)", 10);
+			
+//			location.href="./index.php?menuaction=listAdmin.uimaillists.list_maillists";
+	//		return;
+		}
+		cExecute ('$this.maillist.delete&uidnumber='+uidnumber, handler_delete_maillist);
+	}
+}
+
+function handler_delete_maillist_sync(data){
+	//Converte os dados do vetor oriundo de um script PHP para um vetor JavaScript
+	var dados_serializados = eval(data);
+	return_handler_delete_maillist_sync(dados_serializados);
+}
+
+function return_handler_delete_maillist_sync(data){
+	//Depois de processar a sincronização do Mailman com o RHDS, redireciona o usuário para a tela inicial
+	//Mesmo que não tenha tido êxito, segue o comportamento default da aplicação, redirecionando o usuário
+	//EM CASO DE ERRO NA SINCRONIZAÇÃO: CONFERIR O LOG "expresso_sincronizacao_mailmanrhds.log" em "/tmp"
+	//alert("Retorno do socket:\nSTATUS=" + data['status'] +'\nMSG=' + data['msg']);
+	alert('Lista de email deletada com êxito!!');
+	location.href="./index.php?menuaction=listAdmin.uimaillists.list_maillists";		
+	
+}
+
+
Index: /branches/2.2/listAdmin/index.php
===================================================================
--- /branches/2.2/listAdmin/index.php	(revision 3514)
+++ /branches/2.2/listAdmin/index.php	(revision 3514)
@@ -0,0 +1,47 @@
+<?php
+	/************************************************************************************************\
+	* Administracao de Listas (baseadas no Mailman)							*
+	* by Rommel de Brito Cysne (rommel.cysne@serpro.gov.br, rommel.cysne@gmail.com)			*
+	* ----------------------------------------------------------------------------------------------*
+	*  This program is free software; you can redistribute it and/or modify it			*
+	*  under the terms of the GNU General Public License as published by the			*
+	*  Free Software Foundation; either version 2 of the License, or (at your			*
+	*  option) any later version.									*
+	\************************************************************************************************/
+
+	$GLOBALS['phpgw_info'] = array();
+	$GLOBALS['phpgw_info']['flags']['currentapp'] = 'listAdmin';
+	include('../header.inc.php');
+
+	$c = CreateObject('phpgwapi.config','listAdmin');
+	$c->read_repository();
+	$current_config = $c->config_data;
+	
+	$_SESSION['phpgw_info']['expresso']['user'] = $GLOBALS['phpgw_info']['user'];
+	$_SESSION['phpgw_info']['expresso']['server'] = $GLOBALS['phpgw_info']['server'];
+	$_SESSION['phpgw_info']['expresso']['listAdmin'] = $current_config;
+	$_SESSION['phpgw_info']['expresso']['global_denied_users'] = $GLOBALS['phpgw_info']['server']['global_denied_users'];
+	$_SESSION['phpgw_info']['expresso']['global_denied_groups'] = $GLOBALS['phpgw_info']['server']['global_denied_groups'];
+	
+	$template = CreateObject('phpgwapi.Template',PHPGW_APP_TPL);
+	$template->set_file(Array('listAdmin' => 'index.tpl'));
+	$template->set_block('listAdmin','body');
+	
+
+	$exibir = 'inline';
+	$ocultar = 'none';
+
+	$var = Array(
+		'lang_email_lists'              => lang('Email Lists'),
+		'msg'                           => $msg,
+		'exibir'                        => $exibir,
+		'ocultar'                       => $ocultar
+	);
+	$template->set_var($var);
+	$template->pfp('out','body');
+
+//	$obj = CreateObject('listAdmin.uimaillists');
+//	$obj->list_maillists();
+	
+	$GLOBALS['phpgw']->common->phpgw_footer();
+?>
Index: /branches/2.2/listAdmin/templates/default/maillists.tpl
===================================================================
--- /branches/2.2/listAdmin/templates/default/maillists.tpl	(revision 3514)
+++ /branches/2.2/listAdmin/templates/default/maillists.tpl	(revision 3514)
@@ -0,0 +1,62 @@
+<!-- BEGIN list -->
+<p>
+  <div align="center">
+   <table border="0" width="95%">
+    <tr>
+	 	<td align="left" width="25%">
+	  		<form name="form" method="POST" action="{add_action}">
+	  			<input type="submit" value="{lang_add_email_lists}" {desabilitado} />
+				<input type="button" value="{lang_back}" onClick="document.location.href='{back_url}'" />
+	  		</form>
+	 	</td>
+	 	<td align="center" "left" width="50%">
+			{lang_context}: <font color="blue">{context_display}</font>
+	 	</td>
+     	<td align="right" width="25%">
+     		<form method="POST" action="{accounts_url}">
+     			{lang_search}:
+     			<input type="text" name="query" autocomplete="on" value="{query}" /><input type="submit" value="Pesquisar" />
+      		</form>
+     	</td>
+    </tr>
+   </table>
+  </div>
+ 
+ <div align="center">
+  <table border="0" width="95%">
+   <tr bgcolor="{th_bg}">
+<!--    <td width="20%">{lang_email_lists_uid}</td>-->
+    <td width="30%">{lang_email_lists_names}</td>
+    <td width="40%">{lang_email}</td>
+    <td width="8%" align="center">{lang_edit}</td>
+    <td width="8%" align="center"><span title='Sending Control List'>{lang_scl}<span></td>
+    <td width="8%" align="center"><span title='Adm Listas'>{lang_adm}<span></td>
+    <td width="8%" align="center">{lang_delete}</td>
+   </tr>
+
+   {rows}
+
+  </table>
+ </div>
+<!-- END list -->
+
+<!-- BEGIN row -->
+   <tr bgcolor="{tr_color}">
+<!--    <td width="20%">{row_uid}</td>-->
+    <td width="20%">{row_name}</td>
+    <td width="20%">{row_email}</td>
+    <td width="6%" align="center">{edit_link}</td>
+    <td width="6%" align="center">{scl_link}</td>
+    <td width="6%" align="center">{adm_link}</td>
+    <td width="7%" align="center">{delete_link}</td>
+   </tr>
+<!-- END row -->
+
+<!-- BEGIN row_empty -->
+   <tr>
+    <td colspan="5" align="center"><font color="red"><b>{message}</b></font></td>
+   </tr>
+   <tr>
+	<td><input type="button" value="{lang_back}" onClick="document.location.href='{back_url}'" /></td>
+   </tr>
+<!-- END row_empty -->
Index: /branches/2.2/listAdmin/templates/default/maillists_adm.tpl
===================================================================
--- /branches/2.2/listAdmin/templates/default/maillists_adm.tpl	(revision 3514)
+++ /branches/2.2/listAdmin/templates/default/maillists_adm.tpl	(revision 3514)
@@ -0,0 +1,97 @@
+<table border="0" width="90%" align="center">
+	<tr>
+		<td valign="top">
+			{rows}
+		</td>
+		<td valign="top">
+			<table border="0" width=100% cellspacing="4">
+			<form action="{form_action}" method="POST" name="app_form">
+					<input type="hidden" name="uidnumber" value="{uidnumber}">
+					<input type="hidden" name="old_uid" value="{uid}">
+					<input type="hidden" name="ldap_context" value="{ldap_context}">
+					<input type="hidden" name="tipo" value="{type}">
+					<input type="hidden" name="manager_context" value="{manager_context}">
+					<input type="hidden" name="restrictionsOnEmailLists" value="{restrictionsOnEmailLists}">
+
+				<tr>
+					<td colspan="3" align="right" bgcolor="{color_bg1}">
+						<input type="button" value="{lang_back}" onClick="document.location.href='{back_url}'" />
+						<!--<input type="button" value="{lang_save}" onClick="javascript:validate_fields('{type}');" {desabilitado} />-->
+						<input type="button" value="{lang_save}" onClick="javascript:save_adm();" {desabilitado} />
+					</td>
+				</tr>
+
+				<tr style="display:none;">
+					<td width="25%" bgcolor="#DDDDDD">
+						Organização da Lista:<br />
+						<select name="context" onchange="javascript:sinc_combos_org(this.value, ea_check_allUsers.checked);">{combo_org}</select><br />
+					</td>
+					<td width="25%" bgcolor="#DDDDDD"></td>
+					<td width="25%" bgcolor="#DDDDDD"></td>
+				</tr>
+				<tr>
+					<td width="25%" bgcolor="#DDDDDD">
+						{lang_maillist_uid}:<br />
+						<input name="uid" size="35" value="{uid}" autocomplete="off" readonly /><br />
+					</td>
+					<td width="25%" bgcolor="#DDDDDD"></td>
+					<td width="25%" bgcolor="#DDDDDD">
+						<p style="display:none;">Senha: <font color="blue"><br /> </font></p>
+						<input name="listPass" size="35" type="password" value="{listPass}" autocomplete="off" style="display:none;" />
+					</td>
+				</tr>
+				<tr>	
+					<td width="25%" bgcolor="#DDDDDD">					
+						{lang_maillist_mail}:<br />
+						<input name="mail" size="60" value="{mail}" autocomplete="off" readonly /><br />
+
+						{lang_maillist_description}:<br />
+						<input name="description" size="60" value="{description}" autocomplete="off" readonly /><br />
+						Lista de E-mail está ativa: <input type="checkbox" {accountStatus_checked} name="accountStatus" {desabilitado} /><br />
+						Ocultar Lista de E-mail ??: <input type="checkbox" {phpgwAccountVisible_checked} name="phpgwAccountVisible" {desabilitado} /><br />
+						<b>{lang_maillist_adm}:</b><br />
+						<select id="ea_select_ADM_Maillist" name="members[]" style="width:400px; height:150px" multiple size="13">{ea_select_ADM_Maillist}
+						</select>
+					</td>
+
+					<td valign="middle" align="center" bgcolor="#DDDDDD">
+						<button type="button" onClick="javascript:add_user2adm_maillist();" {desabilitad} ><img src="listAdmin/templates/default/images/add.png" style="vertical-align: middle;" >&nbsp;{lang_add_user}</button>
+						<br /><br />
+						<button type="button" onClick="javascript:remove_user2adm_maillist();" {desabilitad} ><img src="listAdmin/templates/default/images/rem.png" style="vertical-align: middle;" >&nbsp;{lang_rem_user}</button>
+					</td>
+
+					<td valign="bottom" bgcolor="#DDDDDD">
+						<p style="display: none;" >Organizações:</p><br />
+						<select name="org_context" id="ea_combo_org_maillists" onchange="//javascript:get_available_users_only(this.value, ea_check_allUsers.checked);" disabled style="display:none;" >{combo_org}
+						</select>
+
+						<br />
+<!--						<input type="checkbox" name="ea_check_allUsers" id="ea_check_allUsers" onclick="javascript:get_available_users_only(org_context.value, this.checked);" />{lang_all_users}.-->
+						<br />
+
+						Procurar usuário:<br />
+						<input id="ea_input_searchUser" size="35" autocomplete="off" onkeyup="//javascript:optionFinderTimeout(this)" {somente_leitur} />
+
+						<!-- botao de pesquisa manual -->
+						<input type="button" id="search_user" value="Pesquisar" onClick="javascript:search_users();" {desabilitad} /><br />
+
+						<!-- <font color="red"><span id="ea_span_searching">&nbsp;</span></font> -->
+						<br />
+						 <b>Usuários:</b>
+						 <select id="ea_select_available_users" style="width:400px; height:150px" multiple size="13">
+						</select>
+
+					</td>
+				</tr>
+				<tr>
+					<td colspan="3" align="left" bgcolor="{color_bg1}">
+						<!--<input type="button" value="{lang_save}" onClick="javascript:validate_fields('{type}');" {desabilitad} />-->
+						<input type="button" value="{lang_save}" onClick="javascript:save_adm();" {desabilitad} />
+						<input type="button" value="{lang_back}" onClick="document.location.href='{back_url}'" />
+					</td>
+				</tr>
+			</form>
+			</table>
+		</td>
+	</tr>
+</table>
Index: /branches/2.2/listAdmin/templates/default/maillists_scl.tpl
===================================================================
--- /branches/2.2/listAdmin/templates/default/maillists_scl.tpl	(revision 3514)
+++ /branches/2.2/listAdmin/templates/default/maillists_scl.tpl	(revision 3514)
@@ -0,0 +1,83 @@
+<table border="0" width="90%" align="center">
+	<tr>
+		<td valign="top">
+			{rows}
+		</td>
+		<td valign="top">
+			<table border="0" width=100% cellspacing="4">
+				<form action="{form_action}" method="POST" name="app_form">
+					<input type="hidden" name="uidnumber" value="{uidnumber}">
+					<input type="hidden" name="dn" value="{dn}">
+					<input type="hidden" name="ldap_context" value="{ldap_context}">
+					<input type="hidden" name="tipo" value="{type}">
+					<input type="hidden" name="manager_context" value="{manager_context}">
+					
+					<tr>
+						<td colspan="3" align="right" bgcolor="{color_bg1}">
+							<input type="button" value="{lang_back}" onClick="document.location.href='{back_url}'" />
+							<input type="button" value="{lang_save}" onClick="javascript:save_scl();" {desabilitado} />
+						</td>
+					</tr>
+
+					
+					<tr>
+						<td width="25%" bgcolor="#DDDDDD">
+							{lang_maillist_uid}:<br/>
+							<input name="uid" size="35" value="{uid}" autocomplete="off" readonly /><br />
+						</td>
+						<td width="25%" bgcolor="#DDDDDD"></td>
+						<td width="25%" bgcolor="#DDDDDD"></td>
+					</tr>
+
+					<tr>
+						<td width="25%" valign="bottom" bgcolor="#DDDDDD">
+							{lang_maillist_mail}:<br/>
+							<input name="mail" size="60" value="{mail}" autocomplete="off" readonly /><br />
+
+							{lang_maillist_description}:<br />
+							<input name="description" size="60" value="{description}" autocomplete="off" readonly /><br />
+							Aplicar controle de envio a esta lista ? <input type="checkbox" {accountRestrictive_checked} name="accountRestrictive" {desabilitado} ><br />
+							Participantes da lista podem enviar email ? <input type="checkbox" {participantCanSendMail_checked} name="participantCanSendMail" {desabilitado} ><br />
+							<b>Usuários que podem enviar email para esta lista:</b><br />
+							<select id="ea_select_users_SCL_Maillist" name="members[]" style="width:400px; height:200px" multiple size="13">{ea_select_users_SCL_Maillist}</select>
+						</td>
+						
+						<td valign="middle" align="center" bgcolor="#DDDDDD">
+							<br /><br /><br /><br /><br /><br />
+							<button type="button" onClick="javascript:add_user2scl_maillist();" {desabilitad} ><img src="listAdmin/templates/default/images/add.png" style="vertical-align: middle;" >&nbsp;{lang_add_user}</button>
+							<br /><br />
+							<button type="button" onClick="javascript:remove_user2scl_maillist();" {desabilitad} ><img src="listAdmin/templates/default/images/rem.png" style="vertical-align: middle;" >&nbsp;{lang_rem_user}</button>
+						</td>
+						
+						<td valign="bottom" bgcolor="#DDDDDD">
+							<p style="display: none;" >Organizações:</p><br />
+							<select name="org_context" id="ea_combo_org_maillists" onchange="//javascript:get_available_users(this.value, ea_check_allUsers.checked);" disabled style="display: none;" >{combo_org}</select>
+							
+							<br />
+<!--							<input type="checkbox" name="ea_check_allUsers" id="ea_check_allUsers" onclick="javascript:get_available_users(org_context.value, this.checked);">{lang_all_users}.-->
+							<br />
+							
+							Procurar usuário:<br />
+							<input id="ea_input_searchUser" size="35" autocomplete="off" onkeyup="//javascript:optionFinderTimeout(this)" {somente_leitur} />
+						
+							<!-- botao de pesquisa manual -->
+							<input type="button" id="search_user" value="Pesquisar" onClick="javascript:search_users();" {desabilitad} /><br />
+	
+<!--							<font color="red"><span id="ea_span_searching">&nbsp;</span></font>-->
+							<br />
+							<b>Usuários:</b>
+							<select id="ea_select_available_users" style="width:400px; height:200px" multiple size="13"></select>
+						</td>
+					</tr>
+					
+					<tr>
+						<td colspan="3" align="left" bgcolor="{color_bg1}">
+							<input type="button" value="{lang_save}" onClick="javascript:save_scl();" {desabilitad} />
+							<input type="button" value="{lang_back}" onClick="document.location.href='{back_url}'" />
+						</td>
+					</tr>
+				</form>
+			</table>
+		</td>
+	</tr>
+</table>
Index: /branches/2.2/listAdmin/templates/default/maillists_form.tpl
===================================================================
--- /branches/2.2/listAdmin/templates/default/maillists_form.tpl	(revision 3514)
+++ /branches/2.2/listAdmin/templates/default/maillists_form.tpl	(revision 3514)
@@ -0,0 +1,104 @@
+<table border="0" width="90%" align="center">
+	<tr>
+		<td valign="top">
+			{rows}
+		</td>
+		<td valign="top">
+			<table border="0" width=100% cellspacing="4">
+				<form action="{form_action}" method="POST" name="app_form">
+					<input type="hidden" name="uidnumber" value="{uidnumber}">
+					<input type="hidden" name="old_uid" value="{uid}">
+					<input type="hidden" name="ldap_context" value="{ldap_context}">
+					<input type="hidden" name="tipo" value="{type}">
+					<input type="hidden" name="manager_context" value="{manager_context}">
+					<input type="hidden" name="restrictionsOnEmailLists" value="{restrictionsOnEmailLists}">
+
+					<tr>
+						<td colspan="3" align="right" bgcolor="{color_bg1}">
+							<input type="button" value="{lang_back}" onClick="document.location.href='{back_url}'" />
+							<input type="button" value="{lang_save}" onClick="javascript:validate_fields('{type}');" {desabilitado} />
+						</td>
+					</tr>
+					
+					<tr style="display: none;">
+						<td width="25%" bgcolor="#DDDDDD">
+							Organizaï¿œï¿œo da Lista:<br />
+							<select name="context" onchange="javascript:sinc_combos_org(this.value, ea_check_allUsers.checked);">{combo_org}</select><br />
+						</td>
+						<td width="25%" bgcolor="#DDDDDD"></td>
+						<td width="25%" bgcolor="#DDDDDD"></td>
+					</tr>
+					<tr>
+					        <td width="25%" bgcolor="#DDDDDD">
+							{lang_maillist_uid}: <font color="blue">Ex: lista-rh</font>
+							<input name="uid" size="35" value="{cn}" autocomplete="off" {somente_leitura} {soAdminLe} /><br />
+						</td>
+					        <td width="25%" bgcolor="#DDDDDD"></td>
+					        <td width="25%" bgcolor="#DDDDDD">
+					        	Senha: <font color="blue"><br /> </font>
+					                <input name="listPass" size="35" type="password" value="{listPass}" autocomplete="off" {somente_leitur} />
+						</td>
+					</tr>
+					<tr>	
+						<td valign="top" width="25%" bgcolor="#DDDDDD">
+							<div {exibir_div} >
+								{lang_maillist_mail}: <font color="blue">Ex: lista-rh@organiza&ccedil;&atilde;o.gov.br</font>
+								<input name="mail" size="60" value="{mail}" autocomplete="off" {somente_leitura} {soAdminLe} />
+							</div>
+
+							{lang_maillist_description}:<br />
+							<input name="description" size="60" value="{description}" autocomplete="off" {somente_leitura} {soAdminLe} /><br />
+							Lista de E-mail estï¿œ ativa: <input type="checkbox" {accountStatus_checked} name="accountStatus" {desabilitado} /><br />
+							Ocultar Lista de E-mail ??: <input type="checkbox" {phpgwAccountVisible_checked} name="phpgwAccountVisible" {desabilitado} /><br />
+							Lista Publica :	<input type="checkbox" {defaultMemberModeration_checked} name="defaultMemberModeration" {desabilitado} /><br />
+							<b>{lang_maillist_users}:</b><br />
+							<select id="ea_select_usersInMaillist" name="members[]" style="width:400px; height:150px" multiple size="13">{ea_select_usersInMaillist}
+							</select>
+						</td>
+						
+						<td valign="middle" align="center" bgcolor="#DDDDDD">
+							<button type="button" onClick="javascript:add_user2maillist();" {desabilitad} ><img src="listAdmin/templates/default/images/add.png" style="vertical-align: middle;"  >&nbsp;{lang_add_user}</button>
+							<br /><br />
+							<button type="button" onClick="javascript:remove_user2maillist();" {desabilitad} ><img src="listAdmin/templates/default/images/rem.png" style="vertical-align: middle;"  >&nbsp;{lang_rem_user}</button>
+						</td>
+						<td valign="top" bgcolor="#DDDDDD">
+							<p style="display:none;" >Organizaï¿œï¿œes:</p>
+							<select name="org_context" id="ea_combo_org_maillists" onchange="//javascript:get_available_users(this.value, ea_check_allUsers.checked);" disabled style="display:none;" >{combo_org}</select>
+							
+<!--							<input type="checkbox" name="ea_check_allUsers" id="ea_check_allUsers" onclick="javascript:get_available_users(org_context.value, this.checked);">{lang_all_users}.-->
+							
+							Procurar usuï¿œrio:<br />
+							<input id="ea_input_searchUser" size="35" autocomplete="off" onkeyup="//javascript:optionFinderTimeout(this)" {somente_leitur} />
+							
+							<!-- botao de pesquisa manual -->
+							<input type="button" id="search_user" value="Pesquisar" onClick="javascript:search_users();" {desabilitad} /><br />
+
+<!--							<font color="red"><span id="ea_span_searching">&nbsp;</span></font>-->
+							
+							<br />
+							<b>Usuï¿œrios:</b>
+							<select id="ea_select_available_users" style="width:400px; height:150px" multiple size="13"></select>
+							<br />
+							<br />
+							
+							<b>Usuï¿œrio externo:</b>
+							<br />
+							<input type="text" id="ea_input_externalUser" size="35" />
+							
+							<input type="button" id="input_user" value="Adicionar" onClick="javascript:add_externalUser2maillist();" {desabilitad} /><br />
+
+						</td>
+					</tr>
+                			<font color="blue"><br /> </font>
+        				</td>
+					<tr>
+						<td colspan="3" align="left" bgcolor="{color_bg1}">
+							<input type="button" value="{lang_save}" onClick="javascript:validate_fields('{type}');" {desabilitad} />
+							<input type="button" value="{lang_back}" onClick="document.location.href='{back_url}'" />
+						</td>
+					</tr>
+				</form>
+			</table>
+		</td>
+	</tr>
+</table>
Index: /branches/2.2/listAdmin/templates/default/config.tpl
===================================================================
--- /branches/2.2/listAdmin/templates/default/config.tpl	(revision 3514)
+++ /branches/2.2/listAdmin/templates/default/config.tpl	(revision 3514)
@@ -0,0 +1,134 @@
+<!-- BEGIN header -->
+
+<form method="POST" action="{action_url}">
+<table border="0" align="center">
+<tbody>
+	<tr class="th">
+		<td colspan="2"><font color="{th_text}">&nbsp;<b>{title}</b></font></td>
+	</tr>
+	<tr>
+		<td colspan="2"><b>{error}</b></td>
+	</tr>
+	<tr>
+		<td colspan="2"></td>
+	</tr>
+<!-- END header -->
+<!-- BEGIN body -->
+
+<!-- INICIO BLOCO MAILMAN -->
+
+	<tr class="row_off">
+		<td>
+			<b>
+				Digite o DN usado pelas listas. (Ex.: ou=listas,dc=company,dc=com,dc=br)
+			</b>
+		</td>
+		
+		<td>
+			<INPUT size="50" name="newsettings[dn_listas]" value="{value_dn_listas}" />
+		</td>
+	</tr>
+	<tr class="row_on">
+		<td>
+			<b>
+				Digite o NOME do grupo de administradores de listas. (Ex.: listadmin)
+			</b>
+		</td>
+
+		<td>
+			<INPUT size="50" name="newsettings[name_listadmin]" value="{value_name_listadmin}" />
+		</td>
+	</tr>
+	<tr class="row_off">
+		<td>
+			<b>
+				Digite o DN do grupo de administradores de listas. (Ex.: ou=grupos,dc=company,dc=com,dc=br)
+			</b>
+		</td>
+
+		<td>
+			<INPUT size="50" name="newsettings[dn_listadmin]" value="{value_dn_listadmin}" />
+		</td>
+	</tr>
+	<tr class="row_on">
+		<td>
+			<b>
+				Digite o dominio usado pelas listas. (Ex.: dominio.com.br)
+			</b>
+		</td>
+
+		<td>
+			<INPUT size="50" name="newsettings[dominio_listas]" value="{value_dominio_listas}" />
+		</td>
+	</tr>
+	<tr class="row_off">
+		<td>
+			<b>
+				Digite a porta utilizada pelo Mailman. (Ex: 80)
+			</b>
+		</td>
+
+		<td>
+			<INPUT size="50" name="newsettings[porta_mailman]" value="{value_porta_mailman}" onkeypress="return soNumero(this, event);"/>
+		</td>
+	</tr>
+	<tr class="row_on">
+		<td>
+			<b>
+				Digite o endereco IP do servidor Mailman. (Ex.: 192.168.0.1)
+			</b>
+		</td>
+
+		<td>
+			<INPUT size="50" name="newsettings[host_mailman]" value="{value_host_mailman}" />
+		</td>
+	</tr>
+	<tr class="row_off">
+		<td>
+			<b>
+				Digite o caminho do programa de sincronizacao do Mailman.
+			</b>
+		</td>
+
+		<td>
+			<INPUT size="50" name="newsettings[url_mailman]" value="{value_url_mailman}" />
+		</td>
+	</tr>
+
+	<tr class="th">
+		<td colspan="2">&nbsp;</td>
+	</tr>
+
+	<tr class="row_off">
+		<td>
+			<b>
+				{lang_Show_lists_automatically}:
+			</b>
+		</td>
+		<td>
+			<select name="newsettings[mm_ldap_query_automatic]">
+				<option value="true" {selected_mm_ldap_query_automatic_true}>Sim</option>
+				<option value="false" {selected_mm_ldap_query_automatic_false}>Nï¿œo</option>
+			</select>
+		</td>
+	</tr>
+<!-- FIM BLOCO MAILMAN -->
+
+<!-- END body -->
+<!-- BEGIN footer -->
+	<tr>
+		<td colspan="2"></td>
+	</tr>
+	<tr class="th">
+		<td colspan="2">&nbsp;</td>
+	</tr>
+	<tr>
+		<td colspan="2" align="center">
+			<input type="submit" name="submit" value="{lang_submit}">
+			<input type="submit" name="cancel" value="{lang_cancel}">
+		</td>
+	</tr>
+</tbody>
+</table>
+</form>
+<!-- END footer -->
Index: /branches/2.2/listAdmin/templates/default/index.tpl
===================================================================
--- /branches/2.2/listAdmin/templates/default/index.tpl	(revision 3514)
+++ /branches/2.2/listAdmin/templates/default/index.tpl	(revision 3514)
@@ -0,0 +1,17 @@
+<!-- BEGIN body -->
+<table width="90%" border="0" cellspacing="4" cellpadding="0" align="center"> 
+	<tr style="display: {exibir};" >
+		<td width="1%" align="center">
+			<img src='./templates/default/images/mail_list.png'>
+		</td>
+		<td>
+			<a href="../index.php?menuaction=listAdmin.uimaillists.list_maillists">{lang_email_lists}</a>
+		</td>
+	</tr> 
+	<tr style="display: {ocultar};" >
+		<td>
+			{msg}
+		</td>
+	</tr>
+</table>
+<!-- END body -->
Index: /branches/2.2/listAdmin/templates/default/access_denied.tpl
===================================================================
--- /branches/2.2/listAdmin/templates/default/access_denied.tpl	(revision 3514)
+++ /branches/2.2/listAdmin/templates/default/access_denied.tpl	(revision 3514)
@@ -0,0 +1,10 @@
+<!-- BEGIN main -->
+<table width="100%" border="0" cellspacing="0" cellpadding="0">
+	<tr>
+  		<td align="center"><font size="3" color="red"><b>{lang_access_denied}<b></font></td>
+  	</tr>
+	<tr>
+		<td align="center"><input type="button" value="{lang_back}" onClick="document.location.href='{back_url}'"><td>
+	</tr>
+</table>
+<!-- END main -->
