Предназначен для создания файлов логирования
Author: Zmi
Example #1
0
 public function setError($errors)
 {
     if (!is_array($errors)) {
         $errors = array($errors);
     }
     parent::setError($errors);
     foreach ($errors as $error) {
         $this->logger->logError($error);
     }
 }
 function testFileLoggerErrorLevel()
 {
     $buffer = fopen('php://memory', 'rw');
     $logger = new FileLogger($buffer, ILogger::ERROR);
     $logger->debug('debug message');
     $logger->info('info message');
     $logger->error('error message');
     $this->assertTrue(rewind($buffer));
     $out = fread($buffer, 5000);
     $this->assertEqual($out, "error message\n");
 }
Example #3
0
 /**
  * @see FrontController::postProcess()
  */
 public function postProcess()
 {
     // Log requests from Privat API side in Debug mode.
     if (Configuration::get('PRIVAT24_DEBUG_MODE')) {
         $logger = new FileLogger();
         $logger->setFilename(_PS_ROOT_DIR_ . '/log/' . $this->module->name . '_' . date('Ymd_His') . '_response.log');
         $logger->logError($_POST);
     }
     $payment = array();
     parse_str(Tools::getValue('payment'), $payment);
     $hash = sha1(md5(Tools::getValue('payment') . $this->module->merchant_password));
     if ($payment && $hash === Tools::getValue('signature')) {
         if ($payment['state'] == 'ok') {
             $state = Configuration::get('PRIVAT24_WAITINGPAYMENT_OS');
             $cart_id = (int) $payment['order'];
             $order = new Order(Order::getOrderByCartId($cart_id));
             if (!Validate::isLoadedObject($order)) {
                 PrestaShopLogger::addLog('Privat24: cannot get order by cart id ' . $cart_id, 3);
                 die;
             }
             if ($order->getCurrentState() != $state) {
                 PrestaShopLogger::addLog(sprintf('Privat24: order id %s current state %s !== expected state %s', $order->id, $order->getCurrentState(), $state), 3);
                 die;
             }
             // Check paid currency and paid amount.
             $id_currency = Currency::getIdByIsoCode($payment['ccy']);
             if (!$id_currency) {
                 PrestaShopLogger::addLog(sprintf('Privat24: order id %s cannot get currency id by iso code: %s', $order->id, $payment['ccy']), 3);
                 die;
             }
             if ($order->id_currency != $id_currency) {
                 PrestaShopLogger::addLog(sprintf('Privat 24: order id %s, order currency id %s does not match with %s', $order->id, $order->id_currency, $id_currency), 3);
                 die;
             }
             if ((double) $order->total_paid != (double) $payment['amt']) {
                 PrestaShopLogger::addLog(sprintf('Privat 24: order id %s order total paid %s does not match %s', $order->id, $order->total_paid, $payment['amt']), 3);
                 die;
             }
             $order_history = new OrderHistory();
             $order_history->id_order = $order->id;
             $order_history->changeIdOrderState(_PS_OS_PAYMENT_, $order->id);
             $order_history->addWithemail();
             $this->setPaymentTransaction($order, $payment);
             $this->module->paymentNotify($order, $payment);
             PrestaShopLogger::addLog(sprintf('Privat24 payment accepted: order id: %s, amount: %s, ref: %s', $order->id, $payment['amt'], $payment['ref']), 1);
         } else {
             PrestaShopLogger::addLog(sprintf('Privat24 payment failed: state: %s, order: %s, ref: %s', $payment['state'], $payment['order'], $payment['ref']), 3, null, null, null, true);
         }
     } else {
         PrestaShopLogger::addLog('Privat24: Payment callback bad signature.', 3, null, null, null, true);
     }
     die;
 }
 /**
  * log message only if logs are enabled
  *
  * @param string message
  * @param level
  */
 public function log($message, $level = self::DEBUG)
 {
     if (!$this->logsEnabled) {
         return;
     }
     parent::log($message, $level);
 }
Example #5
0
function ToLog($msg, $path = '')
{
    global $g_config;
    $path = empty($path) ? $g_config['logPath'] : $path;
    $logger = FileLogger::Create($path);
    $logger->Message($msg);
}
Example #6
0
 public function __construct($fname)
 {
     // Такой синтаксис используется для вызова методов базового класса.
     // Обратите внимание, что ссылки $this нет! Она подразумевается.
     parent::__construct(basename($fname), $fname);
     // Здесь можно проинициализировать другие свойства текущего
     // класса, если они будут.
 }
