/**
	 * Constructs a new Debug-Object.
	 *
	 * The first parameter has to be the file name with extension, but without directory. The second
	 * parameter has to be a valid and existing directory path with trainling directory separator
	 * (make sure the directory is writable). Standard value for this paramteer is null. If the
	 * directory is null or invalid  "data/logs/" will be used. If the specified file doesn't exist
	 * it will created. If it is not possible to create a file a NonFatalException will be thrown.
	 *
	 * @param string File for saving the logdata
	 * @param string Valid Directory for saving the logfile or null (directory will be "data/logs/")
	 * @throws NonFatalException
	 */
	public function __construct($file, $dir = null) {
		if ($dir === null || is_dir($dir) === false) {
			$dir = 'data/logs/';
		}
		$this->file = new File($dir.basename($file));
		if ($this->file->create() === false) {
			throw new NonFatalException('Could not create log file "'.$this->file->relPath().'".');
		}
		if ($this->file->readable() === false || $this->file->writable() === false) {
			$this->file->setPermissions(666);
		}
		$this->logs = array();
		$this->benchmarks = array();
		$this->temp = array();
	}
Example #2
0
 /**
  * Writes given message to a log file in the logs directory.
  *
  * @param string $type Type of log, becomes part of the log's filename
  * @param string $msg  Message to log
  * @return boolean Success
  * @access public
  * @static
  */
 function write($type, $msg)
 {
     if (!defined('LOG_ERROR')) {
         define('LOG_ERROR', 2);
     }
     if (!defined('LOG_ERR')) {
         define('LOG_ERR', LOG_ERROR);
     }
     $levels = array(LOG_WARNING => 'warning', LOG_NOTICE => 'notice', LOG_INFO => 'info', LOG_DEBUG => 'debug', LOG_ERR => 'error', LOG_ERROR => 'error');
     if (is_int($type) && isset($levels[$type])) {
         $type = $levels[$type];
     }
     if ($type == 'error' || $type == 'warning') {
         $filename = LOGS . 'error.log';
     } elseif (in_array($type, $levels)) {
         $filename = LOGS . 'debug.log';
     } else {
         $filename = LOGS . $type . '.log';
     }
     $output = date('Y-m-d H:i:s') . ' ' . ucfirst($type) . ': ' . $msg . "\n";
     $log = new File($filename, true);
     if ($log->writable()) {
         return $log->append($output);
     }
 }
 function _checkDatabaseFile()
 {
     $oDBConfig = new File(CONFIGS . 'database.php', true, 0777);
     if (!$oDBConfig->writable()) {
         return false;
     }
     return $oDBConfig;
 }
Example #4
0
 /**
  * Outputs a single or multiple error messages to stderr. If no parameters
  * are passed outputs just a newline.
  *
  * @param mixed $message A string or a an array of strings to output
  * @param integer $newlines Number of newlines to append
  * @access public
  */
 function out($message = null, $newlines = 1)
 {
     if (is_array($message)) {
         $message = implode($this->nl(), $message);
     }
     $output = $message . $this->nl($newlines);
     if (isset($this->File) && $this->File->writable()) {
         $this->File->append($output);
     }
     return $output;
 }
 /**
  * Constructs a new Debug-Object.
  *
  * The first parameter has to be the file name with extension, but without directory.
  * Standard value is null, then the filename will be "internal.log".
  * The second parameter has to be a valid and existing directory with trailing slash.
  * Standard value is also null, then the directory will be "data/logs/" (make sure that it is writable).
  * If the specified file doesn't exist, it will created.
  * If it is not possible to create a file nn Exception will be thrown.
  *
  * @param string File for saving the logdata or null (filename is internal.log then)
  * @param string Directory for saving the logfile or null (directory is data/logs/ then)
  * @throws Exception
  */
 public function __construct($file = null, $dir = null)
 {
     if ($dir == null || is_dir($dir) == false) {
         $dir = 'data/logs/';
     }
     if ($file == null) {
         $file = 'internal.log';
     }
     $this->file = new File($dir . basename($file));
     if ($this->file->create() == false) {
         throw new Exception('Could not create log file in method Debug::__construct().');
     }
     if ($this->file->readable() == false || $this->file->writable() == false) {
         $writable = new CHMOD(666);
         $this->file->setChmod($writable);
     }
     $this->logs = array();
     $this->benchmarks = array();
     $this->temp = array();
 }
