예제 #1
0
 /**
  * getLessCss
  *
  * Returns compiled css from less file
  * @version 1.0.0  
  */
 public function getLessCss($options = array('files' => array(), 'variables' => array()))
 {
     // extract array params
     extract($options);
     // If files are not passed retutn null
     if (!isset($files)) {
         return null;
     }
     // If variables are not passed set empty
     if (!isset($variables)) {
         $variables = array();
     }
     //get basepath helper
     $basePath = $this->serviceLocator->get('ViewHelperManager')->get('basePath');
     // less file array
     $files_arr = array();
     foreach ($files as $file) {
         $files_arr[INFINITY_PUBLIC_PATH . $file] = $basePath($file);
     }
     // less compile options
     $less_options = array('cache_dir' => INFINITY_PUBLIC_CACHE_PATH, 'compress' => true);
     // Generate css file from less file, if css already cached then return that one
     $css_file_name = \Less_Cache::Get($files_arr, $less_options, $variables);
     // Returns compiled css file url
     return $basePath('/cache/' . $css_file_name);
 }
예제 #2
0
 /**
  * Compare the parser results with the expected css
  *
  */
 function CompareFile($expected_file)
 {
     $less_file = $this->TranslateFile($expected_file);
     $expected_css = trim(file_get_contents($expected_file));
     // Check with standard parser
     echo "\n  " . basename($expected_file);
     echo "\n    - Standard Compiler";
     $parser = new Less_Parser();
     $parser->parseFile($less_file);
     $css = $parser->getCss();
     $css = trim($css);
     $this->assertEquals($expected_css, $css);
     // Check with cache
     if ($this->cache_dir) {
         $options = array('cache_dir' => $this->cache_dir);
         $files = array($less_file => '');
         echo "\n    - Regenerating Cache";
         $css_file_name = Less_Cache::Regen($files, $options);
         $css = file_get_contents($this->cache_dir . '/' . $css_file_name);
         $css = trim($css);
         $this->assertEquals($expected_css, $css);
         // Check using the cached data
         echo "\n    - Using Cache";
         $css_file_name = Less_Cache::Get($files, $options);
         $css = file_get_contents($this->cache_dir . '/' . $css_file_name);
         $css = trim($css);
         $this->assertEquals($expected_css, $css);
     }
 }
예제 #3
0
 /**
  * @param string $file
  * @return bool|string
  * @throws \Exception
  */
 public static function getCompiledFile($file)
 {
     $file = GeneralUtility::getFileAbsFileName($file);
     $pathParts = pathinfo($file);
     if ($pathParts['extension'] === 'less') {
         try {
             $options = array('cache_dir' => GeneralUtility::getFileAbsFileName('typo3temp/mooxcore'));
             $settings = $GLOBALS['TSFE']->tmpl->setup['plugin.']['tx_mooxcore.']['settings.'] ?: array();
             if ($settings['cssSourceMapping']) {
                 // enable source mapping
                 $optionsForSourceMap = array('sourceMap' => true, 'sourceMapWriteTo' => GeneralUtility::getFileAbsFileName('typo3temp/mooxcore') . '/mooxcore.map', 'sourceMapURL' => '/typo3temp/mooxcore/mooxcore.map', 'sourceMapBasepath' => PATH_site, 'sourceMapRootpath' => '/');
                 $options += $optionsForSourceMap;
                 // disable CSS compression
                 /** @var $pageRenderer \TYPO3\CMS\Core\Page\PageRenderer */
                 $pageRenderer = $GLOBALS['TSFE']->getPageRenderer();
                 $pageRenderer->disableCompressCss();
             }
             if ($settings['overrideLessVariables']) {
                 $variables = self::getVariablesFromConstants();
             } else {
                 $variables = array();
             }
             $files = array();
             $files[$file] = '../../' . str_replace(PATH_site, '', dirname($file)) . '/';
             $compiledFile = \Less_Cache::Get($files, $options, $variables);
             $file = "typo3temp/mooxcore/" . $compiledFile;
             return $file;
         } catch (\Exception $e) {
             throw new \Exception($e->getMessage());
         }
     }
     return false;
 }
 public static function loadStyles() {
     require_once ($_SERVER['DOCUMENT_ROOT'] . '/inc/less/Less.php');
     Less_Cache::$cache_dir = $_SERVER['DOCUMENT_ROOT'] . '/css/cache/';
     $files[$_SERVER['DOCUMENT_ROOT'] . '/css/style.less'] = '/css/';
     $css_file_name = Less_Cache::Get($files);
     self::$styles = '<link rel="stylesheet" type="text/css" href="/css/cache/' . $css_file_name . '">';
 }
