Exemple #1
0
 /**
  * Index Page for this controller.
  */
 function __construct()
 {
     parent::__construct();
     $this->load->helper('cgminerapi');
     $this->load->helper('functions');
     $this->load->library('form_validation');
     $this->init();
     setTimezone('GMT');
 }
 /**
  * Generates the server config and updates the firewall server
  *
  * @since 1.0
  * @package fmFirewall
  */
 function buildServerConfig($post_data)
 {
     global $fmdb, $__FM_CONFIG;
     /** Get datetime formatting */
     $date_format = getOption('date_format', $_SESSION['user']['account_id']);
     $time_format = getOption('time_format', $_SESSION['user']['account_id']);
     setTimezone();
     $files = array();
     $server_serial_no = sanitize($post_data['SERIALNO']);
     extract($post_data);
     $data->server_build_all = true;
     basicGet('fm_' . $__FM_CONFIG[$_SESSION['module']]['prefix'] . 'servers', $server_serial_no, 'server_', 'server_serial_no');
     if ($fmdb->num_rows) {
         $server_result = $fmdb->last_result;
         $data = $server_result[0];
         extract(get_object_vars($data), EXTR_SKIP);
         /** Disabled server */
         if ($server_status != 'active') {
             $error = "Server is {$server_status}.\n";
             if ($compress) {
                 echo gzcompress(serialize($error));
             } else {
                 echo serialize($error);
             }
             exit;
         }
         include ABSPATH . 'fm-includes/version.php';
         $config = '# This file was built using ' . $_SESSION['module'] . ' ' . $__FM_CONFIG[$_SESSION['module']]['version'] . ' on ' . date($date_format . ' ' . $time_format . ' e') . "\n\n";
         basicGetList('fm_' . $__FM_CONFIG[$_SESSION['module']]['prefix'] . 'policies', 'policy_order_id', 'policy_', "AND server_serial_no={$server_serial_no} AND policy_status='active'");
         if ($fmdb->num_rows) {
             $policy_count = $fmdb->num_rows;
             $policy_result = $fmdb->last_result;
             $function = $server_type . 'BuildConfig';
             $config .= $this->{$function}($policy_result, $policy_count);
         }
         $data->files[$server_config_file] = $config;
         if (is_array($files)) {
             $data->files = array_merge($data->files, $files);
         }
         return array(get_object_vars($data), null);
     }
     /** Bad server */
     $error = "Server is not found.\n";
     if ($compress) {
         echo gzcompress(serialize($error));
     } else {
         echo serialize($error);
     }
 }
 /**
  * Generates the server config and updates the DNS server
  *
  * @since 1.0
  * @package fmDNS
  */
 function buildServerConfig($post_data)
 {
     global $fmdb, $__FM_CONFIG, $fm_dns_acls, $fm_dns_keys, $fm_module_servers;
     /** Get datetime formatting */
     $date_format = getOption('date_format', $_SESSION['user']['account_id']);
     $time_format = getOption('time_format', $_SESSION['user']['account_id']);
     include_once ABSPATH . 'fm-modules/' . $_SESSION['module'] . '/classes/class_acls.php';
     include_once ABSPATH . 'fm-modules/' . $_SESSION['module'] . '/classes/class_keys.php';
     setTimezone();
     $files = array();
     $server_serial_no = sanitize($post_data['SERIALNO']);
     $message = null;
     extract($post_data);
     if (!isset($fm_module_servers)) {
         include ABSPATH . 'fm-modules/fmDNS/classes/class_servers.php';
     }
     $server_group_ids = $fm_module_servers->getServerGroupIDs(getNameFromID($server_serial_no, 'fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'servers', 'server_', 'server_serial_no', 'server_id'));
     $GLOBALS['built_domain_ids'] = null;
     basicGet('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'servers', $server_serial_no, 'server_', 'server_serial_no');
     if ($fmdb->num_rows) {
         $server_result = $fmdb->last_result;
         $data = $server_result[0];
         extract(get_object_vars($data), EXTR_SKIP);
         /** Disabled DNS server */
         if ($server_status != 'active') {
             $error = "DNS server is {$server_status}.\n";
             if ($compress) {
                 echo gzcompress(serialize($error));
             } else {
                 echo serialize($error);
             }
             exit;
         }
         include ABSPATH . 'fm-includes/version.php';
         $config = $zones = $key_config = '// This file was built using ' . $_SESSION['module'] . ' ' . $__FM_CONFIG[$_SESSION['module']]['version'] . ' on ' . date($date_format . ' ' . $time_format . ' e') . "\n\n";
         $query = "SELECT * FROM `fm_{$__FM_CONFIG['fmDNS']['prefix']}config` WHERE `cfg_name`='directory'";
         $config_dir_result = $fmdb->query($query);
         $config_dir_result = $fmdb->last_result;
         $logging = $keys = $servers = null;
         /** Build keys config */
         basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'keys', 'key_id', 'key_', 'AND key_view=0 AND key_status="active"');
         if ($fmdb->num_rows) {
             $key_result = $fmdb->last_result;
             $key_config_count = $fmdb->num_rows;
             for ($i = 0; $i < $key_config_count; $i++) {
                 $key_name = trimFullStop($key_result[$i]->key_name);
                 $keys .= $key_name . "\n";
                 if ($key_result[$i]->key_comment) {
                     $comment = wordwrap($key_result[$i]->key_comment, 50, "\n");
                     $key_config .= '// ' . str_replace("\n", "\n// ", $comment) . "\n";
                     unset($comment);
                 }
                 $key_config .= "key \"{$key_name}\" {\n";
                 $key_config .= "\talgorithm " . $key_result[$i]->key_algorithm . ";\n";
                 $key_config .= "\tsecret \"" . $key_result[$i]->key_secret . "\";\n";
                 $key_config .= "};\n\n";
                 /** Get associated servers */
                 basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'servers', 'server_id', 'server_', 'AND server_serial_no!="' . $server_serial_no . '" AND server_key=' . $key_result[$i]->key_id . ' AND server_status="active"');
                 if ($fmdb->num_rows) {
                     $server_result = $fmdb->last_result;
                     $server_count = $fmdb->num_rows;
                     for ($j = 0; $j < $server_count; $j++) {
                         $servers .= $this->formatServerKeys($server_result[$j]->server_name, $key_name);
                     }
                 }
             }
         }
         $config .= $servers;
         if ($keys) {
             $data->files[dirname($server_config_file) . '/named.conf.keys'] = $key_config;
             $config .= "include \"" . dirname($server_config_file) . "/named.conf.keys\";\n\n";
         }
         /** Build ACLs */
         basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'acls', 'acl_id', 'acl_', 'AND acl_status="active" AND server_serial_no="0"');
         if ($fmdb->num_rows) {
             $acl_result = $fmdb->last_result;
             for ($i = 0; $i < $fmdb->num_rows; $i++) {
                 if ($acl_result[$i]->acl_predefined != 'as defined:') {
                     $global_acl_array[$acl_result[$i]->acl_name] = array($acl_result[$i]->acl_predefined, $acl_result[$i]->acl_comment);
                 } else {
                     $addresses = explode(',', $acl_result[$i]->acl_addresses);
                     $global_acl_array[$acl_result[$i]->acl_name] = null;
                     foreach ($addresses as $address) {
                         if (trim($address)) {
                             $global_acl_array[$acl_result[$i]->acl_name] .= "\t" . $address . ";\n";
                         }
                     }
                     $global_acl_array[$acl_result[$i]->acl_name] = array(rtrim(ltrim($global_acl_array[$acl_result[$i]->acl_name], "\t"), ";\n"), $acl_result[$i]->acl_comment);
                 }
             }
         } else {
             $global_acl_array = array();
         }
         $server_acl_array = array();
         /** Override with group-specific configs */
         if (is_array($server_group_ids)) {
             basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'acls', 'acl_id', 'acl_', 'AND acl_status="active" AND server_serial_no IN ("g_' . implode('","g_', $server_group_ids) . '")');
             if ($fmdb->num_rows) {
                 $server_acl_result = $fmdb->last_result;
                 $acl_config_count = $fmdb->num_rows;
                 for ($j = 0; $j < $acl_config_count; $j++) {
                     if ($server_acl_result[$j]->acl_predefined != 'as defined:') {
                         $server_acl_array[$server_acl_result[$j]->acl_name] = array($server_acl_result[$j]->acl_predefined, $server_acl_result[$j]->acl_comment);
                     } else {
                         $addresses = explode(',', $server_acl_result[$j]->acl_addresses);
                         $server_acl_addresses = null;
                         foreach ($addresses as $address) {
                             if (trim($address)) {
                                 $server_acl_addresses .= "\t" . trim($address) . ";\n";
                             }
                         }
                         $server_acl_array[$server_acl_result[$j]->acl_name] = array(rtrim(ltrim($server_acl_addresses, "\t"), ";\n"), $server_acl_result[$j]->acl_comment);
                     }
                 }
             }
         }
         /** Override with server-specific ACLs */
         basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'acls', 'acl_id', 'acl_', 'AND acl_status="active" AND server_serial_no="' . $server_serial_no . '"');
         if ($fmdb->num_rows) {
             $server_acl_result = $fmdb->last_result;
             $acl_config_count = $fmdb->num_rows;
             for ($j = 0; $j < $acl_config_count; $j++) {
                 if ($server_acl_result[$j]->acl_predefined != 'as defined:') {
                     $server_acl_array[$server_acl_result[$j]->acl_name] = array($server_acl_result[$j]->acl_predefined, $server_acl_result[$j]->acl_comment);
                 } else {
                     $addresses = explode(',', $server_acl_result[$j]->acl_addresses);
                     $server_acl_addresses = null;
                     foreach ($addresses as $address) {
                         if (trim($address)) {
                             $server_acl_addresses .= "\t" . trim($address) . ";\n";
                         }
                     }
                     $server_acl_array[$server_acl_result[$j]->acl_name] = array(rtrim(ltrim($server_acl_addresses, "\t"), ";\n"), $server_acl_result[$j]->acl_comment);
                 }
             }
         }
         /** Merge arrays */
         $acl_array = array_merge($global_acl_array, $server_acl_array);
         /** Format ACL config */
         foreach ($acl_array as $acl_name => $acl_data) {
             list($acl_item, $acl_comment) = $acl_data;
             if ($acl_comment) {
                 $comment = wordwrap($acl_comment, 50, "\n");
                 $config .= '// ' . str_replace("\n", "\n// ", $comment) . "\n";
                 unset($comment);
             }
             $config .= 'acl "' . $acl_name . "\" {\n";
             $config .= "\t" . $acl_item . ";\n";
             $config .= "};\n\n";
         }
         /** Build logging config */
         if (is_array($server_group_ids)) {
             basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'config', 'cfg_name` DESC,`cfg_data`,`cfg_id', 'cfg_', 'AND cfg_type="logging" AND cfg_isparent="yes" AND cfg_status="active" AND server_serial_no in ("0", "' . $server_serial_no . '", "g_' . implode('","g_', $server_group_ids) . '")');
         } else {
             basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'config', 'cfg_name` DESC,`cfg_data`,`cfg_id', 'cfg_', 'AND cfg_type="logging" AND cfg_isparent="yes" AND cfg_status="active" AND server_serial_no in ("0", "' . $server_serial_no . '")');
         }
         if ($fmdb->num_rows) {
             $logging_result = $fmdb->last_result;
             $count = $fmdb->num_rows;
             for ($i = 0; $i < $count; $i++) {
                 if ($logging_result[$i]->cfg_comment) {
                     $comment = wordwrap($logging_result[$i]->cfg_comment, 50, "\n");
                     $logging .= "\t// " . str_replace("\n", "\n\t// ", $comment) . "\n";
                     unset($comment);
                 }
                 $logging .= "\t" . $logging_result[$i]->cfg_name . ' ' . $logging_result[$i]->cfg_data . " {\n";
                 /** Get logging config details */
                 basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'config', 'cfg_id` ASC,`cfg_name`,`cfg_data', 'cfg_', 'AND cfg_type="logging" AND cfg_parent="' . $logging_result[$i]->cfg_id . '" AND cfg_status="active"');
                 if ($fmdb->num_rows) {
                     $child_result = $fmdb->last_result;
                     $count2 = $fmdb->num_rows;
                     for ($j = 0; $j < $count2; $j++) {
                         if ($logging_result[$i]->cfg_name == 'channel') {
                             $logging .= "\t\t" . $child_result[$j]->cfg_name;
                             if ($child_result[$j]->cfg_data && $child_result[$j]->cfg_data != $child_result[$j]->cfg_name) {
                                 $logging .= ' ' . $child_result[$j]->cfg_data;
                             }
                             $logging .= ";\n";
                         } else {
                             $channels = null;
                             $assoc_channels = explode(';', $child_result[$j]->cfg_data);
                             foreach ($assoc_channels as $channel) {
                                 if (is_numeric($channel)) {
                                     $channel = getNameFromID($channel, 'fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'config', 'cfg_', 'cfg_id', 'cfg_data');
                                 }
                                 $channels .= "\t\t{$channel};\n";
                             }
                             $logging .= $channels;
                         }
                     }
                 }
                 /** Close */
                 $logging .= "\t};\n";
             }
         }
         if ($logging) {
             $logging = "logging {\n{$logging}};\n\n";
         }
         $config .= $logging;
         /** Build global configs */
         $config .= "options {\n";
         $config .= "\tdirectory \"" . str_replace('$ROOT', $server_root_dir, $config_dir_result[0]->cfg_data) . "\";\n";
         basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'config', 'cfg_id', 'cfg_', 'AND cfg_type="global" AND cfg_name!="include" AND view_id=0 AND domain_id=0 AND server_serial_no="0" AND cfg_status="active"');
         if ($fmdb->num_rows) {
             $config_result = $fmdb->last_result;
             $global_config_count = $fmdb->num_rows;
             for ($i = 0; $i < $global_config_count; $i++) {
                 $global_config[$config_result[$i]->cfg_name] = array($config_result[$i]->cfg_data, $config_result[$i]->cfg_comment);
             }
         } else {
             $global_config = array();
         }
         $server_config = array();
         /** Override with group-specific configs */
         if (is_array($server_group_ids)) {
             basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'config', 'cfg_id', 'cfg_', 'AND cfg_type="global" AND cfg_name!="include" AND view_id=0 AND domain_id=0  AND server_serial_no IN ("g_' . implode('","g_', $server_group_ids) . '") AND cfg_status="active"');
             if ($fmdb->num_rows) {
                 $server_config_result = $fmdb->last_result;
                 $global_config_count = $fmdb->num_rows;
                 for ($j = 0; $j < $global_config_count; $j++) {
                     $server_config[$server_config_result[$j]->cfg_name] = @array($server_config_result[$j]->cfg_data, $server_config_result[$j]->cfg_comment);
                 }
             }
         }
         /** Override with server-specific configs */
         basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'config', 'cfg_id', 'cfg_', 'AND cfg_type="global" AND cfg_name!="include" AND view_id=0 AND domain_id=0  AND server_serial_no="' . $server_serial_no . '" AND cfg_status="active"');
         if ($fmdb->num_rows) {
             $server_config_result = $fmdb->last_result;
             $global_config_count = $fmdb->num_rows;
             for ($j = 0; $j < $global_config_count; $j++) {
                 $server_config[$server_config_result[$j]->cfg_name] = @array($server_config_result[$j]->cfg_data, $server_config_result[$j]->cfg_comment);
             }
         }
         /** Merge arrays */
         $config_array = array_merge($global_config, $server_config);
         $include_hint_zone = false;
         foreach ($config_array as $cfg_name => $cfg_data) {
             list($cfg_info, $cfg_comment) = $cfg_data;
             /** Include hint zone (root servers) */
             if ($cfg_name == 'recursion' && $cfg_info == 'yes') {
                 $include_hint_zone = true;
             }
             $config .= $this->formatConfigOption($cfg_name, $cfg_info, $cfg_comment, "\t");
         }
         /** Build includes */
         $config .= $this->getIncludeFiles(0, $server_serial_no, $server_group_ids);
         /** Build rate limits */
         $config .= $this->getRateLimits(0, $server_serial_no);
         $config .= "};\n\n";
         /** Build controls configs */
         if (is_array($server_group_ids)) {
             basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'controls', 'control_id', 'control_', 'AND server_serial_no IN ("0","' . $server_serial_no . '", "g_' . implode('","g_', $server_group_ids) . '") AND control_status="active"');
         } else {
             basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'controls', 'control_id', 'control_', 'AND server_serial_no IN ("0","' . $server_serial_no . '") AND control_status="active"');
         }
         if ($fmdb->num_rows) {
             $control_result = $fmdb->last_result;
             $control_config_count = $fmdb->num_rows;
             $control_config = "controls {\n";
             for ($i = 0; $i < $control_config_count; $i++) {
                 if ($control_result[$i]->control_comment) {
                     $comment = wordwrap($control_result[$i]->control_comment, 50, "\n");
                     $control_config .= "\t// " . str_replace("\n", "\n// ", $comment) . "\n";
                     unset($comment);
                 }
                 $control_config .= "\tinet " . $control_result[$i]->control_ip;
                 if ($control_result[$i]->control_port != 953) {
                     $control_config .= ' port ' . $control_result[$i]->control_port;
                 }
                 if (!empty($control_result[$i]->control_addresses)) {
                     $control_config .= ' allow { ' . trim($fm_dns_acls->parseACL($control_result[$i]->control_addresses), '; ') . '; }';
                 }
                 $control_config .= !empty($control_result[$i]->control_keys) ? ' keys { "' . $fm_dns_keys->parseKey($control_result[$i]->control_keys) . '"; };' : ";";
                 $control_config .= "\n";
             }
             $control_config .= "};\n\n";
         } else {
             $control_config = null;
         }
         $config .= $control_config;
         unset($control_config);
         /** Debian-based requires named.conf.options */
         if (isDebianSystem($server_os_distro)) {
             $data->files[dirname($server_config_file) . '/named.conf.options'] = $config;
             $config = $zones . "include \"" . dirname($server_config_file) . "/named.conf.options\";\n\n";
             $data->files[$server_config_file] = $config;
             $config = $zones;
         }
         /** Build Views */
         if (is_array($server_group_ids)) {
             basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'views', 'view_id', 'view_', "AND view_status='active' AND server_serial_no IN ('0', '{$server_serial_no}', 'g_" . implode("','g_", $server_group_ids) . "')");
         } else {
             basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'views', 'view_id', 'view_', "AND view_status='active' AND server_serial_no IN ('0', '{$server_serial_no}')");
         }
         if ($fmdb->num_rows) {
             $view_result = $fmdb->last_result;
             $view_count = $fmdb->num_rows;
             for ($i = 0; $i < $view_count; $i++) {
                 if ($view_result[$i]->view_comment) {
                     $comment = wordwrap($view_result[$i]->view_comment, 50, "\n");
                     $config .= '// ' . str_replace("\n", "\n// ", $comment) . "\n";
                     unset($comment);
                 }
                 $config .= 'view "' . $view_result[$i]->view_name . "\" {\n";
                 /** Get cooresponding config records */
                 basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'config', 'cfg_id', 'cfg_', "AND cfg_status='active' AND cfg_name!='include' AND cfg_type='global' AND server_serial_no='0' AND view_id='" . $view_result[$i]->view_id . "'");
                 if ($fmdb->num_rows) {
                     $config_result = $fmdb->last_result;
                     $view_config_count = $fmdb->num_rows;
                     for ($j = 0; $j < $view_config_count; $j++) {
                         $view_config[$config_result[$j]->cfg_name] = array($config_result[$j]->cfg_data, $config_result[$j]->cfg_comment);
                     }
                 } else {
                     $view_config = array();
                 }
                 $server_view_config = array();
                 /** Override with group-specific configs */
                 if (is_array($server_group_ids)) {
                     basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'config', 'cfg_id', 'cfg_', "AND cfg_status='active' AND cfg_name!='include' AND cfg_type='global' AND server_serial_no IN ('g_" . implode("','g_", $server_group_ids) . "') AND view_id='" . $view_result[$i]->view_id . "'");
                     if ($fmdb->num_rows) {
                         $server_config_result = $fmdb->last_result;
                         $view_config_count = $fmdb->num_rows;
                         for ($j = 0; $j < $view_config_count; $j++) {
                             $server_view_config[$server_config_result[$j]->cfg_name] = array($server_config_result[$j]->cfg_data, $server_config_result[$j]->cfg_comment);
                         }
                     }
                 }
                 /** Override with server-specific configs */
                 basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'config', 'cfg_id', 'cfg_', "AND cfg_status='active' AND cfg_name!='include' AND cfg_type='global' AND server_serial_no='{$server_serial_no}' AND view_id='" . $view_result[$i]->view_id . "'");
                 if ($fmdb->num_rows) {
                     $server_config_result = $fmdb->last_result;
                     $view_config_count = $fmdb->num_rows;
                     for ($j = 0; $j < $view_config_count; $j++) {
                         $server_view_config[$server_config_result[$j]->cfg_name] = array($server_config_result[$j]->cfg_data, $server_config_result[$j]->cfg_comment);
                     }
                 }
                 /** Merge arrays */
                 $config_array = array_merge($view_config, $server_view_config);
                 foreach ($config_array as $cfg_name => $cfg_data) {
                     list($cfg_info, $cfg_comment) = $cfg_data;
                     $config .= $this->formatConfigOption($cfg_name, $cfg_info, $cfg_comment, "\t");
                 }
                 /** Build includes */
                 $config .= $this->getIncludeFiles($view_result[$i]->view_id, $server_serial_no, $server_group_ids);
                 /** Build rate limits */
                 $config .= $this->getRateLimits($view_result[$i]->view_id, $server_serial_no);
                 /** Get cooresponding keys */
                 basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'keys', 'key_id', 'key_', "AND key_status='active' AND key_view='" . $view_result[$i]->view_id . "'");
                 if ($fmdb->num_rows) {
                     $key_result = $fmdb->last_result;
                     $key_config = '// This file was built using ' . $_SESSION['module'] . ' ' . $fm_version . ' on ' . date($date_format . ' ' . $time_format . ' e') . "\n\n";
                     $key_count = $fmdb->num_rows;
                     for ($k = 0; $k < $key_count; $k++) {
                         $key_name = trimFullStop($key_result[$k]->key_name) . '.';
                         if ($key_result[$k]->key_comment) {
                             $comment = wordwrap($key_result[$k]->key_comment, 50, "\n");
                             $key_config .= '// ' . str_replace("\n", "\n// ", $comment) . "\n";
                             unset($comment);
                         }
                         $key_config .= "key \"" . $key_name . "\" {\n";
                         $key_config .= "\talgorithm " . $key_result[$k]->key_algorithm . ";\n";
                         $key_config .= "\tsecret \"" . $key_result[$k]->key_secret . "\";\n";
                         $key_config .= "};\n\n";
                         /** Get associated servers */
                         basicGetList('fm_' . $__FM_CONFIG['fmDNS']['prefix'] . 'servers', 'server_id', 'server_', 'AND server_serial_no!="' . $server_serial_no . '" AND server_key=' . $key_result[$k]->key_id . ' AND server_status="active"');
                         if ($fmdb->num_rows) {
                             $server_result = $fmdb->last_result;
                             $server_count = $fmdb->num_rows;
                             $servers = null;
                             for ($j = 0; $j < $server_count; $j++) {
                                 $config .= $this->formatServerKeys($server_result[$j]->server_name, $key_name, true);
                             }
                         }
                     }
                     $data->files[$server_zones_dir . '/views.conf.' . sanitize($view_result[$i]->view_name, '-') . '.keys'] = $key_config;
                 }
                 /** Generate zone file */
                 list($tmp_files, $error) = $this->buildZoneDefinitions($server_zones_dir, $server_serial_no, $view_result[$i]->view_id, sanitize($view_result[$i]->view_name, '-'), $include_hint_zone);
                 if ($error) {
                     $message = $error;
                 }
                 /** Include zones for view */
                 if (is_array($tmp_files)) {
                     /** Include view keys if present */
                     if (@array_key_exists($server_zones_dir . '/views.conf.' . sanitize($view_result[$i]->view_name, '-') . '.keys', $data->files)) {
                         $config .= "\tinclude \"" . $server_zones_dir . "/views.conf." . sanitize($view_result[$i]->view_name, '-') . ".keys\";\n";
                     }
                     $config .= "\tinclude \"" . $server_zones_dir . '/zones.conf.' . sanitize($view_result[$i]->view_name, '-') . "\";\n";
                     $files = array_merge($files, $tmp_files);
                 }
                 $config .= "};\n\n";
                 $key_config = $view_config = $server_view_config = null;
             }
         } else {
             /** Generate zones.all.conf */
             list($files, $message) = $this->buildZoneDefinitions($server_zones_dir, $server_serial_no, 0, null, $include_hint_zone);
             /** Include all zones in one file */
             if (is_array($files)) {
                 $config .= "\ninclude \"" . $server_zones_dir . "/zones.conf.all\";\n";
             }
         }
         /** Debian-based requires named.conf.local */
         if (isDebianSystem($server_os_distro)) {
             $data->files[dirname($server_config_file) . '/named.conf.local'] = $config;
             $config = $data->files[$server_config_file] . "include \"" . dirname($server_config_file) . "/named.conf.local\";\n\n";
         }
         $data->files[$server_config_file] = $config;
         if (is_array($files)) {
             $data->files = array_merge($data->files, $files);
         }
         /** Set variable containing all loaded domain_ids */
         if (!$dryrun) {
             $data->built_domain_ids = array_unique($GLOBALS['built_domain_ids']);
             $this->setBuiltDomainIDs($server_serial_no, $data->built_domain_ids);
         }
         return array(get_object_vars($data), $message);
     }
     /** Bad DNS server */
     $error = "DNS server is not found.\n";
     if ($compress) {
         echo gzcompress(serialize($error));
     } else {
         echo serialize($error);
     }
 }
