/**
  * Perform actual compression
  * @param $src
  * @param $out
  * @param $mode
  * @return bool
  */
 function concatListAndPack($src, $out, $mode)
 {
     if (!is_file($src) || !is_readable($src)) {
         return false;
     }
     // Concat List into one big string
     $jscode = '';
     $handle = @fopen($src, 'r');
     if ($handle) {
         while (!feof($handle)) {
             $jsline = fgets($handle, 4096);
             if (rtrim($jsline, "\n") != "") {
                 $code = file_get_contents(AJXP_INSTALL_PATH . "/" . CLIENT_RESOURCES_FOLDER . "/" . rtrim($jsline, "\n\r"));
                 if ($code) {
                     $jscode .= $code;
                 }
             }
         }
         fclose($handle);
     }
     // Pack and write to file
     require_once "packer/class.JavaScriptPacker.php";
     $packer = new JavaScriptPacker($jscode, $mode, true, false);
     $packed = $packer->pack();
     if ($mode == "None") {
         // css case, hack for I.E.
         $packed = str_replace("solid#", "solid #", $packed);
     }
     @file_put_contents($out, $packed);
     return true;
 }
Beispiel #2
0
 public function pack($file)
 {
     $file = realpath($file);
     $home = dirname(__FILE__);
     $jar = realpath("{$home}/compiler.jar");
     $java = "java";
     exec("{$java} -version", &$output, &$result);
     if ($result != 0) {
         throw new BuildException("Java not found.");
     }
     // first we pack the file using DOJO shrinksafe
     $cmd = "{$java} -jar \"{$jar}\" --js=\"{$file}\" --js_output_file=\"{$file}.tmp\"";
     exec($cmd, &$output, &$result);
     if ($result != 0) {
         throw new BuildException("Java error.");
     }
     unlink($file);
     rename("{$file}.tmp", $file);
     // after DOJO, we use the Packer to tighten it up.
     $script = file_get_contents($file);
     $packer = new JavaScriptPacker($script, 62, true, false);
     $packed = $packer->pack();
     file_put_contents($file, $packed);
     $this->log("{$file} packed.", Project::MSG_INFO);
 }
 public function filterDump(AssetInterface $asset)
 {
     $script = $asset->getContent();
     $packer = new \JavaScriptPacker($script, $this->_encoding, $this->_fastDecode, $this->_specialChars);
     $script = $packer->pack();
     $asset->setContent(str_replace(";;", ";", trim($script) . ";"));
 }
Beispiel #4
0
 /**
  * Combines, minifies and caches internal js files
  *
  * @param $files an array of internal js filenames. should be in modules/jQuery - EX: 	array('soundmanager2.js', 'jquery.omniplayer.js')
  * @param $useCache the default is to use a cached version, but for testing changes you might want to set to false
  */
 public function packedScriptSrc($files, $useCache = true)
 {
     $hash = md5(join(',', $files));
     $fileName = $hash . '.min.js';
     $dir = $this->installPath . '/js/';
     $scriptDir = '/accelsite/js/';
     $metaKey = 'accel_js_cached_packed_' . $hash;
     $externalPath = $scriptDir . $fileName;
     if ($useCache) {
         if ($cachedSrc = SiteInfo::findThis()->getMeta($metaKey, 0)) {
             if (file_exists($dir . $fileName)) {
                 return $cachedSrc;
             }
         }
     }
     foreach ($files as $src) {
         $script .= file_get_contents($this->includePath . '/modules/jQuery/' . $src) . ";";
     }
     $packer = new JavaScriptPacker($script, 'Normal', true, false);
     if (!file_exists($dir)) {
         mkdir($dir);
     }
     file_put_contents($dir . $fileName, $packer->pack() . "/*  cached:  " . date('r') . " */");
     SiteInfo::findThis()->setMeta($metaKey, $externalPath);
     return $externalPath;
 }
