function.php 43.3 KB
Newer Older
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
1 2 3 4
<?php
/*
#########################################
#
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
5
# Copyright (C) 2017 EyesOfNetwork Team
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
6
# DEV NAME : Jean-Philippe LEVY
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
7
# VERSION : 5.2
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
# APPLICATION : eonweb for eyesofnetwork project
#
# LICENCE :
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
#########################################
*/

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
23
# Internationalization
24 25 26 27 28 29 30 31
include("classes/Translator.class.php");

# Actions
include("classes/Actions.class.php");	
if(file_exists(dirname(__FILE__)."/classes/Custom.Actions.class.php")) { 
	include("classes/Custom.Actions.class.php"); 
}
$CustomActions = class_exists("CustomActions") ? new CustomActions() : new Actions();
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
32

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
33 34 35
// Display Error Message 
function message($id, $text, $type){
	
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
36
	global $array_msg;
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
37 38 39 40 41 42
	
	// Get standard message if exists
	if(isset($array_msg[$id])) { $tempid=$array_msg[$id]; } 
	else { $tempid=""; }
	
	// Define the message type and icon
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
43 44 45
	switch($type)
	{
		case "critical":
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
46 47
			$alert_type = "danger";
			$alert_icon = "fa-exclamation-circle";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
48 49
			break;
		case "warning":
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
50 51
			$alert_type = "warning";
			$alert_icon = "fa-warning";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
52 53
			break;
   		case "ok":
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
54 55
   			$alert_type = "success";
			$alert_icon = "fa-check-circle";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
56 57
			break;
		default:
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
58 59 60
			$alert_type = "info";
			$alert_icon = "fa-info-circle";
			break;
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
61 62
	}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
63 64 65 66 67 68 69 70
	// Display the message
	echo "<p class='alert alert-dismissible alert-".$alert_type." fade in'>
			<button type='button' class='close' data-dismiss='alert' aria-label='Close'>
			  <span aria-hidden='true'>&times;</span>
			</button>
			<i class='fa ".$alert_icon."'></i> $tempid $text
		  </p>";
}
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
71 72

// Connect to Database
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
73
function sqlrequest($database,$sql,$id=false,$prepare=false){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

	// Get the global value
	global $database_host;
	global $database_username;
	global $database_password;

	$connexion = mysqli_connect($database_host, $database_username, $database_password, $database);
	if (!$connexion) {
		echo "<ul>";
		echo "<li class='msg_title'>Alert EyesOfNetwork - Message EON-database connect</li>";
		echo "<li class='msg'> Could not connect to database : $database ($database_host)</li>";
		echo "</ul>";
		exit(1);
	}

	if ( $database == "eonweb" ) {
		// Force UTF-8
		mysqli_query($connexion, "SET NAMES 'utf8'");
	}
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
	
	if(is_array($prepare)) {
		$stmt = mysqli_prepare($connexion,$sql);
		
		if(isset($prepare[0]) && isset($prepare[1])) {
			$ref = new ReflectionClass('mysqli_stmt');
			$method = $ref->getMethod("bind_param");
			$method->invokeArgs($stmt,$prepare);
		}
		
		mysqli_stmt_execute($stmt);
		$result = mysqli_stmt_get_result($stmt);
	} else {
		$result=mysqli_query($connexion, "$sql");
	}
		
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
109 110 111 112 113 114 115 116
	if($id==true)
		$result=mysqli_insert_id($connexion);
		
	mysqli_close($connexion);
	return $result;
}

// Display array value
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
117
function display_value($value, $key){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
118 119 120 121
	echo "$value\n";
}

// Function Edit and Modify a file
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
122
function filemodify($path,$get=false){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
	if(is_writable($path)) {
	
		// Test If Update or Display.
		if (isset($_POST['maj'])) {
			if (!$fconf = fopen($path, "w")) message(2,$path,"critical");
			// Write the change
			if (fwrite ($fconf, str_replace("\r\n", "\n", $_POST['maj'])) === FALSE) message(3,$path,"critical");
			else { 
				message(6," : File updated","ok");
			}
			fclose ($fconf);
			if (!$fconf = fopen($path, "r")) message(2,$path,"critical");
		}
		else if (!$fconf = fopen($path, "r")) message(2,$path,"critical");

		// Display the Text Area and button
		echo "<form method='post' action='./index.php";
		if($get)
			echo "?file=$get";
		echo "'>";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
143 144
		echo '<div class="form-group">';
		echo "<textarea class='form-control textarea' cols='100' rows='20' name='maj' scrolling='no'>";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
145
			print file_get_contents($path);
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
146 147 148 149 150
		echo "</textarea>";
		echo '</div>';
		echo '<div class="form-group">';
		echo "<input class='btn btn-primary' type='submit' value='".getLabel("action.update")."'>";
		echo '</div>';
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
151 152 153 154 155 156 157
		echo "</form>";
		fclose ($fconf);
	}
	else message(3,$path,"critical");
}

// Host List form Nagios
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
158
function get_host_list_from_nagios($field=false, $queue = false){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
159
	global $database_lilac;
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
160
	global $database_ged;
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
161 162
	$hosts=array();

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
163 164 165 166 167 168 169 170 171 172 173
	if($field && $field != 'owner'){
		switch ($field) {
			case 'service': $column = 'description'; break;
			case 'description': echo json_encode($hosts); return; break;
			default: $column = 'name'; break;
		}
		$request="SELECT DISTINCT $column FROM nagios_$field ORDER BY $column";
		$db = $database_lilac;
	} elseif ($field && $field === 'owner') {
		$request="SELECT DISTINCT owner FROM nagios_queue_$queue WHERE owner != '' ORDER BY owner";
		$db = $database_ged;
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
174 175 176 177
	}
	else {
		$request="SELECT name FROM nagios_host
		UNION SELECT name from nagios_hostgroup
178
		UNION SELECT DISTINCT description from nagios_service
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
179 180
		UNION SELECT name from nagios_service_group
		ORDER BY name";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
181
		$db = $database_lilac;
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
182 183
	}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
184
	$result=sqlrequest($db,$request);
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
185
 	while ($line = mysqli_fetch_array($result)){ 
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
186
		array_push($hosts, $line[0]);
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
187 188 189 190
	}
	echo json_encode($hosts);
}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
191 192
// Host and Address list from nagios. //TODO send the adress
function get_host_list(){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
193 194 195 196 197 198 199 200 201 202 203 204
	global $database_lilac;
	$hosts=array();

	$result=sqlrequest($database_lilac,"SELECT name,address FROM nagios_host ORDER BY name");

 	while ($line = mysqli_fetch_array($result)){ 
		$hosts[]=$line[0];
		$hosts[]=$line[1];
	}
	echo json_encode($hosts);
}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
205
// Host and Address listbox from nagios. //TODO send the adress
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
206 207 208
function get_host_listbox_from_nagios(){
	global $database_lilac;
	
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
209 210 211 212
	// create input autocomplete with all nagios host values
	echo "<label>Host</label>";
	$result=sqlrequest($database_lilac,"SELECT DISTINCT name FROM nagios_host UNION ALL SELECT DISTINCT address FROM nagios_host");
	$input = "<input id='host_list' class='form-control' type='text' name='host_list' onFocus='$(this).autocomplete({source: [";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
213 214
	while ($line = mysqli_fetch_array($result))
	{
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
215
		$input .= '"'.$line[0].'",';
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
216
	}
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
217 218 219 220 221 222 223 224 225 226
	$input = rtrim($input, ",");
	$input .= "]})'>";
	
	echo '<div class="input-group">';
	echo 	$input;
	echo 	'<span class="input-group-btn">
				<input class="btn btn-primary" type="submit" name="run" value="'.getLabel("action.run").'" >
			</span>
			';
	echo '</div>';
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
227 228 229
}

