Merge branch 'maint/7.0'
[ninja.git] / modules / reports / helpers / reports.php
blob9dfe1e6a144bebeb86c06c1621e495725f48a842
1 <?php defined('SYSPATH') OR die('No direct access allowed.');
2 /**
3 * Help class for reports
4 */
5 class reports
7 /** Colors for status in trends graph and such */
8 public static $colors = array(
9 'green' => '#aade53',
10 'yellow' => '#ffd92f',
11 'orange' => '#ff9d08',
12 'red' => '#f7261b',
13 'grey' => '#a19e95',
14 'lightblue' => '#EAF0F2', # actual color is #ddeceb, but it is hardly visible
15 'white' => '#ffffff',
16 'transparent' => 'transparent'
19 /** Array of month_number => days_in_month */
20 public static $days_per_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
21 /** Array of weekday names */
22 public static $valid_weekdays = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
23 /** Array of month names */
24 public static $valid_months = array
26 1 => 'january',
27 2 => 'february',
28 3 => 'march',
29 4 => 'april',
30 5 => 'may',
31 6 => 'june',
32 7 => 'july',
33 8 => 'august',
34 9 => 'september',
35 10 => 'october',
36 11 => 'november',
37 12 => 'december'
40 /**
41 * Called by PHP as an assert callback to format errors usefully
43 public function lib_reports_assert_handler($filename, $line, $code)
45 if (!posix_isatty(0))
46 echo "<pre>\n";
48 echo "ASSERT FAILED\n";
49 debug_print_backtrace();
51 echo "File: $filename\n\n";
52 echo "Line: $line\n";
53 echo "Assertion: $code\n";
55 if (!posix_isatty(0))
56 echo "</pre>\n";
59 /**
60 * Generate a percentage easily
62 * @param $dividend The whole
63 * @param $divisor The part
64 * @return The percentage
66 static function percent($dividend, $divisor)
68 if (!$dividend || !$divisor)
69 return 0;
71 return ($dividend / $divisor) * 100;
74 /**
75 * Assigns color to labels to be used in a piechart
77 static function get_color_values($labels=false)
79 if (empty($labels)) return false;
80 $green = '#88cd18';
81 $yellow = '#ffd92f';
82 $orange = '#ff9d08';
83 $red = '#f7261b';
84 $grey = '#a0a084';
86 $return = array();
87 $colors = array(
88 'OK' => $green,
89 'UP' => $green,
90 'WARNING' => $yellow,
91 'UNREACHABLE' => $orange,
92 'UNKNOWN' => $orange,
93 'DOWN' => $red,
94 'CRITICAL' => $red,
95 'UNDETERMINED' => $grey,
96 'EXCLUDE' => null
98 foreach ($labels as $key) {
99 $return[] = array($colors[strtoupper($key)], NULL, NULL);
101 return $return;
105 * Format report value output
107 static function format_report_value($val)
109 $return = 0;
110 if ($val == '0.000' || $val == '100.000')
111 $return = number_format($val, 0);
112 else
113 $return = number_format(str_replace(',', '.', $val), 3);
115 return $return;
119 * Create common translated javascript strings
121 public static function js_strings()
123 $js_strings = "var _ok_str = '"._('OK')."';\n";
124 $js_strings .= "var _cancel_str = '"._('Cancel')."';\n";
125 $js_strings .= "var _reports_err_str_noobjects = '".sprintf(_("Please select what objects to base the report on by moving %sobjects from the left selectbox to the right selectbox"), '<br />')."';\n";
126 $js_strings .= "var _reports_err_str_nostatus = '"._("You must provide at least one status to filter on")."';\n";
127 $js_strings .= "var _reports_invalid_startdate = \""._("You haven't entered a valid Start date")."\";\n";
128 $js_strings .= "var _reports_invalid_enddate = \""._("You haven't entered a valid End date")."\";\n";
129 $js_strings .= "var _reports_invalid_timevalue = \""._("You haven't entered a valid time value")."\";\n";
130 $js_strings .= "var _reports_enddate_infuture = '".sprintf(_("You have entered an End date in the future.%sClick OK to change this to current time or cancel to modify."), '\n')."';\n";
131 $js_strings .= "var _reports_enddate_lessthan_startdate = '"._("You have entered an End date before Start Date.")."';\n";
132 $js_strings .= "var _reports_send_now = '"._('Send this report now')."';\n";
133 $js_strings .= "var _reports_send = '"._('Send')."';\n";
134 $js_strings .= "var _reports_invalid_email = '"._('You have entered an invalid email address')."';\n";
135 $js_strings .= "var _label_direct_link = '"._('Direct link')."';\n";
136 $js_strings .= "var _reports_confirm_delete = '"._("Are you really sure that you would like to remove this saved report?")."';\n";
137 $js_strings .= "var _reports_confirm_delete_warning = '"._("Please note that this is a scheduled report and if you decide to delete it, \\n" .
138 "the corresponding schedule(s) will be deleted as well.\\n\\n Are you really sure that this is what you want?")."';\n";
140 $js_strings .= "Date.monthNames = ".json_encode(date::month_names()).";\n";
141 $js_strings .= 'Date.abbrMonthNames = '.json_encode(date::abbr_month_names()).";\n";
142 $js_strings .= 'Date.dayNames = '.json_encode(date::day_names()).";\n";
143 $js_strings .= 'Date.abbrDayNames = '.json_encode(date::abbr_day_names()).";\n";
144 $js_strings .= "Date.firstDayOfWeek = 1;\n";
145 $js_strings .= "Date.format = '".cal::get_calendar_format(false)."';\n";
146 $js_strings .= "var _start_date = '".date(cal::get_calendar_format(true), mktime(0,0,0,1, 1, 1996))."';\n";
147 $js_strings .= "var _reports_success = '"._('Success')."';\n";
148 $js_strings .= "var _reports_error = '"._('Error')."';\n";
149 $js_strings .= "var _reports_missing_objects = \""._("Some items in your saved report do not exist anymore and have been removed")."\";\n";
150 $js_strings .= "var _reports_missing_objects_pleaseremove = '"._('Please modify the objects to include in your report below and then save it.')."';\n";
152 return $js_strings;
156 * Return a text string representing the included host or service states
158 public static function get_included_states($report_type, $options)
160 switch ($report_type) {
161 case 'hosts':
162 case 'hostgroups':
163 $subtype = 'host';
164 break;
165 case 'services':
166 case 'servicegroups':
167 $subtype = 'service';
168 break;
169 default:
170 return _("Unknown states included: '$report_type' is not a recognized object type");
173 $res = $subtype === 'host' ? _('Showing hosts in state: ') : _('Showing services in state: ');
175 $j = 0;
176 foreach(Reports_Model::${$subtype.'_states'} as $key => $value) {
177 if ($value === 'excluded')
178 continue;
179 if (!isset($options[$subtype.'_filter_status'][$key])) {
180 $res .= ($j > 0) ? ', ' : '';
181 $res .= '<strong>'.$value.'</strong>';
182 $j++;
185 return $res;
189 * Determine what color to assign to an event
191 static function _state_colors($type='host', $state=false)
193 $colors = self::_state_color_table($type);
194 return $colors[$state];
198 * @param $type string = 'host'
199 * @return array
201 static function _state_color_table($type='host') {
202 $colors = array(
203 'host' => array(
204 Reports_Model::HOST_UP => self::$colors['green'],
205 Reports_Model::HOST_DOWN => self::$colors['red'],
206 Reports_Model::HOST_UNREACHABLE => self::$colors['orange'],
207 Reports_Model::HOST_PENDING => self::$colors['grey'],
208 Reports_Model::HOST_EXCLUDED => self::$colors['transparent']
210 'service' => array(
211 Reports_Model::SERVICE_OK => self::$colors['green'],
212 Reports_Model::SERVICE_WARNING => self::$colors['yellow'],
213 Reports_Model::SERVICE_CRITICAL => self::$colors['red'],
214 Reports_Model::SERVICE_UNKNOWN => self::$colors['orange'],
215 Reports_Model::SERVICE_PENDING => self::$colors['grey'],
216 Reports_Model::SERVICE_EXCLUDED => self::$colors['transparent']
219 return $colors[$type];
223 * Given bunch of somewhat-magical parameters, return a whole multi-object report table
225 static function format_multi_object_table($data, $title, $rowdescriber, $columns, $is_summary, $down_as_up_diff, &$i=0)
227 $coldefs = array(
228 'ok' => array('PERCENT_KNOWN_TIME_OK', _('Ok')),
229 'unknown' => array('PERCENT_KNOWN_TIME_UNKNOWN', _('Unknown')),
230 'warning' => array('PERCENT_KNOWN_TIME_WARNING', _('Warning')),
231 'critical' => array('PERCENT_KNOWN_TIME_CRITICAL', _('Critical')),
232 'up' => array('PERCENT_KNOWN_TIME_UP', _('Up')),
233 'unreachable' => array('PERCENT_KNOWN_TIME_UNREACHABLE', _('Unreachable')),
234 'down' => array('PERCENT_KNOWN_TIME_DOWN', _('Down')),
235 'pending' => array('PERCENT_TOTAL_TIME_UNDETERMINED', _('Undetermined')),
237 $res = '<div class="report-block">
238 <table class="multiple_services">
239 <tr>
240 <th>'.$title.'</th>';
241 foreach ($columns as $col)
242 $res .= '<th class="headerNone" style="width: 80px">' . $coldefs[$col][1] .'</th>';
243 $res .='</tr>';
245 foreach ($data as $k => $row) {
246 if (!is_array($row) || !isset($row['states']))
247 continue;
248 $res .= '<tr class="'.($i++%2?'even':'odd').'">'.$rowdescriber($row);
249 foreach ($columns as $col) {
250 $res .= '<td style="width: 80px" class="summary '.($is_summary?'tally ':'').$col.' '.($row['states'][$coldefs[$col][0]]>0?'nonzero':'') .'">'.reports::format_report_value($row['states'][$coldefs[$col][0]]).' % '. html::image(ninja::add_path('icons/12x12/shield-'.($row['states'][$coldefs[$col][0]] > 0 ? '' : 'not-').$col.'.png'), array( 'alt' => $coldefs[$col][1], 'title' => $coldefs[$col][1], 'style' => 'height: 12px; width: 12px'));
251 if (($col == 'ok' || $col == 'up') && $down_as_up_diff && $row['states']['PERCENT_TIME_DOWN_COUNTED_AS_UP']) {
252 $res .= ' ('.reports::format_report_value($row['states']['PERCENT_TIME_DOWN_COUNTED_AS_UP']).' % in other states)';
254 $res .= '</td>';
256 $res .= '</tr>';
258 $res .= '</table></div>';
259 return $res;
263 * Returns the alias for the specified object of the specified type, or false
264 * Liberated from the report controller
266 static function get_alias($type, $name)
268 if (empty($type) || empty($name))
269 return false;
271 $filter = array('name' => $name);
272 $res = Livestatus::instance()->{'get'.ucfirst($type)}(array('columns' => array('alias'), 'filter' => array('name' => $name)));
273 if (!$res)
274 return false;
275 return $res[0]['alias'];