AmdaStats.php 8.94 KB
<?php
/**
 * @class AmdaStats
 * @version  $Id: AmdaStats.php 2964 2015-06-26 07:53:48Z elena $ 
 */ 
 
class AmdaStats {

	public $statXml;
	public $tasks = array('plot', 'mining', 'print', 'statistics');
	public $tasksAdd = array('ttoper', 'samp', 'upload', 'create', 'images');
	public $usersToExclude = array('bouchemit', 'impex');
	public $success = true;
	private $user = null;
	private $task = array('request'=>'plot','condition'=>'mining', 'download'=>'print','statistics'=>'statistics');
	
	public function __construct($user) {
		
		$this->statXml = new DomDocument('1.0','UTF-8');
		$this->statXml->preserveWhiteSpace = false;
		$this->statXml->formatOutput = true;
	
		if (!defined("StatsXml")){
			$thisYear = date("Y");
			if (!$user){  
			// general - to read
			// define('StatsXml',DATAPATH.'Statistics/Stats.xml');
				define("StatsXml",DATAPATH."Statistics/Stats$thisYear.xml");
			// if (file_exists(StatsXml)) unlink(StatsXml);
			}
			else {
			// individual - to write
			// define("StatsXml", USERPATH."/".$user."/Stats.xml");
				define("StatsXml", USERPATH.$user."/Stats$thisYear.xml"); 
				$this->user = $user;
			}
		}

		if (!file_exists(StatsXml)) {
			if (!is_dir(DATAPATH.'Statistics')) {
					if (!mkdir(DATAPATH.'Statistics', 0775)) $this->success = false; //return -1;
					if (!chgrp(DATAPATH.'Statistics', APACHE_USER)) $this->success = false; // return -1;                 
			}

			$status = $this->generateXml(); 
			if (!$status) {
				error_log('Cannot create Stats.xml: Fatal Error '.$user,1,email); 
				$this->success = false;
			}
		}
		else {
			$status = $this->statXml->load(StatsXml); 
			if (!$status) {
				$status = $this->generateXml(); 
				$msg = $status ? 'Cannot load Stats.xml. New Stats.xml was created' : 
						'Cannot load Stats.xml. Cannot create Stats.xml: Fatal Error ';
						
				error_log($msg.$user,1,email);
				
				if (!$status) 
					$this->success = false;
			}
		}         
  }

/*
*  Merge individual User Stats.xml into one generique Stats.xml
*/
	public function mergeXml($year) {
		// long procedure
		ini_set('max_execution_time', 600); 
		
		$tags = array_merge($this->tasks, $this->tasksAdd);

		$doc2 = new DomDocument("1.0");
		if ($year == null) $year = date("Y");
		
		$users=glob(USERPATH."*");
		foreach ($users as $user) {        
			 $name2 = $user."/Stats$year.xml";

			if (!file_exists($name2)) continue;

			$doc2->load($name2);
			
			foreach ($tags as $tag) {    
				$tag1 = $this->statXml->getElementsByTagName($tag)->item(0);
				$tag2 = $doc2->getElementsByTagName($tag)->item(0);
				$items2 = $tag2->getElementsByTagName("item");
				if ($items2->length > 0) {
					foreach ($items2 as $item2) {
						$item1 = $this->statXml->importNode($item2, true);
						$tag1->appendChild($item1);
					}
				}          
			}
		}

		// write task statistics as json
		$this->getModulesStat(null,null,true);
		// write data statistics as json
		$this->getDataStat(0,null,null,true);

		return  $this->statXml->save(StatsXml);
	}

	private function generateXml() {

		$rootElement = $this->statXml->createElement('stats');

		$allTasks = array_merge($this->tasks, $this->tasksAdd);
		
		foreach ($allTasks as $task) {            
			$element = $this->statXml->createElement("$task");        
			$rootElement->appendChild($element);        
		}

		$this->statXml->appendChild($rootElement);

		return $this->statXml->save(StatsXml);
	}
 
