Passed
Push — master ( 38a638...9c837b )
by Tony
08:34
created

includes/billing.php (3 issues)

1
<?php
2
3
4
function format_bytes_billing($value)
5
{
6
    global $config;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
7
8
    return format_number($value, $config['billing']['base']).'B';
9
}//end format_bytes_billing()
10
11
12
function format_bytes_billing_short($value)
13
{
14
    global $config;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
15
16
    return format_number($value, $config['billing']['base'], 2, 3);
17
}//end format_bytes_billing_short()
18
19
20
function getDates($dayofmonth, $months = 0)
21
{
22
    $dayofmonth = zeropad($dayofmonth);
23
    $year       = date('Y');
24
    $month      = date('m');
25
26
    if (date('d') > $dayofmonth) {
27
        // Billing day is past, so it is next month
28
        $date_end   = date_create($year.'-'.$month.'-'.$dayofmonth);
29
        $date_start = date_create($year.'-'.$month.'-'.$dayofmonth);
30
        date_add($date_end, date_interval_create_from_date_string('1 month'));
31
    } else {
32
        // Billing day will happen this month, therefore started last month
33
        $date_end   = date_create($year.'-'.$month.'-'.$dayofmonth);
34
        $date_start = date_create($year.'-'.$month.'-'.$dayofmonth);
35
        date_sub($date_start, date_interval_create_from_date_string('1 month'));
36
    }
37
38
    if ($months > 0) {
39
        date_sub($date_start, date_interval_create_from_date_string($months.' month'));
40
        date_sub($date_end, date_interval_create_from_date_string($months.' month'));
41
    }
42
43
    // date_sub($date_start, date_interval_create_from_date_string('1 month'));
44
    date_sub($date_end, date_interval_create_from_date_string('1 day'));
45
46
    $date_from = date_format($date_start, 'Ymd').'000000';
47
    $date_to   = date_format($date_end, 'Ymd').'235959';
48
49
    date_sub($date_start, date_interval_create_from_date_string('1 month'));
50
    date_sub($date_end, date_interval_create_from_date_string('1 month'));
51
52
    $last_from = date_format($date_start, 'Ymd').'000000';
53
    $last_to   = date_format($date_end, 'Ymd').'235959';
54
55
    $return      = array();
56
    $return['0'] = $date_from;
57
    $return['1'] = $date_to;
58
    $return['2'] = $last_from;
59
    $return['3'] = $last_to;
60
61
    return ($return);
62
}//end getDates()
63
64
function getPredictedUsage($bill_day, $cur_used)
65
{
66
67
    $tmp = getDates($bill_day, 0);
68
    $start = new DateTime($tmp[0], new DateTimeZone(date_default_timezone_get()));
69
    $end   = new DateTime($tmp[1], new DateTimeZone(date_default_timezone_get()));
70
    $now   = new DateTime(date("Y-m-d"), new DateTimeZone(date_default_timezone_get()));
71
    $total = $end->diff($start)->format("%a");
72
    $since = $now->diff($start)->format("%a");
73
    return($cur_used/$since*$total);
74
}
75
76
function getValue($host, $port, $id, $inout)
77
{
78
    global $config;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
79
80
    $oid    = 'IF-MIB::ifHC'.$inout.'Octets.'.$id;
81
    $device = dbFetchRow("SELECT * from `devices` WHERE `hostname` = '".mres($host)."' LIMIT 1");
82
    $value  = snmp_get($device, $oid, '-Oqv');
83
84
    if (!is_numeric($value)) {
85
        $oid   = 'IF-MIB::if'.$inout.'Octets.'.$id;
86
        $value = snmp_get($device, $oid, '-Oqv');
87
    }
88
89
    return $value;
90
}//end getValue()
91
92
function getLastPortCounter($port_id, $bill_id)
93
{
94
    $return = array();
95
    $row    = dbFetchRow("SELECT timestamp, in_counter, in_delta, out_counter, out_delta FROM bill_port_counters WHERE `port_id` = ? AND `bill_id` = ?", array($port_id, $bill_id));
96
    if (!is_null($row)) {
97
        $return['timestamp']   = $row['timestamp'];
98
        $return['in_counter']  = $row['in_counter'];
99
        $return['in_delta']    = $row['in_delta'];
100
        $return['out_counter'] = $row['out_counter'];
101
        $return['out_delta']   = $row['out_delta'];
102
        $return['state']       = 'ok';
103
    } else {
104
        $return['state']       = 'failed';
105
    }
106
    return $return;
107
}//end getLastPortCounter()
108
109
110
function getLastMeasurement($bill_id)
111
{
112
    $return = array();
113
    $row    = dbFetchRow("SELECT timestamp,delta,in_delta,out_delta FROM bill_data WHERE bill_id = ? ORDER BY timestamp DESC LIMIT 1", array($bill_id));
114
    if (!is_null($row)) {
115
        $return['delta']     = $row['delta'];
116
        $return['delta_in']  = $row['delta_in'];
117
        $return['delta_out'] = $row['delta_out'];
118
        $return['timestamp'] = $row['timestamp'];
119
        $return['state']     = 'ok';
120
    } else {
121
        $return['state'] = 'failed';
122
    }
123
    return ($return);
124
}//end getLastMeasurement()
125
126
127
function get95thin($bill_id, $datefrom, $dateto)
128
{
129
    $mq_sql           = "SELECT count(delta) FROM bill_data WHERE bill_id = '".mres($bill_id)."'";
130
    $mq_sql          .= " AND timestamp > '".mres($datefrom)."' AND timestamp <= '".mres($dateto)."'";
131
    $measurements     = dbFetchCell($mq_sql);
132
    $measurement_95th = (round(($measurements / 100 * 95)) - 1);
133
134
    $q_95_sql  = "SELECT (in_delta / period * 8) AS rate FROM bill_data  WHERE bill_id = '".mres($bill_id)."'";
135
    $q_95_sql .= " AND timestamp > '".mres($datefrom)."' AND timestamp <= '".mres($dateto)."' ORDER BY rate ASC";
136
    $a_95th    = dbFetchColumn($q_95_sql);
137
    $m_95th    = $a_95th[$measurement_95th];
138
139
    return (round($m_95th, 2));
140
}//end get95thin()
141
142
143
function get95thout($bill_id, $datefrom, $dateto)
144
{
145
    $mq_sql           = "SELECT count(delta) FROM bill_data WHERE bill_id = '".mres($bill_id)."'";
146
    $mq_sql          .= " AND timestamp > '".mres($datefrom)."' AND timestamp <= '".mres($dateto)."'";
147
    $measurements     = dbFetchCell($mq_sql);
148
    $measurement_95th = (round(($measurements / 100 * 95)) - 1);
149
150
    $q_95_sql  = "SELECT (out_delta / period * 8) AS rate FROM bill_data  WHERE bill_id = '".mres($bill_id)."'";
151
    $q_95_sql .= " AND timestamp > '".mres($datefrom)."' AND timestamp <= '".mres($dateto)."' ORDER BY rate ASC";
152
153
    $a_95th = dbFetchColumn($q_95_sql);
154
    $m_95th = $a_95th[$measurement_95th];
155
156
    return (round($m_95th, 2));
157
}//end get95thout()
158
159
160
function getRates($bill_id, $datefrom, $dateto)
161
{
162
    $data = [];
163
164
    $sum_data = getSum($bill_id, $datefrom, $dateto);
165
    $mtot     = $sum_data['total'];
166
    $mtot_in  = $sum_data['inbound'];
167
    $mtot_out = $sum_data['outbound'];
168
    $ptot     = $sum_data['period'];
169
170
    $data['rate_95th_in']  = get95thIn($bill_id, $datefrom, $dateto);
171
    $data['rate_95th_out'] = get95thOut($bill_id, $datefrom, $dateto);
172
173
    if ($data['rate_95th_out'] > $data['rate_95th_in']) {
174
        $data['rate_95th'] = $data['rate_95th_out'];
175
        $data['dir_95th']  = 'out';
176
    } else {
177
        $data['rate_95th'] = $data['rate_95th_in'];
178
        $data['dir_95th']  = 'in';
179
    }
180
181
    $data['total_data']     = $mtot;
182
    $data['total_data_in']  = $mtot_in;
183
    $data['total_data_out'] = $mtot_out;
184
    $data['rate_average']   = ($mtot / $ptot * 8);
185
    $data['rate_average_in']   = ($mtot_in / $ptot * 8);
186
    $data['rate_average_out']  = ($mtot_out / $ptot * 8);
187
188
    // print_r($data);
189
    return ($data);
190
}//end getRates()
191
192
193
function getTotal($bill_id, $datefrom, $dateto)
194
{
195
    $mtot = dbFetchCell("SELECT SUM(delta) FROM bill_data WHERE bill_id = '".mres($bill_id)."' AND timestamp > '".mres($datefrom)."' AND timestamp <= '".mres($dateto)."'");
196
    return ($mtot);
197
}//end getTotal()
198
199
200
function getSum($bill_id, $datefrom, $dateto)
201
{
202
    $sum = dbFetchRow("SELECT SUM(period) as period, SUM(delta) as total, SUM(in_delta) as inbound, SUM(out_delta) as outbound FROM bill_data WHERE bill_id = '".mres($bill_id)."' AND timestamp > '".mres($datefrom)."' AND timestamp <= '".mres($dateto)."'");
203
    return ($sum);
204
}//end getSum()
205
206
207
function getPeriod($bill_id, $datefrom, $dateto)
208
{
209
    $ptot = dbFetchCell("SELECT SUM(period) FROM bill_data WHERE bill_id = '".mres($bill_id)."' AND timestamp > '".mres($datefrom)."' AND timestamp <= '".mres($dateto)."'");
210
    return ($ptot);
211
}//end getPeriod()
212
213
function getBillingHistoryBitsGraphData($bill_id, $bill_hist_id, $reducefactor)
214
{
215
    $histrow = dbFetchRow('SELECT UNIX_TIMESTAMP(bill_datefrom) as `from`, UNIX_TIMESTAMP(bill_dateto) AS `to`, rate_95th, rate_average, bill_type FROM bill_history WHERE bill_id = ? AND bill_hist_id = ?', array($bill_id, $bill_hist_id));
216
217
    if (is_null($histrow)) {
218
        return null;
219
    }
220
221
    $graph_data = getBillingBitsGraphData($bill_id, $histrow['from'], $histrow['to'], $reducefactor);
222
223
    // Overwrite the rate data with the historical version
224
    $graph_data['rate_95th']    = $histrow['rate_95th'];
225
    $graph_data['rate_average'] = $histrow['rate_average'];
226
    $graph_data['bill_type']    = $histrow['bill_type'];
227
228
    return $graph_data;
229
}
230
231
function getBillingBitsGraphData($bill_id, $from, $to, $reducefactor)
232
{
233
    $i          = '0';
234
    $iter       = 0;
235
    $first      = null;
236
    $last       = null;
237
    $iter_in    = 0;
238
    $iter_out   = 0;
239
    $iter_period = 0;
240
    $max_in     = 0;
241
    $max_out    = 0;
242
    $tot_in     = 0;
243
    $tot_out    = 0;
244
    $tot_period = 0;
245
    $in_delta   = null;
246
    $out_delta  = null;
247
    $period     = null;
248
    $in_data    = array();
249
    $out_data   = array();
250
    $tot_data   = array();
251
    $ticks      = array();
252
253
    if (!isset($reducefactor) || !is_numeric($reducefactor) || $reducefactor < 1) {
254
        // Auto calculate reduce factor
255
        $expectedpoints = ceil(($to - $from) / 300);
256
        $desiredpoints = 400;
257
        $reducefactor = max(1, floor($expectedpoints / $desiredpoints));
258
    }
259
260
    $bill_data    = dbFetchRow('SELECT * from `bills` WHERE `bill_id`= ? LIMIT 1', array($bill_id));
261
262
    foreach (dbFetch('SELECT *, UNIX_TIMESTAMP(timestamp) AS formatted_date FROM bill_data WHERE bill_id = ? AND `timestamp` >= FROM_UNIXTIME( ? ) AND `timestamp` <= FROM_UNIXTIME( ? ) ORDER BY timestamp ASC', array($bill_id, $from, $to)) as $row) {
263
        $timestamp = $row['formatted_date'];
264
        if (!$first) {
265
            $first = $timestamp;
266
        }
267
268
        $period    = $row['period'];
269
        $in_delta  = $row['in_delta'] * 8;
270
        $out_delta = $row['out_delta'] * 8;
271
        $last      = $timestamp;
272
273
        $iter_in     += $in_delta;
274
        $iter_out    += $out_delta;
275
        $iter_period += $period;
276
277
        if ($period > 0) {
278
            $max_in    = max($max_in, $in_delta / $period);
279
            $max_out   = max($max_out, $out_delta / $period);
280
            $tot_in    += $in_delta;
281
            $tot_out   += $out_delta;
282
            $tot_period+= $period;
283
284
            if (++$iter >= $reducefactor) {
285
                $out_data[$i] = round(($iter_out / $iter_period), 2);
286
                $in_data[$i]  = round(($iter_in / $iter_period), 2);
287
                $tot_data[$i] = ($out_data[$i] + $in_data[$i]);
288
                $ticks[$i]    = $timestamp;
289
                $i++;
290
                $iter         = 0;
291
                unset($iter_out, $iter_in, $iter_period);
292
            }
293
        }
294
    }//end foreach
295
296
    if (!empty($iter_in)) {  // Write last element
297
        $out_data[$i] = round(($iter_out / $iter_period), 2);
298
        $in_data[$i]  = round(($iter_in / $iter_period), 2);
299
        $tot_data[$i] = ($out_data[$i] + $in_data[$i]);
300
        $ticks[$i]    = $timestamp;
301
        $i++;
302
    }
303
    $result = array(
304
        'from'          => $from,
305
        'to'            => $to,
306
        'first'         => $first,
307
        'last'          => $last,
308
309
        'in_data'       => $in_data,
310
        'out_data'      => $out_data,
311
        'tot_data'      => $tot_data,
312
        'ticks'         => $ticks,
313
314
        'rate_95th'     => $bill_data['rate_95th'],
315
        'rate_average'  => $bill_data['rate_average'],
316
        'bill_type'     => $bill_data['bill_type']
317
    );
318
319
    if ($period) {
320
        $result['max_in']   = $max_in;
321
        $result['max_out']  = $max_out;
322
        $result['ave_in']   = $tot_in / $tot_period;
323
        $result['ave_out']  = $tot_out / $tot_period;
324
        $result['last_in']  = $in_delta / $period;
325
        $result['last_out'] = $out_delta / $period;
326
    }
327
    return $result;
328
}//end getBillingBitsGraphData
329
330
function getHistoricTransferGraphData($bill_id)
331
{
332
    $i = '0';
333
334
    $in_data      = array();
335
    $out_data     = array();
336
    $tot_data     = array();
337
    $allow_data   = array();
338
    $ave_data     = array();
339
    $overuse_data = array();
340
    $ticklabels   = array();
341
    $allowed_val  = null;
342
343
    foreach (dbFetchRows('SELECT * FROM `bill_history` WHERE `bill_id` = ? ORDER BY `bill_datefrom` DESC LIMIT 12', array($bill_id)) as $data) {
344
        $datefrom          = strftime('%Y-%m-%d', strtotime($data['bill_datefrom']));
345
        $dateto        = strftime('%Y-%m-%d', strtotime($data['bill_dateto']));
346
        $datelabel     = $datefrom." - ".$dateto;
347
348
        array_push($ticklabels, $datelabel);
349
        array_push($in_data, $data['traf_in']);
350
        array_push($out_data, $data['traf_out']);
351
        array_push($tot_data, $data['traf_total']);
352
        array_push($allow_data, $allowed_val = ($data['bill_type'] == 'Quota' ? $data['bill_allowed'] : 0));
353
        array_push($overuse_data, $data['bill_type'] == 'Quota' ? $data['bill_overuse'] : 0);
354
        $i++;
355
    }//end foreach
356
357
    if ($i < 12) {
358
        $y = (12 - $i);
359
        for ($x = 0; $x < $y; $x++) {
360
            $allowed = (($x == '0') ? $allowed_val : '0' );
361
            array_push($in_data, '0');
362
            array_push($out_data, '0');
363
            array_push($tot_data, '0');
364
            array_push($allow_data, $allowed);
365
            array_push($overuse_data, '0');
366
            array_push($ticklabels, '');
367
        }
368
    }
369
370
    $graph_name = 'Historical bandwidth over the last 12 billing periods';
371
372
    return array(
373
        'graph_name'        => $graph_name,
374
        'in_data'           => $in_data,
375
        'out_data'          => $out_data,
376
        'tot_data'          => $tot_data,
377
        'allow_data'        => $allow_data,
378
        'ave_data'          => $ave_data,
379
        'overuse_data'      => $overuse_data,
380
        'ticklabels'        => $ticklabels
381
    );
382
}
383
384
function getBillingBandwidthGraphData($bill_id, $bill_hist_id, $from, $to, $imgtype)
385
{
386
    if (is_numeric($bill_hist_id)) {
387
        $histrow = dbFetchRow('SELECT UNIX_TIMESTAMP(bill_datefrom) as `from`, UNIX_TIMESTAMP(bill_dateto) AS `to`, rate_95th, rate_average FROM bill_history WHERE bill_id = ? AND bill_hist_id = ?', array($bill_id, $bill_hist_id));
388
389
        if (is_null($histrow)) {
390
            return null;
391
        }
392
        $from  = $histrow['from'];
393
        $to    = $histrow['to'];
394
    } else {
395
        if (!is_numeric($from) || !is_numeric($to)) {
396
            die('Must supply from and to if bill_hist_id is not supplied');
397
        }
398
    }
399
400
    $in_data      = array();
401
    $out_data     = array();
402
    $tot_data     = array();
403
    $allow_data   = array();
404
    $ave_data     = array();
405
    $overuse_data = array();
406
    $ticklabels   = array();
407
408
    $data    = array();
409
    $average = 0;
410
    if ($imgtype == 'day') {
411
        foreach (dbFetch('SELECT DISTINCT UNIX_TIMESTAMP(timestamp) as timestamp, SUM(delta) as traf_total, SUM(in_delta) as traf_in, SUM(out_delta) as traf_out FROM bill_data WHERE `bill_id` = ? AND `timestamp` >= FROM_UNIXTIME(?) AND `timestamp` <= FROM_UNIXTIME(?) GROUP BY DATE(timestamp) ORDER BY timestamp ASC', array($bill_id, $from, $to)) as $data) {
412
            array_push($ticklabels, strftime("%Y-%m-%d", $data['timestamp']));
413
            array_push($in_data, isset($data['traf_in']) ? $data['traf_in'] : 0);
414
            array_push($out_data, isset($data['traf_out']) ? $data['traf_out'] : 0);
415
            array_push($tot_data, isset($data['traf_total']) ? $data['traf_total'] : 0);
416
            $average += $data['traf_total'];
417
        }
418
419
        $ave_count = count($tot_data);
420
421
        // Add empty items for the days not yet passed
422
        $days = (strftime('%e', date($to - $from)) - $ave_count - 1);
423
        for ($x = 0; $x < $days; $x++) {
424
            array_push($ticklabels, '');
425
            array_push($in_data, 0);
426
            array_push($out_data, 0);
427
            array_push($tot_data, 0);
428
        }
429
    } elseif ($imgtype == 'hour') {
430
        foreach (dbFetch('SELECT DISTINCT HOUR(timestamp) as hour, SUM(delta) as traf_total, SUM(in_delta) as traf_in, SUM(out_delta) as traf_out FROM bill_data WHERE `bill_id` = ? AND `timestamp` >= FROM_UNIXTIME(?) AND `timestamp` <= FROM_UNIXTIME(?) GROUP BY HOUR(timestamp) ORDER BY HOUR(timestamp) ASC', array($bill_id, $from, $to)) as $data) {
431
            array_push($ticklabels, sprintf('%02d', $data['hour']) . ":00");
432
            array_push($in_data, isset($data['traf_in']) ? $data['traf_in'] : 0);
433
            array_push($out_data, isset($data['traf_out']) ? $data['traf_out'] : 0);
434
            array_push($tot_data, isset($data['traf_total']) ? $data['traf_total'] : 0);
435
            $average += $data['traf_total'];
436
        }
437
438
        $ave_count = count($tot_data);
439
    } else {
440
        die("Unknown graph type $imgtype");
441
    }//end if
442
443
    $average = ($average / $ave_count);
444
    $tot_data_size = count($tot_data);
445
    for ($x = 0; $x <= $tot_data_size; $x++) {
446
        array_push($ave_data, $average);
447
    }
448
449
    $graph_name = date('M j g:ia', $from).' - '.date('M j g:ia', $to);
450
451
    return array(
452
        'graph_name'        => $graph_name,
453
        'in_data'           => $in_data,
454
        'out_data'          => $out_data,
455
        'tot_data'          => $tot_data,
456
        'allow_data'        => $allow_data,
457
        'ave_data'          => $ave_data,
458
        'overuse_data'      => $overuse_data,
459
        'ticklabels'        => $ticklabels
460
    );
461
}
462
//end getBillingBandwidthGraphData
463