[feladat @ 182]
authorrejo
Tue, 25 Mar 2008 22:45:31 +0000
changeset 82 c255196bc447
parent 81 c72d6d51f3d3
child 83 90fbb34b3d97
[feladat @ 182] Merged r125:181 of branches/rewrite-user-management into trunk. This incorporates the [wiki:ProposalUserPermissionManagement a new user and permission management system] and closes ticket:22. Be aware, this database structure has changed, this version is incompatible with previous versions.
add_record.php
add_supermaster.php
add_user.php
add_zone_master.php
add_zone_slave.php
change_password.php
delete_domain.php
delete_record.php
delete_supermaster.php
delete_user.php
docs/CHANGELOG
docs/poweradmin-mysql-db-structure.sql
edit.php
edit_perm_templ.php
edit_record.php
edit_user.php
inc/auth.inc.php
inc/config-me.inc.php
inc/database.inc.php
inc/dns.inc.php
inc/error.inc.php
inc/header.inc.php
inc/record.inc.php
inc/toolkit.inc.php
inc/users.inc.php
index.php
install.php
list_perm_templ.php
list_supermasters.php
list_zones.php
search.php
style/example.inc.php
style/style.css.php
users.php
--- a/add_record.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/add_record.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,63 +20,111 @@
  */
 
 require_once("inc/toolkit.inc.php");
+include_once("inc/header.inc.php");
 