// Host list from CACTI
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
230 231 232 233 234 235 236 237 238 239 240 241
function get_title_list_from_cacti(){

	global $database_cacti;

	$titles=array();
	$request="SELECT DISTINCT graph_templates_graph.title FROM graph_local,graph_templates_graph WHERE graph_templates_graph.local_graph_id=graph_local.id ORDER BY title";
	$result=sqlrequest($database_cacti,$request);
	while ($line = mysqli_fetch_array($result)){
	$line[0]=str_replace("|host_description| - ","",$line[0]);
		$titles[]=$line[0];
	}
	echo json_encode($titles);
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
242 243
}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
244
// Host listbox from CACTI
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
245
function get_host_listbox_from_cacti(){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
246
	
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
247
	global $database_cacti;
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
248
	
249
	$ref = "";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
250 251 252 253
	if( isset($_GET['host']) ){
		$ref = $_GET['host'];
	}
	
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
254
	$result=sqlrequest($database_cacti,"SELECT DISTINCT host.id,hostname,description FROM host INNER JOIN graph_local ON host.id = graph_local.host_id ORDER BY hostname ASC");
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
255
	echo "<SELECT name='host' class='form-control' size=7>";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
256 257
        while ($line = mysqli_fetch_array($result))
        {
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
258 259 260
			echo "<OPTION value='$line[0]' ";
			if($ref == $line[0]){echo 'selected="selected"';}
			echo ">&nbsp;$line[1] ($line[2])&nbsp;</OPTION>";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
261
        }
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
262
        echo "</SELECT><br>";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
263 264 265
}

// system function : CUT
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
266
function cut($string, $width, $padding = "..."){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
267 268 269 270 271 272 273 274
    return (strlen($string) > $width ? substr($string, 0, $width-strlen($padding)).$padding : $string);
} 

// Get graph from CACTI
function get_graph_listbox_from_cacti(){
	
	global $database_cacti;
	
275
	$ref = "";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
276 277 278 279 280 281 282 283 284 285 286 287 288
	if( isset($_GET['graph']) ){
		$ref = $_GET['graph'];
	}
	
	$result=sqlrequest($database_cacti,"SELECT DISTINCT graph_templates.id,name FROM graph_templates INNER JOIN graph_local ON graph_local.graph_template_id = graph_templates.id ORDER BY name ASC");
	echo "<SELECT name='graph' class='form-control' size=7>";
	while ($line = mysqli_fetch_array($result))
	{
		echo "<OPTION value='$line[0]' ";
		if($ref == $line[0]){echo 'selected="selected"';}
		echo ">&nbsp;$line[1]&nbsp;</OPTION>";
	}
	echo "</SELECT><br>";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
289 290 291 292 293 294
}

// Display TOOL list
function get_tool_listbox(){
	// Get the global table
	global $array_tools;
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
295 296
	
	echo "<label>".getLabel("label.tool_all.tool")."</label>";	
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
297

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
298 299
	// Get the first array key
	reset($array_tools);
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
300 301

	// Display the list of tool
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
302
	echo "<SELECT id='tool_list' name='tool_list' class='form-control'>";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
303 304
 	while (list($tool_name, $tool_url) = each($array_tools)) 
	{
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
305 306 307
		echo "<OPTION value='$tool_url'>$tool_name</OPTION>";
	}
	echo "</SELECT>";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
308 309 310 311 312 313
}

// Display min and max port value for show port tool
function get_toolport_ports(){
	global $default_minport;
	global $default_maxport;
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
314 315 316 317
	
	echo "<label>Port min - Port max</label>";
	echo "<div class='row'><div class='col-md-4'><input id='min_port' class='form-control' type=text name='min_port' value=$default_minport size=8></div>";
	echo "<div class='col-md-4'><input id='max_port' class='form-control' type=text name='max_port' value=$default_maxport size=8></div></div>";
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
}

// Display User list
function get_user_listbox(){
	echo "<h2>Select user : </h2>";
        global $database_eonweb;

        $result=sqlrequest($database_eonweb,"SELECT DISTINCT user_name,user_id,group_id,user_descr FROM users ORDER BY user_name");
        print "<SELECT name='users_list' class='select' size=15>";
        while ($line = mysqli_fetch_array($result))
        {
                print "<OPTION value='$line[1]'>$line[0] : $line[3]</OPTION>";
        }
        print "</SELECT>";
}

// Retrive form data
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
335
function retrieve_form_data($field_name,$default_value){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
336 337 338 339 340 341 342 343 344
	if (!isset ($_GET[$field_name]))
		if (!isset ($_POST[$field_name]))
			return $default_value;
		else
			return $_POST[$field_name];	
	else 
		return $_GET[$field_name];
}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
345 346
// Delete accents
function stripAccents($str, $charset='utf-8'){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
347 348 349 350 351 352 353 354 355 356
    $str = htmlentities($str, ENT_NOQUOTES, $charset);

    $str = preg_replace('#\&([A-za-z])(?:acute|cedil|circ|grave|ring|tilde|uml)\;#', '\1', $str);
    $str = preg_replace('#\&([A-za-z]{2})(?:lig)\;#', '\1', $str); 
    $str = preg_replace('#\&[^;]+\;#', '', $str); 

    return $str;
}

// Add Logs
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
357
function logging($module,$command,$user=false){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
358 359 360 361
	global $database_eonweb;
	global $dateformat;
	if($user)
		sqlrequest($database_eonweb,"insert into logs values ('','".time()."','$user','$module','$command','".$_SERVER["REMOTE_ADDR"]."');");
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
362
	elseif(isset($_COOKIE['user_name']))
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
363 364 365 366
		sqlrequest($database_eonweb,"insert into logs values ('','".time()."','".$_COOKIE['user_name']."','$module','$command','".$_SERVER["REMOTE_ADDR"]."');");
}

