示例#1
0
文件: Data.php 项目: mygento/minify
 /**
  * Merge specified files into one
  *
  * By default will not merge, if there is already merged file exists and it
  * was modified after its components
  * If target file is specified, will attempt to write merged contents into it,
  * otherwise will return merged content
  * May apply callback to each file contents. Callback gets parameters:
  * (<existing system filename>, <file contents>)
  * May filter files by specified extension(s)
  * Returns false on error
  *
  * @param array $srcFiles
  * @param string|false $targetFile - file path to be written
  * @param bool $mustMerge
  * @param callback $beforeMergeCallback
  * @param array|string $extensionsFilter
  * @return bool|string
  */
 public function mergeFiles(array $srcFiles, $targetFile = false, $mustMerge = false, $beforeMergeCallback = null, $extensionsFilter = array())
 {
     $content_type = pathinfo($targetFile, PATHINFO_EXTENSION);
     if (!Mage::getStoreConfig('minify/general/enabled') || $content_type != 'css' && $content_type != 'js') {
         return parent::mergeFiles($srcFiles, $targetFile, $mustMerge, $beforeMergeCallback, $extensionsFilter);
     }
     if (!Mage::getStoreConfig('minify/general/' . $content_type)) {
         return parent::mergeFiles($srcFiles, $targetFile, $mustMerge, $beforeMergeCallback, $extensionsFilter);
     }
     try {
         $shouldMinify = $this->shouldMinify($mustMerge, $targetFile, $srcFiles);
         if ($shouldMinify) {
             $result = parent::mergeFiles($srcFiles, false, $mustMerge, $beforeMergeCallback, $extensionsFilter);
             Varien_Profiler::start('minify_file_' . $targetFile);
             switch ($content_type) {
                 case 'css':
                     $minifier = new MatthiasMullie\Minify\CSS($result);
                     break;
                 case 'js':
                     $minifier = new MatthiasMullie\Minify\JS($result);
                     break;
             }
             $minifier->minify($targetFile);
             Varien_Profiler::stop('minify_file_' . $targetFile);
         }
         return true;
     } catch (Exception $e) {
         Mage::logException($e);
     }
     return false;
 }
示例#2
0
 public static function url($files)
 {
     $ident = self::ident($files);
     if (!\SYSTEM\CACHE\cache_js::get($ident)) {
         \LIB\lib_minify::php();
         $minifier = new \MatthiasMullie\Minify\JS();
         foreach ($files as $f) {
             $minifier->add($f->SERVERPATH());
         }
         \SYSTEM\CACHE\cache_js::put($ident, $minifier->minify());
     }
     return './api.php?call=cache&id=' . self::CACHE_JS . '&ident=' . $ident;
 }
 public static function createConfigJs($objConfig, $debug = false)
 {
     if (!static::isJQueryEnabled()) {
         return false;
     }
     $cache = !$GLOBALS['TL_CONFIG']['debugMode'];
     $objT = new \FrontendTemplate('jquery.slick');
     $arrData = static::createConfig($objConfig);
     $objT->setData($arrData['config']);
     $objT->config = static::createConfigJSON($objConfig);
     $objT->selector = static::getSlickContainerSelectorFromModel($objConfig);
     $objT->wrapperClass = static::getSlickCssClassFromModel($objConfig);
     if ($objConfig->initCallback) {
         $objT->initCallback = $objConfig->initCallback;
     }
     if ($objConfig->afterInitCallback) {
         $objT->afterInitCallback = $objConfig->afterInitCallback;
     }
     $strFile = 'assets/js/' . $objT->wrapperClass . '.js';
     $strFileMinified = 'assets/js/' . $objT->wrapperClass . '.min.js';
     $objFile = new \File($strFile, file_exists(TL_ROOT . '/' . $strFile));
     $objFileMinified = new \File($strFileMinified, file_exists(TL_ROOT . '/' . $strFileMinified));
     $minify = $cache && class_exists('\\MatthiasMullie\\Minify\\JS');
     // simple file caching
     if (static::doRewrite($objConfig, $objFile, $objFileMinified, $cache, $debug)) {
         $strChunk = $objT->parse();
         $objFile->write($objT->parse());
         $objFile->close();
         // minify js
         if ($minify) {
             $objFileMinified = new \File($strFileMinified);
             $objMinify = new \MatthiasMullie\Minify\JS();
             $objMinify->add($strChunk);
             $objFileMinified->write(rtrim($objMinify->minify(), ";") . ";");
             // append semicolon, otherwise "(intermediate value)(...) is not a function"
             $objFileMinified->close();
         }
     }
     $GLOBALS['TL_JAVASCRIPT']['slick'] = 'system/modules/slick/assets/vendor/slick-carousel/slick/slick' . ($cache ? '.min.js|static' : '.js');
     $GLOBALS['TL_JAVASCRIPT']['slick-functions'] = 'system/modules/slick/assets/js/jquery.slick-functions' . ($cache ? '.min.js|static' : '.js');
     $GLOBALS['TL_JAVASCRIPT'][$objT->wrapperClass] = $minify ? $strFileMinified . '|static' : $strFile;
 }