Example #7
0
 public function setError($errors)
 {
     static $logger = null;
     if (null === $logger) {
         $cacheDir = _PS_ROOT_DIR_ . '/app/logs/';
         $file = $cacheDir . (_PS_MODE_DEV_ ? 'dev' : 'prod') . '_' . @date('Ymd') . '_installation.log';
         $logger = new FileLogger();
         $logger->setFilename($file);
         $this->logger = $logger;
     }
     if (!is_array($errors)) {
         $errors = array($errors);
     }
     parent::setError($errors);
     foreach ($errors as $error) {
         $this->logger->logError($error);
     }
 }
 /**
  * logs message to [PS ROOT]/log/YYYYMMDD_piwik.debug.log
  * @param string $message
  */
 public static function DebugLogger($message)
 {
     if (PKHelper::DEBUGLOG != 1) {
         return;
     }
     if (self::$_debug_logger == NULL) {
         self::$_debug_logger = new FileLogger(FileLogger::DEBUG);
         self::$_debug_logger->setFilename(_PS_ROOT_DIR_ . '/log/' . date('Ymd') . '_piwik.debug.log');
     }
     self::$_debug_logger->logDebug($message);
 }
 /**
  * The primary constructor.
  *
  * This method validates the input parameters and trims them to limits.
  *
  * The filename parameter (and it's directory) are checked for appropriate permissions.  If a directory is not specified in the $filename parameter, the current working directory is assumed.
  *
  * @param  string                                          $filename    The destination filename.
  * @param  int                                             $max_age_h   The maximum age of a log file before rotation.  Default is 30*24.  Max is 60*24.
  * @param  int                                             $max_size_kb The maximum size of a file before rotation (kilobytes).  Default is 10*1024.  Max is 50*1024
  * @param  int keepmax The maximum number of files to keep.  Default is 10.
  * @throws \LogicException
  * @throws \RuntimeException
  */
 public function __construct($filename, $max_age_h = null, $max_size_kb = null, $keepmax = null)
 {
     parent::__construct($filename);
     if (!$max_age_h) {
         $max_age_h = 30 * 24;
     }
     if (!$max_size_kb) {
         $max_size_kb = 10 * 1024;
     }
     if (!$keepmax) {
         $keepmax = 10;
     }
     $this->_max_age = $max_age_h;
     $this->_max_size = $max_size_kb;
     $this->_keepmax = $keepmax;
 }
 protected function _notifyText($subject, $body)
 {
     global $g_config;
     // Подготовка сообщения ошибки
     $msg = PHP_EOL . "Text notification:" . PHP_EOL . "\tsubject: {$subject}" . PHP_EOL . "\t{$body}" . PHP_EOL;
     // Запись ошибки в лог-файл
     $path = $g_config['logErrors']['logFile'];
     $fileLogger = FileLogger::Create($path);
     $fileLogger->Error($msg);
     // Вывод ошибки на экран
     if ($g_config['phpIni']['display_errors']) {
         echo "<pre>{$msg}</pre>";
     } else {
         IncludeCom('500');
     }
 }
Example #11
0
 public static function DbSimpleError($message, $info)
 {
     global $g_config;
     if (!error_reporting()) {
         return;
     }
     if ($info['query'] == "mysql_connect()") {
         exit("Can not connect to database(s)");
         // Не работаем дальше с кодом
     }
     static $fileLogger = NULL;
     if (is_null($fileLogger)) {
         $fileLogger = FileLogger::Create($g_config['dbSimple']['dbLogFile']);
     }
     $fileLogger->Error(PHP_EOL . "\tquery: " . $info['query'] . PHP_EOL . "\tmessage: " . $info['message'] . PHP_EOL . "\tcode: " . $info['code'] . PHP_EOL . "\tcontext: " . $info['context'] . PHP_EOL . PHP_EOL);
 }
