1<?php
2
3/**
4 * Observium Network Management and Monitoring System
5 * Copyright (C) 2006-2013, Observium Developers - http://www.observium.org
6 *
7 * @package    observium
8 * @subpackage config
9 * @author     Tom Laermans <sid3windr@observium.org>
10 * @copyright  (C) 2006-2013 Adam Armstrong, (C) 2013-2019 Observium Limited
11 *
12 */
13
14// Load configuration file into $config variable
15if (!isset($config['install_dir']))
16{
17  $base_dir = realpath(dirname(__FILE__) . '/..');
18} else {
19  $base_dir = $config['install_dir'];
20}
21
22// Clear config array, we're starting with a clean state
23$config = array();
24
25require($base_dir."/includes/defaults.inc.php");
26require($base_dir."/config.php");
27
28// Base dir, if it's not set in config
29if (!isset($config['install_dir']))
30{
31  $config['install_dir'] = $base_dir;
32}
33
34// Include necessary supporting files
35require_once($config['install_dir'] . "/includes/functions.inc.php");
36
37// Die if exec/proc_open functions disabled in php.ini. This install not functional for run Observium.
38if (!is_exec_available()) { die; }
39
40// Load definitions
41require($config['install_dir'] . "/includes/definitions.inc.php");
42
43// CLEANME, this already included in functions.inc.php
44// Common functions, for is_ssl and print_warning/print_error
45//include_once($config['install_dir'].'/includes/common.inc.php');
46
47// Connect to database
48if (!$GLOBALS[OBS_DB_LINK])
49{
50  if (defined('OBS_DB_SKIP') && OBS_DB_SKIP === TRUE)
51  {
52    print_warning("WARNING: In PHP Unit tests we can skip DB connect. But if you test db functions, check your configs.");
53  } else {
54    print_error("DB Error " . dbErrorNo() . ": " . dbError());
55    die; // Die if not PHP Unit tests
56  }
57}
58else if (!get_db_version() && !(isset($options['u']) || isset($options['V'])))
59{
60  if (!dbQuery('SELECT 1 FROM `devices` LIMIT 1;'))
61  {
62    // DB schema not installed, install first
63    print_error("DB schema not installed, first install it.");
64    die;
65  }
66} else {
67  // Disable STRICT mode for DB session (we not fully support them)
68  $db_modes = explode(',', dbFetchCell("SELECT @@SESSION.sql_mode;"));
69  $db_modes_exclude = array('STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES', 'ONLY_FULL_GROUP_BY');
70  $db_modes_update  = array();
71  foreach ($db_modes_exclude as $db_mode_exclude)
72  {
73    if (in_array($db_mode_exclude, $db_modes))
74    {
75      $db_modes_update[] = $db_mode_exclude;
76    }
77  }
78  if (count($db_modes_update))
79  {
80    $db_modes = array_diff($db_modes, $db_modes_update);
81    dbQuery('SET SESSION `sql_mode` = ?', array(implode(',', $db_modes)));
82    print_debug('DB mode(s) disabled: '.implode(', ', $db_modes_update));
83  }
84  //register_shutdown_function('dbClose');
85  // Maybe better in another place, but at least here it runs always; keep track of what svn revision we last saw, and eventlog the upgrade versions.
86  // We have versions here from the includes above, and we just connected to the DB.
87  $rev_old = @get_obs_attrib('current_rev');
88  if (($rev_old < OBSERVIUM_REV || !is_numeric($rev_old)) && OBSERVIUM_VERSION_LONG != '0.SVN.ERROR')
89  {
90    // Ignore changes to not correctly detected version (0.SVN.ERROR)
91    // Version update detected, log it
92    $version_old = @get_obs_attrib('current_version');
93    log_event("Observium updated: $version_old -> " . OBSERVIUM_VERSION_LONG, NULL, NULL, NULL, 5);
94
95    set_obs_attrib('current_rev',     OBSERVIUM_REV);
96    set_obs_attrib('current_version', OBSERVIUM_VERSION_LONG);
97  }
98
99  // Clean
100  unset($db_modes, $db_modes_exclude, $db_mode_exclude, $db_modes_update, $rev_old);
101}
102
103// Load SQL configuration into $config variable
104load_sqlconfig($config);
105
106/**
107 * OHMYGOD, this is very dangerous, because this is secure hole for override static definitions,
108 * now already defined configs skipped in load_sqlconfig().
109 *
110// Reload configuration file into $config variable to make sure it overrules all SQL-supplied and default settings
111// Not the greatest hack, but array_merge was unfit for the job, unfortunately.
112include($config['install_dir']."/config.php");
113
114*/
115
116// Init RRDcached
117
118if (isset($config['rrdcached']) && !preg_match('!^\s*(unix:)?/!i', $config['rrdcached']))
119{
120  // RRD files located on remote server
121  define('OBS_RRD_NOLOCAL', TRUE);
122} else {
123  define('OBS_RRD_NOLOCAL', FALSE);
124}
125
126// Init StatsD
127
128if ($config['statsd']['enable'] && class_exists('StatsD'))
129{
130  //$statsd = new StatsD(array('host' => $config['statsd']['host'], 'port' => $config['statsd']['port']));
131  StatsD::$config = array(
132    'host' => $config['statsd']['host'],
133    'port' => $config['statsd']['port'],
134  );
135}
136
137
138// Escape all cmd paths
139//FIXME, move all cmd config into $config['cmd'][path]
140$cmds = array('rrdtool', 'fping', 'fping6', 'snmpwalk', 'snmpget',
141              'snmpbulkget', 'snmpbulkwalk', 'snmptranslate', 'whois',
142              'mtr', 'nmap', 'ipmitool', 'virsh', 'dot', 'unflatten',
143              'neato', 'sfdp', 'svn', 'git', 'wmic', 'file', 'wc',
144              'sudo', 'tail', 'cut', 'tr',
145             );
146
147foreach ($cmds as $path)
148{
149  if (isset($config[$path])) { $config[$path] = escapeshellcmd($config[$path]); }
150}
151unset($cmds, $path);
152
153// Disable nonexistant features in CE, do not try to turn on, it will not give effect
154if (OBSERVIUM_EDITION == 'community')
155{
156  $config['enable_billing'] = 0;
157  $config['api']['enabled'] = 0;
158
159  // Disabled (not exist) modules
160  unset($config['poller_modules']['oids'],
161        $config['poller_modules']['loadbalancer'],
162        $config['poller_modules']['aruba-controller'],
163        $config['poller_modules']['netscaler-vsvr']);
164}
165
166// Self hostname for observium server
167// FIXME, used only in smokeping integration
168if (!isset($config['own_hostname']))
169{
170  $config['own_hostname'] = get_localhost();
171}
172
173// Set web_url/base_url setting to default, add trailing slash if not present
174
175if (!isset($config['web_url']))
176{
177  $config['web_url'] = isset($config['base_url']) ? $config['base_url'] : 'http://' . get_localhost();
178}
179if (substr($config['web_url'], -1) != '/') { $config['web_url'] .= '/'; }
180
181if (is_cli() && isset($config['external_url']))
182{
183  // Overwrite the autogenerated base_url with external_url when we're on CLI.
184  $config['base_url'] = $config['external_url'];
185}
186else if (!isset($config['base_url']))
187{
188  if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["SERVER_PORT"]))
189  {
190    if (strpos($_SERVER["SERVER_NAME"] , ":"))
191    {
192      // Literal IPv6
193      $config['base_url']  = "http://[" . $_SERVER["SERVER_NAME"] ."]" . ($_SERVER["SERVER_PORT"] != 80 ? ":".$_SERVER["SERVER_PORT"] : '') ."/";
194    } else {
195      $config['base_url']  = "http://" . $_SERVER["SERVER_NAME"] . ($_SERVER["SERVER_PORT"] != 80 ? ":".$_SERVER["SERVER_PORT"] : '') ."/";
196    }
197  }
198  //} else {
199  //  // Try to detect base_url in cli based on hostname
200  //  /// FIXME. Here require get_localhost(), but this function loaded after definitions
201  //  //$config['base_url'] = "http://" . get_localhost() . "/";
202  //}
203} else {
204  // Add / to base_url if not there
205  if (substr($config['base_url'], -1) != '/') { $config['base_url'] .= '/'; }
206}
207
208// If we're on SSL, let's properly detect it
209if (is_ssl())
210{
211  $config['base_url'] = preg_replace('/^http:/','https:', $config['base_url']);
212}
213
214// Old variable backwards compatibility
215if (isset($config['rancid_configs']) && !is_array($config['rancid_configs'])) { $config['rancid_configs'] = array($config['rancid_configs']); }
216if (isset($config['auth_ldap_group']) && !is_array($config['auth_ldap_group'])) { $config['auth_ldap_group'] = array($config['auth_ldap_group']); }
217if (isset($config['auth_ldap_kerberized']) && $config['auth_ldap_kerberized'] && $config['auth_mechanism'] == 'ldap') { $config['auth']['remote_user'] = TRUE; }
218
219//print_vars($config['location_map']);
220if (isset($config['location_map']))
221{
222  $config['location']['map'] = array_merge((array)$config['location_map'], (array)$config['location']['map']);
223  unset($config['location_map']);
224}
225//print_vars($config['location']['map']);
226//print_vars($config['location']['map_regexp']);
227if ($config['location']['menu']['type'] == 'geocoded')
228{
229  if (isset($config['geocoding']['enable']) && !$config['geocoding']['enable'])            { $config['location']['menu']['type'] = 'plain'; }
230  else if (isset($config['location_menu_geocoded']) && !$config['location_menu_geocoded']) { $config['location']['menu']['type'] = 'plain'; }
231}
232
233// Security fallback check
234if (isset($config['auth']['remote_user']) && $config['auth']['remote_user'] && !isset($_SERVER['REMOTE_USER']))
235{
236  // Disable remote_user, Apache did not pass a username! Misconfigured?
237  // FIXME log this somewhere?
238  $config['auth']['remote_user'] = FALSE;
239}
240
241// Database currently stores v6 networks non-compressed, check for any compressed subnet and expand them
242foreach ($config['ignore_common_subnet'] as $i => $content)
243{
244  if (strstr($content,':') !== FALSE) { $config['ignore_common_subnet'][$i] = Net_IPv6::uncompress($content); }
245}
246
247unset($i); unset($content);
248
249if (isset($config['rrdgraph_def_text']))
250{
251  $config['rrdgraph_def_text'] = str_replace("  ", " ", $config['rrdgraph_def_text']);
252  $config['rrd_opts_array'] = explode(" ", trim($config['rrdgraph_def_text']));
253}
254
255// Disable phpFastCache 5.x for PHP less than 5.5, since it unsupported
256if ($config['cache']['enable'] && version_compare(PHP_VERSION, '5.5.0', '<'))
257{
258  $config['cache']['enable'] = FALSE;
259}
260
261// Generate poller id if we're a partitioned poller and we don't yet have one.
262/*
263if (isset($config['poller_id']))
264{
265  // Use already configured poller_id
266}
267else
268*/
269if (isset($config['poller_name']))
270{
271  $poller_id = dbFetchCell("SELECT `poller_id` FROM `pollers` WHERE `poller_name` = ?", array($GLOBALS['config']['poller_name']));
272
273  if (is_numeric($poller_id))
274  {
275    $config['poller_id'] = $poller_id;
276  } else {
277    // This poller not exist, create it
278    // I not sure that this should be in global sql-config include @mike
279    $config['poller_id'] = dbInsert('pollers', array('poller_name' => $config['poller_name']));
280  }
281  unset($poller_id);
282
283} else {
284  // Default poller
285  $config['poller_id'] = 0;
286
287}
288
289// EOF
290