protected function generate()
 {
     if (!is_dir(TL_ROOT . '/' . $this->cacheDirectory)) {
         $this->makeCacheDirectory();
     }
     $file = new \File($this->cacheFile);
     $file->truncate();
     $file->putContent($file->path, json_encode($this->cacheUrl));
     $automator = new \Automator();
     $automator->purgePageCache();
 }
	/**
	 * Log file will be cleared.
	 *
	 * After using this method the file still exists, but the file is empty.
	 * The content of the log file will be returned as an array.
	 * Each element of the array corresponds to a line in the file.
	 *
	 * If an error occurs null will be returned.
	 *
	 * @return array Content of log file
	 */
	public function clearFile() {
		$array = $this->file->read(FILE_LINES_TRIM);
		if ($array == null) {
			$array = array();
		}
		if ($this->file->truncate() == false) {
			return null;
		}
		else {
			return $array;
		}
	}
Example #3
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 #4
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;
 }
Example #5
0
<?php

require 'file.php';
File::truncate('sample.txt');
Example #6
0
 /**
  * Generate the Google XML sitemaps
  *
  * @param integer $intId The root page ID
  */
 public function generateSitemap($intId = 0)
 {
     $time = \Date::floorToMinute();
     $objDatabase = \Database::getInstance();
     $this->purgeXmlFiles();
     // Only root pages should have sitemap names
     $objDatabase->execute("UPDATE tl_page SET createSitemap='', sitemapName='' WHERE type!='root'");
     // Get a particular root page
     if ($intId > 0) {
         do {
             $objRoot = $objDatabase->prepare("SELECT * FROM tl_page WHERE id=?")->limit(1)->execute($intId);
             if ($objRoot->numRows < 1) {
                 break;
             }
             $intId = $objRoot->pid;
         } while ($objRoot->type != 'root' && $intId > 0);
         // Make sure the page is published
         if (!$objRoot->published || $objRoot->start != '' && $objRoot->start > $time || $objRoot->stop != '' && $objRoot->stop <= $time + 60) {
             return;
         }
         // Check the sitemap name
         if (!$objRoot->createSitemap || !$objRoot->sitemapName) {
             return;
         }
         $objRoot->reset();
     } else {
         $objRoot = $objDatabase->execute("SELECT id, language, sitemapName FROM tl_page WHERE type='root' AND createSitemap='1' AND sitemapName!='' AND (start='' OR start<='{$time}') AND (stop='' OR stop>'" . ($time + 60) . "') AND published='1'");
     }
     // Return if there are no pages
     if ($objRoot->numRows < 1) {
         return;
     }
     // Create the XML file
     while ($objRoot->next()) {
         $objFile = new \File('share/' . $objRoot->sitemapName . '.xml', true);
         $objFile->truncate();
         $objFile->append('<?xml version="1.0" encoding="UTF-8"?>');
         $objFile->append('<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">');
         // Find the searchable pages
         $arrPages = \Backend::findSearchablePages($objRoot->id, '', true);
         // HOOK: take additional pages
         if (isset($GLOBALS['TL_HOOKS']['getSearchablePages']) && is_array($GLOBALS['TL_HOOKS']['getSearchablePages'])) {
             foreach ($GLOBALS['TL_HOOKS']['getSearchablePages'] as $callback) {
                 $this->import($callback[0]);
                 $arrPages = $this->{$callback[0]}->{$callback[1]}($arrPages, $objRoot->id, true, $objRoot->language);
             }
         }
         // Add pages
         foreach ($arrPages as $strUrl) {
             $strUrl = rawurlencode($strUrl);
             $strUrl = str_replace(array('%2F', '%3F', '%3D', '%26', '%3A//'), array('/', '?', '=', '&', '://'), $strUrl);
             $strUrl = ampersand($strUrl, true);
             $objFile->append('  <url><loc>' . $strUrl . '</loc></url>');
         }
         $objFile->append('</urlset>');
         $objFile->close();
         // Add a log entry
         $this->log('Generated sitemap "' . $objRoot->sitemapName . '.xml"', __METHOD__, TL_CRON);
     }
 }
