append() public static method

Append to a file.
public static append ( string $path, string $data ) : integer
$path string
$data string
return integer
Example #1
0
function w_serverlog($server, $log)
{
    $logfile = TMP . "server/" . $server . ".log";
    $file = new File($logfile);
    if ($file->exists()) {
        $file->append('
[' . date('Y-m-d H:i:s') . '] ' . $log);
    } else {
        $file->create();
        $file->append('[' . date('Y-m-d H:i:s') . '] ' . $log);
    }
}
 /**
  * 
  * @param type $contents
  */
 public final function write()
 {
     $logFile = $this;
     $path = $logFile->getPath();
     $logHeader = $logFile->getLogHeader();
     $logContents = $logFile->logContents;
     $file = new File($path, true, 0777);
     $file->lock = true;
     $file->append($logHeader);
     $file->append("\n");
     $file->append($logContents);
     $file->append("\n\n");
     $file->close();
 }
Example #3
0
 /**
  * Write a message to the log file.
  *
  * <code>
  *		// Write an "error" message to the log file
  *		Log::write('error', 'Something went horribly wrong!');
  *
  *		// Write an "error" message using the class' magic method
  *		Log::error('Something went horribly wrong!');
  *
  *		// Log an arrays data
  *		Log::write('info', array('name' => 'Sawny', 'passwd' => '1234', array(1337, 21, 0)), true);
  *      //Result: Array ( [name] => Sawny [passwd] => 1234 [0] => Array ( [0] => 1337 [1] => 21 [2] => 0 ) )
  *      //If we had omit the third parameter the result had been: Array
  * </code>
  *
  * @param  string  $type
  * @param  string  $message
  * @return void
  */
 public static function write($type, $message, $pretty_print = false)
 {
     $message = $pretty_print ? print_r($message, true) : $message;
     // If there is a listener for the log event, we'll delegate the logging
     // to the event and not write to the log files. This allows for quick
     // swapping of log implementations for debugging.
     if (Event::listeners('laravel.log')) {
         Event::fire('laravel.log', array($type, $message));
     }
     $trace = debug_backtrace();
     foreach ($trace as $item) {
         if (isset($item['class']) and $item['class'] == __CLASS__) {
             continue;
         }
         $caller = $item;
         break;
     }
     $function = $caller['function'];
     if (isset($caller['class'])) {
         $class = $caller['class'] . '::';
     } else {
         $class = '';
     }
     $message = static::format($type, $class . $function . ' - ' . $message);
     File::append(path('storage') . 'logs/' . date('Y-m-d') . '.log', $message);
 }
Example #4
0
 /**
  * Report all logger data with appropriate output
  *
  * @param   string Log file
  * @param   bool   Whether to write it or to return as array
  * @return  mixed
  */
 public static function report($logPath = '', $as_array = FALSE)
 {
     $logs = array();
     $profiler = self::$profiler;
     $log = self::$log;
     foreach ($log as $header => $content) {
         // Initial empty message
         $message = '';
         // @codeCoverageIgnoreStart
         if ($content->isEmpty()) {
             // Do nothing
         } else {
             // @codeCoverageIgnoreEnd
             // Iterate over all content and place as lines
             foreach ($content as $line) {
                 $timestamp = key($line);
                 $message .= $timestamp . '-' . $line[$timestamp] . '(' . $header . ')' . "\n";
             }
             $logs[] = $message;
         }
     }
     // Just log if there are something to report
     if (!empty($logs)) {
         $appPath = defined('PATH_APP') ? PATH_APP : '/tmp';
         $path = empty($logPath) ? $appPath . DIRECTORY_SEPARATOR . 'log_' . date('Y-m-d') . '.txt' : $logPath;
         if ($as_array) {
             return $logs;
         } else {
             $report = implode("\n", $logs);
             File::append($path, $report);
         }
     }
 }
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     // Get the Name and Value of the environment variable.
     $name = $this->argument('name');
     $value = $this->argument('value');
     // If the name of the environment variable has not been included, ask the user for it.
     if (empty($name)) {
         $name = $this->ask('What is the name of the environment variable?');
     }
     // If the value of the environment variable has not been included, ask the user for it.
     if (empty($value)) {
         $value = $this->ask('What is the value of the environment variable?');
     }
     // Append the new environment variable to the file.
     try {
         \File::get('.env');
         // Encrypt the value.
         $encrypted_value = Crypt::encrypt($value);
         // Append the value to the .env file.
         \File::append('.env', "\n{$name} = {$encrypted_value} ");
         // Display success message using the decrypted value of the encrypted value.
         $this->info('The environment variable named ' . $name . ' has been added with the value of ' . Crypt::decrypt($encrypted_value) . '. Please check that the value displayed is the supplied value.');
     } catch (\Illuminate\Contracts\Filesystem\FileNotFoundException $e) {
         $this->error('Unable to load the .env file.');
     }
 }
