Exemplo n.º 1
0
Arquivo: Leafo.php Projeto: jbzoo/less
 /**
  * {@inheritdoc}
  */
 protected function _initCompiler()
 {
     if ($this->_compiler) {
         return $this->_compiler;
     }
     $this->_compiler = new \lessc();
     if (class_exists('\\lessc_formatter_lessjs')) {
         $formatter = new \lessc_formatter_lessjs();
         // configurate css view
         $formatter->openSingle = ' { ';
         $formatter->closeSingle = "}\n";
         $formatter->close = "}\n";
         $formatter->indentChar = '    ';
         $formatter->disableSingle = true;
         $formatter->breakSelectors = true;
         $formatter->assignSeparator = ': ';
         $formatter->selectorSeparator = ', ';
         $this->_compiler->setFormatter($formatter);
     }
     $this->_compiler->setPreserveComments(false);
     // Set paths
     $importPaths = (array) $this->_options->get('import_paths', []);
     foreach ($importPaths as $fullPath => $relPath) {
         $this->setImportPath($fullPath, $relPath);
     }
     // Set paths
     $this->_compiler->setVariables((array) $this->_options->get('global_vars', []));
     return $this->_compiler;
 }
 public function __construct(Ai1ec_Registry_Object $registry, $default_theme_url = AI1EC_DEFAULT_THEME_URL)
 {
     parent::__construct($registry);
     $this->lessc = $this->_registry->get('lessc');
     $this->lessc->setFormatter('compressed');
     $this->default_theme_url = $this->sanitize_default_theme_url($default_theme_url);
     $this->parsed_css = '';
     $this->files = array('style.less', 'event.less', 'calendar.less');
 }
Exemplo n.º 3
0
function auto_less_compile($inputFile, $outputFile)
{
    // load the cache
    $cacheFile = $inputFile . ".cache";
    if (file_exists($cacheFile)) {
        $cache = unserialize(file_get_contents($cacheFile));
    } else {
        $cache = $inputFile;
    }
    // custom formatter
    $formatter = new lessc_formatter_classic();
    $formatter->indentChar = "\t";
    $less = new lessc();
    $less->setFormatter($formatter);
    try {
        // create a new cache object, and compile
        $newCache = $less->cachedCompile($cache);
        // the next time we run, write only if it has updated
        if (!is_array($cache) || $newCache["updated"] > $cache["updated"]) {
            file_put_contents($cacheFile, serialize($newCache));
            file_put_contents($outputFile, $newCache['compiled']);
        }
    } catch (Exception $ex) {
        echo "lessphp fatal error: " . $ex->getMessage();
    }
}
Exemplo n.º 4
0
 /**
  * @param string $src
  * @return string
  */
 public function lessCompile($src)
 {
     $path = $this->lessCompiledPath . DIRECTORY_SEPARATOR . basename($src, '.less') . '.css';
     $lessCompile = false;
     if (!$this->lessForceCompile && $this->lessCompile) {
         $lessFiles = $this->_cacheGet('EAssetManager-less-updated-' . $src);
         if ($lessFiles && is_array($lessFiles)) {
             foreach ($lessFiles as $_file => $_time) {
                 if (filemtime($_file) != $_time) {
                     $lessCompile = true;
                     break;
                 }
             }
         } else {
             $lessCompile = true;
         }
         unset($lessFiles);
     }
     if (!file_exists($path) || $lessCompile || $this->lessForceCompile) {
         if (!$this->_lessc) {
             $this->_lessc = new lessc();
         }
         $this->_lessc->setFormatter($this->lessFormatter);
         $lessCache = $this->_lessc->cachedCompile($src);
         file_put_contents($path, $lessCache['compiled'], LOCK_EX);
         $this->_cacheSet('EAssetManager-less-updated-' . $src, $lessCache['files']);
     }
     return $path;
 }
 public function boot(Application $app)
 {
     // Validate this params.
     $this->validate($app);
     // Define default formatter if not already set.
     $formatter = isset($app['less.formatter']) ? $app['less.formatter'] : self::FORMATTER_CLASSIC;
     $sources = $app['less.sources'];
     $target = $app['less.target'];
     $targetContent = '';
     $needToRecompile = false;
     !is_array($sources) and $sources = array($sources);
     foreach ($sources as $source) {
         if (!$needToRecompile) {
             $needToRecompile = $this->targetNeedsRecompile($source, $target);
         }
         if ($needToRecompile) {
             $handle = new \lessc($source);
             $handle->setFormatter($formatter);
             $targetContent .= $handle->parse();
         }
     }
     if (isset($handle)) {
         if ($targetContent) {
             file_put_contents($target, $targetContent);
             if (isset($app['less.target_mode'])) {
                 chmod($target, $app['less.target_mode']);
             }
         } else {
             throw new \Exception("No content after parsing less source files. Please check your .less files");
         }
     }
 }
