четверг, июля 26, 2007

Вебинтерфейс для добавления почтовых пользователей в mysql

Был написан для решения описанного в статье Mysql+cyrus-sasl+courier-imap+postfix Freebsd 6.2 Авторство скриптов принадлежит Евгении, спасибо ей за это.

Состоит из 5 файлов:

addressbook.csv
adduser.php
connect.inc
edit.php
editform.php


addressbook.csv пустой

содержимое connect.inc

<?php
$dbuser = 'mail_user';
$dbname = 'mail';
$dbpassword = 'secret';
$dbhost = 'localhost';
$domain='my_company.com';
mysql_connect($dbhost,$dbuser,$dbpassword)or die ("Could not connect");
mysql_select_db($dbname) or die ("Could not select database");
?>

содержимое adduser.php

<?php
include 'connect.inc';
$query="select login, password, maildir, comment as fio from users order by login";
$result=mysql_query($query) or die("Query failed");
if (mysql_num_rows($result)==0)
mysql_close();
?>
<HTML><HEAD><TITLE>Пользователи почтового домена</TITLE>
<META http-equiv="Content-Type" content="text/html; charset=windows-1251">
<script language="JavaScript">
function _onclick(str)
{document.forms["mainform"].action.value=str;}
</script>
</HEAD><BODY>
<form action ="editform.php" method="post" name="mainform">
<input type="hidden" name=action value="">
<TABLE border="0" width="100%" >
<tr>
<td width="20%" align="center" colspan="2"><b>Пользователи почтового домена <?php echo("@$domain");?></b></td>
</tr>
<tr>
<td width="20%" align="center" colspan="2"> </td>
</tr>
<tr>
<td width="20%" align="center"><input type="submit" name="" value="Insert" style="width:100%" onClick="_onclick('ins')"></td>
<td width="80%" align="left"><input type="submit" name="" value="Delete" onClick="_onclick('del')" style="width:30%"></td>
</tr>
<tr>
<td width="20%" align="center" colspan="2"> </td>
</tr>
<tr>
<td width="100%" colspan="2">
<TABLE border="2" width="100%" bordercolor="#000000" cellpadding="0" cellspacing="0">
<tr>
<td align="center"><B>Login</B></td>
<td align="center"><B>Password</B></td>
<td align="center"><B>MailDir</B></td>
<td align="center"><B>FIO</B></td>
<td> </td>
<td> </td>
</tr>
<?php
while ($line = mysql_fetch_array($result)){
echo("<tr><td>$line[login]</td>");
if (empty($line['password'])) echo("<td> </td>");
else echo("<td>$line[password]</td>");
echo("<td>$line[maildir]</td>");
$fio=substr($line['fio'],0,50);
if (empty($fio)) echo("<td> </td>");
else echo("<td>$fio</td>");
$login=substr($line['login'],0,strpos($line['login'],"@"));
echo("<td><input type=\"submit\" name=\"\" value=\"Update\" style=\"width:100%\" onClick=\"_onclick('upd_$login')\"></td>");
echo("<td align=\"center\"><input type=\"checkbox\" value=\"$login\" name=\"$login\"></td></tr>");
}
mysql_close();
?>
</TABLE>
</td>
</tr>
</TABLE></form></BODY></HTML>

содержимое edit.php

<?php

function sendmail()
{
$result=mysql_query("select login, comment from users");
$num_rows=mysql_num_rows($result);
if ($num_rows>0){
$to="";
$fname="addressbook.csv";
$fp=fopen($fname,"w");
fwrite($fp,"Имя;Электронная почта\n");
while ($line = mysql_fetch_array($result)){
$to.=trim($line['login']).", ";
$fio=trim($line['comment']);
if (empty($fio)) $fio=trim($line['login']);
fwrite($fp,$fio.";".trim($line['login'])."\n");
}

fclose($fp);
$to=substr_replace($to,'',strlen($to)-2,2);
$message = "
<html><head>
<title>Уведомление</title></head>
<body><p>Добавился новый пользователь почтового домена ".$domain.".<br>
Просьба обновить адресную книгу.</p>
</body></html>
";
$fp= fopen($fname,"r");
$un = strtoupper(uniqid(time()));
$head = "MIME-Version: 1.0\n";
$head .= "Content-Type: multipart/mixed;\n";
$head .= " boundary=\"-".$un."\"\n\n";
$zag = "---".$un."\n";
$zag .= "Content-type: text/html; charset=Windows-1251\n\n";
$zag .= $message."\n\n";
$zag .= "---".$un."\n";
$zag .= "Content-type: application/octet-stream;";
$zag .= " name=\"".basename($fname)."\"\n";
$zag .= "Content-Transfer-Encoding: base64\n";
$zag .= "Content-Disposition: attachment;";
$zag .= " filename=\"".basename($fname)."\"\n";
$zag .= chunk_split(base64_encode(fread($fp,filesize($fname))))."\n";
$zag .= "---".$un."--\n";
fclose($fp);
mail($to, "", $zag, $head);
}
}

