Location: PHPKode > projects > NaWui > nawui/includes/functions.inc.php
<?php

#
#
# array LoadNawuiConfig()
#
# This will load NaWui configurations defined in config.inc
# and it will export them as an array similar to those found 
# in 'nagiosdata.inc', so it can be passed like '$proptions' widgets.
#
function LoadNawuiConfig()	{

	global $website_url, $nawui_root, $nawui_url, $tmp_dir, $objects_per_page, 
	$page_refresh, $nawui_plugin, $nagios_bin, $nagios_etc, $nagios_plugins, 
	$nagios_webroot, $nagios_url, $nagios_cgis, $debug, $error_level, 
	$show_page_info;

	$nawuicfg = array();

	$nawuicfg["website_url"][0]=$website_url;
	$nawuicfg["nawui_root"][0]=$nawui_root;
	$nawuicfg["nawui_url"][0]=$nawui_url;
	$nawuicfg["tmp_dir"][0]=$tmp_dir;
	$nawuicfg["objects_per_page"][0]=$objects_per_page;
	$nawuicfg["page_refresh"][0]=$page_refresh;
	$nawuicfg["nawui_plugin"][0]=$nawui_plugin;
	$nawuicfg["nagios_bin"][0]=$nagios_bin;
	$nawuicfg["nagios_etc"][0]=$nagios_etc;
	$nawuicfg["nagios_plugins"][0]=$nagios_plugins;
	$nawuicfg["nagios_webroot"][0]=$nagios_webroot;
	$nawuicfg["nagios_url"][0]=$nagios_url;
	$nawuicfg["nagios_cgis"][0]=$nagios_cgis;
	$nawuicfg["debug"][0]=$debug;
	$nawuicfg["error_level"][0]=$error_level;
	$nawuicfg["show_page_info"][0]=$show_page_info;

	return($nawuicfg);

}

function SaveNawuiConfig($nawuicfg = NULL)	{

	if ($nawuicfg == NULL) return("Empty Nawui configuration array.");
	
	$website_url		= $nawuicfg["website_url"][0];
	$nawui_root		= $nawuicfg["nawui_root"][0];
	$nawui_url		= $nawuicfg["nawui_url"][0];
	$tmp_dir		= $nawuicfg["tmp_dir"][0];
	$objects_per_page	= $nawuicfg["objects_per_page"][0];
	$page_refresh		= $nawuicfg["page_refresh"][0];
	$nawui_plugin		= $nawuicfg["nawui_plugin"][0];
	$nagios_bin		= $nawuicfg["nagios_bin"][0];
	$nagios_etc		= $nawuicfg["nagios_etc"][0];
	$nagios_plugins		= $nawuicfg["nagios_plugins"][0];
	$nagios_webroot		= $nawuicfg["nagios_webroot"][0];
	$nagios_url		= $nawuicfg["nagios_url"][0];
	$nagios_cgis		= $nawuicfg["nagios_cgis"][0];
	$debug			= $nawuicfg["debug"][0];
	$error_level		= $nawuicfg["error_level"][0];
	$show_page_info		= $nawuicfg["show_page_info"][0];

	$filename = "includes/config.inc";
	$content = "<?php\n"
."\n"
."# - Main Settings - \n"
."\n"
."# Webserver complete URL (ex: http://nagios.domain.com)\n"
.'$'."website_url = \"$website_url\";\n"
."\n"
."# Server directory location of NAWUI HTML files.\n"
.'$'."nawui_root = \"$nawui_root\";\n"
."\n"
."# Relative NaWui URL (ex: /nawui). This will be appended to the WEBSITE_URL defined above.\n"
.'$'."nawui_url = \"$nawui_url\";\n"
."\n"
."# Temporary directory. MUST be world writeable.\n"
.'$'."tmp_dir = \"$tmp_dir\";\n"
."\n"
."# Objects shown per-page in tables.\n"
.'$'."objects_per_page = \"$objects_per_page\";\n"
."\n"
."# Time between table pages refreshes (0 = None).\n"
.'$'."page_refresh = \"$page_refresh\";\n"
."\n"
."# NaWui Plugin to be used. You can find them in '/plugins' directory.\n"
."# This should be defined only by name ignoring the file extention, since all files have '.inc'.\n"
."# (ex: 'serialized'  to use serialized.inc file)\n"
.'$'."nawui_plugin = \"$nawui_plugin\";\n"
."\n"
."\n"
."# - Nagios Settings -\n"
."\n"
."# Location of Nagios executable file (ex: /usr/bin/nagios)\n"
.'$'."nagios_bin = \"$nagios_bin\";\n"
."\n"
."# Directory location of Nagios configuration files (ex: nagios.cfg, cgi.cfg, etc.)\n"
.'$'."nagios_etc = \"$nagios_etc\";\n"
."\n"
."# Directory location of Nagios plugin files (ex: check_disk, check_ping, etc.)\n"
.'$'."nagios_plugins = \"$nagios_plugins\";\n"
."\n"
."# Server directory location of Nagios HTML files (ex: /var/www/html/nagios)\n"
.'$'."nagios_webroot = \"$nagios_webroot\";\n"
."\n"
."# Relative Nagios URL (ex: /nagios). This will be appended to the WEBSITE_URL defined above.\n"
.'$'."nagios_url = \"$nagios_url\";\n"
."\n"
."# Relative Nagios CGI-BIN (ex: /cgi-bin/nagios). This will be appended to the WEBSITE_URL defined above.\n"
.'$'."nagios_cgis = \"$nagios_cgis\";\n"
."\n"
."\n"
."# *********** TROUBLESHOOTING SETTINGS ************\n"
."\n"
."# To enable HTML DEBUG in all php files.\n"
.'$'."debug = \"$debug\";\n"
."\n"
."# PHP Error Level. Default is  7, for good troubleshooting use 9.  \n"
."#(You should check PHP Documentation for information on php eror levels)\n"
.'$'."error_level = \"$error_level\";\n"
."\n"
."# Show pages information at bottom (ex: pagename, version, date, etc.)\n"
.'$'."show_page_info = \"$show_page_info\";\n"
."\n"
."\n"
."?>";

	if (file_exists($filename)) {
	
		if (!is_writable($filename)) 
			return("Config file is not writeable.");
	} 

	$file = fopen($filename, "w");

	if (!fwrite($file, $content))
		return ("Could not write to file.");
    
    	fclose($file);
	return(TRUE);
}

