public function minify($inPath, $outPath) { global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength; $extension = $this->getExtension($inPath); $this->output(basename($inPath) . ' -> ' . basename($outPath) . '...'); $inText = file_get_contents($inPath); if ($inText === false) { $this->error("Unable to open file {$inPath} for reading."); exit(1); } $outFile = fopen($outPath, 'w'); if (!$outFile) { $this->error("Unable to open file {$outPath} for writing."); exit(1); } switch ($extension) { case 'js': $outText = JavaScriptMinifier::minify($inText, $this->getOption('js-statements-on-own-line', $wgResourceLoaderMinifierStatementsOnOwnLine), $this->getOption('js-max-line-length', $wgResourceLoaderMinifierMaxLineLength)); break; case 'css': $outText = CSSMin::minify($inText); break; default: $this->error("No minifier defined for extension \"{$extension}\""); } fwrite($outFile, $outText); fclose($outFile); $this->output(" ok\n"); }
function outputMinfiedCached($jsContent) { global $wgScriptCacheDirectory, $wgMwEmbedVersion, $wgBaseMwEmbedPath, $wgResourceLoaderMinifierStatementsOnOwnLine; // Get the JSmin class: require_once $wgBaseMwEmbedPath . '/includes/libs/JavaScriptMinifier.php'; // Create cache directory if not exists if (!file_exists($wgScriptCacheDirectory)) { $created = @mkdir($wgScriptCacheDirectory); if (!$created) { echo "if( console ){ console.log('Error in creating cache directory: " . $wgScriptCacheDirectory . "'); }"; } } $loaderCacheFile = $wgScriptCacheDirectory . '/uiConfJs.' . $wgMwEmbedVersion . $this->getKey() . '.js'; $cacheModTime = @filemtime($loaderCacheFile); // check if there were any updates to the mwEmbedLoader file if (is_file($loaderCacheFile) && $this->lastFileModTime < $cacheModTime) { echo file_get_contents($loaderCacheFile); } else { $jsMinContent = JavaScriptMinifier::minify($jsContent, $wgResourceLoaderMinifierStatementsOnOwnLine); if (!@file_put_contents($loaderCacheFile, $jsMinContent)) { echo "if( console ){ console.log('Error in creating loader cache: " . $wgScriptCacheDirectory . "'); }"; } echo $jsMinContent; } }
/** * Get contents of a javascript file for inline use. * * Roughly based MediaWiki core methods: * - ResourceLoader::filter() * - ResourceLoaderFileModule::readScriptFiles() * * @param string $name Path to file relative to /modules/inline/ * @return string Minified script * @throws Exception If file doesn't exist */ protected static function getInlineScript($name) { // Get file $filePath = __DIR__ . '/../../modules/inline/' . $name; if (!file_exists($filePath)) { throw new Exception(__METHOD__ . ": file not found: \"{$filePath}\""); } $contents = file_get_contents($filePath); // Try minified from cache $key = wfMemcKey('centralauth', 'minify-js', md5($contents)); $cache = wfGetCache(CACHE_ANYTHING); $cacheEntry = $cache->get($key); if (is_string($cacheEntry)) { return $cacheEntry; } // Compute new value $result = ''; try { $result = JavaScriptMinifier::minify($contents) . "\n/* cache key: {$key} */"; $cache->set($key, $result); } catch (Exception $e) { MWExceptionHandler::logException($e); wfDebugLog('CentralAuth', __METHOD__ . ": minification failed for {$name}: {$e}"); $result = ResourceLoader::formatException($e) . "\n" . $contents; } return $result; }
/** * @dataProvider provideCases */ function testJavaScriptMinifierOutput($code, $expectedOutput) { $minified = JavaScriptMinifier::minify($code); // JSMin+'s parser will throw an exception if output is not valid JS. // suppression of warnings needed for stupid crap wfSuppressWarnings(); $parser = new JSParser(); wfRestoreWarnings(); $parser->parse($minified, 'minify-test.js', 1); $this->assertEquals($expectedOutput, $minified, "Minified output should be in the form expected."); }
/** * @dataProvider provideExponentLineBreaking * @covers JavaScriptMinifier::minify */ public function testExponentLineBreaking($num) { // Long line breaking was being incorrectly done between the base and // exponent part of a number, causing a syntax error. The line should // instead break at the start of the number. (T34548) $prefix = 'var longVarName' . str_repeat('_', 973) . '='; $suffix = ',shortVarName=0;'; $input = $prefix . $num . $suffix; $expected = $prefix . "\n" . $num . $suffix; $minified = JavaScriptMinifier::minify($input); $this->assertEquals($expected, $minified, "Line breaks must not occur in middle of exponent"); }
public function minimizeFiles($files) { $js_out = ''; foreach ($files as $file_info) { $file = $file_info[0] . '/' . $file_info[2]; $js_out .= '/* ' . $file . ' */' . "\n"; $js_out .= file_get_contents($file); } if (!defined('DEBUG') || !DEBUG) { $js_out = JavaScriptMinifier::minify($js_out); } return $js_out; }
private static function applyFilter($filter, $data, Config $config) { switch ($filter) { case 'minify-js': return JavaScriptMinifier::minify($data, $config->get('ResourceLoaderMinifierStatementsOnOwnLine'), $config->get('ResourceLoaderMinifierMaxLineLength')); case 'minify-css': return CSSMin::minify($data); } return $data; }
private static function applyFilter($filter, $data) { $data = trim($data); if ($data) { try { $data = $filter === 'minify-css' ? CSSMin::minify($data) : JavaScriptMinifier::minify($data); } catch (Exception $e) { MWExceptionHandler::logException($e); return null; } } return $data; }
function getInlinePSResource($resourcePath) { global $wgBaseMwEmbedPath, $wgScriptCacheDirectory, $wgResourceLoaderMinifierStatementsOnOwnLine; // Get the real resource path: $resourcePath = $this->getFilePath($resourcePath); // Check if path is valid and exists if (!$resourcePath) { $this->logger->log('Unable to find resource: ' . $resourcePath); return false; } if (substr($resourcePath, -2) !== 'js') { // error attempting to load a non-js file return false; } // last modified time: $lmtime = @filemtime($resourcePath); // set the cache key $cachePath = $wgScriptCacheDirectory . '/OnPage_' . md5($resourcePath) . $lmtime . 'min.js'; // check for cached version: if (is_file($cachePath)) { return file_get_contents($cachePath); } // Get the JSmin class: require_once $wgBaseMwEmbedPath . '/includes/libs/JavaScriptMinifier.php'; // get the contents inline: $jsContent = @file_get_contents($resourcePath); $jsMinContent = JavaScriptMinifier::minify($jsContent, $wgResourceLoaderMinifierStatementsOnOwnLine); // try to store the cached file: @file_put_contents($cachePath, $jsMinContent); return $jsMinContent; }
/** * Run JavaScript or CSS data through a filter, caching the filtered result for future calls. * * Available filters are: * * - minify-js \see JavaScriptMinifier::minify * - minify-css \see CSSMin::minify * * If $data is empty, only contains whitespace or the filter was unknown, * $data is returned unmodified. * * @param string $filter Name of filter to run * @param string $data Text to filter, such as JavaScript or CSS text * @param string $cacheReport Whether to include the cache key report * @return string Filtered data, or a comment containing an error message */ public function filter($filter, $data, $cacheReport = true) { // For empty/whitespace-only data or for unknown filters, don't perform // any caching or processing if (trim($data) === '' || !in_array($filter, array('minify-js', 'minify-css'))) { return $data; } // Try for cache hit // Use CACHE_ANYTHING since filtering is very slow compared to DB queries $key = wfMemcKey('resourceloader', 'filter', $filter, self::$filterCacheVersion, md5($data)); $cache = wfGetCache(CACHE_ANYTHING); $cacheEntry = $cache->get($key); if (is_string($cacheEntry)) { wfIncrStats("rl-{$filter}-cache-hits"); return $cacheEntry; } $result = ''; // Run the filter - we've already verified one of these will work try { wfIncrStats("rl-{$filter}-cache-misses"); switch ($filter) { case 'minify-js': $result = JavaScriptMinifier::minify($data, $this->config->get('ResourceLoaderMinifierStatementsOnOwnLine'), $this->config->get('ResourceLoaderMinifierMaxLineLength')); if ($cacheReport) { $result .= "\n/* cache key: {$key} */"; } break; case 'minify-css': $result = CSSMin::minify($data); if ($cacheReport) { $result .= "\n/* cache key: {$key} */"; } break; } // Save filtered text to Memcached $cache->set($key, $result); } catch (Exception $e) { MWExceptionHandler::logException($e); wfDebugLog('resourceloader', __METHOD__ . ": minification failed: {$e}"); $this->errors[] = self::formatExceptionNoComment($e); } return $result; }
/** * Runs JavaScript or CSS data through a filter, caching the filtered result for future calls. * * Available filters are: * - minify-js \see JavaScriptMinifier::minify * - minify-css \see CSSMin::minify * * If $data is empty, only contains whitespace or the filter was unknown, * $data is returned unmodified. * * @param $filter String: Name of filter to run * @param $data String: Text to filter, such as JavaScript or CSS text * @return String: Filtered data, or a comment containing an error message */ protected function filter($filter, $data) { global $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength; wfProfileIn(__METHOD__); // For empty/whitespace-only data or for unknown filters, don't perform // any caching or processing if (trim($data) === '' || !in_array($filter, array('minify-js', 'minify-css'))) { wfProfileOut(__METHOD__); return $data; } // Try for cache hit // Use CACHE_ANYTHING since filtering is very slow compared to DB queries $key = wfMemcKey('resourceloader', 'filter', $filter, self::$filterCacheVersion, md5($data)); $cache = wfGetCache(CACHE_ANYTHING); $cacheEntry = $cache->get($key); if (is_string($cacheEntry)) { wfProfileOut(__METHOD__); return $cacheEntry; } $result = ''; // Run the filter - we've already verified one of these will work try { switch ($filter) { case 'minify-js': $result = JavaScriptMinifier::minify($data, $wgResourceLoaderMinifierStatementsOnOwnLine, $wgResourceLoaderMinifierMaxLineLength); $result .= "\n/* cache key: {$key} */"; break; case 'minify-css': $result = CSSMin::minify($data); $result .= "\n/* cache key: {$key} */"; break; } // Save filtered text to Memcached $cache->set($key, $result); } catch (Exception $exception) { // Return exception as a comment $result = $this->makeComment($exception->__toString()); } wfProfileOut(__METHOD__); return $result; }
private function getMinCombinedLoaderJs() { global $wgHTTPProtocol, $wgMwEmbedVersion, $wgResourceLoaderMinifierStatementsOnOwnLine; $key = '/loader_' . $wgHTTPProtocol . '.min.' . $wgMwEmbedVersion . '.js'; $cacheJS = $this->getCacheFileContents($key); if ($cacheJS !== false) { return $cacheJS; } // Else get from files: $rawScript = $this->getCombinedLoaderJs(); // Get the JSmin class: require_once realpath(dirname(__FILE__)) . '/includes/libs/JavaScriptMinifier.php'; $minjs = JavaScriptMinifier::minify($rawScript, $wgResourceLoaderMinifierStatementsOnOwnLine); // output the file to the cache: $this->outputFileCache($key, $minjs); // return the minified js: return $minjs; }
private static function applyFilter($filter, $data, Config $config) { switch ($filter) { case 'minify-js': return JavaScriptMinifier::minify($data); case 'minify-css': return CSSMin::minify($data); } return $data; }
public function minify($inPath, $outPath) { $extension = $this->getExtension($inPath); $this->output(basename($inPath) . ' -> ' . basename($outPath) . '...'); $inText = file_get_contents($inPath); if ($inText === false) { $this->error("Unable to open file {$inPath} for reading."); exit(1); } $outFile = fopen($outPath, 'w'); if (!$outFile) { $this->error("Unable to open file {$outPath} for writing."); exit(1); } switch ($extension) { case 'js': $outText = JavaScriptMinifier::minify($inText); break; case 'css': $outText = CSSMin::minify($inText); break; default: $this->error("No minifier defined for extension \"{$extension}\""); } fwrite($outFile, $outText); fclose($outFile); $this->output(" ok\n"); }
function getInlinePSResource($resourcePath) { global $wgBaseMwEmbedPath, $wgKalturaPSHtml5SettingsPath, $wgScriptCacheDirectory, $wgResourceLoaderMinifierStatementsOnOwnLine; // Get the real resource path: $basePsPath = realpath(dirname($wgKalturaPSHtml5SettingsPath) . '/../ps/'); $resourcePath = realpath(str_replace('{html5ps}', $basePsPath, $resourcePath)); // Don't allow directory traversing: if (strpos($resourcePath, $basePsPath) !== 0) { // Error attempted directory traversal: return false; } if (substr($resourcePath, -2) !== 'js') { // error attempting to load a non-js file return false; } // last modified time: $lmtime = @filemtime($resourcePath); // set the cache key $cachePath = $wgScriptCacheDirectory . '/' . md5($resourcePath) . $lmtime . 'min.js'; // check for cached version: if (is_file($cachePath)) { return file_get_contents($cachePath); } // Get the JSmin class: require_once $wgBaseMwEmbedPath . '/includes/libs/JavaScriptMinifier.php'; // get the contents inline: $jsContent = @file_get_contents($resourcePath); $jsMinContent = JavaScriptMinifier::minify($jsContent, $wgResourceLoaderMinifierStatementsOnOwnLine); // try to store the cached file: @file_put_contents($cachePath, $jsMinContent); return $jsMinContent; }
$f = fopen($path, "w+"); flock($f, LOCK_EX); fwrite($f, $v); flock($f, LOCK_UN); fclose($f); } $header = _read(realpath('./..') . '/src/000_header.js') . "\n"; $footer = _read(realpath('./..') . '/src/999_footer.js') . "\n"; $path = realpath('./..') . '/src/'; $js = ''; foreach (array(1 => 'base', 5 => 'detect', 10 => 'polyfill', 15 => 'cls', 20 => 'math', 25 => 'date', 30 => 'util', 35 => 'local', 40 => 'network', 45 => 'style', 50 => 'css', 55 => 'key', 60 => 'event', 70 => 'win', 80 => 'query', 90 => 'dom', 100 => 'template', 110 => 'i18n', 120 => 'vali', 130 => 'ani', 140 => 'img', 150 => 'ga', 900 => 'boot') as $k => $v) { $js .= _read($path . substr('0' . $k, -3) . '_' . $v . '.js', "r") . "\n"; } _write(realpath('') . '/build.js', $header . $js . $footer); require_once dirname(__FILE__) . '/JSMin.php'; $min = JavaScriptMinifier::minify($js); _write(realpath('') . '/min.js', $header . $min . $footer); $root = isset($_GET['root']) && $_GET['root'] == 'true' ? TRUE : FALSE; switch (isset($_GET['live']) ? $_GET['live'] : 'full') { case 'min': _write(realpath('./..') . '/index.js', $header . $min . $footer); $live = 'min'; if ($root) { _write(realpath('./../..') . '/index.js', $header . $min . $footer); } break; case 'full': _write(realpath('./..') . '/index.js', $header . $js . $footer); $live = 'full'; if ($root) { _write(realpath('./../..') . '/index.js', $header . $js . $footer);