Example #7
0
 /**
  * Generate the combined file and return its path
  *
  * @param string $strUrl An optional URL to prepend
  *
  * @return string The path to the combined file
  */
 public function getCombinedFile($strUrl = null)
 {
     if ($strUrl === null) {
         $strUrl = TL_ASSETS_URL;
     }
     $strTarget = substr($this->strMode, 1);
     $strKey = substr(md5($this->strKey), 0, 12);
     // Do not combine the files in debug mode (see #6450)
     if (\Config::get('debugMode')) {
         $return = array();
         foreach ($this->arrFiles as $arrFile) {
             $content = file_get_contents(TL_ROOT . '/' . $arrFile['name']);
             // Compile SCSS/LESS files into temporary files
             if ($arrFile['extension'] == self::SCSS || $arrFile['extension'] == self::LESS) {
                 $strPath = 'assets/' . $strTarget . '/' . str_replace('/', '_', $arrFile['name']) . $this->strMode;
                 $objFile = new \File($strPath, true);
                 $objFile->write($this->handleScssLess($content, $arrFile));
                 $objFile->close();
                 $return[] = $strPath;
             } else {
                 $name = $arrFile['name'];
                 // Add the media query (see #7070)
                 if ($arrFile['media'] != '' && $arrFile['media'] != 'all' && strpos($content, '@media') === false) {
                     $name .= '" media="' . $arrFile['media'];
                 }
                 $return[] = $name;
             }
         }
         if ($this->strMode == self::JS) {
             return implode('"></script><script src="', $return);
         } else {
             return implode('"><link rel="stylesheet" href="', $return);
         }
     }
     // Load the existing file
     if (file_exists(TL_ROOT . '/assets/' . $strTarget . '/' . $strKey . $this->strMode)) {
         return $strUrl . 'assets/' . $strTarget . '/' . $strKey . $this->strMode;
     }
     // Create the file
     $objFile = new \File('assets/' . $strTarget . '/' . $strKey . $this->strMode, true);
     $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, $arrFile);
             }
         }
         if ($arrFile['extension'] == self::CSS) {
             $content = $this->handleCss($content, $arrFile);
         } elseif ($arrFile['extension'] == self::SCSS || $arrFile['extension'] == self::LESS) {
             $content = $this->handleScssLess($content, $arrFile);
         }
         $objFile->append($content);
     }
     unset($content);
     $objFile->close();
     // Create a gzipped version
     if (\Config::get('gzipScripts') && function_exists('gzencode')) {
         \File::putContent('assets/' . $strTarget . '/' . $strKey . $this->strMode . '.gz', gzencode(file_get_contents(TL_ROOT . '/assets/' . $strTarget . '/' . $strKey . $this->strMode), 9));
     }
     return $strUrl . 'assets/' . $strTarget . '/' . $strKey . $this->strMode;
 }
 protected function putContentForCacheFile()
 {
     $this->cacheFile->truncate();
     $this->cacheFile->putContent($this->cacheFile->path, json_encode($this->cacheUrl));
 }
Example #9
0
 /**
  * Outputs concatenated CSS for the specified view
  * @param string view | the view - optional
  */
 public function css()
 {
     $this->setContentType('text/css; charset=utf-8;');
     $this->setCache(Date::SPAN_MONTH);
     require_once Pimple::instance()->getBaseDir() . 'lib/Stylesheet.php';
     $cacheDir = Pimple::instance()->getSiteDir() . 'cache/css/';
     Dir::ensure($cacheDir);
     $templates = array();
     if (!Request::get('skipLayout', false)) {
         $templates[] = 'application';
     }
     $view = Request::get('view', false);
     if ($view) {
         $templates[] = $view;
     }
     $used = array();
     $isDebug = Settings::get(Settings::DEBUG, false);
     foreach ($templates as $template) {
         $cacheFile = $cacheDir . $template . '.css';
         echo "/* {$template} */\n";
         if ($isDebug) {
             $view = new View($template);
             $files = $view->getInternalCssFiles();
             echo "/*FILES:\n\t" . implode("\n\t", $files) . '*/' . chr(10);
             foreach ($files as $file) {
                 if (in_array($file, $used) || String::StartsWith($file, "http://") || String::StartsWith($file, "https://")) {
                     continue;
                 }
                 $used[] = $file;
                 echo "/*FILE:" . basename($file) . '*/' . chr(10) . Stylesheet::minify($file) . chr(10);
             }
         } else {
             Dir::ensure(dirname($cacheFile));
             if (!is_file($cacheFile)) {
                 File::truncate($cacheFile);
                 $view = new View($template);
                 $files = $view->getInternalCssFiles();
                 File::append($cacheFile, "/*FILES:\n\t" . implode("\n\t", $files) . '*/' . chr(10));
                 foreach ($files as $file) {
                     if (in_array($file, $used) || String::StartsWith($file, "http://") || String::StartsWith($file, "https://")) {
                         continue;
                     }
                     $used[] = $file;
                     File::append($cacheFile, "/*FILE:" . basename($file) . '*/' . chr(10) . Stylesheet::minify($file) . chr(10));
                 }
             }
             echo file_get_contents($cacheFile);
         }
     }
     Pimple::end();
 }