예제 #5
0
function handle_lesscss_request($lessfile, $relative_path)
{
    $dir = forceslash(sys_get_temp_dir());
    $css_file = Less_Cache::Get([$lessfile => $relative_path], ['sourceMap' => true, 'compress' => true, 'relativeUrls' => true, 'cache_dir' => $dir]);
    $css = file_get_contents($dir . $css_file);
    header('Content-Type: text/css');
    header('Content-Length: ' . strlen($css));
    print $css;
}
 function css($file, $media = null)
 {
     /* Only initiate if webiste is in dev mode or a ?flush is called */
     if (preg_match('/\\.less$/i', $file) || Director::isDev() || isset($_GET['flush'])) {
         /* If file is CSS, check if there is a LESS file */
         if (preg_match('/\\.css$/i', $file)) {
             $less = preg_replace('/\\.css$/i', '.less', $file);
             if (is_file(Director::getAbsFile($less))) {
                 $file = $less;
             }
         }
         /* If less file exists, then check/compile it */
         if (preg_match('/\\.less$/i', $file)) {
             $out = preg_replace('/\\.less$/i', '.css', $file);
             $css_file = Director::getAbsFile($out);
             $options = array();
             /* Automatically compress if in live mode */
             if (Director::isLive()) {
                 $options['compress'] = true;
             }
             try {
                 /* Force recompile & only write to css if updated */
                 if (isset($_GET['flush']) || !Director::isLive()) {
                     /* Force deleting of all cache files on flush */
                     if (file_exists(self::$cacheDir) && isset($_GET['flush']) && !self::$already_flushed) {
                         $paths = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(self::$cacheDir, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST);
                         foreach ($paths as $path) {
                             $path->isDir() && !$path->isLink() ? rmdir($path->getPathname()) : unlink($path->getPathname());
                         }
                         /* make sure we only flush once per request and not for each *.less */
                         self::$already_flushed = true;
                     }
                     /* Set cache directory */
                     $options['cache_dir'] = self::$cacheDir;
                     /* Set cache method */
                     $options['cache_method'] = self::$cacheMethod;
                     /* Calculate the LESS file's parent URL */
                     $css_dir = dirname(Director::baseURL() . $file) . '/';
                     /* Generate and return cached file path */
                     $cached_file = self::$cacheDir . '/' . Less_Cache::Get(array(Director::getAbsFile($file) => $css_dir), $options, self::$variables);
                     /* check cache vs. css and overwrite if necessary */
                     if (!is_file($css_file) || md5_file($css_file) != md5_file($cached_file)) {
                         copy($cached_file, $css_file);
                     }
                 }
             } catch (Exception $ex) {
                 trigger_error('Less.php fatal error: ' . $ex->getMessage(), E_USER_ERROR);
             }
             $file = $out;
         }
     }
     /* Return css file path */
     return parent::css($file, $media);
 }
예제 #7
0
 /**
  * @return array
  * @throws Exception
  */
 public function compile()
 {
     $lessFiles = $this->getFileList($this->config->fileNames);
     try {
         $filePath = \Less_Cache::Get($lessFiles, $this->setOptions());
         $error = false;
     } catch (\Exception $e) {
         $filePath = false;
         $error = $e->getMessage();
     }
     $arReturn = array('filePath' => $filePath, 'error' => $error);
     return $arReturn;
 }
예제 #8
0
 /**
  * 
  * @param string $lessFile
  * @param string $id
  * @return string
  */
 public function __invoke($lessFile, $id = "")
 {
     // less options
     $options = array('compress' => $this->options->getMinify());
     // file to cache
     $to_cache = array($lessFile => $this->view->basePath(""));
     \Less_Cache::$cache_dir = $this->options->getCacheFolder();
     $css_file_name = \Less_Cache::Get($to_cache, $options);
     if ($id == "") {
         $id = substr($css_file_name, 0, -4);
     }
     return "<link type='text/css' id='" . $id . "' rel='stylesheet' href='" . $this->options->getCacheFolderUrl() . $css_file_name . "' />";
 }
예제 #9
0
 /**
  * @param $inputFilename
  * @param $outputFilename
  * @param $cacheFilename
  *
  * @return string
  */
 protected function _compileFile($inputFilename, $preparedFilename, $outputFilename, $cacheFilename)
 {
     try {
         $options = array('import_dirs' => array(dirname($inputFilename) => dirname($inputFilename), PATH_site => PATH_site), 'cache_dir' => GeneralUtility::getFileAbsFileName('typo3temp/DynCss/Cache'));
         if ($this->config['enableDebugMode']) {
             $options['sourceMap'] = TRUE;
         }
         $files = array($inputFilename => '');
         $compiledFile = $options['cache_dir'] . '/' . \Less_Cache::Get($files, $options, $this->overrides);
         return file_get_contents($compiledFile);
     } catch (\Exception $e) {
         return $e;
     }
 }
예제 #10
0
 /**
  * Компилирует файл less и возвращает текст css-файла
  *
  * @param $aFile
  * @param $sCacheDir
  * @param $sMapPath
  * @param $aParams
  * @param $bCompress
  * @return string
  */
 public function CompileFile($aFile, $sCacheDir, $sMapPath, $aParams, $bCompress)
 {
     if (!($sMapPath && $sCacheDir && $aFile)) {
         return '';
     }
     try {
         $options = array('sourceMap' => TRUE, 'sourceMapWriteTo' => $sMapPath, 'sourceMapURL' => E::ModuleViewerAsset()->AssetFileUrl($sMapPath), 'cache_dir' => $sCacheDir);
         if ($bCompress) {
             $options = array_merge($options, array('compress' => TRUE));
         }
         $sCssFileName = Less_Cache::Get($aFile, $options, $aParams);
         return file_get_contents($sCacheDir . $sCssFileName);
     } catch (Exception $e) {
         E::ModuleMessage()->AddErrorSingle($e->getMessage());
     }
     return '';
 }
 /**
  * Perform the crunch work of compiling less files on initilisation,
  * but only do this when we are running on dev (and the file is in
  * need of updating).
  * 
  */
 public function onBeforeInit()
 {
     // Only check and compile when on dev
     if (Director::isDev()) {
         $files = LessCompilerConfig::config()->file_mappings;
         $root_path = LessCompilerConfig::config()->root_path;
         $temp_folder = TEMP_FOLDER;
         if (is_array($files)) {
             $theme_dir = Controller::join_links("themes", SSViewer::current_theme());
             $base_theme = Controller::join_links($theme_dir, SSViewer::current_theme());
             $options = array('cache_dir' => $temp_folder);
             if (LessCompilerConfig::config()->compress) {
                 $options['compress'] = true;
             }
             // First loop through all files and deal with inputs
             foreach ($files as $input => $output) {
                 if ($input && $output) {
                     // Does output and input contain a path
                     if (strpos($input, '/') === false) {
                         $input = Controller::join_links($theme_dir, "less", $input);
                     }
                     if (strpos($output, '/') === false) {
                         $output = Controller::join_links($theme_dir, "css", $output);
                     }
                     // Now append the full system path to the input
                     // and output file.
                     $input = Controller::join_links(BASE_PATH, $input);
                     $output = Controller::join_links(BASE_PATH, $output);
                     // Finally try to compile our less files
                     try {
                         $css_file_name = Less_Cache::Get(array($input => $root_path), $options);
                         $css = file_get_contents(Controller::join_links($temp_folder, $css_file_name));
                         $output_file = fopen($output, "w");
                         fwrite($output_file, $css);
                         fclose($output_file);
                     } catch (exception $e) {
                         error_log($e->getMessage());
                     }
                 }
             }
         }
     }
 }
