inc/record.inc.php
changeset 1 58094faf794d
child 5 ebf8868e99f5
equal deleted inserted replaced
0:2cd8c1649ba9 1:58094faf794d
       
     1 <?
       
     2 
       
     3 // +--------------------------------------------------------------------+
       
     4 // | PowerAdmin                                                         |
       
     5 // +--------------------------------------------------------------------+
       
     6 // | Copyright (c) 1997-2002 The PowerAdmin Team                        |
       
     7 // +--------------------------------------------------------------------+
       
     8 // | This source file is subject to the license carried by the overal   |
       
     9 // | program PowerAdmin as found on http://poweradmin.sf.net            |
       
    10 // | The PowerAdmin program falls under the QPL License:                |
       
    11 // | http://www.trolltech.com/developer/licensing/qpl.html              |
       
    12 // +--------------------------------------------------------------------+
       
    13 // | Authors: Roeland Nieuwenhuis <trancer <AT> trancer <DOT> nl>       |
       
    14 // |          Sjeemz <sjeemz <AT> sjeemz <DOT> nl>                      |
       
    15 // +--------------------------------------------------------------------+
       
    16 
       
    17 // Filename: record.inc.php
       
    18 // Startdate: 26-10-2002
       
    19 // This file is ought to edit the records in the database.
       
    20 // Records are domains aswell, they also belong here.
       
    21 // All database functions are associative.
       
    22 // use nextID first to get a new id. Then insert it into the database.
       
    23 // do not rely on auto_increment (see above).
       
    24 // use dns.inc.php for validation functions.
       
    25 //
       
    26 // $Id: record.inc.php,v 1.21 2003/05/10 20:21:01 azurazu Exp $
       
    27 //
       
    28 
       
    29 
       
    30 function update_soa_serial($domain_id)
       
    31 {
       
    32     global $db;
       
    33 	/*
       
    34 	 * THIS CODE ISNT TESTED THROUGH MUCH YET!
       
    35 	 * !!!!!!! BETACODE !!!!!!!!!!
       
    36 	 * Code committed by DeViCeD, Thanks a lot!
       
    37 	 * Heavily hax0red by Trancer/azurazu
       
    38 	 *
       
    39 	 * First we have to check, wheather current searial number 
       
    40 	 * was already updated on the other nameservers.
       
    41 	 * If field 'notified_serial' is NULL, then I guess domain is
       
    42 	 * NATIVE and we don't have any secondary nameservers for this domain.
       
    43 	 * NOTICE: Serial number *will* be RFC1912 compilant after update 
       
    44 	 * NOTICE: This function will allow only 100 DNS zone transfers ;-)
       
    45 	 * YYYYMMDDnn
       
    46 	 */
       
    47 
       
    48 	$sqlq = "SELECT `notified_serial` FROM `domains` WHERE `id` = '".$domain_id."'";
       
    49 	$notified_serial = $db->getOne($sqlq);
       
    50 
       
    51 	$sqlq = "SELECT `content` FROM `records` WHERE `type` = 'SOA' AND `domain_id` = '".$domain_id."'";
       
    52 	$content = $db->getOne($sqlq);
       
    53     $need_to_update = false;
       
    54 	
       
    55 	// Getting the serial field.
       
    56 	$soa = explode(" ", $content);
       
    57 	
       
    58 	if(empty($notified_serial))
       
    59     {
       
    60         // Ok native replication, so we have to update.
       
    61         $need_to_update = true;
       
    62     }
       
    63     elseif($notified_serial >= $soa[2])
       
    64     {
       
    65         $need_to_update = true;
       
    66     }
       
    67     elseif(strlen($soa[2]) != 10)
       
    68     {
       
    69         $need_to_update = true;
       
    70     }
       
    71     else
       
    72     {
       
    73         $need_to_update = false;
       
    74     }
       
    75     if($need_to_update)
       
    76     {
       
    77         // Ok so we have to update it seems.
       
    78         $current_serial = $soa[2];
       
    79         
       
    80 		/*
       
    81 		 * What we need here (for RFC1912) is YEAR, MONTH and DAY
       
    82 		 * so let's get it ...
       
    83 		 */
       
    84 		$new_serial = date('Ymd'); // we will add revision number later
       
    85 
       
    86 		if(strncmp($new_serial, $current_serial, 8) === 0)
       
    87 		{
       
    88             /*
       
    89              * Ok, so we already made updates tonight
       
    90              * let's just increase the revision number
       
    91              */				
       
    92             $revision_number = (int) substr($current_serial, -2);
       
    93             if ($revision_number == 99) return false; // ok, we cannot update anymore tonight
       
    94             ++$revision_number;
       
    95             // here it is ... same date, new revision
       
    96             $new_serial .= str_pad($revision_number, 2, "0", STR_PAD_LEFT);	
       
    97 		}
       
    98  		else
       
    99 		{
       
   100             /*
       
   101 			 * Current serial is not RFC1912 compilant, so let's make a new one
       
   102 			 */
       
   103  			$new_serial .= '00';
       
   104 		}
       
   105         $soa[2] = $new_serial; // change serial in SOA array
       
   106 		$new_soa = "";		
       
   107 		// build new soa and update SQL after that
       
   108 		for ($i = 0; $i < count($soa); $i++) 
       
   109 		{	
       
   110 			$new_soa .= $soa[$i] . " "; 
       
   111 		}
       
   112 		$sqlq = "UPDATE `records` SET `content` = '".$new_soa."' WHERE `domain_id` = '".$domain_id."' AND `type` = 'SOA' LIMIT 1";
       
   113 		$db->Query($sqlq);
       
   114 		return true;
       
   115 	}
       
   116 }  
       
   117 
       
   118 /*
       
   119  * Edit a record.
       
   120  * This function validates it if correct it inserts it into the database.
       
   121  * return values: true if succesful.
       
   122  */
       
   123 function edit_record($recordid, $zoneid, $name, $type, $content, $ttl, $prio)
       
   124 {
       
   125 	global $db;
       
   126   	if($content == "")
       
   127   	{
       
   128   		error(ERR_RECORD_EMPTY_CONTENT);
       
   129   	}
       
   130   	// Edits the given record (validates specific stuff first)
       
   131 	if (!xs(recid_to_domid($recordid)))
       
   132 	{
       
   133 		error(ERR_RECORD_ACCESS_DENIED);
       
   134 	}
       
   135 	if (is_numeric($zoneid))
       
   136 	{
       
   137 		validate_input($recordid, $zoneid, $type, $content, $name, $prio, $ttl);
       
   138                 $change = time();
       
   139                 $db->query("UPDATE records set name='$name', type='$type', content='$content', ttl='$ttl', prio='$prio', change_date='$change' WHERE id=$recordid");
       
   140 		
       
   141 		/*
       
   142 		 * Added by DeViCeD - Update SOA Serial number
       
   143 		 * There should be more checks
       
   144 		 */
       
   145 		if ($type != 'SOA')
       
   146 		{
       
   147 			update_soa_serial($zoneid);
       
   148 		}
       
   149 		return true;
       
   150 	}
       
   151 	else
       
   152 	{
       
   153 		error(sprintf(ERR_INV_ARGC, "edit_record", "no zoneid given"));
       
   154 	}
       
   155 
       
   156 }
       
   157 
       
   158 
       
   159 /*
       
   160  * Adds a record.
       
   161  * This function validates it if correct it inserts it into the database.
       
   162  * return values: true if succesful.
       
   163  */
       
   164 function add_record($zoneid, $name, $type, $content, $ttl, $prio)
       
   165 {
       
   166 
       
   167 	global $db;
       
   168 	if (!xs($zoneid))
       
   169 	{
       
   170 		error(ERR_RECORD_ACCESS_DENIED);
       
   171 	}
       
   172 	if (is_numeric($zoneid))
       
   173 	{
       
   174 
       
   175 		// Get the Insert ID, we can not rely on auto_increment
       
   176 		$idrecords = $db->nextID('records');
       
   177 
       
   178 		// Check the user input.
       
   179 		validate_input($idrecords, $zoneid, $type, $content, $name, $prio, $ttl);
       
   180 
       
   181 		// Generate new timestamp for the Daemon
       
   182 		$change = time();
       
   183 		// Execute query.
       
   184 		$db->query("INSERT INTO records (id, domain_id, name, type, content, ttl, prio, change_date) VALUES ($idrecords, $zoneid, '$name', '$type', '$content', $ttl, '$prio', $change)");
       
   185 		if ($type != 'SOA')
       
   186 		{
       
   187 			update_soa_serial($zoneid);
       
   188 		}
       
   189 		return true;
       
   190 	}
       
   191 	else
       
   192 	{
       
   193 		error(sprintf(ERR_INV_ARG, "add_record"));
       
   194 	}
       
   195 }
       
   196 
       
   197 
       
   198 /*
       
   199  * Delete a record by a given id.
       
   200  * return values: true, this function is always succesful.
       
   201  */
       
   202 function delete_record($id)
       
   203 {
       
   204 	global $db;
       
   205 
       
   206 	// Check if the user has access.
       
   207 	if (!xs(recid_to_domid($id)))
       
   208 	{
       
   209 		error(ERR_RECORD_ACCESS_DENIED);
       
   210 	}
       
   211 
       
   212 	// Retrieve the type of record to see if we can actually remove it.
       
   213 	$recordtype = get_recordtype_from_id($id);
       
   214 
       
   215 	// If the record type is NS and the user tries to delete it while ALLOW_NS_EDIT is set to 0
       
   216 	// OR
       
   217 	// check if the name of the record isnt the domain name (if so it should delete all records)
       
   218 	// OR
       
   219 	// check if we are dealing with a SOA field (same story as NS)
       
   220 	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))
       
   221 	{
       
   222 		error(sprintf(ERR_RECORD_DELETE_TYPE_DENIED, $recordtype));
       
   223 
       
   224 	}
       
   225 	if (is_numeric($id))
       
   226 	{
       
   227 	    $did = recid_to_domid($id);
       
   228 		$db->query('DELETE FROM records WHERE id=' . $id . ' LIMIT 1');
       
   229 		if ($type != 'SOA')
       
   230 		{
       
   231 			update_soa_serial($did);
       
   232 		}
       
   233         // $id doesnt exist in database anymore so its deleted or just not there which means "true"	
       
   234 		return true;
       
   235 	}
       
   236 	else
       
   237 	{
       
   238 		error(sprintf(ERR_INV_ARG, "delete_record"));
       
   239 	}
       
   240 }
       
   241 
       
   242 
       
   243 /*
       
   244  * Add a domain to the database.
       
   245  * A domain is name obligatory, so is an owner.
       
   246  * return values: true when succesful.
       
   247  * Empty means templates dont have to be applied.
       
   248  * --------------------------------------------------------------------------
       
   249  * This functions eats a template and by that it inserts various records.
       
   250  * first we start checking if something in an arpa record
       
   251  * remember to request nextID's from the database to be able to insert record.
       
   252  * if anything is invalid the function will error
       
   253  */
       
   254 function add_domain($domain, $owner, $webip, $mailip, $empty, $type)
       
   255 {
       
   256 
       
   257 	global $db;
       
   258 
       
   259 	if (!level(5))
       
   260 	{
       
   261 		error(ERR_LEVEL_5);
       
   262 	}
       
   263 
       
   264 	// If domain, owner and mailip are given
       
   265 	// OR
       
   266 	// empty is given and owner and domain
       
   267 	// OR
       
   268 	// the domain is an arpa record and owner is given
       
   269 	// THAN
       
   270 	// Continue this function
       
   271 	if (($domain && $owner && $webip && $mailip) || ($empty && $owner && $domain) || (eregi('in-addr.arpa', $domain) && $owner))
       
   272 	{
       
   273 		// Retrieve next zones id.
       
   274 		$idzones = $db->nextID('zones');
       
   275 		$iddomains = $db->nextID('domains');
       
   276 
       
   277 		$db->query("INSERT INTO zones (id, domain_id, owner) VALUES ('$idzones', '$iddomains', $owner)");
       
   278 
       
   279 		/*
       
   280 		 * TODO : NATIVE OPERATION ONLY FOR NOW
       
   281 		 */
       
   282 
       
   283 		$db->query("INSERT INTO domains (id, name, type) VALUES ('$iddomains', '$domain', '$type')");
       
   284 
       
   285 		// Generate new timestamp. We need this one anyhow.
       
   286 		$now = time();
       
   287 
       
   288 		if ($empty && $iddomains)
       
   289 		{
       
   290 			// If we come into this if statement we dont want to apply templates.
       
   291 			// Retrieve configuration settings.
       
   292 			$ns1 = $GLOBALS["NS1"];
       
   293 			$hm  = $GLOBALS["HOSTMASTER"];
       
   294 			$ttl = $GLOBALS["DEFAULT_TTL"];
       
   295 
       
   296 			// Retrieve next records id
       
   297 			$idrecords = $db->nextID('records');
       
   298 
       
   299 			// Build and execute query
       
   300 			$sql = "INSERT INTO records (id, domain_id, name, content, type, ttl, prio, change_date) VALUES ('$idrecords', '$iddomains', '$domain', '$ns1 $hm 1', 'SOA', $ttl, '', '$now')";
       
   301 			$db->query($sql);
       
   302 
       
   303 			// Done
       
   304 			return true;
       
   305 		}
       
   306 		elseif ($iddomains)
       
   307 		{
       
   308 			// If we are here we want to apply templates.
       
   309 			global $template;
       
   310 
       
   311 			// Iterate over the template and apply it for each field.
       
   312 			foreach ($template as $r)
       
   313 			{
       
   314 				// Same type of if statement as previous.
       
   315 				if ((eregi('in-addr.arpa', $domain) && ($r["type"] == "NS" || $r["type"] == "SOA")) || (!eregi('in-addr.arpa', $domain)))
       
   316 				{
       
   317 					// Parse the template.
       
   318 					$name     = parse_template_value($r["name"], $domain, $webip, $mailip);
       
   319 					$type     = $r["type"];
       
   320 					$content  = parse_template_value($r["content"], $domain, $webip, $mailip);
       
   321 					$ttl      = $r["ttl"];
       
   322 					$prio     = $r["prio"];
       
   323 
       
   324 					// If no ttl is given, use the default.
       
   325 					if (!$ttl)
       
   326 					{
       
   327 						$ttl = $GLOBALS["DEFAULT_TTL"];
       
   328 					}
       
   329 
       
   330 					// Retrieve new record id;
       
   331 					$idrecords = $db->nextID('records');
       
   332 					$sql = "INSERT INTO records (id, domain_id, name, content, type, ttl, prio, change_date) VALUES ('$idrecords', '$iddomains', '$name','$content','$type','$ttl','$prio','$now')";
       
   333 					$db->query($sql);
       
   334 				}
       
   335 			}
       
   336 			// All done.
       
   337 			return true;
       
   338                  }
       
   339                  else
       
   340                  {
       
   341 			error(sprintf(ERR_INV_ARGC, "add_domain", "could not create zone"));
       
   342                  }
       
   343 	}
       
   344 	else
       
   345 	{
       
   346 		error(sprintf(ERR_INV_ARG, "add_domain"));
       
   347 	}
       
   348 }
       
   349 
       
   350 
       
   351 /*
       
   352  * Deletes a domain by a given id.
       
   353  * Function always succeeds. If the field is not found in the database, thats what we want anyway.
       
   354  */
       
   355 function delete_domain($id)
       
   356 {
       
   357 	global $db;
       
   358 
       
   359 	if (!level(5))
       
   360 	{
       
   361 		error(ERR_LEVEL_5);
       
   362 	}
       
   363 
       
   364 	// See if the ID is numeric.
       
   365 	if (is_numeric($id))
       
   366 	{
       
   367 		$db->query("DELETE FROM zones WHERE domain_id=$id");
       
   368 		$db->query("DELETE FROM domains WHERE id=$id");
       
   369 		$db->query("DELETE FROM records WHERE domain_id=$id");
       
   370 		// Nothing in the database. If the delete deleted 0 records it means the id is just not there.
       
   371 		// therefore the is no need to check the affectedRows values.
       
   372 		return true;
       
   373 	}
       
   374 	else
       
   375 	{
       
   376 		error(sprintf(ERR_INV_ARGC, "delete_domain", "id must be a number"));
       
   377 	}
       
   378 }
       
   379 
       
   380 
       
   381 /*
       
   382  * Gets the id of the domain by a given record id.
       
   383  * return values: the domain id that was requested.
       
   384  */
       
   385 function recid_to_domid($id)
       
   386 {
       
   387 	global $db;
       
   388 	if (is_numeric($id))
       
   389 	{
       
   390 		$result = $db->query("SELECT domain_id FROM records WHERE id=$id");
       
   391 		$r = $result->fetchRow();
       
   392 		return $r["domain_id"];
       
   393 	}
       
   394 	else
       
   395 	{
       
   396 		error(sprintf(ERR_INV_ARGC, "recid_to_domid", "id must be a number"));
       
   397 	}
       
   398 }
       
   399 
       
   400 
       
   401 /*
       
   402  * Sorts a zone by records.
       
   403  * return values: the sorted zone.
       
   404  */
       
   405 function sort_zone($records)
       
   406 {
       
   407 	$ar_so = array();
       
   408 	$ar_ns = array();
       
   409 	$ar_mx = array();
       
   410 	$ar_mb = array();
       
   411 	$ar_ur = array();
       
   412 	$ar_ov = array();
       
   413 	foreach ($records as $c)
       
   414 	{
       
   415 		switch(strtoupper($c['type']))
       
   416 		{
       
   417 			case "SOA":
       
   418 				$ar_so[] = $c;
       
   419 				break;
       
   420 			case "NS":
       
   421 				$ar_ns[] = $c;
       
   422 				break;
       
   423 			case "MX":
       
   424 				$ar_mx[] = $c;
       
   425 				break;
       
   426 			case "MBOXFW":
       
   427 				$ar_mb[] = $c;
       
   428 				break;
       
   429 			case "URL":
       
   430 				$ar_ur[] = $c;
       
   431 				break;
       
   432 			default:
       
   433 				$ar_ov[] = $c;
       
   434 				break;
       
   435 		}
       
   436 	}
       
   437 
       
   438 	$res = array_merge($ar_so, $ar_ns, $ar_mx, $ar_mb, $ar_ur, $ar_ov);
       
   439 
       
   440 	if (count($records) == count($res))
       
   441 	{
       
   442 		$records = $res;
       
   443 	}
       
   444 	else
       
   445 	{
       
   446 		error(sprintf(ERR_INV_ARGC, "sort_zone", "records sorting failed!"));
       
   447 	}
       
   448 	return $records;
       
   449 }
       
   450 
       
   451 
       
   452 /*
       
   453  * Change owner of a domain.
       
   454  * Function should actually be in users.inc.php. But its more of a record modification than a user modification
       
   455  * return values: true when succesful.
       
   456  */
       
   457 function add_owner($domain, $newowner)
       
   458 {
       
   459 	global $db;
       
   460 
       
   461 	if (!level(5))
       
   462 	{
       
   463 		error(ERR_LEVEL_5);
       
   464 	}
       
   465 
       
   466 	if (is_numeric($domain) && is_numeric($newowner) && is_valid_user($newowner))
       
   467 	{
       
   468 		$iid = $db->nextID('zones');
       
   469 		if($db->getOne("SELECT COUNT(id) FROM zones WHERE owner=$newowner AND domain_id=$domain") == 0)
       
   470 		{
       
   471 			$db->query("INSERT INTO zones(id, domain_id, owner) VALUES($iid, $domain, $newowner)");
       
   472 		}
       
   473 		return true;
       
   474 	}
       
   475 	else
       
   476 	{
       
   477 		error(sprintf(ERR_INV_ARGC, "change_owner", "$domain / $newowner"));
       
   478 	}
       
   479 }
       
   480 
       
   481 
       
   482 function delete_owner($domain, $owner)
       
   483 {
       
   484 	global $db;
       
   485 	if($db->getOne("SELECT COUNT(id) FROM zones WHERE owner=$owner AND domain_id=$domain") != 0)
       
   486 	{
       
   487 		$db->query("DELETE FROM zones WHERE owner=$owner AND domain_id=$domain");
       
   488 	}
       
   489 	return true;
       
   490 }
       
   491 
       
   492 /*
       
   493  * Retrieves all supported dns record types
       
   494  * This function might be deprecated.
       
   495  * return values: array of types in string form.
       
   496  */
       
   497 function get_record_types()
       
   498 {
       
   499 	global $rtypes;
       
   500 	return $rtypes;
       
   501 }
       
   502 
       
   503 
       
   504 /*
       
   505  * Retrieve all records by a given type and domain id.
       
   506  * Example: get all records that are of type A from domain id 1
       
   507  * return values: a DB class result object
       
   508  */
       
   509 function get_records_by_type_from_domid($type, $recid)
       
   510 {
       
   511 	global $rtypes;
       
   512 	global $db;
       
   513 
       
   514 	// Does this type exist?
       
   515 	if(!in_array(strtoupper($type), $rtypes))
       
   516 	{
       
   517 		error(sprintf(ERR_INV_ARGC, "get_records_from_type", "this is not a supported record"));
       
   518 	}
       
   519 
       
   520 	// Get the domain id.
       
   521 	$domid = recid_to_domid($recid);
       
   522 
       
   523 	$result = $db->query("select id, type from records where domain_id=$recid and type='$type'");
       
   524 	return $result;
       
   525 }
       
   526 
       
   527 
       
   528 /*
       
   529  * Retrieves the type of a record from a given id.
       
   530  * return values: the type of the record (one of the records types in $rtypes assumable).
       
   531  */
       
   532 function get_recordtype_from_id($id)
       
   533 {
       
   534 	global $db;
       
   535 	if (is_numeric($id))
       
   536 	{
       
   537 		$result = $db->query("SELECT type FROM records WHERE id=$id");
       
   538 		$r = $result->fetchRow();
       
   539 		return $r["type"];
       
   540 	}
       
   541 	else
       
   542 	{
       
   543 		error(sprintf(ERR_INV_ARG, "get_recordtype_from_id"));
       
   544 	}
       
   545 }
       
   546 
       
   547 
       
   548 /*
       
   549  * Retrieves the name (e.g. bla.test.com) of a record by a given id.
       
   550  * return values: the name associated with the id.
       
   551  */
       
   552 function get_name_from_record_id($id)
       
   553 {
       
   554 	global $db;
       
   555 	if (is_numeric($id))
       
   556 	{
       
   557 		$result = $db->query("SELECT name FROM records WHERE id=$id");
       
   558 		$r = $result->fetchRow();
       
   559 		return $r["name"];
       
   560 	}
       
   561 	else
       
   562 	{
       
   563 		error(sprintf(ERR_INV_ARG, "get_name_from_record_id"));
       
   564 	}
       
   565 }
       
   566 
       
   567 
       
   568 /*
       
   569  * Get all the domains from a database of which the user is the owner.
       
   570  * return values: an array with the id of the domain and its name.
       
   571  */
       
   572 function get_domains_from_userid($id)
       
   573 {
       
   574 	global $db;
       
   575 	if (is_numeric($id))
       
   576 	{
       
   577 		$result = $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=$id");
       
   578 
       
   579 		$ret = array();
       
   580 
       
   581 		// Put all the information in a big array.
       
   582 		while ($r = $result->fetchRow())
       
   583 		{
       
   584 			$ret[] = array(
       
   585 			"id"            =>              $r["domain_id"],
       
   586 			"name"          =>              $r["name"]
       
   587 			);
       
   588 		}
       
   589 		return $ret;
       
   590 	}
       
   591 	else
       
   592 	{
       
   593 		error(sprintf(ERR_INV_ARGC, "get_domains_from_userid", "This is not a valid userid: $id"));
       
   594 	}
       
   595 }
       
   596 
       
   597 
       
   598 /*
       
   599  * Get domain name from a given id
       
   600  * return values: the name of the domain associated with the id.
       
   601  */
       
   602 function get_domain_name_from_id($id)
       
   603 {
       
   604 	global $db;
       
   605 	if (!xs($id))
       
   606 	{
       
   607 		error(ERR_RECORD_ACCESS_DENIED);
       
   608 	}
       
   609 	if (is_numeric($id))
       
   610 	{
       
   611 		$result = $db->query("SELECT name FROM domains WHERE id=$id");
       
   612 		if ($result->numRows() == 1)
       
   613 		{
       
   614  			$r = $result->fetchRow();
       
   615  			return $r["name"];
       
   616 		}
       
   617 		else
       
   618 		{
       
   619 	 		error(sprintf(ERR_INV_ARGC, "get_domain_name_from_id", "more than one domain found?! whaaa! BAD! BAD! Contact admin!"));
       
   620 		}
       
   621 	}
       
   622 	else
       
   623 	{
       
   624 		error(sprintf(ERR_INV_ARGC, "get_domain_name_from_id", "Not a valid domainid: $id"));
       
   625 	}
       
   626 }
       
   627 
       
   628 
       
   629 /*
       
   630  * Get information about a domain name from a given domain id.
       
   631  * the function looks up the domainname, the owner of the domain and the number of records in it.
       
   632  * return values: an array containing the information.
       
   633  */
       
   634 function get_domain_info_from_id($id)
       
   635 {
       
   636 	global $db;
       
   637 	if (!xs($id))
       
   638 	{
       
   639 		error(ERR_RECORD_ACCESS_DENIED);
       
   640 	}
       
   641 	if (is_numeric($id))
       
   642 	{
       
   643 
       
   644 	if ($_SESSION[$id."_ispartial"] == 1) {
       
   645 	
       
   646 	$sqlq = "SELECT domains.name AS name,
       
   647 	users.fullname AS owner,
       
   648 	count(record_owners.id) AS aantal
       
   649 	FROM domains, users, record_owners, records
       
   650 	
       
   651         WHERE record_owners.user_id = ".$_SESSION["userid"]."
       
   652         AND record_owners.record_id = records.id
       
   653 	AND records.domain_id = ".$id."
       
   654 
       
   655 	GROUP BY name, owner, users.fullname
       
   656 	ORDER BY name";
       
   657 	
       
   658 	$result = $db->getRow($sqlq);
       
   659 
       
   660 	$ret = array(
       
   661 	"name"          =>              $result["name"],
       
   662 	"ownerid"       =>              $_SESSION["userid"],
       
   663 	"owner"         =>              $result["owner"],
       
   664 	"numrec"        =>              $result["aantal"]
       
   665 	);
       
   666 
       
   667 	return $ret;
       
   668 
       
   669 	} else{
       
   670 	
       
   671 		// Query that retrieves the information we need.
       
   672 		$sqlq = "SELECT domains.name AS name,
       
   673 			min(zones.owner) AS ownerid,
       
   674 			users.fullname AS owner,
       
   675 			count(records.domain_id) AS aantal
       
   676 			FROM domains
       
   677 			LEFT JOIN records ON domains.id=records.domain_id
       
   678 			LEFT JOIN zones ON domains.id=zones.domain_id
       
   679 			LEFT JOIN users ON zones.owner=users.id
       
   680 			WHERE domains.id=$id
       
   681 			GROUP BY name, owner, users.fullname
       
   682 			ORDER BY zones.id";
       
   683 
       
   684 		// Put the first occurence in an array and return it.
       
   685 		$result = $db->getRow($sqlq);
       
   686 
       
   687 		//$result["ownerid"] = ($result["ownerid"] == NULL) ? $db->getOne("select min(id) from users where users.level=10") : $result["ownerid"];
       
   688 
       
   689 		$ret = array(
       
   690 		"name"          =>              $result["name"],
       
   691 		"ownerid"       =>              $result["ownerid"],
       
   692 		"owner"         =>              $result["owner"],
       
   693 		"numrec"        =>              $result["aantal"]
       
   694 		);
       
   695 		return $ret;
       
   696 	}
       
   697 
       
   698 	}
       
   699 	else
       
   700 	{
       
   701 		error(sprintf(ERR_INV_ARGC, "get_domain_num_records_from_id", "This is not a valid domainid: $id"));
       
   702 	}
       
   703 }
       
   704 
       
   705 
       
   706 /*
       
   707  * Check if a domain is already existing.
       
   708  * return values: true if existing, false if it doesnt exist.
       
   709  */
       
   710 function domain_exists($domain)
       
   711 {
       
   712 	global $db;
       
   713 
       
   714 	if (!level(5))
       
   715 	{
       
   716 		error(ERR_LEVEL_5);
       
   717 	}
       
   718 	if (is_valid_domain($domain))
       
   719 	{
       
   720 		$result = $db->query("SELECT id FROM domains WHERE name='$domain'");
       
   721 		if ($result->numRows() == 0)
       
   722 		{
       
   723 			return false;
       
   724 		}
       
   725 		elseif ($result->numRows() >= 1)
       
   726 		{
       
   727 			return true;
       
   728 		}
       
   729 	}
       
   730 	else
       
   731 	{
       
   732 		error(ERR_DOMAIN_INVALID);
       
   733 	}
       
   734 }
       
   735 
       
   736 
       
   737 /*
       
   738  * Get all domains from the database.
       
   739  * This function gets all the domains from the database unless a user id is below 5.
       
   740  * if a user id is below 5 this function will only retrieve records for that user.
       
   741  * return values: the array of domains or -1 if nothing is found.
       
   742  */
       
   743 function get_domains($userid=true,$letterstart=all,$rowstart=0,$rowamount=999999)
       
   744 {
       
   745 	global $db;
       
   746 	if((!level(5) || !$userid) && !level(10) && !level(5))
       
   747 	{
       
   748 		$add = " AND zones.owner=".$_SESSION["userid"];
       
   749 	}
       
   750 	else
       
   751 	{
       
   752 		$add = "";
       
   753 	}
       
   754 
       
   755 	$sqlq = "SELECT domains.id AS domain_id,
       
   756 	min(zones.owner) AS owner,
       
   757 	count(DISTINCT records.id) AS aantal,
       
   758 	domains.name AS domainname
       
   759 	FROM domains
       
   760 	LEFT JOIN zones ON domains.id=zones.domain_id 
       
   761 	LEFT JOIN records ON records.domain_id=domains.id
       
   762 	WHERE 1 $add ";
       
   763 	if ($letterstart!=all && $letterstart!=1) {
       
   764 	   $sqlq.=" AND domains.name LIKE '".$letterstart."%' ";
       
   765 	} elseif ($letterstart==1) {
       
   766 	      $sqlq.=" AND ";
       
   767 	   for ($i=0;$i<=9;$i++) {
       
   768 	      $sqlq.="domains.name LIKE '".$i."%'";
       
   769 	      if ($i!=9) $sqlq.=" OR ";
       
   770 	   }
       
   771 	}
       
   772 	$sqlq.=" GROUP BY domainname, domain_id
       
   773 	ORDER BY domainname
       
   774 	LIMIT $rowstart,$rowamount";
       
   775 
       
   776 	$result = $db->query($sqlq);
       
   777 	$result2 = $db->query($sqlq);
       
   778 
       
   779 	$andnot="";
       
   780 	while($r = $result2->fetchRow()) {
       
   781 	   $andnot.=" AND domains.id!= '".$r["domain_id"]."' ";
       
   782 	}
       
   783 
       
   784 if ($letterstart!=all && $letterstart!=1) {
       
   785 
       
   786 	$sqlq = "SELECT domains.id AS domain_id,
       
   787 	count(DISTINCT record_owners.record_id) AS aantal,
       
   788 	domains.name AS domainname
       
   789 	FROM domains, record_owners,records, zones
       
   790 	WHERE record_owners.user_id = '".$_SESSION["userid"]."'
       
   791 	AND (records.id = record_owners.record_id
       
   792 	AND domains.id = records.domain_id)
       
   793 	$andnot 
       
   794 	AND domains.name LIKE '".$letterstart."%' 
       
   795 	AND (zones.domain_id != records.domain_id AND zones.owner!='".$_SESSION["userid"]."')
       
   796 	GROUP BY domainname, domain_id
       
   797 	ORDER BY domainname";
       
   798 
       
   799 	$result_extra = $db->query($sqlq);
       
   800 
       
   801 } else {
       
   802 
       
   803    for ($i=0;$i<=9;$i++) {
       
   804         $sqlq = "SELECT domains.id AS domain_id,
       
   805         count(DISTINCT record_owners.record_id) AS aantal,
       
   806         domains.name AS domainname
       
   807         FROM domains, record_owners,records, zones
       
   808         WHERE record_owners.user_id = '".$_SESSION["userid"]."'
       
   809         AND (records.id = record_owners.record_id
       
   810         AND domains.id = records.domain_id)
       
   811         $andnot 
       
   812         AND domains.name LIKE '".$i."%' 
       
   813         AND (zones.domain_id != records.domain_id AND zones.owner!='".$_SESSION["userid"]."')
       
   814         GROUP BY domainname, domain_id
       
   815         ORDER BY domainname";
       
   816 
       
   817         $result_extra[$i] = $db->query($sqlq);
       
   818    }
       
   819 
       
   820 }
       
   821 
       
   822 /*
       
   823 	if ($result->numRows() == 0)
       
   824 	{
       
   825 		// Nothing found.
       
   826 		return -1;
       
   827 	}
       
   828 */
       
   829 
       
   830 	while($r = $result->fetchRow())
       
   831 	{
       
   832 		$r["owner"] = ($r["owner"] == NULL) ? $db->getOne("select min(id) from users where users.level=10") : $r["owner"];
       
   833 	     	$ret[$r["domainname"]] = array(
       
   834 		"name"          =>              $r["domainname"],
       
   835 		"id"            =>              $r["domain_id"],
       
   836 		"owner"         =>              $r["owner"],
       
   837 		"numrec"        =>              $r["aantal"]
       
   838 		);
       
   839 	}
       
   840 
       
   841 
       
   842 if ($letterstart!=all && $letterstart!=1) {
       
   843 
       
   844 	while($r = $result_extra->fetchRow())
       
   845         {
       
   846                $ret[$r["domainname"]] = array(
       
   847 	       "name"          =>              $r["domainname"]."*",
       
   848                "id"            =>              $r["domain_id"],
       
   849                "owner"         =>              $_SESSION["userid"],
       
   850                "numrec"        =>              $r["aantal"]
       
   851                );
       
   852 	       $_SESSION["partial_".$r["domainname"]] = 1;
       
   853         }
       
   854 
       
   855 } else {
       
   856 
       
   857 	foreach ($result_extra as $result_e) {
       
   858         while($r = $result_e->fetchRow())
       
   859         {
       
   860                $ret[$r["domainname"]] = array(
       
   861                "name"          =>              $r["domainname"]."*",
       
   862                "id"            =>              $r["domain_id"],
       
   863                "owner"         =>              $_SESSION["userid"],
       
   864                "numrec"        =>              $r["aantal"]
       
   865                );
       
   866 	       $_SESSION["partial_".$r["domainname"]] = 1;
       
   867         }
       
   868 	}
       
   869 
       
   870 }
       
   871 
       
   872 if (empty($ret)) {
       
   873    return -1;
       
   874 } else {
       
   875    sort($ret);
       
   876    return $ret;
       
   877 }
       
   878 
       
   879 }
       
   880 
       
   881 
       
   882 /*
       
   883  * Get a record from an id.
       
   884  * Retrieve all fields of the record and send it back to the function caller.
       
   885  * return values: the array with information, or -1 is nothing is found.
       
   886  */
       
   887 function get_record_from_id($id)
       
   888 {
       
   889 	global $db;
       
   890 	if (is_numeric($id))
       
   891 	{
       
   892 		$result = $db->query("SELECT id, domain_id, name, type, content, ttl, prio, change_date FROM records WHERE id=$id");
       
   893 		if($result->numRows() == 0)
       
   894 		{
       
   895 			return -1;
       
   896 		}
       
   897 		elseif ($result->numRows() == 1)
       
   898 		{
       
   899 			$r = $result->fetchRow();
       
   900 			$ret = array(
       
   901 			"id"            =>      $r["id"],
       
   902 			"domain_id"     =>      $r["domain_id"],
       
   903 			"name"          =>      $r["name"],
       
   904 			"type"          =>      $r["type"],
       
   905 			"content"       =>      $r["content"],
       
   906 			"ttl"           =>      $r["ttl"],
       
   907 			"prio"          =>      $r["prio"],
       
   908 			"change_date"   =>      $r["change_date"]
       
   909 			);
       
   910 			return $ret;
       
   911 		}
       
   912 		else
       
   913 		{
       
   914 			error(sprintf(ERR_INV_ARGC, "get_record_from_id", "More than one row returned! This is bad!"));
       
   915 		}
       
   916 	}
       
   917 	else
       
   918 	{
       
   919 		error(sprintf(ERR_INV_ARG, "get_record_from_id"));
       
   920 	}
       
   921 }
       
   922 
       
   923 
       
   924 /*
       
   925  * Get all records from a domain id.
       
   926  * Retrieve all fields of the records and send it back to the function caller.
       
   927  * return values: the array with information, or -1 is nothing is found.
       
   928  */
       
   929 function get_records_from_domain_id($id,$rowstart=0,$rowamount=999999)
       
   930 {
       
   931 	global $db;
       
   932 	if (is_numeric($id))
       
   933 	{
       
   934 		if ($_SESSION[$id."_ispartial"] == 1) {
       
   935 
       
   936 		$result = $db->query("SELECT record_owners.record_id as id
       
   937 		FROM record_owners,domains,records
       
   938 		WHERE record_owners.user_id = ".$_SESSION["userid"]."
       
   939 		AND record_owners.record_id = records.id
       
   940 		AND records.domain_id = ".$id."
       
   941 		GROUP bY record_owners.record_id
       
   942 		LIMIT $rowstart,$rowamount");
       
   943 
       
   944 		$ret = array();
       
   945 		if($result->numRows() == 0)
       
   946 		{
       
   947 		return -1;
       
   948 		}
       
   949 		else
       
   950 		{
       
   951 		$ret[] = array();
       
   952 		$retcount = 0;
       
   953 		while($r = $result->fetchRow())
       
   954 		{
       
   955 		// Call get_record_from_id for each row.
       
   956 		$ret[$retcount] = get_record_from_id($r["id"]);
       
   957 		$retcount++;
       
   958 		}
       
   959 		return $ret;
       
   960 		}
       
   961 
       
   962 		} else {
       
   963 
       
   964 		$result = $db->query("SELECT id FROM records WHERE domain_id=$id LIMIT $rowstart,$rowamount");
       
   965 		$ret = array();
       
   966 		if($result->numRows() == 0)
       
   967 		{
       
   968 			return -1;
       
   969 		}
       
   970 		else
       
   971 		{
       
   972 			$ret[] = array();
       
   973 			$retcount = 0;
       
   974 			while($r = $result->fetchRow())
       
   975 			{
       
   976 				// Call get_record_from_id for each row.
       
   977 				$ret[$retcount] = get_record_from_id($r["id"]);
       
   978 				$retcount++;
       
   979 			}
       
   980 			return $ret;
       
   981 		}
       
   982 
       
   983 		}
       
   984 	}
       
   985 	else
       
   986 	{
       
   987 		error(sprintf(ERR_INV_ARG, "get_records_from_domain_id"));
       
   988 	}
       
   989 }
       
   990 
       
   991 
       
   992 function get_users_from_domain_id($id)
       
   993 {
       
   994 	global $db;
       
   995 	$result = $db->getCol("SELECT owner FROM zones WHERE domain_id=$id");
       
   996 	$ret = array();
       
   997 	foreach($result as $uid)
       
   998 	{
       
   999 		$fullname = $db->getOne("SELECT fullname FROM users WHERE id=$uid");
       
  1000 		$ret[] = array(
       
  1001 		"id" 		=> 	$uid,
       
  1002 		"fullname"	=>	$fullname		
       
  1003 		);		
       
  1004 	}
       
  1005 	return $ret;	
       
  1006 }
       
  1007 
       
  1008 function search_record($question)
       
  1009 {
       
  1010 	global $db;
       
  1011 	$question = trim($question);
       
  1012 	if (empty($question)) 
       
  1013 	{
       
  1014 		$S_INPUT_TYPE = -1;
       
  1015 	}
       
  1016 
       
  1017 	/* now for some input-type searching */
       
  1018 	if (is_valid_ip($question) || is_valid_ip6($question))
       
  1019 	{
       
  1020 		$S_INPUT_TYPE = 0;
       
  1021 	}
       
  1022 	elseif(is_valid_domain($question) || 
       
  1023 		is_valid_hostname($question) ||
       
  1024 		is_valid_mboxfw($question)) // I guess this one can appear in records table too (content?!)
       
  1025 	{
       
  1026 		$S_INPUT_TYPE = 1;
       
  1027 	}	  
       
  1028 	else 
       
  1029 	{
       
  1030 		$S_INPUT_TYPE = -1;
       
  1031 	}
       
  1032 	switch($S_INPUT_TYPE)
       
  1033 	{
       
  1034 		case '0': 
       
  1035 			$sqlq = "SELECT * FROM `records` WHERE `content` = '".$question."' ORDER BY `type` DESC";
       
  1036 			$result = $db->query($sqlq);
       
  1037 			$ret_r = array();
       
  1038 			while ($r = $result->fetchRow())
       
  1039 			{
       
  1040 			    if(xs($r['domain_id']))
       
  1041 			    {
       
  1042     				$ret_r[] = array(
       
  1043     				  'id'			=>	$r['id'],
       
  1044     				  'domain_id'		=>	$r['domain_id'],
       
  1045     				  'name'		=>	$r['name'],
       
  1046     				  'type'		=>	$r['type'],
       
  1047     				  'content'		=>	$r['content'],
       
  1048     				  'ttl'			=>	$r['ttl'],
       
  1049     				  'prio'		=>	$r['prio'],
       
  1050     				  'change_date'		=>	$r['change_date']
       
  1051     				);
       
  1052 				}
       
  1053 			}
       
  1054 			break;
       
  1055 	    
       
  1056 		case '1' :
       
  1057 			$sqlq = "SELECT `domains`.*, count(`records`.`id`) AS `numrec`, `zones`.`owner`  
       
  1058 					FROM `domains`, `records`, `zones`  
       
  1059 					WHERE `domains`.`id` = `records`.`domain_id` 
       
  1060 					AND `zones`.`domain_id` = `domains`.`id` 
       
  1061 					AND `domains`.`name` = '".$question."' 
       
  1062 					GROUP BY (`domains`.`id`)";
       
  1063 
       
  1064 			$result = $db->query($sqlq);
       
  1065 			$ret_d = array();
       
  1066 			while ($r = $result->fetchRow())
       
  1067 			{
       
  1068 			    if(xs($r['domain_id']))
       
  1069 			    {
       
  1070 				    $ret_d[] = array(
       
  1071     					'id'			=>	$r['id'],
       
  1072     					'name'		=>	$r['name'],
       
  1073     					'numrec'		=>	$r['numrec'],
       
  1074     					'owner'		=>	$r['owner']
       
  1075     				);
       
  1076 				}
       
  1077 			}
       
  1078 
       
  1079 			$sqlq = "SELECT * FROM `records` WHERE `name` = '".$question."' OR `content` = '".$question."' ORDER BY `type` DESC";
       
  1080 			$result = $db->query($sqlq);
       
  1081 			while ($r = $result->fetchRow())
       
  1082 			{
       
  1083 			    if(xs($r['domain_id']))
       
  1084 			    {
       
  1085     				$ret_r[] = array(
       
  1086     					'id'			=>	$r['id'],
       
  1087     					'domain_id'		=>	$r['domain_id'],
       
  1088     					'name'		=>	$r['name'],
       
  1089     					'type'		=>	$r['type'],
       
  1090     					'content'		=>	$r['content'],
       
  1091     					'ttl'			=>	$r['ttl'],
       
  1092     					'prio'		=>	$r['prio'],
       
  1093     				);
       
  1094     			}
       
  1095 			}
       
  1096 			break;
       
  1097 	}
       
  1098 	if($S_INPUT_TYPE == 1)
       
  1099 	{
       
  1100 		return array('domains' => $ret_d, 'records' => $ret_r);
       
  1101 	}
       
  1102 	return array('records' => $ret_r);
       
  1103 }
       
  1104 
       
  1105 function get_domain_type($id)
       
  1106 {
       
  1107 	global $db;
       
  1108 	$type = $db->getOne("SELECT `type` FROM `domains` WHERE `id` = '".$id."'");
       
  1109 	if($type == "")
       
  1110 	{
       
  1111 		$type = "NATIVE";
       
  1112 	}
       
  1113 	return $type;
       
  1114     
       
  1115 }
       
  1116 
       
  1117 function change_domain_type($type, $id)
       
  1118 {
       
  1119     global $db;
       
  1120     $result = $db->query("UPDATE `domains` SET `type` = '" .$type. "' WHERE `id` = '".$id."'");
       
  1121 }
       
  1122 ?>