Example #12
0
 function testFileLogger()
 {
     $sep = DIRECTORY_SEPARATOR;
     $fName = dirname(__FILE__) . $sep . 'data' . $sep . 'general.log';
     $this->fl = $logger = new FileLogger($fName, null, Logger::DEVEL);
     $logger->reset();
     $logger->devel('1');
     $logger->debug('2');
     $logger->info('3');
     $logger->warn('4');
     $logger->error('5');
     $len = filesize($fName);
     if ($len !== 161) {
         return "{$len} bytes instead of 161 bytes";
     }
     $len = strlen($logger->get());
     if ($len !== 161) {
         return "{$len} chars instead 161 chars";
     }
 }
 /**
  * Put Message to log file
  *
  * @param  $message (string) - message who need put to file
  * @param  $logFileName (string) - file name where put
  * @param  $logFilePath (string) - file location from PS ROOT
  * @return $this (mix) - this class
  */
 public static function log($message, $logFileName = 'dpd.log', $logFilePath = 'log')
 {
     $logger = new FileLogger(0);
     //0 == debug level, logDebug() won’t work without this.
     $logger->setFilename(_PS_ROOT_DIR_ . '/' . $logFilePath . '/' . $logFileName);
     $logger->logDebug(date('Y-m-d H:i:s') . ':' . $message);
     return __CLASS__;
 }