예제 #12
0
function smarty_function_lessphp($params, &$smarty)
{
    if (!isset($params['file']) or !($file = $params['file'])) {
        return;
    }
    $modx = $smarty->modx;
    $template_dir = MODX_ASSETS_PATH . 'components/modxsite/templates/';
    $template = $modx->getOption('modxSmarty.template', $scriptProperties, 'default');
    $template_url = $modx->getOption('modxSite.template_url');
    if ($pre_template = $modx->getOption('modxSmarty.pre_template', null, false)) {
        $template = $pre_template;
    }
    $template_url .= $template . '/';
    $template_dir .= $template . '/';
    $less_fname = $template_dir . $file;
    $less_files = array($less_fname => $template_url . 'css/');
    $options = array('cache_dir' => $template_dir . 'cache/', 'compress' => true);
    return $template_url . 'cache/' . Less_Cache::Get($less_files, $options);
}
예제 #13
0
function stormbringer_preprocessor() {

	$preprocessor = get_theme_mod('bootstrap_preprocessor', true);

	$cssfile = 'css/styles.css';

	if ( $preprocessor === 'less' ) {
		if ( ! is_admin() ) {
			if ( current_user_can( 'administrator' ) && $_GET['lesscompile'] != '1' ) {

			}
			else {
				$to_cache              = array( STYLESHEETPATH . '/less/application.less' => '' );
				Less_Cache::$cache_dir = STYLESHEETPATH . '/css/';
				$css_file_name         = Less_Cache::Get( $to_cache );
				wp_register_style( 'theme',  get_stylesheet_directory_uri() . '/'.$cssfile, array(), null, null );
				wp_enqueue_style( 'theme' );
			}

		}
	}

	if ( $preprocessor === 'scss' || $preprocessor == 1) {

		if ( ! is_admin() ) {
			if ( current_user_can( 'administrator' ) || $_GET['scsscompile'] == '1' ) {
				wp_register_style( 'theme', get_stylesheet_directory_uri() . '/css/styles.css', array(), null, null );
				wp_enqueue_style( 'theme' );
			} else {

				$cssfile      = 'css/styles.min.css';
				$grunt_assets = get_theme_mod('grunt_assets');
				//if(isset($grunt_assets[$cssfile])) {
				//	$cssfile = $grunt_assets[$cssfile];
				//}

				wp_register_style( 'theme', get_stylesheet_directory_uri() . '/'.$cssfile, array(), null, null );
				wp_enqueue_style( 'theme' );
			}
		}
	}

}
예제 #14
0
 public function filterLoad(AssetInterface $asset)
 {
     $filePath = $asset->getSourceRoot() . DS . $asset->getSourcePath();
     Tlog::getInstance()->addDebug("Starting CSS processing: {$filePath}...");
     $importDirs = [];
     if ($dir = $asset->getSourceDirectory()) {
         $importDirs[$dir] = '';
     }
     foreach ($this->loadPaths as $loadPath) {
         $importDirs[$loadPath] = '';
     }
     $options = ['cache_dir' => $this->cacheDir, 'relativeUrls' => false, 'compress' => true, 'import_dirs' => $importDirs];
     $css_file_name = \Less_Cache::Get([$filePath => ''], $options);
     $content = @file_get_contents($this->cacheDir . DS . $css_file_name);
     if ($content === false) {
         $content = '';
         Tlog::getInstance()->warning("Compilation of {$filePath} did not generate an output file.");
     }
     $asset->setContent($content);
     Tlog::getInstance()->addDebug("CSS processing done.");
 }
 public function index()
 {
     $filename = implode('/', array_slice($this->uri->rsegments, 2));
     $filename = preg_replace('/\\.{2,}/', '', $filename);
     // Sanitazing the name.
     $base_path = DEFAULTFCPATH;
     if (defined('APPSEGMENT') && APPSEGMENT != '') {
         $base_path .= APPSEGMENT . '/';
     }
     $file_path = $base_path . $filename;
     $this->config->load('less_compile', false, true);
     $less_compile_config = !empty($this->config->config['less_compile']) && is_array($this->config->config['less_compile']) ? $this->config->config['less_compile'] : array();
     if (empty($less_compile_config)) {
         $this->_show_404();
         return;
     }
     $found = false;
     foreach ($less_compile_config as $options) {
         $name = isset($options['name']) ? (string) $options['name'] : '';
         $source = isset($options['source']) ? (string) $options['source'] : '';
         $destination = isset($options['destination']) ? (string) $options['destination'] : '';
         if ($destination == $file_path && $name != '' && $source != '' && $destination != '') {
             $found = true;
             break;
         }
     }
     if (!$found) {
         $this->_show_404();
         return;
     }
     unset($options['name']);
     unset($options['source']);
     unset($options['destination']);
     $cache_dir = WRITABLEPATH . 'cache_lessphp/' . sha1($name) . '/';
     is_dir($cache_dir) or @mkdir($cache_dir, 0755, TRUE);
     $options['cache_dir'] = $cache_dir;
     $options['cache_method'] = 'serialize';
     $this->output->set_content_type('text/css');
     $this->output->set_output(@(string) file_get_contents($cache_dir . Less_Cache::Get(array($source => ''), $options)));
 }