Example #6
0
 public function write($str, $type = null)
 {
     $type = is_null($type) ? 'INFO' : $type;
     $type = Inflector::upper($type);
     $data = date('Y-m-d H:i:s') . ":{$type}:{$str}";
     File::append($this->file, $data . "\n");
 }
Example #7
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
  */
 function write($type, $msg)
 {
     $filename = LOGS . $type . '.log';
     $output = date('Y-m-d H:i:s') . ' ' . ucfirst($type) . ': ' . $msg . "\n";
     $log = new File($filename);
     return $log->append($output);
 }
 /**
  * Register any other events for your application.
  *
  * @param  \Illuminate\Contracts\Events\Dispatcher  $events
  * @return void
  */
 public function boot(DispatcherContract $events)
 {
     parent::boot($events);
     $events->listen('eloquent.saving: *', function ($model) {
         \File::append('audit', "Table {$model->getTable()} has been saved." . PHP_EOL);
     });
 }
    /**
     * @inheritdoc
     */
    public function handle()
    {
        foreach ($this->dumper_config as $class => $file) {
            if (\File::exists($file)) {
                if (!$this->confirm("file {$file} exists, are you sure to OVERWRITE it? [y|N]")) {
                    continue;
                }
                \File::delete($file);
            }
            $instance = new $class();
            $config = FormDumper::dump($instance);
            $php = var_export($config, true);
            $now = date('Y-m-d H:i:s', time());
            $data = <<<DATA
<?php
/**
 * Created by FormDumper
 * Date: {$now}
 */

 return {$php};
DATA;
            \File::append($file, $data);
        }
    }
Example #10
0
 public static function compileDir($dir, $destFile)
 {
     $dh = opendir($dir);
     if (!$dh) {
         throw new Exception('Unknown dir: ' . $dir);
     }
     while ($file = readdir($dh)) {
         if ($file[0] == '.') {
             continue;
         }
         $absfile = Dir::normalize($dir) . $file;
         if (is_file($absfile) && File::getExtension($file) == 'js') {
             File::append($destFile, "//FILE: {$file}" . chr(10));
             if (filesize($absfile) > 200000) {
                 File::append($destFile, file_get_contents($absfile));
             } else {
                 File::append($destFile, self::minify($absfile));
             }
             File::append($destFile, chr(10) . chr(10));
         } else {
             if (is_dir($absfile)) {
                 self::compileDir($absfile, $destFile);
             }
         }
     }
     closedir($dh);
 }