Example #6
0
 /**
  * Implements writing to log files.
  *
  * @param string $type The type of log you are making.
  * @param string $message The message you want to log.
  * @return boolean success of write.
  */
 function write($type, $message)
 {
     $debugTypes = array('notice', 'info', 'debug');
     if ($type == 'error' || $type == 'warning') {
         $filename = $this->_path . 'error.log';
     } elseif (in_array($type, $debugTypes)) {
         $filename = $this->_path . 'debug.log';
     } else {
         $filename = $this->_path . $type . '.log';
     }
     $output = date('Y-m-d H:i:s') . ' ' . ucfirst($type) . ': ' . $message . "\n";
     $log = new File($filename, true);
     if ($log->writable()) {
         return $log->append($output);
     }
 }
 function setSettings($data)
 {
     $data = array_merge($this->_settings[$this->_settingsName], $data);
     $configs = $this->expandArray($data, "['" . $this->_settingsName . "']");
     $this->log("Settings Data:" . print_r($configs, true) . "\nfrom:" . print_r($data, true), 'debug');
     foreach ($configs as $config) {
         $content .= $config;
     }
     if (!class_exists('File')) {
         require LIBS . 'file.php';
     }
     $fileClass = new File($this->settingsFile, true, '0744');
     $content = "<?php\n" . $content . "\n?>";
     if ($fileClass->writable()) {
         $fileClass->write($content);
     }
 }
Example #8
0
 public function open($dir, $filename, $write = false)
 {
     $this->_currentFile = null;
     $this->_currentFileLastModified = null;
     $ds = $this->getDataSource();
     $file = new File($filepath = $ds->config['path'] . DS . $dir . DS . $filename, false);
     if (!$file) {
         return false;
     }
     if (!$file->readable()) {
         return false;
     }
     if ($write && !$file->writable()) {
         return false;
     }
     $this->_currentFile = $file;
     $this->_currentFileLastChange = $file->lastChange();
     return $file;
 }
Example #9
0
 /**
  * Creates a cached version of a configuration file.
  * Appends values passed from Configure::store() to the cached file
  *
  * @param string $content Content to write on file
  * @param string $name Name to use for cache file
  * @param boolean $write true if content should be written, false otherwise
  * @return void
  * @access private
  */
 function __writeConfig($content, $name, $write = true)
 {
     $file = CACHE . 'persistent' . DS . $name . '.php';
     if (Configure::read() > 0) {
         $expires = "+10 seconds";
     } else {
         $expires = "+999 days";
     }
     $cache = cache('persistent' . DS . $name . '.php', null, $expires);
     if ($cache === null) {
         cache('persistent' . DS . $name . '.php', "<?php\n\$config = array();\n", $expires);
     }
     if ($write === true) {
         if (!class_exists('File')) {
             require LIBS . 'file.php';
         }
         $fileClass = new File($file);
         if ($fileClass->writable()) {
             $fileClass->append($content);
         }
     }
 }
Example #10
0
 public function grabFiles()
 {
     $validItems = $this->getFileRules();
     App::uses('Folder', 'Utility');
     App::uses('File', 'Utility');
     $result = array();
     foreach ($validItems as $k => &$item) {
         $dir = new Folder($item['path']);
         $files = $dir->find($item['regex'], true);
         foreach ($files as $file) {
             $f = new File($item['path'] . DS . $file);
             $validItems[$k]['files'][] = array('filename' => $file, 'filesize' => $f->size(), 'read' => $f->readable(), 'write' => $f->writable(), 'execute' => $f->executable());
         }
     }
     return $validItems;
 }