	public function addTask($user, $task, $vars) {
	
// 		if (!$this->user) {
// 			error_log('User is null', 1, email);
// 			return;
// 		}
		if ($task == 'killplot')
			return;
			
		if ($vars)
			$realTask = $this->task[$task];
		else
			$realTask = $task;

		if (!in_array($user, $this->usersToExclude)) {
			$taskElementNode = $this->statXml->getElementsByTagName("$realTask");

			if ($taskElementNode->length < 1) 
					return; 
					
			$taskElement = $taskElementNode->item(0);
			if (is_object($taskElement)) {
				$newTask = $this->statXml->createElement('item');
				$newTask->setAttribute('date', date('Y-m-d'));
				$newTask->setAttribute('user', $user);
           
				if ($vars) { 
					$ID = array();

					foreach ($vars as $var) {
						$ID[] = $var;
					}
						
					$ID = array_unique($ID);

					foreach ($ID as $id) {
						$datasetElement = $this->statXml->createElement('dataset', $id);
						$newTask->appendChild($datasetElement);  
					}         
				}
				
				$taskElement->appendChild($newTask);
				$this->statXml->save(StatsXml);  
			}
			else 
				error_log('Check Stats.xml - no task element '.$task, 1, email);
		}
	}
 
/*
*     Show Statistics
*/
	public function getModulesStat($start, $stop, $update){

		if (!$update && file_exists(DATAPATH.'Statistics/tasks.json')) {
					return  file_get_contents(DATAPATH.'Statistics/tasks.json');
		}
		
		$taskArray = array();

		foreach (array_merge($this->tasks,$this->tasksAdd) as $task) {
			$theTask = $this->statXml->getElementsByTagName($task)->item(0);
			$items = $theTask->getElementsByTagName('item');
			$hints = $items->length;

			$startStop = $this->getStartStop($items, $start, $stop);
			$taskArray[] = array('task' => $task, 'number' => $hints, 
										'start' => $startStop[0], 'stop' => $startStop[1]); 
		}

		$objToReturn = json_encode(array('stats' => $taskArray));

		file_put_contents(DATAPATH.'Statistics/tasks.json', $objToReturn);

		return $objToReturn;
	}

/*
*     Show Statistics
*/
	public function getDataStat($index, $start, $stop, $update){

		if (!$update && file_exists(DATAPATH.'Statistics/data.json')) {
			$GENERALarray = json_decode(file_get_contents(DATAPATH.'Statistics/data.json'));
		}
		else {
			$VIarray = array();
			$TOTALarray = array();
			$STARTarray = array();
			$STOParray = array();

			foreach ($this->tasks as $task) {
				$theTask = $this->statXml->getElementsByTagName($task)->item(0);
				$items = $theTask->getElementsByTagName('item');
				$TASKarray = array();
		
				foreach ($items as $item){
					$VIs = $item->getElementsByTagName('dataset');
					$time = strtotime($item->getAttribute('date'));

					foreach ($VIs as $VI) {
						$id = $VI->nodeValue;
						if ($id) {
							if ($TASKarray[$id]) {
								$TASKarray[$id]++;
								$TOTALarray[$id]++;
								if ($STARTarray[$id] > $time) 
											$STARTarray[$id] = $time;
								if ($STOParray[$id] < $time) 
											$STOParray[$id] = $time;
							}
							else {
								if (!$TOTALarray[$id]) { 
									$STARTarray[$id] = $time;
									$STOParray[$id] = $time;
									$TOTALarray[$id] = 1;
								} 
								else {
									if ($STARTarray[$id] > $time) 
													$STARTarray[$id] = $time;
									if ($STOParray[$id] < $time) 
													$STOParray[$id] = $time;
									$TOTALarray[$id]++;
								}
								$TASKarray[$id] = 1;
							}            
						}                     
					}
				}
				$VIarray[$task] = $TASKarray;
			}
	
			$GENERALarray = array();
			arsort($TOTALarray);
			
			$Ntotal = 0; 
           
			foreach ($TOTALarray as $key => $value) {
				$viStart = $STARTarray[$key];
				$viStop = $STOParray[$key];
				$plot = $VIarray['plot'][$key];
				$mining = $VIarray['mining'][$key];
				$print = $VIarray['print'][$key];
				$stat = $VIarray['statistics'][$key];
				if ($key != 'undefined') 
				{
					$GENERALarray[] = array('id' => $key, 'number' => $value, 'percent' => $value,
												'plot' => $plot, 'mining' => $mining, 
												'print' => $print,'statistics' => $stat, 
												'start' => $viStart, 'stop' => $viStop);
												
					$Ntotal += $value;							
				}
			}
			
			$Ntotal /= 100;

			foreach ($GENERALarray as &$elem) {
						$elem['percent'] = round($elem['percent'] / $Ntotal, 2);
			}
			
		}
 
		$Nmax = count($GENERALarray);
 
		$length = $index + 20 > $Nmax ? $Nmax - $index + 1 : 20;
		$objToReturn = array('stats' => array_reverse(array_slice($GENERALarray, $index, $length)));
		
		file_put_contents(DATAPATH.'Statistics/data.json',json_encode($GENERALarray)); 
		
		//  $objToReturn = array('stats' => $GENERALarray);
		return $objToReturn;
	}

	public function getStartStop($items, $start, $stop) {
		if (!$start) $start = 0;
		if (!$stop) $stop = 100000000000;
		
		$date = array();
		
		foreach ($items as $item) {
			$newDate = strtotime($item->getAttribute('date'));

			if (($newDate > $start) && ($newDate < $stop))
							$date[] =  $newDate;        
		}

		return array(min($date), max($date));
	}

	public function mergeStats($inXml) {

		if (!file_exists(StatsXml)) return 0;
		if (!file_exists($inXml)) return 0;

		$tags = array_merge($this->tasks,$this->tasksAdd);

		$doc1 = new DomDocument("1.0");
		$doc2 = new DomDocument("1.0");

		if (!$doc1->load(StatsXml)) return 0;
		if (!$doc2->load($inXml)) return 0;

		foreach ($tags as $tag){
			$tag1 = $doc1->getElementsByTagName($tag)->item(0);
			$tag2 = $doc2->getElementsByTagName($tag)->item(0);
			$items2 = $tag2->getElementsByTagName("item");
			if ($items2->length > 0) {
				foreach ($items2 as $item2) {
					$item1 = $doc1->importNode($item2, true);
					$tag1->appendChild($item1);
				}
			}
		}

		return $doc1->save(StatsXml);
	} 
}
?>