Example #11
0
 public function addAdminRouteGroup()
 {
     $content = \File::get(__DIR__ . '/../../templates/routes/adminRoutes.txt');
     $route_file = \File::get(app_path() . '/routes.php');
     if (!strpos($route_file, "'prefix' => 'admin'")) {
         \File::append(app_path() . '/routes.php', $content);
     }
 }
 public function testWrite()
 {
     $file = new File('/tmp/test');
     $this->assertEquals(true, $file->append("test\n"));
     $this->assertEquals(true, $file->append("test\n"));
     $this->assertEquals(true, $file->copy('/tmp/test2'));
     $this->assertEquals(true, $file->delete());
     $file = new File('/tmp/test2');
     $linecount = 0;
     foreach ($file->lines() as $line) {
         $linecount = $linecount + 1;
     }
     $array = $file->toArray();
     $this->assertEquals(2, count($array));
     $this->assertEquals(2, $linecount);
     $this->assertEquals(true, $file->delete());
     $this->assertEquals(false, $file->isFile());
 }
 public function onFinish()
 {
     if ($this->_queriesCount < $this->_limit) {
         return;
     }
     $filename = storage_path('/logs/query.' . date('d.m.y') . '.request.log');
     $string = '[' . date('H:i:s') . '] ' . \Request::fullUrl() . ': ' . $this->_queriesCount . ' queries in ' . $this->_totalTime . 'ms.' . PHP_EOL;
     \File::append($filename, $string);
 }
 /**
  * Cria o snapshot na pasta que esta configurada
  *
  * @return boolean
  */
 public function generate()
 {
     $this->Menu = ClassRegistry::init("Cms.Menu");
     $aDados = $this->Menu->find('all');
     if (!$this->isUpToDate($aDados)) {
         App::import("Helper", "Xml");
         App::import("File");
         $oXml = new XmlHelper();
         $oXml->header();
         $oXml->serialize($aDados);
         $oFile = new File(Configure::read('Cms.CheckPoint.menus') . time() . ".xml", true, 0777);
         $oFile->append($oXml->header());
         $oFile->append("<menus>");
         $oFile->append($oXml->serialize($aDados));
         $oFile->append("</menus>");
         return true;
     }
     return false;
 }
Example #15
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;
 }
Example #16
0
 /**
  * Write a message to the log file.
  *
  * <code>
  *		// Write an "error" message to the log file
  *		Log::write('error', 'Something went horribly wrong!');
  *
  *		// Write an "error" message using the class' magic method
  *		Log::error('Something went horribly wrong!');
  * </code>
  *
  * @param  string  $type
  * @param  string  $message
  * @return void
  */
 public static function write($type, $message)
 {
     // If there is a listener for the log event, we'll delegate the logging
     // to the event and not write to the log files. This allows for quick
     // swapping of log implementations for debugging.
     if (Event::listeners('laravel.log')) {
         Event::fire('laravel.log', array($type, $message));
     }
     $message = static::format($type, $message);
     File::append(path('storage') . 'logs/' . date('Y-m-d') . '.log', $message);
 }
Example #17
0
File: Log.php Project: schpill/thin
 /**
  * Write a message to the log file.
  *
  * <code>
  *      // Write an "error" message to the log file
  *      Log::write('error', 'Something went horribly wrong!');
  *
  *      // Write an "error" message using the class' magic method
  *      Log::error('Something went horribly wrong!');
  *
  *      // Log an arrays data
  *      Log::write('info', array('name' => 'Sawny', 'passwd' => '1234', array(1337, 21, 0)), true);
  *      //Result: Array ( [name] => Sawny [passwd] => 1234 [0] => Array ( [0] => 1337 [1] => 21 [2] => 0 ) )
  *      //If we had omit the third parameter the result had been: Array
  * </code>
  *
  * @param  string  $type
  * @param  string  $message
  * @return void
  */
 public static function write($type, $message, $prettyPrint = false)
 {
     if (!isset(static::$_logFile)) {
         static::$_logFile = LOGS_PATH . DS . date('Y-m-d') . '.log';
     }
     if (!File::exists(static::$_logFile)) {
         File::create(static::$_logFile);
     }
     $message = false !== $prettyPrint ? print_r($message, true) : $message;
     $message = static::format($type, $message);
     File::append(static::$_logFile, $message);
 }
 /**
  * Bootstrap any application services.
  *
  * @return void
  */
 public function boot()
 {
     $path = storage_path() . '/logs/query.log';
     \Event::listen('illuminate.query', function ($sql, $bindings, $time) use($path) {
         // Uncomment this if you want to include bindings to queries
         $sql = str_replace(array('%', '?'), array('%%', '%s'), $sql);
         $sql = vsprintf($sql, $bindings);
         $time_now = (new \DateTime())->format('Y-m-d H:i:s');
         $log = $time_now . ' | ' . $sql . ' | ' . $time . 'ms' . PHP_EOL;
         \File::append($path, $log);
     });
 }