Example #11
0
 /**
  * Creates a file at given path
  *
  * @param string $path Where to put the file.
  * @param string $contents Content to put in the file.
  * @return boolean Success
  * @link http://book.cakephp.org/2.0/en/console-and-shells.html#Shell::createFile
  */
 public function createFile($path, $contents)
 {
     $path = str_replace(DS . DS, DS, $path);
     $this->out();
     if (is_file($path) && empty($this->params['force']) && $this->interactive === true) {
         $this->out(__d('cake_console', '<warning>File `%s` exists</warning>', $path));
         $key = $this->in(__d('cake_console', 'Do you want to overwrite?'), array('y', 'n', 'q'), 'n');
         if (strtolower($key) === 'q') {
             $this->out(__d('cake_console', '<error>Quitting</error>.'), 2);
             return $this->_stop();
         } elseif (strtolower($key) !== 'y') {
             $this->out(__d('cake_console', 'Skip `%s`', $path), 2);
             return false;
         }
     } else {
         $this->out(__d('cake_console', 'Creating file %s', $path));
     }
     $File = new File($path, true);
     if ($File->exists() && $File->writable()) {
         $data = $File->prepare($contents);
         $File->write($data);
         $this->out(__d('cake_console', '<success>Wrote</success> `%s`', $path));
         return true;
     }
     $this->err(__d('cake_console', '<error>Could not write to `%s`</error>.', $path), 2);
     return false;
 }
Example #12
0
 private function __advancedFileFind($conditions)
 {
     if (empty($this->fileList[1])) {
         $this->return = array();
         return true;
     }
     $i = 0;
     foreach ($this->fileList[1] as $file) {
         if (in_array($file, $this->ignore)) {
             continue;
         }
         if ($this->recursive > -2) {
             $Folder = new Folder($this->path);
             $this->return[$i]['File']['path'] = $Folder->path . DS . $file;
             $this->return[$i]['File']['relative'] = $this->__relativePath($this->return[$i]['File']['path']);
             $stat = stat($this->return[$i]['File']['path']);
             $this->__fileStatus($i, $stat);
             if ($this->recursive > -1) {
                 $this->return[$i]['File']['accessed'] = date('Y-m-d H:i:s', $stat['atime']);
                 $this->return[$i]['File']['modified'] = date('Y-m-d H:i:s', $stat['mtime']);
                 $this->return[$i]['File']['created'] = date('Y-m-d H:i:s', $stat['ctime']);
                 $File = new File($this->return[$i]['File']['path']);
                 $info = $File->info();
                 $this->return[$i]['File']['dirname'] = $info['dirname'];
                 $this->return[$i]['File']['name'] = $info['basename'];
                 $this->return[$i]['File']['extension'] = isset($info['extension']) ? $info['extension'] : null;
                 $this->return[$i]['File']['filename'] = $info['filename'];
                 $this->return[$i]['File']['writable'] = $File->writable();
                 if ($this->recursive > 0) {
                     $this->return[$i]['File']['size'] = $File->size();
                     $this->return[$i]['File']['owner'] = $File->owner();
                     $this->return[$i]['File']['group'] = $File->group();
                     $this->return[$i]['File']['accessed'] = $File->lastAccess();
                     $this->return[$i]['File']['modidfied'] = $File->lastChange();
                     $this->return[$i]['File']['charmod'] = $File->perms();
                     if ($this->recursive > 1) {
                         $this->return[$i]['File']['type'] = filetype($this->return[$i]['File']['path']);
                         $this->return[$i]['File']['md5'] = $File->md5();
                         $this->return[$i]['File']['Extended'] = stat($this->return[$i]['File']['path']);
                         $i++;
                         continue;
                     }
                     $i++;
                 }
                 $i++;
             }
             $i++;
         }
         $i++;
     }
     return true;
 }
Example #13
0
 public function writeToFile($target)
 {
     $log = new File($target, true);
     if ($log->size() == 0 && $log->writable()) {
         $log->append('<?xml version="1.0" encoding="utf-8" ?>');
     }
     if ($log->writable()) {
         return $log->append($this->toXml());
     }
     return false;
 }
