public static function getSetup() { global $wgUser, $IP, $wgMemc; $isHHM = wikihowAds::isHHM(); $isABTest = wikihowAds::isABTestArticle(); $cachekey = wfMemcKey('ads_setup', intval($isHHM), intval($isABTest), WH_SITEREV); //$html = $wgMemc->get($cachekey); $html = null; if ($html === null) { $js = wfMsg('Wikihowads_setup', $isHHM, intVal($isABTest)); require_once "{$IP}/extensions/min/lib/JSMinPlus.php"; $adsClass = file_get_contents("{$IP}/extensions/wikihow/wikihowAds/wikihowAds.js"); $min = JSMinPlus::minify($adsClass . $js); $html = <<<EOHTML <!-- MediaWiki:wikihowads_setup --> <script type='text/javascript'> <!-- {$min} //--> </script> EOHTML; $wgMemc->set($cachekey, $html); } return $html; }
/** * Summarize the file registry in a way like * [ 'ext1' => 'contents', 'ext2' => 'contents' ] * * @return array */ function summarize_registry() { $summasummarum = array(); $keys = array_keys($_SESSION['files_registry']); foreach ($keys as $filename) { $summarized = ""; $last_dot_pos = strrpos($filename, "."); $ext = strtolower(substr($filename, $last_dot_pos + 1, strlen($filename) - $last_dot_pos - 1)); if (!$_SESSION['files_registry'][$filename]['good']) { unset($_SESSION['files_registry'][$filename]); echo sprintf("[Deleted] %s\n-- %s\n\n", date('H:i:s'), $filename); continue; } $summarized .= trim(file_get_contents($filename)); if (!isset($summasummarum[$ext])) { $summasummarum[$ext] = ""; } if ($ext == 'css') { $summarized = Minify_CSS::minify(file_get_contents($filename)); } else { if ($ext == 'js') { $summarized = JSMinPlus::minify(file_get_contents($filename)); } else { $summarized = trim(file_get_contents($filename)); } } $summasummarum[$ext] .= $summarized; } return $summasummarum; }
function test_JSMinPlus() { global $thisDir; $src = file_get_contents($thisDir . '/_test_files/js/condcomm.js'); $minExpected = file_get_contents($thisDir . '/_test_files/js/condcomm.min_plus.js'); $minOutput = JSMinPlus::minify($src); $passed = assertTrue($minExpected == $minOutput, 'JSMinPlus : Conditional Comments'); if (__FILE__ === realpath($_SERVER['SCRIPT_FILENAME'])) { echo "\n---Output: " . countBytes($minOutput) . " bytes\n\n{$minOutput}\n\n"; echo "---Expected: " . countBytes($minExpected) . " bytes\n\n{$minExpected}\n\n"; echo "---Source: " . countBytes($src) . " bytes\n\n{$src}\n\n\n"; } return; $src = file_get_contents($thisDir . '/_test_files/js/before.js'); $minExpected = file_get_contents($thisDir . '/_test_files/js/before.min_plus.js'); $minOutput = JSMinPlus::minify($src); $passed = assertTrue($minExpected == $minOutput, 'JSMinPlus : Overall'); if (__FILE__ === realpath($_SERVER['SCRIPT_FILENAME'])) { echo "\n---Output: " . countBytes($minOutput) . " bytes\n\n{$minOutput}\n\n"; echo "---Expected: " . countBytes($minExpected) . " bytes\n\n{$minExpected}\n\n"; echo "---Source: " . countBytes($src) . " bytes\n\n{$src}\n\n\n"; } $src = file_get_contents($thisDir . '/_test_files/js/issue74.js'); $minExpected = file_get_contents($thisDir . '/_test_files/js/issue74.min_plus.js'); $minOutput = JSMinPlus::minify($src); $passed = assertTrue($minExpected == $minOutput, 'JSMinPlus : Quotes in RegExp literals (Issue 74)'); if (__FILE__ === realpath($_SERVER['SCRIPT_FILENAME'])) { echo "\n---Output: " . countBytes($minOutput) . " bytes\n\n{$minOutput}\n\n"; echo "---Expected: " . countBytes($minExpected) . " bytes\n\n{$minExpected}\n\n"; echo "---Source: " . countBytes($src) . " bytes\n\n{$src}\n\n\n"; } }
/** * Minify JS code. * * @param string $content * @return string minified JS code */ public static function js($content) { global $CFG; require_once "{$CFG->libdir}/minify/lib/JSMinPlus.php"; try { ob_start(); // JSMinPlus just echos errors, weird... $compressed = JSMinPlus::minify($content); if ($compressed !== false) { ob_end_clean(); return $compressed; } $error = ob_get_clean(); } 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 function postprocess(&$path, &$content) { if (!class_exists('JSMinPlus')) { $dir = Templates_HTML_Postprocess::option('minify_php_dir'); require_once $dir . 'JSMin/JSMin.php'; } $content = JSMinPlus::minify($content); }
public function doProcessFile($file, $replace = false) { $optimizedContent = JSMinPlus::minify(file_get_contents($file)); if ($replace) { return parent::replaceFile($file, $optimizedContent); } else { return $optimizedContent; } }
/** */ public function apply($in, $params = []) { require_php_lib('jsminplus'); if (!class_exists('\\JSMinPlus')) { throw new Exception('Assets: class \\JSMinPlus not found'); return $in; } return \JSMinPlus::minify($in); }
public function compress($string) { // Compress the js-code $jsMinPhp = JPATH_SITE . '/components/com_scriptmerge/lib/jsminplus.php'; if (file_exists($jsMinPhp)) { include_once $jsMinPhp; if (class_exists('JSMinPlus')) { $string = JSMinPlus::minify($string); } } return $string; }
public function postprocess($path, $data, $content = null) { if (!class_exists('JSMinPlus')) { $dir = Templates_HTML_Assets_Postprocess_Minify::option('minify_php_dir'); require_once $dir . 'JSMinPlus/JSMinPlus.php'; } if ($this->filter($path, $data)) { if (empty($content)) { list($content, $path) = $this->load($path); } if (!empty($content)) { $content = JSMinPlus::minify($content); } } return array($path, $content); }
function test_JSMinPlus() { global $thisDir; $src = file_get_contents($thisDir . '/_test_files/js/condcomm.js'); $minExpected = file_get_contents($thisDir . '/_test_files/js/condcomm.min_plus.js'); $minOutput = JSMinPlus::minify($src); $passed = assertTrue($minExpected == $minOutput, 'JSMinPlus : Conditional Comments'); if (__FILE__ === realpath($_SERVER['SCRIPT_FILENAME'])) { echo "\n---Output: " . strlen($minOutput) . " bytes\n\n{$minOutput}\n\n"; echo "---Expected: " . strlen($minExpected) . " bytes\n\n{$minExpected}\n\n"; echo "---Source: " . strlen($src) . " bytes\n\n{$src}\n\n\n"; } return; $src = file_get_contents($thisDir . '/_test_files/js/before.js'); $minExpected = file_get_contents($thisDir . '/_test_files/js/before.min_plus.js'); $minOutput = JSMinPlus::minify($src); $passed = assertTrue($minExpected == $minOutput, 'JSMinPlus : Overall'); if (__FILE__ === realpath($_SERVER['SCRIPT_FILENAME'])) { echo "\n---Output: " . strlen($minOutput) . " bytes\n\n{$minOutput}\n\n"; echo "---Expected: " . strlen($minExpected) . " bytes\n\n{$minExpected}\n\n"; echo "---Source: " . strlen($src) . " bytes\n\n{$src}\n\n\n"; } $src = file_get_contents($thisDir . '/_test_files/js/issue74.js'); $minExpected = file_get_contents($thisDir . '/_test_files/js/issue74.min_plus.js'); $minOutput = JSMinPlus::minify($src); $passed = assertTrue($minExpected == $minOutput, 'JSMinPlus : Quotes in RegExp literals (Issue 74)'); if (__FILE__ === realpath($_SERVER['SCRIPT_FILENAME'])) { echo "\n---Output: " . strlen($minOutput) . " bytes\n\n{$minOutput}\n\n"; echo "---Expected: " . strlen($minExpected) . " bytes\n\n{$minExpected}\n\n"; echo "---Source: " . strlen($src) . " bytes\n\n{$src}\n\n\n"; /* test_JSMin_exception('"Hello' ,'Unterminated String' ,'JSMin_UnterminatedStringException' ,"Unterminated String: '\"Hello'"); test_JSMin_exception("return /regexp\n}" ,'Unterminated RegExp' ,'JSMin_UnterminatedRegExpException' ,"Unterminated RegExp: '/regexp\n'"); test_JSMin_exception("/* Comment " ,'Unterminated Comment' ,'JSMin_UnterminatedCommentException' ,"Unterminated Comment: '/* Comment '"); //*/ } }
public function compile() { $doc = JFactory::getDocument(); $headers = $doc->getHeadData(); $javascripts = JArrayHelper::getValue($headers, 'scripts'); $dest = JPath::clean($this->paths->get('js.compressed')); $compile = $this->params->get('minify_js', 1); $changed = (bool) $this->isJsUpdated(); JLog::add('Javascript cache changed: ' . ((bool) $changed ? 'true' : 'false'), JLog::DEBUG, $this->logger); $force = (bool) ($compile == 2); $changed = (bool) ($compile == 1 && $changed); JLog::add('Force Javascript minification: ' . ((bool) $force ? 'true' : 'false'), JLog::DEBUG, $this->logger); JLog::add('Minify Javascript: ' . ((bool) $changed ? 'true' : 'false'), JLog::DEBUG, $this->logger); $uncompressed = ''; foreach (array_keys($javascripts) as $script) { $url = new JUri($script); if (!$url->getScheme()) { $url = new JUri(JUri::base()); $url->setPath($script); } $key = str_replace(JUri::base(), JPATH_ROOT . '/', (string) $url); if (array_search($key, $this->paths->get('js.uncompressed')) !== false) { unset($headers['scripts'][$script]); if (!JFile::exists($dest) || $changed || $force) { JLog::add('Compressing: ' . $key . ' to ' . $dest, JLog::DEBUG, $this->logger); $stream = new JStream(); $stream->open($key); $response = $stream->read($stream->filesize()); $stream->close(); $uncompressed .= $response; } } } if ($uncompressed) { file_put_contents($dest, JSMinPlus::minify($uncompressed, $dest)); $this->updateCache(self::CACHEKEY . '.files.js', $this->paths->get('js.uncompressed')); } // workaround. There needs to be at least one script. if (count($headers['scripts']) == 0) { $url = str_replace(JPATH_ROOT . '/', JUri::base(), $dest); $headers['scripts'][$url] = array('mime' => 'text/javascript', 'defer' => false, 'async' => false); } $doc->setHeadData($headers); }
public function parse_string($template, $data = array(), $return = FALSE, $options = array()) { if (!is_array($options)) { $options = array(); } $options = array_merge($this->config, $options); $ci = $this->ci; $is_mx = false; if (!$return) { list($ci, $is_mx) = $this->detect_mx(); } ob_start(); $template = JSMinPlus::minify($template); $exception_message = ob_get_contents(); ob_end_clean(); if ($exception_message != '') { throw new Exception('JSMinPlus: ' . $exception_message); } return $this->output($template, $return, $ci, $is_mx); }
public function minify($js) { try { if ($this->conf->outputfilters->javascriptminifyalgorithm == "jsminplus") { $js = JSMinPlus::minify($js); } else { if ($this->conf->outputfilters->javascriptminifyalgorithm == "yuicompressor") { Minify_YUICompressor::$tempDir = PIMCORE_TEMPORARY_DIRECTORY; Minify_YUICompressor::$jarFile = PIMCORE_PATH . "/lib/Minify/yuicompressor-2.4.2.jar"; $js = Minify_YUICompressor::minifyJs($js); } else { $js = JSMin::minify($js); } } } catch (Exception $e) { Logger::error("Unable to minify javascript"); Logger::error($e); } return $js; }
protected function compress($data, $config) { switch ($config['type']) { case 'jsmin': include_once Kohana::find_file('vendor', 'JSMin'); return JSMin::minify($data); case 'jsminplus': include_once Kohana::find_file('vendor', 'jsminplus'); return JSMinPlus::minify($data); case 'packer': include_once Kohana::find_file('vendor', 'JavaScriptPacker'); $packer = new JavaScriptPacker($data, empty($config['level']) ? 'Normal' : $config['level']); return $packer->pack(); case 'yuicompressor': $options = isset($config['options']) ? $config['options'] : ''; return yuicompressor::compress($data, 'js', $options); default: throw new Kohana_User_Exception('Unknown Javascript Compression Type', 'Unknown type: ' . $config['type']); } }
/** * doExecute * * @return int */ protected function doExecute() { $path = $this->getArgument(0); $package = $this->getOption('p'); $folder = $this->console->get('asset.folder', 'asset'); if ($package = PackageHelper::getPackage($package)) { $path = $package->getDir() . '/Resources/asset/' . $path; } else { $path = WINDWALKER_PUBLIC . '/' . trim($folder, '/') . '/' . $path; } if (is_file($path)) { $files = array(new \SplFileInfo($path)); } elseif (is_dir($path)) { $files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \FilesystemIterator::FOLLOW_SYMLINKS)); } else { throw new \InvalidArgumentException('No path'); } /** @var \SplFileInfo $file */ foreach ($files as $file) { $ext = File::getExtension($file->getPathname()); if (StringHelper::endsWith($file->getBasename(), '.min.' . $ext)) { continue; } if ($ext == 'css') { $this->out('[<comment>Compressing</comment>] ' . $file); $data = \Minify_CSS_Compressor::process(file_get_contents($file)); $data = str_replace("\n", ' ', $data); } elseif ($ext == 'js') { $this->out('[<comment>Compressing</comment>] ' . $file); $data = \JSMinPlus::minify(file_get_contents($file)); $data = str_replace("\n", ';', $data); } else { continue; } $newName = $file->getPath() . '/' . File::stripExtension($file->getBasename()) . '.min.' . $ext; file_put_contents($newName, $data); $this->out('[<info>Compressed</info>] ' . $newName); } }
static function minify_javascript(&$root, $indent_string = ' ', $wrap_comment = true, $recursive = true) { include_once 'third party/jsminplus.php'; $errors = array(); foreach ($root->select('script:not-empty > "~text~"', false, $recursive, true) as $c) { try { $text = $c->text; while ($text) { $text = trim($text); if (substr($text, 0, 4) === '<!--') { $text = substr($text, 5); continue; } elseif (strtolower(substr($text, 0, 9)) === '<![cdata[') { $text = substr($text, 10); continue; } if (($end = substr($text, -3)) && ($end === '-->' || $end === ']]>')) { $text = substr($text, 0, -3); continue; } break; } if (trim($text)) { $text = JSMinPlus::minify($text); if ($wrap_comment) { $text = "<!--\n" . $text . "\n//-->"; } if ($indent_string && ($wrap_comment || strpos($text, "\n") !== false)) { $text = indent_text("\n" . $text, $c->indent(), $indent_string); } } $c->text = $text; } catch (Exception $e) { $errors[] = array($e, $c->parent->dumpLocation()); } } return $errors ? $errors : true; }
/** * Get a file's content, minified. * @param string $path The file path. * @return string The file's content, minified. */ public function executeGetMinified($path) { $manager = $this->managers()->getManagerOf('file'); if (!$manager->exists($path)) { throw new \RuntimeException('"' . $path . '" : no such file or directory', 404); } $out = $manager->read($path); if ($manager->extension($manager->filename($path)) != 'min' && false) { $ext = $manager->extension($path); switch ($ext) { case 'js': $out = \JSMinPlus::minify($out); break; case 'css': $minifier = new \CssMin(); $out = $minifier->minify($out); break; default: throw new \RuntimeException('Cannot minify "' . $path . '" : unsupported file type', 406); } } $this->responseContent->setChannel(1, $out); }
public static function minify($js, $filename='') { static $instance; // this is a singleton if(!$instance) $instance = new JSMinPlus(); return $instance->min($js, $filename); }
/** * Optimize script code * @param string $data script code * @return string optimized script code */ private function optimizeScriptCode($code) { require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'JSMinPlus.php'; $minified = JSMinPlus::minify($code); return $minified === false ? $code : $minified; }
if (file_exists($minifiedPathname) && filemtime($minifiedPathname) > filemtime($pathname)) { // Is het cache bestand up2date? echo ' "' . $filename . '" (cached) '; flush(); $minifiedSize = filesize($minifiedPathname); $fullSize = filesize($pathname); } else { // Het bestand moet (opnieuw) geminified worden echo " Processing: \"" . $filename . "\""; flush(); $script = file_get_contents($pathname); $fullSize = strlen($script); if ($type === 'css') { $minifiedScript = \CssMin::minify($script); } elseif ($type === 'javascript') { $minifiedScript = \JSMinPlus::minify($script); } else { $minifiedScript = ImageOptimizer::minify($script, $filename); } if ($minifiedScript === false) { // Is het minify proces mislukt? $minifiedScript = $script; // Gebruik dan het orginele bestand. } $minifiedSize = strlen($minifiedScript); mkdirs(dirname($minifiedPathname) . '/'); if (file_put_contents($minifiedPathname, $minifiedScript) === false) { echo "\n FAILED.\n"; exit; } }
/** * [filterDump description] * @param AssetInterface $asset [description] * @return [type] [description] */ public function filterDump(AssetInterface $asset) { $asset->setContent(\JSMinPlus::minify($asset->getContent()) . ';'); }
public function performMinification($script) { require_once "third_party/jsminplus/jsminplus.php"; $minified = \JSMinPlus::minify($script); return $minified; }
$css .= '<link rel="stylesheet" type="text/css" href="' . $cssFile . '" />'; } } /*JAVASCRIPT COMPRESS*/ $js = ''; if ($compressJS_mob) { if (!file_exists("cache/compressed-mob.js")) { require_once 'inc/jsminplus.php'; $totalFilesHandle = fopen("cache/compressfilescount-mob.txt", 'w'); $handle = fopen("cache/compressed-mob.js", 'w'); $compressedJs = ''; foreach ($jsFiles as $jsFile) { $compressedJs .= file_get_contents($jsFile) . "\n"; } if (!$onlyCombineJS_mob) { $compressedJs = JSMinPlus::minify($compressedJs); } fwrite($handle, $compressedJs); $totalFiles += count($jsFiles); fwrite($totalFilesHandle, $totalFiles); } $js = '<script type="text/javascript" src="cache/compressed-mob.js" /></script>'; } else { foreach ($jsFiles as $jsFile) { $js .= '<script type="text/javascript" src="' . $jsFile . '" /></script>'; } } /*FUNCTION FLUSHCACHE*/ function flushCache() { if (file_exists("cache/compressed-mob.css")) {
/** * Minify js code. * * @param ResponseInterface $response * * @return ResponseInterface */ protected function minifyJs(ResponseInterface $response) { $stream = Middleware::createStream(); $stream->write(JsMinify::minify((string) $response->getBody())); return $response->withBody($stream); }
/** * Implements jsminplus as alternative to closure compiler * * @param string $data Source to compress * * @return string */ private function _jsminplus($data) { require_once APPPATH . 'libraries/minify/JSMinPlus.php'; return JSMinPlus::minify($data); }
/** * Internal function for (maybe) minifying assets * * @param Type of asset to minify (css/js) * @param Contents to be minified * @param The name of the file being minified (used for logging) * @param mixed A relative path to use, if provided (for css minification) * @return String (maybe) minified contents of file */ protected function _minify($type, $contents, $filename, $rel = FALSE) { // used in case we need to return orig $contents_orig = $contents; switch ($type) { case 'js': /** * JS pre-minify hook */ if ($this->EE->extensions->active_hook('minimee_pre_minify_js')) { Minimee_helper::log('Hook `minimee_pre_minify_js` has been activated.', 3); // pass contents to be minified, and instance of self $contents = $this->EE->extensions->call('minimee_pre_minify_js', $contents, $filename, $this); if ($this->EE->extensions->end_script === TRUE) { return $contents; } // re-set $contents_orig in case we need to return $contents_orig = $contents; } // HOOK END // be sure we want to minify if ($this->config->is_yes('minify_js')) { // See if JSMinPlus was explicitly requested if ($this->config->js_library == 'jsminplus') { Minimee_helper::log('Running minification with JSMinPlus.', 3); Minimee_helper::library('jsminplus'); $contents = JSMinPlus::minify($contents); } else { if ($this->config->js_library == 'jsmin') { Minimee_helper::log('Running minification with JSMin.', 3); Minimee_helper::library('jsmin'); $contents = JSMin::minify($contents); } } } break; case 'css': /** * CSS pre-minify hook */ if ($this->EE->extensions->active_hook('minimee_pre_minify_css')) { Minimee_helper::log('Hook `minimee_pre_minify_css` has been activated.', 3); // pass contents to be minified, relative path, and instance of self $contents = $this->EE->extensions->call('minimee_pre_minify_css', $contents, $filename, $rel, $this); if ($this->EE->extensions->end_script === TRUE) { return $contents; } // copy to $contents_orig in case we need to return $contents_orig = $contents; } // HOOK END // prepend URL if relative path exists & configured to do so if ($rel !== FALSE && $this->config->is_yes('css_prepend_mode')) { Minimee_helper::library('css_urirewriter'); $contents = Minify_CSS_UriRewriter::prepend($contents, $rel . '/'); // copy to $contents_orig in case we need to return $contents_orig = $contents; } // minify if configured to do so if ($this->config->is_yes('minify_css')) { // See if CSSMin was explicitly requested if ($this->config->css_library == 'cssmin') { Minimee_helper::log('Running minification with CSSMin.', 3); Minimee_helper::library('cssmin'); $cssmin = new CSSmin(FALSE); $contents = $cssmin->run($contents); unset($cssmin); } else { if ($this->config->css_library == 'minify') { Minimee_helper::log('Running minification with Minify_CSS.', 3); Minimee_helper::library('minify'); $contents = Minify_CSS::minify($contents); } } } break; } // calculate weight loss $before = strlen($contents_orig); $after = strlen($contents); $diff = $before - $after; // quick check that contents are not empty if ($after == 0) { Minimee_helper::log('Minification has returned an empty string for `' . $filename . '`.', 2); } // did we actually reduce our file size? It's possible an already minified asset // uses a more aggressive algorithm than Minify; in that case, keep original contents if ($diff > 0) { $diff_formatted = $diff < 100 ? $diff . 'b' : round($diff / 1000, 2) . 'kb'; $change = round($diff / $before * 100, 2); Minimee_helper::log('Minification has reduced ' . $filename . ' by ' . $diff_formatted . ' (' . $change . '%).', 3); // add to our running total $this->diff_total($diff); } else { Minimee_helper::log('Minification unable to reduce ' . $filename . ', so using original content.', 3); $contents = $contents_orig; } // cleanup (leave some smaller variables because they may or may not have ever been set) unset($contents_orig); // return our (maybe) minified contents return $contents; }
function minJs($js) { return JSMinPlus::minify($js); }
function minify_js($js, $do_output, $file) { $min = JSMinPlus::minify($js); $min_file = str_replace(".js", ".min.js", $file); return place_file($min_file, $min, $do_output, $file); }
/** * Function: loadFiles() * Param: $file -> The name of the file to load * * */ function loadFiles($file) { global $script, $loaded, $loadDir; $arr = explode(',', $file); foreach ($arr as $fileN) { $fileN = trim($fileN); if (!in_array($fileN, $loaded)) { $loaded[] = $fileN; echo "Loaded File: " . $fileN . " -> "; $file = str_replace(pack("CCC", 0xef, 0xbb, 0xbf), "", file_get_contents($loadDir . '/' . $fileN)); if (!preg_match('/min\\./', $fileN)) { $result = JSMinPlus::minify($file); // $result = JSMin::minify($file); if ($result === false) { return remove_comments($file); } else { echo "OK!\n"; return $result; } } else { echo "Pass\n"; return remove_comments($file); } } } }
public static function minify($js, $filename = '') { static $instance = null; // this is a singleton if ($instance === null) { $instance = new JSMinPlus(); } return $instance->min($js, $filename); }