示例#4
0
文件: minify.php 项目: dg711/moodle
    /**
     * Minify JS code.
     *
     * @param string $content
     * @return string minified JS code
     */
    public static function js($content)
    {
        try {
            $minifier = new MatthiasMullie\Minify\JS($content);
            return $minifier->minify();
        } catch (Exception $e) {
            ob_end_clean();
            $error = $e->getMessage();
        }
        $return = <<<EOD

try {console.log('Error: Minimisation of JavaScript failed!');} catch (e) {}

// Error: {$error}
// Problem detected during JavaScript minimisation, please review the following code
// =================================================================================


EOD;
        return $return . $content;
    }
 public static function createConfigJs($objConfig, $debug = false)
 {
     if (!static::isJQueryEnabled()) {
         return false;
     }
     $objInstance = new static($objConfig);
     $cache = !$GLOBALS['TL_CONFIG']['debugMode'];
     $objT = new \FrontendTemplate('datamap.defaults');
     $objT->config = $objInstance->getConfigJs();
     $objT->bubbles = $objInstance->getConfigBubblesJs();
     $objT->states = $objInstance->getConfigStateJs();
     $objT->cssID = static::getCssIDFromModel($objConfig);
     $strName = $objT->cssID;
     $strFile = 'assets/js/' . $strName . '.js';
     $strFileMinified = 'assets/js/' . $strName . '.min.js';
     $objFile = new \File($strFile, file_exists(TL_ROOT . '/' . $strFile));
     $objFileMinified = new \File($strFileMinified, file_exists(TL_ROOT . '/' . $strFileMinified));
     $minify = $cache && class_exists('\\MatthiasMullie\\Minify\\JS');
     // simple file caching
     if (static::doRewrite($objConfig, $objFile, $objFileMinified, $cache, $debug)) {
         $strChunk = $objT->parse();
         $objFile->write($objT->parse());
         $objFile->close();
         // minify js
         if ($minify) {
             $objFileMinified = new \File($strFileMinified);
             $objMinify = new \MatthiasMullie\Minify\JS();
             $objMinify->add($strChunk);
             $objFileMinified->write(rtrim($objMinify->minify(), ";") . ";");
             // append semicolon, otherwise "(intermediate value)(...) is not a function"
             $objFileMinified->close();
         }
     }
     $GLOBALS['TL_JAVASCRIPT']['d3.js'] = 'system/modules/datamaps/assets/vendor/d3/d3' . (!$GLOBALS['TL_CONFIG']['debugMode'] ? '.min' : '') . '.js|static';
     $GLOBALS['TL_JAVASCRIPT']['topojson'] = 'system/modules/datamaps/assets/vendor/topojson/topojson.js|static';
     $GLOBALS['TL_JAVASCRIPT']['datamaps.all'] = 'system/modules/datamaps/assets/vendor/datamaps/dist/datamaps.all' . ($GLOBALS['TL_CONFIG']['debugMode'] ? '.min' : '') . '.js|static';
     $GLOBALS['TL_JAVASCRIPT'][$strName] = $minify ? $strFileMinified . '|static' : $strFile;
 }
 /**
  * Get file information
  *
  * @param string $fileName The file name
  * @param string $targetIe Target IE of file
  * @param string $media Media of file
  * @param bool $forceMinify Whether this file should be minified
  * @return stdClass The file information
  */
 private function getFileInfo($fileName, $targetIe = '', $media = 'all', $forceMinify = false)
 {
     static $existsInfo = array();
     if (self::$minify === null) {
         self::$minify = Context::getDBInfo()->minify_scripts ?: 'common';
     }
     if (isset($existsInfo[$existsKey])) {
         return $existsInfo[$existsKey];
     }
     $pathInfo = pathinfo($fileName);
     $file = new stdClass();
     $file->fileName = $pathInfo['basename'];
     $file->filePath = $this->_getAbsFileUrl($pathInfo['dirname']);
     $file->fileRealPath = FileHandler::getRealPath($pathInfo['dirname']);
     $file->fileExtension = strtolower($pathInfo['extension']);
     if (preg_match('/^(.+)\\.min$/', $pathInfo['filename'], $matches)) {
         $file->fileNameNoExt = $matches[1];
         $file->isMinified = true;
     } else {
         $file->fileNameNoExt = $pathInfo['filename'];
         $file->isMinified = false;
     }
     $file->isExternalURL = preg_match('@^(https?:)?//@i', $file->filePath) ? true : false;
     $file->isCachedScript = !$file->isExternalURL && strpos($file->filePath, 'files/cache/') !== false;
     $file->keyName = $file->fileNameNoExt . '.' . $file->fileExtension;
     $file->cdnPath = $this->_normalizeFilePath($pathInfo['dirname']);
     $originalFilePath = $file->fileRealPath . '/' . $pathInfo['basename'];
     // Fix incorrectly minified URL
     if ($file->isMinified && !$file->isExternalURL && (!file_exists($originalFilePath) || is_link($originalFilePath) || filesize($originalFilePath) < 32 && trim(file_get_contents($originalFilePath)) === $file->keyName)) {
         if (file_exists($file->fileRealPath . '/' . $file->fileNameNoExt . '.' . $file->fileExtension)) {
             $file->fileName = $file->fileNameNoExt . '.' . $file->fileExtension;
             $file->isMinified = false;
             $originalFilePath = $file->fileRealPath . '/' . $file->fileNameNoExt . '.' . $file->fileExtension;
         }
     }
     // Decide whether to minify this file
     if (self::$minify === 'all') {
         $minify_enabled = true;
     } elseif (self::$minify === 'none') {
         $minify_enabled = false;
     } else {
         $minify_enabled = $forceMinify;
     }
     // Minify file
     if ($minify_enabled && !$file->isMinified && !$file->isExternalURL && !$file->isCachedScript && strpos($file->filePath, 'common/js/plugins') === false) {
         if (($file->fileExtension === 'css' || $file->fileExtension === 'js') && file_exists($originalFilePath)) {
             $minifiedFileName = $file->fileNameNoExt . '.min.' . $file->fileExtension;
             $minifiedFileHash = ltrim(str_replace(array('/', '\\'), '.', $pathInfo['dirname']), '.');
             $minifiedFilePath = _XE_PATH_ . 'files/cache/minify/' . $minifiedFileHash . '.' . $minifiedFileName;
             if (!file_exists($minifiedFilePath) || filemtime($minifiedFilePath) < filemtime($originalFilePath)) {
                 if ($file->fileExtension === 'css') {
                     $minifier = new MatthiasMullie\Minify\CSS($originalFilePath);
                     $content = $minifier->execute($minifiedFilePath);
                 } else {
                     $minifier = new MatthiasMullie\Minify\JS($originalFilePath);
                     $content = $minifier->execute($minifiedFilePath);
                 }
                 FileHandler::writeFile($minifiedFilePath, $content);
             }
             $file->fileName = $minifiedFileHash . '.' . $minifiedFileName;
             $file->filePath = $this->_getAbsFileUrl('./files/cache/minify');
             $file->fileRealPath = _XE_PATH_ . 'files/cache/minify';
             $file->keyName = $minifiedFileHash . '.' . $file->fileNameNoExt . '.' . $file->fileExtension;
             $file->cdnPath = $this->_normalizeFilePath('./files/cache/minify');
             $file->isMinified = true;
         }
     }
     // Process targetIe and media attributes
     $file->targetIe = $targetIe;
     if ($file->fileExtension == 'css') {
         $file->media = $media;
         if (!$file->media) {
             $file->media = 'all';
         }
         $file->key = $file->filePath . $file->keyName . "\t" . $file->targetIe . "\t" . $file->media;
     } else {
         if ($file->fileExtension == 'js') {
             $file->key = $file->filePath . $file->keyName . "\t" . $file->targetIe;
         }
     }
     return $file;
 }
