AmdaStats.php 11.5 KB
<?php
/**
 * @class AmdaStats
 * @version  $Id: AmdaStats.php 2964 2015-06-26 07:53:48Z elena $
 * 
 */ 
 
class AmdaStats {
  
  public $statXml;
  public $tasks = array('mining', 'print', 'plot');
  public $tasksAdd = array('ttoper', 'samp', 'upload', 'create', 'images');
  public $usersToExclude = array( 'bouchemit', 'impex');
  public $success = true;
  public $paramInfo;

  public function __construct($user) {
     
        $this->statXml = new DomDocument('1.0','UTF-8');
        $this->statXml->preserveWhiteSpace = false;
        $this->statXml->formatOutput = true;
    
        if (!defined("StatsXml")){
         if (!$user){  
            // general - to read
                define('StatsXml',DATAPATH.'Statistics/Stats.xml');
              // if (file_exists(StatsXml)) unlink(StatsXml);
            }
           else {
            // individual - to write
                define("StatsXml", USERPATH."/".$user."/Stats.xml"); 
            }
        }

        if (!file_exists(StatsXml)){
            if (!is_dir(DATAPATH.'Statistics')) {
                if (!mkdir(DATAPATH.'Statistics', 0775)) 
                                                    return -1;
                if (!chgrp(DATAPATH.'Statistics', APACHE_USER))
                                                    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() {
            
     $tags = array_merge($this->tasks, $this->tasksAdd);
   
     $doc2 = new DomDocument("1.0");
 
     $users=glob(USERPATH."*");
     foreach ($users as $user) {        
        $name2 = $user."/Stats.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 getInfo($var) {

     $info = $this->paramInfo->GetParamInfo($var);
     $id = $info['ddinfos']['dataset']['id'];

     if (!$id) {
        $id = $info['codeinfos']['vi'];
        // check if from Remote base
        if (!$id) {
            $info = $this->paramInfo->getRemoteParamInfo($var);
            if (!$info)
                    return 'undefined';
            else 
                return  $info['base'].':'.$info['vi'];             
        }
        else 
           return $id;       
    }
    else  
        return $id;
    
 }

  public function addTask($task, $user, $vars){
 
   if (!in_array($user, $this->usersToExclude)) {

        $taskElement = $this->statXml->getElementsByTagName("$task")->item(0);
        if (is_object($taskElement)) {
            $newTask = $this->statXml->createElement('item');
            $newTask->setAttribute('date', date('Y-m-d'));
            $newTask->setAttribute('user', $user);
    
            if ($vars) { 
                $this->paramInfo = new ParamsInfoMgr();

                $ID = array();

                foreach ($vars as $var) {
                    if ((substr($var, 0, 7) == 'impex__') || (substr($var, 0, 13) == 'spase___IMPEX')){
                        $ID[] = 'impex';
                    }
                    elseif (substr($var, 0, 4) == 'wsd_') {
                        $ID[] = 'uploadedData';
                    } 
                    // if derived parameter parse it                                                               
                    elseif (substr($var, 0, 3) == 'ws_') {

                        if (!$parser) $parser = new Parser(); 
                        $realVar = $parser->replaceAll($var);         
                        $varArr = $parser->getVars($realVar);
                        foreach ($varArr as $var) {
                           $ID[] = $this->getInfo($var);
                        }
                    }
                    else {
                        $ID[] = $this->getInfo($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);
            
        foreach ($TOTALarray as $key => $value) {
                $viStart = $STARTarray[$key];
                $viStop = $STOParray[$key];
                $plot = $VIarray['plot'][$key];
                $mining = $VIarray['mining'][$key];
                $print = $VIarray['print'][$key];
                if ($key != 'undefined') 
                {
                    $GENERALarray[] = array('id' => $key, 'number' => $value,
                                        'plot' => $plot, 'mining' => $mining, 
                                        'print' => $print, 'start' => $viStart, 
                                        'stop' => $viStop);
                }
        } 
   }

   $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);

  } 
}
?>