Exemplo n.º 6
0
 /**
  * Compile CSS files used by admin ui
  *
  * @throws Exception
  */
 protected function _compileCss()
 {
     $bootstrapPath = WWW_ROOT . 'bootstrap';
     if (!file_exists($bootstrapPath)) {
         if (!$this->_clone) {
             throw new Exception('You don\'t have "bootstrap" directory in ' . WWW_ROOT);
         }
         CakeLog::info('Cloning Bootstrap...');
         chdir(WWW_ROOT);
         exec('git clone git://github.com/twitter/bootstrap');
     }
     chdir($bootstrapPath);
     exec('git checkout -f v2.2.0');
     App::import('Vendor', 'Lessc', array('file' => 'lessphp' . DS . 'lessc.inc.php'));
     $lessc = new lessc();
     $formatter = new lessc_formatter_lessjs();
     $formatter->compressColors = false;
     ini_set('precision', 16);
     $lessc->setFormatter($formatter);
     $files = array('less' . DS . 'admin.less' => CSS . 'croogo-bootstrap.css', 'less' . DS . 'admin-responsive.less' => CSS . 'croogo-bootstrap-responsive.css');
     foreach ($files as $file => $output) {
         $out = str_replace(APP, '', $output);
         if ($lessc->compileFile(WWW_ROOT . $file, $output)) {
             $text = __('CSS : %s created', $out);
             CakeLog::info($text);
         } else {
             $text = __('CSS : %s failed', $out);
             CakeLog::error($text);
         }
     }
 }
 function css($file, $media = null)
 {
     /* 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, then check/compile it */
     if (preg_match('/\\.less$/i', $file)) {
         $compiler = 'checkedCompile';
         $out = preg_replace('/\\.less$/i', '.css', $file);
         /* Force recompile if ?flush */
         if (isset($_GET['flush'])) {
             $compiler = 'compileFile';
         }
         /* Create instance */
         $less = new lessc();
         /* Automatically compress if in live mode */
         if (DIRECTOR::isLive()) {
             $less->setFormatter("compressed");
         }
         try {
             $less->{$compiler}(Director::getAbsFile($file), Director::getAbsFile($out));
         } catch (Exception $ex) {
             trigger_error("lessphp fatal error: " . $ex->getMessage(), E_USER_ERROR);
         }
         $file = $out;
     }
     /* Return css path */
     return parent::css($file, $media);
 }
Exemplo n.º 8
0
/**
 * Generate custom color scheme css
 *
 * @since 1.0
 */
function bigboom_generate_custom_color_scheme()
{
    parse_str($_POST['data'], $data);
    if (!isset($data['custom_color_scheme'])) {
        return;
    }
    if (!$data['custom_color_scheme']) {
        return;
    }
    $color_1 = $data['custom_color_1'];
    if (!$color_1) {
        return;
    }
    // Prepare LESS to compile
    $less = file_get_contents(THEME_DIR . '/css/color-schemes/mixin.less');
    $less .= ".custom-color-scheme { .color-scheme({$color_1}); }";
    // Compile
    require THEME_DIR . '/inc/libs/lessc.inc.php';
    $compiler = new lessc();
    $compiler->setFormatter('compressed');
    $css = $compiler->compile($less);
    // Get file path
    $upload_dir = wp_upload_dir();
    $dir = path_join($upload_dir['basedir'], 'custom-css');
    $file = $dir . '/color-scheme.css';
    // Create directory if it doesn't exists
    wp_mkdir_p($dir);
    @file_put_contents($file, $css);
    wp_send_json_success();
}
Exemplo n.º 9
0
 /**
  * Compile CSS files used by admin ui
  *
  * @throws Exception
  */
 protected function _compileCss()
 {
     $bootstrapPath = $this->_croogoWebroot . 'bootstrap';
     if (!file_exists($bootstrapPath)) {
         if (!$this->_clone) {
             throw new Exception('You don\'t have "bootstrap" directory in ' . WWW_ROOT);
         }
         chdir($this->_croogoPath);
         CakeLog::info('Cloning Bootstrap...');
         $command = sprintf('git clone -b %s %s %s', escapeshellarg($this->_tags['bootstrap']), escapeshellarg($this->_repos['bootstrap']), escapeshellarg($bootstrapPath));
         CakeLog::info("\t{$command}");
         exec($command);
     }
     chdir($bootstrapPath);
     exec(sprintf('git checkout -f %s', escapeshellarg($this->_tags['bootstrap'])));
     App::import('Vendor', 'Croogo.Lessc', array('file' => 'lessphp' . DS . 'lessc.inc.php'));
     $lessc = new lessc();
     $formatter = new lessc_formatter_lessjs();
     $formatter->compressColors = false;
     ini_set('precision', 16);
     $lessc->setFormatter($formatter);
     $files = array('less' . DS . 'admin.less' => 'css' . DS . 'croogo-bootstrap.css', 'less' . DS . 'admin-responsive.less' => 'css' . DS . 'croogo-bootstrap-responsive.css');
     foreach ($files as $file => $output) {
         $file = $this->_croogoWebroot . $file;
         $output = $this->_croogoWebroot . $output;
         $out = str_replace(APP, '', $output);
         if ($lessc->compileFile($file, $output)) {
             $text = __d('croogo', 'CSS : %s created', $out);
             CakeLog::info($text);
         } else {
             $text = __d('croogo', 'CSS : %s failed', $out);
             CakeLog::error($text);
         }
     }
 }