示例#7
0
 /**
  * Minify JS.
  * 
  * @param string|array $source_filename
  * @param string $target_filename
  * @return bool
  */
 public static function minifyJS($source_filename, $target_filename)
 {
     $minifier = new \MatthiasMullie\Minify\JS();
     if (is_array($source_filename)) {
         foreach ($source_filename as $filename) {
             $minifier->add($filename);
         }
     } else {
         $minifier->add($source_filename);
     }
     $content = $minifier->execute($target_filename);
     Storage::write($target_filename, $content);
     return strlen($content) ? true : false;
 }
 public function compress_js_action($full_path)
 {
     if (is_file($full_path)) {
         $file_size_before = filesize($full_path);
         if (function_exists('exec') && exec('command -v java >/dev/null && echo "yes" || echo "no"') == 'yes') {
             file_put_contents($full_path . '.log', date('c') . " - COMPRESSING JS WITH CLOSURE\n", FILE_APPEND);
             // Remove Javascript String Continuations
             $contents = file_get_contents($full_path);
             if (strpos($contents, "\\" . PHP_EOL) !== FALSE) {
                 //only remove continuations if they exist
                 $contents = preg_replace('#\\\\(\\n|\\r\\n?)#', '', $contents);
                 file_put_contents($full_path, $contents);
             }
             $cmd = 'java -jar \'' . WP_PLUGIN_DIR . '/merge-minify-refresh/closure-compiler.jar\' --language_in ECMASCRIPT5 --warning_level QUIET --js \'' . $full_path . '\' --js_output_file \'' . $full_path . '.tmp\'';
             exec($cmd . ' 2>&1', $output);
             if (count($output) == 0) {
                 $min_path = str_replace('.js', '.min.js', $full_path);
                 rename($full_path . '.tmp', $min_path);
                 $file_size_after = filesize($min_path);
                 file_put_contents($full_path . '.log', date('c') . " - COMPRESSION COMPLETE - " . $this->human_filesize($file_size_before - $file_size_after) . " saved\n", FILE_APPEND);
             } else {
                 ob_start();
                 var_dump($output);
                 $error = ob_get_contents();
                 ob_end_clean();
                 file_put_contents($full_path . '.log', date('c') . " - COMPRESSION FAILED\n" . $error, FILE_APPEND);
                 unlink($full_path . '.tmp');
             }
         } else {
             require_once 'Minify/Minify.php';
             require_once 'Minify/CSS.php';
             require_once 'Minify/Converter.php';
             require_once 'Minify/Exception.php';
             require_once 'Minify/JS.php';
             file_put_contents($full_path . '.log', date('c') . " - COMPRESSING WITH MINIFY (PHP exec not available)\n", FILE_APPEND);
             $minifier = new MatthiasMullie\Minify\JS($full_path);
             $min_path = str_replace('.js', '.min.js', $full_path);
             $minifier->minify($min_path);
             $file_size_after = filesize($min_path);
             file_put_contents($full_path . '.log', date('c') . " - COMPRESSION COMPLETE - " . $this->human_filesize($file_size_before - $file_size_after) . " saved\n", FILE_APPEND);
         }
     }
 }