Example #19
0
 /**
  * Writes a line in the log file
  *
  * @param string $line
  */
 public function write($line)
 {
     File::append($this->filepath, date($this->date_format) . ' - ' . $line . "\n");
     // If the max size is exceeded
     if (File::getSize($this->filepath) >= $this->max_size) {
         File::delete($this->filepath . '.' . $this->nb_old_logs);
         for ($i = $this->nb_old_logs; $i >= 1; $i--) {
             if (File::exists($this->filepath . ($i == 1 ? '' : '.' . ($i - 1)))) {
                 File::rename($this->filepath . ($i == 1 ? '' : '.' . ($i - 1)), $this->filepath . '.' . $i);
             }
         }
     }
 }
 public static function setUpBeforeClass()
 {
     self::$testDir = dirname(dirname(__DIR__)) . DS . 'tmp';
     self::cleanTempDir();
     $shellClassFile = new File(self::$testDir . DS . 'Console' . DS . 'Command' . DS . 'JobClassOneShell.php', true, 0755);
     $shellClassFile->append('<?php class JobClassOneShell { public function funcOne() {} public function funcTwo() {} public function perform() {} }');
     $pluginShellClassFile = new File(self::$testDir . DS . 'Plugin' . DS . 'MyPlugin' . DS . 'Console' . DS . 'Command' . DS . 'PluginJobClassOneShell.php', true, 0755);
     $pluginShellClassFile->append('<?php class PluginJobClassOneShell { public function funcOne() {} public function funcTwo() {} public function perform() {} }');
     $invalidShellClassFile = new File(self::$testDir . DS . 'Console' . DS . 'Command' . DS . 'InvalidJobClassShell.php', true, 0755);
     $invalidShellClassFile->append('<?php class NotTheSameClassShell { public function funcOne() {} public function funcTwo() {} public function perform() {} }');
     $shellClassFile = new File(self::$testDir . DS . 'Console' . DS . 'Command' . DS . 'NotAJobShellClass.php', true, 0755);
     $shellClassFile->append('<?php class NotAJobShellClass { public function funcOne() {} }');
     Resque_Job_Creator::$rootFolder = self::$testDir . DS;
     parent::setUpBeforeClass();
 }
 public function generateText()
 {
     $this->FormalWord->recursive = -1;
     $data = $this->FormalWord->find('all', array('fields' => array('text')));
     App::uses('Folder', 'Utility');
     App::uses('File', 'Utility');
     $dir = new Folder(WWW_ROOT . 'files', true, 0755);
     $file = new File(WWW_ROOT . 'files/dic.txt', true, 0644);
     foreach ($data as $d) {
         if ($file->exists()) {
             $file->append($d['FormalWord']['text'] . ' ');
         }
     }
     echo "done";
     exit;
 }
Example #22
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);
     }
 }
 public function startQueueMessage($devices, $data)
 {
     $deviceCollection = $this->generateDeviceCollection($devices);
     $devices = PushNotification::DeviceCollection($deviceCollection);
     $message = PushNotification::Message($data['message'], array('badge' => 1));
     Queue::push(function ($job) use($devices, $data) {
         //PushNotification::app('appNameIOS')
         //  ->to($devices)
         //  ->send($message);
         $message = '';
         foreach ($devices as $device) {
             $message .= 'sending message(' . $data['message'] . ') to ' . $device->token . ' : ';
         }
         File::append(app_path() . '/queue.txt', $message . PHP_EOL);
         $job->delete();
     });
 }
