':'') . 'Where /pathcacti/ is the path to your Cacti install location.' . ($is_web ? '
':"\n");
print ($is_web ? '
':'') . 'Change someuser and somepassword to match your site preferences. The defaults are cactiuser for both user and password.' . ($is_web ? '
':"\n");
print ($is_web ? '
':'') . 'NOTE: When installing a remote poller, the config.php file must be writable by the Web Server account, and must include valid connection information to the main Cacti server. The file should be changed to read only after the install is completed.' . ($is_web ? '
':"\n");
print ($is_web ? '
':'');
exit;
}
}
/* db_column_exists - checks whether a column exists
@param $table - the name of the table
@param $column - the name of the column
@param $log - whether to log error messages, defaults to true
@returns - (bool) the output of the sql query as a single variable */
function db_column_exists($table, $column, $log = TRUE, $db_conn = FALSE) {
return (db_fetch_cell("SHOW columns FROM `$table` LIKE '$column'", '', $log, $db_conn) ? true : false);
}
/* db_get_table_column_types - returns all the types for each column of a table
@param $table - the name of the table
@returns - (array) an array of column types indexed by the column names */
function db_get_table_column_types($table, $db_conn = FALSE) {
global $database_sessions, $database_default, $database_hostname, $database_port;
/* check for a connection being passed, if not use legacy behavior */
if (!is_object($db_conn)) {
$db_conn = $database_sessions["$database_hostname:$database_port:$database_default"];
}
if (!is_object($db_conn)) return FALSE;
$columns = db_fetch_assoc("SHOW COLUMNS FROM $table", false, $db_conn);
$cols = array();
if (sizeof($columns)) {
foreach($columns as $col) {
$cols[$col['Field']] = array('type' => $col['Type'], 'null' => $col['Null'], 'default' => $col['Default'], 'extra' => $col['Extra']);;
}
}
return $cols;
}
function db_update_table ($table, $data, $removecolumns = FALSE, $log = TRUE, $db_conn = FALSE) {
global $database_sessions, $database_default, $database_hostname, $database_port;
/* check for a connection being passed, if not use legacy behavior */
if (!is_object($db_conn)) {
$db_conn = $database_sessions["$database_hostname:$database_port:$database_default"];
}
if (!is_object($db_conn)) return FALSE;
if (!db_table_exists($table, $log, $db_conn)) {
return db_table_create ($table, $data, $log, $db_conn);
}
$allcolumns = array();
foreach ($data['columns'] as $column) {
$allcolumns[] = $column['name'];
if (!db_column_exists($table, $column['name'], $log, $db_conn)) {
db_add_column ($table, $column, $log, $db_conn);
} else {
// Check that column is correct and fix it
// FIXME: Need to still check default value
$arr = db_fetch_row("SHOW columns FROM `$table` LIKE '" . $column['name'] . "'", $log, $db_conn);
if ($column['type'] != $arr['Type'] || (isset($column['NULL']) && ($column['NULL'] ? 'YES' : 'NO') != $arr['Null'])
|| (isset($column['auto_increment']) && ($column['auto_increment'] ? 'auto_increment' : '') != $arr['Extra'])) {
$sql = 'ALTER TABLE `' . $table . '` CHANGE `' . $column['name'] . '` `' . $column['name'] . '`';
if (isset($column['type']))
$sql .= ' ' . $column['type'];
if (isset($column['unsigned']))
$sql .= ' unsigned';
if (isset($column['NULL']) && $column['NULL'] == false)
$sql .= ' NOT NULL';
if (isset($column['NULL']) && $column['NULL'] == true && !isset($column['default']))
$sql .= ' default NULL';
if (isset($column['default']))
$sql .= ' default ' . (is_numeric($column['default']) ? $column['default'] : "'" . $column['default'] . "'");
if (isset($column['on_update']))
$sql .= ' ON UPDATE ' . $column['on_update'];
if (isset($column['auto_increment']))
$sql .= ' auto_increment';
if (isset($column['comment']))
$sql .= " COMMENT '" . $column['comment'] . "'";
db_execute($sql, $log, $db_conn);
}
}
}
if ($removecolumns) {
$result = db_fetch_assoc('SHOW columns FROM `' . $table . '`', $log, $db_conn);
foreach($result as $arr) {
if (!in_array($arr['Field'], $allcolumns)) {
db_remove_column ($table, $arr['Field'], $log, $db_conn);
}
}
}
$info = db_fetch_row("SELECT ENGINE, TABLE_COMMENT FROM information_schema.TABLES WHERE TABLE_NAME = '$table'", $log, $db_conn);
if (isset($info['TABLE_COMMENT']) && str_replace("'", '', $info['TABLE_COMMENT']) != str_replace("'", '', $data['comment'])) {
db_execute("ALTER TABLE `$table` COMMENT '" . str_replace("'", '', $data['comment']) . "'", $log, $db_conn);
}
if (isset($info['ENGINE']) && strtolower($info['ENGINE']) != strtolower($data['type'])) {
db_execute("ALTER TABLE `$table` ENGINE = " . $data['type'], $log, $db_conn);
}
// Correct any indexes
$indexes = db_fetch_assoc("SHOW INDEX FROM `$table`", $log, $db_conn);
$allindexes = array();
foreach ($indexes as $index) {
$allindexes[$index['Key_name']][$index['Seq_in_index']-1] = $index['Column_name'];
}
foreach ($allindexes as $n => $index) {
if ($n != 'PRIMARY' && isset($data['keys'])) {
$removeindex = TRUE;
foreach ($data['keys'] as $k) {
if ($k['name'] == $n) {
$removeindex = FALSE;
$add = array_diff($k['columns'], $index);
$del = array_diff($index, $k['columns']);
if (!empty($add) || !empty($del)) {
db_execute("ALTER TABLE `$table` DROP INDEX `$n`", $log, $db_conn);
db_execute("ALTER TABLE `$table` ADD INDEX `$n` (`" . (is_array($k['columns']) ? implode('`,`', $k['columns']) : $k['columns']) . '`)', $log, $db_conn);
}
break;
}
}
if ($removeindex) {
db_execute("ALTER TABLE `$table` DROP INDEX `$n`", $log, $db_conn);
}
}
}
// Add any indexes
if (isset($data['keys'])) {
foreach ($data['keys'] as $k) {
if (!isset($allindexes[$k['name']])) {
db_execute("ALTER TABLE `$table` ADD INDEX `" . $k['name'] . '` (`' . (is_array($k['columns']) ? implode('`,`', $k['columns']) : $k['columns']) . '`)', $log, $db_conn);
}
}
}
// FIXME: It won't allow us to drop a primary key that is set to auto_increment
// Check Primary Key
if (!isset($data['primary']) && isset($allindexes['PRIMARY'])) {
db_execute("ALTER TABLE `$table` DROP PRIMARY KEY", $log, $db_conn);
unset($allindexes['PRIMARY']);
}
if (isset($data['primary'])) {
if (!isset($allindexes['PRIMARY'])) {
// No current primary key, so add it
if (is_array($data['primary'])) {
$data['primary'] = implode(',', $data['primary']);
}
db_execute("ALTER TABLE `$table` ADD PRIMARY KEY(" . $data['primary'] . ")", $log, $db_conn);
} else {
$add = array_diff($data['primary'], $allindexes['PRIMARY']);
$del = array_diff($allindexes['PRIMARY'], $data['primary']);
if (!empty($add) || !empty($del)) {
db_execute("ALTER TABLE `$table` DROP PRIMARY KEY", $log, $db_conn);
db_execute("ALTER TABLE `$table` ADD PRIMARY KEY(`" . (is_array($data['primary']) ? implode('`,`', $data['primary']) : $data['primary']) . "`)", $log, $db_conn);
}
}
}
return TRUE;
}
/* db_table_create - checks whether a table exists
@param $table - the name of the table
@param $data - data array
@param $log - whether to log error messages, defaults to true
@returns - (bool) the output of the sql query as a single variable */
function db_table_create ($table, $data, $log = TRUE, $db_conn = FALSE) {
global $database_sessions, $database_default, $database_hostname, $database_port;
/* check for a connection being passed, if not use legacy behavior */
if (!is_object($db_conn)) {
$db_conn = $database_sessions["$database_hostname:$database_port:$database_default"];
}
if (!is_object($db_conn)) return FALSE;
if (!db_table_exists($table, $log, $db_conn)) {
$c = 0;
$sql = 'CREATE TABLE `' . $table . "` (\n";
foreach ($data['columns'] as $column) {
if (isset($column['name'])) {
if ($c > 0)
$sql .= ",\n";
$sql .= '`' . $column['name'] . '`';
if (isset($column['type']))
$sql .= ' ' . $column['type'];
if (isset($column['unsigned']))
$sql .= ' unsigned';
if (isset($column['NULL']) && $column['NULL'] == false)
$sql .= ' NOT NULL';
if (isset($column['NULL']) && $column['NULL'] == true && !isset($column['default']))
$sql .= ' default NULL';
if (isset($column['default']))
$sql .= ' default ' . (is_numeric($column['default']) ? $column['default'] : "'" . $column['default'] . "'");
if (isset($column['on_update']))
$sql .= ' ON UPDATE ' . $column['on_update'];
if (isset($column['comment']))
$sql .= " COMMENT '" . $column['comment'] . "'";
if (isset($column['auto_increment']))
$sql .= ' auto_increment';
$c++;
}
}
if (isset($data['primary'])) {
if (is_array($data['primary'])) {
$sql .= ",\n PRIMARY KEY (`" . implode('`,`'. $data['primary']) . '`)';
} else {
$sql .= ",\n PRIMARY KEY (`" . $data['primary'] . '`)';
}
}
if (isset($data['keys']) && sizeof($data['keys'])) {
foreach ($data['keys'] as $key) {
if (isset($key['name'])) {
if (is_array($key['columns'])) {
$sql .= ",\n KEY `" . $key['name'] . '` (`' . implode('`,`', $key['columns']) . '`)';
} else {
$sql .= ",\n KEY `" . $key['name'] . '` (`' . $key['columns'] . '`)';
}
}
}
}
$sql .= ') ENGINE = ' . $data['type'];
if (isset($data['comment'])) {
$sql .= " COMMENT = '" . $data['comment'] . "'";
}
if (db_execute($sql, $log, $db_conn)) {
return true;
}
return false;
}
}
/* array_to_sql_or - loops through a single dimentional array and converts each
item to a string that can be used in the OR portion of an sql query in the
following form:
column=item1 OR column=item2 OR column=item2 ...
@param $array - the array to convert
@param $sql_column - the column to set each item in the array equal to
@returns - a string that can be placed in a SQL OR statement */
function array_to_sql_or($array, $sql_column) {
/* if the last item is null; pop it off */
if (end($array) === NULL) {
array_pop($array);
}
if (sizeof($array)) {
$sql_or = "($sql_column IN('" . implode("','", $array) . "'))";
return $sql_or;
}
}
/* db_replace - replaces the data contained in a particular row
@param $table_name - the name of the table to make the replacement in
@param $array_items - an array containing each column -> value mapping in the row
@param $keyCols - a string or array of primary keys
@param $autoQuote - whether to use intelligent quoting or not
@returns - the auto incriment id column (if applicable) */
function db_replace($table_name, $array_items, $keyCols, $db_conn = FALSE) {
global $database_sessions, $database_default, $database_hostname, $database_port;
/* check for a connection being passed, if not use legacy behavior */
if (!is_object($db_conn)) {
$db_conn = $database_sessions["$database_hostname:$database_port:$database_default"];
}
cacti_log("DEVEL: SQL Replace on table '$table_name': \"" . serialize($array_items) . '"', FALSE, 'DBCALL', POLLER_VERBOSITY_DEVDBG);
_db_replace($db_conn, $table_name, $array_items, $keyCols);
return db_fetch_insert_id($db_conn);
}
// FIXME: Need to Rename and cleanup a bit
function _db_replace($db_conn, $table, $fieldArray, $keyCols, $has_autoinc) {
global $database_sessions, $database_default, $database_hostname, $database_port;
/* check for a connection being passed, if not use legacy behavior */
if (!is_object($db_conn)) {
$db_conn = $database_sessions["$database_hostname:$database_port:$database_default"];
}
if (!is_object($db_conn)) return FALSE;
if (!is_array($keyCols)) {
$keyCols = array($keyCols);
}
$sql = "INSERT INTO $table (";
$sql2 = '';
$sql3 = '';
$first = true;
$first3 = true;
foreach($fieldArray as $k => $v) {
if (!$first) {
$sql .= ', ';
$sql2 .= ', ';
}
$sql .= "`$k`";
$sql2 .= $v;
$first = false;
if (in_array($k, $keyCols)) continue; // skip UPDATE if is key
if (!$first3) {
$sql3 .= ', ';
}
$sql3 .= "`$k`=VALUES(`$k`)";
$first3 = false;
}
$sql .= ") VALUES ($sql2)" . ($sql3 != '' ? " ON DUPLICATE KEY UPDATE $sql3" : '');
$return_code = db_execute($sql, true, $db_conn);
if (!$return_code) {
cacti_log("ERROR: SQL Save Failed for Table '$table'. SQL:'" . $sql . "'", FALSE, 'DBCALL');
}
return db_fetch_insert_id($db_conn);
}
/* sql_save - saves data to an sql table
@param $array_items - an array containing each column -> value mapping in the row
@param $table_name - the name of the table to make the replacement in
@param $key_cols - the primary key(s)
@returns - the auto incriment id column (if applicable) */
function sql_save($array_items, $table_name, $key_cols = 'id', $autoinc = TRUE, $db_conn = FALSE) {
global $database_sessions, $database_default, $database_hostname, $database_port;
/* check for a connection being passed, if not use legacy behavior */
if (!is_object($db_conn)) {
$db_conn = $database_sessions["$database_hostname:$database_port:$database_default"];
}
$cols = db_get_table_column_types($table_name, $db_conn);
cacti_log("DEVEL: SQL Save on table '$table_name': \"" . serialize($array_items) . '"', FALSE, 'DBCALL', POLLER_VERBOSITY_DEVDBG);
while (list($key, $value) = each($array_items)) {
if (strstr($cols[$key]['type'], 'int') !== false ||
strstr($cols[$key]['type'], 'float') !== false ||
strstr($cols[$key]['type'], 'double') !== false ||
strstr($cols[$key]['type'], 'decimal') !== false) {
if ($value == '') {
if ($cols[$key]['null'] == 'YES') {
// TODO: We should make 'NULL', but there are issues that need to be addressed first
$array_items[$key] = 0;
}elseif (strpos($cols[$key]['extra'], 'auto_increment') !== false) {
$array_items[$key] = 0;
}elseif ($cols[$key]['default'] == '') {
// TODO: We should make 'NULL', but there are issues that need to be addressed first
$array_items[$key] = 0;
}else{
$array_items[$key] = $cols[$key]['default'];
}
}elseif (empty($value)) {
$array_items[$key] = 0;
}else{
$array_items[$key] = $value;
}
}else{
$array_items[$key] = db_qstr($value);
}
}
$replace_result = _db_replace($db_conn, $table_name, $array_items, $key_cols, $autoinc);
/* get the last AUTO_ID and return it */
if (!$replace_result || db_fetch_insert_id($db_conn) == '0') {
if (!is_array($key_cols)) {
if (isset($array_items[$key_cols])) {
return str_replace('"', '', $array_items[$key_cols]);
}
}
return FALSE;
} else {
return $replace_result;
}
}
/* sql_sanitize - removes and quotes unwanted chars in values passed for use in SQL statements
@param $value - value to sanitize
@return - fixed value */
function sql_sanitize($value) {
$value = db_qstr($value);
return $value;
}
/* sql_column_exists - checks if a named column exists in the table specified
@param $table_name - table to check
@param $column_name - column name
@return true or false; */
function sql_column_exists($table_name, $column_name, $db_conn = FALSE) {
global $database_sessions, $database_default, $database_hostname, $database_port;
/* check for a connection being passed, if not use legacy behavior */
if (!is_object($db_conn)) {
$db_conn = $database_sessions["$database_hostname:$database_port:$database_default"];
}
$columns = db_fetch_assoc("SHOW COLUMNS FROM `$table_name`", false, $db_conn);
foreach ($columns as $column) {
if ($column_name === $column['name']) {
return true;
}
}
return false;
}
/* sql_function_timestamp - abstracts timestamp function across databases
@return - fixed value */
function sql_function_timestamp($db_conn = FALSE) {
global $database_sessions, $database_default, $database_hostname, $database_port;
/* check for a connection being passed, if not use legacy behavior */
if (!is_object($db_conn)) {
$db_conn = $database_sessions["$database_hostname:$database_port:$database_default"];
}
return 'NOW()';
//if (isset($db_conn->sysTimeStamp)) {
// return $db_conn->sysTimeStamp;
//}
//return "'".date('Y-m-d H:i:s')."'";
}
/* sql_function_substr - abstracts substring function across databases
@return - fixed value */
function sql_function_substr($db_conn = FALSE) {
global $database_sessions, $database_default, $database_hostname, $database_port;
/* check for a connection being passed, if not use legacy behavior */
if (!is_object($db_conn)) {
$db_conn = $database_sessions["$database_hostname:$database_port:$database_default"];
}
return 'substring';
// if (isset($db_conn->substr)) {
// return $db_conn->substr;
// }
// switch($db_conn->databaseType) {
// case 'oci805':
// case 'oci8':
// case 'oci8po':
// case 'oracle':
// return 'substr';
// break;
// case 'postgres64':
// case 'postgres7':
// case 'postgres':
// return 'substr';
// break;
// case 'db2':
// case 'fbsql':
// case 'firebird':
// case 'ibase':
// default:
// return 'substr';
// }
}
/* sql_function_concat - abstracts concatenation function across databases
@return - fixed value */
function sql_function_concat($db_conn = FALSE) {
global $database_sessions, $database_default, $database_hostname, $database_port;
/* check for a connection being passed, if not use legacy behavior */
if (!is_object($db_conn)) {
$db_conn = $database_sessions["$database_hostname:$database_port:$database_default"];
}
//if (method_exists($db_conn, 'Concat')) {
// $args = func_get_args();
// return call_user_func_array(array(&$db_conn, 'Concat'), $args);
//}
return "concat('".implode("','", func_get_args())."')";
}
/* sql_function_replace - abstracts replace function across databases
@return - fixed value */
function sql_function_replace($db_conn = FALSE) {
global $database_sessions, $database_default, $database_hostname, $database_port;
/* check for a connection being passed, if not use legacy behavior */
if (!is_object($db_conn)) {
$db_conn = $database_sessions["$database_hostname:$database_port:$database_default"];
}
return 'replace';
// switch($db_conn->databaseType) {
// case 'mssql':
// case 'mssqlpo':
// return 'replace';
// break;
// case 'mysql':
// case 'mysqli':
// case 'mysqlt':
// return 'replace';
// break;
// case 'oci805':
// case 'oci8':
// case 'oci8po':
// case 'oracle':
// return 'replace';
// break;
// case 'postgres64':
// case 'postgres7':
// case 'postgres':
// return 'replace';
// break;
// case 'db2':
// case 'firebird':
// case 'ibase':
// default:
// return 'replace';
// }
}
/* sql_function_dateformat - abstracts dateformat function across databases
@return - fixed value */
function sql_function_dateformat($fmt, $col = false, $db_conn = FALSE) {
global $database_sessions, $database_default, $database_hostname, $database_port;
/* check for a connection being passed, if not use legacy behavior */
if (!is_object($db_conn)) {
$db_conn = $database_sessions["$database_hostname:$database_port:$database_default"];
}
return 'date_format';
// if (method_exists($db_conn, 'SQLDate')) {
// return call_user_func_array(array(&$db_conn, 'SQLDate'), array($fmt,$col));
// }
//
// switch($db_conn->databaseType) {
// default:
// return 'date_format';
// }
}
function db_qstr($s, $db_conn = FALSE) {
global $database_sessions, $database_default, $database_hostname, $database_port;
/* check for a connection being passed, if not use legacy behavior */
if (!is_object($db_conn)) {
$db_conn = $database_sessions["$database_hostname:$database_port:$database_default"];
}
$replaceQuote = "\\'";
if (is_null($s)) return 'NULL';
if (is_object($db_conn)) {
return $db_conn->quote($s);
}
if ($replaceQuote == "\\'") {
$s = str_replace(array('\\', "\0"), array('\\\\', "\\\0"), $s);
}
return "'" . str_replace("'",$replaceQuote, $s) . "'";
}