<?php
/* Logaholic Web Analytics software             Copyright(c) 2005-2013 Logaholic B.V.
 *                                                               All rights Reserved.
 * This code is subject to the Logaholic license. Unauthorized copying is prohibited.
 * support@logaholic.com                         http://www.logaholic.com/License.txt
 * 
 * This is an example file. Please make sure to name your file: updateall.php for correct useage.
 *
 */ 
//PHPCIPHER NO ENCRYPT
// PHPLOCKITOPT NOENCODE
/*
  Logaholic Update All Script
  This script should be started from the command line only.
  It will update statistics for all profiles in your system.
  
  Usage:
  php -q updateall.php
  
  Example:
  In a cron job, you could set this up to run evey hour at minute 55 like this:
  55    *       *       *       * cd /path_to_your_logaholic/;php -q updateall.php -email
  
  Options:
  php -q updateall.php -reset profilename
  This will reset the 'profilename' running status to 'no'
  
  php -q updateall.php -email
  This will email a summary status of each updated profile to the admin
  
  php -q updateall.php -emailproblems
  This will email only if any problems were encountered 

*/


// --------------------------------------------------------------------------------
// Please change settings below
// --------------------------------------------------------------------------------
// Admin email address:
define('ADMINEMAIL','');  
// the email address to send email from
define('FROMEMAIL','');
// the path to the actual php command on the machine (e.g. C:\PHP\php-cgi.exe)
define('PHPCOMMAND','php'); 
// the absolute path to your logaholic directory
define('LOGAHOLIC_DIR','');
// the absolute path to a directory where you want to keep logs of updateall output (only used if you use the -launch parameter to start mutiple instances of updateall.php)
define('LOG_DIR','');

// only use this if you know what you are doing, see the documentation: http://www.logaholic.com/manual/update-now/updating-with-advanced-command-line-options/
define('FORCE','false');
define('MOVEDONE','false');
define('DELFILE', 'false');


// --------------------------------------------------------------------------------
// Don't edit beyond this point
// --------------------------------------------------------------------------------

if (php_sapi_name() == 'cli' || ( php_sapi_name() === 'cgi-fcgi' && empty($_SERVER['REMOTE_ADDR']) ) ) {
  # Ok
} else {
  die('This script can only be run from the command line');
}

if ($_SERVER['DOCUMENT_ROOT'])
{
    if ($_REQUEST['key']!="4d5a5f95fa0a09d19ba898c4f4bb8b08") {
    echo "This script should be started from the command line only.<br>Terminating.";
    exit();
  }
}

set_time_limit(86400);
$running_from_command_line=true;
$notifyadmin=false;
$notifyadmin_of_problems=false;
$output="";
$mailmess="";
$problem_message="";
$quiet="1";
include(LOGAHOLIC_DIR."/common.inc.php");

//$limit="limit 100";
//$delfile="&delfile=true";
$extraparams="";
if (FORCE == "true") {
  $extraparams.="&force=true";
}
if (MOVEDONE == "true") {
  $extraparams.="&movedone=true";
}
if (DELFILE == "true") {
  $extraparams.="&delfile=true";
}

if (@isset($argv[1])) {
    if ($argv[1] == "-resetall") {
        $db->Execute("update ".TBL_PROFILES." set `update_status`='ready' where `update_status` !='ready'");
        echo "Reset Update running status to 'no' for all profiles.\n";
        exit(); 
    }
    if ($argv[1] == "-reset") {
        if ($argv[2]!="") {
        $db->Execute("UPDATE ". TBL_PROFILES ." SET `update_status` = 'ready' WHERE `profilename` = ". $db->Quote($argv[2]));
            echo "Reset Update running status to 'no' for {$argv[2]}\n";
            sleep(1);
        } else {
            echo "Reset failed, don't know what profile to reset\nyou can reset by starting the command with the reset parameter,\ni.e:\nphp -q updateall.php -reset PROFILENAME\n";
        } 
    }
    if ($argv[1] == "-email") {
        echo "Email mode - sending summary output to email: ".ADMINEMAIL."\n";
        $notifyadmin=true;    
    }
    if ($argv[1] == "-emailproblems") {
        echo "Email mode - sending any problems to email: ".ADMINEMAIL."\n";
        $notifyadmin_of_problems=true;    
    }
  
  if (strpos($argv[1],"-launch=") !== false) {
        $n=str_replace("-launch=","",$argv[1]);
    Launch($n);
    exit();
    }
  
  if (strpos($argv[1],"-range=") !== false) {
        $limit="limit ".str_replace("-range=","",$argv[1]);
    }
  if (strpos($argv[2],"-range=") !== false) {
        $limit="limit ".str_replace("-range=","",$argv[2]);
    }
  
  
}