#
# void PrintArray (mixed expression)
#
# Same as print_r function in PHP but PrintArray prints surrounds it with a
# <pre> HTML tag.
#
function PrintArray($expression)	{

	print("\n<pre>\n");
	print_r($expression);
	print("</pre>\n");
}

#
# void ErrorMsg(string msg)
#
# Prints an error message (not very smart)
#
function ErrorMsg($msg)	{

	if( $msg != "" )	{
	
		print("<font class=\"error\">$msg</font>\n");
	}
}



#
# string FileSelect(string dirname, string name, string selected
#		[, mixed fileext] )
#
# Creates a dropdown of files of with a certain file extention in a directory
#
# Return a HTML select or a string when something went wrong.
#
# Note: not finished!
# 
function FileSelect($dirname,$name,$selected,$fileext = NULL)	{
	$exts = array();
	$option = '   <option value="%s" %s> %s';

	$dir = @opendir($dirname);
	if( $dir == FALSE ) {
		return "Could not open dir $dir";
	}
 	if( $fileext != NULL ) {
		if( is_array($fileext) == FALSE) {
			$exts[] = $fileext;
		} else {
			$exts = $fileext;
		}
	}
	while (($file = readdir($dir)) !== false) {
		$add = TRUE;
		if( preg_match("/\.(\w+)$/",$file,$m) == TRUE) {
			$ext = $m[1];
		} else {
			$ext = '';
		}

		if( filetype($dirname."/".$file) != "file") {
			$add = FALSE;
		} else if( in_array($ext,$exts) && $fileext != NULL ) {
			$add = TRUE;
		} else if( $fileext != NULL ) {
			$add = FALSE;
		}

		if( $add == TRUE ) { 
			$sel = ($selected == $file) ? 'selected' : '';
			$opts[$file] = sprintf($option, $file, $sel, $file);
		}
	}

	ksort($opts);
	$options = implode("\n",$opts);

	return <<<HTML
<select name="$name">
<option value="">
$options
</select>
HTML;
}

#
# array PrepareObject(string name, string type, array objects)
#
# Helper function for the *edit.php scripts. It takes some information and
# figures out whether it is an existing object or a new one. In case of a new
# one it will try to set some default values
#
# Returns a hash containing object information.
#
function PrepareObject($name,$type,$objects)	
{
	global $message, $errmsg;
	$object = array();

	if( $name != "newobject" ) {
		$object = NagiosSearchObject($type,$objects,$name);
		if( $object == NULL ) {
			$errmsg = "<br> '$type' object $name not found!";
			$name = "newobject";
		}
	}

	if( $name == "newobject" ) { 
		$object['__cfgfile'] = @$objects[$type][0]['__cfgfile'];
		$object['__type'] = $type;
		$message = "New '$type' object.";
	}
	
	return $object;
}

