protected function construct() { $this->cache = new Prefix('precincts/violations'); $this->precincts_cache = new Prefix('precincts'); $this->data_model['images'] = function ($images) { return _json_encode(array_values(array_filter($images, function ($image) { return preg_match("#^(http[s]?://)#", $image); }))); }; $this->data_model['location'] = function ($location) { return _json_encode(_float($location)); }; $this->data_model['video'] = function ($video) { if (preg_match('/ustream.tv\\/(channel|embed)\\/([0-9]+)/i', $video, $m)) { $video = "https://www.ustream.tv/embed/{$m['2']}"; } elseif (preg_match('/ustream.tv\\/(recorded|embed\\/recorded)\\/([0-9]+)/i', $video, $m)) { $video = "https://www.ustream.tv/embed/recorded/{$m['2']}"; } elseif (preg_match('/(youtube.com\\/embed\\/|youtube.com\\/watch\\?v=)([0-9a-z\\-]+)/i', $video, $m)) { $video = "https://www.youtube.com/embed/{$m['2']}"; } else { $video = ''; } return $video; }; }
/** * Adding key into specified database * * @param int|object $database Keys database * @param bool|string $key If <b>false</b> - key will be generated automatically, otherwise must contain 56 character [0-9a-z] key * @param null|mixed $data Data to be stored with key * @param int $expire Timestamp of key expiration, if not specified - default system value will be used * * @return bool|string */ function add($database, $key, $data = null, $expire = 0) { if (!is_object($database)) { $database = DB::instance()->{$database}(); } if (!preg_match('/^[a-z0-9]{56}$/', $key)) { if ($key === false) { $key = $this->generate($database); } else { return false; } } $expire = (int) $expire; $Config = Config::instance(); if ($expire == 0 || $expire < TIME) { $expire = TIME + $Config->core['key_expire']; } $this->del($database, $key); $database->q("INSERT INTO `[prefix]keys`\n\t\t\t\t(\n\t\t\t\t\t`key`,\n\t\t\t\t\t`expire`,\n\t\t\t\t\t`data`\n\t\t\t\t) VALUES (\n\t\t\t\t\t'%s',\n\t\t\t\t\t'%s',\n\t\t\t\t\t'%s'\n\t\t\t\t)", $key, $expire, _json_encode($data)); $id = $database->id(); /** * Cleaning old keys */ if ($id && $id % $Config->core['inserts_limit'] == 0) { $time = TIME; $database->aq("DELETE FROM `[prefix]keys`\n\t\t\t\tWHERE `expire` < {$time}"); } return $key; }
/** * Put or change data of cache item * * @param string $item May contain "/" symbols for cache structure, for example users/<i>user_id</i> * @param mixed $data * * @return bool */ function set($item, $data) { $data = @_json_encode($data); if (mb_strpos($item, '/') !== false) { $path = mb_substr($item, 0, mb_strrpos($item, '/')); if (!is_dir(CACHE . "/{$path}")) { @mkdir(CACHE . "/{$path}", 0700, true); } unset($path); } if (!file_exists(CACHE . "/{$item}") || is_writable(CACHE . "/{$item}")) { if ($this->cache_size > 0) { $dsize = strlen($data); if ($dsize > $this->cache_size) { return false; } if (file_exists(CACHE . "/{$item}")) { $dsize -= filesize(CACHE . "/{$item}"); } $cache_size_file = fopen(CACHE . '/size', 'c+b'); $time = microtime(true); while (!flock($cache_size_file, LOCK_EX | LOCK_NB)) { if ($time < microtime(true) - 0.5) { fclose($cache_size_file); return false; } usleep(1000); } unset($time); $cache_size = (int) stream_get_contents($cache_size_file); $cache_size += $dsize; if ($cache_size > $this->cache_size) { $cache_list = get_files_list(CACHE, false, 'f', true, true, 'date|desc'); foreach ($cache_list as $file) { $cache_size -= filesize($file); unlink($file); $disk_size = $this->cache_size * 2 / 3; if ($cache_size <= $disk_size * Config::instance()->core['update_ratio'] / 100) { break; } } unset($cache_list, $file); } if (($return = file_put_contents(CACHE . "/{$item}", $data, LOCK_EX | FILE_BINARY)) !== false) { ftruncate($cache_size_file, 0); fseek($cache_size_file, 0); fwrite($cache_size_file, $cache_size > 0 ? $cache_size : 0); } flock($cache_size_file, LOCK_UN); fclose($cache_size_file); return $return; } else { return file_put_contents(CACHE . "/{$item}", $data, LOCK_EX | FILE_BINARY); } } else { $L = Language::instance(); trigger_error($L->file . ' ' . CACHE . "/{$item} {$L->not_writable}", E_USER_WARNING); return false; } }
/** * Is used as error handler * * @param int $level Error level * @param null|string $string Error message */ function trigger($level, $string = null) { if (!$this->error) { return; } $string = xap($string); $dump = 'null'; $debug_backtrace = debug_backtrace(); if (isset($debug_backtrace[0]['file'], $debug_backtrace[0]['file'])) { $file = $debug_backtrace[0]['file']; $line = $debug_backtrace[0]['line']; } else { $file = $debug_backtrace[1]['file']; $line = $debug_backtrace[1]['line']; } if (DEBUG) { $dump = _json_encode($debug_backtrace); } unset($debug_backtrace); $log_file = LOGS . '/' . date('d-m-Y') . '_' . strtr(date_default_timezone_get(), '/', '_'); $time = date('d-m-Y h:i:s') . ' [' . microtime(true) . ']'; switch ($level) { case E_USER_ERROR: case E_ERROR: ++$this->num; file_put_contents($log_file, "E {$time} {$string} Occurred: {$file}:{$line} Dump: {$dump}\n", LOCK_EX | FILE_APPEND); unset($dump); $this->errors_list[] = "E {$time} {$string} Occurred: {$file}:{$line}"; error_code(500); /** * If Index instance exists - execution will be stopped there, otherwise in Page instance */ Index::instance(true)->__finish(); Page::instance()->error(); break; case E_USER_WARNING: case E_WARNING: ++$this->num; file_put_contents($log_file, "W {$time} {$string} Occurred: {$file}:{$line} Dump: {$dump}\n", LOCK_EX | FILE_APPEND); unset($dump); $this->errors_list[] = "W {$time} {$string} Occurred: {$file}:{$line}"; break; default: file_put_contents($log_file, "N {$time} {$string} Occurred: {$file}:{$line} Dump: {$dump}\n", LOCK_EX | FILE_APPEND); unset($dump); $this->errors_list[] = "N {$time} {$string} Occurred: {$file}:{$line}"; break; } /** * If too many non-critical errors - also stop execution */ if ($this->num >= 100) { /** * If Index instance exists - execution will be stopped there, otherwise in Page instance */ Index::instance(true)->__finish(); Page::instance()->error(); } }
function OnActionLogout() { global $user, $data, $db; $ret['ret'] = $user->Logout(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { _json_encode($ret); } else { header("Location: /"); } }
function input($fieldName, $options = array(), $acOptions = array()) { $acFieldName = 'Ac' . $fieldName; $hiddenFieldOptions = array('type' => 'hidden'); $fieldId = $this->_getFieldName($fieldName); $acFieldId = $this->_getFieldName($acFieldName); $controller = $this->_getControllerName($fieldName); $out = $this->Form->input($fieldName, $hiddenFieldOptions); $out .= $this->Form->input($acFieldName, $options); $url = Router::url(array('controller' => $controller, 'action' => 'autocomplete', 'ext' => 'json'), true); $acOptions += array('dataType' => 'json', 'parse' => ' <script> function(data) { return $.map(data, function(row) { return { data: row, value: row.id, result: row.title } }); } </script>', 'formatItem' => ' <script> function(item) { return item.title; } </script>'); App::import('Vendor', 'Cholesterol.utils'); $jsonAcOptions = _json_encode($acOptions); $script = <<<EOF \$(document).ready(function() { \t\$('#{$acFieldId}').autocomplete('{$url}', \t\t{$jsonAcOptions} ) \t.result(function(e, item) { \t\t\$('#{$fieldId}').val(item.id); \t}); }); EOF; $this->Javascript->codeBlock($script, array('inline' => false)); return $out; }
/** * @param array $data Key => value array * * @return array|bool Return array(headers, body) */ protected function request($data) { $socket = fsockopen($this->host[0], isset($this->host[1]) ? $this->host[1] : 80, $errno, $errstr); if (!is_resource($socket)) { trigger_error("#{$errno} {$errstr}", E_USER_WARNING); $this->connected = false; return false; } if (empty($data)) { return false; } else { $data['key'] = md5(_json_encode($data) . $this->user . $this->password); } $data = 'data=' . urlencode(json_encode($data)); time_limit_pause(); fwrite($socket, "POST /Storage.php HTTP/1.1\r\n" . 'Host: ' . implode(':', $this->host) . "\r\n" . "Content-Type: application/x-www-form-urlencoded\r\n" . "Content-length:" . strlen($data) . "\r\n" . "Accept:*/*\r\n" . "User-agent: CleverStyle CMS\r\n\r\n" . $data . "\r\n\r\n"); $return = explode("\r\n\r\n", stream_get_contents($socket), 2); time_limit_pause(false); fclose($socket); return $return; }
function _json_encode($val) { if (is_string($val)) { return '"' . addslashes($val) . '"'; } if (is_numeric($val)) { return $val; } if ($val === null) { return 'null'; } if ($val === true) { return 'true'; } if ($val === false) { return 'false'; } $assoc = false; $i = 0; foreach ($val as $k => $v) { if ($k !== $i++) { $assoc = true; break; } } $res = array(); foreach ($val as $k => $v) { $v = _json_encode($v); if ($assoc) { $k = '"' . addslashes($k) . '"'; $v = $k . ':' . $v; } $res[] = $v; } $res = implode(',', $res); return $assoc ? '{' . $res . '}' : '[' . $res . ']'; }
function poll_service($service) { global $config; $update = array(); $old_status = $service['service_status']; $check_cmd = ""; // if we have a script for this check, use it. $check_script = $config['install_dir'] . '/includes/services/check_' . strtolower($service['service_type']) . '.inc.php'; if (is_file($check_script)) { include $check_script; } // If we do not have a cmd from the check script, build one. if ($check_cmd == "") { $check_cmd = $config['nagios_plugins'] . "/check_" . $service['service_type'] . " -H " . ($service['service_ip'] ? $service['service_ip'] : $service['hostname']); $check_cmd .= " " . $service['service_param']; } $service_id = $service['service_id']; // Some debugging d_echo("\nNagios Service - {$service_id}\n"); // the check_service function runs $check_cmd through escapeshellcmd, so // echo the command as it will be run after being escaped $escaped_check_cmd = escapeshellcmd($check_cmd); d_echo("Request: {$escaped_check_cmd}\n"); list($new_status, $msg, $perf) = check_service($check_cmd); d_echo("Response: {$msg}\n"); // If we have performance data we will store it. if (count($perf) > 0) { // Yes, We have perf data. $rrd_name = array('services', $service_id); // Set the DS in the DB if it is blank. $DS = array(); foreach ($perf as $k => $v) { $DS[$k] = $v['uom']; } d_echo("Service DS: " . _json_encode($DS) . "\n"); if ($service['service_ds'] == "") { $update['service_ds'] = json_encode($DS); } // rrd definition $rrd_def = array(); foreach ($perf as $k => $v) { if ($v['uom'] == 'c') { // This is a counter, create the DS as such $rrd_def[] = "DS:" . $k . ":COUNTER:600:0:U"; } else { // Not a counter, must be a gauge $rrd_def[] = "DS:" . $k . ":GAUGE:600:0:U"; } } // Update data $fields = array(); foreach ($perf as $k => $v) { $fields[$k] = $v['value']; } $tags = compact('service_id', 'rrd_name', 'rrd_def'); //TODO not sure if we have $device at this point, if we do replace faked $device data_update(array('hostname' => $service['hostname']), 'services', $tags, $fields); } if ($old_status != $new_status) { // Status has changed, update. $update['service_changed'] = time(); $update['service_status'] = $new_status; $update['service_message'] = $msg; } if ($service['service_message'] != $msg) { // Message has changed, update. $update['service_message'] = $msg; } if (count($update) > 0) { edit_service($update, $service['service_id']); } return true; }
require_once '../includes/functions.php'; require_once 'includes/authenticate.inc.php'; if (!$_SESSION['authenticated']) { echo 'unauthenticated'; exit; } $type = mres($_POST['type']); if ($type == 'placeholder') { $output = "<span style='text-align:left;'><br><h3>Click on the Edit Dashboard button (next to the list of dashboards) to add widgets</h3><br><h4><strong>Remember:</strong> You can only move & resize widgets when you're in <strong>Edit Mode</strong>.</h4><span>"; $status = 'ok'; $title = 'Placeholder'; } elseif (is_file('includes/common/' . $type . '.inc.php')) { $results_limit = 10; $no_form = true; $title = ucfirst($type); $unique_id = str_replace(array("-", "."), "_", uniqid($type, true)); $widget_id = mres($_POST['id']); $widget_settings = json_decode(dbFetchCell('select settings from users_widgets where user_widget_id = ?', array($widget_id)), true); $widget_dimensions = $_POST['dimensions']; if (!empty($_POST['settings'])) { define('show_settings', true); } include 'includes/common/' . $type . '.inc.php'; $output = implode('', $common_output); $status = 'ok'; $title = $widget_settings['title'] ?: $title; } $response = array('status' => $status, 'html' => $output, 'title' => $title); header('Content-type: application/json'); echo _json_encode($response);
function update_device() { global $config; $app = \Slim\Slim::getInstance(); $router = $app->router()->getCurrentRoute()->getParams(); $status = 'error'; $code = 500; $hostname = $router['hostname']; // use hostname as device_id if it's all digits $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname); $data = json_decode(file_get_contents('php://input'), true); $bad_fields = array('id', 'hostname'); if (empty($data['field'])) { $message = 'Device field to patch has not been supplied'; } elseif (in_array($data['field'], $bad_fields)) { $message = 'Device field is not allowed to be updated'; } else { if (dbUpdate(array(mres($data['field']) => mres($data['data'])), 'devices', '`device_id`=?', array($device_id)) >= 0) { $status = 'ok'; $message = 'Device ' . mres($data['field']) . ' field has been updated'; $code = 200; } else { $message = 'Device ' . mres($data['field']) . ' field failed to be updated'; } } $output = array('status' => $status, 'message' => $message); $app->response->setStatus($code); $app->response->headers->set('Content-Type', 'application/json'); echo _json_encode($output); }
/** * Set group data * * @param array $data May contain items title|description|data * @param int $group * * @return bool */ function set($data, $group) { $group = (int) $group; if (!$group) { return false; } $update = []; if (isset($data['title'])) { $update[] = '`title` = ' . $this->db_prime()->s(xap($data['title'], false)); } if (isset($data['description'])) { $update[] = '`description` = ' . $this->db_prime()->s(xap($data['description'], false)); } if (isset($data['data'])) { $update[] = '`data` = ' . $this->db_prime()->s(_json_encode($data['data'])); } $update = implode(', ', $update); if (!empty($update) && $this->db_prime()->q("UPDATE `[prefix]groups` SET {$update} WHERE `id` = '{$group}' LIMIT 1")) { $Cache = $this->cache; unset($Cache->{$group}, $Cache->all); return true; } else { return false; } }
function list_services() { global $config; $app = \Slim\Slim::getInstance(); $router = $app->router()->getCurrentRoute()->getParams(); $status = 'ok'; $code = 200; $message = ''; $host_par = array(); $sql_param = array(); $services = array(); $where = ''; $devicewhere = ''; // Filter BY STATE if (isset($_GET['state'])) { $where = " AND S.service_status= ? AND S.service_disabled='0' AND S.service_ignore='0'"; $host_par[] = $_GET['state']; if (!is_numeric($_GET['state'])) { $status = 'error'; $message = "No valid service state provided, valid option is 0=Ok, 1=Warning, 2=Critical"; } } // GET BY HOST if (isset($router['hostname'])) { $hostname = $router['hostname']; $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname); $where .= " AND S.device_id = ?"; $host_par[] = $device_id; if (!is_numeric($device_id)) { $status = 'error'; $message = "No valid hostname or device id provided"; } } // DEVICE $host_sql = 'SELECT * FROM devices AS D, services AS S WHERE D.device_id = S.device_id ' . $where . ' GROUP BY D.hostname ORDER BY D.hostname'; // SERVICE foreach (dbFetchRows($host_sql, $host_par) as $device) { $device_id = $device['device_id']; $sql_param[0] = $device_id; // FILTER BY TYPE if (isset($_GET['type'])) { $devicewhere = " AND `service_type` LIKE ?"; $sql_param[1] = $_GET['type']; } $services = dbFetchRows("SELECT * FROM `services` WHERE `device_id` = ?" . $devicewhere, $sql_param); } $count = count($services); $output = array('status' => $status, 'err-msg' => $message, 'count' => $count, 'services' => $services); $app->response->setStatus($code); $app->response->headers->set('Content-Type', 'application/json'); echo _json_encode($output); }
function get_devices_by_group() { $app = \Slim\Slim::getInstance(); $router = $app->router()->getCurrentRoute()->getParams(); $status = 'error'; $code = 404; $count = 0; $name = urldecode($router['name']); $devices = array(); if (empty($name)) { $message = 'No device group name provided'; } else { $group_id = dbFetchCell("SELECT `id` FROM `device_groups` WHERE `name`=?", array($name)); $devices = GetDevicesFromGroup($group_id); $count = count($devices); if (empty($devices)) { $message = 'No devices found in group ' . $name; } else { $message = "Found {$count} in group {$name}"; $code = 200; } } $output = array('status' => $status, 'message' => $message, 'count' => $count, 'devices' => $devices); $app->response->setStatus($code); $app->response->headers->set('Content-Type', 'application/json'); echo _json_encode($output); }
/** Generate javascript block for jqGrid * @param $id string id of html element * @param $gridOptions mixed jqgrid's option * @param $navGridOption mixed jqgrid's navigator options */ function script($id, $gridOptions = array(), $navGridOptions = array()) { $gridOptions = Set::merge(array('caption' => null, 'datatype' => 'json', 'mtype' => 'GET', 'gridModel' => true, 'url' => null, 'pager' => null, 'colNames' => array(), 'colModel' => array(), 'rowNum' => 5, 'rowList' => array(5, 10), 'viewrecords' => true, 'width' => '100%', 'jsonReader' => array('repeatitems' => false, 'id' => 'id')), $gridOptions); $navGridOptions = Set::merge(array('o' => array('add' => false, 'edit' => false, 'del' => false, 'search' => true), 'pEdit' => false, 'pAdd' => false, 'pDel' => false, 'pSearch' => array('multipleSearch' => true), 'pView' => null), $navGridOptions); if (!empty($this->pager)) { $pager = $this->pager; } if (!empty($gridOptions['pager'])) { $pager = $gridOptions['pager']; } if (!empty($pager)) { $gridOptions['pager'] = $pager; } if (empty($gridOptions['colModel'])) { $this->_useModelSchema($gridOptions); } $jsonOptions = _json_encode($gridOptions); $jsonNavGridOptions = _json_encode($navGridOptions['o']); $jsonPEdit = _json_encode($navGridOptions['pEdit']); $jsonPAdd = _json_encode($navGridOptions['pAdd']); $jsonPDel = _json_encode($navGridOptions['pDel']); $jsonPSearch = _json_encode($navGridOptions['pSearch']); $jsonPView = _json_encode($navGridOptions['pView']); $code = ''; if (!empty($pager)) { $code .= <<<EOF var grid = \$('#{$id}').jqGrid({$jsonOptions}).navGrid('#{$pager}', {$jsonNavGridOptions}, \t{$jsonPEdit}, {$jsonPAdd}, {$jsonPDel}, {$jsonPSearch}, {$jsonPView}); EOF; } else { $code .= <<<EOF var grid = \$('#{$id}').jqGrid({$jsonOptions}); EOF; } if ($this->filterMode) { $code .= <<<EOF grid.getPostData().filterMode = '{$this->filterMode}'; EOF; } if ($this->filterToolbar) { $code .= <<<EOF grid.navButtonAdd('#{$pager}',{ \tcaption: '', \ttitle: 'Clear Filter', \tbuttonicon: 'ui-icon-arrowrefresh-1-n', \tonClickButton: function() { \t\tgrid[0].clearToolbar(); \t}, \tposition: 'last' }); EOF; } if (!empty($this->exportOptions)) { $code .= <<<EOF grid.navButtonAdd('#{$pager}',{ \tcaption: '', \ttitle: 'Export to CSV', \tbuttonicon: 'ui-icon-disk', \tonClickButton: function() { \t\tvar url = grid.getGridParam('url') \t\tvar post = grid.getPostData(); \t\tvar param = []; \t\tvar form = \$('#form_download_{$id}'); \t\tpost.gridId = 'form_download_{$id}'; \t\tvar inputs = ''; \t\tfor (p in post) { \t\t\tvar item = p + '=' + post[p]; \t\t\tinputs += '<input name="' + p + '" value="' + post[p] + '">'; \t\t\tparam.push(item) \t\t} \t\tform.html(inputs); \t\tdelete post.exportOptions; \t\tform.attr('action', url).submit(); \t}, \tposition: 'last' }); EOF; } if ($this->filterToolbar) { $code .= <<<EOF grid.filterToolbar(); EOF; } $script = <<<EOF \$(document).ready(function() { \t{$code} }); EOF; return $this->Javascript->codeBlock($script); }
/** * file_put_contents(_json_encode()) * * @param string $filename Name of the file to read. * @param mixed $data The data to write * @param int $flags * @param resource $context * * @return mixed */ function file_put_json($filename, $data, $flags = null, &$context = null) { return file_put_contents($filename, _json_encode($data), $flags, $context); }
function list_oxidized() { // return details of a single device $app = \Slim\Slim::getInstance(); $app->response->headers->set('Content-Type', 'application/json'); $devices = array(); foreach (dbFetchRows("SELECT hostname,os FROM `devices` WHERE `status`='1'") as $device) { $devices[] = $device; } $app->response->headers->set('Content-Type', 'application/json'); echo _json_encode($devices); }
function ack_alert() { global $config; $app = \Slim\Slim::getInstance(); $router = $app->router()->getCurrentRoute()->getParams(); $alert_id = mres($router['id']); $status = 'error'; $err_msg = ''; $message = ''; $code = 500; if (is_numeric($alert_id)) { $status = 'ok'; $code = 200; if (dbUpdate(array("state" => 2), 'alerts', '`id` = ? LIMIT 1', array($alert_id))) { $message = 'Alert has been ackgnowledged'; } else { $message = 'No alert by that ID'; } } else { $err_msg = 'Invalid alert has been provided'; } $output = array("status" => $status, "err-msg" => $err_msg, "message" => $message); $app->response->setStatus($code); $app->response->headers->set('Content-Type', 'application/json'); echo _json_encode($output); }
$KEY = substr($data['key'], 0, 32); unset($data['key']); if (md5(_json_encode($data) . $STORAGE_USER . $STORAGE_PASSWORD) !== $KEY) { exit; } unset($GLOBALS['STORAGE_USER'], $GLOBALS['STORAGE_PASSWORD'], $KEY); } else { exit; } switch ($data['function']) { default: exit; case 'get_files_list': exit(_json_encode(get_files_list($data['dir'], $data['mask'], $data['mode'], $data['prefix_path'], $data['subfolders'], $data['sort'], $data['exclusion'], $data['system_files'], null, $data['limit']))); case 'file': exit(_json_encode(file($data['filename'], $data['flags']))); case 'file_get_contents': exit(file_get_contents($data['filename'], $data['flags'], null, $data['offset'], $data['maxlen'])); case 'file_put_contents': exit(file_put_contents($data['filename'], $data['data'], $data['flags'])); case 'copy': exit(copy($data['source'], $data['dest'])); case 'unlink': exit(unlink($data['filename'])); case 'file_exists': exit(file_exists($data['filename'])); case 'move_uploaded_file': exit(copy($data['filename'], $data['destination'])); case 'rename': exit(rename($data['oldname'], $data['newname'])); case 'mkdir':
*/ if ($_SESSION['userlevel'] < 10) { print_error_permission(); return; } $export_device = $device; if ($config['snmp']['hide_auth']) { $params = array('snmp_community', 'snmp_authlevel', 'snmp_authname', 'snmp_authpass', 'snmp_authalgo', 'snmp_cryptopass', 'snmp_cryptoalgo'); foreach ($params as $param) { if (strlen($export_device[$param])) { $export_device[$param] = '***'; } } } if ($vars['saveas'] == 'yes' && $vars['filename']) { download_as_file(gzencode(_json_encode($export_device)), $vars['filename']); } else { if ($config['snmp']['hide_auth']) { print_warning("NOTE, <strong>\$config['snmp']['hide_auth']</strong> is set to <strong>TRUE</strong>, snmp community and snmp v3 auth hidden from output and export."); } else { print_error("WARNING, <strong>\$config['snmp']['hide_auth']</strong> is set to <strong>FALSE</strong>, snmp community and snmp v3 auth <strong>NOT hidden</strong> from output and export."); } $form = array('type' => 'rows', 'space' => '10px', 'url' => generate_url($vars)); // Filename $form['row'][0]['filename'] = array('type' => 'text', 'name' => 'Filename', 'value' => $device['hostname'] . '.json.txt.gz', 'width' => '100%', 'placeholder' => TRUE); // Compress //$form['row'][0]['compress'] = array( // 'type' => 'switch', // 'value' => 1); // Search button $form['row'][0]['saveas'] = array('type' => 'submit', 'name' => 'Export', 'icon' => 'icon-save', 'right' => TRUE, 'value' => 'yes');
function list_ipsec() { $app = \Slim\Slim::getInstance(); $router = $app->router()->getCurrentRoute()->getParams(); $status = 'error'; $code = 404; $message = ''; $hostname = $router['hostname']; // use hostname as device_id if it's all digits $device_id = ctype_digit($hostname) ? $hostname : getidbyname($hostname); if (!is_numeric($device_id)) { $message = "No valid hostname or device ID provided"; } else { $ipsec = dbFetchRows("SELECT `D`.`hostname`, `I`.* FROM `ipsec_tunnels` AS `I`, `devices` AS `D` WHERE `I`.`device_id`=? AND `D`.`device_id` = `I`.`device_id`", array($device_id)); $total = count($ipsec); $status = 'ok'; $code = 200; } $output = array('status' => $status, 'err-msg' => $message, 'count' => $total, 'ipsec' => $ipsec); $app->response->setStatus($code); $app->response->headers->set('Content-Type', 'application/json'); echo _json_encode($output); }
/** * Creates cached version of given js and css files.<br> * Resulting file name consists of <b>$filename_prefix</b> and <b>$this->pcache_basename</b> * * @param string $filename_prefix * @param array $includes Array of paths to files, may have keys: <b>css</b> and/or <b>js</b> * * @return array */ protected function create_cached_includes_files($filename_prefix, $includes) { $cache_hash = []; foreach ($includes as $extension => &$files) { $files_content = ''; foreach ($files as $file) { if (!file_exists($file)) { continue; } /** * Insert external elements into resulting css file. * It is needed, because those files will not be copied into new destination of resulting css file. */ if ($extension == 'css') { $files_content .= $this->css_includes_processing(file_get_contents($file), $file); } else { $files_content .= file_get_contents($file) . ';'; } } if ($filename_prefix == '' && $extension == 'js') { $files_content = "window.cs.Language=" . _json_encode(Language::instance()) . ";{$files_content}"; } file_put_contents(PCACHE . "/{$filename_prefix}{$this->pcache_basename}.{$extension}", gzencode($files_content, 9), LOCK_EX | FILE_BINARY); $cache_hash[$extension] = substr(md5($files_content), 0, 5); } return $cache_hash; }
<?php /* * LibreNMS * * Copyright (c) 2016 Aaron Daniels <*****@*****.**> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. Please see LICENSE.txt at the top level of * the source code distribution for details. */ if (is_admin() === false) { $status = array('status' => 1, 'message' => 'ERROR: You need to be admin to delete services'); } else { if (!is_numeric($vars['service_id'])) { $status = array('status' => 1, 'message' => 'No Service has been selected'); } else { if (delete_service($vars['service_id'])) { $status = array('status' => 0, 'message' => 'Service: <i>' . $vars['service_id'] . ', has been deleted.</i>'); } else { $status = array('status' => 1, 'message' => 'Service: <i>' . $vars['service_id'] . ', has NOT been deleted.</i>'); } } } header('Content-Type: application/json'); echo _json_encode($status);
$NombreOtorgante = $xCR->getNombreOtorgante(); $DomicilioDevolucion = ""; //str_replace(",", ";", EACP_DOMICILIO_CORTO); //============================== ELEMENTOS DE CONTROL $linea .= "{$TotalSaldosActuales}|{$TotalSaldosVencidos}|{$TotalElementosNombres}|{$TotalElementosDireccion}|{$TotalElementosEmpleo}|{$TotalElementosCuenta}|{$NombreOtorgante}|{$DomicilioDevolucion}"; // if ($xSoc->getEsPersonaFisica() == true) { if ($toJson == true) { $arrLinea = explode("|", $linea); $jsonNew = array(); foreach ($itemJson as $ix => $item) { $jsonNew[$item] = isset($arrLinea[$ix]) ? $arrLinea[$ix] : "ERORR"; } $lineaJson[] = $jsonNew; } else { echo $linea . "\r\n"; } } else { //OMITIDO $xLog->add("WARN\t{$idpersona}-{$idcredito}\t{$sucres}\tOmitir por ser Persona Moral " . $xSoc->getNombre() . "\r\n", $xLog->DEVELOPER); } $icnt++; } if (MODO_DEBUG) { $xFil = new cFileLog(); $xFil->setWrite($xLog->getMessages()); $xFil->setSendToMail($xHP->getTitle(), ADMIN_MAIL); } if ($toJson == true) { echo _json_encode($lineaJson, JSON_PRETTY_PRINT); }
function json_encode($var, $obj = FALSE) { return _json_encode($var); }
$max_val = 0; foreach (dbFetchRows($query, $param) as $return_value) { $date = $return_value['Date']; $loss = $return_value['loss']; $min = $return_value['min']; $max = $return_value['max']; $avg = $return_value['avg']; if ($max > $max_val) { $max_val = $max; } $data[] = array('x' => $date, 'y' => $loss, 'group' => 0); $data[] = array('x' => $date, 'y' => $min, 'group' => 1); $data[] = array('x' => $date, 'y' => $max, 'group' => 2); $data[] = array('x' => $date, 'y' => $avg, 'group' => 3); } $graph_data = _json_encode($data); ?> var names = ['Loss','Min latency','Max latency','Avg latency']; var groups = new vis.DataSet(); groups.add({ id: 0, content: names[0], options: { drawPoints: { style: 'circle' }, shaded: { orientation: 'bottom' } } });
<?php /* * LibreNMS * * Copyright (c) 2014 Neil Lathwood <https://github.com/laf/ http://www.lathwood.co.uk/fa> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. Please see LICENSE.txt at the top level of * the source code distribution for details. */ if (is_admin() === false) { header('Content-type: text/plain'); die('ERROR: You need to be admin'); } $alert_id = $_POST['alert_id']; if (is_numeric($alert_id) && $alert_id > 0) { $rule = dbFetchRow('SELECT * FROM `alert_rules` WHERE `id` = ? LIMIT 1', array($alert_id)); $rule_split = preg_split('/([a-zA-Z0-9_\\-\\.\\=\\%\\<\\>\\ \\"\'\\!\\~\\(\\)\\*\\/\\@\\|]+[&&|\\|\\|]{2})/', $rule['rule'], -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $count = count($rule_split) - 1; $rule_split[$count] = $rule_split[$count] . ' &&'; $output = array('severity' => $rule['severity'], 'extra' => $rule['extra'], 'name' => $rule['name'], 'proc' => $rule['proc'], 'rules' => $rule_split); header('Content-type: application/json'); echo _json_encode($output); }
* under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. Please see LICENSE.txt at the top level of * the source code distribution for details. */ if (is_admin() === false) { die('ERROR: You need to be admin'); } $transport = mres($_POST['transport']); $obj = array('contacts' => $config['alert']['default_mail'], 'title' => 'Testing transport from ' . $config['project_name'], 'msg' => 'This is a test alert', 'severity' => 'critical', 'state' => 'critical', 'hostname' => 'testing', 'name' => 'Testing rule'); unset($obj); $obj['contacts'] = 'test'; $obj['title'] = 'test'; $obj['msg'] = 'test'; $obj['severity'] = 'test'; $obj['state'] = 'test'; $obj['hostname'] = 'test'; $obj['name'] = 'test'; $status = 'error'; if (file_exists($config['install_dir'] . "/includes/alerts/transport.{$transport}.php")) { $opts = $config['alert']['transports'][$transport]; if ($opts) { eval('$tmp = function($obj,$opts) { global $config; ' . file_get_contents($config['install_dir'] . '/includes/alerts/transport.' . $transport . '.php') . ' };'); $tmp = $tmp($obj, $opts); if ($tmp) { $status = 'ok'; } } } echo _json_encode(array('status' => $status));
function list_bills() { global $config; $app = \Slim\Slim::getInstance(); $router = $app->router()->getCurrentRoute()->getParams(); $status = 'ok'; $err_msg = ''; $message = ''; $code = 200; $bills = array(); $bill_id = mres($router['bill_id']); $bill_ref = mres($_GET['ref']); $bill_custid = mres($_GET['custid']); if (!empty($bill_custid)) { $sql = '`bill_custid` = ?'; $param = array($bill_custid); } elseif (!empty($bill_ref)) { $sql = '`bill_ref` = ?'; $param = array($bill_ref); } elseif (is_numeric($bill_id)) { $sql = '`bill_id` = ?'; $param = array($bill_id); } else { $sql = ''; $param = array(); } if (count($param) >= 1) { $sql = "WHERE {$sql}"; } foreach (dbFetchRows("SELECT `bills`.*,COUNT(port_id) AS `ports_total` FROM `bills` LEFT JOIN `bill_ports` ON `bill_ports`.`bill_id`=`bills`.`bill_id` {$sql} GROUP BY `bill_name`,`bill_ref` ORDER BY `bill_name`", $param) as $bill) { $rate_data = $bill; $allowed = ''; $used = ''; $percent = ''; $overuse = ''; if ($bill['bill_type'] == "cdr") { $allowed = format_si($bill['bill_cdr']) . "bps"; $used = format_si($rate_data['rate_95th']) . "bps"; $percent = round($rate_data['rate_95th'] / $bill['bill_cdr'] * 100, 2); $overuse = $rate_data['rate_95th'] - $bill['bill_cdr']; $overuse = $overuse <= 0 ? "-" : format_si($overuse); } elseif ($bill['bill_type'] == "quota") { $allowed = format_bytes_billing($bill['bill_quota']); $used = format_bytes_billing($rate_data['total_data']); $percent = round($rate_data['total_data'] / $bill['bill_quota'] * 100, 2); $overuse = $rate_data['total_data'] - $bill['bill_quota']; $overuse = $overuse <= 0 ? "-" : format_bytes_billing($overuse); } $bill['allowed'] = $allowed; $bill['used'] = $used; $bill['percent'] = $percent; $bill['overuse'] = $overuse; $bills[] = $bill; } $count = count($bills); $output = array('status' => $status, 'message' => $message, 'err-msg' => $err_msg, 'count' => $count, 'bills' => $bills); $app->response->setStatus($code); $app->response->headers->set('Content-Type', 'application/json'); echo _json_encode($output); }
/** * JSON encode wrapper * - missing or broken in some php 5.x versions * * @param mixed $value * @return string */ public static function json_encode($value) { if (self::useJsonLibrary()) { return _json_encode($value); } return @json_encode($value); }