Exemplo n.º 10
0
function shoestrap_buttons_css()
{
    $btn_color = get_theme_mod('shoestrap_buttons_color');
    // Make sure colors are properly formatted
    $btn_color = '#' . str_replace('#', '', $btn_color);
    // if no color has been selected, set to #0066cc. This prevents errors with the php-less compiler.
    if (strlen($btn_color) < 3) {
        $btn_color = '#0066cc';
    }
    ?>

  <style>
    <?php 
    if (class_exists('lessc')) {
        $less = new lessc();
        $less->setVariables(array("btnColor" => $btn_color));
        $less->setFormatter("compressed");
        if (shoestrap_get_brightness($btn_color) <= 160) {
            // The code below is a copied from bootstrap's buttons.less + mixins.less files
            echo $less->compile("\n          @btnColorHighlight: darken(spin(@btnColor, 5%), 10%);\n  \n          .gradientBar(@primaryColor, @secondaryColor, @textColor: #fff, @textShadow: 0 -1px 0 rgba(0,0,0,.25)) {\n            color: @textColor;\n            text-shadow: @textShadow;\n            #gradient > .vertical(@primaryColor, @secondaryColor);\n            border-color: @secondaryColor @secondaryColor darken(@secondaryColor, 15%);\n            border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) fadein(rgba(0,0,0,.1), 15%);\n          }\n  \n          #gradient {\n            .vertical(@startColor: #555, @endColor: #333) {\n              background-color: mix(@startColor, @endColor, 60%);\n              background-image: -moz-linear-gradient(top, @startColor, @endColor); // FF 3.6+\n              background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+\n              background-image: -webkit-linear-gradient(top, @startColor, @endColor); // Safari 5.1+, Chrome 10+\n              background-image: -o-linear-gradient(top, @startColor, @endColor); // Opera 11.10\n              background-image: linear-gradient(to bottom, @startColor, @endColor); // Standard, IE10\n              background-repeat: repeat-x;\n            }\n          }\n  \n          .buttonBackground(@startColor, @endColor, @textColor: #fff, @textShadow: 0 -1px 0 rgba(0,0,0,.25)) {\n            .gradientBar(@startColor, @endColor, @textColor, @textShadow);\n            *background-color: @endColor; /* Darken IE7 buttons by default so they stand out more given they won't have borders */\n            .reset-filter();\n            &:hover, &:active, &.active, &.disabled, &[disabled] {\n              color: @textColor;\n              background-color: @endColor;\n              *background-color: darken(@endColor, 5%);\n            }\n          }\n          .btn, .btn-primary{\n            .buttonBackground(@btnColor, @btnColorHighlight);\n          }\n        ");
        } else {
            echo $less->compile("\n          @btnColorHighlight: darken(@btnColor, 15%);\n  \n          .gradientBar(@primaryColor, @secondaryColor, @textColor: #333, @textShadow: 0 -1px 0 rgba(0,0,0,.25)) {\n            color: @textColor;\n            text-shadow: @textShadow;\n            #gradient > .vertical(@primaryColor, @secondaryColor);\n            border-color: @secondaryColor @secondaryColor darken(@secondaryColor, 15%);\n            border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) fadein(rgba(0,0,0,.1), 15%);\n          }\n  \n          #gradient {\n            .vertical(@startColor: #555, @endColor: #333) {\n              background-color: mix(@startColor, @endColor, 60%);\n              background-image: -moz-linear-gradient(top, @startColor, @endColor); // FF 3.6+\n              background-image: -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+\n              background-image: -webkit-linear-gradient(top, @startColor, @endColor); // Safari 5.1+, Chrome 10+\n              background-image: -o-linear-gradient(top, @startColor, @endColor); // Opera 11.10\n              background-image: linear-gradient(to bottom, @startColor, @endColor); // Standard, IE10\n              background-repeat: repeat-x;\n            }\n          }\n  \n          .buttonBackground(@startColor, @endColor, @textColor: #333, @textShadow: 0 -1px 0 rgba(0,0,0,.25)) {\n            .gradientBar(@startColor, @endColor, @textColor, @textShadow);\n            *background-color: @endColor; /* Darken IE7 buttons by default so they stand out more given they won't have borders */\n            .reset-filter();\n            &:hover, &:active, &.active, &.disabled, &[disabled] {\n              color: @textColor;\n              background-color: @endColor;\n              *background-color: darken(@endColor, 5%);\n            }\n          }\n          .btn, .btn-primary{\n            .buttonBackground(@btnColor, @btnColorHighlight);\n          }\n        ");
        }
    }
    ?>
  </style>
  <?php 
}
 function autoCompilerLess($params)
 {
     global $modx;
     $inputFile = MODX_BASE_PATH . $params["input_less"];
     $outputFile = MODX_BASE_PATH . $params["output_css"];
     define("PHPLESS_CSS_PATH", dirname($outputFile) . "/");
     define("PHPLESS_IMAGESIZE", 32);
     if (!is_file(MODX_BASE_PATH . $params["input_less"])) {
         return;
     }
     if (!class_exists('lessc')) {
         include $params['less_path'] . 'lessc.inc.php';
     }
     if (!class_exists('DataUriLess')) {
         include $params['less_path'] . 'class.datauriless.php';
     }
     $cacheFile = $inputFile . ".cache";
     if (is_file($cacheFile)) {
         $cache = unserialize(file_get_contents($cacheFile));
     } else {
         $cache = $inputFile;
     }
     switch ($params['output_formating']) {
         case 'lessjs':
         case 'compressed':
             $formatter = 'lessjs';
             break;
         case 'classic':
             $formatter = $params['output_formating'];
             break;
         case 'tabing':
             $formatter = new lessc_formatter_classic();
             $formatter->indentChar = "\t";
             break;
         default:
             $formatter = 'lessjs';
             break;
     }
     $less = new lessc();
     $less->setFormatter($formatter);
     try {
         $newCache = $less->cachedCompile($cache);
     } catch (Exception $ex) {
         $modx->logEvent(0, 3, $ex->getMessage(), $e->activePlugin);
     }
     if (!is_array($cache) || $newCache["updated"] > $cache["updated"] || !is_file($outputFile)) {
         file_put_contents($cacheFile, serialize($newCache));
         $datauri = new DataUriLess($newCache['compiled']);
         $output_compile = $datauri->run();
         if (@file_put_contents($outputFile, $output_compile)) {
             //if($params["compiler_log"]==="true"){
             $e =& $modx->Event;
             $modx->logEvent($modx->toDateFormat(time() + $modx->config['server_offset_time']), 1, "less файл скомпилирован " . $modx->nicesize(filesize($outputFile)), $e->activePlugin);
             //}
         } else {
             $modx->logEvent(0, 3, "Невозможно сохранить CSS файл", $e->activePlugin);
         }
     }
 }