Example #14
0
require_once "MSALParser.php";
require_once "MSALDB.php";
$arrayOfLines = file("php://input");
if ($arrayOfLines) {
    //$fp = fopen("test.txt","w+");
    //fwrite($fp, $msal);
    //fclose($fp);
    try {
        $msal = MSALParser::parse($arrayOfLines, 0, count($arrayOfLines) - 1);
        MSALDB::saveMSAL($msal);
    } catch (MSALParserException $msalpe) {
        // kol kirilir yen icinde kalir
        FileLogger::ERROR($msalpe->getMessage());
    } catch (MSALDBException $msaldbe) {
        // kol kirilir yen icinde kalir
        FileLogger::ERROR($msaldbe->getMessage());
    }
}
/*
 * A NOTE:
 * 
 * in mlogc.conf;
 *    CollectorRoot "/var/log/mlogc"
 *    ConsoleURI "http://[serverip]/rpc/auditLogReceiver"
 *    LogStorageDir "data"  
 *    Keep 1
 * 
 * in modsecurity_crs_10_config.conf;
 *    SecAuditLogStorageDir /var/log/mlogc/data
 * 
 * Individual log files will be created and rest in;
Example #15
0
<?php

## Использование класса с деструктором.
require_once "File/Logger.php";
for ($n = 0; $n < 10; $n++) {
    $logger = new FileLogger("test{$n}", "test.log");
    $logger->log("Hello!");
    // Теперь нет необходимости заботиться о корректном
    // уничтожении объекта - PHP делает все сам!
}
exit;
Example #16
0
}
// need for upgrade before 1.5
if (!defined('__PS_BASE_URI__')) {
    define('__PS_BASE_URI__', str_replace('//', '/', '/' . trim(preg_replace('#/(install(-dev)?)$#', '/', str_replace('\\', '/', dirname($_SERVER['REQUEST_URI']))), '/') . '/'));
}
// need for upgrade before 1.5
if (!defined('_THEME_NAME_')) {
    define('_THEME_NAME_', 'default');
}
require_once dirname(__FILE__) . '/../init.php';
// set logger
require_once _PS_INSTALL_PATH_ . 'upgrade/classes/AbstractLogger.php';
eval('abstract class AbstractLogger extends AbstractLoggerCore{}');
require_once _PS_INSTALL_PATH_ . 'upgrade/classes/FileLogger.php';
eval('class FileLogger extends FileLoggerCore{}');
$logger = new FileLogger();
$logger->setFilename(_PS_ROOT_DIR_ . '/log/' . @date('Ymd') . '_upgrade.log');
if (function_exists('date_default_timezone_set')) {
    date_default_timezone_set('Europe/Paris');
}
// if _PS_ROOT_DIR_ is defined, use it instead of "guessing" the module dir.
if (defined('_PS_ROOT_DIR_') and !defined('_PS_MODULE_DIR_')) {
    define('_PS_MODULE_DIR_', _PS_ROOT_DIR_ . '/modules/');
} elseif (!defined('_PS_MODULE_DIR_')) {
    define('_PS_MODULE_DIR_', _PS_INSTALL_PATH_ . '/../modules/');
}
if (!defined('_PS_INSTALLER_PHP_UPGRADE_DIR_')) {
    define('_PS_INSTALLER_PHP_UPGRADE_DIR_', _PS_INSTALL_PATH_ . 'upgrade/php/');
}
if (!defined('_PS_INSTALLER_SQL_UPGRADE_DIR_')) {
    define('_PS_INSTALLER_SQL_UPGRADE_DIR_', _PS_INSTALL_PATH_ . 'upgrade/sql/');
Example #17
0
function croak(FileLogger $l, $msg)
{
    $l->log($msg);
    exit;
}
 public function testLogWriting()
 {
     $SofortLibLogger = new FileLogger();
     $this->assertTrue($SofortLibLogger->log('test', 'log'));
 }
 /**
  * 用户同步报告(默认汇总前一日)
  */
 public function actionEmailReport($startTime = false, $endTime = false)
 {
     list($startTime, $endTime) = $this->_getTime($startTime, $endTime, false);
     $ihmMobiles = [];
     $ihmUsers = Member::getByTime($startTime, $endTime);
     $dcUsers = UserBaseInfo::getByTime($startTime, $endTime);
     if (!$dcUsers) {
         die(date('Y-m-d H:i:s', $startTime) . ' 至 ' . date('Y-m-d H:i:s', $endTime) . " 暂无用户注册\n");
     }
     $msgData = ['<h3>' . date('Y-m-d H:i:s', $startTime) . ' 至 ' . date('Y-m-d H:i:s', $endTime) . "  iHeima用户注册情况</h3>"];
     $msgData[] = '<table cellpadding=\'5\' cellspacing=\'0\' style=\'border: 2px solid #EEE\'>';
     $msgData[] = '<tr style=\'background-color: #EEE;\'><td>手机号码</td><td>OPENID</td><td>同步状态</td></tr>';
     $stat = ['sync_ok' => 0, 'sync_fail' => 0, 'openid_incon' => 0, 'multi_openid' => 0];
     $ihmUsers = $this->_transform($ihmUsers);
     foreach ($dcUsers as $user) {
         $mobile = $user['mobile'];
         $openid = $user['open_id'];
         if (isset($ihmUsers[$mobile])) {
             if (is_array($ihmUsers[$mobile])) {
                 $msgData[] = '<tr><td>' . $mobile . '</td><td>' . $openid . '</td><td>存在多OPENID</td></tr>';
                 $stat['multi_openid']++;
             } else {
                 if ($ihmUsers[$mobile] == $user['open_id']) {
                     // $msgData[] = $mobile . '  (' . $openid . '): 同步无误';
                     $msgData[] = '<tr><td>' . $mobile . '</td><td>' . $openid . '</td><td>同步无误</td></tr>';
                     $stat['sync_ok']++;
                 } else {
                     // $msgData[] = $mobile . '  (' . $openid . '): OPENID不匹配';
                     $msgData[] = '<tr><td>' . $mobile . '</td><td>' . $openid . '</td><td>OPENID不匹配</td></tr>';
                     $stat['openid_incon']++;
                 }
             }
         } else {
             // $msgData[] = $mobile . '  (' . $openid . '): 不存在';
             $msgData[] = '<tr><td>' . $mobile . '</td><td>' . $openid . '</td><td>不存在</td></tr>';
             $stat['sync_fail']++;
         }
     }
     $msgData[] = '</tr></table>';
     $statMsg = ['<div>'];
     foreach ($stat as $key => $val) {
         $statMsg[] = $key . ':' . $val;
     }
     $statMsg[] = '</div>';
     //        echo implode("\n", $msgData) . "\n\n";
     //        echo implode("\t", $statMsg) . "\n\n";
     $email = Yii::$app->params['syncuser_notify_email'];
     $data = ['userID' => 0, 'to' => $email, 'appID' => '100000', 'business' => 'S_SYNCUSER_REPORT', 'tplno' => 6, 'subject' => '检测同步用户报告(' . date('Y-m-d', $startTime) . ')', 'msg' => implode('', $msgData) . implode('&nbsp;&nbsp;', $statMsg)];
     $sender = Yii::$app->mailer;
     $result = $sender->check($data, true);
     if (!$result[0]) {
         $result = $sender->exec($result[1]);
     } else {
         //邮箱发送失败记录到日志文件中
         FileLogger::getInstance(date('Ymd') . '_sync_user_report.log')->writeOne('邮箱发送失败', Logger::LEVEL_ERROR, 'report');
     }
 }
Example #20
0
<?php