示例#9
0
 /**
  * Minify and concatenate JS files.
  *
  * @param string $group
  *
  * @return string
  */
 protected function pipelineJs($group = 'head')
 {
     // temporary list of assets to pipeline
     $temp_js = [];
     // clear no-pipeline assets lists
     $this->js_no_pipeline = [];
     // Compute uid based on assets and timestamp
     $uid = md5(json_encode($this->js) . $this->js_minify . $group);
     $file = $uid . '.js';
     $inline_file = $uid . '-inline.js';
     $relative_path = "{$this->base_url}{$this->assets_url}/{$file}";
     // If inline files exist set them on object
     if (file_exists($this->assets_dir . $inline_file)) {
         $this->js_no_pipeline = json_decode(file_get_contents($this->assets_dir . $inline_file), true);
     }
     // If pipeline exist return it
     if (file_exists($this->assets_dir . $file)) {
         return $relative_path . $this->getTimestamp();
     }
     // Remove any non-pipeline files
     foreach ($this->js as $id => $asset) {
         if ($asset['group'] == $group) {
             if (!$asset['pipeline'] || $asset['remote'] && $this->js_pipeline_include_externals === false) {
                 $this->js_no_pipeline[] = $asset;
             } else {
                 $temp_js[$id] = $asset;
             }
         }
     }
     //if nothing found get out of here!
     if (count($temp_js) == 0) {
         return false;
     }
     // Write non-pipeline files out
     if (!empty($this->js_no_pipeline)) {
         file_put_contents($this->assets_dir . $inline_file, json_encode($this->js_no_pipeline));
     }
     // Concatenate files
     $buffer = $this->gatherLinks($temp_js, JS_ASSET);
     if ($this->js_minify) {
         $minifier = new \MatthiasMullie\Minify\JS();
         $minifier->add($buffer);
         $buffer = $minifier->minify();
     }
     // Write file
     if (strlen(trim($buffer)) > 0) {
         file_put_contents($this->assets_dir . $file, $buffer);
         return $relative_path . $this->getTimestamp();
     } else {
         return false;
     }
 }