Example #14
0
 /**
  * Database configuration step
  */
 public function database()
 {
     $this->set('title_for_layout', __d('hurad', 'Database Configuration'));
     if ($this->request->is('post')) {
         $this->Installer->set($this->request->data);
         if ($this->Installer->validates()) {
             if (!$this->isValidConnection('validation_test', $this->request->data['Installer']) && !array_key_exists('content', $this->request->data['Installer'])) {
                 $this->Session->setFlash(__d('hurad', 'Database connection "Mysql" is missing, or could not be created.'), 'flash_message', ['class' => 'danger']);
                 $this->redirect(['action' => 'database']);
             }
             $file = new File(CONFIG . 'database.php', true, 0644);
             $databaseConfig = $this->getDatabaseConfig($this->request->data['Installer']);
             if (!$file->exists()) {
                 $this->Session->setFlash(__d('hurad', 'Hurad can not create <b>"Config/database.php"</b>. <br> Please create <b>"Config/database.php"</b> and insert the following content in it.'), 'flash_message', ['class' => 'danger']);
                 $this->Session->write('contentFile', $databaseConfig);
                 $this->Session->write('databaseConfig', $this->request->data['Installer']);
                 $this->redirect(['action' => 'config']);
             } else {
                 if (!$file->writable() && !array_key_exists('content', $this->request->data['Installer'])) {
                     $this->Session->setFlash(__d('hurad', 'Hurad can not insert database config in <b>"Config/database.php"</b>. <br> Please insert the following content in <b>"Config/database.php"</b>.'), 'flash_message', ['class' => 'danger']);
                     $this->Session->write('contentFile', $databaseConfig);
                     $this->Session->write('databaseConfig', $this->request->data['Installer']);
                     $this->redirect(['action' => 'config']);
                 } else {
                     $file->write($databaseConfig);
                     try {
                         $dataSource = ConnectionManager::getDataSource('default');
                         if ($dataSource->connected) {
                             if ($this->__executeSQL('hurad.sql', $dataSource, ['$[prefix]' => $this->request->data['Installer']['prefix']])) {
                                 $this->Session->setFlash(__d('hurad', 'Database successfully installed'), 'flash_message', ['class' => 'success']);
                                 $this->redirect(['action' => 'finalize']);
                             }
                         }
                     } catch (Exception $exc) {
                         $this->Session->setFlash($exc->getMessage(), 'flash_message', ['class' => 'danger']);
                     }
                 }
             }
         }
     }
 }