Beispiel #5
0
 function allowed_components()
 {
     $sOutput = '';
     $bSendPack = $this->config->item("send_pack");
     $sFileProd = $this->config->item("file_prod");
     $sFileDebug = $this->config->item("file_debug");
     $aFiels = get_filenames($sFileDebug);
     foreach ($aFiels as $sFile) {
         $aFileData = pathinfo($sFile);
         if (isset($aFileData["extension"]) && $aFileData["extension"] != "js") {
             continue;
         }
         if ($bSendPack) {
             $script = file_get_contents($sFileDebug . $sFile);
             $filemtime = @filemtime($sFileDebug . $sFile);
             $filemtimeCache = @filemtime($sFileProd . $sFile);
             $t1 = microtime(true);
             if (!$filemtimeCache || $filemtime > $filemtimeCache) {
                 $packer = new JavaScriptPacker($script, 'Normal', true, false);
                 $packed = $packer->pack();
                 file_put_contents($sFileProd . $sFile, $packed);
             }
             $t2 = microtime(true);
             $time = sprintf('%.4f', $t2 - $t1);
             $sOutput .= '/* Script ' . $sFile . ' packed in ' . $time . " s. */\n";
             $sOutput .= read_file($sFileProd . $sFile) . "\n\n";
         } else {
             $sOutput .= read_file($sFileDebug . $sFile) . "\n\n";
         }
     }
     header("Content-type: application/javascript");
     echo $sOutput;
     die;
 }
Beispiel #6
0
function pack_cQuery($chemin) {
	$flux = spip_file_get_contents($chemin);
	$flux = str_replace('jQuery', 'cQuery', $flux);

	// On ne compacte PAS deux fois (c'est inutile et en plus ca bugge)
	if (!strlen($flux)
	// mode debug des crayons
	OR _request('debug_crayons')
	// le vieil auto_compress_js
	OR ($GLOBALS['meta']['auto_compress_js'] == 'oui'
	  AND @file_exists(_DIR_RESTREINT.'inc/compacte_js.php'))
	// ou l'espace prive
	OR !function_exists('test_espace_prive')
	OR test_espace_prive())
		return $flux;

	include_spip('lib/JavaScriptPacker/class.JavaScriptPacker');
	$packer = new JavaScriptPacker($flux, 0, true, false);

	// en cas d'echec (?) renvoyer l'original
	if (strlen($t = $packer->pack()))
		return $t;

	// erreur
	spip_log('erreur de pack_js');
	return $flux;
}
Beispiel #7
0
 public function tocpjs($path)
 {
     if (!is_dir($this->devpath . $path)) {
         if (strpos(strtolower($path), '.js') == strlen($path) - 3) {
             if (file_exists($this->propath . $path) && filemtime($this->devpath . $path) < filemtime($this->propath . $path)) {
                 return;
             }
             File::creat_dir_with_filepath($this->propath . $path);
             $buffer = file_get_contents($this->devpath . $path);
             //如果传入的是JS文件则压缩
             if (!$this->needcomp) {
                 file_put_contents($this->propath . $path, $buffer);
             } else {
                 $packer = new JavaScriptPacker($buffer, 'Normal', true, false);
                 file_put_contents($this->propath . $path, $packer->pack());
             }
         } else {
             @copy($this->devpath . $path, $this->propath . $path);
         }
         return;
     }
     //如果传入的参数是目录
     $handle = File::scandir($this->devpath . $path);
     foreach ($handle as $file) {
         if ($file != '.' && $file != '..') {
             $dir = $path . '/' . $file;
             //当前文件$dir为文件目录+文件
             $this->tocpjs($dir);
         }
     }
     return;
 }
Beispiel #8
0
 public static function pack($compression = 'none', $code = '')
 {
     if (!$code) {
         throw new PHPJS_Exception('No code to pack');
         return false;
     }
     switch ($compression) {
         case 'packed':
             require_once dirname(__FILE__) . '/Pack/class.JavaScriptPacker.php';
             $packer = new JavaScriptPacker($code, 'Normal', true, false);
             $code = $packer->pack();
             break;
         case 'minified':
             require_once dirname(__FILE__) . '/Pack/jsmin.php';
             $code = JSMin::minify($code);
             break;
         case 'none':
             break;
         default:
             throw new PHPJS_Exception('No such packer: "' . $compression . '"');
             return false;
             break;
     }
     return '// Compression: ' . $compression . "\n\n" . $code;
 }
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */
function smarty_function_script($params, &$smarty)
{
    static $scripts = array();
    static $packer_loaded = false;
    /*if (!empty($params['include'])) {
    		return implode("\n", $scripts);
    	}*/
    if (!isset($scripts[$params['src']])) {
        $path = Registry::get('config.current_path');
        if (Registry::get('config.tweaks.js_compression') == true && strpos($params['src'], 'lib/') === false) {
            if (!file_exists(DIR_CACHE . $params['src'])) {
                if ($packer_loaded == false) {
                    include_once DIR_LIB . 'packer/class.JavaScriptPacker.php';
                    $packer_loaded = true;
                }
                fn_mkdir(dirname(DIR_CACHE . $params['src']));
                $packer = new JavaScriptPacker(fn_get_contents(DIR_ROOT . '/' . $params['src']));
                fn_put_contents(DIR_CACHE . $params['src'], $packer->pack());
            }
            $path = Registry::get('config.cache_path');
        }
        $scripts[$params['src']] = '<script type="text/javascript" src="' . $path . '/' . $params['src'] . '"></script>';
        // If output is captured, don't print script tag in the buffer, it will be printed directly to the screen
        if (!empty($smarty->_in_capture)) {
            $buff = array_pop($smarty->_in_capture);
            $smarty->_in_capture[] = $buff;
            $smarty->_scripts[$buff][] = $scripts[$params['src']];
            return '';
        }
        return $scripts[$params['src']];
    }
}
Beispiel #10
0
 private function _js_compress($content)
 {
     App::import('vendor', 'inc/jspacker');
     $js = new JavaScriptPacker($content, $this->_js_encode, true, false);
     $this->setEncode(0);
     return $js->pack();
 }