// Time
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
367
function getmtime(){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
368 369 370 371 372 373 374
  
    $temps = microtime();
    $temps = explode(' ', $temps);
    return $temps[1] + $temps[0];
 
}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
375 376
// Get the informations of nagios' config's file.
function getBpProcess(){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
	
	global $path_nagiosbpcfg ;
	global $path_nagiosbpcfg_lock ;

	wait($path_nagiosbpcfg_lock);	//Wait for the file to not be in use.
	$fp=@fopen($path_nagiosbpcfg_lock,"w");	//Lock the file
    fputs($fp,getmypid());
    fclose($fp);

    $tabProcess = array() ;
	$lines = file($path_nagiosbpcfg);
	if (!$lines) {
		unlink($path_nagiosbpcfg_lock);	//Unlock the file
		message(2,$path_nagiosbpcfg,"critical");
	}
	foreach( $lines as $line) {
		
		if ( trim($line) == "# Fin def") {	//End of definition
			$tabProcess[] = $tabProp ;
			$tabProp = null ;
		}
		elseif ( preg_match("/^# (ET|OU|MIN)$/", $line, $match)) {
			$tabProp['type'] = $match[1];	//Get the type of the process
		}
		elseif ( preg_match("/^display (\d)*/", $line, $match)) {	//Get the prirority
			$tabProp['prio'] = $match[1] ;
			$tab = explode(";",$line);
			$tabProp['pnom'] = $tab[2];
		}
		elseif ( strpos($line,"info_url") !== false) {	//Get the link
			$tab = explode(";", $line);
			$tabProp['url'] = $tab[count($tab)-1] ;
		}
		elseif ( strpos($line,"external_info") !== false) {	//Get the command
			$tab = explode(";", $line);
			$tabProp['cmd'] = $tab[count($tab)-1] ;
		}
		elseif ( strpos($line,"=") !== false) {	//Get the name, the minimun, and the services
			$tab = explode("=", $line);
			$tabProp['nom'] = trim($tab[0]);
			if ($tabProp['type'] == "MIN") {
				$tabProp['min'] = (int)trim($tab[1]);
				$tab = explode(":",$tab[1]);
				$tabProp['serv'] = $tab[1];
			}
			else $tabProp['serv'] = $tab[1];
		}
	}

	unlink($path_nagiosbpcfg_lock);	//Unlock the file
	return $tabProcess ;
}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
430
// Wait the end of modification of a file
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
431 432 433 434 435 436 437 438 439 440
function wait($file){
	$retry = 0 ;

	while (file_exists($file)){
		if($retry>20) { die ("$file is already in use!"); }
        $retry++;
        sleep(1);
	}
}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
441
// Insert a value in an array
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
function array_push_after($src,$in,$pos){
    if(is_int($pos)) $R=array_merge(array_slice($src,0,$pos+1), $in, array_slice($src,$pos+1));
    else{
        foreach($src as $k=>$v){
            $R[$k]=$v;
            if($k==$pos)$R=array_merge($R,$in);
        }
    }return $R;
}

//Format the nagios.conf file
function formatFile(){
	global $path_nagiosbpcfg;
	global $path_nagiosbpcfg_lock;
	global $database_nagios;

	wait($path_nagiosbpcfg_lock);	//Wait for the file to not be in use.
	$fp=@fopen($path_nagiosbpcfg_lock,"w");	//Lock the file.
	fputs($fp,getmypid());
	fclose($fp);

	$lines = file($path_nagiosbpcfg);
	$file[0] = "# Checked\n";
	if ( empty($lines) || trim($lines[0]) != "# Checked"){	//Not checked. Let's read it !

		write_file($path_nagiosbpcfg,array_merge($file,$lines),"w"," : File updated");

		sqlrequest($database_nagios,"DELETE FROM bp");
		sqlrequest($database_nagios,"DELETE FROM bp_services");
		sqlrequest($database_nagios,"DELETE FROM bp_links");
		$tabName = array();
		$tabDef = array();			

		foreach($lines as $i => $line){
			if ($line[0] == "#"){
				unset($lines[$i]); continue;	//A commented line. Delete.
			}
			if (($posComment = strpos($line,"#")) !== false){	//Found a commentary. Delete.
				$line = substr($line,0,$posComment);	
			}
			//No more commentary in the file

			if (strpos($line,"=") !== false){	//Found a name
				$tab = explode("=",$line);
				$tabName[] = trim($tab[0]);	//Keep the name
				$vals = explode("=",$line);
				$tabDef[] = $vals[1];	//Keep the whole line
				unset($lines[$i]);
			}
		}

		//There we got all the names.
		$serv = null;
		foreach($tabName as $i => $name){
			$type = $prio = $url = $cmd = $val = $desc = "" ;
			//Try to get the type. Default ET
			if ( strpos($tabDef[$i], ":")){
				$vals = explode("of:",$tabDef[$i]);
				$val = trim($vals[0]);
				$type = "MIN";
				$serv = $vals[1];
			}
			else {
				if ( strpos($tabDef[$i], "&")) $type = "ET";
				elseif ( strpos($tabDef[$i], "|")) $type = "OU";
				else $type = "ET";
				$serv = $tabDef[$i];
			}
			
			foreach($lines as $j=>$line){
				if (strpos($line,"$name;") !== false){	//We found a name
					if ( preg_match("/^display (\d)+/", $line,$match)){
						$prio = $match[1];
						$vals = explode(";",$line);
						$desc = trim($vals[2]);
					} 
					elseif ( strpos($line,"info_url") !== false) {
						$vals = explode(";",$line);
						$url = trim($vals[1]);
					}
					elseif ( strpos($line,"external_info") !== false) {
						$vals = explode(";",$line);
						$cmd= trim($vals[1]);
					}
					unset($lines[$j]);
				}
			}

			if ($prio == "" ) $prio = "null";
			sqlrequest($database_nagios,"INSERT INTO bp VALUES('$name','$desc','$prio','$type','$cmd','$url','$val','1')");

			switch ($type){
				case "ET": $vals = explode("&",$serv);
					break;
				case "OU": $vals = explode("|",$serv);
					break;
				case "MIN": $vals = explode("+",$serv);
					break;
			}
			foreach ($vals as $v) {
				if ( strpos($v,";") !== false ){
					$val = explode(";",$v); $host=trim($val[0]); $service=trim($val[1]);
					sqlrequest($database_nagios,"INSERT INTO bp_services VALUES('','$name','$host','$service')");
				}
				else sqlrequest($database_nagios,"INSERT INTO bp_links VALUES('','$name','".trim($v)."')");
			}
		}
		message(6," : Database updated with configuration file","ok");
	}
	unlink($path_nagiosbpcfg_lock);
}