示例#10
0
$app->view->setTemplatesDirectory("../Onboard/view");
/******************************************* THE CONFIGS *******************************************************/
// Configs for mode "development" (Slim's default), see the GitHub readme for details on setting the environment
$app->configureMode('development', function () use($app) {
    // pre-application hook, performs stuff before real action happens @see http://docs.slimframework.com/#Hooks
    $app->hook('slim.before', function () use($app) {
        // SASS-to-CSS compiler @see https://github.com/panique/php-sass
        SassCompiler::run("scss/", "css/");
        // CSS minifier @see https://github.com/matthiasmullie/minify
        $minifier = new MatthiasMullie\Minify\CSS('css/style.css');
        $minifier->minify('css/style.css');
        // JS minifier @see https://github.com/matthiasmullie/minify
        // DON'T overwrite your real .js files, always save into a different file
        $minifier = new MatthiasMullie\Minify\JS('js/index-page.js');
        $minifier->minify('js/index-page.minified.js');
        $minifier = new MatthiasMullie\Minify\JS('js/search-properties.js');
        $minifier->minify('js/search-properties.minified.js');
    });
    // Set the configs for development environment
    // Get Onboard Property API Key here, https://developer.onboard-apis.com/
    $app->config(array('debug' => true, 'obpropapi' => array('api_url' => 'https://search.onboard-apis.com/propertyapi/v1.0.0/', 'api_key' => 'Insert Your Onboard Property API Key')));
});
/******************************************** THE MODEL ********************************************************/
// Initialize the model, pass the api configs. $model can now perform all methods from Onboard\model\model.php
$model = new \Onboard\Model\Model($app->config('obpropapi'));
/************************************ THE ROUTES / CONTROLLERS *************************************************/
// GET request on homepage, simply show the view template index.twig
$app->get('/', function () use($app) {
    $app->render('index.twig');
});
// GET requests on /property-records
示例#11
0
 /**
  * import common .js and .css files for (both desktop and mobile)
  */
 private function _loadCommonJSCSS()
 {
     Context::loadFile(array('./common/css/xe.css', '', '', -1600000), true);
     $original_file_list = array('x', 'common', 'js_app', 'xml_handler', 'xml_js_filter');
     $jquery_version = preg_match('/MSIE [5-8]\\./', $_SERVER['HTTP_USER_AGENT']) ? '1.11.3' : '2.1.4';
     if (config('view.minify_scripts') === 'none') {
         Context::loadFile(array('./common/js/jquery-' . $jquery_version . '.js', 'head', '', -1730000), true);
         Context::loadFile(array('./common/js/plugins/jquery.migrate/jquery-migrate-1.2.1.js', 'head', '', -1720000), true);
         foreach ($original_file_list as $filename) {
             Context::loadFile(array('./common/js/' . $filename . '.js', 'head', '', -1700000), true);
         }
     } else {
         Context::loadFile(array('./common/js/jquery-' . $jquery_version . '.min.js', 'head', '', -1730000), true);
         Context::loadFile(array('./common/js/plugins/jquery.migrate/jquery-migrate-1.2.1.min.js', 'head', '', -1720000), true);
         $concat_target_filename = 'files/cache/minify/xe.min.js';
         if (file_exists(_XE_PATH_ . $concat_target_filename)) {
             $concat_target_mtime = filemtime(_XE_PATH_ . $concat_target_filename);
             $original_mtime = 0;
             foreach ($original_file_list as $filename) {
                 $original_mtime = max($original_mtime, filemtime(_XE_PATH_ . 'common/js/' . $filename . '.js'));
             }
             if ($concat_target_mtime > $original_mtime) {
                 Context::loadFile(array('./' . $concat_target_filename, 'head', '', -100000), true);
                 return;
             }
         }
         $minifier = new MatthiasMullie\Minify\JS();
         foreach ($original_file_list as $filename) {
             $minifier->add(_XE_PATH_ . 'common/js/' . $filename . '.js');
         }
         FileHandler::writeFile(_XE_PATH_ . $concat_target_filename, $minifier->execute());
         Context::loadFile(array('./' . $concat_target_filename, 'head', '', -100000), true);
     }
 }
