Implement an autoloader (#4140)

* Implement an autoloader

When cleaning up classes for psr2, things got a bit unwieldy, so I implemented a class autoloader.
I created a PSR-0 compliant LibreNMS directory and moved all classes there that made sense.
Implemented LibreNMS\ClassLoader which supports adding manual class mappings

This reduces the file includes needed and only loads classes when needed.

* Add teh autoloader to graph.php

* Add a small bit of docs
Fix incomplete class in includes/discovery/functions.inc.php
This commit is contained in:
Tony Murray 2016-08-21 08:07:14 -05:00 committed by Neil Lathwood
parent c2f7602cc5
commit b8e9b2d917
55 changed files with 891 additions and 503 deletions

128
LibreNMS/ClassLoader.php Normal file
View File

@ -0,0 +1,128 @@
<?php
/**
* ClassLoader.php
*
* PSR-0 and custom class loader for LibreNMS
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2016 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace LibreNMS;
/**
* Class ClassLoader
* @package LibreNMS
*/
class ClassLoader
{
/**
* @var array stores dynamically added class > file mappings
*/
private $classMap;
/**
* ClassLoader constructor.
*/
public function __construct()
{
$this->classMap = array();
}
/**
* Loads classes conforming to the PSR-0 specificaton
*
* @param string $name Class name to load
*/
public static function psrLoad($name)
{
global $config, $vdebug;
$file = str_replace(array('\\', '_'), DIRECTORY_SEPARATOR, $name) . '.php';
$fullFile = $config['install_dir'] ? $config['install_dir'] . '/' . $file : $file;
if($vdebug) {
echo __CLASS__ . " [[ $name > $fullFile ]]\n";
}
if (is_readable($fullFile)) {
include $fullFile;
}
}
/**
* Loads classes defined by mapClass()
*
* @param string $name Class name to load
*/
public function customLoad($name)
{
global $vdebug;
if (array_key_exists($name, $this->classMap)) {
$file = $this->classMap[$name];
if($vdebug) {
echo __CLASS__ . " (( $name > $file ))\n";
}
if (is_readable($file)) {
include $file;
}
}
}
/**
* Add or set a custom class > file mapping
*
* @param string $class The full class name
* @param string $file The path to the file containing the class, full path is preferred
*/
public function mapClass($class, $file)
{
$this->classMap[$class] = $file;
}
/**
* Remove a class from the list of class > file mappings
*
* @param string $class The full class name
*/
public function unMapClass($class)
{
unset($this->classMap[$class]);
}
/**
* Register this autoloader
* Custom mappings will take precedence over PSR-0
*/
public function register()
{
spl_autoload_register(array($this, 'customLoad'));
spl_autoload_register(__NAMESPACE__.'\ClassLoader::psrLoad');
}
/**
* Unregister this autoloader
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'customLoad'));
spl_autoload_unregister(__NAMESPACE__.'\ClassLoader::psrLoad');
}
}

View File

@ -1,342 +1,356 @@
<?php <?php
/* /**
* LibreNMS module to Interface with the Component System * Component.php
* *
* Copyright (c) 2015 Aaron Daniels <aaron@daniels.id.au> * LibreNMS module to Interface with the Component System
* *
* This program is free software: you can redistribute it and/or modify it * This program is free software: you can redistribute it and/or modify
* under the terms of the GNU General Public License as published by the * it under the terms of the GNU General Public License as published by
* Free Software Foundation, either version 3 of the License, or (at your * the Free Software Foundation, either version 3 of the License, or
* option) any later version. Please see LICENSE.txt at the top level of * (at your option) any later version.
* the source code distribution for details. *
*/ * This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
class component { * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
/* * GNU General Public License for more details.
* These fields are used in the component table. They are returned in the array *
* so that they can be modified but they can not be set as user attributes. We * You should have received a copy of the GNU General Public License
* also set their default values. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ *
private $reserved = array( * @package LibreNMS
'type' => '', * @link http://librenms.org
'label' => '', * @copyright 2015 Aaron Daniels <aaron@daniels.id.au>
'status' => 0, * @author Aaron Daniels <aaron@daniels.id.au>
'ignore' => 0, */
'disabled' => 0,
'error' => '', namespace LibreNMS;
);
class Component {
public function getComponentType($TYPE=null) { /*
if (is_null($TYPE)) { * These fields are used in the component table. They are returned in the array
$SQL = "SELECT DISTINCT `type` as `name` FROM `component` ORDER BY `name`"; * so that they can be modified but they can not be set as user attributes. We
$row = dbFetchRow($SQL, array()); * also set their default values.
} */
else { private $reserved = array(
$SQL = "SELECT DISTINCT `type` as `name` FROM `component` WHERE `type` = ? ORDER BY `name`"; 'type' => '',
$row = dbFetchRow($SQL, array($TYPE)); 'label' => '',
} 'status' => 0,
'ignore' => 0,
if (!isset($row)) { 'disabled' => 0,
// We didn't find any component types 'error' => '',
return false; );
}
else { public function getComponentType($TYPE=null) {
// We found some.. if (is_null($TYPE)) {
return $row; $SQL = "SELECT DISTINCT `type` as `name` FROM `component` ORDER BY `name`";
} $row = dbFetchRow($SQL, array());
} }
else {
public function getComponents($device_id=null,$options=array()) { $SQL = "SELECT DISTINCT `type` as `name` FROM `component` WHERE `type` = ? ORDER BY `name`";
// Define our results array, this will be set even if no rows are returned. $row = dbFetchRow($SQL, array($TYPE));
$RESULT = array(); }
$PARAM = array();
if (!isset($row)) {
// Our base SQL Query, with no options. // We didn't find any component types
$SQL = "SELECT `C`.`id`,`C`.`device_id`,`C`.`type`,`C`.`label`,`C`.`status`,`C`.`disabled`,`C`.`ignore`,`C`.`error`,`CP`.`attribute`,`CP`.`value` FROM `component` as `C` LEFT JOIN `component_prefs` as `CP` on `C`.`id`=`CP`.`component` WHERE "; return false;
}
// Device_id is shorthand for filter C.device_id = $device_id. else {
if (!is_null($device_id)) { // We found some..
$options['filter']['device_id'] = array('=', $device_id); return $row;
} }
}
// Type is shorthand for filter type = $type.
if (isset($options['type'])) { public function getComponents($device_id=null,$options=array()) {
$options['filter']['type'] = array('=', $options['type']); // Define our results array, this will be set even if no rows are returned.
} $RESULT = array();
$PARAM = array();
// filter field => array(operator,value)
// Filters results based on the field, operator and value // Our base SQL Query, with no options.
$COUNT = 0; $SQL = "SELECT `C`.`id`,`C`.`device_id`,`C`.`type`,`C`.`label`,`C`.`status`,`C`.`disabled`,`C`.`ignore`,`C`.`error`,`CP`.`attribute`,`CP`.`value` FROM `component` as `C` LEFT JOIN `component_prefs` as `CP` on `C`.`id`=`CP`.`component` WHERE ";
if (isset($options['filter'])) {
$COUNT++; // Device_id is shorthand for filter C.device_id = $device_id.
$validFields = array('device_id','type','id','label','status','disabled','ignore','error'); if (!is_null($device_id)) {
$SQL .= " ( "; $options['filter']['device_id'] = array('=', $device_id);
foreach ($options['filter'] as $field => $array) { }
// Only add valid fields to the query
if (in_array($field,$validFields)) { // Type is shorthand for filter type = $type.
if ($array[0] == 'LIKE') { if (isset($options['type'])) {
$SQL .= "`".$field."` LIKE ? AND "; $options['filter']['type'] = array('=', $options['type']);
$array[1] = "%".$array[1]."%"; }
}
else { // filter field => array(operator,value)
// Equals operator is the default // Filters results based on the field, operator and value
$SQL .= "`".$field."` = ? AND "; $COUNT = 0;
} if (isset($options['filter'])) {
array_push($PARAM,$array[1]); $COUNT++;
} $validFields = array('device_id','type','id','label','status','disabled','ignore','error');
} $SQL .= " ( ";
// Strip the last " AND " before closing the bracket. foreach ($options['filter'] as $field => $array) {
$SQL = substr($SQL,0,-5)." )"; // Only add valid fields to the query
} if (in_array($field,$validFields)) {
if ($array[0] == 'LIKE') {
if ($COUNT == 0) { $SQL .= "`".$field."` LIKE ? AND ";
// Strip the " WHERE " that we didn't use. $array[1] = "%".$array[1]."%";
$SQL = substr($SQL,0,-7); }
} else {
// Equals operator is the default
// sort column direction $SQL .= "`".$field."` = ? AND ";
// Add SQL sorting to the results }
if (isset($options['sort'])) { array_push($PARAM,$array[1]);
$SQL .= " ORDER BY ".$options['sort']; }
} }
// Strip the last " AND " before closing the bracket.
// Get our component records using our built SQL. $SQL = substr($SQL,0,-5)." )";
$COMPONENTS = dbFetchRows($SQL, $PARAM); }
// if we have no components we need to return nothing if ($COUNT == 0) {
if (count($COMPONENTS) == 0) { // Strip the " WHERE " that we didn't use.
return $RESULT; $SQL = substr($SQL,0,-7);
} }
// Add the AVP's to the array. // sort column direction
foreach ($COMPONENTS as $COMPONENT) { // Add SQL sorting to the results
if ($COMPONENT['attribute'] != "") { if (isset($options['sort'])) {
// if this component has attributes, set them in the array. $SQL .= " ORDER BY ".$options['sort'];
$RESULT[$COMPONENT['device_id']][$COMPONENT['id']][$COMPONENT['attribute']] = $COMPONENT['value']; }
}
} // Get our component records using our built SQL.
$COMPONENTS = dbFetchRows($SQL, $PARAM);
// Populate our reserved fields into the Array, these cant be used as user attributes.
foreach ($COMPONENTS as $COMPONENT) { // if we have no components we need to return nothing
foreach ($this->reserved as $k => $v) { if (count($COMPONENTS) == 0) {
$RESULT[$COMPONENT['device_id']][$COMPONENT['id']][$k] = $COMPONENT[$k]; return $RESULT;
} }
// Sort each component array so the attributes are in order. // Add the AVP's to the array.
ksort($RESULT[$RESULT[$COMPONENT['device_id']][$COMPONENT['id']]]); foreach ($COMPONENTS as $COMPONENT) {
ksort($RESULT[$RESULT[$COMPONENT['device_id']]]); if ($COMPONENT['attribute'] != "") {
} // if this component has attributes, set them in the array.
$RESULT[$COMPONENT['device_id']][$COMPONENT['id']][$COMPONENT['attribute']] = $COMPONENT['value'];
// limit array(start,count) }
if (isset($options['limit'])) { }
$TEMP = array();
$COUNT = 0; // Populate our reserved fields into the Array, these cant be used as user attributes.
// k = device_id, v = array of components for that device_id foreach ($COMPONENTS as $COMPONENT) {
foreach ($RESULT as $k => $v) { foreach ($this->reserved as $k => $v) {
// k1 = component id, v1 = component array $RESULT[$COMPONENT['device_id']][$COMPONENT['id']][$k] = $COMPONENT[$k];
foreach ($v as $k1 => $v1) { }
if ( ($COUNT >= $options['limit'][0]) && ($COUNT < $options['limit'][0]+$options['limit'][1])) {
$TEMP[$k][$k1] = $v1; // Sort each component array so the attributes are in order.
} ksort($RESULT[$RESULT[$COMPONENT['device_id']][$COMPONENT['id']]]);
// We are counting components. ksort($RESULT[$RESULT[$COMPONENT['device_id']]]);
$COUNT++; }
}
} // limit array(start,count)
$RESULT = $TEMP; if (isset($options['limit'])) {
} $TEMP = array();
$COUNT = 0;
return $RESULT; // k = device_id, v = array of components for that device_id
} foreach ($RESULT as $k => $v) {
// k1 = component id, v1 = component array
public function getComponentStatus($device=null) { foreach ($v as $k1 => $v1) {
$sql_query = "SELECT status, count(status) as count FROM component WHERE"; if ( ($COUNT >= $options['limit'][0]) && ($COUNT < $options['limit'][0]+$options['limit'][1])) {
$sql_param = array(); $TEMP[$k][$k1] = $v1;
$add = 0; }
// We are counting components.
if (!is_null($device)) { $COUNT++;
// Add a device filter to the SQL query. }
$sql_query .= " `device_id` = ?"; }
$sql_param[] = $device; $RESULT = $TEMP;
$add++; }
}
return $RESULT;
if ($add == 0) { }
// No filters, remove " WHERE" -6
$sql_query = substr($sql_query, 0, strlen($sql_query)-6); public function getComponentStatus($device=null) {
} $sql_query = "SELECT status, count(status) as count FROM component WHERE";
$sql_query .= " GROUP BY status"; $sql_param = array();
d_echo("SQL Query: ".$sql_query); $add = 0;
// $service is not null, get only what we want. if (!is_null($device)) {
$result = dbFetchRows($sql_query, $sql_param); // Add a device filter to the SQL query.
$sql_query .= " `device_id` = ?";
// Set our defaults to 0 $sql_param[] = $device;
$count = array(0 => 0, 1 => 0, 2 => 0); $add++;
// Rebuild the array in a more convenient method }
foreach ($result as $v) {
$count[$v['status']] = $v['count']; if ($add == 0) {
} // No filters, remove " WHERE" -6
$sql_query = substr($sql_query, 0, strlen($sql_query)-6);
d_echo("Component Count by Status: ".print_r($count,TRUE)."\n"); }
return $count; $sql_query .= " GROUP BY status";
} d_echo("SQL Query: ".$sql_query);
public function getComponentStatusLog($component=null,$start=null,$end=null) { // $service is not null, get only what we want.
if ( ($component == null) || ($start == null) || ($end == null) ) { $result = dbFetchRows($sql_query, $sql_param);
// Error...
d_echo("Required arguments are missing. Component: ".$component.", Start: ".$start.", End: ".$end."\n"); // Set our defaults to 0
return false; $count = array(0 => 0, 1 => 0, 2 => 0);
} // Rebuild the array in a more convenient method
foreach ($result as $v) {
// Create our return array. $count[$v['status']] = $v['count'];
$return = array(); }
// 1. find the previous value, this is the value when $start occurred. d_echo("Component Count by Status: ".print_r($count,TRUE)."\n");
$sql_query = "SELECT status FROM component_statuslog WHERE `component` = ? AND time < ? ORDER BY `id` desc LIMIT 1"; return $count;
$sql_param = array($component,$start); }
$result = dbFetchRow($sql_query, $sql_param);
if ($result == false) { public function getComponentStatusLog($component=null,$start=null,$end=null) {
$return['initial'] = false; if ( ($component == null) || ($start == null) || ($end == null) ) {
} // Error...
else { d_echo("Required arguments are missing. Component: ".$component.", Start: ".$start.", End: ".$end."\n");
$return['initial'] = $result['status']; return false;
} }
// 2. Then we just need a list of all the entries for the time period. // Create our return array.
$sql_query = "SELECT status, time, message FROM component_statuslog WHERE `component` = ? AND time >= ? AND time < ? ORDER BY `time`"; $return = array();
$sql_param = array($component,$start,$end);
$return['data'] = dbFetchRows($sql_query, $sql_param); // 1. find the previous value, this is the value when $start occurred.
$sql_query = "SELECT status FROM component_statuslog WHERE `component` = ? AND time < ? ORDER BY `id` desc LIMIT 1";
d_echo("Status Log Data: ".print_r($return,TRUE)."\n"); $sql_param = array($component,$start);
return $return; $result = dbFetchRow($sql_query, $sql_param);
} if ($result == false) {
$return['initial'] = false;
public function createComponent ($device_id,$TYPE) { }
// Prepare our default values to be inserted. else {
$DATA = $this->reserved; $return['initial'] = $result['status'];
}
// Add the device_id and type
$DATA['device_id'] = $device_id; // 2. Then we just need a list of all the entries for the time period.
$DATA['type'] = $TYPE; $sql_query = "SELECT status, time, message FROM component_statuslog WHERE `component` = ? AND time >= ? AND time < ? ORDER BY `time`";
$sql_param = array($component,$start,$end);
// Insert a new component into the database. $return['data'] = dbFetchRows($sql_query, $sql_param);
$id = dbInsert($DATA, 'component');
d_echo("Status Log Data: ".print_r($return,TRUE)."\n");
// Add a default status log entry - we always start ok. return $return;
$this->createStatusLogEntry($id,0,'Component Created'); }
// Create a default component array based on what was inserted. public function createComponent ($device_id,$TYPE) {
$ARRAY = array(); // Prepare our default values to be inserted.
$ARRAY[$id] = $DATA; $DATA = $this->reserved;
unset ($ARRAY[$id]['device_id']); // This doesn't belong here.
return $ARRAY; // Add the device_id and type
} $DATA['device_id'] = $device_id;
$DATA['type'] = $TYPE;
public function createStatusLogEntry($component,$status,$message) {
// Add an entry to the statuslog table for a particular component. // Insert a new component into the database.
$DATA = array( $id = dbInsert($DATA, 'component');
'component' => $component,
'status' => $status, // Add a default status log entry - we always start ok.
'message' => $message, $this->createStatusLogEntry($id,0,'Component Created');
);
// Create a default component array based on what was inserted.
return dbInsert($DATA, 'component_statuslog'); $ARRAY = array();
} $ARRAY[$id] = $DATA;
unset ($ARRAY[$id]['device_id']); // This doesn't belong here.
public function deleteComponent ($id) { return $ARRAY;
// Delete a component from the database. }
return dbDelete('component', "`id` = ?",array($id));
} public function createStatusLogEntry($component,$status,$message) {
// Add an entry to the statuslog table for a particular component.
public function setComponentPrefs ($device_id,$ARRAY) { $DATA = array(
// Compare the arrays. Update/Insert where necessary. 'component' => $component,
'status' => $status,
$OLD = $this->getComponents($device_id); 'message' => $message,
// Loop over each component. );
foreach ($ARRAY as $COMPONENT => $AVP) {
return dbInsert($DATA, 'component_statuslog');
// Make sure the component already exists. }
if (!isset($OLD[$device_id][$COMPONENT])) {
// Error. Component doesn't exist in the database. public function deleteComponent ($id) {
continue; // Delete a component from the database.
} return dbDelete('component', "`id` = ?",array($id));
}
// Ignore type, we cant change that.
unset($AVP['type'],$OLD[$device_id][$COMPONENT]['type']); public function setComponentPrefs ($device_id,$ARRAY) {
// Compare the arrays. Update/Insert where necessary.
// If the Status has changed we need to add a log entry
if ($AVP['status'] != $OLD[$device_id][$COMPONENT]['status']) { $OLD = $this->getComponents($device_id);
d_echo("Status Changed - Old: ".$OLD[$device_id][$COMPONENT]['status'].", New: ".$AVP['status']."\n"); // Loop over each component.
$this->createStatusLogEntry($COMPONENT,$AVP['status'],$AVP['error']); foreach ($ARRAY as $COMPONENT => $AVP) {
}
// Make sure the component already exists.
// Process our reserved components first. if (!isset($OLD[$device_id][$COMPONENT])) {
$UPDATE = array(); // Error. Component doesn't exist in the database.
foreach ($this->reserved as $k => $v) { continue;
// does the reserved field exist, if not skip. }
if (isset($AVP[$k])) {
// Ignore type, we cant change that.
// Has the value changed? unset($AVP['type'],$OLD[$device_id][$COMPONENT]['type']);
if ($AVP[$k] != $OLD[$device_id][$COMPONENT][$k]) {
// The value has been modified, add it to our update array. // If the Status has changed we need to add a log entry
$UPDATE[$k] = $AVP[$k]; if ($AVP['status'] != $OLD[$device_id][$COMPONENT]['status']) {
} d_echo("Status Changed - Old: ".$OLD[$device_id][$COMPONENT]['status'].", New: ".$AVP['status']."\n");
$this->createStatusLogEntry($COMPONENT,$AVP['status'],$AVP['error']);
// Unset the reserved field. We don't want to insert it below. }
unset($AVP[$k],$OLD[$device_id][$COMPONENT][$k]);
} // Process our reserved components first.
} $UPDATE = array();
foreach ($this->reserved as $k => $v) {
// Has anything changed, do we need to update? // does the reserved field exist, if not skip.
if (count($UPDATE) > 0) { if (isset($AVP[$k])) {
// We have data to update
dbUpdate($UPDATE, 'component', '`id` = ?', array($COMPONENT)); // Has the value changed?
if ($AVP[$k] != $OLD[$device_id][$COMPONENT][$k]) {
// Log the update to the Eventlog. // The value has been modified, add it to our update array.
$MSG = "Component ".$COMPONENT." has been modified: "; $UPDATE[$k] = $AVP[$k];
foreach ($UPDATE as $k => $v) { }
$MSG .= $k." => ".$v.",";
} // Unset the reserved field. We don't want to insert it below.
$MSG = substr($MSG,0,-1); unset($AVP[$k],$OLD[$device_id][$COMPONENT][$k]);
log_event($MSG,$device_id,'component',$COMPONENT); }
} }
// Process our AVP Adds and Updates // Has anything changed, do we need to update?
foreach ($AVP as $ATTR => $VALUE) { if (count($UPDATE) > 0) {
// We have our AVP, lets see if we need to do anything with it. // We have data to update
dbUpdate($UPDATE, 'component', '`id` = ?', array($COMPONENT));
if (!isset($OLD[$device_id][$COMPONENT][$ATTR])) {
// We have a newly added attribute, need to insert into the DB // Log the update to the Eventlog.
$DATA = array('component'=>$COMPONENT, 'attribute'=>$ATTR, 'value'=>$VALUE); $MSG = "Component ".$COMPONENT." has been modified: ";
dbInsert($DATA, 'component_prefs'); foreach ($UPDATE as $k => $v) {
$MSG .= $k." => ".$v.",";
// Log the addition to the Eventlog. }
log_event ("Component: " . $AVP[$COMPONENT]['type'] . "(" . $COMPONENT . "). Attribute: " . $ATTR . ", was added with value: " . $VALUE, $device_id, 'component', $COMPONENT); $MSG = substr($MSG,0,-1);
} log_event($MSG,$device_id,'component',$COMPONENT);
elseif ($OLD[$device_id][$COMPONENT][$ATTR] != $VALUE) { }
// Attribute exists but the value is different, need to update
$DATA = array('value'=>$VALUE); // Process our AVP Adds and Updates
dbUpdate($DATA, 'component_prefs', '`component` = ? AND `attribute` = ?', array($COMPONENT, $ATTR)); foreach ($AVP as $ATTR => $VALUE) {
// We have our AVP, lets see if we need to do anything with it.
// Add the modification to the Eventlog.
log_event("Component: ".$AVP[$COMPONENT]['type']."(".$COMPONENT."). Attribute: ".$ATTR.", was modified from: ".$OLD[$COMPONENT][$ATTR].", to: ".$VALUE,$device_id,'component',$COMPONENT); if (!isset($OLD[$device_id][$COMPONENT][$ATTR])) {
} // We have a newly added attribute, need to insert into the DB
$DATA = array('component'=>$COMPONENT, 'attribute'=>$ATTR, 'value'=>$VALUE);
} // End Foreach AVP dbInsert($DATA, 'component_prefs');
// Process our Deletes. // Log the addition to the Eventlog.
$DELETE = array_diff_key($OLD[$device_id][$COMPONENT], $AVP); log_event ("Component: " . $AVP[$COMPONENT]['type'] . "(" . $COMPONENT . "). Attribute: " . $ATTR . ", was added with value: " . $VALUE, $device_id, 'component', $COMPONENT);
foreach ($DELETE as $KEY => $VALUE) { }
// As the Attribute has been removed from the array, we should remove it from the database. elseif ($OLD[$device_id][$COMPONENT][$ATTR] != $VALUE) {
dbDelete('component_prefs', "`component` = ? AND `attribute` = ?",array($COMPONENT,$KEY)); // Attribute exists but the value is different, need to update
$DATA = array('value'=>$VALUE);
// Log the addition to the Eventlog. dbUpdate($DATA, 'component_prefs', '`component` = ? AND `attribute` = ?', array($COMPONENT, $ATTR));
log_event ("Component: " . $AVP[$COMPONENT]['type'] . "(" . $COMPONENT . "). Attribute: " . $KEY . ", was deleted.", $COMPONENT);
} // Add the modification to the Eventlog.
log_event("Component: ".$AVP[$COMPONENT]['type']."(".$COMPONENT."). Attribute: ".$ATTR.", was modified from: ".$OLD[$COMPONENT][$ATTR].", to: ".$VALUE,$device_id,'component',$COMPONENT);
} }
return true; } // End Foreach AVP
}
// Process our Deletes.
} $DELETE = array_diff_key($OLD[$device_id][$COMPONENT], $AVP);
foreach ($DELETE as $KEY => $VALUE) {
// As the Attribute has been removed from the array, we should remove it from the database.
dbDelete('component_prefs', "`component` = ? AND `attribute` = ?",array($COMPONENT,$KEY));
// Log the addition to the Eventlog.
log_event ("Component: " . $AVP[$COMPONENT]['type'] . "(" . $COMPONENT . "). Attribute: " . $KEY . ", was deleted.", $COMPONENT);
}
}
return true;
}
}