//Write in a file, with error or succes message
function write_file($file,$contenu,$mode,$message = null){
	if(is_writable($file)){
		$error = 0 ;
		if (!$fconf = fopen($file, $mode)) message(2,$file,"critical");
		
		if ( is_array($contenu)){
			foreach ($contenu as $line) {
				if (fwrite ($fconf, $line) === FALSE) $error = 1 ;
			}
		}
		else if (fwrite ($fconf, $contenu) === FALSE) $error = 1 ;

		if ($error) message(3,$file,"critical");
		else if ( $message != null )message(6,$message,"ok");
		fclose ($fconf);
	}
	else 
		message(3,$file,"critical");
}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
575 576
// MySQL request in php array 
function sqlArrayNagios($request){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
577 578 579 580 581 582 583
	global $database_nagios;
	$result = sqlrequest($database_nagios,$request);
	$values = array();
	for ($i=0; $i<mysqli_num_rows($result); ++$i) $values[] = mysqli_fetch_assoc($result);
	return $values ;
}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
584
// NagiosBP file backup
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
function backup_file($start){
	global $path_nagiosbpcfg;
	global $path_nagiosbpcfg_bu;

	for ($i = $start; $i > 0; $i--){
		if ( file_exists($path_nagiosbpcfg_bu.$i)){
			if ( $i == $start) unlink($path_nagiosbpcfg_bu.$i);
			else {
				rename($path_nagiosbpcfg_bu.$i,$path_nagiosbpcfg_bu.($i+1));
			}
		}
	}
	copy($path_nagiosbpcfg,$path_nagiosbpcfg_bu.'1');
}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
600
// NagiosBP file creation
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
function buildFile(){

	global $path_nagiosbpcfg_lock;
	wait($path_nagiosbpcfg_lock);	//Wait for the file to not be in use.
	$fp=@fopen($path_nagiosbpcfg_lock,"w");	//Lock the file.
	fputs($fp,getmypid());
	fclose($fp);

	global $max_bu_file;
	backup_file($max_bu_file);
	global $path_nagiosbpcfg;
	$request = "SELECT * FROM bp WHERE `name` NOT IN (SELECT bp_name FROM bp_links) AND `is_define`='1'";
	$values = sqlArrayNagios($request);
	$prevRequest = str_replace("*","name",$request); 

	$file[] = "# Checked";
	foreach( $values as $metier){
		$writenBP[] = $metier['name'];
	  	switch( $metier['type']) {
	   		case "ET" : $sep = "&";break;
	   		case "OU" : $sep = "|";break;
	   		case "MIN" : $sep = "+";break;
	   	}
	   	$result = sqlArrayNagios("SELECT host,service FROM bp_services WHERE bp_name='$metier[name]'");
	   	$strServ = $string = null;
	   	foreach($result as $serv){
	   		if ( is_null($strServ) ) {
	   			$string = "\n#\n# Name : $metier[name]\n# Type : $metier[type]\n$metier[name] = ";
	   			if ( $metier['type'] == "MIN") $string .= "$metier[min_value] of: ";
	   			$strServ = "$serv[host];$serv[service]";
	   		}
	   		else $strServ .= " $sep $serv[host];$serv[service]";
	   	}
	   	$string .= $strServ."\n";
	   	if ( $metier['priority'] != "null") $string .= "display $metier[priority];$metier[name];$metier[description]\n";
	   	if ( $metier['command'] != "") $string .= "external_info $metier[name];$metier[command]\n";
	   	if ( $metier['url'] != "") $string .= "info_url $metier[name];$metier[url]\n";
	   	$file[] = $string;
    }

	if ( $values ) build($prevRequest,$file,$writenBP);
    write_file($path_nagiosbpcfg,$file,"w"," : File updated");
    unlink($path_nagiosbpcfg_lock);
}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
646
// Nagiosbp build
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
function build($pRequest,&$file,$pWritenBP){

	$values = sqlArrayNagios($pRequest);
	unset($r);
	foreach( $values as $v){
		if ( !isset($r) ) $r = "SELECT bp_name FROM bp_links WHERE (bp_link='$v[name]' ";
		else $r .= " OR bp_link='$v[name]'";
	}
	$values = sqlArrayNagios($r.")");

	if ($values){
		unset($r);
		foreach ($values as $v) {
			if ( !isset($r) ) $r = "SELECT * FROM bp WHERE (name='$v[bp_name]' ";
			else $r .= " OR name='$v[bp_name]'";
		}
		$values = sqlArrayNagios($r.") AND `is_define`='1'");
		/*$request = "SELECT * FROM bp WHERE `name` IN (SELECT bp_name FROM bp_links WHERE bp_link IN ($pRequest)) AND `is_define`='1'";
		$values = sqlArrayNagios($request);
		sql takes to much time with this type of request. We split it in multiple request instead.*/
		$prevRequest = str_replace("*","name",$r.") AND `is_define`='1'");
		$writenBP = $pWritenBP;


		foreach ($pWritenBP as $r) {
			if ( !isset($reqC)) $reqC = "SELECT COUNT(bp_name) AS nbr FROM bp_links WHERE (bp_link='$r' ";
			else $reqC .= " OR bp_link='$r'";
		}

		foreach( $values as $metier){
			if (in_array($metier, $pWritenBP)) continue;
			
			$requestC = $reqC.") AND bp_name='$metier[name]'";
			$count = sqlArrayNagios($requestC);
			$cnt = sqlArrayNagios("SELECT COUNT(bp_name) AS nbr FROM bp_links WHERE bp_name='$metier[name]'");
			
			if ( $count[0]['nbr'] == $cnt[0]['nbr']){
				$writenBP[] = $metier['name'];
			  	switch( $metier['type']) {
			   		case "ET" : $sep = "&";break;
			   		case "OU" : $sep = "|";break;
			   		case "MIN" : $sep = "+";break;
			   	}
			   	$result = sqlArrayNagios("SELECT host,service FROM bp_services WHERE bp_name='$metier[name]'");
			   	$strServ = $string = null;

			   	foreach($result as $serv){
			   		if ( is_null($strServ) ) {
			   			$string = "\n#\n# Name : $metier[name]\n# Type : $metier[type]\n$metier[name] = ";
			   			if ( $metier['type'] == "MIN") $string .= "$metier[min_value] of: ";
			   			$strServ = "$serv[host];$serv[service]";
			   		}
			   		else $strServ .= " $sep $serv[host];$serv[service]";
			   	}
			   	$result = sqlArrayNagios("SELECT bp_link FROM bp_links WHERE bp_name='$metier[name]'");
			   	foreach($result as $serv){
			   		if ( is_null($strServ) ) {
			   			$string = "\n#\n# Name : $metier[name]\n# Type : $metier[type]\n$metier[name] = ";
			   			if ( $metier['type'] == "MIN") $string .= "$metier[min_value] of: ";
			   			$strServ = "$serv[bp_link]";
			   		}
			   		else $strServ .= " $sep $serv[bp_link]";
			   	}
			   	$string .= $strServ."\n";
			   	if ( $metier['priority'] != "null") $string .= "display $metier[priority];$metier[name];$metier[description]\n";
			   	if ( $metier['command'] != "") $string .= "external_info $metier[name];$metier[command]\n";
			   	if ( $metier['url'] != "") $string .= "info_url $metier[name];$metier[url]\n";
			   	$file[] = $string;
			}
	    }

	    build($prevRequest,$file,$writenBP);
	}
}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
722
// Ldap escape special caracters
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
723
function ldap_escape($str, $login=false, $escape=false){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
724 725

	$str = trim($str);
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
726 727 728 729 730 731
	if ( $login ) {
		$search = array("\\\\",'"','+','>','<');
		$replace = array("\\",'\"','\\2B','\>','\<');
	} else {
		$search = array("\\","'",'"');
		$replace = array("\\\\","\'",'\"');
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
732
	}
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
733 734 735 736
	
	$str = str_replace($search, $replace, $str);
	if ( $escape ) { $str = str_replace("\\", "\\\\", $str); }
	
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
737 738 739 740
	return $str;

}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
741
// User creation
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
742
function insert_user($user_name, $user_descr, $user_group, $user_password1, $user_password2, $user_type, $user_location, $user_mail, $user_limitation, $message, $in_nagvis = false, $in_cacti = false, $nagvis_group = false, $user_language = false){
743 744 745 746 747
	global $database_host;
	global $database_cacti;
	global $database_username;
	global $database_password;

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
748 749 750 751 752 753 754 755 756 757 758
	global $database_eonweb;
	global $database_lilac;
	$user_id=null;

	// Check if user exist
	$user_exist=mysqli_result(sqlrequest("$database_eonweb","SELECT count('user_name') from users where user_name='$user_name';"),0);

	// Check user descr
	if($user_descr=="")
		$user_descr=$user_name;

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
759 760 761 762 763 764 765 766 767 768 769 770 771
	if($user_location != "" && $user_location != null){
		if( strpos($user_location, " -- ") !== false && strpos($user_location, "|") !== false ){
			$user_location_parts = explode(" -- ", $user_location);
			$user_loc = explode("|", $user_location_parts[1]);
			$user_dn_name = $user_loc[0];
			$user_name = $user_dn_name;
			$user_location = $user_loc[1];
		}
		else{
			$user_location = $user_location;
		}
	}
	
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
772 773 774 775 776
	if (($user_name != "") && ($user_name != null) && ($user_exist == 0)) {
		if (($user_password1 != "") && ($user_password1 != null) && ($user_password1 == $user_password2)) {
			$user_password = md5($user_password1);
			
			// Insert into eonweb
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
777
			sqlrequest("$database_eonweb","INSERT INTO users (user_name,user_descr,group_id,user_passwd,user_type,user_location,user_limitation,user_language) VALUES('$user_name', '$user_descr', '$user_group', '$user_password', '$user_type', '$user_location', '$user_limitation', '$user_language')");
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
778 779 780 781 782 783 784 785 786 787 788 789 790
			$user_id=mysqli_result(sqlrequest("$database_eonweb","SELECT user_id FROM users WHERE user_name='$user_name'"),0,"user_id");
			$group_name=mysqli_result(sqlrequest("$database_eonweb","SELECT group_name FROM groups WHERE group_id='$user_group'"),0,"group_name");

			// Insert into lilac
			$lilac_period=mysqli_result(sqlrequest("$database_lilac","SELECT id FROM nagios_timeperiod limit 1"),0,"id");
			sqlrequest("$database_lilac","INSERT INTO nagios_contact (id,name,alias,email,host_notifications_enabled,service_notifications_enabled,host_notification_period,service_notification_period,host_notification_on_down,host_notification_on_unreachable,host_notification_on_recovery,host_notification_on_flapping,service_notification_on_warning,service_notification_on_unknown,service_notification_on_critical,service_notification_on_recovery,service_notification_on_flapping,can_submit_commands,retain_status_information,retain_nonstatus_information,host_notification_on_scheduled_downtime) VALUES('','$user_name','$user_descr','$user_mail', 1, 1, '$lilac_period', '$lilac_period', 1, 1, 1, 1, 1, 1, 1, 1, 1 ,1 ,1, 1, 1);");

			// Lilac contact_group_member
			$lilac_contactgroupid=mysqli_result(sqlrequest("$database_lilac","SELECT id FROM nagios_contact_group WHERE name='$group_name'"),0,"id");
			$lilac_contactid=mysqli_result(sqlrequest("$database_lilac","SELECT id FROM nagios_contact where name='$user_name'"),0,"id");
			if($lilac_contactgroupid!="" and $lilac_contactid!="" and $user_limitation!="1")
				sqlrequest("$database_lilac","INSERT INTO nagios_contact_group_member (contactgroup, contact) VALUES ('$lilac_contactgroupid', '$lilac_contactid')");

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
			// Insert into nagvis
			if($in_nagvis == "yes"){
				$bdd = new PDO('sqlite:/srv/eyesofnetwork/nagvis/etc/auth.db');

				$req = $bdd->query("SELECT count(*) FROM users WHERE name = '$user_name'");
				$nagvis_user_exist = $req->fetch();

				if ($nagvis_user_exist["count(*)"] == 0){
					// this is nagvis default salt for password encryption security
					$nagvis_salt = '29d58ead6a65f5c00342ae03cdc6d26565e20954';
					
					// insert user in nagvis SQLite DB
					$sql = "INSERT INTO users (name, password) VALUES ('$user_name', '".sha1($nagvis_salt.$user_password1)."')";
					$bdd->exec($sql);

					// insert user's right as "Guest" by default
					$sql = "SELECT userId FROM users WHERE name = '$user_name'";
					$req = $bdd->query($sql);
					$result = $req->fetch();
					$nagvis_id = $result['userId'];

					$sql = "INSERT INTO users2roles (userId, roleId) VALUES ($nagvis_id, $nagvis_group)";
					$bdd->exec($sql);
				}
			}

			// Insert into cacti
			if($in_cacti == "yes"){
				$bdd = new PDO('mysql:host='.$database_host.';dbname='.$database_cacti, $database_username, $database_password);
				$req = $bdd->query("SELECT count(*) FROM user_auth WHERE username='$user_name'");
				$cacti_user_exist = $req->fetch();
				if ($cacti_user_exist["count(*)"] == 0){
					$bdd->exec("INSERT INTO user_auth (username,password,realm,full_name,show_tree,show_list,show_preview,graph_settings,login_opts,policy_graphs,policy_trees,policy_hosts,policy_graph_templates,enabled) VALUES ('$user_name','',2,'$user_descr','on','on','on','on',3,2,2,2,2,'on')");
				}
			}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
			// Messages
			logging("admin_user","INSERT : $user_name $user_descr $user_limitation $user_group $user_type $user_location");
			if($message){ message(8," : User Inserted",'ok'); }

			// Lilac contact_commands
			$lilac_contact_hcommand=mysqli_result(sqlrequest("$database_lilac","select id from nagios_command where name like 'notify-by-email-host'"),0,"id");
			$lilac_contact_scommand=mysqli_result(sqlrequest("$database_lilac","select id from nagios_command where name like 'notify-by-email-service'"),0,"id");
			if($lilac_contactid!="" and $lilac_contact_hcommand!="")
				sqlrequest("$database_lilac","INSERT INTO nagios_contact_notification_command (contact_id,command,type) values ('$lilac_contactid','$lilac_contact_hcommand','host')");
			elseif($lilac_contact_hcommand=="")
				message(8," : Verify contact 'notify-by-email-host' command in nagios configurator",'warning');
			if($lilac_contactid!="" and $lilac_contact_scommand!="")
				sqlrequest("$database_lilac","INSERT INTO nagios_contact_notification_command (contact_id,command,type) values ('$lilac_contactid','$lilac_contact_scommand','service')");
			elseif($lilac_contact_scommand=="")
				message(8," : Verify contact 'notify-by-email-service' command in nagios configurator",'warning');
		}
		else
			message(8," : Passwords do not match or are empty",'warning');
	}
	elseif($user_exist != 0 )
		message(8," : User $user_name already exists",'warning');
	else
		message(8," : User name can not be empty",'warning');
	return $user_id;
}