#
# string ObjectUsage(string name, string objecttype, array userobjs)
#
# Creates a summary for an object from $userobjs.
#
# Returns HTML code. 
#
function ObjectUsage($name, $objecttype, $userobjs, $editview = 'view')	{

	$output = array();
	$rowcolor = "";
	$cntusers = "";

	foreach($userobjs as $objectgroup)
		$cntusers += count($objectgroup);
		
	$output[] = <<<HTML
<tr class="data">
  <th colspan="4" class="data">
  The following <b>$cntusers</b> object(s) are using this object:
  </td>
</tr>
HTML;
	foreach ($userobjs as $type => $objectgroup)	{
	
		foreach ($objectgroup as $key => $userobj)	{
	
			# Handle service objects
			if ($type == 'service')	{
			
				if (empty($userobj['name']))	{
				
					$text = $userobj['service_description'].' on host '.$userobj['host_name'];
					
				} else {
				
					$text = ' template '.$userobj['name'];
					
				}
				
			} else {
			
				$text = $userobj[$type.'_name'];
				
			}
			$rand_win = rand(0, count($objectgroup)); 	# Randomize a number to create a new popup window name for each object (ex: nw2, nw43)
			
			$rowcolor = ($rowcolor != "dataOdd") ? "dataOdd" : "dataEven";
			
			$output[] = <<<HTML
<tr class="{$rowcolor}">
  <td>'$type' object:
  <td></td>
  <td>&nbsp;
  <a href="{$type}{$editview}.php?objectid=$key" onclick="nw{$rand_win}=window.open('', 'object_usage{$rand_win}', 'resizable=no, scrollbars=1, copyhistory=0, width=700, height=550');nw{$rand_win}.opener=self" target="object_usage{$rand_win}">$text</a>&nbsp;
  </td>
  <td>&nbsp;</td> 
</tr>
HTML;

		}
	}

	return(implode("\n",$output));
}

#
# string ObjectInheritance(array objects, string name, string objecttype)
#
# Generates HTML showing which objects are inheriting from this object.
#
# Returns HTML code. 
#
function ObjectInheritance($name, $objecttype, $editable)	{

	global $Plugin;

	$objects = $Plugin->GetObjects($objecttype);

	if (!is_array($objects))	{
	
		return(NULL);
	}

	$output = array();

	$output[] = <<<HTML
<tr class="data">
  <th colspan="3">
  The following object(s) inherit from this object:
  </th>
</tr>
HTML;

	foreach ($objects as $key => $inhobj)	{

		if (!isset($inhobj['use']) ) 
			continue;

		if ($inhobj['use'] != $name ) 
			continue;

		# We have one
		if ($objecttype == 'service')	{
		
			$inhname = $inhobj['service_description']. ' on host '.$inhobj['host_name'];
			
		} else {
		
			$inhname = $inhobj[$objecttype.'_name'];
			
		}
		if ($editable) $ahref = "<a href=\"".$objecttype."edit.php?objectid=".$key."\" onclick=\"nw".$key."=window.open('', 'object_usage".$key."', 'resizable=no, scrollbars=1, copyhistory=0, width=700, height=550');nw{$rand_win}.opener=self\" target=\"object_usage".$key."\">".$inhname."</a>&nbsp;";
		else $ahref = "<a href=\"".$objecttype."view.php?objectid=".$key."\" onclick=\"nw".$key."=window.open('', 'object_usage".$key."', 'resizable=no, scrollbars=1, copyhistory=0, width=700, height=550');nw{$rand_win}.opener=self\" target=\"object_usage".$key."\">".$inhname."</a>&nbsp;";

		$rand_win = rand(0, count($objectgroup)); 	# Randomize a number to create a new popup window name for each object (ex: nw2, nw43)
	        
		$alter = ($alter != "dataOdd") ? "dataOdd" : "dataEven";
		
		$output[] = <<<HTML
<tr class="{$alter}">
  <td>&nbsp;Service Object:&nbsp;</td>
  <td>&nbsp;</td>
  <td colspan="2">$ahref</td>
</tr>
HTML;
	}

	return(implode("\n", $output));
}


# --------------------

# SORT FUNCTIONS

# The Two functions below were taken from user comments in PHP.NET online documentation.
/**
** comesafter ($s1, $s2)
**
** Returns 1 if $s1 comes after $s2 alphabetically, 0 if not.
**/

function comesafter ($s1, $s2) {
/**
** We don't want to overstep the bounds of one of the strings and segfault,
** so let's see which one is shorter.
**/
	$order = 1;
	if (strlen ($s1) > strlen ($s2)) {
		$temp = $s1;
		$s1 = $s2;
		$s2 = $temp;
		$order = 0;
	}
	for ($index = 0; $index < strlen ($s1); $index++)       {
		/** ** $s1 comes after $s2 **/
		if ($s1[$index] > $s2[$index]) return ($order);
		/** ** $s1 comes before $s2 **/
		if ($s1[$index] < $s2[$index]) return (1 - $order);
	}
	/** Special case in which $s1 is a substring of $s2 **/
	return ($order);
}



