/** * Colors the given string with the given color (if coloring is available) * * @param string $colorCode * @param string $message * * @return string */ protected function color($colorCode, $message) { if ($this->consoleColor !== null) { $message = $this->consoleColor->convert($colorCode . $message . '%n'); } return $message; }
function print_message($text) { if (isCli()) { print Console_Color2::convert("%g" . $text . "%n\n", false); } else { echo '<div class="alert alert-success"><img src="images/16/tick.png" align="absmiddle"> ' . $text . '</div>'; } }
/** * Calculates the ANSI code from the given context name * * @param string $context_name Name of context, from parseToken * * @return string ANSI color code to output, null if no color shall be used. */ protected function getAnsiCode($context_name) { if (isset($this->ansiCache[$context_name])) { return $this->ansiCache[$context_name]; } $style = $this->_styler->getStyle($context_name); $color = $style['font']['color']; $bold = $style['font']['style']['bold']; $colorname = $this->getColorName(255 * $color['R'], 255 * $color['G'], 255 * $color['B']); if ($colorname === 'black' && !$style['font']['style']['bold']) { return null; } $index = 0 + (int) $bold; $ansicode = $this->ccolor->convert(self::$ansi[$colorname][$index]); $this->ansiCache[$context_name] = $ansicode; return $ansicode; }
/** * Process command * * @return string */ public function process() { try { $this->command = $this->parser->parse(); if (empty($this->command->command_name)) { $this->parser->displayUsage(); self::end(0); } $return = $this->controller->execute($this->command->command_name, $this->command->command->options, $this->command->command->args, $this->color, $this->logger, $this->tasks); } catch (ShellException $se) { $this->parser->displayError($this->color->convert("\n\n%R" . $se->getMessage() . "%n\n")); self::end(1); } catch (Exception $e) { $this->parser->displayError($this->color->convert("\n\n%r" . $e->getMessage() . "%n\n")); self::end(1); } echo "\n" . $return . "\n\n"; self::end(0); }
/** * Returns the character length of a string. * * @param string $str A multibyte or singlebyte string. * * @return integer The string length. */ function _strlen($str) { static $mbstring; // Strip ANSI color codes if requested. if ($this->_ansiColor) { $str = $this->_ansiColor->strip($str); } // Cache expensive function_exists() calls. if (!isset($mbstring)) { $mbstring = function_exists('mb_strwidth'); } if ($mbstring) { return mb_strwidth($str, $this->_charset); } return strlen($str); }
#!/usr/bin/env php <?php require '../includes/console_colour.php'; require '../includes/console_table.php'; require '../includes/defaults.inc.php'; require '../config.php'; require_once '../includes/definitions.inc.php'; require '../includes/functions.php'; require '../html/includes/functions.inc.php'; $console_color = new Console_Color2(); $long_opts = array('list::', 'device-stats'); $options = getopt('l:d:', $long_opts); $end = 0; while ($end == 0) { passthru('clear'); $tbl = new Console_Table(CONSOLE_TABLE_ALIGN_RIGHT); foreach (dbFetchRows('SELECT * FROM `devices` ORDER BY `hostname`') as $device) { if (get_dev_attrib($device, 'override_sysLocation_bool')) { $device['real_location'] = $device['location']; $device['location'] = get_dev_attrib($device, 'override_sysLocation_string'); } $devices['count']++; $cache['devices']['hostname'][$device['hostname']] = $device['device_id']; $cache['devices']['id'][$device['device_id']] = $device; $cache['device_types'][$device['type']]++; } // Include the required SQL queries to get our data include '../includes/db/status_count.inc.php'; $tbl->addRow(array('Devices (' . $devices['count'] . ')', print $console_color->convert('%g' . $devices['up'] . ' Up%n'), print $console_color->convert('%r' . $devices['down'] . ' Down%n'), print $console_color->convert('%y' . $devices['ignored'] . ' Ignored%n'), print $console_color->convert('%p' . $devices['disabled'] . ' Disabled%n'))); $tbl->addRow(array('Ports (' . $ports['count'] . ')', print $console_color->convert('%g' . $ports['up'] . ' Up%n'), print $console_color->convert('%r' . $ports['down'] . ' Down%n'), print $console_color->convert('%y' . $ports['ignored'] . ' Ignored%n'), print $console_color->convert('%p' . $ports['shutdown'] . ' Shutdown%n'))); $tbl->addRow(array('Services (' . $services['count'] . ')', print $console_color->convert('%g' . $services['up'] . ' Up%n'), print $console_color->convert('%r' . $services['down'] . ' Down%n'), print $console_color->convert('%y' . $services['ignored'] . ' Ignored%n'), print $console_color->convert('%p' . $services['disabled'] . ' Shutdown%n')));
#!/usr/bin/env php <?php include '../includes/console_colour.php'; include '../includes/console_table.php'; include "../includes/defaults.inc.php"; include "../config.php"; include_once "../includes/definitions.inc.php"; include "../includes/functions.php"; include "../html/includes/functions.inc.php"; $console_color = new Console_Color2(); $long_opts = array('list::', 'device-stats'); $options = getopt("l:d:", $long_opts); $end = 0; while ($end == 0) { passthru('clear'); $tbl = new Console_Table(CONSOLE_TABLE_ALIGN_RIGHT); foreach (dbFetchRows("SELECT * FROM `devices` ORDER BY `hostname`") as $device) { if (get_dev_attrib($device, 'override_sysLocation_bool')) { $device['real_location'] = $device['location']; $device['location'] = get_dev_attrib($device, 'override_sysLocation_string'); } $devices['count']++; $cache['devices']['hostname'][$device['hostname']] = $device['device_id']; $cache['devices']['id'][$device['device_id']] = $device; $cache['device_types'][$device['type']]++; } // Include the required SQL queries to get our data require '../includes/db/status_count.inc.php'; $tbl->addRow(array('Devices (' . $devices['count'] . ')', print $console_color->convert("%g" . $devices['up'] . " Up%n"), print $console_color->convert("%r" . $devices['down'] . " Down%n"), print $console_color->convert("%y" . $devices['ignored'] . " Ignored%n"), print $console_color->convert("%p" . $devices['disabled'] . " Disabled%n"))); $tbl->addRow(array('Ports (' . $ports['count'] . ')', print $console_color->convert("%g" . $ports['up'] . " Up%n"), print $console_color->convert("%r" . $ports['down'] . " Down%n"), print $console_color->convert("%y" . $ports['ignored'] . " Ignored%n"), print $console_color->convert("%p" . $ports['shutdown'] . " Shutdown%n"))); $tbl->addRow(array('Services (' . $services['count'] . ')', print $console_color->convert("%g" . $services['up'] . " Up%n"), print $console_color->convert("%r" . $services['down'] . " Down%n"), print $console_color->convert("%y" . $services['ignored'] . " Ignored%n"), print $console_color->convert("%p" . $services['disabled'] . " Shutdown%n")));
function print_message($text, $type = '', $strip = TRUE) { global $config; $type = trim(strtolower($type)); switch ($type) { case 'success': $color = array('cli' => '%g', 'cli_color' => FALSE, 'class' => 'alert alert-success'); // green $icon = 'oicon-tick-circle'; break; case 'warning': $color = array('cli' => '%b', 'cli_color' => FALSE, 'class' => 'alert'); // yellow $icon = 'oicon-bell'; break; case 'error': $color = array('cli' => '%r', 'cli_color' => FALSE, 'class' => 'alert alert-error'); // red $icon = 'oicon-exclamation-red'; break; case 'debug': $color = array('cli' => '%r', 'cli_color' => FALSE, 'class' => 'alert alert-error'); // red $icon = 'oicon-exclamation-red'; break; case 'color': $color = array('cli' => '', 'cli_color' => TRUE, 'class' => 'alert alert-info'); // blue $icon = 'oicon-information'; break; default: $color = array('cli' => '%W', 'cli_color' => FALSE, 'class' => 'alert alert-info'); // blue $icon = 'oicon-information'; break; } if (is_cli()) { include_once $config['install_dir'] . "/includes/pear/Console/Color2.php"; if ($strip) { $text = strip_tags($text); } $msg = new Console_Color2(); print $msg->convert($color['cli'] . $text . "%n\n", $color['cli_color']); } else { if ($text === '') { return NULL; } // Do not web output if the string is empty $msg = '<div class="' . $color['class'] . '">'; if ($type != 'warning' && $type != 'error') { $msg .= '<button type="button" class="close" data-dismiss="alert">×</button>'; } $msg .= ' <div class="pull-left" style="padding:0 5px 0 0"><i class="' . $icon . '"></i></div> <div>' . nl2br($text) . '</div> </div>'; echo $msg; } }
public static function formatTimed($startTime, $message) { static $color = null; if ($color === null) { if (PieCrustDefaults::IS_WINDOWS()) { $color = false; } else { $color = new \Console_Color2(); } } $endTime = microtime(true); $endTimeStr = sprintf('%8.1f ms', ($endTime - $startTime) * 1000.0); if ($color) { $endTimeStr = $color->escape($endTimeStr); $message = $color->escape($message); return $color->convert("[%g{$endTimeStr}%n] {$message}"); } else { return "[{$endTimeStr}] {$message}"; } }
#!/usr/bin/php <?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. */ require 'includes/console_colour.php'; $console_color = new Console_Color2(); $options = getopt('m:h::'); if (isset($options['h'])) { print $console_color->convert("\n Validate setup tool\n\n Usage: ./validate.php [-m <module>] [-h]\n -h This help section.\n -m Any sub modules you want to run, comma separated:\n - mail: this will test your email settings (uses default_mail option even if default_only is not set).\n\n Example: ./validate.php -m mail.\n\n "); exit; } if (strstr(`php -ln config.php`, 'No syntax errors detected')) { $first_line = `head -n1 config.php`; $last_lines = explode(PHP_EOL, `tail -n2 config.php`); if (strstr($first_line, '\\<\\?php')) { print_fail("config.php doesn't start with a <?php - please fix this ({$first_line})"); } else { if ($last_lines[0] == '?>' && $last_lines[1] == '') { print_fail('config.php contains a new line at the end, please remove any whitespace at the end of the file and also remove ?>'); } else { if ($last_lines[1] == '?>') { print_warn("It looks like you have ?> at the end of config.php, it's suggested you remove this");
<?php $color = new Console_Color2(); $ok = $color->color('green'); $fail = $color->color('red'); $reset = $color->color('reset'); print $ok . "OK " . $reset . "Something succeeded!\n"; print $fail . "FAIL " . $reset . "Something failed!\n";
<?php require 'Console/Color2.php'; $color = new Console_Color2(); // Let's add a little color to the world // %n resets the color so the following stuff doesn't get messed up print $color->convert("%bHello World!%n\n"); // Colorless mode, in case you need to strip colorcodes off a text print $color->convert("%rHello World!%n\n", false); // The uppercase version makes a colorcode bold/bright print $color->convert("%BHello World!%n\n"); // To print a %, you use %% print $color->convert("3 out of 4 people make up about %r75%% %nof the " . "world population.\n"); // Or you can use the escape() method. print $color->convert("%y" . $color->escape('If you feel that you do everying wrong, be random' . ', there\'s a 50% Chance of making the right ' . 'decision.') . "%n\n");
/** * This function echoes text with specific styles (different for cli and web output). * * @param string $text * @param string $type Supported types: default, success, warning, error, debug * @param boolean $strip Stripe special characters (for web) or html tags (for cli) */ function print_message($text, $type = '', $strip = TRUE) { global $config; // Do nothing if input text not any string (like NULL, array or other). (Empty string '' still printed). if (!is_string($text) && !is_numeric($text)) { return NULL; } $type = trim(strtolower($type)); switch ($type) { case 'success': $color = array('cli' => '%g', 'cli_color' => FALSE, 'class' => 'alert alert-success'); // green $icon = 'oicon-tick-circle'; break; case 'warning': $color = array('cli' => '%b', 'cli_color' => FALSE, 'class' => 'alert alert-warning'); // yellow $icon = 'oicon-bell'; break; case 'error': $color = array('cli' => '%r', 'cli_color' => FALSE, 'class' => 'alert alert-danger'); // red $icon = 'oicon-exclamation-red'; break; case 'debug': $color = array('cli' => '%r', 'cli_color' => FALSE, 'class' => 'alert alert-danger'); // red $icon = 'oicon-exclamation-red'; break; case 'color': $color = array('cli' => '', 'cli_color' => TRUE, 'class' => 'alert alert-info'); // blue $icon = 'oicon-information'; break; case 'console': // This is special type used nl2br conversion for display console messages on WUI with correct line breaks $color = array('cli' => '', 'cli_color' => TRUE, 'class' => 'alert alert-suppressed'); // purple $icon = 'oicon-information'; break; default: $color = array('cli' => '%W', 'cli_color' => FALSE, 'class' => 'alert alert-info'); // blue $icon = 'oicon-information'; break; } if (is_cli()) { if ($strip) { $text = html_entity_decode($text, ENT_QUOTES, 'UTF-8'); // Convert special HTML entities back to characters $text = str_ireplace(array('<br />', '<br>', '<br/>'), PHP_EOL, $text); // Convert html <br> to into newline $text = strip_tags($text); } if ($type == 'debug' && !$color['cli_color']) { // For debug just echo message. echo $text . PHP_EOL; } else { include_once "Console/Color2.php"; $msg = new Console_Color2(); print $msg->convert($color['cli'] . $text . '%n' . PHP_EOL, $color['cli_color']); } } else { if ($text === '') { return NULL; } // Do not web output if the string is empty if ($strip) { if ($text == strip_tags($text)) { // Convert special characters to HTML entities only if text not have html tags $text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8'); } if ($color['cli_color']) { // Replace some Pear::Console_Color2 color codes with html styles $replace = array('%', '</span>', '<span class="label label-warning">', '<span class="label label-success">', '<span class="label label-danger">', '<span class="label label-primary">', '<span class="label label-info">', '<span class="label label-default">', '<span class="label label-default" style="color:black;">', '<span style="font-weight: bold;">', '<span style="text-decoration: underline;">'); } else { $replace = array('%', ''); } $text = str_replace(array('%%', '%n', '%y', '%g', '%r', '%b', '%c', '%W', '%k', '%_', '%U'), $replace, $text); } $msg = PHP_EOL . ' <div class="' . $color['class'] . '">'; if ($type != 'warning' && $type != 'error') { $msg .= '<button type="button" class="close" data-dismiss="alert">×</button>'; } if ($type == 'console') { $text = nl2br(trim($text)); // Convert newline to <br /> for console messages with line breaks } $msg .= ' <div>' . $text . '</div> </div>' . PHP_EOL; echo $msg; } }
/** * Retrieve/format statistics. * * @since 15xxxx Initial release. */ protected function statistics() { $args = ['type' => $this->type, 'days' => $this->days, 'weeks' => $this->weeks, 'months' => $this->months, 'years' => $this->years, 'start_time' => $this->start_time, 'source' => $this->source, 'sku' => $this->sku, 'key' => $this->config->websharks->api_key]; $endpoint = 'https://www.websharks-inc.com/sales/api.php'; $endpoint = $this->UrlQuery->addArgs($args, $endpoint); $response = json_decode($this->UrlRemote->request('GET::' . $endpoint)); if (!is_object($response) || !empty($response->error)) { if (!empty($response->error)) { throw new \Exception('Unable to retrieve statistics.' . "\n" . 'The API said: `' . $response->error . '`'); } throw new \Exception('Unable to retrieve statistics.' . "\n" . 'The API call failed w/ an unknown error.'); } $statistics = ''; // Initialize. $table = new \Console_Table(CONSOLE_TABLE_ALIGN_LEFT, CONSOLE_TABLE_BORDER_ASCII, 1, 'UTF-8', true); $table_color = new \Console_Color2(); // Coloration class. $table_colorize_amount = function ($amount) use($table_color) { return $table_color->convert('%G' . $amount . '%n'); }; $table_colorize_from = function ($from) use($table_color) { return $table_color->convert('%b' . $from . '%n'); }; $table_colorize_to = function ($to) use($table_color) { return $table_color->convert('%b' . $to . '%n'); }; $table->setHeaders(['From', 'To', 'Amount']); $table->addFilter(0, $table_colorize_from); $table->addFilter(1, $table_colorize_to); $table->addFilter(2, $table_colorize_amount); $chart = ''; // Initialize. $chart_data = ''; // Initialize. $chart_gnuplot = []; // Initialize. $chart_first_from = $chart_last_to = ''; // Initialize. $chart_data_file = $this->FsDir->tmp() . '/' . md5(__CLASS__ . 'gnuplot') . '.dat'; date_default_timezone_set('UTC'); // UTC timezone. $statistics .= '**' . $response->title . '**'; if ($response->caption) { // Caption also? $statistics .= ' _*' . $response->caption . '*_'; } $statistics .= "\n"; // Additional line break. foreach ($response->results as $_result) { $_from = date('D M d, Y @ H:i a T', strtotime($_result->from)); $_to = date('D M d, Y @ H:i a T', strtotime($_result->to)); $table->addRow([$_from, $_to, '$' . $_result->amount]); } unset($_result); // Housekeeping. $statistics .= $table->getTable(); // Append table. foreach ($response->results as $_result) { if (empty($chart_first_from)) { $chart_first_from = date('D M d, Y @ H:i a T', strtotime($_result->from)); } $chart_last_to = date('D M d, Y @ H:i a T', strtotime($_result->to)); $chart_data .= '"" ' . $_result->amount . "\n"; } $chart_data = trim($chart_data); file_put_contents($chart_data_file, $chart_data); unset($_result); // Housekeeping. $chart_gnuplot[] = 'gnuplot'; $chart_gnuplot[] = '-e'; // Eval the following. $chart_gnuplot[] = 'set terminal dumb size 83, 20;' . ' set yrange [0:*]; set ylabel "Gross Revenue (in USD)";' . ' set xlabel "' . $chart_first_from . ' - ' . $chart_last_to . '";' . ' plot "' . str_replace('"', '', $chart_data_file) . '" using 2:xtic(1) notitle with histograms'; exec(implode(' ', array_map('escapeshellarg', $chart_gnuplot)), $chart, $chart_status); if ($chart_status === 0) { $statistics .= implode("\n", $chart); // Append chart. } return $statistics; }
function print_cli($text, $colour = TRUE) { //include_once("Console/Color2.php"); $msg = new Console_Color2(); print $msg->convert($text, $colour); }