Merge pull request 'feature/make-logrotation-switchable-#9' (#50) from feature/make-logrotation-switchable-#9 into develop

Reviewed-on: #50
Dieser Commit ist enthalten in:
Ortwin Pinke 2024-03-12 18:26:55 +00:00
Commit 28b037b0a5
29 geänderte Dateien mit 1014 neuen und 1232 gelöschten Zeilen

Datei anzeigen

@ -0,0 +1,8 @@
<?php
namespace ConLite\Exceptions;
class Exception extends \Exception
{
}

Datei anzeigen

@ -0,0 +1,8 @@
<?php
namespace ConLite\Exceptions;
class FileNotFoundException extends RuntimeException
{
}

Datei anzeigen

@ -0,0 +1,8 @@
<?php
namespace ConLite\Exceptions;
class InvalidArgumentException extends LogicException
{
}

Datei anzeigen

@ -0,0 +1,8 @@
<?php
namespace ConLite\Exceptions;
class LogicException extends Exception
{
}

Datei anzeigen

@ -0,0 +1,8 @@
<?php
namespace ConLite\Exceptions;
class RuntimeException extends Exception
{
}

306
conlite/classes/Log/Log.php Normale Datei
Datei anzeigen

@ -0,0 +1,306 @@
<?php
namespace ConLite\Log;
use ConLite\Exceptions\InvalidArgumentException;
use cString;
use ReflectionClass;
class Log
{
/**
* logging level
*
* @var int
*/
const EMERG = 0;
/**
* logging level
*
* @var int
*/
const ALERT = 1;
/**
* logging level
*
* @var int
*/
const CRIT = 2;
/**
* logging level
*
* @var int
*/
const ERR = 3;
/**
* logging level
*
* @var int
*/
const WARN = 4;
/**
* logging level
*
* @var int
*/
const NOTICE = 5;
/**
* logging level
*
* @var int
*/
const INFO = 6;
/**
* logging level
*
* @var int
*/
const DEBUG = 7;
protected $writer;
protected $shortcutHandlers = [];
protected $priorities = [];
protected $defaultPriorities = [];
protected $buffer = [];
/**
* @throws InvalidArgumentException
*/
public function __construct(LogWriter $writer = null)
{
$createWriter = false;
if(!$writer) {
$createWriter = true;
} elseif (!is_object($writer) || !($writer instanceof LogWriter)) {
cWarning(__FILE__, __LINE__, 'The passed class is not a subclass of ConLite LogWriter. Creating new one.');
$createWriter = true;
}
if($createWriter) {
$options = ['destination' => \cRegistry::getConfigValue('path', 'logs') . 'conlite.log'];
$writer = LogWriter::factory('File', $options);
}
$this->setWriter($writer);
$this->setShortcutHandler('%date', [$this, 'shDate']);
$this->setShortcutHandler('%level', [$this, 'shLevel']);
$this->setShortcutHandler('%message', [$this, 'shMessage']);
$this->getWriter()->setOption('log_format', '[%date] [%level] %message', false);
$reflection = new ReflectionClass($this);
$this->priorities = $this->defaultPriorities = array_flip($reflection->getConstants());
}
public function getWriter() {
return $this->writer;
}
public function setWriter(LogWriter $writer): void
{
$this->writer = $writer;
}
/**
* @throws InvalidArgumentException
*/
public function setShortcutHandler($shortcut, $handler): bool
{
if ($shortcut == '') {
throw new InvalidArgumentException('The shortcut name must not be empty.');
}
if (cString::getPartOfString($shortcut, 0, 1) == '%') {
$shortcut = cString::getPartOfString($shortcut, 1);
}
if (!is_callable($handler)) {
throw new InvalidArgumentException('The specified shortcut handler does not exist.');
}
if (array_key_exists($shortcut, $this->shortcutHandlers)) {
throw new InvalidArgumentException('The shortcut ' . $shortcut . ' is already in use!');
}
$this->shortcutHandlers[$shortcut] = $handler;
return true;
}
public function unsetShortcutHandler($shortcut)
{
if(!in_array($shortcut, $this->shortcutHandlers)) {
throw new InvalidArgumentException('The specified shortcut handler does not exist.');
}
unset($this->shortcutHandlers[$shortcut]);
return true;
}
public function buffer(string $message, $priority = null): void
{
$this->buffer[] = [$message, $priority];
}
public function commit(bool $clearBuffer = true)
{
if (count($this->buffer) == 0) {
cWarning(__FILE__, __LINE__, 'There are no buffered messages to commit.');
return false;
}
foreach ($this->buffer as $bufferInfo) {
$this->log($bufferInfo[0], $bufferInfo[1]);
}
if ($clearBuffer) {
$this->clearBuffer();
}
}
public function clearBuffer(): void
{
$this->buffer = [];
}
public function log(string $message, $priority = null): void
{
if ($priority && !is_int($priority) && in_array($priority, $this->priorities)) {
$priority = array_search($priority, $this->priorities);
}
if ($priority === null || !array_key_exists($priority, $this->priorities)) {
$priority = $this->getWriter()->getOption('default_priority');
}
$logMessage = $this->getWriter()->getOption('log_format');
$lineEnding = $this->getWriter()->getOption('line_ending');
foreach ($this->shortcutHandlers as $shortcut => $handler) {
if (cString::getPartOfString($shortcut, 0, 1) != '%') {
$shortcut = '%' . $shortcut;
}
$info = [
'message' => $message,
'priority' => $priority
];
$value = call_user_func($handler, $info);
$logMessage = str_replace($shortcut, $value, $logMessage);
}
$this->getWriter()->write($logMessage . $lineEnding, $priority);
}
/**
* @throws InvalidArgumentException
*/
public function addPriority(string $name, int $value): void
{
if ($name == '') {
throw new InvalidArgumentException('Priority name must not be empty.');
}
if (in_array($name, $this->priorities)) {
throw new InvalidArgumentException('The given priority name already exists.');
}
if (array_key_exists($value, $this->priorities)) {
throw new InvalidArgumentException('The priority value already exists.');
}
$this->priorities[$value] = $name;
}
/**
* @throws InvalidArgumentException
*/
public function removePriority(string $name): void
{
if ($name == '') {
throw new InvalidArgumentException('Priority name must not be empty.');
}
if (!in_array($name, $this->priorities)) {
throw new InvalidArgumentException('Priority name does not exist.');
}
if (in_array($name, $this->defaultPriorities)) {
throw new InvalidArgumentException('Removing default priorities is not allowed.');
}
$priorityIndex = array_search($name, $this->priorities);
unset($this->priorities[$priorityIndex]);
}
/**
* @throws InvalidArgumentException
*/
public function __call(string $method, array $arguments) {
$priorityName = cString::toUpperCase($method);
if (!in_array($priorityName, $this->priorities)) {
throw new InvalidArgumentException('The given priority ' . $priorityName . ' is not supported.');
}
$priorityIndex = array_search($priorityName, $this->priorities);
$this->log($arguments[0], $priorityIndex);
}
/**
* Shortcut Handler Date.
* Returns the current date.
*
* @return string
* The current date
*/
public function shDate(): string
{
return date('Y-m-d H:i:s');
}
/**
* Shortcut Handler Level.
* Returns the canonical name of the priority.
* The canonical name is padded to 10 characters to achieve a better
* formatting.
*
* @param array $info
* @return string
* The canonical log level
*/
public function shLevel(array $info): string
{
$logLevel = $info['priority'];
return str_pad($this->priorities[$logLevel], 10, ' ', STR_PAD_BOTH);
}
/**
* Shortcut Handler Message.
* Returns the log message.
*
* @param array $info
* @return string
* The log message
*/
public function shMessage(array $info): string
{
return $info['message'];
}
}

Datei anzeigen

@ -0,0 +1,66 @@
<?php
namespace ConLite\Log;
use ConLite\Exceptions\InvalidArgumentException;
abstract class LogWriter
{
/**
* @param array $options
*/
public function __construct(
protected array $options = []
)
{
$this->setOptions($options);
$this->setOption('default_priority', Log::INFO, false);
$this->setOption('line_ending', PHP_EOL, false);
}
/**
* @throws invalidArgumentException
*/
public static function factory($writerName, array $writerOptions): LogWriter
{
$logWriterClassName = __NAMESPACE__ . '\\LogWriter' . ucfirst($writerName);
if(!class_exists($logWriterClassName)) {
throw new InvalidArgumentException('Unknown ConLite LogWriter class: ' . $logWriterClassName);
}
$writer = new $logWriterClassName($writerOptions);
if(!($writer instanceof LogWriter)) {
throw new InvalidArgumentException('Provided class is not an instance of ConLite LogWriter');
}
return $writer;
}
public function getOptions(): array
{
return $this->options;
}
public function getOption($option) {
return $this->options[$option];
}
public function setOptions(array $options): void
{
$this->options = $options;
}
public function setOption($option, $value, $force = false) {
if (!$force && isset($this->options[$option])) {
return;
}
$this->options[$option] = $value;
}
public function removeOption($option) {
unset($this->options[$option]);
}
abstract function write($message, $priority);
}

Datei anzeigen

@ -0,0 +1,135 @@
<?php
namespace ConLite\Log;
use ConLite\Exceptions\Exception;
use ConLite\Exceptions\FileNotFoundException;
use DirectoryIterator;
class LogWriterFile extends LogWriter
{
/**
* @var resource
*/
protected $handle = NULL;
/**
* @var int
*/
protected int $maxLogFileSize = 1024;
/**
* @var int
*/
protected int $maxRotationFiles = 10;
/**
* @throws FileNotFoundException
* @throws Exception
*/
public function __construct(array $options = []) {
parent::__construct($options);
$logFileSize = (int) getEffectiveSetting('log', 'writer-file-size-' . basename($this->getOption('destination')), $this->getOption('logFileSize') ?? 0);
if($logFileSize > 0) {
$this->maxLogFileSize = $logFileSize;
}
$this->createHandle();
}
/**
* @param string $message
* @param int $priority
* @return bool
*/
public function write($message, $priority): bool
{
$this->rotateLog();
return fwrite($this->handle, $message) != false;
}
public function __destruct()
{
$this->closeHandle();
}
/**
* @throws Exception
* @throws FileNotFoundException
*/
protected function createHandle(): void
{
$destination = $this->getOption('destination');
if ($destination == '') {
throw new Exception('No destination was specified.');
}
if (($this->handle = fopen($destination, 'a')) === false) {
throw new FileNotFoundException('Destination handle could not be created.');
}
}
protected function closeHandle(): void
{
fclose($this->handle);
}
protected function rotateLog()
{
$logfile = $this->getOption('destination');
if(!file_exists($logfile)) {
cWarning(__FILE__, __LINE__, 'Logfile ' . $logfile . ' not found.');
return false;
} elseif (!is_readable($logfile)) {
cWarning(__FILE__, __LINE__, 'Logfile ' . $logfile . ' not readable.');
return false;
}
if (filesize($logfile) >= $this->maxLogFileSize * 1024) {
$pathInfo = pathinfo($logfile);
$baseDirectory = $pathInfo['dirname'];
$baseName = $pathInfo['basename'];
$numMap = [];
foreach (new DirectoryIterator($baseDirectory) as $fileInfo) {
if ($fileInfo->isDot() || !$fileInfo->isFile()) {
continue;
}
if (preg_match('/^' . $baseName . '\.?([0-9]*)$/', $fileInfo->getFilename(), $matches)) {
$num = $matches[1];
$file2move = $fileInfo->getFilename();
if ($num == '') {
$num = 0;
}
$numMap[$num] = $file2move;
}
}
krsort($numMap);
foreach ($numMap as $num => $file2move) {
$targetN = $num + 1;
if($targetN > $this->maxRotationFiles) {
unlink($baseDirectory . DIRECTORY_SEPARATOR . $file2move);
continue;
}
rename($baseDirectory . DIRECTORY_SEPARATOR . $file2move, $baseDirectory . DIRECTORY_SEPARATOR .$baseName . '.' . $targetN);
}
return true;
}
return false;
}
public function getMaxLogFileSize(): int
{
return $this->maxLogFileSize;
}
public function setMaxLogFileSize(int $maxLogFileSize): void
{
$this->maxLogFileSize = $maxLogFileSize;
}
}

Datei anzeigen

@ -0,0 +1,8 @@
<?php
namespace ConLite\Log;
class ModuleLog extends Log
{
}

Datei anzeigen

@ -19,6 +19,10 @@
*
* $Id$
*/
use ConLite\Log\LogWriter;
use ConLite\Log\Log;
if (!defined('CON_FRAMEWORK')) {
die('Illegal call');
}
@ -148,9 +152,9 @@ class cApiModule extends Item {
try {
mkdir($this->_aModFileEditConf['modPath'], 0777, true);
} catch (Exception $ex) {
$oWriter = cLogWriter::factory("File", ['destination' => $sPathErrorLog]);
$oLog = new cLog($oWriter);
$oLog->log($ex->getFile() . " (" . $ex->getLine() . "): " . $ex->getMessage(), cLog::WARN);
$writer = LogWriter::factory("File", ['destination' => $sPathErrorLog]);
$log = new Log($writer);
$log->log($ex->getFile() . " (" . $ex->getLine() . "): " . $ex->getMessage(), Log::WARN);
}
}
@ -160,9 +164,9 @@ class cApiModule extends Item {
try {
mkdir($this->getModulePath(), 0777);
} catch (Exception $ex) {
$oWriter = cLogWriter::factory("File", ['destination' => $sPathErrorLog]);
$oLog = new cLog($oWriter);
$oLog->log($ex->getFile() . " (" . $ex->getLine() . "): " . $ex->getMessage(), cLog::WARN);
$writer = LogWriter::factory("File", ['destination' => $sPathErrorLog]);
$log = new Log($writer);
$log->log($ex->getFile() . " (" . $ex->getLine() . "): " . $ex->getMessage(), Log::WARN);
}
if (is_writable($this->getModulePath())) {
@ -171,9 +175,9 @@ class cApiModule extends Item {
umask($this->_oldumask);
}
} else {
$oWriter = cLogWriter::factory("File", ['destination' => $sPathErrorLog]);
$oLog = new cLog($oWriter);
$oLog->log(__FILE__ . " (" . __LINE__ . "): " . 'Error: Cannot create mod path '.$this->getModulePath(), cLog::WARN);
$writer = LogWriter::factory("File", ['destination' => $sPathErrorLog]);
$log = new Log($writer);
$log->log(__FILE__ . " (" . __LINE__ . "): " . 'Error: Cannot create mod path '.$this->getModulePath(), Log::WARN);
}
return FALSE;
}
@ -244,7 +248,8 @@ class cApiModule extends Item {
*
* @return array Found strings for this module
*/
public function parseModuleForStrings() {
public function parseModuleForStrings(): bool|array
{
global $cfg;
if ($this->virgin == true) {
return false;

Datei anzeigen

@ -1,393 +0,0 @@
<?php
/**
* This file contains the log class.
*
* @package Core
* @subpackage Log
* @version SVN Revision $Rev$
*
* @author Dominik Ziegler
* @copyright four for business AG <www.4fb.de>
* @license http://www.contenido.org/license/LIZENZ.txt
* @link http://www.4fb.de
* @link http://www.contenido.org
*/
defined('CON_FRAMEWORK') || die('Illegal call: Missing framework initialization - request aborted.');
/**
* This class contains the main functionalities for the logging in CONTENIDO.
*
* Examples:
*
* $writer = cLogWriter::factory("File", array('destination' => 'contenido.log'));
* $log = new cLog($writer);
*
* $log->addPriority("CONTENIDO", 10);
* $log->log("Contenido Log Message.", "CONTENIDO");
* $log->contenido("Same log entry in short notation.");
* $log->removePriority("CONTENIDO");
*
* $log->emerg("System down.");
*
* $log->log('Notice Log Message', cLog::NOTICE);
*
* $log->buffer('Buffered Log Message', cLog::WARN);
* $log->commit();
*
* @package Core
* @subpackage Log
*/
class cLog {
/**
* @var int logging level
*/
const EMERG = 0;
/**
* @var int logging level
*/
const ALERT = 1;
/**
* @var int logging level
*/
const CRIT = 2;
/**
* @var int logging level
*/
const ERR = 3;
/**
* @var int logging level
*/
const WARN = 4;
/**
* @var int logging level
*/
const NOTICE = 5;
/**
* @var int logging level
*/
const INFO = 6;
/**
* @var int logging level
*/
const DEBUG = 7;
/**
* @var cLogWriter Contains the local log writer instance.
*/
protected $_writer;
/**
* @var array Contains all shortcut handlers
*/
protected $_shortcutHandlers = array();
/**
* @var array Contains all available priorities
*/
protected $_priorities = array();
/**
* @var array Contains all default priorities
*/
protected $_defaultPriorities = array();
/**
* @var array Contains all buffered messages
*/
protected $_buffer = array();
/**
* Creates a new instance of the CONTENIDO Log mechanism.
*
* The log format interface of cLog is capable of being extended by subclasses. See the note about
* the log shortcuts below.
*
*
* About Log Shortcuts
* -------------------
* Log shortcuts are placeholders which are replaced when a log entry is created. Placeholders start with a
* percentage sign (%) and contain one or more characters. Each placeholder is handled by an own function which
* decides what to do.
*
* @param mixed $writer Writer object (any subclass of cLogWriter), or false if cLog should handle the writer creation
*/
public function __construct($writer = false) {
$cfg = cRegistry::getConfig();
$createWriter = false;
if ($writer == false) {
$createWriter = true;
} else if (!is_object($writer) || ($writer instanceof cLogWriter) == false) {
cWarning(__FILE__, __LINE__, "The passed class is not a subclass of cLogWriter. Creating new one.");
$createWriter = true;
}
if ($createWriter == true) {
$options = array(
'destination' => cRegistry::getConfigValue('path', 'contenido')
.cRegistry::getConfigValue('path', 'logs')
.'contenido.log');
$writer = cLogWriter::factory("File", $options);
}
$this->setWriter($writer);
$this->setShortcutHandler("%date", array($this, "shDate"));
$this->setShortcutHandler("%level", array($this, "shLevel"));
$this->setShortcutHandler("%message", array($this, "shMessage"));
$this->getWriter()->setOption('log_format', '[%date] [%level] %message', false);
$reflection = new ReflectionClass($this);
$this->_priorities = $this->_defaultPriorities = array_flip($reflection->getConstants());
}
/**
* Returns the local writer instance.
* @return cLogWriter
*/
public function getWriter() {
return $this->_writer;
}
/**
* Sets the local writer instance.
*
* @param cLogWriter $writer Writer instacne
*/
public function setWriter(cLogWriter $writer) {
$this->_writer = $writer;
}
/**
* Defines a custom shortcut handler.
*
* Each shortcut handler receives an array with the
* message and the priority of the entry.
*
* @param string $shortcut Shortcut name
* @param string $handler Name of the function to call
* @throws cInvalidArgumentException if the given shortcut is empty or
* already in use or if the handler is not callable
* @return bool True if setting was successful
*/
public function setShortcutHandler($shortcut, $handler) {
if ($shortcut == '') {
throw new Exception('The shortcut name must not be empty.');
}
if (substr($shortcut, 0, 1) == "%") {
$shortcut = substr($shortcut, 1);
}
if (is_callable($handler) == false) {
throw new Exception('The specified shortcut handler does not exist.');
}
if (array_key_exists($shortcut, $this->_shortcutHandlers)) {
throw new Exception('The shortcut ' . $shortcut . ' is already in use!');
}
$this->_shortcutHandlers[$shortcut] = $handler;
return true;
}
/**
* Unsets a specific shortcut handler.
*
* @param string $shortcut Name of the shortcut
* @throws cInvalidArgumentException if the given shortcut handler does not
* exist
* @return boolean
*/
public function unsetShortcutHandler($shortcut) {
if (!in_array($shortcut, $this->_shortcutHandlers)) {
throw new Exception('The specified shortcut handler does not exist.');
}
unset($this->_shortcutHandlers[$shortcut]);
return true;
}
/**
* Buffers a log message for committing them on a later moment.
*
* @param string $message Message to buffer
* @param mixed $priority Priority of the log entry (optional)
*/
public function buffer($message, $priority = NULL) {
$this->_buffer[] = array($message, $priority);
}
/**
* Commits all buffered messages and empties the message buffer if parameter is not false.
*
* @param boolean $revoke Flag, whether the buffer is cleared or not (optional, default: true)
*/
public function commit($revoke = true) {
if (count($this->_buffer) == 0) {
cWarning(__FILE__, __LINE__, "There are no buffered messages to commit.");
return false;
}
foreach ($this->_buffer as $bufferInfo) {
$this->log($bufferInfo[0], $bufferInfo[1]);
}
if ($revoke == true) {
$this->revoke();
}
}
/**
* Empties the message buffer.
*/
public function revoke() {
$this->_buffer = array();
}
/**
* Logs a message using the local writer instance
*
* @param string $message Message to log
* @param mixed $priority Priority of the log entry (optional)
*/
public function log($message, $priority = NULL) {
if ($priority && is_int($priority) == false && in_array($priority, $this->_priorities)) {
$priority = array_search($priority, $this->_priorities);
}
if ($priority === NULL || array_key_exists($priority, $this->_priorities) == false) {
$priority = $this->getWriter()->getOption('default_priority');
}
$logMessage = $this->getWriter()->getOption('log_format');
$lineEnding = $this->getWriter()->getOption('line_ending');
foreach ($this->_shortcutHandlers as $shortcut => $handler) {
if (substr($shortcut, 0, 1) != "%") {
$shortcut = "%" . $shortcut;
}
$info = array(
'message' => $message,
'priority' => $priority
);
$value = call_user_func($handler, $info);
$logMessage = str_replace($shortcut, $value, $logMessage);
}
$this->getWriter()->write($logMessage . $lineEnding, $priority);
}
/**
* Adds a new priority to the log.
*
* @param string $name Name of the log priority
* @param int $value Index value of the log priority
* @throws cInvalidArgumentException if the given name is empty, already
* exists or the value already exists
*/
public function addPriority($name, $value) {
if ($name == '') {
throw new Exception('Priority name must not be empty.');
}
if (in_array($name, $this->_priorities)) {
throw new Exception('The given priority name already exists.');
}
if (array_key_exists($value, $this->_priorities)) {
throw new Exception('The priority value already exists.');
}
$this->_priorities[$value] = $name;
}
/**
* Removes a priority from log.
* Default properties can not be removed.
*
* @param string $name Name of the log priority to remove
* @throws cInvalidArgumentException if the given name is empty, does not
* exist or is a default priority
*/
public function removePriority($name) {
if ($name == '') {
throw new Exception('Priority name must not be empty.');
}
if (in_array($name, $this->_priorities) == false) {
throw new Exception('Priority name does not exist.');
}
if (in_array($name, $this->_defaultPriorities) == true) {
throw new Exception('Removing default priorities is not allowed.');
}
$priorityIndex = array_search($name, $this->_priorities);
unset($this->_priorities[$priorityIndex]);
}
/**
* Magic call method for direct priority named calls.
*
* @param string $method Name of the method
* @param array $arguments Array with the method arguments
* @throws cInvalidArgumentException if the given priority is not supported
*/
public function __call($method, $arguments) {
$priorityName = strtoupper($method);
if (in_array($priorityName, $this->_priorities) == false) {
throw new Exception('The given priority ' . $priorityName . ' is not supported.');
}
$priorityIndex = array_search($priorityName, $this->_priorities);
return $this->log($arguments[0], $priorityIndex);
}
/**
* Shortcut Handler Date.
* Returns the current date
* @return string The current date
*/
public function shDate() {
return date("Y-m-d H:i:s");
}
/**
* Shortcut Handler Level.
* Returns the canonical name of the priority.
* The canonical name is padded to 10 characters to achieve a better formatting.
* @return string The canonical log level
*/
public function shLevel($info) {
$logLevel = $info['priority'];
return str_pad($this->_priorities[$logLevel], 10, " ", STR_PAD_BOTH);
}
/**
* Shortcut Handler Message.
* Returns the log message.
* @return string The log message
*/
public function shMessage($info) {
return $info['message'];
}
}
?>

Datei anzeigen

@ -1,67 +0,0 @@
<?php
/**
* This file contains the log file writer class.
*
* @package Core
* @subpackage Log
* @version SVN Revision $Rev$
*
* @author Dominik Ziegler
* @copyright four for business AG <www.4fb.de>
* @license http://www.contenido.org/license/LIZENZ.txt
* @link http://www.4fb.de
* @link http://www.contenido.org
*/
defined('CON_FRAMEWORK') || die('Illegal call: Missing framework initialization - request aborted.');
/**
* This class contains the file writer class for the logging mechanism.
*
* @package Core
* @subpackage Log
*/
class cLogWriterFile extends cLogWriter {
/**
* @var resource Destination handle
*/
protected $_handle = NULL;
/**
* Constructor of the writer instance.
* @param array $options Array with options for the writer instance (optional)
*/
public function __construct($options = array()) {
parent::__construct($options);
$this->_createHandle();
}
/**
* Checks destination and creates the handle for the write process.
*
* @throws cException if not destination is specified
* @throws cFileNotFoundException if the destination file could not be read
*/
protected function _createHandle() {
$destination = $this->getOption('destination');
if ($destination == '') {
throw new Exception('No destination was specified.');
}
if (($this->_handle = fopen($destination, 'a')) === false) {
throw new Exception('Destination handle could not be created.');
}
}
/**
* Writes the content to file handle.
*
* @param string $message Message to write
* @param int $priority Priority of the log entry
* @return boolean State of the write process
*/
public function write($message, $priority) {
return (fwrite($this->_handle, $message) != false);
}
}

Datei anzeigen

@ -1,127 +0,0 @@
<?php
/**
* This file contains the abstract log writer class.
*
* @package Core
* @subpackage Log
* @version SVN Revision $Rev$
*
* @author Dominik Ziegler
* @copyright four for business AG <www.4fb.de>
* @license http://www.contenido.org/license/LIZENZ.txt
* @link http://www.4fb.de
* @link http://www.contenido.org
*/
defined('CON_FRAMEWORK') || die('Illegal call: Missing framework initialization - request aborted.');
/**
* This class contains the main functionalities for the logging writer in CONTENIDO.
*
* @package Core
* @subpackage Log
*/
abstract class cLogWriter {
/**
* @var array Contains all options of the current writer instance.
*/
protected $_options = array();
/**
* Constructor of the writer instance.
* @param array $options Array with options for the writer instance (optional)
*/
public function __construct($options = array()) {
$this->setOptions($options);
// Set all default options if they were not set already
$this->setOption('default_priority', cLog::INFO, false);
$this->setOption('line_ending', PHP_EOL, false);
}
/**
* Factory method for a new writer instance.
*
* @param string $writerName Name of the writer
* @param array $writerOptions Options array for the writer instance
* @throws cInvalidArgumentException if the writer class with the given name
* does not exist or is not an instance of clogWriter
* @return cLogWriter Log writer instance
*/
public static function factory($writerName, array $writerOptions) {
$logWriterClassName = 'cLogWriter' . ucfirst($writerName);
if (!class_exists($logWriterClassName)) {
throw new Exception('Unknown writer class: ' . $writerName);
}
$writer = new $logWriterClassName($writerOptions);
if (($writer instanceof cLogWriter) == false) {
throw new Exception('Provided class is not an instance of cLogWriter');
}
return $writer;
}
/**
* Sets the whole options array.
*
* @param array $options Array with options
*/
public function setOptions(array $options) {
$this->_options = $options;
}
/**
* Returns an array with all options.
* @return array Array with all options
*/
public function getOptions() {
return $this->_options;
}
/**
* Sets a option. If option was set previously, it must be forced to overwrite the value.
*
* @param string $option Name of the option
* @param mixed $value Value of the option
* @param boolean $force Flag to force setting the option value (optional, default: false)
*/
public function setOption($option, $value, $force = false) {
if ($force == false && isset($this->_options[$option]) == true) {
return;
}
$this->_options[$option] = $value;
}
/**
* Returns the value of an option entry.
*
* @param string $option Name of the option
*
* @return mixed Value of the option entry
*/
public function getOption($option) {
return $this->_options[$option];
}
/**
* Removes an option entry.
*
* @param string $option Name of the option
*/
public function removeOption($option) {
unset($this->_options[$option]);
}
/**
* Abstract function for the write process.
* This method must be implemented in the specific writer.
*
* @param string $message Message to write
* @param int $priority Priority of the log entry
*
* @return boolean State of the write process
*/
abstract function write($message, $priority);
}

Datei anzeigen

@ -1,90 +0,0 @@
<?php
/**
* This file contains the module log class.
*
* @package Core
* @subpackage Log
* @version SVN Revision $Rev$
*
* @author Dominik Ziegler
* @copyright four for business AG <www.4fb.de>
* @license http://www.contenido.org/license/LIZENZ.txt
* @link http://www.4fb.de
* @link http://www.contenido.org
*/
defined('CON_FRAMEWORK') || die('Illegal call: Missing framework initialization - request aborted.');
/**
* This class contains the main functionalities for the module logging in
* CONTENIDO.
* The funcationality is almost the same like normal logging with the exception,
* that log entries contains an additional information about the used module.
*
* Example:
* $writer = cLogWriter::factory("File", array('destination' =>
* 'contenido.log'));
*
* $log = new cModuleLog($writer);
* $log->setModule(1);
* $log->log("Anything you want to log.");
*
* @package Core
* @subpackage Log
*/
class cModuleLog extends cLog {
/**
* @var cApiModule instance of module model
*/
private $_module;
/**
* Constructor of the module log.
*
* @param mixed $writer Writer object (any subclass of cLogWriter), or false
* if cLog should handle the writer creation
*
*/
public function __construct($writer = false) {
parent::__construct($writer);
$this->setShortcutHandler('module', array(
$this,
'shModule'
));
$this->getWriter()->setOption("log_format", "[%date] [%level] [%module] %message", true);
}
/**
* Sets the module to use.
*
* setModule automatically buffers basic module information to the log to
* assist the developer in debugging his modules.
*
* @param int $idmod The module ID to use
* @throws cException if the module with the given idmod could not be loaded
*/
public function setModule($idmod) {
$this->_module = new cApiModule($idmod);
if ($this->_module->isLoaded() == false) {
throw new Exception('Could not load module information.');
}
}
/**
* Shortcut Handler Module.
* Returns the ID and the name of the module.
*
* @return string ID and name of the module
*/
public function shModule() {
if ($this->_module->isLoaded() == false) {
return '';
}
return $this->_module->get("idmod") . ": " . $this->_module->get("name");
}
}
?>

Datei anzeigen

@ -25,27 +25,26 @@ if (!defined("CON_FRAMEWORK")) {
// Contenido startup process
include_once ('../includes/startup.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.user.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.xml.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.navigation.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'template/class.template.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.backend.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.table.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.notification.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.area.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.layout.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.client.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.cat.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.treeitem.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["includes"] . 'cfg_language_de.inc.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["includes"] . 'functions.con.php');
$classPath = cRegistry::getConfigValue('path', 'conlite') . cRegistry::getConfigValue('path', 'classes');
$includesPath = cRegistry::getConfigValue('path', 'conlite') . cRegistry::getConfigValue('path', 'includes');
include_once ($classPath . 'class.user.php');
include_once ($classPath . 'class.xml.php');
include_once ($classPath . 'class.navigation.php');
include_once ($classPath . 'template/class.template.php');
include_once ($classPath . 'class.backend.php');
include_once ($classPath . 'class.table.php');
include_once ($classPath . 'class.notification.php');
include_once ($classPath . 'class.area.php');
include_once ($classPath . 'class.layout.php');
include_once ($classPath . 'class.client.php');
include_once ($classPath . 'class.cat.php');
include_once ($classPath . 'class.treeitem.php');
include_once ($includesPath . 'cfg_language_de.inc.php');
include_once ($includesPath . 'functions.con.php');
if(!isRunningFromWeb() || function_exists("runJob") || $area == "cronjobs") {
$db = new DB_ConLite;
conFlagOnOffline();
conMoveArticles();
}
?>

Datei anzeigen

@ -25,20 +25,23 @@ if (!defined("CON_FRAMEWORK")) {
// Contenido startup process
include_once ('../includes/startup.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.user.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.xml.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.navigation.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'template/class.template.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.backend.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.table.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.notification.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.area.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.layout.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.client.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.cat.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.treeitem.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["includes"] . 'cfg_language_de.inc.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["includes"] . 'functions.stat.php');
$classPath = cRegistry::getConfigValue('path', 'conlite') . cRegistry::getConfigValue('path', 'classes');
$includesPath = cRegistry::getConfigValue('path', 'conlite') . cRegistry::getConfigValue('path', 'includes');
include_once ($classPath . 'class.user.php');
include_once ($classPath . 'class.xml.php');
include_once ($classPath . 'class.navigation.php');
include_once ($classPath . 'template/class.template.php');
include_once ($classPath . 'class.backend.php');
include_once ($classPath . 'class.table.php');
include_once ($classPath . 'class.notification.php');
include_once ($classPath . 'class.area.php');
include_once ($classPath . 'class.layout.php');
include_once ($classPath . 'class.client.php');
include_once ($classPath . 'class.cat.php');
include_once ($classPath . 'class.treeitem.php');
include_once ($includesPath . 'cfg_language_de.inc.php');
include_once ($includesPath . 'functions.stat.php');
if (!isRunningFromWeb() || function_exists("runJob") || $area == "cronjobs")
{
@ -58,4 +61,3 @@ if (!isRunningFromWeb() || function_exists("runJob") || $area == "cronjobs")
statsArchive(sprintf("%04d%02d",$year,$month));
}
?>

Datei anzeigen

@ -25,37 +25,41 @@ if (!defined("CON_FRAMEWORK")) {
// Contenido startup process
include_once ('../includes/startup.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.user.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.xml.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.navigation.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'template/class.template.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.backend.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.table.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.notification.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.area.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.layout.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.client.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.cat.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["classes"] . 'class.treeitem.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["includes"] . 'cfg_language_de.inc.php');
include_once ($cfg['path']['contenido'].$cfg["path"]["includes"] . 'functions.stat.php');
$classPath = cRegistry::getConfigValue('path', 'conlite') . cRegistry::getConfigValue('path', 'classes');
$includesPath = cRegistry::getConfigValue('path', 'conlite') . cRegistry::getConfigValue('path', 'includes');
include_once ($classPath . 'class.user.php');
include_once ($classPath . 'class.xml.php');
include_once ($classPath . 'class.navigation.php');
include_once ($classPath . 'template/class.template.php');
include_once ($classPath . 'class.backend.php');
include_once ($classPath . 'class.table.php');
include_once ($classPath . 'class.notification.php');
include_once ($classPath . 'class.area.php');
include_once ($classPath . 'class.layout.php');
include_once ($classPath . 'class.client.php');
include_once ($classPath . 'class.cat.php');
include_once ($classPath . 'class.treeitem.php');
include_once ($includesPath . 'cfg_language_de.inc.php');
include_once ($includesPath . 'functions.stat.php');
global $cfg;
if(!isRunningFromWeb() || function_exists("runJob") || $area == "cronjobs") {
$db = new DB_ConLite;
foreach ($cfg["tab"] as $key => $value)
$tables = cRegistry::getConfigValue('tab');
foreach ($tables as $key => $value)
{
$sql = "OPTIMIZE TABLE ".$value;
$db->query($sql);
}
if ($cfg["statistics_heap_table"]) {
$sHeapTable = $cfg['tab']['stat_heap_table'];
if (cRegistry::getConfigValue('statistics_heap_table')) {
$sHeapTable = cRegistry::getConfigValue('tab', 'stat_heap_table');
buildHeapTable ($sHeapTable, $db);
}
}
?>

Datei anzeigen

@ -35,7 +35,8 @@ if (!defined('CON_FRAMEWORK')) {
* @author Jan Lengowski <Jan.Lengowski@4fb.de>
* @copyright four for business AG
*/
function getAvailableContentTypes($idartlang) {
function getAvailableContentTypes($idartlang)
{
global $db, $cfg, $a_content, $a_description;
$sql = "SELECT
@ -63,7 +64,8 @@ function getAvailableContentTypes($idartlang) {
* @param int $idart Article-Id
* @return bool Article assigned to multiple categories
*/
function isArtInMultipleUse($idart) {
function isArtInMultipleUse($idart)
{
global $cfg, $client;
$db = new DB_ConLite;
@ -80,10 +82,11 @@ function isArtInMultipleUse($idart) {
* @param bool $umlauts [Use german Umlaute] Optional
* @return bool Value is alphanumeric
*/
function is_alphanumeric($test, $umlauts = true) {
function is_alphanumeric($test, $umlauts = true)
{
if ($umlauts == true) {
$match = "/^[a-z0-9<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> ]+$/i";
$match = "/^[a-z0-9ÄäÖöÜüß ]+$/i";
} else {
$match = "/^[a-z0-9 ]+$/i";
}
@ -97,7 +100,8 @@ function is_alphanumeric($test, $umlauts = true) {
* @param int $month
* @return string
*/
function getCanonicalMonth($month) {
function getCanonicalMonth($month)
{
switch ($month) {
case 1 :
return (i18n("January"));
@ -144,7 +148,8 @@ function getCanonicalMonth($month) {
* @param int $iDay The day number of date(w)
* @return string Dayname of current language
*/
function getCanonicalDay($iDay) {
function getCanonicalDay($iDay)
{
switch ($iDay) {
case 1 :
return (i18n("Monday"));
@ -167,7 +172,8 @@ function getCanonicalDay($iDay) {
case 0 :
return (i18n("Sunday"));
break;
default: break;
default:
break;
}
}
@ -177,7 +183,8 @@ function getCanonicalDay($iDay) {
* @param mixed $area Area name
* @return int
*/
function getIDForArea($area) {
function getIDForArea($area)
{
global $client, $lang, $cfg, $sess;
$db = new DB_ConLite;
@ -205,7 +212,8 @@ function getIDForArea($area) {
* @param mixed $area
* @return int
*/
function getParentAreaId($area) {
function getParentAreaId($area)
{
global $client, $lang, $cfg, $sess;
$db = new DB_ConLite;
@ -247,7 +255,8 @@ function getParentAreaId($area) {
* @author Jan Lengowski <Jan.Lengowski@4fb.de>
* @copyright four for business AG <www.4fb.de>
*/
function markSubMenuItem($menuitem, $return = false) {
function markSubMenuItem($menuitem, $return = false)
{
$str = '<script type="text/javascript">
try {
@ -289,7 +298,8 @@ function markSubMenuItem($menuitem, $return = false) {
* @author Jan Lengowski <Jan.Lengowski@4fb.de>
* @copyright four for business AG <www.4fb.de>
*/
function backToMainArea($send) {
function backToMainArea($send)
{
if ($send) {
/* Global vars */
global $area, $cfg, $db, $sess, $idart, $idcat, $idartlang, $idcatart, $frame;
@ -319,7 +329,8 @@ function backToMainArea($send) {
}
}
function showLocation($area) {
function showLocation($area)
{
global $db;
global $cfgPath, $lngArea;
global $cfg;
@ -361,7 +372,8 @@ function showLocation($area) {
}
}
function showTable($tablename) {
function showTable($tablename)
{
global $db;
$sql = "SELECT * FROM $tablename";
@ -377,12 +389,13 @@ function showTable($tablename) {
/**
* Get languages for given client
*
* @deprecated since ConLite version 2.0.0, use method in class cApiLanguageCollection instead
*
* @param int $client
* @return array Array of language ids
* @deprecated since ConLite version 2.0.0, use method in class cApiLanguageCollection instead
*
*/
function getLanguagesByClient($client) {
function getLanguagesByClient($client)
{
$oClLangs = new cApiLanguageCollection();
return $oClLangs->getClientLanguages($client);
}
@ -393,7 +406,8 @@ function getLanguagesByClient($client) {
* @param int $client
* @return array List of languages where the key is the language id and value the language name
*/
function getLanguageNamesByClient($client) {
function getLanguageNamesByClient($client)
{
global $db;
global $cfg;
$list = [];
@ -418,7 +432,8 @@ function getLanguageNamesByClient($client) {
return $list;
}
function set_magic_quotes_gpc(&$code) {
function set_magic_quotes_gpc(&$code)
{
$code = addslashes($code);
}
@ -431,7 +446,8 @@ function set_magic_quotes_gpc(&$code) {
* - $arr[0]['idclient']
* - $arr[0]['clientname']
*/
function getAllClientsAndLanguages() {
function getAllClientsAndLanguages()
{
global $db, $cfg;
$sql = "SELECT
@ -460,7 +476,8 @@ function getAllClientsAndLanguages() {
return $aRs;
}
function fakeheader($time) {
function fakeheader($time)
{
global $con_time0;
if (!isset($con_time0)) {
$con_time0 = $time;
@ -472,7 +489,8 @@ function fakeheader($time) {
} // end if
}
function recursive_copy($from_path, $to_path) {
function recursive_copy($from_path, $to_path)
{
$oldumask = umask(0);
if (mkdir($to_path, 0777)) {
umask($oldumask);
@ -502,16 +520,18 @@ function recursive_copy($from_path, $to_path) {
}
}
function getmicrotime() {
function getmicrotime()
{
list ($usec, $sec) = explode(" ", microtime());
return ((float) $usec + (float) $sec);
return ((float)$usec + (float)$sec);
}
/* Small hack to clean up unused sessions.
As we are probably soon rewriting the
session management, this hack is OK. */
function cleanupSessions() {
function cleanupSessions()
{
global $cfg;
$db = new DB_ConLite;
@ -547,7 +567,8 @@ function cleanupSessions() {
}
}
function isGroup($uid) {
function isGroup($uid)
{
$users = new User;
if ($users->loadUserByUserID($uid) == false) {
@ -557,7 +578,8 @@ function isGroup($uid) {
}
}
function getGroupOrUserName($uid) {
function getGroupOrUserName($uid)
{
$users = new User;
if ($users->loadUserByUserID($uid) === false) {
@ -628,7 +650,8 @@ function getGroupOrUserName($uid) {
* @return array see above for example
* @author Marco Jahn
*/
function getPhpModuleInfo($moduleName) {
function getPhpModuleInfo($moduleName)
{
$moduleSettings = array();
ob_start();
phpinfo(INFO_MODULES); // get information vor modules
@ -675,7 +698,8 @@ function getPhpModuleInfo($moduleName) {
return $moduleSettings;
}
function isValidMail($sEMail, $bStrict = false) {
function isValidMail($sEMail, $bStrict = false)
{
if ($bStrict) {
// HerrB (14.02.2008), code posted by Calvini
// See http://www.contenido.org/forum/viewtopic.php?p=106612#106612
@ -699,7 +723,8 @@ function isValidMail($sEMail, $bStrict = false) {
}
}
function htmldecode($string) {
function htmldecode($string)
{
$trans_tbl = clGetHtmlTranslationTable(HTML_ENTITIES);
$trans_tbl = array_flip($trans_tbl);
$ret = strtr($string, $trans_tbl);
@ -716,7 +741,8 @@ function htmldecode($string) {
* @global DB_ConLite $db
* @global array $cfg
*/
function rereadClients() {
function rereadClients()
{
global $cfgClient;
global $errsite_idcat;
global $errsite_idart;
@ -800,7 +826,8 @@ function rereadClients() {
* @param string $value The value of the item
* @param int $idsystemprop The sysprop id, use optional. If set it allows to modify type name and value
*/
function setSystemProperty($type, $name, $value, $idsystemprop = 0) {
function setSystemProperty($type, $name, $value, $idsystemprop = 0)
{
global $cfg;
if ($type == "" || $name == "") {
return false;
@ -840,7 +867,8 @@ function setSystemProperty($type, $name, $value, $idsystemprop = 0) {
* @param string $type The type of the item
* @param string $name The name of the item
*/
function deleteSystemProperty($type, $name) {
function deleteSystemProperty($type, $name)
{
global $cfg;
$db_systemprop = new DB_ConLite;
@ -863,7 +891,8 @@ function deleteSystemProperty($type, $name) {
* @param boolean bGetPropId - if true special mode is activated which generates for each property a third array, which also contains idsystemprop value
* @return array
*/
function getSystemProperties($bGetPropId = 0) {
function getSystemProperties($bGetPropId = 0)
{
global $cfg;
$db_systemprop = new DB_ConLite;
@ -893,7 +922,8 @@ function getSystemProperties($bGetPropId = 0) {
* @param string $name The name of the item
* @return mixed boolean false if nothing was found, or
*/
function getSystemProperty($sType, $sName) {
function getSystemProperty($sType, $sName)
{
$oProperties = new cApiSystemPropertyCollection();
return $oProperties->getSystemProperty($sType, $sName);
@ -922,7 +952,8 @@ function getSystemProperty($sType, $sName) {
* @param string $type The type of the item
* @return array Value
*/
function getSystemPropertiesByType($sType) {
function getSystemPropertiesByType($sType)
{
global $cfg;
$aResult = array();
@ -953,7 +984,8 @@ function getSystemPropertiesByType($sType) {
* @param string $default Optional default value
* @return mixed boolean false if nothing was found
*/
function getEffectiveSetting($type, $name, $default = "") {
function getEffectiveSetting($type, $name, $default = "")
{
global $auth, $client, $lang;
if ($auth->auth["uid"] != "nobody") {
@ -999,18 +1031,19 @@ function getEffectiveSetting($type, $name, $default = "") {
*
* You may use default array to preset settings, this will not override found settings
*
* @param string $sType
* @param array $aDefault
* @return array
* @global int $client
* @global array $cfg
* @global int $lang
* @version $Rev$
* @author Ortwin Pinke <o.pinke@conlite.org>
*
* @global object $auth
* @global int $client
* @global array $cfg
* @global int $lang
* @param string $sType
* @param array $aDefault
* @return array
*/
function getEffectiveSettingsByType($sType, $aDefault = array()) {
function getEffectiveSettingsByType($sType, $aDefault = array())
{
global $auth, $client, $cfg, $lang;
$aResult = getSystemPropertiesByType($sType);
@ -1047,7 +1080,8 @@ function getEffectiveSettingsByType($sType, $aDefault = array()) {
*
* @return array list of article specifications
*/
function getArtspec() {
function getArtspec()
{
global $db, $cfg, $lang, $client;
$sql = "SELECT artspec, idartspec, online, artspecdefault FROM " . $cfg['tab']['art_spec'] . "
WHERE client='" . Contenido_Security::toInteger($client) . "' AND lang='" . Contenido_Security::toInteger($lang) . "' ORDER BY artspec ASC";
@ -1070,7 +1104,8 @@ function getArtspec() {
*
* @return void
*/
function addArtspec($artspectext, $online) {
function addArtspec($artspectext, $online)
{
global $db, $cfg, $lang, $client;
if (isset($_POST['idartspec'])) { //update
@ -1096,7 +1131,8 @@ function addArtspec($artspectext, $online) {
*
* @return void
*/
function deleteArtspec($idartspec) {
function deleteArtspec($idartspec)
{
global $db, $cfg;
$sql = "DELETE FROM " . $cfg['tab']['art_spec'] . " WHERE idartspec = '" . Contenido_Security::toInteger($idartspec) . "'";
$db->query($sql);
@ -1115,7 +1151,8 @@ function deleteArtspec($idartspec) {
*
* @return void
*/
function setArtspecOnline($idartspec, $online) {
function setArtspecOnline($idartspec, $online)
{
global $db, $cfg;
$sql = "UPDATE " . $cfg['tab']['art_spec'] . " SET online=" . Contenido_Security::toInteger($online) . " WHERE idartspec=" . Contenido_Security::toInteger($idartspec) . "";
$db->query($sql);
@ -1130,7 +1167,8 @@ function setArtspecOnline($idartspec, $online) {
*
* @return void
*/
function setArtspecDefault($idartspec) {
function setArtspecDefault($idartspec)
{
global $db, $cfg, $lang, $client;
$sql = "UPDATE " . $cfg['tab']['art_spec'] . " SET artspecdefault=0 WHERE client='" . Contenido_Security::toInteger($client) . "' AND lang='" . Contenido_Security::toInteger($lang) . "'";
$db->query($sql);
@ -1146,7 +1184,8 @@ function setArtspecDefault($idartspec) {
* @param String Value of the SelectBox
* @return String HTML
*/
function buildArticleSelect($sName, $iIdCat, $sValue) {
function buildArticleSelect($sName, $iIdCat, $sValue)
{
global $cfg, $client, $lang, $idcat;
$db = new DB_ConLite;
@ -1184,7 +1223,8 @@ function buildArticleSelect($sName, $iIdCat, $sValue) {
* @param String Optional style informations for select
* @return String HTML
*/
function buildCategorySelect($sName, $sValue, $sLevel = 0, $sStyle = "") {
function buildCategorySelect($sName, $sValue, $sLevel = 0, $sStyle = "")
{
global $cfg, $client, $lang, $idcat;
$db = new DB_ConLite;
@ -1259,7 +1299,8 @@ function buildCategorySelect($sName, $sValue, $sLevel = 0, $sStyle = "") {
* @param string $filename Name of the file
* @return extension on success, false if no extension could be extracted.
*/
function getFileExtension($filename) {
function getFileExtension($filename)
{
$dotposition = strrpos($filename, ".");
if ($dotposition !== false) {
@ -1269,14 +1310,15 @@ function getFileExtension($filename) {
}
}
function human_readable_size($number) {
function human_readable_size($number)
{
$base = 1024;
$suffixes = array(" B", " KB", " MB", " GB", " TB", " PB", " EB");
$usesuf = 0;
$n = (float) $number; //Appears to be necessary to avoid rounding
$n = (float)$number; //Appears to be necessary to avoid rounding
while ($n >= $base) {
$n /= (float) $base;
$n /= (float)$base;
$usesuf++;
}
@ -1292,7 +1334,8 @@ function human_readable_size($number) {
* @param array Array to trim
* @return array Trimmed array
*/
function trim_array($array) {
function trim_array($array)
{
if (!is_array($array)) {
return $array;
}
@ -1304,7 +1347,8 @@ function trim_array($array) {
return $array;
}
function array_csort() { //coded by Ichier2003
function array_csort()
{ //coded by Ichier2003
$args = func_get_args();
$marray = array_shift($args);
$msortline = "return(array_multisort(";
@ -1322,7 +1366,7 @@ function array_csort() { //coded by Ichier2003
$msortline .= "\$sortarr[" . $i . "],";
}
$msortline .= "\$marray));";
if(is_array($marray) && count($marray) > 0) {
if (is_array($marray) && count($marray) > 0) {
@ eval($msortline);
}
return $marray;
@ -1339,7 +1383,8 @@ function array_csort() { //coded by Ichier2003
*
* @return string Processed string
*/
function str_ireplace_once($find, $replace, $subject) {
function str_ireplace_once($find, $replace, $subject)
{
$start = strpos(strtolower($subject), strtolower($find));
if ($start === false) {
@ -1367,7 +1412,8 @@ function str_ireplace_once($find, $replace, $subject) {
*
* @return string Processed string
*/
function str_ireplace_once_reverse($find, $replace, $subject) {
function str_ireplace_once_reverse($find, $replace, $subject)
{
$start = str_rpos(strtolower($subject), strtolower($find));
if ($start === false) {
@ -1396,7 +1442,8 @@ function str_ireplace_once_reverse($find, $replace, $subject) {
*
* @return string Processed string
*/
function str_rpos($haystack, $needle, $start = 0) {
function str_rpos($haystack, $needle, $start = 0)
{
$tempPos = strpos($haystack, $needle, $start);
if ($tempPos === false) {
@ -1418,7 +1465,8 @@ function str_rpos($haystack, $needle, $start = 0) {
*
* @return boolean true if ImageMagick is available
*/
function isImageMagickAvailable() {
function isImageMagickAvailable()
{
global $_imagemagickAvailable;
if (is_bool($_imagemagickAvailable)) {
@ -1429,7 +1477,7 @@ function isImageMagickAvailable() {
}
}
$_imagemagickAvailable = (extension_loaded('imagick'))?true:false;
$_imagemagickAvailable = (extension_loaded('imagick')) ? true : false;
return $_imagemagickAvailable;
}
@ -1438,7 +1486,8 @@ function isImageMagickAvailable() {
*
* @return boolean true if the script is running from the web
*/
function isRunningFromWeb() {
function isRunningFromWeb()
{
if ($_SERVER["PHP_SELF"] == "" || php_sapi_name() == "cgi" || php_sapi_name() == "cli") {
return false;
}
@ -1451,7 +1500,8 @@ function isRunningFromWeb() {
*
* @return string client name
*/
function getClientName($idclient) {
function getClientName($idclient)
{
global $cfg;
$db = new DB_ConLite;
@ -1467,7 +1517,8 @@ function getClientName($idclient) {
}
}
function scanDirectory($sDirectory, $bRecursive = false) {
function scanDirectory($sDirectory, $bRecursive = false)
{
if (substr($sDirectory, strlen($sDirectory) - 1, 1) == "/") {
$sDirectory = substr($sDirectory, 0, strlen($sDirectory) - 1);
}
@ -1520,10 +1571,10 @@ function scanDirectory($sDirectory, $bRecursive = false) {
* The plugin's directory and file name have to be the
* same, otherwise the function won't find them!
*
* @param $entity Name of the directory to scan
* @return string client name
* @param string $entity Name of the directory to scan
*/
function scanPlugins($entity) {
function scanPlugins(string $entity)
{
global $cfg;
$pluginorder = getSystemProperty("plugin", $entity . "-pluginorder");
@ -1586,9 +1637,10 @@ function scanPlugins($entity) {
* Example:
* includePlugins("frontendusers");
*
* @param $entity Name of the directory to scan
* @param string $entity Name of the directory to scan
*/
function includePlugins($entity) {
function includePlugins(string $entity): void
{
global $cfg;
if (is_array($cfg['plugins'][$entity])) {
@ -1604,31 +1656,36 @@ function includePlugins($entity) {
* Example:
* callPluginStore("frontendusers");
*
* @param $entity Name of the directory to scan
* @param string $entity Name of the directory to scan
*/
function callPluginStore($entity) {
function callPluginStore(string $entity): void
{
global $cfg;
/* Check out if there are any plugins */
if (is_array($cfg['plugins'][$entity])) {
foreach ($cfg['plugins'][$entity] as $plugin) {
if (function_exists($entity . "_" . $plugin . "_wantedVariables") && function_exists($entity . "_" . $plugin . "_store")) {
if (function_exists($entity . "_" . $plugin . "_wantedVariables")
&& function_exists($entity . "_" . $plugin . "_store")) {
$wantVariables = call_user_func($entity . "_" . $plugin . "_wantedVariables");
$varArray = [];
if (is_array($wantVariables)) {
$varArray = array();
foreach ($wantVariables as $value) {
$varArray[$value] = stripslashes($GLOBALS[$value]);
}
}
if (count($varArray) > 0) {
$store = call_user_func($entity . "_" . $plugin . "_store", $varArray);
}
}
}
}
}
function displayPlugin($entity, & $form) {
function displayPlugin($entity, &$form): void
{
/* TODO: Function can't work, as $feuser is not defined (see $display =
* call_user_func($entity."_".$plugin."_display", $feuser);) and plugins need
* - if data has to be shown - global objects ...
@ -1667,7 +1724,8 @@ function displayPlugin($entity, & $form) {
* @param $nameLength Length of the generated string
* @return string random name
*/
function createRandomName($nameLength) {
function createRandomName($nameLength)
{
$NameChars = 'abcdefghijklmnopqrstuvwxyz';
$Vouel = 'aeiou';
$Name = "";
@ -1697,7 +1755,8 @@ function createRandomName($nameLength) {
* @param $referer Referer (optional)
* @param $port Port (default: 80)
*/
function sendPostRequest($host, $path, $data, $referer = "", $port = 80) {
function sendPostRequest($host, $path, $data, $referer = "", $port = 80)
{
$fp = fsockopen($host, $port);
fputs($fp, "POST $path HTTP/1.1\n");
@ -1717,8 +1776,9 @@ function sendPostRequest($host, $path, $data, $referer = "", $port = 80) {
return $res;
}
function is_dbfs($file) {
if(is_null($file)) {
function is_dbfs($file)
{
if (is_null($file)) {
$file = '';
}
if (substr($file, 0, 5) == "dbfs:") {
@ -1726,7 +1786,8 @@ function is_dbfs($file) {
}
}
function setHelpContext($area) {
function setHelpContext($area)
{
global $cfg;
if ($cfg['help'] == true) {
@ -1738,7 +1799,8 @@ function setHelpContext($area) {
return $hc;
}
function define_if($constant, $value) {
function define_if($constant, $value)
{
if (!defined($constant)) {
define($constant, $value);
}
@ -1756,7 +1818,8 @@ if (!defined('PHP_EOL')) {
}
}
function locale_arsort($locale, $array) {
function locale_arsort($locale, $array)
{
$oldlocale = setlocale(LC_COLLATE, 0);
setlocale(LC_COLLATE, $locale);
@ -1771,7 +1834,8 @@ function locale_arsort($locale, $array) {
/* Note: If subarrays exists, this function currently returns the key of the array
given by $array, and not from the subarrays (todo: add flag to allow this) */
function array_search_recursive($search, $array, $partial = false, $strict = false) {
function array_search_recursive($search, $array, $partial = false, $strict = false)
{
foreach ($array as $key => $value) {
if (is_array($value)) {
$val = array_search_recursive($search, $value, $partial, $strict);
@ -1803,14 +1867,15 @@ function array_search_recursive($search, $array, $partial = false, $strict = fal
/**
* cDie: Contenido die-alternative
*
* @author unknown
*
* @param string $file File name (use __FILE__)
* @param string $line Line number (use __LINE__)
* @param string $message Message to display
* @return void
* @author unknown
*
*/
function cDie($file, $line, $message) {
function cDie(string $file, string $line, string $message): void
{
cError($file, $line, $message);
die("$file $line: $message");
}
@ -1818,39 +1883,38 @@ function cDie($file, $line, $message) {
/**
* cWarning: Contenido warning
*
* @param $file File name (use __FILE__)
* @param $line Line number (use __LINE__)
* @param $message Message to display
* @param string $file File name (use __FILE__)
* @param string $line Line number (use __LINE__)
* @param string $message Message to display
*/
function cWarning($file, $line, $message) {
function cWarning(string $file, string $line, string $message): void
{
trigger_error("$file $line: $message", E_USER_WARNING);
}
/**
* cError: Contenido error
*
* @param $file File name (use __FILE__)
* @param $line Line number (use __LINE__)
* @param $message Message to display
* @param string $file File name (use __FILE__)
* @param string $line Line number (use __LINE__)
* @param string $message Message to display
*/
function cError($file, $line, $message) {
function cError(string $file, string $line, string $message): void
{
trigger_error("$file $line: $message", E_USER_ERROR);
}
/**
* cDeprecated: Trigger deprecated stuff
*
* @author Ortwin Pinke <o.pinke@conlite.org>
* @param string $file File name (use __FILE__)
* @param string $line Line number (use __LINE__)
* @param string $message Message to display
* @author Ortwin Pinke <o.pinke@conlite.org>
*/
function cDeprecated($file, $line, $message) {
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
trigger_error($file . " " . $line . ": " . $message, E_USER_DEPRECATED);
} else {
function cDeprecated(string $file, string $line, string $message): void
{
trigger_error("$file $line: $message", E_USER_WARNING);
}
}
/**
@ -1859,7 +1923,8 @@ function cDeprecated($file, $line, $message) {
* @param $frame Frame number
* @return string Canonical name of the frame
*/
function getNamedFrame($frame) {
function getNamedFrame($frame)
{
switch ($frame) {
case 1 :
return ("left_top");
@ -1887,7 +1952,8 @@ function getNamedFrame($frame) {
*
* @return int uuid for this measure process
*/
function startTiming($function, $parameters = array()) {
function startTiming($function, $parameters = array())
{
global $_timings, $cfg;
if ($cfg["debug"]["functiontiming"] == false) {
@ -1915,7 +1981,8 @@ function startTiming($function, $parameters = array()) {
*
* @param uuid int UUID which has been used for timing
*/
function endAndLogTiming($uuid) {
function endAndLogTiming($uuid)
{
global $_timings, $cfg;
if ($cfg["debug"]["functiontiming"] == false) {
@ -1959,7 +2026,8 @@ function endAndLogTiming($uuid) {
}
// @TODO: it's better to create a instance of DB_ConLite class, the class constructor connects also to the database.
function checkMySQLConnectivity() {
function checkMySQLConnectivity()
{
global $contenido_host, $contenido_database, $contenido_user, $contenido_password, $cfg;
if ($cfg["database_extension"] == "mysqli") {
@ -2017,7 +2085,8 @@ function checkMySQLConnectivity() {
}
}
function notifyOnError($errortitle, $errormessage) {
function notifyOnError($errortitle, $errormessage)
{
global $cfg;
$sFileNotify = $cfg['path']['conlite_logs'] . "notify.txt";
@ -2060,7 +2129,8 @@ function notifyOnError($errortitle, $errormessage) {
* @param multi $mDefault default value
* @return boolean false if no array is given, void otherwise
*/
function cInitializeArrayKey(&$aArray, $sKey, $mDefault = "") {
function cInitializeArrayKey(&$aArray, $sKey, $mDefault = "")
{
if (!is_array($aArray)) {
if (isset($aArray)) {
return false;
@ -2089,7 +2159,8 @@ function cInitializeArrayKey(&$aArray, $sKey, $mDefault = "") {
* @version 1.0.0
* @author Holger Librenz
*/
function sendEncodingHeader($db, $cfg, $lang) {
function sendEncodingHeader($db, $cfg, $lang)
{
if (array_key_exists("use_encoding", $_GET)) {
$use_encoding = trim(strip_tags($_GET["use_encoding"]));
}
@ -2140,7 +2211,8 @@ function sendEncodingHeader($db, $cfg, $lang) {
* @param string $ip
* @return boolean
*/
function IP_match($network, $mask, $ip) {
function IP_match($network, $mask, $ip)
{
bcscale(3);
$ip_long = ip2long($ip);
$mask_long = ip2long($network);
@ -2173,63 +2245,67 @@ function IP_match($network, $mask, $ip) {
/**
* Wrapper for php-function htmlspecialchars
*
* @author Ortwin Pinke <ortwinpinke@conlite.org>
* @since 2.3.0
* @uses htmlspecialchars php-function
*
* @param string $value
* @param int $flags
* @param string $encoding default UTF-8
* @return string Returns the converted string
* @since 2.3.0
* @uses htmlspecialchars php-function
*
* @author Ortwin Pinke <ortwinpinke@conlite.org>
*/
function clHtmlSpecialChars(string $value, ?int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, string $encoding = 'UTF-8') {
function clHtmlSpecialChars(string $value, ?int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, string $encoding = 'UTF-8')
{
return htmlspecialchars($value, $flags, $encoding);
}
/**
* Wrapper for php-function html_entity_decode
*
* @author Ortwin Pinke <ortwinpinke@conlite.org>
* @since 2.3.0
* @uses html_entity_decode php-function
*
* @param string $value
* @param int $flags
* @param string $encoding default UTF-8
* @return string Returns the decoded string
* @since 2.3.0
* @uses html_entity_decode php-function
*
* @author Ortwin Pinke <ortwinpinke@conlite.org>
*/
function clHtmlEntityDecode(string $value, ?int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, string $encoding = 'UTF-8') {
function clHtmlEntityDecode(string $value, ?int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, string $encoding = 'UTF-8')
{
return html_entity_decode($value, $flags, $encoding);
}
/**
* Wrapper for php-function htmlentities
*
* @author Ortwin Pinke <ortwinpinke@conlite.org>
* @since 2.3.0
* @uses htmlentities php-function
*
* @param string $value
* @param int $flags
* @param string $encoding default UTF-8
* @return string Returns the converted string
* @since 2.3.0
* @uses htmlentities php-function
*
* @author Ortwin Pinke <ortwinpinke@conlite.org>
*/
function clHtmlEntities(string $value,?int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, string $encoding = 'UTF-8') {
function clHtmlEntities(string $value, ?int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, string $encoding = 'UTF-8')
{
return htmlentities($value, $flags, $encoding);
}
/**
* Wrapper for php-function get_html_translation_table
*
* @author Ortwin Pinke <ortwinpinke@conlite.org>
* @since 2.3.0
* @uses get_html_translation_table php-function
*
* @param int $table
* @param int $flags
* @param string $encoding
* @return array
* @since 2.3.0
* @uses get_html_translation_table php-function
*
* @author Ortwin Pinke <ortwinpinke@conlite.org>
*/
function clGetHtmlTranslationTable(int $table = HTML_SPECIALCHARS, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, string $encoding = "UTF-8") {
function clGetHtmlTranslationTable(int $table = HTML_SPECIALCHARS, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, string $encoding = "UTF-8")
{
return get_html_translation_table($table, $flags, $encoding);
}

Datei anzeigen

@ -1,132 +0,0 @@
<?php
/**
* Description:
* Fix functions for PHP 5.4
*
* @package Core
* @subpackage CL-Includes
* @author Ortwin Pinke <ortwin.pinke@conlite.org>
* @copyright (c) 2014, www.conlite.org
* @version $Rev$
*
* $Id$
*/
// security
if (!defined('CON_FRAMEWORK')) {
die('Illegal call');
}
/**
*
* @return string
*/
function clCheckForPhp54() {
if(!defined("CL_PHP54")) {
/**
* PHP-version equal or greater PHP 5.4
* @constant CL_PHP54 phpversion >= 5.4
*/
define('CL_PHP54', version_compare(PHP_VERSION, '5.4.0', '>=') ? 1:0);
}
return CL_PHP54;
}
function clPhp54FixedFunc($funcname, $value, $flags = '', $encoding = '') {
if(clCheckForPhp54()) {
if($funcname == "get_html_translation_table") {
$value = ($value == '') ? HTML_SPECIALCHARS : $value;
}
$flags = (empty($flags))?ENT_COMPAT|ENT_HTML401:$flags;
$encoding = (empty($encoding))?'ISO-8859-1':$encoding;
} else {
$flags = (empty($flags))?ENT_COMPAT:$flags;
}
if($funcname == "get_html_translation_table") {
return $funcname($value, $flags);
} else {
return $funcname($value, $flags, $encoding);
}
}
/**
*
* @uses clPhp54FixedFunc multi fix func for PHP5.4
* @author Ortwin Pinke <ortwinpinke@conlite.org>
*
* @param string $value
* @param mixed $flags
* @param string $encoding
* @return string
*/
/*
function clHtmlSpecialChars($value, $flags = '', $encoding = '') {
return clPhp54FixedFunc("htmlspecialchars", $value, $flags, $encoding);
}
*/
/**
*
* @uses clPhp54FixedFunc multi fix func for PHP5.4
* @author Ortwin Pinke <ortwinpinke@conlite.org>
*
* @param string $value
* @param mixed $flags
* @param string $encoding
* @return string
*/
/*
function clHtmlEntityDecode($value, $flags = '', $encoding = '') {
return clPhp54FixedFunc("html_entity_decode", $value, $flags, $encoding);
}
*
*/
/**
*
* @uses clPhp54FixedFunc multi fix func for PHP5.4
* @author Ortwin Pinke <ortwinpinke@conlite.org>
*
* @param string $value
* @param mixed $flags
* @param string $encoding
* @return string
*/
/*
function clHtmlEntities($value, $flags = '', $encoding = '') {
return clPhp54FixedFunc("htmlentities", $value, $flags, $encoding);
}
*
*/
/**
*
* @uses clPhp54FixedFunc multi fix func for PHP5.4
* @author Ortwin Pinke <ortwinpinke@conlite.org>
*
* @param string $table
* @param mixed $flags
* @return string
*/
/*
function clGetHtmlTranslationTable($table = '', $flags = '') {
return clPhp54FixedFunc("get_html_translation_table", $table, $flags);
}
*
*/
// hold old functions from con 4.8 but use new ConLite functions, mark them as deprecated
/**
* Use compatible clHtmlSpecialChars instead
* @deprecated since version 2.0
*/
/**
if (function_exists('conHtmlSpecialChars') == false) {
function conHtmlSpecialChars($value, $flags = '', $encoding = '') {
return clHtmlSpecialChars($value, $flags, $encoding);
}
}
*
*/

Datei anzeigen

@ -1,38 +0,0 @@
<?php
/**
* PHP 7.3 functions for older PHP versions
*
* @package Core
* @subpackage functions
* @version $Rev$
* @since 2.0.3
* @author Ortwin Pinke <o.pinke@conlite.org>
* @copyright (c) 2019, conlite.org
* @license http://www.gnu.de/documents/gpl.en.html GPL v3 (english version)
* @license http://www.gnu.de/documents/gpl.de.html GPL v3 (deutsche Version)
* @link http://www.conlite.org ConLite.org
*
* $Id$
*/
// security check
defined('CON_FRAMEWORK') or die('Illegal call');
if (!function_exists('is_countable')) {
/**
* Verify that the contents of a variable is a countable value
* <p>Verify that the contents of a variable is an <code>array</code> or an object implementing Countable</p>
* @param mixed $var <p>The value to check</p>
* @return bool <p>Returns <b><code>TRUE</code></b> if <code>var</code> is countable, <b><code>FALSE</code></b> otherwise.</p>
* @link http://php.net/manual/en/function.is-countable.php
*
* @param Countable $var
* @return boolean
*/
function is_countable($var) {
return (is_array($var) || $var instanceof Countable);
}
}

Datei anzeigen

@ -107,6 +107,9 @@
* ************************************************************************* */
use ConLite\Log\Log;
use ConLite\Log\LogWriter;
if (!defined('CON_FRAMEWORK')) {
die('Illegal call');
}
@ -182,7 +185,8 @@ chdir($PC_reqDir);
if ($PC_debug)
echo "\n</pre>";
function logMessage($msg, $PC_writeDir, $PC_useLog, $PC_debug) {
function logMessage($msg, $PC_writeDir, $PC_useLog, $PC_debug): void
{
$oCronLog = new cCronJob();
$oCronLog->useCronLog($PC_useLog);
$oCronLog->logMessages($msg);
@ -193,7 +197,8 @@ function logMessage($msg, $PC_writeDir, $PC_useLog, $PC_debug) {
}
}
function lTrimZeros($number) {
function lTrimZeros($number)
{
/*
while ($number[0] == '0') {
@ -203,10 +208,11 @@ function lTrimZeros($number) {
*/
$number = intval(ltrim($number, '0'));
return (is_numeric($number))?$number:0;
return (is_numeric($number)) ? $number : 0;
}
function parseElement($element, &$targetArray, $numberOfElements) {
function parseElement($element, &$targetArray, $numberOfElements)
{
$subelements = explode(",", $element);
for ($i = 0; $i < $numberOfElements; $i++) {
@ -235,7 +241,8 @@ function parseElement($element, &$targetArray, $numberOfElements) {
}
}
function decDate(&$dateArr, $amount, $unit, $PC_debug) {
function decDate(&$dateArr, $amount, $unit, $PC_debug)
{
if ($PC_debug)
echo sprintf("Decreasing from %02d.%02d. %02d:%02d by %d %6s ", $dateArr[mday], $dateArr[mon], $dateArr[hours], $dateArr[minutes], $amount, $unit);
@ -249,11 +256,11 @@ function decDate(&$dateArr, $amount, $unit, $PC_debug) {
$dateArr["wday"] += 7;
}
if ($dateArr["mday"] < 1) {
$dateArr["mon"] --;
$dateArr["mon"]--;
switch ($dateArr["mon"]) {
case 0:
$dateArr["mon"] = 12;
$dateArr["year"] --;
$dateArr["year"]--;
// fall through
case 1:
case 3:
@ -281,28 +288,29 @@ function decDate(&$dateArr, $amount, $unit, $PC_debug) {
} else {
$dateArr["minutes"] = 59;
$dateArr["seconds"] = 59;
$dateArr["hours"] --;
$dateArr["hours"]--;
}
} elseif ($unit == "minute") {
if ($dateArr["minutes"] == 0) {
decDate($dateArr, 1, "hour", $PC_debug);
} else {
$dateArr["seconds"] = 59;
$dateArr["minutes"] --;
$dateArr["minutes"]--;
}
}
if ($PC_debug)
echo sprintf("to %02d.%02d. %02d:%02d\n", $dateArr[mday], $dateArr[mon], $dateArr[hours], $dateArr[minutes]);
}
function getLastScheduledRunTime($job, $PC_debug) {
function getLastScheduledRunTime($job, $PC_debug)
{
$dateArr = getdate();
$minutesBack = 0;
while (
$minutesBack < 525600 AND ( !$job[PC_MINUTE][$dateArr["minutes"]] OR ! $job[PC_HOUR][$dateArr["hours"]] OR ( !$job[PC_DOM][$dateArr["mday"]] OR ! $job[PC_DOW][$dateArr["wday"]]) OR ! $job[PC_MONTH][$dateArr["mon"]])
$minutesBack < 525600 and (!$job[PC_MINUTE][$dateArr["minutes"]] or !$job[PC_HOUR][$dateArr["hours"]] or (!$job[PC_DOM][$dateArr["mday"]] or !$job[PC_DOW][$dateArr["wday"]]) or !$job[PC_MONTH][$dateArr["mon"]])
) {
if (!$job[PC_DOM][$dateArr["mday"]] OR ! $job[PC_DOW][$dateArr["wday"]]) {
if (!$job[PC_DOM][$dateArr["mday"]] or !$job[PC_DOW][$dateArr["wday"]]) {
decDate($dateArr, 1, "mday", $PC_debug);
$minutesBack += 1440;
continue;
@ -325,13 +333,15 @@ function getLastScheduledRunTime($job, $PC_debug) {
return mktime($dateArr["hours"], $dateArr["minutes"], 0, $dateArr["mon"], $dateArr["mday"], $dateArr["year"]);
}
function getJobFileName($jobname, $PC_writeDir) {
function getJobFileName($jobname, $PC_writeDir)
{
$jobfile = $PC_writeDir . urlencode($jobname) . ".job";
return $jobfile;
}
function getLastActialRunTime($jobname, $PC_writeDir) {
function getLastActialRunTime($jobname, $PC_writeDir)
{
$jobfile = getJobFileName($jobname, $PC_writeDir);
if (file_exists($jobfile)) {
@ -345,7 +355,8 @@ function getLastActialRunTime($jobname, $PC_writeDir) {
return 0;
}
function markLastRun($jobname, $lastRun, $PC_writeDir) {
function markLastRun($jobname, $lastRun, $PC_writeDir)
{
$jobfile = getJobFileName($jobname, $PC_writeDir);
@ -357,12 +368,13 @@ function markLastRun($jobname, $lastRun, $PC_writeDir) {
}
}
function runJob($job, $PC_jobDir, $PC_writeDir, $PC_useLog, $PC_debug = false) {
function runJob($job, $PC_jobDir, $PC_writeDir, $PC_useLog, $PC_debug = false)
{
global $cfg, $sess, $PC_logDir;
if (!is_writable($PC_writeDir)) {
return false;
}
$extjob = Array();
$extjob = array();
$jobfile = getJobFileName($job[PC_CMD], $PC_writeDir);
parseElement($job[PC_MINUTE], $extjob[PC_MINUTE], 60);
parseElement($job[PC_HOUR], $extjob[PC_HOUR], 24);
@ -377,8 +389,8 @@ function runJob($job, $PC_jobDir, $PC_writeDir, $PC_useLog, $PC_debug = false) {
if ($lastScheduled > $lastActual) {
logMessage("Running " . $job[PC_CRONLINE], $PC_writeDir, $PC_useLog, $PC_debug);
logMessage(" Last run: " . date("r", $lastActual), $PC_writeDir, $PC_useLog, $PC_debug);
logMessage(" Last scheduled: " . date("r", $lastScheduled), $PC_writeDir, $PC_useLog, $PC_debug);
logMessage("Last run: " . date("r", $lastActual), $PC_writeDir, $PC_useLog, $PC_debug);
logMessage("Last scheduled: " . date("r", $lastScheduled), $PC_writeDir, $PC_useLog, $PC_debug);
markLastRun($job[PC_CMD], $lastScheduled, $PC_writeDir);
if ($PC_debug) {
@ -398,20 +410,21 @@ function runJob($job, $PC_jobDir, $PC_writeDir, $PC_useLog, $PC_debug = false) {
} else {
if ($PC_debug) {
logMessage("Skipping " . $job[PC_CRONLINE], $PC_writeDir, $PC_useLog, $PC_debug);
logMessage(" Last run: " . date("r", $lastActual), $PC_writeDir, $PC_useLog, $PC_debug);
logMessage(" Last scheduled: " . date("r", $lastScheduled), $PC_writeDir, $PC_useLog, $PC_debug);
logMessage("Last run: " . date("r", $lastActual), $PC_writeDir, $PC_useLog, $PC_debug);
logMessage("Last scheduled: " . date("r", $lastScheduled), $PC_writeDir, $PC_useLog, $PC_debug);
logMessage("Completed " . $job[PC_CRONLINE], $PC_writeDir, $PC_useLog, $PC_debug);
}
return false;
}
}
function parseCronFile($PC_cronTabFile, $PC_debug) {
function parseCronFile($PC_cronTabFile, $PC_debug)
{
$file = @file($PC_cronTabFile);
$job = Array();
$jobs = Array();
if(!is_countable($file)) {
$job = [];
$jobs = [];
if (!is_countable($file)) {
return $jobs;
}
for ($i = 0; $i < count($file); $i++) {
@ -421,9 +434,9 @@ function parseCronFile($PC_cronTabFile, $PC_debug) {
if (preg_match("~^([-0-9,/*]+)\\s+([-0-9,/*]+)\\s+([-0-9,/*]+)\\s+([-0-9,/*]+)\\s+([-0-7,/*]+|(-|/|Sun|Mon|Tue|Wed|Thu|Fri|Sat)+)\\s+([^#]*)(#.*)?$~i", $file[$i], $job)) {
$jobNumber = count($jobs);
$jobs[$jobNumber] = $job;
if ($jobs[$jobNumber][PC_DOW][0] != '*' AND ! is_numeric($jobs[$jobNumber][PC_DOW])) {
if ($jobs[$jobNumber][PC_DOW][0] != '*' and !is_numeric($jobs[$jobNumber][PC_DOW])) {
$jobs[$jobNumber][PC_DOW] = str_replace(
Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"), Array(0, 1, 2, 3, 4, 5, 6), $jobs[$jobNumber][PC_DOW]);
array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"), array(0, 1, 2, 3, 4, 5, 6), $jobs[$jobNumber][PC_DOW]);
}
$jobs[$jobNumber][PC_CMD] = trim($job[PC_CMD]);
$jobs[$jobNumber][PC_CRONLINE] = $file[$i];
@ -436,32 +449,41 @@ function parseCronFile($PC_cronTabFile, $PC_debug) {
return $jobs;
}
class cCronJob {
class cCronJob
{
protected $_sCronTabFileName = "crontab.txt";
protected $_sCronTabLocalFileName = "crontab.local.txt";
protected $_sLogFileName = "pseudo-cron.log";
protected $_sJobDir;
protected $_sCronDir;
protected $_sLogDir;
private $_bUseLog;
private $_iMaxLogFileSize = 1024;
protected string $_sCronTabFileName = "crontab.txt";
protected string $_sCronTabLocalFileName = "crontab.local.txt";
protected string $_sLogFileName = "pseudo-cron.log";
protected string $_sJobDir;
protected string|array|null $_sCronDir;
protected string|array|null $_sLogDir;
private bool $_bUseLog;
private int $_iMaxLogFileSize = 1024;
public function __construct() {
public function __construct()
{
$this->_sJobDir = cRegistry::getConfigValue('path', 'conlite') . cRegistry::getConfigValue('path', 'cronjobs');
$this->_sCronDir = cRegistry::getConfigValue('path', 'conlite_cronlog');
$this->_sLogDir = cRegistry::getConfigValue('path', 'conlite_logs');
}
public function runJob() {
}
public function useCronLog($bUse = TRUE) {
public function runJob()
{
}
public function useCronLog($bUse = TRUE): void
{
$this->_bUseLog = boolval($bUse);
}
public function logMessages($sMsg) {
/**
* @throws \ConLite\Exceptions\InvalidArgumentException
*/
public function logMessages($sMsg): void
{
if (!$this->_bUseLog) {
return;
}
@ -474,44 +496,9 @@ class cCronJob {
return;
}
if ($sMsg[strlen($sMsg) - 1] != "\n") {
$sMsg .= "\r\n";
}
$this->_rotateLogFiles($logfile);
file_put_contents($logfile, $sMsg, FILE_APPEND);
}
private function _rotateLogFiles($sLogFile) {
if (file_exists($sLogFile) &&
filesize($sLogFile) >= $this->_iMaxLogFileSize * 1024) {
// rotate
$path_info = pathinfo($sLogFile);
$base_directory = $path_info['dirname'];
$base_name = $path_info['basename'];
$num_map = array();
foreach (new DirectoryIterator($base_directory) as $fInfo) {
if ($fInfo->isDot() || !$fInfo->isFile()) {
continue;
}
if (preg_match('/^' . $base_name . '\.?([0-9]*)$/', $fInfo->getFilename(), $matches)) {
$num = $matches[1];
$file2move = $fInfo->getFilename();
if ($num == '') {
$num = 0;
}
$num_map[$num] = $file2move;
}
}
krsort($num_map);
foreach ($num_map as $num => $file2move) {
$targetN = $num + 1;
if($targetN > 10) {
unlink($base_directory . DIRECTORY_SEPARATOR . $file2move);
continue;
}
rename($base_directory . DIRECTORY_SEPARATOR . $file2move, $base_directory . DIRECTORY_SEPARATOR .$base_name . '.' . $targetN);
}
}
$writer = LogWriter::factory('File', ['destination' => $logfile]);
$log = new Log($writer);
$log->addPriority('CRON', 200);
$log->log($sMsg, 'CRON');
}
}
?>

Datei anzeigen

@ -75,13 +75,6 @@ define('CL_VERSION', '3.0.0 RC');
}
// fixed functions for PHP 5.4 and later
// @todo: Check what is needed for PHP7+
include_once(str_replace('\\', '/', realpath(dirname(__FILE__) . '/..')) . '/includes/functions.php54.php');
// simulate PHP 7.3 functions
include_once(str_replace('\\', '/', realpath(dirname(__FILE__) . '/..')) . '/includes/functions.php73.php');
// 1. security check: Include security class and invoke basic request checks
include_once(str_replace('\\', '/', realpath(dirname(__FILE__) . '/..')) . '/classes/class.security.php');
try {
@ -218,7 +211,7 @@ if (!isset($encoding) || !is_array($encoding) || count($encoding) == 0) {
$encoding = array();
$sql = "SELECT idlang, encoding FROM " . $cfg["tab"]["lang"];
$db->query($sql);
while ($db->next_record()) {
while ($db->nextRecord()) {
$encoding[$db->f('idlang')] = $db->f('encoding');
}
}
@ -228,4 +221,3 @@ if($cfg['debug']['sendnocacheheader']) {
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.
}
?>

Datei anzeigen

@ -1,4 +1,8 @@
<?php
use ConLite\Log\LogWriter;
use ConLite\Log\Log;
if(!defined('CON_FRAMEWORK')) {
die('Illegal call');
}
@ -12,11 +16,11 @@ class pimExeption extends Exception {
parent::__construct($message, $code, $previous);
// create a logger class and save it for all logging purposes
$writer = cLogWriter::factory("File", array(
$writer = LogWriter::factory("File", array(
'destination' => cRegistry::getConfigValue('path', 'data')
. 'logs/exception.log'
));
$this->_logger = new cLog($writer);
$this->_logger = new Log($writer);
// determine if exception should be logged
if (false === $this->_log_exception

18
vendor/autoload.php vendored
Datei anzeigen

@ -2,24 +2,6 @@
// autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
trigger_error(
$err,
E_USER_ERROR
);
}
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit030320213c853f2cfb8481e1bb7caf00::getLoader();

Datei anzeigen

@ -2,7 +2,7 @@
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(__DIR__);
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(

Datei anzeigen

@ -2,7 +2,7 @@
// autoload_files.php @generated by Composer
$vendorDir = dirname(__DIR__);
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(

Datei anzeigen

@ -2,7 +2,7 @@
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(__DIR__);
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(

Datei anzeigen

@ -2,7 +2,7 @@
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(__DIR__);
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(

Datei anzeigen

@ -25,15 +25,38 @@ class ComposerAutoloaderInit030320213c853f2cfb8481e1bb7caf00
require __DIR__ . '/platform_check.php';
spl_autoload_register(array('ComposerAutoloaderInit030320213c853f2cfb8481e1bb7caf00', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(\dirname(__FILE__)));
spl_autoload_unregister(array('ComposerAutoloaderInit030320213c853f2cfb8481e1bb7caf00', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInit030320213c853f2cfb8481e1bb7caf00::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
$includeFiles = \Composer\Autoload\ComposerStaticInit030320213c853f2cfb8481e1bb7caf00::$files;
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInit030320213c853f2cfb8481e1bb7caf00::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequire030320213c853f2cfb8481e1bb7caf00($fileIdentifier, $file);
}