Code

a86f5491fafd41c1b50085d41c5209c2c2de12cb
[gosa.git] / gosa-core / plugins / generic / statistics / class_statistics.inc
1 <?php
3 class statistics extends plugin
4 {
5     var $plHeadline = 'Statistics';
6     var $plDescription = 'GOsa usage statistics';
7     var $plShortIcon = 'statistics.png';
8     var $plIcon = 'plugin.png';
9     
10     var $rpcHandle = NULL;
11     var $rpcConfigured = FALSE;
13     var $statisticData = array();
15     var $graphID_1 = 0;
16     var $graphID_2 = 0;
17     var $graphID_3 = 0;
18     var $graphID_4 = 0;
19     var $graphID_5 = 0;
21     var $legendR = 235;
22     var $legendG = 235;
23     var $legendB = 235;
25     var $font = "./themes/default/fonts/LiberationSans-Regular.ttf";
27     var $graph1DatePicker1 = 0;
28     var $graph1DatePicker2 = 0;
30     var $unsbmittedFiles = array();
32     function __construct($config)
33     {
34         plugin::plugin($config, NULL);
36         // Init start and stop times for graph 1
37         $this->graph1DatePicker1 = date('d.m.Y', time() - 14 * 24 * 60 *60);
38         $this->graph1DatePicker2 = date('d.m.Y', time());
40         // First try to retrieve values via RPC
41         $this->rpcConfigured = FALSE;
42         if ($this->config->get_cfg_value("core","gosaRpcServer") != ""){
43             $this->rpcConfigured = TRUE;
44             $this->rpcHandle = $this->config->getRpcHandle(
45                     "http://10.3.64.59:4000",
46                     "65717fe6-9e3e-11df-b010-5452005f1250",
47                     "WyukwauWoid2",
48                     TRUE);
49         }
51         // Get list of unsubmitted files.
52         $this->unsbmittedFiles = $this->getUnsubmittedStatistics();
54         // Collect category translations
55         $this->catTranslations = array();
56         foreach($this->config->configRegistry->getListOfPlugins() as $plugin => $data){
57             if(isset($data['plCategory'])){
58                 foreach($data['plCategory'] as $id => $name){
59                     if(!is_numeric($id)){
60                         $this->catTranslations[$id] = $name['description'];
61                     }
62                 }
63             }
64         }
65     }
67     /*! \brief      Returns a list local stored statistic files
68         @param      Array   A list of filenames and dates.
69      */ 
70     function getLocalStatisticsFiles()
71     {
72         $res = stats::getLocalStatFiles();
73         $tmp = array();
74         if(count($res)){
75             foreach($res as $file){
76                 $date = strtotime($file);
77                 if($date){
78                     $tmp[$file] = $date;
79                 }
80             }
81         }
82         return($tmp);
83     }
85    
86     /*! \brief      Returns a list of not transmitted stat files (except files for the current day)
87      *  @return     Array   A list of unsubmitted statistic files.
88      */ 
89     function getUnsubmittedStatistics()
90     {
91         $available = $this->getLocalStatisticsFiles();
92         $alreadyTransmitted = $this->getStatisticsDatesFromServer();
94         $unsubmitted = array();
95         foreach($available as $key => $day){
96             if(!isset($alreadyTransmitted[$key])) $unsubmitted [$key] = $day;
97         }
99         // Exclude statistic collection from today, they are still active and cannot be submitted.
100         $curDate =  date('Y-m-d');
101         if(isset($unsubmitted)) unset($unsubmitted[$curDate]);
103         return($unsubmitted);  
104     }
107     /*! \brief      Request a list of dates for which the server can return statistics.
108         @param      Array   A list of dates    $ret=[iso-str] = timestamp
109      */ 
110     function getStatisticsDatesFromServer()
111     {
112         $res = $this->rpcHandle->getInstanceStatDates();
113         $dates = array();
114         if(!$this->rpcHandle->success()){
115             msg_dialog::display(_("Error"),msgPool::rpcError($this->rpcHandle->get_error()),ERROR_DIALOG);
116         }else{
117             foreach($res as $date){
118                 $dates[$date] = strtotime($date);
119             }
120         }
121         return($dates);
122     }
125     function execute()
126     {
127         $smarty = get_smarty();
128         $smarty->assign('graph1DatePicker1', $this->graph1DatePicker1);
129         $smarty->assign('graph1DatePicker2', $this->graph1DatePicker2);
131         // Do not render anything if we are not prepared to send and receive data via rpc.
132         $smarty->assign("rpcConfigured", $this->rpcConfigured);
133         $smarty->assign("validRpcHandle", TRUE);
134         if(!$this->rpcConfigured || !$this->rpcHandle){
135             $smarty->assign("validRpcHandle", FALSE);
136             return($smarty->fetch(get_template_path('statistics.tpl', TRUE)));
137         }
139         // Send stats 
140         if(isset($_POST['transmitStatistics'])){
141             $this->unsbmittedFiles = $this->getUnsubmittedStatistics();
142             foreach($this->unsbmittedFiles as $filename => $date){
143                 $tmp = stats::dumpTables($filename);
144                 $dump = array();
145                 foreach($tmp as $entry){
146                     $dump[] = array_values($entry);
147                 }
148                 $res = $this->rpcHandle->updateInstanceStatus($dump);
149                 if(!$this->rpcHandle->success()){
150                     msg_dialog::display(_("Error"),msgPool::rpcError($this->rpcHandle->get_error()),ERROR_DIALOG);
151                 }else{
152                     stats::removeStatsFile($filename);
153                     echo "Inserted ".$res." entries for date ".date('d.m.Y', $date)."<br>";
154                 }
155             }
156             $this->unsbmittedFiles = $this->getUnsubmittedStatistics();
157         }
159         // Transmit daily statistics to GOsa-Server
160         if(isset($_POST['receiveStatistics']) && $this->rpcConfigured){
161             $start = strtotime($this->graph1DatePicker1);
162             $stop  = strtotime($this->graph1DatePicker2);
163             $res = $this->rpcHandle->getInstanceStats($start,$stop);
164             if(!$this->rpcHandle->success()){
165                 msg_dialog::display(_("Error"),msgPool::rpcError($this->rpcHandle->get_error()),ERROR_DIALOG);
166             }elseif($res){
167                 $this->statisticData = $this->prepareGraphData($res); 
168                 $this->reloadGraphs();
169             }
170         }
172         $smarty->assign('graphID_1', $this->graphID_1);
173         $smarty->assign('graphID_2', $this->graphID_2);
174         $smarty->assign('graphID_3', $this->graphID_3);
175         $smarty->assign('graphID_4', $this->graphID_4);
176         $smarty->assign('graphID_5', $this->graphID_5);
177         $smarty->assign('unsbmittedFiles', count($this->unsbmittedFiles));
178         $smarty->assign('unsbmittedFilesMsg', sprintf(
179                     _("You have currently %s unsubmitted statistic collection, do you want to transmit them now?"),
180                     count($this->unsbmittedFiles)));
181         return($smarty->fetch(get_template_path('statistics.tpl', TRUE)));
182     }
185     /*! \brief      Prepares the graph data we've received from the rpc-service.
186      *              This method will construct a usable data-array with converted 
187      *               date strings.
188      */
189     function prepareGraphData($res)
190     { 
192         /* Build up array which represents the amount of errors per
193          *  interval.
194          */
195         $gData = array();
196         foreach($res['errorsPerInterval'] as $dateStr => $data){
197             $date = strtotime($dateStr);
198             $gData['errorsPerInterval'][$date] = $data;
199         }
200         ksort($gData['errorsPerInterval']);
203         /* Build up timeline
204          */
205         $Xam = 5; 
206         $cnt = 0;
207         $numCnt = $res['errorsPerInterval'];
208         foreach($gData['errorsPerInterval'] as $date => $data){
209             if((count($numCnt) <= $Xam) || 
210                     ($cnt % (floor(count($numCnt) / $Xam )) == 0)){
211                 $gData['dates'][$date] = date('d.m.Y', $date);
212             }else{
213                 $gData['dates'][$date] = ' ';
214             }
215             $cnt ++;
216         }
217         ksort($gData['dates']);
219         
220         /* Build up 'actions per category' array, this will later
221          *   be represented using a pie chart.
222          */
223         $gData['actionsPerCategory'] = $res['actionsPerCategory'];
224         arsort($gData['actionsPerCategory']);
227         /* Build up system-info array per interval.
228          */
229         foreach($res['usagePerInterval'] as $dateStr => $data){
230             $date = strtotime($dateStr);
231             foreach($data as $type => $count){
232                 $gData['usagePerInterval'][$type][$date] = $count;
233             }
234         }
235         foreach($gData['usagePerInterval'] as $key => $data)
236             ksort($gData['usagePerInterval'][$key]);
239         /* Prepare actions-per-interval array.
240          */    
241         foreach($res['actionsPerInterval'] as $category => $data){
242             if(empty($category)) continue;
243             foreach($data as $dateStr => $count){
244                 $date = strtotime($dateStr);
245                 $gData['actionsPerInterval'][$category][$date]=$count;
246             }
247             ksort($gData['actionsPerInterval'][$category]);
248         }
249         return($gData);
250     }
253     function check()
254     {
255         $messages = plugin::check();
256         return($messages);
257     }
260     function save_object()
261     {
262         plugin::save_object();
263         if(isset($_POST['graph1DatePicker1'])) $this->graph1DatePicker1 = get_post('graph1DatePicker1');
264         if(isset($_POST['graph1DatePicker2'])) $this->graph1DatePicker2 = get_post('graph1DatePicker2');
265     }
268     /*! \brief      This method tries to translate category names.
269      *  @param      The category name to translate
270      *  @return     String  The translated category names.
271      */
272     function getCategoryTranslation($name)
273     {
274         $ret ="";
276         // Extract category names from the given string.
277         $list = preg_split("/, /", $name);
279         // We do not have a category for systems directly, so we've to map all system types to 'System'.
280         // If we do not map to _(Systems) the graph legend will be half screen width.
281         if(count(array_intersect(array('server','terminal','workstation', 'opsi', 'component'), $list))){
282             return(_("Systems"));
283         }
285         // Walk through category names and try to find a translation.
286         foreach($list as $cat){
287             $cat = trim($cat);
288             if(isset($this->catTranslations[$cat])){
289                 $cat = _($this->catTranslations[$cat]);
290             }elseif(!empty($cat)){
291                 $cat = _($cat);
292             }
293             $ret .= $cat.", ";
294         }
295         return(rtrim($ret, ', '));
296     }
299     /*! \brief  Reload the graph images.
300      */ 
301     function reloadGraphs()
302     {
303         new pChartInclude();
304         $gData = $this->statisticData;
305         if(count($gData['actionsPerCategory'])){
306             $this->generateCategoryPieGraph($gData['actionsPerCategory']);
307         }
308         $this->generateActionsGraph($gData);
309         $this->generateSystemStatsGraph($gData);
310     }
313     /*! \brief  Generates the line-graph which displays the plugin usage over time.
314      */ 
315     function generateActionsGraph($gData)
316     {
317         $lineMax = 100;
318         $errorMax = (max($gData['errorsPerInterval']) < 100)? 100:max($gData['errorsPerInterval']);
319         $dataSet = new pData;  
320         foreach($gData['actionsPerInterval'] as $category => $entriesPerDate){
321             if(empty($category)) continue;
323             // Add results to our data set.
324             $dataSet->AddPoint($entriesPerDate, $category);
325             $dataSet->SetSerieName($this->getCategoryTranslation($category), $category);
326             $dataSet->AddSerie($category);
328             // Detect maximum value, to adjust the Y-Axis
329             $tmpMax = max($entriesPerDate);
330             if($tmpMax > $lineMax) $lineMax = $tmpMax;
331         }
333         // Add timeline
334         $dataSet->AddPoint($gData['dates'], 'date');
335         $dataSet->SetAbsciseLabelSerie('date');  
337         $chart = new pChart(800,230);  
338         $chart->setFixedScale(0.000,$lineMax);
339         $chart->setFontProperties("./themes/default/fonts/LiberationSans-Regular.ttf",10);  
340         $chart->setGraphArea(50,30,585,200);  
341         $chart->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240);  
342         $chart->drawRoundedRectangle(5,5,695,225,5,230,230,230);  
343         $chart->drawGraphArea(255,255,255,TRUE);  
344         $chart->drawGrid(4,TRUE,200,200,200,50);  
345         $chart->drawTreshold(0,143,55,72,TRUE,TRUE);  
346         $chart->drawTitle(50,22,"Plugin usage over time",50,50,50,585);  
347         $chart->drawScale($dataSet->GetData(),$dataSet->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2, TRUE);     
348         $chart->drawFilledLineGraph($dataSet->GetData(),$dataSet->GetDataDescription(),50,TRUE);
349         $chart->setColorPalette(count($gData['actionsPerInterval']),255,0,0);   
351         // Draw legend
352         $dataSet->AddPoint($gData['errorsPerInterval'], 'Errors');
353         $dataSet->SetSerieName(_('Error'), 'Errors');
354         $dataSet->AddSerie('Errors');
355         $chart->drawLegend(650,30,$dataSet->GetDataDescription(),255,255,255);  
357         // Remove all graph series and add the error-series, then draw the new graph.
358         foreach($gData['actionsPerInterval'] as $category => $data){
359             $dataSet->RemoveSerie($category);
360         }
361         $chart->setFixedScale(0,$errorMax);
362         $chart->drawRightScale($dataSet->GetData(),$dataSet->GetDataDescription(),SCALE_NORMAL,120,150,150,TRUE,0,2, TRUE);
363         $chart->drawBarGraph($dataSet->GetData(),$dataSet->GetDataDescription());
365         // Generate new and unique graph id
366         $this->graphID_2 = preg_replace("/[^0-9]/","",microtime(TRUE));
367         $file = '/tmp/graph_'.$this->graphID_2;
368         $chart->Render($file);
369         session::set('statistics::graphFile'.$this->graphID_2,$file);
371         return;
372     }
373    
375     /*! \brief  Generates a graph about system informations.
376      */ 
377     function generateSystemStatsGraph($gData, $key = "", $series= array(), $title = "", $gID=0 )
378     { 
380         $title = _("Memory usage");
381         $key    = "usagePerInterval";
382         $series = array(
383             'max_mem' => _('Max'),
384             'avg_mem' => _('Avergae'),
385             'min_mem' => _('Min'));
386         $gID = 3;
388         // Add series data to dataSet        
389         $dataSet = new pData;  
390         $max = 0;
391         foreach($series as $seriesName => $seriesDesc){
392             if(isset($gData[$key][$seriesName])){
393                 $dataSet->AddPoint($gData[$key][$seriesName],$seriesName);
394                 $dataSet->SetSerieName($seriesDesc,$seriesName);
395                 if($max < max($gData[$key][$seriesName])) $max = max($gData[$key][$seriesName]);
396             }
397         }
398         $dataSet->AddAllSeries();  
399         $dataSet->AddPoint($gData['dates'], 'date');
400         $dataSet->SetAbsciseLabelSerie('date');  
401         
402         $chart = new pChart(800,230);  
403         $chart->setFixedScale(0.0001,($max*1.1));  
404         $chart->setFontProperties("./themes/default/fonts/LiberationSans-Regular.ttf",10);  
405         $chart->setGraphArea(50,30,585,200);  
406         $chart->drawFilledRoundedRectangle(7,7,693,223,5,240,240,240);  
407         $chart->drawRoundedRectangle(5,5,695,225,5,230,230,230);  
408         $chart->drawGraphArea(255,255,255,TRUE);  
409         $chart->drawGrid(4,TRUE,200,200,200,50);  
410         $chart->drawTreshold(0,143,55,72,TRUE,TRUE);  
411         $chart->drawTitle(50,22,"Memory usage",50,50,50,585);  
412         $chart->drawLegend(650,30,$dataSet->GetDataDescription(),255,255,255);  
414         $chart->drawScale($dataSet->GetData(),$dataSet->GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2, FALSE);
415         $chart->drawFilledCubicCurve($dataSet->GetData(),$dataSet->GetDataDescription(),.1,50); 
417         $gName = "graphID_".$gID;
418         $this->$gName = preg_replace("/[^0-9]/","",microtime(TRUE));
419         $file = '/tmp/graph_'.$this->$gName;
420         $chart->Render($file);
421         session::set('statistics::graphFile'.$this->$gName,$file);
422     }
425     /*! \brief  Generate the pie-chart which displays the overall-plugin-usage
426      */
427     function generateCategoryPieGraph($data)
428     {
429         // Sort data by usage count and slice array to get 
430         //  the eight most used categories
431         arsort($data);
432         $mostUsedCategories = array_slice($data,0,7);
434         // Get the rest of categories and combine them 'others'
435         $theRest = array_slice($data,7);
436         $mostUsedCategories['remaining'] = array_sum($theRest);
438         // Try to find a translation for the given category names
439         $values = array_values($mostUsedCategories);
440         $keys = array_keys($mostUsedCategories);
441         foreach($keys as $id => $cat){
442             $keys[$id] = $this->getCategoryTranslation($cat);
443         }
445         // Dataset definition   
446         $dataSet = new pData;  
447         $dataSet->AddPoint($values,"Serie1");  
448         $dataSet->AddAllSeries();  
449         $dataSet->AddPoint($keys,"Serie2");  
450         $dataSet->SetAbsciseLabelSerie("Serie2");  
452         // Set graph area
453         $x = 400;
454         $y = 200;
456         // Initialise the graph  
457         $chart = new pChart($x,$y);  
458         $chart->setFontProperties($this->font,10);  
459         $chart->drawPieGraph($dataSet->GetData(),$dataSet->GetDataDescription(),($x/3),($y/2)-10,($y/2),PIE_PERCENTAGE,TRUE,50,20,3);  
460         $chart->drawPieLegend(($x/3*2),15,$dataSet->GetData(),$dataSet->GetDataDescription(),
461                 $this->legendR,$this->legendG,$this->legendB);
463         // Store graph data
464         $this->graphID_1 = preg_replace("/[^0-9]/","",microtime(TRUE));
465         $file = '/tmp/graph_'.$this->graphID_1;
466         $chart->Render($file);
467         session::set('statistics::graphFile'.$this->graphID_1,$file);
468     }
470 ?>