Exemplo n.º 12
0
function generate_less_css()
{
    include_once __DIR__ . '/../vendor/lessc.inc.php';
    $less = new lessc();
    $less->setFormatter("compressed");
    $less_file = __DIR__ . "/../less/site.less";
    $css_file = __DIR__ . "/../css/style.css";
    return $less->compileFile($less_file, $css_file);
}
Exemplo n.º 13
0
 /**
  * Compile all files into one file.
  *
  * @param string $filePath File location.
  * @param string $format   Formatter for less.
  *
  * @return void
  */
 public function compileTo($filePath, $format = 'compressed')
 {
     $less = '';
     foreach ($this->_files as $file) {
         $less .= file_get_contents($file) . "\n\n";
     }
     $this->_lessc->setImportDir($this->_importDirs);
     $this->_lessc->setFormatter($format);
     $result = $this->_lessc->compile($less);
     file_put_contents($filePath, $result);
 }
Exemplo n.º 14
0
 /**
  * Builds a LESS/CSS resource from string
  *
  * @param string $string
  *
  * @return type
  * The compiled and compressed CSS
  */
 public static function buildString($string)
 {
     $obj = new \lessc();
     $obj->setFormatter('compressed');
     try {
         $output = $obj->compile($string);
     } catch (\Exception $e) {
         throw $e;
     }
     return $output;
 }