// "mysqli" version of mysql_result
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
854
function mysqli_result($res, $row, $field=0){
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
855 856 857 858 859 860 861 862 863 864
    $res->data_seek($row);
	if(gettype($field) == "string"){
		$datarow = $res->fetch_assoc();
	}
    else{
		$datarow = $res->fetch_array();
	}
    return $datarow[$field];
}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
865 866 867 868 869 870 871 872 873 874 875
// get traduction words
function getLabel($reference){

        global $dictionnary;
        global $path_messages;
        global $path_messages_custom;
        global $t;

        // Load dictionnary if not isset
        if(!isset($t)) {
                $t = new Translator();
876 877
                $t->initFile($path_messages,$path_messages_custom);
                $dictionnary = $t->createPHPDictionnary();
Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
878 879 880 881 882 883 884 885 886 887 888 889 890 891
        }

        // Display dictionnary reference if isset or reference
        if(isset($dictionnary[$reference])) {
                $label = $dictionnary[$reference];
        }
        else {
                $label = $reference;
        }

        return $label;

}

892 893 894 895 896
// get default page
function getDefaultPage($usrlimit=0){

	global $t;
	global $defaultpage;
897
	global $path_frame;
898 899 900 901 902 903 904 905 906 907 908 909 910
	global $path_menu_limited;
	global $path_menu_limited_custom;
	global $path_menus;
	global $path_menus_custom;

	// load dictionnary if not isset
	if(!isset($t)) {
		$t = new Translator();
	}
	
	// get json file
	if(isset($_COOKIE["user_limitation"])) { $usrlimit = $_COOKIE["user_limitation"]; }
	if($usrlimit == 1){
911
		$file=$t->getFile($path_menu_limited, $path_menu_limited_custom);
912 913 914 915 916
		$json_content = file_get_contents($file);
		$links = json_decode($json_content, true);
		foreach ($links["link"] as $link) {
			if(isset($link["default"])) {
				if( $link["default"] != null ){
917
					if($link["target"]=="frame") { $link["url"]=$path_frame.urlencode($link['url']); }
918 919 920 921 922 923 924 925 926 927
					$defaultpage = $link["url"];
				}
			}
		}
	} 
	
	return $defaultpage;

}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
// get frame url
function getFrameURL($url){
	global $path_frame;
	
	$frame_url = $path_frame.urlencode($url);
	return $frame_url;
}

