\n";
api_plugin_hook('nav_login_after');
} elseif (isset($_SESSION['sess_user_id']) && $using_guest_account == false) {
$user = db_fetch_row_prepared('SELECT username, password_change, realm FROM user_auth WHERE id = ?', array($_SESSION['sess_user_id']));
api_plugin_hook('nav_login_before');
print __('Logged in as') . "
\n";
api_plugin_hook('nav_login_after');
}
}
/* draw_navigation_text - determines the top header navigation text for the current page and displays it to
@arg $type - (string) Either 'url' or 'title'
@returns (string> Either the navigation text or title */
function draw_navigation_text($type = 'url') {
global $config;
$nav_level_cache = (isset($_SESSION['sess_nav_level_cache']) ? $_SESSION['sess_nav_level_cache'] : array());
$nav = array(
'auth_profile.php:' => array(
'title' => __('User Profile (Edit)'),
'mapping' => '',
'url' => '',
'level' => '0'
),
'auth_profile.php:edit' => array(
'title' => __('User Profile (Edit)'),
'mapping' => '',
'url' => '',
'level' => '0'
),
'graph_view.php:' => array(
'title' => __('Graphs'),
'mapping' => '',
'url' => 'graph_view.php',
'level' => '0'
),
'graph_view.php:tree' => array(
'title' => __('Tree Mode'),
'mapping' => 'graph_view.php:',
'url' => 'graph_view.php?action=tree',
'level' => '0'
),
'graph_view.php:tree_content' => array(
'title' => __('Tree Mode'),
'mapping' => 'graph_view.php:',
'url' => 'graph_view.php?action=tree',
'level' => '0'
),
'graph_view.php:list' => array(
'title' => __('List Mode'),
'mapping' => '',
'url' => 'graph_view.php?action=list',
'level' => '0'
),
'graph_view.php:preview' => array(
'title' => __('Preview Mode'),
'mapping' => '',
'url' => 'graph_view.php?action=preview',
'level' => '0'
),
'graph.php:' => array(
'title' => '|current_graph_title|',
'mapping' => 'graph_view.php:,?',
'level' => '2'
),
'graph.php:view' => array(
'title' => '|current_graph_title|',
'mapping' => 'graph_view.php:,?',
'level' => '2'
),
'index.php:' => array(
'title' => __('Console'),
'mapping' => '',
'url' => $config['url_path'] . 'index.php',
'level' => '0'
),
'index.php:login' => array(
'title' => __('Console'),
'mapping' => '',
'url' => $config['url_path'] . 'index.php',
'level' => '0'
),
'graphs.php:' => array(
'title' => __('Graph Management'),
'mapping' => 'index.php:',
'url' => 'graphs.php',
'level' => '1'
),
'graphs.php:graph_edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,graphs.php:',
'url' => '',
'level' => '2'
),
'graphs.php:graph_diff' => array(
'title' => __('Change Graph Template'),
'mapping' => 'index.php:,graphs.php:,graphs.php:graph_edit',
'url' => '',
'level' => '3'
),
'graphs.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,graphs.php:',
'url' => '',
'level' => '2'
),
'graphs_items.php:item_edit' => array(
'title' => __('Graph Items'),
'mapping' => 'index.php:,graphs.php:,graphs.php:graph_edit',
'url' => '',
'level' => '3'
),
'graphs_new.php:' => array(
'title' => __('Create New Graphs'),
'mapping' => 'index.php:',
'url' => 'graphs_new.php',
'level' => '1'
),
'graphs_new.php:save' => array(
'title' => __('Create Graphs from Data Query'),
'mapping' => 'index.php:,graphs_new.php:',
'url' => '',
'level' => '2'
),
'gprint_presets.php:' => array(
'title' => __('GPRINT Presets'),
'mapping' => 'index.php:',
'url' => 'gprint_presets.php',
'level' => '1'
),
'gprint_presets.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,gprint_presets.php:',
'url' => '',
'level' => '2'
),
'gprint_presets.php:remove' => array(
'title' => __('(Remove)'),
'mapping' => 'index.php:,gprint_presets.php:',
'url' => '',
'level' => '2'
),
'cdef.php:' => array(
'title' => __('CDEFs'),
'mapping' => 'index.php:',
'url' => 'cdef.php',
'level' => '1'
),
'cdef.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,cdef.php:',
'url' => '',
'level' => '2'
),
'cdef.php:remove' => array(
'title' => __('(Remove)'),
'mapping' => 'index.php:,cdef.php:',
'url' => '',
'level' => '2'
),
'cdef.php:item_edit' => array(
'title' => __('CDEF Items'),
'mapping' => 'index.php:,cdef.php:,cdef.php:edit',
'url' => '',
'level' => '3'
),
'cdef.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,cdef.php:',
'url' => '',
'level' => '2'
),
'clog.php:' => array(
'title' => __('View Cacti Log'),
'mapping' => '',
'url' => 'clog.php',
'level' => '0'
),
'clog.php:preview' => array(
'title' => __('View Cacti Log'),
'mapping' => '',
'url' => 'clog.php',
'level' => '0'
),
'clog_user.php:' => array(
'title' => __('View Cacti Log'),
'mapping' => '',
'url' => 'clog_user.php',
'level' => '0'
),
'clog_user.php:preview' => array(
'title' => __('View Cacti Log'),
'mapping' => '',
'url' => 'clog_user.php',
'level' => '0'
),
'tree.php:' => array(
'title' => __('Graph Trees'),
'mapping' => 'index.php:',
'url' => 'tree.php',
'level' => '1'
),
'tree.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,tree.php:',
'url' => '',
'level' => '2'
),
'color.php:' => array(
'title' => __('Colors'),
'mapping' => 'index.php:',
'url' => 'color.php',
'level' => '1'
),
'color.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,color.php:',
'url' => '',
'level' => '2'
),
'graph_templates.php:' => array(
'title' => __('Graph Templates'),
'mapping' => 'index.php:',
'url' => 'graph_templates.php',
'level' => '1'
),
'graph_templates.php:template_edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,graph_templates.php:',
'url' => '',
'level' => '2'
),
'graph_templates.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,graph_templates.php:',
'url' => '',
'level' => '2'
),
'graph_templates_items.php:item_edit' => array(
'title' => __('Graph Template Items'),
'mapping' => 'index.php:,graph_templates.php:,graph_templates.php:template_edit',
'url' => '',
'level' => '3'
),
'graph_templates_inputs.php:input_edit' => array(
'title' => __('Graph Item Inputs'),
'mapping' => 'index.php:,graph_templates.php:,graph_templates.php:template_edit',
'url' => '',
'level' => '3'
),
'graph_templates_inputs.php:input_remove' => array(
'title' => __('(Remove)'),
'mapping' => 'index.php:,graph_templates.php:,graph_templates.php:template_edit',
'url' => '',
'level' => '3'
),
'host_templates.php:' => array(
'title' => __('Device Templates'),
'mapping' => 'index.php:',
'url' => 'host_templates.php',
'level' => '1'
),
'host_templates.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,host_templates.php:',
'url' => '',
'level' => '2'
),
'host_templates.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,host_templates.php:',
'url' => '',
'level' => '2'
),
'data_templates.php:' => array(
'title' => __('Data Templates'),
'mapping' => 'index.php:',
'url' => 'data_templates.php',
'level' => '1'
),
'data_templates.php:template_edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,data_templates.php:',
'url' => '',
'level' => '2'
),
'data_templates.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,data_templates.php:',
'url' => '',
'level' => '2'
),
'data_sources.php:' => array(
'title' => __('Data Sources'),
'mapping' => 'index.php:',
'url' => 'data_sources.php',
'level' => '1'
),
'data_sources.php:ds_edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,data_sources.php:',
'url' => '',
'level' => '2'
),
'data_sources.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,data_sources.php:',
'url' => '',
'level' => '2'
),
'host.php:' => array(
'title' => __('Devices'),
'mapping' => 'index.php:',
'url' => 'host.php',
'level' => '1'
),
'host.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,host.php:',
'url' => '',
'level' => '2'
),
'host.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,host.php:',
'url' => '',
'level' => '2'
),
'rra.php:' => array(
'title' => __('Round Robin Archives'),
'mapping' => 'index.php:',
'url' => 'rra.php',
'level' => '1'
),
'rra.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,rra.php:',
'url' => '',
'level' => '2'
),
'rra.php:remove' => array(
'title' => __('(Remove)'),
'mapping' => 'index.php:,rra.php:',
'url' => '',
'level' => '2'
),
'data_input.php:' => array(
'title' => __('Data Input Methods'),
'mapping' => 'index.php:',
'url' => 'data_input.php',
'level' => '1'
),
'data_input.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,data_input.php:',
'url' => '',
'level' => '2'
),
'data_input.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,data_input.php:',
'url' => '',
'level' => '2'
),
'data_input.php:remove' => array(
'title' => __('(Remove)'),
'mapping' => 'index.php:,data_input.php:',
'url' => '',
'level' => '2'
),
'data_input.php:field_edit' => array(
'title' => __('Data Input Fields'),
'mapping' => 'index.php:,data_input.php:,data_input.php:edit',
'url' => '',
'level' => '3'
),
'data_input.php:field_remove' => array(
'title' => __('(Remove Item)'),
'mapping' => 'index.php:,data_input.php:,data_input.php:edit',
'url' => '',
'level' => '3'
),
'data_queries.php:' => array(
'title' => __('Data Queries'),
'mapping' => 'index.php:',
'url' => 'data_queries.php',
'level' => '1'
),
'data_queries.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,data_queries.php:',
'url' => '',
'level' => '2'
),
'data_queries.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,data_queries.php:',
'url' => '',
'level' => '2'
),
'data_queries.php:item_edit' => array(
'title' => __('Associated Graph Templates'),
'mapping' => 'index.php:,data_queries.php:,data_queries.php:edit',
'url' => '',
'level' => '3'
),
'data_queries.php:item_remove' => array(
'title' => __('(Remove Item)'),
'mapping' => 'index.php:,data_queries.php:,data_queries.php:edit',
'url' => '',
'level' => '3'
),
'rrdcleaner.php:' => array(
'title' => __('RRD Cleaner'),
'mapping' => 'index.php:,utilities.php:',
'url' => 'rrdcleaner.php',
'level' => '2'
),
'rrdcleaner.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,rrdcleaner.php:',
'url' => 'rrdcleaner.php?action=actions',
'level' => '2'
),
'rrdcleaner.php:restart' => array(
'title' => __('List unused Files'),
'mapping' => 'rrdcleaner.php:',
'url' => 'rrdcleaner.php?action=restart',
'level' => '2'
),
'utilities.php:' => array(
'title' => __('Utilities'),
'mapping' => 'index.php:',
'url' => 'utilities.php',
'level' => '1'
),
'utilities.php:view_poller_cache' => array(
'title' => __('View Poller Cache'),
'mapping' => 'index.php:,utilities.php:',
'url' => 'utilities.php',
'level' => '2'
),
'utilities.php:view_snmp_cache' => array(
'title' => __('View Data Query Cache'),
'mapping' => 'index.php:,utilities.php:',
'url' => 'utilities.php',
'level' => '2'
),
'utilities.php:clear_poller_cache' => array(
'title' => __('View Poller Cache'),
'mapping' => 'index.php:,utilities.php:',
'url' => 'utilities.php',
'level' => '2'
),
'utilities.php:view_logfile' => array(
'title' => __('View Cacti Log'),
'mapping' => 'index.php:,utilities.php:',
'url' => 'utilities.php',
'level' => '2'
),
'utilities.php:clear_logfile' => array(
'title' => __('Clear Cacti Log'),
'mapping' => 'index.php:,utilities.php:',
'url' => 'utilities.php',
'level' => '2'
),
'utilities.php:view_user_log' => array(
'title' => __('View User Log'),
'mapping' => 'index.php:,utilities.php:',
'url' => 'utilities.php',
'level' => '2'
),
'utilities.php:clear_user_log' => array(
'title' => __('Clear User Log'),
'mapping' => 'index.php:,utilities.php:',
'url' => 'utilities.php',
'level' => '2'
),
'utilities.php:view_tech' => array(
'title' => __('Technical Support'),
'mapping' => 'index.php:,utilities.php:',
'url' => 'utilities.php',
'level' => '2'
),
'utilities.php:view_boost_status' => array(
'title' => __('Boost Status'),
'mapping' => 'index.php:,utilities.php:',
'url' => 'utilities.php',
'level' => '2'
),
'utilities.php:view_snmpagent_cache' => array(
'title' => __('View SNMP Agent Cache'),
'mapping' => 'index.php:,utilities.php:',
'url' => 'utilities.php',
'level' => '2'
),
'utilities.php:view_snmpagent_events' => array(
'title' => __('View SNMP Agent Notification Log'),
'mapping' => 'index.php:,utilities.php:',
'url' => 'utilities.php',
'level' => '2'
),
'vdef.php:' => array(
'title' => __('VDEFs'),
'mapping' => 'index.php:',
'url' => 'vdef.php',
'level' => '1'
),
'vdef.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,vdef.php:',
'url' => 'vdef.php',
'level' => '2'
),
'vdef.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,vdef.php:',
'url' => 'vdef.php',
'level' => '2'
),
'vdef.php:remove' => array(
'title' => __('(Remove)'),
'mapping' => 'index.php:,vdef.php:',
'url' => 'vdef.php',
'level' => '2'
),
'vdef.php:item_edit' => array(
'title' => __('VDEF Items'),
'mapping' => 'index.php:,vdef.php:,vdef.php:edit',
'url' => '',
'level' => '3'
),
'managers.php:' => array(
'title' => __('View SNMP Notification Receivers'),
'mapping' => 'index.php:,utilities.php:',
'url' => 'managers.php',
'level' => '2'
),
'managers.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,utilities.php:,managers.php:',
'url' => '',
'level' => '3'
),
'settings.php:' => array(
'title' => __('Cacti Settings'),
'mapping' => 'index.php:',
'url' => 'settings.php',
'level' => '1'
),
'user_admin.php:' => array(
'title' => __('Users'),
'mapping' => 'index.php:',
'url' => 'user_admin.php',
'level' => '1'
),
'user_admin.php:user_edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,user_admin.php:',
'url' => '',
'level' => '2'
),
'user_admin.php:actions' => array(
'title' => __('(Action)'),
'mapping' => 'index.php:,user_admin.php:',
'url' => '',
'level' => '2'
),
'user_domains.php:' => array(
'title' => __('User Domains'),
'mapping' => 'index.php:',
'url' => 'user_domains.php',
'level' => '1'
),
'user_domains.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'user_domains.php:,index.php:',
'url' => 'user_domains.php:edit',
'level' => '2'
),
'user_group_admin.php:' => array(
'title' => __('User Groups'),
'mapping' => 'index.php:',
'url' => 'user_group_admin.php',
'level' => '1'
),
'user_group_admin.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,user_group_admin.php:',
'url' => '',
'level' => '2'
),
'user_group_admin.php:actions' => array(
'title' => __('(Action)'),
'mapping' => 'index.php:,user_group_admin.php:',
'url' => '',
'level' => '2'
),
'about.php:' => array(
'title' => __('About Cacti'),
'mapping' => 'index.php:',
'url' => 'about.php',
'level' => '1'
),
'templates_export.php:' => array(
'title' => __('Export Templates'),
'mapping' => 'index.php:',
'url' => 'templates_export.php',
'level' => '1'
),
'templates_export.php:save' => array(
'title' => __('Export Results'),
'mapping' => 'index.php:,templates_export.php:',
'url' => 'templates_export.php',
'level' => '2'
),
'templates_import.php:' => array(
'title' => __('Import Templates'),
'mapping' => 'index.php:',
'url' => 'templates_import.php',
'level' => '1'
),
'reports_admin.php:' => array(
'title' => __('Reporting'),
'mapping' => '',
'url' => 'reports_admin.php',
'level' => '0'
),
'reports_admin.php:actions' => array(
'title' => __('Report Add'),
'mapping' => 'reports_admin.php:',
'url' => 'reports_admin.php',
'level' => '1'
),
'reports_admin.php:delete' => array(
'title' => __('Report Delete'),
'mapping' => 'reports_admin.php:',
'url' => 'reports_admin.php',
'level' => '1'
),
'reports_admin.php:edit' => array(
'title' => __('Report Edit'),
'mapping' => 'reports_admin.php:',
'url' => 'reports_admin.php?action=edit',
'level' => '1'
),
'reports_admin.php:item_edit' => array(
'title' => __('Report Edit Item'),
'mapping' => 'reports_admin.php:,reports_admin.php:edit',
'url' => '',
'level' => '2'
),
'reports_user.php:' => array(
'title' => __('Reporting'),
'mapping' => '',
'url' => 'reports_user.php',
'level' => '0'
),
'reports_user.php:actions' => array(
'title' => __('Report Add'),
'mapping' => 'reports_user.php:',
'url' => 'reports_user.php',
'level' => '1'
),
'reports_user.php:delete' => array(
'title' => __('Report Delete'),
'mapping' => 'reports_user.php:',
'url' => 'reports_user.php',
'level' => '1'
),
'reports_user.php:edit' => array(
'title' => __('Report Edit'),
'mapping' => 'reports_user.php:',
'url' => 'reports_user.php?action=edit',
'level' => '1'
),
'reports_user.php:item_edit' => array(
'title' => __('Report Edit Item'),
'mapping' => 'reports_user.php:,reports_user.php:edit',
'url' => '',
'level' => '2'
),
'color_templates.php:' => array(
'title' => __('Color Templates'),
'mapping' => 'index.php:',
'url' => 'color_templates.php',
'level' => '1'
),
'color_templates.php:template_edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,color_templates.php:',
'url' => '',
'level' => '2'
),
'color_templates.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,color_templates.php:',
'url' => '',
'level' => '2'
),
'color_templates_items.php:item_edit' => array(
'title' => __('Color Template Items'),
'mapping' => 'index.php:,color_templates.php:,color_templates.php:template_edit',
'url' => '',
'level' => '3'
),
'aggregate_templates.php:' => array(
'title' => __('Aggregate Templates'),
'mapping' => 'index.php:',
'url' => 'aggregate_templates.php',
'level' => '1'
),
'aggregate_templates.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,aggregate_templates.php:',
'url' => '',
'level' => '2'
),
'aggregate_templates.php:actions'=> array(
'title' => __('Actions'),
'mapping' => 'index.php:,aggregate_templates.php:',
'url' => '',
'level' => '2'
),
'aggregate_graphs.php:' => array(
'title' => __('Aggregate Graphs'),
'mapping' => 'index.php:',
'url' => 'aggregate_graphs.php',
'level' => '1'
),
'aggregate_graphs.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,aggregate_graphs.php:',
'url' => '',
'level' => '2'
),
'aggregate_graphs.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,aggregate_graphs.php:',
'url' => '',
'level' => '2'
),
'aggregate_items.php:' => array(
'title' => __('Aggregate Items'),
'mapping' => 'index.php:',
'url' => 'aggregate_items.php',
'level' => '1'
),
'aggregate_items.php:item_edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,aggregate_graphs.php:,aggregate_items.php:',
'url' => '',
'level' => '2'
),
'aggregate_items.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,aggregate_items.php:',
'url' => '',
'level' => '2'
),
'automation_graph_rules.php:' => array(
'title' => __('Graph Rules'),
'mapping' => 'index.php:',
'url' => 'automation_graph_rules.php',
'level' => '1'
),
'automation_graph_rules.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,automation_graph_rules.php:',
'url' => '',
'level' => '2'
),
'automation_graph_rules.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,automation_graph_rules.php:',
'url' => '',
'level' => '2'
),
'automation_graph_rules.php:item_edit' => array(
'title' => __('Graph Rule Items'),
'mapping' => 'index.php:,automation_graph_rules.php:,automation_graph_rules.php:edit',
'url' => '',
'level' => '3'
),
'automation_tree_rules.php:' => array(
'title' => __('Tree Rules'),
'mapping' => 'index.php:',
'url' => 'automation_tree_rules.php',
'level' => '1'
),
'automation_tree_rules.php:edit' => array(
'title' => __('(Edit)'),
'mapping' => 'index.php:,automation_tree_rules.php:',
'url' => '',
'level' => '2'
),
'automation_tree_rules.php:actions' => array(
'title' => __('Actions'),
'mapping' => 'index.php:,automation_tree_rules.php:',
'url' => '',
'level' => '2'
),
'automation_tree_rules.php:item_edit' => array(
'title' => __('Tree Rule Items'),
'mapping' => 'index.php:,automation_tree_rules.php:,automation_tree_rules.php:edit',
'url' => '',
'level' => '3'
)
);
$nav = api_plugin_hook_function('draw_navigation_text', $nav);
$current_page = get_current_page();
if (!isempty_request_var('action')) {
get_filter_request_var('action', FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^([-a-zA-Z0-9_\s]+)$/')));
}
$current_action = (isset_request_var('action') ? get_request_var('action') : '');
/* find the current page in the big array */
if (isset($nav[$current_page . ':' . $current_action])) {
$current_array = $nav[$current_page . ':' . $current_action];
} else {
$current_array = array(
'mapping' => 'index.php:',
'title' => ucwords(str_replace('_', ' ', basename(get_current_page(), '.php'))),
'level' => 1
);
}
if (isset($current_array['mapping'])) {
$current_mappings = explode(',', $current_array['mapping']);
} else {
$current_mappings = array();
}
$current_nav = "
";
$title = '';
$nav_count = 0;
/* resolve all mappings to build the navigation string */
for ($i=0; ($i") . html_escape(resolve_navigation_variables($nav[$nav_level_cache[$i]['id']]['title'])) . (empty($url) ? '' : '' . (get_selected_theme() == 'classic' ? ' -> ':'') . '');
$title .= html_escape(resolve_navigation_variables($nav[$nav_level_cache[$i]['id']]['title'])) . ' -> ';
}
} else {
/* there is no '?' - pull from the above array */
$current_nav .= (empty($url) ? '' : "- ") . html_escape(resolve_navigation_variables($nav{basename($current_mappings[$i])}['title'])) . (empty($url) ? '' : '' . (get_selected_theme() == 'classic' ? ' -> ':'') . '
');
$title .= html_escape(resolve_navigation_variables($nav{basename($current_mappings[$i])}['title'])) . ' -> ';
}
$nav_count++;
}
if ($nav_count) {
if (isset($current_array['title'])) {
$current_nav .= "- " . html_escape(resolve_navigation_variables($current_array['title'])) . '
';
}
} else {
$current_array = $nav[$current_page . ':' . $current_action];
$url = (isset($current_array['url']) ? $current_array['url']:'');
if (isset($current_array['title'])) {
$current_nav .= "- " . html_escape(resolve_navigation_variables($current_array['title'])) . '
';
}
}
if (isset_request_var('tree_id') || isset_request_var('leaf_id')) {
if (isset_request_var('leaf_id') && get_nfilter_request_var('leaf_id') != '') {
$leaf = db_fetch_row_prepared('SELECT host_id, title, graph_tree_id FROM graph_tree_items WHERE id = ?', array(get_filter_request_var('leaf_id')));
if (sizeof($leaf)) {
if ($leaf['host_id'] > 0) {
$leaf_name = db_fetch_cell_prepared('SELECT description FROM host WHERE id = ?', array($leaf['host_id']));
} else {
$leaf_name = $leaf['title'];
}
$tree_name = db_fetch_cell_prepared('SELECT name FROM graph_tree WHERE id = ?', array($leaf['graph_tree_id']));
} else {
$leaf_name = __('Leaf');
$tree_name = '';
}
if (isset_request_var('host_group_data') && get_nfilter_request_var('host_group_data') != '') {
$parts = explode(':', get_nfilter_request_var('host_group_data'));
input_validate_input_number($parts[1]);
if ($parts[0] == 'graph_template') {
$leaf_sub = db_fetch_cell_prepared('SELECT name FROM graph_templates WHERE id = ?', array($parts[1]));
} else {
if ($parts[1] > 0) {
$leaf_sub = db_fetch_cell_prepared('SELECT name FROM snmp_query WHERE id = ?', array($parts[1]));
} else {
$leaf_sub = __('Non Query Based');
}
}
} else {
$leaf_sub = '';
}
} else {
$leaf_name = '';
$leaf_sub = '';
if (isset_request_var('tree_id')) {
$tree_name = db_fetch_cell_prepared('SELECT name FROM graph_tree WHERE id = ?', array(get_filter_request_var('tree_id')));
} else {
$tree_name = '';
}
}
$tree_title = $tree_name . ($leaf_name != '' ? ' (' . $leaf_name:'') . ($leaf_sub != '' ? ':' . $leaf_sub . ')':($leaf_name != '' ? ')':''));
if ($tree_title != '') {
$current_nav .= "- " . html_escape($tree_title) . '
';
}
} elseif (preg_match('#link.php\?id=(\d+)#', $_SERVER['REQUEST_URI'], $matches)) {
$externalLinks = db_fetch_row_prepared('SELECT title, style FROM external_links WHERE id = ?', array($matches[1]));
$title = $externalLinks['title'];
$style = $externalLinks['style'];
if ($style == 'CONSOLE') {
$current_nav = "- " . __('Console') . '' . (get_selected_theme() == 'classic' ? ' -> ':'') . '
';
$current_nav .= "- Link " . $title . '
';
} else {
$current_nav = "- " . $title . '
';
}
$tree_title = '';
} else {
$tree_title = '';
}
if (isset($current_array['title'])) {
$title .= html_escape(resolve_navigation_variables($current_array['title']) . ' ' . $tree_title);
}
/* keep a cache for each level we encounter */
$nav_level_cache[$current_array['level']] = array(
'id' => $current_page . ':' . $current_action,
'url' => get_browser_query_string()
);
$current_nav .= '
';
$_SESSION['sess_nav_level_cache'] = $nav_level_cache;
if ($type == 'url') {
return $current_nav;
} else {
return $title;
}
}
/* resolve_navigation_variables - substitute any variables contained in the navigation text
@arg $text - the text to substitute in
@returns - the original navigation text with all substitutions made */
function resolve_navigation_variables($text) {
$graphTitle = get_graph_title(get_filter_request_var('local_graph_id'));
if (preg_match_all("/\|([a-zA-Z0-9_]+)\|/", $text, $matches)) {
for ($i=0; $i $name) {
if ($timespan > $index) {
$last = $index;
continue;
} elseif ($timespan == $index) {
return $index;
} else {
return $last;
}
}
return $last;
}
/* get_browser_query_string - returns the full url, including args requested by the browser
@returns - the url requested by the browser */
function get_browser_query_string() {
if (!empty($_SERVER['REQUEST_URI'])) {
return sanitize_uri($_SERVER['REQUEST_URI']);
} else {
return sanitize_uri(get_current_page() . (empty($_SERVER['QUERY_STRING']) ? '' : '?' . $_SERVER['QUERY_STRING']));
}
}
/* get_current_page - returns the basename of the current page in a web server friendly way
@returns - the basename of the current script file */
function get_current_page($basename = true) {
if (isset($_SERVER['PHP_SELF']) && $_SERVER['PHP_SELF'] != '') {
if ($basename) {
return basename($_SERVER['PHP_SELF']);
} else {
return $_SERVER['PHP_SELF'];
}
} elseif (isset($_SERVER['SCRIPT_NAME']) && $_SERVER['SCRIPT_NAME'] != '') {
if ($basename) {
return basename($_SERVER['SCRIPT_NAME']);
} else {
return $_SERVER['SCRIPT_NAME'];
}
} elseif (isset($_SERVER['SCRIPT_FILENAME']) && $_SERVER['SCRIPT_FILENAME'] != '') {
if ($basename) {
return basename($_SERVER['SCRIPT_FILENAME']);
} else {
return $_SERVER['SCRIPT_FILENAME'];
}
} else {
cacti_log('ERROR: unable to determine current_page');
}
return false;
}
/* get_hash_graph_template - returns the current unique hash for a graph template
@arg $graph_template_id - (int) the ID of the graph template to return a hash for
@arg $sub_type (optional) return the hash for a particlar sub-type of this type
@returns - a 128-bit, hexadecimal hash */
function get_hash_graph_template($graph_template_id, $sub_type = 'graph_template') {
switch ($sub_type) {
case 'graph_template':
$hash = db_fetch_cell_prepared('SELECT hash FROM graph_templates WHERE id = ?', array($graph_template_id));
break;
case 'graph_template_item':
$hash = db_fetch_cell_prepared('SELECT hash FROM graph_templates_item WHERE id = ?', array($graph_template_id));
break;
case 'graph_template_input':
$hash = db_fetch_cell_prepared('SELECT hash FROM graph_template_input WHERE id = ?', array($graph_template_id));
break;
default:
return generate_hash();
break;
}
if (preg_match('/[a-fA-F0-9]{32}/', $hash)) {
return $hash;
} else {
return generate_hash();
}
}
/* get_hash_data_template - returns the current unique hash for a data template
@arg $graph_template_id - (int) the ID of the data template to return a hash for
@arg $sub_type (optional) return the hash for a particlar sub-type of this type
@returns - a 128-bit, hexadecimal hash */
function get_hash_data_template($data_template_id, $sub_type = 'data_template') {
switch ($sub_type) {
case 'data_template':
$hash = db_fetch_cell_prepared('SELECT hash FROM data_template WHERE id = ?', array($data_template_id));
break;
case 'data_template_item':
$hash = db_fetch_cell_prepared('SELECT hash FROM data_template_rrd WHERE id = ?', array($data_template_id));
break;
default:
return generate_hash();
break;
}
if (preg_match('/[a-fA-F0-9]{32}/', $hash)) {
return $hash;
} else {
return generate_hash();
}
}
/* get_hash_data_input - returns the current unique hash for a data input method
@arg $graph_template_id - (int) the ID of the data input method to return a hash for
@arg $sub_type (optional) return the hash for a particlar sub-type of this type
@returns - a 128-bit, hexadecimal hash */
function get_hash_data_input($data_input_id, $sub_type = 'data_input_method') {
switch ($sub_type) {
case 'data_input_method':
$hash = db_fetch_cell_prepared('SELECT hash FROM data_input WHERE id = ?', array($data_input_id));
break;
case 'data_input_field':
$hash = db_fetch_cell_prepared('SELECT hash FROM data_input_fields WHERE id = ?', array($data_input_id));
break;
default:
return generate_hash();
break;
}
if (preg_match('/[a-fA-F0-9]{32}/', $hash)) {
return $hash;
} else {
return generate_hash();
}
}
/* get_hash_cdef - returns the current unique hash for a cdef
@arg $graph_template_id - (int) the ID of the cdef to return a hash for
@arg $sub_type (optional) return the hash for a particlar sub-type of this type
@returns - a 128-bit, hexadecimal hash */
function get_hash_cdef($cdef_id, $sub_type = 'cdef') {
if (!is_numeric($cdef_id)) {
return generate_hash();
}
switch ($sub_type) {
case 'cdef':
$hash = db_fetch_cell_prepared('SELECT hash FROM cdef WHERE id = ?', array($cdef_id));
break;
case 'cdef_item':
$hash = db_fetch_cell_prepared('SELECT hash FROM cdef_items WHERE id = ?', array($cdef_id));
break;
default:
return generate_hash();
break;
}
if (strlen($hash) == 32 && ctype_xdigit($hash)) {
return $hash;
} else {
return generate_hash();
}
}
/* get_hash_gprint - returns the current unique hash for a gprint preset
@arg $graph_template_id - (int) the ID of the gprint preset to return a hash for
@returns - a 128-bit, hexadecimal hash */
function get_hash_gprint($gprint_id) {
$hash = db_fetch_cell_prepared('SELECT hash FROM graph_templates_gprint WHERE id = ?', array($gprint_id));
if (strlen($hash) == 32 && ctype_xdigit($hash)) {
return $hash;
} else {
return generate_hash();
}
}
/**
* returns the current unique hash for a vdef
* @param $graph_template_id - (int) the ID of the vdef to return a hash for
* @param $sub_type (optional) return the hash for a particlar sub-type of this type
* @returns - a 128-bit, hexadecimal hash */
function get_hash_vdef($vdef_id, $sub_type = "vdef") {
switch ($sub_type) {
case 'vdef':
$hash = db_fetch_cell_prepared('SELECT hash FROM vdef WHERE id = ?', array($vdef_id));
break;
case 'vdef_item':
$hash = db_fetch_cell_prepared('SELECT hash FROM vdef_items WHERE id = ?', array($vdef_id));
break;
default:
return generate_hash();
break;
}
if (strlen($hash) == 32 && ctype_xdigit($hash)) {
return $hash;
} else {
return generate_hash();
}
}
/**
* returns the current unique hash for a vdef
* @param $data_source_profile_id - (int) the ID of the data_source_profile to return a hash for
* @returns - a 128-bit, hexadecimal hash */
function get_hash_data_source_profile($data_source_profile_id) {
$hash = db_fetch_cell_prepared('SELECT hash FROM data_source_profiles WHERE id = ?', array($data_source_profile_id));
if (strlen($hash) == 32 && ctype_xdigit($hash)) {
return $hash;
} else {
return generate_hash();
}
}
/* get_hash_host_template - returns the current unique hash for a gprint preset
@arg $host_template_id - (int) the ID of the host template to return a hash for
@returns - a 128-bit, hexadecimal hash */
function get_hash_host_template($host_template_id) {
$hash = db_fetch_cell_prepared('SELECT hash FROM host_template WHERE id = ?', array($host_template_id));
if (strlen($hash) == 32 && ctype_xdigit($hash)) {
return $hash;
} else {
return generate_hash();
}
}
/* get_hash_data_query - returns the current unique hash for a data query
@arg $graph_template_id - (int) the ID of the data query to return a hash for
@arg $sub_type (optional) return the hash for a particlar sub-type of this type
@returns - a 128-bit, hexadecimal hash */
function get_hash_data_query($data_query_id, $sub_type = 'data_query') {
switch ($sub_type) {
case 'data_query':
$hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query WHERE id = ?', array($data_query_id));
break;
case 'data_query_graph':
$hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query_graph WHERE id = ?', array($data_query_id));
break;
case 'data_query_sv_data_source':
$hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query_graph_rrd_sv WHERE id = ?', array($data_query_id));
break;
case 'data_query_sv_graph':
$hash = db_fetch_cell_prepared('SELECT hash FROM snmp_query_graph_sv WHERE id = ?', array($data_query_id));
break;
default:
return generate_hash();
break;
}
if (strlen($hash) == 32 && ctype_xdigit($hash)) {
return $hash;
} else {
return generate_hash();
}
}
/* get_hash_version - returns the item type and cacti version in a hash format
@arg $type - the type of item to represent ('graph_template','data_template',
'data_input_method','cdef','vdef','gprint_preset','data_query','host_template')
@returns - a 24-bit hexadecimal hash (8-bits for type, 16-bits for version) */
function get_hash_version($type) {
global $hash_type_codes, $cacti_version_codes, $config;
return $hash_type_codes[$type] . $cacti_version_codes[CACTI_VERSION];
}
/* generate_hash - generates a new unique hash
@returns - a 128-bit, hexadecimal hash */
function generate_hash() {
return md5(session_id() . microtime() . rand(0,1000));
}
/* debug_log_insert_section_start - creates a header item for breaking down the debug log
@arg $type - the 'category' or type of debug message
@arg $text - section header */
function debug_log_insert_section_start($type, $text, $allowcopy = false) {
$copy_prefix = '';
$copy_dataid = '';
if ($allowcopy) {
$uid = generate_hash();
$copy_prefix = '';
$copy_dataid = ' id=\'clipboardData'.$uid.'\'';
$copy_headerid = ' id=\'clipboardHeader'.$uid.'\'';
}
debug_log_insert($type, '');
}
/* debug_log_insert_section_end - finalizes the header started with the start function
@arg $type - the 'category' or type of debug message */
function debug_log_insert_section_end($type) {
debug_log_insert($type, " |
|
");
}
/* debug_log_insert - inserts a line of text into the debug log
@arg $type - the 'category' or type of debug message
@arg $text - the actual debug message */
function debug_log_insert($type, $text) {
global $config;
if ($config['poller_id'] == 1 || isset($_SESSION)) {
if (!isset($_SESSION['debug_log'][$type])) {
$_SESSION['debug_log'][$type] = array();
}
array_push($_SESSION['debug_log'][$type], $text);
} else {
if (!isset($config['debug_log'][$type])) {
$config['debug_log'][$type] = array();
}
array_push($config['debug_log'][$type], $text);
}
}
/* debug_log_clear - clears the debug log for a particular category
@arg $type - the 'category' to clear the debug log for. omitting this argument
implies all categories */
function debug_log_clear($type = '') {
if ($type == '') {
kill_session_var('debug_log');
} else {
if (isset($_SESSION['debug_log'])) {
unset($_SESSION['debug_log'][$type]);
}
}
}
/* debug_log_return - returns the debug log for a particular category
@arg $type - the 'category' to return the debug log for.
@returns - the full debug log for a particular category */
function debug_log_return($type) {
$log_text = '';
if ($type == 'new_graphs') {
if (isset($_SESSION['debug_log'][$type])) {
$log_text .= "";
for ($i=0; $i';
}
$log_text .= '
';
}
} else {
if (isset($_SESSION['debug_log'][$type])) {
$log_text .= "";
foreach($_SESSION['debug_log'][$type] as $key => $val) {
$log_text .= "| $val |
\n";
unset($_SESSION['debug_log'][$type][$key]);
}
$log_text .= '
';
}
}
return $log_text;
}
/* sanitize_search_string - cleans up a search string submitted by the user to be passed
to the database. NOTE: some of the code for this function came from the phpBB project.
@arg $string - the original raw search string
@returns - the sanitized search string */
function sanitize_search_string($string) {
static $drop_char_match = array('(',')','^', '$', '<', '>', '`', '\'', '"', '|', ',', '?', '+', '[', ']', '{', '}', '#', ';', '!', '=', '*');
static $drop_char_replace = array('','',' ', ' ', ' ', ' ', '', '', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ');
/* Replace line endings by a space */
$string = preg_replace('/[\n\r]/is', ' ', $string);
/* HTML entities like */
$string = preg_replace('/\b&[a-z]+;\b/', ' ', $string);
/* Remove URL's */
$string = preg_replace('/\b[a-z0-9]+:\/\/[a-z0-9\.\-]+(\/[a-z0-9\?\.%_\-\+=&\/]+)?/', ' ', $string);
/* Filter out strange characters like ^, $, &, change "it's" to "its" */
for($i = 0; $i < count($drop_char_match); $i++) {
$string = str_replace($drop_char_match[$i], $drop_char_replace[$i], $string);
}
return $string;
}
/** cleans up a URI, e.g. from REQUEST_URI and/or QUERY_STRING
* in case of XSS attac, expect the result to be broken
* we do NOT sanitize in a way, that attacs are converted to valid HTML
* it is ok, when the result is broken but the application stays alive
* @arg string $uri - the uri to be sanitized
* @returns string - the sanitized uri
*/
function sanitize_uri($uri) {
static $drop_char_match = array('^', '$', '<', '>', '`', '\'', '"', '|', '+', '[', ']', '{', '}', ';', '!');
static $drop_char_replace = array( '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
return str_replace($drop_char_match, $drop_char_replace, strip_tags(urldecode($uri)));
}
/** Checks to see if a string is base64 encoded
* @arg string $data - the string to be validated
* @returns boolean - true is the string is base64 otherwise false
*/
function is_base64_encoded($data) {
// Perform a simple check first
if (!preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $data)) {
return false;
}
// Now test with the built-in function
$ndata = base64_decode($data, true);
if ($ndata === false) {
return false;
}
// Do a re-encode test and compare
if (base64_encode($ndata) != $data) {
return false;
}
return true;
}
/** cleans up a CDEF/VDEF string
* the CDEF/VDEF must have passed all magic string replacements beforehand
* @arg string $cdef - the CDEF/VDEF to be sanitized
* @returns string - the sanitized CDEF/VDEF
*/
function sanitize_cdef($cdef) {
static $drop_char_match = array('^', '$', '<', '>', '`', '\'', '"', '|', '[', ']', '{', '}', ';', '!');
static $drop_char_replace = array( '', '', '', '', '', '', '', '', '', '', '', '', '', '');
return str_replace($drop_char_match, $drop_char_replace, $cdef);
}
/** verifies all selected items are numeric to guard against injection
* @arg array $items - an array of serialized items from a post
* @returns array - the sanitized selected items array
*/
function sanitize_unserialize_selected_items($items) {
if ($items != '') {
$items = unserialize(stripslashes($items));
if (is_array($items)) {
foreach ($items as $item) {
if (is_array($item)) {
return false;
} elseif (!is_numeric($item) && ($item != '')) {
return false;
}
}
} else {
return false;
}
} else {
return false;
}
return $items;
}
function cacti_escapeshellcmd($string) {
global $config;
if ($config['cacti_server_os'] == 'unix') {
return escapeshellcmd($string);
} else {
$replacements = "#&;`|*?<>^()[]{}$\\";
for ($i=0; $i < strlen($replacements); $i++) {
$string = str_replace($replacements[$i], ' ', $string);
}
return $string;
}
}
/**
* mimics escapeshellarg, even for windows
* @param $string - the string to be escaped
* @param $quote - true: do NOT remove quotes from result; false: do remove quotes
* @return - the escaped [quoted|unquoted] string
*/
function cacti_escapeshellarg($string, $quote = true) {
global $config;
/* we must use an apostrophe to escape community names under Unix in case the user uses
characters that the shell might interpret. the ucd-snmp binaries on Windows flip out when
you do this, but are perfectly happy with a quotation mark. */
if ($config['cacti_server_os'] == 'unix') {
$string = escapeshellarg($string);
if ( $quote ) {
return $string;
} else {
# remove first and last char
return substr($string, 1, (strlen($string)-2));
}
} else {
/* escapeshellarg takes care of different quotation for both linux and windows,
* but unfortunately, it blanks out percent signs
* we want to keep them, e.g. for GPRINT format strings
* so we need to create our own escapeshellarg
* on windows, command injection requires to close any open quotation first
* so we have to escape any quotation here */
if (substr_count($string, CACTI_ESCAPE_CHARACTER)) {
$string = str_replace(CACTI_ESCAPE_CHARACTER, "\\" . CACTI_ESCAPE_CHARACTER, $string);
}
/* ... before we add our own quotation */
if ($quote) {
return CACTI_ESCAPE_CHARACTER . $string . CACTI_ESCAPE_CHARACTER;
} else {
return $string;
}
}
}
/**
* set a page refresh in Cacti through a callback
* @param $refresh - an array containing the page, seconds, and logout
* @return - nill
*/
function set_page_refresh($refresh) {
if (isset($refresh['seconds'])) {
$_SESSION['refresh']['seconds'] = $refresh['seconds'];
}
if (isset($refresh['logout'])) {
if ($refresh['logout'] == 'true' || $refresh['logout'] === true) {
$_SESSION['refresh']['logout'] = 'true';
} else {
$_SESSION['refresh']['logout'] = 'false';
}
} else {
$_SESSION['refresh']['logout'] = 'true';
}
if (isset($refresh['page'])) {
$_SESSION['refresh']['page'] = $refresh['page'];
}
}
function bottom_footer() {
global $config;
include($config['base_path'] . '/include/global_session.php');
if (!isset_request_var('header') || get_nfilter_request_var('header') == 'true') {
/* display output messages */
display_messages();
include($config['base_path'] . '/include/bottom_footer.php');
} else {
/* display output messages */
display_messages();
/* we use this session var to store field values for when a save fails,
this way we can restore the field's previous values. we reset it here, because
they only need to be stored for a single page */
kill_session_var('sess_field_values');
/* close the session */
session_write_close();
/* make sure the debug log doesn't get too big */
debug_log_clear();
/* close the database connection */
db_close();
}
}
function display_messages() {
?>
name format
* @arg $cc - either a string of comma delimited email addresses, or an array of addresses in email_address => name format
* @arg $bcc - either a string of comma delimited email addresses, or an array of addresses in email_address => name format
* @arg $replyto - a string email address, or an array in array(email_address, name format)
* @arg $subject - the email subject
* @arg $body - the email body, in HTML format. If content_text is not set, the function will attempt to extract
* from the HTML format.
* @arg $body_text - the email body in TEXT format. If set, it will override the stripping tags method
* @arg $attachments - the emails attachments as an array
* @arg $headers - an array of name value pairs representing custom headers.
* @arg $html - if set to true, html is the default, otherwise text format will be used
*/
function mailer($from, $to, $cc, $bcc, $replyto, $subject, $body, $body_text = '', $attachments = '', $headers = '', $html = true) {
global $config;
include_once($config['include_path'] . '/phpmailer/PHPMailerAutoload.php');
// Set the to informaiotn
if ($to == '') {
return __('Mailer Error: No TO address set!!
If using the Test Mail link, please set the Alert e-mail setting.');
}
/* perform data substitution */
if (strpos($subject, '|date_time|') !== false) {
$date = read_config_option('date');
if (!empty($date)) {
$time = strtotime($date);
} else {
$time = time();
}
$subject = str_replace('|date_time|', date(CACTI_DATE_TIME_FORMAT, $time), $subject);
}
if (is_array($to)) {
$toText = $to[1] . ' <' . $to[0] . '>';
} else {
$toText = $to;
}
if (is_array($from)) {
$fromText = $from[1] . ' <' . $from[0] . '>';
} else {
$fromText = $from;
}
$body = str_replace('', $subject, $body);
$body = str_replace('', $toText, $body);
$body = str_replace('', $fromText, $body);
// Create the PHPMailer instance
$mail = new PHPMailer;
// Set a reasonable timeout of 5 seconds
$timeout = read_config_option('settings_smtp_timeout');
if (empty($timeout) || $timeout < 0 || $timeout > 300) {
$mail->Timeout = 5;
} else {
$mail->Timeout = $timeout;
}
// Set the subject
$mail->Subject = $subject;
// Support i18n
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
$how = read_config_option('settings_how');
if ($how < 0 || $how > 2) {
$how = 0;
}
if ($how == 0) {
$mail->isMail();
} else if ($how == 1) {
$mail->Sendmail = read_config_option('settings_sendmail_path');
$mail->isSendmail();
} else if ($how == 2) {
$mail->isSMTP();
$mail->Host = read_config_option('settings_smtp_host');
$mail->Port = read_config_option('settings_smtp_port');
if (read_config_option('settings_smtp_username') != '') {
$mail->SMTPAuth = true;
$mail->Username = read_config_option('settings_smtp_username');
if (read_config_option('settings_smtp_password') != '') {
$mail->Password = read_config_option('settings_smtp_password');
}
} else {
$mail->SMTPAuth = false;
}
// Set a reasonable timeout of 5 seconds
$timeout = read_config_option('settings_smtp_timeout');
if (empty($timeout) || $timeout < 0 || $timeout > 300) {
$mail->Timeout = 10;
} else {
$mail->Timeout = $timeout;
}
$secure = read_config_option('settings_smtp_secure');
if (!empty($secure) && $secure != 'none') {
$mail->SMTPSecure = true;
if (substr_count($mail->Host, ':') == 0) {
$mail->Host = $secure . '://' . $mail->Host;
}
} else {
$mail->SMTPSecure = false;
}
}
// Set the from information
if (!is_array($from)) {
$fromname = '';
if ($from == '') {
$fromname = read_config_option('settings_from_name');
if (isset($_SERVER['HOSTNAME'])) {
$from = 'Cacti@' . $_SERVER['HOSTNAME'];
} else {
$from = 'Cacti@cacti.net';
}
if ($fromname == '') {
$fromname = 'Cacti';
}
}
$mail->setFrom($from, $fromname);
} else {
$mail->setFrom($from[0], $from[1]);
}
if (!is_array($to)) {
$to = explode(',', $to);
foreach($to as $t) {
$t = trim($t);
if ($t != '') {
$mail->addAddress($t);
}
}
} else {
foreach($to as $email => $name) {
$mail->addAddress($email, $name);
}
}
if (!is_array($cc)) {
if ($cc != '') {
$cc = explode(',', $cc);
foreach($cc as $c) {
$c = trim($c);
$mail->addCC($c);
}
}
} else {
foreach($cc as $email => $name) {
$mail->addCC($email, $name);
}
}
if (!is_array($bcc)) {
if ($bcc != '') {
$bcc = explode(',', $bcc);
foreach($bcc as $bc) {
$bc = trim($bc);
$mail->addBCC($bc);
}
}
} else {
foreach($bcc as $email => $name) {
$mail->addBCC($email, $name);
}
}
if (!is_array($replyto)) {
if ($replyto != '') {
$mail->addReplyTo($replyto);
}
} else {
$mail->addReplyTo($replyto[0], $replyto[1]);
}
// Set the wordwrap limits
$wordwrap = read_config_option('settings_wordwrap');
if ($wordwrap == '') {
$wordwrap = 76;
} elseif ($wordwrap > 9999) {
$wordwrap = 9999;
} elseif ($wordwrap < 0) {
$wordwrap = 76;
}
$mail->WordWrap = $wordwrap;
$mail->setWordWrap();
$i = 0;
// Handle Graph Attachments
if (is_array($attachments) && sizeof($attachments) && substr_count($body, '') > 0) {
foreach($attachments as $attachment) {
if ($attachment['attachment'] != '') {
/* get content id and create attachment */
$cid = getmypid() . '_' . $i . '@' . 'localhost';
/* attempt to attach */
if ($mail->addStringEmbeddedImage($attachment['attachment'], $cid, $attachment['filename'], 'base64', $attachment['mime_type'], $attachment['inline']) === false) {
cacti_log('ERROR: ' . $mail->ErrorInfo, false);
return $mail->ErrorInfo;
}
$body = str_replace('', "
", $body);
$i++;
} else {
$body = str_replace('' . $attachment['local_graph_id'] . '>', "
Could not open!
" . $attachment['filename'], $body);
}
}
} elseif (is_array($attachments) && sizeof($attachments) && substr_count($body, ' 0) {
foreach($attachments as $attachment) {
if ($attachment['attachment'] != '') {
/* get content id and create attachment */
$cid = getmypid() . '_' . $i . '@' . 'localhost';
/* attempt to attach */
if ($mail->addStringEmbeddedImage($attachment['attachment'], $cid, $attachment['filename'], 'base64', $attachment['mime_type'], $attachment['inline']) === false) {
cacti_log('ERROR: ' . $mail->ErrorInfo, false);
return $mail->ErrorInfo;
}
/* handle the body text */
switch ($attachment['inline']) {
case 'inline':
$body = str_replace('', "
", $body);
break;
case 'attachment':
$body = str_replace('', '', $body);
break;
}
$i++;
} else {
$body = str_replace('', "
Could not open!
" . $attachment['filename'], $body);
}
}
}
/* process custom headers */
if (is_array($headers) && sizeof($headers)) {
foreach($headers as $name => $value) {
$mail->addCustomHeader($name, $value);
}
}
// Set both html and non-html bodies
$text = array('text' => '', 'html' => '');
if ($body_text != '' && $html == true) {
$text['html'] = $body . '
';
$text['text'] = $body_text;
$mail->isHTML(true);
$mail->Body = $text['html'];
$mail->AltBody = $text['text'];
} elseif ($attachments == '' && $html == false) {
if ($body_text != '') {
$body = $body_text;
} else {
$body = str_replace('
', "\n", $body);
$body = str_replace('
', "\n", $body);
$body = str_replace('', "\n", $body);
}
$text['text'] = strip_tags($body);
$mail->isHTML(false);
$mail->Body = $text['text'];
} elseif ($html == false) {
$text['text'] = strip_tags($body);
$mail->isHTML(false);
$mail->Body = $text['text'];
} else {
$text['html'] = $body . '
';
$text['text'] = strip_tags(str_replace('
', "\n", $body));
$mail->isHTML(true);
$mail->Body = $text['html'];
$mail->AltBody = $text['text'];
}
if ($mail->send()) {
cacti_log("Mail Sucessfully Sent to '" . $toText . "', Subject: '" . $mail->Subject . "'", false, 'MAILER');
return '';
} else {
cacti_log("Mail Failed to '" . $toText . "', Subject: '" . $mail->Subject . "'", false, 'MAILER');
return $mail->ErrorInfo;
}
}
function ping_mail_server($host, $port, $user, $password, $timeout = 10, $secure = 'none') {
global $config;
include_once($config['include_path'] . '/phpmailer/PHPMailerAutoload.php');
//Create a new SMTP instance
$smtp = new SMTP;
if (!empty($secure) && $secure != 'none') {
$smtp->SMTPSecure = $secure;
if (substr_count($host, ':') == 0) {
$host = $secure . '://' . $host;
}
}
//Enable connection-level debug output
$smtp->do_debug = 0;
//$smtp->do_debug = SMTP::DEBUG_LOWLEVEL;
$results = true;
try {
//Connect to an SMTP server
if ($smtp->connect($host, $port, $timeout)) {
//Say hello
if ($smtp->hello(gethostbyname(gethostname()))) { //Put your host name in here
//Authenticate
if ($user != '') {
if ($smtp->authenticate($user, $password)) {
$results = true;
} else {
throw new Exception(__('Authentication failed: %s', $smtp->getLastReply()));
}
}
} else {
throw new Exception(__('HELO failed: %s', $smtp->getLastReply()));
}
} else {
throw new Exception(__('Connect failed: %s', $smtp->getLastReply()));
}
} catch (Exception $e) {
$results = __('SMTP error: ') . $e->getMessage();
cacti_log($results);
}
//Whatever happened, close the connection.
$smtp->quit(true);
return $results;
}
function email_test() {
global $config;
$message = __('This is a test message generated from Cacti. This message was sent to test the configuration of your Mail Settings.') . '
';
$message .= __('Your email settings are currently set as follows') . '
';
$message .= '' . __('Method') . ': ';
print __('Checking Configuration...
');
$ping_results = true;
$how = read_config_option('settings_how');
if ($how < 0 || $how > 2)
$how = 0;
if ($how == 0) {
$mail = __('PHP\'s Mailer Class');
} else if ($how == 1) {
$mail = __('Sendmail') . '
' . __('Sendmail Path'). ': ';
$sendmail = read_config_option('settings_sendmail_path');
$mail .= $sendmail;
} else if ($how == 2) {
print __('Method: SMTP') . '
';
$mail = __('SMTP') . '
';
$smtp_host = read_config_option('settings_smtp_host');
$smtp_port = read_config_option('settings_smtp_port');
$smtp_username = read_config_option('settings_smtp_username');
$smtp_password = read_config_option('settings_smtp_password');
$smtp_secure = read_config_option('settings_smtp_secure');
$smtp_timeout = read_config_option('settings_smtp_timeout');
$mail .= "" . __('Device') . ": $smtp_host
";
$mail .= "" . __('Port') . ": $smtp_port
";
if ($smtp_username != '' && $smtp_password != '') {
$mail .= '' . __('Authentication') . ': true
';
$mail .= '' . __('Username') . ": $smtp_username
";
$mail .= '' . __('Password') . ': (' . __('Not Shown for Security Reasons') . ')
';
$mail .= '' . __('Security') . ": $smtp_secure
";
} else {
$mail .= '' . __('Authentication') . ': false
';
}
if (read_config_option('settings_ping_mail') == 0) {
$ping_results = ping_mail_server($smtp_host, $smtp_port, $smtp_username, $smtp_password, $smtp_timeout, $smtp_secure);
print __('Ping Results:') . ' ' . ($ping_results == 1 ? __('Success'):$ping_results) . '
';
if ($ping_results != 1) {
$mail .= '' . __('Ping Results') . ': ' . $ping_results . '
';
} else {
$mail .= '' . __('Ping Results') . ': ' . __('Success') . '
';
}
} else {
$ping_results = 1;
$mail .= '' . __('Ping Results') . ': ' . __('Bypassed') . '
';
}
}
$message .= $mail;
$message .= '
';
$errors = '';
if ($ping_results == 1) {
print __('Creating Message Text...') . '
';
print "
";
print __('Sending Message...') . '
';
$global_alert_address = read_config_option('settings_test_email');
$errors = send_mail($global_alert_address, '', __('Cacti Test Message'), $message, '', '', true);
if ($errors == '') {
$errors = __('Success!');
}
} else {
print __('Message Not Sent due to ping failure.'). '
';
}
print "";
}
/* gethostbyaddr_wtimeout - This function provides a good method of performing
a rapid lookup of a DNS entry for a host so long as you don't have to look far.
*/
function get_dns_from_ip ($ip, $dns, $timeout = 1000) {
/* random transaction number (for routers etc to get the reply back) */
$data = rand(10, 99);
/* trim it to 2 bytes */
$data = substr($data, 0, 2);
/* create request header */
$data .= "\1\0\0\1\0\0\0\0\0\0";
/* split IP into octets */
$octets = explode('.', $ip);
/* perform a quick error check */
if (count($octets) != 4) return 'ERROR';
/* needs a byte to indicate the length of each segment of the request */
for ($x=3; $x>=0; $x--) {
switch (strlen($octets[$x])) {
case 1: // 1 byte long segment
$data .= "\1"; break;
case 2: // 2 byte long segment
$data .= "\2"; break;
case 3: // 3 byte long segment
$data .= "\3"; break;
default: // segment is too big, invalid IP
return 'ERROR';
}
/* and the segment itself */
$data .= $octets[$x];
}
/* and the final bit of the request */
$data .= "\7in-addr\4arpa\0\0\x0C\0\1";
/* create UDP socket */
$handle = @fsockopen("udp://$dns", 53);
@stream_set_timeout($handle, floor($timeout/1000), ($timeout*1000)%1000000);
@stream_set_blocking($handle, 1);
/* send our request (and store request size so we can cheat later) */
$requestsize = @fwrite($handle, $data);
/* get the response */
$response = @fread($handle, 1000);
/* check to see if it timed out */
$info = @stream_get_meta_data($handle);
/* close the socket */
@fclose($handle);
if ($info['timed_out']) {
return 'timed_out';
}
/* more error handling */
if ($response == '') { return $ip; }
/* parse the response and find the response type */
$type = @unpack('s', substr($response, $requestsize+2));
if (isset($type[1]) && $type[1] == 0x0C00) {
/* set up our variables */
$host = '';
$len = 0;
/* set our pointer at the beginning of the hostname uses the request
size from earlier rather than work it out.
*/
$position = $requestsize + 12;
/* reconstruct the hostname */
do {
/* get segment size */
$len = unpack('c', substr($response, $position));
/* null terminated string, so length 0 = finished */
if ($len[1] == 0) {
/* return the hostname, without the trailing '.' */
return strtoupper(substr($host, 0, strlen($host) -1));
}
/* add the next segment to our host */
$host .= substr($response, $position+1, $len[1]) . '.';
/* move pointer on to the next segment */
$position += $len[1] + 1;
} while ($len != 0);
/* error - return the hostname we constructed (without the . on the end) */
return strtoupper($ip);
}
/* error - return the hostname */
return strtoupper($ip);
}
function poller_maintenance () {
global $config;
$command_string = trim(read_config_option('path_php_binary'));
// If its not set, just assume its in the path
if (trim($command_string) == '') {
$command_string = 'php';
}
$extra_args = ' -q ' . $config['base_path'] . '/poller_maintenance.php';
exec_background($command_string, $extra_args);
}
function clog_admin() {
if (!isset($_SESSION['sess_clog_level'])) {
clog_authorized();
}
if ($_SESSION["sess_clog_level"] == CLOG_PERM_ADMIN) {
return true;
} else {
return false;
}
}
function clog_authorized() {
if (!isset($_SESSION['sess_clog_level'])) {
if (isset($_SESSION['sess_user_id'])) {
if (is_realm_allowed(18)) {
$_SESSION['sess_clog_level'] = CLOG_PERM_ADMIN;
} else {
if (is_realm_allowed(19)) {
$_SESSION['sess_clog_level'] = CLOG_PERM_USER;
}else {
$_SESSION['sess_clog_level'] = CLOG_PERM_NONE;
}
}
} else {
$_SESSION['sess_clog_level'] = CLOG_PERM_NONE;
}
}
if ($_SESSION['sess_clog_level'] == CLOG_PERM_USER) {
return true;
} elseif ($_SESSION['sess_clog_level'] == CLOG_PERM_ADMIN) {
return true;
} else {
return false;
}
}
function update_system_mibs($host_id) {
global $sessions;
$system_mibs = array(
'snmp_sysDescr' => '.1.3.6.1.2.1.1.1.0',
'snmp_sysObjectID' => '.1.3.6.1.2.1.1.2.0',
'snmp_sysUpTimeInstance' => '.1.3.6.1.2.1.1.3.0',
'snmp_sysContact' => '.1.3.6.1.2.1.1.4.0',
'snmp_sysName' => '.1.3.6.1.2.1.1.5.0',
'snmp_sysLocation' => '.1.3.6.1.2.1.1.6.0'
);
$h = db_fetch_row_prepared('SELECT * FROM host WHERE id = ?', array($host_id));
if (sizeof($h)) {
open_snmp_session($host_id, $h);
if (isset($sessions[$host_id . '_' . $h['snmp_version'] . '_' . $h['snmp_port']])) {
foreach($system_mibs as $name => $oid) {
$value = cacti_snmp_session_get($sessions[$host_id . '_' . $h['snmp_version'] . '_' . $h['snmp_port']], $oid);
if (!empty($value)) {
db_execute_prepared("UPDATE host SET $name = ? WHERE id = ?",
array($value, $host_id));
}
}
} else {
cacti_log("WARNING: Unable to open session for System Mib collection for Device[$host_id]", false, 'POLLER');
}
}
}
function cacti_debug_backtrace($entry = '', $html = false) {
global $config;
if (defined('IN_CACTI_INSTALL')) {
return true;
}
$callers = debug_backtrace();
$s = '';
foreach ($callers as $c) {
if (isset($c['file'])) {
$file = str_replace($config['base_path'], '', $c['file']);
} else {
$file = '';
}
if (isset($c['line'])) {
$line = $c['line'];
} else {
$line = '';
}
$func = $c['function'];
$s = "(" . ($file != '' ? "$file: ":'') . ($line != '' ? "$line ":'') . "$func)" . $s;
}
if ($html) {
echo "\n";
}
cacti_log(trim("$entry Backtrace: $s"), false);
}
/* calculate_percentiles - Given and array of numbers, calculate the Nth percentile,
* optionally, return an array of numbers containing elements required for
* a whisker chart.
*
* @arg $data - an array of data
* @arg $percentile - the Nth percentile to calculate. By default 95th.
* #arg $whisker - if whisker is true, an array of values will be returne
* including 25th, median, 75th, and 90th perecentiles.
*
* @returns - either the Nth percentile, the elements for a whisker chart,
* or false if there is insufficient data to determine. */
function calculate_percentiles($data, $percentile = 95, $whisker = false) {
if ($percentile > 0 && $percentile < 1) {
$p = $percentile;
} elseif ($percentile > 1 && $percentile <= 100) {
$p = $percentile * .01;
}else {
return false;
}
if ($whisker) {
$tiles = array(
'25th' => 0.25,
'50th' => 0.50,
'75th' => 0.75,
'90th' => 0.90,
'95th' => 0.95,
);
} else {
$tiles = array(
'custom' => $p
);
}
$results = array();
$elements = sizeof($data);
/* sort the array to return */
sort($data);
foreach($tiles as $index => $p) {
/* calculate offsets into the array */
$allindex = ($elements - 1) * $p;
$intvalindex = intval($allindex);
$floatval = $allindex - $intvalindex;
if (!is_float($floatval)) {
$ptile = $data[$intvalindex];
} else {
if ($elements > $intvalindex + 1) {
$ptile = $floatval * ($data[$intvalindex + 1] - $data[$intvalindex]) + $data[$intvalindex];
} else {
$ptile = $data[$intvalindex];
}
}
if ($index == 'custom') {
return $ptile;
} else {
$results[$index] = $ptile;
}
}
return $results;
}
function get_timeinstate($host) {
$interval = read_config_option('poller_interval');
if ($host['status_event_count'] > 0) {
$time = $host['status_event_count'] * $interval;
} elseif (strtotime($host['status_rec_date']) > 943916400) {
$time = time() - strtotime($host['status_rec_date']);
} elseif ($host['snmp_sysUpTimeInstance'] > 0) {
$time = $host['snmp_sysUpTimeInstance']/100;
} else {
$time = 0;
}
if ($time > 86400) {
$days = floor($time/86400);
$time %= 86400;
} else {
$days = 0;
}
if ($time > 3600) {
$hours = floor($time/3600);
$time %= 3600;
} else {
$hours = 0;
}
$minutes = floor($time/60);
return $days . 'd:' . $hours . 'h:' . $minutes . 'm';
}
function get_classic_tabimage($text, $down = false) {
global $config;
$images = array(
false => 'tab_template_blue.gif',
true => 'tab_template_red.gif'
);
if ($text == '') return false;
$text = strtolower($text);
$possibles = array(
array('DejaVuSans-Bold.ttf', 9, true),
array('DejaVuSansCondensed-Bold.ttf', 9, false),
array('DejaVuSans-Bold.ttf', 9, false),
array('DejaVuSansCondensed-Bold.ttf', 9, false),
array('DejaVuSans-Bold.ttf', 8, false),
array('DejaVuSansCondensed-Bold.ttf', 8, false),
array('DejaVuSans-Bold.ttf', 7, false),
array('DejaVuSansCondensed-Bold.ttf', 7, true),
);
$y = 30;
$x = 44;
$wlimit = 72;
$wrapsize = 12;
if (file_exists($config['base_path'] . '/images/' . $images[$down])) {
$originalpath = getenv('GDFONTPATH');
putenv('GDFONTPATH=' . $config['base_path'] . '/include/fonts/');
$template = imagecreatefromgif($config['base_path'] . '/images/' . $images[$down]);
$w = imagesx($template);
$h = imagesy($template);
$tab = imagecreatetruecolor($w, $h);
imagecopy($tab, $template, 0, 0, 0, 0, $w, $h);
$txcol = imagecolorat($tab, 0, 0);
imagecolortransparent($tab,$txcol);
$white = imagecolorallocate($tab, 255, 255, 255);
foreach ($possibles as $variation) {
$font = $variation[0];
$fontsize = $variation[1];
$lines = array();
// if no wrapping is requested, or no wrapping is possible...
if((!$variation[2]) || ($variation[2] && strpos($text,' ') === false)) {
$bounds = imagettfbbox($fontsize, 0, $font, $text);
$w = $bounds[4] - $bounds[0];
$h = $bounds[1] - $bounds[5];
$realx = $x - $w/2 -1;
$lines[] = array($text, $font, $fontsize, $realx, $y);
$maxw = $w;
} else {
$texts = explode("\n", wordwrap($text, $wrapsize), 2);
$line = 1;
$maxw = 0;
foreach ($texts as $txt) {
$bounds = imagettfbbox($fontsize, 0, $font, $txt);
$w = $bounds[4] - $bounds[0];
$h = $bounds[1] - $bounds[5];
$realx = $x - $w/2 -1;
$realy = $y - $h * $line + 3;
$lines[] = array($txt, $font, $fontsize, $realx, $realy);
if ($maxw < $w) {
$maxw = $w;
}
$line--;
}
}
if($maxw<$wlimit) break;
}
foreach ($lines as $line) {
if (function_exists('imagettftext')) {
imagettftext($tab, $line[2], 0, $line[3], $line[4], $white, $line[1], $line[0]);
}else{
imagestring($tab, $line[2], $line[3], $line[4], $string, $white);
}
}
putenv('GDFONTPATH=' . $originalpath);
imagetruecolortopalette($tab, true, 256);
// generate the image an return the data directly
ob_start();
imagegif($tab);
$image = ob_get_contents();
ob_end_clean();
return("data:image/gif;base64," . base64_encode($image));
} else {
return false;
}
}
function cacti_oid_numeric_format() {
if (function_exists('snmp_set_oid_output_format')) {
snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC);
} elseif (function_exists("snmp_set_oid_numeric_print")) {
snmp_set_oid_numeric_print(true);
}
}
function IgnoreErrorHandler($message) {
global $snmp_error;
$snmp_ignore = array(
'No response from',
'noSuchName',
'No Such Object',
'Error in packet',
'This name does not exist',
'End of MIB',
'Unknown host',
'Name or service not known'
);
foreach ($snmp_ignore as $i) {
if (strpos($message, $i)) {
$snmp_error = trim($message, "\\\n\t ");
return true;
}
}
$ignore = array(
'unable to read from socket' # ping.php line 387 socket refusal
);
foreach ($ignore as $i) {
if (strpos($message, $i)) {
return true;
}
}
return false;
}
function CactiErrorHandler($level, $message, $file, $line, $context) {
global $phperrors;
if (defined('IN_CACTI_INSTALL')) {
return true;
}
if (IgnoreErrorHandler($message)) {
return true;
}
preg_match("/.*\/plugins\/([\w-]*)\/.*/", $file, $output_array);
$plugin = (isset($output_array[1]) ? $output_array[1] : '');
$error = 'PHP ' . $phperrors[$level] . ($plugin != '' ? " in Plugin '$plugin'" : '') . ": $message in file: $file on line: $line";
switch ($level) {
case E_COMPILE_ERROR:
case E_CORE_ERROR:
case E_ERROR:
case E_PARSE:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR PARSE');
if ($plugin != '') {
api_plugin_disable_all($plugin);
cacti_log("ERRORS DETECTED - DISABLING PLUGIN '$plugin'");
}
break;
case E_RECOVERABLE_ERROR:
case E_USER_ERROR:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR');
break;
case E_COMPILE_WARNING:
case E_CORE_WARNING:
case E_USER_WARNING:
case E_WARNING:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR WARNING');
break;
case E_NOTICE:
case E_USER_NOTICE:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR NOTICE');
break;
case E_STRICT:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR STRICT');
break;
default:
cacti_log($error, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR');
}
return false;
}
function CactiShutdownHandler () {
global $phperrors;
$error = error_get_last();
if (IgnoreErrorHandler($error['message'])) {
return true;
}
switch ($error['type']) {
case E_ERROR:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
case E_PARSE:
preg_match('/.*\/plugins\/([\w-]*)\/.*/', $error['file'], $output_array);
$plugin = (isset($output_array[1]) ? $output_array[1] : '' );
$message = 'PHP ' . $phperrors[$error['type']] .
($plugin != '' ? " in Plugin '$plugin'" : '') . ': ' . $error['message'] .
' in file: ' . $error['file'] . ' on line: ' . $error['line'];
cacti_log($message, false, 'ERROR');
cacti_debug_backtrace('PHP ERROR');
if ($plugin != '') {
api_plugin_disable_all($plugin);
cacti_log("ERRORS DETECTED - DISABLING PLUGIN '$plugin'");
}
}
}
/** enable_device_debug - Enables device debug for a device
* if it is disabled.
*
* @arg $host_id - the device id to search for
*
* @returns - void */
function enable_device_debug($host_id) {
$device_debug = read_config_option('selective_device_debug', true);
if ($device_debug != '') {
$devices = explode(',', $device_debug);
if (array_search($host_id, $devices) === false) {
set_config_option('selective_device_debug', $device_debug . ',' . $host_id);
}
} else {
set_config_option('selective_device_debug', $host_id);
}
}
/** disable_device_debug - Disables device debug for a device
* if it is enabled.
*
* @arg $host_id - the device id to search for
*
* @returns - void */
function disable_device_debug($host_id) {
$device_debug = read_config_option('selective_device_debug', true);
if ($device_debug != '') {
$devices = explode(',', $device_debug);
foreach($devices as $key => $device) {
if ($device == $host_id) {
unset($devices[$key]);
break;
}
}
set_config_option('selective_device_debug', implode(',', $devices));
}
}
/** is_device_debug_enabled - Determines if device debug is enabled
* for a device.
*
* @arg $host_id - the device id to search for
*
* @returns - boolean true or false */
function is_device_debug_enabled($host_id) {
$device_debug = read_config_option('selective_device_debug', true);
if ($device_debug != '') {
$devices = explode(',', $device_debug);
if (array_search($host_id, $devices) !== false) {
return true;
}
}
return false;
}
/** get_url_type - Determines if remote communications are over
* http or https for remote services.
*
* @returns - http or https */
function get_url_type() {
if (read_config_option('force_https') == 'on') {
return 'https';
} else {
return 'http';
}
}
/** get_default_contextoption - Sets default context options for self-signed SSL
* related protocols if necessary. Allows plugins to add addional header information
* to fullfill system setup related requirements like the usage of Web Single Login
* cookies for example.
*
* @returns - an array of stream context options or false */
function get_default_contextoption($protocol = false, $options = false) {
$fgc_contextoption = false;
$timeout = read_config_option('script_timeout');
if (!$protocol) {
$protocol = get_url_type();
}
if (in_array($protocol, array('ssl', 'https', 'ftps'))) {
$fgc_contextoption = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true,
)
);
}
if ($protocol == 'https') {
$fgc_contextoption['https'] = array(
'timeout' => $timeout
);
} elseif ($protocol == 'http') {
$fgc_contextoption['http'] = array(
'timeout' => $timeout
);
}
if (is_array($options)) {
$fgc_contextoption = array_replace_recursive($fgc_contextoption, $options);
}
$fgc_contextoption = api_plugin_hook_function('fgc_contextoption', $fgc_contextoption);
return $fgc_contextoption;
}
/** repair_system_data_input_methods - This utility will repair
* system data input methods when they are detected on the system
*
* @returns - null */
function repair_system_data_input_methods($step = 'import') {
$system_hashes = array(
'3eb92bb845b9660a7445cf9740726522', // Get SNMP Data
'bf566c869ac6443b0c75d1c32b5a350e', // Get SNMP Data (Indexed)
'80e9e4c4191a5da189ae26d0e237f015', // Get Script Data (Indexed)
'332111d8b54ac8ce939af87a7eac0c06', // Get Script Server Data (Indexed)
);
$good_field_hashes = array(
'3eb92bb845b9660a7445cf9740726522' => array( // Get SNMP Data (1)
'92f5906c8dc0f964b41f4253df582c38', // IP Address
'012ccb1d3687d3edb29c002ea66e72da', // SNMP Version
'32285d5bf16e56c478f5e83f32cda9ef', // SNMP Community
'fc64b99742ec417cc424dbf8c7692d36', // SNMP Port
'ad14ac90641aed388139f6ba86a2e48b', // SNMP Username
'9c55a74bd571b4f00a96fd4b793278c6', // SNMP Password
'20832ce12f099c8e54140793a091af90', // SNMP Authentication Protocol
'c60c9aac1e1b3555ea0620b8bbfd82cb', // SNMP Privacy Passphrase
'feda162701240101bc74148415ef415a', // SNMP Privacy Protocol
'4276a5ec6e3fe33995129041b1909762' // SNMP OID
),
'bf566c869ac6443b0c75d1c32b5a350e' => array( // Get SNMP Data (Indexed) (2)
'617cdc8a230615e59f06f361ef6e7728', // IP Address
'b5c23f246559df38662c255f4aa21d6b', // SNMP Version
'acb449d1451e8a2a655c2c99d31142c7', // SNMP Community
'c1f36ee60c3dc98945556d57f26e475b', // SNMP Port
'f4facc5e2ca7ebee621f09bc6d9fc792', // SNMP Username
'1cc1493a6781af2c478fa4de971531cf', // SNMP Password
'2cf7129ad3ff819a7a7ac189bee48ce8', // SNMP Authentication Protocol
'6b13ac0a0194e171d241d4b06f913158', // SNMP Privacy Passphrase
'3a33d4fc65b8329ab2ac46a36da26b72', // SNMP Privacy Protocol
'6027a919c7c7731fbe095b6f53ab127b', // Index Type
'cbbe5c1ddfb264a6e5d509ce1c78c95f', // Index Value
'e6deda7be0f391399c5130e7c4a48b28' // Output Type ID
),
'80e9e4c4191a5da189ae26d0e237f015' => array( // Get Script Data (Indexed) 11
'd39556ecad6166701bfb0e28c5a11108', // Index Type
'3b7caa46eb809fc238de6ef18b6e10d5', // Index Value
'74af2e42dc12956c4817c2ef5d9983f9', // Output Type ID
'8ae57f09f787656bf4ac541e8bd12537' // Output Value
),
'332111d8b54ac8ce939af87a7eac0c06' => array( // Get Script Server Data (Indexed) 12
'172b4b0eacee4948c6479f587b62e512', // Index Type
'30fb5d5bcf3d66bb5abe88596f357c26', // Index Value
'31112c85ae4ff821d3b288336288818c', // Output Type ID
'5be8fa85472d89c621790b43510b5043' // Output Value
)
);
foreach($good_field_hashes as $hash => $field_hashes) {
$data_input_id = db_fetch_cell_prepared('SELECT id FROM data_input WHERE hash = ?', array($hash));
if (!empty($data_input_id)) {
$bad_hashes = db_fetch_assoc_prepared('SELECT *
FROM data_input_fields
WHERE hash NOT IN ("' . implode('","', $field_hashes) . '")
AND hash != ""
AND data_input_id = ?',
array($data_input_id));
if (sizeof($bad_hashes)) {
cacti_log(strtoupper($step) . ' NOTE: Repairing ' . sizeof($bad_hashes) . ' Damaged data_input_fields', false);
foreach($bad_hashes as $bhash) {
$good_field_id = db_fetch_cell_prepared('SELECT id
FROM data_input_fields
WHERE hash != ?
AND data_input_id = ?
AND data_name = ?',
array($bhash['hash'], $data_input_id, $bhash['data_name']));
if (!empty($good_field_id)) {
cacti_log("Data Input ID $data_input_id Bad Field ID is " . $bhash['id'] . ", Good Field ID: " . $good_field_id, false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
cacti_log('Executing Data Input Data Check', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
// Data Input Data
$bad_mappings = db_fetch_assoc_prepared('SELECT *
FROM data_input_data
WHERE data_input_field_id = ?',
array($bhash['id']));
if (sizeof($bad_mappings)) {
cacti_log(strtoupper($step) . ' NOTE: Found ' . sizeof($bad_mappings) . ' Damaged data_input_fields', false);
foreach($bad_mappings as $mfid) {
$good_found = db_fetch_cell_prepared('SELECT COUNT(*)
FROM data_input_data
WHERE data_input_field_id = ?
AND data_template_data_id = ?',
array($good_field_id, $mfid['data_template_data_id']));
if ($good_found > 0) {
cacti_log('Good Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
db_execute_prepared('DELETE FROM data_input_data
WHERE data_input_field_id = ?
AND data_template_data_id = ?',
array($mfid['data_input_field_id'], $mfid['data_template_data_id']));
} else {
cacti_log('Good NOT Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
db_execute_prepared('UPDATE data_input_data
SET data_input_field_id = ?
WHERE data_input_field_id = ?
AND data_template_data_id = ?',
array($good_field_id, $mfid['data_input_field_id'], $mfid['data_template_data_id']));
}
}
} else {
cacti_log('No Bad Data Input Data Records', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
}
// Data Template RRD
cacti_log('Executing Data Template RRD Check', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);;
$bad_mappings = db_fetch_assoc_prepared('SELECT *
FROM data_template_rrd
WHERE data_input_field_id = ?',
array($bhash['id']));
if (sizeof($bad_mappings)) {
cacti_log(strtoupper($step) . ' NOTE: Found ' . sizeof($bad_mappings) . ' Damaged data_template_rrd', false);
foreach($bad_mappings as $mfid) {
$good_found = db_fetch_cell_prepared('SELECT COUNT(*)
FROM data_template_rrd
WHERE data_input_field_id = ?
AND id = ?',
array($good_field_id, $mfid['id']));
if ($good_found > 0) {
cacti_log('Good Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
db_execute_prepared('DELETE FROM data_template_rrd
WHERE data_input_field_id = ?
AND id = ?',
array($mfid['data_input_field_id'], $mfid['id']));
} else {
cacti_log('Good NOT Found for ' . $mfid['data_input_field_id'] . ', Fixing', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
db_execute_prepared('UPDATE data_template_rrd
SET data_input_field_id = ?
WHERE data_input_field_id = ?
AND id = ?',
array($good_field_id, $mfid['data_input_field_id'], $mfid['id']));
}
}
} else {
cacti_log('No Bad Data Template RRD Records', false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
}
db_execute_prepared('DELETE FROM data_input_fields WHERE hash = ?', array($bhash['hash']));
} else {
cacti_log('WARNING: Could not find Cacti default matching hash for unknown system hash "' . $bhash['hash'] . '" for ' . $data_input_id . '. No repair performed.');
}
}
}
} else {
cacti_log("Could not find hash '" . $hash . "' for Data Input", false, 'WEBUI', POLLER_VERBOSITY_DEVDBG);
}
}
}
if ($config['cacti_server_os'] == 'win32' && !function_exists('posix_kill')) {
function posix_kill($pid, $signal = SIGTERM) {
$wmi = new COM("winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\cimv2");
$procs = $wmi->ExecQuery("SELECT ProcessId FROM Win32_Process WHERE ProcessId='" . $pid . "'");
if (sizeof($procs)) {
if ($signal == SIGTERM) {
foreach($procs as $proc) {
$proc->Terminate();
}
} else {
return true;
}
} else {
return false;
}
}
}
function is_ipaddress($ip_address = '') {
/* check for ipv4/v6 */
if (function_exists('filter_var')) {
if (filter_var($ip_address, FILTER_VALIDATE_IP) !== false) {
return true;
} else {
return false;
}
} elseif (inet_pton($ip_address) !== false) {
return true;
} else {
return false;
}
}
/** date_time_format create a format string for date/time
* @return string returns date time format
*/
function date_time_format() {
$datechar = array(
GDC_HYPHEN => '-',
GDC_SLASH => '/',
GDC_DOT => '.'
);
/* setup date format */
$date_fmt = read_config_option('default_date_format');
$dateCharSetting = read_config_option('default_datechar');
if (!isset($datechar[$dateCharSetting])) {
$dateCharSetting = GDC_SLASH;
}
$datecharacter = $datechar[$dateCharSetting];
switch ($date_fmt) {
case GD_MO_D_Y:
return 'm' . $datecharacter . 'd' . $datecharacter . 'Y H:i:s';
case GD_MN_D_Y:
return 'M' . $datecharacter . 'd' . $datecharacter . 'Y H:i:s';
case GD_D_MO_Y:
return 'd' . $datecharacter . 'm' . $datecharacter . 'Y H:i:s';
case GD_D_MN_Y:
return 'd' . $datecharacter . 'M' . $datecharacter . 'Y H:i:s';
case GD_Y_MO_D:
return 'Y' . $datecharacter . 'm' . $datecharacter . 'd H:i:s';
case GD_Y_MN_D:
return 'Y' . $datecharacter . 'M' . $datecharacter . 'd H:i:s';
default:
return 'Y' . $datecharacter . 'm' . $datecharacter . 'd H:i:s';
}
}
/**
* get_cacti_version Generic function to get the cacti version
*/
function get_cacti_version() {
static $version = '';
if ($version == '') {
$version = trim(db_fetch_cell('SELECT cacti FROM version LIMIT 1'));
}
return $version;
}
/**
* cacti_version_compare - Compare Cacti version numbers
*/
function cacti_version_compare($version1, $version2, $operator = '>') {
$length = max(sizeof(explode('.', $version1)), sizeof(explode('.', $version2)));
$version1 = version_to_decimal($version1, $length);
$version2 = version_to_decimal($version2, $length);
switch ($operator) {
case '<':
if ($version1 < $version2) {
return true;
}
break;
case '<=':
if ($version1 <= $version2) {
return true;
}
break;
case '>=':
if ($version1 >= $version2) {
return true;
}
break;
case '>':
if ($version1 > $version2) {
return true;
}
break;
case '==':
if ($version1 == $version2) {
return true;
}
break;
default:
return version_compare($version1, $version2, $operator);
}
return false;
}
/**
* version_to_decimal - convert version string to decimal
*/
function version_to_decimal($version, $length = 1) {
$newver = '';
$minor = '';
$parts = explode('.', $version);
foreach($parts as $part) {
if (is_numeric($part)) {
$part = substr('00' . $part, -2);
$newver .= $part;
} else {
$minor = substr($part, -1);
$major = substr($part, 0, strlen($part)-1);
$major = substr('00' . $major, -2);
$newver .= $major;
}
}
if (sizeof($parts) < $length) {
$i = sizeof($parts);
while($i < $length) {
$newver .= '00';
$i++;
}
}
if ($minor != '') {
$int = ord($minor);
} else {
$int = 0;
}
return hexdec($newver) * 1000 + $int;
}
/**
* cacti_gethostinfo - obtains the dns information for a host
*/
function cacti_gethostinfo($hostname, $type = DNS_ALL) {
return dns_get_record($hostname, $type);
}
/**
* cacti_gethostbyname - a ip/ipv6 replacement for php's gethostbyname function
*/
function cacti_gethostbyname($hostname, $type = '') {
if ($type == '') {
$type = DNS_A + DNS_AAAA;
}
if ($type != DNS_AAAA) {
$host = gethostbyname($hostname);
if ($host !== $hostname) {
return $host;
}
}
$return = cacti_gethostinfo($hostname, $type);
if (sizeof($return)) {
foreach($return as $record) {
switch($record['type']) {
case 'A':
return $record['ip'];
break;
case 'AAAA':
return $record['ipv6'];
break;
}
}
}
return $hostname;
}