if (empty($_POST["mail1"]))
$mail1="";
else
$mail1=$_POST["mail1"];
switch ($_POST["action"]){
case "":
header("location: adduser.php");
break;
case "ins":
if (!empty($_POST['login']))
{
include "connect.inc";
$login=$_POST["login"]."@".$domain;
$maildir=$domain."/".$_POST['login']."/";
mysql_query("insert into users (login, password, maildir,comment) values ('$login',encrypt('$_POST[pass]'),'$maildir','$_POST[fio]')");
if ($mail1=="send") sendmail();
mysql_close();
}

header("location: adduser.php");
break;
case "upd":
include "connect.inc";
$login=$_POST['login']."@".$domain;
$maildir=$domain."/".$_POST['login']."/";
if (empty($_POST["changepass"]))
mysql_query("update users set comment='$_POST[fio]' where login='$_POST[id_login]'");
elseif ($_POST["changepass"]=="ok")
mysql_query("update users set password=encrypt('$_POST[pass]'),comment='$_POST[fio]' where login='$_POST[id_login]'");
if ($mail1=="send") sendmail();
mysql_close();
header("location: adduser.php");
break;
}

?>

содержимое editform.php

<?php
if (strtolower($_POST["action"])=="del")
{
include "connect.inc";
$result=mysql_query("select login from users");
while ($line = mysql_fetch_array($result))
{
$login=substr($line['login'],0,strpos($line['login'],"@"));
if ($_POST[$login]==$login)
{
mysql_query("delete from users where users.login=\"$line[login]\"");
}
}
mysql_close();
header("location: adduser.php");
}
elseif (strtolower($_POST["action"])=="ins" or (substr($_POST["action"],0,3))=="upd") {
include "connect.inc";
?>
<html>
<head>
<META http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1251\"></head>
<body>
<form action="edit.php" method="post">
<table border="0" width="50%" align="center">
<tr><td colspan="2"> </td></tr>
<?
if (strtolower(substr($_POST["action"],0,3))=="upd") {
?>
<input type="hidden" name="action" value="upd">
<?
$login=substr($_POST["action"],4)."@".$domain;
$result=mysql_query("select login,comment,maildir from users where users.login=\"$login\"");
$line = mysql_fetch_array($result);
$fio=$line["comment"];
$log=substr($line['login'],0,strpos($line['login'],"@"));
echo("<input type=\"hidden\" name=id_login value=\"$line[login]\">");
$MailDir=trim($line["maildir"]);
?>
<tr><td colspan="2" align="center" style="font-variant: small-caps;"><b>Редактировать данные пользователя</b></td></tr>
<?
}
elseif (strtolower($_POST["action"])=="ins") {
echo("<input type=\"hidden\" name=action value=\"ins\">");
$log="";
$fio="";
$MailDir=$domain."/";
echo("<tr><td colspan=\"2\" align=\"center\" style=\"font-variant: small-caps;\"><b>Добавить нового пользователя</b></td></tr>");
}
?>
<tr><td colspan="2" align="center"><b>domain @<?echo("$domain");?></b></td></tr>
<tr><td width="10%"><b>FIO</b></td>
<td width="40%"><input type = "text" style="width:100%" name = "fio" value= "<?echo("$fio");?>"></td></tr>
<tr><td width="10%"><b>Login</b></td>
<? if (strtolower($_POST["action"])=="ins")
echo("<td><input type = \"text\" style=\"width:50%\" name = \"login\" value= \"$log\" maxlength=\"255\"></td></tr>");
else
echo("<td><b>$log</b></td></tr>");
?>

<tr><td width="10%"><b>Password</b></td>
<td><input type = "password" style="width:50%" name = "pass" value= "" maxlength="255"></td></tr>
<tr><td width="10%"><b>MailDir</b></td>
<td><b><?echo("$MailDir");?></b></td></tr>
<tr><td width="10%"> </td>
<td><input type="checkbox" value="send" name="mail1" checked>Отправить письмо пользователю</td></tr>
<?
if (strtolower(substr($_POST["action"],0,3))=="upd")
{
?>
<tr><td width="10%"> </td>
<td><input type="checkbox" value="ok" name="changepass">Сменить пароль</td></tr>
<?
}
?>
<tr><td colspan=\"2\"> </td></tr>
</table>
<table border="0" width="50%" align="center">
<tr><td align="center" width="50%"><input type="submit" name="" value="Apply"></td>
<td align="center"><input type="button" value="Cancel" onClick="self.history.back();"></td></tr>
</table></form></body>
</html>
<?
mysql_close();
}
?>

Запускаем это все файлом adduser.php

P.S. Ногами не пинать, не хотел выкладывать, попросили. :)

5 комментариев:

Анонимный комментирует...

Давно уже существует postfixadmin.

Рамиль комментирует...

не возражаю, у меня попросили я выложил

Анонимный комментирует...
Этот комментарий был удален администратором блога.
Анонимный комментирует...

все бы хорошо, но нет никакой валидации в скрипте и он дырявый как решето

Рамиль комментирует...

Поправьте, спасибо скажем.