Exemplo n.º 15
0
 /**
  * Compiles a less css file. The the compiler will create a css file output.
  * 
  * @param array $config Array of less compile configuration
  */
 public function compile($config = array())
 {
     $config = new KConfig($config);
     $config->append(array('parse_urls' => true, 'compress' => true, 'import' => array(), 'force' => false, 'output' => null, 'input' => null));
     $less = new lessc();
     $less->setPreserveComments(!$config->compress);
     if ($config->compress) {
         $less->setFormatter('compressed');
     }
     $config['import'] = $config['import'];
     $less->setImportDir($config['import']);
     $cache_file = JPATH_CACHE . '/less-' . md5($config->input);
     if (file_exists($cache_file)) {
         $cache = unserialize(file_get_contents($cache_file));
     } else {
         $cache = $config->input;
     }
     $force = $config->force;
     //if output doesn't exsit then force compile
     if (!is_readable($config->output)) {
         $force = true;
     }
     //check if any of the import folder have changed or
     //if yes then re-compile
     if (is_array($cache)) {
         foreach ($config['import'] as $path) {
             if (is_readable($path) && filemtime($path) > $cache['updated']) {
                 $force = true;
                 break;
             }
         }
     }
     try {
         $new_cache = $less->cachedCompile($cache, $force);
     } catch (Exception $e) {
         print $e->getMessage();
         return;
     }
     if (!is_array($cache) || $new_cache['updated'] > $cache['updated']) {
         if ($config->parse_urls) {
             $new_cache['compiled'] = $this->_parseUrls($new_cache['compiled'], $config->import);
         }
         //store the cache
         file_put_contents($cache_file, serialize($new_cache));
         //store the compiled file
         //create a directory if
         if (!file_exists(dirname($config->output))) {
             mkdir(dirname($config->output), 0755);
         }
         file_put_contents($config->output, $new_cache['compiled']);
     }
 }
Exemplo n.º 16
0
 /**
  * Parse a Less file to CSS
  */
 public function parse($src, $dst, $options)
 {
     $this->auto = isset($options['auto']) ? $options['auto'] : $this->auto;
     $variables = $this->variables;
     $assetManager = Yii::$app->assetManager;
     // Final url of the file being compiled
     $assetUrl = substr($dst, strpos($assetManager->basePath, $assetManager->baseUrl));
     $variables['published-url'] = '"' . $assetUrl . '"';
     // Root for the published folder
     $variables['published-base-url'] = '"/' . implode('/', array_slice(explode('/', ltrim($assetUrl, '/')), 0, 2)) . '"';
     $less = new \lessc();
     $less->setVariables($variables);
     // Compressed setting
     if ($this->compressed) {
         $less->setFormatter('compressed');
     }
     \Less_Parser::$default_options['compress'] = $this->compressed;
     \Less_Parser::$default_options['relativeUrls'] = $this->relativeUrls;
     // Send out pre-compile event
     $event = new \yii\base\Event();
     $this->runtime = ['sourceFile' => $src, 'destinationFile' => $dst, 'compiler' => $less];
     $event->sender = $this;
     Event::trigger($this, self::EVENT_BEFORE_COMPILE, $event);
     try {
         if ($this->auto) {
             /* @var FileCache $cacheMgr */
             $cacheMgr = Yii::createObject('yii\\caching\\FileCache');
             $cacheMgr->init();
             $cacheId = 'less#' . $dst;
             $cache = $cacheMgr->get($cacheId);
             if ($cache === false || @filemtime($dst) < @filemtime($src)) {
                 $cache = $src;
             }
             $newCache = $less->cachedCompile($cache);
             if (!is_array($cache) || $newCache["updated"] > $cache["updated"]) {
                 $cacheMgr->set($cacheId, $newCache);
                 file_put_contents($dst, $newCache['compiled']);
             }
         } else {
             $less->compileFile($src, $dst);
         }
         // If needed, respect the users configuration
         if ($assetManager->fileMode !== null) {
             @chmod($dst, $assetManager->fileMode);
         }
         unset($this->less);
     } catch (\Exception $e) {
         throw new \Exception(__CLASS__ . ': Failed to compile less file : ' . $e->getMessage() . '.');
     }
 }
Exemplo n.º 17
0
function shoestrap_phpless()
{
    $shoestrap_responsive = get_theme_mod('shoestrap_responsive');
    if (!class_exists('lessc')) {
        require_once TEMPLATEPATH . '/lib/less_compiler/lessc.inc.php';
    }
    $less = new lessc();
    $less->setFormatter("compressed");
    if ($shoestrap_responsive == '0') {
        $less->checkedCompile(TEMPLATEPATH . '/assets/css/app-fixed.less', TEMPLATEPATH . '/assets/css/app-fixed.css');
    } else {
        $less->checkedCompile(TEMPLATEPATH . '/assets/css/app-responsive.less', TEMPLATEPATH . '/assets/css/app-responsive.css');
    }
}
Exemplo n.º 18
0
 public function filterLoad(AssetInterface $asset)
 {
     $lc = new \lessc();
     if ($dir = $asset->getSourceDirectory()) {
         $lc->importDir = $dir;
     }
     foreach ($this->loadPaths as $loadPath) {
         $lc->addImportDir($loadPath);
     }
     if ($this->formatter) {
         $lc->setFormatter($this->formatter);
     }
     if (null !== $this->preserveComments) {
         $lc->setPreserveComments($this->preserveComments);
     }
     $asset->setContent($lc->parse($asset->getContent(), $this->presets));
 }