Example #24
0
 /**
  * Execute the console command.
  *
  * @return mixed
  */
 public function fire()
 {
     $this->deleteFiles(['thumbnail', 'gallery', 'origin', 'avatar_origin', 'avatar_large', 'avatar_middle', 'avatar_small']);
     $s3 = AWS::get('s3');
     $prefix = 'https://yolanothertest.s3-us-west-2.amazonaws.com/';
     $objects = $s3->getIterator('listObjects', ['Bucket' => 'yolanothertest']);
     foreach ($objects as $object) {
         $imageUrl = $prefix . $object['Key'];
         if ($thumbnail = Image::where('thumbnail', $prefix . $object['Key'])->whereNotNull('imageable_id')->first()) {
             if ($thumbnail) {
                 File::append(storage_path('thumbnail.csv'), "{$thumbnail->id}, {$object['Key']}, {$thumbnail->imageable_type}, {$thumbnail->imageable_id}, {$object['Size']}, " . $this->getImageSize($imageUrl) . PHP_EOL);
                 $this->line("{$thumbnail->id} thumbnail {$object['Key']} {$thumbnail->imageable_type} {$thumbnail->imageable_id} {$object['Size']}");
             }
         } elseif ($large = Image::where('regular', $prefix . $object['Key'])->whereNotNull('imageable_id')->first()) {
             if ($large) {
                 File::append(storage_path('gallery.csv'), "{$large->id},  {$object['Key']}, {$large->imageable_type}, {$large->imageable_id}, {$object['Size']}, " . $this->getImageSize($imageUrl) . PHP_EOL);
                 $this->line("{$large->id} gallery {$object['Key']} {$large->imageable_type} {$large->imageable_id} {$object['Size']}");
             }
         } elseif ($origin = Image::where('origin', $prefix . $object['Key'])->whereNotNull('imageable_id')->first()) {
             if ($origin) {
                 File::append(storage_path('origin.csv'), "{$origin->id}, {$object['Key']}, {$origin->imageable_type}, {$origin->imageable_id}, {$object['Size']}, " . $this->getImageSize($imageUrl) . PHP_EOL);
             }
         } elseif ($avatarOrigin = User::where('img_origin', $prefix . $object['Key'])->first()) {
             if ($avatarOrigin) {
                 File::append(storage_path('avatar_origin.csv'), "{$avatarOrigin->id}, {$object['Key']}, {$object['Size']}, " . $this->getImageSize($imageUrl) . PHP_EOL);
             }
         } elseif ($avatarLarge = User::where('img_large', $prefix . $object['Key'])->first()) {
             if ($avatarLarge) {
                 File::append(storage_path('avatar_large.csv'), "{$avatarLarge->id}, {$object['Key']}, {$object['Size']}, " . $this->getImageSize($imageUrl) . PHP_EOL);
             }
         } elseif ($avatarMiddle = User::where('img_middle', $prefix . $object['Key'])->first()) {
             if ($avatarMiddle) {
                 File::append(storage_path('avatar_middle.csv'), "{$avatarMiddle->id}, {$object['Key']}, {$object['Size']}, " . $this->getImageSize($imageUrl) . PHP_EOL);
             }
         } elseif ($avatarSmall = User::where('img_small', $prefix . $object['Key'])->first()) {
             if ($avatarSmall) {
                 File::append(storage_path('avatar_small.csv'), "{$avatarSmall->id}, {$object['Key']}, {$object['Size']}, " . $this->getImageSize($imageUrl) . PHP_EOL);
             }
         }
     }
 }
Example #25
0
 /**
  * Write a message to the log file.
  *
  * <code>
  *		// Write an "error" message to the log file
  *		Log::write('error', 'Something went horribly wrong!');
  *
  *		// Log an arrays data
  *		Log::write('info', array('name' => 'Sawny', 'passwd' => '1234', array(1337, 21, 0)));
  *      //Result: Array ( [name] => Sawny [passwd] => 1234 [0] => Array ( [0] => 1337 [1] => 21 [2] => 0 ) )
  * </code>
  *
  * @param  string  $type
  * @param  string  $message
  * @return void
  */
 public static function write($type, $message)
 {
     if (is_array($message) || is_object($message)) {
         $message = print_r($message, true);
     }
     $trace = debug_backtrace();
     foreach ($trace as $item) {
         if (isset($item["class"]) and $item["class"] == __CLASS__) {
             continue;
         }
         $caller = $item;
         break;
     }
     $function = $caller["function"];
     if (isset($caller["class"])) {
         $class = $caller["class"] . "::";
     } else {
         $class = "";
     }
     File::mkdir(J_APPPATH . "storage" . DS . "logs" . DS);
     File::append(J_APPPATH . "storage" . DS . "logs" . DS . date("Y-m-d") . ".log", date("Y-m-d H:i:s") . " " . Str::upper($type) . " - " . $class . $function . " - " . $message . CRLF);
 }