<?php

require_once dirname(__FILE__) . '/vendor/autoload.php';
use JsonRPC\Client;
require_once dirname(__FILE__) . '/util.php';
setTimezone("GMT");
/**------ FUNCTIONS ---------**/
if (!function_exists('json_last_error_msg')) {
    function json_last_error_msg()
    {
        static $errors = array(JSON_ERROR_NONE => null, JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded');
        $error = json_last_error();
        return array_key_exists($error, $errors) ? $errors[$error] : "Unknown error ({$error})";
    }
}
/**-------- END FUNCTIONS --------------**/
if ($argc !== 6 && $argc !== 7) {
    echo 'Use this small tool to import your Trello JSON export into your kanboard, using it JSON-RPC interface.' . PHP_EOL;
    printf('Usage: php %s http://server/jsonrpc.php apitoken trellokey trellotoken trelloboard [userId]%s', $argv[0], PHP_EOL);
    echo 'To get the Trello key and token, login to Trello and go to https://trello.com/app-key' . PHP_EOL;
    echo 'The user id is optional. If you provide it, comments will be created with that userId.' . PHP_EOL;
    die;
}
$server = $argv[1];
$token = $argv[2];
$trellokey = $argv[3];
$trellotoken = $argv[4];
$trelloboard = $argv[5];
$userId = null;
if (isset($argv[6])) {
    $userId = $argv[6];
    public function testEnsureIndex() {
      setTimezone();

      $mongoConnection = new Mongo('127.0.0.1:27017');
      $collection = $mongoConnection->selectCollection("debug", "col1");
      $data = array("field"=>"some data","date"=>date("Y-m-s"));
      $result = $collection->save($data, array("safe" => true));
      $this->assertEquals(1, $result["ok"], json_encode($result));

      $tmp = array("date" => 1);
      $this->assertEquals(1, $tmp['date']);
      $this->assertEquals(true, $collection->ensureIndex($tmp));
      $this->assertEquals(1, $tmp['date']);

      unsetTimezone();
    }
Exemple #6
0
 * Global editor vars (ckeditor)
 *
 * @global (str) 	$EDHEIGHT editor custom height
 * @global (str) 	$EDLANG editor custom user lang or lang file specified
 * @global (mixed) 	$EDTOOL editor custom toolbar, json array | php array | 'none' | ck toolbar_ name
 * @global (str) 	$EDOPTIONS editor custom options config, js obj string, comma delimited
 */
// Init Editor globals
global $EDTOOL, $EDHEIGHT, $EDLANG, $EDOPTIONS;
// init editor globals
$EDHEIGHT = getEditorHeight();
$EDLANG = getEditorLang();
$EDOPTIONS = getEditorOptions();
$EDTOOL = getEditorToolbar();
$TIMEZONE = getDefaultTimezone();
setTimezone($TIMEZONE);
$dump = array('GSROOT' => GSROOTPATH, 'SITENAME' => $SITENAME, 'SITEURL' => $SITEURL, 'TEMPLATE' => $TEMPLATE, 'PRETTYURLS' => $PRETTYURLS, 'PERMALINK' => $PERMALINK, 'SITEEMAIL' => $SITEEMAIL, 'SITETIMEZONE' => $SITETIMEZONE, 'SITELANG' => $SITELANG, 'SITEUSR' => $SITEUSR, 'USR' => $USR, 'HTMLEDITOR' => $HTMLEDITOR, 'USRTIMEZONE' => $USRTIMEZONE, 'USRLANG' => $USRLANG, 'ASSETURL' => $ASSETURL, 'i18n' => count($i18n), 'SALT' => $SALT, 'SESSIONHASH' => $SESSIONHASH, 'EDTOOL' => $EDTOOL, 'EDOPTIONS' => $EDOPTIONS, 'EDLANG' => $EDLANG, 'EDHEIGHT' => $EDHEIGHT, 'OLDLOCALE' => $OLDLOCALE, 'NEWLOCALE' => $NEWLOCALE);
// debugLog($dump);
/**
 * Check to make sure site is already installed
 */
if (notInInstall()) {
    $fullpath = suggest_site_path();
    # if there is no SITEURL set, then it's a fresh install. Start installation process
    # siteurl check is not good for pre 3.0 since it will be empty, so skip and run update first.
    if ($SITEURL == '' && get_gs_version() >= 3.0) {
        serviceUnavailable();
        redirect($fullpath . $GSADMIN . '/install.php');
    } else {
        # if an update file was included in the install package, redirect there first
        if (file_exists(GSADMINPATH . 'update.php') && !isset($_GET['updated']) && !getDef('GSDEBUGINSTALL')) {
Exemple #7
0
function loadRAWData($from, $id_plan, $id_item, $to = null, $id_host = null)
{
    $cacheAge = 60 * 60;
    $offset = getOffset();
    setTimezone();
    $cache = phpFastCache();
    //$cache->clean();
    $dt = getDates($from);
    $from = $dt[0];
    if ($to == null) {
        $to = $dt[1];
    }
    $from = str_replace("-", "/", $from);
    $to = str_replace("-", "/", $to);
    $phour = getPeakHours();
    $unit = getUnit($id_item);
    $plan = getPlan($id_plan);
    $item = getItem($id_item);
    $div = 1;
    if (strtolower($unit) == 'bps') {
        $div = 1024 * 1024;
        $unit = 'Mbps';
    }
    $rtag = "";
    foreach ($_SESSION['tag'] as $key => $value) {
        if ($key != "" && $key != "None") {
            $rtag = $rtag . ',"' . $key . '"';
        }
    }
    if ($rtag == '') {
        $rtag = 'bm_tags.tag like "%"';
    } else {
        $rtag = 'bm_tags.tag in (' . substr($rtag, 1) . ')';
    }
    if ($id_plan == 0) {
        $id_plan = '> 0';
    } else {
        $id_plan = '=' . $id_plan;
    }
    if ($id_host == null) {
        $id_host = "";
    } else {
        $id_host = " and bm_host.id_host=" . $id_host;
    }
    $hosts = 'select bm_host.id_host,bm_host.id_plan,bm_plan.plan,bm_plan.nacD,bm_plan.nacU,bm_threshold.critical,bm_threshold.warning,bm_threshold.nominal,bm_host.host
						from bm_host,bm_plan,bm_plan_groups,bm_threshold,bi_dashboard
						where bm_host.id_plan=bm_plan.id_plan
							and bm_host.groupid = ' . $_SESSION['groupid'] . '
							and bm_plan.id_plan ' . $id_plan . '
							and bm_plan_groups.id_plan = bm_plan.id_plan
							and bm_host.borrado=0
							and bm_host.id_plan=bm_plan.id_plan
							and bm_plan_groups.groupid=bm_host.groupid
							and bm_threshold.id_item=bi_dashboard.id_item
							and bm_host.id_host in (select id from bm_tags where ' . $rtag . ')
							and bi_dashboard.id_item=' . $id_item . $id_host . '
						order by bm_host.id_plan';
    //var_dump($hosts);
    // Find Percentile 5 and 95
    if (true) {
        $hostsr = mysql_query($hosts);
        while ($host = mysql_fetch_array($hostsr, MYSQL_ASSOC)) {
            $id_host = $host['id_host'];
            $hostName = $host['host'];
            $nominal = $host['nominal'];
            $critical = $host['critical'];
            $warning = $host['warning'];
            $nacD = $host['nacD'] * 1024;
            $nacU = $host['nacU'] * 1024;
            if ($nominal == -1) {
                $nominal = $nacD;
            }
            if ($nominal == -2) {
                $nominal = $nacU;
            }
            $hostList[] = array('host' => $hostName, 'id_host' => $id_host, 'nominal' => $nominal, 'critical' => $critical, 'warning' => $warning, 'nacD' => $nacD, 'nacU' => $nacU);
            $incache = true;
            unset($cachedData);
            $dfrom = $key = date('Y/m/d', strtotime($from . ' -1 days'));
            while ($dfrom != $to) {
                $dfrom = date('Y/m/d', strtotime($dfrom . ' +1 days'));
                $key = $dfrom . '-' . $id_host . '-' . $id_item;
                //if (isset($_SESSION['cache'][$key]))
                //	$obj = $_SESSION['cache'][$key];
                //else
                //echo $key . "<br>";
                $obj = $cache->get($key);
                if ($obj == null) {
                    $incache = false;
                    $_SESSION['cacheFull'] = false;
                } else {
                    $_SESSION['cachePartial'] = true;
                    foreach ($obj as $key => $value) {
                        if (isset($value['clock'])) {
                            $cachedData[] = $value;
                        }
                    }
                }
            }
            if (!isset($cachedData)) {
                $incache = false;
            }
            if ($incache) {
                foreach ($cachedData as $key => $row) {
                    $skip = false;
                    if (isset($_SESSION['filter']['< 1.5x']) && $row['value'] > $nominal * 1.5) {
                        $skip = true;
                    }
                    if (isset($_SESSION['filter']['< 2.0x']) && $row['value'] > $nominal * 2.0) {
                        $skip = true;
                    }
                    if (isset($_SESSION['filter']['< 3.0x']) && $row['value'] > $nominal * 3.0) {
                        $skip = true;
                    }
                    if (isset($_SESSION['filter']['> 0']) && $row['value'] <= 0) {
                        $skip = true;
                    }
                    if (isset($_SESSION['filter']['Off Peak Hour']) && $row['t'] == 'P') {
                        $skip = true;
                    }
                    if (isset($_SESSION['filter']['Peak Hour']) && $row['t'] == 'O') {
                        $skip = true;
                    }
                    if (!$skip) {
                        $allData[] = $row['value'];
                        $historyList[$id_host][] = array('clock' => $row['clock'], 'value' => $row['value'], 'valid' => $row['valid'], 't' => $row['t']);
                    }
                }
            } else {
                $table = 'xyz_' . str_pad($id_item, 10, "0", STR_PAD_LEFT);
                //var_dump($table);
                if (mysql_num_rows(mysql_query("SHOW TABLES LIKE '" . $table . "'")) == 1) {
                    if ($phour['peak'] > $phour['offpeak']) {
                        $q = 'select clock,value,valid,if((date_format(from_unixtime(clock),"%H")>=0 and date_format(from_unixtime(clock),"%H")<=' . $phour['offpeak'] . ') or date_format(from_unixtime(clock),"%H")>=' . $phour['peak'] . ',"P","O") as t
							from ' . $table . '
							where clock between unix_timestamp("' . $from . ' 00:00:00") AND unix_timestamp("' . $to . ' 23:59:59") and
								id_host=' . $id_host;
                    } else {
                        $q = 'select clock,value,valid,if(date_format(from_unixtime(clock),"%H")>=' . $phour['peak'] . ' and date_format(from_unixtime(clock),"%H")<=' . $phour['offpeak'] . ',"P","O") as t
							from ' . $table . '
							where clock between unix_timestamp("' . $from . ' 00:00:00") AND unix_timestamp("' . $to . ' 23:59:59") and
								id_host=' . $id_host;
                    }
                    //var_dump($q);
                    $qr = mysql_query($q);
                    while ($row = mysql_fetch_array($qr, MYSQL_ASSOC)) {
                        $key = date('Y/m/d', $row['clock']);
                        $data[$key][$id_host . '-' . $id_item][] = array('clock' => $row['clock'], 'value' => $row['value'], 'valid' => $row['valid'], 't' => $row['t']);
                        $skip = false;
                        if (isset($_SESSION['filter']['< 1.5x']) && $row['value'] > $nominal * 1.5) {
                            $skip = true;
                        }
                        if (isset($_SESSION['filter']['< 2.0x']) && $row['value'] > $nominal * 2.0) {
                            $skip = true;
                        }
                        if (isset($_SESSION['filter']['< 3.0x']) && $row['value'] > $nominal * 3.0) {
                            $skip = true;
                        }
                        if (isset($_SESSION['filter']['> 0']) && $row['value'] <= 0) {
                            $skip = true;
                        }
                        if (isset($_SESSION['filter']['Off Peak Hour']) && $row['t'] == 'P') {
                            $skip = true;
                        }
                        if (isset($_SESSION['filter']['Peak Hour']) && $row['t'] == 'O') {
                            $skip = true;
                        }
                        if (!$skip) {
                            $allData[] = $row['value'];
                            $historyList[$id_host][] = array('clock' => $row['clock'], 'value' => $row['value'], 'valid' => $row['valid'], 't' => $row['t']);
                        }
                    }
                }
                // check miising data
                $dfrom = $key = date('Y/m/d', strtotime($from . ' -1 days'));
                while ($dfrom != $to) {
                    $dfrom = date('Y/m/d', strtotime($dfrom . ' +1 days'));
                    $key = $dfrom . '-' . $id_host . '-' . $id_item;
                    $obj = $cache->get($key);
                    if ($obj == null) {
                        $cache->set($key, array('clock' => 0, 'value' => 0, 'valid' => 0, 't' => ''), $cacheAge);
                        //$_SESSION['cache'][$key]= array('clock'=>0,'value'=>0,'valid'=>0,'t'=>'');
                    }
                }
            }
        }
    }
    if (isset($incache) && !$incache && isset($data)) {
        foreach ($data as $key => $value) {
            foreach ($value as $hkey => $hvalue) {
                $thekey = $key . '-' . $hkey;
                //echo $thekey . ' ';
                $cache->set($thekey, $hvalue, $cacheAge);
                //$_SESSION['cache'][$thekey] = $hvalue;
            }
        }
    }
    if (isset($allData)) {
        return array('allData' => $allData, 'historyList' => $historyList, 'hostList' => $hostList, 'offpeak' => $phour['offpeak'], 'peak' => $phour['peak'], 'unit' => $unit, 'div' => $div, 'plan' => $plan, 'item' => $item, 'from' => $from, 'to' => $to);
    } else {
        return array('allData' => null, 'historyList' => null, 'hostList' => null, 'offpeak' => $phour['offpeak'], 'peak' => $phour['peak'], 'unit' => $unit, 'div' => $div, 'plan' => $plan, 'item' => $item, 'from' => $from, 'to' => $to);
    }
}
Exemple #8
0
        if ($pos) {
            // When it is, it's in the "/usr/share/zoneinfo/" folder
            $timezone = substr($filename, $pos + strlen("zoneinfo/"));
        } else {
            // If not, bail
            $timezone = $default;
        }
    } else {
        // On other systems, like Ubuntu, there's file with the Olsen time
        // right inside it.
        $timezone = file_get_contents("/etc/timezone");
        if (!strlen($timezone)) {
            $timezone = $default;
        }
    }
    date_default_timezone_set(str_replace("\n", '', $timezone));
}
setTimezone('UTC');
//Translate function for different PO-Files - Register in Service Class!
function _t($string, $domain = '')
{
    if ($domain == '' && defined('newLocale')) {
        $domain = newLocale;
    }
    return dgettext($domain, $string);
}
//Load Main-Service-Class that is implemented by most services
include_once 'controller/Service.php';
//Parse Plugin-Folder for additional Services / Modules to load
$plugins = $service->getActivePlugins();
// Header, Klassenpfad für index.php, usw. anpassen auf Basis der Pluginstruktur
 public function setUp()
 {
     setTimezone();
 }
 | but WITHOUT ANY WARRANTY; without even the implied warranty of          |
 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the           |
 | GNU General Public License for more details.                            |
 +-------------------------------------------------------------------------+
 | facileManager: Easy System Administration                               |
 +-------------------------------------------------------------------------+
 | http://www.facilemanager.com/                                           |
 +-------------------------------------------------------------------------+
*/
/**
 * Contains variables for facileManager
 *
 * @package facileManager
 *
 */
setTimezone();
/**
 * The facileManager name string
 *
 * @global string $fm_name
 */
$fm_name = 'facileManager';
/** Set global variables */
$GLOBALS['REQUEST_PROTOCOL'] = isSiteSecure() ? 'https' : 'http';
$GLOBALS['FM_URL'] = $GLOBALS['REQUEST_PROTOCOL'] . '://' . $_SERVER['HTTP_HOST'] . $GLOBALS['RELPATH'];
if (!@is_array($__FM_CONFIG)) {
    $__FM_CONFIG = array();
}
/** Images */
$__FM_CONFIG['icons']['fail'] = sprintf('<img src="fm-modules/%1$s/images/error24.png" border="0" alt="%2$s" title="%2$s" />', $fm_name, _('Failed'));
$__FM_CONFIG['icons']['caution'] = sprintf('<img src="fm-modules/%1$s/images/orangequestion.jpg" border="0" alt="%2$s" title="%2$s" width="20" />', $fm_name, _('Caution'));
function GraphHour($chart, $id_chart, $id_plan, $id_item, $tag, $from, &$hgram, &$low, &$mid, &$max, &$dir)
{
    $offset = getOffset();
    setTimezone();
    $ldata = loadRAWData($from, $id_plan, $id_item);
    $unit = $ldata['unit'];
    $div = $ldata['div'];
    $percentile = calculatePercentile($ldata['allData']);
    $low = 0;
    $mid = 0;
    $max = 0;
    if (isset($ldata['hostList'])) {
        foreach ($ldata['hostList'] as $host) {
            $id_host = $host['id_host'];
            $nacD = $host['nacD'];
            $nacU = $host['nacU'];
            $critical = $host['critical'];
            $warning = $host['warning'];
            $nominal = $host['nominal'];
            if ($warning > 100) {
                $dir = 1;
            } else {
                $dir = 0;
            }
            if ($nominal == -1) {
                $nominal = $nacD;
            }
            if ($nominal == -2) {
                $nominal = $nacU;
            }
            if (isset($ldata['historyList'][$id_host])) {
                foreach ($ldata['historyList'][$id_host] as $key => $row) {
                    $tk = date('H', $row['clock']) * 1;
                    if (!isset($hourAvg[$tk])) {
                        $hourAvg[$tk] = array($tk, 0, 0);
                    }
                    if (!isset($hourQoE[$tk])) {
                        $hourQoE[$tk] = array($tk, 0, 0);
                    }
                    $skip = false;
                    if (isset($_SESSION['filter']['P95']) && $row['value'] > $percentile['P95']) {
                        $skip = true;
                    }
                    if (isset($_SESSION['filter']['P5']) && $row['value'] < $percentile['P5']) {
                        $skip = true;
                    }
                    if (!$skip) {
                        $filteredData[] = array(round($row['value'] / $div, 2));
                        if ($warning <= 100) {
                            if ($row['value'] >= $nominal * $warning / 100) {
                                $max++;
                            }
                            if ($row['value'] < $nominal * $warning / 100 && $row['value'] >= $nominal * $critical / 100) {
                                $mid++;
                            }
                            if ($row['value'] < $nominal * $critical / 100) {
                                $low++;
                            }
                        } else {
                            if ($row['value'] <= $nominal * $warning / 100) {
                                $max++;
                            }
                            if ($row['value'] > $nominal * $warning / 100 && $row['value'] <= $nominal * $critical / 100) {
                                $mid++;
                            }
                            if ($row['value'] > $nominal * $critical / 100) {
                                $low++;
                            }
                        }
                        $sum = $hourAvg[$tk][1];
                        $cnt = $hourAvg[$tk][2];
                        $x = $sum + $row['value'];
                        $y = $cnt + 1;
                        $hourAvg[$tk] = array($tk, $x, $y);
                        if ($row['value'] > $nacD) {
                            $row['value'] = $nacD;
                        }
                        $sum = $hourQoE[$tk][1];
                        $cnt = $hourQoE[$tk][2];
                        $x = $sum + $row['value'];
                        $y = $cnt + 1;
                        $hourQoE[$tk] = array($tk, $x, $y);
                    }
                }
            }
        }
    }
    $offset = 0;
    unset($dataQoE);
    unset($dataAvg);
    unset($data3);
    unset($data4);
    unset($data5);
    if (isset($hourQoE)) {
        aasort($hourQoE, 0);
        unset($k);
        for ($h = 0; $h < 24; $h++) {
            if (isset($hourQoE[$h])) {
                $dataQoE[] = ColorBar($h, $nominal, $warning, $critical, $hourQoE[$h][1] / $hourQoE[$h][2], $div);
                $data3[] = array('x' => $h, 'y' => round($nominal / $div, 2));
                $data4[] = array('x' => $h, 'y' => round($nominal / $div * $warning / 100, 2));
                $data5[] = array('x' => $h, 'y' => round($nominal / $div * $critical / 100, 2));
            } else {
                $dataQoE[] = null;
                $data3[] = array('x' => $h, 'y' => round($nominal / $div, 2));
                $data4[] = array('x' => $h, 'y' => round($nominal / $div * $warning / 100, 2));
                $data5[] = array('x' => $h, 'y' => round($nominal / $div * $critical / 100, 2));
            }
        }
        aasort($hourAvg, 0);
        for ($h = 0; $h < 24; $h++) {
            if (isset($hourQoE[$h])) {
                $dataAvg[] = array('x' => $h, 'y' => round($hourQoE[$h][1] / $hourQoE[$h][2] / $div, 2), 'color' => 'silver');
                $category[] = str_pad($h . ":00", 5, "0", STR_PAD_LEFT);
            } else {
                $dataAvg[] = null;
                $category[] = str_pad($h . ":00", 5, "0", STR_PAD_LEFT);
            }
        }
        for ($i = 0; $i < count($dataAvg); $i++) {
            $dataAvg[$i]['y'] = round($dataAvg[$i]['y'] - $dataQoE[$i]['y'], 2);
        }
    }
    if (!isset($filteredData)) {
        $filteredData = null;
        $nominal = 0;
        $category = null;
        $data3 = null;
        $data4 = null;
        $data5 = null;
        $warning = 0;
        $critical = 0;
        $dataAvg = null;
        $dataQoE = null;
    }
    $hgram = createHistogram($filteredData, 0, round($nominal / $div * 2, 0), round($nominal / $div / 6, 0) + 1, 0);
    $title = 'Average by Hour for "' . $ldata['item'] . '" on plan "' . $ldata['plan'] . '"';
    $subtitle = 'From ' . $ldata['from'] . ' to ' . $ldata['to'];
    $chart = chartHeader($chart, $id_chart, $title, $subtitle, $ldata['unit'], $category);
    $chart->plotOptions->series->pointPadding = -0.2;
    if ($ldata['peak'] > $ldata['offpeak']) {
        $chart->xAxis->plotBands = array(array('label' => array('text' => 'Peak Hour', 'x' => 2, 'style' => array('fontSize' => '8px', 'color' => 'red')), 'from' => $ldata['peak'] - 0.5, 'to' => 24 - 1.5, 'color' => '#FCFFC5'), array('label' => array('text' => 'Peak Hour', 'x' => 2, 'style' => array('fontSize' => '8px', 'color' => 'red')), 'from' => -0.5, 'to' => $ldata['offpeak'] + 1.5, 'color' => '#FCFFC5'));
    } else {
        $chart->xAxis->plotBands = array('label' => array('text' => 'Peak Hour', 'x' => 2, 'style' => array('fontSize' => '8px', 'color' => 'red')), 'from' => $ldata['peak'] - 0.5, 'to' => $ldata['offpeak'] + 0.5, 'color' => '#FCFFC5');
    }
    $chart->series[0]->type = 'column';
    $chart->title->style->fontSize = '14px';
    $chart->subtitle->style->fontSize = '10px';
    $chart->series[0]->data = $dataAvg;
    $chart->series[0]->stack = 0;
    $chart->series[0]->tooltip->valueSuffix = ' ' . $ldata['unit'];
    $chart->series[0]->name = 'Sample average for ' . $ldata['plan'];
    $chart->series[0]->dataLabels->enabled = true;
    $chart->series[0]->dataLabels->crop = true;
    $chart->series[0]->dataLabels->overflow = 'none';
    $chart->series[0]->dataLabels->align = 'center';
    $chart->series[0]->dataLabels->y = -8;
    $chart->series[0]->dataLabels->color = 'black';
    //'#000000';
    $chart->series[0]->dataLabels->style->fontSize = '10px';
    $chart->series[0]->dataLabels->style->fontFamily = 'Verdana, sans-serif';
    $chart->series[0]->dataLabels->formatter = new HighchartJsExpr("function() { return Highcharts.numberFormat(this.point.stackTotal, 2, '.');}");
    $chart->series[1]->type = 'column';
    $chart->series[1]->data = $dataQoE;
    $chart->series[1]->stack = 0;
    $chart->series[1]->tooltip->valueSuffix = ' ' . $ldata['unit'];
    $chart->series[1]->name = 'Real average for ' . $ldata['plan'];
    $chart->series[1]->dataLabels->enabled = true;
    $chart->series[1]->dataLabels->rotation = -90;
    $chart->series[1]->dataLabels->crop = false;
    $chart->series[1]->dataLabels->align = 'center';
    $chart->series[1]->dataLabels->color = '#FFFFFF';
    $chart->series[1]->dataLabels->style->fontSize = '13px';
    $chart->series[1]->dataLabels->style->fontFamily = 'Verdana, sans-serif';
    $chart->series[1]->dataLabels->formatter = new HighchartJsExpr("function() { return Highcharts.numberFormat(this.y, 2, '.');}");
    $chart->series[2]->type = 'spline';
    $chart->series[2]->data = $data3;
    $chart->series[2]->stack = 1;
    $chart->series[2]->tooltip->valueSuffix = ' ' . $ldata['unit'];
    $chart->series[2]->name = 'Nominal at 100%';
    $chart->series[2]->dataLabels->crop = false;
    $chart->series[2]->dataLabels->enabled = false;
    $chart->series[2]->dataLabels->rotation = -90;
    $chart->series[2]->dataLabels->align = 'right';
    $chart->series[2]->dataLabels->x = 4;
    $chart->series[2]->dataLabels->y = 10;
    $chart->series[2]->dataLabels->color = '#FFFFFF';
    $chart->series[2]->dataLabels->style->fontSize = '13px';
    $chart->series[2]->dataLabels->style->fontFamily = 'Verdana, sans-serif';
    $chart->series[2]->lineWidth = 2;
    $chart->series[2]->color = 'green';
    $chart->series[2]->marker->fillColor = 'green';
    $chart->series[2]->marker->radius = 2;
    $chart->series[2]->dataLabels->formatter = new HighchartJsExpr("function() { return Highcharts.numberFormat(this.y, 2, '.');}");
    $chart->series[3]->type = 'spline';
    $chart->series[3]->data = $data4;
    $chart->series[3]->stack = 2;
    $chart->series[3]->tooltip->valueSuffix = ' ' . $ldata['unit'];
    $chart->series[3]->dataLabels->crop = false;
    $chart->series[3]->name = 'Warning at ' . $warning . '% of the threashold';
    $chart->series[3]->dataLabels->enabled = false;
    $chart->series[3]->dataLabels->rotation = -90;
    $chart->series[3]->dataLabels->align = 'right';
    $chart->series[3]->dataLabels->x = 4;
    $chart->series[3]->dataLabels->y = 10;
    $chart->series[3]->dataLabels->color = '#FFFFFF';
    $chart->series[3]->dataLabels->style->fontSize = '10px';
    $chart->series[3]->dataLabels->style->fontFamily = 'Verdana, sans-serif';
    $chart->series[3]->lineWidth = 2;
    $chart->series[3]->color = '#F79E03';
    $chart->series[3]->marker->fillColor = '#F79E03';
    $chart->series[3]->marker->radius = 2;
    $chart->series[3]->dataLabels->formatter = new HighchartJsExpr("function() { return Highcharts.numberFormat(this.y, 2, '.');}");
    $chart->series[4]->type = 'line';
    $chart->series[4]->data = $data5;
    $chart->series[4]->stack = 3;
    $chart->series[4]->tooltip->valueSuffix = ' ' . $ldata['unit'];
    $chart->series[4]->dataLabels->crop = false;
    $chart->series[4]->name = 'Critical at ' . $critical . '% of the threashold';
    $chart->series[4]->dataLabels->enabled = false;
    $chart->series[4]->dataLabels->rotation = -90;
    $chart->series[4]->dataLabels->align = 'right';
    $chart->series[4]->dataLabels->x = 4;
    $chart->series[4]->dataLabels->y = 10;
    $chart->series[4]->dataLabels->color = '#FFFFFF';
    $chart->series[4]->dataLabels->style->fontSize = '10px';
    $chart->series[4]->dataLabels->style->fontFamily = 'Verdana, sans-serif';
    $chart->series[4]->lineWidth = 2;
    $chart->series[4]->marker->radius = 2;
    $chart->series[4]->color = 'red';
    $chart->series[4]->marker->fillColor = 'red';
    $chart->series[4]->dataLabels->formatter = new HighchartJsExpr("function() { return Highcharts.numberFormat(this.y, 2, '.');}");
    return $chart;
}
function Dashboard($dashboard, $plan, $tag, $move)
{
    $offset = getOffset();
    setTimezone();
    $r = '-7' - $_GET['move'];
    $s = '-1' - $_GET['move'];
    $from = date("Y/m/d", strtotime($r . ' days'));
    $to = date("Y/m/d", strtotime($s . ' days'));
    $theDate = date('Y/m/d', strtotime($from . ' -1 days'));
    while ($theDate != $to) {
        $theDate = date('Y/m/d', strtotime($theDate . ' +1 days'));
        $category[] = $theDate;
    }
    $dashList = readDashboard($dashboard);
    $peakHour = str_replace(":", "", "18");
    $offPeakHour = str_replace(":", "", "22");
    foreach ($dashList as $dash) {
        $id_item = $dash['id_item'];
        $descriptionLong = $dash['descriptionLong'];
        $planList = readPlan();
        foreach ($planList as $plan) {
            unset($weekAvgPeak);
            unset($weekAvgOffPeak);
            unset($weekQoEPeak);
            unset($weekQoEOffPeak);
            $id_plan = $plan['id_plan'];
            $ldata = loadRAWData($from, $id_plan, $id_item);
            $unit = $ldata['unit'];
            $div = $ldata['div'];
            $plan = $ldata['plan'];
            $percentile = calculatePercentile($ldata['allData']);
            if (isset($ldata['hostList'])) {
                foreach ($ldata['hostList'] as $host) {
                    $id_host = $host['id_host'];
                    $nacD = $host['nacD'];
                    $nacU = $host['nacU'];
                    $critical = $host['critical'];
                    $warning = $host['warning'];
                    $nominal = $host['nominal'];
                    if ($warning > 100) {
                        $dir = 1;
                    } else {
                        $dir = 0;
                    }
                    if ($nominal == -1) {
                        $nominal = $nacD;
                    }
                    if ($nominal == -2) {
                        $nominal = $nacU;
                    }
                    if (isset($ldata['historyList'][$id_host])) {
                        foreach ($ldata['historyList'][$id_host] as $key => $row) {
                            $tk = date('m/d', $row['clock']);
                            if (!isset($weekAvgPeak[$tk])) {
                                $weekAvgPeak[$tk] = array($tk, 0, 0);
                            }
                            if (!isset($weekAvgOffPeak[$tk])) {
                                $weekAvgOffPeak[$tk] = array($tk, 0, 0);
                            }
                            if (!isset($weekQoEPeak[$tk])) {
                                $weekQoEPeak[$tk] = array($tk, 0, 0);
                            }
                            if (!isset($weekQoEOffPeak[$tk])) {
                                $weekQoEOffPeak[$tk] = array($tk, 0, 0);
                            }
                            $skip = false;
                            if (isset($_SESSION['filter']['P95']) && $row['value'] > $percentile['P95']) {
                                $skip = true;
                            }
                            if (isset($_SESSION['filter']['P5']) && $row['value'] < $percentile['P5']) {
                                $skip = true;
                            }
                            if (!$skip) {
                                if ($row['t'] == 'P') {
                                    $sum = $weekAvgPeak[$tk][1];
                                    $cnt = $weekAvgPeak[$tk][2];
                                    $x = $sum + $row['value'];
                                    $y = $cnt + 1;
                                    $weekAvgPeak[$tk] = array($tk, $x, $y);
                                }
                                if ($row['t'] == 'O') {
                                    $sum = $weekAvgOffPeak[$tk][1];
                                    $cnt = $weekAvgOffPeak[$tk][2];
                                    $x = $sum + $row['value'];
                                    $y = $cnt + 1;
                                    $weekAvgOffPeak[$tk] = array($tk, $x, $y);
                                }
                                if ($row['value'] > $nacD) {
                                    $row['value'] = $nominal;
                                }
                                if ($row['t'] == 'P') {
                                    $sum = $weekQoEPeak[$tk][1];
                                    $cnt = $weekQoEPeak[$tk][2];
                                    $x = $sum + $row['value'];
                                    $y = $cnt + 1;
                                    $weekQoEPeak[$tk] = array($tk, $x, $y);
                                }
                                if ($row['t'] == 'O') {
                                    $sum = $weekQoEOffPeak[$tk][1];
                                    $cnt = $weekQoEOffPeak[$tk][2];
                                    $x = $sum + $row['value'];
                                    $y = $cnt + 1;
                                    $weekQoEOffPeak[$tk] = array($tk, $x, $y);
                                }
                            }
                        }
                    }
                }
            }
            unset($dataPeak);
            unset($dataOffPeak);
            unset($dataQoEPeak);
            unset($dataQoEOffPeak);
            unset($dataNominal);
            unset($dataWarning);
            unset($dataCritical);
            if (isset($weekQoEPeak)) {
                aasort($weekQoEPeak, 0);
                aasort($weekQoEOffPeak, 0);
                aasort($weekAvgPeak, 0);
                aasort($weekAvgOffPeak, 0);
                $sumQoEPeak = 0;
                $cntQoEPeak = 0;
                $sumQoEOffPeak = 0;
                $cntQoEOffPeak = 0;
                foreach (array_reverse($weekQoEPeak) as $tvalue) {
                    $key = $tvalue[0];
                    $sumQoEPeak += $weekQoEPeak[$key][1];
                    $cntQoEPeak += $weekQoEPeak[$key][2];
                    $sumQoEOffPeak += $weekQoEOffPeak[$key][1];
                    $cntQoEOffPeak += $weekQoEOffPeak[$key][2];
                    if ($weekQoEPeak[$key][2] > 0) {
                        $dataQoEPeak[$key] = array('x' => $key, 'y' => round($weekQoEPeak[$key][1] / $weekQoEPeak[$key][2] / $div, 2), 'cnt' => $weekQoEPeak[$key][2]);
                    }
                    // ColorBar($x,$nominal,$warning,$critical,$value,$div)
                    if ($weekQoEOffPeak[$key][2] > 0) {
                        $dataQoEOffPeak[$key] = array('x' => $key, 'y' => round($weekQoEOffPeak[$key][1] / $weekQoEOffPeak[$key][2] / $div, 2), 'cnt' => $weekQoEOffPeak[$key][2]);
                    }
                    if ($weekAvgPeak[$key][2] > 0) {
                        $dataAvgPeak[$key] = array('x' => $key, 'y' => round($weekAvgPeak[$key][1] / $weekAvgPeak[$key][2] / $div, 2), 'cnt' => $weekAvgPeak[$key][2]);
                    }
                    if ($weekAvgOffPeak[$key][2] > 0) {
                        $dataAvgOffPeak[$key] = array('x' => $key, 'y' => round($weekAvgOffPeak[$key][1] / $weekAvgOffPeak[$key][2] / $div, 2), 'cnt' => $weekAvgOffPeak[$key][2]);
                    }
                }
                //echo  $items['descriptionLong'] . " " .  $plans['plan']  . " " . $host['host'] ;
                //var_dump($dataQoEPeak);
                //echo "<br>";
                if (!isset($dataAvgOffPeak)) {
                    $dataAvgOffPeak = null;
                }
                if (!isset($dataQoEPeak)) {
                    $dataQoEPeak = null;
                }
                if (!isset($dataAvgPeak)) {
                    $dataAvgPeak = null;
                }
                if ($cntQoEOffPeak == 0) {
                    $cntQoEOffPeak = 1.0E+22;
                }
                if ($cntQoEPeak == 0) {
                    $cntQoEPeak = 9.999999999999999E+22;
                }
                $dataList[] = array('descriptionLong' => $descriptionLong, 'plan' => $plan, 'id_plan' => $id_plan, 'id_item' => $id_item, 'QoEPeak' => $dataQoEPeak, 'QoEPeakAvg' => round($sumQoEPeak / $cntQoEPeak / $div, 2), 'QoEOffPeak' => $dataQoEOffPeak, 'QoEOffPeakAvg' => round($sumQoEOffPeak / $cntQoEOffPeak / $div, 2), 'AvgPeak' => $dataAvgPeak, 'AvgOffPeak' => $dataAvgOffPeak, 'nominal' => round($nominal / $div, 2), 'warning' => round($warning, 2), 'critical' => round($critical, 2), 'unit' => $unit, 'cntQoEPeak' => $cntQoEPeak, 'cntQoEOffPeak' => $cntQoEOffPeak, 'category' => $category);
            }
        }
    }
    echo '<table width="100%" border="0"><tr><td><center>';
    echo '<table class="tooltip-tabla">';
    $img1 = '<a href="./index.php?route=home0&dashboard=' . $dashboard . '&move=' . ($_GET['move'] + 1) . '"><span class="glyphicon glyphicon-backward"></span></a>';
    $img2 = '<a href="./index.php?route=home0&dashboard=' . $dashboard . '&move=' . ($_GET['move'] - 1) . '"><span class="glyphicon glyphicon-forward"></a>';
    $img3 = '<a href="./index.php?route=home0&dashboard=' . $dashboard . '&move=' . ($_GET['move'] + 7) . '"><span class="glyphicon glyphicon-fast-backward"></span></a>';
    $img4 = '<a href="./index.php?route=home0&dashboard=' . $dashboard . '&move=' . ($_GET['move'] - 7) . '"><span class="glyphicon glyphicon-fast-forward"></a>';
    echo '<tbody><tr><th>' . $img1 . "&nbsp;" . $img3 . '</th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th style="text-align: right;">' . $img4 . "&nbsp;" . $img2 . '</th></tr></tbody>';
    $t = '';
    if (isset($dataList)) {
        foreach ($dataList as $data) {
            $timeSlot = 'PEAK';
            for ($ij = 1; $ij <= 2; $ij++) {
                if ($timeSlot == 'PEAK') {
                    $QoE = 'QoEPeak';
                    $Avg = 'QoEPeakAvg';
                    $Cnt = 'cntQoEPeak';
                } else {
                    $QoE = 'QoEOffPeak';
                    $Avg = 'QoEOffPeakAvg';
                    $Cnt = 'cntQoEOffPeak';
                }
                if ($t != $data['descriptionLong']) {
                    $t = $data['descriptionLong'];
                    echo '<tbody><tr><th class="success" colspan="12"><center><big>' . $t . '</big></center></th></tr></tbody>';
                    echo '<tr>';
                    echo '<td>Plan</td>';
                    echo '<td align="center">Left</td>';
                    echo '<td align="center">Nominal</td>';
                    //echo '<td align="center">Warning</td>';
                    //echo '<td align="center">Critical</td>';
                    echo '<td>Week Average&nbsp;&nbsp;&nbsp;&nbsp;</td>';
                    for ($i = 0; $i < 7; $i++) {
                        if (date("w", strtotime($data['category'][$i])) == 0) {
                            $sun = '<font color="red">';
                        } else {
                            $sun = '<font color="black">';
                        }
                        echo '<td align="right">' . $sun . substr($data['category'][$i], 5) . '</font>&nbsp;&nbsp;&nbsp;&nbsp;</td>';
                    }
                    echo '</tr>';
                }
                $nominal = $data['nominal'];
                $warning = $data['warning'];
                $critical = $data['critical'];
                $unit = $data['unit'];
                echo '<tr>';
                echo '<td>' . $data['plan'] . '&nbsp;&nbsp;&nbsp;</td>';
                echo '<td>' . $timeSlot . '&nbsp;&nbsp;&nbsp;</td>';
                echo '<td align="right">&nbsp;' . number_format($nominal, 2) . ' ' . $unit . '&nbsp;</td>';
                //echo '<td align="right">&nbsp;' . number_format($nominal*$warning/100,2) . ' ' . $unit. '&nbsp;</td>';
                //echo '<td align="right">&nbsp;' . number_format($nominal*$critical/100,2) . ' ' . $unit. '&nbsp;</td>';
                echo '<td>';
                // . '&tag=' . $_GET['tag']
                echo '<a href="index.php?route=home0&type=bar&dashboard=' . $dashboard . '&move=' . $_GET['move'] . '&tag=' . $tag . '&idplan=' . $data['id_plan'] . '&from=' . $from . '&iditem=' . $data['id_item'] . '">';
                if (!isset($data[$Avg]) || $data[$Avg] == 0) {
                    echo '<center><img align="center" src="./images/Button-Close-icon.png" title="' . number_format($data[$Avg], 2) . ' ' . $unit . "<b>Q:" . '0' . '"></center>';
                } else {
                    if ($warning <= 100) {
                        $T1 = $nominal * $warning / 100;
                        $T2 = $nominal * $critical / 100;
                        if ($data[$Avg] >= $T1) {
                            $color = "./images/Green-Ball-icon.png";
                        } elseif ($data[$Avg] >= $T2 && $data[$Avg] < $T1) {
                            $color = "./images/Yellow-Ball-icon.png";
                        } else {
                            $color = "./images/Red-Ball-icon.png";
                        }
                    } else {
                        $T1 = $nominal * $warning / 100;
                        $T2 = $nominal * $critical / 100;
                        if ($data[$Avg] < $T1) {
                            $color = "./images/Green-Ball-icon.png";
                        } elseif ($data[$Avg] >= $T1 && $data[$Avg] < $T2) {
                            $color = "./images/Yellow-Ball-icon.png";
                        } else {
                            $color = "./images/Red-Ball-icon.png";
                        }
                    }
                    echo '<center><img align="center" src="' . $color . '" data-toggle="tooltip" title="(' . number_format($data[$Avg] / $nominal * 100, 2) . '%) ' . number_format($data[$Avg], 2) . ' ' . $unit . "  Q:" . $data[$Cnt] . '"></center>';
                }
                echo '</a>';
                echo '</span></td>';
                for ($i = 0; $i < 7; $i++) {
                    $ky = substr($data['category'][$i], 5);
                    echo '<td>';
                    //echo '(' . $data[$QoE][$ky]['y'] . ')' . '<br>';
                    if (!isset($data[$QoE][$ky]['y']) || $data[$QoE][$ky]['y'] == 0 || $data[$QoE][$ky]['y'] == null) {
                        echo '<center><img align="center" src="./images/Button-Close-icon.png" title="No data"></center>';
                    } else {
                        if ($warning <= 100) {
                            $T1 = $nominal * $warning / 100;
                            $T2 = $nominal * $critical / 100;
                            if ($data[$QoE][$ky]['y'] >= $T1) {
                                $color = "./images/Flag-green-icon.png";
                            } elseif ($data[$QoE][$ky]['y'] >= $T2 && $data[$QoE][$ky]['y'] < $T1) {
                                $color = "./images/Flag-yellow-icon.png";
                            } else {
                                $color = "./images/Flag-red-icon.png";
                            }
                        } else {
                            $T1 = $nominal * $warning / 100;
                            $T2 = $nominal * $critical / 100;
                            if ($data[$QoE][$ky]['y'] < $T1) {
                                $color = "./images/Flag-green-icon.png";
                            } elseif ($data[$QoE][$ky]['y'] >= $T1 && $data[$QoE][$ky]['y'] < $T2) {
                                $color = "./images/Flag-yellow-icon.png";
                            } else {
                                $color = "./images/Flag-red-icon.png";
                            }
                        }
                        echo '<center><img align="center" src="' . $color . '" data-toggle="tooltip" title="' . $data[$QoE][$ky]['x'] . ' ' . number_format($data[$QoE][$ky]['y'], 2) . ' ' . $unit . "  Q:" . $data[$QoE][$ky]['cnt'] . '"></center>';
                    }
                    echo '</span></td>';
                }
                echo '</tr>';
                if ($timeSlot == 'PEAK') {
                    $timeSlot = 'OFFPEAK';
                } else {
                    $timeSlot = 'PEAK';
                }
            }
        }
    }
    echo '</table>';
    echo '</center></td></tr></table>';
}
function GraphBar($chart, $id_chart, $id_plan, $id_item, $tag, $from)
{
    $offset = getOffset();
    setTimezone();
    $dt = getDates($from);
    $ldata = loadRAWData($from, $id_plan, $id_item);
    $unit = $ldata['unit'];
    $div = $ldata['div'];
    $percentile = calculatePercentile($ldata['allData']);
    if (isset($ldata['hostList'])) {
        foreach ($ldata['hostList'] as $host) {
            $nacD = $host['nacD'];
            $nacU = $host['nacU'];
            $critical = $host['critical'];
            $warning = $host['warning'];
            $nominal = $host['nominal'];
            if ($nominal == -1) {
                $nominal = $nacD;
            }
            if ($nominal == -2) {
                $nominal = $nacU;
            }
            $id_host = $host['id_host'];
            if (isset($ldata['historyList'][$id_host])) {
                foreach ($ldata['historyList'][$id_host] as $key => $row) {
                    $tk = date('Y/m/d', $row['clock']);
                    if (!isset($weekAvgPeak[$tk])) {
                        $weekAvgPeak[$tk] = array($tk, 0, 0);
                    }
                    if (!isset($weekAvgOffPeak[$tk])) {
                        $weekAvgOffPeak[$tk] = array($tk, 0, 0);
                    }
                    if (!isset($weekQoEPeak[$tk])) {
                        $weekQoEPeak[$tk] = array($tk, 0, 0);
                    }
                    if (!isset($weekQoEOffPeak[$tk])) {
                        $weekQoEOffPeak[$tk] = array($tk, 0, 0);
                    }
                    $skip = false;
                    if (isset($_SESSION['filter']['P95']) && $row['value'] > $percentile['P95']) {
                        $skip = true;
                    }
                    if (isset($_SESSION['filter']['P5']) && $row['value'] < $percentile['P5']) {
                        $skip = true;
                    }
                    if (!$skip) {
                        if ($row['t'] == 'P') {
                            $sum = $weekAvgPeak[$tk][1];
                            $cnt = $weekAvgPeak[$tk][2];
                            $x = $sum + $row['value'];
                            $y = $cnt + 1;
                            $weekAvgPeak[$tk] = array($tk, $x, $y);
                        }
                        if ($row['t'] == 'O') {
                            $sum = $weekAvgOffPeak[$tk][1];
                            $cnt = $weekAvgOffPeak[$tk][2];
                            $x = $sum + $row['value'];
                            $y = $cnt + 1;
                            $weekAvgOffPeak[$tk] = array($tk, $x, $y);
                        }
                        if ($row['value'] > $nacD) {
                            $row['value'] = $nominal;
                        }
                        if ($row['t'] == 'P') {
                            $sum = $weekQoEPeak[$tk][1];
                            $cnt = $weekQoEPeak[$tk][2];
                            $x = $sum + $row['value'];
                            $y = $cnt + 1;
                            $weekQoEPeak[$tk] = array($tk, $x, $y);
                        }
                        if ($row['t'] == 'O') {
                            $sum = $weekQoEOffPeak[$tk][1];
                            $cnt = $weekQoEOffPeak[$tk][2];
                            $x = $sum + $row['value'];
                            $y = $cnt + 1;
                            $weekQoEOffPeak[$tk] = array($tk, $x, $y);
                        }
                    }
                }
            }
        }
    }
    if (isset($weekQoEPeak)) {
        aasort($weekQoEPeak, 0);
        aasort($weekQoEOffPeak, 0);
        aasort($weekAvgPeak, 0);
        aasort($weekAvgOffPeak, 0);
        $h = -100;
        foreach ($weekQoEPeak as $tvalue) {
            $key = $tvalue[0];
            if ($weekQoEPeak[$key][2] > 0) {
                $dataQoEPeak[] = ColorBar($h, $nominal, $warning, $critical, $weekQoEPeak[$key][1] / $weekQoEPeak[$key][2], $div);
            } else {
                $dataQoEPeak[] = ColorBar($h, $nominal, $warning, $critical, 0, $div);
            }
            // ColorBar($x,$nominal,$warning,$critical,$value,$div)
            if ($weekQoEOffPeak[$key][2] > 0) {
                $dataQoEOffPeak[] = ColorBar($h, $nominal, $warning, $critical, $weekQoEOffPeak[$key][1] / $weekQoEOffPeak[$key][2], $div);
            } else {
                $dataQoEOffPeak[] = ColorBar($h, $nominal, $warning, $critical, 0, $div);
            }
            if ($weekAvgPeak[$key][2] > 0) {
                $dataAvgPeak[] = array('x' => $h, 'y' => round($weekAvgPeak[$key][1] / $weekAvgPeak[$key][2] / $div, 2), 'color' => 'silver');
            } else {
                $dataAvgPeak[] = array('x' => $h, 'y' => 0, 'color' => 'silver');
            }
            if ($weekAvgOffPeak[$key][2] > 0) {
                $dataAvgOffPeak[] = array('x' => $h, 'y' => round($weekAvgOffPeak[$key][1] / $weekAvgOffPeak[$key][2] / $div, 2), 'color' => 'silver');
            } else {
                $dataAvgOffPeak[] = array('x' => $h, 'y' => 0, 'color' => 'silver');
            }
            $dataNominal[] = array('x' => $h, 'y' => round($nominal / $div, 2));
            $dataWarning[] = array('x' => $h, 'y' => round($nominal / $div * $warning / 100, 2));
            $dataCritical[] = array('x' => $h, 'y' => round($nominal / $div * $critical / 100, 2));
            $category[$h] = $key;
            $h++;
        }
        for ($i = 0; $i < count($dataAvgPeak); $i++) {
            $dataAvgPeak[$i]['y'] -= $dataQoEPeak[$i]['y'];
            $dataAvgOffPeak[$i]['y'] -= $dataQoEOffPeak[$i]['y'];
        }
    }
    if (!isset($category)) {
        $category = null;
        $dataAvgPeak = null;
        $dataQoEPeak = null;
        $dataAvgOffPeak = null;
        $dataQoEOffPeak = null;
        $dataNominal = null;
        $dataWarning = null;
        $dataCritical = null;
        $warning = 0;
        $critical = 0;
    }
    $title = 'Average by Hour for "' . $ldata['item'] . '" on plan "' . $ldata['plan'] . '"';
    $subtitle = 'From ' . $ldata['from'] . ' to ' . $ldata['to'];
    $chart = chartHeader($chart, $id_chart, $title, $subtitle, $ldata['unit'], $category);
    $fontSize = '10px';
    if (count($category) > 15) {
        $fontSize = '6px';
        $chart->plotOptions->series->pointPadding = -1 / 300;
    }
    $chart->xAxis->type = 'datetime';
    $chart->xAxis->labels->rotation = -90;
    $chart->xAxis->labels->style->color = "#000000";
    $chart->legend->enabled = false;
    /*
      $chart->option3d->enabled = true;
      $chart->option3d->alpha = 45;
      $chart->option3d->beta = 0;
      $chart->option3d->depth = 50;
      $chart->option3d->viewDistance = 25;
      $chart->plotOptions->column->depth = 25;
      $chart->option3d->beta = 0;
    */
    $chart->series[0]->type = 'column';
    $chart->series[0]->stack = 0;
    $chart->series[0]->data = $dataAvgPeak;
    $chart->series[0]->tooltip->valueSuffix = ' ' . $unit;
    $chart->series[0]->name = 'Sample Average PEAK';
    $chart->series[0]->dataLabels->enabled = true;
    $chart->series[0]->dataLabels->rotation = 0;
    $chart->series[0]->dataLabels->rotation = 0;
    $chart->series[0]->dataLabels->crop = false;
    $chart->series[0]->dataLabels->y = -10;
    $chart->series[0]->dataLabels->zIndexy = 12;
    $chart->series[0]->dataLabels->color = '#000000';
    $chart->series[0]->dataLabels->style->fontSize = $fontSize;
    $chart->series[0]->dataLabels->style->fontFamily = 'Verdana, sans-serif';
    $chart->series[0]->dataLabels->formatter = new HighchartJsExpr("function() { return  Highcharts.numberFormat(this.point.stackTotal, 2, '.');}");
    $chart->series[1]->type = 'column';
    $chart->series[1]->stack = 0;
    $chart->series[1]->data = $dataQoEPeak;
    $chart->series[1]->name = 'Sample Average PEAK';
    $chart->series[1]->dataLabels->enabled = true;
    $chart->series[1]->dataLabels->crop = false;
    $chart->series[1]->dataLabels->rotation = -90;
    $chart->series[1]->dataLabels->align = 'left';
    $chart->series[1]->tooltip->valueSuffix = ' ' . $unit;
    $chart->series[1]->dataLabels->x = 2;
    $chart->series[1]->dataLabels->color = '#FFFFFF';
    $chart->series[1]->dataLabels->style->fontSize = $fontSize;
    $chart->series[1]->dataLabels->style->fontFamily = 'Verdana, sans-serif';
    $chart->series[1]->dataLabels->formatter = new HighchartJsExpr("function() { return 'PEAK: ' + Highcharts.numberFormat(this.y, 2, '.');}");
    $chart->series[2]->type = 'column';
    $chart->series[2]->stack = 1;
    $chart->series[2]->data = $dataAvgOffPeak;
    $chart->series[2]->name = 'Real Average OFFPEAK';
    $chart->series[2]->tooltip->valueSuffix = ' ' . $unit;
    $chart->series[2]->dataLabels->crop = false;
    $chart->series[2]->dataLabels->enabled = true;
    $chart->series[2]->dataLabels->rotation = 0;
    $chart->series[2]->dataLabels->align = 'center';
    $chart->series[2]->dataLabels->y = -10;
    $chart->series[2]->dataLabels->zIndexy = 12;
    $chart->series[2]->dataLabels->color = '#000000';
    $chart->series[2]->dataLabels->style->fontSize = $fontSize;
    $chart->series[2]->dataLabels->style->fontFamily = 'Verdana, sans-serif';
    $chart->series[2]->dataLabels->formatter = new HighchartJsExpr("function() { return Highcharts.numberFormat(this.point.stackTotal, 2, '.');}");
    $chart->series[3]->type = 'column';
    $chart->series[3]->stack = 1;
    $chart->series[3]->data = $dataQoEOffPeak;
    $chart->series[3]->tooltip->valueSuffix = ' ' . $unit;
    $chart->series[3]->name = 'Real Average OFFPEAK';
    $chart->series[3]->dataLabels->crop = false;
    $chart->series[3]->dataLabels->enabled = true;
    $chart->series[3]->dataLabels->rotation = -90;
    $chart->series[3]->dataLabels->align = 'left';
    $chart->series[3]->dataLabels->x = 2;
    $chart->series[3]->dataLabels->color = '#FFFFFF';
    $chart->series[3]->dataLabels->style->fontSize = $fontSize;
    $chart->series[3]->dataLabels->style->fontFamily = 'Verdana, sans-serif';
    $chart->series[3]->dataLabels->formatter = new HighchartJsExpr("function() { return 'OFFPEAK: ' +Highcharts.numberFormat(this.y, 2, '.');}");
    $chart->series[4]->type = 'spline';
    $chart->series[4]->data = $dataNominal;
    $chart->series[4]->stack = 2;
    $chart->series[4]->tooltip->valueSuffix = ' ' . $unit;
    $chart->series[4]->dataLabels->crop = false;
    $chart->series[4]->name = 'Nominal PEAK';
    $chart->series[4]->dataLabels->enabled = false;
    $chart->series[4]->dataLabels->rotation = -90;
    $chart->series[4]->dataLabels->align = 'right';
    $chart->series[4]->dataLabels->x = 4;
    $chart->series[4]->dataLabels->y = 10;
    $chart->series[4]->dataLabels->color = '#FFFFFF';
    $chart->series[4]->dataLabels->style->fontSize = $fontSize;
    $chart->series[4]->dataLabels->style->fontFamily = 'Verdana, sans-serif';
    $chart->series[4]->lineWidth = 2;
    $chart->series[4]->color = 'green';
    $chart->series[4]->marker->fillColor = 'green';
    $chart->series[4]->marker->radius = 2;
    $chart->series[4]->dataLabels->formatter = new HighchartJsExpr("function() { return Highcharts.numberFormat(this.y, 2, '.');}");
    $chart->series[5]->type = 'spline';
    $chart->series[5]->data = $dataWarning;
    $chart->series[5]->stack = 2;
    $chart->series[5]->tooltip->valueSuffix = ' ' . $unit;
    $chart->series[5]->dataLabels->crop = false;
    $chart->series[5]->name = $warning . '% of the plan';
    $chart->series[5]->dataLabels->enabled = false;
    $chart->series[5]->dataLabels->rotation = -90;
    $chart->series[5]->dataLabels->align = 'right';
    $chart->series[5]->dataLabels->x = 4;
    $chart->series[5]->dataLabels->y = 10;
    $chart->series[5]->dataLabels->color = '#FFFFFF';
    $chart->series[5]->dataLabels->style->fontSize = $fontSize;
    $chart->series[5]->dataLabels->style->fontFamily = 'Verdana, sans-serif';
    $chart->series[5]->lineWidth = 2;
    $chart->series[5]->color = '#F79E03';
    $chart->series[5]->marker->fillColor = '#F79E03';
    $chart->series[5]->marker->radius = 2;
    $chart->series[5]->dataLabels->formatter = new HighchartJsExpr("function() { return Highcharts.numberFormat(this.y, 2, '.');}");
    $chart->series[6]->type = 'spline';
    $chart->series[6]->data = $dataCritical;
    $chart->series[6]->stack = 2;
    $chart->series[6]->tooltip->valueSuffix = ' ' . $unit;
    $chart->series[6]->dataLabels->crop = false;
    $chart->series[6]->name = $critical . '% of the plan';
    $chart->series[6]->dataLabels->enabled = false;
    $chart->series[6]->dataLabels->rotation = -90;
    $chart->series[6]->dataLabels->align = 'right';
    $chart->series[6]->dataLabels->x = 4;
    $chart->series[6]->dataLabels->y = 10;
    $chart->series[6]->dataLabels->color = '#FFFFFF';
    $chart->series[6]->dataLabels->style->fontSize = $fontSize;
    $chart->series[6]->dataLabels->style->fontFamily = 'Verdana, sans-serif';
    $chart->series[6]->lineWidth = 2;
    $chart->series[6]->color = 'red';
    $chart->series[6]->marker->fillColor = 'red';
    $chart->series[6]->marker->radius = 2;
    $chart->series[6]->dataLabels->formatter = new HighchartJsExpr("function() { return Highcharts.numberFormat(this.y, 2, '.');}");
    return $chart;
}
function GraphGroup($chart, $id_chart, $item, $itemName, $from, $avg, $type)
{
    $offset = getOffset();
    setTimezone();
    $dt = getDates($from);
    $from = $dt[0];
    $to = $dt[1];
    $chart->chart->renderTo = $id_chart;
    $chart->chart->zoomType = 'x';
    $chart->chart->spacingRight = 20;
    $chart->xAxis->type = 'datetime';
    $chart->xAxis->lineWidth = 0;
    $chart->xAxis->tickWidth = 1;
    $chart->chart->shadow = true;
    $chart->chart->plotShadow = true;
    $chart->yAxis->startOnTick = false;
    $chart->yAxis->showFirstLabel = false;
    $chart->yAxis->min = 0;
    $chart->xAxis->gridLineWidth = 1;
    $chart->tooltip->shared = true;
    $chart->legend->enabled = true;
    $chart->subtitle->text = 'From ' . $from . ' to ' . $to;
    $index = 0;
    $thezero = '-1';
    $average = getAverage($avg);
    $format = $average[0];
    $divide = $average[1];
    $filterHost = '';
    if ($_GET['host'] != '') {
        $filterHost = ' and host="' . $_GET['host'] . '" ';
    }
    switch ($type) {
        case 'YouTube':
            $list = '%video youtube%AVG%';
            $txt = 'Youtube Average for Plan ' . $_GET['plan'];
            if ($_GET['host'] != '') {
                $txt .= ' for Sonda ' . $_GET['host'];
            }
            $chart->title->text = $txt;
            break;
        case 'File':
            $list = 'file download% speed';
            $txt = 'File Download Average for Plan ' . $_GET['plan'];
            if ($_GET['host'] != '') {
                $txt .= ' for Sonda ' . $_GET['host'];
            }
            $chart->title->text = $txt;
            break;
        case 'Video':
            $list = 'Video %experience%';
            $txt = 'Video Experience for Plan ' . $_GET['plan'];
            if ($_GET['host'] != '') {
                $txt .= ' for Sonda ' . $_GET['host'];
            }
            $chart->title->text = $txt;
            break;
        case 'Ping':
            $list = 'ping%avg%';
            $txt = 'Ping Average for Plan ' . $_GET['plan'];
            if ($_GET['host'] != '') {
                $txt .= ' for Sonda ' . $_GET['host'];
            }
            $chart->title->text = $txt;
            break;
    }
    $thezero = '0';
    $q = 'select distinct descriptionLong from bm_items where descriptionLong like "' . $list . '" order by 1';
    $q1 = mysql_query($q);
    while ($r = mysql_fetch_array($q1, MYSQL_ASSOC)) {
        $desc = $r['descriptionLong'];
        $query = "SELECT descriptionLong,unix_timestamp(date_format(from_unixtime(round(clock/" . $divide . ",0)*" . $divide . "),'" . $format . "')) as clk,\n              round(avg(value),0) as value,\n              max(unit) as unit \n              FROM  bm_host,bm_items,bm_history,bm_plan,bm_host_groups\n              WHERE bm_host.id_host=bm_history.id_host and bm_history.id_item=bm_items.id_item and  descriptionLong = '" . $desc . "'\n                and bm_host.id_plan=bm_plan.id_plan \n                and clock between unix_timestamp('" . $from . "') and unix_timestamp('" . $to . " 23:59:59')+3600*24\n                and value > " . $thezero . "\n                and plan='" . $_GET['plan'] . "' " . $filterHost . " \n                and bm_host_groups.groupid=bm_host.groupid\n                and bm_host_groups.groupid=" . $_SESSION['groupid'] . "\n              GROUP BY descriptionLong,unit,unix_timestamp(date_format(from_unixtime(round(clock/" . $divide . ",0)*" . $divide . "),'" . $format . "'))\n              ORDER BY 1";
        //var_dump($query);
        $result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
        unset($data2);
        $unit = '';
        if (mysql_num_rows($result) > 0) {
            while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                $unit = $row['unit'];
                $div = 1;
                if ($unit == 'bps') {
                    $div = 1024 * 1024;
                    $unit = 'Mbps';
                }
                $data2[] = array($row['clk'] * 1000, round($row['value'] * 1 / $div, 2));
            }
            $chart->yAxis->title->text = $unit;
            //$chart->tooltip->formatter = new HighchartJsExpr("function() { return '<b>'+ this.series.name +'</b><br/>'+ Highcharts.dateFormat('%e. %b %H:%M', this.x) +': '+ Highcharts.numberFormat(this.y, 2, ',') +' " . $unit . "';}");
            $chart->series[]->name = $desc;
            $chart->series[$index]->type = 'spline';
            $chart->series[$index]->data = $data2;
            $index++;
        }
    }
    return $chart;
}