Example #10
0
 /**
  * Generate the combined file and return its path
  * 
  * @param string $strUrl An optional URL to prepend
  * 
  * @return string The path to the combined file
  */
 public function getCombinedFile($strUrl = null)
 {
     if ($strUrl === null) {
         $strUrl = TL_ASSETS_URL;
     }
     $strTarget = substr($this->strMode, 1);
     $strKey = substr(md5($this->strKey), 0, 12);
     // Load the existing file
     if (file_exists(TL_ROOT . '/assets/' . $strTarget . '/' . $strKey . $this->strMode)) {
         return $strUrl . 'assets/' . $strTarget . '/' . $strKey . $this->strMode;
     }
     // Create the file
     $objFile = new \File('assets/' . $strTarget . '/' . $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, $arrFile);
             }
         }
         // Handle style sheets
         if ($this->strMode == self::CSS) {
             // Adjust the file paths
             $strDirname = dirname($arrFile['name']);
             $strGlue = $strDirname != '.' ? $strDirname . '/' : '';
             $strBuffer = '';
             $chunks = preg_split('/url\\("([^"]+)"\\)/', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
             // Check the URLs
             for ($i = 0; $i < count($chunks); $i = $i + 2) {
                 $strBuffer .= $chunks[$i];
                 if (!isset($chunks[$i + 1])) {
                     break;
                 }
                 $strData = $chunks[$i + 1];
                 // Skip absolute links and embedded images
                 if (strncmp($strData, 'data:', 5) !== 0 && strncmp($strData, 'http://', 7) !== 0 && strncmp($strData, 'https://', 8) !== 0) {
                     // Make the paths relative to the root (see #4161)
                     if (strncmp($strData, '../', 3) !== 0) {
                         $strData = '../../' . $strGlue . $strData;
                     } else {
                         $dir = $strDirname;
                         // Remove relative paths
                         while (strncmp($strData, '../', 3) === 0) {
                             $dir = dirname($dir);
                             $strData = substr($strData, 3);
                         }
                         $glue = $dir != '.' ? $dir . '/' : '';
                         $strData = '../../' . $glue . $strData;
                     }
                 }
                 $strBuffer .= 'url("' . $strData . '")';
             }
             $content = $strBuffer;
             // Add the media type if there is no @media command in the code
             if ($arrFile['media'] != '' && $arrFile['media'] != 'all' && strpos($content, '@media') === false) {
                 $content = '@media ' . $arrFile['media'] . "{\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('assets/' . $strTarget . '/' . $strKey . $this->strMode . '.gz');
         $objFile->write(gzencode(file_get_contents(TL_ROOT . '/assets/' . $strTarget . '/' . $strKey . $this->strMode), 9));
         $objFile->close();
     }
     return $strUrl . 'assets/' . $strTarget . '/' . $strKey . $this->strMode;
 }
Example #11
0
<?php

require "file.php";
echo File::exists("sample.txt") ? "it does" : "it doesn't";
echo "<br>";
echo File::size("file.php");
echo "<br>";
echo File::name("sample.txt");
echo "<br>";
echo File::extension("sample.txt");
echo "<br>";
echo File::last_updated("file.php");
echo "<br>";
echo File::get("sample2.txt", "A default value");
//echo "<br>";
//echo File::delete("sample.txt");
echo "<br>";
echo File::append("sample.txt", "here is some more new data" . PHP_EOL);
echo "<br>";
echo File::truncate("sample.txt");
?>

<!DOCTYPE html>
<html>
<head>
	<title></title>
</head>
<body>

</body>
</html>