View File

@ -0,0 +1,32 @@
<?php
/**
* FileExistsException.php
*
* -Description-
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2016 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace LibreNMS\Exceptions;
class FileExistsException extends \Exception
{
}

View File

@ -0,0 +1,32 @@
<?php
/**
* HostExistsException.php
*
* -Description-
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2016 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace LibreNMS\Exceptions;
class HostExistsException extends \Exception
{
}

View File

@ -0,0 +1,32 @@
<?php
/**
* HostIpExistsException.php
*
* -Description-
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2016 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace LibreNMS\Exceptions;
class HostIpExistsException extends HostExistsException
{
}

View File

@ -1,8 +1,8 @@
<?php <?php
/** /**
* exceptions.inc.php * HostUnreachableException.php
* *
* Custom Exception definitions * -Description-
* *
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
@ -23,17 +23,10 @@
* @author Tony Murray <murraytony@gmail.com> * @author Tony Murray <murraytony@gmail.com>
*/ */
namespace LibreNMS\Exceptions;
// ---- addHost Excpetions ----
class HostExistsException extends Exception {}
class HostIpExistsException extends HostExistsException {} class HostUnreachableException extends \Exception
class InvalidPortAssocModeException extends Exception {}
class SnmpVersionUnsupportedException extends Exception {}
class HostUnreachableException extends Exception
{ {
protected $reasons = array(); protected $reasons = array();
@ -64,7 +57,3 @@ class HostUnreachableException extends Exception
return $this->reasons; return $this->reasons;
} }
} }
class HostUnreachablePingException extends HostUnreachableException {}
class HostUnreachableSnmpException extends HostUnreachableException {}