function pieChart($queue, $field, $search, $period)
{
	// all external variables we need
	global $database_ged;
	global $array_ged_states;
	if($queue == "active"){ global $ged_active_intervals; extract($ged_active_intervals); }
	else{ global $ged_history_intervals; extract($ged_history_intervals); }
	
	$array_result = array();
	$sql = "SELECT pkt_type_name FROM pkt_type WHERE pkt_type_id!='0' AND pkt_type_id<'100'";
	$pkt_result = sqlrequest($database_ged, $sql);
	
	// set the search clause (according to field and value)
	$search_clause = "";
	if( isset($search) && $search != "" )
	{
		switch ($field) {
			case 'host': $field = 'equipment'; break;
			case 'hostgroup': $field = 'hostgroups'; break;
			case 'service_group': $field = 'servicegroups'; break;
		}
		$like = "'";
		if( substr($search, 0, 1) === '*' ){
			$like .= "%";
		}
		$like .= trim($search, '*');
		if ( substr($search, -1) === '*' ) {
			$like .= "%";
		}
		$like .= "'";
		$search_clause = " AND $field LIKE $like";
	}
	
	// set the period clause (according to checkboxes checked)
	$period_clause = "";
	if( isset($period) && $period != "" )
	{
		switch($period)
		{
			case "day": $period_clause = " AND o_sec >= $day"; break;
			case "week": $period_clause = " AND o_sec >= $week AND o_sec < $day"; break;
			case "month": $period_clause = " AND o_sec >= $month AND o_sec < $week"; break;
			case "year": $period_clause = " AND o_sec >= $year AND o_sec < $month"; break;
		}
	}
	
	while( $pkt = mysqli_fetch_row($pkt_result) )
	{
		foreach($array_ged_states as $key => $state)
		{
			if($key == "ok")
			{
				continue;
			}
			
			if( !isset($array_result["$key"]) ){
				$array_result["$key"] = 0;
			}
			$sql = "SELECT count(id) FROM ".$pkt[0]."_queue_".$queue." WHERE state='".$state."' AND queue='".substr($queue{0},0,1)."'";
			$sql .= $search_clause;
			$sql .= $period_clause;
			
			$result = sqlrequest($database_ged, $sql);
			$result = mysqli_fetch_row($result);
			$array_result["$key"] += $result[0];
		}
	}
	return json_encode($array_result);
}

