mirror of
https://github.com/stylersnico/librenms.git
synced 2026-07-28 00:24:21 +02:00
Merge branch 'master' of github.com:laf/librenms into issue-1626
This commit is contained in:
+1
-1
@@ -23,7 +23,7 @@ Contributors to LibreNMS:
|
||||
- Stuart Henderson <stu@spacehopper.org> (sthen)
|
||||
- Filippo Giunchedi <filippo@esaurito.net> (filippog)
|
||||
- Lasse Leegaard <lasse@brandbil.dk> (lasseleegaard)
|
||||
- Mickael Marchand <mmarchand@corp.free.fr> (mmarchand)
|
||||
- Mickael Marchand <mmarchand@corp.free.fr> (mmarchand)
|
||||
- Mohammad Al-Shami <mohammad@al-shami.net> (mohshami)
|
||||
- Rudy Hardeman <zarya@gigafreak.net> (zarya)
|
||||
- Arjit Chaudhary (arjit.c@gmail.com) (arjitc)
|
||||
|
||||
+6
-6
@@ -14,24 +14,24 @@ if ($sql_fh === false) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$connection = mysql_connect($config['db_host'], $config['db_user'], $config['db_pass']);
|
||||
$connection = mysqli_connect($config['db_host'], $config['db_user'], $config['db_pass']);
|
||||
if ($connection === false) {
|
||||
echo 'ERROR: Cannot connect to database: '.mysql_error()."\n";
|
||||
echo 'ERROR: Cannot connect to database: '.mysqli_error($connection)."\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
$select = mysql_select_db($config['db_name']);
|
||||
$select = mysqli_select_db($config['db_name']);
|
||||
if ($select === false) {
|
||||
echo 'ERROR: Cannot select database: '.mysql_error()."\n";
|
||||
echo 'ERROR: Cannot select database: '.mysqli_error($connection)."\n";
|
||||
exit(1);
|
||||
}
|
||||
|
||||
while (!feof($sql_fh)) {
|
||||
$line = fgetss($sql_fh);
|
||||
if (!empty($line)) {
|
||||
$creation = mysql_query($line);
|
||||
$creation = mysqli_query($connection, $line);
|
||||
if (!$creation) {
|
||||
echo 'WARNING: Cannot execute query ('.$line.'): '.mysql_error()."\n";
|
||||
echo 'WARNING: Cannot execute query ('.$line.'): '.mysqli_error($connection)."\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -1,12 +1,13 @@
|
||||
<?php
|
||||
|
||||
## Have a look in defaults.inc.php for examples of settings you can set here. DO NOT EDIT defaults.inc.php!
|
||||
## Have a look in includes/defaults.inc.php for examples of settings you can set here. DO NOT EDIT defaults.inc.php!
|
||||
|
||||
### Database config
|
||||
$config['db_host'] = "localhost";
|
||||
$config['db_user'] = "USERNAME";
|
||||
$config['db_pass'] = "PASSWORD";
|
||||
$config['db_name'] = "librenms";
|
||||
$config['db']['extension'] = 'mysqli';// mysql or mysqli
|
||||
|
||||
### Memcached config - We use this to store realtime usage
|
||||
$config['memcached']['enable'] = FALSE;
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ function iscli() {
|
||||
|
||||
}
|
||||
|
||||
// check if we are running throw the CLI, otherwise abort
|
||||
// check if we are running through the CLI, otherwise abort
|
||||
if (iscli()) {
|
||||
include_once $defaults_file;
|
||||
include_once $config_file;
|
||||
|
||||
@@ -36,6 +36,8 @@ Table of Content:
|
||||
LibreNMS includes a highly customizable alerting system.
|
||||
The system requires a set of user-defined rules to evaluate the situation of each device, port, service or any other entity.
|
||||
|
||||
> You can configure all options for alerting and transports via the WebUI, config options in this document are crossed out but left for reference.
|
||||
|
||||
This document only covers the usage of it. See the [DEVELOPMENT.md](https://github.com/f0o/glowing-tyrion/blob/master/DEVELOPMENT.md) for code-documentation.
|
||||
|
||||
# <a name="rules">Rules</a>
|
||||
@@ -125,34 +127,41 @@ Alert sent to: {foreach %contacts}%value <%key> {/foreach}
|
||||
|
||||
# <a name="transports">Transports</a>
|
||||
|
||||
Transports are located within `$config['install_dir']/includes/alerts/transports.*.php` and defined as well as configured via `$config['alert']['transports']['Example'] = 'Some Options'`.
|
||||
Transports are located within `$config['install_dir']/includes/alerts/transports.*.php` and defined as well as configured via ~~`$config['alert']['transports']['Example'] = 'Some Options'`~~.
|
||||
|
||||
Contacts will be gathered automatically and passed to the configured transports.
|
||||
By default the Contacts will be only gathered when the alert triggers and will ignore future changes in contacts for the incident. If you want contacts to be re-gathered before each dispatch, please set `$config['alert']['fixed-contacts'] = false;` in your config.php.
|
||||
By default the Contacts will be only gathered when the alert triggers and will ignore future changes in contacts for the incident. If you want contacts to be re-gathered before each dispatch, please set ~~`$config['alert']['fixed-contacts'] = false;`~~ in your config.php.
|
||||
|
||||
The contacts will always include the `SysContact` defined in the Device's SNMP configuration and also every LibreNMS-User that has at least `read`-permissions on the entity that is to be alerted.
|
||||
At the moment LibreNMS only supports Port or Device permissions.
|
||||
You can exclude the `SysContact` by setting:
|
||||
~~
|
||||
```php
|
||||
$config['alert']['syscontact'] = false;
|
||||
```
|
||||
~
|
||||
To include users that have `Global-Read` or `Administrator` permissions it is required to add these additions to the `config.php` respectively:
|
||||
~
|
||||
```php
|
||||
$config['alert']['globals'] = true; //Include Global-Read into alert-contacts
|
||||
$config['alert']['admins'] = true; //Include Adminstrators into alert-contacts
|
||||
```
|
||||
~~
|
||||
|
||||
## <a name="transports-email">E-Mail</a>
|
||||
|
||||
> You can configure these options within the WebUI now, please avoid setting these options within config.php
|
||||
|
||||
E-Mail transport is enabled with adding the following to your `config.php`:
|
||||
E-Mail transport is enabled with adding the following to your `config.php`:
|
||||
~
|
||||
```php
|
||||
$config['alert']['transports']['mail'] = true;
|
||||
```
|
||||
~~
|
||||
|
||||
The E-Mail transports uses the same email-configuration like the rest of LibreNMS.
|
||||
As a small reminder, here is it's configuration directives including defaults:
|
||||
~~
|
||||
```php
|
||||
$config['email_backend'] = 'mail'; // Mail backend. Allowed: "mail" (PHP's built-in), "sendmail", "smtp".
|
||||
$config['email_from'] = NULL; // Mail from. Default: "ProjectName" <projectid@`hostname`>
|
||||
@@ -169,13 +178,14 @@ $config['email_smtp_password'] = NULL; // Password f
|
||||
$config['alert']['default_only'] = false; //Only issue to default_mail
|
||||
$config['alert']['default_mail'] = ''; //Default email
|
||||
```
|
||||
~~
|
||||
|
||||
## <a name="transports-api">API</a>
|
||||
|
||||
> You can configure these options within the WebUI now, please avoid setting these options within config.php
|
||||
|
||||
API transports definitions are a bit more complex than the E-Mail configuration.
|
||||
The basis for configuration is `$config['alert']['transports']['api'][METHOD]` where `METHOD` can be `get`,`post` or `put`.
|
||||
The basis for configuration is ~~`$config['alert']['transports']['api'][METHOD]`~~ where `METHOD` can be `get`,`post` or `put`.
|
||||
This basis has to contain an array with URLs of each API to call.
|
||||
The URL can have the same placeholders as defined in the [Template-Syntax](#templates-syntax).
|
||||
If the `METHOD` is `get`, all placeholders will be URL-Encoded.
|
||||
@@ -183,9 +193,11 @@ The API transport uses cURL to call the APIs, therefore you might need to instal
|
||||
__Note__: it is highly recommended to define own [Templates](#templates) when you want to use the API transport. The default template might exceed URL-length for GET requests and therefore cause all sorts of errors.
|
||||
|
||||
Example:
|
||||
~~
|
||||
```php
|
||||
$config['alert']['transports']['api']['get'][] = "https://api.thirdparti.es/issue?apikey=abcdefg&subject=%title";
|
||||
```
|
||||
~~
|
||||
|
||||
## <a name="transports-nagios">Nagios Compatible</a>
|
||||
|
||||
@@ -193,19 +205,23 @@ $config['alert']['transports']['api']['get'][] = "https://api.thirdparti.es/issu
|
||||
|
||||
The nagios transport will feed a FIFO at the defined location with the same format that nagios would.
|
||||
This allows you to use other Alerting-Systems to work with LibreNMS, for example [Flapjack](http://flapjack.io).
|
||||
~~
|
||||
```php
|
||||
$config['alert']['transports']['nagios'] = "/path/to/my.fifo"; //Flapjack expects it to be at '/var/cache/nagios3/event_stream.fifo'
|
||||
```
|
||||
~~
|
||||
|
||||
## <a name="transports-irc">IRC</a>
|
||||
|
||||
> You can configure these options within the WebUI now, please avoid setting these options within config.php
|
||||
|
||||
The IRC transports only works together with the LibreNMS IRC-Bot.
|
||||
Configuration of the LibreNMS IRC-Bot is described [here](https://github.com/librenms/librenms/blob/master/doc/Extensions/IRC-Bot.md).
|
||||
Configuration of the LibreNMS IRC-Bot is described [here](https://github.com/librenms/librenms/blob/master/doc/Extensions/IRC-Bot.md).
|
||||
~~
|
||||
```php
|
||||
$config['alert']['transports']['irc'] = true;
|
||||
```
|
||||
~~
|
||||
|
||||
## <a name="transports-slack">Slack</a>
|
||||
|
||||
@@ -213,12 +229,14 @@ $config['alert']['transports']['irc'] = true;
|
||||
|
||||
The Slack transport will POST the alert message to your Slack Incoming WebHook, you are able to specify multiple webhooks along with the relevant options to go with it. All options are optional, the only required value is for url, without this then no call to Slack will be made. Below is an example of how to send alerts to two channels with different customised options:
|
||||
|
||||
~~
|
||||
```php
|
||||
$config['alert']['transports']['slack'][] = array('url' => "https://hooks.slack.com/services/A12B34CDE/F56GH78JK/L901LmNopqrSTUVw2w3XYZAB4C", 'channel' => '#Alerting');
|
||||
|
||||
$config['alert']['transports']['slack'][] = array('url' => "https://hooks.slack.com/services/A12B34CDE/F56GH78JK/L901LmNopqrSTUVw2w3XYZAB4C", 'channel' => '@john', 'username' => 'LibreNMS', 'icon_emoji' => ':ghost:');
|
||||
|
||||
```
|
||||
~~
|
||||
|
||||
## <a name="transports-hipchat">HipChat</a>
|
||||
|
||||
@@ -249,6 +267,7 @@ for details on acceptable values.
|
||||
|
||||
Below are two examples of sending messages to a HipChat room.
|
||||
|
||||
~~
|
||||
```php
|
||||
$config['alert']['transports']['hipchat'][] = array("url" => "https://api.hipchat.com/v1/rooms/message?auth_token=9109jawregoaih",
|
||||
"room_id" => "1234567",
|
||||
@@ -261,6 +280,7 @@ $config['alert']['transports']['hipchat'][] = array("url" => "https://api.hipcha
|
||||
"notify" => 1,
|
||||
"message_format" => "text");
|
||||
```
|
||||
~~
|
||||
|
||||
> Note: The default message format for HipChat messages is HTML. It is
|
||||
> recommended that you specify the `text` message format to prevent unexpected
|
||||
@@ -277,9 +297,11 @@ All you need is to create a Service with type Generic API on your PagerDuty dash
|
||||
|
||||
Now copy your API-Key from the newly created Service and setup the transport like:
|
||||
|
||||
~~
|
||||
```php
|
||||
$config['alert']['transports']['pagerduty'] = 'MYAPIKEYGOESHERE';
|
||||
```
|
||||
~~
|
||||
|
||||
That's it!
|
||||
|
||||
@@ -293,15 +315,18 @@ Firstly you need to create a new Application (called LibreNMS, for example) in y
|
||||
|
||||
Now copy your API Token/Key from the newly created Application and setup the transport in your config.php like:
|
||||
|
||||
~~
|
||||
```php
|
||||
$config['alert']['transports']['pushover'][] = array(
|
||||
"appkey" => 'APPLICATIONAPIKEYGOESHERE',
|
||||
"userkey" => 'USERKEYGOESHERE',
|
||||
);
|
||||
```
|
||||
~~
|
||||
|
||||
To modify the Critical alert sound, add the 'sound_critical' parameter, example:
|
||||
|
||||
~~
|
||||
```php
|
||||
$config['alert']['transports']['pushover'][] = array(
|
||||
"appkey" => 'APPLICATIONAPIKEYGOESHERE',
|
||||
@@ -309,26 +334,31 @@ $config['alert']['transports']['pushover'][] = array(
|
||||
"sound_critical" => 'siren',
|
||||
);
|
||||
```
|
||||
~~
|
||||
|
||||
## <a name="transports-boxcar">Boxcar</a>
|
||||
|
||||
Enabling Boxcar support is super easy.
|
||||
Copy your access token from the Boxcar app or from the Boxcar.io website and setup the transport in your config.php like:
|
||||
|
||||
~~
|
||||
```php
|
||||
$config['alert']['transports']['boxcar'][] = array(
|
||||
"access_token" => 'ACCESSTOKENGOESHERE',
|
||||
);
|
||||
```
|
||||
~~
|
||||
|
||||
To modify the Critical alert sound, add the 'sound_critical' parameter, example:
|
||||
|
||||
~~
|
||||
```php
|
||||
$config['alert']['transports']['boxcar'][] = array(
|
||||
"access_token" => 'ACCESSTOKENGOESHERE',
|
||||
"sound_critical" => 'detonator-charge',
|
||||
);
|
||||
```
|
||||
~~
|
||||
|
||||
# <a name="entities">Entities
|
||||
|
||||
|
||||
@@ -11,8 +11,8 @@ $config['enable_billing'] = 1; # Enable Billing
|
||||
Edit `/etc/cron.d/librenms` and add the following:
|
||||
|
||||
```bash
|
||||
*/5 * * * * root /opt/librenms/poll-billing.php >> /dev/null 2>&1
|
||||
01 * * * * root /opt/librenms/billing-calculate.php >> /dev/null 2>&1
|
||||
*/5 * * * * librenms /opt/librenms/poll-billing.php >> /dev/null 2>&1
|
||||
01 * * * * librenms /opt/librenms/billing-calculate.php >> /dev/null 2>&1
|
||||
```
|
||||
|
||||
Create billing graphs as required.
|
||||
Create billing graphs as required.
|
||||
|
||||
@@ -19,6 +19,22 @@ $config['log_dir'] = "/opt/librenms/logs";
|
||||
```
|
||||
Log files created by LibreNMS will be stored within this directory.
|
||||
|
||||
#### Database config
|
||||
|
||||
These are the configuration options you will need to use to specify to get started.
|
||||
|
||||
```php
|
||||
$config['db_host'] = "127.0.0.1";
|
||||
$config['db_user'] = "";
|
||||
$config['db_pass'] = "";
|
||||
$config['db_name'] = "";
|
||||
```
|
||||
|
||||
You can also select between the mysql and mysqli php extensions:
|
||||
|
||||
```php
|
||||
$config['db']['extension'] = 'mysqli';
|
||||
```
|
||||
|
||||
#### Progams
|
||||
|
||||
@@ -260,10 +276,6 @@ Please see [Billing](http://docs.librenms.org/Extensions/Billing-Module/) sectio
|
||||
|
||||
```php
|
||||
$config['enable_bgp'] = 1; # Enable BGP session collection and display
|
||||
$config['enable_rip'] = 1; # Enable RIP session collection and display
|
||||
$config['enable_ospf'] = 1; # Enable OSPF session collection and display
|
||||
$config['enable_isis'] = 1; # Enable ISIS session collection and display
|
||||
$config['enable_eigrp'] = 1; # Enable EIGRP session collection and display
|
||||
$config['enable_syslog'] = 0; # Enable Syslog
|
||||
$config['enable_inventory'] = 1; # Enable Inventory
|
||||
$config['enable_pseudowires'] = 1; # Enable Pseudowires
|
||||
|
||||
+2
-2
@@ -28,7 +28,7 @@ if (!$_SESSION['authenticated']) {
|
||||
}
|
||||
|
||||
if (preg_match('/^[a-zA-Z0-9\-]+$/', $_POST['type']) == 1) {
|
||||
if (file_exists('forms/'.$_POST['type'].'.inc.php')) {
|
||||
include_once 'forms/'.$_POST['type'].'.inc.php';
|
||||
if (file_exists('includes/forms/'.$_POST['type'].'.inc.php')) {
|
||||
include_once 'includes/forms/'.$_POST['type'].'.inc.php';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
<?php
|
||||
|
||||
$sql = "SELECT *, DATE_FORMAT(timestamp, '".$config['dateformat']['mysql']['compact']."') AS date from syslog ORDER BY timestamp DESC LIMIT 20";
|
||||
$query = mysql_query($sql);
|
||||
|
||||
$syslog_output = '
|
||||
<div class="container-fluid">
|
||||
|
||||
@@ -12,4 +12,8 @@
|
||||
* the source code distribution for details.
|
||||
*/
|
||||
|
||||
if(is_admin() === false) {
|
||||
die('ERROR: You need to be admin');
|
||||
}
|
||||
|
||||
dbUpdate(array('value' => '2'), 'callback', '`name` = "enabled"', array());
|
||||
+4
@@ -12,6 +12,10 @@
|
||||
* the source code distribution for details.
|
||||
*/
|
||||
|
||||
if(is_admin() === false) {
|
||||
die('ERROR: You need to be admin');
|
||||
}
|
||||
|
||||
if ($_POST['state'] == 'true') {
|
||||
$state = 1;
|
||||
}
|
||||
+5
@@ -13,6 +13,11 @@
|
||||
*/
|
||||
|
||||
// FUA
|
||||
|
||||
if(is_admin() === false) {
|
||||
die('ERROR: You need to be admin');
|
||||
}
|
||||
|
||||
if (!is_numeric($_POST['config_id'])) {
|
||||
echo 'error with data';
|
||||
exit;
|
||||
@@ -13,6 +13,11 @@
|
||||
*/
|
||||
|
||||
// FUA
|
||||
|
||||
if(is_admin() === false) {
|
||||
die('ERROR: You need to be admin');
|
||||
}
|
||||
|
||||
if (!is_numeric($_POST['config_id']) || empty($_POST['data'])) {
|
||||
echo 'error with data';
|
||||
exit;
|
||||
+5
@@ -1,6 +1,11 @@
|
||||
<?php
|
||||
|
||||
// FUA
|
||||
|
||||
if(is_admin() === false) {
|
||||
die('ERROR: You need to be admin');
|
||||
}
|
||||
|
||||
$device['device_id'] = $_POST['device_id'];
|
||||
$module = 'discover_'.$_POST['discovery_module'];
|
||||
|
||||
@@ -13,6 +13,11 @@
|
||||
*/
|
||||
|
||||
// FUA
|
||||
|
||||
if(is_admin() === false) {
|
||||
die('ERROR: You need to be admin');
|
||||
}
|
||||
|
||||
if (!is_numeric($_POST['device_id']) || !is_numeric($_POST['sensor_id']) || (empty($_POST['data']) || !isset($_POST['data']))) {
|
||||
echo 'error with data';
|
||||
exit;
|
||||
+4
@@ -12,6 +12,10 @@
|
||||
* the source code distribution for details.
|
||||
*/
|
||||
|
||||
if(is_admin() === false) {
|
||||
die('ERROR: You need to be admin');
|
||||
}
|
||||
|
||||
if (!is_numeric($_POST['group_id'])) {
|
||||
echo 'error with data';
|
||||
exit;
|
||||
+4
@@ -1,5 +1,9 @@
|
||||
<?php
|
||||
|
||||
if(is_admin() === false) {
|
||||
die('ERROR: You need to be admin');
|
||||
}
|
||||
|
||||
// FUA
|
||||
$device['device_id'] = $_POST['device_id'];
|
||||
$module = 'poll_'.$_POST['poller_module'];
|
||||
@@ -12,6 +12,15 @@
|
||||
* the source code distribution for details.
|
||||
*/
|
||||
|
||||
if (is_admin() === false) {
|
||||
$response = array(
|
||||
'status' => 'error',
|
||||
'message' => 'Need to be admin',
|
||||
);
|
||||
echo _json_encode($response);
|
||||
exit;
|
||||
}
|
||||
|
||||
// FIXME: Make this part of the API instead of a standalone function
|
||||
if (!is_numeric($_POST['device_id'])) {
|
||||
$status = 'error';
|
||||
@@ -13,6 +13,11 @@
|
||||
*/
|
||||
|
||||
// FUA
|
||||
|
||||
if(is_admin() === false) {
|
||||
die('ERROR: You need to be admin');
|
||||
}
|
||||
|
||||
for ($x = 0; $x < count($_POST['sensor_id']); $x++) {
|
||||
dbUpdate(array('sensor_limit' => $_POST['sensor_limit'][$x], 'sensor_limit_low' => $_POST['sensor_limit_low'][$x], 'sensor_alert' => $_POST['sensor_alert'][$x]), 'sensors', '`sensor_id` = ?', array($_POST['sensor_id'][$x]));
|
||||
}
|
||||
+5
@@ -13,6 +13,11 @@
|
||||
*/
|
||||
|
||||
// FUA
|
||||
|
||||
if(is_admin() === false) {
|
||||
die('ERROR: You need to be admin');
|
||||
}
|
||||
|
||||
if (isset($_POST['sub_type']) && !empty($_POST['sub_type'])) {
|
||||
dbUpdate(array('sensor_custom' => 'No'), 'sensors', '`sensor_id` = ?', array($_POST['sensor_id']));
|
||||
}
|
||||
@@ -12,6 +12,15 @@
|
||||
* the source code distribution for details.
|
||||
*/
|
||||
|
||||
if (is_admin() === false) {
|
||||
$response = array(
|
||||
'status' => 'error',
|
||||
'message' => 'Need to be admin',
|
||||
);
|
||||
echo _json_encode($response);
|
||||
exit;
|
||||
}
|
||||
|
||||
$status = 'error';
|
||||
$message = 'Error updating storage information';
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
* the source code distribution for details.
|
||||
*/
|
||||
|
||||
if(is_admin() === false) {
|
||||
die('ERROR: You need to be admin');
|
||||
}
|
||||
|
||||
if (!is_numeric($_POST['user_id']) || !isset($_POST['token'])) {
|
||||
echo 'ERROR: error with data, please ensure a valid user and token have been specified.';
|
||||
exit;
|
||||
@@ -12,6 +12,10 @@
|
||||
* the source code distribution for details.
|
||||
*/
|
||||
|
||||
if(is_admin() === false) {
|
||||
die('ERROR: You need to be admin');
|
||||
}
|
||||
|
||||
if (!is_numeric($_POST['token_id'])) {
|
||||
echo 'error with data';
|
||||
exit;
|
||||
@@ -12,6 +12,10 @@
|
||||
* the source code distribution for details.
|
||||
*/
|
||||
|
||||
if(is_admin() === false) {
|
||||
die('ERROR: You need to be admin');
|
||||
}
|
||||
|
||||
if (!is_numeric($_POST['token_id'])) {
|
||||
echo 'error with data';
|
||||
exit;
|
||||
@@ -1,5 +1,14 @@
|
||||
<?php
|
||||
|
||||
if (is_admin() === false) {
|
||||
$response = array(
|
||||
'status' => 'error',
|
||||
'message' => 'Need to be admin',
|
||||
);
|
||||
echo _json_encode($response);
|
||||
exit;
|
||||
}
|
||||
|
||||
$status = 'error';
|
||||
$message = 'Error with config';
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
if (!is_array($config['customers_descr'])) {
|
||||
$config['customers_descr'] = array($config['customers_descr']);
|
||||
}
|
||||
|
||||
$descr_type = "'".implode("', '", $config['customers_descr'])."'";
|
||||
|
||||
$i = 0;
|
||||
|
||||
$sql = ' FROM `ports` LEFT JOIN `devices` AS `D` ON `ports`.`device_id` = `D`.`device_id` WHERE `port_descr_type` IN (?)';
|
||||
$param[] = array($descr_type);
|
||||
if (isset($searchPhrase) && !empty($searchPhrase)) {
|
||||
$sql .= " AND (`port_descr_descr` LIKE '%$searchPhrase%' OR `ifName` LIKE '%$searchPhrase%' OR `ifDescr` LIKE '%$searchPhrase%' OR `ifAlias` LIKE '%$searchPhrase%' OR `D`.`hostname` LIKE '%$searchPhrase%' OR `port_descr_speed` LIKE '%$searchPhrase%' OR `port_descr_notes` LIKE '%$searchPhrase%')";
|
||||
}
|
||||
|
||||
$count_sql = "SELECT COUNT(DISTINCT(`port_descr_descr`)) $sql";
|
||||
|
||||
$sql .= ' GROUP BY `port_descr_descr`';
|
||||
|
||||
$total = dbFetchCell($count_sql,$param);
|
||||
if (empty($total)) {
|
||||
$total = 0;
|
||||
}
|
||||
|
||||
if (!isset($sort) || empty($sort)) {
|
||||
$sort = '`port_descr_descr`';
|
||||
}
|
||||
|
||||
$sql .= " ORDER BY $sort";
|
||||
|
||||
if (isset($current)) {
|
||||
$limit_low = ($current * $rowCount) - ($rowCount);
|
||||
$limit_high = $rowCount;
|
||||
}
|
||||
|
||||
if ($rowCount != -1) {
|
||||
$sql .= " LIMIT $limit_low,$limit_high";
|
||||
}
|
||||
|
||||
$sql = "SELECT * $sql";
|
||||
|
||||
foreach (dbFetchRows($sql, $param) as $customer) {
|
||||
$i++;
|
||||
|
||||
$customer_name = $customer['port_descr_descr'];
|
||||
|
||||
foreach (dbFetchRows('SELECT * FROM `ports` WHERE `port_descr_type` IN (?) AND `port_descr_descr` = ?', array(array($descr_type), $customer['port_descr_descr'])) as $port) {
|
||||
$device = device_by_id_cache($port['device_id']);
|
||||
|
||||
$ifname = fixifname($device['ifDescr']);
|
||||
$ifclass = ifclass($port['ifOperStatus'], $port['ifAdminStatus']);
|
||||
|
||||
if ($device['os'] == 'ios') {
|
||||
if ($port['ifTrunk']) {
|
||||
$vlan = '<span class=box-desc><span class=red>'.$port['ifTrunk'].'</span></span>';
|
||||
}
|
||||
else if ($port['ifVlan']) {
|
||||
$vlan = '<span class=box-desc><span class=blue>VLAN '.$port['ifVlan'].'</span></span>';
|
||||
}
|
||||
else {
|
||||
$vlan = '';
|
||||
}
|
||||
}
|
||||
|
||||
$response[] = array(
|
||||
'port_descr_descr' => $customer_name,
|
||||
'device_id' => generate_device_link($device),
|
||||
'ifDescr' => generate_port_link($port, makeshortif($port['ifDescr'])),
|
||||
'port_descr_speed' => $port['port_descr_speed'],
|
||||
'port_descr_circuit' => $port['port_descr_circuit'],
|
||||
'port_descr_notes' => $port['port_descr_notes'],
|
||||
|
||||
);
|
||||
|
||||
unset($customer_name);
|
||||
}
|
||||
|
||||
|
||||
$graph_array['type'] = 'customer_bits';
|
||||
$graph_array['height'] = '100';
|
||||
$graph_array['width'] = '220';
|
||||
$graph_array['to'] = $config['time']['now'];
|
||||
$graph_array['id'] = $customer['port_descr_descr'];
|
||||
|
||||
$return_data = true;
|
||||
include 'includes/print-graphrow.inc.php';
|
||||
$response[] = array(
|
||||
'port_descr_descr' => $graph_data[0],
|
||||
'device_id' => $graph_data[1],
|
||||
'ifDescr' => '',
|
||||
'port_descr_speed' => '',
|
||||
'port_descr_circuit' => $graph_data[2],
|
||||
'port_descr_notes' => $graph_data[3],
|
||||
);
|
||||
}
|
||||
|
||||
$output = array(
|
||||
'current' => $current,
|
||||
'rowCount' => $rowCount,
|
||||
'rows' => $response,
|
||||
'total' => $total,
|
||||
);
|
||||
|
||||
echo _json_encode($output);
|
||||
@@ -352,6 +352,7 @@ $config_file = <<<"EOD"
|
||||
\$config\['db_user'\] = "$dbuser";
|
||||
\$config\['db_pass'\] = "$dbpass";
|
||||
\$config\['db_name'\] = "$dbname";
|
||||
\$config\['db'\]\['extension'\] = "mysqli";// mysql or mysqli
|
||||
|
||||
### Memcached config - We use this to store realtime usage
|
||||
\$config\['memcached'\]\['enable'\] = FALSE;
|
||||
|
||||
@@ -212,7 +212,6 @@ if (isset($_GET['format']) && preg_match("/^[a-z]*$/", $_GET['format'])) {
|
||||
}
|
||||
|
||||
if ($where == '') {
|
||||
# $maptool = $config['unflatten'] . ' -f -l 5 | ' . $config['sfdp'] . ' -Gpack -Goverlap=prism -Gcharset=latin1 | dot';
|
||||
$maptool = $config['sfdp'] . ' -Gpack -Goverlap=prism -Gcharset=latin1 -Gsize=20,20';
|
||||
$maptool = $config['dot'];
|
||||
}
|
||||
|
||||
@@ -1,87 +1,34 @@
|
||||
<?php
|
||||
|
||||
echo '<table border=0 cellspacing=0 cellpadding=2 class=devicetable width=100%>';
|
||||
|
||||
echo "
|
||||
<tr bgcolor='$list_colour_a'>
|
||||
<th width='7'></th>
|
||||
<th width='250'><span style='font-weight: bold;' class=interface>Customer</span></th>
|
||||
<th width='150'>Device</th>
|
||||
<th width='100'>Interface</th>
|
||||
<th width='100'>Speed</th>
|
||||
<th width='100'>Circuit</th>
|
||||
<th>Notes</th>
|
||||
</tr>
|
||||
";
|
||||
|
||||
$i = 1;
|
||||
|
||||
$pagetitle[] = 'Customers';
|
||||
|
||||
if (!is_array($config['customers_descr'])) {
|
||||
$config['customers_descr'] = array($config['customers_descr']);
|
||||
}
|
||||
?>
|
||||
|
||||
$descr_type = "'".implode("', '", $config['customers_descr'])."'";
|
||||
<div class="table-responsive">
|
||||
<table id="customers" class="table table-hover table-condensed table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th data-column-id="port_descr_descr" data-order="asc">Customer</th>
|
||||
<th data-column-id="device_id">Device</th>
|
||||
<th data-column-id="ifDescr">Interface</th>
|
||||
<th data-column-id="port_descr_speed">Speed</th>
|
||||
<th data-column-id="port_descr_circuit">Circuit</th>
|
||||
<th data-column-id="port_descr_notes">Notes</th>
|
||||
</tr>
|
||||
</thead>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
foreach (dbFetchRows('SELECT * FROM `ports` WHERE `port_descr_type` IN (?) GROUP BY `port_descr_descr` ORDER BY `port_descr_descr`', array(array($descr_type))) as $customer) {
|
||||
$i++;
|
||||
<script>
|
||||
|
||||
$customer_name = $customer['port_descr_descr'];
|
||||
|
||||
if (!is_integer($i / 2)) {
|
||||
$bg_colour = $list_colour_a;
|
||||
}
|
||||
else {
|
||||
$bg_colour = $list_colour_b;
|
||||
}
|
||||
|
||||
foreach (dbFetchRows('SELECT * FROM `ports` WHERE `port_descr_type` IN (?) AND `port_descr_descr` = ?', array(array($descr_type), $customer['port_descr_descr'])) as $port) {
|
||||
$device = device_by_id_cache($port['device_id']);
|
||||
|
||||
unset($class);
|
||||
|
||||
$ifname = fixifname($device['ifDescr']);
|
||||
$ifclass = ifclass($port['ifOperStatus'], $port['ifAdminStatus']);
|
||||
|
||||
if ($device['os'] == 'ios') {
|
||||
if ($port['ifTrunk']) {
|
||||
$vlan = '<span class=box-desc><span class=red>'.$port['ifTrunk'].'</span></span>';
|
||||
}
|
||||
else if ($port['ifVlan']) {
|
||||
$vlan = '<span class=box-desc><span class=blue>VLAN '.$port['ifVlan'].'</span></span>';
|
||||
}
|
||||
else {
|
||||
$vlan = '';
|
||||
}
|
||||
}
|
||||
|
||||
echo "
|
||||
<tr bgcolor='$bg_colour'>
|
||||
<td width='7'></td>
|
||||
<td width='250'><span style='font-weight: bold;' class=interface>".$customer_name."</span></td>
|
||||
<td width='150'>".generate_device_link($device)."</td>
|
||||
<td width='100'>".generate_port_link($port, makeshortif($port['ifDescr']))."</td>
|
||||
<td width='100'>".$port['port_descr_speed']."</td>
|
||||
<td width='100'>".$port['port_descr_circuit'].'</td>
|
||||
<td>'.$port['port_descr_notes'].'</td>
|
||||
</tr>
|
||||
';
|
||||
|
||||
unset($customer_name);
|
||||
}
|
||||
|
||||
echo "<tr bgcolor='$bg_colour'><td></td><td colspan=6>";
|
||||
|
||||
$graph_array['type'] = 'customer_bits';
|
||||
$graph_array['height'] = '100';
|
||||
$graph_array['width'] = '220';
|
||||
$graph_array['to'] = $config['time']['now'];
|
||||
$graph_array['id'] = $customer['port_descr_descr'];
|
||||
|
||||
include 'includes/print-graphrow.inc.php';
|
||||
|
||||
echo '</tr>';
|
||||
}
|
||||
|
||||
echo '</table>';
|
||||
var grid = $("#customers").bootgrid({
|
||||
ajax: true,
|
||||
post: function ()
|
||||
{
|
||||
return {
|
||||
id: "customers",
|
||||
};
|
||||
},
|
||||
url: "/ajax_table.php"
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -174,7 +174,6 @@ echo '
|
||||
|
||||
if ($config['enable_syslog']) {
|
||||
$sql = "SELECT *, DATE_FORMAT(timestamp, '".$config['dateformat']['mysql']['compact']."') AS date from syslog ORDER BY timestamp DESC LIMIT 20";
|
||||
$query = mysql_query($sql);
|
||||
|
||||
echo '<div class="container-fluid">
|
||||
<div class="row">
|
||||
@@ -214,9 +213,6 @@ else {
|
||||
$alertquery = 'SELECT devices.device_id,name,state,time_logged FROM alert_log LEFT JOIN devices ON alert_log.device_id=devices.device_id LEFT JOIN alert_rules ON alert_log.rule_id=alert_rules.id RIGHT JOIN devices_perms ON alert_log.device_id = devices_perms.device_id AND devices_perms.user_id = '.$_SESSION['user_id'].' ORDER BY `time_logged` DESC LIMIT 0,15';
|
||||
}
|
||||
|
||||
$data = mysql_query($query);
|
||||
$alertdata = mysql_query($alertquery);
|
||||
|
||||
echo '<div class="container-fluid">
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
|
||||
@@ -68,7 +68,6 @@ echo ' </div>
|
||||
//From default.php - This code is not part of above license.
|
||||
if ($config['enable_syslog']) {
|
||||
$sql = "SELECT *, DATE_FORMAT(timestamp, '".$config['dateformat']['mysql']['compact']."') AS date from syslog ORDER BY seq DESC LIMIT 20";
|
||||
$query = mysql_query($sql);
|
||||
echo('<div class="container-fluid">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
@@ -106,8 +105,6 @@ else {
|
||||
P.device_id AND P.user_id = " . $_SESSION['user_id'] . " ORDER BY `datetime` DESC LIMIT 0,15";
|
||||
}
|
||||
|
||||
$data = mysql_query($query);
|
||||
|
||||
echo('<div class="container-fluid">
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
|
||||
@@ -261,7 +261,7 @@ function RunRules($device) {
|
||||
$extra = gzcompress(json_encode(array('contacts' => GetContacts($qry), 'rule'=>$qry)),9);
|
||||
if( dbInsert(array('state' => 1, 'device_id' => $device, 'rule_id' => $rule['id'], 'details' => $extra),'alert_log') ) {
|
||||
if( !dbUpdate(array('state' => 1, 'open' => 1),'alerts','device_id = ? && rule_id = ?', array($device,$rule['id'])) ) {
|
||||
dbInsert(array('state' => 1, 'device_id' => $device, 'rule_id' => $rule['id'], 'open' => 1),'alerts');
|
||||
dbInsert(array('state' => 1, 'device_id' => $device, 'rule_id' => $rule['id'], 'open' => 1,'alerted' => 0),'alerts');
|
||||
}
|
||||
echo " ALERT ";
|
||||
}
|
||||
@@ -274,7 +274,7 @@ function RunRules($device) {
|
||||
else {
|
||||
if( dbInsert(array('state' => 0, 'device_id' => $device, 'rule_id' => $rule['id']),'alert_log') ){
|
||||
if( !dbUpdate(array('state' => 0, 'open' => 1),'alerts','device_id = ? && rule_id = ?', array($device,$rule['id'])) ) {
|
||||
dbInsert(array('state' => 0, 'device_id' => $device, 'rule_id' => $rule['id'], 'open' => 1),'alerts');
|
||||
dbInsert(array('state' => 0, 'device_id' => $device, 'rule_id' => $rule['id'], 'open' => 1, 'alerted' => 0),'alerts');
|
||||
}
|
||||
echo " OK ";
|
||||
}
|
||||
|
||||
+7
-1
@@ -319,7 +319,13 @@ function truncate($substring, $max = 50, $rep = '...') {
|
||||
|
||||
function mres($string) {
|
||||
// short function wrapper because the real one is stupidly long and ugly. aesthetics.
|
||||
return mysql_real_escape_string($string);
|
||||
global $config, $database_link;
|
||||
if ($config['db']['extension'] == 'mysqli') {
|
||||
return mysqli_real_escape_string($database_link,$string);
|
||||
}
|
||||
else {
|
||||
return mysql_real_escape_string($string);
|
||||
}
|
||||
}
|
||||
|
||||
function getifhost($id) {
|
||||
|
||||
@@ -0,0 +1,554 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* dbFacile - A Database API that should have existed from the start
|
||||
* Version 0.4.3
|
||||
*
|
||||
* This code is covered by the MIT license http://en.wikipedia.org/wiki/MIT_License
|
||||
*
|
||||
* By Alan Szlosek from http://www.greaterscope.net/projects/dbFacile
|
||||
*
|
||||
* The non-OO version of dbFacile. It's a bit simplistic, but gives you the
|
||||
* really useful bits in non-class form.
|
||||
*
|
||||
* Usage
|
||||
* 1. Connect to MySQL as you normally would ... this code uses an existing connection
|
||||
* 2. Use dbFacile as you normally would, without the object context
|
||||
* 3. Oh, and dbFetchAll() is now dbFetchRows()
|
||||
*/
|
||||
|
||||
/*
|
||||
* Performs a query using the given string.
|
||||
* Used by the other _query functions.
|
||||
* */
|
||||
|
||||
|
||||
function dbQuery($sql, $parameters=array()) {
|
||||
global $fullSql, $debug, $sql_debug, $console_color;
|
||||
$fullSql = dbMakeQuery($sql, $parameters);
|
||||
if ($debug) {
|
||||
if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
|
||||
print $console_color->convert("\nSQL[%y".$fullSql.'%n] ');
|
||||
}
|
||||
else {
|
||||
$sql_debug[] = $fullSql;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
if($this->logFile)
|
||||
$time_start = microtime(true);
|
||||
*/
|
||||
|
||||
$result = mysql_query($fullSql);
|
||||
// sets $this->result
|
||||
/*
|
||||
if($this->logFile) {
|
||||
$time_end = microtime(true);
|
||||
fwrite($this->logFile, date('Y-m-d H:i:s') . "\n" . $fullSql . "\n" . number_format($time_end - $time_start, 8) . " seconds\n\n");
|
||||
}
|
||||
*/
|
||||
|
||||
if ($result === false && (error_reporting() & 1)) {
|
||||
// aye. this gets triggers on duplicate Contact insert
|
||||
// trigger_error('QDB - Error in query: ' . $fullSql . ' : ' . mysql_error(), E_USER_WARNING);
|
||||
}
|
||||
|
||||
return $result;
|
||||
|
||||
}//end dbQuery()
|
||||
|
||||
|
||||
/*
|
||||
* Passed an array and a table name, it attempts to insert the data into the table.
|
||||
* Check for boolean false to determine whether insert failed
|
||||
* */
|
||||
|
||||
|
||||
function dbInsert($data, $table) {
|
||||
global $fullSql;
|
||||
global $db_stats;
|
||||
// the following block swaps the parameters if they were given in the wrong order.
|
||||
// it allows the method to work for those that would rather it (or expect it to)
|
||||
// follow closer with SQL convention:
|
||||
// insert into the TABLE this DATA
|
||||
if (is_string($data) && is_array($table)) {
|
||||
$tmp = $data;
|
||||
$data = $table;
|
||||
$table = $tmp;
|
||||
// trigger_error('QDB - Parameters passed to insert() were in reverse order, but it has been allowed', E_USER_NOTICE);
|
||||
}
|
||||
|
||||
$sql = 'INSERT INTO `'.$table.'` (`'.implode('`,`', array_keys($data)).'`) VALUES ('.implode(',', dbPlaceHolders($data)).')';
|
||||
|
||||
$time_start = microtime(true);
|
||||
dbBeginTransaction();
|
||||
$result = dbQuery($sql, $data);
|
||||
if ($result) {
|
||||
$id = mysql_insert_id();
|
||||
dbCommitTransaction();
|
||||
// return $id;
|
||||
}
|
||||
else {
|
||||
if ($table != 'Contact') {
|
||||
trigger_error('QDB - Insert failed.', E_USER_WARNING);
|
||||
}
|
||||
|
||||
dbRollbackTransaction();
|
||||
// $id = false;
|
||||
}
|
||||
|
||||
// logfile($fullSql);
|
||||
$time_end = microtime(true);
|
||||
$db_stats['insert_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['insert']++;
|
||||
|
||||
return $id;
|
||||
|
||||
}//end dbInsert()
|
||||
|
||||
|
||||
/*
|
||||
* Passed an array and a table name, it attempts to insert the data into the table.
|
||||
* $data is an array (rows) of key value pairs. keys are fields. Rows need to have same fields.
|
||||
* Check for boolean false to determine whether insert failed
|
||||
* */
|
||||
|
||||
|
||||
function dbBulkInsert($data, $table) {
|
||||
global $db_stats;
|
||||
// the following block swaps the parameters if they were given in the wrong order.
|
||||
// it allows the method to work for those that would rather it (or expect it to)
|
||||
// follow closer with SQL convention:
|
||||
// insert into the TABLE this DATA
|
||||
if (is_string($data) && is_array($table)) {
|
||||
$tmp = $data;
|
||||
$data = $table;
|
||||
$table = $tmp;
|
||||
}
|
||||
if (count($data) === 0) {
|
||||
return false;
|
||||
}
|
||||
if (count($data[0]) === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$sql = 'INSERT INTO `'.$table.'` (`'.implode('`,`', array_keys($data[0])).'`) VALUES ';
|
||||
$values ='';
|
||||
|
||||
foreach ($data as $row) {
|
||||
if ($values != '') {
|
||||
$values .= ',';
|
||||
}
|
||||
$rowvalues='';
|
||||
foreach ($row as $key => $value) {
|
||||
if ($rowvalues != '') {
|
||||
$rowvalues .= ',';
|
||||
}
|
||||
$rowvalues .= "'".mres($value)."'";
|
||||
}
|
||||
$values .= "(".$rowvalues.")";
|
||||
}
|
||||
|
||||
$time_start = microtime(true);
|
||||
$result = dbQuery($sql.$values);
|
||||
|
||||
// logfile($fullSql);
|
||||
$time_end = microtime(true);
|
||||
$db_stats['insert_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['insert']++;
|
||||
|
||||
return $result;
|
||||
|
||||
}//end dbBulkInsert()
|
||||
|
||||
|
||||
/*
|
||||
* Passed an array, table name, WHERE clause, and placeholder parameters, it attempts to update a record.
|
||||
* Returns the number of affected rows
|
||||
* */
|
||||
|
||||
|
||||
function dbUpdate($data, $table, $where=null, $parameters=array()) {
|
||||
global $fullSql;
|
||||
global $db_stats;
|
||||
// the following block swaps the parameters if they were given in the wrong order.
|
||||
// it allows the method to work for those that would rather it (or expect it to)
|
||||
// follow closer with SQL convention:
|
||||
// update the TABLE with this DATA
|
||||
if (is_string($data) && is_array($table)) {
|
||||
$tmp = $data;
|
||||
$data = $table;
|
||||
$table = $tmp;
|
||||
// trigger_error('QDB - The first two parameters passed to update() were in reverse order, but it has been allowed', E_USER_NOTICE);
|
||||
}
|
||||
|
||||
// need field name and placeholder value
|
||||
// but how merge these field placeholders with actual $parameters array for the WHERE clause
|
||||
$sql = 'UPDATE `'.$table.'` set ';
|
||||
foreach ($data as $key => $value) {
|
||||
$sql .= '`'.$key.'` '.'=:'.$key.',';
|
||||
}
|
||||
|
||||
$sql = substr($sql, 0, -1);
|
||||
// strip off last comma
|
||||
if ($where) {
|
||||
$sql .= ' WHERE '.$where;
|
||||
$data = array_merge($data, $parameters);
|
||||
}
|
||||
|
||||
$time_start = microtime(true);
|
||||
if (dbQuery($sql, $data)) {
|
||||
$return = mysql_affected_rows();
|
||||
}
|
||||
else {
|
||||
// echo("$fullSql");
|
||||
trigger_error('QDB - Update failed.', E_USER_WARNING);
|
||||
$return = false;
|
||||
}
|
||||
|
||||
$time_end = microtime(true);
|
||||
$db_stats['update_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['update']++;
|
||||
|
||||
return $return;
|
||||
|
||||
}//end dbUpdate()
|
||||
|
||||
|
||||
function dbDelete($table, $where=null, $parameters=array()) {
|
||||
$sql = 'DELETE FROM `'.$table.'`';
|
||||
if ($where) {
|
||||
$sql .= ' WHERE '.$where;
|
||||
}
|
||||
|
||||
if (dbQuery($sql, $parameters)) {
|
||||
return mysql_affected_rows();
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
|
||||
}//end dbDelete()
|
||||
|
||||
|
||||
/*
|
||||
* Fetches all of the rows (associatively) from the last performed query.
|
||||
* Most other retrieval functions build off this
|
||||
* */
|
||||
|
||||
|
||||
function dbFetchRows($sql, $parameters=array()) {
|
||||
global $db_stats;
|
||||
|
||||
$time_start = microtime(true);
|
||||
$result = dbQuery($sql, $parameters);
|
||||
|
||||
if (mysql_num_rows($result) > 0) {
|
||||
$rows = array();
|
||||
while ($row = mysql_fetch_assoc($result)) {
|
||||
$rows[] = $row;
|
||||
}
|
||||
|
||||
mysql_free_result($result);
|
||||
return $rows;
|
||||
}
|
||||
|
||||
mysql_free_result($result);
|
||||
|
||||
$time_end = microtime(true);
|
||||
$db_stats['fetchrows_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['fetchrows']++;
|
||||
|
||||
// no records, thus return empty array
|
||||
// which should evaluate to false, and will prevent foreach notices/warnings
|
||||
return array();
|
||||
|
||||
}//end dbFetchRows()
|
||||
|
||||
|
||||
/*
|
||||
* This is intended to be the method used for large result sets.
|
||||
* It is intended to return an iterator, and act upon buffered data.
|
||||
* */
|
||||
|
||||
|
||||
function dbFetch($sql, $parameters=array()) {
|
||||
return dbFetchRows($sql, $parameters);
|
||||
/*
|
||||
// for now, don't do the iterator thing
|
||||
$result = dbQuery($sql, $parameters);
|
||||
if($result) {
|
||||
// return new iterator
|
||||
return new dbIterator($result);
|
||||
} else {
|
||||
return null; // ??
|
||||
}
|
||||
*/
|
||||
|
||||
}//end dbFetch()
|
||||
|
||||
|
||||
/*
|
||||
* Like fetch(), accepts any number of arguments
|
||||
* The first argument is an sprintf-ready query stringTypes
|
||||
* */
|
||||
|
||||
|
||||
function dbFetchRow($sql=null, $parameters=array()) {
|
||||
global $db_stats;
|
||||
|
||||
$time_start = microtime(true);
|
||||
$result = dbQuery($sql, $parameters);
|
||||
if ($result) {
|
||||
$row = mysql_fetch_assoc($result);
|
||||
mysql_free_result($result);
|
||||
$time_end = microtime(true);
|
||||
|
||||
$db_stats['fetchrow_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['fetchrow']++;
|
||||
|
||||
return $row;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
|
||||
$time_start = microtime(true);
|
||||
|
||||
}//end dbFetchRow()
|
||||
|
||||
|
||||
/*
|
||||
* Fetches the first call from the first row returned by the query
|
||||
* */
|
||||
|
||||
|
||||
function dbFetchCell($sql, $parameters=array()) {
|
||||
global $db_stats;
|
||||
$time_start = microtime(true);
|
||||
$row = dbFetchRow($sql, $parameters);
|
||||
if ($row) {
|
||||
return array_shift($row);
|
||||
// shift first field off first row
|
||||
}
|
||||
|
||||
$time_end = microtime(true);
|
||||
|
||||
$db_stats['fetchcell_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['fetchcell']++;
|
||||
|
||||
return null;
|
||||
|
||||
}//end dbFetchCell()
|
||||
|
||||
|
||||
/*
|
||||
* This method is quite different from fetchCell(), actually
|
||||
* It fetches one cell from each row and places all the values in 1 array
|
||||
* */
|
||||
|
||||
|
||||
function dbFetchColumn($sql, $parameters=array()) {
|
||||
global $db_stats;
|
||||
$time_start = microtime(true);
|
||||
$cells = array();
|
||||
foreach (dbFetch($sql, $parameters) as $row) {
|
||||
$cells[] = array_shift($row);
|
||||
}
|
||||
|
||||
$time_end = microtime(true);
|
||||
|
||||
$db_stats['fetchcol_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['fetchcol']++;
|
||||
|
||||
return $cells;
|
||||
|
||||
}//end dbFetchColumn()
|
||||
|
||||
|
||||
/*
|
||||
* Should be passed a query that fetches two fields
|
||||
* The first will become the array key
|
||||
* The second the key's value
|
||||
*/
|
||||
|
||||
|
||||
function dbFetchKeyValue($sql, $parameters=array()) {
|
||||
$data = array();
|
||||
foreach (dbFetch($sql, $parameters) as $row) {
|
||||
$key = array_shift($row);
|
||||
if (sizeof($row) == 1) {
|
||||
// if there were only 2 fields in the result
|
||||
// use the second for the value
|
||||
$data[$key] = array_shift($row);
|
||||
}
|
||||
else {
|
||||
// if more than 2 fields were fetched
|
||||
// use the array of the rest as the value
|
||||
$data[$key] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
|
||||
}//end dbFetchKeyValue()
|
||||
|
||||
|
||||
/*
|
||||
* This combines a query and parameter array into a final query string for execution
|
||||
* PDO drivers don't need to use this
|
||||
*/
|
||||
|
||||
|
||||
function dbMakeQuery($sql, $parameters) {
|
||||
// bypass extra logic if we have no parameters
|
||||
if (sizeof($parameters) == 0) {
|
||||
return $sql;
|
||||
}
|
||||
|
||||
$parameters = dbPrepareData($parameters);
|
||||
// separate the two types of parameters for easier handling
|
||||
$questionParams = array();
|
||||
$namedParams = array();
|
||||
foreach ($parameters as $key => $value) {
|
||||
if (is_numeric($key)) {
|
||||
$questionParams[] = $value;
|
||||
}
|
||||
else {
|
||||
$namedParams[':'.$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
// sort namedParams in reverse to stop substring squashing
|
||||
krsort($namedParams);
|
||||
|
||||
// split on question-mark and named placeholders
|
||||
$result = preg_split('/(\?|:[a-zA-Z0-9_-]+)/', $sql, -1, (PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE));
|
||||
|
||||
// every-other item in $result will be the placeholder that was found
|
||||
$query = '';
|
||||
$res_size = sizeof($result);
|
||||
for ($i = 0; $i < $res_size; $i += 2) {
|
||||
$query .= $result[$i];
|
||||
|
||||
$j = ($i + 1);
|
||||
if (array_key_exists($j, $result)) {
|
||||
$test = $result[$j];
|
||||
if ($test == '?') {
|
||||
$query .= array_shift($questionParams);
|
||||
}
|
||||
else {
|
||||
$query .= $namedParams[$test];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $query;
|
||||
|
||||
}//end dbMakeQuery()
|
||||
|
||||
|
||||
function dbPrepareData($data) {
|
||||
$values = array();
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
$escape = true;
|
||||
// don't quote or esc if value is an array, we treat it
|
||||
// as a "decorator" that tells us not to escape the
|
||||
// value contained in the array
|
||||
if (is_array($value) && !is_object($value)) {
|
||||
$escape = false;
|
||||
$value = array_shift($value);
|
||||
}
|
||||
|
||||
// it's not right to worry about invalid fields in this method because we may be operating on fields
|
||||
// that are aliases, or part of other tables through joins
|
||||
// if(!in_array($key, $columns)) // skip invalid fields
|
||||
// continue;
|
||||
if ($escape) {
|
||||
$values[$key] = "'".mysql_real_escape_string($value)."'";
|
||||
}
|
||||
else {
|
||||
$values[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $values;
|
||||
|
||||
}//end dbPrepareData()
|
||||
|
||||
|
||||
/*
|
||||
* Given a data array, this returns an array of placeholders
|
||||
* These may be question marks, or ":email" type
|
||||
*/
|
||||
|
||||
|
||||
function dbPlaceHolders($values) {
|
||||
$data = array();
|
||||
foreach ($values as $key => $value) {
|
||||
if (is_numeric($key)) {
|
||||
$data[] = '?';
|
||||
}
|
||||
else {
|
||||
$data[] = ':'.$key;
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
|
||||
}//end dbPlaceHolders()
|
||||
|
||||
|
||||
function dbBeginTransaction() {
|
||||
mysql_query('begin');
|
||||
|
||||
}//end dbBeginTransaction()
|
||||
|
||||
|
||||
function dbCommitTransaction() {
|
||||
mysql_query('commit');
|
||||
|
||||
}//end dbCommitTransaction()
|
||||
|
||||
|
||||
function dbRollbackTransaction() {
|
||||
mysql_query('rollback');
|
||||
|
||||
}//end dbRollbackTransaction()
|
||||
|
||||
|
||||
/*
|
||||
class dbIterator implements Iterator {
|
||||
private $result;
|
||||
private $i;
|
||||
|
||||
public function __construct($r) {
|
||||
$this->result = $r;
|
||||
$this->i = 0;
|
||||
}
|
||||
public function rewind() {
|
||||
mysql_data_seek($this->result, 0);
|
||||
$this->i = 0;
|
||||
}
|
||||
public function current() {
|
||||
$a = mysql_fetch_assoc($this->result);
|
||||
return $a;
|
||||
}
|
||||
public function key() {
|
||||
return $this->i;
|
||||
}
|
||||
public function next() {
|
||||
$this->i++;
|
||||
$a = mysql_data_seek($this->result, $this->i);
|
||||
if($a === false) {
|
||||
$this->i = 0;
|
||||
}
|
||||
return $a;
|
||||
}
|
||||
public function valid() {
|
||||
return ($this->current() !== false);
|
||||
}
|
||||
}
|
||||
*/
|
||||
@@ -0,0 +1,559 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* dbFacile - A Database API that should have existed from the start
|
||||
* Version 0.4.3
|
||||
*
|
||||
* This code is covered by the MIT license http://en.wikipedia.org/wiki/MIT_License
|
||||
*
|
||||
* By Alan Szlosek from http://www.greaterscope.net/projects/dbFacile
|
||||
*
|
||||
* The non-OO version of dbFacile. It's a bit simplistic, but gives you the
|
||||
* really useful bits in non-class form.
|
||||
*
|
||||
* Usage
|
||||
* 1. Connect to MySQL as you normally would ... this code uses an existing connection
|
||||
* 2. Use dbFacile as you normally would, without the object context
|
||||
* 3. Oh, and dbFetchAll() is now dbFetchRows()
|
||||
*/
|
||||
|
||||
/*
|
||||
* Performs a query using the given string.
|
||||
* Used by the other _query functions.
|
||||
* */
|
||||
|
||||
|
||||
function dbQuery($sql, $parameters=array()) {
|
||||
global $fullSql, $debug, $sql_debug, $console_color, $database_link;
|
||||
$fullSql = dbMakeQuery($sql, $parameters);
|
||||
if ($debug) {
|
||||
if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
|
||||
print $console_color->convert("\nSQL[%y".$fullSql.'%n] ');
|
||||
}
|
||||
else {
|
||||
$sql_debug[] = $fullSql;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
if($this->logFile)
|
||||
$time_start = microtime(true);
|
||||
*/
|
||||
|
||||
$result = mysqli_query($database_link, $fullSql);
|
||||
// sets $this->result
|
||||
/*
|
||||
if($this->logFile) {
|
||||
$time_end = microtime(true);
|
||||
fwrite($this->logFile, date('Y-m-d H:i:s') . "\n" . $fullSql . "\n" . number_format($time_end - $time_start, 8) . " seconds\n\n");
|
||||
}
|
||||
*/
|
||||
|
||||
if ($result === false && (error_reporting() & 1)) {
|
||||
// aye. this gets triggers on duplicate Contact insert
|
||||
// trigger_error('QDB - Error in query: ' . $fullSql . ' : ' . mysql_error(), E_USER_WARNING);
|
||||
}
|
||||
|
||||
return $result;
|
||||
|
||||
}//end dbQuery()
|
||||
|
||||
|
||||
/*
|
||||
* Passed an array and a table name, it attempts to insert the data into the table.
|
||||
* Check for boolean false to determine whether insert failed
|
||||
* */
|
||||
|
||||
|
||||
function dbInsert($data, $table) {
|
||||
global $fullSql, $database_link;
|
||||
global $db_stats;
|
||||
// the following block swaps the parameters if they were given in the wrong order.
|
||||
// it allows the method to work for those that would rather it (or expect it to)
|
||||
// follow closer with SQL convention:
|
||||
// insert into the TABLE this DATA
|
||||
if (is_string($data) && is_array($table)) {
|
||||
$tmp = $data;
|
||||
$data = $table;
|
||||
$table = $tmp;
|
||||
// trigger_error('QDB - Parameters passed to insert() were in reverse order, but it has been allowed', E_USER_NOTICE);
|
||||
}
|
||||
|
||||
$sql = 'INSERT INTO `'.$table.'` (`'.implode('`,`', array_keys($data)).'`) VALUES ('.implode(',', dbPlaceHolders($data)).')';
|
||||
|
||||
$time_start = microtime(true);
|
||||
dbBeginTransaction();
|
||||
$result = dbQuery($sql, $data);
|
||||
if ($result) {
|
||||
$id = mysqli_insert_id($database_link);
|
||||
dbCommitTransaction();
|
||||
// return $id;
|
||||
}
|
||||
else {
|
||||
if ($table != 'Contact') {
|
||||
trigger_error('QDB - Insert failed.', E_USER_WARNING);
|
||||
}
|
||||
|
||||
dbRollbackTransaction();
|
||||
// $id = false;
|
||||
}
|
||||
|
||||
// logfile($fullSql);
|
||||
$time_end = microtime(true);
|
||||
$db_stats['insert_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['insert']++;
|
||||
|
||||
return $id;
|
||||
|
||||
}//end dbInsert()
|
||||
|
||||
|
||||
/*
|
||||
* Passed an array and a table name, it attempts to insert the data into the table.
|
||||
* $data is an array (rows) of key value pairs. keys are fields. Rows need to have same fields.
|
||||
* Check for boolean false to determine whether insert failed
|
||||
* */
|
||||
|
||||
|
||||
function dbBulkInsert($data, $table) {
|
||||
global $db_stats;
|
||||
// the following block swaps the parameters if they were given in the wrong order.
|
||||
// it allows the method to work for those that would rather it (or expect it to)
|
||||
// follow closer with SQL convention:
|
||||
// insert into the TABLE this DATA
|
||||
if (is_string($data) && is_array($table)) {
|
||||
$tmp = $data;
|
||||
$data = $table;
|
||||
$table = $tmp;
|
||||
}
|
||||
if (count($data) === 0) {
|
||||
return false;
|
||||
}
|
||||
if (count($data[0]) === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$sql = 'INSERT INTO `'.$table.'` (`'.implode('`,`', array_keys($data[0])).'`) VALUES ';
|
||||
$values ='';
|
||||
|
||||
foreach ($data as $row) {
|
||||
if ($values != '') {
|
||||
$values .= ',';
|
||||
}
|
||||
$rowvalues='';
|
||||
foreach ($row as $key => $value) {
|
||||
if ($rowvalues != '') {
|
||||
$rowvalues .= ',';
|
||||
}
|
||||
$rowvalues .= "'".mres($value)."'";
|
||||
}
|
||||
$values .= "(".$rowvalues.")";
|
||||
}
|
||||
|
||||
$time_start = microtime(true);
|
||||
$result = dbQuery($sql.$values);
|
||||
|
||||
// logfile($fullSql);
|
||||
$time_end = microtime(true);
|
||||
$db_stats['insert_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['insert']++;
|
||||
|
||||
return $result;
|
||||
|
||||
}//end dbBulkInsert()
|
||||
|
||||
|
||||
/*
|
||||
* Passed an array, table name, WHERE clause, and placeholder parameters, it attempts to update a record.
|
||||
* Returns the number of affected rows
|
||||
* */
|
||||
|
||||
|
||||
function dbUpdate($data, $table, $where=null, $parameters=array()) {
|
||||
global $fullSql, $database_link;
|
||||
global $db_stats;
|
||||
// the following block swaps the parameters if they were given in the wrong order.
|
||||
// it allows the method to work for those that would rather it (or expect it to)
|
||||
// follow closer with SQL convention:
|
||||
// update the TABLE with this DATA
|
||||
if (is_string($data) && is_array($table)) {
|
||||
$tmp = $data;
|
||||
$data = $table;
|
||||
$table = $tmp;
|
||||
// trigger_error('QDB - The first two parameters passed to update() were in reverse order, but it has been allowed', E_USER_NOTICE);
|
||||
}
|
||||
|
||||
// need field name and placeholder value
|
||||
// but how merge these field placeholders with actual $parameters array for the WHERE clause
|
||||
$sql = 'UPDATE `'.$table.'` set ';
|
||||
foreach ($data as $key => $value) {
|
||||
$sql .= '`'.$key.'` '.'=:'.$key.',';
|
||||
}
|
||||
|
||||
$sql = substr($sql, 0, -1);
|
||||
// strip off last comma
|
||||
if ($where) {
|
||||
$sql .= ' WHERE '.$where;
|
||||
$data = array_merge($data, $parameters);
|
||||
}
|
||||
|
||||
$time_start = microtime(true);
|
||||
if (dbQuery($sql, $data)) {
|
||||
$return = mysqli_affected_rows($database_link);
|
||||
}
|
||||
else {
|
||||
// echo("$fullSql");
|
||||
trigger_error('QDB - Update failed.', E_USER_WARNING);
|
||||
$return = false;
|
||||
}
|
||||
|
||||
$time_end = microtime(true);
|
||||
$db_stats['update_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['update']++;
|
||||
|
||||
return $return;
|
||||
|
||||
}//end dbUpdate()
|
||||
|
||||
|
||||
function dbDelete($table, $where=null, $parameters=array()) {
|
||||
global $database_link;
|
||||
$sql = 'DELETE FROM `'.$table.'`';
|
||||
if ($where) {
|
||||
$sql .= ' WHERE '.$where;
|
||||
}
|
||||
|
||||
if (dbQuery($sql, $parameters)) {
|
||||
return mysqli_affected_rows($database_link);
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
|
||||
}//end dbDelete()
|
||||
|
||||
|
||||
/*
|
||||
* Fetches all of the rows (associatively) from the last performed query.
|
||||
* Most other retrieval functions build off this
|
||||
* */
|
||||
|
||||
|
||||
function dbFetchRows($sql, $parameters=array()) {
|
||||
global $db_stats;
|
||||
|
||||
$time_start = microtime(true);
|
||||
$result = dbQuery($sql, $parameters);
|
||||
|
||||
if (mysqli_num_rows($result) > 0) {
|
||||
$rows = array();
|
||||
while ($row = mysqli_fetch_assoc($result)) {
|
||||
$rows[] = $row;
|
||||
}
|
||||
|
||||
mysqli_free_result($result);
|
||||
return $rows;
|
||||
}
|
||||
|
||||
mysqli_free_result($result);
|
||||
|
||||
$time_end = microtime(true);
|
||||
$db_stats['fetchrows_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['fetchrows']++;
|
||||
|
||||
// no records, thus return empty array
|
||||
// which should evaluate to false, and will prevent foreach notices/warnings
|
||||
return array();
|
||||
|
||||
}//end dbFetchRows()
|
||||
|
||||
|
||||
/*
|
||||
* This is intended to be the method used for large result sets.
|
||||
* It is intended to return an iterator, and act upon buffered data.
|
||||
* */
|
||||
|
||||
|
||||
function dbFetch($sql, $parameters=array()) {
|
||||
return dbFetchRows($sql, $parameters);
|
||||
/*
|
||||
// for now, don't do the iterator thing
|
||||
$result = dbQuery($sql, $parameters);
|
||||
if($result) {
|
||||
// return new iterator
|
||||
return new dbIterator($result);
|
||||
} else {
|
||||
return null; // ??
|
||||
}
|
||||
*/
|
||||
|
||||
}//end dbFetch()
|
||||
|
||||
|
||||
/*
|
||||
* Like fetch(), accepts any number of arguments
|
||||
* The first argument is an sprintf-ready query stringTypes
|
||||
* */
|
||||
|
||||
|
||||
function dbFetchRow($sql=null, $parameters=array()) {
|
||||
global $db_stats;
|
||||
|
||||
$time_start = microtime(true);
|
||||
$result = dbQuery($sql, $parameters);
|
||||
if ($result) {
|
||||
$row = mysqli_fetch_assoc($result);
|
||||
mysqli_free_result($result);
|
||||
$time_end = microtime(true);
|
||||
|
||||
$db_stats['fetchrow_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['fetchrow']++;
|
||||
|
||||
return $row;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
|
||||
$time_start = microtime(true);
|
||||
|
||||
}//end dbFetchRow()
|
||||
|
||||
|
||||
/*
|
||||
* Fetches the first call from the first row returned by the query
|
||||
* */
|
||||
|
||||
|
||||
function dbFetchCell($sql, $parameters=array()) {
|
||||
global $db_stats;
|
||||
$time_start = microtime(true);
|
||||
$row = dbFetchRow($sql, $parameters);
|
||||
if ($row) {
|
||||
return array_shift($row);
|
||||
// shift first field off first row
|
||||
}
|
||||
|
||||
$time_end = microtime(true);
|
||||
|
||||
$db_stats['fetchcell_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['fetchcell']++;
|
||||
|
||||
return null;
|
||||
|
||||
}//end dbFetchCell()
|
||||
|
||||
|
||||
/*
|
||||
* This method is quite different from fetchCell(), actually
|
||||
* It fetches one cell from each row and places all the values in 1 array
|
||||
* */
|
||||
|
||||
|
||||
function dbFetchColumn($sql, $parameters=array()) {
|
||||
global $db_stats;
|
||||
$time_start = microtime(true);
|
||||
$cells = array();
|
||||
foreach (dbFetch($sql, $parameters) as $row) {
|
||||
$cells[] = array_shift($row);
|
||||
}
|
||||
|
||||
$time_end = microtime(true);
|
||||
|
||||
$db_stats['fetchcol_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['fetchcol']++;
|
||||
|
||||
return $cells;
|
||||
|
||||
}//end dbFetchColumn()
|
||||
|
||||
|
||||
/*
|
||||
* Should be passed a query that fetches two fields
|
||||
* The first will become the array key
|
||||
* The second the key's value
|
||||
*/
|
||||
|
||||
|
||||
function dbFetchKeyValue($sql, $parameters=array()) {
|
||||
$data = array();
|
||||
foreach (dbFetch($sql, $parameters) as $row) {
|
||||
$key = array_shift($row);
|
||||
if (sizeof($row) == 1) {
|
||||
// if there were only 2 fields in the result
|
||||
// use the second for the value
|
||||
$data[$key] = array_shift($row);
|
||||
}
|
||||
else {
|
||||
// if more than 2 fields were fetched
|
||||
// use the array of the rest as the value
|
||||
$data[$key] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
|
||||
}//end dbFetchKeyValue()
|
||||
|
||||
|
||||
/*
|
||||
* This combines a query and parameter array into a final query string for execution
|
||||
* PDO drivers don't need to use this
|
||||
*/
|
||||
|
||||
|
||||
function dbMakeQuery($sql, $parameters) {
|
||||
// bypass extra logic if we have no parameters
|
||||
if (sizeof($parameters) == 0) {
|
||||
return $sql;
|
||||
}
|
||||
|
||||
$parameters = dbPrepareData($parameters);
|
||||
// separate the two types of parameters for easier handling
|
||||
$questionParams = array();
|
||||
$namedParams = array();
|
||||
foreach ($parameters as $key => $value) {
|
||||
if (is_numeric($key)) {
|
||||
$questionParams[] = $value;
|
||||
}
|
||||
else {
|
||||
$namedParams[':'.$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
// sort namedParams in reverse to stop substring squashing
|
||||
krsort($namedParams);
|
||||
|
||||
// split on question-mark and named placeholders
|
||||
$result = preg_split('/(\?|:[a-zA-Z0-9_-]+)/', $sql, -1, (PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE));
|
||||
|
||||
// every-other item in $result will be the placeholder that was found
|
||||
$query = '';
|
||||
$res_size = sizeof($result);
|
||||
for ($i = 0; $i < $res_size; $i += 2) {
|
||||
$query .= $result[$i];
|
||||
|
||||
$j = ($i + 1);
|
||||
if (array_key_exists($j, $result)) {
|
||||
$test = $result[$j];
|
||||
if ($test == '?') {
|
||||
$query .= array_shift($questionParams);
|
||||
}
|
||||
else {
|
||||
$query .= $namedParams[$test];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $query;
|
||||
|
||||
}//end dbMakeQuery()
|
||||
|
||||
|
||||
function dbPrepareData($data) {
|
||||
global $database_link;
|
||||
$values = array();
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
$escape = true;
|
||||
// don't quote or esc if value is an array, we treat it
|
||||
// as a "decorator" that tells us not to escape the
|
||||
// value contained in the array
|
||||
if (is_array($value) && !is_object($value)) {
|
||||
$escape = false;
|
||||
$value = array_shift($value);
|
||||
}
|
||||
|
||||
// it's not right to worry about invalid fields in this method because we may be operating on fields
|
||||
// that are aliases, or part of other tables through joins
|
||||
// if(!in_array($key, $columns)) // skip invalid fields
|
||||
// continue;
|
||||
if ($escape) {
|
||||
$values[$key] = "'".mysqli_real_escape_string($database_link,$value)."'";
|
||||
}
|
||||
else {
|
||||
$values[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $values;
|
||||
|
||||
}//end dbPrepareData()
|
||||
|
||||
|
||||
/*
|
||||
* Given a data array, this returns an array of placeholders
|
||||
* These may be question marks, or ":email" type
|
||||
*/
|
||||
|
||||
|
||||
function dbPlaceHolders($values) {
|
||||
$data = array();
|
||||
foreach ($values as $key => $value) {
|
||||
if (is_numeric($key)) {
|
||||
$data[] = '?';
|
||||
}
|
||||
else {
|
||||
$data[] = ':'.$key;
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
|
||||
}//end dbPlaceHolders()
|
||||
|
||||
|
||||
function dbBeginTransaction() {
|
||||
global $database_link;
|
||||
mysqli_query($database_link, 'begin');
|
||||
|
||||
}//end dbBeginTransaction()
|
||||
|
||||
|
||||
function dbCommitTransaction() {
|
||||
global $database_link;
|
||||
mysqli_query($database_link, 'commit');
|
||||
|
||||
}//end dbCommitTransaction()
|
||||
|
||||
|
||||
function dbRollbackTransaction() {
|
||||
global $database_link;
|
||||
mysqli_query($database_link, 'rollback');
|
||||
|
||||
}//end dbRollbackTransaction()
|
||||
|
||||
|
||||
/*
|
||||
class dbIterator implements Iterator {
|
||||
private $result;
|
||||
private $i;
|
||||
|
||||
public function __construct($r) {
|
||||
$this->result = $r;
|
||||
$this->i = 0;
|
||||
}
|
||||
public function rewind() {
|
||||
mysql_data_seek($this->result, 0);
|
||||
$this->i = 0;
|
||||
}
|
||||
public function current() {
|
||||
$a = mysql_fetch_assoc($this->result);
|
||||
return $a;
|
||||
}
|
||||
public function key() {
|
||||
return $this->i;
|
||||
}
|
||||
public function next() {
|
||||
$this->i++;
|
||||
$a = mysql_data_seek($this->result, $this->i);
|
||||
if($a === false) {
|
||||
$this->i = 0;
|
||||
}
|
||||
return $a;
|
||||
}
|
||||
public function valid() {
|
||||
return ($this->current() !== false);
|
||||
}
|
||||
}
|
||||
*/
|
||||
+7
-552
@@ -1,554 +1,9 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* dbFacile - A Database API that should have existed from the start
|
||||
* Version 0.4.3
|
||||
*
|
||||
* This code is covered by the MIT license http://en.wikipedia.org/wiki/MIT_License
|
||||
*
|
||||
* By Alan Szlosek from http://www.greaterscope.net/projects/dbFacile
|
||||
*
|
||||
* The non-OO version of dbFacile. It's a bit simplistic, but gives you the
|
||||
* really useful bits in non-class form.
|
||||
*
|
||||
* Usage
|
||||
* 1. Connect to MySQL as you normally would ... this code uses an existing connection
|
||||
* 2. Use dbFacile as you normally would, without the object context
|
||||
* 3. Oh, and dbFetchAll() is now dbFetchRows()
|
||||
*/
|
||||
|
||||
/*
|
||||
* Performs a query using the given string.
|
||||
* Used by the other _query functions.
|
||||
* */
|
||||
|
||||
|
||||
function dbQuery($sql, $parameters=array()) {
|
||||
global $fullSql, $debug, $sql_debug, $console_color;
|
||||
$fullSql = dbMakeQuery($sql, $parameters);
|
||||
if ($debug) {
|
||||
if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
|
||||
print $console_color->convert("\nSQL[%y".$fullSql.'%n] ');
|
||||
}
|
||||
else {
|
||||
$sql_debug[] = $fullSql;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
if($this->logFile)
|
||||
$time_start = microtime(true);
|
||||
*/
|
||||
|
||||
$result = mysql_query($fullSql);
|
||||
// sets $this->result
|
||||
/*
|
||||
if($this->logFile) {
|
||||
$time_end = microtime(true);
|
||||
fwrite($this->logFile, date('Y-m-d H:i:s') . "\n" . $fullSql . "\n" . number_format($time_end - $time_start, 8) . " seconds\n\n");
|
||||
}
|
||||
*/
|
||||
|
||||
if ($result === false && (error_reporting() & 1)) {
|
||||
// aye. this gets triggers on duplicate Contact insert
|
||||
// trigger_error('QDB - Error in query: ' . $fullSql . ' : ' . mysql_error(), E_USER_WARNING);
|
||||
}
|
||||
|
||||
return $result;
|
||||
|
||||
}//end dbQuery()
|
||||
|
||||
|
||||
/*
|
||||
* Passed an array and a table name, it attempts to insert the data into the table.
|
||||
* Check for boolean false to determine whether insert failed
|
||||
* */
|
||||
|
||||
|
||||
function dbInsert($data, $table) {
|
||||
global $fullSql;
|
||||
global $db_stats;
|
||||
// the following block swaps the parameters if they were given in the wrong order.
|
||||
// it allows the method to work for those that would rather it (or expect it to)
|
||||
// follow closer with SQL convention:
|
||||
// insert into the TABLE this DATA
|
||||
if (is_string($data) && is_array($table)) {
|
||||
$tmp = $data;
|
||||
$data = $table;
|
||||
$table = $tmp;
|
||||
// trigger_error('QDB - Parameters passed to insert() were in reverse order, but it has been allowed', E_USER_NOTICE);
|
||||
}
|
||||
|
||||
$sql = 'INSERT INTO `'.$table.'` (`'.implode('`,`', array_keys($data)).'`) VALUES ('.implode(',', dbPlaceHolders($data)).')';
|
||||
|
||||
$time_start = microtime(true);
|
||||
dbBeginTransaction();
|
||||
$result = dbQuery($sql, $data);
|
||||
if ($result) {
|
||||
$id = mysql_insert_id();
|
||||
dbCommitTransaction();
|
||||
// return $id;
|
||||
}
|
||||
else {
|
||||
if ($table != 'Contact') {
|
||||
trigger_error('QDB - Insert failed.', E_USER_WARNING);
|
||||
}
|
||||
|
||||
dbRollbackTransaction();
|
||||
// $id = false;
|
||||
}
|
||||
|
||||
// logfile($fullSql);
|
||||
$time_end = microtime(true);
|
||||
$db_stats['insert_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['insert']++;
|
||||
|
||||
return $id;
|
||||
|
||||
}//end dbInsert()
|
||||
|
||||
|
||||
/*
|
||||
* Passed an array and a table name, it attempts to insert the data into the table.
|
||||
* $data is an array (rows) of key value pairs. keys are fields. Rows need to have same fields.
|
||||
* Check for boolean false to determine whether insert failed
|
||||
* */
|
||||
|
||||
|
||||
function dbBulkInsert($data, $table) {
|
||||
global $db_stats;
|
||||
// the following block swaps the parameters if they were given in the wrong order.
|
||||
// it allows the method to work for those that would rather it (or expect it to)
|
||||
// follow closer with SQL convention:
|
||||
// insert into the TABLE this DATA
|
||||
if (is_string($data) && is_array($table)) {
|
||||
$tmp = $data;
|
||||
$data = $table;
|
||||
$table = $tmp;
|
||||
}
|
||||
if (count($data) === 0) {
|
||||
return false;
|
||||
}
|
||||
if (count($data[0]) === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$sql = 'INSERT INTO `'.$table.'` (`'.implode('`,`', array_keys($data[0])).'`) VALUES ';
|
||||
$values ='';
|
||||
|
||||
foreach ($data as $row) {
|
||||
if ($values != '') {
|
||||
$values .= ',';
|
||||
}
|
||||
$rowvalues='';
|
||||
foreach ($row as $key => $value) {
|
||||
if ($rowvalues != '') {
|
||||
$rowvalues .= ',';
|
||||
}
|
||||
$rowvalues .= "'".mres($value)."'";
|
||||
}
|
||||
$values .= "(".$rowvalues.")";
|
||||
}
|
||||
|
||||
$time_start = microtime(true);
|
||||
$result = dbQuery($sql.$values);
|
||||
|
||||
// logfile($fullSql);
|
||||
$time_end = microtime(true);
|
||||
$db_stats['insert_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['insert']++;
|
||||
|
||||
return $result;
|
||||
|
||||
}//end dbBulkInsert()
|
||||
|
||||
|
||||
/*
|
||||
* Passed an array, table name, WHERE clause, and placeholder parameters, it attempts to update a record.
|
||||
* Returns the number of affected rows
|
||||
* */
|
||||
|
||||
|
||||
function dbUpdate($data, $table, $where=null, $parameters=array()) {
|
||||
global $fullSql;
|
||||
global $db_stats;
|
||||
// the following block swaps the parameters if they were given in the wrong order.
|
||||
// it allows the method to work for those that would rather it (or expect it to)
|
||||
// follow closer with SQL convention:
|
||||
// update the TABLE with this DATA
|
||||
if (is_string($data) && is_array($table)) {
|
||||
$tmp = $data;
|
||||
$data = $table;
|
||||
$table = $tmp;
|
||||
// trigger_error('QDB - The first two parameters passed to update() were in reverse order, but it has been allowed', E_USER_NOTICE);
|
||||
}
|
||||
|
||||
// need field name and placeholder value
|
||||
// but how merge these field placeholders with actual $parameters array for the WHERE clause
|
||||
$sql = 'UPDATE `'.$table.'` set ';
|
||||
foreach ($data as $key => $value) {
|
||||
$sql .= '`'.$key.'` '.'=:'.$key.',';
|
||||
}
|
||||
|
||||
$sql = substr($sql, 0, -1);
|
||||
// strip off last comma
|
||||
if ($where) {
|
||||
$sql .= ' WHERE '.$where;
|
||||
$data = array_merge($data, $parameters);
|
||||
}
|
||||
|
||||
$time_start = microtime(true);
|
||||
if (dbQuery($sql, $data)) {
|
||||
$return = mysql_affected_rows();
|
||||
}
|
||||
else {
|
||||
// echo("$fullSql");
|
||||
trigger_error('QDB - Update failed.', E_USER_WARNING);
|
||||
$return = false;
|
||||
}
|
||||
|
||||
$time_end = microtime(true);
|
||||
$db_stats['update_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['update']++;
|
||||
|
||||
return $return;
|
||||
|
||||
}//end dbUpdate()
|
||||
|
||||
|
||||
function dbDelete($table, $where=null, $parameters=array()) {
|
||||
$sql = 'DELETE FROM `'.$table.'`';
|
||||
if ($where) {
|
||||
$sql .= ' WHERE '.$where;
|
||||
}
|
||||
|
||||
if (dbQuery($sql, $parameters)) {
|
||||
return mysql_affected_rows();
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
|
||||
}//end dbDelete()
|
||||
|
||||
|
||||
/*
|
||||
* Fetches all of the rows (associatively) from the last performed query.
|
||||
* Most other retrieval functions build off this
|
||||
* */
|
||||
|
||||
|
||||
function dbFetchRows($sql, $parameters=array()) {
|
||||
global $db_stats;
|
||||
|
||||
$time_start = microtime(true);
|
||||
$result = dbQuery($sql, $parameters);
|
||||
|
||||
if (mysql_num_rows($result) > 0) {
|
||||
$rows = array();
|
||||
while ($row = mysql_fetch_assoc($result)) {
|
||||
$rows[] = $row;
|
||||
}
|
||||
|
||||
mysql_free_result($result);
|
||||
return $rows;
|
||||
}
|
||||
|
||||
mysql_free_result($result);
|
||||
|
||||
$time_end = microtime(true);
|
||||
$db_stats['fetchrows_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['fetchrows']++;
|
||||
|
||||
// no records, thus return empty array
|
||||
// which should evaluate to false, and will prevent foreach notices/warnings
|
||||
return array();
|
||||
|
||||
}//end dbFetchRows()
|
||||
|
||||
|
||||
/*
|
||||
* This is intended to be the method used for large result sets.
|
||||
* It is intended to return an iterator, and act upon buffered data.
|
||||
* */
|
||||
|
||||
|
||||
function dbFetch($sql, $parameters=array()) {
|
||||
return dbFetchRows($sql, $parameters);
|
||||
/*
|
||||
// for now, don't do the iterator thing
|
||||
$result = dbQuery($sql, $parameters);
|
||||
if($result) {
|
||||
// return new iterator
|
||||
return new dbIterator($result);
|
||||
} else {
|
||||
return null; // ??
|
||||
}
|
||||
*/
|
||||
|
||||
}//end dbFetch()
|
||||
|
||||
|
||||
/*
|
||||
* Like fetch(), accepts any number of arguments
|
||||
* The first argument is an sprintf-ready query stringTypes
|
||||
* */
|
||||
|
||||
|
||||
function dbFetchRow($sql=null, $parameters=array()) {
|
||||
global $db_stats;
|
||||
|
||||
$time_start = microtime(true);
|
||||
$result = dbQuery($sql, $parameters);
|
||||
if ($result) {
|
||||
$row = mysql_fetch_assoc($result);
|
||||
mysql_free_result($result);
|
||||
$time_end = microtime(true);
|
||||
|
||||
$db_stats['fetchrow_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['fetchrow']++;
|
||||
|
||||
return $row;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
|
||||
$time_start = microtime(true);
|
||||
|
||||
}//end dbFetchRow()
|
||||
|
||||
|
||||
/*
|
||||
* Fetches the first call from the first row returned by the query
|
||||
* */
|
||||
|
||||
|
||||
function dbFetchCell($sql, $parameters=array()) {
|
||||
global $db_stats;
|
||||
$time_start = microtime(true);
|
||||
$row = dbFetchRow($sql, $parameters);
|
||||
if ($row) {
|
||||
return array_shift($row);
|
||||
// shift first field off first row
|
||||
}
|
||||
|
||||
$time_end = microtime(true);
|
||||
|
||||
$db_stats['fetchcell_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['fetchcell']++;
|
||||
|
||||
return null;
|
||||
|
||||
}//end dbFetchCell()
|
||||
|
||||
|
||||
/*
|
||||
* This method is quite different from fetchCell(), actually
|
||||
* It fetches one cell from each row and places all the values in 1 array
|
||||
* */
|
||||
|
||||
|
||||
function dbFetchColumn($sql, $parameters=array()) {
|
||||
global $db_stats;
|
||||
$time_start = microtime(true);
|
||||
$cells = array();
|
||||
foreach (dbFetch($sql, $parameters) as $row) {
|
||||
$cells[] = array_shift($row);
|
||||
}
|
||||
|
||||
$time_end = microtime(true);
|
||||
|
||||
$db_stats['fetchcol_sec'] += number_format(($time_end - $time_start), 8);
|
||||
$db_stats['fetchcol']++;
|
||||
|
||||
return $cells;
|
||||
|
||||
}//end dbFetchColumn()
|
||||
|
||||
|
||||
/*
|
||||
* Should be passed a query that fetches two fields
|
||||
* The first will become the array key
|
||||
* The second the key's value
|
||||
*/
|
||||
|
||||
|
||||
function dbFetchKeyValue($sql, $parameters=array()) {
|
||||
$data = array();
|
||||
foreach (dbFetch($sql, $parameters) as $row) {
|
||||
$key = array_shift($row);
|
||||
if (sizeof($row) == 1) {
|
||||
// if there were only 2 fields in the result
|
||||
// use the second for the value
|
||||
$data[$key] = array_shift($row);
|
||||
}
|
||||
else {
|
||||
// if more than 2 fields were fetched
|
||||
// use the array of the rest as the value
|
||||
$data[$key] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
|
||||
}//end dbFetchKeyValue()
|
||||
|
||||
|
||||
/*
|
||||
* This combines a query and parameter array into a final query string for execution
|
||||
* PDO drivers don't need to use this
|
||||
*/
|
||||
|
||||
|
||||
function dbMakeQuery($sql, $parameters) {
|
||||
// bypass extra logic if we have no parameters
|
||||
if (sizeof($parameters) == 0) {
|
||||
return $sql;
|
||||
}
|
||||
|
||||
$parameters = dbPrepareData($parameters);
|
||||
// separate the two types of parameters for easier handling
|
||||
$questionParams = array();
|
||||
$namedParams = array();
|
||||
foreach ($parameters as $key => $value) {
|
||||
if (is_numeric($key)) {
|
||||
$questionParams[] = $value;
|
||||
}
|
||||
else {
|
||||
$namedParams[':'.$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
// sort namedParams in reverse to stop substring squashing
|
||||
krsort($namedParams);
|
||||
|
||||
// split on question-mark and named placeholders
|
||||
$result = preg_split('/(\?|:[a-zA-Z0-9_-]+)/', $sql, -1, (PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE));
|
||||
|
||||
// every-other item in $result will be the placeholder that was found
|
||||
$query = '';
|
||||
$res_size = sizeof($result);
|
||||
for ($i = 0; $i < $res_size; $i += 2) {
|
||||
$query .= $result[$i];
|
||||
|
||||
$j = ($i + 1);
|
||||
if (array_key_exists($j, $result)) {
|
||||
$test = $result[$j];
|
||||
if ($test == '?') {
|
||||
$query .= array_shift($questionParams);
|
||||
}
|
||||
else {
|
||||
$query .= $namedParams[$test];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $query;
|
||||
|
||||
}//end dbMakeQuery()
|
||||
|
||||
|
||||
function dbPrepareData($data) {
|
||||
$values = array();
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
$escape = true;
|
||||
// don't quote or esc if value is an array, we treat it
|
||||
// as a "decorator" that tells us not to escape the
|
||||
// value contained in the array
|
||||
if (is_array($value) && !is_object($value)) {
|
||||
$escape = false;
|
||||
$value = array_shift($value);
|
||||
}
|
||||
|
||||
// it's not right to worry about invalid fields in this method because we may be operating on fields
|
||||
// that are aliases, or part of other tables through joins
|
||||
// if(!in_array($key, $columns)) // skip invalid fields
|
||||
// continue;
|
||||
if ($escape) {
|
||||
$values[$key] = "'".mysql_real_escape_string($value)."'";
|
||||
}
|
||||
else {
|
||||
$values[$key] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
return $values;
|
||||
|
||||
}//end dbPrepareData()
|
||||
|
||||
|
||||
/*
|
||||
* Given a data array, this returns an array of placeholders
|
||||
* These may be question marks, or ":email" type
|
||||
*/
|
||||
|
||||
|
||||
function dbPlaceHolders($values) {
|
||||
$data = array();
|
||||
foreach ($values as $key => $value) {
|
||||
if (is_numeric($key)) {
|
||||
$data[] = '?';
|
||||
}
|
||||
else {
|
||||
$data[] = ':'.$key;
|
||||
}
|
||||
}
|
||||
|
||||
return $data;
|
||||
|
||||
}//end dbPlaceHolders()
|
||||
|
||||
|
||||
function dbBeginTransaction() {
|
||||
mysql_query('begin');
|
||||
|
||||
}//end dbBeginTransaction()
|
||||
|
||||
|
||||
function dbCommitTransaction() {
|
||||
mysql_query('commit');
|
||||
|
||||
}//end dbCommitTransaction()
|
||||
|
||||
|
||||
function dbRollbackTransaction() {
|
||||
mysql_query('rollback');
|
||||
|
||||
}//end dbRollbackTransaction()
|
||||
|
||||
|
||||
/*
|
||||
class dbIterator implements Iterator {
|
||||
private $result;
|
||||
private $i;
|
||||
|
||||
public function __construct($r) {
|
||||
$this->result = $r;
|
||||
$this->i = 0;
|
||||
}
|
||||
public function rewind() {
|
||||
mysql_data_seek($this->result, 0);
|
||||
$this->i = 0;
|
||||
}
|
||||
public function current() {
|
||||
$a = mysql_fetch_assoc($this->result);
|
||||
return $a;
|
||||
}
|
||||
public function key() {
|
||||
return $this->i;
|
||||
}
|
||||
public function next() {
|
||||
$this->i++;
|
||||
$a = mysql_data_seek($this->result, $this->i);
|
||||
if($a === false) {
|
||||
$this->i = 0;
|
||||
}
|
||||
return $a;
|
||||
}
|
||||
public function valid() {
|
||||
return ($this->current() !== false);
|
||||
}
|
||||
}
|
||||
*/
|
||||
if (file_exists($config['install_dir'].'/includes/dbFacile.'.$config['db']['extension'].'.php')) {
|
||||
require_once $config['install_dir'].'/includes/dbFacile.'.$config['db']['extension'].'.php';
|
||||
}
|
||||
else {
|
||||
echo $config['db']['extension'] . " extension not found\n";
|
||||
exit;
|
||||
}
|
||||
|
||||
@@ -43,6 +43,9 @@ $config['temp_dir'] = '/tmp';
|
||||
$config['install_dir'] = '/opt/'.$config['project_id'];
|
||||
$config['log_dir'] = $config['install_dir'].'/logs';
|
||||
|
||||
// MySQL extension to use
|
||||
$config['db']['extension'] = 'mysql';//mysql and mysqli available
|
||||
|
||||
// What is my own hostname (used to identify this host in its own database)
|
||||
$config['own_hostname'] = 'localhost';
|
||||
|
||||
@@ -53,7 +56,6 @@ $config['fping_options']['retries'] = 3;
|
||||
$config['fping_options']['timeout'] = 500;
|
||||
$config['fping_options']['count'] = 3;
|
||||
$config['fping_options']['millisec'] = 20;
|
||||
$config['fping6'] = '/usr/bin/fping6';
|
||||
$config['snmpwalk'] = '/usr/bin/snmpwalk';
|
||||
$config['snmpget'] = '/usr/bin/snmpget';
|
||||
$config['snmpbulkwalk'] = '/usr/bin/snmpbulkwalk';
|
||||
@@ -65,10 +67,7 @@ $config['nagios_plugins'] = '/usr/lib/nagios/plugins';
|
||||
$config['ipmitool'] = '/usr/bin/ipmitool';
|
||||
$config['virsh'] = '/usr/bin/virsh';
|
||||
$config['dot'] = '/usr/bin/dot';
|
||||
$config['unflatten'] = '/usr/bin/unflatten';
|
||||
$config['neato'] = '/usr/bin/neato';
|
||||
$config['sfdp'] = '/usr/bin/sfdp';
|
||||
$config['svn'] = '/usr/bin/svn';
|
||||
|
||||
// Memcached - Keep immediate statistics
|
||||
$config['memcached']['enable'] = false;
|
||||
@@ -102,7 +101,6 @@ if (isset($_SERVER['SERVER_NAME']) && isset($_SERVER['SERVER_PORT'])) {
|
||||
}
|
||||
}
|
||||
|
||||
$config['project_url'] = 'https://github.com/librenms/';
|
||||
$config['project_home'] = 'http://www.librenms.org/';
|
||||
$config['project_issues'] = 'https://github.com/librenms/librenms/issues';
|
||||
$config['site_style'] = 'light';
|
||||
@@ -110,7 +108,6 @@ $config['site_style'] = 'light';
|
||||
$config['stylesheet'] = 'css/styles.css';
|
||||
$config['mono_font'] = 'DejaVuSansMono';
|
||||
$config['favicon'] = '';
|
||||
$config['header_color'] = '#1F334E';
|
||||
$config['page_refresh'] = '300';
|
||||
// Refresh the page every xx seconds, 0 to disable
|
||||
$config['front_page'] = 'pages/front/default.php';
|
||||
@@ -383,14 +380,6 @@ $config['version_check'] = 0;
|
||||
// Poller/Discovery Modules
|
||||
$config['enable_bgp'] = 1;
|
||||
// Enable BGP session collection and display
|
||||
$config['enable_rip'] = 1;
|
||||
// Enable RIP session collection and display
|
||||
$config['enable_ospf'] = 1;
|
||||
// Enable OSPF session collection and display
|
||||
$config['enable_isis'] = 1;
|
||||
// Enable ISIS session collection and display
|
||||
$config['enable_eigrp'] = 1;
|
||||
// Enable EIGRP session collection and display
|
||||
$config['enable_syslog'] = 0;
|
||||
// Enable Syslog
|
||||
$config['enable_inventory'] = 1;
|
||||
@@ -406,8 +395,6 @@ $config['enable_sla'] = 0;
|
||||
// Ports extension modules
|
||||
$config['port_descr_parser'] = 'includes/port-descr-parser.inc.php';
|
||||
// Parse port descriptions into fields
|
||||
$config['enable_ports_Xbcmc'] = 1;
|
||||
// Enable ifXEntry broadcast/multicast
|
||||
$config['enable_ports_etherlike'] = 0;
|
||||
// Enable Polling EtherLike-MIB (doubles interface processing time)
|
||||
$config['enable_ports_junoseatmvp'] = 0;
|
||||
@@ -491,8 +478,6 @@ $config['bad_if_regexp'][] = '/^sl[0-9]/';
|
||||
// Rewrite Interfaces
|
||||
$config['rewrite_if_regexp']['/^cpu interface/'] = 'Mgmt';
|
||||
|
||||
$config['processor_filter'][] = 'An electronic chip that makes the computer work.';
|
||||
|
||||
$config['ignore_mount_removable'] = 1;
|
||||
// Ignore removable disk storage
|
||||
$config['ignore_mount_network'] = 1;
|
||||
@@ -592,7 +577,6 @@ $config['ignore_mount_removable'] = 1;
|
||||
$config['ignore_mount_network'] = 1;
|
||||
// Ignore network mounted storage
|
||||
// Syslog Settings
|
||||
$config['syslog_age'] = '1 month';
|
||||
// Entries older than this will be removed
|
||||
$config['syslog_filter'][] = 'last message repeated';
|
||||
$config['syslog_filter'][] = 'Connection from UDP: [';
|
||||
|
||||
@@ -5,14 +5,30 @@ require_once $config['install_dir'].'/includes/dbFacile.php';
|
||||
require_once $config['install_dir'].'/includes/mergecnf.inc.php';
|
||||
|
||||
// Connect to database
|
||||
$database_link = mysql_pconnect($config['db_host'], $config['db_user'], $config['db_pass']);
|
||||
if ($config['db']['extension'] == 'mysqli') {
|
||||
$database_link = mysqli_connect('p:'.$config['db_host'], $config['db_user'], $config['db_pass']);
|
||||
}
|
||||
else {
|
||||
$database_link = mysql_pconnect($config['db_host'], $config['db_user'], $config['db_pass']);
|
||||
}
|
||||
|
||||
if (!$database_link) {
|
||||
echo '<h2>MySQL Error</h2>';
|
||||
echo mysql_error();
|
||||
if ($config['db']['extension'] == 'mysqli') {
|
||||
echo mysqli_error($database_link);
|
||||
}
|
||||
else {
|
||||
echo mysql_error();
|
||||
}
|
||||
die;
|
||||
}
|
||||
|
||||
$database_db = mysql_select_db($config['db_name'], $database_link);
|
||||
if ($config['db']['extension'] == 'mysqli') {
|
||||
$database_db = mysqli_select_db($database_link, $config['db_name']);
|
||||
}
|
||||
else {
|
||||
$database_db = mysql_select_db($config['db_name'], $database_link);
|
||||
}
|
||||
|
||||
$clone = $config;
|
||||
foreach (dbFetchRows('select config_name,config_value from config') as $obj) {
|
||||
|
||||
@@ -163,8 +163,21 @@ if ($device['os_group'] == 'cisco') {
|
||||
} //end if
|
||||
|
||||
if ($ok) {
|
||||
// echo("\n".$valid['sensor'].", $type, $device, $oid, $index, 'cisco-entity-sensor', $descr, $divisor, $multiplier, $limit_low, $warn_limit_low, $warn_limit, $limit, $current");
|
||||
discover_sensor($valid['sensor'], $type, $device, $oid, $index, 'cisco-entity-sensor', $descr, $divisor, $multiplier, $limit_low, $warn_limit_low, $warn_limit, $limit, $current, 'snmp', $entPhysicalIndex, $entry['entSensorMeasuredEntity']);
|
||||
#Cisco IOS-XR : add a fake sensor to graph as dbm
|
||||
if ($type == "power" and $device['os'] == "iosxr" and preg_match ("/Transceiver (R|T)x/i", $descr) ) {
|
||||
// convert Watts to dbm
|
||||
$type = "dbm";
|
||||
$limit_low = 10 * log10($limit_low*1000);
|
||||
$warn_limit_low = 10 * log10($warn_limit_low*1000);
|
||||
$warn_limit = 10 * log10($warn_limit*1000);
|
||||
$limit = 10 * log10($limit*1000);
|
||||
$current = round(10 * log10($current*1000),3);
|
||||
$multiplier = 1;
|
||||
$divisor = 1;
|
||||
//echo("\n".$valid['sensor'].", $type, $device, $oid, $index, 'cisco-entity-sensor', $descr, $divisor, $multiplier, $limit_low, $warn_limit_low, $warn_limit, $limit, $current");
|
||||
discover_sensor($valid['sensor'], $type, $device, $oid, $index, 'cisco-entity-sensor', $descr, $divisor, $multiplier, $limit_low, $warn_limit_low, $warn_limit, $limit, $current, 'snmp', $entPhysicalIndex, $entry['entSensorMeasuredEntity']);
|
||||
}
|
||||
}
|
||||
|
||||
$cisco_entity_temperature = 1;
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
// Author: Paul Gear <librenms@libertysys.com.au>
|
||||
// License: GPLv3
|
||||
//
|
||||
require_once '../../includes/print-interface.inc.php';
|
||||
|
||||
echo 'ARP Discovery: ';
|
||||
|
||||
|
||||
@@ -545,9 +545,6 @@ function discover_storage(&$valid, $device, $index, $type, $mib, $descr, $size,
|
||||
),
|
||||
'storage'
|
||||
);
|
||||
if ($debug) {
|
||||
mysql_error();
|
||||
}
|
||||
|
||||
echo '+';
|
||||
}
|
||||
|
||||
@@ -56,11 +56,9 @@ $sql = "SELECT * FROM `hrDevice` WHERE `device_id` = '".$device['device_id']."'
|
||||
foreach (dbFetchRows($sql) as $test_hrDevice) {
|
||||
if (!$valid_hrDevice[$test_hrDevice['hrDeviceIndex']]) {
|
||||
echo '-';
|
||||
mysql_query("DELETE FROM `hrDevice` WHERE hrDevice_id = '".$test_hrDevice['hrDevice_id']."'");
|
||||
dbDelete('hrDevice', '`hrDevice_id` = ?', array($test_hrDevice['hrDevice_id']));
|
||||
if ($debug) {
|
||||
print_r($test_hrDevice);
|
||||
echo mysql_affected_rows().' row deleted';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* LibreNMS
|
||||
*
|
||||
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
|
||||
*
|
||||
* 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. Please see LICENSE.txt at the top level of
|
||||
* the source code distribution for details.
|
||||
*/
|
||||
|
||||
if ($device['os'] == 'zywall') {
|
||||
echo 'Zywall mempool: ';
|
||||
$oid = '.1.3.6.1.4.1.890.1.6.22.1.2.0';
|
||||
$usage = snmp_get($device,$oid, '-Ovq');
|
||||
if (is_numeric($usage)) {
|
||||
discover_mempool($valid_mempool, $device, $oid, 'zywall', 'Memory', '1', null, null);
|
||||
}
|
||||
}
|
||||
@@ -20,9 +20,6 @@ foreach ($stack_poll_array as $port_id_high => $entry_high) {
|
||||
else {
|
||||
dbUpdate(array('ifStackStatus' => $ifStackStatus), 'ports_stack', 'device_id=? AND port_id_high=? AND `port_id_low`=?', array($device['device_id'], $port_id_high, $port_id_low));
|
||||
echo 'U';
|
||||
if ($debug) {
|
||||
echo mysql_error();
|
||||
}
|
||||
}
|
||||
|
||||
unset($stack_db_array[$port_id_high][$port_id_low]);
|
||||
@@ -30,9 +27,6 @@ foreach ($stack_poll_array as $port_id_high => $entry_high) {
|
||||
else {
|
||||
dbInsert(array('device_id' => $device['device_id'], 'port_id_high' => $port_id_high, 'port_id_low' => $port_id_low, 'ifStackStatus' => $ifStackStatus), 'ports_stack');
|
||||
echo '+';
|
||||
if ($debug) {
|
||||
echo mysql_error();
|
||||
}
|
||||
}
|
||||
}//end foreach
|
||||
}//end foreach
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* LibreNMS
|
||||
*
|
||||
* Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa>
|
||||
*
|
||||
* 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. Please see LICENSE.txt at the top level of
|
||||
* the source code distribution for details.
|
||||
*/
|
||||
|
||||
if ($device['os'] == 'zywall') {
|
||||
echo 'Zywall Processors: ';
|
||||
$descr = 'Processor';
|
||||
$oid = '.1.3.6.1.4.1.890.1.6.22.1.1.0';
|
||||
$usage = snmp_get($device, $oid, '-OQUvs');
|
||||
if (is_numeric($usage)) {
|
||||
discover_processor($valid['processor'], $device, $oid, '0', 'zywall', $descr, 1, $usage, null, null);
|
||||
}
|
||||
}
|
||||
@@ -583,7 +583,8 @@ function createHost($host, $community = NULL, $snmpver, $port = 161, $transport
|
||||
'transport' => $transport,
|
||||
'status' => '1',
|
||||
'snmpver' => $snmpver,
|
||||
'poller_group' => $poller_group
|
||||
'poller_group' => $poller_group,
|
||||
'status_reason' => '',
|
||||
);
|
||||
|
||||
$device = array_merge($device, $v3);
|
||||
|
||||
@@ -44,6 +44,13 @@ function poll_sensor($device, $class, $unit) {
|
||||
else if ($class == 'state') {
|
||||
$sensor_value = trim(str_replace('"', '', snmp_walk($device, $sensor['sensor_oid'], '-Oevq', 'SNMPv2-MIB')));
|
||||
}
|
||||
else if ($class == 'dbm') {
|
||||
$sensor_value = trim(str_replace('"', '', snmp_get($device, $sensor['sensor_oid'], '-OUqnv', "SNMPv2-MIB$mib")));
|
||||
//iosxr does not expose dbm values through SNMP so we convert Watts to dbm to have a nice graph to show
|
||||
if ($device['os'] == "iosxr") {
|
||||
$sensor_value = round(10*log10($sensor_value/1000),3);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if ($sensor['sensor_type'] == 'apc') {
|
||||
$sensor_value = trim(str_replace('"', '', snmp_walk($device, $sensor['sensor_oid'], '-OUqnv', "SNMPv2-MIB:PowerNet-MIB$mib")));
|
||||
|
||||
@@ -120,7 +120,7 @@ else if ($poll_device['sysObjectID'] == '.1.3.6.1.4.1.311.1.1.3.1.2') {
|
||||
}
|
||||
|
||||
if (strstr($poll_device['sysDescr'], 'Build 9600')) {
|
||||
$version = 'Server 2012 R2 (NT 6.3)';
|
||||
$version = 'Server 2012 R2 Datacenter (NT 6.3)';
|
||||
}
|
||||
|
||||
}
|
||||
@@ -162,7 +162,7 @@ else if ($poll_device['sysObjectID'] == '.1.3.6.1.4.1.311.1.1.3.1.3') {
|
||||
}
|
||||
|
||||
if (strstr($poll_device['sysDescr'], 'Build 9600')) {
|
||||
$version = 'Server 2012 R2 Datacenter (NT 6.3)';
|
||||
$version = 'Server 2012 R2 (NT 6.3)';
|
||||
}
|
||||
|
||||
}//end if
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
<?php
|
||||
|
||||
$hardware = $poll_device['sysDescr'];
|
||||
|
||||
$version = snmp_get($device, '.1.3.6.1.4.1.890.1.15.3.1.6.0', '-Osqv');
|
||||
$serial = snmp_get($device, '1.3.6.1.4.1.890.1.15.3.1.12.0', '-Osqv');
|
||||
|
||||
@@ -108,11 +108,21 @@ foreach ($filelist as $file) {
|
||||
}
|
||||
|
||||
if ($line[0] != '#') {
|
||||
$update = mysql_query($line);
|
||||
if ($config['db']['extension'] == 'mysqli') {
|
||||
$update = mysqli_query($database_link, $line);
|
||||
}
|
||||
else {
|
||||
$update = mysql_query($line);
|
||||
}
|
||||
if (!$update) {
|
||||
$err++;
|
||||
if ($debug) {
|
||||
echo mysql_error()."\n";
|
||||
if ($config['db']['extension'] == 'mysqli') {
|
||||
echo mysqli_error($database_link)."\n";
|
||||
}
|
||||
else {
|
||||
echo mysql_error()."\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
<?php
|
||||
|
||||
// MYSQL Check - FIXME
|
||||
// 1 DROP
|
||||
// 1 CREATE
|
||||
// 25 ALTERS
|
||||
|
||||
include("includes/defaults.inc.php");
|
||||
include("config.php");
|
||||
|
||||
echo("Updating Billing...");
|
||||
|
||||
$create_sql = "CREATE TABLE IF NOT EXISTS `bill_history` (
|
||||
`bill_hist_id` int(11) NOT NULL AUTO_INCREMENT,
|
||||
`bill_id` int(11) NOT NULL,
|
||||
`updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
`bill_datefrom` datetime NOT NULL,
|
||||
`bill_dateto` datetime NOT NULL,
|
||||
`bill_type` text NOT NULL,
|
||||
`bill_allowed` bigint(20) NOT NULL,
|
||||
`bill_used` bigint(20) NOT NULL,
|
||||
`bill_overuse` bigint(20) NOT NULL,
|
||||
`bill_percent` decimal(10,2) NOT NULL,
|
||||
`rate_95th_in` bigint(20) NOT NULL,
|
||||
`rate_95th_out` bigint(20) NOT NULL,
|
||||
`rate_95th` bigint(20) NOT NULL,
|
||||
`dir_95th` varchar(3) NOT NULL,
|
||||
`rate_average` bigint(20) NOT NULL,
|
||||
`rate_average_in` bigint(20) NOT NULL,
|
||||
`rate_average_out` bigint(20) NOT NULL,
|
||||
`traf_in` bigint(20) NOT NULL,
|
||||
`traf_out` bigint(20) NOT NULL,
|
||||
`traf_total` bigint(20) NOT NULL,
|
||||
`pdf` longblob,
|
||||
PRIMARY KEY (`bill_hist_id`),
|
||||
UNIQUE KEY `unique_index` (`bill_id`,`bill_datefrom`,`bill_dateto`),
|
||||
KEY `bill_id` (`bill_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;";
|
||||
|
||||
mysql_query("DROP TABLE `bill_history`");
|
||||
mysql_query($create_sql);
|
||||
mysql_query("ALTER TABLE `bills` ADD `bill_quota` bigint(20) NOT NULL AFTER `bill_gb`;");
|
||||
|
||||
mysql_query("ALTER TABLE `bills` DROP `rate_95th_in`;");
|
||||
mysql_query("ALTER TABLE `bills` DROP `rate_95th_out`;");
|
||||
mysql_query("ALTER TABLE `bills` DROP `rate_95th`;");
|
||||
mysql_query("ALTER TABLE `bills` DROP `dir_95th`;");
|
||||
mysql_query("ALTER TABLE `bills` DROP `total_data`;");
|
||||
mysql_query("ALTER TABLE `bills` DROP `total_data_in`;");
|
||||
mysql_query("ALTER TABLE `bills` DROP `total_data_out`;");
|
||||
mysql_query("ALTER TABLE `bills` DROP `rate_average_in`;");
|
||||
mysql_query("ALTER TABLE `bills` DROP `rate_average_out`;");
|
||||
mysql_query("ALTER TABLE `bills` DROP `rate_average`;");
|
||||
mysql_query("ALTER TABLE `bills` DROP `bill_last_calc`;");
|
||||
|
||||
mysql_query("ALTER TABLE `bills` ADD `rate_95th_in` bigint(20) NOT NULL;");
|
||||
mysql_query("ALTER TABLE `bills` ADD `rate_95th_out` bigint(20) NOT NULL;");
|
||||
mysql_query("ALTER TABLE `bills` ADD `rate_95th` bigint(20) NOT NULL;");
|
||||
mysql_query("ALTER TABLE `bills` ADD `dir_95th` varchar(3) NOT NULL;");
|
||||
mysql_query("ALTER TABLE `bills` ADD `total_data` bigint(20) NOT NULL;");
|
||||
mysql_query("ALTER TABLE `bills` ADD `total_data_in` bigint(20) NOT NULL;");
|
||||
mysql_query("ALTER TABLE `bills` ADD `total_data_out` bigint(20) NOT NULL;");
|
||||
mysql_query("ALTER TABLE `bills` ADD `rate_average_in` bigint(20) NOT NULL;");
|
||||
mysql_query("ALTER TABLE `bills` ADD `rate_average_out` bigint(20) NOT NULL;");
|
||||
mysql_query("ALTER TABLE `bills` ADD `rate_average` bigint(20) NOT NULL;");
|
||||
mysql_query("ALTER TABLE `bills` ADD `bill_last_calc` datetime NOT NULL;");
|
||||
mysql_query("ALTER TABLE `bills` CHANGE `bill_cdr` bigint(20) NOT NULL;");
|
||||
|
||||
foreach (dbFetchRows("SELECT * FROM `bills`") as $bill_data) {
|
||||
echo("Bill ".$bill['bill_id']." ".$bill['bill_name']);
|
||||
if($bill_data['bill_gb'] > 0) {
|
||||
$bill_data['bill_quota'] = $bill_data['bill_gb'] * $config['billing']['base'] * $config['billing']['base'];
|
||||
dbUpdate(array('bill_quota' => $bill_data['bill_quota']), 'bills', '`bill_id` = ?', array($bill_data['bill_id']));
|
||||
echo("Quota -> ".$bill_data['bill_quota']);
|
||||
}
|
||||
|
||||
if($bill_data['bill_cdr'] > 0) {
|
||||
$bill_data['bill_cdr'] = $bill_data['bill_cdr'] * 1000;
|
||||
dbUpdate(array('bill_cdr' => $bill_data['bill_cdr']), 'bills', '`bill_id` = ?', array($bill_data['bill_id']));
|
||||
echo("CDR -> ".$bill_data['bill_cdr']);
|
||||
}
|
||||
echo("\n");
|
||||
}
|
||||
|
||||
mysql_query("ALTER TABLE `bills` DROP `bill_gb`");
|
||||
|
||||
?>
|
||||
@@ -1,20 +0,0 @@
|
||||
<?php
|
||||
|
||||
// MYSQL Check - FIXME
|
||||
// 3 ALTERS
|
||||
// 1 SELECT
|
||||
// 1 UPDATE
|
||||
mysql_query('ALTER TABLE `eventlog` DROP `id`');
|
||||
mysql_query('ALTER TABLE `eventlog` ADD `event_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST');
|
||||
|
||||
$s = 'SELECT * FROM eventlog';
|
||||
$q = mysql_query($s);
|
||||
while ($event = mysql_fetch_assoc($q)) {
|
||||
if ($event['interface']) {
|
||||
mysql_query("UPDATE `eventlog` SET `interface` = NULL, `type` = 'interface', `reference` = '".$event['interface']."' WHERE `event_id` = '".$event['event_id']."'");
|
||||
}
|
||||
|
||||
$i++;
|
||||
}
|
||||
|
||||
mysql_query('ALTER TABLE `eventlog` DROP `interface`');
|
||||
@@ -1,202 +0,0 @@
|
||||
<?php
|
||||
require 'includes/defaults.inc.php';
|
||||
require 'config.php';
|
||||
|
||||
$basepath = $config['rrd_dir'].'/';
|
||||
|
||||
$files = (getDirectoryTree($basepath));
|
||||
|
||||
$count = count($files);
|
||||
|
||||
if ($config['rrdcached']) {
|
||||
$rrdcached = ' --daemon '.$config['rrdcached'];
|
||||
}
|
||||
|
||||
echo $count." Files \n";
|
||||
$start = date('U');
|
||||
$i = 0;
|
||||
foreach ($files as $file) {
|
||||
fixRdd($file);
|
||||
$i++;
|
||||
if ((date('U') - $start) > 1) {
|
||||
echo (round((($i / $count) * 100), 2)."% \r");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function getDirectoryTree($outerDir, &$files=array())
|
||||
{
|
||||
$dirs = array_diff(scandir($outerDir), array( '.', '..' ));
|
||||
foreach ($dirs as $d) {
|
||||
if (is_dir($outerDir.'/'.$d)) {
|
||||
getDirectoryTree($outerDir.'/'.$d, $files);
|
||||
}
|
||||
else {
|
||||
if (preg_match('/^[\d]+.rrd$/', $d)) {
|
||||
array_push($files, preg_replace('/\/+/', '/', $outerDir.'/'.$d));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $files;
|
||||
|
||||
}//end getDirectoryTree()
|
||||
|
||||
|
||||
function fixRdd($file)
|
||||
{
|
||||
global $config;
|
||||
global $rrdcached;
|
||||
$fileC = shell_exec("{$config['rrdtool']} dump $file $rrdcached");
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------
|
||||
$first = <<<FIRST
|
||||
<ds>
|
||||
<name> INDISCARDS </name>
|
||||
<type> DERIVE </type>
|
||||
<minimal_heartbeat> 600 </minimal_heartbeat>
|
||||
<min> 0.0000000000e+00 </min>
|
||||
<max> 1.2500000000e+10 </max>
|
||||
<!-- PDP Status -->
|
||||
<last_ds> UNKN </last_ds>
|
||||
<value> 0.0000000000e+00 </value>
|
||||
<unknown_sec> 0 </unknown_sec>
|
||||
</ds>
|
||||
<ds>
|
||||
<name> OUTDISCARDS </name>
|
||||
<type> DERIVE </type>
|
||||
<minimal_heartbeat> 600 </minimal_heartbeat>
|
||||
<min> 0.0000000000e+00 </min>
|
||||
<max> 1.2500000000e+10 </max>
|
||||
<!-- PDP Status -->
|
||||
<last_ds> UNKN </last_ds>
|
||||
<value> 0.0000000000e+00 </value>
|
||||
<unknown_sec> 0 </unknown_sec>
|
||||
</ds>
|
||||
<ds>
|
||||
<name> INUNKNOWNPROTOS </name>
|
||||
<type> DERIVE </type>
|
||||
<minimal_heartbeat> 600 </minimal_heartbeat>
|
||||
<min> 0.0000000000e+00 </min>
|
||||
<max> 1.2500000000e+10 </max>
|
||||
<!-- PDP Status -->
|
||||
<last_ds> UNKN </last_ds>
|
||||
<value> 0.0000000000e+00 </value>
|
||||
<unknown_sec> 0 </unknown_sec>
|
||||
</ds>
|
||||
<ds>
|
||||
<name> INBROADCASTPKTS </name>
|
||||
<type> DERIVE </type>
|
||||
<minimal_heartbeat> 600 </minimal_heartbeat>
|
||||
<min> 0.0000000000e+00 </min>
|
||||
<max> 1.2500000000e+10 </max>
|
||||
<!-- PDP Status -->
|
||||
<last_ds> UNKN </last_ds>
|
||||
<value> 0.0000000000e+00 </value>
|
||||
<unknown_sec> 0 </unknown_sec>
|
||||
</ds>
|
||||
<ds>
|
||||
<name> OUTBROADCASTPKTS </name>
|
||||
<type> DERIVE </type>
|
||||
<minimal_heartbeat> 600 </minimal_heartbeat>
|
||||
<min> 0.0000000000e+00 </min>
|
||||
<max> 1.2500000000e+10 </max>
|
||||
<!-- PDP Status -->
|
||||
<last_ds> UNKN </last_ds>
|
||||
<value> 0.0000000000e+00 </value>
|
||||
<unknown_sec> 0 </unknown_sec>
|
||||
</ds>
|
||||
<ds>
|
||||
<name> INMULTICASTPKTS </name>
|
||||
<type> DERIVE </type>
|
||||
<minimal_heartbeat> 600 </minimal_heartbeat>
|
||||
<min> 0.0000000000e+00 </min>
|
||||
<max> 1.2500000000e+10 </max>
|
||||
<!-- PDP Status -->
|
||||
<last_ds> UNKN </last_ds>
|
||||
<value> 0.0000000000e+00 </value>
|
||||
<unknown_sec> 0 </unknown_sec>
|
||||
</ds>
|
||||
<ds>
|
||||
<name> OUTMULTICASTPKTS </name>
|
||||
<type> DERIVE </type>
|
||||
<minimal_heartbeat> 600 </minimal_heartbeat>
|
||||
<min> 0.0000000000e+00 </min>
|
||||
<max> 1.2500000000e+10 </max>
|
||||
<!-- PDP Status -->
|
||||
<last_ds> UNKN </last_ds>
|
||||
<value> 0.0000000000e+00 </value>
|
||||
<unknown_sec> 0 </unknown_sec>
|
||||
</ds>
|
||||
|
||||
<!-- Round Robin Archives -->
|
||||
FIRST;
|
||||
|
||||
$second = <<<SECOND
|
||||
<ds>
|
||||
<primary_value> 0.0000000000e+00 </primary_value>
|
||||
<secondary_value> NaN </secondary_value>
|
||||
<value> NaN </value>
|
||||
<unknown_datapoints> 0 </unknown_datapoints>
|
||||
</ds>
|
||||
<ds>
|
||||
<primary_value> 0.0000000000e+00 </primary_value>
|
||||
<secondary_value> NaN </secondary_value>
|
||||
<value> NaN </value>
|
||||
<unknown_datapoints> 0 </unknown_datapoints>
|
||||
</ds>
|
||||
<ds>
|
||||
<primary_value> 0.0000000000e+00 </primary_value>
|
||||
<secondary_value> NaN </secondary_value>
|
||||
<value> NaN </value>
|
||||
<unknown_datapoints> 0 </unknown_datapoints>
|
||||
</ds>
|
||||
<ds>
|
||||
<primary_value> 0.0000000000e+00 </primary_value>
|
||||
<secondary_value> NaN </secondary_value>
|
||||
<value> NaN </value>
|
||||
<unknown_datapoints> 0 </unknown_datapoints>
|
||||
</ds>
|
||||
<ds>
|
||||
<primary_value> 0.0000000000e+00 </primary_value>
|
||||
<secondary_value> NaN </secondary_value>
|
||||
<value> NaN </value>
|
||||
<unknown_datapoints> 0 </unknown_datapoints>
|
||||
</ds>
|
||||
<ds>
|
||||
<primary_value> 0.0000000000e+00 </primary_value>
|
||||
<secondary_value> NaN </secondary_value>
|
||||
<value> NaN </value>
|
||||
<unknown_datapoints> 0 </unknown_datapoints>
|
||||
</ds>
|
||||
<ds>
|
||||
<primary_value> 0.0000000000e+00 </primary_value>
|
||||
<secondary_value> NaN </secondary_value>
|
||||
<value> NaN </value>
|
||||
<unknown_datapoints> 0 </unknown_datapoints>
|
||||
</ds>
|
||||
</cdp_prep>
|
||||
SECOND;
|
||||
|
||||
$third = <<<THIRD
|
||||
<v> NaN </v><v> NaN </v><v> NaN </v><v> NaN </v><v> NaN </v><v> NaN </v><v> NaN </v></row>
|
||||
THIRD;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------------------
|
||||
if (!preg_match('/DISCARDS/', $fileC)) {
|
||||
$fileC = str_replace('<!-- Round Robin Archives -->', $first, $fileC);
|
||||
$fileC = str_replace('</cdp_prep>', $second, $fileC);
|
||||
$fileC = str_replace('</row>', $third, $fileC);
|
||||
$tmpfname = tempnam('/tmp', 'OBS');
|
||||
file_put_contents($tmpfname, $fileC);
|
||||
@unlink($file);
|
||||
$newfile = preg_replace('/(\d+)\.rrd/', 'port-\\1.rrd', $file);
|
||||
@unlink($newfile);
|
||||
shell_exec($config['rrdtool']." restore $tmpfname $newfile");
|
||||
unlink($tmpfname);
|
||||
}
|
||||
|
||||
}//end fixRdd()
|
||||
|
||||
|
||||
echo "\n";
|
||||
@@ -1,81 +0,0 @@
|
||||
<?php
|
||||
require 'includes/defaults.inc.php';
|
||||
require 'config.php';
|
||||
|
||||
$basepath = $config['rrd_dir'].'/';
|
||||
|
||||
$files = (sensor_getDirectoryTree($basepath));
|
||||
|
||||
$count = count($files);
|
||||
|
||||
echo $count." Files \n";
|
||||
$start = date('U');
|
||||
$i = 0;
|
||||
|
||||
foreach ($files as $file) {
|
||||
sensor_fixRdd($file);
|
||||
$i++;
|
||||
if ((date('U') - $start) > 1) {
|
||||
echo (round((($i / $count) * 100), 2)."% \r");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function sensor_getDirectoryTree($outerDir, &$files=array())
|
||||
{
|
||||
|
||||
$dirs = array_diff(scandir($outerDir), array( '.', '..' ));
|
||||
foreach ($dirs as $d) {
|
||||
if (is_dir($outerDir.'/'.$d)) {
|
||||
sensor_getDirectoryTree($outerDir.'/'.$d, $files);
|
||||
}
|
||||
else {
|
||||
if ((preg_match('/^fan-.*.rrd$/', $d))
|
||||
|| (preg_match('/^current-.*.rrd$/', $d))
|
||||
|| (preg_match('/^freq-.*.rrd$/', $d))
|
||||
|| (preg_match('/^humidity-.*.rrd$/', $d))
|
||||
|| (preg_match('/^volt-.*.rrd$/', $d))
|
||||
|| (preg_match('/^temp-.*.rrd$/', $d))
|
||||
) {
|
||||
array_push($files, preg_replace('/\/+/', '/', $outerDir.'/'.$d));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $files;
|
||||
|
||||
}
|
||||
|
||||
|
||||
function sensor_fixRdd($file)
|
||||
{
|
||||
global $config;
|
||||
global $rrdcached;
|
||||
$fileC = shell_exec("{$config['rrdtool']} dump $file $rrdcached");
|
||||
if (preg_match('/<name> fan/', $fileC)) {
|
||||
shell_exec("{$config['rrdtool']} tune $file $rrdcached -r fan:sensor");
|
||||
rename($file, str_replace('/fan-', '/fanspeed-', $file));
|
||||
}
|
||||
else if (preg_match('/<name> volt/', $fileC)) {
|
||||
shell_exec("{$config['rrdtool']} tune $file $rrdcached -r volt:sensor");
|
||||
rename($file, str_replace('/volt-', '/voltage-', $file));
|
||||
}
|
||||
else if (preg_match('/<name> current/', $fileC)) {
|
||||
shell_exec("{$config['rrdtool']} tune $file $rrdcached -r current:sensor");
|
||||
}
|
||||
else if (preg_match('/<name> freq/', $fileC)) {
|
||||
shell_exec("{$config['rrdtool']} tune $file $rrdcached -r freq:sensor");
|
||||
rename($file, str_replace('/freq-', '/frequency-', $file));
|
||||
}
|
||||
else if (preg_match('/<name> humidity/', $fileC)) {
|
||||
shell_exec("{$config['rrdtool']} tune $file $rrdcached -r humidity:sensor");
|
||||
}
|
||||
else if (preg_match('/<name> temp/', $fileC)) {
|
||||
shell_exec("{$config['rrdtool']} tune $file $rrdcached -r temp:sensor");
|
||||
rename($file, str_replace('/temp-', '/temperature-', $file));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
echo "\n";
|
||||
Reference in New Issue
Block a user