Example #26
0
 function edit($id = null)
 {
     $this->loadModel('User');
     $this->set('Userlist', $this->User->find('all'));
     $this->Pagem->id = $id;
     $page = $this->Pagem->read(null, $id);
     $file = new File("'../../../../../Pages/" . $page['Pagem']['name'] . ".php", false, 0777);
     $this->set('mybody', $file->read());
     if (empty($this->data)) {
         $this->data = $this->Pagem->read();
     } else {
         if ($this->Pagem->save($this->data)) {
             $file = new File("'../../../../../Pages/" . $this->request->data['Pagem']['name'] . ".php", false, 0777);
             $file->delete();
             $file = new File("'../../../../../Pages/" . $this->request->data['Pagem']['name'] . ".php", true, 0777);
             $file->append($this->request->data['Pagem']['body']);
             $file->close();
             $this->Session->setFlash('Your Page has been updated.');
             $this->redirect(array('action' => 'index'));
         }
     }
 }
 /**
  * @param $userId
  * @param $fileUniName
  * @param $oriFileName
  * @param $tmpFileUrl
  * @param $chunk
  * @param $chunks
  * @param string $uploadTo
  * @return AmaotoFile|\Illuminate\Database\Eloquent\Model|mixed|null|static
  * @throws NeedMoreDataException
  */
 public static function uploadFile($userId, $fileUniName, $oriFileName, $tmpFileUrl, $chunk, $chunks, $uploadTo = 'upload')
 {
     $fileMergePath = self::getUploadToPath($uploadTo) . '/' . $fileUniName . '.merge';
     if ($chunk === 0) {
         File::put($fileMergePath, File::get($tmpFileUrl));
     } else {
         File::append($fileMergePath, File::get($tmpFileUrl));
     }
     if (!$chunks || $chunk == $chunks - 1) {
         //文件已上传完整
         //计算哈希值
         $fileMd5 = md5_file($fileMergePath);
         $fileFinalUrl = self::getUploadToPath($uploadTo) . '/' . $fileMd5 . '.' . File::extension($oriFileName);
         //判断文件是否存在
         if (file_exists($fileFinalUrl)) {
             File::delete($fileMergePath);
         } else {
             File::move($fileMergePath, $fileFinalUrl);
         }
         if (AmaotoFile::whereMd5($fileMd5)->count() == 0) {
             $thatFile = new AmaotoFile();
             $thatFile->md5 = $fileMd5;
             $thatFile->name = $oriFileName;
             $thatFile->size = File::size($fileFinalUrl);
             $thatFile->url = str_replace(public_path(), '', $fileFinalUrl);
             $thatFile->user_id = $userId;
             $thatFile->updateTypeByGetId3();
             $thatFile->save();
             return $thatFile;
         } else {
             $thatFile = AmaotoFile::whereMd5($fileMd5)->first();
             return $thatFile;
         }
     }
     throw new NeedMoreDataException('文件未接收完整,请求继续发送数据');
 }
 /**
  * testAppend method
  *
  * @return void
  */
 public function testAppend()
 {
     if (!($tmpFile = $this->_getTmpFile())) {
         return false;
     }
     if (file_exists($tmpFile)) {
         unlink($tmpFile);
     }
     $TmpFile = new File($tmpFile);
     $this->assertFalse(file_exists($tmpFile));
     $fragments = array('CakePHP\'s', ' test suite', ' was here ...');
     $data = null;
     $size = 0;
     foreach ($fragments as $fragment) {
         $r = $TmpFile->append($fragment);
         $this->assertTrue($r);
         $this->assertTrue(file_exists($tmpFile));
         $data = $data . $fragment;
         $this->assertEquals($data, file_get_contents($tmpFile));
         $newSize = $TmpFile->size();
         $this->assertTrue($newSize > $size);
         $size = $newSize;
         $TmpFile->close();
     }
     $TmpFile->append('');
     $this->assertEquals($data, file_get_contents($tmpFile));
     $TmpFile->close();
 }