예제 #16
0
 /**
  * @param string $file
  * @return bool|string
  */
 public static function getCompiledFile($file)
 {
     $file = GeneralUtility::getFileAbsFileName($file);
     $pathParts = pathinfo($file);
     if ($pathParts['extension'] === 'less') {
         if (!class_exists('Less_Cache')) {
             $autoload = GeneralUtility::makeInstance('Less_Autoloader');
             $autoload::register();
         }
         try {
             $options = array('cache_dir' => GeneralUtility::getFileAbsFileName('typo3temp/mooxcore'));
             $variables = self::getVariablesFromConstants();
             $files = array();
             $files[$file] = "";
             $compiledFile = \Less_Cache::Get($files, $options, $variables);
             $file = "typo3temp/mooxcore/" . $compiledFile;
             return $file;
         } catch (\Exception $e) {
             $error_message = $e->getMessage();
         }
     }
     return false;
 }
예제 #17
0
 /**
  * Compiles an input less file to an output css file using the PHP compiler
  * @param  array   $input       The input .less files to be compiled
  * @param  array   $options     Options to be passed to the php parser
  * @param  array   $modify_vars Less modify_vars
  * @param  boolean $cache       Whether to cache or not
  * @return string               If cache is not enabled will return the full CSS compiled.
  *                              Otherwise it will return the resulting filename from the compilation.
  */
 public function compile(array $input, array $options = [], array $modify_vars = [], $cache = true)
 {
     $to_parse = [];
     foreach ($input as $in) {
         $less = realpath(WWW_ROOT . $in);
         // If we have plugin notation (Plugin.less/file.less)
         // ensure to properly load the files
         list($plugin, $basefile) = $this->_View->pluginSplit($in, false);
         if (!empty($plugin)) {
             $less = realpath(Plugin::path($plugin) . 'webroot' . DS . $basefile);
             if ($less !== false) {
                 $to_parse[$less] = $this->assetBaseUrl($plugin, $basefile);
                 continue;
             }
         }
         if ($less !== false) {
             $to_parse[$less] = '';
         } else {
             // Plugins without plugin notation (/plugin/less/file.less)
             list($plugin, $basefile) = $this->assetSplit($in);
             if ($file = $this->pluginAssetFile([$plugin, $basefile])) {
                 $to_parse[$file] = $this->assetBaseUrl($plugin, $basefile);
             } else {
                 // Will probably throw a not found error
                 $to_parse[$in] = '';
             }
         }
     }
     if ($cache) {
         $options += ['cache_dir' => $this->css_path];
         return \Less_Cache::Get($to_parse, $options, $modify_vars);
     }
     $lessc = new \Less_Parser($options);
     foreach ($to_parse as $file => $path) {
         $lessc->parseFile($file, $path);
     }
     // ModifyVars must be called at the bottom of the parsing,
     // this way we're ensuring they override their default values.
     // http://lesscss.org/usage/#command-line-usage-modify-variable
     $lessc->ModifyVars($modify_vars);
     return $lessc->getCss();
 }
예제 #18
0
<?php