View File

@ -0,0 +1,32 @@
<?php
/**
* HostUnreachablePingException.php
*
* -Description-
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2016 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace LibreNMS\Exceptions;
class HostUnreachablePingException extends HostUnreachableException
{
}

View File

@ -0,0 +1,32 @@
<?php
/**
* HostUnreachableSnmpException.php
*
* -Description-
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2016 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace LibreNMS\Exceptions;
class HostUnreachableSnmpException extends HostUnreachableException
{
}

View File

@ -0,0 +1,32 @@
<?php
/**
* InvalidPortAssocModeException.php
*
* -Description-
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2016 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace LibreNMS\Exceptions;
class InvalidPortAssocModeException extends \Exception
{
}

View File

@ -0,0 +1,32 @@
<?php
/**
* SnmpVersionUnsupportedException.php
*
* -Description-
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2016 Tony Murray
* @author Tony Murray <murraytony@gmail.com>
*/
namespace LibreNMS\Exceptions;
class SnmpVersionUnsupportedException extends \Exception
{
}

View File

@ -1,7 +1,9 @@
<?php <?php
/**
/* * ObjectCache.php
* Copyright (C) 2015 Daniel Preussker <f0o@devilcode.org> *
* -Description-
*
* This program is free software: you can redistribute it and/or modify * 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 * it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or * the Free Software Foundation, either version 3 of the License, or
@ -14,18 +16,19 @@
* *
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2015 Daniel Preussker <f0o@devilcode.org>
* @copyright 2015 LibreNMS
* @author Daniel Preussker (f0o) <f0o@devilcode.org>
*/ */
/* namespace LibreNMS;
* Object-Cache
* @author f0o <f0o@devilcode.org>
* @copyright 2015 f0o, LibreNMS
* @license GPL
* @package LibreNMS
* @subpackage Cache
*/
class ObjCache implements ArrayAccess { use ArrayAccess;
class ObjectCache implements ArrayAccess {
private $data = array(); private $data = array();
@ -33,9 +36,8 @@ class ObjCache implements ArrayAccess {
/** /**
* Initialize ObjCache * Initialize ObjectCache
* @param string $obj Name of Object * @param string $obj Name of Object
* @return void
*/ */
public function __construct($obj) { public function __construct($obj) {
global $config; global $config;

View File

@ -1,4 +1,27 @@
<?php <?php
/**
* Plugins.php
*
* -Description-
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2016
* @author
*/
namespace LibreNMS; namespace LibreNMS;

View File

@ -0,0 +1,50 @@
<?php
/**
* RRDRecursiveFilterIterator.php
*
* Reursive Filter Iterator to iterate directories and locate .rrd files.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @package LibreNMS
* @link http://librenms.org
* @copyright 2016
* @author
*/
namespace LibreNMS;
/**
* Reursive Filter Iterator to iterate directories and locate .rrd files.
*
* @method boolean isDir()
*
**/
class RRDRecursiveFilterIterator extends \RecursiveFilterIterator {
public function accept() {
$filename = $this->current()->getFilename();
if ($filename[0] === '.') {
// Ignore hidden files and directories
return false;
}
if ($this->isDir()) {
// We want to search into directories
return true;
}
// Matches files with .rrd in the filename.
// We are only searching rrd folder, but there could be other files and we don't want to cause a stink.
return strpos($filename, '.rrd') !== false;
}
}

View File

@ -12,6 +12,8 @@
* @copyright (C) 2006 - 2012 Adam Armstrong * @copyright (C) 2006 - 2012 Adam Armstrong
*/ */
use LibreNMS\Exceptions\HostUnreachableException;
chdir(dirname($argv[0])); chdir(dirname($argv[0]));
require 'includes/defaults.inc.php'; require 'includes/defaults.inc.php';

View File

@ -19,7 +19,6 @@ require 'includes/defaults.inc.php';
require 'config.php'; require 'config.php';
require 'includes/definitions.inc.php'; require 'includes/definitions.inc.php';
require 'includes/functions.php'; require 'includes/functions.php';
require 'html/lib/PasswordHash.php';
if (file_exists('html/includes/authentication/'.$config['auth_mechanism'].'.inc.php')) { if (file_exists('html/includes/authentication/'.$config['auth_mechanism'].'.inc.php')) {
include 'html/includes/authentication/'.$config['auth_mechanism'].'.inc.php'; include 'html/includes/authentication/'.$config['auth_mechanism'].'.inc.php';

View File

@ -3,7 +3,10 @@
This document will try and provide a good overview of how the code is structured within LibreNMS. We will go through the main directories and provide information on how and when they are used. This document will try and provide a good overview of how the code is structured within LibreNMS. We will go through the main directories and provide information on how and when they are used.
### doc/ ### doc/
This is the location of all the documentation for LibreNMS, this is in GitHub markdown format and can be viewed (online)[http://docs.librenms.org/] This is the location of all the documentation for LibreNMS, this is in GitHub markdown format and can be viewed [online](http://docs.librenms.org/)
### LibreNMS/
Any classes should be under this directory, with a directory structure that matches the namespace. One class per file. See [PSR-0](http://www.php-fig.org/psr/psr-0/) for details.
### html/ ### html/
All web accessible files are located here. All web accessible files are located here.

View File

@ -70,24 +70,10 @@ Because of this all fields of the component table are reserved, they cannot be u
# <a name="using">Using Components</a> # <a name="using">Using Components</a>
To use components in you application, first you need to include the code. Create an instance of the component class:
From a Discovery/Poller module:
```php ```php
require_once 'includes/component.php'; $COMPONENT = new LibreNMS\Component();
```
From the html tree:
```php
require_once "../includes/component.php";
```
Once the code is loaded, create an instance of the component class:
```php
$COMPONENT = new component();
``` ```
## <a name="get">Retrieving Components</a> ## <a name="get">Retrieving Components</a>
@ -144,7 +130,7 @@ Options can be supplied to `getComponents` to influence which and how components
You can filter on any of the [reserved](#reserved) fields. Filters are created in the following format: You can filter on any of the [reserved](#reserved) fields. Filters are created in the following format:
```php ```php
$OPTIONS['filter'][FIELD] = array ('OPERATOR', 'CRITERIA'); $options['filter']['FIELD'] = array ('OPERATOR', 'CRITERIA');
``` ```
Where: Where:

View File

@ -33,8 +33,15 @@ if (isset($_GET['debug'])) {
require_once '../includes/defaults.inc.php'; require_once '../includes/defaults.inc.php';
require_once '../config.php'; require_once '../config.php';
require_once '../includes/definitions.inc.php'; require_once '../includes/definitions.inc.php';
// initialize the class loader and add custom mappings
require_once $config['install_dir'] . '/LibreNMS/ClassLoader.php';
$classLoader = new LibreNMS\ClassLoader();
$classLoader->mapClass('Console_Color2', $config['install_dir'] . '/includes/console_colour.php');
$classLoader->mapClass('PasswordHash', $config['install_dir'] . '/html/lib/PasswordHash.php');
$classLoader->register();
require_once '../includes/common.php'; require_once '../includes/common.php';
require_once '../includes/console_colour.php';
require_once '../includes/dbFacile.php'; require_once '../includes/dbFacile.php';
require_once '../includes/rewrites.php'; require_once '../includes/rewrites.php';
require_once 'includes/functions.inc.php'; require_once 'includes/functions.inc.php';

View File

@ -13,7 +13,6 @@
*/ */
require_once '../includes/functions.php'; require_once '../includes/functions.php';
require_once '../includes/component.php';
require_once '../includes/device-groups.inc.php'; require_once '../includes/device-groups.inc.php';
if (file_exists('../html/includes/authentication/'.$config['auth_mechanism'].'.inc.php')) { if (file_exists('../html/includes/authentication/'.$config['auth_mechanism'].'.inc.php')) {
include '../html/includes/authentication/'.$config['auth_mechanism'].'.inc.php'; include '../html/includes/authentication/'.$config['auth_mechanism'].'.inc.php';
@ -513,7 +512,7 @@ function get_components()
// use hostname as device_id if it's all digits // use hostname as device_id if it's all digits
$device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname); $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
$COMPONENT = new component(); $COMPONENT = new LibreNMS\Component();
$components = $COMPONENT->getComponents($device_id, $options); $components = $COMPONENT->getComponents($device_id, $options);
$output = array( $output = array(
@ -541,7 +540,7 @@ function add_components()
// use hostname as device_id if it's all digits // use hostname as device_id if it's all digits
$device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname); $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
$COMPONENT = new component(); $COMPONENT = new LibreNMS\Component();
$component = $COMPONENT->createComponent($device_id, $ctype); $component = $COMPONENT->createComponent($device_id, $ctype);
$output = array( $output = array(
@ -566,7 +565,7 @@ function edit_components()
// use hostname as device_id if it's all digits // use hostname as device_id if it's all digits
$device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname); $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname);
$COMPONENT = new component(); $COMPONENT = new LibreNMS\Component();
if ($COMPONENT->setComponentPrefs($device_id, $data)) { if ($COMPONENT->setComponentPrefs($device_id, $data)) {
// Edit Success. // Edit Success.
@ -599,7 +598,7 @@ function delete_components()
$router = $app->router()->getCurrentRoute()->getParams(); $router = $app->router()->getCurrentRoute()->getParams();
$cid = $router['component']; $cid = $router['component'];
$COMPONENT = new component(); $COMPONENT = new LibreNMS\Component();
if ($COMPONENT->deleteComponent($cid)) { if ($COMPONENT->deleteComponent($cid)) {
// Edit Success. // Edit Success.
$code = 200; $code = 200;

View File

@ -2,7 +2,6 @@
@ini_set('session.use_only_cookies', 1); @ini_set('session.use_only_cookies', 1);
@ini_set('session.cookie_httponly', 1); @ini_set('session.cookie_httponly', 1);
require 'lib/PasswordHash.php';
session_start(); session_start();

View File

@ -1,7 +1,6 @@
<?php <?php
require_once "../includes/component.php"; $OBJCOMP = new LibreNMS\Component();
$OBJCOMP = new component();
$common_output[] = ' $common_output[] = '
<div> <div>

View File

@ -16,8 +16,7 @@ $message = 'Error with config';
// enable/disable components on devices. // enable/disable components on devices.
$device_id = intval($_POST['device']); $device_id = intval($_POST['device']);
require_once "../includes/component.php"; $OBJCOMP = new LibreNMS\Component();
$OBJCOMP = new component();
// Go get the component array. // Go get the component array.
$COMPONENTS = $OBJCOMP->getComponents($device_id); $COMPONENTS = $OBJCOMP->getComponents($device_id);

View File

@ -11,8 +11,7 @@
* the source code distribution for details. * the source code distribution for details.
*/ */
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options['filter']['type'] = array('=','Cisco-OTV'); $options['filter']['type'] = array('=','Cisco-OTV');
$components = $component->getComponents($device['device_id'], $options); $components = $component->getComponents($device['device_id'], $options);

View File

@ -11,8 +11,7 @@
* the source code distribution for details. * the source code distribution for details.
*/ */
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options['filter']['type'] = array('=','Cisco-OTV'); $options['filter']['type'] = array('=','Cisco-OTV');
$components = $component->getComponents($device['device_id'], $options); $components = $component->getComponents($device['device_id'], $options);

View File

@ -11,8 +11,7 @@
* the source code distribution for details. * the source code distribution for details.
*/ */
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options = array(); $options = array();
$options['filter']['type'] = array('=','ntp'); $options['filter']['type'] = array('=','ntp');
$components = $component->getComponents($device['device_id'], $options); $components = $component->getComponents($device['device_id'], $options);

View File

@ -11,8 +11,7 @@
* the source code distribution for details. * the source code distribution for details.
*/ */
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options = array(); $options = array();
$options['filter']['type'] = array('=','ntp'); $options['filter']['type'] = array('=','ntp');
$components = $component->getComponents($device['device_id'], $options); $components = $component->getComponents($device['device_id'], $options);

View File

@ -11,8 +11,7 @@
* the source code distribution for details. * the source code distribution for details.
*/ */
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options = array(); $options = array();
$options['filter']['type'] = array('=','ntp'); $options['filter']['type'] = array('=','ntp');
$components = $component->getComponents($device['device_id'], $options); $components = $component->getComponents($device['device_id'], $options);

View File

@ -11,8 +11,7 @@
* the source code distribution for details. * the source code distribution for details.
*/ */
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options = array(); $options = array();
$options['filter']['type'] = array('=','ntp'); $options['filter']['type'] = array('=','ntp');
$components = $component->getComponents($device['device_id'], $options); $components = $component->getComponents($device['device_id'], $options);

View File

@ -11,8 +11,7 @@
* the source code distribution for details. * the source code distribution for details.
*/ */
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options = array(); $options = array();
$options['filter']['type'] = array('=','Cisco-CBQOS'); $options['filter']['type'] = array('=','Cisco-CBQOS');
$components = $component->getComponents($device['device_id'], $options); $components = $component->getComponents($device['device_id'], $options);

View File

@ -11,8 +11,7 @@
* the source code distribution for details. * the source code distribution for details.
*/ */
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options = array(); $options = array();
$options['filter']['type'] = array('=','Cisco-CBQOS'); $options['filter']['type'] = array('=','Cisco-CBQOS');
$components = $component->getComponents($device['device_id'], $options); $components = $component->getComponents($device['device_id'], $options);

View File

@ -11,8 +11,7 @@
* the source code distribution for details. * the source code distribution for details.
*/ */
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options = array(); $options = array();
$options['filter']['type'] = array('=','Cisco-CBQOS'); $options['filter']['type'] = array('=','Cisco-CBQOS');
$components = $component->getComponents($device['device_id'], $options); $components = $component->getComponents($device['device_id'], $options);

View File

@ -1,10 +1,10 @@
<?php <?php
require_once $config['install_dir'].'/includes/object-cache.inc.php';
// FIXME queries such as the one below should probably go into index.php? // FIXME queries such as the one below should probably go into index.php?
// FIXME: This appears to keep a complete cache of device details in memory for every page load. // FIXME: This appears to keep a complete cache of device details in memory for every page load.
// It would be interesting to know where this is used. It probably should have its own API. // It would be interesting to know where this is used. It probably should have its own API.
use LibreNMS\ObjectCache;
foreach (dbFetchRows('SELECT * FROM `devices` ORDER BY `hostname`') as $device) { foreach (dbFetchRows('SELECT * FROM `devices` ORDER BY `hostname`') as $device) {
$cache['devices']['hostname'][$device['hostname']] = $device['device_id']; $cache['devices']['hostname'][$device['hostname']] = $device['device_id'];
$cache['devices']['id'][$device['device_id']] = $device; $cache['devices']['id'][$device['device_id']] = $device;
@ -12,9 +12,9 @@ foreach (dbFetchRows('SELECT * FROM `devices` ORDER BY `hostname`') as $device)
$cache['device_types'][$device['type']]++; $cache['device_types'][$device['type']]++;
} }
$devices = new ObjCache('devices'); $devices = new ObjectCache('devices');
$ports = new ObjCache('ports'); $ports = new ObjectCache('ports');
$services = new ObjCache('services'); $services = new ObjectCache('services');
if ($devices['down']) { if ($devices['down']) {
$devices['bgcolour'] = '#ffcccc'; $devices['bgcolour'] = '#ffcccc';

View File

@ -1,8 +1,8 @@
<?php <?php
require $config['install_dir'].'/includes/object-cache.inc.php';
// FIXME - this could do with some performance improvements, i think. possible rearranging some tables and setting flags at poller time (nothing changes outside of then anyways) // FIXME - this could do with some performance improvements, i think. possible rearranging some tables and setting flags at poller time (nothing changes outside of then anyways)
use LibreNMS\ObjectCache;
$service_status = get_service_status(); $service_status = get_service_status();
$typeahead_limit = $config['webui']['global_search_result_limit']; $typeahead_limit = $config['webui']['global_search_result_limit'];
$if_alerts = dbFetchCell("SELECT COUNT(port_id) FROM `ports` WHERE `ifOperStatus` = 'down' AND `ifAdminStatus` = 'up' AND `ignore` = '0'"); $if_alerts = dbFetchCell("SELECT COUNT(port_id) FROM `ports` WHERE `ifOperStatus` = 'down' AND `ifAdminStatus` = 'up' AND `ignore` = '0'");
@ -247,7 +247,7 @@ if ($_SESSION['userlevel'] >= '10') {
<li><a href="ports/"><i class="fa fa-link fa-fw fa-lg"></i> All Ports</a></li> <li><a href="ports/"><i class="fa fa-link fa-fw fa-lg"></i> All Ports</a></li>
<?php <?php
$ports = new ObjCache('ports'); $ports = new ObjectCache('ports');
if ($ports['errored'] > 0) { if ($ports['errored'] > 0) {
echo(' <li><a href="ports/errors=1/"><i class="fa fa-exclamation-circle fa-fw fa-lg"></i> Errored ('.$ports['errored'].')</a></li>'); echo(' <li><a href="ports/errors=1/"><i class="fa fa-exclamation-circle fa-fw fa-lg"></i> Errored ('.$ports['errored'].')</a></li>');
@ -435,8 +435,7 @@ $routing_count['ospf'] = dbFetchCell("SELECT COUNT(ospf_instance_id) FROM `ospf_
$routing_count['cef'] = dbFetchCell("SELECT COUNT(cef_switching_id) from `cef_switching`"); $routing_count['cef'] = dbFetchCell("SELECT COUNT(cef_switching_id) from `cef_switching`");
$routing_count['vrf'] = dbFetchCell("SELECT COUNT(vrf_id) from `vrfs`"); $routing_count['vrf'] = dbFetchCell("SELECT COUNT(vrf_id) from `vrfs`");
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options['type'] = 'Cisco-OTV'; $options['type'] = 'Cisco-OTV';
$otv = $component->getComponents(null, $options); $otv = $component->getComponents(null, $options);
$routing_count['cisco-otv'] = count($otv); $routing_count['cisco-otv'] = count($otv);
@ -533,7 +532,7 @@ if (is_file("includes/print-menubar-custom.inc.php")) {
<ul class="nav navbar-nav navbar-right"> <ul class="nav navbar-nav navbar-right">
<li class="dropdown"> <li class="dropdown">
<?php <?php
$notifications = new ObjCache('notifications'); $notifications = new ObjectCache('notifications');
$style = ''; $style = '';
if (empty($notifications['count']) && empty($notifications['sticky_count'])) { if (empty($notifications['count']) && empty($notifications['sticky_count'])) {
$style = 'style="background-color:grey; color:white;"'; $style = 'style="background-color:grey; color:white;"';
@ -544,7 +543,7 @@ if (empty($notifications['count']) && empty($notifications['sticky_count'])) {
<li role="presentation" class="dropdown-header"> Settings</li> <li role="presentation" class="dropdown-header"> Settings</li>
<li><a href="preferences/"><i class="fa fa-cog fa-fw fa-lg"></i> My Settings</a></li> <li><a href="preferences/"><i class="fa fa-cog fa-fw fa-lg"></i> My Settings</a></li>
<?php <?php
$notifications = new ObjCache('notifications'); $notifications = new ObjectCache('notifications');
echo ('<li><a href="notifications/"><span class="badge count-notif">'.($notifications['sticky_count']+$notifications['count']).'</span> Notifications</a></li>'); echo ('<li><a href="notifications/"><span class="badge count-notif">'.($notifications['sticky_count']+$notifications['count']).'</span> Notifications</a></li>');
?> ?>
<li role="presentation" class="divider"></li> <li role="presentation" class="divider"></li>

View File

@ -4,8 +4,7 @@ $row = 1;
$device_id = $_POST['device_id']; $device_id = $_POST['device_id'];
require_once "../includes/component.php"; $OBJCOMP = new LibreNMS\Component();
$OBJCOMP = new component();
// Add a filter if supplied // Add a filter if supplied
if (isset($searchPhrase) && !empty($searchPhrase)) { if (isset($searchPhrase) && !empty($searchPhrase)) {

View File

@ -66,13 +66,10 @@ require_once '../includes/definitions.inc.php';
require '../includes/functions.php'; require '../includes/functions.php';
require 'includes/functions.inc.php'; require 'includes/functions.inc.php';
require 'includes/vars.inc.php'; require 'includes/vars.inc.php';
require 'includes/plugins.inc.php';
use LibreNMS\Plugins;
$config['memcached']['ttl'] = $config['time']['now']+300; $config['memcached']['ttl'] = $config['time']['now']+300;
Plugins::start(); LibreNMS\Plugins::start();
$runtime_start = microtime(true); $runtime_start = microtime(true);

View File

@ -1,5 +1,7 @@
<?php <?php
use LibreNMS\Exceptions\HostUnreachableException;
$no_refresh = true; $no_refresh = true;
if ($_SESSION['userlevel'] < 10) { if ($_SESSION['userlevel'] < 10) {

View File

@ -11,8 +11,7 @@
* the source code distribution for details. * the source code distribution for details.
*/ */
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options = array(); $options = array();
$options['filter']['ignore'] = array('=',0); $options['filter']['ignore'] = array('=',0);
$options['type'] = 'ntp'; $options['type'] = 'ntp';

View File

@ -209,8 +209,7 @@ if (device_permitted($vars['device']) || $check_device == $vars['device']) {
$routing_tabs[] = 'vrf'; $routing_tabs[] = 'vrf';
} }
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options['type'] = 'Cisco-OTV'; $options['type'] = 'Cisco-OTV';
$options['filter']['device_id'] = array('=',$device['device_id']); $options['filter']['device_id'] = array('=',$device['device_id']);
$otv = $component->getComponents(null, $options); $otv = $component->getComponents(null, $options);

View File

@ -11,8 +11,7 @@
* the source code distribution for details. * the source code distribution for details.
*/ */
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options = array(); $options = array();
$options['filter']['ignore'] = array('=',0); $options['filter']['ignore'] = array('=',0);
$options['type'] = 'ntp'; $options['type'] = 'ntp';

View File

@ -32,9 +32,8 @@ echo('
<div class="col-md-6"> <div class="col-md-6">
'); ');
require 'includes/dev-overview-data.inc.php'; require 'includes/dev-overview-data.inc.php';
use LibreNMS\Plugins;
Plugins::call('device_overview_container', array($device)); LibreNMS\Plugins::call('device_overview_container', array($device));
require 'overview/ports.inc.php'; require 'overview/ports.inc.php';
echo(' echo('

View File

@ -88,8 +88,7 @@ if (dbFetchCell("SELECT COUNT(*) FROM `ports_vlans` WHERE `port_id` = '".$port['
} }
// Are there any CBQoS components for this device? // Are there any CBQoS components for this device?
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options = array(); // Re-init array in case it has been declared previously. $options = array(); // Re-init array in case it has been declared previously.
$options['filter']['type'] = array('=','Cisco-CBQOS'); $options['filter']['type'] = array('=','Cisco-CBQOS');
$components = $component->getComponents($device['device_id'], $options); $components = $component->getComponents($device['device_id'], $options);

View File

@ -1,7 +1,6 @@
<?php <?php
require_once "../includes/component.php"; $component = new LibreNMS\Component();
$component = new component();
$options = array(); $options = array();
$options['filter']['ignore'] = array('=',0); $options['filter']['ignore'] = array('=',0);
$options['type'] = 'Cisco-OTV'; $options['type'] = 'Cisco-OTV';

View File

@ -22,7 +22,9 @@
* @subpackage Notifications * @subpackage Notifications
*/ */
$notifications = new ObjCache('notifications'); use LibreNMS\ObjectCache;
$notifications = new ObjectCache('notifications');
?> ?>
<div class="container"> <div class="container">
<div class="row"> <div class="row">

View File

@ -1,7 +1,6 @@
<?php <?php
require_once "../includes/component.php"; $COMPONENT = new LibreNMS\Component();
$COMPONENT = new component();
$options = array(); $options = array();
$options['filter']['ignore'] = array('=',0); $options['filter']['ignore'] = array('=',0);
$options['type'] = 'Cisco-OTV'; $options['type'] = 'Cisco-OTV';

View File

@ -15,8 +15,7 @@ if ($device['os_group'] == 'cisco') {
$module = 'Cisco-CBQOS'; $module = 'Cisco-CBQOS';
require_once 'includes/component.php'; $component = new LibreNMS\Component();
$component = new component();
$components = $component->getComponents($device['device_id'],array('type'=>$module)); $components = $component->getComponents($device['device_id'],array('type'=>$module));
// We only care about our device id. // We only care about our device id.

View File

@ -59,8 +59,7 @@ if ($device['os_group'] == 'cisco') {
$module = 'Cisco-OTV'; $module = 'Cisco-OTV';
require_once 'includes/component.php'; $component = new LibreNMS\Component();
$component = new component();
$components = $component->getComponents($device['device_id'],array('type'=>$module)); $components = $component->getComponents($device['device_id'],array('type'=>$module));
// We only care about our device id. // We only care about our device id.

View File

@ -12,6 +12,8 @@
* See COPYING for more details. * See COPYING for more details.
*/ */
use LibreNMS\Exceptions\HostExistsException;
function discover_new_device($hostname, $device = '', $method = '', $interface = '') { function discover_new_device($hostname, $device = '', $method = '', $interface = '') {
global $config; global $config;

View File

@ -13,8 +13,7 @@
$module = 'ntp'; $module = 'ntp';
require_once 'includes/component.php'; $component = new LibreNMS\Component();
$component = new component();
$components = $component->getComponents($device['device_id'],array('type'=>$module)); $components = $component->getComponents($device['device_id'],array('type'=>$module));
// We only care about our device id. // We only care about our device id.

View File

@ -12,15 +12,31 @@
* *
*/ */
use LibreNMS\Exceptions\HostExistsException;
use LibreNMS\Exceptions\HostIpExistsException;
use LibreNMS\Exceptions\HostUnreachableException;
use LibreNMS\Exceptions\HostUnreachablePingException;
use LibreNMS\Exceptions\InvalidPortAssocModeException;
use LibreNMS\Exceptions\SnmpVersionUnsupportedException;
// initialize the class loader and add custom mappings
require_once $config['install_dir'] . '/LibreNMS/ClassLoader.php';
$classLoader = new LibreNMS\ClassLoader();
$classLoader->mapClass('Console_Color2', $config['install_dir'] . '/includes/console_colour.php');
$classLoader->mapClass('Console_Table', $config['install_dir'] . '/includes/console_table.php');
$classLoader->mapClass('PHPMailer', $config['install_dir'] . "/includes/phpmailer/class.phpmailer.php");
$classLoader->mapClass('SMTP', $config['install_dir'] . "/includes/phpmailer/class.smtp.php");
$classLoader->mapClass('PasswordHash', $config['install_dir'] . '/html/lib/PasswordHash.php');
$classLoader->register();
// Include from PEAR // Include from PEAR
include_once("Net/IPv4.php"); include_once("Net/IPv4.php");
include_once("Net/IPv6.php"); include_once("Net/IPv6.php");
// Includes // Includes
include_once($config['install_dir'] . "/includes/exceptions.inc.php");
include_once($config['install_dir'] . "/includes/dbFacile.php"); include_once($config['install_dir'] . "/includes/dbFacile.php");
include_once($config['install_dir'] . "/includes/common.php"); include_once($config['install_dir'] . "/includes/common.php");
include_once($config['install_dir'] . "/includes/datastore.inc.php"); include_once($config['install_dir'] . "/includes/datastore.inc.php");
include_once($config['install_dir'] . "/includes/billing.php"); include_once($config['install_dir'] . "/includes/billing.php");
@ -29,15 +45,9 @@ include_once($config['install_dir'] . "/includes/syslog.php");
include_once($config['install_dir'] . "/includes/rewrites.php"); include_once($config['install_dir'] . "/includes/rewrites.php");
include_once($config['install_dir'] . "/includes/snmp.inc.php"); include_once($config['install_dir'] . "/includes/snmp.inc.php");
include_once($config['install_dir'] . "/includes/services.inc.php"); include_once($config['install_dir'] . "/includes/services.inc.php");
include_once($config['install_dir'] . "/includes/console_colour.php");
$console_color = new Console_Color2(); $console_color = new Console_Color2();
if ($config['alerts']['email']['enable']) {
include_once($config['install_dir'] . "/includes/phpmailer/class.phpmailer.php");
include_once($config['install_dir'] . "/includes/phpmailer/class.smtp.php");
}
function array_sort($array, $on, $order=SORT_ASC) { function array_sort($array, $on, $order=SORT_ASC) {
$new_array = array(); $new_array = array();
$sortable_array = array(); $sortable_array = array();
@ -691,8 +701,6 @@ function parse_email($emails) {
function send_mail($emails,$subject,$message,$html=false) { function send_mail($emails,$subject,$message,$html=false) {
global $config; global $config;
if( is_array($emails) || ($emails = parse_email($emails)) ) { if( is_array($emails) || ($emails = parse_email($emails)) ) {
if( !class_exists("PHPMailer",false) )
include_once($config['install_dir'] . "/includes/phpmailer/class.phpmailer.php");
$mail = new PHPMailer(); $mail = new PHPMailer();
$mail->Hostname = php_uname('n'); $mail->Hostname = php_uname('n');
if (empty($config['email_from'])) if (empty($config['email_from']))
@ -1370,30 +1378,7 @@ function dnslookup($device,$type=false,$return=false) {
}//end dnslookup }//end dnslookup
/**
* Reursive Filter Iterator to iterate directories and locate .rrd files.
*
* @method boolean isDir()
*
**/
class RRDRecursiveFilterIterator extends \RecursiveFilterIterator {
public function accept() {
$filename = $this->current()->getFilename();
if ($filename[0] === '.') {
// Ignore hidden files and directories
return false;
}
if ($this->isDir()) {
// We want to search into directories
return true;
}
// Matches files with .rrd in the filename.
// We are only searching rrd folder, but there could be other files and we don't want to cause a stink.
return strpos($filename, '.rrd') !== false;
}
}
/** /**
* Run rrdtool info on a file path * Run rrdtool info on a file path

View File

@ -15,8 +15,7 @@ if ($device['os_group'] == "cisco") {
$module = 'Cisco-CBQOS'; $module = 'Cisco-CBQOS';
require_once 'includes/component.php'; $component = new LibreNMS\Component();
$component = new component();
$options['filter']['type'] = array('=',$module); $options['filter']['type'] = array('=',$module);
$options['filter']['disabled'] = array('=',0); $options['filter']['disabled'] = array('=',0);
$options['filter']['ignore'] = array('=',0); $options['filter']['ignore'] = array('=',0);

View File

@ -59,8 +59,7 @@ if ($device['os_group'] == "cisco") {
$module = 'Cisco-OTV'; $module = 'Cisco-OTV';
require_once 'includes/component.php'; $component = new LibreNMS\Component();
$component = new component();
$options['filter']['type'] = array('=',$module); $options['filter']['type'] = array('=',$module);
$options['filter']['disabled'] = array('=',0); $options['filter']['disabled'] = array('=',0);
$components = $component->getComponents($device['device_id'],$options); $components = $component->getComponents($device['device_id'],$options);

View File

@ -13,8 +13,7 @@
$module = 'ntp'; $module = 'ntp';
require_once 'includes/component.php'; $component = new LibreNMS\Component();
$component = new component();
$options = array(); $options = array();
$options['filter']['type'] = array('=',$module); $options['filter']['type'] = array('=',$module);
$options['filter']['disabled'] = array('=',0); $options['filter']['disabled'] = array('=',0);

View File

@ -1,8 +1,6 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
require '../includes/console_colour.php';
require '../includes/console_table.php';
require '../includes/defaults.inc.php'; require '../includes/defaults.inc.php';
require '../config.php'; require '../config.php';
require_once '../includes/definitions.inc.php'; require_once '../includes/definitions.inc.php';

View File

@ -25,6 +25,10 @@
* @subpackage Discovery * @subpackage Discovery
*/ */
use LibreNMS\Exceptions\HostExistsException;
use LibreNMS\Exceptions\HostUnreachableException;
use LibreNMS\Exceptions\HostUnreachablePingException;
$ts = microtime(true); $ts = microtime(true);
chdir(dirname($argv[0])); chdir(dirname($argv[0]));
@ -32,15 +36,14 @@ chdir(dirname($argv[0]));
require 'includes/defaults.inc.php'; require 'includes/defaults.inc.php';
require 'config.php'; require 'config.php';
require 'includes/definitions.inc.php'; require 'includes/definitions.inc.php';
require 'includes/functions.php';
require 'includes/discovery/functions.inc.php';
if ($config['autodiscovery']['snmpscan'] == false) { if ($config['autodiscovery']['snmpscan'] == false) {
echo 'SNMP-Scan disabled.'.PHP_EOL; echo 'SNMP-Scan disabled.'.PHP_EOL;
exit(2); exit(2);
} }
require 'includes/functions.php';
require 'includes/discovery/functions.inc.php';
function perform_snmp_scan($net) { function perform_snmp_scan($net) {
global $stats, $config, $debug, $vdebug; global $stats, $config, $debug, $vdebug;
echo 'Range: '.$net->network.'/'.$net->bitmask.PHP_EOL; echo 'Range: '.$net->network.'/'.$net->bitmask.PHP_EOL;

View File

@ -307,7 +307,7 @@ foreach ($modules as $module) {
// Loop through the rrd_dir // Loop through the rrd_dir
$rrd_directory = new RecursiveDirectoryIterator($config['rrd_dir']); $rrd_directory = new RecursiveDirectoryIterator($config['rrd_dir']);
// Filter out any non rrd files // Filter out any non rrd files
$rrd_directory_filter = new RRDRecursiveFilterIterator($rrd_directory); $rrd_directory_filter = new LibreNMS\RRDRecursiveFilterIterator($rrd_directory);
$rrd_iterator = new RecursiveIteratorIterator($rrd_directory_filter); $rrd_iterator = new RecursiveIteratorIterator($rrd_directory_filter);
$rrd_total = iterator_count($rrd_iterator); $rrd_total = iterator_count($rrd_iterator);
$rrd_iterator->rewind(); // Rewind iterator in case iterator_count left iterator in unknown state $rrd_iterator->rewind(); // Rewind iterator in case iterator_count left iterator in unknown state