Location: PHPKode > projects > NaWui > nawui/plugins/serialized.inc
<?php

/*
 * Nawui default plugin
 *
 * Original Author : Geert Vanderkelen <hide@address.com>
 *
 * Description	   : Default plugin for saving Nawui data and exporting it to and
 *		    and importing from Nagios.
 *
 *	 	    This plugin uses the 'serialize' functionallity from PHP to
 *	 	    store some hashes in files. PHP doesn't need an special
 * 		    stuff compiled into it to let this work.
 *
 *		    Nawui storage:
 *		    NGT_CFGLOG in local.inc should be a directory. In most cases
 *		    this will be the Nagios /etc directory. It must be writeable
 *		    for the user running the webserver.
 *
 *		    Importing form Nagios:
 *		    This plugin reads template-based configurations files as
 *		    found in Nagios. It those not support the old Netsaint
 *		    style.
 *
 *		    Exporting to Nagios:
 *		    Nagios configuration is written in the new template-based
 *		    form. Old Netsaint style is not supported.
 */

/*
 * 
 * Information for PluginCfg writers:
 * 
 * This file is the default Nawui method for reading, manipulating and saving 
 * nagios configuration. It contains information how to build other methods,
 * like saving to a database.
 * 
 * Functions starting with 'Plugin..' are required and used by Nawui. Those 
 * starting with 'Privat..' are only used within the plugin as helper
 * funtions. I suggest you stick to these to prefixes.
 *
 * NGT_CFGLOC is an important constant set in the local.inc file. It contains
 * the location where the information is stored (not Nagios files). It can be
 * a directory (like in this default plugin) or a string specifying some login
 * information for a database like MySQL, PostgreSQL, et al.
 *
 * (More docs comming)
 *
 */


# ------------  PLUGIN INFORMATION ----------------
#
# All plugins should have this array to allow to get some 
# information about the type of database used, author of the plugin, description,etc.
# 
#


# Main plugin definition. Every function will be called by this name,
# ex: plugin->GetConfig();
#
$Plugin = new serialized;

#$filename = $Plugin->$database["objects_filename"];