示例#12
0
 protected function parseExtJs($objLayout, &$arrReplace)
 {
     $arrJs = array();
     $objJs = ExtJsModel::findMultipleByIds(deserialize($objLayout->extjs));
     if ($objJs === null) {
         return false;
     }
     $cache = !$GLOBALS['TL_CONFIG']['debugMode'];
     while ($objJs->next()) {
         $objFiles = ExtJsFileModel::findMultipleByPid($objJs->id);
         if ($objFiles === null) {
             continue;
         }
         $strChunk = '';
         $strFile = 'assets/js/' . $objJs->title . '.js';
         $strFileMinified = str_replace('.js', '.min.js', $strFile);
         $objGroup = new \File($strFile, file_exists(TL_ROOT . '/' . $strFile));
         $objGroupMinified = new \File($strFileMinified, file_exists(TL_ROOT . '/' . $strFile));
         $rewrite = $objJs->tstamp > $objGroup->mtime || $objGroup->size == 0 || $cache && $objGroupMinified->size == 0;
         while ($objFiles->next()) {
             $objFileModel = \FilesModel::findByPk($objFiles->src);
             if ($objFileModel === null || !file_exists(TL_ROOT . '/' . $objFileModel->path)) {
                 continue;
             }
             $objFile = new \File($objFileModel->path);
             $strChunk .= $objFile->getContent() . "\n";
             if ($objFile->mtime > $objGroup->mtime) {
                 $rewrite = true;
             }
         }
         // simple file caching
         if ($rewrite) {
             $objGroup->write($strChunk);
             $objGroup->close();
             // minify js
             if ($cache) {
                 $objGroup = new \File($strFileMinified);
                 $objMinify = new \MatthiasMullie\Minify\JS();
                 $objMinify->add($strChunk);
                 $objGroup->write(rtrim($objMinify->minify(), ";") . ";");
                 // append semicolon, otherwise "(intermediate value)(...) is not a function"
                 $objGroup->close();
             }
         }
         $arrJs[] = $cache ? "{$strFileMinified}|static" : "{$strFile}";
     }
     // HOOK: add custom css
     if (isset($GLOBALS['TL_HOOKS']['parseExtJs']) && is_array($GLOBALS['TL_HOOKS']['parseExtJs'])) {
         foreach ($GLOBALS['TL_HOOKS']['parseExtJs'] as $callback) {
             $arrJs = static::importStatic($callback[0])->{$callback}[1]($arrJs);
         }
     }
     if ($objJs->addBootstrap) {
         $this->addTwitterBootstrap();
     }
     // inject extjs before other plugins, otherwise bootstrap may not work
     $GLOBALS['TL_JAVASCRIPT'] = is_array($GLOBALS['TL_JAVASCRIPT']) ? array_merge($GLOBALS['TL_JAVASCRIPT'], $arrJs) : $arrJs;
 }