/**
** asortbyindex ($sortarray, $index)
**
** Sort a multi-dimensional array by a second-degree index in REVERSE ORDER. For instance, the 0th index
** of the Ith member of both the group and user arrays is a string identifier. In the
** case of a user array this is the username; with the group array it is the group name.
** arsortby
**/

function arsortbyindex ($sortarray, $index)     {

	# Check if first record of array start at [0] or [1] and ajust $lastindex.
	if (is_array($sortarray[0])) {
		$firstindex = 0;
		$lastindex = count ($sortarray) - 1;
	}
	else	{
		$firstindex = 1;
		$lastindex = count ($sortarray);
	}
	
	for ($subindex = 0; $subindex < $lastindex; $subindex++) {
		$lastiteration = $lastindex - $subindex;
		for ($iteration = $firstindex; $iteration < $lastiteration; $iteration++) {
			$nextchar = 0;
			if (!@comesafter ($sortarray[$iteration][$index], $sortarray[$iteration + 1][$index]))   {
				$temp = $sortarray[$iteration];
				$sortarray[$iteration] = $sortarray[$iteration + 1];
				$sortarray[$iteration + 1] = $temp;
			}
		}
	}
	return ($sortarray);
}



/**
** asortbyindex ($sortarray, $index)
**
** Sort a multi-dimensional array by a second-degree index. For instance, the 0th index
** of the Ith member of both the group and user arrays is a string identifier. In the
** case of a user array this is the username; with the group array it is the group name.
** asortby
**/

function asortbyindex ($sortarray, $index)      {

	# Check if first record of array start at [0] or [1] and ajust $lastindex.
	if (is_array($sortarray[0])) {
		$firstindex = 0;
		$lastindex = count ($sortarray) - 1;
	}
	else	{
		$firstindex = 1;
		$lastindex = count ($sortarray);
	}
	
	$lastindex = count ($sortarray) - 1;
	for ($subindex = 0; $subindex < $lastindex; $subindex++) {
		$lastiteration = $lastindex - $subindex;
		for ($iteration = $firstindex; $iteration < $lastiteration; $iteration++) {
			$nextchar = 0;
			if (@comesafter($sortarray[$iteration][$index], $sortarray[$iteration + 1][$index]))    {
				$temp = $sortarray[$iteration];
				$sortarray[$iteration] = $sortarray[$iteration + 1];
				$sortarray[$iteration + 1] = $temp;
			}
		}
	}
	return ($sortarray);
}




function debug_window_msg($msg)	{


	print "$msg";

}


function scandir($dir, $sorting_order)	{


	$files = array();

	if ($handle = opendir($dir)) {

		while (false !== ($filename = readdir($handle))) { 
			
			$files[]=$filename;
		}
	
		if ($sorting_order == 0) sort($files);
		else rsort($files);

		closedir($handle); 
		return($files);
		
	} else {

		trigger_error ("Cannot open dir", E_WARNING);
		return(FALSE);
	}


} #function


function filter_valid_files($src_files)	{


	$files = NULL;

	for ($i=0; $i<count($src_files); $i++)	{

		# FIX ME - To be rewriten has a perl-compatible reg exprexion
		if (!strstr($src_files[$i], ".swp") && !strstr($src_files[$i], "~") && !strstr($src_files[$i], "core"))

				$files[] = $src_files[$i];
	} #for
	return($files);
} #function


function filter_plugin_files($src_files)	{


	$files = NULL;

	# Pay attention that we start from 2, because [0]='.' and [1]='..'
	for ($i=2; $i<count($src_files); $i++)	{

		# FIX ME - To be rewriten has a perl-compatible reg exprexion
		$src_files=filter_valid_files($src_files);

			if (preg_match("/^plugin_./", $src_files[$i]))

				$files[] = $src_files[$i];
	} #for
	return($files);
} #function


# -- Functions ---

function load_plugins()	{

	global $plugindir, $plugins, $plugin, $plugin_files;

	if (!is_dir($plugindir))	{
				
		debug_msg("No plugin directory found ($plugindir)."."<br>\n");
		return("No plugins found!");
	} #if

	$plugin_files=scandir($plugindir);

	if (count($plugin_files) < 2)	{

		debug_msg("No plugins found in '$plugindir'.".count($plugin_files)."<br>\n");
		return("No plugins found.");
	} #if

	$plugin_files=filter_plugin_files($plugin_files);

	for ($i=0; $i<count($plugin_files);$i++)	{

		debug_msg("Including".$plugindir."/".basename($plugin_files[$i])."<br>\n");
		include_once($plugindir."/".basename($plugin_files[$i]));
	} #for
} #function


?>
Return current item: NaWui