Example #29
0
 /**
  * Synchronize the file system with the database
  *
  * @return string The path to the synchronization log file
  *
  * @throws \Exception If a parent ID entry is missing
  */
 public static function syncFiles()
 {
     // Try to raise the limits (see #7035)
     @ini_set('memory_limit', -1);
     @ini_set('max_execution_time', 0);
     $objDatabase = \Database::getInstance();
     // Lock the files table
     $objDatabase->lockTables(array('tl_files'));
     // Reset the "found" flag
     $objDatabase->query("UPDATE tl_files SET found=''");
     // Get a filtered list of all files
     $objFiles = new \RecursiveIteratorIterator(new \Dbafs\Filter(new \RecursiveDirectoryIterator(TL_ROOT . '/' . \Config::get('uploadPath'), \FilesystemIterator::UNIX_PATHS | \FilesystemIterator::FOLLOW_SYMLINKS | \FilesystemIterator::SKIP_DOTS)), \RecursiveIteratorIterator::SELF_FIRST);
     $strLog = 'system/tmp/' . md5(uniqid(mt_rand(), true));
     // Open the log file
     $objLog = new \File($strLog, true);
     $objLog->truncate();
     $arrModels = array();
     // Create or update the database entries
     foreach ($objFiles as $objFile) {
         $strRelpath = str_replace(TL_ROOT . '/', '', $objFile->getPathname());
         // Get all subfiles in a single query
         if ($objFile->isDir()) {
             $objSubfiles = \FilesModel::findMultipleFilesByFolder($strRelpath);
             if ($objSubfiles !== null) {
                 while ($objSubfiles->next()) {
                     $arrModels[$objSubfiles->path] = $objSubfiles->current();
                 }
             }
         }
         // Get the model
         if (isset($arrModels[$strRelpath])) {
             $objModel = $arrModels[$strRelpath];
         } else {
             $objModel = \FilesModel::findByPath($strRelpath);
         }
         if ($objModel === null) {
             // Add a log entry
             $objLog->append("[Added] {$strRelpath}");
             // Get the parent folder
             $strParent = dirname($strRelpath);
             // Get the parent ID
             if ($strParent == \Config::get('uploadPath')) {
                 $strPid = null;
             } else {
                 $objParent = \FilesModel::findByPath($strParent);
                 if ($objParent === null) {
                     throw new \Exception("No parent entry for {$strParent}");
                 }
                 $strPid = $objParent->uuid;
             }
             // Create the file or folder
             if (is_file(TL_ROOT . '/' . $strRelpath)) {
                 $objFile = new \File($strRelpath, true);
                 $objModel = new \FilesModel();
                 $objModel->pid = $strPid;
                 $objModel->tstamp = time();
                 $objModel->name = $objFile->name;
                 $objModel->type = 'file';
                 $objModel->path = $objFile->path;
                 $objModel->extension = $objFile->extension;
                 $objModel->found = 2;
                 $objModel->hash = $objFile->hash;
                 $objModel->uuid = $objDatabase->getUuid();
                 $objModel->save();
             } else {
                 $objFolder = new \Folder($strRelpath);
                 $objModel = new \FilesModel();
                 $objModel->pid = $strPid;
                 $objModel->tstamp = time();
                 $objModel->name = $objFolder->name;
                 $objModel->type = 'folder';
                 $objModel->path = $objFolder->path;
                 $objModel->extension = '';
                 $objModel->found = 2;
                 $objModel->hash = $objFolder->hash;
                 $objModel->uuid = $objDatabase->getUuid();
                 $objModel->save();
             }
         } else {
             // Check whether the MD5 hash has changed
             $objResource = $objFile->isDir() ? new \Folder($strRelpath) : new \File($strRelpath);
             $strType = $objModel->hash != $objResource->hash ? 'Changed' : 'Unchanged';
             // Add a log entry
             $objLog->append("[{$strType}] {$strRelpath}");
             // Update the record
             $objModel->found = 1;
             $objModel->hash = $objResource->hash;
             $objModel->save();
         }
     }
     // Check for left-over entries in the DB
     $objFiles = \FilesModel::findByFound('');
     if ($objFiles !== null) {
         $arrMapped = array();
         $arrPidUpdate = array();
         while ($objFiles->next()) {
             $objFound = \FilesModel::findBy(array('hash=?', 'found=2'), $objFiles->hash);
             if ($objFound !== null) {
                 // Check for matching file names if the result is ambiguous (see #5644)
                 if ($objFound->count() > 1) {
                     while ($objFound->next()) {
                         if ($objFound->name == $objFiles->name) {
                             $objFound = $objFound->current();
                             break;
                         }
                     }
                 }
                 // If another file has been mapped already, delete the entry (see #6008)
                 if (in_array($objFound->path, $arrMapped)) {
                     $objLog->append("[Deleted] {$objFiles->path}");
                     $objFiles->delete();
                     continue;
                 }
                 $arrMapped[] = $objFound->path;
                 // Store the PID change
                 if ($objFiles->type == 'folder') {
                     $arrPidUpdate[$objFound->uuid] = $objFiles->uuid;
                 }
                 // Add a log entry BEFORE changing the object
                 $objLog->append("[Moved] {$objFiles->path} to {$objFound->path}");
                 // Update the original entry
                 $objFiles->pid = $objFound->pid;
                 $objFiles->tstamp = $objFound->tstamp;
                 $objFiles->name = $objFound->name;
                 $objFiles->type = $objFound->type;
                 $objFiles->path = $objFound->path;
                 $objFiles->found = 1;
                 // Delete the newer (duplicate) entry
                 $objFound->delete();
                 // Then save the modified original entry (prevents duplicate key errors)
                 $objFiles->save();
             } else {
                 // Add a log entry BEFORE changing the object
                 $objLog->append("[Deleted] {$objFiles->path}");
                 // Delete the entry if the resource has gone
                 $objFiles->delete();
             }
         }
         // Update the PID of the child records
         if (!empty($arrPidUpdate)) {
             foreach ($arrPidUpdate as $from => $to) {
                 $objChildren = \FilesModel::findByPid($from);
                 if ($objChildren !== null) {
                     while ($objChildren->next()) {
                         $objChildren->pid = $to;
                         $objChildren->save();
                     }
                 }
             }
         }
     }
     // Close the log file
     $objLog->close();
     // Reset the found flag
     $objDatabase->query("UPDATE tl_files SET found=1 WHERE found=2");
     // Unlock the tables
     $objDatabase->unlockTables();
     // Return the path to the log file
     return $strLog;
 }