-$xsid = (isset($_GET['id'])) ? $_GET['id'] : $_POST['zoneid'];
-if ((!level(5)) && ((!xs($xsid) || ($_SESSION[$xsid.'_ispartial'])))) {
-	error(ERR_RECORD_ACCESS_DENIED);
+if (verify_permission(zone_content_view_others)) { $perm_view = "all" ; }
+elseif (verify_permission(zone_content_view_own)) { $perm_view = "own" ; }
+else { $perm_view = "none" ; }
+
+if (verify_permission(zone_content_edit_others)) { $perm_content_edit = "all" ; }
+elseif (verify_permission(zone_content_edit_own)) { $perm_content_edit = "own" ; }
+else { $perm_content_edit = "none" ; }
+
+if (verify_permission(zone_meta_edit_others)) { $perm_meta_edit = "all" ; }
+elseif (verify_permission(zone_meta_edit_own)) { $perm_meta_edit = "own" ; }
+else { $perm_meta_edit = "none" ; }
+
+$zone_id = "-1";
+if ((isset($_GET['id'])) && (v_num($_GET['id']))) {
+	$zone_id = $_GET['id'];
+}
+
+$ttl = $DEFAULT_TTL;
+if ((isset($_POST['ttl'])) && (v_num($_POST['ttl']))) {
+	$ttl = $_POST['ttl'];
 }
 
-if (isset($_POST["commit"]) && isset($_POST['zoneid']) && isset($_POST['name']) && isset($_POST['type']) && isset($_POST['content']) && isset($_POST['ttl']) && isset($_POST['prio']) ) {
-        $ret = add_record($_POST["zoneid"], $_POST["name"], $_POST["type"], $_POST["content"], $_POST["ttl"], $_POST["prio"]);
-        if ($ret != '1') {
-                die("$ret");
-        }
-        clean_page("edit.php?id=".$_POST["zoneid"]);
+$prio = "10";
+if ((isset($_GET['prio'])) && (v_num($_GET['prio']))) {
+	$prio = $_GET['prio'];
+}
+
+$name = $_POST['name'];
+$type = $_POST['type'];
+$content = $_POST['content'];
+
+if ($zone_id == "-1") {
+	error(ERR_INV_INPUT);
+	include_once("inc/footer.inc.php");
+	exit;
+}
+
+$user_is_zone_owner = verify_user_is_owner_zoneid($zone_id);
+$zone_type = get_domain_type($zone_id);
+$zone_name = get_domain_name_from_id($zone_id);
+
+if ($_POST["commit"]) {
+	if ( $zone_type == "SLAVE" || $perm_content_edit == "none" || $perm_content_edit == "own" && $user_is_zone_owner == "0" ) {
+		error(ERR_PERM_ADD_RECORD);
+	} else {
+		if ( add_record($zone_id, $name, $type, $content, $ttl, $prio)) {
+			success(_('The record was succesfully added.'));
+			unset($zone_id, $name, $type, $content, $ttl, $prio);
+		}
+	}
 }
 
-include_once("inc/header.inc.php");
-?>
-
-    <h2><?php echo _('Add record to zone'); ?> "<?php echo get_domain_name_from_id($_GET["id"]) ?>"</H2>
+echo "    <h2>" . _('Add record in zone') . " " .  $zone_name . "</h2>\n";
 
-    <form method="post">
-     <input type="hidden" name="zoneid" value="<?php echo $_GET["id"] ?>">
-     <table border="0" cellspacing="4">
-      <tr>
-       <td class="n"><?php echo _('Name'); ?></td>
-       <td class="n">&nbsp;</td>
-       <td class="n"><?php echo _('Type'); ?></td>
-       <td class="n"><?php echo _('Priority'); ?></td>
-       <td class="n"><?php echo _('Content'); ?></td>
-       <td class="n"><?php echo _('TTL'); ?></td>
-      </tr>
-      <tr>
-       <td class="n"><input type="text" name="name" class="input">.<?php echo get_domain_name_from_id($_GET["id"]) ?></td>
-       <td class="n">IN</td>
-       <td class="n">
-        <select name="type">
-<?php
-$dname = get_domain_name_from_id($_GET["id"]);
-foreach (get_record_types() as $c) {
-        if (eregi('in-addr.arpa', $dname) && strtoupper($c) == 'PTR') {
-                $add = " SELECTED";
-        } elseif (strtoupper($c) == 'A') {
-                $add = " SELECTED";
-        } else {
-                $add = '';
-        }
-        ?><option<?php echo $add ?> value="<?php echo $c ?>"><?php echo $c ?></option><?php
+if ( $zone_type == "SLAVE" || $perm_content_edit == "none" || $perm_content_edit == "own" && $user_is_zone_owner == "0" ) {
+	error(ERR_PERM_ADD_RECORD); 
+} else {
+	echo "     <form method=\"post\">\n";
+	echo "      <input type=\"hidden\" name=\"domain\" value=\"" . $zone_id . "\">\n";
+	echo "      <table border=\"0\" cellspacing=\"4\">\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Name') . "</td>\n";
+	echo "        <td class=\"n\">&nbsp;</td>\n";
+	echo "        <td class=\"n\">" . _('Type') . "</td>\n";
+	echo "        <td class=\"n\">" . _('Priority') .  "</td>\n";
+	echo "        <td class=\"n\">" . _('Content') . "</td>\n";
+	echo "        <td class=\"n\">" . _('TTL') . "</td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\"><input type=\"text\" name=\"name\" class=\"input\" value=\"" . $name . "\">." . $zone_name . "</td>\n";
+	echo "        <td class=\"n\">IN</td>\n";
+	echo "        <td class=\"n\">\n";
+	echo "         <select name=\"type\">\n";
+	foreach (get_record_types() as $record_type) {
+		if ($type) {
+			if ($type == $record_type) {
+				$add = " SELECTED";
+			} else {
+				unset ($add);
+			}
+		} else {
+			if (eregi('in-addr.arpa', $zone_name) && strtoupper($record_type) == 'PTR') {
+				$add = " SELECTED";
+			} elseif (strtoupper($record_type) == 'A') {
+				$add = " SELECTED";
+			} else {
+				unset($add);
+			}
+		}
+		echo "          <option" . $add . " value=\"" . $record_type . "\">" . $record_type . "</option>\n";
+	}
+	echo "         </select>\n";
+	echo "        </td>\n";
+	echo "        <td class=\"n\"><input type=\"text\" name=\"prio\" class=\"sinput\" value=\"" . $prio . "\"></td>\n";
+	echo "        <td class=\"n\"><input type=\"text\" name=\"content\" class=\"input\" value=\"" . $content . "\"></td>\n";
+	echo "        <td class=\"n\"><input type=\"text\" name=\"ttl\" class=\"sinput\" value=\"" . $ttl . "\"</td>\n";
+	echo "       </tr>\n";
+	echo "      </table>\n";
+	echo "      <br>\n";
+	echo "      <input type=\"submit\" name=\"commit\" value=\"" .  _('Add record') . "\" class=\"button\">\n";
+	echo "     </form>\n";
 }
+
+include_once("inc/footer.inc.php"); 
+
 ?>
-        </select>
-       </td>
-       <td class="n"><input type="text" name="prio" class="sinput"></td>
-       <td class="n"><input type="text" name="content" class="input"></td>
-       <td class="n"><input type="text" name="ttl" class="sinput" value="<?php echo $DEFAULT_TTL?>"></td>
-      </tr>
-     </table>
-     <br>
-     <input type="submit" name="commit" value="<?php echo _('Add record'); ?>" class="button">
-    </form>
-
-<?php include_once("inc/footer.inc.php"); ?>
--- a/add_supermaster.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/add_supermaster.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,82 +20,68 @@
  */
 
 require_once("inc/toolkit.inc.php");
+include_once("inc/header.inc.php");
 
-if (!level(5))
-{
-	 error(ERR_LEVEL_5);
-}
+$master_ip = $_POST["master_ip"];
+$ns_name = $_POST["ns_name"];
+$account = $_POST["account"];
 
-if(isset($_POST["submit"]))
+(verify_permission(supermaster_add)) ? $supermasters_add = "1" :  $supermasters_add = "0";
+
+if($_POST["submit"])
 {
-	$master_ip = (isset($_POST['master_ip']) ? $_POST["master_ip"] : '');
-	$ns_name = (isset($_POST['ns_name']) ? $_POST["ns_name"] : '');
-	$account = (isset($_POST["account"]) ? $_POST['account'] : '');
-	if (!isset($error))
-	{
-		if (!is_valid_ip($master_ip) && !is_valid_ip6($master_ip))
-		{
-			$error = _('Given master IP address is not valid IPv4 or IPv6.');
-		}
-		elseif (!is_valid_hostname($ns_name))
-		{
-			$error = _('Given hostname for NS record not valid.');
-		}
-		elseif (!validate_account($account))
-		{
-			$error = _('Account name is not valid (may contain only alpha chars).');
-		}
-		else    
-		{
-			if(add_supermaster($master_ip, $ns_name, $account))
-			{
-				$success = _('Successfully added supermaster.');
-			}
-		}
+	if (add_supermaster($master_ip, $ns_name, $account)) {
+		echo "     <div class=\"success\">" .  _('Successfully added supermaster.') . "</div>\n";
+	} else {
+		$error = "1";
 	}
 }
 
-include_once("inc/header.inc.php");
-    
-    if ((isset($error)) && ($error != ""))
-    {
-    	?><div class="error"><?php echo _('Error'); ?>: <?php echo $error; ?></div><?php
-    }
-    elseif ((isset($success)) && ($success != ""))
-    {
-    	?><div class="success"><?php echo $success; ?></div><?php
-    }
-    
-    ?>
-    <h2><?php echo _('Add supermaster'); ?></h2>
-    <form method="post" action="add_supermaster.php">
-     <table>
-      <tr>
-       <td class="n"><?php echo _('IP address of supermaster'); ?>:</td>
-       <td class="n">
-        <input type="text" class="input" name="master_ip" value="<?php if (isset($error)) print $_POST["master_ip"]; ?>">
-       </td>
-      </tr>
-      <tr>
-       <td class="n"><?php echo _('Hostname in NS record'); ?>:</td>
-       <td class="n">
-        <input type="text" class="input" name="ns_name" value="<?php if (isset($error)) print $_POST["ns_name"]; ?>">
-       </td>
-      </tr>
-      <tr>
-       <td class="n"><?php echo _('Account'); ?>:</td>
-       <td class="n">
-        <input type="text" class="input" name="account" value="<?php if (isset($error)) print $_POST["account"]; ?>">
-       </td>
-      </tr>
-      <tr>
-       <td class="n">&nbsp;</td>
-       <td class="n">
-        <input type="submit" class="button" name="submit" value="<?php echo _('Add supermaster'); ?>">
-       </td>
-      </tr>
-     </table>
-    </form>
-<?php
+echo "     <h2>" . _('Add supermaster') . "</h2>\n";
+
+if ( $supermasters_add != "1" ) {
+	echo "     <p>" . _("You do not have the permission to add a new supermaster.") . "</p>\n"; 
+} else {
+	echo "     <form method=\"post\" action=\"add_supermaster.php\">\n";
+	echo "      <table>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('IP address of supermaster') . "</td>\n";
+	echo "        <td class=\"n\">\n";
+	if ($error) {
+		echo "         <input type=\"text\" class=\"input\" name=\"master_ip\" value=\"" . $master_ip . "\">\n";
+	} else {
+		echo "         <input type=\"text\" class=\"input\" name=\"master_ip\" value=\"\">\n";
+	}
+	echo "        </td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Hostname in NS record') . "</td>\n";
+	echo "        <td class=\"n\">\n";
+	if ($error) {
+		echo "         <input type=\"text\" class=\"input\" name=\"ns_name\" value=\"" . $ns_name . "\">\n";
+	} else {
+		echo "         <input type=\"text\" class=\"input\" name=\"ns_name\" value=\"\">\n";
+	}
+	echo "        </td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Account') . "</td>\n";
+	echo "        <td class=\"n\">\n";
+	if ($error) {
+		echo "         <input type=\"text\" class=\"input\" name=\"account\" value=\"" . $account . "\">\n";
+	} else {
+		echo "         <input type=\"text\" class=\"input\" name=\"account\" value=\"\">\n";
+	}
+	echo "        </td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">&nbsp;</td>\n";
+	echo "        <td class=\"n\">\n";
+	echo "         <input type=\"submit\" class=\"button\" name=\"submit\" value=\"" . _('Add supermaster') . "\">\n";
+	echo "        </td>\n";
+	echo "       </tr>\n";
+	echo "      </table>\n";
+	echo "     </form>\n";
+}
 include_once("inc/footer.inc.php");
 ?>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/add_user.php	Tue Mar 25 22:45:31 2008 +0000
@@ -0,0 +1,79 @@
+<?php
+
+/*  PowerAdmin, a friendly web-based admin tool for PowerDNS.
+ *  See <https://rejo.zenger.nl/poweradmin> for more details.
+ *
+ *  Copyright 2007, 2008  Rejo Zenger <rejo@zenger.nl>
+ *
+ *  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 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+require_once("inc/toolkit.inc.php");
+include_once("inc/header.inc.php");
+
+if (!verify_permission(user_add_new)) {
+	error(ERR_PERM_ADD_USER);
+} else {
+	if($_POST["commit"]) {
+		add_new_user($_POST);
+		success(SUC_USER_ADD);
+	}
+
+	echo "     <h2>" . _('Add a  user') . "</h2>\n";
+	echo "     <form method=\"post\">\n";
+	echo "      <table>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Username') . "</td>\n"; 
+	echo "        <td class=\"n\"><input type=\"text\" class=\"input\" name=\"username\" value=\"\"></td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Fullname') . "</td>\n"; 
+	echo "        <td class=\"n\"><input type=\"text\" class=\"input\" name=\"fullname\" value=\"\"></td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Password') . "</td>\n";
+	echo "        <td class=\"n\"><input type=\"text\" class=\"input\" name=\"password\"></td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Email') . "</td>\n"; 
+	echo "        <td class=\"n\"><input type=\"text\" class=\"input\" name=\"email\" value=\"\"></td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Permission template') . "</td>\n"; 
+	echo "        <td class=\"n\">\n";
+	echo "         <select name=\"perm_templ\">\n";
+	foreach (list_permission_templates() as $template) {
+		echo "          <option value=\"" . $template['id'] . "\">" . $template['name'] . "</option>\n";
+	}
+	echo "         </select>\n";
+	echo "       </td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Description') . "</td>\n"; 
+	echo "        <td class=\"n\"><textarea rows=\"4\" cols=\"30\" class=\"inputarea\" name=\"descr\"></textarea></td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Enabled') . "</td>\n"; 
+	echo "        <td class=\"n\"><input type=\"checkbox\" class=\"input\" name=\"active\" value=\"1\"></td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">&nbsp;</td>\n"; 
+	echo "        <td class=\"n\"><input type=\"submit\" class=\"button\" name=\"commit\" value=\"" . _('Commit changes') . "\"></td>\n"; 
+	echo "      </table>\n";
+	echo "     </form>\n";
+}
+
+include_once("inc/footer.inc.php");
+
+?>
--- a/add_zone_master.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/add_zone_master.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,126 +20,119 @@
  */
 
 require_once("inc/toolkit.inc.php");
+include_once("inc/header.inc.php");
 
-if (!level(5))
-{
-        error(ERR_LEVEL_5);
+$owner = "-1";
+if ((isset($_POST['owner'])) && (v_num($_POST['owner']))) {
+        $owner = $_POST['owner'];
+}
 
+$dom_type = "NATIVE";
+if (isset($_POST["dom_type"]) && (in_array($_POST['dom_type'], $server_types))) {
+	$dom_type = $_POST["dom_type"];
 }
 
-if (isset($_POST["submit"]))
-{
-        $domain = (isset($_POST['domain']) ? trim($_POST["domain"]) : '');
-        $owner = (isset($_POST['owner']) ? $_POST["owner"] : 0 );
-        $webip = (isset($_POST["webip"]) ? $_POST['webip'] : '');
-        $mailip = (isset($_POST["mailip"]) ? $_POST['mailip'] : '');
-        $empty = (isset($_POST["empty"]) ? $_POST['empty'] : 0);
-        $dom_type = (isset($_POST["dom_type"]) ? $_POST["dom_type"] : "NATIVE");
-        if(!$empty)
-        {
+$domain = trim($_POST["domain"]);
+$webip = $_POST["webip"];
+$mailip = $_POST["mailip"];
+$empty = $_POST["empty"];
+
+(verify_permission(zone_master_add)) ? $zone_master_add = "1" : $zone_master_add = "0" ;
+
+if ($_POST['submit'] && $zone_master_add == "1" ) {
+
+	// Boy. I will be happy when I have found the time to replace
+	// this "template wanabee" code with something that is really 
+	// worth to be called "templating". Whoever wrote this should 
+	// be... should be... how can I say this politicaly correct?
+	// 20080303/RZ
+
+        if(!$empty) {
                 $empty = 0;
-                if(!eregi('in-addr.arpa', $domain) && (!is_valid_ip($webip) || !is_valid_ip($mailip)) )
-                {
-                        $error = "Web or Mail ip is invalid!";
+                if(!eregi('in-addr.arpa', $domain) && (!is_valid_ip($webip) || !is_valid_ip($mailip)) ) {
+                        error(_('Web or mail ip is invalid!')); 
+			$error = "1";
                 }
         }
-        if (!isset($error))
-        {
-                if (!is_valid_domain($domain))
-                {
-                        $error = "Zone name is invalid!";
-                }
-                elseif (domain_exists($domain))
-                {
-                        $error = "Zone already exists!";
-                }
-                //elseif (isset($mailip) && is_valid_ip(
-                else
-                {
-                        add_domain($domain, $owner, $webip, $mailip, $empty, $dom_type, '');
-			$success = _('Successfully added master zone.');
+
+        if (!$error) {
+                if (!is_valid_domain($domain)) {
+                        error(_('Zone name is invalid!')); 
+			$error = "1";
+                } elseif (domain_exists($domain)) {
+                        error(_('Zone already exists!!')); 
+			$error = "1";
+                } else {
+                        if (add_domain($domain, $owner, $webip, $mailip, $empty, $dom_type, '')) {
+				success(SUC_ZONE_ADD);
+				unset($domain, $owner, $webip, $mailip, $empty, $dom_type);
+			} else {
+				$error = "1";
+			}
                 }
         }
 }
 
-include_once("inc/header.inc.php");
+echo "     <h2>" . _('Add master zone') . "</h2>\n"; 
 
-	if ((isset($error)) && ($error != ""))
-	{
-	        ?><div class="error"><?php echo _('Error'); ?>: <?php echo $error; ?></div><?php
-	}
-	elseif ((isset($success)) && ($success != ""))
-	{
-		?><div class="success"><?php echo $success; ?></div><?php
-	}
-
-	?>
-	<h2>Add master zone</h2>
-	<?php
+if ( $zone_master_add != "1" ) {
+	echo "     <p>" . _("You do not have the permission to add a new master zone.") . "</p>\n"; 
+} else {
+	$available_zone_types = array("MASTER", "NATIVE");
+	$users = show_users();
 
-	// Zone type set to master and native only, slave zones are created
-	// on a different page. 
-        $zone_types = array("MASTER", "NATIVE");
-        $users = show_users();
-        ?>
-        <form method="post" action="add_zone_master.php">
-         <table>
-          <tr>
-           <td class="n"><?php echo _('Zone name'); ?>:</td>
-           <td class="n">
-            <input type="text" class="input" name="domain" value="<?php if (isset($error)) print $_POST["domain"]; ?>">
-           </td>
-          </tr>
-          <tr>
-           <td class="n"><?php echo _('Web IP'); ?>:</td>
-           <td class="n">
-            <input type="text" class="input" name="webip" value="<?php if (isset($error)) print $_POST["webip"]; ?>">
-           </td>
-          </tr>
-          <tr>
-           <td class="n"><?php echo _('Mail IP'); ?>:</TD>
-           <td class="n">
-            <input type="text" class="input" name="mailip" value="<?php if (isset($error)) print $_POST["mailip"]; ?>">
-           </td>
-          </tr>
-          <tr>
-           <td class="n"><?php echo _('Owner'); ?>:</td>
-           <td class="n">
-            <select name="owner">
-        <?php
-        foreach ($users as $u)
-        {
-           ?><option value="<?php echo $u['id'] ?>"><?php echo $u['fullname'] ?></option><?php
+	echo "     <form method=\"post\" action=\"add_zone_master.php\">\n";
+	echo "      <table>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Zone name') . ":</td>\n";
+	echo "        <td class=\"n\">\n";
+	echo "         <input type=\"text\" class=\"input\" name=\"domain\" value=\"" .  $domain . "\">\n";
+	echo "        </td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Web IP') . ":</td>\n";
+	echo "        <td class=\"n\">\n";
+	echo "         <input type=\"text\" class=\"input\" name=\"webip\" value=\"" . $webip . "\">\n";
+	echo "        </td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Mail IP') . ":</td>\n";
+	echo "        <td class=\"n\">\n";
+	echo "         <input type=\"text\" class=\"input\" name=\"mailip\" value=\"" . $mailip . "\">\n";
+	echo "        </td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Owner') . ":</td>\n";
+	echo "        <td class=\"n\">\n";
+	echo "         <select name=\"owner\">\n";
+        foreach ($users as $user) {
+		echo "          <option value=\"" . $user['id'] . "\">" . $user['fullname'] . "</option>\n";
         }
-        ?>
-            </select>
-           </td>
-          </tr>
-          <tr>
-           <td class="n"><?php echo _('Zone type'); ?>:</td>
-           <td class="n">
-            <select name="dom_type">
-        <?php
-        foreach($zone_types as $s)
-        {
-           ?><option value="<?php echo $s?>"><?php echo $s ?></option><?php
+	echo "         </select>\n";
+	echo "        </td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Zone type') . ":</td>\n";
+	echo "        <td class=\"n\">\n";
+	echo "         <select name=\"dom_type\">\n";
+        foreach($available_zone_types as $type) {
+		echo "          <option value=\"" . $type . "\">" . strtolower($type) . "</option>\n";
         }
-        ?>
-            </select>
-           </td>
-          </tr>
-          <tr>
-           <td class="n"><?php echo _('Create zone without applying records-template'); ?>:</td>
-	   <td class="n"><input type="checkbox" name="empty" value="1"></td>
-	  </tr>
-          <tr>
-	   <td class="n">&nbsp;</td>
-	   <td class="n">
-	    <input type="submit" class="button" name="submit" value="<?php echo _('Add zone'); ?>">
-	   </td>
-	  </tr>
-         </table>
-        </form>
-<?php
+	echo "         </select>\n";
+	echo "        </td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Create zone without applying records-template') . "</td>\n";
+	echo "        <td class=\"n\"><input type=\"checkbox\" name=\"empty\" value=\"1\"></td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">&nbsp;</td>\n";
+	echo "        <td class=\"n\">\n";
+	echo "         <input type=\"submit\" class=\"button\" name=\"submit\" value=\"" . _('Add zone') . "\">\n";
+	echo "        </td>\n";
+	echo "       </tr>\n";
+	echo "      </table>\n";
+	echo "     </form>\n";
+} 
 
 include_once("inc/footer.inc.php");
--- a/add_zone_slave.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/add_zone_slave.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,93 +20,73 @@
  */
 
 require_once("inc/toolkit.inc.php");
-
-if (!level(5))
-{
-        error(ERR_LEVEL_5);
-
-}
-
-if (isset($_POST["submit"]))
-{
-     $domain = trim($_POST["domain"]);
-     $owner = $_POST["owner"];
-     $slave_master = $_POST["slave_master"];
-     $dom_type = "SLAVE";
-     if (!isset($error))
-     {
-             if (!is_valid_domain($domain))
-             {
-                     $error = "Zone name is invalid!";
-             }
-             elseif (domain_exists($domain))
-             {
-                     $error = "Zone already exists!";
-             }
-             elseif (!is_valid_ip($slave_master))
-             {
-                     $error = "IP of master NS for slave zone is not valid!";
-             }
-             else
-             {
-                     if(add_domain($domain, $owner, '', '', 1, $dom_type, $slave_master))
-		     {
-                                $success = _('Successfully added slave zone.');
-		     }
-             }
-     }
-}
-
 include_once("inc/header.inc.php");
 
-	if ((isset($error)) && ($error != ""))
-	{
-	        ?><div class="error"><?php echo _('Error'); ?>: <?php echo $error; ?></div><?php
+$owner = "-1";
+if ((isset($_POST['owner'])) && (v_num($_POST['owner']))) {
+        $owner = $_POST['owner'];
+}
+
+$zone = trim($_POST['domain']);
+$master = $_POST['slave_master'];
+$type = "SLAVE";
+
+(verify_permission(zone_slave_add)) ? $zone_slave_add = "1" : $zone_slave_add = "0" ;
+
+if ($_POST['submit'] && $zone_slave_add == "1") {
+	if (!is_valid_domain($zone)) {
+		error(ERR_DNS_HOSTNAME);
+	} elseif (domain_exists($zone)) {
+		error(ERR_DOMAIN_EXISTS);
+	} elseif (!is_valid_ip($master)) {
+		error(ERR_DNS_IP);
+	} else {
+		if(add_domain($zone, $owner, $webip, $mailip, $empty, $type, $master)) {
+			success(SUC_ZONE_ADD);
+			unset($zone, $owner, $webip, $mailip, $empty, $type, $master);
+		}
 	}
-	elseif ((isset($success)) && ($success != ""))
-	{
-		?><div class="success"><?php echo $success; ?></div><?php
-	}
-	
+}
+
+echo "     <h2>" . _('Add slave zone') . "</h2>\n"; 
+
+if ( $zone_slave_add != "1" ) {
+	echo "     <p>" . _("You do not have the permission to add a new slave zone.") . "</p>\n"; 
+} else {
 	$users = show_users();
-	
-	?>
-	    <h2><?php echo _('Add slave zone'); ?></h2>
-	    <form method="post" action="add_zone_slave.php">
-	     <table>
-	      <tr>
-	       <td class="n"><?php echo _('Zone name'); ?>:</td>
-	       <td class="n">
-	        <input type="text" class="input" name="domain" value="<?php if (isset($error)) print $_POST["domain"]; ?>">
-	       </td>
-	      </tr>
-	      <tr>
-	       <td class="n"><?php echo _('IP of master NS'); ?>:</td>
-	       <td class="n">
-	        <input type="text" class="input" name="slave_master" value="<?php if (isset($error)) print $_POST["slave_master"]; ?>">
-	       </td>
-	      </tr>
-	      <tr>
-	       <td class="n"><?php echo _('Owner'); ?>:</td>
-	       <td class="n">
-	        <select name="owner">
-	         <?php 
-	         foreach ($users as $u)
-	         {
-	           ?><option value="<?php echo $u['id'] ?>"><?php echo $u['fullname'] ?></option><?php
-	         } 
-	        ?>
-	        </select>
-	       </td>
-	      </tr>
-	      <tr>
-	       <td class="n">&nbsp;</td>
-	       <td class="n">
-	        <input type="submit" class="button" name="submit" value="<?php echo _('Add domain'); ?>">
-	       </td>
-	      </tr>
-	     </table>
-	    </form>
-<?php
+	echo "     <form method=\"post\" action=\"add_zone_slave.php\">\n";
+	echo "      <table>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Zone name') . "</td>\n";
+	echo "        <td class=\"n\">\n";
+	echo "         <input type=\"text\" class=\"input\" name=\"domain\" value=\"" . $zone . "\">\n";
+	echo "        </td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('IP of master NS') . ":</td>\n";
+	echo "        <td class=\"n\">\n";
+	echo "         <input type=\"text\" class=\"input\" name=\"slave_master\" value=\"" . $master . "\">\n";
+	echo "        </td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Owner') . ":</td>\n";
+	echo "        <td class=\"n\">\n";
+	echo "         <select name=\"owner\">\n";
+	foreach ($users as $user) {
+		echo "          <option value=\"" . $user['id'] . "\">" . $user['fullname'] . "</option>\n";
+	}
+	echo "         </select>\n";
+	echo "        </td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">&nbsp;</td>\n";
+	echo "        <td class=\"n\">\n";
+	echo "         <input type=\"submit\" class=\"button\" name=\"submit\" value=\"" .  _('Add domain') . "\">\n";
+	echo "        </td>\n";
+	echo "       </tr>\n";
+	echo "      </table>\n";
+	echo "     </form>\n";
+}
+
 include_once("inc/footer.inc.php");
 ?>
--- a/change_password.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/change_password.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,45 +20,35 @@
  */
 
 require_once("inc/toolkit.inc.php");
+include_once("inc/header.inc.php");
 
-if(isset($_POST["submit"]))
-{
-	if((!isset($_POST['newpass'])) || (strlen($_POST["newpass"]) < 8))
-	{
-		error('Password length should be at least 8 characters.');
-	}
-	else
-	{
-		change_user_pass($_POST["currentpass"], $_POST["newpass"], $_POST["newpass2"]);
-	}
+if($_POST["submit"]) {
+	change_user_pass($_POST);
 }
 
-include_once("inc/header.inc.php");
-?>
-    <h2><?php echo _('Change password'); ?></h2>
-    <form method="post" action="change_password.php">
-     <table border="0" CELLSPACING="4">
-      <tr>
-       <td class="n"><?php echo _('Current password'); ?>:</td>
-       <td class="n"><input type="password" class="input" NAME="currentpass" value=""></td>
-      </tr>
-      <tr>
-       <td class="n"><?php echo _('New password'); ?>:</td>
-       <td class="n"><input type="password" class="input" NAME="newpass" value=""></td>
-      </tr>
-      <tr>
-       <td class="n"><?php echo _('New password'); ?>:</td>
-       <td class="n"><input type="password" class="input" NAME="newpass2" value=""></td>
-      </tr>
-      <tr>
-       <td class="n">&nbsp;</td>
-       <td class="n">
-        <input type="submit" class="button" NAME="submit" value="<?php echo _('Change password'); ?>">
-       </td>
-      </tr>
-     </table>
-    </form>
+echo "    <h2>" . _('Change password') . "</h2>\n";
+echo "    <form method=\"post\" action=\"change_password.php\">\n";
+echo "     <table border=\"0\" CELLSPACING=\"4\">\n";
+echo "      <tr>\n";
+echo "       <td class=\"n\">" . _('Current password') . ":</td>\n";
+echo "       <td class=\"n\"><input type=\"password\" class=\"input\" NAME=\"currentpass\" value=\"\"></td>\n";
+echo "      </tr>\n";
+echo "      <tr>\n";
+echo "       <td class=\"n\">" . _('New password') . ":</td>\n";
+echo "       <td class=\"n\"><input type=\"password\" class=\"input\" NAME=\"newpass\" value=\"\"></td>\n";
+echo "      </tr>\n";
+echo "      <tr>\n";
+echo "       <td class=\"n\">" . _('New password') . ":</td>\n";
+echo "       <td class=\"n\"><input type=\"password\" class=\"input\" NAME=\"newpass2\" value=\"\"></td>\n";
+echo "      </tr>\n";
+echo "      <tr>\n";
+echo "       <td class=\"n\">&nbsp;</td>\n";
+echo "       <td class=\"n\">\n";
+echo "        <input type=\"submit\" class=\"button\" NAME=\"submit\" value=\"" . _('Change password') . "\">\n";
+echo "       </td>\n";
+echo "      </tr>\n";
+echo "     </table>\n";
+echo "    </form>\n";
 
-<?php
 include_once("inc/footer.inc.php");
 ?>
--- a/delete_domain.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/delete_domain.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,50 +20,59 @@
  */
 
 require_once("inc/toolkit.inc.php");
+include_once("inc/header.inc.php");
 
-if (!level(5))
-{
-        error(ERR_LEVEL_5);
-        
+if (verify_permission(zone_content_edit_others)) { $perm_edit = "all" ; }
+elseif (verify_permission(zone_content_edit_own)) { $perm_edit = "own" ;}
+else { $perm_edit = "none" ; }
+
+$zone_id = "-1";
+if (isset($_GET['id']) && v_num($_GET['id'])) {
+	$zone_id = $_GET['id'];
+}
+
+$confirm = "-1";
+if (isset($_GET['confirm']) && v_num($_GET['confirm'])) {
+	$confirm = $_GET['confirm'];
+}
+
+$zone_info = get_zone_info_from_id($zone_id);
+$zone_owners = get_fullnames_owners_from_domainid($zone_id);
+$user_is_zone_owner = verify_user_is_owner_zoneid($zone_id);
+
+if ($zone_id == "-1"){
+	error(ERR_INV_INPUT);
+	include_once("inc/footer.inc.php");
+	exit;
 }
 
-if (isset($_GET["id"])) {
-        if ((isset($_GET["confirm"])) && ($_GET['confirm'] == '0')) {
-                clean_page("index.php");
-        } elseif ((isset($_GET["confirm"])) && ($_GET['confirm'] == '1')) {
-                delete_domain($_GET["id"]);
-                clean_page("index.php");
-        }
-        include_once("inc/header.inc.php");
-        $info = get_domain_info_from_id($_GET["id"]);
-        ?><h2><?php echo _('Delete zone'); ?> "<?php echo $info["name"] ?>"</h2>
-        <?php
-	if($info["owner"])
-	{
-		print (_('Owner') . ": " . $info["owner"] . "<br>"); 
+echo "     <h2>" . _('Delete zone') . " \"" . $zone_info['name']. "\"</h2>\n";
+
+if ($confirm == '1') {
+	if ( delete_domain($zone_id) ) {
+		success(SUC_ZONE_DEL);
 	}
-	print (_('Type') . ": " . strtolower($info["type"]) . "<br>");
-	print (_('Number of records in zone') . ": " . $info["numrec"] . "<br>");
-	if($info["type"] == "SLAVE")
-	{
-		$slave_master = get_domain_slave_master($_GET["id"]);
-		if(supermaster_exists($slave_master))
-		{
-			print ("<font class=\"warning\">");
-			printf(_('You are about to delete a slave zone of which the master nameserver, %s, is a supermaster. Deleting the zone now, will result in temporary removal only. Whenever the supermaster sends a notification for this zone, it will be added again!'), $slave_master);
-			print ("</font><br>");
+} else {
+	if ( $perm_edit == "all" || ( $perm_edit == "own" && $user_is_zone_owner == "1") ) {	
+		echo "      " . _('Owner') . ": " . $zone_owners . "<br>\n";
+		echo "      " . _('Type') . ": " . $zone_info['type'] . "\n";
+		if ( $zone_info['type'] == "SLAVE" ) {
+			$slave_master = get_domain_slave_master($zone_id);
+			if(supermaster_exists($slave_master)) {
+				echo "        <p>         \n";
+				printf (_('You are about to delete a slave zone of which the master nameserver, %s, is a supermaster. Deleting the zone now, will result in temporary removal only. Whenever the supermaster sends a notification for this zone, it will be added again!'), $slave_master);
+				echo "        </p>\n";
+			}
 		}
+		echo "     <p>" . _('Are you sure?') . "</p>\n";
+		echo "     <br><br>\n";
+		echo "     <input type=\"button\" class=\"button\" OnClick=\"location.href='" . $_SERVER["REQUEST_URI"] . "&confirm=1'\" value=\"" . _('Yes') . "\">\n";
+		echo "     <input type=\"button\" class=\"button\" OnClick=\"location.href='index.php'\" value=\"" . _('No') . "\">\n";
+	} else {
+		error(ERR_PERM_DEL_ZONE);
 	}
-	?>
-	<font class="warning"><?php echo _('Are you sure?'); ?></font>
-	<br><br>
-	<input type="button" class="button" OnClick="location.href='<?php echo $_SERVER["REQUEST_URI"] ?>&confirm=1'" value="<?php echo _('Yes'); ?>">
-	<input type="button" class="button" OnClick="location.href='<?php echo $_SERVER["REQUEST_URI"] ?>&confirm=0'" value="<?php echo _('No'); ?>">
-	<?php
-} elseif ($_GET["edit"]) {
-        include_once("inc/header.inc.php");
-} else {
-        include_once("inc/header.inc.php");
-        echo _('Nothing to do!');
 }
+
 include_once("inc/footer.inc.php");
+
+?>
--- a/delete_record.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/delete_record.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,42 +20,66 @@
  */
 
 require_once("inc/toolkit.inc.php");
+include_once("inc/header.inc.php");
 
-if ($_GET["id"]) {
-	// check if we have access to the given id
-	$zoneId = recid_to_domid($_GET['id']);
-	if ((!level(5)) && (!xs($zoneId))) {
-    		error(ERR_RECORD_ACCESS_DENIED);
-	}
-	if ((!level(5)) && ($_SESSION[$zoneId.'_ispartial'] == 1)) {
-		$db->setLimit(1);
-		$checkPartial = $db->queryOne("SELECT id FROM record_owners WHERE record_id=".$db->quote($_GET["id"])." AND user_id=".$db->quote($_SESSION["userid"]));
-		if (empty($checkPartial)) {
-			error(ERR_RECORD_ACCESS_DENIED);
+$record_id = "-1";
+if (isset($_GET['id']) && v_num($_GET['id'])) {
+	$record_id = $_GET['id'];
+}
+
+
+$confirm = "-1";
+if ((isset($_GET['confirm']) && v_num($_GET['confirm'])
+        $confirm = $_GET['confirm'];
+}
+
+if (verify_permission(zone_content_edit_others)) { $perm_content_edit = "all" ; }
+elseif (verify_permission(zone_content_edit_own)) { $perm_content_edit = "own" ; }
+else { $perm_content_edit = "none" ; }
+
+$user_is_zone_owner = verify_user_is_owner_zoneid($_GET["domain"]);
+
+if ($record_id == "-1" ) {
+	if ($confirm == '1') {
+		if ( delete_record($record_id) ) {
+			success(SUC_RECORD_DEL);
 		}
-	}
-        if ($_GET["confirm"] == '0') {
-                clean_page("edit.php?id=".$_GET["domain"]);
-        } elseif ($_GET["confirm"] == '1') {
-                delete_record($_GET["id"]);
-                clean_page("edit.php?id=".$_GET["domain"]);
-        }
-        include_once("inc/header.inc.php");
-        ?>
+	} else {
+		$zone_id = recid_to_domid($record_id);
+		$zone_name = get_domain_name_from_id($zone_id);
+		$user_is_zone_owner = verify_user_is_owner_zoneid($zone_id);
+		$record_info = get_record_from_id($record_id);
 	
-	<h2><?php echo _('Delete record'); ?> "<?php
-        $data = get_record_from_id($_GET["id"]);
-        print $data["name"]." IN ".$data["type"]." ".$data["content"];
-        ?>"</h2><?php
-        if (($data["type"] == "NS" && $data["name"] == get_domain_name_from_id($_GET["domain"])) || $data["type"] == "SOA") {
-                print "<font class=\"warning\">" . _('You are trying to delete a record that is needed for this zone to work.') . "</font><br>";
+		echo "     <h2>" . _('Delete record') . " in zone \"" . $zone_name . "\"</h2>\n";
+
+		if ( $zone_type == "SLAVE" || $perm_content_edit == "none" || $perm_content_edit == "own" && $user_is_zone_owner == "0" ) {
+			error(ERR_PERM_EDIT_RECORD);
+		} else {
+			echo "     <table>\n";
+			echo "      <tr>\n";
+			echo "       <th>Name</th>\n";
+			echo "       <th>Type</th>\n";
+			echo "       <th>Content</th>\n";
+			echo "       <th>Priority</th>\n";
+			echo "       <th>TTL</th>\n";
+			echo "      </tr>\n";
+			echo "      <tr>\n";
+			echo "       <td>" . $record_info['name'] . "</td>\n";
+			echo "       <td>" . $record_info['type'] . "</td>\n";
+			echo "       <td>" . $record_info['content'] . "</td>\n";
+			echo "       <td>" . $record_info['priority'] . "</td>\n";
+			echo "       <td>" . $record_info['ttl'] . "</td>\n";
+			echo "      </tr>\n";
+			echo "     </table>\n";
+			if (($record_info['type'] == 'NS' && $record_info['name'] == $zone_name) || $record_info['type'] == 'SOA') {
+				echo "     <p>" . _('You are trying to delete a record that is needed for this zone to work.') . "</p>\n";
+			}
+			echo "     <p>" . _('Are you sure?') . "</p>\n";
+			echo "     <input type=\"button\" class=\"button\" OnClick=\"location.href='" . $_SERVER["REQUEST_URI"] . "&confirm=1'\" value=\"" . _('Yes') . "\">\n";
+			echo "     <input type=\"button\" class=\"button\" OnClick=\"location.href='index.php'\" value=\"" . _('No') . "\">\n";
+		}
         }
-        ?><br><font class="warning"><?php echo _('Are you sure?'); ?></font><br><br>
-        <input type="button" class="button" OnClick="location.href='<?php echo $_SERVER["REQUEST_URI"] ?>&confirm=1'" value="<?php echo _('Yes'); ?>"> 
-	<input type="button" class="button" OnClick="location.href='<?php echo $_SERVER["REQUEST_URI"] ?>&confirm=0'" value="<?php echo _('No'); ?>">
-        <?php
 } else {
-        include_once("inc/header.inc.php");
-        echo _('Nothing to do!');
+	error(ERR_INV_INPUT);
 }
 include_once("inc/footer.inc.php");
--- a/delete_supermaster.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/delete_supermaster.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,32 +20,43 @@
  */
 
 require_once("inc/toolkit.inc.php");
+include_once("inc/header.inc.php");
 
-if (!level(5))
-{
-        error(ERR_LEVEL_5);
-        
+$master_ip = "-1"
+if (isset($_GET['master_ip']) && (is_valid_ip($_GET['master_ip']) || is_valid_ip6($_GET['master_ip']))) {
+	 $master_ip = $_GET['master_ip'];
+}
+
+$confirm = "-1";
+if ((isset($_GET['confirm']) && v_num($_GET['confirm'])
+        $confirm = $_GET['confirm'];
 }
 
-if (isset($_GET["master_ip"])) {
-        if ((isset($_GET['confirm'])) && ($_GET["confirm"] == '0')) {
-                clean_page("index.php");
-        } elseif ((isset($_GET["confirm"])) && ($_GET['confirm'] == '1')) {
-                delete_supermaster($_GET["master_ip"]);
-                clean_page("index.php");
-        }
-        include_once("inc/header.inc.php");
-	$info = get_supermaster_info_from_ip($_GET["master_ip"]);
-        ?>
-	<h2><?php echo _('Delete supermaster'); ?> "<?php echo $_GET["master_ip"] ?>"</h2>
-	<?php echo _('Hostname in NS record'); ?>: <?php echo $info["ns_name"] ?><br>
-	<?php echo _('Account'); ?>: <?php echo $info["account"] ?><br><br>
-        <font class="warning"><?php echo _('Are you sure?'); ?></font><br><br>
-        <input type="button" class="button" OnClick="location.href='<?php echo $_SERVER["REQUEST_URI"] ?>&confirm=1'" value="<?php echo _('Yes'); ?>"> 
-	<input type="button" class="button" OnClick="location.href='<?php echo $_SERVER["REQUEST_URI"] ?>&confirm=0'" value="<?php echo _('No'); ?>">
-        <?php
+if ($master_ip == "-1"){
+	error(ERR_INV_INPUT);
 } else {
-        include_once("inc/header.inc.php");
-        echo _('Nothing to do!');
+	(verify_permission(supermaster_edit)) ? $perm_sm_edit = "1" :  $perm_sm_edit = "0" ;
+	if ($perm_sm_edit == "0") {
+		error(ERR_PERM_DEL_SM);
+	} else {
+		$info = get_supermaster_info_from_ip($master_ip);
+
+		echo "     <h2>" . _('Delete supermaster') . " \"" . $master_ip . "\"</h2>\n";
+
+		if ($_GET["confirm"] == '1') {
+			if (delete_supermaster($master_ip)) {
+				success(SUC_ZONE_DEL);
+			}
+		} else {
+			echo "     <p>\n";
+			echo "      " . _('Hostname in NS record') . ": " . $info['ns_name'] . "<br>\n";
+			echo "      " . _('Account') . ": " . $info['account'] . "\n";
+			echo "     </p>\n";
+			echo "     <p>" . _('Are you sure?') . "</p>\n";
+			echo "     <input type=\"button\" class=\"button\" OnClick=\"location.href='" . $_SERVER['REQUEST_URI'] . "&confirm=1'\" value=\"" . _('Yes') . "\">\n"; 
+			echo "     <input type=\"button\" class=\"button\" OnClick=\"location.href='index.php'\" value=\"" . _('No') . "\">\n";
+		}
+	}
 }
+
 include_once("inc/footer.inc.php");
--- a/delete_user.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/delete_user.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,103 +20,87 @@
  */
 
 require_once("inc/toolkit.inc.php");
+include_once("inc/header.inc.php");
 
-$id = ($_POST["id"]) ? $_POST["id"] : $_GET["id"];
+verify_permission(user_edit_own) ? $perm_edit_own = "1" : $perm_edit_own = "0" ;
+verify_permission(user_edit_others) ? $perm_edit_others = "1" : $perm_edit_others = "0" ;
+
+if (!(isset($_GET['id']) && v_num($_GET['id']))) {
+	error(ERR_INV_INPUT);
+	include_once("inc/footer.inc.php");
+	exit;
+} else {
+	$uid = $_GET['id'];
+}
+
+if ($_POST['commit']) {
+	if (delete_user($uid,$_POST['zone'])) {
+		success(SUC_USER_DEL);	
+	}
+} else {
+
+	if (($uid != $_SESSION['userid'] && !verify_permission(user_edit_others)) || ($uid == $_SESSION['userid'] && !verify_permission(user_edit_own))) {
+		error(ERR_PERM_DEL_USER);
+		include_once("inc/footer.inc.php");
+		exit;
+	} else {
+		$fullname = get_fullname_from_userid($uid);
+		$zones = get_zones("own",$uid);
+
+		echo "     <h2>" . _('Delete user') . " \"" . $fullname . "\"</h2>\n";
+		echo "     <form method=\"post\">\n";
+		echo "      <table>\n";
+
+		if (count($zones) > 0) {
 
-if(isset($id)) 
-{
-	if($_POST["confirm"] == '1') 
-	{                
-                $domain = is_array($_POST["domain"]) ? $_POST["domain"] : $domain = array();
-                $delete = is_array($_POST["delete"]) ? $_POST["delete"] : $delete = array();
-                
-		if(count($domain) > 0) 
-		{
-			foreach ($domain as $dom => $newowner) 
-			{
-				if (!in_array($dom, $delete)) 
-				{
-					add_owner($dom, $newowner);
-                                }
-                        }
-                }
-                if(count($delete) > 0) 
-                {
-                	foreach ($delete as $del) 
-                	{
-                		delete_domain($del);
+			$users = show_users();
+
+			echo "       <tr>\n";
+			echo "        <td colspan=\"5\">\n";
+
+			echo "         " . _('You are about to delete a user. This user is owner for a number of zones. Please decide what to do with these zones.') . "\n";
+			echo "        </td>\n";
+			echo "       </tr>\n";
+
+			echo "       <tr>\n";
+			echo "        <th>" . _('Zone') . "</th>\n";
+			echo "        <th>" . _('Delete') . "</th>\n";
+			echo "        <th>" . _('Leave') . "</th>\n";
+			echo "        <th>" . _('Add new owner') . "</th>\n";
+			echo "        <th>" . _('Owner to be added') . "</th>\n";
+			echo "       </tr>\n";
+
+			foreach ($zones as $zone) {
+				echo "       <input type=\"hidden\" name=\"zone[" . $zone['id'] . "][zid]\" value=\"" . $zone['id'] . "\">\n";
+				echo "       <tr>\n";
+				echo "        <td>" . $zone['name'] . "</td>\n";
+				echo "        <td><input type=\"radio\" name=\"zone[" . $zone['id'] . "][target]\" value=\"delete\"></td>\n";
+				echo "        <td><input type=\"radio\" name=\"zone[" . $zone['id'] . "][target]\" value=\"leave\" CHECKED></td>\n";
+				echo "        <td><input type=\"radio\" name=\"zone[" . $zone['id'] . "][target]\" value=\"new_owner\"></td>\n";
+				echo "        <td>\n";
+				echo "         <select name=\"zone[" . $zone['id'] . "][newowner]\">\n";
+
+				foreach ($users as $user) {
+					echo "          <option value=\"" . $user["id"] . "\">" . $user["fullname"] . "</option>\n";
+				}
+
+				echo "         </select>\n";
+				echo "        </td>\n";
+				echo "       </tr>\n";
+
 			}
 		}
-		
-                delete_user($id);
-                clean_page("users.php");
-        }
-        include_once("inc/header.inc.php");
-        ?>
-	
-    <h3><?php echo _('Delete user'); ?> "<?php echo get_fullname_from_userid($id) ?>"</h3>
-     <form method="post">
-        <?php
-        $domains = get_domains_from_userid($id);
-        if (count($domains) > 0) 
-        {
-        	echo _('This user has access to the following zone(s)'); ?> :<BR><?php
-                $users = show_users($id);
-                if(count($users) < 1) 
-                {
-                        $add = " CHECKED DISABLED";
-                        $no_users = 1;
-                }
-                ?>
-                <table>
-                 <tr>
-		  <td class="n">Delete</td>
-		  <td class="n">Name</td>
-		<?php if (!$no_users) { ?>
-		  <td class="n">New owner</td>
-		<?php } ?>
-		 </tr>
-                <?php
-                foreach ($domains as $d) 
-                {
-                        ?>
-                 <tr>
-		  <td class="n" align="center"><?php
-                        if ($no_users) 
-                     	{ 
-                     		?><input type="hidden" name="delete[]" value="<?php echo $d["id"] ?>"><?php
-                        } 
-                        ?><input type="checkbox"<?php echo $add ?> name="delete[]" value="<?php echo $d["id"] ?>"></td><td class="n"><?php echo $d["name"] ?></td><td class="n"><?php 
-                        if (!$no_users) 
-                        { 
-                        	?><select name="domain[<?php echo $d["id"] ?>]"><?php
-                        	foreach($users as $u) 
-                        	{
-                        	        ?><option value="<?php echo $u["id"] ?>"><?php echo $u["fullname"] ?></option><?php
-                        	}
-                        	?></select></td><?php 
-                        } 
-                        ?></tr><?php
-                }
-                ?></table><?php
-        }
-        
-        $message = _('You are going to delete this user, are you sure?');
-        if(($numrows = $db->queryOne("SELECT count(id) FROM zones WHERE owner=".$db->quote($id))) != 0)
-        {
-        	$message .= " " . _('This user has access to ') . $numrows . _(' zones, by deleting him you will also delete these zones.');
-        }
+		echo "       <tr>\n";
+		echo "        <td colspan=\"5\">\n";
+
+		echo "         " . _('Really delete this user?') . "\n";
+		echo "        </td>\n";
+		echo "       </tr>\n";
 
-        ?>
-        <font class="warning"><?php echo $message ?></font><br>
-        <input type="hidden" name="id" value="<?php echo $id ?>">
-        <input type="hidden" name="confirm" value="1">
-        <input type="submit" class="button" value="<?php echo _('Yes'); ?>"> <input type="button" class="button" OnClick="location.href='users.php'" value="<?php echo _('No'); ?>"></FORM>
-        <?php
-        include_once("inc/footer.inc.php");
-} 
-else 
-{
-        message("Nothing to do!");
+		echo "      </table>\n";
+		echo "     <input type=\"submit\" class=\"button\" name=\"commit\" value=\"" . _('Comit changes') . "\">\n";
+		echo "     </form>\n";
+	}
 }
-
+include_once("inc/footer.inc.php");
+?>
--- a/docs/CHANGELOG	Wed Mar 12 20:45:56 2008 +0000
+++ b/docs/CHANGELOG	Tue Mar 25 22:45:31 2008 +0000
@@ -1,5 +1,4 @@
 CHANGELOG
 
+Please see <https://code.krikkit.nl/trac/poweradmin/log/trunk>.
 
-Please see <https://code.krikkit.nl/trac/poweradmin/log/>.
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/docs/poweradmin-mysql-db-structure.sql	Tue Mar 25 22:45:31 2008 +0000
@@ -0,0 +1,62 @@
+DROP TABLE IF EXISTS `users`;
+CREATE TABLE `users` (
+  `id` int(11) NOT NULL auto_increment,
+  `username` varchar(16) NOT NULL default '',
+  `password` varchar(34) NOT NULL default '',
+  `fullname` varchar(255) NOT NULL default '',
+  `email` varchar(255) NOT NULL default '',
+  `description` text NOT NULL,
+  `perm_templ` tinyint(11) NOT NULL default '0',
+  `active` tinyint(1) NOT NULL default '0',
+  PRIMARY KEY  (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=latin1;
+
+LOCK TABLES `users` WRITE;
+INSERT INTO `users` VALUES (1,'admin','21232f297a57a5a743894a0e4a801fc3','Administrator','admin@example.net','Administrator with full rights.',1,1);
+UNLOCK TABLES;
+
+DROP TABLE IF EXISTS `perm_items`;
+CREATE TABLE `perm_items` (
+  `id` int(11) NOT NULL auto_increment,
+  `name` varchar(64) NOT NULL,
+  `descr` text NOT NULL,
+  PRIMARY KEY  (`id`)
+) ENGINE=MyISAM AUTO_INCREMENT=62 DEFAULT CHARSET=latin1;
+
+LOCK TABLES `perm_items` WRITE;
+INSERT INTO `perm_items` VALUES (41,'zone_master_add','User is allowed to add new master zones.'),(42,'zone_slave_add','User is allowed to add new slave zones.'),(43,'zone_content_view_own','User is allowed to see the content and meta data of zones he owns.'),(44,'zone_content_edit_own','User is allowed to edit the content of zones he owns.'),(45,'zone_meta_edit_own','User is allowed to edit the meta data of zones he owns.'),(46,'zone_content_view_others','User is allowed to see the content and meta data of zones he does not own.'),(47,'zone_content_edit_others','User is allowed to edit the content of zones he does not own.'),(48,'zone_meta_edit_others','User is allowed to edit the meta data of zones he does not own.'),(49,'search','User is allowed to perform searches.'),(50,'supermaster_view','User is allowed to add view supermasters.'),(51,'supermaster_add','User is allowed to add new supermasters.'),(52,'supermaster_edit','User is allowed to edit new supermasters.'),(53,'user_is_ueberuser','User has full access. God-like. Redeemer.'),(54,'user_view_others','User is allowed to see other users and their details.'),(55,'user_add_new','User is allowed to add new users.'),(56,'user_edit_own','User is allowed to edit their own details.'),(57,'user_edit_others','User is allowed to edit other users.'),(58,'user_passwd_edit_others','User is allowed to edit the password of other users.'),(59,'user_edit_templ_perm','User is allowed to change the permission template that is assigned to a user.'),(60,'templ_perm_add','User is allowed to add new permission templates.'),(61,'templ_perm_edit','User is allowed to edit existing permission templates.');
+UNLOCK TABLES;
+
+DROP TABLE IF EXISTS `perm_templ`;
+CREATE TABLE `perm_templ` (
+  `id` int(11) NOT NULL auto_increment,
+  `name` varchar(128) NOT NULL,
+  `descr` text NOT NULL,
+  PRIMARY KEY  (`id`)
+) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
+
+LOCK TABLES `perm_templ` WRITE;
+INSERT INTO `perm_templ` VALUES (1,'Administrator','Administrator template with full rights.');
+UNLOCK TABLES;
+
+DROP TABLE IF EXISTS `perm_templ_items`;
+CREATE TABLE `perm_templ_items` (
+  `id` int(11) NOT NULL auto_increment,
+  `templ_id` int(11) NOT NULL,
+  `perm_id` int(11) NOT NULL,
+  PRIMARY KEY  (`id`)
+) ENGINE=MyISAM AUTO_INCREMENT=269 DEFAULT CHARSET=latin1;
+
+LOCK TABLES `perm_templ_items` WRITE;
+INSERT INTO `perm_templ_items` VALUES (58,2,43),(268,1,43),(267,1,46),(266,1,54),(265,1,56),(264,1,58),(263,1,45),(262,1,48),(261,1,44),(260,1,47),(259,1,57),(258,1,52),(257,1,61),(57,2,51),(56,2,42),(55,2,60),(54,2,41),(256,1,59),(255,1,50),(156,3,56),(155,3,58),(254,1,55),(253,1,51),(252,1,42),(251,1,60),(250,1,41),(249,1,53);
+UNLOCK TABLES;
+
+DROP TABLE IF EXISTS `zones`;
+CREATE TABLE `zones` (
+  `id` int(11) NOT NULL auto_increment,
+  `domain_id` int(11) NOT NULL default '0',
+  `owner` int(11) NOT NULL default '0',
+  `comment` text,
+  PRIMARY KEY  (`id`),
+  KEY `owner` (`owner`)
+) ENGINE=MyISAM AUTO_INCREMENT=22001 DEFAULT CHARSET=latin1;
--- a/edit.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/edit.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,346 +20,234 @@
  */
 
 require_once("inc/toolkit.inc.php");
+include_once("inc/header.inc.php");
 
-// Assigning records to user: Check for records owned by user
-$recordOwnerError = '';
-if (isset($_POST["action"]) && $_POST["action"]=="record-user") {
-	if (!is_array($_POST['rowid'])) {
-		$recordOwnerError = 'No records where selected to assign an sub-owner.';
-	} else {
-		foreach ($_POST["rowid"] as $x_user => $recordid){
-			$x_userid = $db->queryOne("SELECT id FROM record_owners WHERE user_id = ".$db->quote($_POST["userid"])." AND record_id=".$db->quote($recordid));
-			if (empty($x_userid)) {
-				add_record_owner($_GET["id"],$_POST["userid"],$recordid);
-			}
-		}
+$zone_id = "-1";
+if (isset($_GET['id']) && v_num($_GET['id'])) {
+	$zone_id = $_GET['id'];
+}
+
+if ($zone_id == "-1") {
+	error(ERR_INV_INPUT);
+	include_once("inc/footer.inc.php");
+	exit;
+}
+
+if (isset($_POST['commit'])) {
+	foreach ($_POST['record'] as $record) {
+		edit_record($record);
 	}
 }
-if(isset($_POST['change_slave_master']) && is_numeric($_POST["domain"]) && level(5))
-{
-	change_domain_slave_master($_POST['domain'], $_POST['slave_master']);
-}
-if(isset($_POST['type_change']) && in_array($_POST['newtype'], $server_types))
-{
-	change_domain_type($_POST['newtype'], $_GET['id']);
-}
-if(isset($_POST["newowner"]) && is_numeric($_POST["domain"]) && is_numeric($_POST["newowner"]))
-{
-	add_owner($_POST["domain"], $_POST["newowner"]);
+
+if (verify_permission(zone_content_view_others)) { $perm_view = "all" ; } 
+elseif (verify_permission(zone_content_view_own)) { $perm_view = "own" ; } 
+else { $perm_view = "none" ; }
+
+if (verify_permission(zone_content_edit_others)) { $perm_content_edit = "all" ; } 
+elseif (verify_permission(zone_content_edit_own)) { $perm_content_edit = "own" ; } 
+else { $perm_content_edit = "none" ; }
+
+if (verify_permission(zone_meta_edit_others)) { $perm_meta_edit = "all" ; } 
+elseif (verify_permission(zone_meta_edit_own)) { $perm_meta_edit = "own" ; } 
+else { $perm_meta_edit = "none" ; }
+
+$user_is_zone_owner = verify_user_is_owner_zoneid($zone_id);
+if ( $perm_meta_edit == "all" || ( $perm_meta_edit == "own" && $user_is_zone_owner == "1") ) {
+	$meta_edit = "1";
 }
-if(isset($_POST["del_user"]) && is_numeric($_POST["del_user"]) && level(5))
-{
-	delete_owner($_GET["id"], $_POST["del_user"]);
+
+if(isset($_POST['slave_master_change']) && is_numeric($_POST["domain"]) ) {
+	change_zone_slave_master($_POST['domain'], $_POST['new_master']);
 }
-$info = get_domain_info_from_id($_GET["id"]);
-include_once("inc/header.inc.php");
-	
-$domain_type=get_domain_type($_GET['id']);
-if ($domain_type == "SLAVE" ) { $slave_master=get_domain_slave_master($_GET['id']); };
-
-if (strlen($recordOwnerError)) {
-?>
-  <div class="error"><?php echo _('Error'); ?>: <?php echo _($recordOwnerError); ?></div>
-<?php
+if(isset($_POST['type_change']) && in_array($_POST['newtype'], $server_types)) {
+	change_zone_type($_POST['newtype'], $zone_id);
+}
+if(isset($_POST["newowner"]) && is_numeric($_POST["domain"]) && is_numeric($_POST["newowner"])) {
+	add_owner_to_zone($_POST["domain"], $_POST["newowner"]);
+}
+if(isset($_POST["delete_owner"]) && is_numeric($_POST["delete_owner"]) ) {
+	delete_owner_from_zone($zone_id, $_POST["delete_owner"]);
 }
 
-if(!isset($info["ownerid"]) && $domain_type != "SLAVE")
-{
-?>
-    <div class="error"><?php echo _('Error'); ?>: <?php echo ('There is no owner for this zone, please assign someone.'); ?></div>
-<?php
-}
-if ($domain_type == "SLAVE" && ! $slave_master )
-{
-?>
-    <div class="error"><?php echo _('Error'); ?>: <?php echo _('Type of this zone is "slave", but there is no IP address for it\'s master given.'); ?></div>
-<?php
-}
-?>
-    <h2><?php echo _('Edit zone'); ?> "<?php echo get_domain_name_from_id($_GET["id"]) ?>"</h2>
-<?php
-if (level(5)) 
-{ ?>	
-       <div id="meta">
-        <div id="meta-left">
-	 <table>
-   	  <tr>
-  	   <th colspan="2"><?php echo _('Owner of zone'); ?></th>
-  	  </tr>
-<?php
-	if(isset($info["ownerid"]))
-	{
-		$userRes = get_users_from_domain_id($_GET["id"]);
-		foreach($userRes as $user)
-		{ ?>
-  	  <tr>
-  	   <form method="post" action="edit.php?id=<?php echo $_GET['id']?>">
-  	    <td>
-	     <?php echo $user["fullname"]?>
-	    </td>
-            <td>
-  	     <input type="hidden" name="del_user" value="<?php echo $user["id"]?>">
-             <input type="submit" class="sbutton" name="co" value="<?php echo _('Delete'); ?>">
-  	    </td>
-           </form>
-  	  </tr>
-<?php
+$domain_type=get_domain_type($zone_id);
+$record_count=count_zone_records($zone_id);
+
+echo "   <h2>" . _('Edit zone') . " \"" . get_domain_name_from_id($zone_id) . "\"</h2>\n";
+
+if ( $perm_view == "none" || $perm_view == "own" && $user_is_zone_owner == "0" ) {
+	error(ERR_PERM_VIEW_ZONE);
+} else {
+	echo "   <div class=\"showmax\">\n";
+	show_pages($record_count,ROWAMOUNT,$zone_id);
+	echo "   </div>\n";
+
+	$records = get_records_from_domain_id($zone_id,ROWSTART,ROWAMOUNT);
+	if ( $records == "-1" ) { 
+		echo " <p>" .  _("This zone does not have any records. Weird.") . "</p>\n";
+	} else {
+		echo "   <form method=\"post\">\n";
+		echo "   <table>\n";
+		echo "    <tr>\n";
+		echo "     <th>&nbsp;</th>\n";
+		echo "     <th>" . _('Name') . "</th>\n";
+		echo "     <th>" . _('Type') . "</th>\n";
+		echo "     <th>" . _('Content') . "</th>\n";
+		echo "     <th>" . _('Priority') . "</th>\n";
+		echo "     <th>" . _('TTL') . "</th>\n";
+		echo "    </tr>\n";
+		foreach ($records as $r) {
+			echo "    <input type=\"hidden\" name=\"record[" . $r['id'] . "][rid]\" value=\"" . $r['id'] . "\">\n";
+			echo "    <input type=\"hidden\" name=\"record[" . $r['id'] . "][zid]\" value=\"" . $zone_id . "\">\n";
+			echo "    <tr>\n";
+			if ( $domain_type == "SLAVE" || $perm_content_edit == "none" || $perm_content_edit == "own" && $user_is_zone_owner == "0" ) {
+				echo "     <td class=\"n\">&nbsp;</td>\n";
+			} else {
+				echo "     <td class=\"n\">\n";
+				echo "      <a href=\"edit_record.php?id=" . $r['id'] . "&amp;domain=" . $zone_id . "\">
+						<img src=\"images/edit.gif\" alt=\"[ ". _('Edit record') . " ]\"></a>\n";
+				echo "      <a href=\"delete_record.php?id=" . $r['id'] . "&amp;domain=" . $zone_id . "\">
+						<img src=\"images/delete.gif\" ALT=\"[ " . _('Delete record') . " ]\" BORDER=\"0\"></a>\n";
+				echo "     </td>\n";
+			}
+			echo "      <td class=\"u\"><input class=\"wide\" name=\"record[" . $r['id'] . "][name]\" value=\"" . $r['name'] . "\"></td>\n";
+			echo "      <td class=\"u\">\n";
+			echo "       <select name=\"record[" . $r['id'] . "][type]\">\n";
+			foreach (get_record_types() as $type_available) {
+				if ($type_available == $r["type"]) {
+					$add = " SELECTED";
+				} else {
+					$add = "";
+				}
+				echo "         <option" . $add . " value=\"" . $type_available . "\" >" . $type_available . "</option>\n";
+			}
+			echo "       </select>\n";
+			echo "      </td>\n";
+			echo "      <td class=\"u\"><input class=\"wide\" name=\"record[" . $r['id'] . "][content]\" value=\"" . $r['content'] . "\"></td>\n";
+			if ($r['type'] == "MX") { 
+				echo "      <td class=\"u\"><input name=\"record[" . $r['id'] . "][prio]\" value=\"" .  $r['prio'] . "\"></td>\n";
+			} else {
+				echo "      <td class=\"n\">&nbsp;</td>\n";
+			}
+			echo "      <td class=\"u\"><input name=\"record[" . $r['id'] . "][ttl]\" value=\"" . $r['ttl'] . "\"></td>\n";
+			echo "     </tr>\n";
+		}
+		echo "    </table>\n";
+		echo "     <input type=\"submit\" class=\"button\" name=\"commit\" value=\"" . _('Commit changes') . "\">\n";
+		echo "    </form>";
+	}
+	
+	if ( $perm_content_edit == "all" || $perm_content_edit == "own" && $user_is_zone_owner == "1" ) {
+		if ( $domain_type != "SLAVE") {
+			echo "    <input type=\"button\" class=\"button\" OnClick=\"location.href='add_record.php?id=" . $zone_id . "'\" value=\"" . _('Add record') . "\">&nbsp;&nbsp\n";
+		}
+		echo "    <input type=\"button\" class=\"button\" OnClick=\"location.href='delete_domain.php?id=" . $zone_id . "'\" value=\"" . _('Delete zone') . "\">\n";
+	}
+
+	echo "   <div id=\"meta\">\n";
+	echo "    <table>\n";
+	echo "     <tr>\n";
+	echo "      <th colspan=\"2\">" . _('Owner of zone') . "</th>\n";
+	echo "     </tr>\n";
+
+	$owners = get_users_from_domain_id($zone_id);
+
+	if ($owners == "-1") {
+		echo "      <tr><td>" . _('No owner set or this zone!') . "</td></tr>";
+	} else {
+		if ($meta_edit) {
+			foreach ($owners as $owner) {
+				echo "      <form method=\"post\" action=\"edit.php?id=" . $zone_id . "\">\n";
+				echo "       <tr>\n";
+				echo "        <td>" . $owner["fullname"] . "</td>\n";
+				echo "        <td>\n";
+				echo "         <input type=\"hidden\" name=\"delete_owner\" value=\"" . $owner["id"] . "\">\n";
+				echo "         <input type=\"submit\" class=\"sbutton\" name=\"co\" value=\"" . _('Delete') . "\">\n";
+				echo "        </td>\n";
+				echo "       </tr>\n";
+				echo "      </form>\n";
+			}
+		} else {
+			foreach ($owners as $owner) {
+				echo "    <tr><td>" . $owner["fullname"] . "</td><td>&nbsp;</td></tr>";
+			}
+		}
+
+	}
+	if ($meta_edit) {
+		echo "      <form method=\"post\" action=\"edit.php?id=" . $zone_id . "\">\n";
+		echo "       <input type=\"hidden\" name=\"domain\" value=\"" . $zone_id . "\">\n";
+		echo "       <tr>\n";
+		echo "        <td>\n";
+		echo "         <select name=\"newowner\">\n";
+		$users = show_users();
+		foreach ($users as $user) {
+			unset($add);
+			if ($user["id"] == $_SESSION["userid"]) {
+				$add = " SELECTED";
+			}
+			echo "          <option" . $add . " value=\"" . $user["id"] . "\">" . $user["fullname"] . "</option>\n";
+		}
+		echo "         </select>\n";
+		echo "        </td>\n";
+		echo "        <td>\n";
+		echo "         <input type=\"submit\" class=\"sbutton\" name=\"co\" value=\"" . _('Add') . "\">\n";
+		echo "        </td>\n";
+		echo "       </tr>\n";
+		echo "      </form>\n";
+	}
+	echo "      <tr>\n";
+	echo "       <th colspan=\"2\">" . _('Type of zone') . "</th>\n";
+	echo "      </tr>\n";
+
+	if ($meta_edit) {
+		echo "      <form action=\"" . $_SERVER['PHP_SELF'] . "?id=" . $zone_id . "\" method=\"post\">\n";
+		echo "       <input type=\"hidden\" name=\"domain\" value=\"" . $zone_id . "\">\n";
+		echo "       <tr>\n";
+		echo "        <td>\n";
+		echo "         <select name=\"newtype\">\n";
+		foreach($server_types as $type) {
+			unset($add);
+			if ($type == $domain_type) {
+				$add = " SELECTED";
+			}
+			echo "          <option" .  $add . " value=\"" . $type . "\">" .  strtolower($type) . "</option>\n";
+		}
+		echo "         </select>\n";
+		echo "        </td>\n";
+		echo "        <td>\n";
+		echo "         <input type=\"submit\" class=\"sbutton\" name=\"type_change\" value=\"" . _('Change') . "\">\n";
+		echo "        </td>\n";
+		echo "       </tr>\n";
+		echo "      </form>\n";
+	} else {
+		echo "      <tr><td>" . strtolower($domain_type) . "</td><td>&nbsp;</td></tr>\n";
+	}
+
+	if ($domain_type == "SLAVE" ) { 
+		$slave_master=get_domain_slave_master($zone_id);
+		echo "      <tr>\n";
+		echo "       <th colspan=\"2\">" . _('IP address of master NS') . "</th>\n";
+		echo "      </tr>\n";
+
+		if ($meta_edit) {
+			echo "      <form action=\"" . $_SERVER['PHP_SELF'] . "?id=" . $zone_id . "\" method=\"post\">\n";
+			echo "       <input type=\"hidden\" name=\"domain\" value=\"" . $zone_id . "\">\n";
+			echo "       <tr>\n";
+			echo "        <td>\n";
+			echo "         <input type=\"text\" name=\"new_master\" value=\"" . $slave_master . "\" class=\"input\">\n";
+			echo "        </td>\n";
+			echo "        <td>\n";
+			echo "         <input type=\"submit\" class=\"sbutton\" name=\"slave_master_change\" value=\"" . _('Change') . "\">\n";
+			echo "        </td>\n";
+			echo "       </tr>\n";
+			echo "      </form>\n";
+		} else {
+			echo "      <tr><td>" . $slave_master . "</td><td>&nbsp;</td></tr>\n";
 		}
 	}
-	else
-	{
-?>
-	  <tr>
-	   <td><?php echo _('No owner set or this zone!'); ?></td>
-	  </tr>
-<?php
-	}
-  ?>
-          <tr>
-  	   <form method="post" action="edit.php?id=<?php echo $_GET['id']?>">
-  	    <td>
-  	     <input type="hidden" name="domain" value="<?php echo $_GET["id"] ?>">
-  	     <select name="newowner">
-  			<?php
-  			$users = show_users();
-  			foreach ($users as $u)
-  			{
-  				$add = '';
-  				if ($u["id"] == $info["ownerid"])
-  				{
-  					$add = " SELECTED";
-  				}
-  				?>
-  				<option<?php echo $add ?> value="<?php echo $u["id"] ?>"><?php echo $u["fullname"] ?></option><?php
-  			}
-  			?>
-  			</select>
-  	    </td>
-  	    <td>
-     	     <input type="submit" class="sbutton" name="co" value="<?php echo _('Add'); ?>">
-            </td>
-  	   </form>
-  	  </tr>
-         </table>
-	</div> <?php // eo div meta-left ?>
-        <div id="meta-right">
-         <table>
-	  <tr>
-	   <th colspan="2"><?php echo _('Type of zone'); ?></th>
-	  </tr>
-	  <form action="<?php echo $_SERVER['PHP_SELF']?>?id=<?php echo $_GET['id']?>" method="post">
-	   <input type="hidden" name="domain" value="<?php echo $_GET["id"] ?>">
-	   <tr>
-	    <td>
-	     <select name="newtype">
-<?php
-	foreach($server_types as $s)
-	{
-		$add = '';
-		if ($s == $domain_type)
-		{
-			$add = " SELECTED";
-		}
-?>
-              <option<?php echo $add ?> value="<?php echo $s?>"><?php echo $s?></option><?php
-	}
-?>
-             </select>
-            </td>
-	    <td>
-	     <input type="submit" class="sbutton" name="type_change" value="<?php echo _('Change'); ?>">
-	    </td>
-	   </tr>
-	  </form>
-
-<?php
-	if ($domain_type == "SLAVE" ) 
-	{ 
-		$slave_master=get_domain_slave_master($_GET['id']);
-?>
-          <tr>
-	   <th colspan="2">
-	    <?php echo _('IP address of master NS'); ?>
-	   </th>
-	  </tr>
-	  <form action="<?php echo $_SERVER['PHP_SELF']?>?&amp;id=<?php echo $_GET['id']?>" method="post">
-	   <input type="hidden" name="domain" value="<?php echo $_GET["id"] ?>">
-	   <tr>
-	    <td>
-	     <input type="text" name="slave_master" value="<?php echo $slave_master; ?>" class="input">
-            </td>
-            <td>
-	     <input type="submit" class="sbutton" name="change_slave_master" value="<?php echo _('Change'); ?>">
-            </td>
-           </tr>
-          </form>
-<?php
-	}
-?>
-         </table>  
-        </div> <?php // eo div meta-right ?>
-       </div> <?php // eo div meta 
-}
-else
-{
-?>
-       <div id="meta">
-        <div id="meta-right">
-         <table>
- 	  <tr>
- 	   <th><?php echo _('Type of zone'); ?></th><td class="y"><?php echo $domain_type; ?></td>
-	  </tr>
-<?php
-	if ($domain_type == "SLAVE" &&  $slave_master )
-	{
-?>
-	  <tr>
-	   <th><?php echo _('IP address of master NS'); ?></th><td class="y"><?php echo $slave_master; ?></td>
-	  </tr>
-<?php
-	}
-?>
-         </table>
-        </div> <?php //eo div meta-right ?>
-        </div> <?php // eo div meta
+	echo "     </table>\n";
+	echo "   </div>\n";	// eo div meta 
 }
-?>
-       <div id="meta">
-<?php
-	if ($_SESSION[$_GET["id"]."_ispartial"] != 1 && $domain_type != "SLAVE" )
-	{
-?>
-        <input type="button" class="button" OnClick="location.href='add_record.php?id=<?php echo $_GET["id"] ?>'" value="<?php echo _('Add record'); ?>">&nbsp;&nbsp;
-<?php
-	}
-	if (level(5))
-	{
-?>
-	<input type="button" class="button" OnClick="location.href='delete_domain.php?id=<?php echo $_GET["id"] ?>'" value="<?php echo _('Delete zone'); ?>">
-<?php
-	}
-?>
-        </div> <?php // eo div meta ?>
-       <div class="showmax">
-<?php
-show_pages($info["numrec"],ROWAMOUNT,$_GET["id"]);
-?>
-        </div> <?php // eo div showmax ?>
-         <form action="<?php echo $_SERVER["PHP_SELF"]?>?id=<?php echo $_GET["id"]?>" method="post">
-          <input type="hidden" name="action" value="record-user">
-          <table>
-<?php
-$countinput=0;
-$rec_result = get_records_from_domain_id($_GET["id"],ROWSTART,ROWAMOUNT);
-if($rec_result != -1)
-{
-?>
-           <tr>
-	    <th>&nbsp;</th>
-<?php 
-	if (level(10) && $domain_type != "SLAVE") 
-	{ 
-		echo "<th class=\"n\">" . _('Sub-owners') . "</td>"; 
-	} 
-?>
-	    <th><?php echo _('Name'); ?></th>
-	    <th><?php echo _('Type'); ?></th>
-	    <th><?php echo _('Content'); ?></th>
-	    <th><?php echo _('Priority'); ?></th>
-	    <th><?php echo _('TTL'); ?></th>
-           </tr>
-<?php
-  	$recs = sort_zone($rec_result);
-  	foreach($recs as $r)
-  	{
-?>
-           <tr>
-	    <td class="n">
-<?php
-		if ($domain_type != "SLAVE" )
-		{	
-			if(level(5) || (!($r["type"] == "SOA" && !$GLOBALS["ALLOW_SOA_EDIT"]) && !($r["type"] == "NS" && !$GLOBALS["ALLOW_NS_EDIT"])))
-			{
-?>
-			     <a href="edit_record.php?id=<?php echo $r['id'] ?>&amp;domain=<?php echo $_GET["id"] ?>"><img src="images/edit.gif" alt="[ <?php echo _('Edit record'); ?> ]"></a>
-			     <a href="delete_record.php?id=<?php echo $r['id'] ?>&amp;domain=<?php echo $_GET["id"] ?>"><img src="images/delete.gif" ALT="[ <?php echo _('Delete record'); ?> ]" BORDER="0"></a>
-<?php
-			}
-		}
-		if(level(10) && $domain_type != "SLAVE") 
-		{ 
-?>
-		     <input type="checkbox" name="rowid[<?php echo $countinput++?>]" value="<?php echo $r['id']?>" />
-<?php 
-		}
-?>
-            </td>
-<?php 
-		if (level(10) && $domain_type != "SLAVE") 
-		{ 
-?>
-            <td class="n">
-<?php 
-			$x_result = $db->query("SELECT r.user_id,u.username,u.fullname FROM record_owners as r, users as u WHERE r.record_id=".$db->quote($r['id'])." AND u.id=r.user_id");
-			echo "<select style=\"width:120px;\">";
-			while ($x_r = $x_result->fetchRow()) {
-				echo "<option value=\"".$x_r["username"]."\">".$x_r["fullname"]."</option>";
-			}
-			echo "</select>";
-?>
-            </td>
-<?php 
-		} 
-?>
-	    <td class="y"><?php echo $r['name'] ?></td>
-	    <td class="y"><?php echo $r['type'] ?></td>
-	    <td class="y"><?php echo $r['content'] ?></td>
-<?php
-		if ($r['prio'] != 0) 
-		{
-?>
-            <td class="y"><?php echo $r['prio']; ?></td>
-<?php
-		} else {
-?>
-            <td class="n"></td><?php
-		}
-?>
-            <td class="y"><?php echo $r['ttl'] ?></td>
-	   </tr>
-<?php
-	}
-}
-else
-{
-?>
-           <tr>
-            <td class="n">
-	     <div class="warning"><?php echo _('No records for this zone.'); ?></div>
-	    </td>
-           </tr>
-<?php
-}
-?>
-          </table>
 
-<?php
-if ($domain_type != "SLAVE")
-{
-	if (level(10)) { ?>
-	   <img src="images/arrow.png" alt="arrow" class="edit-assign-to-user">
-	   <select name="userid">
-		<?php
-		$users = show_users();
-		foreach ($users as $user) {
-			echo "<option value=\"".$user[id]."\">".$user[fullname]."</option>";
-		}
-		?>
-           </select>
-	   <input type="submit" class="button" value="<?php echo _('Assign to user'); ?>">
-	  </form>
-<?php 
-	} 
-}
 include_once("inc/footer.inc.php");
 ?>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/edit_perm_templ.php	Tue Mar 25 22:45:31 2008 +0000
@@ -0,0 +1,92 @@
+<?php
+
+/*  PowerAdmin, a friendly web-based admin tool for PowerDNS.
+ *  See <https://rejo.zenger.nl/poweradmin> for more details.
+ *
+ *  Copyright 2007, 2008  Rejo Zenger <rejo@zenger.nl>
+ *
+ *  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 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+require_once("inc/toolkit.inc.php");
+include_once("inc/header.inc.php");
+
+$id = "-1";
+if ((isset($_GET['id'])) || (v_num($_GET['id']))) {
+	$id = $_GET['id'] ;
+}
+
+if ($id == "-1") {
+	error(ERR_INV_INPUT);
+} elseif (!verify_permission(templ_perm_edit)) {
+	error(ERR_PERM_EDIT_PERM_TEMPL);
+} else {
+	$id = $_GET['id'];
+
+	if (isset($_POST['commit'])) {
+		update_perm_templ_details($_POST);	
+	}
+
+	$templ_details = get_permission_template_details($id);
+	$perms_templ = get_permissions_by_template_id($id);
+	$perms_avail = get_permissions_by_template_id();
+
+	echo "    <h2>" . _('Edit permission template') . "</h2>\n"; 
+        echo "    <form method=\"post\">\n";
+	echo "    <input type=\"hidden\" name=\"templ_id\" value=\"" . $id . "\">\n";
+
+	foreach ($templ_details as $templ) {
+		echo "     <table>\n";
+		echo "      <tr>\n";
+		echo "       <th>" . _('Name') . "</th>\n"; 
+		echo "       <td><input class=\"wide\" type=\"text\" name=\"templ_name\" value=\"" . $templ['name'] . "\"></td>\n";
+		echo "      </tr>\n";
+		echo "      <tr>\n";
+		echo "       <th>" . _('Description') . "</th>\n"; 
+		echo "       <td><input class=\"wide\" type=\"text\" name=\"templ_descr\" value=\"" . $templ['descr'] . "\"></td>\n";
+		echo "      </tr>\n";
+		echo "     </table>\n";
+	}
+
+	echo "     <table>\n";
+	echo "      <tr>\n";
+	echo "       <th>&nbsp;</th>\n";
+	echo "       <th>" . _('Name') . "</th>\n"; 
+	echo "       <th>" . _('Description') . "</th>\n"; 
+	echo "      </tr>\n";
+
+	foreach ($perms_avail as $perm_a) {
+
+		echo "      <tr>\n";
+
+		$has_perm = "";
+		foreach ($perms_templ as $perm_t) {
+			if (in_array( $perm_a['id'], $perm_t )) {
+				$has_perm = "checked";
+			}
+		}
+
+		echo "       <td><input type=\"checkbox\" name=\"perm_id[]\" value=\"" . $perm_a['id'] . "\" " . $has_perm . "></td>\n";
+		echo "       <td>" . $perm_a['name'] . "</td>\n";
+		echo "       <td>" . $perm_a['descr'] . "</td>\n";
+		echo "      </tr>\n";
+	}
+	echo "     </table>\n";
+	echo "     <input type=\"submit\" class=\"button\" name=\"commit\" value=\"" . _('Commit changes') . "\">\n";
+	echo "     </form>\n";
+
+}
+
+include_once("inc/footer.inc.php");
+?>
--- a/edit_record.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/edit_record.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,135 +20,94 @@
  */
 
 require_once("inc/toolkit.inc.php");
+include_once("inc/header.inc.php");
 
-if (isset($_GET["delid"]) && isset($_GET['delid']) && isset($_GET['id'])) {
-   delete_record_owner($_GET["domain"],$_GET["delid"],$_GET["id"]);
-}
+if (verify_permission(zone_content_view_others)) { $perm_view = "all" ; }
+elseif (verify_permission(zone_content_view_own)) { $perm_view = "own" ; }
+else { $perm_view = "none" ; }
+
+if (verify_permission(zone_content_edit_others)) { $perm_content_edit = "all" ; }
+elseif (verify_permission(zone_content_edit_own)) { $perm_content_edit = "own" ; }
+else { $perm_content_edit = "none" ; }
+
+if (verify_permission(zone_meta_edit_others)) { $perm_meta_edit = "all" ; }
+elseif (verify_permission(zone_meta_edit_own)) { $perm_meta_edit = "own" ; }
+else { $perm_meta_edit = "none" ; }
 
-$xsid = (isset($_GET['id'])) ? $_GET['id'] : $_POST['recordid'];
+$user_is_zone_owner = verify_user_is_owner_zoneid($_GET["domain"]);
+$zone_type = get_domain_type($_GET["domain"]);
+$zone_name = get_domain_name_from_id($_GET["domain"]);
 
-if(!xs(recid_to_domid($xsid)))
-{
-    error(ERR_RECORD_ACCESS_DENIED);
+if ($_POST["commit"]) {
+	if ( $zone_type == "SLAVE" || $perm_content_edit == "none" || $perm_content_edit == "own" && $user_is_zone_owner == "0" ) {
+		error(ERR_PERM_EDIT_RECORD);
+	} else {
+		$ret_val = edit_record($_POST["recordid"], $_POST["domainid"], $_POST["name"], $_POST["type"], $_POST["content"], $_POST["ttl"], $_POST["prio"]);
+		if ( $ret_val == "1" ) {
+			success(SUC_RECORD_UPD);
+		} else {
+			echo "     <div class=\"error\">" . $ret_val . "</div>\n";  
+		}
+	}
 }
 
-if (isset($_GET['domain'])) {
-	$domain_name = get_domain_name_from_id($_GET['domain']);
-}
-if (isset($_POST["commit"]) && isset($_POST['recordid']) && isset($_POST['domainid']) && isset($_POST['name']) && isset($_POST['type']) && isset($_POST['content']) && isset($_POST['ttl']) && isset($_POST['prio']))
-{
-        edit_record($_POST["recordid"], $_POST["domainid"], $_POST["name"], $_POST["type"], $_POST["content"], $_POST["ttl"], $_POST["prio"]);
-        clean_page("edit.php?id=".$_POST["domainid"]);
-} elseif(isset($_SESSION['partial_'.$domain_name]) && ($_SESSION["partial_".$domain_name] == 1))
-{
-	$db->setLimit(1);
-    $checkPartial = $db->queryOne("SELECT id FROM record_owners WHERE record_id=".$db->quote($_GET["id"])." AND user_id=".$db->quote($_SESSION["userid"]));
-    if (empty($checkPartial)) {
-        error(ERR_RECORD_ACCESS_DENIED);
-    }
-}
-include_once("inc/header.inc.php");
-?>
-    <h2><?php echo _('Edit record in zone'); ?> "<?php echo  $domain_name ?>"</h2>
-<?php
+echo "    <h2>" . _('Edit record in zone') . " " .  $zone_name . "</h2>\n";
+
+if ( $perm_view == "none" || $perm_view == "own" && $user_is_zone_owner == "0" ) {
+	error(ERR_PERM_VIEW_RECORD);
+} else {
+	$record = get_record_from_id($_GET["id"]);
+	echo "     <form method=\"post\" action=\"edit_record.php?domain=" . $_GET["domain"] . "&id=" . $_GET["id"] . "\">\n";
+	echo "      <table>\n";
+	echo "       <tr>\n";
+	echo "        <th>" . _('Name') . "</td>\n";
+	echo "        <th>&nbsp;</td>\n";
+	echo "        <th>" . _('Type') . "</td>\n";
+	echo "        <th>" . _('Priority') . "</td>\n";
+	echo "        <th>" . _('Content') . "</td>\n";
+	echo "        <th>" . _('TTL') . "</td>\n";
+	echo "       </tr>\n";
 
-$x_result = $db->query("SELECT r.id,u.fullname FROM record_owners as r, users as u WHERE r.record_id=".$db->quote($_GET['id'])." AND u.id=r.user_id");
-if (level(10) && ($x_result->numRows() > 0)) 
-{
-?>
-    <div id="meta">
-     <div id="meta-left">
-      <table>
-       <tr>
-        <th><?php echo _('Sub-owners'); ?></td>
-        <th>&nbsp;</td>
-       </tr>
-<?php
-	while ($x_r = $x_result->fetchRow()) 
-	{
-?>
-        <tr>
-	 <td class="tdbg"><?php echo $x_r["fullname"]; ?></td>
-	 <td class="tdbg"><a href="<?php echo $_SERVER["PHP_SELF"]; ?>?id=<?php echo $_GET["id"]; ?>&amp;domain=<?php echo $_GET["domain"]; ?>&amp;delid=<?php echo $x_r["id"]; ?>"><img src="images/delete.gif" alt="trash"></a></td>
-	</tr>
-<?php
+	if ( $zone_type == "SLAVE" || $perm_content_edit == "none" || $perm_content_edit == "own" && $user_is_zone_owner == "0" ) {
+		echo "      <tr>\n";
+		echo "       <td>" . $record["name"] . "</td>\n";
+		echo "       <td>IN</td>\n";
+		echo "       <td>" . $record["type"] . "</td>\n";
+		echo "       <td>" . $record["content"] . "</td>\n";
+		echo "       <td>" . $record["prio"] . "</td>\n";
+		echo "       <td>" . $record["ttl"] . "</td>\n";
+		echo "      </tr>\n";
+	} else {
+		echo "      <input type=\"hidden\" name=\"recordid\" value=\"" . $_GET["id"] . "\">\n";
+		echo "      <input type=\"hidden\" name=\"domainid\" value=\"" . $_GET["domain"] . "\">\n";
+		echo "      <tr>\n";
+		echo "       <td><input type=\"text\" name=\"name\" value=\"" . trim(str_replace($zone_name, '', $record["name"]), '.') . "\" class=\"input\">." . $zone_name . "</td>\n";
+		echo "       <td>IN</td>\n";
+		echo "       <td>\n";
+		echo "        <select name=\"type\">\n";
+		foreach (get_record_types() as $type_available) {
+			if ($type_available == $record["type"]) {
+				$add = " SELECTED";
+			} else {
+				$add = "";
+			}
+			echo "         <option" . $add . " value=\"" . $type_available . "\" >" . $type_available . "</option>\n";
+		}
+		echo "        </select>\n";
+		echo "       </td>\n";
+		echo "       <td><input type=\"text\" name=\"prio\" value=\"" .  $record["prio"] . "\" class=\"sinput\"></td>\n";
+		echo "       <td><input type=\"text\" name=\"content\" value=\"" .  $record["content"] . "\" class=\"input\"></td>\n";
+		echo "       <td><input type=\"text\" name=\"ttl\" value=\"" . $record["ttl"] . "\" class=\"sinput\"></td>\n";
+		echo "      </tr>\n";
 	}
-?>
-       </table>
-      </div>
-     </div>
-<?php 
-}
-?>
-	<div id="meta">&nbsp;</div>
-	<div>
-    <form method="post" action="edit_record.php">
-     <input type="hidden" name="recordid" value="<?php echo  $_GET["id"] ?>">
-     <input type="hidden" name="domainid" value="<?php echo  $_GET["domain"] ?>">
-     <table>
-      <tr>
-       <th><?php echo _('Name'); ?></td>
-       <th>&nbsp;</td>
-       <th><?php echo _('Type'); ?></td>
-       <th><?php echo _('Priority'); ?></td>
-       <th><?php echo _('Content'); ?></td>
-       <th><?php echo _('TTL'); ?></td>
-      </tr>
-<?php
-	$rec = get_record_from_id($_GET["id"]);
-?>
-       <tr>
-        <td>
-<?php 
-if ($_SESSION[$_GET["domain"]."_ispartial"] == 1)  
-{
-?>
-         <input type="hidden" name="name" value="<?php echo  trim(str_replace($domain_name, '', $rec["name"]), '.')?>" class="input">
-
-<?php echo  trim(str_replace($domain_name, '', $rec["name"]), '.') ?>
-<?php 
-} 
-else 
-{ 
-?>
-         <input type="text" name="name" value="<?php echo  trim(str_replace($domain_name, '', $rec["name"]), '.') ?>" class="input">
-<?php 
-} 
-?>
-.<?php echo  $domain_name ?>
-        </td>
-	<td class="n">IN</td>
-	<td>
-	 <select name="type">
-<?php
-foreach (get_record_types() as $c)
-{
-	if ($c == $rec["type"])
-	{
-		$add = " SELECTED";
-	}
-	else
-	{
-		$add = "";
-	}
-	?>
-	<option<?php echo  $add ?> value="<?php echo  $c ?>"><?php echo  $c ?></option><?php
+	echo "      </table>\n";
+	echo "      <p>\n";
+	echo "       <input type=\"submit\" name=\"commit\" value=\"" . _('Commit changes') . "\" class=\"button\">&nbsp;&nbsp;\n";
+	echo "      </p>\n";
+	echo "     </form>\n";
 }
 
-?>
-         </select>
-	</td>
-	<td><input type="text" name="prio" value="<?php echo  $rec["prio"] ?>" class="sinput"></td>
-	<td><input type="text" name="content" value="<?php echo  $rec["content"] ?>" class="input"></td>
-	<td><input type="text" name="ttl" value="<?php echo  $rec["ttl"] ?>" class="sinput"></td>
-       </tr>
-      </table>
-      <p>
-       <input type="submit" name="commit" value="<?php echo _('Commit changes'); ?>" class="button">&nbsp;&nbsp;
-       <input type="reset" name="reset" value="<?php echo _('Reset changes'); ?>" class="button">
-      </p>
-     </form>
-	</div>
-<?php
+
 include_once("inc/footer.inc.php");
 ?>
+
--- a/edit_user.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/edit_user.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,88 +20,141 @@
  */
 
 require_once("inc/toolkit.inc.php");
-
-if($_POST["commit"])
-{
-	if($_POST["username"] && $_POST["level"] && $_POST["fullname"])
-	{
-		if(!isset($_POST["active"]))
-		{
-			$active = 0;
-		}
-		else
-		{
-			$active = 1;
-		}
-		if(edit_user($_POST["number"], $_POST["username"], $_POST["fullname"], $_POST["email"], $_POST["level"], $_POST["description"], $active, $_POST["password"]))
-		{
-			clean_page("users.php");
-		}
-		else
-		{
-			error("Error editting user!");
-		}
-	}
-}
-
 include_once("inc/header.inc.php");
 
-if (!level(10))
-{
-	error("You do not have the required access level.");
+$edit_id = "-1";
+if (isset($_GET['id']) && v_num($_GET['id'])) {
+	$edit_id = $_GET['id'];
 }
-?>
-    <h2><?php echo _('Edit user'); ?> "<?php echo get_fullname_from_userid($_GET["id"]) ?>"</h2>
-<?php
-$r = array();
-$r = get_user_info($_GET["id"]);
-?>
-    <form method="post">
-     <input type="HIDDEN" name="number" value="<?php echo $_GET["id"] ?>">
-     <table>
-      <tr>
-       <td class="n"><?php echo _('User name'); ?>:</td>
-       <td class="n"><input type="text" class="input" name="username" value="<?php echo $r["username"]?>"></td>
-      </tr>
-      <tr>
-       <td class="n"><?php echo _('Full name'); ?>:</td>
-       <td class="n"><input type="text" class="input" name="fullname" value="<?php echo $r["fullname"]?>"></td>
-      </tr>
-      <tr>
-       <td class="n"><?php echo _('Password'); ?>:</td>
-       <td class="n"><input type="password" class="input" name="password" value=""></td>
-      </tr>
-      <tr>
-       <td class="n"><?php echo _('E-mail'); ?>:</td>
-       <td class="n"><input type="text" class="input" name="email" value="<?php echo $r["email"]?>"></td>
-      </tr>
-      <tr>
-       <td class="n"><?php echo _('User level'); ?>:</td>
-       <td class="n">
-        <select name="level">
-	 <option value="1" <?php if($r["level"] == 1) { echo "selectED"; } ?>>1 (<?php echo _('Normal user'); ?>)</option>
-	 <option value="5" <?php if($r["level"] == 5) { echo "selectED"; } ?>>5 (<?php echo _('Administrator'); ?>)</option>
-	 <option value="10" <?php if($r["level"] == 10) { echo "selectED"; } ?>>10 (<?php echo _('Administrator w/ user admin rights'); ?>)</option>
-	</select>
-       </td>
-      </tr>
-      <tr>
-       <td class="n"><?php echo _('Description'); ?>:</td>
-       <td class="n">
-        <textarea rows="6" cols="30" class="inputarea" name="description"><?php echo $r["description"]?></textarea>
-       </td>
-      </tr>
-      <tr>
-       <td class="n"><?php echo _('Active'); ?>:</td>
-       <td class="n"><input type="checkbox" name="active" value="1" <?php if($r["active"]) { ?>CHECKED<?php } ?>></td>
-      </tr>
-      <tr>
-       <td class="n">&nbsp;</td>
-       <td class="n"><input type="submit" class="button" name="commit" value="<?php echo _('Commit changes'); ?>"></td>
-      </tr>
-     </table>
-    </form>
-<?php
+
+verify_permission(user_edit_own) ? $perm_edit_own = "1" : $perm_edit_own = "0" ;
+verify_permission(user_edit_others) ? $perm_edit_others = "1" : $perm_edit_others = "0" ;
+
+if ($edit_id == "-1") {
+	error(ERR_INV_INPUT);
+} elseif (($edit_id == $_SESSION["userid"] && $perm_edit_own == "1") || ($edit_id != $_SESSION["userid"] && $perm_edit_others == "1" )) {
+
+	if($_POST["commit"]) {
+
+		$i_username = "-1";
+		$i_fullname = "-1";
+		$i_email = "-1";
+		$i_description = "-1";
+		$i_password = "-1";
+		$i_perm_templ = "0";
+		$i_active = "0";
+
+		if (isset($_POST['username'])) {
+			$i_username = $_POST['username'];
+		}
+
+		if (isset($_POST['fullname'])) {
+			$i_fullname = $_POST['fullname'];
+		}
+
+		if (isset($_POST['email'])) {
+			$i_email = $_POST['email'];
+		}
+
+		if (isset($_POST['description'])) {
+			$i_description = $_POST['description'];
+		}
+
+		if (isset($_POST['password'])) {
+			$i_password = $_POST['password'];
+		}
+		
+		if (isset($_POST['perm_templ']) && v_num($_POST['perm_templ'])) {
+			$i_perm_templ = $_POST['perm_templ'];
+		}
+		
+		if (isset($_POST['active']) && v_num($_POST['active'])) {
+			$i_active = $_POST['active'];
+		}
+		
+		if ( $i_username == "-1" || $i_fullname == "-1" || $i_email < "1" || $i_description == "-1" || $i_password == "-1" ) {
+			error(ERR_INV_INPUT);
+		} else {
+			if($i_username != "" && $i_perm_templ > "0" && $i_fullname) {
+				if(!isset($i_active)) {
+					$active = 0;
+				} else {
+					$active = 1;
+				}
+				if(edit_user($edit_id, $i_username, $i_fullname, $i_email, $i_perm_templ, $i_description, $active, $i_password)) {
+					success(SUC_USER_UPD);
+				} 
+			}
+		}
+	}
+
+	$users = get_user_detail_list($edit_id)	;
+
+	foreach ($users as $user) {
+		
+		(($user['active']) == "1") ? $check = " CHECKED" : $check = "" ;
+
+		echo "     <h2>" . _('Edit user') . " \"" . $user['fullname'] . "\"</h2>\n";
+		echo "     <form method=\"post\">\n";
+		echo "      <input type=\"hidden\" name=\"number\" value=\"" . $edit_id . "\">\n";
+		echo "      <table>\n";
+		echo "       <tr>\n";
+		echo "        <td class=\"n\">" . _('Username') . "</td>\n"; 
+		echo "        <td class=\"n\"><input type=\"text\" class=\"input\" name=\"username\" value=\"" . $user['username'] . "\"></td>\n";
+		echo "       </tr>\n";
+		echo "       <tr>\n";
+		echo "        <td class=\"n\">" . _('Fullname') . "</td>\n"; 
+		echo "        <td class=\"n\"><input type=\"text\" class=\"input\" name=\"fullname\" value=\"" . $user['fullname'] . "\"></td>\n";
+		echo "       </tr>\n";
+		echo "       <tr>\n";
+		echo "        <td class=\"n\">" . _('Password') . "</td>\n";
+		echo "        <td class=\"n\"><input type=\"text\" class=\"input\" name=\"password\"></td>\n";
+		echo "       </tr>\n";
+		echo "       <tr>\n";
+		echo "        <td class=\"n\">" . _('Email') . "</td>\n"; 
+		echo "        <td class=\"n\"><input type=\"text\" class=\"input\" name=\"email\" value=\"" . $user['email'] . "\"></td>\n";
+		echo "       </tr>\n";
+		echo "       <tr>\n";
+		echo "        <td class=\"n\">" . _('Permission template') . "</td>\n"; 
+		echo "        <td class=\"n\">\n";
+		echo "         <select name=\"perm_templ\">\n";
+		foreach (list_permission_templates() as $template) {
+			($template['id'] == $user['tpl_id']) ? $select = " SELECTED" : $select = "" ;
+			echo "          <option value=\"" . $template['id'] . "\"" . $select . ">" . $template['name'] . "</option>\n";
+		}
+		echo "         </select>\n";
+		echo "       </td>\n";
+		echo "       </tr>\n";
+		echo "       <tr>\n";
+		echo "        <td class=\"n\">" . _('Description') . "</td>\n"; 
+		echo "        <td class=\"n\"><textarea rows=\"4\" cols=\"30\" class=\"inputarea\" name=\"description\">" . $user['descr'] . "</textarea></td>\n";
+		echo "       </tr>\n";
+		echo "       <tr>\n";
+		echo "        <td class=\"n\">" . _('Enabled') . "</td>\n"; 
+		echo "        <td class=\"n\"><input type=\"checkbox\" class=\"input\" name=\"active\" value=\"1\"" . $check . "></td>\n";
+		echo "       </tr>\n";
+		echo "       <tr>\n";
+	echo "        <td class=\"n\">&nbsp;</td>\n"; 
+		echo "        <td class=\"n\"><input type=\"submit\" class=\"button\" name=\"commit\" value=\"" . _('Commit changes') . "\"></td>\n"; 
+		echo "      </table>\n";
+		echo "     </form>\n";
+
+		echo "     <p>\n";
+		printf("      This user has been assigned the \"%s\" permission template.", $user['tpl_name']);
+		if ($user['tpl_descr'] != "") { 
+			echo " The description for this template is: \"" . $user['tpl_descr'] . "\".";
+		}
+		echo " Based on this template, this user has the following permissions:";
+		echo "     </p>\n";
+		echo "     <ul>\n";
+		foreach (get_permissions_by_template_id($user['tpl_id']) as $item) {
+			echo "      <li>" . $item['descr'] . " (" . $item['name'] . ")</li>\n";
+		}
+		echo "     </ul>\n";
+	}
+} else {
+	error(ERR_PERM_EDIT_USER);
+}
 
 include_once("inc/footer.inc.php");
 
--- a/inc/auth.inc.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/inc/auth.inc.php	Tue Mar 25 22:45:31 2008 +0000
@@ -21,55 +21,57 @@
 
 //session_start();
 
-if (isset($_SERVER["QUERY_STRING"]) && $_SERVER["QUERY_STRING"] == "logout")
-{
-	logout();
-}
+function doAuthenticate() {
+	global $db;
+	global $EXPIRE;
+	if (isset($_SERVER["QUERY_STRING"]) && $_SERVER["QUERY_STRING"] == "logout") {
+		logout();
+	}
 
-// If a user had just entered his/her login && password, store them in our session.
-if(isset($_POST["authenticate"]))
-{
-    	$_SESSION["userpwd"] = $_POST["password"];
-    	$_SESSION["userlogin"] = $_POST["username"];
-}
+	// If a user had just entered his/her login && password, store them in our session.
+	if(isset($_POST["authenticate"]))
+	{
+			$_SESSION["userpwd"] = $_POST["password"];
+			$_SESSION["userlogin"] = $_POST["username"];
+	}
 
-// Check if the session hasnt expired yet.
-if ((isset($_SESSION["userid"])) && ($_SESSION["lastmod"] != "") && ((time() - $_SESSION["lastmod"]) > $EXPIRE))
-{
-	logout( _('Session expired, please login again.'),"error");
-}
+	// Check if the session hasnt expired yet.
+	if ((isset($_SESSION["userid"])) && ($_SESSION["lastmod"] != "") && ((time() - $_SESSION["lastmod"]) > $EXPIRE))
+	{
+		logout( _('Session expired, please login again.'),"error");
+	}
 
-// If the session hasn't expired yet, give our session a fresh new timestamp.
-$_SESSION["lastmod"] = time();
+	// If the session hasn't expired yet, give our session a fresh new timestamp.
+	$_SESSION["lastmod"] = time();
 
-if(isset($_SESSION["userlogin"]) && isset($_SESSION["userpwd"]))
-{
-    //Username and password are set, lets try to authenticate.
-	$result = $db->query("SELECT id, fullname, level FROM users WHERE username=". $db->quote($_SESSION["userlogin"])  ." AND password=". $db->quote(md5($_SESSION["userpwd"]))  ." AND active=1");
-	if($result->numRows() == 1)
+	if(isset($_SESSION["userlogin"]) && isset($_SESSION["userpwd"]))
 	{
-        	$rowObj = $result->fetchRow();
-		$_SESSION["userid"] = $rowObj["id"];
-		$_SESSION["name"] = $rowObj["fullname"];
-		$_SESSION["level"] = $rowObj["level"];
-        	if(isset($_POST["authenticate"]))
-        	{
-            		//If a user has just authenticated, redirect him to index with timestamp, so post-data gets lost.
-            		session_write_close();
-            		clean_page("index.php");
-            		exit;
-        	}
-    	}
-    	else
-    	{
-        	//Authentication failed, retry.
-	        auth( _('Authentication failed!'),"error");
+		//Username and password are set, lets try to authenticate.
+		$result = $db->query("SELECT id, fullname FROM users WHERE username=". $db->quote($_SESSION["userlogin"])  ." AND password=". $db->quote(md5($_SESSION["userpwd"]))  ." AND active=1");
+		if($result->numRows() == 1)
+		{
+			$rowObj = $result->fetchRow();
+			$_SESSION["userid"] = $rowObj["id"];
+			$_SESSION["name"] = $rowObj["fullname"];
+			if($_POST["authenticate"])
+			{
+				//If a user has just authenticated, redirect him to index with timestamp, so post-data gets lost.
+				session_write_close();
+				clean_page("index.php");
+				exit;
+			}
+		}
+		else
+		{
+			//Authentication failed, retry.
+			auth( _('Authentication failed!'),"error");
+		}
 	}
-}
-else
-{
-	//No username and password set, show auth form (again).
-	auth();
+	else
+	{
+		//No username and password set, show auth form (again).
+		auth();
+	}
 }
 
 /*
@@ -105,6 +107,11 @@
 	  </tr>
 	 </table>
 	</form>
+        <script type="text/javascript">
+         <!--
+          document.login.username.focus();
+         //-->
+        </script>
 	<?php
 	include_once('inc/footer.inc.php');
 	exit;
@@ -124,7 +131,6 @@
 	};
 	unset($_SESSION["userid"]);
 	unset($_SESSION["name"]);
-	unset($_SESSION["level"]);;
 	session_destroy();
 	session_write_close();
 	auth($msg, $type);
--- a/inc/config-me.inc.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/inc/config-me.inc.php	Tue Mar 25 22:45:31 2008 +0000
@@ -95,26 +95,11 @@
 // After this $EXPIRE you are automatically logged out from the system.
 $EXPIRE = 1800;
 
-// $ALLOW_SOA_EDIT
-// Allow users with level 1 to edit/delete SOA records?
-$ALLOW_SOA_EDIT = 0;
-
-// $ALLOW_NS_EDIT
-// Allow users with level 1 to edit/delete pre-set NS records for their domain.
-$ALLOW_NS_EDIT = 1;
-
 // $DEFAULT_TTL
 // Default TTL for records.
 // Default time to live for all records. This notation is in seconds.
 $DEFAULT_TTL = 86400;      // (3600 seconds / 1 hour by default)
 
-
-// $NAME_LEVEL_X
-// These directives allow you to change the statusnames of users on the system.
-$NAME_LEVEL_1 = _('Normal user');
-$NAME_LEVEL_5 = _('Administrator');
-$NAME_LEVEL_10 = _('Administrator w/ user admin rights');
-
 // Enable fancy records or not (http://doc.powerdns.com/fancy-records.html)? true/false
 $FANCY_RECORDS = true;
 
--- a/inc/database.inc.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/inc/database.inc.php	Tue Mar 25 22:45:31 2008 +0000
@@ -35,34 +35,43 @@
 
 PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, 'dbError');
 
-$dsn = "$dbdsntype://$dbuser:$dbpass@$dbhost/$dbdatabase";
-$db = MDB2::connect($dsn);
-$db->setOption('portability', MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL);
+function dbConnect() {
+	global $dbdsntype;
+	global $dbuser;
+	global $dbpass;
+	global $dbhost;
+	global $dbdatabase;
+	global $sql_regexp;
 
-if (MDB2::isError($db))
-{
-	// Error handling should be put.
-        error(MYSQL_ERROR_FATAL, $db->getMessage());
-}
+	$dsn = "$dbdsntype://$dbuser:$dbpass@$dbhost/$dbdatabase";
+	$db = MDB2::connect($dsn);
+	$db->setOption('portability', MDB2_PORTABILITY_ALL ^ MDB2_PORTABILITY_EMPTY_TO_NULL);
 
-// Do an ASSOC fetch. Gives us the ability to use ["id"] fields.
-$db->setFetchMode(MDB2_FETCHMODE_ASSOC);
-
-/* erase info */
-$mysql_pass = $dsn = '';
+	if (MDB2::isError($db))
+	{
+		// Error handling should be put.
+		error(MYSQL_ERROR_FATAL, $db->getMessage());
+	}
 
-// Add support for regular expressions in both MySQL and PostgreSQL
-if ( $dbdsntype == "mysql" ) 
-{
-	$sql_regexp = "REGEXP";
-} 
-elseif ( $dbdsntype == "pgsql" ) 
-{
-	$sql_regexp = "~";
+	// Do an ASSOC fetch. Gives us the ability to use ["id"] fields.
+	$db->setFetchMode(MDB2_FETCHMODE_ASSOC);
+
+	/* erase info */
+	$mysql_pass = $dsn = '';
+
+	// Add support for regular expressions in both MySQL and PostgreSQL
+	if ( $dbdsntype == "mysql" ) 
+	{
+		$sql_regexp = "REGEXP";
+	} 
+	elseif ( $dbdsntype == "pgsql" ) 
+	{
+		$sql_regexp = "~";
+	}
+	else
+	{
+		error(_('Unknown database type in inc/config.inc.php.'));
+	};
+	return $db;
 }
-else
-{
-	error(_('Unknown database type in inc/config.inc.php.'));
-};
-
 ?>
--- a/inc/dns.inc.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/inc/dns.inc.php	Tue Mar 25 22:45:31 2008 +0000
@@ -43,129 +43,110 @@
 	$ip4 = false;
 	$ip6 = false;
 
-	if(!in_array(strtoupper($type), $nocheck))
-	{
-
-		if(!is_valid_ip6($content))
-		{
-			if(!is_valid_ip($content))
-			{
-				if(!is_valid_hostname($content))
-				{
+	if(!in_array(strtoupper($type), $nocheck)) {
+		if(!is_valid_ip6($content)) {
+			if(!is_valid_ip($content)) {
+				if(!is_valid_hostname($content)) {
 					error(ERR_DNS_CONTENT);
-				}
-				else
-				{
+					return false;
+				} else {
 					$hostname = true;
 				}
-			}
-			else
-			{
+			} else {
 				$ip4 = true;
 			}
-		}
-		else
-		{
+		} else {
 			$ip6 = true;
 		}
 	}
 
 	// Prepare total hostname.
 
-	if($name == '*')
-	{
+	if ($name == '*') {
 		$wildcard = true;
 	} else {
 		$wildcard = false;
 	}
 
-	if ($name=="0") {
-	   $name=$name.".".$domain;
-	} else {
-	   $name = ($name) ? $name.".".$domain : $domain;
-	}
+// TODO:	Needs to be checked what this is good for. Since we started insert an array
+//		in functions like edit_record, "name"'s like "sub-fqdn.example.net" became 
+//		"sub-fqdn.example.net.example.net". 
+//	if ($name=="0") {
+//		$name=$name.".".$domain;
+//	} else {
+//		$name = ($name) ? $name.".".$domain : $domain;
+//	}
 
 	if (preg_match('!@\.!i', $name))
 	{
 		$name = str_replace('@.', '@', $name);
 	}
-
-	if(!$wildcard)
-	{
-		if(!is_valid_hostname($name))
-		{
+	if(!$wildcard) {
+		if(!is_valid_hostname($name)) {
 			error(ERR_DNS_HOSTNAME);
+			return false;
 		}
 	}
 
 	// Check record type (if it exists in our allowed list.
-	if (!in_array(strtoupper($type), get_record_types()))
-	{
+	if (!in_array(strtoupper($type), get_record_types())) {
 		error(ERR_DNS_RECORDTYPE);
+		return false;
 	}
 
 	// Start handling the demands for the functions.
 	// Validation for IN A records. Can only have an IP. Nothing else.
-	if ($type == 'A' && !$ip4)
-	{
+	if ($type == 'A' && !$ip4) {
 		error(ERR_DNS_IPV4);
+		return false;
 	}
 
-	if ($type == 'AAAA' && !$ip6)
-	{
+	if ($type == 'AAAA' && !$ip6) {
 		error(ERR_DNS_IPV6);
+		return false;
 	}
 
-	if ($type == 'CNAME' && $hostname)
-	{
-		if(!is_valid_cname($name))
-		{
+	if ($type == 'CNAME' && $hostname) {
+		if(!is_valid_cname($name)) {
 			error(ERR_DNS_CNAME);
+			return false;
 		}
 	}
 
-	if ($type == 'NS')
-	{
+	if ($type == 'NS') {
 		$status = is_valid_ns($content, $hostname);
-		if($status == -1)
-		{
+		if($status == -1) {
 			error(ERR_DNS_NS_HNAME);
+			return false;
 		}
-		elseif($status == -2)
-		{
+		elseif($status == -2) {
 			error(ERR_DNS_NS_CNAME);
+			return false;
 		}
-		// Otherwise its ok
 	}
 
-	if ($type == 'SOA')
-	{
+	if ($type == 'SOA') {
 		$status = is_valid_soa($content, $zoneid);
-		if($status == -1)
-		{
+		if($status == -1) {
 			error(ERR_DNS_SOA_UNIQUE);
-			// Make nicer error
-		}
-		elseif($status == -2)
-		{
+		} elseif($status == -2) {
 			error(ERR_DNS_SOA_NUMERIC);
+			return false;
 		}
 	}
 
 	// HINFO and TXT require no validation.
 
-	if ($type == 'URL')
-	{
-		if(!is_valid_url($content))
-		{
+	if ($type == 'URL') {
+		if(!is_valid_url($content)) {
 			error(ERR_INV_URL);
+			return false;
 		}
 	}
-	if ($type == 'MBOXFW')
-	{
-		if(!is_valid_mboxfw($content))
-		{
+	if ($type == 'MBOXFW') 	{
+		if(!is_valid_mboxfw($content)) {
 			error(ERR_INV_EMAIL);
+			return false;
 		}
 	}
 
@@ -177,36 +158,32 @@
 
 	// See if the prio field is valid and if we have one.
 	// If we dont have one and the type is MX record, give it value '10'
-	if($type == 'NAPTR')
-	{
+	if($type == 'NAPTR') {
 
 	}
 	
-	if($type == 'MX')
-	{
-		if($hostname)
-		{
+	if($type == 'MX') {
+		if($hostname) {
 			$status = is_valid_mx($content, $prio);
-			if($status == -1)
-			{
+			if($status == -1) {
 				error(ERR_DNS_MX_CNAME);
+				return false;
 			}
-			elseif($status == -2)
-			{
+			elseif($status == -2) {
 				error(ERR_DNS_MX_PRIO);
+				return false;
 			}
+		} else {
+			error( _('If you specify an MX record it must be a hostname.') ); // TODO make error
+			return false;
 		}
-		else
-		{
-			error( _('If you specify an MX record it must be a hostname.') );
-		}
-	}
-	else
-	{
+	} else {
 		$prio=0;
 	}
 	// Validate the TTL, it has to be numeric.
 	$ttl = (!isset($ttl) || !is_numeric($ttl)) ? $DEFAULT_TTL : $ttl;
+	
+	return true;
 }
 
 
--- a/inc/error.inc.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/inc/error.inc.php	Tue Mar 25 22:45:31 2008 +0000
@@ -23,9 +23,20 @@
 // if this is the best (or at least a proper) location for this. /RZ.
 require_once("inc/i18n.inc.php");
 
-/* USER LEVELS */
-define("ERR_LEVEL_5", _('You need user level 5 for this operation'));
-define("ERR_LEVEL_10", _('You need user level 10 for this operation'));
+/* PERMISSIONS */
+define("ERR_PERM_SEARCH", _("You do not have the permission to perform searches.")); 
+define("ERR_PERM_ADD_RECORD", _("You do not have the permission to add a record to this zone.")); 
+define("ERR_PERM_EDIT_RECORD", _("You do not have the permission to edit this record.")); 
+define("ERR_PERM_VIEW_RECORD", _("You do not have the permission to view this record.")); 
+define("ERR_PERM_DEL_RECORD", _("You do not have the permission to delete this record.")); 
+define("ERR_PERM_ADD_ZONE_MASTER", _("You do not have the permission to add a master zone.")); 
+define("ERR_PERM_DEL_ZONE", _("You do not have the permission to delete a zone.")); 
+define("ERR_PERM_DEL_SM", _("You do not have the permission to delete a supermaster.")); 
+define("ERR_PERM_VIEW_ZONE", _("You do not have the permission to view this zone.")); 
+define("ERR_PERM_EDIT_USER", _("You do not have the permission to edit this user.")); 
+define("ERR_PERM_EDIT_PERM_TEMPL", _("You do not have the permission to edit permission templates.")); 
+define("ERR_PERM_ADD_USER", _("You do not have the permission to add a new user.")); 
+define("ERR_PERM_DEL_USER", _("You do not have the permission to delete this user.")); 
 
 /* RECORD STUFF */
 define("ERR_RECORD_EMPTY_CONTENT", _('Your content field is empty'));
@@ -34,6 +45,8 @@
 
 /* DOMAIN STUFF */
 define("ERR_DOMAIN_INVALID", _('This is an invalid zone name'));
+define("ERR_SM_EXISTS", _('There is already a supermaster with this IP address.')); 
+define("ERR_DOMAIN_EXISTS", _('There is already a zone with this name.')); 
 
 /* USER STUFF */
 define("ERR_USER_EXIST", _('Username exist already, please choose another one'));
@@ -43,6 +56,7 @@
 define("ERR_USER_EDIT", _('Error editting user'));
 
 /* OTHER */
+define("ERR_INV_INPUT", _('Invalid or unexpected input given.'));  
 define("ERR_INV_ARG", _('Invalid argument(s) given to function %s'));
 define("ERR_INV_ARGC", _('Invalid argument(s) given to function %s %s'));
 define("ERR_UNKNOWN", _('unknown error'));
@@ -52,6 +66,7 @@
 define("ERR_DNS_CONTENT", _('Your content field doesnt have a legit value'));
 define("ERR_DNS_HOSTNAME", _('Invalid hostname'));
 define("ERR_DNS_RECORDTYPE", _('Invalid record type! You shouldnt even been able to get that here'));
+define("ERR_DNS_IP", _('This is not a valid IPv4 or IPv6 address.')); 
 define("ERR_DNS_IPV6", _('This is not a valid IPv6 ip.'));
 define("ERR_DNS_IPV4", _('This is not a valid IPv4 ip.'));
 define("ERR_DNS_CNAME", _('This is not a valid CNAME. Did you assign an MX or NS record to the record?'));
@@ -62,4 +77,15 @@
 define("ERR_DNS_SOA_NUMERIC", _('One of your SOA data fields is not numeric!'));
 define("ERR_DNS_SOA_NUMERIC_FIELDS", _('You can only have 5 numeric fields'));
 define("ERR_DNS_SOA_HOSTNAME", _('The first part of your SOA record does not contain a valid hostname for a DNS Server'));
+
+/* GOOD! */
+define("SUC_ZONE_ADD", _('Zone has been added succesfully.')); 
+define("SUC_ZONE_DEL", _('Zone has been deleted succesfully.')); 
+define("SUC_USER_UPD", _('The user has been updated succesfully.')); 
+define("SUC_USER_ADD", _('The user has been created succesfully.')); 
+define("SUC_USER_DEL", _('The user has been deleted succesfully.')); 
+define("SUC_RECORD_UPD", _('The record has been updated succesfully.')); 
+define("SUC_RECORD_DEL", _('The record has been deleted succesfully.')); 
+define("SUC_SM_DEL", _('The supermaster has been deleted succesfully.')); 
+
 ?>
--- a/inc/header.inc.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/inc/header.inc.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,57 +20,57 @@
  */
 
 global $STYLE;
-?>
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-<html>
- <head>
-  <title><?php echo _('Poweradmin'); ?></title>
-  <link rel=stylesheet href="style/<?php echo $STYLE; ?>.inc.php" type="text/css">
- </head>
- <body>
-<?php
-if(file_exists('inc/custom_header.inc.php')) 
-{
+
+echo "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n";
+echo "<html>\n";
+echo " <head>\n";
+echo "  <title>PowerAdmin</title>\n";
+echo "  <link rel=stylesheet href=\"style/" . $STYLE . ".inc.php\" type=\"text/css\">\n";
+echo " </head>\n";
+echo " <body>\n";
+
+if(file_exists('inc/custom_header.inc.php')) {
 	include('inc/custom_header.inc.php');
 }
-?>
-  <h1><?php echo _('Poweradmin'); ?></h1> 
-<?php
-if (isset($_SESSION["userid"]))
-{
-?>
-  
-	  <div class="menu">
-	   <span class="menuitem"><a href="index.php"><?php echo _('Index'); ?></a></span>
-	   <span class="menuitem"><a href="search.php"><?php echo _('Search zones or records'); ?></a></span>
-	   <span class="menuitem"><a href="list_zones.php"><?php echo _('List all zones'); ?></a></span>
-	<?php
-	if (level(5))
-	{
-	?>
-	   <span class="menuitem"><a href="list_supermasters.php"><?php echo _('List all supermasters'); ?></a></span>
-	   <span class="menuitem"><a href="add_zone_master.php"><?php echo _('Add master zone'); ?></a></span>
-	   <span class="menuitem"><a href="add_zone_slave.php"><?php echo _('Add slave zone'); ?></a></span>
-	   <span class="menuitem"><a href="add_supermaster.php"><?php echo _('Add supermaster'); ?></a></span>
-	<?php
+
+echo "  <h1>PowerAdmin</h1>\n";
+
+if (isset($_SESSION["userid"])) {
+
+	verify_permission(search) ? $perm_search = "1" : $perm_search = "0" ;
+	verify_permission(zone_content_view_own) ? $perm_view_zone_own = "1" : $perm_view_zone_own = "0" ;
+	verify_permission(zone_content_view_other) ? $perm_view_zone_other = "1" : $perm_view_zone_other = "0" ;
+	verify_permission(supermaster_view) ? $perm_supermaster_view = "1" : $perm_supermaster_view = "0" ;
+	verify_permission(zone_master_add) ? $perm_zone_master_add = "1" : $perm_zone_master_add = "0" ;
+	verify_permission(zone_slave_add) ? $perm_zone_slave_add = "1" : $perm_zone_slave_add = "0" ;
+	verify_permission(supermaster_add) ? $perm_supermaster_add = "1" : $perm_supermaster_add = "0" ;
+
+	echo "    <div class=\"menu\">\n";
+	echo "    <span class=\"menuitem\"><a href=\"index.php\">" . _('Index') . "</a></span>\n";
+	if ( $perm_search == "1" ) { 
+		echo "    <span class=\"menuitem\"><a href=\"search.php\">" . _('Search zones or records') . "</a></span>\n"; 
 	}
-	?>
-	   <span class="menuitem"><a href="change_password.php"><?php echo _('Change password'); ?></a></span>
-	<?php
-	if (level(10))
-	{
-	?>
-	   <span class="menuitem"><a href="users.php"><?php echo _('User administration'); ?></a></span>
-	<?php
+	if ( $perm_view_zone_own == "1" || $perm_view_zone_other == "1" ) { 
+		echo "    <span class=\"menuitem\"><a href=\"list_zones.php\">" . _('List all zones') . "</a></span>\n"; 
+	}
+	if ( $perm_supermaster_view ) { 
+		echo "    <span class=\"menuitem\"><a href=\"list_supermasters.php\">" . _('List all supermasters') . "</a></span>\n"; 
+	}
+	if (  $perm_zone_master_add ) { 
+		echo "    <span class=\"menuitem\"><a href=\"add_zone_master.php\">" . _('Add master zone') . "</a></span>\n"; 
 	}
-	?>
-	   <span class="menuitem"><a href="index.php?logout"><?php echo _('Logout'); ?></a></span>
-
-	  </div> <!-- /menu -->
-<?php
+	if ( $perm_zone_slave_add ) { 
+		echo "    <span class=\"menuitem\"><a href=\"add_zone_slave.php\">" . _('Add slave zone') . "</a></span>\n"; 
+	}
+	if ( $supermaster_add ) { 
+		echo "    <span class=\"menuitem\"><a href=\"add_supermaster.php\">" . _('Add supermaster') . "</a></span>\n"; 
+	}
+	echo "    <span class=\"menuitem\"><a href=\"change_password.php\">" . _('Change password') . "</a></span>\n";
+	echo "    <span class=\"menuitem\"><a href=\"users.php\">" . _('User administration') . "</a></span>\n";
+	echo "    <span class=\"menuitem\"><a href=\"index.php?logout\">" . _('Logout') . "</a></span>\n";
+	echo "    </div> <!-- /menu -->\n";
 }
-?>
-  <div class="content">
+echo "    <div class=\"content\">\n";
 
   
 
--- a/inc/record.inc.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/inc/record.inc.php	Tue Mar 25 22:45:31 2008 +0000
@@ -19,86 +19,59 @@
  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
+function count_zone_records($zone_id) {
+	global $db;
+	$sqlq = "SELECT COUNT(id) FROM records WHERE domain_id = ".$db->quote($zone_id);
+	$record_count = $db->queryOne($sqlq);
+	return $record_count;
+}
+
 function update_soa_serial($domain_id)
 {
-    global $db;
-	/*
-	 * THIS CODE ISNT TESTED THROUGH MUCH YET!
-	 * !!!!!!! BETACODE !!!!!!!!!!
-	 * Code committed by DeViCeD, Thanks a lot!
-	 * Heavily hax0red by Trancer/azurazu
-	 *
-	 * First we have to check, wheather current searial number 
-	 * was already updated on the other nameservers.
-	 * If field 'notified_serial' is NULL, then I guess domain is
-	 * NATIVE and we don't have any secondary nameservers for this domain.
-	 * NOTICE: Serial number *will* be RFC1912 compilant after update 
-	 * NOTICE: This function will allow only 100 DNS zone transfers ;-)
-	 * YYYYMMDDnn
-	 */
+	global $db;
 
 	$sqlq = "SELECT notified_serial FROM domains WHERE id = ".$db->quote($domain_id);
 	$notified_serial = $db->queryOne($sqlq);
 
 	$sqlq = "SELECT content FROM records WHERE type = 'SOA' AND domain_id = ".$db->quote($domain_id);
 	$content = $db->queryOne($sqlq);
-    $need_to_update = false;
-	
+	$need_to_update = false;
+
 	// Getting the serial field.
 	$soa = explode(" ", $content);
-	
-	if(empty($notified_serial))
-    {
-        // Ok native replication, so we have to update.
-        $need_to_update = true;
-    }
-    elseif($notified_serial >= $soa[2])
-    {
-        $need_to_update = true;
-    }
-    elseif(strlen($soa[2]) != 10)
-    {
-        $need_to_update = true;
-    }
-    else
-    {
-        $need_to_update = false;
-    }
-    if($need_to_update)
-    {
-        // Ok so we have to update it seems.
-        $current_serial = $soa[2];
-        
-		/*
-		 * What we need here (for RFC1912) is YEAR, MONTH and DAY
-		 * so let's get it ...
-		 */
+
+	if(empty($notified_serial)) {
+		// Ok native replication, so we have to update.
+		$need_to_update = true;
+	} elseif($notified_serial >= $soa[2]) {
+		$need_to_update = true;
+	} elseif(strlen($soa[2]) != 10) {
+		$need_to_update = true;
+	} else {
+		$need_to_update = false;
+	}
+
+	if($need_to_update) {
+		// Ok so we have to update it seems.
+		$current_serial = $soa[2];
 		$new_serial = date('Ymd'); // we will add revision number later
 
-		if(strncmp($new_serial, $current_serial, 8) === 0)
-		{
-            /*
-             * Ok, so we already made updates tonight
-             * let's just increase the revision number
-             */				
-            $revision_number = (int) substr($current_serial, -2);
-            if ($revision_number == 99) return false; // ok, we cannot update anymore tonight
-            ++$revision_number;
-            // here it is ... same date, new revision
-            $new_serial .= str_pad($revision_number, 2, "0", STR_PAD_LEFT);	
-		}
- 		else
-		{
-            /*
+		if(strncmp($new_serial, $current_serial, 8) === 0) {
+			$revision_number = (int) substr($current_serial, -2);
+			if ($revision_number == 99) return false; // ok, we cannot update anymore tonight
+			++$revision_number;
+			// here it is ... same date, new revision
+			$new_serial .= str_pad($revision_number, 2, "0", STR_PAD_LEFT);	
+		} else {
+			/*
 			 * Current serial is not RFC1912 compilant, so let's make a new one
 			 */
- 			$new_serial .= '00';
+			$new_serial .= '00';
 		}
-        $soa[2] = $new_serial; // change serial in SOA array
+		$soa[2] = $new_serial; // change serial in SOA array
 		$new_soa = "";		
 		// build new soa and update SQL after that
-		for ($i = 0; $i < count($soa); $i++) 
-		{	
+		for ($i = 0; $i < count($soa); $i++) {	
 			$new_soa .= $soa[$i] . " "; 
 		}
 		$sqlq = "UPDATE records SET content = ".$db->quote($new_soa)." WHERE domain_id = ".$db->quote($domain_id)." AND type = 'SOA'";
@@ -112,147 +85,123 @@
  * This function validates it if correct it inserts it into the database.
  * return values: true if succesful.
  */
-function edit_record($recordid, $zoneid, $name, $type, $content, $ttl, $prio)
-{
-	global $db;
-  	if($content == "")
-  	{
-  		error(ERR_RECORD_EMPTY_CONTENT);
-  	}
-  	// Edits the given record (validates specific stuff first)
-	if (!xs(recid_to_domid($recordid)))
-	{
-		error(ERR_RECORD_ACCESS_DENIED);
+function edit_record($record) {
+
+	if (verify_permission(zone_content_edit_others)) { $perm_content_edit = "all" ; }
+	elseif (verify_permission(zone_content_edit_own)) { $perm_content_edit = "own" ; }
+	else { $perm_content_edit = "none" ; }
+
+	$user_is_zone_owner = verify_user_is_owner_zoneid($record['zid']);
+	$zone_type = get_domain_type($record['zid']);
+
+	if ( $zone_type == "SLAVE" || $perm_content_edit == "none" || $perm_content_edit == "own" && $user_is_zone_owner == "0" ) {
+		return _("You are not allowed to edit this record.") ; 
+	} else {
+		if($record['content'] == "") {
+			return _("Error: content field may not be empty.") ; 
+		}
+		global $db;
+		// TODO: no need to check for numeric-ness of zone id if we check with validate_input as well?
+		if (is_numeric($record['zid'])) {
+			validate_input($record['zid'], $record['type'], $record['content'], $record['name'], $record['prio'], $record['ttl']);
+			$query = "UPDATE records 
+					SET name=".$db->quote($record['name']).", 
+					type=".$db->quote($record['type']).", 
+					content=".$db->quote($record['content']).", 
+					ttl=".$db->quote($record['ttl']).", 
+					prio=".$db->quote($record['prio']).", 
+					change_date=".$db->quote(time())." 
+					WHERE id=".$db->quote($record['rid']);
+			$result = $db->Query($query);
+			if (PEAR::isError($result)) {
+				error($result->getMessage());
+				return false;
+			} elseif ($record['type'] != 'SOA') {
+				update_soa_serial($record['zid']);
+			}
+			return true;
+		}
+		else
+		{
+			// TODO change to error style as above (returning directly)
+			error(sprintf(ERR_INV_ARGC, "edit_record", "no zoneid given"));
+		}
 	}
-	if (is_numeric($zoneid))
-	{
-		validate_input($zoneid, $type, $content, $name, $prio, $ttl);
-                $change = time();
-                $db->query("UPDATE records set name=".$db->quote($name).", type=".$db->quote($type).", content=".$db->quote($content).", ttl=".$db->quote($ttl).", prio=".$db->quote($prio).", change_date=".$db->quote($change)." WHERE id=".$db->quote($recordid));
-		
-		/*
-		 * Added by DeViCeD - Update SOA Serial number
-		 * There should be more checks
-		 */
-		if ($type != 'SOA')
-		{
-			update_soa_serial($zoneid);
-		}
-		return true;
-	}
-	else
-	{
-		error(sprintf(ERR_INV_ARGC, "edit_record", "no zoneid given"));
-	}
-
+	return true;
 }
 
 
-function add_record_owner($zoneid,$userid,$recordid)
-{
-	global $db;
-	if (!xs($zoneid))
-	{
-		error(ERR_RECORD_ACCESS_DENIED);
-	}
-	if (is_numeric($zoneid) || is_numeric($userid) || is_numeric($recordid))
-	{
-		$db->query("INSERT INTO record_owners (user_id, record_id) VALUES (".$db->quote($userid).", ".$db->quote($recordid).")");
-		return true;
-	}
-	else
-	{
-		error(sprintf(ERR_INV_ARGC, "add_record_owner", "at least one of the arguments is not numeric"));
-	}
-}
-
-function delete_record_owner($zoneid,$rowid,$recordid)
-{
-	global $db;
-	if (!xs($zoneid))
-	{
-		error(ERR_RECORD_ACCESS_DENIED);
-	}
-	if (is_numeric($zoneid) || is_numeric($rowid) || is_numeric($recordid))
-	{
-		$db->query("DELETE FROM record_owners WHERE id=".$db->quote($rowid)." AND record_id=".$db->quote($recordid));
-		return true;
-	}
-	else
-	{
-		error(sprintf(ERR_INV_ARGC, "delete_record_owner", "at least one of the arguments is not numeric"));
-	}
-}
-
 /*
  * Adds a record.
  * This function validates it if correct it inserts it into the database.
  * return values: true if succesful.
  */
-function add_record($zoneid, $name, $type, $content, $ttl, $prio)
-{
-
+function add_record($zoneid, $name, $type, $content, $ttl, $prio) {
 	global $db;
-	if (!xs($zoneid))
-	{
-		error(ERR_RECORD_ACCESS_DENIED);
-	}
-	if (is_numeric($zoneid))
-	{
-		// Check the user input.
-		validate_input($zoneid, $type, $content, $name, $prio, $ttl);
+
+	if (verify_permission(zone_content_edit_others)) { $perm_content_edit = "all" ; }
+	elseif (verify_permission(zone_content_edit_own)) { $perm_content_edit = "own" ; }
+	else { $perm_content_edit = "none" ; }
+
+	$user_is_zone_owner = verify_user_is_owner_zoneid($zoneid);
+	$zone_type = get_domain_type($zoneid);
 
-		// Generate new timestamp for the daemon
-		$change = time();
-		
-		// Execute query.
-		$db->query("INSERT INTO records (domain_id, name, type, content, ttl, prio, change_date) VALUES (".$db->quote($zoneid).", ".$db->quote($name).", ".$db->quote($type).", ".$db->quote($content).", ".$db->quote($ttl).", ".$db->quote($prio).", ".$db->quote($change).")");
-		if ($type != 'SOA')
-		{
-			update_soa_serial($zoneid);
+        if ( $zone_type == "SLAVE" || $perm_content_edit == "none" || $perm_content_edit == "own" && $user_is_zone_owner == "0" ) {
+		error(ERR_PERM_ADD_RECORD);
+		return false;
+	} else {
+		if (validate_input($zoneid, $type, $content, $name, $prio, $ttl) ) {
+			$change = time();
+			$query = "INSERT INTO records VALUES ('',"
+						. $db->quote($zoneid) . ","
+						. $db->quote($name) . "," 
+						. $db->quote($type) . "," 
+						. $db->quote($content) . ","
+						. $db->quote($ttl) . ","
+						. $db->quote($prio) . ","
+						. $db->quote($change) . ")";
+			$response = $db->query($query);
+			if (PEAR::isError($response)) {
+				error($response->getMessage());
+				return false;
+			} else {
+				if ($type != 'SOA') { update_soa_serial($zoneid); }
+				return true;
+			}
+		} else {
+			return false;
 		}
 		return true;
 	}
-	else
-	{
-		error(sprintf(ERR_INV_ARG, "add_record"));
-	}
 }
 
 
 function add_supermaster($master_ip, $ns_name, $account)
 {
         global $db;
-        if (!is_valid_ip($master_ip) && !is_valid_ip6($master_ip))
-        {
-                error(sprintf(ERR_INV_ARGC, "add_supermaster", "No or no valid ipv4 or ipv6 address given."));
+        if (!is_valid_ip($master_ip) && !is_valid_ip6($master_ip)) {
+                error(ERR_DNS_IP);
+		return false;
         }
-        if (!is_valid_hostname($ns_name))
-        {
+        if (!is_valid_hostname($ns_name)) {
                 error(ERR_DNS_HOSTNAME);
+		return false;
         }
-	if (!validate_account($account))
-	{
+	if (!validate_account($account)) {
 		error(sprintf(ERR_INV_ARGC, "add_supermaster", "given account name is invalid (alpha chars only)"));
+		return false;
 	}
-        if (supermaster_exists($master_ip))
-        {
-                error(sprintf(ERR_INV_ARGC, "add_supermaster", "supermaster already exists"));
-        }
-        else
-        {
+        if (supermaster_exists($master_ip)) {
+                error(ERR_SM_EXISTS);
+		return false;
+        } else {
                 $db->query("INSERT INTO supermasters VALUES (".$db->quote($master_ip).", ".$db->quote($ns_name).", ".$db->quote($account).")");
                 return true;
         }
 }
 
-function delete_supermaster($master_ip)
-{
-        global $db;
-        if (!level(5))
-        {
-                error(ERR_LEVEL_5);
-        }
+function delete_supermaster($master_ip) {
+	global $db;
         if (is_valid_ip($master_ip) || is_valid_ip6($master_ip))
         {
                 $db->query("DELETE FROM supermasters WHERE ip = ".$db->quote($master_ip));
@@ -267,10 +216,6 @@
 function get_supermaster_info_from_ip($master_ip)
 {
 	global $db;
-        if (!level(5))
-        {
-                error(ERR_LEVEL_5);
-        }
         if (is_valid_ip($master_ip) || is_valid_ip6($master_ip))
 	{
 	        $result = $db->queryRow("SELECT ip,nameserver,account FROM supermasters WHERE ip = ".$db->quote($master_ip));
@@ -289,48 +234,57 @@
         }
 }
 
+function get_record_details_from_record_id($rid) {
+
+	global $db;
+
+	$query = "SELECT * FROM records WHERE id = " . $db->quote($rid) ;
+
+	$response = $db->query($query);
+	if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+
+	while ($r = $response->fetchRow()) {
+		$return[] = array(
+			"rid"		=>	$r['id'],
+			"zid"		=>	$r['domain_id'],
+			"name"		=>	$r['name'],
+			"type"		=>	$r['type'],
+			"content"	=>	$r['content'],
+			"ttl"		=>	$r['ttl'],
+			"prio"		=>	$r['prio'],
+			"change_date"	=>	$r['change_date']);
+	}
+	return $return;
+}
 
 /*
  * Delete a record by a given id.
  * return values: true, this function is always succesful.
  */
-function delete_record($id)
+function delete_record($rid)
 {
 	global $db;
 
-	// Check if the user has access.
-	if (!xs(recid_to_domid($id)))
-	{
-		error(ERR_RECORD_ACCESS_DENIED);
-	}
+	if (verify_permission(zone_content_edit_others)) { $perm_content_edit = "all" ; } 
+	elseif (verify_permission(zone_content_edit_own)) { $perm_content_edit = "own" ; } 
+	else { $perm_content_edit = "none" ; }
 
-	// Retrieve the type of record to see if we can actually remove it.
-	$recordtype = get_recordtype_from_id($id);
+	// Determine ID of zone first.
+	$record = get_record_details_from_record_id($rid);
+	$user_is_zone_owner = verify_user_is_owner_zoneid($record['zid']);
 
-	// If the record type is NS and the user tries to delete it while ALLOW_NS_EDIT is set to 0
-	// OR
-	// check if the name of the record isnt the domain name (if so it should delete all records)
-	// OR
-	// check if we are dealing with a SOA field (same story as NS)
-	if (($recordtype == "NS" && $GLOBALS["ALLOW_NS_EDIT"] != 1 && (get_name_from_record_id($id) == get_domain_name_from_id(recid_to_domid($id)))) || ($recordtype == "SOA" && $GLOBALS["ALLOW_SOA_EDIT"] != 1))
-	{
-		error(sprintf(ERR_RECORD_DELETE_TYPE_DENIED, $recordtype));
-
-	}
-	if (is_numeric($id))
-	{
-	    $did = recid_to_domid($id);
-		$db->query('DELETE FROM records WHERE id=' . $db->quote($id) );
-		if ($type != 'SOA')
-		{
-			update_soa_serial($did);
+	if ( $perm_content_edit == "all" || ($perm_content_edit == "own" && $user_is_zone_owner == "0" )) {
+		if ($record['type'] == "SOA") {
+			error(_('You are trying to delete the SOA record. If are not allowed to remove it, unless you remove the entire zone.'));
+		} else {
+			$quote = "DELETE FROM records WHERE id = " . $db->quote($rid);
+			$response = $db->query($query);
+			if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+			return true;
 		}
-        // $id doesnt exist in database anymore so its deleted or just not there which means "true"	
-		return true;
-	}
-	else
-	{
-		error(sprintf(ERR_INV_ARG, "delete_record"));
+	} else {
+		error(ERR_PERM_DEL_RECORD);
+		return false;
 	}
 }
 
@@ -348,104 +302,87 @@
  */
 function add_domain($domain, $owner, $webip, $mailip, $empty, $type, $slave_master)
 {
+	if(verify_permission(zone_master_add)) { $zone_master_add = "1" ; } ;
+	if(verify_permission(zone_slave_add)) { $zone_slave_add = "1" ; } ;
 
-	global $db;
+	// TODO: make sure only one is possible if only one is enabled
+	if($zone_master_add == "1" || $zone_master_add == "1") {
 
-	if (!level(5))
-	{
-		error(ERR_LEVEL_5);
-	}
+		global $db;
+		if (($domain && $owner && $webip && $mailip) || 
+				($empty && $owner && $domain) || 
+				(eregi('in-addr.arpa', $domain) && $owner) || 
+				$type=="SLAVE" && $domain && $owner && $slave_master) {
+
+			$response = $db->query("INSERT INTO domains (name, type) VALUES (".$db->quote($domain).", ".$db->quote($type).")");
+			if (PEAR::isError($response)) { error($response->getMessage()); return false; }
 
-	// If domain, owner and mailip are given
-	// OR
-	// empty is given and owner and domain
-	// OR
-	// the domain is an arpa record and owner is given
-	// OR
-	// the type is slave, domain, owner and slave_master are given
-	// THAN
-	// Continue this function
-	if (($domain && $owner && $webip && $mailip) || ($empty && $owner && $domain) || (eregi('in-addr.arpa', $domain) && $owner) || $type=="SLAVE" && $domain && $owner && $slave_master)
-	{
-                // First insert zone into domain table
-                $db->query("INSERT INTO domains (name, type) VALUES (".$db->quote($domain).", ".$db->quote($type).")");
+			$domain_id = $db->lastInsertId('domains', 'id');
+			if (PEAR::isError($domain_id)) { error($id->getMessage()); return false; }
+
+			$response = $db->query("INSERT INTO zones (domain_id, owner) VALUES (".$db->quote($domain_id).", ".$db->quote($owner).")");
+			if (PEAR::isError($response)) { error($response->getMessage()); return false; }
 
-                // Determine id of insert zone (in other words, find domain_id)
-                $iddomain = $db->lastInsertId('domains', 'id');
-                if (PEAR::isError($iddomain)) {
-                        die($id->getMessage());
-                }
-
-                // Second, insert into zones tables
-                $db->query("INSERT INTO zones (domain_id, owner) VALUES (".$db->quote($iddomain).", ".$db->quote($owner).")");
-
-		if ($type == "SLAVE")
-		{
-			$db->query("UPDATE domains SET master = ".$db->quote($slave_master)." WHERE id = ".$db->quote($iddomain));
-			
-			// Done
-			return true;
-		}
-		else
-		{
-			// Generate new timestamp. We need this one anyhow.
-			$now = time();
+			if ($type == "SLAVE") {
+				$response = $db->query("UPDATE domains SET master = ".$db->quote($slave_master)." WHERE id = ".$db->quote($domain_id));
+				if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+				return true;
+			} else {
+				$now = time();
+				if ($empty && $domain_id) {
+					$ns1 = $GLOBALS['NS1'];
+					$hm  = $GLOBALS['HOSTMASTER'];
+					$ttl = $GLOBALS['DEFAULT_TTL'];
 
-			if ($empty && $iddomain)
-			{
-				// If we come into this if statement we dont want to apply templates.
-				// Retrieve configuration settings.
-				$ns1 = $GLOBALS["NS1"];
-				$hm  = $GLOBALS["HOSTMASTER"];
-				$ttl = $GLOBALS["DEFAULT_TTL"];
+					$query = "INSERT INTO records VALUES (''," 
+							. $db->quote($domain_id) . "," 
+							. $db->quote($domain) . "," 
+							. $db->quote($ns1.' '.$hm.' 1') 
+							. ",'SOA',"
+							. $db->quote($ttl) 
+							. ", 0, "
+							. $db->quote($now).")";
+					$response = $db->query($query);
+					if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+				} elseif ($domain_id) {
+					global $template;
 
-				// Build and execute query
-				$sql = "INSERT INTO records (domain_id, name, content, type, ttl, prio, change_date) VALUES (".$db->quote($iddomain).", ".$db->quote($domain).", ".$db->quote($ns1.' '.$hm.' 1').", 'SOA', ".$db->quote($ttl).", 0, ".$db->quote($now).")";
-				$db->query($sql);
-
-				// Done
-				return true;
-			}
-			elseif ($iddomain)
-			{
-				// If we are here we want to apply templates.
-				global $template;
+					foreach ($template as $r) {
+						if ((eregi('in-addr.arpa', $domain) && ($r["type"] == "NS" || $r["type"] == "SOA")) || (!eregi('in-addr.arpa', $domain)))
+						{
+							$name     = parse_template_value($r["name"], $domain, $webip, $mailip);
+							$type     = $r["type"];
+							$content  = parse_template_value($r["content"], $domain, $webip, $mailip);
+							$ttl      = $r["ttl"];
+							$prio     = intval($r["prio"]);
 
-				// Iterate over the template and apply it for each field.
-				foreach ($template as $r)
-				{
-					// Same type of if statement as previous.
-					if ((eregi('in-addr.arpa', $domain) && ($r["type"] == "NS" || $r["type"] == "SOA")) || (!eregi('in-addr.arpa', $domain)))
-					{
-						// Parse the template.
-						$name     = parse_template_value($r["name"], $domain, $webip, $mailip);
-						$type     = $r["type"];
-						$content  = parse_template_value($r["content"], $domain, $webip, $mailip);
-						$ttl      = $r["ttl"];
-						$prio     = intval($r["prio"]);
+							if (!$ttl) {
+								$ttl = $GLOBALS["DEFAULT_TTL"];
+							}
 
-						// If no ttl is given, use the default.
-						if (!$ttl)
-						{
-							$ttl = $GLOBALS["DEFAULT_TTL"];
+							$query = "INSERT INTO records VALUES (''," 
+									. $db->quote($domain_id) . ","
+									. $db->quote($name) . ","
+									. $db->quote($content) . ","
+									. $db->quote($type) . ","
+									. $db->quote($ttl) . ","
+									. $db->quote($prio) . ","
+									. $db->quote($now) . ")";
+							$response = $db->query($query);
+							if (PEAR::isError($response)) { error($response->getMessage()); return false; }
 						}
-
-						$sql = "INSERT INTO records (domain_id, name, content, type, ttl, prio, change_date) VALUES (".$db->quote($iddomain).", ".$db->quote($name).", ".$db->quote($content).", ".$db->quote($type).", ".$db->quote($ttl).", ".$db->quote($prio).", ".$db->quote($now).")";
-						$db->query($sql);
 					}
-				}
-				// All done.
-				return true;
-			 }
-			 else
-			 {
-				error(sprintf(ERR_INV_ARGC, "add_domain", "could not create zone"));
-			 }
+					return true;
+				 } else {
+					error(sprintf(ERR_INV_ARGC, "add_domain", "could not create zone"));
+				 }
+			}
+		} else {
+			error(sprintf(ERR_INV_ARG, "add_domain"));
 		}
-	}
-	else
-	{
-		error(sprintf(ERR_INV_ARG, "add_domain"));
+	} else {
+		error(ERR_PERM_ADD_ZONE_MASTER);
+		return false;
 	}
 }
 
@@ -458,24 +395,23 @@
 {
 	global $db;
 
-	if (!level(5))
-	{
-		error(ERR_LEVEL_5);
-	}
+	if (verify_permission(zone_content_edit_others)) { $perm_edit = "all" ; }
+	elseif (verify_permission(zone_content_edit_own)) { $perm_edit = "own" ; }
+	else { $perm_edit = "none" ; }
+	$user_is_zone_owner = verify_user_is_owner_zoneid($id);
 
-	// See if the ID is numeric.
-	if (is_numeric($id))
-	{
-		$db->query("DELETE FROM zones WHERE domain_id=".$db->quote($id));
-		$db->query("DELETE FROM domains WHERE id=".$db->quote($id));
-		$db->query("DELETE FROM records WHERE domain_id=".$db->quote($id));
-		// Nothing in the database. If the delete deleted 0 records it means the id is just not there.
-		// therefore the is no need to check the affectedRows values.
-		return true;
-	}
-	else
-	{
-		error(sprintf(ERR_INV_ARGC, "delete_domain", "id must be a number"));
+        if ( $perm_edit == "all" || ( $perm_edit == "own" && $user_is_zone_owner == "1") ) {    
+		if (is_numeric($id)) {
+			$db->query("DELETE FROM zones WHERE domain_id=".$db->quote($id));
+			$db->query("DELETE FROM domains WHERE id=".$db->quote($id));
+			$db->query("DELETE FROM records WHERE domain_id=".$db->quote($id));
+			return true;
+		} else {
+			error(sprintf(ERR_INV_ARGC, "delete_domain", "id must be a number"));
+			return false;
+		}
+	} else {
+		error(ERR_PERM_DEL_ZONE);
 	}
 }
 
@@ -501,93 +437,50 @@
 
 
 /*
- * Sorts a zone by records.
- * return values: the sorted zone.
- */
-function sort_zone($records)
-{
-	$ar_so = array();
-	$ar_ns = array();
-	$ar_mx = array();
-	$ar_mb = array();
-	$ar_ur = array();
-	$ar_ov = array();
-	foreach ($records as $c)
-	{
-		switch(strtoupper($c['type']))
-		{
-			case "SOA":
-				$ar_so[] = $c;
-				break;
-			case "NS":
-				$ar_ns[] = $c;
-				break;
-			case "MX":
-				$ar_mx[] = $c;
-				break;
-			case "MBOXFW":
-				$ar_mb[] = $c;
-				break;
-			case "URL":
-				$ar_ur[] = $c;
-				break;
-			default:
-				$ar_ov[] = $c;
-				break;
-		}
-	}
-
-	$res = array_merge($ar_so, $ar_ns, $ar_mx, $ar_mb, $ar_ur, $ar_ov);
-
-	if (count($records) == count($res))
-	{
-		$records = $res;
-	}
-	else
-	{
-		error(sprintf(ERR_INV_ARGC, "sort_zone", "records sorting failed!"));
-	}
-	return $records;
-}
-
-
-/*
  * Change owner of a domain.
- * Function should actually be in users.inc.php. But its more of a record modification than a user modification
  * return values: true when succesful.
  */
-function add_owner($domain, $newowner)
+function add_owner_to_zone($zone_id, $user_id)
 {
 	global $db;
-
-	if (!level(5))
-	{
-		error(ERR_LEVEL_5);
-	}
-
-	if (is_numeric($domain) && is_numeric($newowner) && is_valid_user($newowner))
-	{
-		if($db->queryOne("SELECT COUNT(id) FROM zones WHERE owner=".$db->quote($newowner)." AND domain_id=".$db->quote($domain)) == 0)
+	if ( (verify_permission(zone_meta_edit_others)) || (verify_permission(zone_meta_edit_own)) && verify_user_is_owner_zoneid($_GET["id"])) {
+		// User is allowed to make change to meta data of this zone.
+		if (is_numeric($zone_id) && is_numeric($user_id) && is_valid_user($user_id))
 		{
-			$db->query("INSERT INTO zones (domain_id, owner) VALUES(".$db->quote($domain).", ".$db->quote($newowner).")");
+			if($db->queryOne("SELECT COUNT(id) FROM zones WHERE owner=".$db->quote($user_id)." AND domain_id=".$db->quote($zone_id)) == 0)
+			{
+				$db->query("INSERT INTO zones (domain_id, owner) VALUES(".$db->quote($zone_id).", ".$db->quote($user_id).")");
+			}
+			return true;
+		} else {
+			error(sprintf(ERR_INV_ARGC, "add_owner_to_zone", "$zone_id / $user_id"));
 		}
-		return true;
-	}
-	else
-	{
-		error(sprintf(ERR_INV_ARGC, "change_owner", "$domain / $newowner"));
+	} else {
+		return false;
 	}
 }
 
 
-function delete_owner($domain, $owner)
+function delete_owner_from_zone($zone_id, $user_id)
 {
 	global $db;
-	if($db->queryOne("SELECT COUNT(id) FROM zones WHERE owner=".$db->quote($owner)." AND domain_id=".$db->quote($domain)) != 0)
-	{
-		$db->query("DELETE FROM zones WHERE owner=".$db->quote($owner)." AND domain_id=".$db->quote($domain));
+	if ( (verify_permission(zone_meta_edit_others)) || (verify_permission(zone_meta_edit_own)) && verify_user_is_owner_zoneid($_GET["id"])) {
+		// User is allowed to make change to meta data of this zone.
+		if (is_numeric($zone_id) && is_numeric($user_id) && is_valid_user($user_id))
+		{
+			// TODO: Next if() required, why not just execute DELETE query?
+			if($db->queryOne("SELECT COUNT(id) FROM zones WHERE owner=".$db->quote($user_id)." AND domain_id=".$db->quote($zone_id)) != 0)
+			{
+				$db->query("DELETE FROM zones WHERE owner=".$db->quote($user_id)." AND domain_id=".$db->quote($zone_id));
+			}
+			return true;
+		} else {
+			error(sprintf(ERR_INV_ARGC, "delete_owner_from_zone", "$zone_id / $user_id"));
+		}
+	} else {
+		return false;
 	}
-	return true;
+	
 }
 
 /*
@@ -653,130 +546,37 @@
 function get_name_from_record_id($id)
 {
 	global $db;
-	if (is_numeric($id))
-	{
+	if (is_numeric($id)) {
 		$result = $db->query("SELECT name FROM records WHERE id=".$db->quote($id));
 		$r = $result->fetchRow();
 		return $r["name"];
-	}
-	else
-	{
+	} else {
 		error(sprintf(ERR_INV_ARG, "get_name_from_record_id"));
 	}
 }
 
 
 /*
- * Get all the domains from a database of which the user is the owner.
- * return values: an array with the id of the domain and its name.
- */
-function get_domains_from_userid($id)
-{
-	global $db;
-	if (is_numeric($id))
-	{
-		$a_zones = array();
-
-		// Check for zones the user has full access for (the 
-		// user is owner of the zone.
-
-		$res_full = $db->query("SELECT 
-					domains.id AS domain_id, 
-					domains.name AS name 
-					FROM domains 
-					LEFT JOIN zones ON domains.id=zones.domain_id 
-					WHERE owner=".$db->quote($id)); 
-		
-		// Process the output.
-
-		$numrows = $res_full->numRows();
-		$i=1;
-		if ($numrows > 0) 
-		{
-			$andnot=" AND NOT domains.id IN (";
-			while($r = $res_full->fetchRow()) {
-				
-				// Create array of zone id's and name's the owner
-				// has full access to.
-
-				$a_zones[] = array(
-				"id"            =>              $r["domain_id"],
-				"name"          =>              $r["name"],
-				"partial"	=>		"0"
-				);
-
-				// Create AND NOT for query of zones the user has 
-				// only partial access to. In that query we just 
-				// want to see the zones he has not full access to 
-				// as well.
-
-				$andnot.=$db->quote($r["domain_id"]);
-				if ($i < $numrows) {
-					$andnot.=",";
-					$i++;
-				}
-
-			}
-			$andnot.=")";
-		}
-		else
-		{
-			$andnot="";
-		}
-
-		// Check for zones the user has partial access only to.
-
-		$res_partial = $db->query("SELECT DISTINCT 
-					records.domain_id, 
-					domains.name 
-					FROM records, record_owners, domains 
-					WHERE record_owners.user_id = ".$db->quote($id)." 
-					AND records.id = record_owners.record_id 
-					AND domains.id = records.domain_id
-					".$andnot);
-		
-		// Add these zones to the array as well.
-
-		while ($r = $res_partial->fetchRow())
-		{
-			$a_zones[] = array(
-			"id"            =>              $r["domain_id"],
-			"name"          =>              $r["name"],
-			"partial"	=>		"1"
-			);
-		}
-
-		return $a_zones;
-	}
-	else
-	{
-		error(sprintf(ERR_INV_ARGC, "get_domains_from_userid", "This is not a valid userid: $id"));
-	}
-}
-
-
-/*
  * Get domain name from a given id
  * return values: the name of the domain associated with the id.
  */
 function get_domain_name_from_id($id)
 {
 	global $db;
-	if (!xs($id))
-	{
-		error(ERR_RECORD_ACCESS_DENIED);
-	}
+
 	if (is_numeric($id))
 	{
 		$result = $db->query("SELECT name FROM domains WHERE id=".$db->quote($id));
-		if ($result->numRows() == 1)
-		{
+		$rows = $result->numRows() ;
+		if ($rows == 1) {
  			$r = $result->fetchRow();
  			return $r["name"];
-		}
-		else
-		{
+		} elseif ($rows == "0") {
+			error(sprintf("Zone does not exist."));
+			return false;
+		} else {
 	 		error(sprintf(ERR_INV_ARGC, "get_domain_name_from_id", "more than one domain found?! whaaa! BAD! BAD! Contact admin!"));
+			return false;
 		}
 	}
 	else
@@ -785,86 +585,34 @@
 	}
 }
 
-
-/*
- * Get information about a domain name from a given domain id.
- * the function looks up the domainname, the owner of the domain and the number of records in it.
- * return values: an array containing the information.
- */
-function get_domain_info_from_id($id)
-{
-	global $db;
-	if (!xs($id))
-	{
-		error(ERR_RECORD_ACCESS_DENIED);
-	}
-	if (is_numeric($id))
-	{
+function get_zone_info_from_id($zone_id) {
 
-	if ($_SESSION[$id."_ispartial"] == 1) {
-	
-	$sqlq = "SELECT 
-	domains.type AS type,
-	domains.name AS name,
-	users.fullname AS owner,
-	count(record_owners.id) AS aantal
-	FROM domains, users, record_owners, records
-	
-        WHERE record_owners.user_id = ".$db->quote($_SESSION["userid"])."
-        AND record_owners.record_id = records.id
-	AND records.domain_id = ".$db->quote($id)."
+	if (verify_permission(zone_content_view_others)) { $perm_view = "all" ; } 
+	elseif (verify_permission(zone_content_view_own)) { $perm_view = "own" ; }
+	else { $perm_view = "none" ;}
 
-	GROUP BY domains.name, owner, users.fullname, domains.type
-	ORDER BY domains.name";
-	
-	$result = $db->queryRow($sqlq);
+	if ($perm_view == "none") { 
+		error(ERR_PERM_VIEW_ZONE);
+	} else {
+		global $db;
 
-	$ret = array(
-	"name"          =>              $result["name"],
-	"ownerid"       =>              $_SESSION["userid"],
-	"owner"         =>              $result["owner"],
-	"type"		=>		$result["type"],
-	"numrec"        =>              $result["aantal"]
-	);
-
-	return $ret;
+		$query = "SELECT 	domains.type AS type, 
+					domains.name AS name, 
+					domains.master AS master_ip,
+					count(records.domain_id) AS record_count
+					FROM domains, records 
+					WHERE domains.id = " . $db->quote($zone_id) . "
+					AND domains.id = records.domain_id 
+					GROUP BY domains.id";
 
-	} else{
-	
-		// Query that retrieves the information we need.
-		$sqlq = "SELECT 
-			domains.type AS type,
-			domains.name AS name,
-			min(zones.owner) AS ownerid,
-			users.fullname AS owner,
-			count(records.domain_id) AS aantal
-			FROM domains
-			LEFT JOIN records ON domains.id=records.domain_id
-			LEFT JOIN zones ON domains.id=zones.domain_id
-			LEFT JOIN users ON zones.owner=users.id
-			WHERE domains.id=$id
-			GROUP BY domains.name, owner, users.fullname, domains.type, zones.id
-			ORDER BY zones.id";
-
-		// Put the first occurence in an array and return it.
-		$result = $db->queryRow($sqlq);
-
-		//$result["ownerid"] = ($result["ownerid"] == NULL) ? $db->queryOne("select min(id) from users where users.level=10") : $result["ownerid"];
-
-		$ret = array(
-		"name"          =>              $result["name"],
-		"ownerid"       =>              $result["ownerid"],
-		"owner"         =>              $result["owner"],
-		"type"          =>              $result["type"],
-		"numrec"        =>              $result["aantal"]
-		);
-		return $ret;
-	}
-
-	}
-	else
-	{
-		error(sprintf(ERR_INV_ARGC, "get_domain_num_records_from_id", "This is not a valid domainid: $id"));
+		$response = $db->queryRow($query);
+		if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+		$return = array(
+			"name"		=>	$response['name'],
+			"type"		=>	$response['type'],
+			"master_ip"	=>	$response['master_ip'],
+			"record_count"	=>	$response['record_count']);
+		return $return;
 	}
 }
 
@@ -877,24 +625,14 @@
 {
 	global $db;
 
-	if (!level(5))
-	{
-		error(ERR_LEVEL_5);
-	}
-	if (is_valid_domain($domain))
-	{
+	if (is_valid_domain($domain)) {
 		$result = $db->query("SELECT id FROM domains WHERE name=".$db->quote($domain));
-		if ($result->numRows() == 0)
-		{
+		if ($result->numRows() == 0) {
 			return false;
-		}
-		elseif ($result->numRows() >= 1)
-		{
+		} elseif ($result->numRows() >= 1) {
 			return true;
 		}
-	}
-	else
-	{
+	} else {
 		error(ERR_DOMAIN_INVALID);
 	}
 }
@@ -902,17 +640,16 @@
 function get_supermasters()
 {
         global $db;
-        $result = $db->query("SELECT ip, nameserver, account FROM supermasters");
+        
+	$result = $db->query("SELECT ip, nameserver, account FROM supermasters");
+	if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+
         $ret = array();
 
-        if($result->numRows() == 0)
-        {
+        if($result->numRows() == 0) {
                 return -1;
-        }
-        else
-        {
-                while ($r = $result->fetchRow())
-                {
+        } else {
+                while ($r = $result->fetchRow()) {
                         $ret[] = array(
                         "master_ip"     => $r["ip"],
                         "ns_name"       => $r["nameserver"],
@@ -926,10 +663,6 @@
 function supermaster_exists($master_ip)
 {
         global $db;
-        if (!level(5))
-        {
-                error(ERR_LEVEL_5);
-        }
         if (is_valid_ip($master_ip) || is_valid_ip6($master_ip))
         {
                 $result = $db->query("SELECT ip FROM supermasters WHERE ip = ".$db->quote($master_ip));
@@ -949,206 +682,92 @@
 }
 
 
-/*
- * Get all domains from the database 
- * This function gets all the domains from the database unless a user id is below 5.
- * if a user id is below 5 this function will only retrieve records for that user.
- * return values: the array of domains or -1 if nothing is found.
- */
-function get_domains($userid=true,$letterstart='all',$rowstart=0,$rowamount=999999)
+function get_zones($perm,$userid=0,$letterstart=all,$rowstart=0,$rowamount=999999) 
 {
 	global $db;
 	global $sql_regexp;
-	if((!level(5) || !$userid) && !level(10) && !level(5))
-	{
-		$add = " AND zones.owner=".$db->quote($_SESSION["userid"]);
+	if ($perm != "own" && $perm != "all") {
+		error(ERR_PERM_VIEW_ZONE);
+		return false;
 	}
 	else
 	{
-		$add = "";
+		if ($perm == "own") {
+			$sql_add = " AND zones.domain_id = domains.id
+				AND zones.owner = ".$db->quote($userid);
+		}
+		if ($letterstart!=all && $letterstart!=1) {
+			$sql_add .=" AND domains.name LIKE ".$db->quote($letterstart."%")." ";
+		} elseif ($letterstart==1) {
+			$sql_add .=" AND substring(domains.name,1,1) ".$sql_regexp." '^[[:digit:]]'";
+		}
 	}
-
-	$sqlq = "SELECT domains.id AS domain_id,
-	min(zones.owner) AS owner,
-	count(DISTINCT records.id) AS aantal,
-	domains.name AS domainname
-	FROM domains
-	LEFT JOIN zones ON domains.id=zones.domain_id 
-	LEFT JOIN records ON records.domain_id=domains.id
-	WHERE 1=1 $add ";
-	if ($letterstart!='all' && $letterstart!=1) {
-	   $sqlq.=" AND substring(domains.name,1,1) ".$sql_regexp." ".$db->quote("^".$letterstart);
-	} elseif ($letterstart==1) {
-	   $sqlq.=" AND substring(domains.name,1,1) ".$sql_regexp." '^[[:digit:]]'";
-	}
-	$sqlq.=" GROUP BY domainname, domains.id
-	ORDER BY domainname";
-
+	
+	$sqlq = "SELECT domains.id, 
+			domains.name,
+			domains.type,
+			COUNT(DISTINCT records.id) AS count_records
+			FROM domains
+			LEFT JOIN zones ON domains.id=zones.domain_id 
+			LEFT JOIN records ON records.domain_id=domains.id
+			WHERE 1=1".$sql_add." 
+			GROUP BY domains.name, domains.id
+			ORDER BY domains.name";
+	
 	$db->setLimit($rowamount, $rowstart);
 	$result = $db->query($sqlq);
-	// Set limit needs to be called before each query
-	$db->setLimit($rowamount, $rowstart);
-	$result2 = $db->query($sqlq); 
-	
-	$numrows = $result2->numRows();
-	$i=1;
-	if ($numrows > 0) {
-		$andnot=" AND NOT domains.id IN (";
-		while($r = $result2->fetchRow()) {
-			$andnot.=$db->quote($r["domain_id"]);
-			if ($i < $numrows) {
-				$andnot.=",";
-				$i++;
-			}
-		}
-		$andnot.=")";
-	}
-	else
-	{
-		$andnot="";
-	}
-
-	if ($letterstart!='all' && $letterstart!=1) {
-
-		$sqlq = "SELECT domains.id AS domain_id,
-		count(DISTINCT record_owners.record_id) AS aantal,
-		domains.name AS domainname
-		FROM domains, record_owners,records, zones
-		WHERE record_owners.user_id = ".$db->quote($_SESSION["userid"])."
-		AND (records.id = record_owners.record_id
-		AND domains.id = records.domain_id)
-		$andnot 
-		AND domains.name LIKE ".$db->quote($letterstart."%")." 
-		AND (zones.domain_id != records.domain_id AND zones.owner!=".$db->quote($_SESSION["userid"]).")
-		GROUP BY domainname, domains.id
-		ORDER BY domainname";
-
-		$result_extra = $db->query($sqlq);
-
-	} else {
-
-		$sqlq = "SELECT domains.id AS domain_id,
-		count(DISTINCT record_owners.record_id) AS aantal,
-		domains.name AS domainname
-		FROM domains, record_owners,records, zones
-		WHERE record_owners.user_id = ".$db->quote($_SESSION["userid"])."
-		AND (records.id = record_owners.record_id
-		AND domains.id = records.domain_id)
-		$andnot";
-		if ($letterstart != 'all') { 
-			$sqlq .= " AND substring(domains.name,1,1) ".$sql_regexp." '^[[:digit:]]'";
-		}
-		$sqlq .= "AND (zones.domain_id != records.domain_id AND zones.owner!=".$db->quote($_SESSION["userid"]).")
-		GROUP BY domainname, domains.id
-		ORDER BY domainname";
-
-		$result_extra[$i] = $db->query($sqlq);
-
-	}
 
 	while($r = $result->fetchRow())
 	{
-		$r["owner"] = ($r["owner"] == NULL) ? $db->queryOne("select min(id) from users where users.level=10") : $r["owner"];
-	     	$ret[$r["domainname"]] = array(
-		"name"          =>              $r["domainname"],
-		"id"            =>              $r["domain_id"],
-		"owner"         =>              $r["owner"],
-		"numrec"        =>              $r["aantal"]
-		);
+		$ret[$r["name"]] = array(
+		"id"		=>	$r["id"],
+		"name"		=>	$r["name"],
+		"type"		=>	$r["type"],
+		"count_records"	=>	$r["count_records"]
+		);	
 	}
-
-
-	if ($letterstart!='all' && $letterstart!=1) {
-
-		while($r = $result_extra->fetchRow())
-		{
-		       $ret[$r["domainname"]] = array(
-		       "name"          =>              $r["domainname"]."*",
-		       "id"            =>              $r["domain_id"],
-		       "owner"         =>              $_SESSION["userid"],
-		       "numrec"        =>              $r["aantal"]
-		       );
-		       $_SESSION["partial_".$r["domainname"]] = 1;
-		}
-
-	} else {
-
-		foreach ($result_extra as $result_e) {
-		while($r = $result_e->fetchRow())
-		{
-		       $ret[$r["domainname"]] = array(
-		       "name"          =>              $r["domainname"]."*",
-		       "id"            =>              $r["domain_id"],
-		       "owner"         =>              $_SESSION["userid"],
-		       "numrec"        =>              $r["aantal"]
-		       );
-		       $_SESSION["partial_".$r["domainname"]] = 1;
-		}
-		}
-
-	}
-
-	if (empty($ret)) {
-	   return -1;
-	} else {
-	   sort($ret);
-	   return $ret;
-	}
-
+	return $ret;
 }
 
-
-/*
- * zone_count
- * Does a select query to count how many zones we have in the database
- *
- * @todo: see whether or not it is possible to add the records
- * @param $userid integer The userid of the current user
- * @return integer the number of zones
- */
-
-function zone_count($userid=true, $letterstart='all') {
-        global $db;
+// TODO: letterstart limitation and userid permission limitiation should be applied at the same time?
+function zone_count_ng($perm, $letterstart=all) {
+	global $db;
 	global $sql_regexp;
-        if((!level(5) || !$userid) && !level(10) && !level(5))
-        {
-		// First select the zones for which we have ownership on one or more records.
-		$query = 'SELECT records.domain_id FROM records, record_owners WHERE user_id = '.$db->quote($_SESSION['userid']).' AND records.id = record_owners.record_id';
-		$result = $db->query($query);
-		$zones = array();
-		if (!PEAR::isError($result)) {
-			$zones = $result->fetchCol();
+	if ($perm != "own" && $perm != "all") {
+		$zone_count = "0";
+	} 
+	else 
+	{
+		if ($perm == "own") {
+			$sql_add = " AND zones.domain_id = domains.id
+					AND zones.owner = ".$db->quote($_SESSION['userid']);
+		}
+		if ($letterstart!=all && $letterstart!=1) {
+			$sql_add .=" AND domains.name LIKE ".$db->quote($letterstart."%")." ";
+		} elseif ($letterstart==1) {
+			$sql_add .=" AND substring(domains.name,1,1) ".$sql_regexp." '^[[:digit:]]'";
 		}
-	
-                $add = " AND (zones.owner=".$db->quote($_SESSION["userid"]);
-		if (count($zones) > 0) {
-			$add .= ' OR zones.domain_id IN ('.implode(',', $zones).') '; 
 
-		}
-		$add .= ')';
-        }
-        else
-        {
-                $add = "";
-        }
+		$sqlq = "SELECT COUNT(distinct domains.id) AS count_zones 
+			FROM domains,zones 
+			WHERE 1=1
+			".$sql_add.";";
+
+		$zone_count = $db->queryOne($sqlq);
+	}
+	return $zone_count;
+}
 
-        if ($letterstart!='all' && $letterstart!=1) {
-           $add .=" AND domains.name LIKE ".$db->quote($letterstart."%")." ";
-        } elseif ($letterstart==1) {
-           $add .=" AND substring(domains.name,1,1) ".$sql_regexp." '^[[:digit:]]'";
-        }
+function zone_count_for_uid($uid) {
+	global $db;
+	$query = "SELECT COUNT(domain_id) 
+			FROM zones 
+			WHERE owner = " . $db->quote($uid) . " 
+			ORDER BY domain_id";
+	$zone_count = $db->queryOne($query);
+	return $zone_count;
+}
 
-        if (level(5))
-        {
-                $query = 'SELECT count(distinct domains.id) as zone_count FROM domains WHERE 1=1 '.$add;
-        }
-        else
-        {
-                $query = 'SELECT count(distinct zones.domain_id) as zone_count FROM zones, domains WHERE zones.domain_id = domains.id '.$add;
-        }
-        $numRows = $db->queryOne($query);
-        return $numRows;
-}
 
 /*
  * Get a record from an id.
@@ -1169,15 +788,15 @@
 		{
 			$r = $result->fetchRow();
 			$ret = array(
-			"id"            =>      $r["id"],
-			"domain_id"     =>      $r["domain_id"],
-			"name"          =>      $r["name"],
-			"type"          =>      $r["type"],
-			"content"       =>      $r["content"],
-			"ttl"           =>      $r["ttl"],
-			"prio"          =>      $r["prio"],
-			"change_date"   =>      $r["change_date"]
-			);
+				"id"            =>      $r["id"],
+				"domain_id"     =>      $r["domain_id"],
+				"name"          =>      $r["name"],
+				"type"          =>      $r["type"],
+				"content"       =>      $r["content"],
+				"ttl"           =>      $r["ttl"],
+				"prio"          =>      $r["prio"],
+				"change_date"   =>      $r["change_date"]
+				);
 			return $ret;
 		}
 		else
@@ -1197,58 +816,53 @@
  * Retrieve all fields of the records and send it back to the function caller.
  * return values: the array with information, or -1 is nothing is found.
  */
-function get_records_from_domain_id($id,$rowstart=0,$rowamount=999999)
-{
+function get_records_from_domain_id($id,$rowstart=0,$rowamount=999999) {
 	global $db;
-	if (is_numeric($id))
-	{
+	if (is_numeric($id)) {
 		if ($_SESSION[$id."_ispartial"] == 1) {
-		$db->setLimit($rowamount, $rowstart);
-		$result = $db->query("SELECT record_owners.record_id as id
-		FROM record_owners,domains,records
-		WHERE record_owners.user_id = ".$db->quote($_SESSION["userid"])."
-		AND record_owners.record_id = records.id
-		AND records.domain_id = ".$db->quote($id)."
-		GROUP bY record_owners.record_id");
+			$db->setLimit($rowamount, $rowstart);
+			$result = $db->query("SELECT record_owners.record_id as id
+					FROM record_owners,domains,records
+					WHERE record_owners.user_id = " . $db->quote($_SESSION["userid"]) . "
+					AND record_owners.record_id = records.id
+					AND records.domain_id = " . $db->quote($id) . "
+					GROUP BY record_owners.record_id");
 
-		$ret = array();
-		if($result->numRows() == 0)
-		{
-		return -1;
-		}
-		else
-		{
-		$ret[] = array();
-		$retcount = 0;
-		while($r = $result->fetchRow())
-		{
-		// Call get_record_from_id for each row.
-		$ret[$retcount] = get_record_from_id($r["id"]);
-		$retcount++;
-		}
-		return $ret;
-		}
+			$ret = array();
+			if($result->numRows() == 0) {
+				return -1;
+			} else {
+				$ret[] = array();
+				$retcount = 0;
+				while($r = $result->fetchRow())
+				{
+					// Call get_record_from_id for each row.
+					$ret[$retcount] = get_record_from_id($r["id"]);
+					$retcount++;
+				}
+				return $ret;
+			}
 
 		} else {
-		$db->setLimit($rowamount, $rowstart);
-		$result = $db->query("SELECT id FROM records WHERE domain_id=".$db->quote($id));
-		$ret = array();
-		if($result->numRows() == 0)
-		{
-			return -1;
-		}
-		else
-		{
-			$ret[] = array();
-			$retcount = 0;
-			while($r = $result->fetchRow())
+			$db->setLimit($rowamount, $rowstart);
+			$result = $db->query("SELECT id FROM records WHERE domain_id=".$db->quote($id));
+			$ret = array();
+			if($result->numRows() == 0)
+			{
+				return -1;
+			}
+			else
 			{
-				// Call get_record_from_id for each row.
-				$ret[$retcount] = get_record_from_id($r["id"]);
-				$retcount++;
+				$ret[] = array();
+				$retcount = 0;
+				while($r = $result->fetchRow())
+				{
+					// Call get_record_from_id for each row.
+					$ret[$retcount] = get_record_from_id($r["id"]);
+					$retcount++;
+				}
+				return $ret;
 			}
-			return $ret;
-		}
 
 		}
 	}
@@ -1259,165 +873,164 @@
 }
 
 
-function get_users_from_domain_id($id)
-{
+function get_users_from_domain_id($id) {
 	global $db;
-	$result = $db->queryCol("SELECT owner FROM zones WHERE domain_id=".$db->quote($id));
-	$ret = array();
-	foreach($result as $uid)
-	{
-		$fullname = $db->queryOne("SELECT fullname FROM users WHERE id=".$db->quote($uid));
-		$ret[] = array(
-		"id" 		=> 	$uid,
-		"fullname"	=>	$fullname		
-		);		
+	$sqlq = "SELECT owner FROM zones WHERE domain_id =" .$db->quote($id);
+	$id_owners = $db->query($sqlq);
+	if ($id_owners->numRows() == 0) {
+		return -1;
+	} else {
+		while ($r = $id_owners->fetchRow()) {
+			$fullname = $db->queryOne("SELECT fullname FROM users WHERE id=".$r['owner']);
+			$owners[] = array(
+				"id" 		=> 	$r['owner'],
+				"fullname"	=>	$fullname		
+			);		
+		}
 	}
-	return $ret;	
+	return $owners;	
 }
 
-function search_record($question)
-{
+
+function search_zone_and_record($holy_grail,$perm) {
+	
 	global $db;
-	$question = trim($question);
+
+	$holy_grail = trim($holy_grail);
+
+	if (verify_permission(zone_content_view_others)) { $perm_view = "all" ; }
+	elseif (verify_permission(zone_content_view_own)) { $perm_view = "own" ; }
+	else { $perm_view = "none" ; }
+
+	if (verify_permission(zone_content_edit_others)) { $perm_content_edit = "all" ; }
+	elseif (verify_permission(zone_content_edit_own)) { $perm_content_edit = "own" ; }
+	else { $perm_content_edit = "none" ; }
+
+	// Search for matching domains
 
-	if (is_valid_search($question))
-	{
-		$sqlq = "SELECT * 
-				FROM records 
-				WHERE content LIKE ".$db->quote($question)." 
-				OR name LIKE ".$db->quote($question)."
-				ORDER BY type DESC";
-		$result = $db->query($sqlq);
-		$ret_r = array();
-		while ($r = $result->fetchRow())
-		{
-		    if(xs($r['domain_id']))
-		    {
-			$ret_r[] = array(
-			  'id'			=>	$r['id'],
-			  'domain_id'		=>	$r['domain_id'],
-			  'name'		=>	$r['name'],
-			  'type'		=>	$r['type'],
-			  'content'		=>	$r['content'],
-			  'ttl'			=>	$r['ttl'],
-			  'prio'		=>	$r['prio'],
-			  'change_date'		=>	$r['change_date']
-			);
-			}
-		}
+	if ($perm == "own") {
+		$sql_add_from = ", zones ";
+		$sql_add_where = " AND zones.domain_id = domains.id AND zones.owner = " . $db->quote($userid);
+	}
+	
+	$query = "SELECT 
+			domains.id AS zid,
+			domains.name AS name,
+			domains.type AS type,
+			domains.master AS master
+			FROM domains" . $sql_add_from . "
+			WHERE domains.name LIKE " . $db->quote($holy_grail)
+			. $sql_add_where ;
+	
+	$response = $db->query($query);
+	if (PEAR::isError($response)) { error($response->getMessage()); return false; }
 
-		$sqlq = "SELECT domains.id, domains.name, count(records.id) AS numrec, zones.owner, records.domain_id
-				FROM domains LEFT JOIN records ON domains.id = records.domain_id, zones  
-				WHERE zones.domain_id = domains.id 
-				AND domains.name LIKE ".$db->quote($question)." 
-				GROUP BY domains.id, domains.name, zones.owner, records.domain_id";
-		$result = $db->query($sqlq);
-		$ret_d = array();
-		while ($r = $result->fetchRow())
-		{
-		    if(xs($r['id']))
-		    {
-			    $ret_d[] = array(
-				'id'			=>	$r['id'],
-				'name'		=>	$r['name'],
-				'numrec'		=>	$r['numrec'],
-				'owner'		=>	$r['owner']
-			);
-			}
-		}
-		return array('domains' => $ret_d, 'records' => $ret_r);
-	}
-	else
-	{
-		error(sprintf(ERR_INV_ARGC, "search_record", "Invalid searchstring: $question"));
+	while ($r = $response->fetchRow()) {
+		$return_zones[] = array(
+			"zid"		=>	$r['zid'],
+			"name"		=>	$r['name'],
+			"type"		=>	$r['type'],
+			"master"	=>	$r['master']);
 	}
 
+	// Search for matching records
+
+	if ($perm == "own") {
+		$sql_add_from = ", zones ";
+		$sql_add_where = " AND zones.domain_id = record.id AND zones.owner = " . $db->quote($userid);
+	}
+
+	$query = "SELECT
+			records.id AS rid,
+			records.name AS name,
+			records.type AS type,
+			records.content AS content,
+			records.ttl AS ttl,
+			records.prio AS prio,
+			records.domain_id AS zid
+			FROM records" . $sql_add_from . "
+			WHERE (records.name LIKE " . $db->quote($holy_grail) . " OR records.content LIKE " . $db->quote($holy_grail) . ")"
+			. $sql_add_where ;
+
+	$response = $db->query($query);
+	if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+
+	while ($r = $response->fetchRow()) {
+		$return_records[] = array(
+			"rid"		=>	$r['rid'],
+			"name"		=>	$r['name'],
+			"type"		=>	$r['type'],
+			"content"	=>	$r['content'],
+			"ttl"		=>	$r['ttl'],
+			"zid"		=>	$r['zid'],
+			"prio"		=>	$r['prio']);
+	}
+	return array('zones' => $return_zones, 'records' => $return_records);
 }
 
-function get_domain_type($id)
-{
+function get_domain_type($id) {
 	global $db;
-        if (is_numeric($id))
-	{
+        if (is_numeric($id)) {
 		$type = $db->queryOne("SELECT type FROM domains WHERE id = ".$db->quote($id));
-		if($type == "")
-		{
+		if ($type == "") {
 			$type = "NATIVE";
 		}
 		return $type;
-        }
-        else
-        {
+        } else {
                 error(sprintf(ERR_INV_ARG, "get_record_from_id", "no or no valid zoneid given"));
         }
 }
 
-function get_domain_slave_master($id)
-{
+function get_domain_slave_master($id){
 	global $db;
-        if (is_numeric($id))
-	{
+        if (is_numeric($id)) {
 		$slave_master = $db->queryOne("SELECT master FROM domains WHERE type = 'SLAVE' and id = ".$db->quote($id));
 		return $slave_master;
-        }
-        else
-        {
+        } else {
                 error(sprintf(ERR_INV_ARG, "get_domain_slave_master", "no or no valid zoneid given"));
         }
 }
 
-function change_domain_type($type, $id)
+function change_zone_type($type, $id)
 {
 	global $db;
 	$add = '';
         if (is_numeric($id))
 	{
-		// It is not really neccesary to clear the master field if a 
-		// zone is not of the type "slave" as powerdns will ignore that
-		// fiedl, but it is cleaner anyway.
-		if ($type != "SLAVE")
-		{
+		// It is not really neccesary to clear the field that contains the IP address 
+		// of the master if the type changes from slave to something else. PowerDNS will
+		// ignore the field if the type isn't something else then slave. But then again,
+		// it's much clearer this way.
+		if ($type != "SLAVE") {
 			$add = ", master=''";
 		}
-		$result = $db->query("UPDATE domains SET type = " .$db->quote($type). $add." WHERE id = ".$db->quote($id));
-	}
-        else
-        {
+		$result = $db->query("UPDATE domains SET type = " . $db->quote($type) . $add . " WHERE id = ".$db->quote($id));
+	} else {
                 error(sprintf(ERR_INV_ARG, "change_domain_type", "no or no valid zoneid given"));
         }
 }
 
-function change_domain_slave_master($id, $slave_master)
-{
+function change_zone_slave_master($zone_id, $ip_slave_master) {
 	global $db;
-        if (is_numeric($id))
-	{
-       		if (is_valid_ip($slave_master) || is_valid_ip6($slave_master))
-		{
-			$result = $db->query("UPDATE domains SET master = " .$db->quote($slave_master). " WHERE id = ".$db->quote($id));
+        if (is_numeric($zone_id)) {
+       		if (is_valid_ip($ip_slave_master) || is_valid_ip6($ip_slave_master)) {
+			$result = $db->query("UPDATE domains SET master = " .$db->quote($ip_slave_master). " WHERE id = ".$db->quote($zone_id));
+		} else {
+			error(sprintf(ERR_INV_ARGC, "change_domain_ip_slave_master", "This is not a valid IPv4 or IPv6 address: $ip_slave_master"));
 		}
-		else
-		{
-			error(sprintf(ERR_INV_ARGC, "change_domain_slave_master", "This is not a valid IPv4 or IPv6 address: $slave_master"));
-		}
-	}
-        else
-        {
+	} else {
                 error(sprintf(ERR_INV_ARG, "change_domain_type", "no or no valid zoneid given"));
         }
 }
 
 
-function validate_account($account)
-{
-	
-  	if(preg_match("/^[A-Z0-9._-]+$/i",$account))
-	{
+function validate_account($account) {
+  	if(preg_match("/^[A-Z0-9._-]+$/i",$account)) {
 		return true;
-	}
-	else
-	{
+	} else {
 		return false;
 	}
 }
+
+
 ?>
--- a/inc/toolkit.inc.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/inc/toolkit.inc.php	Tue Mar 25 22:45:31 2008 +0000
@@ -22,7 +22,6 @@
 session_start();
 
 
-
 if(!@include_once("config.inc.php"))
 {
 	error( _('You have to create a config.inc.php!') );
@@ -79,6 +78,9 @@
 require_once("dns.inc.php");
 require_once("record.inc.php");
 
+$db = dbConnect();
+doAuthenticate();
+
 
 /*************
  * Functions *
@@ -92,7 +94,7 @@
 {
    if ($amount > $rowamount) {
       if (!isset($_GET["start"])) $_GET["start"]=1;
-      echo _('Show page') . "<br>";
+      echo _('Show page') . ":<br>";
       for ($i=1;$i<=ceil($amount / $rowamount);$i++) {
          if ($_GET["start"] == $i) {
             echo "[ <b>".$i."</b> ] ";
@@ -111,7 +113,7 @@
 
 function show_letters($letterstart,$userid=true)
 {
-        echo _('Show zones beginning with:') . "<br>";
+        echo _('Show zones beginning with') . ":<br>";
 
 	$letter = "[[:digit:]]";
 	if ($letterstart == "1")
@@ -148,68 +150,42 @@
 {
         global $db;
 	global $sql_regexp;
-        $sqlq = "SELECT domains.id AS domain_id,
-        zones.owner,
-        records.id,
-        domains.name AS domainname
-        FROM domains
-        LEFT JOIN zones ON domains.id=zones.domain_id 
-        LEFT JOIN records ON records.domain_id=domains.id
-        WHERE 1=1";
-        if((!level(5) || !$userid) && !level(10) && !level(5))
-        {
-		// First select the zones for which we have ownership on one or more records.
-		$query = 'SELECT records.domain_id FROM records, record_owners WHERE user_id = '.$db->quote($_SESSION['userid']).' AND records.id = record_owners.record_id';
-		$result = $db->query($query);
-		$zones = array();
-		if (!PEAR::isError($result)) {
-			$zones = $result->fetchCol();
-		}
-	
-                $sqlq .= " AND (zones.owner=".$db->quote($_SESSION["userid"]);
-		if (count($zones) > 0) {
-			$sqlq .= ' OR zones.domain_id IN ('.implode(',', $zones).') '; 
-
-		}
-		$sqlq .= ')';
-        }
-        $sqlq .= " AND substring(domains.name,1,1) ".$sql_regexp." ".$db->quote("^".$letter);
-		$db->setLimit(1);
-        $result = $db->query($sqlq);
+        $query = "SELECT 
+			domains.id AS domain_id,
+			zones.owner,
+			records.id,
+			domains.name AS domainname
+			FROM domains
+			LEFT JOIN zones ON domains.id=zones.domain_id 
+			LEFT JOIN records ON records.domain_id=domains.id
+			AND substring(domains.name,1,1) ".$sql_regexp." ".$db->quote("^".$letter);
+	$db->setLimit(1);
+        $result = $db->query($query);
         $numrows = $result->numRows();
-        if ( $numrows == "1" ) 
-        {
+        if ( $numrows == "1" ) {
                 return 1;
-        }
-        else
-        {
+        } else {
                 return 0;
         }
 }
 
-/*
- * Print a nice useraimed error.
- */
-function error($msg)
-{
-	// General function for printing critical errors.
-	if ($msg)
-	{
-		include_once("header.inc.php");
-	?>
-	<p><?php echo _('Oops! An error occured!'); ?></p>
-	<p><?php echo nl2br($msg) ?></p>
-	<?php
-		include_once("footer.inc.php");
-		die();
-	}
-	else
-	{
-		include_once("footer.inc.php");
-		die("No error specified!");
+function error($msg) {
+	if ($msg) {
+		echo "     <div class=\"error\">Error: " . $msg . "</div>\n";
+	} else {
+		echo "     <div class=\"error\">" . _('An unknown error has occurred.') . "</div>\n"; 
 	}
 }
 
+function success($msg) {
+	if ($msg) {
+		echo "     <div class=\"success\">" . $msg . "</div>\n";
+	} else {
+		echo "     <div class=\"success\">" . _('Something has been successfully performed. What exactly, however, will remain a mystery.') . "</div>\n"; 
+	}
+}
+
+
 /*
  * Something has been done nicely, display a message and a back button.
  */
@@ -268,47 +244,6 @@
 	}
 }
 
-function level($l)
-{
-	if ($_SESSION["level"] >= $l)
-	{
-		return 1;
-	}
-	else
-	{
-		return 0;
-	}
-}
-
-function xs($zoneid)
-{
-	global $db;
-	if (is_numeric($zoneid) && is_numeric($_SESSION["level"]))
-	{
-		$result = $db->query("SELECT id FROM zones WHERE owner=".$db->quote($_SESSION["userid"])." AND domain_id=".$db->quote($zoneid));
-		$db->setLimit(1);
-		$result_extra = $db->query("SELECT record_owners.id FROM record_owners,records WHERE record_owners.user_id=".$db->quote($_SESSION["userid"])." AND records.domain_id = ".$db->quote($zoneid)." AND records.id = record_owners.record_id");
-
-                if ($result->numRows() == 1 || $_SESSION["level"] >= 5)
-                {
-			$_SESSION[$zoneid."_ispartial"] = 0;
-			return true;
-		}
-		elseif ($result_extra->numRows() == 1)
-		{
-			$_SESSION[$zoneid."_ispartial"] = 1;
-			return true;
-		}
-		else
-		{
-			return false;
-		}
-	}
-	else
-	{
-        	return false;
-        }
-}
 
 function get_status($res)
 {
@@ -344,4 +279,20 @@
 	}
 	return true;
 }
+
+
+function v_num($string) {
+	if (!eregi("^[0-9]+$", $string)) { 
+		return false ;
+	} else {
+		return true ;
+	}
+}
+
+function debug_r($array) {
+	echo "<pre style=\"border: 2px solid blue;\">\n";
+	print_r($array);
+	echo "</pre>\n";
+}
+
 ?>
--- a/inc/users.inc.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/inc/users.inc.php	Tue Mar 25 22:45:31 2008 +0000
@@ -21,6 +21,77 @@
 
 require_once("inc/toolkit.inc.php");
 
+
+/* 
+ *  Function to see if user has right to do something. It will check if
+ *  user has "ueberuser" bit set. If it isn't, it will check if the user has
+ *  the specific permission. It returns "false" if the user doesn't have the
+ *  right, and "true" if the user has. 
+ */
+
+function verify_permission($permission) {
+
+        global $db;
+
+	if ((!isset($_SESSION['userid'])) || (!is_object($db))) {
+		return 0;
+	}
+
+        // Set current user ID.
+        $userid=$_SESSION['userid'];
+
+        // Find the template ID that this user has been assigned.
+        $query = "SELECT perm_templ
+			FROM users 
+			WHERE id = " . $db->quote($userid) ;
+        $templ_id = $db->queryOne($query);
+
+        // Does this user have ueberuser rights?
+        $query = "SELECT id 
+			FROM perm_templ_items 
+			WHERE templ_id = " . $db->quote($templ_id) . " 
+			AND perm_id = '53'";
+        $result = $db->query($query);
+        if ( $result->numRows() > 0 ) {
+                return 1;
+        }
+
+        // Find the permission ID for the requested permission.
+        $query = "SELECT id 
+			FROM perm_items 
+			WHERE name = " . $db->quote($permission) ;
+        $perm_id = $db->queryOne($query);
+
+        // Check if the permission ID is assigned to the template ID. 
+        $query = "SELECT id 
+			FROM perm_templ_items 
+			WHERE templ_id = " . $db->quote($templ_id) . " 
+			AND perm_id = " . $db->quote($perm_id) ;
+        $result = $db->query($query);
+        if ( $result->numRows() > 0 ) {
+                return 1;
+        } else {
+                return 0;
+        }
+}
+
+function list_permission_templates() {
+	global $db;
+	$query = "SELECT * FROM perm_templ";
+	$result = $db->query($query);
+	if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+
+	$template_list = array();
+	while ($template= $result->fetchRow()) {
+		$tempate_list[] = array(
+			"id"	=>	$template['id'],
+			"name"	=>	$template['name'],
+			"descr"	=>	$template['descr']
+			);
+	}
+	return $tempate_list;
+}
+
 /*
  * Retrieve all users.
  * Its to show_users therefore the odd name. Has to be changed.
@@ -42,8 +113,8 @@
 		users.fullname AS fullname,
 		users.email AS email,
 		users.description AS description,
-		users.level AS level,
 		users.active AS active,
+		users.perm_templ AS perm_templ,
 		count(zones.owner) AS aantal FROM users
 		LEFT JOIN zones ON users.id=zones.owner$add
 		GROUP BY
@@ -52,7 +123,7 @@
 			users.fullname,
 			users.email,
 			users.description,
-			users.level,
+			users.perm_templ,
 			users.active
 		ORDER BY
 			users.fullname";
@@ -102,33 +173,6 @@
 
 
 /*
- * Gives a textdescribed value of the given levelid
- * return values: the text associated with the level
- */
-function leveldescription($id)
-{
-	switch($id)
-	{
-		case 1:
-			global $NAME_LEVEL_1;
-			return $NAME_LEVEL_1;
-			break;
-		case 5:
-			global $NAME_LEVEL_5;
-			return $NAME_LEVEL_5;
-			break;
-		case 10:
-			global $NAME_LEVEL_10;
-			return $NAME_LEVEL_10;
-			break;
-		default:
-			return "Unknown";
-			break;
-	}
-}
-
-
-/*
  * Checks if a given username exists in the database.
  * return values: true if exists, false if not.
  */
@@ -151,79 +195,39 @@
 }
 
 
-/*
- * Get all user info for the given user in an array.
- * return values: the database style array with the information about the user.
- */
-function get_user_info($id)
-{
-	global $db;
-	if (is_numeric($id))
-	{
-		$result = $db->query("SELECT id, username, fullname, email, description, level, active from users where id=".$db->quote($id));
-		$r = $result->fetchRow();
-		return $r;
-	}
-	else
-	{
-		error(sprintf(ERR_INV_ARGC,"get_user_info", "you gave illegal arguments: $id"));
-	}
-}
-
 
 /*
  * Delete a user from the system
  * return values: true if user doesnt exist.
  */
-function delete_user($id)
+function delete_user($uid,$zones)
 {
 	global $db;
-	if (!level(10))
-	{
-		error(ERR_LEVEL_10);
-	}
-	if (is_numeric($id))
-	{
-        	$db->query("DELETE FROM users WHERE id=".$db->quote($id));
-        	$db->query("DELETE FROM zones WHERE owner=".$db->quote($id));
-        	return true;
-        	// No need to check the affected rows. If the affected rows would be 0,
-        	// the user isnt in the dbase, just as we want.
-        }
-	else
-	{
-		error(ERR_INV_ARG);
-	}
-}
 
+	if (($uid != $_SESSION['userid'] && !verify_permission(user_edit_others)) || ($uid == $_SESSION['userid'] && !verify_permission(user_edit_own))) {
+		 error(ERR_PERM_DEL_USER);
+		 return false;
+	} else {
 
-/*
- * Adds a user to the system.
- * return values: true if succesfully added.
- */
-function add_user($user, $password, $fullname, $email, $level, $description, $active)
-{
-	global $db;
-	if (!level(10))
-	{
-		error(ERR_LEVEL_10);
+		if (is_array($zones)) {
+			foreach ($zones as $zone) {
+				if ($zone['target'] == "delete") {
+					delete_domain($zone['zid']);
+				} elseif ($zone['target'] == "new_owner") {
+					add_owner_to_zone($zone['zid'], $zone['newowner']);
+				}
+			}
+		}
+
+		$query = "DELETE FROM zones WHERE owner = " . $db->quote($uid) ;
+		$result = $db->query($query);
+		if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+
+		$query = "DELETE FROM users WHERE id = " . $db->quote($uid) ;
+		$result = $db->query($query);
+		if (PEAR::isError($response)) { error($response->getMessage()); return false; }
 	}
-	if (!user_exists($user))
-	{
-		if (!is_valid_email($email)) 
-		{
-			error(ERR_INV_EMAIL);
-		}
-		if ($active != 1) {
-			$active = 0;
-		}
-		$db->query("INSERT INTO users (username, password, fullname, email, description, level, active) VALUES (".$db->quote($user).", '" . md5($password) . "', ".$db->quote($fullname).", ".$db->quote($email).", ".$db->quote($description).", ".$db->quote($level).", ".$db->quote($active).")");
-		return true;
-	}
-	else
-	{
-		error(ERR_USER_EXISTS);
-	}
+	return true;
 }
 
 
@@ -231,57 +235,81 @@
  * Edit the information of an user.. sloppy implementation with too many queries.. (2) :)
  * return values: true if succesful
  */
-function edit_user($id, $user, $fullname, $email, $level, $description, $active, $password)
+function edit_user($id, $user, $fullname, $email, $perm_templ, $description, $active, $password)
 {
 	global $db;
-	if(!level(10)) {
-		error(ERR_LEVEL_10);
-	}
+
+	verify_permission(user_edit_own) ? $perm_edit_own = "1" : $perm_edit_own = "0" ;
+	verify_permission(user_edit_others) ? $perm_edit_others = "1" : $perm_edit_others = "0" ;
+
+	if (($id == $_SESSION["userid"] && $perm_edit_own == "1") || ($id != $_SESSION["userid"] && $perm_edit_others == "1" )) {
+
+		if (!is_valid_email($email)) {
+			error(ERR_INV_EMAIL);
+			return false;
+		}
 
-	if (!is_valid_email($email)) 
-	{
-		error(ERR_INV_EMAIL);
-	}
-	if ($active != 1) {
-		$active = 0;
-	}
-	$sqlquery = "UPDATE users set username=".$db->quote($user).", fullname=".$db->quote($fullname).", email=".$db->quote($email).", level=".$db->quote($level).", description=".$db->quote($description).", active=".$db->quote($active);
+		if ($active != 1) {
+			$active = 0;
+		}
+		
+		// Before updating the database we need to check whether the user wants to 
+		// change the username. If the user wants to change the username, we need 
+		// to make sure it doesn't already exists. 
+		//
+		// First find the current username of the user ID we want to change. If the 
+		// current username is not the same as the username that was given by the 
+		// user, the username should apparantly changed. If so, check if the "new" 
+		// username already exists.
 
-	if($password != "")
-	{
-		$sqlquery .= ", password= '" . md5($password) . "' ";
-	}
+		$query = "SELECT username FROM users WHERE id = " . $db->quote($id);
+		$result = $db->query($query);
+		if (PEAR::isError($response)) { error($response->getMessage()); return false; }
 
-	$sqlquery .= " WHERE id=".$db->quote($id) ;
+		$usercheck = array();
+		$usercheck = $result->fetchRow();
 
-  	// Search the username that right now goes with this ID.
-	$result = $db->query("SELECT username from users where id=".$db->quote($id));
-	$r = array();
-	$r = $result->fetchRow();
+		if ($usercheck['username'] != $user) {
+			
+			// Username of user ID in the database is different from the name
+			// we have been given. User wants a change of username. Now, make
+			// sure it doesn't already exist.
+			
+			$query = "SELECT id FROM users WHERE username = " . $db->query($user);
+			$result = $db->query($query);
+			if (PEAR::isError($response)) { error($response->getMessage()); return false; }
 
-  	// If the found username with this ID is the given username with the command.. execute.
+			if($result->numRows() > 0) {
+				error(ERR_USER_EXIST);
+				return false;
+			}
+		}
 
-	if($r["username"] == $user)
-	{
-		$db->query($sqlquery);
-  		return true;
-  	}
+		// So, user doesn't want to change username or, if he wants, there is not
+		// another user that goes by the wanted username. So, go ahead!
 
-  	// Its not.. so the user wants to change.
-  	// Find if there is an id that has the wished username.
-  	$otheruser = $db->query("SELECT id from users where username=".$db->query($user));
-  	if($otheruser->numRows() > 0)
-  	{
-  		error(ERR_USER_EXIST);
-  	}
+		$query = "UPDATE users SET
+				username = " . $db->quote($user) . ",
+				fullname = " . $db->quote($fullname) . ",
+				email = " . $db->quote($email) . ",
+				perm_templ = " . $db->quote($perm_templ) . ",
+				description = " . $db->quote($description) . ", 
+				active = " . $db->quote($active) ;
 
-  	// Its fine it seems.. :)
-  	// Lets execute it.
-  	else
-  	{
-		$db->query($sqlquery);
-		return true;
+		if($password != "") {
+			$query .= ", password = " . $db->quote(md5($password)) ;
+		}
+
+		$query .= " WHERE id = " . $db->quote($id) ;
+
+		$result = $db->query($query);
+		if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+		
+	} else {
+		error(ERR_PERM_EDIT_USER);
+		return false;
 	}
+	return true;
 }
 
 /*
@@ -289,32 +317,29 @@
  * The user is automatically logged out after the pass change.
  * return values: none.
  */
-function change_user_pass($currentpass, $newpass, $newpass2)
-{
+function change_user_pass($details) {
 	global $db;
-
-	// Check if the passwords are equal.
-	if($newpass != $newpass2)
-	{
+	
+	if ($details['newpass'] != $details['newpass2']) {
 		error(ERR_USER_MATCH_NEW_PASS);
+		return false;
 	}
 
-	// Retrieve the users password.
-	$result = $db->query("SELECT password, id FROM users WHERE username=".$db->quote($_SESSION["userlogin"]));
+	$query = "SELECT id, password FROM users WHERE username = " . $db->quote($_SESSION["userlogin"]);
+	$result = $db->query($query);
+	if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+
 	$rinfo = $result->fetchRow();
 
-	// Check the current password versus the database password and execute the update.
-	if(md5($currentpass) == $rinfo["password"])
-	{
-		$sqlquery = "update users set password='" . md5($newpass) . "' where id='" . $rinfo["id"] . "'";
-		$db->query($sqlquery);
+	if(md5($details['currentpass']) == $rinfo['password']) {
+		$query = "UPDATE users SET password = " . $db->quote(md5($details['newpass'])) . " WHERE id = " . $db->quote($rinfo['id']) ;
+		$result = $db->query($query);
+		if (PEAR::isError($response)) { error($response->getMessage()); return false; }
 
-		// Logout the user.
-		logout("Pass changed please re-login");
-	}
-	else
-	{
+		logout( _('Password has been changed, please login.')); 
+	} else {
 		error(ERR_USER_WRONG_CURRENT_PASS);
+		return false;
 	}
 }
 
@@ -323,18 +348,15 @@
  * Get a fullname when you have a userid.
  * return values: gives the fullname from a userid.
  */
-function get_fullname_from_userid($id)
-{
+function get_fullname_from_userid($id) {
 	global $db;
-	if (is_numeric($id))
-	{
+	if (is_numeric($id)) {
 		$result = $db->query("SELECT fullname FROM users WHERE id=".$db->quote($id));
 		$r = $result->fetchRow();
 		return $r["fullname"];
-	}
-	else
-	{
+	} else {
 		error(ERR_INV_ARG);
+		return false;
 	}
 }
 
@@ -369,7 +391,7 @@
  * @param $id integer the id of the domain
  * @return String the list of owners for this domain
  */
-function get_owners_from_domainid($id) {
+function get_fullnames_owners_from_domainid($id) {
       
       global $db;
       if (is_numeric($id))
@@ -392,4 +414,311 @@
       error(ERR_INV_ARG);
 }
 
+
+
+function verify_user_is_owner_zoneid($zoneid) {
+	global $db;
+
+	$userid=$_SESSION["userid"];
+
+	if (is_numeric($zoneid)) {
+		$result = $db->query("SELECT zones.id 
+				FROM zones 
+				WHERE zones.owner = " . $db->quote($userid) . "
+				AND zones.domain_id = ". $db->quote($zoneid)) ;
+		if ($result->numRows() == 0) {
+			return "0";
+		} else {
+			return "1";
+		}
+	}
+	error(ERR_INV_ARG);
+}
+
+
+function get_user_detail_list($specific) {
+
+	global $db;
+	$userid=$_SESSION['userid'];
+
+
+	if (v_num($specific)) {
+		$sql_add = "AND users.id = " . $db->quote($specific) ;
+	} else {
+		if (verify_permission(user_view_others)) {
+			$sql_add = "";
+		} else {
+			$sql_add = "AND users.id = " . $db->quote($userid) ;
+		}
+	}
+
+	$query = "SELECT users.id AS uid, 
+			username, 
+			fullname, 
+			email, 
+			description AS descr,
+			active,
+			perm_templ.id AS tpl_id,
+			perm_templ.name AS tpl_name,
+			perm_templ.descr AS tpl_descr
+			FROM users, perm_templ 
+			WHERE users.perm_templ = perm_templ.id " 
+			. $sql_add . "
+			ORDER BY username";
+
+	$result = $db->query($query);
+	if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+	
+	while ($user = $result->fetchRow()) {
+		$userlist[] = array(
+			"uid"		=>	$user['uid'],
+			"username"	=>	$user['username'],
+			"fullname"	=>	$user['fullname'],
+			"email"		=>	$user['email'],
+			"descr"		=>	$user['descr'],
+			"active"	=>	$user['active'],
+			"tpl_id"	=>	$user['tpl_id'],
+			"tpl_name"	=>	$user['tpl_name'],
+			"tpl_descr"	=>	$user['tpl_descr']
+			);
+	}
+	return $userlist;
+}
+
+
+// Get a list of permissions that are available. If first argument is "0", it
+// should return all available permissions. If the first argument is > "0", it
+// should return the permissions assigned to that particular template only. If
+// second argument is true, only the permission names are returned.
+
+function get_permissions_by_template_id($templ_id=0,$return_name_only=false) {
+	global $db;
+	
+	if ($templ_id > 0) {
+		$limit = ", perm_templ_items 
+			WHERE perm_templ_items.templ_id = " . $db->quote($templ_id) . "
+			AND perm_templ_items.perm_id = perm_items.id";
+	}
+
+	$query = "SELECT perm_items.id AS id, 
+			perm_items.name AS name, 
+			perm_items.descr AS descr
+			FROM perm_items" 
+			. $limit . "
+			ORDER BY descr";
+	$result = $db->query($query);
+	if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+
+	$permission_list = array();
+	while ($permission = $result->fetchRow()) {
+		if ($return_name_only == false) {
+			$permission_list[] = array(
+				"id"	=>	$permission['id'],
+				"name"	=>	$permission['name'],
+				"descr"	=>	$permission['descr']
+				);
+		} else {
+			$permission_list[] = $permission['name'];
+		}
+	}
+	return $permission_list;
+}
+
+
+// Get name and description of template based on template ID.
+
+function get_permission_template_details($templ_id) {
+	global $db;
+
+	$query = "SELECT *
+			FROM perm_templ
+			WHERE perm_templ.id = " . $db->quote($templ_id);
+
+	$result = $db->query($query);
+	if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+
+	while($details = $result->fetchRow()) {
+		$detail_list[] = array (
+			"name"	=>	$details['name'],
+			"descr"	=>	$details['descr']
+			);
+	}
+	return $detail_list;
+}	
+
+
+// Get a list of all available permission templates.
+
+function get_list_permission_templates() {
+	global $db;
+
+	$query = "SELECT * FROM perm_templ";
+	$result = $db->query($query);
+	if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+
+	$perm_templ_list = array();
+	while ($perm_templ = $result->fetchRow()) {
+		$perm_templ_list[] = array(
+			"id"	=>	$perm_templ['id'],
+			"name"	=>	$perm_templ['name'],
+			"descr"	=>	$perm_templ['descr']
+			);
+	}
+	return $perm_templ_list;
+}
+
+
+// Update all details of a permission template.
+
+function update_perm_templ_details($details) {
+	global $db;
+
+	// Fix permission template name and description first. 
+
+	$query = "UPDATE perm_templ 
+			SET name = " . $db->quote($details['templ_name']) . ",
+			descr = " . $db->quote($details['templ_descr']) . "
+			WHERE id = " . $db->quote($details['templ_id']) ;
+	
+	$result = $db->query($query);
+	if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+
+	// Now, update list of permissions assigned to this template. We could do 
+	// this The Correct Way [tm] by comparing the list of permissions that are
+	// currently assigned with a list of permissions that should be assigned and
+	// apply the difference between these two lists to the database. That sounds 
+	// like to much work. Just delete all the permissions currently assigned to 
+	// the template, than assign all the permessions the template should have.
+
+	$query = "DELETE FROM perm_templ_items WHERE templ_id = " . $details['templ_id'] ;
+	$result = $db->query($query);
+	if (pear::iserror($response)) { error($response->getmessage()); return false; }
+
+	foreach ($details['perm_id'] AS $perm_id) {
+		$r_insert_values[] = "(''," . $db->quote($details['templ_id']) . "," . $db->quote($perm_id) . ")";
+	}
+	$query = "INSERT INTO perm_templ_items VALUES " . implode(',', $r_insert_values) ;
+	$result = $db->query($query);
+	if (pear::iserror($response)) { error($response->getmessage()); return false; }
+
+	return true;
+}
+
+function update_user_details($details) {
+
+	global $db;
+
+	verify_permission(user_edit_own) ? $perm_edit_own = "1" : $perm_edit_own = "0" ;
+	verify_permission(user_edit_others) ? $perm_edit_others = "1" : $perm_edit_others = "0" ;
+
+	if (($details['uid'] == $_SESSION["userid"] && $perm_edit_own == "1") || 
+			($details['uid'] != $_SESSION["userid"] && $perm_edit_others == "1" )) {
+
+		if (!is_valid_email($details['email'])) {
+			error(ERR_INV_EMAIL);
+			return false;
+		}
+
+		if (!isset($details['active']) || $details['active'] != "on" ) {
+			$active = 0;
+		} else {
+			$active = 1;
+		}
+
+		// Before updating the database we need to check whether the user wants to 
+		// change the username. If the user wants to change the username, we need 
+		// to make sure it doesn't already exists. 
+		//
+		// First find the current username of the user ID we want to change. If the 
+		// current username is not the same as the username that was given by the 
+		// user, the username should apparantly changed. If so, check if the "new" 
+		// username already exists.
+		$query = "SELECT username FROM users WHERE id = " . $db->quote($details['uid']);
+		$result = $db->query($query);
+		if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+
+		$usercheck = array();
+		$usercheck = $result->fetchRow();
+
+		if ($usercheck['username'] != $details['username']) {
+			// Username of user ID in the database is different from the name
+			// we have been given. User wants a change of username. Now, make
+			// sure it doesn't already exist.
+			$query = "SELECT id FROM users WHERE username = " . $db->quote($details['username']);
+			$result = $db->query($query);
+			if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+
+			if($result->numRows() > 0) {
+				error(ERR_USER_EXIST);
+				return false;
+			}
+		}
+
+		// So, user doesn't want to change username or, if he wants, there is not
+		// another user that goes by the wanted username. So, go ahead!
+
+		$query = "UPDATE users SET
+				username = " . $db->quote($details['username']) . ",
+				fullname = " . $db->quote($details['fullname']) . ",
+				email = " . $db->quote($details['email']) . ",
+				perm_templ = " . $db->quote($details['templ_id']) . ",
+				description = " . $db->quote($details['descr']) . ", 
+				active = " . $db->quote($active) ;
+
+		// TODO Check if function works if password is set too.
+		if($details['password'] != "") {
+			$query .= ", password = '" . md5($db->quote($details['password'])) . "' ";
+		}
+
+		$query .= " WHERE id = " . $db->quote($details['uid']) ;
+
+		$result = $db->query($query);
+		if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+
+	} else {
+		error(ERR_PERM_EDIT_USER);
+		return false;
+	}
+	return true;		
+}
+
+// Add a new user
+
+function add_new_user($details) {
+	global $db;
+
+	if (!verify_permission(user_add_new)) {
+		error(ERR_PERM_ADD_USER);
+
+	} elseif (user_exists($details['username'])) {
+		error(ERR_USER_EXISTS);
+
+	} elseif (!is_valid_email($details['email'])) {
+		error(ERR_INV_EMAIL);
+	
+	} elseif ($details['active'] == 1) {
+		$active = 1;
+	} else {
+		$active = 0;
+	}
+
+	$query = "INSERT INTO users VALUES ( "
+			. "'', "
+			. $db->quote($details['username']) . ", "
+			. $db->quote(md5($details['password'])) . ", "
+			. $db->quote($details['fullname']) . ", "
+			. $db->quote($details['email']) . ", "
+			. $db->quote($details['descr']) . ", "
+			. $db->quote($details['perm_templ']) . ", "
+			. $db->quote($active) 
+			. ")";
+
+	$result = $db->query($query);
+	if (PEAR::isError($response)) { error($response->getMessage()); return false; }
+	
+	return true;
+}
+
+			
+
 ?>
--- a/index.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/index.php	Tue Mar 25 22:45:31 2008 +0000
@@ -22,34 +22,41 @@
 //session_start();
 require_once("inc/toolkit.inc.php");
 include_once("inc/header.inc.php");
-?>
-   <h3><?php echo _('Welcome'); ?>, <?php echo $_SESSION["name"] ?></h3>
-   <ul>
-    <li><a href="search.php"><?php echo _('Search zones or records'); ?></a></li>
-    <li><a href="list_zones.php"><?php echo _('List all zones'); ?></a></li>
-<?php
-if (level(5))
-{
-?>
-    <li><a href="list_supermasters.php"><?php echo _('List all supermasters'); ?></a></li>
-    <li><a href="add_zone_master.php"><?php echo _('Add master zone'); ?></a></li>
-    <li><a href="add_zone_slave.php"><?php echo _('Add slave zone'); ?></a></li>
-    <li><a href="add_supermaster.php"><?php echo _('Add supermaster'); ?></a></li>
-<?php
+
+echo "     <h3>" . _('Welcome') . " " . $_SESSION["name"] . "</h3>\n";
+
+verify_permission(search) ? $perm_search = "1" : $perm_search = "0" ;
+verify_permission(zone_content_view_own) ? $perm_view_zone_own = "1" : $perm_view_zone_own = "0" ;
+verify_permission(zone_content_view_other) ? $perm_view_zone_other = "1" : $perm_view_zone_other = "0" ;
+verify_permission(supermaster_view) ? $perm_supermaster_view = "1" : $perm_supermaster_view = "0" ;
+verify_permission(zone_master_add) ? $perm_zone_master_add = "1" : $perm_zone_master_add = "0" ;
+verify_permission(zone_slave_add) ? $perm_zone_slave_add = "1" : $perm_zone_slave_add = "0" ;
+verify_permission(supermaster_add) ? $perm_supermaster_add = "1" : $perm_supermaster_add = "0" ;
+
+echo "    <ul>\n";
+echo "    <li><a href=\"index.php\">" . _('Index') . "</a></li>\n";
+if ( $perm_search == "1" ) {
+	echo "    <li><a href=\"search.php\">" . _('Search zones or records') . "</a></li>\n";
 }
-?>
-    <li><a href="change_password.php"><?php echo _('Change password'); ?></a></li>
-<?php
-if (level(10))
-{
-?>
-    <li><a href="users.php"><?php echo _('User administration'); ?></a></li>
-<?php
+if ( $perm_view_zone_own == "1" || $perm_view_zone_other == "1" ) {
+	echo "    <li><a href=\"list_zones.php\">" . _('List all zones') . "</a></li>\n";
+}
+if ( $perm_supermaster_view ) {
+	echo "    <li><a href=\"list_supermasters.php\">" . _('List all supermasters') . "</a></li>\n";
+}
+if (  $perm_zone_master_add ) {
+	echo "    <li><a href=\"add_zone_master.php\">" . _('Add master zone') . "</a></li>\n";
 }
-?>
-    <li><a href="index.php?logout"><?php echo _('Logout'); ?></a></li>
-   </ul>
+if ( $perm_zone_slave_add ) { 
+	echo "    <li><a href=\"add_zone_slave.php\">" . _('Add slave zone') . "</a></li>\n";
+}
+if ( $supermaster_add ) { 
+	echo "    <li><a href=\"add_supermaster.php\">" . _('Add supermaster') . "</a></li>\n";
+}
+echo "    <li><a href=\"change_password.php\">" . _('Change password') . "</a></li>\n";
+echo "    <li><a href=\"users.php\">" . _('User administration') . "</a></li>\n";
+echo "    <li><a href=\"index.php?logout\">" . _('Logout') . "</a></li>\n";
+echo "   </ul>\n";
 
-<?php
 include_once("inc/footer.inc.php");
 ?>
--- a/install.php	Wed Mar 12 20:45:56 2008 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,225 +0,0 @@
-<?php
-
-/*  PowerAdmin, a friendly web-based admin tool for PowerDNS.
- *  See <https://rejo.zenger.nl/poweradmin> for more details.
- *
- *  Copyright 2007, 2008  Rejo Zenger <rejo@zenger.nl>
- *
- *  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 3 of the License, or
- *  (at your option) any later version.
- *
- *  This program is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *  GNU General Public License for more details.
- *
- *  You should have received a copy of the GNU General Public License
- *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-
-// addslashes to vars if magic_quotes_gpc is off
-function slash_input_data(&$data)
-{
-	if ( is_array($data) )
-	{
-		foreach ( $data as $k => $v )
-		{
-			$data[$k] = ( is_array($v) ) ? slash_input_data($v) : addslashes($v);
-		}
-	}
-	return $data;
-}
-
-set_magic_quotes_runtime(0);
-
-// If magic quotes is off, addslashes
-if ( !get_magic_quotes_gpc() )
-{
-	$_GET = slash_input_data($_GET);
-	$_POST = slash_input_data($_POST);
-	$_COOKIE = slash_input_data($_COOKIE);
-}
-
-
-error_reporting(E_ALL);
-if(!@require_once("inc/config.inc.php"))
-{
-	error("You have to create a config.inc.php!");
-}
-include_once("inc/header.inc.php");
-
-$sup_types = array('mysql');
-
-function error($msg=false)
-{
-       	// General function for printing critical errors.
-        if ($msg)
-	    {
-		?>
-                <P><TABLE CLASS="error"><TR><TD CLASS="error"><H2><?php echo _('Oops! An error occured!'); ?></H2>
-       	        <BR>
-               	<FONT STYLE="font-weight: Bold"><?php nl2br($msg) ?><BR><BR><a href="javascript:history.go(-1)">&lt;&lt; back</a></FONT><BR></TABLE>
-                <?php
-      	        die();
-        }
-	    else
-	    {
-       	        die("No error specified!");
-        }
-}
-
-if(isset($_POST["submit"]))
-{
-	//$dbtype = $_POST["dbtype"];
-	require_once("inc/database.inc.php");
-
-	if($dbdsntype == "mysql")
-	{
-		$sqlusers =	"CREATE TABLE users (
-				  id int(11) NOT NULL auto_increment,
-				  username varchar(16) NOT NULL default '',
-				  password varchar(34) NOT NULL default '',
-				  fullname varchar(255) NOT NULL default '',
-				  email varchar(255) NOT NULL default '',
-				  description text NOT NULL,
-				  level tinyint(3) NOT NULL default '0',
-				  active tinyint(1) NOT NULL default '0',
-				  PRIMARY KEY  (id)
-				) TYPE=InnoDB";
-		$sqlzones =	"CREATE TABLE zones (
-  				  id int(11) NOT NULL auto_increment,
-				  domain_id int(11) NOT NULL default '0',
-				  owner int(11) NOT NULL default '0',
-				  comment text,
-				  PRIMARY KEY  (id)
-				) TYPE=InnoDB";
-                $sqlrecowns =   "CREATE TABLE record_owners (
-                                  id int(11) NOT NULL auto_increment,
-                                  user_id int(11) NOT NULL default '0',
-                                  record_id int(11) NOT NULL default '0',
-                                  PRIMARY KEY  (id)
-                                ) TYPE=InnoDB";
-	}
-
-	// PGSQL Is trivial still, the relations are different.
-	if($dbdsntype == "pgsql")
-	{
-		$sqlusers =	"CREATE TABLE users (
-				id SERIAL PRIMARY KEY,
-				username varchar(16) NOT NULL,
-				password varchar(34) NOT NULL,
-				fullname varchar(255) NOT NULL,
-				email varchar(255) NOT NULL,
-				description text NOT NULL,
-				level smallint DEFAULT 0,
-				active smallint DEFAULT 0
-				)";
-		$sqlzones =	"CREATE TABLE zones (
-				id SERIAL PRIMARY KEY,
-				domain_id integer NOT NULL,
-				owner integer NOT NULL,
-				comment text NULL
-				)";
-                $sqlrecowns =   "CREATE TABLE record_owners (
-                                id SERIAL PRIMARY KEY,
-                                user_id integer NOT NULL,
-                                record_id integer NOT NULL
-                                )";
-	}
-
-	if(!empty($_POST['login']) && !empty($_POST['password']) && !empty($_POST['fullname']) && !empty($_POST['email']))
-	{
-		// Declare default tables.
-
-
-
-		// It just tries to rough create. If it flunks.. bad a user exists or the dbase exists.
-
-		$resusers = $db->query($sqlusers);
-
-		if($db->isError($resusers))
-		{
-			error("Can not create table users in $dbdatabase");
-		}
-
-		$reszones = $db->query($sqlzones);
-
-		if($db->isError($reszones))
-		{
-			error("Can not create zones table in $dbdatabase");
-		}
-                $reszones = $db->query($sqlrecowns);
-
-                if($db->isError($reszones))
-                {
-                        error("Can not create record_owners table in $dbdatabase");
-                }
-		
-		$sqlinsert =	"INSERT INTO 
-					users 
-					(username, password, fullname, email, description, level, active)
-				VALUES (
-					'". $_POST['login'] ."', 
-					'". md5(stripslashes($_POST['password'])) ."',
-					'". $_POST["fullname"] ."',
-					'". $_POST["email"] ."',
-					'". $_POST["description"] ."',
-					10,
-					1)";
-
-		$resadmin = $db->query($sqlinsert);
-
-		if($db->isError($resadmin))
-		{
-
-			error("Can not add the admin to database $dbdatabase.users");
-		}
-		else
-		{
-
-			?>
-<h2><?php echo _('PowerAdmin has succesfully been installed.'); ?></h2>
-<br />
-<?php echo _('Remove this file (install.php) from your webdir.'); ?><br />
-<b><?php echo _('WARNING'); ?>:</b> <?php echo _('PowerAdmin will not work until you delete install.php'); ?><br />
-<br />
-<?php echo _('You can click'); ?> <a href="index.php">here</a> <?php echo _('to start using PowerAdmin'); ?>
-</BODY></HTML>
-<?php
-			die();
-		}
-
-	}
-	else
-	{
-		echo "<DIV CLASS=\"warning\">" . _('You didnt fill in one of the required fields!') . "</DIV>";
-	}
-}
-
-else
-{
-?>
-
-<H2><?php echo _('PowerAdmin for PowerDNS'); ?></H2>
-<BR>
-<B><?php echo _('This config file will setup your database to be ready for PowerAdmin. Please fill in the next fields which will create an
-administrator login.'); ?><BR>
-<?php echo _('Fields marked with a'); ?> <FONT COLOR="#FF0000">*</FONT> <?php echo _('are required.'); ?>
-</B><BR><BR>
-
-<FORM METHOD="post">
-<TABLE BORDER="0" CELLSPACING="4">
-<TR><TD CLASS="tdbg"><?php echo _('Login Name'); ?>:</TD><TD WIDTH="510" CLASS="tdbg"><INPUT TYPE="text" CLASS="input" NAME="login" VALUE=""> <FONT COLOR="#FF0000">*</FONT> </TD></TR>
-<TR><TD CLASS="tdbg"><?php echo _('Password'); ?>:</TD><TD WIDTH="510" CLASS="tdbg"><INPUT TYPE="password" CLASS="input" NAME="password" VALUE=""> <FONT COLOR="#FF0000">*</FONT> </TD></TR>
-<TR><TD CLASS="tdbg"><?php echo _('Full name'); ?>:</TD><TD WIDTH="510" CLASS="tdbg"><INPUT TYPE="text" CLASS="input" NAME="fullname" VALUE=""> <FONT COLOR="#FF0000">*</FONT> </TD></TR>
-<TR><TD CLASS="tdbg"><?php echo _('Email'); ?>:</TD><TD CLASS="tdbg"><INPUT TYPE="text" CLASS="input" NAME="email" VALUE=""> <FONT COLOR="#FF0000">*</FONT> </TD></TR>
-<TR><TD CLASS="tdbg"><?php echo _('Description'); ?>:</TD><TD CLASS="tdbg"><TEXTAREA ROWS="6" COLS="30" CLASS="inputarea" NAME="description"></TEXTAREA></TD></TR>
-<TR><TD CLASS="tdbg">&nbsp;</TD><TD CLASS="tdbg"><INPUT TYPE="submit" CLASS="button" NAME="submit" VALUE="<?php echo _('Make Account'); ?>"></TD></TR>
-</TABLE>
-</FORM>
-<?php
-}
-include_once('inc/footer.inc.php');
-?>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/list_perm_templ.php	Tue Mar 25 22:45:31 2008 +0000
@@ -0,0 +1,62 @@
+<?php
+
+/*  PowerAdmin, a friendly web-based admin tool for PowerDNS.
+ *  See <https://rejo.zenger.nl/poweradmin> for more details.
+ *
+ *  Copyright 2007, 2008  Rejo Zenger <rejo@zenger.nl>
+ *
+ *  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 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+require_once("inc/toolkit.inc.php");
+include_once("inc/header.inc.php");
+verify_permission(templ_perm_edit) ? $perm_templ_perm_edit = "1" : $perm_templ_perm_edit = "0" ;
+
+$permission_templates = get_list_permission_templates() ;
+
+if ($perm_templ_perm_edit == "0") {
+	error(ERR_PERM_EDIT_PERM_TEMPL);
+} else {
+	echo "    <h2>" . _('Permission templates') . "</h2>\n"; 
+	echo "     <table>\n";
+	echo "      <tr>\n";
+	echo "       <th>&nbsp;</th>\n";
+	echo "       <th>" . _('Name') . "</th>\n";
+	echo "       <th>" . _('Description') . "</th>\n";
+	echo "      </tr>\n";
+
+	foreach ($permission_templates as $template) {
+
+		$perm_item_list = get_permissions_by_template_id($template['id'], true);
+		$perm_items = implode(', ', $perm_item_list);
+
+		echo "      <tr>\n";
+		if ($perm_templ_perm_edit == "1") {
+			echo "       <td>\n";
+			echo "        <a href=\"edit_perm_templ.php?id=" . $template["id"] . "\"><img src=\"images/edit.gif\" alt=\"[ " . _('Edit template') . "\" ]></a>\n";
+			echo "        <a href=\"delete_perm_templ.php?id=" . $template["id"] . "\"><img src=\"images/delete.gif\" alt=\"[ " . _('Delete template') . "\" ]></a>\n";
+			echo "       </td>\n";
+		} else {
+			echo "       <td>&nbsp;</td>\n";
+		}
+		echo "       <td class=\"y\">" . $template['name'] . "</td>\n";
+		echo "       <td class=\"y\">" . $template['descr'] . "</td>\n";
+		echo "      </tr>\n";
+	}
+
+	echo "     </table>\n";
+}
+
+include_once("inc/footer.inc.php");
+?>
--- a/list_supermasters.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/list_supermasters.php	Tue Mar 25 22:45:31 2008 +0000
@@ -22,60 +22,41 @@
 require_once("inc/toolkit.inc.php");
 include_once("inc/header.inc.php");
 
-if (!level(5))
-{
-?>
-     <h3><?php echo _('Oops!'); ?></h3>
-     <p><?php echo _('You are not allowed to add supermasters with your current access level!'); ?></p>
-<?php
-} 
-else
-{
+(verify_permission(supermaster_view)) ? $perm_sm_view = "1" :  $perm_sm_view = "0" ;
+(verify_permission(supermaster_edit)) ? $perm_sm_edit = "1" :  $perm_sm_edit = "0" ;
 
-	$supermasters = get_supermasters(0);
-	$num_supermasters = ($supermasters == -1) ? 0 : count($supermasters);
-	?>
+$supermasters = get_supermasters();
 
-	   <h3><?php printf(_('List all %s supermasters'), $num_supermasters); ?></h3>
-	   <table>
-	    <tr>
-	     <th>&nbsp;</td>
-	     <th><?php echo _('IP address of supermaster'); ?></td>
-	     <th><?php echo _('Hostname in NS record'); ?></td>
-	     <th><?php echo _('Account'); ?></td>
-	    </tr>
-	<?php
-	   if ($num_supermasters == 0)
-	   {
-	?>
-	    <tr>
-	     <td class="n">&nbsp;</td>
-	     <td class="n" colspan="3">
-	      <?php echo _('No supermasters in this listing, sorry.'); ?>
-	     </td>
-	    </tr>
-	<?php
-	   }
-	   else
-	   {
-		   foreach ($supermasters as $c)
-		   {
-	?>
-	    <tr>
-	     <td class="n">
-	      <a href="delete_supermaster.php?master_ip=<?php echo $c["master_ip"] ?>"><img src="images/delete.gif" title="<?php print _('Delete supermaster') . ' ' . $c["master_ip"]; ?>" alt="[ <?php echo _('Delete supermaster'); ?> ]"></a>
-	     </td>
-	     <td class="y"><?php echo $c["master_ip"] ?></td>
-	     <td class="y"><?php echo $c["ns_name"] ?></td>
-	     <td class="y"><?php echo $c["account"] ?></td>
-	    </tr>
-	<?php
-		   }
-	   }
-	?>
-	   </table>
-<?php
+echo "     <h2>" . _('List all supermasters') . "</h2>\n";  
+echo "     <table>\n";
+echo "      <tr>\n";
+echo "       <th>&nbsp;</th>\n";
+echo "       <th>" . _('IP address of supermaster') . "</th>\n";
+echo "       <th>" . _('Hostname in NS record') . "</th>\n";
+echo "       <th>" . _('Account') . "</th>\n";
+echo "      </tr>\n";
+if ($num_supermasters == "0") {
+	echo "      <tr>\n";
+	echo "       <td class=\"n\">&nbsp;</td>\n";
+	echo "       <td class=\"n\" colspan=\"3\">\n";
+	echo "        " . _('No supermasters in this listing, sorry.') . "\n";
+	echo "       </td>\n";
+	echo "      </tr>\n";
+} else {
+	foreach ($supermasters as $c) {
+		echo "      <tr>\n";
+		if ($perm_sm_edit == "1") {
+			echo "        <td class=\"n\"><a href=\"delete_supermaster.php?master_ip=" .  $c['master_ip'] . "\"><img src=\"images/delete.gif\" title=\"" . _('Delete supermaster') . ' ' . $c['master_ip'] . "\" alt=\"[  " . _('Delete supermaster') . " ]\"></a></td>\n";
+		} else {
+			echo "<td>&nbsp;</td>\n";
+		}
+		echo "       <td class=\"y\">" . $c['master_ip'] . "</td>\n";
+		echo "       <td class=\"y\">" . $c['ns_name'] . "</td>\n";
+		echo "       <td class=\"y\">" . $c['account'] . "</td>\n";
+		echo "      </tr>\n";
+	}
 }
+echo "     </table>\n";
 
 include_once("inc/footer.inc.php");
 ?>
--- a/list_zones.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/list_zones.php	Tue Mar 25 22:45:31 2008 +0000
@@ -22,110 +22,72 @@
 require_once("inc/toolkit.inc.php");
 include_once("inc/header.inc.php");
 
-$num_all_domains = zone_count(0);
-$doms = zone_count(0, LETTERSTART);
-?>
-   <h2><?php echo _('List all zones'); ?></h2>
-<?php
-        echo "<div class=\"showmax\">";
-        show_pages($doms,ROWAMOUNT);
-        echo "</div>";
+if (verify_permission(zone_content_view_others)) { $perm_view = "all" ; } 
+elseif (verify_permission(zone_content_view_own)) { $perm_view = "own" ; }
+else { $perm_view = "none" ;}
+
+if (verify_permission(zone_content_edit_others)) { $perm_edit = "all" ; } 
+elseif (verify_permission(zone_content_edit_own)) { $perm_edit = "own" ;} 
+else { $perm_edit = "none" ; }
+
+$count_zones_all = zone_count_ng("all");
+$count_zones_all_letterstart = zone_count_ng($perm_view,LETTERSTART); 
+$count_zones_view = zone_count_ng($perm_view);
+$count_zones_edit = zone_count_ng($perm_edit);
+
+echo "    <h2>" . _('List zones') . "</h2>\n";
+
+if ($perm_view == "none") { 
+	echo "     <p>" . _("You do not have the permission to see any zones.") . "</p>\n";
+} else {
+	echo "     <div class=\"showmax\">\n";
+	show_pages($count_zones_all_letterstart,ROWAMOUNT);
+	echo "     </div>\n";
 
-if ($num_all_domains > ROWAMOUNT)
-{
-        echo "<div class=\"showmax\">";
-        show_letters(LETTERSTART);
-        echo "</div>";
-}
-?>
-   <table>
-    <tr>
-     <th>&nbsp;</th>
-     <th><?php echo _('Name'); ?></th>
-     <th><?php echo _('Type'); ?></th>
-     <th><?php echo _('Records'); ?></th>
-     <th><?php echo _('Owner'); ?></th>
-    </tr>
-    <tr>
+	if ($count_zones_view > ROWAMOUNT) {
+		echo "<div class=\"showmax\">";
+		show_letters(LETTERSTART);
+		echo "</div>";
+	}
+	echo "     <table>\n";
+	echo "      <tr>\n";
+	echo "       <th>&nbsp;</th>\n";
+	echo "       <th>" . _('Name') . "</th>\n";
+	echo "       <th>" . _('Type') . "</th>\n";
+	echo "       <th>" . _('Records') . "</th>\n";
+	echo "       <th>" . _('Owner') . "</th>\n";
+	echo "      </tr>\n";
+	echo "      <tr>\n";
 
-<?php
-if ($num_all_domains < ROWAMOUNT) {
-   $doms = get_domains(0,"all",ROWSTART,ROWAMOUNT);
-} else {
-   $doms = get_domains(0,LETTERSTART,ROWSTART,ROWAMOUNT);
-   $num_show_domains = ($doms == -1) ? 0 : count($doms);
-}
+	if ($count_zones_view < ROWAMOUNT) {
+		$zones = get_zones($perm_view,$_SESSION['userid'],"all",ROWSTART,ROWAMOUNT);
+	} else {
+		$zones = get_zones($perm_view,$_SESSION['userid'],LETTERSTART,ROWSTART,ROWAMOUNT);
+		$count_zones_shown = ($zones == -1) ? 0 : count($zones);
+	}
+	foreach ($zones as $zone)
+	{
+		$zone_owners = get_fullnames_owners_from_domainid($zone["id"]);
 
-// If the user doesnt have any domains print a message saying so
-if ($doms < 0)
-{
-	?>
-    <tr>
-     <td>&nbsp;</td>
-     <td colspan="4"><?php echo _('There are no zones.'); ?></td>
-    </tr>
-<?php
+		echo "         <tr>\n";
+		echo "          <td>\n";
+		echo "           <a href=\"edit.php?id=" . $zone['id'] . "\"><img src=\"images/edit.gif\" title=\"" . _('View zone') . " " . $zone['name'] . "\" alt=\"[ " . _('View zone') . " " . $zone['name'] . " ]\"></a>\n";
+		if ( $perm_edit != "all" || $perm_edit != "none") {
+			$user_is_zone_owner = verify_user_is_owner_zoneid($zone["id"]);
+		}
+		if ( $perm_edit == "all" || ( $perm_edit == "own" && $user_is_zone_owner == "1") ) {
+      			echo "           <a href=\"delete_domain.php?id=" . $zone["id"] . "\"><img src=\"images/delete.gif\" title=\"" . _('Delete zone') . " " . $zone['name'] . "\" alt=\"[ ". _('Delete zone') . " " . $zone['name'] . " ]\"></a>\n";
+		}
+		echo "          </td>\n";
+		echo "          <td class=\"y\">" . $zone["name"] . "</td>\n";
+		echo "          <td class=\"y\">" . strtolower($zone["type"]) . "</td>\n";
+		echo "          <td class=\"y\">" . $zone["count_records"] . "</td>\n";
+		echo "          <td class=\"y\">" . $zone_owners . "</td>\n";
+	}
+	echo "           </tr>\n";
+	echo "          </table>\n";
+
 }
 
-// If he has domains, dump them (duh)
-else
-{
-	foreach ($doms as $c)
-	{
-		?>
-		
-    <tr>
-     <td>
-      <a href="edit.php?id=<?php echo $c["id"] ?>"><img src="images/edit.gif" title="<?php echo _('Edit zone') . " " . $c['name']; ?>" alt="[ <?php echo _('Edit zone') . " " . $c['name']; ?> ]"></a>
-<?php
-		if (level(5))
-		{
-?>
-      <a href="delete_domain.php?id=<?php echo $c["id"] ?>"><img src="images/delete.gif" title="<?php print _('Delete zone') . " " . $c['name']; ?>" alt="[<?php echo _('Delete zone') . " " . $c['name']; ?>]"></a>
-<?php
-		}
-?>
-     </td>
-     <td class="y"><?php echo $c["name"] ?></td>
-     <td class="y"><?php echo strtolower(get_domain_type($c["id"])) ?></td>
-     <td class="y"><?php echo $c["numrec"] ?></td>
-
-<?php
-		$zone_owners = get_owners_from_domainid($c["id"]);
-		if ($zone_owners == "")
-		{
-			echo "<td class=\"n\"></td>";
-		}
-		else
-		{
-			print "<td class=\"y\">".$zone_owners."</td>";
-		}
-		print "</tr>\n";
-	}
-}
-
-?>
-   </table>
-
-<?php
-if ($num_all_domains < ROWAMOUNT) {
-?>
-   <p><?php printf(_('This lists shows all %s zones(s) you have access to.'), $num_all_domains); ?></p>
-<?php
-}
-else
-{
-?>
-   <p><?php printf(_('This lists shows %s out of %s zones you have access to.'), $num_show_domains, $num_all_domains); ?></p>
-<?php
-}
-?>
-
-
-<?php // RZ TODO Check next, does it work? 
-//  <small> echo _('You only administer some records of domains marked with an (*).'); </small>
-?>
-
-<?php
 include_once("inc/footer.inc.php");
 ?>
--- a/search.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/search.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,157 +20,117 @@
  */
 
 require_once('inc/toolkit.inc.php');
+include_once('inc/header.inc.php');
 
-if (isset($_POST['s_submit']) || isset($_POST['q']))
-{
-	$submitted=true;
-	$search_result=search_record($_POST['q']);
+if (!(verify_permission(search))) {
+	error(ERR_PERM_SEARCH);
+	include_once('inc/footer.inc.php');
+	exit;
+	
 } else {
-	$submitted = false;
-}
+	echo "     <h2>" . _('Search zones and records') . "</h2>\n";
+
+	if ($_POST['submit']) {
 
-// we will continue after the search form ... 
-include_once('inc/header.inc.php');
-?>
+		if (verify_permission(zone_content_view_others)) { $perm_view = "all" ; }
+		elseif (verify_permission(zone_content_view_own)) { $perm_view = "own" ; }
+		else { $perm_view = "none" ; }
 
-    <h2><?php echo _('Search zones or records'); ?></h2>
-    <h3>Query</h3>
-    <table>
-     <form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
-      <tr>
-       <td class="n"><?php echo _('Enter a hostname or IP address'); ?></td>
-       <td class="n"><input type="text" class="input" name="q"></td>
-      </tr>
-      <tr>
-       <td class="n">&nbsp;</td>
-       <td class="n"><input type="submit" class="button" name="s_submit" value="<?php echo _('Search'); ?>"></td>
-      </tr>
-     </form>
-    </table>
-      
-<?php
-// results
+		if (verify_permission(zone_content_edit_others)) { $perm_edit = "all" ; }
+		elseif (verify_permission(zone_content_edit_own)) { $perm_edit = "own" ; }
+		else { $perm_edit = "none" ; }
+	
+		$holy_grail = $_POST['query'];
+
+		$result = search_zone_and_record($holy_grail,$perm_view);
 
-if ($submitted)
-{
-	echo '<br><br>';
+		if (is_array($result['zones'])) {
+			echo "     <h3>" . _('Zones found') . ":</h3>\n";
+			echo "     <table>\n";
+			echo "      <tr>\n";
+			echo "       <th>&nbsp;</th>\n";
+			echo "       <th>" . _('Name') . "</th>\n";
+			echo "       <th>" . _('Type') . "</th>\n";
+			echo "       <th>" . _('Master') . "</th>\n";
+			echo "      </tr>\n";
 
-  	// let's check if we found any domains ...
-	if (count($search_result) == 2 && count($search_result['domains']))
-  	{
-	?>
-	<h4><?php echo _('Zones found'); ?>:</h4>
-	<table>
-	 <tr>
-	  <th>&nbsp;</th>
-	  <th><?php echo _('Name'); ?></th>
-	  <th><?php echo _('Records'); ?></th>
-	  <th><?php echo _('Owner'); ?></th>
-         </tr>
-<?php
-foreach($search_result['domains'] as $d)
-{
-?>
-         <tr>
-<?php
-  if (level(5))
-  {
-  ?>
-     <td class="n">
-      <a href="edit.php?id=<?php echo $d["id"] ?>"><img src="images/edit.gif" title="<?php echo _('Edit zone') . " " . $d['name']; ?>" alt="[ <?php echo _('Edit zone') . " " . $d['name']; ?> ]"></a>
-      <a href="delete_domain.php?id=<?php echo $d["id"] ?>"><img src="images/delete.gif" title="<?php print _('Delete zone') . " " . $d['name']; ?>" alt="[<?php echo _('Delete zone') . " " . $d['name']; ?>]"></a>
-     </td>
-<?php
-}
-else
-{
-?>
-     <td class="n">
-      &nbsp;
-     </td>
-<?php
-}
-?>
-     <td class="y"><?php echo $d['name']?></td>
-     <td class="y"><?php echo $d['numrec']?></td>
-     <td class="y"><?php echo get_owner_from_id($d['owner'])?></td>
-    </tr>
-			<?php
-		} // end foreach ...
-		?>
-	</table>
-	<br><br>
-	<?php
-	} // end if
-	
-	// any records ?!
-	if(count($search_result['records']))
-	{
-		?>
-		<b><?php echo _('Records found'); ?>:</b>
-		<p>
-		<table>
-			<tr>
-				<td class="n">&nbsp;</td>
-				<td class="n"><?php echo _('Name'); ?></td>
-				<td class="n"><?php echo _('Type'); ?></td>
-				<td class="n"><?php echo _('Content'); ?></td>
-				<td class="n"><?php echo _('Priority'); ?></td>
-				<td class="n"><?php echo _('TTL'); ?></td>
-			</tr>
-		<?php
-		foreach($search_result['records'] as $r)
-		{
-		?>
-			<tr>
-				<td class="n">
-			<?php
-			if (($r["type"] != "SOA" && $r["type"] != "NS") ||
-			  ($GLOBALS["ALLOW_SOA_EDIT"] && $r["type"] == "SOA") ||
-			  ($GLOBALS["ALLOW_NS_EDIT"] && $r["type"] == "NS") ||
-			  ($r["type"] == "NS" && get_name_from_record_id($r["id"]) != get_domain_name_from_id(recid_to_domid($r["id"])) && 
-			  $GLOBALS["ALLOW_NS_EDIT"] != 1))
-			{
-				?>
-				<a href="edit_record.php?id=<?php echo $r['id']?>&amp;domain=<?php echo $r['domain_id']?>"><img src="images/edit.gif" alt="[ <?php echo _('Edit record'); ?> ]" border="0"></a>
-				<a href="delete_record.php?id=<?php echo $r['id']?>&amp;domain=<?php echo $r['domain_id']?>"><img src="images/delete.gif" alt="[ <?php echo _('Delete record'); ?> ]" border="0"></a>
-				<?php 
-			} // big if ;-)
-			?>
-			</td>
-			<td class="y"><?php echo $r['name']?></td>
-			<td class="y"><?php echo $r['type']?></td>
-			<td class="y"><?php echo $r['content']?></td>
-			<?php
-			if ($r['prio'] != 0)
-			{
-				?><td class="y"><?php echo $r['prio']?></td><?php
+			foreach ($result['zones'] as $zone) {
+				echo "      <tr>\n";
+				echo "          <td>\n";
+				echo "           <a href=\"edit.php?id=" . $zone['zid'] . "\"><img src=\"images/edit.gif\" title=\"" . _('Edit zone') . " " . $zone['name'] . "\" alt=\"[ " . _('Edit zone') . " " . $zone['name'] . " ]\"></a>\n";
+				if ( $perm_edit != "all" || $perm_edit != "none") {
+					$user_is_zone_owner = verify_user_is_owner_zoneid($zone['zid']);
+				}
+				if ( $perm_edit == "all" || ( $perm_edit == "own" && $user_is_zone_owner == "1") ) {
+					echo "           <a href=\"delete_domain.php?id=" . $zone['zid'] . "\"><img src=\"images/delete.gif\" title=\"" . _('Delete zone') . " " . $zone['name'] . "\" alt=\"[ ". _('Delete zone') . " " . $zone['name'] . " ]\"></a>\n";
+				}
+				echo "          </td>\n";
+				echo "       <td>" . $zone['name'] . "</td>\n";
+				echo "       <td>" . $zone['type'] . "</td>\n";
+				if ($zone['type'] == "SLAVE") {
+					echo "       <td>" . $zone['master'] . "</td>\n";
+				} else {
+					echo "       <td>&nbsp;</td>\n";
+				}
+				echo "      </tr>\n";
 			}
-			else 
-			{
-			?><td class="n"></td><?php
-			} // else
-			?><td class="y"><?php echo $r['ttl']?></td>
-			</tr>
-			<?php
-		} // foreach
-	?>
-	</table>
-	<?php
-	} // if
-	if(count($search_result['domains']) == 0 && count($search_result['records']) == 0)
-	{
-	?>
-		<table border="0" cellspacing="4">
-			<tr>
-				<td width="510" class="n">
-				<?php echo _('Nothing found for query'); ?> "<?php echo $_POST['q']?>".
-				</td>
-			</tr>
-		</table>
-	<?php
+			echo "     </table>\n";
+		}
+
+		if (is_array($result['records'])) {
+			echo "     <h3>" . _('Records found') . ":</h3>\n";
+			echo "     <table>\n";
+			echo "      <tr>\n";
+			echo "       <th>&nbsp;</th>\n";
+			echo "       <th>" . _('Name') . "</th>\n";
+			echo "       <th>" . _('Type') . "</th>\n";
+			echo "       <th>" . _('Prio') . "</th>\n";
+			echo "       <th>" . _('Content') . "</th>\n";
+			echo "       <th>" . _('TTL') . "</th>\n";
+			echo "      </tr>\n";
+
+			foreach ($result['records'] as $record) {
+
+				echo "      <tr>\n";
+				echo "          <td>\n";
+				echo "           <a href=\"edit_record.php?id=" . $record['rid'] . "\"><img src=\"images/edit.gif\" title=\"" . _('Edit record') . " " . $record['name'] . "\" alt=\"[ " . _('Edit record') . " " . $record['name'] . " ]\"></a>\n";
+				if ( $perm_edit != "all" || $perm_edit != "none") {
+					$user_is_zone_owner = verify_user_is_owner_zoneid($record['zid']);
+				}
+				if ( $perm_edit == "all" || ( $perm_edit == "own" && $user_is_zone_owner == "1") ) {
+					echo "           <a href=\"delete_record.php?id=" . $record['rid'] . "\"><img src=\"images/delete.gif\" title=\"" . _('Delete record') . " " . $record['name'] . "\" alt=\"[ ". _('Delete record') . " " . $record['name'] . " ]\"></a>\n";
+				}
+				echo "          </td>\n";
+				echo "       <td>" . $record['name'] . "</td>\n";
+				echo "       <td>" . $record['type'] . "</td>\n";
+				if ($record['type'] == "MX") {
+					echo "       <td>" . $record['prio'] . "</td>\n";
+				} else {
+					echo "       <td>&nbsp;</td>\n";
+				}
+				echo "       <td>" . $record['content'] . "</td>\n";
+				echo "       <td>" . $record['ttl'] . "</td>\n";
+				echo "      </tr>\n";
+			}
+			echo "     </table>\n";
+		}
+
 	}
-		
+
+	echo "     <h3>" . _('Query') . ":</h3>\n";
+	echo "     <table>\n";
+	echo "      <form method=\"post\" action=\"" . $_SERVER['PHP_SELF'] . "\">\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">" . _('Enter a hostname or IP address') . "</td>\n";
+	echo "        <td class=\"n\"><input type=\"text\" class=\"input\" name=\"query\" value=\"" . $holy_grail . "\"></td>\n";
+	echo "       </tr>\n";
+	echo "       <tr>\n";
+	echo "        <td class=\"n\">&nbsp;</td>\n";
+	echo "        <td class=\"n\"><input type=\"submit\" class=\"button\" name=\"submit\" value=\"" . _('Search') . "\"></td>\n";
+	echo "       </tr>\n";
+	echo "      </form>\n";
+	echo "     </table>\n";
+
 }
 include_once('inc/footer.inc.php');
 ?>
--- a/style/example.inc.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/style/example.inc.php	Tue Mar 25 22:45:31 2008 +0000
@@ -138,12 +138,12 @@
 
 
 
-
-
-
-
-
-
+textarea {
+	width: 			100%;
+}
+input.wide {
+	width: 			100%;
+}
 
 
 <?php
--- a/style/style.css.php	Wed Mar 12 20:45:56 2008 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,148 +0,0 @@
-<?php
-
-/*  PowerAdmin, a friendly web-based admin tool for PowerDNS.
- *  See <https://rejo.zenger.nl/poweradmin> for more details.
- *
- *  Copyright 2007, 2008  Rejo Zenger <rejo@zenger.nl>
- *
- *  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 3 of the License, or
- *  (at your option) any later version.
- *
- *  This program is distributed in the hope that it will be useful,
- *  but WITHOUT ANY WARRANTY; without even the implied warranty of
- *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *  GNU General Public License for more details.
- *
- *  You should have received a copy of the GNU General Public License
- *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-
-include_once("../inc/config.inc.php");
-$bgcolor = "#FCC229"; //Original style
-?>
-
-
-A:link { color: #000000}
-A:visited { color: #000000}
-A:active { color: #000000}
-A:hover {text-decoration: none}
-BODY {font-family: Verdana, Arial, Helvetica; background-image: url("<?php echo $GLOBALS["BASE_URL"].$GLOBALS["BASE_PATH"]; ?>images/background.jpg");}
-TABLE {background-color: <?php echo $bgcolor; ?>; border: 1px solid #000000; width: 900px;}
-TD {background-color: White; font-size: 12px;}
-TR {background-color: <?php echo $bgcolor; ?>}
-.TDBG {
-        background-color: <?php echo $bgcolor; ?>;
-}
-.ERROR {
-        background-color: #FF0000;
-        border: 1px solid;
-        width: 600px;
-}
-.MESSAGETABLE {
-        background-color: <?php echo $bgcolor; ?>;
-        border: 1px solid;
-        width: 600px;
-}
-
-.MESSAGE {
-        background-color: <?php echo $bgcolor; ?>;
-        width: 600px;
-}
-.NONE {
-        background-color: transparent;
-        border: none;
-        width: 0px;
-}
-.TEXT {
-	background-color: transparent !important; 
-	border: 0px; 
-}
-.SBUTTON {
-        BORDER-BOTTOM: #999999 1px solid;
-        BORDER-LEFT: #999999 1px solid;
-        BORDER-RIGHT: #999999 1px solid;
-        BORDER-TOP: #999999 1px solid;
-        BACKGROUND-COLOR: <?php echo $bgcolor; ?>;
-        COLOR: #000000;
-        BORDER-COLOR: #000000;
-        FONT-FAMILY: Verdana;
-        FONT-WEIGHT: Bold;
-        FONT-SIZE: 10px;
-        WIDTH MENARU: 60px;
-}
-.BUTTON {
-        BORDER-BOTTOM: #999999 1px solid;
-        BORDER-LEFT: #999999 1px solid;
-        BORDER-RIGHT: #999999 1px solid;
-        BORDER-TOP: #999999 1px solid;
-        BACKGROUND-COLOR: <?php echo $bgcolor; ?>;
-        COLOR: #000000;
-        BORDER-COLOR: #000000;
-        FONT-FAMILY: Verdana;
-        FONT-WEIGHT: Bold;
-        FONT-SIZE: 10px;
-        WIDTH MENARU: 120px;
-}
-.INPUT {
-        BORDER-BOTTOM: #999999 1px solid;
-        BORDER-LEFT: #999999 1px solid;
-        BORDER-RIGHT: #999999 1px solid;
-        BORDER-TOP: #999999 1px solid;
-        BACKGROUND-COLOR: #FFFFFF;
-
-        COLOR: #000000;
-        BORDER-COLOR: #000000;
-        FONT-FAMILY: Verdana;
-        FONT-SIZE: 11px;
-        WIDTH MENARU: 180px;
-}
-.SINPUT {
-        BORDER-BOTTOM: #999999 1px solid;
-        BORDER-LEFT: #999999 1px solid;
-        BORDER-RIGHT: #999999 1px solid;
-        BORDER-TOP: #999999 1px solid;
-        BACKGROUND-COLOR: #FFFFFF;
-        COLOR: #000000;
-        BORDER-COLOR: #000000;
-        FONT-FAMILY: Verdana;
-        FONT-SIZE: 11px;
-        WIDTH MENARU: 40px;
-}
-.WARNING {
-        color: #FF0000;
-        font-weight: Bold;
-}
-.FOOTER {
-        font-size: 10px;
-}
-.ACTIVE {
-        color: #669933;
-        font-weight: Bold;
-}
-.INACTIVE {
-        color: #FF0000;
-        font-weight: Bold;
-}
-.NAV {
-        color: #0000FF;
-        font-weight: Bold;
-        A:link { color: #0000FF}
-        A:visited { color: #0000FF}
-        A:active { color: #0000FF}
-        A:hover {text-decoration: none}
-}
-.inputarea {
-        BORDER-BOTTOM: #999999 1px solid;
-        BORDER-LEFT: #999999 1px solid;
-        BORDER-RIGHT: #999999 1px solid;
-        BORDER-TOP: #999999 1px solid;
-        BACKGROUND-COLOR: #FFFFFF;
-        COLOR: #000000;
-        BORDER-COLOR: #000000;
-        FONT-FAMILY: Verdana;
-        FONT-SIZE: 11px;
-        WIDTH MENARU: 300px;
-        HEIGHT MENARU: 100px;
-}
--- a/users.php	Wed Mar 12 20:45:56 2008 +0000
+++ b/users.php	Tue Mar 25 22:45:31 2008 +0000
@@ -20,144 +20,80 @@
  */
 
 require_once("inc/toolkit.inc.php");
+include_once("inc/header.inc.php");
+verify_permission(user_view_others) ? $perm_view_others = "1" : $perm_view_others = "0" ;
+verify_permission(user_edit_own) ? $perm_edit_own = "1" : $perm_edit_own = "0" ;
+verify_permission(user_edit_others) ? $perm_edit_others = "1" : $perm_edit_others = "0" ;
+verify_permission(templ_perm_edit) ? $perm_templ_perm_edit = "1" : $perm_templ_perm_edit = "0" ;
+verify_permission(is_ueberuser) ? $perm_is_godlike = "1" : $perm_is_godlike = "0" ; 
 
-if(isset($_POST["submit"])
-&& isset($_POST['username']) && $_POST["username"] != ""
-&& isset($_POST['password']) && $_POST["password"] != "" 
-&& isset($_POST['fullname']) && $_POST["fullname"] != ""
-&& isset($_POST['email']) && $_POST["email"] != ""
-&& isset($_POST['level']) && $_POST["level"] > 0)
-{
-	if(substr_count($_POST["username"], " ") == 0)
-	{
-		if(strlen($_POST["password"]) < 8)
-		{
-		$error = _('Password length should be at least 8 characters.');
-		}
-		else
-		{
-			add_user($_POST["username"], $_POST["password"], $_POST["fullname"], $_POST["email"], $_POST["level"], $_POST["description"], $_POST["active"]);
-			clean_page("users.php");
-		}
+if (isset($_POST['commit'])) {
+	foreach ($_POST['user'] as $user) {
+		update_user_details($user);
 	}
-        else
-        {
-        	$error = _('Usernames can\'t contain spaces');
-        }
-}
-elseif(isset($_POST["submit"]))
-{
-	$error = _('Please fill in all fields');
 }
 
-include_once("inc/header.inc.php");
-if (isset($error) && $error != "") 
-{
-?>
-	<div class="error"><?php echo $error ; ?></div>
-<?php
-}
-?>
-    <h2><?php echo _('User admin'); ?></h2>
-<?php
-if (!level(10)) 
-{
-	error(ERR_LEVEL_10);
-}
-?>
-     <h3><?php echo _('Current users'); ?></h3>
-<?php
-$users = show_users('');
-?>  
+$users = get_user_detail_list("");
+echo "    <h2>" . _('User admin') . "</h2>\n";
+echo "    <form method=\"post\">\n";
+echo "     <table>\n";
+echo "      <tr>\n";
+echo "       <th>&nbsp;</th>\n";
+echo "       <th>" . _('Username') . "</th>\n";
+echo "       <th>" . _('Fullname') . "</th>\n";
+echo "       <th>" . _('Description') . "</th>\n";
+echo "       <th>" . _('Emailaddress') . "</th>\n";
+echo "       <th>" . _('Template') . "</th>\n";
+echo "       <th>" . _('Enabled') . "</th>\n";
+echo "      </tr>\n";
 
-      <table>
-       <tr>
-        <th>&nbsp;</th>
-        <th><?php echo _('Name'); ?></th>
-        <th><?php echo _('Zones'); ?> (<?php echo _('access'); ?>)</th>
-        <th><?php echo _('Zones'); ?> (<?php echo _('owner'); ?>)</th>
-        <th><?php echo _('Zone list'); ?></th>
-        <th><?php echo _('Level'); ?></th>
-        <th><?php echo _('Status'); ?></th>
-       </tr>
-<?php
-$users = show_users('',ROWSTART,ROWAMOUNT);
-foreach ($users as $c)
-{
-        $domains = get_domains_from_userid($c["id"]);
-	$num_zones_access = count($domains);
-?>
-       <tr>
-        <td class="n"><a href="delete_user.php?id=<?php echo $c["id"] ?>"><img src="images/delete.gif" alt="[ <?php echo _('Delete user'); ?> ]"></a></td>
-        <td class="n"><a href="edit_user.php?id=<?php echo $c["id"] ?>"><?php echo $c["fullname"] ?></A> (<?php echo $c["username"] ?>)</td>
-        <td class="n"><?php echo $num_zones_access ?></td>
-        <td class="n"><?php echo $c["numdomains"] ?></td>
-        <td class="n">
-        <?php
-        foreach ($domains as $d)
-        {
-                ?><a href="delete_domain.php?id=<?php echo $d["id"] ?>"><img src="images/delete.gif" alt="[ <?php echo _('Delete domain'); ?> ]"></a>&nbsp;<a href="edit.php?id=<?php echo $d["id"] ?>"><?php echo $d["name"] ?><?php if ($d["partial"] == "1") { echo " *"; } ; ?></a><br><?php
-        }
-        ?></td>
-	<td class="n"><?php echo $c["level"] ?></td>
-	<td class="n"><?php echo get_status($c["active"]) ?></td>
-       </tr><?php
-        print "\n";
+foreach ($users as $user) {
+	if ($user['active'] == "1" ) {
+		$active = " checked";
+	} else {
+		$active = "";
+	}
+	echo "      <input type=\"hidden\" name=\"user[" . $user['uid'] . "][uid]\" value=\"" . $user['uid'] . "\">\n";
+	echo "      <tr>\n";
+	echo "       <td>\n";
+	if (($user['uid'] == $_SESSION["userid"] && $perm_edit_own == "1") || ($user['uid'] != $_SESSION["userid"] && $perm_edit_others == "1" )) {
+		echo "        <a href=\"edit_user.php?id=" . $user['uid'] . "\"><img src=\"images/edit.gif\" alt=\"[ " . _('Edit user') . "\" ]></a>\n";
+		echo "        <a href=\"delete_user.php?id=" . $user['uid'] . "\"><img src=\"images/delete.gif\" alt=\"[ " . _('Delete user') . "\" ]></a>\n";
+	} else {
+		echo "        &nbsp;\n";
+	}
+	echo "       </td>\n";
+	echo "       <td><input type=\"text\" name=\"user[" . $user['uid'] . "][username]\" value=\"" . $user['username'] . "\"></td>\n";
+	echo "       <td><input type=\"text\" name=\"user[" . $user['uid'] . "][fullname]\" value=\"" . $user['fullname'] . "\"></td>\n";
+	echo "       <td><input type=\"text\" name=\"user[" . $user['uid'] . "][descr]\" value=\"" . $user['descr'] . "\"></td>\n";
+	echo "       <td><input type=\"text\" name=\"user[" . $user['uid'] . "][email]\" value=\"" . $user['email'] . "\"></td>\n";
+	echo "       <td>\n";
+	echo "        <select name=\"user[" . $user['uid'] . "][templ_id]\">\n";
+
+	foreach (list_permission_templates() as $template) {
+		($template['id'] == $user['tpl_id']) ? $select = " SELECTED" : $select = "" ;
+		echo "          <option value=\"" . $template['id'] . "\"" . $select . ">" . $template['name'] . "</option>\n";
+	}
+	echo "         </select>\n";
+	echo "       </td>\n";
+	echo "       <td><input type=\"checkbox\" name=\"user[" . $user['uid'] . "][active]\"" . $active . "></td>\n";
+	echo "      </tr>\n";
 }
-?>
-       
-      </table>
-      <p><?php echo _('Users may only change some of the records of zones marked with an (*).'); ?></p>
-      <p><?php echo _('Number of users') ;?>: <?php echo count($users); ?>.</p>
-      <div class="showmax">
-<?php
-show_pages(count($users),ROWAMOUNT);
-?>
-      </div> <?php // eo div showmax ?>
+
+echo "     </table>\n";
+echo "     <input type=\"submit\" class=\"button\" name=\"commit\" value=\"" . _('Commit changes') . "\">\n";
+echo "    </form>\n";
 
-      <h3><?php echo _('Create new user'); ?></h3>
-      <form method="post" action="users.php">
-       <table>
-        <tr>
-         <td class="n"><?php echo _('User name'); ?>:</td>
-         <td class="n"><input type="text" class="input" name="username" value="<?php if (isset($error)) print $_POST["username"]; ?>"></td>
-	</tr>
-	<tr>
-	 <td class="n"><?php echo _('Full name'); ?>:</td>
-	 <td class="n"><input type="text" class="input" NAME="fullname" VALUE="<?php if (isset($error)) print $_POST["fullname"]; ?>"></td>
-	</tr>
-	<tr>
-	 <td class="n"><?php echo _('Password'); ?>:</td>
-	 <td class="n"><input type="password" class="input" NAME="password" VALUE="<?php if (isset($error)) print $_POST["password"]; ?>"></td>
-	</tr>
-	<tr>
-	 <td class="n"><?php echo _('E-mail'); ?>:</td>
-	 <td class="n"><input type="text" class="input" NAME="email" VALUE="<?php if (isset($error)) print $_POST["email"]; ?>"></td>
-	</tr>
-	<tr>
-	 <td class="n"><?php echo _('User level'); ?>:</td>
-	 <td class="n">
-	  <select name="level">
-	   <option value="1">1 (<?php echo leveldescription(1) ?>)</option>
-	   <option value="5">5 (<?php echo leveldescription(5) ?>)</option>
-	   <option value="10">10 (<?php echo leveldescription(10) ?>)</option>
-	  </select>
-	 </td>
-	</tr>
-        <tr>
-	 <td class="n"><?php echo _('Description'); ?>:</td>
-	 <td class="n"><textarea rows="6" cols="30" class="inputarea" name="description"><?php if (isset($error)) print $_POST["description"]; ?></textarea></td>
-	</tr>
-	<tr>
-	 <td class="n"><?php echo _('Active'); ?>:</td>
-	 <td class="n"><input type="checkbox" name="active" value="1" checked></td>
-	</tr>
-	<tr>
-	 <td class="n">&nbsp;</td>
-	 <td class="n"><input type="submit" class="button" name="submit" value="<?php echo _('Add user'); ?>"></td>
-	</tr>
-       </table>
-      </form>
-<?php
+echo "    <p>\n";
+if ($perm_templ_perm_edit == "1") {
+	echo _('Edit') . " <a href=\"list_perm_templ.php\">" . _('permission templates') . "</a>. \n";
+}
+
+if (verify_permission(user_add_new)) {
+	echo _('Add') . " <a href=\"add_user.php\">" . _('user') . "</a>. \n";
+}
+echo "    </p>\n";
+
+
 include_once("inc/footer.inc.php");
 ?>