Beispiel #11
0
function packJavascript($version)
{
    $jsDir = 'resources/htdocs/js';
    $packFile = "{$jsDir}/packed-{$version}.js";
    $unpackFile = "{$jsDir}/unpacked-{$version}.js";
    $licenses = '';
    $allScript = '';
    $preloadFiles = array('jquery.js', 'sockso.js');
    $postloadFiles = array('init.js');
    foreach ($preloadFiles as $preloadFile) {
        $allScript .= file_get_contents("{$jsDir}/{$preloadFile}");
        $licenses .= extractLicenses($allScript);
    }
    $d = opendir($jsDir);
    $dirlist = array();
    // then read in all javascript files and pack them up
    while ($file = readdir($d)) {
        $dirlist[] = $file;
    }
    sort($dirlist);
    foreach ($dirlist as $key => $file) {
        $path = "{$jsDir}/{$file}";
        // remove old pack files
        if (preg_match('/packed-/', $file)) {
            unlink($path);
        } elseif (!in_array($file, array_merge($preloadFiles, $postloadFiles)) && substr($file, -2) == 'js' && !preg_match('/locale.\\w+/', $file)) {
            echo "Include: {$path}\n";
            $script = file_get_contents($path);
            $licenses .= extractLicenses($script);
            $allScript .= $script;
        }
    }
    foreach ($postloadFiles as $file) {
        $allScript .= file_get_contents("{$jsDir}/{$file}");
        $licenses .= extractLicenses($allScript);
    }
    // write unpacked javascript
    $f = fopen($unpackFile, 'w');
    fwrite($f, $allScript);
    fclose($f);
    // write packed javascript
    $f = fopen($packFile, 'w');
    switch (PACK_TYPE) {
        case PACK_PACKER:
            include 'lib/php/JavaScriptPacker.class.php';
            $packer = new JavaScriptPacker($allScript, 'Normal', true, false);
            fwrite($f, $licenses . $packer->pack());
            break;
        case PACK_YUI:
            fwrite($f, $allScript);
            system(sprintf('java -jar lib/dev/yuicompressor-2.4.2.jar --type js -o "%s" "%s"', $packFile, $unpackFile));
            break;
        case PACK_NONE:
            fwrite($f, $allScript);
            // not packed
            break;
    }
    fclose($f);
}
Beispiel #12
0
function combine_getArchive($aFiles, $fileType)
{
    $sDocRoot = $_SERVER['DOCUMENT_ROOT'];
    $iETag = (int) $_GET['version'];
    $sLastModified = gmdate('D, d M Y H:i:s', $iETag) . ' GMT';
    // see if the user has an updated copy in browser cache
    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $_SERVER['HTTP_IF_MODIFIED_SINCE'] == $sLastModified || isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] == $iETag) {
        header("{$_SERVER['SERVER_PROTOCOL']} 304 Not Modified");
        exit;
    }
    // create a directory for storing current and archive versions
    if (CREATE_ARCHIVE && !is_dir("{$sDocRoot}/" . ARCHIVE_FOLDER)) {
        mkdir("{$sDocRoot}/" . ARCHIVE_FOLDER);
    }
    // get code from archive folder if it exists, otherwise grab latest files, merge and save in archive folder
    if (CREATE_ARCHIVE && file_exists("{$sDocRoot}/" . ARCHIVE_FOLDER . "/{$iETag}.cache")) {
        $sCode = file_get_contents("{$sDocRoot}/" . ARCHIVE_FOLDER . "/{$iETag}.cache");
    } else {
        // get and merge code
        $sCode = '';
        $aLastModifieds = array();
        foreach ($aFiles as $sFile) {
            $aLastModifieds[] = filemtime("{$sDocRoot}/{$sFile}");
            $sCode .= file_get_contents("{$sDocRoot}/{$sFile}") . "\n";
        }
        // sort dates, newest first
        rsort($aLastModifieds);
        if (CREATE_ARCHIVE) {
            if ($iETag == $aLastModifieds[0]) {
                // check for valid etag, we don't want invalid requests to fill up archive folder
                $oFile = fopen("{$sDocRoot}/" . ARCHIVE_FOLDER . "/{$iETag}.cache", 'w');
                if (flock($oFile, LOCK_EX)) {
                    fwrite($oFile, $sCode);
                    flock($oFile, LOCK_UN);
                }
                fclose($oFile);
            } else {
                // archive file no longer exists or invalid etag specified
                header("{$_SERVER['SERVER_PROTOCOL']} 404 Not Found");
                exit;
            }
        }
    }
    // send HTTP headers to ensure aggressive caching
    header('Expires: ' . gmdate('D, d M Y H:i:s', time() + CACHE_LENGTH) . ' GMT');
    // 1 year from now
    header('Content-Type: ' . $fileType);
    header('Content-Length: ' . strlen($sCode));
    header("Last-Modified: {$sLastModified}");
    header("ETag: {$iETag}");
    header('Cache-Control: max-age=' . CACHE_LENGTH);
    // output merged code
    if (PACK == 1) {
        $packer = new JavaScriptPacker($sCode);
        $sCode = $packer->pack();
    }
    echo $sCode;
}
 protected function _compression_js($script)
 {
     $this->load->library('web_apps/JavaScriptPacker');
     //$packer = new JavaScriptPacker($script, 'Normal', true, false);
     //$packer = new JavaScriptPacker($script, 62, false, true);
     $packer = new JavaScriptPacker($script, 62, false, true);
     $packed = $packer->pack();
     return $packed;
 }
 public function compress($script_in)
 {
     try {
         $packer = new JavaScriptPacker($script_in);
     } catch (Exception $e) {
         throw new PreprocessFailureException(array('processor' => 'JavaScriptPacker'));
     }
     return $packer->pack();
 }
