diff options
author | Matthieu Aubry <matt@piwik.org> | 2013-09-28 07:05:34 +0400 |
---|---|---|
committer | Matthieu Aubry <matt@piwik.org> | 2013-09-28 07:05:34 +0400 |
commit | 9e9b3cbd3c56e0aabe0e8b08456381daab984481 (patch) | |
tree | e3b14c2f6b87283ada922114b903c8ceaa1d09a7 | |
parent | cb5f723e88eec5f75b65a15eeecfb6ed817b6f44 (diff) | |
parent | 729ffe8bfe5b6f6db70ba52209704486d696ad5a (diff) |
Merge pull request #110 from piwik/log
Rewrite logging in Piwik and remove Zend_Log
goal: logging easily reusable by plugin developers. The next step will be to allow developers to easily view the logs, Log Viewer UI is in http://dev.piwik.org/trac/ticket/2473 (would be useful to view eg. archive.php frequency&exec times)
53 files changed, 1042 insertions, 4026 deletions
diff --git a/config/global.ini.php b/config/global.ini.php index 8958b464ee..acfd06f306 100644 --- a/config/global.ini.php +++ b/config/global.ini.php @@ -469,11 +469,13 @@ username = ; Proxy username: optional; if specified, password is mandatory password = ; Proxy password: optional; if specified, username is mandatory [log] -;possible values for log: screen, database, file -; by default, standard logging/debug messages are hidden from screen -;logger_message[] = screen -logger_error[] = screen -logger_exception[] = screen +; possible values for log: screen, database, file +log_writers[] = file + +; log level, everything logged w/ this level or one of greater severity +; will be logged. everything else will be ignored. possible values are: +; NONE, ERROR, WARN, INFO, DEBUG, VERBOSE +log_level = WARN ; if set to 1, only requests done in CLI mode (eg. the archive.php cron run) will be logged ; NOTE: log_only_when_debug_parameter will also be checked for @@ -487,10 +489,6 @@ log_only_when_debug_parameter = 0 ; eg. if the value is tmp/logs files will be created in /path/to/piwik/tmp/logs/ logger_file_path = tmp/logs -; all calls to the API (method name, parameters, execution time, caller IP, etc.) -; disabled by default as it can cause serious overhead and should only be used wisely -;logger_api_call[] = file - [Plugins] Plugins[] = CorePluginsAdmin Plugins[] = CoreAdminHome diff --git a/core/Db/Schema/Myisam.php b/core/Db/Schema/Myisam.php index 58430ff071..f9dc5faa1a 100644 --- a/core/Db/Schema/Myisam.php +++ b/core/Db/Schema/Myisam.php @@ -127,7 +127,9 @@ class Myisam implements SchemaInterface 'logger_message' => "CREATE TABLE {$prefixTables}logger_message ( idlogger_message INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, + tag VARCHAR(50) NULL, timestamp TIMESTAMP NULL, + level TINYINT NULL, message TEXT NULL, PRIMARY KEY(idlogger_message) ) DEFAULT CHARSET=utf8 diff --git a/core/Error.php b/core/Error.php new file mode 100644 index 0000000000..b186cdd731 --- /dev/null +++ b/core/Error.php @@ -0,0 +1,225 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * + * @category Piwik + * @package Piwik + */ +namespace Piwik; + +use Piwik\Log; +use Piwik\Version; + +/** + * Holds PHP error information (non-exception errors). Also contains log formatting logic + * for PHP errors and Piwik's error handler function. + */ +class Error +{ + /** + * The backtrace string to use when testing. + * + * @var string + */ + public static $debugBacktraceForTests = null; + + /** + * The error number. See http://php.net/manual/en/errorfunc.constants.php#errorfunc.constants.errorlevels + * + * @var int + */ + public $errno; + + /** + * The error message. + * + * @var string + */ + public $errstr; + + /** + * The file in which the error occurred. + * + * @var string + */ + public $errfile; + + /** + * The line number on which the error occurred. + * + * @var int + */ + public $errline; + + /** + * The error backtrace. + * + * @var string + */ + public $backtrace; + + /** + * Constructor. + * + * @param int $errno + * @param string $errstr + * @param string $errfile + * @param int $errline + * @param string $backtrace + */ + public function __construct($errno, $errstr, $errfile, $errline, $backtrace) + { + $this->errno = $errno; + $this->errstr = $errstr; + $this->errfile = $errfile; + $this->errline = $errline; + $this->backtrace = $backtrace; + } + + public function getErrNoString() + { + switch ($this->errno) { + case E_ERROR: + return "Error"; + case E_WARNING: + return "Warning"; + case E_PARSE: + return "Parse Error"; + case E_NOTICE: + return "Notice"; + case E_CORE_ERROR: + return "Core Error"; + case E_CORE_WARNING: + return "Core Warning"; + case E_COMPILE_ERROR: + return "Compile Error"; + case E_COMPILE_WARNING: + return "Compile Warning"; + case E_USER_ERROR: + return "User Error"; + case E_USER_WARNING: + return "User Warning"; + case E_USER_NOTICE: + return "User Notice"; + case E_STRICT: + return "Strict Notice"; + case E_RECOVERABLE_ERROR: + return "Recoverable Error"; + case E_DEPRECATED: + return "Deprecated"; + case E_USER_DEPRECATED: + return "User Deprecated"; + default: + return "Unknown error ({$this->errno})"; + } + } + + public static function formatFileAndDBLogMessage(&$message, $level, $tag, $datetime, $log) + { + if ($message instanceof Error) { + $message = $message->errfile . '(' . $message->errline . '): ' . $message->getErrNoString() + . ' - ' . $message->errstr . "\n" . $message->backtrace; + + $message = $log->formatMessage($level, $tag, $datetime, $message); + } + } + + public static function formatScreenMessage(&$message, $level, $tag, $datetime, $log) + { + if ($message instanceof Error) { + $errno = $message->errno & error_reporting(); + + // problem when using error_reporting with the @ silent fail operator + // it gives an errno 0, and in this case the objective is to NOT display anything on the screen! + // is there any other case where the errno is zero at this point? + if ($errno == 0) { + $message = false; + return; + } + + if (!Common::isPhpCliMode()) { + @header('Content-Type: text/html; charset=utf-8'); + } + + $htmlString = ''; + $htmlString .= "\n<div style='word-wrap: break-word; border: 3px solid red; padding:4px; width:70%; background-color:#FFFF96;'> + <strong>There is an error. Please report the message (Piwik " . (class_exists('Piwik\Version') ? Version::VERSION : '') . ") + and full backtrace in the <a href='?module=Proxy&action=redirect&url=http://forum.piwik.org' target='_blank'>Piwik forums</a> (please do a Search first as it might have been reported already!).<br /><br/> + "; + $htmlString .= $message->getErrNoString(); + $htmlString .= ":</strong> <em>{$message->errstr}</em> in <strong>{$message->errfile}</strong>"; + $htmlString .= " on line <strong>{$message->errline}</strong>\n"; + $htmlString .= "<br /><br />Backtrace --><div style=\"font-family:Courier;font-size:10pt\"><br />\n"; + $htmlString .= str_replace("\n", "<br />\n", $message->backtrace); + $htmlString .= "</div><br />"; + $htmlString .= "\n </pre></div><br />"; + + $message = $htmlString; + } + } + + public static function setErrorHandler() + { + Piwik_AddAction('Log.formatFileMessage', array('\\Piwik\\Error', 'formatFileAndDBLogMessage')); + Piwik_AddAction('Log.formatDatabaseMessage', array('\\Piwik\\Error', 'formatFileAndDBLogMessage')); + Piwik_AddAction('Log.formatScreenMessage', array('\\Piwik\\Error', 'formatScreenMessage')); + + set_error_handler(array('\\Piwik\\Error', 'errorHandler')); + } + + public static function errorHandler($errno, $errstr, $errfile, $errline) + { + // if the error has been suppressed by the @ we don't handle the error + if (error_reporting() == 0) { + return; + } + + $backtrace = ''; + if (empty(self::$debugBacktraceForTests)) { + $bt = @debug_backtrace(); + if ($bt !== null && isset($bt[0])) { + foreach ($bt as $i => $debug) { + $backtrace .= "#$i " + . (isset($debug['class']) ? $debug['class'] : '') + . (isset($debug['type']) ? $debug['type'] : '') + . (isset($debug['function']) ? $debug['function'] : '') + . '(...) called at [' + . (isset($debug['file']) ? $debug['file'] : '') . ':' + . (isset($debug['line']) ? $debug['line'] : '') . ']' . "\n"; + } + } + } else { + $backtrace = self::$debugBacktraceForTests; + } + + $error = new Error($errno, $errstr, $errfile, $errline, $backtrace); + Log::error($error); + + switch ($errno) { + case E_ERROR: + case E_PARSE: + case E_CORE_ERROR: + case E_CORE_WARNING: + case E_COMPILE_ERROR: + case E_COMPILE_WARNING: + case E_USER_ERROR: + exit; + break; + + case E_WARNING: + case E_NOTICE: + case E_USER_WARNING: + case E_USER_NOTICE: + case E_STRICT: + case E_RECOVERABLE_ERROR: + case E_DEPRECATED: + case E_USER_DEPRECATED: + default: + // do not exit + break; + } + } +}
\ No newline at end of file diff --git a/core/ErrorHandler.php b/core/ErrorHandler.php deleted file mode 100644 index 963d46e3f6..0000000000 --- a/core/ErrorHandler.php +++ /dev/null @@ -1,79 +0,0 @@ -<?php -/** - * Piwik - Open source web analytics - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - * - * @category Piwik - * @package Piwik - */ - -/** - * Error handler used to display nicely errors in Piwik - * - * @param int $errno Error number - * @param string $errstr Error message - * @param string $errfile File name - * @param int $errline Line number - * @return void - */ -function Piwik_ErrorHandler($errno, $errstr, $errfile, $errline) -{ - // if the error has been suppressed by the @ we don't handle the error - if (error_reporting() == 0) { - return; - } - - if (function_exists('debug_backtrace')) { - $backtrace = ''; - $bt = @debug_backtrace(); - if ($bt !== null && isset($bt[0])) { - foreach ($bt as $i => $debug) { - $backtrace .= "#$i " - . (isset($debug['class']) ? $debug['class'] : '') - . (isset($debug['type']) ? $debug['type'] : '') - . (isset($debug['function']) ? $debug['function'] : '') - . '(...) called at [' - . (isset($debug['file']) ? $debug['file'] : '') . ':' - . (isset($debug['line']) ? $debug['line'] : '') . ']' . "\n"; - } - } - } else { - ob_start(); - @debug_print_backtrace(); - $backtrace = ob_get_contents(); - ob_end_clean(); - } - - try { - \Zend_Registry::get('logger_error')->logEvent($errno, $errstr, $errfile, $errline, $backtrace); - } catch (Exception $e) { - // in case the error occurs before the logger creation, we simply display it - print("<pre>$errstr \nin '$errfile' at the line $errline\n\n$backtrace\n</pre>"); - exit; - } - switch ($errno) { - case E_ERROR: - case E_PARSE: - case E_CORE_ERROR: - case E_CORE_WARNING: - case E_COMPILE_ERROR: - case E_COMPILE_WARNING: - case E_USER_ERROR: - exit; - break; - - case E_WARNING: - case E_NOTICE: - case E_USER_WARNING: - case E_USER_NOTICE: - case E_STRICT: - case E_RECOVERABLE_ERROR: - case E_DEPRECATED: - case E_USER_DEPRECATED: - default: - // do not exit - break; - } -} diff --git a/core/ExceptionHandler.php b/core/ExceptionHandler.php index c6d4f1d22b..081e4601a8 100644 --- a/core/ExceptionHandler.php +++ b/core/ExceptionHandler.php @@ -8,41 +8,62 @@ * @category Piwik * @package Piwik */ +namespace Piwik; + +use Piwik\Common; use Piwik\Piwik; +use Piwik\Plugin; use Piwik\Log; -use Piwik\Log\ExceptionScreenFormatter; use Piwik\FrontController; +use Piwik\API\ResponseBuilder; /** - * Exception handler used to display nicely exceptions in Piwik - * - * @param Exception $exception - * @throws Exception + * Contains Piwik's uncaught exception handler and log file formatting for exception + * instances. */ -function Piwik_ExceptionHandler(Exception $exception) +class ExceptionHandler { - try { - \Zend_Registry::get('logger_exception')->logEvent($exception); - } catch (Exception $e) { + /** + * The backtrace string to use when testing. + * + * @var string + */ + public static $debugBacktraceForTests = null; - if (FrontController::shouldRethrowException()) { - throw $exception; - } + public static function setUp() + { + Piwik_AddAction('Log.formatFileMessage', array('\\Piwik\\ExceptionHandler', 'formatFileAndDBLogMessage')); + Piwik_AddAction('Log.formatDatabaseMessage', array('\\Piwik\\ExceptionHandler', 'formatFileAndDBLogMessage')); + Piwik_AddAction('Log.formatScreenMessage', array('\\Piwik\\ExceptionHandler', 'formatScreenMessage')); + + set_exception_handler(array('\\Piwik\\ExceptionHandler', 'exceptionHandler')); + } - // case when the exception is raised before the logger being ready - // we handle the exception a la mano, but using the Logger formatting properties - $event = array(); - $event['errno'] = $exception->getCode(); - $event['message'] = $exception->getMessage(); - $event['errfile'] = $exception->getFile(); - $event['errline'] = $exception->getLine(); - $event['backtrace'] = $exception->getTraceAsString(); + public static function formatFileAndDBLogMessage(&$message, $level, $tag, $datetime, $log) + { + if ($message instanceof \Exception) { + $message = sprintf("%s(%d): %s\n%s", $message->getFile(), $message->getLine(), $message->getMessage(), + self::$debugBacktraceForTests ?: $message->getTraceAsString()); - $formatter = new ExceptionScreenFormatter(); + $message = $log->formatMessage($level, $tag, $datetime, $message); + } + } + + public static function formatScreenMessage(&$message, $level, $tag, $datetime, $log) + { + if ($message instanceof \Exception) { + if (!Common::isPhpCliMode()) { + @header('Content-Type: text/html; charset=utf-8'); + } - $message = $formatter->format($event); - $message .= "<br /><br />And this exception raised another exception \"" . $e->getMessage() . "\""; + $outputFormat = strtolower(Common::getRequestVar('format', 'html', 'string')); + $response = new ResponseBuilder($outputFormat); + $message = $response->getResponseException(new \Exception($message->getMessage())); + } + } - Piwik::exitWithErrorMessage($message); + public static function exceptionHandler(Exception $exception) + { + Log::error($exception); } -} +}
\ No newline at end of file diff --git a/core/FrontController.php b/core/FrontController.php index 89aaefd9ef..a97337e97d 100644 --- a/core/FrontController.php +++ b/core/FrontController.php @@ -13,7 +13,6 @@ namespace Piwik; use Exception; use Piwik\API\Request; use Piwik\API\ResponseBuilder; -use Piwik\Log; use Piwik\Session; use Zend_Registry; @@ -268,8 +267,6 @@ class FrontController throw $e; } - Log::make(); - // Init the Access object, so that eg. core/Updates/* can enforce Super User and use some APIs Access::getInstance(); diff --git a/core/Log.php b/core/Log.php index bb2b624ee3..06755e41de 100644 --- a/core/Log.php +++ b/core/Log.php @@ -10,196 +10,460 @@ */ namespace Piwik; -use Piwik\Log\APICall; -use Piwik\Log\Error; -use Piwik\Log\Exception; -use Piwik\Log\Message; +use Piwik\Common; +use Piwik\Db; /** - * - * @package Piwik - * @subpackage Log - * @see Zend_Log, libs/Zend/Log.php - * @link http://framework.zend.com/manual/en/zend.log.html + * Logging utility. + * + * You can log messages using one of the public static functions (eg, 'error', 'warning', + * 'info', etc.). + * + * Currently, Piwik supports the following logging backends: + * - logging to the screen + * - logging to a file + * - logging to a database + * + * The logging utility can be configured by manipulating the INI config options in the + * [log] section. */ -abstract class Log extends \Zend_Log +class Log { - protected $logToDatabaseTableName = null; - protected $logToDatabaseColumnMapping = null; - protected $logToFileFilename = null; - protected $fileFormatter = null; - protected $screenFormatter = null; - protected $currentRequestKey; + // log levels + const NONE = 0; + const ERROR = 1; + const WARN = 2; + const INFO = 3; + const DEBUG = 4; + const VERBOSE = 5; + + // config option names + const LOG_LEVEL_CONFIG_OPTION = 'log_level'; + const LOG_WRITERS_CONFIG_OPTION = 'log_writers'; + const LOGGER_FILE_PATH_CONFIG_OPTION = 'logger_file_path'; + const STRING_MESSAGE_FORMAT_OPTION = 'string_message_format'; /** - * @param string $logToFileFilename filename of logfile - * @param \Zend_Log_Formatter_Interface $fileFormatter - * @param \Zend_Log_Formatter_Interface $screenFormatter - * @param string $logToDatabaseTableName - * @param array $logToDatabaseColumnMapping + * This event is called when trying to log an object to a file. Plugins can use + * this event to convert objects to strings before they are logged. + * + * Callback signature: function (&$message, $level, $tag, $datetime, $logger) + * + * The $message parameter is the object that is being logged. Event handlers should + * check if the object is of a certain type and if it is, set $message to the + * string that should be logged. */ - function __construct($logToFileFilename, - $fileFormatter, - $screenFormatter, - $logToDatabaseTableName, - $logToDatabaseColumnMapping) - { - parent::__construct(); + const FORMAT_FILE_MESSAGE_EVENT = 'Log.formatFileMessage'; + + /** + * This event is called when trying to log an object to the screen. Plugins can use + * this event to convert objects to strings before they are logged. + * + * Callback signature: function (&$message, $level, $tag, $datetiem, $logger) + * + * The $message parameter is the object that is being logged. Event handlers should + * check if the object is of a certain type and if it is, set $message to the + * string that should be logged. + * + * The result of this callback can be HTML so no sanitization is done on the result. + * This means YOU MUST SANITIZE THE MESSAGE YOURSELF if you use this event. + */ + const FORMAT_SCREEN_MESSAGE_EVENT = 'Log.formatScreenMessage'; + + /** + * This event is called when trying to log an object to a database table. Plugins can use + * this event to convert objects to strings before they are logged. + * + * Callback signature: function (&$message, $level, $tag, $datetiem, $logger) + * + * The $message parameter is the object that is being logged. Event handlers should + * check if the object is of a certain type and if it is, set $message to the + * string that should be logged. + */ + const FORMAT_DATABASE_MESSAGE_EVENT = 'Log.formatDatabaseMessage'; - $this->currentRequestKey = substr(Common::generateUniqId(), 0, 8); + /** + * The singleton Log instance. + * + * @var Log + */ + private static $instance = null; - $log_dir = Config::getInstance()->log['logger_file_path']; - if ($log_dir[0] != '/' && $log_dir[0] != DIRECTORY_SEPARATOR) { - $log_dir = PIWIK_USER_PATH . '/' . $log_dir; + /** + * Returns the singleton Log instance or creates it if it doesn't exist. + * + * @return Log + */ + public static function getInstance() + { + if (self::$instance === null) { + self::$instance = new Log(); } - $this->logToFileFilename = $log_dir . '/' . $logToFileFilename; + return self::$instance; + } - $this->fileFormatter = $fileFormatter; - $this->screenFormatter = $screenFormatter; - $this->logToDatabaseTableName = Common::prefixTable($logToDatabaseTableName); - $this->logToDatabaseColumnMapping = $logToDatabaseColumnMapping; + /** + * Unsets the singleton instance so it will be re-created the next time getInstance() is + * called. For testing purposes only. + */ + public static function clearInstance() + { + self::$instance = null; } - function addWriteToFile() + /** + * The current logging level. Everything of equal or greater priority will be logged. + * Everything else will be ignored. + * + * @var int + */ + private $currentLogLevel = self::WARN; + + /** + * The array of callbacks executed when logging to a file. Each callback writes a log + * message to a logging backend. + * + * @var array + */ + private $writers = array(); + + /** + * The log message format string that turns a tag name, date-time and message into + * one string to log. + * + * @var string + */ + private $logMessageFormat = "[%tag%:%datetime%] %message%"; + + /** + * If we're logging to a file, this is the path to the file to log to. + * + * @var string + */ + private $logToFilePath; + + /** + * True if we're currently setup to log to a screen, false if otherwise. + * + * @var bool + */ + private $loggingToScreen; + + /** + * Constructor. + */ + private function __construct() { - Filesystem::mkdir(dirname($this->logToFileFilename)); - $writerFile = new \Zend_Log_Writer_Stream($this->logToFileFilename); - $writerFile->setFormatter($this->fileFormatter); - $this->addWriter($writerFile); + $logConfig = Config::getInstance()->log; + $this->setCurrentLogLevelFromConfig($logConfig); + $this->setLogWritersFromConfig($logConfig); + $this->setLogFilePathFromConfig($logConfig); + $this->setStringLogMessageFormat($logConfig); + $this->disableLoggingBasedOnConfig($logConfig); } - function addWriteToNull() + /** + * Logs a message using the ERROR log level. + * + * Note: Messages logged with the ERROR level are always logged to the screen in addition + * to configured writers. + * + * @param string $message The log message. This can be a sprintf format string. + * @param ... mixed Optional sprintf params. + */ + public static function error($message /* ... */) { - $this->addWriter(new \Zend_Log_Writer_Null); + self::log(self::ERROR, $message, array_slice(func_get_args(), 1)); } - function addWriteToDatabase() + /** + * Logs a message using the WARNING log level. + * + * @param string $message The log message. This can be a sprintf format string. + * @param ... mixed Optional sprintf params. + */ + public static function warning($message /* ... */) { - $writerDb = new \Zend_Log_Writer_Db( - Db::get(), - $this->logToDatabaseTableName, - $this->logToDatabaseColumnMapping); + self::log(self::WARN, $message, array_slice(func_get_args(), 1)); + } - $this->addWriter($writerDb); + /** + * Logs a message using the INFO log level. + * + * @param string $message The log message. This can be a sprintf format string. + * @param ... mixed Optional sprintf params. + */ + public static function info($message /* ... */) + { + self::log(self::INFO, $message, array_slice(func_get_args(), 1)); } - function addWriteToScreen() + /** + * Logs a message using the DEBUG log level. + * + * @param string $message The log message. This can be a sprintf format string. + * @param ... mixed Optional sprintf params. + */ + public static function debug($message /* ... */) { - $writerScreen = new \Zend_Log_Writer_Stream('php://output'); - $writerScreen->setFormatter($this->screenFormatter); - $this->addWriter($writerScreen); + self::log(self::DEBUG, $message, array_slice(func_get_args(), 1)); } - public function getWritersCount() + /** + * Logs a message using the VERBOSE log level. + * + * @param string $message The log message. This can be a sprintf format string. + * @param ... mixed Optional sprintf params. + */ + public static function verbose($message /* ... */) { - return count($this->_writers); + self::log(self::VERBOSE, $message, array_slice(func_get_args(), 1)); } /** - * Log an event - * @param string $event - * @param int $priority - * @param null $extras - * @throws \Zend_Log_Exception - * @return void + * Creates log message combining logging info including a log level, tag name, + * date time, and caller provided log message. The log message can be set through + * the string_message_format ini option in the [log] section. By default it will + * create log messages like: + * + * [tag:datetime] log message + * + * @param int $level + * @param string $tag + * @param string $datetime + * @param string $message + * @return string */ - public function log($event, $priority, $extras = null) + public function formatMessage($level, $tag, $datetime, $message) { - // sanity checks - if (empty($this->_writers)) { - throw new \Zend_Log_Exception('No writers were added'); - } + return str_replace( + array("%tag%", "%message%", "%datetime%", "%level%"), + array($tag, $message, $datetime, $this->getStringLevel($level)), + $this->logMessageFormat + ); + } - $event['timestamp'] = date('Y-m-d H:i:s'); - $event['requestKey'] = $this->currentRequestKey; - // pack into event required by filters and writers - $event = array_merge($event, $this->_extras); + private function setLogWritersFromConfig($logConfig) + { + // set the log writers + $logWriters = $logConfig[self::LOG_WRITERS_CONFIG_OPTION]; - // one message must stay on one line - if (isset($event['message'])) { - $event['message'] = str_replace(array(PHP_EOL, "\n"), " ", $event['message']); - } + $logWriters = array_map('trim', $logWriters); + foreach ($logWriters as $writerName) { + $writer = $this->createWriterByName($writerName); + if (!empty($writer)) { + $this->writers[] = $writer; + } - // Truncate the backtrace which can be too long to display in the browser - if (!empty($event['backtrace'])) { - $maxSizeOutputBytes = 1024 * 1024; // no more than 1M output please - $truncateBacktraceLineAfter = 1000; - $maxLines = ceil($maxSizeOutputBytes / $truncateBacktraceLineAfter); - $bt = explode("\n", $event['backtrace']); - foreach ($bt as $count => &$line) { - if (strlen($line) > $truncateBacktraceLineAfter) { - $line = substr($line, 0, $truncateBacktraceLineAfter) . '...'; - } - if ($count > $maxLines) { - $line .= "\nTruncated error message."; - break; - } + if ($writerName == 'screen') { + $this->loggingToScreen = true; } - $event['backtrace'] = implode("\n", $bt); } - // abort if rejected by the global filters - foreach ($this->_filters as $filter) { - if (!$filter->accept($event)) { - return; + } + + private function setCurrentLogLevelFromConfig($logConfig) + { + if (!empty($logConfig[self::LOG_LEVEL_CONFIG_OPTION])) { + $logLevel = $this->getLogLevelFromStringName(self::LOG_LEVEL_CONFIG_OPTION); + + if ($logLevel >= self::NONE // sanity check + && $logLevel <= self::VERBOSE + ) { + $this->currentLogLevel = $logLevel; } } + } - // send to each writer - foreach ($this->_writers as $writer) { - $writer->write($event); + private function setStringLogMessageFormat($logConfig) + { + if (isset($logConfig['string_message_format'])) { + $this->logMessageFormat = $logConfig['string_message_format']; } } + private function setLogFilePathFromConfig($logConfig) + { + $logPath = $logConfig[self::LOGGER_FILE_PATH_CONFIG_OPTION]; + if ($logPath[0] != '/' && $logPath[0] != DIRECTORY_SEPARATOR) { + $logPath = PIWIK_USER_PATH . '/' . $logPath; + } + if (is_dir($logPath)) { + $logPath .= '/piwik.log'; + } + $this->logToFilePath = $logPath; + } - /** - * Create log object - * @throws Exception - */ - static public function make() + private function createWriterByName($writerName) { - $configAPI = Config::getInstance()->log; + $writer = false; + if ($writerName == 'file') { + $writer = array($this, 'logToFile'); + } else if ($writerName == 'screen') { + $writer = array($this, 'logToScreen'); + } else if ($writerName == 'database') { + $writer = array($this, 'logToDatabase'); + } + return $writer; + } - /** @var Log[] $aLoggers */ - $aLoggers = array( - 'logger_api_call' => new APICall, - 'logger_exception' => new Exception, - 'logger_error' => new Error, - 'logger_message' => new Message, - ); + private function logToFile($level, $tag, $datetime, $message) + { + if (is_string($message)) { + $message = $this->formatMessage($level, $tag, $datetime, $message); + } else { + Piwik_PostEvent(self::FORMAT_FILE_MESSAGE_EVENT, array(&$message, $level, $tag, $datetime, $this)); + } - foreach ($configAPI as $loggerType => $aRecordTo) { - if (isset($aLoggers[$loggerType])) { - $logger = $aLoggers[$loggerType]; - - foreach ($aRecordTo as $recordTo) { - switch ($recordTo) { - case 'screen': - $logger->addWriteToScreen(); - break; - - case 'database': - $logger->addWriteToDatabase(); - break; - - case 'file': - $logger->addWriteToFile(); - break; - - default: - throw new \Exception("'$recordTo' is not a valid Log type. Valid logger types are: screen, database, file."); - break; - } - } - } + if (empty($message)) { + return; + } + + file_put_contents($this->logToFilePath, $message . "\n", FILE_APPEND); + } + + private function logToScreen($level, $tag, $datetime, $message) + { + if (is_string($message)) { + $message = Common::sanitizeInputValue($this->formatMessage($level, $tag, $datetime, $message)); + $message = '<pre>' . $message . '</pre>'; + } else { + Piwik_PostEvent(self::FORMAT_SCREEN_MESSAGE_EVENT, array(&$message, $level, $tag, $datetime, $this)); + } + + if (empty($message)) { + return; } - foreach ($aLoggers as $loggerType => $logger) { - if ($logger->getWritersCount() == 0) { - $logger->addWriteToNull(); + echo $message . "\n"; + } + + private function logToDatabase($level, $tag, $datetime, $message) + { + if (is_string($message)) { + $message = $this->formatMessage($level, $tag, $datetime, $message); + } else { + Piwik_PostEvent(self::FORMAT_DATABASE_MESSAGE_EVENT, array(&$message, $level, $tag, $datetime, $this)); + } + + if (empty($message)) { + return; + } + + $sql = "INSERT INTO " . Common::prefixTable('logger_message') + . " (tag, timestamp, level, message)" + . " VALUES (?, ?, ?, ?)"; + Db::query($sql, array($tag, $datetime, $level, (string)$message)); + } + + private function doLog($level, $message, $sprintfParams = array()) + { + if ($this->shouldLoggerLog($level)) { + $datetime = date("Y-m-d H:i:s"); + if (is_string($message) + && !empty($sprintfParams) + ) { + $message = vsprintf($message, $sprintfParams); } - \Zend_Registry::set($loggerType, $logger); + + $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); + $tag = Plugin::getPluginNameFromBacktrace($backtrace); + + // if we can't determine the plugin, use the name of the calling class + if ($tag == false) { + $tag = $this->getClassNameThatIsLogging($backtrace); + } + + $this->writeMessage($level, $tag, $datetime, $message); + } + } + + private function writeMessage($level, $tag, $datetime, $message) + { + foreach ($this->writers as $writer) { + call_user_func($writer, $level, $tag, $datetime, $message); + } + + // errors are always printed to screen + if ($level == self::ERROR + && !$this->loggingToScreen + ) { + $this->logToScreen($level, $tag, $datetime, $message); } } -} + private static function log($level, $message, $sprintfParams) + { + self::getInstance()->doLog($level, $message, $sprintfParams); + } + + private function shouldLoggerLog($level) + { + return $level <= $this->currentLogLevel; + } + + private function disableLoggingBasedOnConfig($logConfig) + { + $disableLogging = false; + + if (!empty($logConfig['log_only_when_cli']) + && !Common::isPhpCliMode() + ) { + $disableLogging = true; + } + + if (!empty($logConfig['log_only_when_debug_parameter']) + && !isset($_REQUEST['debug']) + ) { + $disableLogging = true; + } + if ($disableLogging) { + $this->currentLogLevel = self::NONE; + } + } + + private function getLogLevelFromStringName($name) + { + switch (strtoupper($name)) { + case 'NONE': + return self::NONE; + case 'ERROR': + return self::ERROR; + case 'WARN': + return self::WARN; + case 'INFO': + return self::INFO; + case 'DEBUG': + return self::DEBUG; + case 'VERBOSE': + return self::VERBOSE; + default: + return -1; + } + } + + private function getStringLevel($level) + { + static $levelToName = array( + self::NONE => 'NONE', + self::ERROR => 'ERROR', + self::WARN => 'WARN', + self::INFO => 'INFO', + self::DEBUG => 'DEBUG', + self::VERBOSE => 'VERBOSE' + ); + return $levelToName[$level]; + } + + private function getClassNameThatIsLogging($backtrace) + { + foreach ($backtrace as $tracepoint) { + if (isset($tracepoint['class']) + && $tracepoint['class'] != "Piwik\\Log" + ) { + return $tracepoint['class']; + } + } + return false; + } +}
\ No newline at end of file diff --git a/core/Log/APICall.php b/core/Log/APICall.php deleted file mode 100644 index b07fbc56ba..0000000000 --- a/core/Log/APICall.php +++ /dev/null @@ -1,77 +0,0 @@ -<?php -/** - * Piwik - Open source web analytics - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - * - * @category Piwik - * @package Piwik - */ -namespace Piwik\Log; - -use Piwik\IP; -use Piwik\Log; - -/** - * Class used to log all the API Calls information (class / method / parameters / returned value / time spent) - * - * @package Piwik - * @subpackage Log - */ -class APICall extends Log -{ - const ID = 'logger_api_call'; - - /** - * Constructor - */ - function __construct() - { - $logToFileFilename = self::ID; - $logToDatabaseTableName = self::ID; - $logToDatabaseColumnMapping = array( - 'class_name' => 'class_name', - 'method_name' => 'method_name', - 'parameter_names_default_values' => 'parameter_names_default_values', - 'parameter_values' => 'parameter_values', - 'execution_time' => 'execution_time', - 'caller_ip' => 'caller_ip', - 'timestamp' => 'timestamp', - 'returned_value' => 'returned_value' - ); - $screenFormatter = new APICallScreenFormatter(); - $fileFormatter = new FileFormatter(); - - parent::__construct($logToFileFilename, - $fileFormatter, - $screenFormatter, - $logToDatabaseTableName, - $logToDatabaseColumnMapping); - - $this->setEventItem('caller_ip', IP::P2N(IP::getIpFromHeader())); - } - - /** - * Logs the given api call event with the parameters - * - * @param string $className - * @param string $methodName - * @param array $parameterNames - * @param array $parameterValues - * @param number $executionTime - * @param mixed $returnedValue - */ - public function logEvent($className, $methodName, $parameterNames, $parameterValues, $executionTime, $returnedValue) - { - $event = array(); - $event['class_name'] = $className; - $event['method_name'] = $methodName; - $event['parameter_names_default_values'] = serialize($parameterNames); - $event['parameter_values'] = serialize($parameterValues); - $event['execution_time'] = $executionTime; - $event['returned_value'] = is_array($returnedValue) ? serialize($returnedValue) : $returnedValue; - parent::log($event, Log::INFO, null); - } -} - diff --git a/core/Log/APICallScreenFormatter.php b/core/Log/APICallScreenFormatter.php deleted file mode 100644 index 11bf5348d9..0000000000 --- a/core/Log/APICallScreenFormatter.php +++ /dev/null @@ -1,73 +0,0 @@ -<?php -/** - * Piwik - Open source web analytics - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - * - * @category Piwik - * @package Piwik - */ -namespace Piwik\Log; - -use Piwik\IP; -use Piwik\Log; - -/** - * Class used to format the API Call log on the screen. - * - * @package Piwik - * @subpackage Log - */ -class APICallScreenFormatter extends ScreenFormatter -{ - /** - * Formats data into a single line to be written by the writer. - * - * @param array $event event data - * @return string formatted line to write to the log - */ - public function format($event) - { - $str = "\n<br /> "; - $str .= "Called: {$event['class_name']}.{$event['method_name']} (took {$event['execution_time']}ms)\n<br /> "; - $str .= "Parameters: "; - $parameterNamesAndDefault = unserialize($event['parameter_names_default_values']); - $parameterValues = unserialize($event['parameter_values']); - $i = 0; - foreach ($parameterNamesAndDefault as $pName => $pDefault) { - if (isset($parameterValues[$i])) { - $currentValue = $parameterValues[$i]; - } else { - $currentValue = $pDefault; - } - $currentValue = $this->formatValue($currentValue); - $str .= "$pName = $currentValue, "; - - $i++; - } - $str .= "\n<br /> "; - $str .= "\n<br /> "; - return parent::format($str); - } - - /** - * Converts the given value to a string - * - * @param mixed $value - * @return string - */ - private function formatValue($value) - { - if (is_string($value)) { - $value = "'$value'"; - } - if (is_null($value)) { - $value = 'null'; - } - if (is_array($value)) { - $value = "array( " . implode(", ", $value) . ")"; - } - return $value; - } -}
\ No newline at end of file diff --git a/core/Log/Error.php b/core/Log/Error.php deleted file mode 100644 index 0b99ecabd2..0000000000 --- a/core/Log/Error.php +++ /dev/null @@ -1,81 +0,0 @@ -<?php -/** - * Piwik - Open source web analytics - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - * - * @category Piwik - * @package Piwik - */ -namespace Piwik\Log; -use Piwik\Log; -use Zend_Log_Writer_Stream; - -/** - * Class used to log an error event. - * - * @package Piwik - * @subpackage Log - */ -class Error extends Log -{ - const ID = 'logger_error'; - - /** - * Constructor - */ - function __construct() - { - $logToFileFilename = self::ID; - $logToDatabaseTableName = self::ID; - $logToDatabaseColumnMapping = array( - 'timestamp' => 'timestamp', - 'message' => 'message', - 'errno' => 'errno', - 'errline' => 'errline', - 'errfile' => 'errfile', - 'backtrace' => 'backtrace' - ); - $screenFormatter = new ErrorScreenFormatter(); - $fileFormatter = new FileFormatter(); - parent::__construct($logToFileFilename, - $fileFormatter, - $screenFormatter, - $logToDatabaseTableName, - $logToDatabaseColumnMapping); - } - - /** - * Adds the writer - */ - function addWriteToScreen() - { - parent::addWriteToScreen(); - $writerScreen = new \Zend_Log_Writer_Stream('php://stderr'); - $writerScreen->setFormatter($this->screenFormatter); - $this->addWriter($writerScreen); - } - - /** - * Logs the given error event - * - * @param int $errno - * @param string $errstr - * @param string $errfile - * @param int $errline - * @param string $backtrace - */ - public function logEvent($errno, $errstr, $errfile, $errline, $backtrace) - { - $event = array(); - $event['errno'] = $errno; - $event['message'] = $errstr; - $event['errfile'] = $errfile; - $event['errline'] = $errline; - $event['backtrace'] = $backtrace; - - parent::log($event, Log::ERR, null); - } -} - diff --git a/core/Log/ErrorScreenFormatter.php b/core/Log/ErrorScreenFormatter.php deleted file mode 100644 index 17c312e91c..0000000000 --- a/core/Log/ErrorScreenFormatter.php +++ /dev/null @@ -1,108 +0,0 @@ -<?php -/** - * Piwik - Open source web analytics - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - * - * @category Piwik - * @package Piwik - */ -namespace Piwik\Log; -use Piwik\Log; -use Piwik\Version; - -/** - * Format an error event to be displayed on the screen. - * - * @package Piwik - * @subpackage Log - */ -class ErrorScreenFormatter extends ScreenFormatter -{ - /** - * Formats data into a single line to be written by the writer. - * - * @param array $event event data - * @return string formatted line to write to the log - */ - public function format($event) - { - $event = parent::formatEvent($event); - - $errno = $event['errno']; - $errstr = $event['message']; - $errfile = $event['errfile']; - $errline = $event['errline']; - $backtrace = $event['backtrace']; - - $strReturned = ''; - $errno = $errno & error_reporting(); - - // problem when using error_reporting with the @ silent fail operator - // it gives an errno 0, and in this case the objective is to NOT display anything on the screen! - // is there any other case where the errno is zero at this point? - if ($errno == 0) return ''; - $strReturned .= "\n<div style='word-wrap: break-word; border: 3px solid red; padding:4px; width:70%; background-color:#FFFF96;'> - <strong>There is an error. Please report the message (Piwik " . (class_exists('Piwik\Version') ? Version::VERSION : '') . ") - and full backtrace in the <a href='?module=Proxy&action=redirect&url=http://forum.piwik.org' target='_blank'>Piwik forums</a> (please do a Search first as it might have been reported already!).<br /><br/> - "; - switch ($errno) { - case E_ERROR: - $strReturned .= "Error"; - break; - case E_WARNING: - $strReturned .= "Warning"; - break; - case E_PARSE: - $strReturned .= "Parse Error"; - break; - case E_NOTICE: - $strReturned .= "Notice"; - break; - case E_CORE_ERROR: - $strReturned .= "Core Error"; - break; - case E_CORE_WARNING: - $strReturned .= "Core Warning"; - break; - case E_COMPILE_ERROR: - $strReturned .= "Compile Error"; - break; - case E_COMPILE_WARNING: - $strReturned .= "Compile Warning"; - break; - case E_USER_ERROR: - $strReturned .= "User Error"; - break; - case E_USER_WARNING: - $strReturned .= "User Warning"; - break; - case E_USER_NOTICE: - $strReturned .= "User Notice"; - break; - case E_STRICT: - $strReturned .= "Strict Notice"; - break; - case E_RECOVERABLE_ERROR: - $strReturned .= "Recoverable Error"; - break; - case E_DEPRECATED: - $strReturned .= "Deprecated"; - break; - case E_USER_DEPRECATED: - $strReturned .= "User Deprecated"; - break; - default: - $strReturned .= "Unknown error ($errno)"; - break; - } - $strReturned .= ":</strong> <em>$errstr</em> in <strong>$errfile</strong> on line <strong>$errline</strong>\n"; - $strReturned .= "<br /><br />Backtrace --><div style=\"font-family:Courier;font-size:10pt\">"; - $strReturned .= str_replace(array("\n", '#'), array("<br />\n", "<br />\n#"), $backtrace); - $strReturned .= "</div><br />"; - $strReturned .= "\n </pre></div><br />"; - - return parent::format($strReturned); - } -} diff --git a/core/Log/Exception.php b/core/Log/Exception.php deleted file mode 100644 index e6b9ff0ec7..0000000000 --- a/core/Log/Exception.php +++ /dev/null @@ -1,79 +0,0 @@ -<?php -/** - * Piwik - Open source web analytics - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - * - * @category Piwik - * @package Piwik - */ -namespace Piwik\Log; - -use Piwik\Common; -use Piwik\Log; - -/** - * Class used to log an exception event. - * Displays the exception with a user friendly error message, suggests to get support from piwik.org - * - * @package Piwik - * @subpackage Log - */ -class Exception extends Log -{ - const ID = 'logger_exception'; - - /** - * Constructor - */ - function __construct() - { - $logToFileFilename = self::ID; - $logToDatabaseTableName = self::ID; - $logToDatabaseColumnMapping = array( - 'timestamp' => 'timestamp', - 'message' => 'message', - 'errno' => 'errno', - 'errline' => 'errline', - 'errfile' => 'errfile', - 'backtrace' => 'backtrace' - ); - $screenFormatter = new ExceptionScreenFormatter(); - $fileFormatter = new FileFormatter(); - - parent::__construct($logToFileFilename, - $fileFormatter, - $screenFormatter, - $logToDatabaseTableName, - $logToDatabaseColumnMapping); - } - - /** - * Adds the writer - */ - function addWriteToScreen() - { - parent::addWriteToScreen(); - $writerScreen = new \Zend_Log_Writer_Stream('php://stderr'); - $writerScreen->setFormatter($this->screenFormatter); - $this->addWriter($writerScreen); - } - - /** - * Logs the given exception event - * - * @param \Exception $exception - */ - public function logEvent(\Exception $exception) - { - $event = array(); - $event['errno'] = $exception->getCode(); - $event['message'] = $exception->getMessage(); - $event['errfile'] = $exception->getFile(); - $event['errline'] = $exception->getLine(); - $event['backtrace'] = $exception->getTraceAsString(); - - parent::log($event, Log::CRIT, null); - } -} diff --git a/core/Log/ExceptionScreenFormatter.php b/core/Log/ExceptionScreenFormatter.php deleted file mode 100644 index 0d789ef2aa..0000000000 --- a/core/Log/ExceptionScreenFormatter.php +++ /dev/null @@ -1,41 +0,0 @@ -<?php -/** - * Piwik - Open source web analytics - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - * - * @category Piwik - * @package Piwik - */ -namespace Piwik\Log; - -use Piwik\Common; -use Piwik\Log; -use Piwik\API\ResponseBuilder; - -/** - * Format an exception event to be displayed on the screen. - * - * @package Piwik - * @subpackage Log - */ -class ExceptionScreenFormatter extends ScreenFormatter -{ - /** - * Formats data into a single line to be written by the writer. - * - * @param array $event event data - * @return string formatted line to write to the log - */ - public function format($event) - { - $event = parent::formatEvent($event); - $errstr = $event['message']; - - $outputFormat = strtolower(Common::getRequestVar('format', 'html', 'string')); - $response = new ResponseBuilder($outputFormat); - $message = $response->getResponseException(new \Exception($errstr)); - return parent::format($message); - } -} diff --git a/core/Log/FileFormatter.php b/core/Log/FileFormatter.php deleted file mode 100644 index 960c67a260..0000000000 --- a/core/Log/FileFormatter.php +++ /dev/null @@ -1,36 +0,0 @@ -<?php -/** - * Piwik - Open source web analytics - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - * - * @category Piwik - * @package Piwik - */ -namespace Piwik\Log; -use Piwik\Common; - -/** - * @package Piwik - * @subpackage Log - */ -class FileFormatter implements \Zend_Log_Formatter_Interface -{ - /** - * Formats data into a single line to be written by the writer. - * - * @param array $event event data - * @return string formatted line to write to the log - */ - public function format($event) - { - foreach ($event as &$value) { - $value = str_replace("\n", '\n', $value); - $value = '"' . $value . '"'; - } - $ts = $event['timestamp']; - unset($event['timestamp']); - return $ts . ' ' . implode(" ", $event) . "\n"; - } -} diff --git a/core/Log/Message.php b/core/Log/Message.php deleted file mode 100644 index e6311c1d6e..0000000000 --- a/core/Log/Message.php +++ /dev/null @@ -1,58 +0,0 @@ -<?php -/** - * Piwik - Open source web analytics - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - * - * @category Piwik - * @package Piwik - */ -namespace Piwik\Log; -use Piwik\Piwik; -use Piwik\Common; -use Piwik\Log; - -/** - * Class used to log a standard message event. - * - * @package Piwik - * @subpackage Log - */ -class Message extends Log -{ - const ID = 'logger_message'; - - /** - * Constructor - */ - function __construct() - { - $logToFileFilename = self::ID . ".htm"; - $logToDatabaseTableName = self::ID; - $logToDatabaseColumnMapping = array( - 'message' => 'message', - 'timestamp' => 'timestamp' - ); - $screenFormatter = new MessageScreenFormatter(); - $fileFormatter = new FileFormatter(); - - parent::__construct($logToFileFilename, - $fileFormatter, - $screenFormatter, - $logToDatabaseTableName, - $logToDatabaseColumnMapping); - } - - /** - * Logs the given message - * - * @param string $message - */ - public function logEvent($message) - { - $event = array(); - $event['message'] = $message; - parent::log($event, Log::INFO, null); - } -}
\ No newline at end of file diff --git a/core/Log/MessageScreenFormatter.php b/core/Log/MessageScreenFormatter.php deleted file mode 100644 index 7b9ac48cdf..0000000000 --- a/core/Log/MessageScreenFormatter.php +++ /dev/null @@ -1,50 +0,0 @@ -<?php -/** - * Piwik - Open source web analytics - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - * - * @category Piwik - * @package Piwik - */ -namespace Piwik\Log; -use Piwik\Common; -use Piwik\Profiler; - -/** - * Format a standard message event to be displayed on the screen. - * The message can be a PHP array or a string. - * - * @package Piwik - * @subpackage Log - */ -class MessageScreenFormatter extends ScreenFormatter -{ - /** - * Formats data into a single line to be written by the writer. - * - * @param array $event event data - * @return string formatted line to write to the log - */ - public function format($event) - { - if (is_array($event['message'])) { - $message = "<pre>" . var_export($event['message'], true) . "</pre>"; - } else { - $message = $event['message']; - } - if (!Common::isPhpCliMode()) { - $message .= "<br/>"; - } - $message .= "\n"; - - $memory = ''; - // Hacky: let's hide the memory usage in CLI to hide from the archive.php output - if (!Common::isPhpCliMode()) { - $memory = '[' . Profiler::getMemoryUsage() . '] '; - } - $message = '[' . $event['timestamp'] . '] [' . $event['requestKey'] . '] ' . $memory . $message; - return parent::format($message); - } -} diff --git a/core/Log/ScreenFormatter.php b/core/Log/ScreenFormatter.php deleted file mode 100644 index 69b257d6c6..0000000000 --- a/core/Log/ScreenFormatter.php +++ /dev/null @@ -1,57 +0,0 @@ -<?php -/** - * Piwik - Open source web analytics - * - * @link http://piwik.org - * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later - * - * @category Piwik - * @package Piwik - */ -namespace Piwik\Log; -use Piwik\Common; - -/** - * - * @package Piwik - * @subpackage Log - */ -class ScreenFormatter implements \Zend_Log_Formatter_Interface -{ - /** - * Returns the formatted event array - * - * @param array $event - * @return array - */ - function formatEvent($event) - { - // no injection in error messages, backtrace when displayed on screen - return array_map(array('Piwik\Common', 'sanitizeInputValue'), $event); - } - - /** - * Returns the formatted String - * - * @param string $string - * @return string - */ - function format($string) - { - return self::getFormattedString($string); - } - - /** - * Returns the formatted String - * - * @param string $string - * @return string - */ - static public function getFormattedString($string) - { - if (!Common::isPhpCliMode()) { - @header('Content-Type: text/html; charset=utf-8'); - } - return $string; - } -}
\ No newline at end of file diff --git a/core/Piwik.php b/core/Piwik.php index f57d491156..0d33e42a06 100644 --- a/core/Piwik.php +++ b/core/Piwik.php @@ -14,7 +14,6 @@ use Exception; use Piwik\Db\Adapter; use Piwik\Db\Schema; use Piwik\Db; -use Piwik\Log\ScreenFormatter; use Piwik\Plugin; use Piwik\Plugins\UsersManager\API; use Piwik\Session; @@ -61,26 +60,13 @@ class Piwik public static $shouldLog = null; /** - * Log a message + * Log a message TODO: remove * * @param string $message */ static public function log($message = '') { - if (is_null(self::$shouldLog)) { - self::$shouldLog = SettingsPiwik::shouldLoggerLog(); - // It is possible that the logger is not setup: - // - Tracker request, and debug disabled, - // - and some scheduled tasks call code that tries and log something - try { - \Zend_Registry::get('logger_message'); - } catch (Exception $e) { - self::$shouldLog = false; - } - } - if (self::$shouldLog) { - \Zend_Registry::get('logger_message')->logEvent($message); - } + Log::info($message); } /** @@ -101,12 +87,16 @@ class Piwik */ static public function exitWithErrorMessage($message) { + if (!Common::isPhpCliMode()) { + @header('Content-Type: text/html; charset=utf-8'); + } + $output = "<style>a{color:red;}</style>\n" . "<div style='color:red;font-family:Georgia;font-size:120%'>" . "<p><img src='plugins/Zeitgeist/images/error_medium.png' style='vertical-align:middle; float:left;padding:20 20 20 20' />" . $message . "</p></div>"; - print(ScreenFormatter::getFormattedString($output)); + print($output); exit; } diff --git a/core/Plugin.php b/core/Plugin.php index 5f0c809896..a14cade95b 100644 --- a/core/Plugin.php +++ b/core/Plugin.php @@ -193,4 +193,23 @@ class Plugin { return $this->pluginName; } -} + + /** + * Extracts the plugin name from a backtrace array. Returns false if we can't find one. + * + * @param array $backtrace The result of the debug_backtrace() or Exception::getTrace(). + * @return string|false + */ + public static function getPluginNameFromBacktrace($backtrace) + { + foreach ($backtrace as $tracepoint) { + // try and discern the plugin name + if (isset($tracepoint['class']) + && preg_match("/Piwik\\\\Plugins\\\\([a-zA-Z_0-9]+)\\\\/", $tracepoint['class'], $matches) + ) { + return $matches[1]; + } + } + return false; + } +}
\ No newline at end of file diff --git a/core/Profiler.php b/core/Profiler.php index b959e3990c..2422f5db25 100644 --- a/core/Profiler.php +++ b/core/Profiler.php @@ -17,7 +17,8 @@ namespace Piwik; * enable_sql_profiler = 1 * * [log] - * logger_message[]="screen" + * log_writers[] = file + * log_level=debug * * @package Piwik */ diff --git a/core/SettingsPiwik.php b/core/SettingsPiwik.php index f4efd30c0e..19e9233891 100644 --- a/core/SettingsPiwik.php +++ b/core/SettingsPiwik.php @@ -85,24 +85,6 @@ class SettingsPiwik } /** - * Returns if logging should work - * @return bool - */ - public static function shouldLoggerLog() - { - try { - $shouldLog = (Common::isPhpCliMode() - || Config::getInstance()->log['log_only_when_cli'] == 0) - && - (Config::getInstance()->log['log_only_when_debug_parameter'] == 0 - || isset($_REQUEST['debug'])); - } catch (Exception $e) { - $shouldLog = false; - } - return $shouldLog; - } - - /** * Cache for result of getPiwikUrl. * Can be overwritten for testing purposes only. * diff --git a/core/Updates/2.0-a7.php b/core/Updates/2.0-a7.php new file mode 100644 index 0000000000..2391476d1b --- /dev/null +++ b/core/Updates/2.0-a7.php @@ -0,0 +1,37 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + * + * @category Piwik + * @package Piwik + */ +use Piwik\Common; +use Piwik\Updater; +use Piwik\Updates; + +/** + * @package Updates + */ +class Piwik_Updates_2_0_a7 extends Updates +{ + static function getSql($schema = 'Myisam') + { + return array( + // ignore existing column name error (1060) + 'ALTER TABLE ' . Common::prefixTable('logger_message') + . " ADD COLUMN tag VARCHAR(50) NULL AFTER idlogger_message" => 1060, + + 'ALTER TABLE ' . Common::prefixTable('logger_message') + . " ADD COLUMN level TINYINT AFTER timestamp" => 1060, + ); + } + + static function update() + { + // add tag & level columns to logger_message table + Updater::updateDatabase(__FILE__, self::getSql()); + } +} diff --git a/core/Version.php b/core/Version.php index 172fe9daff..59f77345a8 100644 --- a/core/Version.php +++ b/core/Version.php @@ -22,5 +22,5 @@ final class Version * Current Piwik version * @var string */ - const VERSION = '2.0-a6'; + const VERSION = '2.0-a7'; } @@ -9,6 +9,8 @@ */ use Piwik\FrontController; +use Piwik\Error; +use Piwik\ExceptionHandler; define('PIWIK_DOCUMENT_ROOT', dirname(__FILE__) == '/' ? '' : dirname(__FILE__)); if (file_exists(PIWIK_DOCUMENT_ROOT . '/bootstrap.php')) { @@ -39,10 +41,11 @@ require_once PIWIK_INCLUDE_PATH . '/core/Loader.php'; require_once PIWIK_INCLUDE_PATH . '/core/functions.php'; if (!defined('PIWIK_ENABLE_ERROR_HANDLER') || PIWIK_ENABLE_ERROR_HANDLER) { - require_once PIWIK_INCLUDE_PATH . '/core/ErrorHandler.php'; + require_once PIWIK_INCLUDE_PATH . '/core/Error.php'; + Error::setErrorHandler(); + require_once PIWIK_INCLUDE_PATH . '/core/ExceptionHandler.php'; - set_error_handler('Piwik_ErrorHandler'); - set_exception_handler('Piwik_ExceptionHandler'); + ExceptionHandler::setUp(); } if (!defined('PIWIK_ENABLE_DISPATCH') || PIWIK_ENABLE_DISPATCH) { diff --git a/libs/Zend/Log.php b/libs/Zend/Log.php deleted file mode 100644 index 4f415836c3..0000000000 --- a/libs/Zend/Log.php +++ /dev/null @@ -1,624 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Log.php 23783 2011-03-01 21:47:35Z intiilapa $ - */ - -/** - * @category Zend - * @package Zend_Log - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Log.php 23783 2011-03-01 21:47:35Z intiilapa $ - */ -class Zend_Log -{ - const EMERG = 0; // Emergency: system is unusable - const ALERT = 1; // Alert: action must be taken immediately - const CRIT = 2; // Critical: critical conditions - const ERR = 3; // Error: error conditions - const WARN = 4; // Warning: warning conditions - const NOTICE = 5; // Notice: normal but significant condition - const INFO = 6; // Informational: informational messages - const DEBUG = 7; // Debug: debug messages - - /** - * @var array of priorities where the keys are the - * priority numbers and the values are the priority names - */ - protected $_priorities = array(); - - /** - * @var array of Zend_Log_Writer_Abstract - */ - protected $_writers = array(); - - /** - * @var array of Zend_Log_Filter_Interface - */ - protected $_filters = array(); - - /** - * @var array of extra log event - */ - protected $_extras = array(); - - /** - * - * @var string - */ - protected $_defaultWriterNamespace = 'Zend_Log_Writer'; - - /** - * - * @var string - */ - protected $_defaultFilterNamespace = 'Zend_Log_Filter'; - - /** - * - * @var string - */ - protected $_defaultFormatterNamespace = 'Zend_Log_Formatter'; - - /** - * - * @var callback - */ - protected $_origErrorHandler = null; - - /** - * - * @var boolean - */ - protected $_registeredErrorHandler = false; - - /** - * - * @var array|boolean - */ - protected $_errorHandlerMap = false; - - /** - * - * @var string - */ - protected $_timestampFormat = 'c'; - - /** - * Class constructor. Create a new logger - * - * @param Zend_Log_Writer_Abstract|null $writer default writer - * @return void - */ - public function __construct(Zend_Log_Writer_Abstract $writer = null) - { - $r = new ReflectionClass($this); - $this->_priorities = array_flip($r->getConstants()); - - if ($writer !== null) { - $this->addWriter($writer); - } - } - - /** - * Factory to construct the logger and one or more writers - * based on the configuration array - * - * @param array|Zend_Config Array or instance of Zend_Config - * @return Zend_Log - * @throws Zend_Log_Exception - */ - static public function factory($config = array()) - { - if ($config instanceof Zend_Config) { - $config = $config->toArray(); - } - - if (!is_array($config) || empty($config)) { - /** @see Zend_Log_Exception */ - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Configuration must be an array or instance of Zend_Config'); - } - - $log = new self; - - if (array_key_exists('timestampFormat', $config)) { - if (null != $config['timestampFormat'] && '' != $config['timestampFormat']) { - $log->setTimestampFormat($config['timestampFormat']); - } - unset($config['timestampFormat']); - } - - if (!is_array(current($config))) { - $log->addWriter(current($config)); - } else { - foreach($config as $writer) { - $log->addWriter($writer); - } - } - - return $log; - } - - - /** - * Construct a writer object based on a configuration array - * - * @param array $spec config array with writer spec - * @return Zend_Log_Writer_Abstract - * @throws Zend_Log_Exception - */ - protected function _constructWriterFromConfig($config) - { - $writer = $this->_constructFromConfig('writer', $config, $this->_defaultWriterNamespace); - - if (!$writer instanceof Zend_Log_Writer_Abstract) { - $writerName = is_object($writer) - ? get_class($writer) - : 'The specified writer'; - /** @see Zend_Log_Exception */ - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception("{$writerName} does not extend Zend_Log_Writer_Abstract!"); - } - - if (isset($config['filterName'])) { - $filter = $this->_constructFilterFromConfig($config); - $writer->addFilter($filter); - } - - if (isset($config['formatterName'])) { - $formatter = $this->_constructFormatterFromConfig($config); - $writer->setFormatter($formatter); - } - - return $writer; - } - - /** - * Construct filter object from configuration array or Zend_Config object - * - * @param array|Zend_Config $config Zend_Config or Array - * @return Zend_Log_Filter_Interface - * @throws Zend_Log_Exception - */ - protected function _constructFilterFromConfig($config) - { - $filter = $this->_constructFromConfig('filter', $config, $this->_defaultFilterNamespace); - - if (!$filter instanceof Zend_Log_Filter_Interface) { - $filterName = is_object($filter) - ? get_class($filter) - : 'The specified filter'; - /** @see Zend_Log_Exception */ - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception("{$filterName} does not implement Zend_Log_Filter_Interface"); - } - - return $filter; - } - - /** - * Construct formatter object from configuration array or Zend_Config object - * - * @param array|Zend_Config $config Zend_Config or Array - * @return Zend_Log_Formatter_Interface - * @throws Zend_Log_Exception - */ - protected function _constructFormatterFromConfig($config) - { - $formatter = $this->_constructFromConfig('formatter', $config, $this->_defaultFormatterNamespace); - - if (!$formatter instanceof Zend_Log_Formatter_Interface) { - $formatterName = is_object($formatter) - ? get_class($formatter) - : 'The specified formatter'; - /** @see Zend_Log_Exception */ - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception($formatterName . ' does not implement Zend_Log_Formatter_Interface'); - } - - return $formatter; - } - - /** - * Construct a filter or writer from config - * - * @param string $type 'writer' of 'filter' - * @param mixed $config Zend_Config or Array - * @param string $namespace - * @return object - * @throws Zend_Log_Exception - */ - protected function _constructFromConfig($type, $config, $namespace) - { - if ($config instanceof Zend_Config) { - $config = $config->toArray(); - } - - if (!is_array($config) || empty($config)) { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception( - 'Configuration must be an array or instance of Zend_Config' - ); - } - - $params = isset($config[ $type .'Params' ]) ? $config[ $type .'Params' ] : array(); - $className = $this->getClassName($config, $type, $namespace); - if (!class_exists($className)) { - // require_once 'Zend/Loader.php'; - Zend_Loader::loadClass($className); - } - - $reflection = new ReflectionClass($className); - if (!$reflection->implementsInterface('Zend_Log_FactoryInterface')) { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception( - $className . ' does not implement Zend_Log_FactoryInterface and can not be constructed from config.' - ); - } - - return call_user_func(array($className, 'factory'), $params); - } - - /** - * Get the writer or filter full classname - * - * @param array $config - * @param string $type filter|writer - * @param string $defaultNamespace - * @return string full classname - * @throws Zend_Log_Exception - */ - protected function getClassName($config, $type, $defaultNamespace) - { - if (!isset($config[ $type . 'Name' ])) { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception("Specify {$type}Name in the configuration array"); - } - $className = $config[ $type . 'Name' ]; - - $namespace = $defaultNamespace; - if (isset($config[ $type . 'Namespace' ])) { - $namespace = $config[ $type . 'Namespace' ]; - } - - $fullClassName = $namespace . '_' . $className; - return $fullClassName; - } - - /** - * Packs message and priority into Event array - * - * @param string $message Message to log - * @param integer $priority Priority of message - * @return array Event array - */ - protected function _packEvent($message, $priority) - { - return array_merge(array( - 'timestamp' => date($this->_timestampFormat), - 'message' => $message, - 'priority' => $priority, - 'priorityName' => $this->_priorities[$priority] - ), - $this->_extras - ); - } - - /** - * Class destructor. Shutdown log writers - * - * @return void - */ - public function __destruct() - { - foreach($this->_writers as $writer) { - $writer->shutdown(); - } - } - - /** - * Undefined method handler allows a shortcut: - * $log->priorityName('message') - * instead of - * $log->log('message', Zend_Log::PRIORITY_NAME) - * - * @param string $method priority name - * @param string $params message to log - * @return void - * @throws Zend_Log_Exception - */ - public function __call($method, $params) - { - $priority = strtoupper($method); - if (($priority = array_search($priority, $this->_priorities)) !== false) { - switch (count($params)) { - case 0: - /** @see Zend_Log_Exception */ - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Missing log message'); - case 1: - $message = array_shift($params); - $extras = null; - break; - default: - $message = array_shift($params); - $extras = array_shift($params); - break; - } - $this->log($message, $priority, $extras); - } else { - /** @see Zend_Log_Exception */ - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Bad log priority'); - } - } - - /** - * Log a message at a priority - * - * @param string $message Message to log - * @param integer $priority Priority of message - * @param mixed $extras Extra information to log in event - * @return void - * @throws Zend_Log_Exception - */ - public function log($message, $priority, $extras = null) - { - // sanity checks - if (empty($this->_writers)) { - /** @see Zend_Log_Exception */ - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('No writers were added'); - } - - if (! isset($this->_priorities[$priority])) { - /** @see Zend_Log_Exception */ - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Bad log priority'); - } - - // pack into event required by filters and writers - $event = $this->_packEvent($message, $priority); - - // Check to see if any extra information was passed - if (!empty($extras)) { - $info = array(); - if (is_array($extras)) { - foreach ($extras as $key => $value) { - if (is_string($key)) { - $event[$key] = $value; - } else { - $info[] = $value; - } - } - } else { - $info = $extras; - } - if (!empty($info)) { - $event['info'] = $info; - } - } - - // abort if rejected by the global filters - foreach ($this->_filters as $filter) { - if (! $filter->accept($event)) { - return; - } - } - - // send to each writer - foreach ($this->_writers as $writer) { - $writer->write($event); - } - } - - /** - * Add a custom priority - * - * @param string $name Name of priority - * @param integer $priority Numeric priority - * @throws Zend_Log_Exception - */ - public function addPriority($name, $priority) - { - // Priority names must be uppercase for predictability. - $name = strtoupper($name); - - if (isset($this->_priorities[$priority]) - || false !== array_search($name, $this->_priorities)) { - /** @see Zend_Log_Exception */ - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Existing priorities cannot be overwritten'); - } - - $this->_priorities[$priority] = $name; - return $this; - } - - /** - * Add a filter that will be applied before all log writers. - * Before a message will be received by any of the writers, it - * must be accepted by all filters added with this method. - * - * @param int|Zend_Config|array|Zend_Log_Filter_Interface $filter - * @return Zend_Log - * @throws Zend_Log_Exception - */ - public function addFilter($filter) - { - if (is_int($filter)) { - /** @see Zend_Log_Filter_Priority */ - // require_once 'Zend/Log/Filter/Priority.php'; - $filter = new Zend_Log_Filter_Priority($filter); - - } elseif ($filter instanceof Zend_Config || is_array($filter)) { - $filter = $this->_constructFilterFromConfig($filter); - - } elseif(! $filter instanceof Zend_Log_Filter_Interface) { - /** @see Zend_Log_Exception */ - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Invalid filter provided'); - } - - $this->_filters[] = $filter; - return $this; - } - - /** - * Add a writer. A writer is responsible for taking a log - * message and writing it out to storage. - * - * @param mixed $writer Zend_Log_Writer_Abstract or Config array - * @return Zend_Log - */ - public function addWriter($writer) - { - if (is_array($writer) || $writer instanceof Zend_Config) { - $writer = $this->_constructWriterFromConfig($writer); - } - - if (!$writer instanceof Zend_Log_Writer_Abstract) { - /** @see Zend_Log_Exception */ - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception( - 'Writer must be an instance of Zend_Log_Writer_Abstract' - . ' or you should pass a configuration array' - ); - } - - $this->_writers[] = $writer; - return $this; - } - - /** - * Set an extra item to pass to the log writers. - * - * @param string $name Name of the field - * @param string $value Value of the field - * @return Zend_Log - */ - public function setEventItem($name, $value) - { - $this->_extras = array_merge($this->_extras, array($name => $value)); - return $this; - } - - /** - * Register Logging system as an error handler to log php errors - * Note: it still calls the original error handler if set_error_handler is able to return it. - * - * Errors will be mapped as: - * E_NOTICE, E_USER_NOTICE => NOTICE - * E_WARNING, E_CORE_WARNING, E_USER_WARNING => WARN - * E_ERROR, E_USER_ERROR, E_CORE_ERROR, E_RECOVERABLE_ERROR => ERR - * E_DEPRECATED, E_STRICT, E_USER_DEPRECATED => DEBUG - * (unknown/other) => INFO - * - * @link http://www.php.net/manual/en/function.set-error-handler.php Custom error handler - * - * @return Zend_Log - */ - public function registerErrorHandler() - { - // Only register once. Avoids loop issues if it gets registered twice. - if ($this->_registeredErrorHandler) { - return $this; - } - - $this->_origErrorHandler = set_error_handler(array($this, 'errorHandler')); - - // Contruct a default map of phpErrors to Zend_Log priorities. - // Some of the errors are uncatchable, but are included for completeness - $this->_errorHandlerMap = array( - E_NOTICE => Zend_Log::NOTICE, - E_USER_NOTICE => Zend_Log::NOTICE, - E_WARNING => Zend_Log::WARN, - E_CORE_WARNING => Zend_Log::WARN, - E_USER_WARNING => Zend_Log::WARN, - E_ERROR => Zend_Log::ERR, - E_USER_ERROR => Zend_Log::ERR, - E_CORE_ERROR => Zend_Log::ERR, - E_RECOVERABLE_ERROR => Zend_Log::ERR, - E_STRICT => Zend_Log::DEBUG, - ); - // PHP 5.3.0+ - if (defined('E_DEPRECATED')) { - $this->_errorHandlerMap['E_DEPRECATED'] = Zend_Log::DEBUG; - } - if (defined('E_USER_DEPRECATED')) { - $this->_errorHandlerMap['E_USER_DEPRECATED'] = Zend_Log::DEBUG; - } - - $this->_registeredErrorHandler = true; - return $this; - } - - /** - * Error Handler will convert error into log message, and then call the original error handler - * - * @link http://www.php.net/manual/en/function.set-error-handler.php Custom error handler - * @param int $errno - * @param string $errstr - * @param string $errfile - * @param int $errline - * @param array $errcontext - * @return boolean - */ - public function errorHandler($errno, $errstr, $errfile, $errline, $errcontext) - { - $errorLevel = error_reporting(); - - if ($errorLevel && $errno) { - if (isset($this->_errorHandlerMap[$errno])) { - $priority = $this->_errorHandlerMap[$errno]; - } else { - $priority = Zend_Log::INFO; - } - $this->log($errstr, $priority, array('errno'=>$errno, 'file'=>$errfile, 'line'=>$errline, 'context'=>$errcontext)); - } - - if ($this->_origErrorHandler !== null) { - return call_user_func($this->_origErrorHandler, $errno, $errstr, $errfile, $errline, $errcontext); - } - return false; - } - - /** - * Set timestamp format for log entries. - * - * @param string $format - * @return Zend_Log - */ - public function setTimestampFormat($format) - { - $this->_timestampFormat = $format; - return $this; - } - - /** - * Get timestamp format used for log entries. - * - * @return string - */ - public function getTimestampFormat() - { - return $this->_timestampFormat; - } -} diff --git a/libs/Zend/Log/Exception.php b/libs/Zend/Log/Exception.php deleted file mode 100644 index e21942ce03..0000000000 --- a/libs/Zend/Log/Exception.php +++ /dev/null @@ -1,33 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** Zend_Exception */ -// require_once 'Zend/Exception.php'; - -/** - * @category Zend - * @package Zend_Log - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Exception.php 23775 2011-03-01 17:25:24Z ralph $ - */ -class Zend_Log_Exception extends Zend_Exception -{} diff --git a/libs/Zend/Log/FactoryInterface.php b/libs/Zend/Log/FactoryInterface.php deleted file mode 100644 index 7b3d77e926..0000000000 --- a/libs/Zend/Log/FactoryInterface.php +++ /dev/null @@ -1,38 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: FactoryInterface.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** - * @category Zend - * @package Zend_Log - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: FactoryInterface.php 23775 2011-03-01 17:25:24Z ralph $ - */ -interface Zend_Log_FactoryInterface -{ - /** - * Construct a Zend_Log driver - * - * @param array|Zend_Config $config - * @return Zend_Log_FactoryInterface - */ - static public function factory($config); -} diff --git a/libs/Zend/Log/Filter/Abstract.php b/libs/Zend/Log/Filter/Abstract.php deleted file mode 100644 index 6c38cab286..0000000000 --- a/libs/Zend/Log/Filter/Abstract.php +++ /dev/null @@ -1,60 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Abstract.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** @see Zend_Log_Filter_Interface */ -// require_once 'Zend/Log/Filter/Interface.php'; - -/** @see Zend_Log_FactoryInterface */ -// require_once 'Zend/Log/FactoryInterface.php'; - -/** - * @category Zend - * @package Zend_Log - * @subpackage Filter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Abstract.php 23775 2011-03-01 17:25:24Z ralph $ - */ -abstract class Zend_Log_Filter_Abstract - implements Zend_Log_Filter_Interface, Zend_Log_FactoryInterface -{ - /** - * Validate and optionally convert the config to array - * - * @param array|Zend_Config $config Zend_Config or Array - * @return array - * @throws Zend_Log_Exception - */ - static protected function _parseConfig($config) - { - if ($config instanceof Zend_Config) { - $config = $config->toArray(); - } - - if (!is_array($config)) { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Configuration must be an array or instance of Zend_Config'); - } - - return $config; - } -} diff --git a/libs/Zend/Log/Filter/Interface.php b/libs/Zend/Log/Filter/Interface.php deleted file mode 100644 index 801a62ba97..0000000000 --- a/libs/Zend/Log/Filter/Interface.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Filter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Interface.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** - * @category Zend - * @package Zend_Log - * @subpackage Filter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Interface.php 23775 2011-03-01 17:25:24Z ralph $ - */ -interface Zend_Log_Filter_Interface -{ - /** - * Returns TRUE to accept the message, FALSE to block it. - * - * @param array $event event data - * @return boolean accepted? - */ - public function accept($event); -} diff --git a/libs/Zend/Log/Filter/Message.php b/libs/Zend/Log/Filter/Message.php deleted file mode 100644 index 928b721812..0000000000 --- a/libs/Zend/Log/Filter/Message.php +++ /dev/null @@ -1,85 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Filter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Message.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** Zend_Log_Filter_Abstract */ -// require_once 'Zend/Log/Filter/Abstract.php'; - -/** - * @category Zend - * @package Zend_Log - * @subpackage Filter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Message.php 23775 2011-03-01 17:25:24Z ralph $ - */ -class Zend_Log_Filter_Message extends Zend_Log_Filter_Abstract -{ - /** - * @var string - */ - protected $_regexp; - - /** - * Filter out any log messages not matching $regexp. - * - * @param string $regexp Regular expression to test the log message - * @return void - * @throws Zend_Log_Exception - */ - public function __construct($regexp) - { - if (@preg_match($regexp, '') === false) { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception("Invalid regular expression '$regexp'"); - } - $this->_regexp = $regexp; - } - - /** - * Create a new instance of Zend_Log_Filter_Message - * - * @param array|Zend_Config $config - * @return Zend_Log_Filter_Message - */ - static public function factory($config) - { - $config = self::_parseConfig($config); - $config = array_merge(array( - 'regexp' => null - ), $config); - - return new self( - $config['regexp'] - ); - } - - /** - * Returns TRUE to accept the message, FALSE to block it. - * - * @param array $event event data - * @return boolean accepted? - */ - public function accept($event) - { - return preg_match($this->_regexp, $event['message']) > 0; - } -} diff --git a/libs/Zend/Log/Filter/Priority.php b/libs/Zend/Log/Filter/Priority.php deleted file mode 100644 index b7bb23e54b..0000000000 --- a/libs/Zend/Log/Filter/Priority.php +++ /dev/null @@ -1,101 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Filter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Priority.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** Zend_Log_Filter_Abstract */ -// require_once 'Zend/Log/Filter/Abstract.php'; - -/** - * @category Zend - * @package Zend_Log - * @subpackage Filter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Priority.php 23775 2011-03-01 17:25:24Z ralph $ - */ -class Zend_Log_Filter_Priority extends Zend_Log_Filter_Abstract -{ - /** - * @var integer - */ - protected $_priority; - - /** - * @var string - */ - protected $_operator; - - /** - * Filter logging by $priority. By default, it will accept any log - * event whose priority value is less than or equal to $priority. - * - * @param integer $priority Priority - * @param string $operator Comparison operator - * @return void - * @throws Zend_Log_Exception - */ - public function __construct($priority, $operator = null) - { - if (! is_int($priority)) { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Priority must be an integer'); - } - - $this->_priority = $priority; - $this->_operator = $operator === null ? '<=' : $operator; - } - - /** - * Create a new instance of Zend_Log_Filter_Priority - * - * @param array|Zend_Config $config - * @return Zend_Log_Filter_Priority - */ - static public function factory($config) - { - $config = self::_parseConfig($config); - $config = array_merge(array( - 'priority' => null, - 'operator' => null, - ), $config); - - // Add support for constants - if (!is_numeric($config['priority']) && isset($config['priority']) && defined($config['priority'])) { - $config['priority'] = constant($config['priority']); - } - - return new self( - (int) $config['priority'], - $config['operator'] - ); - } - - /** - * Returns TRUE to accept the message, FALSE to block it. - * - * @param array $event event data - * @return boolean accepted? - */ - public function accept($event) - { - return version_compare($event['priority'], $this->_priority, $this->_operator); - } -} diff --git a/libs/Zend/Log/Filter/Suppress.php b/libs/Zend/Log/Filter/Suppress.php deleted file mode 100644 index 376c81b7aa..0000000000 --- a/libs/Zend/Log/Filter/Suppress.php +++ /dev/null @@ -1,77 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Filter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Suppress.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** Zend_Log_Filter_Interface */ -// require_once 'Zend/Log/Filter/Abstract.php'; - -/** - * @category Zend - * @package Zend_Log - * @subpackage Filter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Suppress.php 23775 2011-03-01 17:25:24Z ralph $ - */ -class Zend_Log_Filter_Suppress extends Zend_Log_Filter_Abstract -{ - /** - * @var boolean - */ - protected $_accept = true; - - /** - * This is a simple boolean filter. - * - * Call suppress(true) to suppress all log events. - * Call suppress(false) to accept all log events. - * - * @param boolean $suppress Should all log events be suppressed? - * @return void - */ - public function suppress($suppress) - { - $this->_accept = (! $suppress); - } - - /** - * Returns TRUE to accept the message, FALSE to block it. - * - * @param array $event event data - * @return boolean accepted? - */ - public function accept($event) - { - return $this->_accept; - } - - /** - * Create a new instance of Zend_Log_Filter_Suppress - * - * @param array|Zend_Config $config - * @return Zend_Log_Filter_Suppress - * @throws Zend_Log_Exception - */ - static public function factory($config) - { - return new self(); - } -} diff --git a/libs/Zend/Log/Formatter/Abstract.php b/libs/Zend/Log/Formatter/Abstract.php deleted file mode 100644 index 310253977c..0000000000 --- a/libs/Zend/Log/Formatter/Abstract.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Formatter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Abstract.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** @see Zend_Log_Formatter_Interface */ -// require_once 'Zend/Log/Formatter/Interface.php'; - -/** @see Zend_Log_FactoryInterface */ -// require_once 'Zend/Log/FactoryInterface.php'; - -/** - * @category Zend - * @package Zend_Log - * @subpackage Formatter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Abstract.php 23775 2011-03-01 17:25:24Z ralph $ - */ -abstract class Zend_Log_Formatter_Abstract - implements Zend_Log_Formatter_Interface, Zend_Log_FactoryInterface -{ -} diff --git a/libs/Zend/Log/Formatter/Firebug.php b/libs/Zend/Log/Formatter/Firebug.php deleted file mode 100644 index e34533cc76..0000000000 --- a/libs/Zend/Log/Formatter/Firebug.php +++ /dev/null @@ -1,61 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Formatter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Firebug.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** Zend_Log_Formatter_Abstract */ -// require_once 'Zend/Log/Formatter/Abstract.php'; - -/** - * @category Zend - * @package Zend_Log - * @subpackage Formatter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Log_Formatter_Firebug extends Zend_Log_Formatter_Abstract -{ - /** - * Factory for Zend_Log_Formatter_Firebug classe - * - * @param array|Zend_Config $options useless - * @return Zend_Log_Formatter_Firebug - */ - public static function factory($options) - { - return new self; - } - - /** - * This method formats the event for the firebug writer. - * - * The default is to just send the message parameter, but through - * extension of this class and calling the - * {@see Zend_Log_Writer_Firebug::setFormatter()} method you can - * pass as much of the event data as you are interested in. - * - * @param array $event event data - * @return mixed event message - */ - public function format($event) - { - return $event['message']; - } -} diff --git a/libs/Zend/Log/Formatter/Interface.php b/libs/Zend/Log/Formatter/Interface.php deleted file mode 100644 index 01272ebed4..0000000000 --- a/libs/Zend/Log/Formatter/Interface.php +++ /dev/null @@ -1,41 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Formatter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Interface.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** - * @category Zend - * @package Zend_Log - * @subpackage Formatter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Interface.php 23775 2011-03-01 17:25:24Z ralph $ - */ -interface Zend_Log_Formatter_Interface -{ - /** - * Formats data into a single line to be written by the writer. - * - * @param array $event event data - * @return string formatted line to write to the log - */ - public function format($event); - -} diff --git a/libs/Zend/Log/Formatter/Simple.php b/libs/Zend/Log/Formatter/Simple.php deleted file mode 100644 index 1680057c3d..0000000000 --- a/libs/Zend/Log/Formatter/Simple.php +++ /dev/null @@ -1,108 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Formatter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Simple.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** Zend_Log_Formatter_Abstract */ -// require_once 'Zend/Log/Formatter/Abstract.php'; - -/** - * @category Zend - * @package Zend_Log - * @subpackage Formatter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Simple.php 23775 2011-03-01 17:25:24Z ralph $ - */ -class Zend_Log_Formatter_Simple extends Zend_Log_Formatter_Abstract -{ - /** - * @var string - */ - protected $_format; - - const DEFAULT_FORMAT = '%timestamp% %priorityName% (%priority%): %message%'; - - /** - * Class constructor - * - * @param null|string $format Format specifier for log messages - * @return void - * @throws Zend_Log_Exception - */ - public function __construct($format = null) - { - if ($format === null) { - $format = self::DEFAULT_FORMAT . PHP_EOL; - } - - if (!is_string($format)) { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Format must be a string'); - } - - $this->_format = $format; - } - - /** - * Factory for Zend_Log_Formatter_Simple classe - * - * @param array|Zend_Config $options - * @return Zend_Log_Formatter_Simple - */ - public static function factory($options) - { - $format = null; - if (null !== $options) { - if ($options instanceof Zend_Config) { - $options = $options->toArray(); - } - - if (array_key_exists('format', $options)) { - $format = $options['format']; - } - } - - return new self($format); - } - - /** - * Formats data into a single line to be written by the writer. - * - * @param array $event event data - * @return string formatted line to write to the log - */ - public function format($event) - { - $output = $this->_format; - - foreach ($event as $name => $value) { - if ((is_object($value) && !method_exists($value,'__toString')) - || is_array($value) - ) { - $value = gettype($value); - } - - $output = str_replace("%$name%", $value, $output); - } - - return $output; - } -} diff --git a/libs/Zend/Log/Formatter/Xml.php b/libs/Zend/Log/Formatter/Xml.php deleted file mode 100644 index 09ea50170e..0000000000 --- a/libs/Zend/Log/Formatter/Xml.php +++ /dev/null @@ -1,165 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Formatter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Xml.php 24237 2011-07-13 18:22:20Z matthew $ - */ - -/** Zend_Log_Formatter_Abstract */ -// require_once 'Zend/Log/Formatter/Abstract.php'; - -/** - * @category Zend - * @package Zend_Log - * @subpackage Formatter - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Xml.php 24237 2011-07-13 18:22:20Z matthew $ - */ -class Zend_Log_Formatter_Xml extends Zend_Log_Formatter_Abstract -{ - /** - * @var string Name of root element - */ - protected $_rootElement; - - /** - * @var array Relates XML elements to log data field keys. - */ - protected $_elementMap; - - /** - * @var string Encoding to use in XML - */ - protected $_encoding; - - /** - * Class constructor - * (the default encoding is UTF-8) - * - * @param array|Zend_Config $options - * @return void - */ - public function __construct($options = array()) - { - if ($options instanceof Zend_Config) { - $options = $options->toArray(); - } elseif (!is_array($options)) { - $args = func_get_args(); - - $options = array( - 'rootElement' => array_shift($args) - ); - - if (count($args)) { - $options['elementMap'] = array_shift($args); - } - - if (count($args)) { - $options['encoding'] = array_shift($args); - } - } - - if (!array_key_exists('rootElement', $options)) { - $options['rootElement'] = 'logEntry'; - } - - if (!array_key_exists('encoding', $options)) { - $options['encoding'] = 'UTF-8'; - } - - $this->_rootElement = $options['rootElement']; - $this->setEncoding($options['encoding']); - - if (array_key_exists('elementMap', $options)) { - $this->_elementMap = $options['elementMap']; - } - } - - /** - * Factory for Zend_Log_Formatter_Xml classe - * - * @param array|Zend_Config $options - * @return Zend_Log_Formatter_Xml - */ - public static function factory($options) - { - return new self($options); - } - - /** - * Get encoding - * - * @return string - */ - public function getEncoding() - { - return $this->_encoding; - } - - /** - * Set encoding - * - * @param string $value - * @return Zend_Log_Formatter_Xml - */ - public function setEncoding($value) - { - $this->_encoding = (string) $value; - return $this; - } - - /** - * Formats data into a single line to be written by the writer. - * - * @param array $event event data - * @return string formatted line to write to the log - */ - public function format($event) - { - if ($this->_elementMap === null) { - $dataToInsert = $event; - } else { - $dataToInsert = array(); - foreach ($this->_elementMap as $elementName => $fieldKey) { - $dataToInsert[$elementName] = $event[$fieldKey]; - } - } - - $enc = $this->getEncoding(); - $dom = new DOMDocument('1.0', $enc); - $elt = $dom->appendChild(new DOMElement($this->_rootElement)); - - foreach ($dataToInsert as $key => $value) { - if (empty($value) - || is_scalar($value) - || (is_object($value) && method_exists($value,'__toString')) - ) { - if($key == "message") { - $value = htmlspecialchars($value, ENT_COMPAT, $enc); - } - $elt->appendChild(new DOMElement($key, (string)$value)); - } - } - - $xml = $dom->saveXML(); - $xml = preg_replace('/<\?xml version="1.0"( encoding="[^\"]*")?\?>\n/u', '', $xml); - - return $xml . PHP_EOL; - } -} diff --git a/libs/Zend/Log/Writer/Abstract.php b/libs/Zend/Log/Writer/Abstract.php deleted file mode 100644 index 974c0179a7..0000000000 --- a/libs/Zend/Log/Writer/Abstract.php +++ /dev/null @@ -1,138 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Abstract.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** Zend_Log_Filter_Priority */ -// require_once 'Zend/Log/Filter/Priority.php'; - -/** - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Abstract.php 23775 2011-03-01 17:25:24Z ralph $ - */ -abstract class Zend_Log_Writer_Abstract implements Zend_Log_FactoryInterface -{ - /** - * @var array of Zend_Log_Filter_Interface - */ - protected $_filters = array(); - - /** - * Formats the log message before writing. - * - * @var Zend_Log_Formatter_Interface - */ - protected $_formatter; - - /** - * Add a filter specific to this writer. - * - * @param Zend_Log_Filter_Interface $filter - * @return Zend_Log_Writer_Abstract - */ - public function addFilter($filter) - { - if (is_int($filter)) { - $filter = new Zend_Log_Filter_Priority($filter); - } - - if (!$filter instanceof Zend_Log_Filter_Interface) { - /** @see Zend_Log_Exception */ - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Invalid filter provided'); - } - - $this->_filters[] = $filter; - return $this; - } - - /** - * Log a message to this writer. - * - * @param array $event log data event - * @return void - */ - public function write($event) - { - foreach ($this->_filters as $filter) { - if (! $filter->accept($event)) { - return; - } - } - - // exception occurs on error - $this->_write($event); - } - - /** - * Set a new formatter for this writer - * - * @param Zend_Log_Formatter_Interface $formatter - * @return Zend_Log_Writer_Abstract - */ - public function setFormatter(Zend_Log_Formatter_Interface $formatter) - { - $this->_formatter = $formatter; - return $this; - } - - /** - * Perform shutdown activites such as closing open resources - * - * @return void - */ - public function shutdown() - {} - - /** - * Write a message to the log. - * - * @param array $event log data event - * @return void - */ - abstract protected function _write($event); - - /** - * Validate and optionally convert the config to array - * - * @param array|Zend_Config $config Zend_Config or Array - * @return array - * @throws Zend_Log_Exception - */ - static protected function _parseConfig($config) - { - if ($config instanceof Zend_Config) { - $config = $config->toArray(); - } - - if (!is_array($config)) { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception( - 'Configuration must be an array or instance of Zend_Config' - ); - } - - return $config; - } -} diff --git a/libs/Zend/Log/Writer/Db.php b/libs/Zend/Log/Writer/Db.php deleted file mode 100644 index 2c657f7ebe..0000000000 --- a/libs/Zend/Log/Writer/Db.php +++ /dev/null @@ -1,145 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Db.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** Zend_Log_Writer_Abstract */ -// require_once 'Zend/Log/Writer/Abstract.php'; - -/** - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Db.php 23775 2011-03-01 17:25:24Z ralph $ - */ -class Zend_Log_Writer_Db extends Zend_Log_Writer_Abstract -{ - /** - * Database adapter instance - * - * @var Zend_Db_Adapter - */ - private $_db; - - /** - * Name of the log table in the database - * - * @var string - */ - private $_table; - - /** - * Relates database columns names to log data field keys. - * - * @var null|array - */ - private $_columnMap; - - /** - * Class constructor - * - * @param Zend_Db_Adapter $db Database adapter instance - * @param string $table Log table in database - * @param array $columnMap - * @return void - */ - public function __construct($db, $table, $columnMap = null) - { - $this->_db = $db; - $this->_table = $table; - $this->_columnMap = $columnMap; - } - - /** - * Create a new instance of Zend_Log_Writer_Db - * - * @param array|Zend_Config $config - * @return Zend_Log_Writer_Db - */ - static public function factory($config) - { - $config = self::_parseConfig($config); - $config = array_merge(array( - 'db' => null, - 'table' => null, - 'columnMap' => null, - ), $config); - - if (isset($config['columnmap'])) { - $config['columnMap'] = $config['columnmap']; - } - - return new self( - $config['db'], - $config['table'], - $config['columnMap'] - ); - } - - /** - * Formatting is not possible on this writer - * - * @return void - * @throws Zend_Log_Exception - */ - public function setFormatter(Zend_Log_Formatter_Interface $formatter) - { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception(get_class($this) . ' does not support formatting'); - } - - /** - * Remove reference to database adapter - * - * @return void - */ - public function shutdown() - { - $this->_db = null; - } - - /** - * Write a message to the log. - * - * @param array $event event data - * @return void - * @throws Zend_Log_Exception - */ - protected function _write($event) - { - if ($this->_db === null) { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Database adapter is null'); - } - - if ($this->_columnMap === null) { - $dataToInsert = $event; - } else { - $dataToInsert = array(); - foreach ($this->_columnMap as $columnName => $fieldKey) { - $dataToInsert[$columnName] = $event[$fieldKey]; - } - } - - $this->_db->insert($this->_table, $dataToInsert); - } -} diff --git a/libs/Zend/Log/Writer/Firebug.php b/libs/Zend/Log/Writer/Firebug.php deleted file mode 100644 index cc80e20f53..0000000000 --- a/libs/Zend/Log/Writer/Firebug.php +++ /dev/null @@ -1,204 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Firebug.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** Zend_Log */ -// require_once 'Zend/Log.php'; - -/** Zend_Log_Writer_Abstract */ -// require_once 'Zend/Log/Writer/Abstract.php'; - -/** Zend_Log_Formatter_Firebug */ -// require_once 'Zend/Log/Formatter/Firebug.php'; - -/** Zend_Wildfire_Plugin_FirePhp */ -// require_once 'Zend/Wildfire/Plugin/FirePhp.php'; - -/** - * Writes log messages to the Firebug Console via FirePHP. - * - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Log_Writer_Firebug extends Zend_Log_Writer_Abstract -{ - /** - * Maps logging priorities to logging display styles - * - * @var array - */ - protected $_priorityStyles = array(Zend_Log::EMERG => Zend_Wildfire_Plugin_FirePhp::ERROR, - Zend_Log::ALERT => Zend_Wildfire_Plugin_FirePhp::ERROR, - Zend_Log::CRIT => Zend_Wildfire_Plugin_FirePhp::ERROR, - Zend_Log::ERR => Zend_Wildfire_Plugin_FirePhp::ERROR, - Zend_Log::WARN => Zend_Wildfire_Plugin_FirePhp::WARN, - Zend_Log::NOTICE => Zend_Wildfire_Plugin_FirePhp::INFO, - Zend_Log::INFO => Zend_Wildfire_Plugin_FirePhp::INFO, - Zend_Log::DEBUG => Zend_Wildfire_Plugin_FirePhp::LOG); - - /** - * The default logging style for un-mapped priorities - * - * @var string - */ - protected $_defaultPriorityStyle = Zend_Wildfire_Plugin_FirePhp::LOG; - - /** - * Flag indicating whether the log writer is enabled - * - * @var boolean - */ - protected $_enabled = true; - - /** - * Class constructor - * - * @return void - */ - public function __construct() - { - if (php_sapi_name() == 'cli') { - $this->setEnabled(false); - } - - $this->_formatter = new Zend_Log_Formatter_Firebug(); - } - - /** - * Create a new instance of Zend_Log_Writer_Firebug - * - * @param array|Zend_Config $config - * @return Zend_Log_Writer_Firebug - */ - static public function factory($config) - { - return new self(); - } - - /** - * Enable or disable the log writer. - * - * @param boolean $enabled Set to TRUE to enable the log writer - * @return boolean The previous value. - */ - public function setEnabled($enabled) - { - $previous = $this->_enabled; - $this->_enabled = $enabled; - return $previous; - } - - /** - * Determine if the log writer is enabled. - * - * @return boolean Returns TRUE if the log writer is enabled. - */ - public function getEnabled() - { - return $this->_enabled; - } - - /** - * Set the default display style for user-defined priorities - * - * @param string $style The default log display style - * @return string Returns previous default log display style - */ - public function setDefaultPriorityStyle($style) - { - $previous = $this->_defaultPriorityStyle; - $this->_defaultPriorityStyle = $style; - return $previous; - } - - /** - * Get the default display style for user-defined priorities - * - * @return string Returns the default log display style - */ - public function getDefaultPriorityStyle() - { - return $this->_defaultPriorityStyle; - } - - /** - * Set a display style for a logging priority - * - * @param int $priority The logging priority - * @param string $style The logging display style - * @return string|boolean The previous logging display style if defined or TRUE otherwise - */ - public function setPriorityStyle($priority, $style) - { - $previous = true; - if (array_key_exists($priority,$this->_priorityStyles)) { - $previous = $this->_priorityStyles[$priority]; - } - $this->_priorityStyles[$priority] = $style; - return $previous; - } - - /** - * Get a display style for a logging priority - * - * @param int $priority The logging priority - * @return string|boolean The logging display style if defined or FALSE otherwise - */ - public function getPriorityStyle($priority) - { - if (array_key_exists($priority,$this->_priorityStyles)) { - return $this->_priorityStyles[$priority]; - } - return false; - } - - /** - * Log a message to the Firebug Console. - * - * @param array $event The event data - * @return void - */ - protected function _write($event) - { - if (!$this->getEnabled()) { - return; - } - - if (array_key_exists($event['priority'],$this->_priorityStyles)) { - $type = $this->_priorityStyles[$event['priority']]; - } else { - $type = $this->_defaultPriorityStyle; - } - - $message = $this->_formatter->format($event); - - $label = isset($event['firebugLabel'])?$event['firebugLabel']:null; - - Zend_Wildfire_Plugin_FirePhp::getInstance()->send($message, - $label, - $type, - array('traceOffset'=>4, - 'fixZendLogOffsetIfApplicable'=>true)); - } -} diff --git a/libs/Zend/Log/Writer/Mail.php b/libs/Zend/Log/Writer/Mail.php deleted file mode 100644 index af7cbbcfd0..0000000000 --- a/libs/Zend/Log/Writer/Mail.php +++ /dev/null @@ -1,430 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Mail.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** Zend_Log_Writer_Abstract */ -// require_once 'Zend/Log/Writer/Abstract.php'; - -/** Zend_Log_Exception */ -// require_once 'Zend/Log/Exception.php'; - -/** Zend_Log_Formatter_Simple*/ -// require_once 'Zend/Log/Formatter/Simple.php'; - -/** - * Class used for writing log messages to email via Zend_Mail. - * - * Allows for emailing log messages at and above a certain level via a - * Zend_Mail object. Note that this class only sends the email upon - * completion, so any log entries accumulated are sent in a single email. - * - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Mail.php 23775 2011-03-01 17:25:24Z ralph $ - */ -class Zend_Log_Writer_Mail extends Zend_Log_Writer_Abstract -{ - /** - * Array of formatted events to include in message body. - * - * @var array - */ - protected $_eventsToMail = array(); - - /** - * Array of formatted lines for use in an HTML email body; these events - * are formatted with an optional formatter if the caller is using - * Zend_Layout. - * - * @var array - */ - protected $_layoutEventsToMail = array(); - - /** - * Zend_Mail instance to use - * - * @var Zend_Mail - */ - protected $_mail; - - /** - * Zend_Layout instance to use; optional. - * - * @var Zend_Layout - */ - protected $_layout; - - /** - * Optional formatter for use when rendering with Zend_Layout. - * - * @var Zend_Log_Formatter_Interface - */ - protected $_layoutFormatter; - - /** - * Array keeping track of the number of entries per priority level. - * - * @var array - */ - protected $_numEntriesPerPriority = array(); - - /** - * Subject prepend text. - * - * Can only be used of the Zend_Mail object has not already had its - * subject line set. Using this will cause the subject to have the entry - * counts per-priority level appended to it. - * - * @var string|null - */ - protected $_subjectPrependText; - - /** - * MethodMap for Zend_Mail's headers - * - * @var array - */ - protected static $_methodMapHeaders = array( - 'from' => 'setFrom', - 'to' => 'addTo', - 'cc' => 'addCc', - 'bcc' => 'addBcc', - ); - - /** - * Class constructor. - * - * Constructs the mail writer; requires a Zend_Mail instance, and takes an - * optional Zend_Layout instance. If Zend_Layout is being used, - * $this->_layout->events will be set for use in the layout template. - * - * @param Zend_Mail $mail Mail instance - * @param Zend_Layout $layout Layout instance; optional - * @return void - */ - public function __construct(Zend_Mail $mail, Zend_Layout $layout = null) - { - $this->_mail = $mail; - if (null !== $layout) { - $this->setLayout($layout); - } - $this->_formatter = new Zend_Log_Formatter_Simple(); - } - - /** - * Create a new instance of Zend_Log_Writer_Mail - * - * @param array|Zend_Config $config - * @return Zend_Log_Writer_Mail - */ - static public function factory($config) - { - $config = self::_parseConfig($config); - $mail = self::_constructMailFromConfig($config); - $writer = new self($mail); - - if (isset($config['layout']) || isset($config['layoutOptions'])) { - $writer->setLayout($config); - } - if (isset($config['layoutFormatter'])) { - $layoutFormatter = new $config['layoutFormatter']; - $writer->setLayoutFormatter($layoutFormatter); - } - if (isset($config['subjectPrependText'])) { - $writer->setSubjectPrependText($config['subjectPrependText']); - } - - return $writer; - } - - /** - * Set the layout - * - * @param Zend_Layout|array $layout - * @return Zend_Log_Writer_Mail - * @throws Zend_Log_Exception - */ - public function setLayout($layout) - { - if (is_array($layout)) { - $layout = $this->_constructLayoutFromConfig($layout); - } - - if (!$layout instanceof Zend_Layout) { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Mail must be an instance of Zend_Layout or an array'); - } - $this->_layout = $layout; - - return $this; - } - - /** - * Construct a Zend_Mail instance based on a configuration array - * - * @param array $config - * @return Zend_Mail - * @throws Zend_Log_Exception - */ - protected static function _constructMailFromConfig(array $config) - { - $mailClass = 'Zend_Mail'; - if (isset($config['mail'])) { - $mailClass = $config['mail']; - } - - if (!array_key_exists('charset', $config)) { - $config['charset'] = null; - } - $mail = new $mailClass($config['charset']); - if (!$mail instanceof Zend_Mail) { - throw new Zend_Log_Exception($mail . 'must extend Zend_Mail'); - } - - if (isset($config['subject'])) { - $mail->setSubject($config['subject']); - } - - $headerAddresses = array_intersect_key($config, self::$_methodMapHeaders); - if (count($headerAddresses)) { - foreach ($headerAddresses as $header => $address) { - $method = self::$_methodMapHeaders[$header]; - if (is_array($address) && isset($address['name']) - && !is_numeric($address['name']) - ) { - $params = array( - $address['email'], - $address['name'] - ); - } else if (is_array($address) && isset($address['email'])) { - $params = array($address['email']); - } else { - $params = array($address); - } - call_user_func_array(array($mail, $method), $params); - } - } - - return $mail; - } - - /** - * Construct a Zend_Layout instance based on a configuration array - * - * @param array $config - * @return Zend_Layout - * @throws Zend_Log_Exception - */ - protected function _constructLayoutFromConfig(array $config) - { - $config = array_merge(array( - 'layout' => 'Zend_Layout', - 'layoutOptions' => null - ), $config); - - $layoutClass = $config['layout']; - $layout = new $layoutClass($config['layoutOptions']); - if (!$layout instanceof Zend_Layout) { - throw new Zend_Log_Exception($layout . 'must extend Zend_Layout'); - } - - return $layout; - } - - /** - * Places event line into array of lines to be used as message body. - * - * Handles the formatting of both plaintext entries, as well as those - * rendered with Zend_Layout. - * - * @param array $event Event data - * @return void - */ - protected function _write($event) - { - // Track the number of entries per priority level. - if (!isset($this->_numEntriesPerPriority[$event['priorityName']])) { - $this->_numEntriesPerPriority[$event['priorityName']] = 1; - } else { - $this->_numEntriesPerPriority[$event['priorityName']]++; - } - - $formattedEvent = $this->_formatter->format($event); - - // All plaintext events are to use the standard formatter. - $this->_eventsToMail[] = $formattedEvent; - - // If we have a Zend_Layout instance, use a specific formatter for the - // layout if one exists. Otherwise, just use the event with its - // default format. - if ($this->_layout) { - if ($this->_layoutFormatter) { - $this->_layoutEventsToMail[] = - $this->_layoutFormatter->format($event); - } else { - $this->_layoutEventsToMail[] = $formattedEvent; - } - } - } - - /** - * Gets instance of Zend_Log_Formatter_Instance used for formatting a - * message using Zend_Layout, if applicable. - * - * @return Zend_Log_Formatter_Interface|null The formatter, or null. - */ - public function getLayoutFormatter() - { - return $this->_layoutFormatter; - } - - /** - * Sets a specific formatter for use with Zend_Layout events. - * - * Allows use of a second formatter on lines that will be rendered with - * Zend_Layout. In the event that Zend_Layout is not being used, this - * formatter cannot be set, so an exception will be thrown. - * - * @param Zend_Log_Formatter_Interface $formatter - * @return Zend_Log_Writer_Mail - * @throws Zend_Log_Exception - */ - public function setLayoutFormatter(Zend_Log_Formatter_Interface $formatter) - { - if (!$this->_layout) { - throw new Zend_Log_Exception( - 'cannot set formatter for layout; ' . - 'a Zend_Layout instance is not in use'); - } - - $this->_layoutFormatter = $formatter; - return $this; - } - - /** - * Allows caller to have the mail subject dynamically set to contain the - * entry counts per-priority level. - * - * Sets the text for use in the subject, with entry counts per-priority - * level appended to the end. Since a Zend_Mail subject can only be set - * once, this method cannot be used if the Zend_Mail object already has a - * subject set. - * - * @param string $subject Subject prepend text. - * @return Zend_Log_Writer_Mail - * @throws Zend_Log_Exception - */ - public function setSubjectPrependText($subject) - { - if ($this->_mail->getSubject()) { - throw new Zend_Log_Exception( - 'subject already set on mail; ' . - 'cannot set subject prepend text'); - } - - $this->_subjectPrependText = (string) $subject; - return $this; - } - - /** - * Sends mail to recipient(s) if log entries are present. Note that both - * plaintext and HTML portions of email are handled here. - * - * @return void - */ - public function shutdown() - { - // If there are events to mail, use them as message body. Otherwise, - // there is no mail to be sent. - if (empty($this->_eventsToMail)) { - return; - } - - if ($this->_subjectPrependText !== null) { - // Tack on the summary of entries per-priority to the subject - // line and set it on the Zend_Mail object. - $numEntries = $this->_getFormattedNumEntriesPerPriority(); - $this->_mail->setSubject( - "{$this->_subjectPrependText} ({$numEntries})"); - } - - - // Always provide events to mail as plaintext. - $this->_mail->setBodyText(implode('', $this->_eventsToMail)); - - // If a Zend_Layout instance is being used, set its "events" - // value to the lines formatted for use with the layout. - if ($this->_layout) { - // Set the required "messages" value for the layout. Here we - // are assuming that the layout is for use with HTML. - $this->_layout->events = - implode('', $this->_layoutEventsToMail); - - // If an exception occurs during rendering, convert it to a notice - // so we can avoid an exception thrown without a stack frame. - try { - $this->_mail->setBodyHtml($this->_layout->render()); - } catch (Exception $e) { - trigger_error( - "exception occurred when rendering layout; " . - "unable to set html body for message; " . - "message = {$e->getMessage()}; " . - "code = {$e->getCode()}; " . - "exception class = " . get_class($e), - E_USER_NOTICE); - } - } - - // Finally, send the mail. If an exception occurs, convert it into a - // warning-level message so we can avoid an exception thrown without a - // stack frame. - try { - $this->_mail->send(); - } catch (Exception $e) { - trigger_error( - "unable to send log entries via email; " . - "message = {$e->getMessage()}; " . - "code = {$e->getCode()}; " . - "exception class = " . get_class($e), - E_USER_WARNING); - } - } - - /** - * Gets a string of number of entries per-priority level that occurred, or - * an emptry string if none occurred. - * - * @return string - */ - protected function _getFormattedNumEntriesPerPriority() - { - $strings = array(); - - foreach ($this->_numEntriesPerPriority as $priority => $numEntries) { - $strings[] = "{$priority}={$numEntries}"; - } - - return implode(', ', $strings); - } -} diff --git a/libs/Zend/Log/Writer/Mock.php b/libs/Zend/Log/Writer/Mock.php deleted file mode 100644 index b4d8fa1252..0000000000 --- a/libs/Zend/Log/Writer/Mock.php +++ /dev/null @@ -1,81 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Mock.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** Zend_Log_Writer_Abstract */ -// require_once 'Zend/Log/Writer/Abstract.php'; - -/** - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Mock.php 23775 2011-03-01 17:25:24Z ralph $ - */ -class Zend_Log_Writer_Mock extends Zend_Log_Writer_Abstract -{ - /** - * array of log events - * - * @var array - */ - public $events = array(); - - /** - * shutdown called? - * - * @var boolean - */ - public $shutdown = false; - - /** - * Write a message to the log. - * - * @param array $event event data - * @return void - */ - public function _write($event) - { - $this->events[] = $event; - } - - /** - * Record shutdown - * - * @return void - */ - public function shutdown() - { - $this->shutdown = true; - } - - /** - * Create a new instance of Zend_Log_Writer_Mock - * - * @param array|Zend_Config $config - * @return Zend_Log_Writer_Mock - */ - static public function factory($config) - { - return new self(); - } -} diff --git a/libs/Zend/Log/Writer/Null.php b/libs/Zend/Log/Writer/Null.php deleted file mode 100644 index f4471aa0f9..0000000000 --- a/libs/Zend/Log/Writer/Null.php +++ /dev/null @@ -1,56 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Null.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** Zend_Log_Writer_Abstract */ -// require_once 'Zend/Log/Writer/Abstract.php'; - -/** - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Null.php 23775 2011-03-01 17:25:24Z ralph $ - */ -class Zend_Log_Writer_Null extends Zend_Log_Writer_Abstract -{ - /** - * Write a message to the log. - * - * @param array $event event data - * @return void - */ - protected function _write($event) - { - } - - /** - * Create a new instance of Zend_Log_Writer_Null - * - * @param array|Zend_Config $config - * @return Zend_Log_Writer_Null - */ - static public function factory($config) - { - return new self(); - } -} diff --git a/libs/Zend/Log/Writer/Stream.php b/libs/Zend/Log/Writer/Stream.php deleted file mode 100644 index 2e576dbecc..0000000000 --- a/libs/Zend/Log/Writer/Stream.php +++ /dev/null @@ -1,138 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Stream.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** Zend_Log_Writer_Abstract */ -// require_once 'Zend/Log/Writer/Abstract.php'; - -/** Zend_Log_Formatter_Simple */ -// require_once 'Zend/Log/Formatter/Simple.php'; - -/** - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Stream.php 23775 2011-03-01 17:25:24Z ralph $ - */ -class Zend_Log_Writer_Stream extends Zend_Log_Writer_Abstract -{ - /** - * Holds the PHP stream to log to. - * - * @var null|stream - */ - protected $_stream = null; - - /** - * Class Constructor - * - * @param array|string|resource $streamOrUrl Stream or URL to open as a stream - * @param string|null $mode Mode, only applicable if a URL is given - * @return void - * @throws Zend_Log_Exception - */ - public function __construct($streamOrUrl, $mode = null) - { - // Setting the default - if (null === $mode) { - $mode = 'a'; - } - - if (is_resource($streamOrUrl)) { - if (get_resource_type($streamOrUrl) != 'stream') { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Resource is not a stream'); - } - - if ($mode != 'a') { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Mode cannot be changed on existing streams'); - } - - $this->_stream = $streamOrUrl; - } else { - if (is_array($streamOrUrl) && isset($streamOrUrl['stream'])) { - $streamOrUrl = $streamOrUrl['stream']; - } - - if (! $this->_stream = @fopen($streamOrUrl, $mode, false)) { - // require_once 'Zend/Log/Exception.php'; - $msg = "\"$streamOrUrl\" cannot be opened with mode \"$mode\""; - throw new Zend_Log_Exception($msg); - } - } - - $this->_formatter = new Zend_Log_Formatter_Simple(); - } - - /** - * Create a new instance of Zend_Log_Writer_Stream - * - * @param array|Zend_Config $config - * @return Zend_Log_Writer_Stream - */ - static public function factory($config) - { - $config = self::_parseConfig($config); - $config = array_merge(array( - 'stream' => null, - 'mode' => null, - ), $config); - - $streamOrUrl = isset($config['url']) ? $config['url'] : $config['stream']; - - return new self( - $streamOrUrl, - $config['mode'] - ); - } - - /** - * Close the stream resource. - * - * @return void - */ - public function shutdown() - { - if (is_resource($this->_stream)) { - fclose($this->_stream); - } - } - - /** - * Write a message to the log. - * - * @param array $event event data - * @return void - * @throws Zend_Log_Exception - */ - protected function _write($event) - { - $line = $this->_formatter->format($event); - - if (false === @fwrite($this->_stream, $line)) { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception("Unable to write to stream"); - } - } -} diff --git a/libs/Zend/Log/Writer/Syslog.php b/libs/Zend/Log/Writer/Syslog.php deleted file mode 100644 index 3c85e709ea..0000000000 --- a/libs/Zend/Log/Writer/Syslog.php +++ /dev/null @@ -1,267 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: Syslog.php 23953 2011-05-03 05:47:39Z ralph $ - */ - -/** Zend_Log */ -// require_once 'Zend/Log.php'; - -/** Zend_Log_Writer_Abstract */ -// require_once 'Zend/Log/Writer/Abstract.php'; - -/** - * Writes log messages to syslog - * - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - */ -class Zend_Log_Writer_Syslog extends Zend_Log_Writer_Abstract -{ - /** - * Maps Zend_Log priorities to PHP's syslog priorities - * - * @var array - */ - protected $_priorities = array( - Zend_Log::EMERG => LOG_EMERG, - Zend_Log::ALERT => LOG_ALERT, - Zend_Log::CRIT => LOG_CRIT, - Zend_Log::ERR => LOG_ERR, - Zend_Log::WARN => LOG_WARNING, - Zend_Log::NOTICE => LOG_NOTICE, - Zend_Log::INFO => LOG_INFO, - Zend_Log::DEBUG => LOG_DEBUG, - ); - - /** - * The default log priority - for unmapped custom priorities - * - * @var string - */ - protected $_defaultPriority = LOG_NOTICE; - - /** - * Last application name set by a syslog-writer instance - * - * @var string - */ - protected static $_lastApplication; - - /** - * Last facility name set by a syslog-writer instance - * - * @var string - */ - protected static $_lastFacility; - - /** - * Application name used by this syslog-writer instance - * - * @var string - */ - protected $_application = 'Zend_Log'; - - /** - * Facility used by this syslog-writer instance - * - * @var int - */ - protected $_facility = LOG_USER; - - /** - * Types of program available to logging of message - * - * @var array - */ - protected $_validFacilities = array(); - - /** - * Class constructor - * - * @param array $params Array of options; may include "application" and "facility" keys - * @return void - */ - public function __construct(array $params = array()) - { - if (isset($params['application'])) { - $this->_application = $params['application']; - } - - $runInitializeSyslog = true; - if (isset($params['facility'])) { - $this->setFacility($params['facility']); - $runInitializeSyslog = false; - } - - if ($runInitializeSyslog) { - $this->_initializeSyslog(); - } - } - - /** - * Create a new instance of Zend_Log_Writer_Syslog - * - * @param array|Zend_Config $config - * @return Zend_Log_Writer_Syslog - */ - static public function factory($config) - { - return new self(self::_parseConfig($config)); - } - - /** - * Initialize values facilities - * - * @return void - */ - protected function _initializeValidFacilities() - { - $constants = array( - 'LOG_AUTH', - 'LOG_AUTHPRIV', - 'LOG_CRON', - 'LOG_DAEMON', - 'LOG_KERN', - 'LOG_LOCAL0', - 'LOG_LOCAL1', - 'LOG_LOCAL2', - 'LOG_LOCAL3', - 'LOG_LOCAL4', - 'LOG_LOCAL5', - 'LOG_LOCAL6', - 'LOG_LOCAL7', - 'LOG_LPR', - 'LOG_MAIL', - 'LOG_NEWS', - 'LOG_SYSLOG', - 'LOG_USER', - 'LOG_UUCP' - ); - - foreach ($constants as $constant) { - if (defined($constant)) { - $this->_validFacilities[] = constant($constant); - } - } - } - - /** - * Initialize syslog / set application name and facility - * - * @return void - */ - protected function _initializeSyslog() - { - self::$_lastApplication = $this->_application; - self::$_lastFacility = $this->_facility; - openlog($this->_application, LOG_PID, $this->_facility); - } - - /** - * Set syslog facility - * - * @param int $facility Syslog facility - * @return Zend_Log_Writer_Syslog - * @throws Zend_Log_Exception for invalid log facility - */ - public function setFacility($facility) - { - if ($this->_facility === $facility) { - return $this; - } - - if (!count($this->_validFacilities)) { - $this->_initializeValidFacilities(); - } - - if (!in_array($facility, $this->_validFacilities)) { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Invalid log facility provided; please see http://php.net/openlog for a list of valid facility values'); - } - - if ('WIN' == strtoupper(substr(PHP_OS, 0, 3)) - && ($facility !== LOG_USER) - ) { - // require_once 'Zend/Log/Exception.php'; - throw new Zend_Log_Exception('Only LOG_USER is a valid log facility on Windows'); - } - - $this->_facility = $facility; - $this->_initializeSyslog(); - return $this; - } - - /** - * Set application name - * - * @param string $application Application name - * @return Zend_Log_Writer_Syslog - */ - public function setApplicationName($application) - { - if ($this->_application === $application) { - return $this; - } - $this->_application = $application; - $this->_initializeSyslog(); - return $this; - } - - /** - * Close syslog. - * - * @return void - */ - public function shutdown() - { - closelog(); - } - - /** - * Write a message to syslog. - * - * @param array $event event data - * @return void - */ - protected function _write($event) - { - if (array_key_exists($event['priority'], $this->_priorities)) { - $priority = $this->_priorities[$event['priority']]; - } else { - $priority = $this->_defaultPriority; - } - - if ($this->_application !== self::$_lastApplication - || $this->_facility !== self::$_lastFacility) - { - $this->_initializeSyslog(); - } - - $message = $event['message']; - if ($this->_formatter instanceof Zend_Log_Formatter_Interface) { - $message = $this->_formatter->format($event); - } - - syslog($priority, $message); - } -} diff --git a/libs/Zend/Log/Writer/ZendMonitor.php b/libs/Zend/Log/Writer/ZendMonitor.php deleted file mode 100644 index 733c1183fb..0000000000 --- a/libs/Zend/Log/Writer/ZendMonitor.php +++ /dev/null @@ -1,131 +0,0 @@ -<?php -/** - * Zend Framework - * - * LICENSE - * - * This source file is subject to the new BSD license that is bundled - * with this package in the file LICENSE.txt. - * It is also available through the world-wide-web at this URL: - * http://framework.zend.com/license/new-bsd - * If you did not receive a copy of the license and are unable to - * obtain it through the world-wide-web, please send an email - * to license@zend.com so we can send you a copy immediately. - * - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: ZendMonitor.php 23775 2011-03-01 17:25:24Z ralph $ - */ - -/** Zend_Log_Writer_Abstract */ -// require_once 'Zend/Log/Writer/Abstract.php'; - -/** - * @category Zend - * @package Zend_Log - * @subpackage Writer - * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com) - * @license http://framework.zend.com/license/new-bsd New BSD License - * @version $Id: ZendMonitor.php 23775 2011-03-01 17:25:24Z ralph $ - */ -class Zend_Log_Writer_ZendMonitor extends Zend_Log_Writer_Abstract -{ - /** - * Is Zend Monitor enabled? - * - * @var boolean - */ - protected $_isEnabled = true; - - /** - * Is this for a Zend Server intance? - * - * @var boolean - */ - protected $_isZendServer = false; - - /** - * @return void - */ - public function __construct() - { - if (!function_exists('monitor_custom_event')) { - $this->_isEnabled = false; - } - if (function_exists('zend_monitor_custom_event')) { - $this->_isZendServer = true; - } - } - - /** - * Create a new instance of Zend_Log_Writer_ZendMonitor - * - * @param array|Zend_Config $config - * @return Zend_Log_Writer_ZendMonitor - */ - static public function factory($config) - { - return new self(); - } - - /** - * Is logging to this writer enabled? - * - * If the Zend Monitor extension is not enabled, this log writer will - * fail silently. You can query this method to determine if the log - * writer is enabled. - * - * @return boolean - */ - public function isEnabled() - { - return $this->_isEnabled; - } - - /** - * Log a message to this writer. - * - * @param array $event log data event - * @return void - */ - public function write($event) - { - if (!$this->isEnabled()) { - return; - } - - parent::write($event); - } - - /** - * Write a message to the log. - * - * @param array $event log data event - * @return void - */ - protected function _write($event) - { - $priority = $event['priority']; - $message = $event['message']; - unset($event['priority'], $event['message']); - - if (!empty($event)) { - if ($this->_isZendServer) { - // On Zend Server; third argument should be the event - zend_monitor_custom_event($priority, $message, $event); - } else { - // On Zend Platform; third argument is severity -- either - // 0 or 1 -- and fourth is optional (event) - // Severity is either 0 (normal) or 1 (severe); classifying - // notice, info, and debug as "normal", and all others as - // "severe" - monitor_custom_event($priority, $message, ($priority > 4) ? 0 : 1, $event); - } - } else { - monitor_custom_event($priority, $message); - } - } -} diff --git a/misc/cron/archive.php b/misc/cron/archive.php index 33625addb0..e7160ece36 100644 --- a/misc/cron/archive.php +++ b/misc/cron/archive.php @@ -638,8 +638,8 @@ class CronArchive { $config = Config::getInstance(); $config->log['log_only_when_debug_parameter'] = 0; - $config->log['logger_message'] = array("logger_message" => "screen"); - \Piwik\Log::make(); + $config->log['logger_writers'] = array("screen"); + $config->log['log_level'] = 'INFO'; if (!function_exists("curl_multi_init")) { $this->log("ERROR: this script requires curl extension php_curl enabled in your CLI php.ini"); diff --git a/tests/PHPUnit/Core/LogTest.php b/tests/PHPUnit/Core/LogTest.php new file mode 100644 index 0000000000..1ae78c63a3 --- /dev/null +++ b/tests/PHPUnit/Core/LogTest.php @@ -0,0 +1,263 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ +use Piwik\Error; +use Piwik\Config; +use Piwik\Log; +use Piwik\Common; +use Piwik\Db; +use Piwik\ExceptionHandler; + +require_once PIWIK_INCLUDE_PATH . '/tests/resources/TestPluginLogClass.php'; +use Piwik\Plugins\TestPlugin\TestLoggingUtility; + +class LogTest extends DatabaseTestCase +{ + const TESTMESSAGE = 'test%smessage'; + const STRING_MESSAGE_FORMAT = '[%tag%] %message%'; + const STRING_MESSAGE_FORMAT_SPRINTF = "[%s] %s"; + + public static $expectedExceptionOutput = array( + 'screen' => 'dummy error message<br /> + <br /> + --> To temporarily debug this error further, set const DISPLAY_BACKTRACE_DEBUG=true; in ResponseBuilder.php', + 'file' => '[LogTest] LogTest.php(156): dummy error message +dummy backtrace', + 'database' => '[LogTest] LogTest.php(156): dummy error message +dummy backtrace' + ); + + public static $expectedErrorOutput = array( + 'screen' => ' +<div style=\'word-wrap: break-word; border: 3px solid red; padding:4px; width:70%; background-color:#FFFF96;\'> + <strong>There is an error. Please report the message (Piwik 2.0-a7) + and full backtrace in the <a href=\'?module=Proxy&action=redirect&url=http://forum.piwik.org\' target=\'_blank\'>Piwik forums</a> (please do a Search first as it might have been reported already!).<br /><br/> + Unknown error (102):</strong> <em>dummy error string</em> in <strong>dummyerrorfile.php</strong> on line <strong>145</strong> +<br /><br />Backtrace --><div style="font-family:Courier;font-size:10pt"><br /> +dummy backtrace</div><br /> + </pre></div><br />', + 'file' => '[LogTest] dummyerrorfile.php(145): Unknown error (102) - dummy error string +dummy backtrace', + 'database' => '[LogTest] dummyerrorfile.php(145): Unknown error (102) - dummy error string +dummy backtrace' + ); + + private $screenOutput; + + public static function setUpBeforeClass() + { + Error::setErrorHandler(); + ExceptionHandler::setUp(); + } + + public static function tearDownAfterClass() + { + restore_error_handler(); + restore_exception_handler(); + } + + public function setUp() + { + parent::setUp(); + + Config::getInstance()->log['string_message_format'] = self::STRING_MESSAGE_FORMAT; + Config::getInstance()->log['logger_file_path'] = self::getLogFileLocation(); + @unlink(self::getLogFileLocation()); + Log::clearInstance(); + Error::$debugBacktraceForTests = ExceptionHandler::$debugBacktraceForTests = "dummy backtrace"; + } + + public function tearDown() + { + parent::tearDown(); + + Log::clearInstance(); + @unlink(self::getLogFileLocation()); + Error::$debugBacktraceForTests = ExceptionHandler::$debugBacktraceForTests = null; + } + + /** + * Data provider for every test. + */ + public function getBackendsToTest() + { + return array(array('screen'), + array('file'), + array('database')); + } + + /** + * @group Core + * @group Access + * @dataProvider getBackendsToTest + */ + public function testLoggingWorksWhenMessageIsString($backend) + { + Config::getInstance()->log['log_writers'] = array($backend); + + ob_start(); + Log::warning(self::TESTMESSAGE); + $this->screenOutput = ob_get_contents(); + ob_end_clean(); + + $this->checkBackend($backend, self::TESTMESSAGE, $formatMessage = true, $tag = 'LogTest'); + } + + /** + * @group Core + * @group Access + * @dataProvider getBackendsToTest + */ + public function testLoggingWorksWhenMessageIsSprintfString($backend) + { + Config::getInstance()->log['log_writers'] = array($backend); + + ob_start(); + Log::warning(self::TESTMESSAGE, " subst "); + $this->screenOutput = ob_get_contents(); + ob_end_clean(); + + $this->checkBackend($backend, sprintf(self::TESTMESSAGE, " subst "), $formatMessage = true, $tag = 'LogTest'); + } + + /** + * @group Core + * @group Access + * @dataProvider getBackendsToTest + */ + public function testLoggingWorksWhenMessageIsError($backend) + { + Config::getInstance()->log['log_writers'] = array($backend); + + ob_start(); + $error = new Error(102, "dummy error string", "dummyerrorfile.php", 145, "dummy backtrace"); + Log::error($error); + $this->screenOutput = ob_get_contents(); + ob_end_clean(); + + $this->checkBackend($backend, self::$expectedErrorOutput[$backend], $formatMessage = false, $tag = 'LogTest'); + $this->checkBackend('screen', self::$expectedErrorOutput['screen']); // errors should always written to the screen + } + + /** + * @group Core + * @group Access + * @dataProvider getBackendsToTest + */ + public function testLoggingWorksWhenMessageIsException($backend) + { + Config::getInstance()->log['log_writers'] = array($backend); + + ob_start(); + $exception = new Exception("dummy error message"); + Log::error($exception); + $this->screenOutput = ob_get_contents(); + ob_end_clean(); + + $this->checkBackend($backend, self::$expectedExceptionOutput[$backend], $formatMessage = false, $tag = 'LogTest'); + $this->checkBackend('screen', self::$expectedExceptionOutput['screen']); // errors should always written to the screen + } + + /** + * @group Core + * @group Access + * @dataProvider getBackendsToTest + */ + public function testLoggingCorrectlyIdentifiesPlugin($backend) + { + Config::getInstance()->log['log_writers'] = array($backend); + + ob_start(); + TestLoggingUtility::doLog(self::TESTMESSAGE); + $this->screenOutput = ob_get_contents(); + ob_end_clean(); + + $this->checkBackend($backend, self::TESTMESSAGE, $formatMessage = true, $tag = 'TestPlugin'); + } + + /** + * @group Core + * @group Access + * @dataProvider getBackendsToTest + */ + public function testLogMessagesIgnoredWhenNotWithinLevel($backend) + { + Config::getInstance()->log['log_writers'] = array($backend); + + ob_start(); + Log::info(self::TESTMESSAGE); + $this->screenOutput = ob_get_contents(); + ob_end_clean(); + + $this->checkNoMessagesLogged($backend); + } + + private function checkBackend($backend, $expectedMessage, $formatMessage = false, $tag = false) + { + if ($formatMessage) { + $expectedMessage = sprintf(self::STRING_MESSAGE_FORMAT_SPRINTF, $tag, $expectedMessage); + } + + if ($backend == 'screen') { + if ($formatMessage) { + $expectedMessage = '<pre>' . $expectedMessage . '</pre>'; + } + + $this->screenOutput = $this->removePathsFromBacktrace($this->screenOutput); + + $this->assertEquals($expectedMessage . "\n", $this->screenOutput); + } else if ($backend == 'file') { + $this->assertTrue(file_exists(self::getLogFileLocation())); + + $fileContents = file_get_contents(self::getLogFileLocation()); + $fileContents = $this->removePathsFromBacktrace($fileContents); + + $this->assertEquals($expectedMessage . "\n", $fileContents); + } else if ($backend == 'database') { + $count = Db::fetchOne("SELECT COUNT(*) FROM " . Common::prefixTable('logger_message')); + $this->assertEquals(1, $count); + + $message = Db::fetchOne("SELECT message FROM " . Common::prefixTable('logger_message') . " LIMIT 1"); + $message = $this->removePathsFromBacktrace($message); + $this->assertEquals($expectedMessage, $message); + + $tagInDb = Db::fetchOne("SELECT tag FROM " . Common::prefixTable('logger_message') . " LIMIT 1"); + if ($tag === false) { + $this->assertEmpty($tagInDb); + } else { + $this->assertEquals($tag, $tagInDb); + } + } + } + + private function checkNoMessagesLogged($backend) + { + if ($backend == 'screen') { + $this->assertEmpty($this->screenOutput); + } else if ($backend == 'file') { + $this->assertFalse(file_exists(self::getLogFileLocation())); + } else if ($backend == 'database') { + $this->assertEquals(0, Db::fetchOne("SELECT COUNT(*) FROM " . Common::prefixTable('logger_message'))); + } + } + + private function removePathsFromBacktrace($content) + { + return preg_replace_callback("/(?:\/[^\s(<>]+)*\//", function ($matches) { + if ($matches[0] == '/') { + return '/'; + } else { + return ''; + } + }, $content); + } + + public static function getLogFileLocation() + { + return PIWIK_INCLUDE_PATH . '/tmp/logs/piwik.test.log'; + } +}
\ No newline at end of file diff --git a/tests/PHPUnit/Core/ReleaseCheckListTest.php b/tests/PHPUnit/Core/ReleaseCheckListTest.php index 3cc3fdd5b2..d4bfc2688d 100644 --- a/tests/PHPUnit/Core/ReleaseCheckListTest.php +++ b/tests/PHPUnit/Core/ReleaseCheckListTest.php @@ -33,9 +33,8 @@ class ReleaseCheckListTest extends PHPUnit_Framework_TestCase $this->_checkEqual(array('Tracker' => 'visit_standard_length'), '1800'); $this->_checkEqual(array('Tracker' => 'trust_visitors_cookies'), '0'); // logging messages are disabled - $this->_checkEqual(array('log' => 'logger_message'), ''); - $this->_checkEqual(array('log' => 'logger_exception'), array('screen')); - $this->_checkEqual(array('log' => 'logger_error'), array('screen')); + $this->_checkEqual(array('log' => 'log_level'), 'WARN'); + $this->_checkEqual(array('log' => 'log_writers'), array('file')); $this->_checkEqual(array('log' => 'logger_api_call'), null); } diff --git a/tests/PHPUnit/DatabaseTestCase.php b/tests/PHPUnit/DatabaseTestCase.php index 112219f177..c91651ad97 100644 --- a/tests/PHPUnit/DatabaseTestCase.php +++ b/tests/PHPUnit/DatabaseTestCase.php @@ -47,7 +47,6 @@ class DatabaseTestCase extends PHPUnit_Framework_TestCase Db::createDatabaseObject(); DbHelper::createTables(); - \Piwik\Log::make(); // \Piwik\PluginsManager::getInstance()->loadPlugins(array()); IntegrationTestCase::loadAllPlugins(); diff --git a/tests/PHPUnit/IntegrationTestCase.php b/tests/PHPUnit/IntegrationTestCase.php index c16614073c..4294f3109b 100755 --- a/tests/PHPUnit/IntegrationTestCase.php +++ b/tests/PHPUnit/IntegrationTestCase.php @@ -168,7 +168,6 @@ abstract class IntegrationTestCase extends PHPUnit_Framework_TestCase Db::createDatabaseObject(); DbHelper::createTables(); - \Piwik\Log::make(); \Piwik\PluginsManager::getInstance()->loadPlugins(array()); } catch (Exception $e) { diff --git a/tests/resources/TestPluginLogClass.php b/tests/resources/TestPluginLogClass.php new file mode 100644 index 0000000000..090824c584 --- /dev/null +++ b/tests/resources/TestPluginLogClass.php @@ -0,0 +1,18 @@ +<?php +/** + * Piwik - Open source web analytics + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ +namespace Piwik\Plugins\TestPlugin; + +use Piwik\Log; + +class TestLoggingUtility +{ + public static function doLog($message) + { + Log::warning($message); + } +}
\ No newline at end of file diff --git a/tests/travis/prepare.sh b/tests/travis/prepare.sh index 3b02122aec..8ba216da70 100755 --- a/tests/travis/prepare.sh +++ b/tests/travis/prepare.sh @@ -33,4 +33,5 @@ mkdir ./tmp/latest mkdir ./tmp/sessions mkdir ./tmp/templates_c mkdir ./tmp/tcpdf +mkdir ./tmp/logs chmod a+rw ./tests/lib/geoip-files |