* @license https://mit-license.org/ MIT License * @link https://git.mysnippetsofcode.com/tts/neatoDeploy */ /** * $cwd is defined in neato.php * * @phpstan-ignore-next-line Variable $cwd might not be defined */ define('PROJECT_LOGS_DIR', $cwd. '/log'); /** * Logs display data * * @category Util * @package Neato * @author Robert S. * @license https://mit-license.org/ MIT License * @link https://git.mysnippetsofcode.com/tts/neatoDeploy * */ class Logger { private $_handle; /** * Get Filename for writing to Log file * * @param string $filename for log * @param int $max_count of lines before file wipe, to keep small logs. */ public function __construct(string $filename = 'neato_Installer', int $max_count = 1000) { if (strpos($filename, "..") !== false) { $this->_handle = false; // Too dangerious, so return false } else { $filename = str_replace("php", "", $filename); if (! is_dir(PROJECT_LOGS_DIR)) { //Directory does not exist, so lets create it. mkdir(PROJECT_LOGS_DIR, 0775); } $filename = preg_replace("|[^A-Za-z0-9_]|", "", $filename); $filename = escapeshellcmd($filename); $file = PROJECT_LOGS_DIR . '/' . $filename . ".log.txt"; if ($max_count > 1) { if ($this->getLines($file) > $max_count) { unlink($file); } } $success = touch($file); if ($success === false) { $this->_handle = false; throw new \Exception('Unable to touch file:' . $file); } chmod($file, 0660); if (! is_writable($file)) { $this->_handle = false; throw new \Exception('Unable to write to file:' . $file); } $this->_handle = fopen($file, 'a'); } } /** * Count number of lines in Log File * * @param string $file filename to check how big it is * * @return int line count */ public function getLines(string $file): int { // No such file, so return zero for length. if (! file_exists($file)) { return 0; } $f = fopen($file, 'rb'); $lines = 0; if ($f === false || !is_resource($f)) { return 0; } while (!feof($f)) { $line = fread($f, 8192); if ($line === false) { return 0; } $lines += substr_count($line, "\n"); } fclose($f); return $lines; } /** * Write to Log File * * @param string $message to save * * @return bool able to write to log file */ public function write(string $message): bool { if ($this->_handle === false || ! is_resource($this->_handle) ) { return false; } $tz = Configure::get('logger_time_zone'); if ($tz !== false && !empty($tz)) { $tz_obj = new \DateTimeZone($tz); $dt = new \DateTime(); $dt->setTimezone($tz_obj); $now = $dt->format('g:i A \o\n l jS F Y'); } else { $dt = new \DateTime(); $now = $dt->format('g:i A \o\n l jS F Y'); } fwrite($this->_handle, $now . ' - ' . print_r($message, true) . "\n"); return true; } /** * Close Log File Handle */ public function __destruct() { if ($this->_handle !== false && is_resource($this->_handle)) { fclose($this->_handle); } } } // end of Logger