function compress_javascript($js)
{
    if (!class_exists('JavaScriptPacker')) {
        if ($JavaScriptPackerDir = RD::$Self->Lib('javascriptpacker')) {
            require_once $JavaScriptPackerDir . DIR_SEP . 'class.JavaScriptPacker.php';
        } else {
            throw new RDE('I need JavaScriptPacker!!! (says compress_javascript function)');
        }
    }
    $Packer = new JavaScriptPacker($js);
    return $Packer->pack();
}
Beispiel #16
0
 private function compile_files()
 {
     foreach ($this->scripts as $value) {
         $script = file_get_contents($value);
         if ($this->compress_file) {
             $packer = new JavaScriptPacker($script, 'None', false, false);
             $script = $packer->pack();
         }
         $scripts[] = $script;
     }
     return $scripts;
 }
Beispiel #17
0
 public function stimulate(&$hash)
 {
     $io = LINB::SC('IO');
     $strArr = array();
     foreach ($this->ARR as $v) {
         array_push($strArr, $io->getString(self::PATH . $v . '.js'));
     }
     $str = implode(';', $strArr);
     $packer = new JavaScriptPacker($str, 'None', false, false);
     $packed = $packer->pack();
     $io->setString(self::PACKED, $packed);
     unset($io);
     unset($packer);
 }