Exemplo n.º 19
0
function loadcssfile($file, $cacheFile)
{
    // load the cache
    if (file_exists($cacheFile)) {
        $cache = unserialize(file_get_contents($cacheFile));
    } else {
        $cache = $file;
    }
    $less = new lessc();
    $less->setFormatter("compressed");
    $less->setImportDir(array(__ROOT__ . DS . ".." . DS . "style" . DS . "less"));
    $newCache = $less->cachedCompile($cache);
    if (!is_array($cache) || $newCache["updated"] > $cache["updated"]) {
        @file_put_contents($cacheFile, serialize($newCache));
    }
    return $newCache['compiled'];
}
Exemplo n.º 20
0
function thim_generate_less2css($fileout, $type, $less_variables = array(), $compile_file = '')
{
    if (!$compile_file) {
        $compile_file = TP_THEME_DIR . 'less' . DIRECTORY_SEPARATOR . 'theme-options.less';
    }
    $css = "";
    WP_Filesystem();
    global $wp_filesystem;
    $compiler = new lessc();
    $compiler->setFormatter('compressed');
    // set less varivalbles
    $compiler->setVariables($less_variables);
    // chose file less to compile
    $css .= $compiler->compileFile($compile_file);
    // get customcss
    $css .= thim_get_customcss();
    // minifile css
    $regex = array("`^([\t\\s]+)`ism" => '', "`^\\/\\*(.+?)\\*\\/`ism" => "", "`([\n\\A;]+)\\/\\*(.+?)\\*\\/`ism" => "\$1", "`([\n\\A;\\s]+)//(.+?)[\n\r]`ism" => "\$1\n", "`(^[\r\n]*|[\r\n]+)[\\s\t]*[\r\n]+`ism" => "", "/\n/i" => "");
    $css = preg_replace(array_keys($regex), $regex, $css);
    /***********************************
     * 		Create style.css file
     ***********************************/
    $style = thim_file_get_contents(TP_THEME_DIR . "inc/theme-info.txt");
    // Determine whether Multisite support is enabled
    if (is_multisite()) {
        // Write Theme Info into style.css
        if (!file_put_contents($fileout . $type, $style, LOCK_EX)) {
            @chmod($fileout . $type, 0777);
            file_put_contents($fileout . $type, $style, LOCK_EX);
        }
        // Write the rest to specific site style-ID.css
        $fileout = $fileout . '-' . get_current_blog_id();
        if (!file_put_contents($fileout . $type, $css, FILE_APPEND)) {
            @chmod($fileout . $type, 0777);
            file_put_contents($fileout . $type, $css, FILE_APPEND);
        }
    } else {
        // If this is not multisite, we write them all in style.css file
        $style .= $css;
        if (!file_put_contents($fileout . $type, $style, LOCK_EX)) {
            @chmod($fileout . $type, 0777);
            file_put_contents($fileout . $type, $style, LOCK_EX);
        }
    }
}
Exemplo n.º 21
0
 public function minify()
 {
     ///TODO: handle errors... at all.
     /// Compile less files
     Module::Requires("extern.JShrink");
     Module::Requires("extern.lessphp");
     $buffer = file_get_contents($this->path);
     switch ($this->getExtension()) {
         case "less":
             $less = new lessc();
             $less->setFormatter("compressed");
             $buffer = $less->compile($buffer);
             break;
         case "js":
             $buffer = \JShrink\Minifier::minify($buffer, array('flaggedComments' => false));
             break;
     }
     return $buffer;
 }
Exemplo n.º 22
0
 public function boot(Application $app)
 {
     // Validate this params.
     $this->validate($app);
     // Define default formatter if not already set.
     $formatter = isset($app['less.formatter']) ? $app['less.formatter'] : self::FORMATTER_CLASSIC;
     $sourcesDir = $app['less.source_dir'];
     $cacheDir = $app['less.cache_dir'];
     $targetDir = $app['less.target_dir'];
     $cacheContents = array();
     foreach ($sourcesDir as $sourceDir) {
         $files = scandir($sourceDir);
         foreach ($files as $file) {
             // if less file
             if (substr($file, -5) === '.less') {
                 $cache = $cacheDir . $this->before('.less', $file) . '.css.cache';
                 // if file cached
                 if (file_exists($cache)) {
                     array_push($cacheContents, ['dir' => $sourceDir, 'name' => $file, 'file' => unserialize(file_get_contents($cache))]);
                 } else {
                     array_push($cacheContents, ['dir' => $sourceDir, 'name' => $file, 'file' => $sourceDir . $file]);
                 }
             }
         }
     }
     $handle = new \lessc();
     $handle->setFormatter($formatter);
     foreach ($cacheContents as $cacheContent) {
         $newCache = $handle->cachedCompile($cacheContent['file']);
         if (!is_array($cacheContent['file']) || $newCache["updated"] > $cacheContent['file']["updated"]) {
             $target = $targetDir . $this->before('.less', $cacheContent['name']) . '.css';
             $cache = $cacheDir . $this->before('.less', $cacheContent['name']) . '.css.cache';
             // Write cache file
             file_put_contents($cache, serialize($newCache));
             // Write CSS file
             file_put_contents($target, $newCache['compiled']);
             // Change CSS permisions
             if (isset($app['less.target_mode'])) {
                 chmod($target, $app['less.target_mode']);
             }
         }
     }
 }