$fileLog = new FileLogger('1.txt');
$fileLog->error('This is error');
$dbLog = new DbLogger('localhost', 'root', '', 'learning');
$dbLog->error('This is error');
Example #21
0
 protected function setupLogging()
 {
     if ($this->verbosity == 0) {
         L::setLogger(new NullLogger());
         return;
     }
     if ($this->log_file) {
         $logger = new FileLogger();
         $logger->setLogFile($this->log_file);
     } else {
         $logger = new ConsoleLogger();
     }
     L::setLogger($logger);
     L::setLevel($this->verbosity);
     L::setOverrides($this->override_verbosity);
 }
Example #22
0
        $this->time = microtime(true);
    }
    // Открытый метод, предназначенный для создания объектов класса.
    // Создать новый объект можно только с его помощью!
    public static function create($fname)
    {
        // Вначале проверяем: возможно, объект для указанного имени
        // файла уже существует? Тогда его и возвращаем.
        if (isset(self::$loggers[$fname])) {
            return self::$loggers[$fname];
        }
        // А иначе создаем полностью новый объект и сохраняем ссылку
        // на него в статическом массиве.
        return self::$loggers[$fname] = new self($fname);
    }
    // Возвращает время создания объекта.
    public function getTime()
    {
        return $this->time;
    }
}
// Пример использования класса.
#$logger = new FileLogger("a"); // Нельзя! Доступ закрыт!
$logger1 = FileLogger::create("file.log");
// ОК!
sleep(1);
// как будто бы программа немного поработала
$logger2 = FileLogger::create("file.log");
// ОК!
// Выводим времена создания обоих объектов.
echo "{$logger1->getTime()}, {$logger2->getTime()} ";
Example #23
0
 * Copyright (c) 2010 the Froxlor Team (see authors).
 *
 * For the full copyright and license information, please view the COPYING
 * file that was distributed with this source code. You can also view the
 * COPYING file online at http://files.froxlor.org/misc/COPYING.txt
 *
 * @copyright  (c) the authors
 * @author     Florian Lippert <flo@syscp.org> (2003-2009)
 * @author     Froxlor team <team@froxlor.org> (2010-)
 * @license    GPLv2 http://files.froxlor.org/misc/COPYING.txt
 * @package    Install
 *
 */
$updatelog = FroxlorLogger::getInstanceOf(array('loginname' => 'updater'));
$updatelogfile = validateUpdateLogFile(makeCorrectFile(dirname(__FILE__) . '/update.log'));
$filelog = FileLogger::getInstanceOf(array('loginname' => 'updater'));
$filelog->setLogFile($updatelogfile);
// if first writing does not work we'll stop, tell the user to fix it
// and then let him try again.
try {
    $filelog->logAction(ADM_ACTION, LOG_WARNING, '-------------- START LOG --------------');
} catch (Exception $e) {
    standard_error('exception', $e->getMessage());
}
/*
 * since froxlor, we have to check if there's still someone
 * out there using syscp and needs to upgrade
 */