Example #30
0
 /**
  * Generate the combined file and return the path
  * @param string
  * @return string
  */
 public function getCombinedFile($strUrl = TL_SCRIPT_URL)
 {
     $strKey = substr(md5($this->strKey), 0, 12);
     // Load the existing file
     if (file_exists(TL_ROOT . '/system/scripts/' . $strKey . $this->strMode)) {
         return $strUrl . 'system/scripts/' . $strKey . $this->strMode;
     }
     // Create the file
     $objFile = new File('system/scripts/' . $strKey . $this->strMode);
     $objFile->truncate();
     foreach ($this->arrFiles as $arrFile) {
         $content = file_get_contents(TL_ROOT . '/' . $arrFile['name']);
         // HOOK: modify the file content
         if (isset($GLOBALS['TL_HOOKS']['getCombinedFile']) && is_array($GLOBALS['TL_HOOKS']['getCombinedFile'])) {
             foreach ($GLOBALS['TL_HOOKS']['getCombinedFile'] as $callback) {
                 $this->import($callback[0]);
                 $content = $this->{$callback}[0]->{$callback}[1]($content, $strKey, $this->strMode);
             }
         }
         // Handle style sheets
         if ($this->strMode == self::CSS) {
             // Adjust the file paths
             $strDirname = dirname($arrFile['name']);
             // Remove relative paths
             while (strpos($content, 'url("../') !== false) {
                 $strDirname = dirname($strDirname);
                 $content = str_replace('url("../', 'url("', $content);
             }
             $strGlue = $strDirname != '.' ? $strDirname . '/' : '';
             $content = preg_replace('/url\\("(?!(data:|https?:\\/\\/|\\/))/', 'url("../../' . $strGlue, $content);
             $content = '@media ' . ($arrFile['media'] != '' ? $arrFile['media'] : 'all') . "{\n" . $content . "\n}";
         }
         $objFile->append($content);
     }
     unset($content);
     $objFile->close();
     // Create a gzipped version
     if ($GLOBALS['TL_CONFIG']['gzipScripts'] && function_exists('gzencode')) {
         $objFile = new File('system/scripts/' . $strKey . $this->strMode . '.gz');
         $objFile->write(gzencode(file_get_contents(TL_ROOT . '/system/scripts/' . $strKey . $this->strMode), 9));
         $objFile->close();
     }
     return $strUrl . 'system/scripts/' . $strKey . $this->strMode;
 }