Beispiel #18
0
	public function __construct($node){
		$this->node=$node;
		
		if(!is_dir($node->ini['front']['cache_dir'])&& !mkdir($node->ini['front']['cache_dir'])) die('<h1>No cache directory available!</h1> <p>Please create '.$node->ini['front']['cache_dir'].' with mode 0777.</p>');
		$min_file=$node->ini['front']['cache_dir'].$node->ini['front']['js_min'];
		$re_minify=false;
		if(!file_exists($min_file)){
			if(!$node->ini['front']['debug_js']) $re_minify=true;
			$min_file_mtime=0;
		}else{
			$min_file_mtime=filemtime($min_file);
		}
		if(isset($node->ini['front']['js']) && is_array($node->ini['front']['js'])){
			foreach($node->ini['front']['js'] as $file){
				if(substr($file,0,2)!=='//' && !$node->ini['front']['debug_js']){
					if(file_exists($file) && filemtime($file) > $min_file_mtime) 
						$re_minify=true;
				}else $this->js[]=$file;
					
			}
		}else{ $re_minify=true; }
		//Reminify css if its been updated
		if($re_minify){ 
			# Include minify library
			require $node->fs_path.'lib/jsmin.php';
			$script = "";
			if(isset($node->ini['front']['js']) && is_array($node->ini['front']['js'])){
				foreach($node->ini['front']['js'] as $file){
					if(substr($file,0,2)!=='//') $script .= file_get_contents($file);
				}
			}
		
			$packer = new JavaScriptPacker($script, 'Normal', true, false);
			$packed = $packer->pack();
			//Save/Update minified version
			if(file_exists($min_file)) unlink($min_file);
			file_put_contents($min_file, $packed);
		}
		if(!$node->ini['front']['debug_js']) $this->js[]=$min_file;
		
		$html='';
		if(isset($node->query['page']))
			$toRoot=str_repeat('../',count(explode('/',$node->query['page']))-1);
		else $toRoot='';
		foreach($this->js as $file){
			$html.='<script src="'.(substr($file,0,2)!=='//' ? $toRoot : '').$file.'"></script>'."\n";
		}
		$node->page['headerHTML'][]=$html;
	}
Beispiel #19
0
function compact_files($header, $srcdir, $files, $destination_packed, $destination)
{
    $t1 = microtime(true);
    $content = '';
    foreach ($files as $src) {
        $src = "{$srcdir}/{$src}";
        $content .= file_get_contents($src);
    }
    $packer = new JavaScriptPacker($content, 'Normal', true, false);
    $packed = $header . $packer->pack();
    $t2 = microtime(true);
    $time = sprintf('%.4f', $t2 - $t1);
    echo 'script ', $destination_packed, ' packed in ', $out, ', in ', $time, ' s.', "\n";
    file_put_contents($destination_packed, $packed);
    file_put_contents($destination, $header . $content);
}
 function minifyJS()
 {
     require ROOT . 'lib/MinifyJS/class.JavaScriptPacker.php';
     $js = array_diff(scandir(ROOT . self::JS_SRC_PATH, 1), array('.', '..'));
     if (empty($js)) {
         return;
     }
     foreach ($js as $file_name) {
         $js_full_path = ROOT . self::JS_SRC_PATH . '/' . $file_name;
         $script = file_get_contents($js_full_path);
         unlink($js_full_path);
         $packer = new JavaScriptPacker($script, 'Normal', true, false);
         $packed = $packer->pack();
         file_put_contents(ROOT . self::JS_PATH . '/' . $file_name, $packed);
     }
 }