Exemplo n.º 23
0
 public function filterLoad(AssetInterface $asset)
 {
     $root = $asset->getSourceRoot();
     $path = $asset->getSourcePath();
     $lc = new \lessc();
     if ($root && $path) {
         $lc->importDir = dirname($root . '/' . $path);
     }
     foreach ($this->loadPaths as $loadPath) {
         $lc->addImportDir($loadPath);
     }
     if ($this->formatter) {
         $lc->setFormatter($this->formatter);
     }
     if (null !== $this->preserveComments) {
         $lc->setPreserveComments($this->preserveComments);
     }
     $asset->setContent($lc->parse($asset->getContent(), $this->presets));
 }
Exemplo n.º 24
0
function autoCompileLess($inputFile, $outputFile)
{
    // load the cache
    if ($_SERVER['PHP_SELF'] != "sobic" && $_SERVER['PHP_SELF'] != "./sobic") {
        $cacheFile = $inputFile . ".cache";
        if (file_exists($cacheFile)) {
            $cache = unserialize(file_get_contents($cacheFile));
        } else {
            $cache = $inputFile;
        }
        $less = new lessc();
        $less->setFormatter("compressed");
        $newCache = $less->cachedCompile($cache);
        if (!is_array($cache) || $newCache["updated"] > $cache["updated"]) {
            file_put_contents($cacheFile, serialize($newCache));
            file_put_contents($outputFile, $newCache['compiled']);
        }
    }
}
Exemplo n.º 25
0
 protected function parseLess($input)
 {
     $parsed = false;
     try {
         //include lessc library
         require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'include' . DIRECTORY_SEPARATOR . 'lessc.inc.php';
         //setup the parser
         $lessc = new lessc();
         if ($this->compress) {
             $lessc->setFormatter("compressed");
         }
         $importDir = array_merge($this->importDir, array(dirname($input)));
         $lessc->setImportDir($importDir);
         //parse the file
         $parsed = $lessc->parse($input);
     } catch (exception $e) {
         throw new CException(__CLASS__ . ': Failed to compile less file with message: ' . $e->getMessage() . '.');
     }
     return $parsed;
 }
Exemplo n.º 26
0
/**
 * Generate custom color scheme css
 *
 * @since 1.0
 */