function barChart($queue, $field, $search)
{
	global $database_ged;
	global $array_ged_states;
	if($queue == "active"){ global $ged_active_intervals; extract($ged_active_intervals); }
	else{ global $ged_history_intervals; extract($ged_history_intervals); }
	
	
	$sql = "SELECT pkt_type_name FROM pkt_type WHERE pkt_type_id!='0' AND pkt_type_id<'100'";
	$pkt_result = sqlrequest($database_ged, $sql);
	
	$array_result = array();
	$array_now_day = array();
	$array_day_week = array();
	$array_week_month = array();
	$array_month_year = array();
	$array_year_more = array();
	
	// set the search clause (according to field and value)
	$search_clause = "";
	if( isset($search) && $search != "" )
	{
		switch ($field) {
			case 'host': $field = 'equipment'; break;
			case 'hostgroup': $field = 'hostgroups'; break;
			case 'service_group': $field = 'servicegroups'; break;
		}
		$like = "'";
		if( substr($search, 0, 1) === '*' ){
			$like .= "%";
		}
		$like .= trim($search, '*');
		if ( substr($search, -1) === '*' ) {
			$like .= "%";
		}
		$like .= "'";
		$search_clause = " AND $field LIKE $like";
	}
	
	while( $pkt = mysqli_fetch_row($pkt_result) )
	{
		foreach($array_ged_states as $key => $state)
		{
			if($key == "ok")
			{
				continue;
			}
			
			if( !isset($array_now_day["$key"]) ){$array_now_day["$key"] = 0;}
			if( !isset($array_day_week["$key"]) ){$array_day_week["$key"] = 0;}
			if( !isset($array_week_month["$key"]) ){$array_week_month["$key"] = 0;}
			if( !isset($array_month_year["$key"]) ){$array_month_year["$key"] = 0;}
			if( !isset($array_year_more["$key"]) ){$array_year_more["$key"] = 0;}
			$sql = "
				SELECT count(id) FROM ".$pkt[0]."_queue_".$queue." WHERE state='".$state."' AND queue='".substr($queue{0},0,1)."' AND o_sec >= $day".$search_clause.
				" UNION ALL
				SELECT count(id) FROM ".$pkt[0]."_queue_".$queue." WHERE state='".$state."' AND queue='".substr($queue{0},0,1)."' AND o_sec >= $week AND o_sec < $day".$search_clause.
				" UNION ALL
				SELECT count(id) FROM ".$pkt[0]."_queue_".$queue." WHERE state='".$state."' AND queue='".substr($queue{0},0,1)."' AND o_sec >= $month AND o_sec < $week".$search_clause.
				" UNION ALL
				SELECT count(id) FROM ".$pkt[0]."_queue_".$queue." WHERE state='".$state."' AND queue='".substr($queue{0},0,1)."' AND o_sec >= $year AND o_sec < $month".$search_clause.
				" UNION ALL
				SELECT count(id) FROM ".$pkt[0]."_queue_".$queue." WHERE state='".$state."' AND queue='".substr($queue{0},0,1)."' AND o_sec < $year".$search_clause;
			$result = sqlrequest($database_ged, $sql);
			
			$cpt = 0;
			while( $row = mysqli_fetch_row($result) )
			{
				switch($cpt)
				{
					case 0: $array_now_day["$key"] += $row[0]; break;
					case 1: $array_day_week["$key"] += $row[0]; break;
					case 2: $array_week_month["$key"] += $row[0]; break;
					case 3: $array_month_year["$key"] += $row[0]; break;
					case 4: $array_year_more["$key"] += $row[0]; break;
				}
				$cpt++;
			}
		}
	}
	array_push($array_result, $array_now_day);
	array_push($array_result, $array_day_week);
	array_push($array_result, $array_week_month);
	array_push($array_result, $array_month_year);
	array_push($array_result, $array_year_more);
	
	return json_encode($array_result);
}

function slaPieChart($field, $search, $period)
{
	// all external variables we need
	global $database_ged;
	global $ged_sla_intervals;
	global $ged_history_intervals;
	extract($ged_sla_intervals);
	extract($ged_history_intervals);
	
	$array_result = array();
	$sql = "SELECT pkt_type_name FROM pkt_type WHERE pkt_type_id!='0' AND pkt_type_id<'100'";
	$pkt_result = sqlrequest($database_ged, $sql);
	
	// set the search clause (according to field and value)
	$search_clause = "";
	if( isset($search) && $search != "" )
	{
		switch ($field) {
			case 'host': $field = 'equipment'; break;
			case 'hostgroup': $field = 'hostgroups'; break;
			case 'service_group': $field = 'servicegroups'; break;
		}
		$like = "'";
		if( substr($search, 0, 1) === '*' ){
			$like .= "%";
		}
		$like .= trim($search, '*');
		if ( substr($search, -1) === '*' ) {
			$like .= "%";
		}
		$like .= "'";
		$search_clause = " AND $field LIKE $like";
	}
	
	// set the period clause (according to checkboxes checked)
	$period_clause = "";
	if( isset($period) && $period != "" )
	{
		switch($period)
		{
			case "day": $period_clause = " AND o_sec >= $day"; break;
			case "week": $period_clause = " AND o_sec >= $week AND o_sec < $day"; break;
			case "month": $period_clause = " AND o_sec >= $month AND o_sec < $week"; break;
			case "year": $period_clause = " AND o_sec >= $year AND o_sec < $month"; break;
		}
	}
	
	while( $pkt = mysqli_fetch_row($pkt_result) )
	{
		foreach($ged_sla_intervals as $key => $value)
		{
			if( !isset($array_result["$key"]) ){
				$array_result["$key"] = 0;
			}
			
			$sla_clause = "";
			switch($key)
			{
				case "first" : $sla_clause = " AND a_sec-o_sec < $first"; break;
				case "second": $sla_clause = " AND a_sec-o_sec >= $first AND a_sec-o_sec < $second"; break;
				case "third" : $sla_clause = " AND a_sec-o_sec >= $second AND a_sec-o_sec < $third"; break;
				case "fourth": $sla_clause = " AND a_sec-o_sec >= $third"; break;
			}
			$sql = "SELECT count(id) FROM ".$pkt[0]."_queue_history WHERE queue='h' AND state!='0'".$sla_clause;
			$sql .= $search_clause;
			$sql .= $period_clause;
			
			$result = sqlrequest($database_ged, $sql);
			$result = mysqli_fetch_row($result);
			$array_result["$key"] += $result[0];
		}
	}
	return json_encode($array_result);
}