class	serialized	{

# Name of current plugin
var $name = "Nawui default plugin";

# Version of current plugin
var $version = "0.1dev";

# Author of plugin
var $author = "Hvm <hide@address.com>";

# Description of plugin
var $description = "Default plugin for saving Nawui data and exporting it to and\n";
/*		."and importing from Nagios.\n"
		."\n"
		."This plugin uses the 'serialize' functionallity from PHP to\n"
		."store some hashes in files. PHP doesn't need an special\n"
		."stuff compiled into it to let this work.\n"
		."\n"
		."Nawui storage:\n"
		."NGT_CFGLOG in local.inc should be a directory. In most cases\n"
		."this will be the Nagios /etc directory. It must be writeable\n"
		."for the user running the webserver.\n"
		."\n"
		."Importing form Nagios:\n"
		."This plugin reads template-based configurations files as\n"
		."found in Nagios. It those not support the old Netsaint\n"
		."style.\n"
		."\n"
		."Exporting to Nagios:\n"
		."Nagios configuration is written in the new template-based\n"
		."form. Old Netsaint style is not supported.\n";
*/
# Source file for this plugin (ex: serialized.inc)
var $source_filename = "serialized.inc";

# Other filenames used by this plugin (ex: default.functions.inc)
var $files_used = "";

# --- Database Information ---

# Type of database used by this plugin. 
# It can be:
# - serialized	: if database uses a file to store its records in PHP serialized method.
#		 "filename" used must be defined below.
# - mysql	: if records are stored in MySQL. (See: username, password and hostname)
# - postgresql	: if records are stored in PostgreSQL. (See: username, password and hostname)
# - other	: somekind of storing method that uses files, ex: plain-text, html, etc.
#		 "filename" used must be defined below.
#
# NOTE: For some other database types update of other Nawui files maybe be needded.
var $database = array (

		'type' => "serialized",

		# Defined only if Database type uses somekind of a file to store its records
		'objects_filename' => "nawuiobjs.dat",
		
		'config_filename' => "nawuicfg.dat",

		# Defined only if Database type is "..sql"
		'user' => "",

		# Defined only if Database type is "..sql"
		'passwd' => "",

		# Defined only if Database type is "..sql"
		'hostname' => "",

); #array

# --------------- FUNCTIONS --------------

# Gets the current Modified Date/Time of database filename used by this plugin.
# Returns: string

function DatabaseModifiedTime()	{

	$filename = NAGIOS_ETC."/".$this->database["objects_filename"];
	$MTime = "";

	if ($filename != "")	{

		if (file_exists($filename)) 
			$MTime = date("H:i:s, F d Y", filemtime($filename));
		else $MTime = "does not exist";
		
	}

	return ($MTime);
}

function Private_GetSerialData($file) {

	
	if (file_exists($file)) {
		
		$fp = fopen($file,"r");
		$serstr = fread($fp, filesize($file));
		fclose($fp);
		
		$data = @unserialize($serstr);
	
		if (is_array($data))	{
		
			return($data);
		}
		
	} 

	return(NULL);
}

function Private_DumpObjects($filename, $objects)	{
	
	$result = FALSE;
	
	if (is_array($objects)) {

		$fp = fopen($filename, "w");
		fwrite($fp, serialize($objects));
		fclose($fp);
		
		$result = TRUE;

	}
	sleep(1);
#	echo "<pre>";
#	print_r($objects);
#	echo "<pre></hr>";

	return($result);
}

function GetConfig($fileid = NULL)	{
	
	$filename = NAGIOS_ETC."/".$this->database["config_filename"];
	
	static $config = NULL;

	#if ($config == NULL) 
		$config = $this->Private_GetSerialData($filename);
	
	if (is_array($config)) {
		
		if ($fileid != NULL)	{
		
			if (isset($config[$fileid]))	{

				if (is_array($config[$fileid]))
					return ($config[$fileid] );
				else 
					return(NULL);

			} else return(NULL);

		} else return ($config);
	
	}

	return( NULL );
}


function GetObjectsCount($type = NULL)	{
	
	$tmp_objects=$this->GetObjects($type);
	if (is_array($tmp_objects))
		return count($tmp_objects);
	else 
		return(NULL);
}



function GetObjectsFromTo($from = 0 , $to = 0, $type = NULL)	{
	

	$tmp_array = array();

	if ($from == $to) return NULL;
	
	$tmp_objects=$this->GetObjects($type);
	
	for ($i=$from; $i<$to; $i++)	{
	
		$tmp_array[]=$tmp_objects[$i];
	}
	return $tmp_array;
}

function GetObjects($type = NULL) 	{

	$filename = NAGIOS_ETC."/".$this->database["objects_filename"];
	
	$objects = $this->Private_GetSerialData($filename);
	
	if (is_array($objects)) {
		
	
		if ($type != NULL)	{
			if (@is_array($objects[$type]))	{
		
				# Reorganize records, exclude empty ones (Array 'id' will be unsyncronized with '__objectid')
				$tmp_objects=array();
			
				foreach ($objects[$type] as $key => $object) {
#				for ($i=0; $i<count($objects[$type]); $i++)	{

					#if (is_array($objects[$type])) 
					$tmp_objects[]=$object;
				}
				$objects=$tmp_objects;
			
				return($objects);
			}
			else return(NULL);

		} else	return($objects);
		
	}
	return(NULL);
}

function GetObjectsByField($field = "", $value ="", $type = NULL)	{

	$selobjs = array();
	$filename = NAGIOS_ETC."/".$this->database["objects_filename"];
	$objects = $this->Private_GetSerialData($filename);

	# Get asked objects
	if( is_array($objects) )	{
	
		foreach( $objects as $key => $obj ) {
		
			if( $obj[$field] == $value ) $selobjs[$key] = $obj;
		
		}
	
	}

	if( count($selobjs) > 0 ) return( $selobjs );

	return( NULL );
}

function GetObjectById($id = 0, $type = NULL) 	{

	$objects = $this->GetObjects($type);

	if (is_array($objects))	{
	

		foreach( $objects as $object) {
		
			# Template object
			if (@$object['__objectid'] == $id ) return($object);
		}
	}
	
	# Only pass trought here if there's no $object with the requested $id
	return(NULL);
}

function GetObjectByName($name = "", $type = NULL) 	{

	$objects = $this->GetObjects($type);

	if( is_array($objects) ) {

		foreach( $objects as $object) {
			
			# Template object
			if( @$object['name'] == $name )	{
				return($object);
			
			} elseif ( @$object[$type."_name"] == $name ) 	{
			
				return($object);
			}
		}
	}
	return(NULL);
}

function GetObjectByIndexName($name = "", $type = NULL, $indexname = "") 	{

	$objects = $this->GetObjects($type);

	if (is_array($objects)) {

		foreach ($objects as $object) {
			
			# Template object
			if ($indexname != "")	{
				if (@$object[$indexname] == $name)
					return($object);
			
			} else {
			
				if (@$object['name'] == $name)	{
					return($object);
			
				} elseif (@$object[$type."_name"] == $name) {
					return($object);
				} #if
			} #if
		} #foreach
	} #if
	return(NULL);
}


function GetAllObjects($type = NULL) 	{

	$filename = NAGIOS_ETC."/".$this->database["objects_filename"];
	
	$objects = $this->Private_GetSerialData($filename);
	
	if (is_array($objects)) {
		
		return ($objects);
	} 
	else return (NULL);
}	


function GetSortedObjects($sortoption = "", $sorttype = "0", $type = NULL) 	{

	$filename = NAGIOS_ETC."/".$this->database["objects_filename"];

	$objects = array();
	#$objects = $this->Private_GetSerialData($filename);
	$objects = $this->GetObjects($type);
#	PrintArray($objects);

	if (is_array($objects)) {
	

		if ($type != NULL)	{
			if (@is_array($objects[$type]))	{

				# Reorganize records, exclude empty ones (Array 'id' will be unsyncronized with '__objectid')
				$tmp_objects=array();

				for ($i=0; $i<count($objects[$type]); $i++)	{

					if (is_array($objects[$type][$i])) $tmp_objects[]=$objects[$type][$i];
				}
				$objects=$tmp_objects;
			} 
		
			if ($sorttype == "1") {
				# Reverse sort
				$objects = arsortbyindex($objects, $sortoption);
			} else {

				$objects = asortbyindex($objects, $sortoption);
			}
			return($objects);
		}
		
	}
	return(NULL);
}

function GetSortedObjectsFromTo($sortoption = "", $sorttype = "0", $from = 0 , $to = 0, $type = NULL)	{
	

	$objects = array();
	$tmp_objects = array();

	if ($from == $to) return NULL;
	
	$tmp_objects=$this->GetSortedObjects($sortoption, $sorttype, $type);
	
	for ($i=$from; $i<$to; $i++)	{
	
		$objects[]=$tmp_objects[$i];
	}
	return $objects;
}



function SaveConfig($fileid, $data) 	{

	
	$newcfg = array();
	$filename = NAGIOS_ETC."/".$this->database["config_filename"];
	
	if (!is_array($data)) return("No configurations to save.");

	$fullcfg = $this->GetConfig();
	
	if ($fullcfg == NULL)	{
	
		$fullcfg = array();
	}

	# Don't save empty values
	foreach ($data as $key => $value)	{

		for ($i = 0; $i < count($value); $i++)	{
		
			if (!empty($value[$i]))
				if ($value[$i] != "0")
					$newcfg[$key][] = $value[$i]; 
		
		}
	}

	$fullcfg[$fileid] = $newcfg;
	
#		echo "<br>Passed: $filename<br>";
#		sleep(10);
#		print_r($fullcfg);
		
	if ($this->Private_DumpObjects($filename, $fullcfg)) 
		return(NULL);
	else
		return("Failed writing configurations ($filename).");

}

function SaveObject($objectid, $data, $objecttype)	{


	$filename = NAGIOS_ETC."/".$this->database["objects_filename"];
	$objectid = (isset($objectid)) ? $objectid : "";
	
	$currobjects = $this->GetObjects(); 
	$newobject = array();

	# Don't save empty values
	foreach($data as $key => $value)	{
	
		if( !empty($value) || "$value" == "0" ) 
			$newobject[$key] = $value;
	
	}

	if (!isset($currobjects[$objecttype][$objectid]) || ($objectid == "")) {
	
		$keys = array_keys($currobjects[$objecttype]);
		rsort($keys);
		$objectid = $keys[0] + 1;
		$currobjects[$objecttype][$objectid] = $newobject;
	}

	$newobject['__objectid'] = $objectid;
	$newobject['__type'] = $objecttype;
	$currobjects[$objecttype][$objectid] = $newobject;

	$this->Private_DumpObjects($filename, $currobjects);
		
	return($objectid);
}


function DeleteObject($objectid, $objecttype)	{

	$filename = NAGIOS_ETC."/".$this->database["objects_filename"];
	$currobjects = $this->GetObjects();

	unset($currobjects[$objecttype][$objectid]);
	$this->Private_DumpObjects($filename, $currobjects);

	return($objectid);
}


function CfgWriteObject($objects, $location)	{

	if( is_array($objects) ) {
	
		$fp = fopen($location, "w");
		fwrite($fp, serialize($objects));
		fclose($fp);
		
	}
}


function ClearTable($type = NULL)	{

	if ($type == NULL) return(-1);

	$this->SaveConfig($type, NULL);
}

function ClearTables($tables = NULL)	{

	if ($tables == NULL) return(-1);

	# Get all objects
	$objects=$this->GetObjects();

	# Get the current NaWui database file
	$objects_filename = NAGIOS_ETC."/".$this->database["objects_filename"];
	
	# Clear the defined tables
	foreach ($tables as $table)
		unset($objects[$table]);
	
	# Write it back as serialized data
	if (is_array($objects))	{
	
		$fp = fopen($objects_filename, "wb");
		flock($fp, LOCK_EX ); // exclusive lock
		if (FALSE === fwrite($fp, serialize($objects)) ) 
			return("-3");
		fclose($fp);
		flock($fp, LOCK_UN ); // relase lock
		fflush($fp);
	}
	return(TRUE);
}


# function ImportCfgFile($fileid)
#
# PlguinImprtCfgFile imports configuration entries found in the files like
# nagios.cfg and cgi.cfg. $fileid is must have a value as defined in 
# nagiosdata.inc, for example
#
#	ImportCfgFile('nagioscfg')
#
# will import the configuration found in NAGIOS_ETC.'nagios.cfg'
#
# Returns a message on failure, NULL when succesful.
#
function ImportCfgFile($fileid)	{


	global $NAGIOS_CFGFILES;

	$entries = array();

	$filename = NAGIOS_ETC."/".$NAGIOS_CFGFILES[$fileid];
	
	if (file_exists($filename) == TRUE)	{

		$configlines = file($filename);
	}
	else 	{

		return("File $filename couldn't be read. Does it exist?");
	}

	foreach ($configlines as $line) {
		
		$line = trim($line);

		# comments and empty lines are not proccessed
		if( preg_match("/^\s*#/", $line) == FALSE && $line != "" )	{

			list($entry, $value) = explode("=",$line,2);
			
			if ( @is_array($entries[$entry]) == FALSE )	{
				$entries[$entry][0] = $value;
			} else {
				$entries[$entry][] = $value;
			}
		}
	}
	
	if( $result = $this->SaveConfig($fileid, $entries) )
		return($result);

	return(NULL);
}


# function ImportObjects($filename)
#
# PlguinImprtCfgObjects imports objects found in files written in the new
# template-based style. $filename is a file found in 'nagios.cfg' entries
# under 'cfg_file'.
#
#	ImportCfgFile('/usr/local/nagios/etc/hosts.cfg')
#
# will import all objects from hosts.cfg. It's important to keep track of this
# filename and it's type (host,contact,timeperiod,..) in the object definition.
#
# Returns a message on failure, NULL when succesful.
#
function ImportObjects($filename) 	{


	$currobj = "";
	$count = -1;
	$loccount = -1;
	$objectsread = 0;
	$objects = array();
	$newobjects = array();
	$objects_filename = NAGIOS_ETC."/".$this->database["objects_filename"];
	
	# Read the serialized data
	if (file_exists($objects_filename))	{
	
		$fp = fopen($objects_filename, "rb");
		flock($fp, LOCK_EX ); // exclusive lock
		$serstr = fread($fp, filesize($objects_filename));
		if ($serstr === FALSE) return("-2");
		fclose($fp);
		$objects = @unserialize($serstr);
		flock($fp, LOCK_UN ); // relase lock
		$fp = NULL;
	}
#	$objects = $this->GetObjects();
	if (file_exists($filename))
		$configlines = file($filename);
	else
		return(-1);

	foreach ($configlines as $line)	{
		
		$line = rtrim($line);

		# comments and emty lines are not processed
		if (preg_match("/^\s*#/", $line) == FALSE && $line != "" )	{

			if (preg_match("/^\s*define\s*(\w+)\s*{/", $line, $m))	{
			
				$currobj = $m[1];
				
				if (!isset($objects[$currobj]))	{
				
					$objects[$currobj] = array();
					$count = 0;
				} else 	
					$count = count($objects[$currobj]);
				
				$objects[$currobj][$count]['__cfgfile'] = $filename;
				$objects[$currobj][$count]['__type'] = $currobj;
				$objects[$currobj][$count]['__objectid'] = $count;

			} elseif (preg_match("/^\s*(\w+)\s*(.*)$/",$line,$m) && $currobj != "")	{
				
				$objects[$currobj][$count][$m[1]] = str_replace("\'", "'", $m[2]);
				$objects[$currobj][$count][$m[1]] = str_replace("\r", "\n", $objects[$currobj][$count][$m[1]]);
				
			} elseif (preg_match("/^\s*}/",$line))	{
			
				$currobj = "";
				$objectsread++;

			}
		}
	}
	# Write it back as serialized data
	if (is_array($objects))	{
	
		$fp = fopen($objects_filename, "wb");
		flock($fp, LOCK_EX ); // exclusive lock
		if (FALSE === fwrite($fp, serialize($objects)) ) 
			return("-3");
		fclose($fp);
		flock($fp, LOCK_UN ); // relase lock
		fflush($fp);
	}

	return($objectsread);
}



function NagiosWriteCGIObjects($file_handler)	{

#Examples:
#
#hostextinfo[es-eds]=/serverinfo/es-eds.html;novell40.gif;novell40.jpg;novell40.gd2;IntranetWare 4.11;100,50;3.5,0.0,-1.5;
#hostextinfo[rosie]=/serverinfo/rosie.html;win40.gif;win40.jpg;win40.gd2;NT Server 4.0;;;
#
#serviceextinfo[es-eds;PING]=http://www.somewhere.com?tracerouteto=$HOSTADDRESS$;;PING rate
#serviceextinfo[rosie;Security Alerts]=;security.gif;Security alerts
#

	$hostextinfo_line    = "hostextinfo[%s]=%s;%s;%s;%s;%s;%s;%s;\n"; # host, notes_url, icon, vrml, gd2, image_alt, 2D, 3D
	$serviceextinfo_line = "serviceextinfo[%s;%s]=%s;%s;%s\n"; # host, service, notes_url, icon, image_alt
	
	$extinfo = "\n\n\n\n";
	$hostextinfo = array ();
	$serviceextinfo = array();

	$cgiobjects1 = $this->GetObjects("hostextinfo");
	$cgiobjects2 = $this->GetObjects("serviceextinfo");

	$cgiobjects  = array_merge($cgiobjects1, $cgiobjects2);
	$cgiobjects1 = NULL;
	$cgiobjects2 = NULL;

	$a = 0;	# Count for $hostextinfo
	$b = 0; # Count for $serviceextinfo
	for ($i=0; $i<count($cgiobjects); $i++)	{

		switch ($cgiobjects[$i]["__type"])	{

			case "hostextinfo":
				$hostextinfo[$a]["host_name"]	= isset($cgiobjects[$i]["host_name"])	? $cgiobjects[$i]["host_name"]	: "";
				$hostextinfo[$a]["notes_url"]	= isset($cgiobjects[$i]["notes_url"])	? $cgiobjects[$i]["notes_url"]	: "";
				$hostextinfo[$a]["icon_image"]	= isset($cgiobjects[$i]["icon_image"])	? $cgiobjects[$i]["icon_image"]	: "";
				$hostextinfo[$a]["vrml_image"]	= isset($cgiobjects[$i]["vrml_image"])	? $cgiobjects[$i]["vrml_image"]	: "";
				$hostextinfo[$a]["gd2_image"]	= isset($cgiobjects[$i]["gd2_image"])	? $cgiobjects[$i]["gd2_image"]	: "";
				$hostextinfo[$a]["image_alt"]	= isset($cgiobjects[$i]["image_alt"])	? $cgiobjects[$i]["image_alt"]	: "";
				$hostextinfo[$a]["2d_coords"]	= isset($cgiobjects[$i]["2d_coords"])	? $cgiobjects[$i]["2d_coords"]	: "";
				$hostextinfo[$a]["3d_coords"]	= isset($cgiobjects[$i]["3d_coords"])	? $cgiobjects[$i]["3d_coords"]	: "";
				$a++;
				break;
			case "serviceextinfo":
				$serviceextinfo[$b]["host_name"]    = isset($cgiobjects[$i]["host_name"]) ? $cgiobjects[$i]["host_name"] : "";
				$serviceextinfo[$b]["service_name"] = isset($cgiobjects[$i]["service_name"]) ? $cgiobjects[$i]["service_name"] : "";
				$serviceextinfo[$b]["notes_url"]    = isset($cgiobjects[$i]["notes_url"]) ? $cgiobjects[$i]["notes_url"] : "";
				$serviceextinfo[$b]["icon_image"]   = isset($cgiobjects[$i]["icon_image"]) ? $cgiobjects[$i]["icon_image"] : "";
				$serviceextinfo[$b]["image_alt"]    = isset($cgiobjects[$i]["image_alt"]) ? $cgiobjects[$i]["image_alt"] : "";
				$b++;
				break;
		} #switch
	} #for

	$extinfo .= "# EXTENDED HOST INFORMATION\n";
	if (!empty($hostextinfo[0]))
		for ($i=0; $i<count($hostextinfo); $i++)	{

			$extinfo .= sprintf($hostextinfo_line, $hostextinfo[$i]["host_name"], $hostextinfo[$i]["notes_url"], 
						$hostextinfo[$i]["icon_image"], $hostextinfo[$i]["vrml_image"], $hostextinfo[$i]["gd2_image"], 
						$hostextinfo[$i]["image_alt"], $hostextinfo[$i]["2d_coords"], $hostextinfo[$i]["3d_coords"]);
		} #for
	# ---- echo " hostextinfo(".count($hostextinfo)." objects), ";

	$extinfo .= "\n";
	$extinfo .= "\n";
	$extinfo .= "# SERVICE HOST INFORMATION\n";
	if (!empty($serviceextinfo[0]))
		for ($i=0; $i<count($serviceextinfo); $i++)	{

			$extinfo .= sprintf($serviceextinfo_line, 
			$serviceextinfo[$i]["host_name"], 
			$serviceextinfo[$i]["service_name"], 
			$serviceextinfo[$i]["notes_url"], 
			$serviceextinfo[$i]["icon_image"], 
			$serviceextinfo[$i]["image_alt"]);
		} #for
	# ---- echo "serviceextinfo(".count($serviceextinfo)." objects)";

	# File has already been opened in the function NagiosWriteConfig
	fwrite($file_handler, $extinfo);
	# ---- echo "...";
}


#
# void NagiosWriteConfig(string filename, array config)
#
# Saves configuration to a file. It will overwrite existing files not
# preserving the original comments nor layout.
#
# Returns NULL on success, or a string when something went wrong.
#

function NagiosWriteConfig($fileid)	{

	global $NAGIOS_CFGFILES;

	$lines = array();
	$filename = $NAGIOS_CFGFILES[$fileid];
	
	$version = VERSION;
	$date = date("H:i:s - d M Y");
	$lines[0] = <<<TXT
#
# $filename - Config file for Nagios (www.nagios.org)
#
# Written by Nawui $version. Manually editing this file is a bad idea since Nawui will
# overwrite it each time you export objects. 
#
# Exported at $date
#

TXT;
	
	$config = $this->GetConfig($fileid);

	foreach(@$config as $key => $values)	{
	
		foreach($values as $value)	{
		
			$value = trim($value);
			if( $value != '' ) 
				$lines[] = "$key=".$value;
		}
	}
	
	# Save the array to the file
	if( $fp = fopen(NAGIOS_ETC."/$filename","w") )	{
	
		fwrite($fp,implode("\n\n",$lines));

		# Only have to pass the $fp file handler, NagiosWriteCGIObjects will use the open file.
		if ($fileid == "cgicfg") $this->NagiosWriteCGIObjects($fp);

		fclose($fp);
		return(NULL);
		
	} else {
		
		return("Could not open $filename for writing");
	}
	return("Something went wrong writing the configuration");
}

function NagiosWriteConfigs()	{


	global $NAGIOS_CFGFILES;

	foreach( $NAGIOS_CFGFILES as $fileid => $filename )	{
			
			print "<li> Writing file $filename...";
			
			if ( $errmsg = $this->NagiosWriteConfig($fileid) )	{
			
				print $errmsg;

			} else 	{
				
				print "success.";
			}
			flush();
	}
}



#
# void tmpNagiosWriteConfig(string filename, array config)
#
# Saves configuration to a file in a temporary directory. 
#
# Returns NULL on success, or a string when something went wrong.
#
# $tmpdir: is a full directory path string, to a writable directory where 
#         we want to store files temporarily to verify them.
#
function tmpNagiosWriteConfig($tmpdir, $fileid)	{
	
	global $NAGIOS_CFGFILES;

	$lines = array();
	$filename = $NAGIOS_CFGFILES[$fileid];
	$tmpdir="$tmpdir/";

	if (!is_dir($tmpdir))
		return "Temporary directory '$tmpdir' does not exist.\n";

	$version = VERSION;
	$date = date("H:i:s - d M Y");
	$lines[0] = <<<TXT
#
# $filename - Config file for Nagios (www.nagios.org)
#
# Written by Nawui $version. Manually editing this file is a bad idea since Nawui will
# overwrite it each time you export objects. 
#
# Exported at $date
#

TXT;

	$config = $this->GetConfig($fileid);

	if (count($config) != 0)	{
		
		foreach(@$config as $key => $values)	{
	
			foreach($values as $value)	{
		
				$value = trim($value);

				if ($value != '') $lines[] = "$key=".str_replace(NAGIOS_ETC, TMP_DIR, $value);
			}
		}
	} else {

		return "\n<br>\nNo objects found in database:";
	} #if
	
	# Save the array to the file
	if( $fp = fopen($tmpdir."$filename","w") ) {
	
		fwrite($fp,implode("\n\n",$lines));
		
		# Only have to pass the $fp file handler, NagiosWriteCGIObjects will use the open file.
		if ($fileid == "cgicfg") $this->NagiosWriteCGIObjects($fp);
		
		fclose($fp);
		return(NULL);
		
	} else {
	
		return("Could not open '$filename' for writing\n");
	}

	return("Something went wrong writing the configuration.\n");
}


function tmpNagiosWriteConfigs($tmpdir)	{

	global $NAGIOS_CFGFILES;

	$tmpdir="$tmpdir/";
	if (!is_dir($tmpdir)) return "Temporary directory '$tmpdir' does not exist.\n";


	foreach( $NAGIOS_CFGFILES as $fileid => $filename )	{
			
			$filename=$tmpdir.basename($filename);
			# ---- echo "<li> $filename...<br>\n";
			
			if ($errmsg = $this->tmpNagiosWriteConfig($tmpdir, $fileid)) 
				print $errmsg;
			
			flush();
	}
}

function tmpNagiosDeleteConfigs($tmpdir)	{

	global $NAGIOS_CFGFILES;

	$tmpdir="$tmpdir/";
	foreach( $NAGIOS_CFGFILES as $fileid => $filename )	{
			
			$filename=str_replace(NAGIOS_ETC, TMP_DIR, $tmpdir.basename($filename));
			
			if (DEBUG == 1) print "<li> Deleting file '$filename'...<br>\n";
			
			if (file_exists($filename))
				if (!unlink($filename)) 
					$errormsg = "Could not delete temporary file '$filename',<br>\n";
			
			flush();
		}
		
	if (isset($errormsg))
		return($errormsg);
	else
		return(NULL);
}


function NagiosWriteObjects()	{

	$foundone = FALSE;
	$index_start = 0;
	$index_stop = 0;
	$gotit = FALSE;
	$space = '';
	$ident = '';
	$fileobjs = array();
	

	$allobjects = $this->GetObjects();

	# Cleanup hostextinfo and serviceextinfo arrays
	# This will be writen in cgi.cfg by NagiosWriteConfigs function
	# and they have a different format
	unset($allobjects["cgicfg"]);		# <- This one should not be a problem if it was set
	unset($allobjects["hostextinfo"]);	# because only OBJECTTYPES are analized and written
	unset($allobjects["serviceextinfo"]);	# in this function. It's only a conscience discard!


	$excluded = array('__cfgfile', '__objectid', '__type');


	# Group objects by filename usage
	foreach( $allobjects as $type => $objarr)	{
		foreach( $objarr as $key => $object)	{
			if (@$object['__cfgfile'] != "")	{
				$fileobjs[$object['__cfgfile']][] = $object; 
				} #if
			} #foreach
		} #foreach

			foreach($fileobjs as $filename => $objects)	{
		
				echo "$filename&nbsp;&nbsp;&nbsp;(".count($objects)." objects)<br>\n";
				if( $fp = fopen($filename, "w") )	{

					$basefilename = basename($filename);
					$header = "#\n"
						 ."# $basefilename - Config file for Nagios (www.nagios.org)\n"
						 ."#\n"
						 ."# Written by Nawui ".VERSION.". Manually editing this file is a bad idea since Nawui will\n"
						 ."# overwrite it. \n"
						 ."#\n"
						 ."# Exported at ".date("H:i:s - d M Y")."\n"
						 ."#\n"
						 ."\n";
						
					fwrite($fp, $header."\n");

					foreach($objects as $object)	{
							
						$type = $object['__type'];
						fwrite($fp, "define $type {\n");
						foreach($object as $key => $val) {
							if( (!empty($val) || $val == 0) && !in_array($key,$excluded) )	{
								if (is_Array($val)) $val=implode(",", $val);
								fwrite($fp, sprintf("\t\t%-30s %s\n", $key, $val));
							}
						}
						fwrite($fp, "\t\t}\n\n");
					} #foreach
					fclose($fp);
				} else	{

					return "Could not open file '$filename' for writing";
				} #if
			} #foreach
	return(NULL);
}

# This function will write Nagios Objects to some temporary directory
# so this files can't overwrite the currently used files.
#
# $tmpdir: is a full directory path string, to a writable directory where 
#         we want to store files temporarily to verify them.

function tmpNagiosWriteObjects($tmpdir)	{

	$foundone = FALSE;
	$index_start = 0;
	$index_stop = 0;
	$gotit = FALSE;
	$space = '';
	$ident = '';
	$fileobjs = array();
	

	$allobjects = $this->GetObjects();
	$tmpdir="$tmpdir/";
	
	# Cleanup hostextinfo and serviceextinfo arrays
	# This will be writen in cgi.cfg by NagiosWriteConfigs function
	# and they have a different format
	unset($allobjects["cgicfg"]);		# <- This one should not be a problem if it was set
	unset($allobjects["hostextinfo"]);	# because only OBJECTTYPES are analized and written
	unset($allobjects["serviceextinfo"]);	# in this function. It's only a conscience discard!

	$excluded = array('__cfgfile', '__objectid', '__type');

	if (!is_dir($tmpdir))
		return "Temporary directory '$tmpdir' does not exist.<br>\n";

	if (count($allobjects) != 0)	{
	
		# Group objects by filename usage
		foreach( $allobjects as $type => $objarr)	{
			foreach( $objarr as $key => $object)	{
				if (@$object['__cfgfile'] != "")		{
			
				    # add $tmpdir to every configuration file
				    $object['__cfgfile'] = $tmpdir.basename($object['__cfgfile']);
				    $fileobjs[$object['__cfgfile']][] = $object;
				} #if
			} #foreach
		} #foreach

		foreach($fileobjs as $filename => $objects)	{

			# ---- echo "<li> $filename&nbsp;&nbsp;&nbsp;(".count($objects)." objects)<br>\n";
			# - echo "<li>".count($objects)." ".ucfirst(basename($filename, ".cfg"))." objects<br>\n";
			if ($fp = fopen($filename, "w"))	{

				$basefilename = basename($filename);
				$header = "#\n"
					 ."# $basefilename - Config file for Nagios (www.nagios.org)\n"
					 ."#\n"
					 ."# Written by Nawui. Manually editing this file is a bad idea since Nawui will\n"
					 ."# overwrite it everytime you export your objects. \n"
					 ."#\n"
					 ."\n";
			
				fwrite($fp, $header."\n");
				
				foreach($objects as $object)	{
						
					$type = $object['__type'];

					fwrite($fp, "define $type {\n");
						
					foreach($object as $key => $val)	{
						if( (!empty($val) || $val == 0) && !in_array($key,$excluded) )	{
						
							if (is_Array($val)) 
								$val=implode(",", $val);
						
							fwrite($fp, sprintf("\t\t%-30s %s\n", $key, $val));
						} #if
					} #foreach
					fwrite($fp, "\t\t}\n\n");
				} #foreach
				fclose($fp);
			
			} else return "Could not open file '$filename' for writing";
		} #foreach
		
	} else return "\n<br>\nNo objects found in database:";

	# Verify if all configuration files defined in nagios.cfg (cfg_file) exist,
	# if not create empty ones.
	$nagioscfg = $this->GetConfig("nagioscfg");
	$cfg_file=$nagioscfg["cfg_file"];
	
	for ($i=0; $i < count($cfg_file); $i++)	{

		$filename = str_replace(NAGIOS_ETC, TMP_DIR, $cfg_file[$i]);

		if (!is_file($filename))	{

				# ---- echo "<li> $filename&nbsp;&nbsp;&nbsp;(0 objects)<br>\n";
				
				$fp = fopen($filename, "w");


				$basefilename = basename($filename);
				$header = "#\n"
					 ."# $basefilename - Config file for Nagios (www.nagios.org)\n"
					 ."#\n"
					 ."# Written by Nawui. Manually editing this file is a bad idea since Nawui will\n"
					 ."# overwrite it everytime you export your objects. \n"
					 ."#\n"
					 ."\n";
			
				fwrite($fp, $header."\n");
				fclose($fp);
		} #if
	} #foreach

	# And finally, also verify or create the 'resource_file'.
	$filename = str_replace(NAGIOS_ETC, TMP_DIR, $nagioscfg["resource_file"][0]);
	if (!is_file($filename))	{

		# ---- echo "<li> $filename...<br>\n";
		$fp = fopen($filename, "w");

		$basefilename = basename($filename);
		$header = "#\n"
			 ."# $basefilename - Config file for Nagios (www.nagios.org)\n"
			 ."#\n"
			 ."# Written by Nawui. Manually editing this file is a bad idea since Nawui will\n"
			 ."# overwrite it everytime you export your objects. \n"
			 ."#\n"
			 ."\n";
			
		fwrite($fp, $header."\n");
		fclose($fp);
	} #if

	return(NULL);
}



# This function will write Nagios Objects to some temporary directory
# so this files can't overwrite the currently used files.
#
# $tmpdir: is a full directory path string, to a writable directory where 
#         we want to store files temporarily to verify them.

function tmpNagiosDeleteObjects($tmpdir)	{
	
	$errormsg = "";
	$error = NULL;

	# Delete all temporary configuration files defined in nagios.cfg (cfg_file)
	$nagioscfg = $this->GetConfig("nagioscfg");
	$cfg_file=$nagioscfg["cfg_file"];
	
	for ($i=0; $i<count($cfg_file); $i++)	{

		$filename = str_replace(NAGIOS_ETC, TMP_DIR, $cfg_file[$i]);
		
		if (is_file($filename))	{
		
			if (DEBUG == "1" ) echo "deleting $filename...<br>\n";

			if (@!unlink($filename)) 
				$error = "Could not delete temporary filename '$filename'.<br>\n";

			if (isset($error))	{

				$errormsg .= $error;
				$error = NULL;
			}
		} #if
	} #for
	# And finally, also remove temporary 'resource_file'.
	$filename = str_replace(NAGIOS_ETC, TMP_DIR, $nagioscfg["resource_file"][0]);

	if (is_file($filename))	{
		if (DEBUG == "1" ) echo "deleting $filename...<br>\n";

		if (@!unlink($filename)) 
			$error = "Could not delete temporary filename '$filename'.<br>\n";

		if (isset($error))	{

			$errormsg .= $error;
			$error = NULL;
		}
	} #if
} #function



} #class


?>
Return current item: NaWui