function Launch($n) {
  global $db;
  $q = "select count(*) from ".TBL_PROFILES;  
  $q= $db->Execute($q);
  $result = $q->FetchRow();
  $total = $result[0];
  $limit = round(($total/$n));
  $i = 0;
  $offset = 0;
  while ($i < $n) {
    $range = "$offset,$limit";
    $cmd = PHPCOMMAND." -q updateall.php -range=$range > ".LOG_DIR."ulog$i.txt 2>&1 &";
    echo $cmd."\n";
    system($cmd);
    $offset = $offset + $limit;
    $i++;
  }
}

function RunUpdate($pname) {
    global $notifyadmin,$mailmess,$quiet,$problem_message,$notifyadmin_of_problems,$extraparams;
    //echo PHPCOMMAND." -q ".LOGAHOLIC_DIR. "/update.php \"conf=$pname{$extraparams}\"\n";
  if ($notifyadmin==true || $notifyadmin_of_problems==true) {
        unset($output);
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
          //This is a server using Windows
          $last = exec("cd ".LOGAHOLIC_DIR." & ".PHPCOMMAND." -q ".LOGAHOLIC_DIR. "/update.php \"conf=$pname{$extraparams}\" 2>&1", $output);
        } else {
          //This is a server not using Windows
          $last = exec("cd ".LOGAHOLIC_DIR."; ".PHPCOMMAND." -q ".LOGAHOLIC_DIR. "/update.php \"conf=$pname{$extraparams}\" 2>&1", $output);
        }
    
    if (strpos($last,"[Finished]")!==FALSE || strpos($last,"Please activate this profile to update.") !==FALSE) {
      # looks good
      echo $output[1]."\n";
      echo $last."\n";
      if ($notifyadmin == true) {
        $mailmess.="\n\n$pname:\n$last";  
      }
    } else {
      $txt = "\n\n$pname (ERROR):\n-----------------------\n".implode("\n",$output)."\n--------------------\n"; 
      echo $txt;
      if ($notifyadmin == true) {
        $mailmess.=$txt;
      }
      if ($notifyadmin_of_problems == true) {
        $problem_message.=$txt;
      }
    }
    
    } else {
      if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        //This is a server using Windows
        system("cd ".LOGAHOLIC_DIR." & ".PHPCOMMAND." -q ".LOGAHOLIC_DIR."/update.php \"conf=$pname{$extraparams}\" 2>&1");
      } else {
        //This is a server not using Windows
        system("cd ".LOGAHOLIC_DIR."; ".PHPCOMMAND." -q ".LOGAHOLIC_DIR."/update.php \"conf=$pname{$extraparams}\" 2>&1");
      }
    }   
}

$start=time();
if (!isset($limit)) { $limit=""; } 
$q = "select profilename, update_status from ".TBL_PROFILES." $limit";
echo $q."\n";
//exit();
$q= $db->Execute($q);

$i=0;
while ($data=$q->FetchRow()) {
    $pname=$data[0];
    echo "\n\n$pname...\n";
    $running = $data['update_status'];
    if ($running !="ready") {
        // we're already running, terminate and warn administrator
        echo $message = "An Update process for '$pname' started while one was still marked as running,\nif you are sure the update is not running anymore,\nyou can reset it's status by starting the command with the reset parameter,\ni.e:\nphp -q updateall.php -reset $pname\n";
        $mailmess.= "\n\n$pname (skipping)\n".$message;
        $problem_message.= "\n\n$pname (skipping)\n".$message;  
    } else {
    RunUpdate($pname);
    }    
    $i++;   
}

$headers = 'From: '.FROMEMAIL;
$took = number_format(((time() - $start) / 60),2);
$endstatus = "\n\nAll Finished!\nUpdating $i profiles took $took minutes\n";
if ($notifyadmin==true) {
    $mailmess.=$endstatus;
    mail(ADMINEMAIL,"Logaholic Update All status",$mailmess,$headers,'-f'.FROMEMAIL);
}
if ($notifyadmin_of_problems==true && $problem_message!="") {
    mail(ADMINEMAIL,"Logaholic Update All Problem status",$problem_message.$endstatus,$headers,'-f'.FROMEMAIL);
}
echo $endstatus;  
?>