function onehost_generate_custom_color_scheme()
{
    parse_str($_POST['data'], $data);
    if (!isset($data['custom_color_scheme']) || !$data['custom_color_scheme']) {
        return;
    }
    $color_1 = $data['custom_color_1'];
    if (!$color_1) {
        return;
    }
    // Getting credentials
    $url = wp_nonce_url('themes.php?page=theme-options');
    if (false === ($creds = request_filesystem_credentials($url, '', false, false, null))) {
        return;
        // stop the normal page form from displaying
    }
    // Try to get the wp_filesystem running
    if (!WP_Filesystem($creds)) {
        // Ask the user for them again
        request_filesystem_credentials($url, '', true, false, null);
        return;
    }
    global $wp_filesystem;
    // Prepare LESS to compile
    $less = $wp_filesystem->get_contents(THEME_DIR . '/css/color-schemes/mixin.less');
    $less .= ".custom-color-scheme { .color-scheme({$color_1}); }";
    // Compile
    require THEME_DIR . '/inc/libs/lessc.inc.php';
    $compiler = new lessc();
    $compiler->setFormatter('compressed');
    $css = $compiler->compile($less);
    // Get file path
    $upload_dir = wp_upload_dir();
    $dir = path_join($upload_dir['basedir'], 'custom-css');
    $file = $dir . '/color-scheme.css';
    // Create directory if it doesn't exists
    wp_mkdir_p($dir);
    $wp_filesystem->put_contents($file, $css, FS_CHMOD_FILE);
    wp_send_json_success();
}
Exemplo n.º 27
0
function generate_less_to_css($less_folder, $params, $ignore_files)
{
    WP_Filesystem();
    global $wp_filesystem;
    $files = scandir($less_folder);
    $css = '';
    $content_file_options = "";
    foreach ($files as $file) {
        if (strpos($file, 'less') !== false) {
            if (exist_in_array($ignore_files, $file) == true) {
                continue;
            }
            $content_file_options = $params;
            $content_file_options .= $wp_filesystem->get_contents($less_folder . $file);
            $compiler = new lessc();
            $compiler->setFormatter('compressed');
            $css .= $compiler->compile($content_file_options);
            $content_file_options = "";
        }
    }
    return $css;
}
Exemplo n.º 28
0
function less_css($handle)
{
    include DUDE_THEME_DIR . "/less/variables.php";
    // output css file name
    $css_path = DUDE_THEME_DIR . '/css/' . "{$handle}.css";
    // automatically regenerate files if source's modified time has changed or vars have changed
    try {
        // initialise the parser
        $less = new lessc();
        // load the cache
        $cache_path = DUDE_THEME_DIR . "/cache/{$handle}.css.cache";
        if (file_exists($cache_path)) {
            $cache = unserialize(file_get_contents($cache_path));
        }
        // If the cache or root path in it are invalid then regenerate
        if (empty($cache) || empty($cache['less']['root']) || !file_exists($cache['less']['root'])) {
            $cache = array('vars' => $vars, 'less' => DUDE_THEME_DIR . "/less/{$handle}.less");
        }
        // less config
        $less->setFormatter("compressed");
        $less->setVariables($vars);
        $less_cache = $less->cachedCompile($cache['less'], false);
        if (!file_exists($css_path) || empty($cache) || empty($cache['less']['updated']) || $less_cache['updated'] > $cache['less']['updated']) {
            file_put_contents($cache_path, serialize(array('vars' => $vars, 'less' => $less_cache)));
            file_put_contents($css_path, $less_cache['compiled']);
        } elseif ($vars !== $cache['vars']) {
            $less_cache = $less->cachedCompile($cache['less'], true);
            file_put_contents($cache_path, serialize(array('vars' => $vars, 'less' => $less_cache)));
            file_put_contents($css_path, $less_cache['compiled']);
        }
    } catch (exception $ex) {
        qa_fatal_error($ex->getMessage());
    }
    // return the compiled stylesheet with the query string it had if any
    $url = DUDE_THEME_URL . "/css/{$handle}.css";
    echo '<link href="' . $url . '" type="text/css" rel="stylesheet">';
}
Exemplo n.º 29
0
 /**
  * Build the Less file
  *
  * @param string $dest      The destination CSS file
  * @param bool   $force     If set to true, will build whereas the cache status
  * @param array  $variables Less variables to set before compiling the Less file
  */
 public function build($dest, $force = false, $variables = array())
 {
     if (!is_dir(dirname($dest))) {
         mkdir(dirname($dest), 0755, true);
     }
     $compiler = new \lessc();
     $lastCompilationFile = App::cache()->getCacheFilePath($this->getLastCompilationInfoFilename());
     if (!$force && is_file($lastCompilationFile)) {
         $cache = (include $lastCompilationFile);
     } else {
         $cache = $this->source;
     }
     $compiler->setFormatter('compressed');
     $compiler->setPreserveComments(false);
     $compilation = $compiler->cachedCompile($cache, $force);
     if (!is_array($cache) || $compilation['updated'] > $cache['updated']) {
         file_put_contents($dest, '/*** ' . date('Y-m-d H:i:s') . ' ***/' . PHP_EOL . $compilation['compiled']);
         $event = new Event('built-less', array('source' => $this->source, 'dest' => $dest));
         $event->trigger();
         // Save the compilation information
         unset($compilation['compiled']);
         $this->saveLastCompilationInfo($compilation);
     }
 }
Exemplo n.º 30
0
/**
 * Compile less to css. Creates a cache-file of the last compiled less-file.
 *
 * This code is originally from the manual of lessphp.
 *
 * @param string $inputFile  the filename of the less-file.
 * @param string $outputFile the filename of the css-file to be created.
 * @param array  $config     with configuration details.
 *
 * @return void
 */
function autoCompileLess($inputFile, $outputFile, $config)
{
    $cacheFile = $inputFile . ".cache";
    if (file_exists($cacheFile)) {
        $cache = unserialize(file_get_contents($cacheFile));
    } else {
        $cache = $inputFile;
    }
    $less = new lessc();
    // Add custom less functions
    if (isset($config['functions'])) {
        foreach ($config['functions'] as $key => $val) {
            $less->registerFunction($key, $val);
        }
    }
    // Add import dirs
    if (isset($config['imports'])) {
        foreach ($config['imports'] as $val) {
            $less->addImportDir($val);
        }
    }
    // Set output formatter
    if (isset($config['formatter'])) {
        $less->setFormatter($config['formatter']);
    }
    // Preserve comments
    if (isset($config['comments'])) {
        $less->setPreserveComments($config['comments']);
    }
    // Compile a new cache
    $newCache = $less->cachedCompile($cache);
    if (!is_array($cache) || $newCache["updated"] > $cache["updated"]) {
        file_put_contents($cacheFile, serialize($newCache));
        file_put_contents($outputFile, $newCache['compiled']);
    }
}