Beispiel #21
0
function compressJS($dir, $compress = 0, $sort = 0)
{
    global $lezaz;
    $pattern = "*.js";
    $vars_dir_path = $lezaz->lezaz_path($dir) . '/';
    $vars_dir_link = $lezaz->lezaz_path($dir, 1) . '/';
    $glop = glob($vars_dir_path . $pattern);
    if ($sort) {
        arsort($glop);
    } else {
        asort($glop);
    }
    foreach ($glop as $filename) {
        $fn = basename($filename);
        if (strpos('XXX' . $filename, 'Xall.js.')) {
            continue;
        }
        if ($compress == 1 || $compress == 2) {
            $Xfile .= hash_file('md5', $filename);
        } else {
            $return .= " <script type=\"text/javascript\" src=\"{$vars_dir_link}{$fn}\"></script> \n";
        }
    }
    if (file_exists($vars_dir_path . 'all.js.' . md5($Xfile) . $compress . '.js')) {
        return " <script type=\"text/javascript\" src=\"" . $vars_dir_link . 'all.js.' . md5($Xfile) . $compress . '.js' . "\"></script> \n";
    }
    if ($return) {
        return $return;
    }
    array_map('unlink', glob($vars_dir_path . "all.js.*.js"));
    // delete all mini files created by lezaz
    foreach (glob($vars_dir_path . $pattern) as $filename) {
        $fn = basename($filename);
        if ($compress == '1') {
            $jsall .= "\n\n\n/*{$fn}*/\n========================\n" . file_get_contents($filename);
        } else {
            if ($compress == '2') {
                $jsau = addslashes(file_get_contents($filename));
                $packer = new JavaScriptPacker($jsau);
                $jsau = $packer->pack();
                $jsall .= "\n\n\n/*{$fn}*/\n========================\n" . $jsau;
            }
        }
    }
    $lezaz->file->write($vars_dir_path . 'all.js.' . md5($Xfile) . $compress . '.js', $jsall);
    return " <script type=\"text/javascript\" src=\"" . $vars_dir_link . 'all.js.' . md5($Xfile) . $compress . '.js' . "\"></script> \n";
}
/**
* javascript obfuscator
* 
* @param mixed $js_code
*/
function js_obfuscator_with_php($js_code)
{
    /*ob_start();
      echo $js_code;
      $generatedoutput = ob_get_contents();
      ob_end_clean();*/
    $generatedoutput = $js_code;
    $generatedoutput = str_replace("\\\r\n", "\\n", $generatedoutput);
    $generatedoutput = str_replace("\\\n", "\\n", $generatedoutput);
    $generatedoutput = str_replace("\\\r", "\\n", $generatedoutput);
    $generatedoutput = str_replace("}\r\n", "};\r\n", $generatedoutput);
    $generatedoutput = str_replace("}\n", "};\n", $generatedoutput);
    $generatedoutput = str_replace("}\r", "};\r", $generatedoutput);
    require '../libs/packer.php-1.1/class.JavaScriptPacker.php';
    $myPacker = new JavaScriptPacker($generatedoutput, 62, true, false);
    $packed = $myPacker->pack();
    return $packed;
}
Beispiel #23
0
function do_merge($version, $src, $nobase, $compress, $viewSource)
{
    $m = new MergeSource();
    $code = $m->merge($version, $src, $nobase);
    if (!$viewSource) {
        try {
            if ($compress == "yui") {
                if ($_SERVER['SERVER_NAME'] == "localhost") {
                    $jarPath = dirname(__FILE__) . DIRECTORY_SEPARATOR . "yuicompressor-2.4.2.jar";
                    $tempFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . time();
                    $file_pointer = fopen($tempFile, "a");
                    fwrite($file_pointer, $code);
                    fclose($file_pointer);
                    $cmd = "java -jar {$jarPath} {$tempFile} --charset UTF-8 --type js";
                    exec($cmd . ' 2>&1', $raw_output);
                    $code = implode("\n", $raw_output);
                    unlink($tempFile);
                } else {
                    $post_data = "code=" . urlencode($code);
                    $url = 'http://fe.baidu.com/~g/docbeta/source/script/yuimini.php';
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    $result = curl_exec($ch);
                    $code = $result;
                }
            } else {
                if ($compress == "mini") {
                    $code = JSMin::minify($code);
                } else {
                    if ($compress == "pack") {
                        $packer = new JavaScriptPacker($code, 62, true);
                        $code = $packer->pack();
                    }
                }
            }
        } catch (Exception $e) {
        }
    }
    return $viewSource ? htmlspecialchars($code) : $code;
}
Beispiel #24
0
function compacte_js($flux) {
	// si la closure est demandee, on pourrait zapper cette etape
	// mais avec le risque, en localhost, de depasser 200ko et d'echec
	#if ($GLOBALS['meta']['auto_compress_closure'] == 'oui')
	#	return $flux;

	if (!strlen($flux))
		return $flux;
	include_spip('lib/JavascriptPacker/class.JavaScriptPacker');
	$packer = new JavaScriptPacker($flux, 0, true, false);

	// en cas d'echec (?) renvoyer l'original
	if (!strlen($t = $packer->pack())) {
		spip_log('erreur de compacte_js');
		return $flux;
	}

	return $t;
}
 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']);
     }
 }
Beispiel #26
0
/**
 * this function will output the URL to a given compressed and cached js file.
 * NOTE: if you use the util package, it will automatically insert the javascript/ subdir
 * 
 * @param string $pParams[ipackage] package the javascript file is in. this will default to: 'util'. e.g.: wiki
 * @param string $pParams[ifile] subdir and filename of the file you wish to pack and cache. e.g.: libs/jsfile.js
 * @param string $pParams[defer] includes defer='defer'
 * @param object $gBitSmarty 
 * @access public
 * @return URL to cached javascript file
 */