示例#13
0
 /**
  * Returns the minified version of the content.
  * Attention: this is only a easy minifing method!
  * 
  * @access protected
  * @param string $type
  * @param string $content
  * @return string
  */
 protected function minifyContent($type, $content)
 {
     $minifier = null;
     if ($type === AssetManager::CSS) {
         $minifier = new \MatthiasMullie\Minify\CSS($content);
     } else {
         if ($type === AssetManager::JS) {
             $minifier = new \MatthiasMullie\Minify\JS($content);
         }
     }
     if ($minifier !== null) {
         return $minifier->minify();
     }
     return $content;
 }
function hm_custom_css_js_publish()
{
    if (!current_user_can('edit_theme_options') || empty($_POST['mode']) || !isset($_POST['rev']) || !is_numeric($_POST['rev'])) {
        wp_send_json_error();
    }
    $_POST['mode'] = strtolower($_POST['mode']);
    if ($_POST['mode'] != 'css' && $_POST['mode'] != 'javascript') {
        wp_send_json_error();
    }
    $post = get_post($_POST['rev']);
    if ($post->post_type != 'hm_custom_' . $_POST['mode']) {
        wp_send_json_error();
    }
    $uploadDir = wp_upload_dir();
    if (!is_dir($uploadDir['basedir'] . '/hm_custom_css_js')) {
        mkdir($uploadDir['basedir'] . '/hm_custom_css_js') or wp_send_json_error();
    }
    $outputFile = $uploadDir['basedir'] . '/hm_custom_css_js/custom.' . ($_POST['mode'] == 'css' ? 'css' : 'js');
    if (file_put_contents($outputFile, $post->post_content) === false) {
        wp_send_json_error();
    }
    if (empty($_POST['minify'])) {
        update_option('hm_custom_' . $_POST['mode'] . '_minify', false);
    } else {
        update_option('hm_custom_' . $_POST['mode'] . '_minify', true);
        require_once __DIR__ . '/minify/src/Minify.php';
        require_once __DIR__ . '/minify/src/Exception.php';
        if ($_POST['mode'] == 'css') {
            require_once __DIR__ . '/minify/src/CSS.php';
            require_once __DIR__ . '/minify/src/Converter.php';
            $minifier = new MatthiasMullie\Minify\CSS();
        } else {
            require_once __DIR__ . '/minify/src/JS.php';
            $minifier = new MatthiasMullie\Minify\JS();
        }
        $minifier->add($outputFile);
        $minifier->minify($outputFile);
    }
    update_option('hm_custom_' . $_POST['mode'] . '_ver', time());
    // Unpublish previous revisions
    $wp_query = new WP_Query(array('post_type' => 'hm_custom_' . $_POST['mode'], 'post_status' => 'publish', 'fields' => 'ids', 'nopaging' => true));
    $posts = $wp_query->get_posts();
    foreach ($posts as $postId) {
        if (!wp_update_post(array('ID' => $postId, 'post_status' => 'draft'))) {
            wp_send_json_error();
        }
    }
    if (!wp_update_post(array('ID' => $_POST['rev'], 'post_status' => 'publish', 'post_date' => current_time('Y-m-d H:i:s')))) {
        wp_send_json_error();
    }
    wp_send_json_success();
}