Code: Alles auswählen
<?php
//v0.6
//------------------ CONFIG - START -------------------------
$DBfile = "/tmp/osstats.db";
$SRVID = "/var/etc/oscam.srvid";
$DRAWpie = 1;
//------------------ CONFIG - END ---------------------------
require('phplot.php');
error_reporting(E_ALL);
ini_set('track_errors',1);
ini_set("max_execution_time", "240");
ob_implicit_flush(true);
@ob_end_flush();
//-----------------------------------------------------------
?>
<!DOCTYPE html>
<html>
<head>
<title>OSCAM Channel Charts</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style>
table { margin: 0px; padding: 3px; border: 0px; }
th { font-family: tahoma; font-size: 11px; margin: 0px; padding: 3px; border: 0px; }
tr { margin: 0px; padding: 3px; border: 0px; }
td { font-family: tahoma; font-size: 11px; margin: 0px; padding: 3px; border: 0px; }
</style>
</head>
<?php
if (!file_exists("$DBfile")) {
$e="font-size:23px; text-align:left; color:firebrick; font-weight:bold;";
echo "<b style='".$e."'>Error: DBfile $DBfile doesnt exists! Aborting..</b><br/>\n";
exit();
}
$c=0;
$unknownchan=0;
$DURATION_start = startTime();
$db = db_con();
// collect users
$query = $db->query("SELECT user FROM osstats WHERE 1 GROUP BY user ORDER BY user ASC");
while ($result = $query->fetch(PDO::FETCH_ASSOC)) {
$user = $result["user"];
$TOTALstats["$user"] = 0;
// collect stats for each user
echo "<b>".$user."</b><br/>\n";
echo "<table border='1'>\n";
echo "<tr>";
echo "<th>CAID</th> <th>IDENT</th> <th>SID</th> <th>Count</th>";
if (file_exists("$SRVID")) { echo " <th>Channel</th>"; }
echo " <th>Time Range</th>";
echo "</tr>\n";
$query2 = $db->query("SELECT startdate,enddate,caid,ident,sid,count FROM osstats WHERE user = '".$user."' ORDER BY enddate DESC");
$cc=2;
while ($result2 = $query2->fetch(PDO::FETCH_ASSOC)) {
$bgc='';
if ($cc == 2) { $bgc = 'background-color:#dcdcdc;'; $cc=0; }
echo "<tr>\n";
echo "<td style='".$bgc."'>".$result2['caid']."</td>";
echo "<td style='".$bgc."'>".$result2['ident']."</td>";
echo "<td style='".$bgc."'>".$result2['sid']."</td>";
echo "<td style='".$bgc."' align='center'>".$result2['count']."</td>";
if (file_exists("$SRVID")) {
$ChanName = get_channelname($result2['caid'],$result2['sid']);
if (empty($ChanName)) {
$unknownchan++;
$ChanName = "<unknown".$unknownchan.">";
}
echo "<td style='".$bgc."'>".$ChanName."</td>";
#$ChannelNames["$CAID"]["$IDENT"]["$SID"] = $ChanName;
}
$StartDate = date("Y/m/d H:i:s",$result2['startdate']);
$EndDate = date("Y/m/d H:i:s",$result2['enddate']);
echo "<td style='".$bgc."' align='center'>".$StartDate." -> ".$EndDate."</td>";
echo "</tr>\n";
$c++;
$cc++;
$STATS["$user"]["$ChanName"] = $result2["count"];
$TOTALstats["$user"] += $result2["count"];
}
echo "</table><br/>\n";
$c++;
if (isset($DRAWpie) AND $DRAWpie == 1) {
// For each User -> Channel Chart
$output_file = "chanscharts_".$user.".png";
$data = array();
foreach ($STATS["$user"] AS $Channel => $COUNT) {
array_push($data,array("$Channel",$COUNT));
}
$plot = new PHPlot(1200,1200);
$plot->SetImageBorderType('plain');
$plot->SetPlotType('pie');
$plot->SetDataType('text-data-single');
$plot->SetDataValues($data);
#$plot->SetTitle("OScam - Users");
foreach ($data AS $row) {
$plot->SetLegend(implode(': ', $row));
}
# Place the legend in the upper left corner:
#$plot->SetLegendPixels(1, 1);
#$plot->SetPieLabelType('value', 'data', 0);
#$plot->SetPieLabelType(array('percent', 'label'), 'custom', 'labelcallback');
$plot->SetOutputFile($output_file);
$plot->DrawGraph();
echo "<br/><img src=\"".$output_file."\"><br/>\n";
}
}
echo "<br/>generating took ".endTime($DURATION_start)." seconds (for ".$c." entries)<br/>\n";
// Draw PIE
if (isset($DRAWpie) AND $DRAWpie == 1) {
// User Channel Chart
$output_file = "charts_users.png";
$data = array();
foreach ($TOTALstats AS $U => $COUNT) {
array_push($data,array("$U",$COUNT));
}
$plot = new PHPlot(600,400);
$plot->SetImageBorderType('plain');
$plot->SetPlotType('pie');
$plot->SetDataType('text-data-single');
$plot->SetDataValues($data);
$plot->SetTitle("OScam - Users");
foreach ($data AS $row) {
$plot->SetLegend(implode(': ', $row));
}
# Place the legend in the upper left corner:
#$plot->SetLegendPixels(5, 5);
#$plot->SetPieLabelType('value', 'data', 0);
#$plot->SetPieLabelType(array('percent', 'label'), 'custom', 'labelcallback');
$plot->SetOutputFile($output_file);
$plot->DrawGraph();
echo "<br/><img src=\"".$output_file."\"><br/>\n";
}
//______________________________________________________________________________________
function labelcallback($str) {
list($percent, $label) = explode(' ', $str, 2);
return sprintf('%s (%.1f%%)', $label, $percent);
}
function get_channelname($CAID,$SID) {
global $SRVID;
$RE = "";
$content = file("$SRVID");
for($i=0; $i<count($content); $i++) {
$line = $content[$i];
if (empty($line)) { continue; }
if (preg_match("/.*$CAID.*\:$SID.+/i",$line)) {
$tmp = explode("|",$line);
$RE = "".$tmp[1]." - ".$tmp[2]."";
break;
}
}
return $RE;
}
function db_con() {
global $DBfile;
if (!$db = new PDO("sqlite:$DBfile")) {
$e="font-size:23px; text-align:left; color:firebrick; font-weight:bold;";
echo "<b style='".$e."'>Fehler beim öffnen der Datenbank:</b><br/>";
echo "<b style='".$e."'>".$db->errorInfo()."</b><br/>";
die;
}
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
function db_query($sql) {
global $db;
if (!isset($db) OR empty($db)) { $db = db_con(); }
$result = $db->query($sql) OR db_error($sql);
return $result;
}
function db_error($sql) {
global $db;
$error = $db->errorInfo();
die('<small><font color="#ff0000"><b>[DB ERROR]</b></font></small><br/><br/><font color="#800000"><b>'.$error.'</b><br/><br/>'.$sql.'</font>');
}
//Add HTML character incoding to strings
function db_output($string) {
return htmlspecialchars_decode($string);
}
//Add slashes to incoming data
function db_input($string) {
return htmlspecialchars($string);
}
function startTime() {
$timeExplode = explode(" ", microtime());
$time = $timeExplode[1] + $timeExplode[0];
return $time;
}
function endTime($timer) {
$timeExplode = explode(" ", microtime());
$time = $timeExplode[1] + $timeExplode[0];
$finish = $time - $timer;
$endTime = sprintf("%4.3f", $finish);
return $endTime;
}
?>
</body>
</html>
get_stats.php
Code: Alles auswählen
<?php
//v0.6
//------------------ CONFIG - START -------------------------
$DBstats = "/tmp/osstats.db";
$DBlog = "/tmp/oslog.db";
#$OSCFG = "/var/etc/oscam.conf";
$OSLOG = "/tmp/OScam.log"; //only if $OSCFG is not set
// delete oslog database after x days.
// must be higher than logfile rotate-time..
// if maxlogsize is high and oscam is not used much, set this higher
$DELDAYloglines = "1";
//------------------ CONFIG - END ---------------------------
$SKIPlines = array('not found','rejected','timeout');
/*
TODO:
ggf. rrd Datenbank erzeugen um die Daten mit Munin anzuzeigen
*/
error_reporting(E_ALL);
ini_set('track_errors',1);
ini_set("max_execution_time", "240");
ob_implicit_flush(true);
@ob_end_flush();
if (!isset($argv[1]) OR empty($argv[1])) {
if (!isset($OSLOG) OR empty($OSLOG) OR !file_exists($OSLOG)) {
if (isset($OSCFG) AND !empty($OSCFG)) {
$OSLOG = GetCFG_OScam($OSCFG,"logfile");
} else {
if (file_exists("/var/etc/oscam.conf")) {
$OSLOG = GetCFG_OScam("/var/etc/oscam.conf","logfile");
}
}
if (!isset($OSLOG) OR empty($OSLOG)) {
if (file_exists("/var/emu/script/functions.sh")) {
ReadFUNCTIONS();
$OSLOG = str_replace("\$CAMLOGS",$CAMLOGS,$OSLOGFILE);
}
}
if (!isset($OSLOG) OR empty($OSLOG)) {
print ASCII::BOLD_RED("Error getting \$OSLOG! Check Configuration! Aborting..\n");
exit();
}
}
}
if (!isset($DELDAYloglines) OR empty($DELDAYloglines)) { $DELDAYloglines = 1; }
$dblog = db_con($DBlog);
$dbstats = db_con($DBstats);
// verify tables exists
$CreateLOG = "CREATE TABLE oslog (id INTEGER PRIMARY KEY,date INT,cis TEXT);";
$CreateSTATS = "CREATE TABLE osstats (id INTEGER PRIMARY KEY,startdate INT,enddate INT,caid TEXT,ident TEXT,sid TEXT,user TEXT,count INT);";
$sqlLOG = "SELECT count(name) FROM sqlite_master WHERE type='table' AND name='oslog'";
$sqlSTATS = "SELECT count(name) FROM sqlite_master WHERE type='table' AND name='osstats'";
$query = $dblog->query($sqlLOG);
$result = $query->fetch(PDO::FETCH_ASSOC);
if (!$result["count(name)"]) { $query = $dblog->query($CreateLOG); }
$query = $dbstats->query($sqlSTATS);
$result = $query->fetch(PDO::FETCH_ASSOC);
if (!$result["count(name)"]) { $query = $dbstats->query($CreateSTATS); }
// check if last modification time is older than $DELloglines and if: drop oslog table
$sql = "SELECT date FROM oslog WHERE 1 ORDER BY date ASC LIMIT 0,1";
$query = $dblog->query($sql);
$result = $query->fetch(PDO::FETCH_ASSOC);
if (!empty($result["date"])) {
$DELDAY = 86400 * $DELDAYloglines;
$diff = time() - $result["date"];
if ($diff > $DELDAY) {
print("Reached $DELDAYloglines days of old loglines. Deleting oslog Database!\n");
unlink($DBlog);
$query = $dblog->query($CreateLOG);
}
}
if (!isset($argv[1]) OR empty($argv[1])) {
echo "Scanning logfile... \n";
if (!$LOGcontent = file("$OSLOG")) {
print ASCII::BOLD_RED("Error getting Data! Aborting..\n");
exit();
}
} else { echo "Parsing logline... \n"; }
$checked=$added=$updated=0;
$DURATION_start = startTime();
if (!isset($argv[1]) OR empty($argv[1])) {
for($i=0; $i<count($LOGcontent); $i++) {
$line = $LOGcontent[$i];
if (empty($line)) { continue; }
parse_line($line);
}
} else {
parse_line($argv[1]);
}
/*
| date | tid |t|user| caid| ident| |sid | |skip | text
2013/01/25 21:23:23 F7134B38 c USER (1722&000000/0000/0081/93:DF65): found (707 ms) by SERVER (2 of 6) - Sky Sport HD 1
2013/01/25 21:23:23 F7134B38 c USER (1722&000000/0000/D035/93:45CA): found (492 ms) by SERVER (2 of 8) - History
*/
function parse_line($line) {
global $dbstats,$dblog,$SKIPlines;
global $checked,$added,$updated;
// check for valid line
if (preg_match("/.+(\([0-9]{4}\&.*).+/",$line)) {
$CONTINUE=0;
foreach ($SKIPlines AS $SKIP) { if (preg_match("/$SKIP/",$line)) { $CONTINUE=1; } }
if ($CONTINUE == 0) {
// check if logline already checked/exists
$l = preg_split("/ /",$line,-1,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
$DATE = $l[0];
$TIME = $l[1];
$DT = strtotime("$DATE $TIME");
$CIS = $l[5];
$CIS = str_replace("):","",substr($CIS,1));
$query = $dblog->query("SELECT date,cis FROM oslog WHERE date = '".$DT."' AND cis = '".db_input($CIS)."'");
$result = $query->fetch(PDO::FETCH_ASSOC);
if (empty($result)) {
// parse logline
#print("$line");
$USER = $l[4];
$CIS2 = explode("&",$CIS);
$CAID = $CIS2[0];
$CIS2 = explode("/",$CIS2[1]);
$IDENT = $CIS2[0];
$SID = $CIS2[2];
$TEXT = explode("):",$line);
$TEXT = trim($TEXT[1]);
#print("$DATE $TIME - $USER $CAID $IDENT $SID - $TEXT\n");
// check if data is already added and if update it..
$query = $dbstats->query("SELECT count FROM osstats WHERE caid = '".$CAID."' AND ident = '".$IDENT."' AND sid = '".$SID."' AND user = '".$USER."'");
$result = $query->fetch(PDO::FETCH_ASSOC);
if (isset($result["count"]) AND !empty($result["count"])) {
$COUNT = $result["count"]+1;
$query = $dbstats->query("UPDATE osstats SET count='".$COUNT."',enddate='".$DT."' WHERE caid = '".$CAID."' AND ident = '".$IDENT."' AND sid = '".$SID."' AND user = '".$USER."'");
$updated++;
} else {
// ..if not, add new entry
$VALUES = "(\"".$DT."\",\"".$DT."\",\"".$CAID."\",\"".$IDENT."\",\"".$SID."\",\"".$USER."\",\"1\")";
$query = $dbstats->query("INSERT INTO osstats (startdate,enddate,caid,ident,sid,user,count) VALUES ".$VALUES."");
$added++;
}
// insert line into oslog table..
$query = $dblog->query("INSERT INTO oslog (date,cis) VALUES (\"".$DT."\",\"".db_input($CIS)."\");");
$checked++;
}
}
}
}
print ASCII::BOLD_GRN("Scan took ".endTime($DURATION_start)." seconds. Checked ".$checked." loglines.");
print ASCII::BOLD_GRN(" Added: ".$added." - Updated: ".$updated."\n");
//______________________________________________________________________________________
function db_con($dbfile) {
if (!$db = new PDO("sqlite:$dbfile")) {
$e="font-size:23px; text-align:left; color:firebrick; font-weight:bold;";
print ASCII::BOLD_RED("Fehler beim öffnen der Datenbank: $dbfile\n");
print ASCII::BOLD_RED("".$db->errorInfo()."\n");
die;
}
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
function db_query($dbfile,$sql) {
$db = db_con($dbfile);
$result = $db->query($sql) OR db_error($sql);
return $result;
}
function db_error($sql) {
global $db;
$error = $db->errorInfo();
die("".$error."\n".$sql."\n");
}
//Add HTML character incoding to strings
function db_output($string) {
return htmlspecialchars_decode($string);
}
//Add slashes to incoming data
function db_input($string) {
#if (function_exists('mysql_real_escape_string')) {
# return mysql_real_escape_string($string);
#}
return addslashes($string);
#return htmlspecialchars($string);
}
function startTime() {
$timeExplode = explode(" ", microtime());
$time = $timeExplode[1] + $timeExplode[0];
return $time;
}
function endTime($timer) {
$timeExplode = explode(" ", microtime());
$time = $timeExplode[1] + $timeExplode[0];
$finish = $time - $timer;
$endTime = sprintf("%4.3f", $finish);
return $endTime;
}
// Auslesen der oscam.conf
function GetCFG_OScam($FILE="",$SEARCH="") {
global $OSCFG;
$SEARCHED="";
if (!empty($FILE)) { $GETFILE = $FILE; } else { $GETFILE = $OSCFG; }
if (file_exists($GETFILE)) {
$file = file("$GETFILE");
if (!empty($SEARCH)) {
for($i=0; $i<count($file); $i++) {
if (preg_match("/$SEARCH/",trim($file[$i]))) {
$zeile = "$file[$i]";
$SEARCHED = trim(substr(strrchr($zeile, "="), 1));
if (isset($zeile[0]) AND $zeile[0]=='#') { $SEARCHED = ""; }
break;
}
}
}
}
return $SEARCHED;
}
// Auslesen der functions.sh
// nur variablen in " " werden ausgelesen
function ReadFUNCTIONS() {
$functions=fopen("/var/emu/script/functions.sh","r");
while($input = fgets($functions, 1024)) {
preg_match("/^(.+)=\"(.*)\"/",trim($input),$find);
if (isset($find[1]) AND !empty($find[1])) {
if (!preg_match("/^\[|^.+\[\".+\"\]/",trim($find[1]))) {
global $$find[1];
if (empty($find[2])) { $find[2]='""'; }
$$find[1] = $find[2];
}
}
}
@fclose($functions);
}
class ASCII {
public static function BOLD_RED($text) { return "\033[31;1m".$text."\033[0m"; }
public static function BOLD_GRN($text) { return "\033[32;1m".$text."\033[0m"; }
public static function BOLD_YLW($text) { return "\033[33;1m".$text."\033[0m"; }
public static function BOLD_TUR($text) { return "\033[36;1m".$text."\033[0m"; }
public static function BOLD_PUR($text) { return "\033[35;1m".$text."\033[0m"; }
public static function BOLD_WHT($text) { return "\033[37;1m".$text."\033[0m"; }
}
?>
get_stats_deamon.sh
Code: Alles auswählen
#!/bin/bash
#
#### CONFIG - START
#
get_stats_php="/var/www/get_stats.php"
phpbin="/usr/bin/php"
#OScfg="/var/etc/oscam.conf"
OSlog="/tmp/OScam.log"
#
#### CONFIG - END
proc_parse_cfg() {
i=0
while read line; do
line=$(echo $line | sed -e 's/ //g')
if [[ "$line" =~ ^[^#]*= ]]; then
cfg_name[$i]=$(echo $line | cut -d'=' -f 1)
cfg_value[$i]=$(echo $line | cut -d'=' -f 2-)
((++i))
fi
done < $1
}
get_cfg_value() {
i=0
for name in ${cfg_name[*]}; do
[ "$1" = "$name" ] && echo "${cfg_value[$i]}" && break
((++i))
done
}
if [ -z "$OSlog" ]; then
proc_parse_cfg $OScfg
OSlog=$(get_cfg_value logfile)
fi
lastmodified=$(stat -c %Y $OSlog)
while true; do
#echo $lastmodified
#echo $(stat -c %Y $OSlog)
if [ -n "$lastmodified" ]&&[ "$(stat -c %Y $OSlog)" -gt "$lastmodified" ]; then
lastmodified=$(stat -c %Y $OSlog)
$phpbin -f $get_stats_php
fi
sleep 10
done
exit 0