function smarty_function_jspack($pParams, &$gBitSmarty)
{
    // make sure we have a file to pack
    if (empty($pParams['ifile'])) {
        die;
    }
    if (empty($pParams['ipackage'])) {
        $pParams['ipackage'] = 'util';
    }
    // get the full path to the file we want to pack - insert javasscript/ into path when we're getting stuff in util
    $jsfile = constant(strtoupper($pParams['ipackage']) . '_PKG_PATH') . ($pParams['ipackage'] == 'util' ? 'javascript/' : '') . $pParams['ifile'];
    if (is_file($jsfile)) {
        // get a name for the cache file we're going to store
        $cachefile = $pParams['ipackage'] . '_' . str_replace('/', '_', $pParams['ifile']);
        require_once KERNEL_PKG_PATH . 'BitCache.php';
        $bitCache = new BitCache('javascript', TRUE);
        // if the file hasn't been packed and cached yet, we do that now.
        if (!$bitCache->isCached($cachefile, filemtime($jsfile))) {
            /*
             * params of the constructor :
             * $script:       the JavaScript to pack, string.
             * $encoding:     level of encoding, int or string :
             *                0,10,62,95 or 'None', 'Numeric', 'Normal', 'High ASCII'.
             *                default: 62.
             * $fastDecode:   include the fast decoder in the packed result, boolean.
             *                default : true.
             * $specialChars: if you have flagged your private and local variables
             *                in the script, boolean.
             *                default: false.
             */
            require_once UTIL_PKG_PATH . 'javascript/class.JavaScriptPacker.php';
            $packer = new JavaScriptPacker(file_get_contents($jsfile), 'Normal', TRUE, FALSE);
            $bitCache->writeCacheFile($cachefile, $packer->pack());
        }
        $defer = !empty($pParams['defer']) ? " defer='" . $pParams['defer'] . "'" : "";
        return '<script' . $defer . ' type="text/javascript" src="' . $bitCache->getCacheUrl($cachefile) . '"></script>';
    } else {
        return "<!-- " . tra('not a valid file: ') . $pParams['ifile'] . " -->";
    }
}
Beispiel #27
0
function admin_Template($pagecontent, $message)
{
    $packJS = get_HtmlHead();
    if (!defined('PLUGINADMIN')) {
        echo '<body class="ui-widget" style="font-size:12px;">' . '<div id="mo-admin-td" class="mo-td-content-width">' . '<noscript><div class="mo-noscript mo-td-content-width ui-state-error ui-corner-all"><div>' . getLanguageValue("error_no_javascript") . '</div></div></noscript>';
        get_Head();
        $border = "";
        if (LOGIN) {
            $border = " mo-ui-tabs";
        }
        echo '<div class="mo-td-content-width ui-tabs ui-widget ui-widget-content ui-corner-all' . $border . '" style="position:relative;">';
        if (LOGIN) {
            get_Tabs();
            echo '<div class="' . ACTION . ' mo-ui-tabs-panel ui-widget-content ui-corner-bottom mo-no-border-top">';
        }
        $menu_fix = "";
        if (is_array($pagecontent)) {
            $menu_fix = '<div id="menu-fix" class="ui-widget ui-widget-content ui-corner-right">' . '<div id="menu-fix-content" class="ui-corner-all">' . $pagecontent[1] . '</div>' . '</div>';
            $pagecontent = $pagecontent[0];
        }
        echo $pagecontent;
        if (LOGIN) {
            echo "</div>";
        }
        echo $menu_fix . "</div>" . '<div class="mo-td-content-width" id="out"></div>';
        if (LOGIN) {
            echo get_Message($message);
        }
        echo '<img class="mo-td-content-width" src="' . ICON_URL_SLICE . '" alt=" " height="1" hspace="0" vspace="0" align="left" border="0" />' . '</div>';
    } else {
        echo '<body class="ui-widget body-pluginadmin" style="font-size:12px;">' . $pagecontent;
        if (LOGIN) {
            echo get_Message($message);
        }
    }
    $javaScriptPacker = new JavaScriptPacker();
    $javaScriptPacker->echoPack($packJS);
    echo "</body></html>";
}
Beispiel #28
0
function getCurrentCommSyFunctions()
{
    global $environment;
    global $c_minimized_js;
    $path_norm = 'htdocs/javascript/jQuery/commsy/';
    $path_min = 'htdocs/javascript/jQuery/commsy_min/';
    // search normal commsy_functions
    $files_found = array();
    $pattern = '/commsy_functions_(.*?)\\.js/';
    if ($dir = opendir($path_norm)) {
        while ($file = readdir($dir)) {
            $matches = array();
            preg_match($pattern, $file, $matches);
            if (sizeof($matches) > 1) {
                $files_found[] = array('path' => $path_norm . $matches[0], 'inc_path' => 'commsy/' . $matches[0], 'version' => $matches[1]);
            }
        }
    }
    // no files found?
    if (empty($files_found)) {
        include_once 'functions/error_functions.php';
        trigger_error('commsy_functions is missing', E_USER_ERROR);
    }
    // multiple files found?
    if (sizeof($files_found) > 1) {
        $modification_time = 0;
        $temp_file = '';
        foreach ($files_found as $file) {
            $modification_time_temp = filemtime($file['path']);
            if ($modification_time < $modification_time_temp) {
                $modification_time = $modification_time_temp;
                $temp_file = $file;
            }
        }
        $files_found = array($temp_file);
    }
    // create min version if not existing or out of date
    $min_file_path = $path_min . 'commsy_functions_' . $files_found[0]['version'] . '.min.js';
    if (!file_exists($min_file_path) || filemtime($files_found[0]['path']) >= filemtime($min_file_path)) {
        include_once 'classes/external_classes/class.JavaScriptPacker.php';
        $unpacked = file_get_contents($files_found[0]['path']);
        $packer = new JavaScriptPacker($unpacked, 62, true, false);
        $packed = $packer->pack();
        unset($packer);
        if (!is_dir($path_min)) {
            mkdir($path_min);
        }
        $file_handle = fopen($min_file_path, 'w');
        fwrite($file_handle, $packed);
        fclose($file_handle);
    }
    // check for using min js version
    if (isset($c_minimized_js) && $c_minimized_js === false) {
        // use normal js
        return $files_found[0]['inc_path'];
    } else {
        // use minimized js
        return 'commsy_min/commsy_functions_' . $files_found[0]['version'] . '.min.js';
    }
    return $functions_file;
}
Beispiel #29
0
$copyright .= " * OTHER DEALINGS IN THE SOFTWARE.\n";
$copyright .= " */ \n";
$copyright .= "\n";
// Original
echo "writing " . $codedir . "/php.js...\n";
file_put_contents($codedir . "/php.js", $copyright . $total_code);
echo "writing " . $codedir . "/php.namespaced.js...\n";
$namespaced_code = surroundNamespaced($namespaced_code);
file_put_contents($codedir . "/php.namespaced.js", "" . $copyright . $namespaced_code);
// Packer
echo "writing " . $codedir . "/php.packed.js...\n";
$myPacker = new JavaScriptPacker($total_code, 'Normal', true, false);
$total_code_packed = $myPacker->pack();
file_put_contents($codedir . "/php.packed.js", $copyright . $total_code_packed);
echo "writing " . $codedir . "/php.namespaced.packed.js...\n";
$myPacker = new JavaScriptPacker($namespaced_code, 'Normal', true, false);
$total_code_packed = $myPacker->pack();
file_put_contents($codedir . "/php.namespaced.packed.js", $copyright . $total_code_packed);
// JSMIN
echo "writing " . $codedir . "/php.min.js...\n";
$total_code_min = JSMin::minify($total_code);
file_put_contents($codedir . "/php.min.js", $copyright . $total_code_min);
echo "writing " . $codedir . "/php.namespaced.min.js...\n";
$total_code_min = JSMin::minify($namespaced_code);
file_put_contents($codedir . "/php.namespaced.min.js", $copyright . $total_code_min);
/*    // Packer With newlines
    echo "writing ".$codedir."/php.packed.newline.js...\n";
    $myPacker = new JavaScriptPacker($total_code, 'None', true, false);
    $total_code_packed = str_replace("function ", "\nfunction ", $myPacker->pack());
    //$total_code_packed = str_replace("}", "}\n", $total_code_packed);
    file_put_contents($codedir."/php.packed.newline.js", $copyright.$total_code_packed);
Beispiel #30
0
/**
 * 
 * @param $urls 载入的脚本
 * @param $encode_url 需加密的脚本
 */
function parse_script($urls, $encode_url = array())
{
    $url = md5(implode(',', $urls));
    $js_url = 'public/runtime/statics/' . $url . '.js';
    $url_path = APP_ROOT_PATH . $js_url;
    if (!file_exists($url_path) || IS_DEBUG) {
        if (!file_exists(APP_ROOT_PATH . 'public/runtime/statics/')) {
            mkdir(APP_ROOT_PATH . 'public/runtime/statics/', 0777);
        }
        if (count($encode_url) > 0) {
            require_once APP_ROOT_PATH . "system/libs/javascriptpacker.php";
        }
        $js_content = '';
        foreach ($urls as $url) {
            $append_content = @file_get_contents($url) . "\r\n";
            if (in_array($url, $encode_url)) {
                $packer = new JavaScriptPacker($append_content);
                $append_content = $packer->pack();
            }
            $js_content .= $append_content;
        }
        //		require_once APP_ROOT_PATH."system/libs/javascriptpacker.php";
        //	    $packer = new JavaScriptPacker($js_content);
        //		$js_content = $packer->pack();
        @file_put_contents($url_path, $js_content);
    }
    return SITE_DOMAIN . APP_ROOT . "/" . $js_url;
}