if (!isFroxlor()) {
    /**
     * Upgrading SysCP to Froxlor-0.9
Example #24
0
 public function logAction($action = USR_ACTION, $type = LOG_NOTICE, $text = null)
 {
     if (self::$logtypes == null) {
         return;
     }
     if ($this->settings['logger']['log_cron'] == '0' && $action == CRON_ACTION) {
         return;
     }
     foreach (self::$logtypes as $logger) {
         switch ($logger) {
             case 'syslog':
                 $_log = SysLogger::getInstanceOf($this->userinfo, $this->settings);
                 break;
             case 'file':
                 try {
                     $_log = FileLogger::getInstanceOf($this->userinfo, $this->settings);
                 } catch (Exception $e) {
                     if ($action != CRON_ACTION) {
                         standard_error('logerror', $e->getMessage());
                     } else {
                         echo 'Log-Error: ' . $e->getMessage();
                     }
                 }
                 break;
             case 'mysql':
                 $_log = MysqlLogger::getInstanceOf($this->userinfo, $this->settings, $this->db);
                 break;
             default:
                 $_log = null;
                 break;
         }
         if ($_log != null) {
             try {
                 $_log->logAction($action, $type, $text);
             } catch (Exception $e) {
                 if ($action != CRON_ACTION) {
                     standard_error('logerror', $e->getMessage());
                 } else {
                     echo 'Log-Error: ' . $e->getMessage();
                 }
             }
         }
     }
 }
Example #25
0
 /**
  * Log the error on the disk
  */
 public function log($messages, $forceDebug = false)
 {
     $debugMode = $this->pfConfig->isDebugMode();
     if (!$debugMode && !$forceDebug) {
         return;
     }
     $logger = new FileLogger();
     $logger->setFilename($this->pfConfig->getLogFileDir());
     $logger->logError($messages);
 }
Example #26
0
 function __construct($scope)
 {
     parent::__construct(APP_ROOT . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . $scope . '.log');
 }
 /**
  * Log the error on the disk
  */
 protected function logError()
 {
     $logger = new FileLogger();
     $logger->setFilename(_PS_ROOT_DIR_ . '/log/' . date('Ymd') . '_exception.log');
     $logger->logError($this->getExtendedMessage(false));
 }
Example #28
0
$_SERVER['REQUEST_URI'] = str_replace('//', '/', $_SERVER['REQUEST_URI']);
define('INSTALL_VERSION', '1.4.7.0');
define('INSTALL_PATH', dirname(__FILE__));
define('PS_INSTALLATION_IN_PROGRESS', true);
require_once INSTALL_PATH . '/classes/ToolsInstall.php';
define('SETTINGS_FILE', INSTALL_PATH . '/../config/settings.inc.php');
define('DEFINES_FILE', INSTALL_PATH . '/../config/defines.inc.php');
define('INSTALLER__PS_BASE_URI', substr($_SERVER['REQUEST_URI'], 0, -1 * (strlen($_SERVER['REQUEST_URI']) - strrpos($_SERVER['REQUEST_URI'], '/')) - strlen(substr(dirname($_SERVER['REQUEST_URI']), strrpos(dirname($_SERVER['REQUEST_URI']), '/') + 1))));
define('INSTALLER__PS_BASE_URI_ABSOLUTE', 'http://' . ToolsInstall::getHttpHost(false, true) . INSTALLER__PS_BASE_URI);
// XML Header
header('Content-Type: text/xml');
// Switching method
if (isset($_GET['method'])) {
    if (in_array($_GET['method'], array('doUpgrade', 'createDB', 'checkShopInfos'))) {
        global $logger;
        $logger = new FileLogger();
        $logger->setFilename(dirname(__FILE__) . '/../log/' . @date('Ymd') . '_installation.log');
    }
    switch ($_GET['method']) {
        case 'checkConfig':
            require_once 'xml/checkConfig.php';
            break;
        case 'checkDB':
            require_once 'xml/checkDB.php';
            break;
        case 'createDB':
            require_once 'xml/createDB.php';
            break;
        case 'checkMail':
            require_once 'xml/checkMail.php';
            break;
 /**
  * model_doUpgrade prepare the call to doUpgrade.php file (like model.php)
  *
  * @return void
  */
 public function _modelDoUpgrade()
 {
     // a. set logger
     // it will be used later
     global $logger;
     $logger = new FileLogger();
     if (function_exists('date_default_timezone_set')) {
         date_default_timezone_set('Europe/Paris');
     }
     // use autoupgrade as log dir
     $logger->setFilename($this->latestRootDir . '/' . date('Ymd') . '_autoupgrade.log');
     // init env.
     @set_time_limit(0);
     @ini_set('max_execution_time', '0');
     // setting the memory limit to 128M only if current is lower
     $memory_limit = ini_get('memory_limit');
     if (substr($memory_limit, -1) != 'G' and (substr($memory_limit, -1) == 'M' and substr($memory_limit, 0, -1) < 128 or is_numeric($memory_limit) and intval($memory_limit) < 131072)) {
         @ini_set('memory_limit', '128M');
     }
     /* Redefine REQUEST_URI if empty (on some webservers...) */
     if (!isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI'] == '') {
         $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'];
     }
     if ($tmp = strpos($_SERVER['REQUEST_URI'], '?')) {
         $_SERVER['REQUEST_URI'] = substr($_SERVER['REQUEST_URI'], 0, $tmp);
     }
     $_SERVER['REQUEST_URI'] = str_replace('//', '/', $_SERVER['REQUEST_URI']);
     ///////////////////////
     // Copy from model.php
     ///////////////////////
     $upgrader = $this->upgrader;
     $upgrader->checkPSVersion();
     define('INSTALL_VERSION', $upgrader->version_num);
     // now the install dir to use is in a subdirectory of the admin dir
     define('INSTALL_PATH', realpath($this->latestRootDir . DIRECTORY_SEPARATOR . 'install'));
     define('PS_INSTALLATION_IN_PROGRESS', true);
     // Note : we don't need ToolsInstall.php
     // include_once(INSTALL_PATH.'/classes/ToolsInstall.php');
     define('SETTINGS_FILE', $this->prodRootDir . '/config/settings.inc.php');
     define('DEFINES_FILE', $this->prodRootDir . '/config/defines.inc.php');
     define('INSTALLER__PS_BASE_URI', substr($_SERVER['REQUEST_URI'], 0, -1 * (strlen($_SERVER['REQUEST_URI']) - strrpos($_SERVER['REQUEST_URI'], '/')) - strlen(substr(dirname($_SERVER['REQUEST_URI']), strrpos(dirname($_SERVER['REQUEST_URI']), '/') + 1))));
     // Note : INSTALLER__PS_BASE_URI_ABSOLUTE is not used for upgrade
     // define('INSTALLER__PS_BASE_URI_ABSOLUTE', 'http://'.ToolsInstall::getHttpHost(false, true).INSTALLER__PS_BASE_URI);
     // XML Header
     header('Content-Type: text/xml');
     require_once INSTALL_PATH . DIRECTORY_SEPARATOR . 'xml' . DIRECTORY_SEPARATOR . 'doUpgrade.php';
     //////////////////////////////
     // End of copy from model.php
     //////////////////////////////
 }
Example #30
-1
 public static function parse(&$lines)
 {
     // the allmighty "ModSecurity Single Audit Log" object
     $msal = new MSAL();
     FileLogger::INFO("MSAL Parsing Started");
     // initialize indexes that point to start and end of a audit log part
     // should the single log starts with empty lines, then we have to eat them
     $startIndex = 0;
     while (preg_match(MSALParser::EMPTY_LINE_PATTERN, $lines[$startIndex])) {
         $startIndex += 1;
     }
     $endIndex = count($lines) - 1;
     // a simple error checking
     if ($startIndex >= $endIndex) {
         throw new MSALParserException("MSAL erroneous audit log (all empty lines or a single line)");
     }
     while (($boundaryLetter = MSALParser::readTillNextBoundary($lines, $startIndex, $endIndex)) != '!') {
         switch ($boundaryLetter) {
             case 'A':
                 FileLogger::INFO("MSAL Parsing part A");
                 $msalHeader = MSALHeaderParser::parse($lines, $startIndex, $endIndex);
                 $msal->setMSALHeader($msalHeader);
                 break;
             case 'B':
                 FileLogger::INFO("MSAL Parsing part B");
                 $msalRequestHeaders = MSALRequestHeadersParser::parse($lines, $startIndex, $endIndex);
                 $msal->setMSALRequestHeaders($msalRequestHeaders);
                 break;
             case 'C':
                 FileLogger::INFO("MSAL Parsing part C");
                 $msalRequestBody = MSALRequestBodyParser::parse($lines, $startIndex, $endIndex);
                 $msal->setMSALRequestBody($msalRequestBody);
                 break;
             case 'F':
                 FileLogger::INFO("MSAL Parsing part F");
                 $msalResponseHeaders = MSALResponseHeadersParser::parse($lines, $startIndex, $endIndex);
                 $msal->setMSALResponseHeaders($msalResponseHeaders);
                 break;
             case 'E':
                 FileLogger::INFO("MSAL Parsing part E");
                 $msalResponseBody = MSALResponseBodyParser::parse($lines, $startIndex, $endIndex);
                 $msal->setMSALResponseBody($msalResponseBody);
                 break;
             case 'H':
                 FileLogger::INFO("MSAL Parsing part H");
                 $msalTrailer = MSALTrailerParser::parse($lines, $startIndex, $endIndex);
                 $msal->setMSALTrailer($msalTrailer);
                 break;
             case 'Z':
                 FileLogger::INFO("MSAL Parsing part Z");
                 break;
             default:
                 // throw an error, an unexpected log part letter is read!
                 throw new MSALParserException("An undefined log boundary specified : " . $boundaryLetter);
                 break;
         }
         // why $endIndex + 1 ?
         // because $endIndex points to a line just before the next boundary
         $startIndex = $endIndex + 1;
         // reset the endIndex
         $endIndex = count($lines) - 1;
         // a simple eof checking
         // should we check boundary Z? not now.
         if ($startIndex > $endIndex) {
             FileLogger::INFO("MSAL Parsing Finished");
             break;
         }
     }
     return $msal;
 }