function slaBarChart($field, $search)
{
	// all external variables we need
	global $database_ged;
	global $array_ged_states;
	global $ged_sla_intervals;
	global $ged_history_intervals;
	extract($ged_sla_intervals);
	extract($ged_history_intervals);
	
	$array_result = array();
	$array_now_day = array();
	$array_day_week = array();
	$array_week_month = array();
	$array_month_year = array();
	$array_year_more = array();
	
	$array_result = array();
	$sql = "SELECT pkt_type_name FROM pkt_type WHERE pkt_type_id!='0' AND pkt_type_id<'100'";
	$pkt_result = sqlrequest($database_ged, $sql);
	
	// set the search clause (according to field and value)
	$search_clause = "";
	if( isset($search) && $search != "" )
	{
		switch ($field) {
			case 'host': $field = 'equipment'; break;
			case 'hostgroup': $field = 'hostgroups'; break;
			case 'service_group': $field = 'servicegroups'; break;
		}
		$like = "'";
		if( substr($search, 0, 1) === '*' ){
			$like .= "%";
		}
		$like .= trim($search, '*');
		if ( substr($search, -1) === '*' ) {
			$like .= "%";
		}
		$like .= "'";
		$search_clause = " AND $field LIKE $like";
	}
	
	while( $pkt = mysqli_fetch_row($pkt_result) )
	{
		foreach($ged_sla_intervals as $key => $value)
		{
			if( !isset($array_now_day["$key"]) ){$array_now_day["$key"] = 0;}
			if( !isset($array_day_week["$key"]) ){$array_day_week["$key"] = 0;}
			if( !isset($array_week_month["$key"]) ){$array_week_month["$key"] = 0;}
			if( !isset($array_month_year["$key"]) ){$array_month_year["$key"] = 0;}
			if( !isset($array_year_more["$key"]) ){$array_year_more["$key"] = 0;}
			
			switch($key)
			{
				case "first" : $sla_clause = " AND a_sec-o_sec < $first"; break;
				case "second": $sla_clause = " AND a_sec-o_sec >= $first AND a_sec-o_sec < $second"; break;
				case "third" : $sla_clause = " AND a_sec-o_sec >= $second AND a_sec-o_sec < $third"; break;
				case "fourth": $sla_clause = " AND a_sec-o_sec >= $third"; break;
			}
			$sql = "SELECT count(id) FROM ".$pkt[0]."_queue_history WHERE queue='h' AND state !='0' AND o_sec >= $day".$sla_clause.$search_clause.
				" UNION ALL
				SELECT count(id) FROM ".$pkt[0]."_queue_history WHERE queue='h' AND state !='0' AND o_sec >= $week AND o_sec < $day".$sla_clause.$search_clause.
				" UNION ALL
				SELECT count(id) FROM ".$pkt[0]."_queue_history WHERE queue='h' AND state !='0' AND o_sec >= $month AND o_sec < $week".$sla_clause.$search_clause.
				" UNION ALL
				SELECT count(id) FROM ".$pkt[0]."_queue_history WHERE queue='h' AND state !='0' AND o_sec >= $year AND o_sec < $month".$sla_clause.$search_clause.
				" UNION ALL
				SELECT count(id) FROM ".$pkt[0]."_queue_history WHERE queue='h' AND state !='0' AND o_sec < $year".$sla_clause.$search_clause;
			$result = sqlrequest($database_ged, $sql);
			
			$cpt = 0;
			while( $row = mysqli_fetch_row($result) )
			{
				switch($cpt)
				{
					case 0: $array_now_day["$key"] += $row[0]; break;
					case 1: $array_day_week["$key"] += $row[0]; break;
					case 2: $array_week_month["$key"] += $row[0]; break;
					case 3: $array_month_year["$key"] += $row[0]; break;
					case 4: $array_year_more["$key"] += $row[0]; break;
				}
				$cpt++;
			}
		}
	}
	array_push($array_result, $array_now_day);
	array_push($array_result, $array_day_week);
	array_push($array_result, $array_week_month);
	array_push($array_result, $array_month_year);
	array_push($array_result, $array_year_more);
	
	return json_encode($array_result);
}

1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
# Convert seconds to human readable
function strTime($s) {

	$d = intval($s/86400);
	$s -= $d*86400;
	$h = intval($s/3600);
	$s -= $h*3600;
	$m = intval($s/60);
	$s -= $m*60;

	if($d<10) $d="0".$d;
	if($h<10) $h="0".$h;
	if($m<10) $m="0".$m;
	if($s<10) $s="0".$s;

	if ($d) $str = $d . 'd ';
	else $str = '00d ';
	if ($h) $str .= $h . 'h ';
	else $str .= '00h ';
	if ($m) $str .= $m . 'm ';
	else $str .= '00m ';
	if ($s) $str .= $s . 's';
	else $str .= '00s';

	return $str;

}

1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314
# Get eon config values
function getEonConfig($name,$type=false)
{

	global $database_eonweb;
	global ${$name};
	
	// mysql request	
	$sql = "SELECT value FROM configs WHERE name='".$name."'";
	$value = sqlrequest($database_eonweb, $sql);
	$result = mysqli_fetch_row($value);
	
	// return value if exists
	if(count($result)==0) {
		return ${$name};
	} elseif($type=="array") {
		return explode(",",$result[0]);
	} else {
		return $result[0];
	}
	
}

Bastien Pujos's avatar
Bastien Pujos committed
1315 1316 1317 1318 1319
function checkUpdateDB(){
	global $version;
	global $database_eonweb;
	global $database_username;
	global $database_password;
Bastien Pujos's avatar
Bastien Pujos committed
1320 1321 1322
	global $path_eonweb;
	
	$dir=$path_eonweb."/appliance/updates/";
Bastien Pujos's avatar
Bastien Pujos committed
1323 1324 1325 1326 1327 1328
	
	$version_sql = sqlrequest($database_eonweb,"SELECT count(value) as value FROM configs WHERE name='version'");
	if(mysqli_result($version_sql,0,"value") == 0){
		$version_sql = sqlrequest($database_eonweb,"INSERT INTO configs (name, value) VALUES('version', '".$version."')");
		
		// execution de tous les .sql jusqu'à la version donné dans config
Bastien Pujos's avatar
Bastien Pujos committed
1329 1330
		$SQL_Files = array_slice(scandir($dir), 2);
		usort($SQL_Files, 'version_compare');
Bastien Pujos's avatar
Bastien Pujos committed
1331 1332
		
		foreach($SQL_Files as $file){
Bastien Pujos's avatar
Bastien Pujos committed
1333 1334 1335
			if(rtrim($file,'.sql') <= $version){
				exec("mysql -u $database_username --password=$database_password < $dir$file");
			}
Bastien Pujos's avatar
Bastien Pujos committed
1336 1337 1338 1339 1340 1341
		}
		
	}else{
		$versionBD = mysqli_result(sqlrequest($database_eonweb,"SELECT value FROM configs WHERE name='version'"),0,"value");
		
		// execution des .sql entre version en BD et celle config
Bastien Pujos's avatar
Bastien Pujos committed
1342 1343 1344 1345
		
		$SQL_Files = array_slice(scandir($dir), 2);
		usort($SQL_Files, 'version_compare');
		
Bastien Pujos's avatar
Bastien Pujos committed
1346 1347
		foreach($SQL_Files as $file){
			if((rtrim($file,'.sql') <= $version && rtrim($file,'.sql') > $versionBD)){
Bastien Pujos's avatar
Bastien Pujos committed
1348
				exec("mysql -u $database_username --password=$database_password < $dir$file");
Bastien Pujos's avatar
Bastien Pujos committed
1349 1350 1351 1352 1353 1354
			}
		}
		sqlrequest($database_eonweb,"UPDATE configs SET value='$version' WHERE name='version'");
	}
}

Jean-Philippe Levy's avatar
Jean-Philippe Levy committed
1355
?>