Example #15
0
 /**
  * serve. The main entry point for this class
  *
  * Check the filename map, and get the files to be processed.
  * Write the file to the webroot so that this script is one-time-only
  *
  * This script is intended to be used either in development; with the files generated added
  * to the project repository.
  *
  * The following locations need to be writable to the php user:
  * 	config/mi_compressor.php
  * 	webroot/css
  * 	webroot/js
  *
  * @param string $request
  * @param mixed $type
  * @static
  * @return contents to be served up
  * @access public
  */
 public static function serve($request = '', $type = null)
 {
     self::$loadedFiles = array();
     self::log('Request String: ' . $request);
     $start = microtime(true);
     if ($type === null) {
         $type = array_pop(explode('.', $_GET['url']));
     }
     $requests = self::listFiles($request, $type);
     if (!$requests) {
         return false;
     }
     $fingerprint = self::_fingerprint($request);
     $_request = str_replace($fingerprint, '', $request);
     $_request = preg_replace('@\\.min$@', '', $_request);
     if (count($requests) > 1 && $request != $_request) {
         if ($_request[0] === '/') {
             $path = WWW_ROOT . $_request . '.' . $type;
         } else {
             $path = WWW_ROOT . $type . DS . $_request . '.' . $type;
         }
         if (file_exists($path)) {
             self::log("Uncompressed file exists ({$path})");
             self::log("\tbypassing process method and using this file as input");
             $oString = file_get_contents($path);
             $return = self::minify($oString, $path);
         }
     }
     if (empty($return)) {
         self::$requestStack = array();
         $return = self::process($requests, $type);
         if (!isset(self::$requestMap[$type][$_request]['all'])) {
             self::$requestMap[$type][$_request]['all'] = self::$requestStack;
             self::_populateRequestMap(true);
         }
     }
     if (self::cRead('store')) {
         if ($request[0] === '/') {
             $path = WWW_ROOT . ltrim($request, '/') . '.' . $type;
         } else {
             $path = WWW_ROOT . $type . DS . $request . '.' . $type;
         }
         if (count($requests) > 1 && strpos($path, '.min.')) {
             $test = str_replace('.min.', '.', $path);
             if (file_exists($test)) {
                 if (self::$__NumberHelper === null) {
                     App::import('Core', 'Helper');
                     App::import('Helper', 'App');
                     App::import('Helper', 'Number');
                     self::$__NumberHelper = new NumberHelper();
                 }
                 $oString = file_get_contents($test);
                 $oLength = strlen($oString);
                 $fLength = strlen($return);
                 $percent = round((1 - $fLength / $oLength) * 100);
                 $oSize = self::$__NumberHelper->toReadableSize($oLength);
                 $fSize = self::$__NumberHelper->toReadableSize($fLength);
                 self::log("Overall Reduction: {$percent}% ({$oSize} to {$fSize})");
             }
         }
         $File = new File($path, true);
         if (!$File->writable()) {
             self::log("PROBLEM: Couldn't open {$path} for writing");
         } else {
             $File->delete();
             $bytes = strlen($return);
             self::log("Writing {$path} {$bytes} bytes");
             $File->write($return);
         }
     }
     if (self::cRead('debug')) {
         $return = self::log() . $return;
     }
     return $return;
 }
 /**
  * Generates an YAML file from the current DB schema
  */
 function generate()
 {
     $this->out('Generating full schema YAML file schema.yml...');
     $this->out('');
     $this->hr();
     $this->out('');
     $oFile = new File(MIGRATIONS_PATH . DS . 'schema.yml', true);
     if (!$oFile->writable()) {
         $this->out('');
         $this->out('Your migrations folder is not writable - I could not write the file schema.yml . Please check your permissions.');
         $this->out('');
         exit;
     }
     $oFile->write($this->oMigrations->generate());
     $this->out('Schema file ( schema.yml ) successfully written!');
     $this->out('');
 }
 /**
  * Logs a message
  *
  * @return void
  */
 public function log($type = 'info', $message = '')
 {
     if (!empty($this->log)) {
         $output = date('Y-m-d H:i:s') . ' ' . ucfirst($type) . ': ' . $message . "\n";
         $log = new File(LOGS . $this->logfile . '.log', true);
         if ($log->writable()) {
             return $log->append($output);
         }
     }
 }
 /**
  * testWritable method
  *
  * @return void
  */
 public function testWritable()
 {
     $someFile = new File(TMP . 'some_file.txt', false);
     $this->assertTrue($someFile->open());
     $this->assertTrue($someFile->writable());
     $someFile->close();
     $someFile->delete();
 }
                <tbody>
                    <?php 
if (File::writable(ROOT . DS . '.htaccess')) {
    ?>
                        <tr>
                            <td><span class="badge badge-error" style="padding-left:5px; padding-right:5px;"><b>!</b></span> </td>
                            <td><?php 
    echo __('The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions. <br>You can do this on unix systems with: <code>chmod a-w :path</code>', 'information', array(':path' => ROOT . DS . '.htaccess'));
    ?>
</td>
                        </tr>
                    <?php 
}
?>
                    <?php 
if (File::writable(ROOT . DS . 'index.php')) {
    ?>
                        <tr>
                            <td><span class="badge badge-error" style="padding-left:5px; padding-right:5px;"><b>!</b></span> </td>
                            <td><?php 
    echo __('The Monstra index.php file has been found to be writable. We would advise you to remove all write permissions. <br>You can do this on unix systems with: <code>chmod a-w :path</code>', 'information', array(':path' => ROOT . DS . 'index.php'));
    ?>
</td>
                        </tr>
                    <?php 
}
?>
                    <?php 
if (Monstra::$environment == Monstra::DEVELOPMENT) {
    ?>
                        <tr>