require 'Cache.php';
Less_Cache::$cache_dir = dirname(__FILE__) . '/cache';
$files = array();
$files[dirname(__FILE__) . '/less/bootstrap.less'] = '/';
//$files['teste.less'] = '/mysite/custom/';
$css_file_name = Less_Cache::Get($files);
//echo '<link rel="stylesheet" type="text/css" href="/_testes/less.php/cache/'.$css_file_name.'">';
header('Content-Type: css/text');
header('Location: cache/' . $css_file_name . '');
예제 #19
0
파일: runless.php 프로젝트: eitamar/j3acc
    $buffer = str_replace('; ', ';', $buffer);
    $buffer = str_replace(', ', ',', $buffer);
    $buffer = str_replace(' {', '{', $buffer);
    $buffer = str_replace('} ', '}', $buffer);
    $buffer = str_replace(': ', ':', $buffer);
    $buffer = str_replace(' ,', ',', $buffer);
    $buffer = str_replace(' ;', ';', $buffer);
    $buffer = str_replace(';}', '}', $buffer);
    return $buffer;
}
$uri = JUri::base();
// less compiler
$lesspath = __DIR__ . '/css';
require_once $lesspath . '/less.php/less.php';
$less_files = array($lesspath . '/template.less' => $uri);
$options = array('cache_dir' => $lesspath . '/cache/');
$css_file_name = Less_Cache::Get($less_files, $options);
$compiled = file_get_contents($lesspath . '/cache/' . $css_file_name);
if (file_exists($lesspath . '/cache/' . $css_file_name)) {
    // merge files
    $compiled = file_get_contents($lesspath . '/cache/' . $css_file_name);
    $compiled .= file_get_contents(JUri::base() . '/media/system/css/system.css');
    $compiled .= file_get_contents(JPATH_THEMES . '/system/css/system.css');
    $compiled .= file_get_contents(JPATH_THEMES . '/system/css/general.css');
    if ($templateparams->get('compressless', 1) == 1) {
        $compressed = compress($compiled);
        file_put_contents($lesspath . '/template.css', $compressed);
    } else {
        file_put_contents($lesspath . '/template.css', $compiled);
    }
}
예제 #20
0
파일: tao.php 프로젝트: techart/bitrix.tao
 /**
  * @param $style
  * @return string
  * @throws Exception
  */
 public static function styleUrl($style)
 {
     if (strpos($style, '/') === false) {
         $style = self::filePath(array(self::localDir('styles'), self::taoDir('styles')), $style);
     }
     if (preg_match('{\\.less$}', $style)) {
         $path = self::rootDir($style);
         if (is_file($path)) {
             $options = array('cache_dir' => self::localDir(self::getOption('less_cache')));
             $css = \Less_Cache::Get(array($path => ''), $options);
             if ($css) {
                 return '/local/' . self::getOption('less_cache') . '/' . $css;
             }
         }
     }
     return $style;
 }
    if (!($ext == "css" || $ext == "less")) {
        throw new Exception("Input less-file required", 403);
    }
    // file not found
    if (!is_file($input)) {
        throw new Exception("File '{$input}' not exists", 404);
    }
    $options = array("sourceMap" => true, "compress" => false, "outputSourceFiles" => true, "sourceMapBasepath" => dirname($input), "sourceMapRootpath" => substr(dirname($input), strlen($docroot)), "cache_dir" => __DIR__ . DIRECTORY_SEPARATOR . "cache", "cache_method" => false, "strictMath" => true, "relativeUrls" => false);
    $options["sourceMapWriteTo"] = $options["cache_dir"] . DIRECTORY_SEPARATOR . "lessphp_" . md5($input) . ".map";
    $options["sourceMapURL"] = substr($options["sourceMapWriteTo"], strlen($docroot));
    if (DIRECTORY_SEPARATOR != "/") {
        $options["sourceMapURL"] = str_replace(DIRECTORY_SEPARATOR, "/", $options["sourceMapURL"]);
    }
    include_once "lib" . DIRECTORY_SEPARATOR . "Less.php";
    include_once "lib" . DIRECTORY_SEPARATOR . "Cache.php";
    $output = Less_Cache::Get(array($input => $options["sourceMapRootpath"] . "/"), $options);
    $css = file_get_contents($options["cache_dir"] . DIRECTORY_SEPARATOR . $output);
    $mtime = filectime($options["cache_dir"] . DIRECTORY_SEPARATOR . $output);
    if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"]) && strtotime($_SERVER["HTTP_IF_MODIFIED_SINCE"]) >= $mtime) {
        header("HTTP/1.0 304 Not Modified");
    } else {
        header("Last-Modified: " . gmdate("D, d M Y H:i:s", $mtime) . " GMT");
        $css = strtr($css, array("\n  " => "\n    ", "\n    " => "\n        "));
        echo "/*! Generated by LESS css compiler: " . gmdate("r", $mtime) . " | {$output} */\n", $css;
    }
    return;
} catch (Exception $exception) {
    if (@ini_get("zlib.output_compression")) {
        @ini_set("zlib.output_compression", false);
        @ini_set("zlib.output_compression_level", 0);
    }
예제 #22
0
 /**
  * Less CSS
  *
  * @param  mixed $mixed CSS string to process with Less compiler or an array with CSS file's Path and URL.
  * @return mixed string or an array with CSS file's Path and URL.
  */
 function _lessCss($mixed)
 {
     require_once BX_DIRECTORY_PATH_PLUGINS . 'lessphp/Less.php';
     if (is_array($mixed) && isset($mixed['url']) && isset($mixed['path'])) {
         $sPathFile = realpath($mixed['path']);
         $aInfoFile = pathinfo($sPathFile);
         if (!isset($aInfoFile['extension']) || $aInfoFile['extension'] != 'less') {
             return $mixed;
         }
         require_once BX_DIRECTORY_PATH_PLUGINS . 'lessphp/Cache.php';
         $aFiles = array($mixed['path'] => $mixed['url']);
         $aOptions = array('cache_dir' => $this->_sCachePublicFolderPath);
         $sFile = Less_Cache::Get($aFiles, $aOptions, $this->_oConfigTemplate->aLessConfig);
         return array('url' => $this->_sCachePublicFolderUrl . $sFile, 'path' => $this->_sCachePublicFolderPath . $sFile);
     }
     $oLess = new Less_Parser();
     $oLess->ModifyVars($this->_oConfigTemplate->aLessConfig);
     $oLess->parse($mixed);
     return $oLess->getCss();
 }
예제 #23
0
 /**
  * Generates and Gets the Cached files
  *
  * This will generated a compiled less file into css format
  * but it will cache it so that it doesnt happen unless the file has changed
  *
  * @param string $dir The directory housing the less files
  * @param string $uri_root The uri root of the web request
  * @param array $variables Array of variables to override
  * @return string the CSS filename
  */
 public function getCachedFile($dir, $uri_root = '', $variables = array())
 {
     if (!file_exists($dir . '/cache')) {
         if (!mkdir($dir . '/cache')) {
             die_freepbx(sprintf(_('Can not create cache folder at %s/cache. Please run (from the CLI): %s'), $dir, 'amportal chown'));
         }
     }
     \Less_Cache::$cache_dir = $dir . '/cache';
     $files = array();
     $basename = basename($dir);
     try {
         if (file_exists($dir . "/bootstrap.less")) {
             $files = array($dir . "/bootstrap.less" => $uri_root);
             $filename = \Less_Cache::Get($files, array('compress' => true), $variables);
         } elseif (file_exists($dir . "/" . $basename . ".less")) {
             $files = array($dir . "/" . $basename . ".less" => $uri_root);
             $filename = \Less_Cache::Get($files, array('compress' => true), $variables);
         } else {
             //load them all randomly. Probably in alpha order
             foreach (glob($dir . "/*.less") as $file) {
                 $files[$file] = $uri_root;
             }
             uksort($files, "strcmp");
             $filename = \Less_Cache::Get($files, array('compress' => true), $variables);
         }
     } catch (\Exception $e) {
         die_freepbx(sprintf(_('Can not write to cache folder at %s/cache. Please run (from the CLI): %s'), $dir, 'amportal chown'));
     }
     return $filename;
 }
예제 #24
0
 /**
  * Recompile CSS if needed
  * @param string $filename CSS filename without extension
  * @param string $recompile Availible options: always (RECOMPILE_ALWAYS), when changed (RECOMPILE_CHANGE) or never (RECOMPILE_NONE)
  * @param array $options Extra compile options
  * @return bool true on recompiled, false when not
  */
 public function recompile($filename, $recompile = null, $options = array())
 {
     if ($this->recompiled === true) {
         return false;
         // This instance is already recompiled. Recompile a new or the same instance using Less::fresh()
     }
     if (is_null($recompile)) {
         $recompile = env('LESS_RECOMPILE');
     }
     $this->recompiled = false;
     // Default value
     switch ($recompile) {
         case self::RECOMPILE_ALWAYS:
             $this->recompiled = $this->compile($filename, $options);
             break;
         case self::RECOMPILE_CHANGE:
             $config = $this->prepareConfig($options);
             $input_path = $config['less_path'] . DIRECTORY_SEPARATOR . $filename . '.less';
             $cache_key = $this->getCacheKey($filename);
             try {
                 $cache_value = \Less_Cache::Get(array($input_path => asset('/')), $config, $this->modified_vars);
             } catch (\Exception $e) {
                 $cache_value = null;
                 $this->cleanCache();
             }
             if ($this->cache->get($cache_key, '') !== $cache_value || !empty($this->parsed_less)) {
                 $this->cache->put($cache_key, $cache_value, 0);
                 $this->recompiled = $this->compile($filename, $options);
             }
             break;
         case self::RECOMPILE_NONE:
         case null:
             // Do nothing obviously
             break;
         default:
             throw new \Exception('Unknown \'' . $recompile . '\' LESS_RECOMPILE setting');
     }
     return $this->recompiled;
 }
예제 #25
0
파일: HeadLink.php 프로젝트: grharry/vufind
 /**
  * Compile a less file to css and add to css folder
  *
  * @param string $file                  Path to less file
  * @param string $media                 Media type
  * @param string $conditionalStylesheet Load condition for file
  *
  * @return void
  */
 public function addLessStylesheet($file, $media = 'all', $conditionalStylesheet = false)
 {
     $relPath = 'less/' . $file;
     $urlHelper = $this->getView()->plugin('url');
     $currentTheme = $this->themeInfo->findContainingTheme($relPath);
     $helperHome = $urlHelper('home');
     $home = APPLICATION_PATH . '/themes/' . $currentTheme . '/';
     $cssDirectory = $helperHome . 'themes/' . $currentTheme . '/css/less/';
     try {
         $less_files = [APPLICATION_PATH . '/themes/' . $currentTheme . '/' . $relPath => $cssDirectory];
         $themeParents = array_keys($this->themeInfo->getThemeInfo());
         $directories = [];
         foreach ($themeParents as $theme) {
             $directories[APPLICATION_PATH . '/themes/' . $theme . '/less/'] = $helperHome . 'themes/' . $theme . '/css/less/';
         }
         $css_file_name = \Less_Cache::Get($less_files, ['cache_dir' => $home . 'css/less/', 'cache_method' => false, 'compress' => true, 'import_dirs' => $directories, 'output' => str_replace('.less', '.css', $file)]);
         $this->prependStylesheet($cssDirectory . $css_file_name, $media, $conditionalStylesheet);
     } catch (\Exception $e) {
         error_log($e->getMessage());
         list($fileName, ) = explode('.', $file);
         $this->prependStylesheet($urlHelper('home') . "themes/{$currentTheme}/css/{$fileName}.css");
     }
 }
예제 #26
0
 /**
  * Action for compile LESS
  *
  * @method GET
  * @route @\.css$
  */
 public function lessAction()
 {
     $di = Di::getDefault();
     $router = $di->get('router');
     $route = $router->request()->pathname();
     $response = $router->response();
     /* Get path to  */
     $baseUrl = $di->get('config')->get('global', 'base_url');
     $route = preg_replace('!' . $baseUrl . '!', '/', $route, 1);
     $route = str_replace('css', 'less', $route);
     /* Remove min */
     $route = str_replace('.min.', '.', $route);
     $centreonPath = realpath($this->centreonPath . '/www/');
     if (false === file_exists($centreonPath . $route)) {
         $this->notFoundAction();
         return;
     }
     // Set Options
     $tempDir = $di->get('config')->get('global', 'centreon_generate_tmp_dir');
     $options = array('cache_dir' => $tempDir, 'use_cache' => false, 'compress' => false, 'relativeUrls' => false);
     if ("dev" !== $di->get('config')->get('global', 'env')) {
         $options['use_cache'] = true;
         $options['compress'] = true;
     }
     /* Response compiled CSS */
     $response->header('Content-Type', 'text/css');
     $imgUrl = rtrim($baseUrl, '/') . '/static/centreon/img/login.jpg")';
     $variables = array('login-background-image' => 'url("' . $imgUrl);
     $less_file = array($centreonPath . $route => $route);
     $css_file_name = \Less_Cache::Get($less_file, $options, $variables);
     $compiled = file_get_contents($tempDir . $css_file_name);
     $response->body($compiled);
 }
예제 #27
0
파일: index.php 프로젝트: nagumo/Phest
 public function testLessJsCssGeneration($dir, $less, $css, $map)
 {
     global $obj_buffer;
     $options = array();
     $options['compress'] = $this->compress;
     //$options['relativeUrls']	= true;
     //$options['cache_dir']		= $this->cache_dir;
     //$options['cache_method']	= 'php';
     //$options['urlArgs']	= '424242';
     $this->files_tested++;
     $matched = false;
     $basename = basename($less);
     $basename = substr($basename, 0, -5);
     //remove .less extension
     $file_less = $dir . $less;
     $file_uri = $this->AbsoluteToRelative(dirname($file_less));
     $file_sourcemap = false;
     $file_css = false;
     echo '<a class="filename" href="?dir=' . rawurlencode($this->dir) . '&amp;file=' . rawurlencode($basename) . '">File: ' . $basename . '</a>';
     if (!file_exists($file_less)) {
         echo '<b>LESS file missing: ' . $file_less . '</b>';
         return false;
     }
     //css or map
     if ($css) {
         $file_css = $dir . $css;
         $file_expected = $this->TranslateFile($file_css, 'expected', 'css');
         if (!file_exists($file_css)) {
             echo '<b>CSS file missing: ' . $file_css . '</b>';
             return false;
         }
     } elseif ($map) {
         $file_sourcemap = $dir . $map;
         $file_expected = $this->TranslateFile($file_sourcemap, 'expected', 'map');
         if (!file_exists($file_sourcemap)) {
             echo '<b>Sourcemap file missing: ' . $file_sourcemap . '</b>';
             return false;
         }
     } else {
         echo '<b>Unknown comparison file</b>';
         return false;
     }
     //generate the sourcemap
     if (file_exists($file_sourcemap)) {
         $generated_map = $this->cache_dir . '/' . $basename . '.map';
         $options['sourceMap'] = true;
         $options['sourceMapBasepath'] = $dir;
         $options['sourceMapWriteTo'] = $generated_map;
         $options['sourceMapURL'] = $this->AbsoluteToRelative($generated_map);
     }
     //example, but not very functional import callback
     /*
     $options['import_callback'] = 'callback';
     if( !function_exists('callback') ){
     	function callback($evald){
     		$evaldPath = $evald->getPath();
     		msg('evaldpath: '.$evaldPath);
     	}
     }
     */
     $compiled = '';
     try {
         /**
          * Less_Cache Testing
          */
         Less_Cache::$cache_dir = $this->cache_dir;
         //$cached_css_file = Less_Cache::Regen( array($file_less=>'') );
         //$options['output'] = md5($file_less).'.css';
         $cached_css_file = Less_Cache::Get(array($file_less => ''), $options);
         $compiled = file_get_contents($this->cache_dir . '/' . $cached_css_file);
         /*
         $parser = new Less_Parser( $options );
         $parser->parseFile( $file_less ); //$file_uri
         $compiled = $parser->getCss();
         */
         //$parser = new Less_Parser( $options );
         //$less_content = file_get_contents( $file_less );
         //$parser->parse( $less_content );
         //$compiled = $parser->getCss();
         //$parser = new lessc();
         //$compiled = $parser->compileFile($file_less);
         //$parser = new lessc();
         //$compiled = $parser->compile(file_get_contents($file_less));
     } catch (Exception $e) {
         $compiled = $e->getMessage();
     }
     //sourcemap comparison
     if ($file_sourcemap) {
         //$expected = file_get_contents($generated_map);
         //$this->SaveExpected($file_expected, $expected);
         $generated_map = $this->ComparableSourceMap($generated_map);
         $file_sourcemap = $this->ComparableSourceMap($file_sourcemap);
         $expected_map = '';
         if (file_exists($file_expected)) {
             $expected_map = $this->ComparableSourceMap($file_expected);
         }
         $matched = $this->CompareFiles($generated_map, $file_sourcemap, $expected_map);
         if (isset($_GET['file'])) {
             $this->PHPDiff($generated_map, $file_sourcemap, true);
             $this->ObjBuffer();
         }
         return $matched;
         //css comparison
     } else {
         //$this->SaveExpected($file_expected, $compiled);
         $css = file_get_contents($file_css);
         // If compress is enabled, add some whitespaces back for comparison
         if ($this->compress) {
             $compiled = str_replace('{', " {\n", $compiled);
             //$compiled = str_replace('}',"\n}",$compiled);
             $compiled = str_replace(';', ";\n", $compiled);
             $compiled = preg_replace('/\\s*}\\s*/', "\n}\n", $compiled);
             $css = preg_replace('/\\n\\s+/', "\n", $css);
             $css = preg_replace('/:\\s+/', ":", $css);
             $css = preg_replace('/;(\\s)}/', '$1}', $css);
         }
         $css = trim($css);
         $compiled = trim($compiled);
         $expected = '';
         if (file_exists($file_expected)) {
             $expected = file_get_contents($file_expected);
         }
         $matched = $this->CompareFiles($compiled, $css, $expected);
     }
     if (isset($_GET['file'])) {
         $this->PHPDiff($compiled, $css);
         echo '<table><tr><td>';
         echo '<textarea id="lessphp_textarea" autocomplete="off">' . htmlspecialchars($compiled) . '</textarea>';
         echo '</td><td>';
         echo '<textarea id="lessjs_textarea" autocomplete="off"></textarea>';
         echo '</td></tr></table>';
         $this->ObjBuffer();
         $this->LessLink($file_less);
     }
     return $matched;
 }
예제 #28
0
<?php

require __DIR__ . '/../vendor/autoload.php';
$parser = new Less_Parser();
$cacheDir = __DIR__ . '/../var/cache/less';
@mkdir($cacheDir, 0755, true);
$compileItems = [__DIR__ . "/../data/less/bootstrap/bootstrap.less" => __DIR__ . '/../public/css/bootstrap.css', __DIR__ . "/../data/less/bootstrap/theme.less" => __DIR__ . '/../public/css/bootstrap-theme.css'];
foreach ($compileItems as $input => $output) {
    $cacheSetting = array($input => '/mysite/');
    Less_Cache::$cache_dir = $cacheDir;
    $cssFileName = Less_Cache::Get($cacheSetting);
    echo "{$cssFileName} \n";
    $compiled = file_get_contents($cacheDir . '/' . $cssFileName);
    file_put_contents($output, $compiled);
}
예제 #29
0
 /**
  * Compile a LESS file inside a theme.
  *
  * @param string $theme Theme containing file
  * @param string $less  Relative path to LESS file
  *
  * @return void
  */
 protected function compileFile($theme, $less)
 {
     $parts = explode(':', $less);
     $less = $parts[0];
     $finalOutDir = $this->basePath . '/themes/' . $theme . '/css/';
     list($fileName, ) = explode('.', $less);
     $finalFile = $finalOutDir . $fileName . '.css';
     $this->logMessage("\tcompiling '" . $less . "' into '" . $finalFile . "'");
     $start = microtime(true);
     $directories = [];
     $info = new ThemeInfo($this->basePath . '/themes', $theme);
     foreach (array_keys($info->getThemeInfo()) as $curTheme) {
         $directories["{$this->basePath}/themes/{$curTheme}/less/"] = $this->fakePath . "themes/{$curTheme}/css/less";
     }
     $lessDir = $this->basePath . '/themes/' . $theme . '/less/';
     if (!file_exists($lessDir . $less)) {
         $this->logMessage("\t\t" . $lessDir . $less . ' does not exist; skipping.');
         return;
     }
     $outFile = \Less_Cache::Get([$lessDir . $less => $this->fakePath . "themes/{$theme}/css/less"], ['cache_dir' => $this->tempPath, 'cache_method' => 'php', 'compress' => true, 'import_dirs' => $directories]);
     $css = file_get_contents($this->tempPath . '/' . $outFile);
     if (!is_dir(dirname($finalFile))) {
         mkdir(dirname($finalFile));
     }
     file_put_contents($finalFile, $this->makeRelative($css, $less));
     $this->logMessage("\t\t" . (microtime(true) - $start) . ' sec');
 }
예제 #30
0
 /**
  * Generates and Gets the Cached files
  *
  * This will generated a compiled less file into css format
  * but it will cache it so that it doesnt happen unless the file has changed
  *
  * @param string $dir The directory housing the less files
  * @param string $uri_root The uri root of the web request
  * @param array $variables Array of variables to override
  * @return string the CSS filename
  */
 public function getCachedFile($dir, $uri_root = '', $variables = array())
 {
     if (!file_exists($dir . '/cache')) {
         // Explicitly don't trigger an E_WARNING, as PHP doesn't tell you what
         // it was trying to mkdir, so the error is useless.
         if (!@mkdir($dir . '/cache')) {
             die_freepbx(sprintf(_('Can not create the LESS cache folder at %s. Please run (from the CLI): %s'), $dir . '/cache', 'fwconsole chown'));
         }
         $ampowner = $this->FreePBX->Config->get('AMPASTERISKWEBUSER');
         $ampgroup = $ampowner != $this->FreePBX->Config->get('AMPASTERISKUSER') ? $this->FreePBX->Config->get('AMPASTERISKGROUP') : $ampowner;
         chown($dir . '/cache', $ampowner);
         chgrp($dir . '/cache', $ampgroup);
     }
     if (!is_readable($dir)) {
         die_freepbx(sprintf(_('Can not read from the LESS folder at %s. Please run (from the CLI): %s'), $dir, 'fwconsole chown'));
     }
     if (!is_readable($dir . '/cache') || !is_writable($dir . '/cache')) {
         die_freepbx(sprintf(_('Can not write to the LESS cache folder at %s. Please run (from the CLI): %s'), $dir . '/cache', 'fwconsole chown'));
     }
     \Less_Cache::$cache_dir = $dir . '/cache';
     $files = array();
     $basename = basename($dir);
     try {
         if (file_exists($dir . "/bootstrap.less")) {
             $files = array($dir . "/bootstrap.less" => $uri_root);
             $filename = \Less_Cache::Get($files, array('compress' => true), $variables);
         } elseif (file_exists($dir . "/" . $basename . ".less")) {
             $files = array($dir . "/" . $basename . ".less" => $uri_root);
             $filename = \Less_Cache::Get($files, array('compress' => true), $variables);
         } else {
             //load them all randomly. Probably in alpha order
             foreach (glob($dir . "/*.less") as $file) {
                 $files[$file] = $uri_root;
             }
             uksort($files, "strcmp");
             $filename = \Less_Cache::Get($files, array('compress' => true), $variables);
         }
     } catch (\Exception $e) {
         die_freepbx(sprintf(_('Error with the templating engine: %s'), $e->getMessage()));
     }
     return $filename;
 }