Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Big improvements to GoogleClosure and HeadScriptBundler services. And…

… some other stability bugfixes.
  • Loading branch information...
commit 5531d9eb8cec9fceb9aed215e3793a0ee5af075b 1 parent 807f362
@balupton balupton authored
View
9 lib/Bal/Locale.php
@@ -405,7 +405,7 @@ protected function _translate_advanced ( $text ) {
# Check
if ( $matches_n === 0 ) {
- throw new Bal_Exception('Translate advanced did not find what it was looking for..');
+ throw new Bal_Exception('Translate advanced did not find what it was looking for...');
}
# Cycle
@@ -424,7 +424,12 @@ protected function _translate_advanced ( $text ) {
$value = $parts[2];
} else {
$value = $match_str;
- }
+ }
+
+ # Check
+ if ( !method_exists($this, $translator) ) {
+ throw new Bal_Exception('Translate advanced was passed invalid arguments...');
+ }
# Apply the translator
$result = $this->$translator($value);
View
424 lib/Bal/Service/GoogleClosure.php
@@ -5,102 +5,274 @@
class Bal_Service_GoogleClosure {
- protected $_srcsToBeMinified = array();
+ /** The Default Compilation Level to Use **/
protected $_compilationLevel = 'SIMPLE_OPTIMIZATIONS';
+
+ /** The Default Warning Level to Use **/
protected $_warningLevel = 'DEFAULT';
- public function compile ( $paths, $path ) {
- $this->_srcsToBeMinified = $paths;
- $compiled = $this->_performRequests();
- file_put_contents($path,$compiled);
+ /**
+ * Compile a series of Files to the Output Path using the Google closure Web Service
+ **/
+ public function compile ( $files, $output_path ) {
+ $compiled = $this->getResultFromFiles($files);
+ file_put_contents($output_path,$compiled);
}
-
- protected function _readSources($sources) {
- $code = '';
- foreach ( $sources as $src ) {
- $code .= file_get_contents($src);
+
+ /**
+ * Takes a File Group to be sent, and converts it into a series of Request Groups.
+ * These Request Groups can then be sent to Google Closure
+ **/
+ protected function generateRequestGroups ( $fileGroup ) {
+ # Prepare
+ $requestGroups = array();
+ $requestGroup = array();
+ $total_size = $file_size = 0;
+ $max_size = 800*1024;
+
+ # Split into Size Groups
+ foreach ( $fileGroup as $file ) {
+ $file_path = $file['path'];
+ $file_size = filesize($file_path);
+ $total_size += $file_size;
+
+ # Reached the end of a request
+ if ( $total_size > $max_size ) {
+ # Append requestGroup to requestGroups
+ $requestGroups[] = $requestGroup;
+
+ # Reset with Current File
+ $total_size = $file_size;
+ $requestGroup = array();
+ }
+
+ # Add file to the request
+ $requestGroup[] = $file;
}
- return $code;
+
+ # Append requestGroup to requestGroups
+ $requestGroups[] = $requestGroup;
+
+ # Return requestGroups
+ return $requestGroups;
}
- protected function _getParamList ( $sources ) {
- $params = array();
- $params['js_code'] = $this->_readSources($sources);
- $params['compilation_level'] = $this->_compilationLevel;
- $params['output_format'] = 'xml';
- $params['warning_level'] = $this->_warningLevel;
- $params['use_closure_library'] = 'true';
- $params['output_info_1'] = 'compiled_code';
- $params['output_info_2'] = 'statistics';
- $params['output_info_3'] = 'warnings';
- $params['output_info_4'] = 'errors';
- return $params;
+ /**
+ * Send a Request Group to Google Closure
+ **/
+ protected function sendRequestGroup ( $request_group ) {
+ # Perform Request
+ $params = $this->generateParamsFromRequestGroup($request_group);
+ $response = $this->sendRequestViaCurl($params);
+ $result = $this->getResultFromResponse($response);
+
+ # Return result
+ return $result;
}
- protected function _getParams ( $sources ) {
- $params = array();
- $paramList = $this->_getParamList($sources);
- foreach ( $paramList as $key => $value) {
- $params[] = preg_replace('/_[0-9]$/', '', $key) . '=' . urlencode($value);
+ /**
+ * Send a File Group
+ **/
+ protected function sendFileGroup ( $file_group ) {
+ $result = '';
+
+ $request_groups = $this->generateRequestGroups($file_group);
+ foreach ( $request_groups as $request_group ) {
+ $result .= ' '.$this->sendRequestGroup($request_group);
}
- return implode('&', $params);
+
+ return $result;
}
- protected function _getSourceGroups ( ) {
- $requests = array(array());
- $currentRequest = &$requests[0];
- $requestsCount = 1;
+ /**
+ * Gets the Result by processing and sending the group of passed files
+ **/
+ protected function getResultFromFiles ( $files ) {
+ # Prepare
+ $result = '';
+ $group = array();
- $currentSize = 0;
- $sizeLimit = 500*1024;
- $filesThisRequest = array();
- foreach ( $this->_srcsToBeMinified as $src ) {
- $currentSize += filesize($src);
- if ( $currentSize > $sizeLimit ) {
- $currentSize = 0;
- $requests[] = array();
- $currentRequest = &$requests[$requestsCount++];
+ # Combine
+ foreach ( $files as $file ) {
+ if ( $file['minified'] ) {
+ $result .= ' '.$this->sendFileGroup($group); $group = array();
+ $result .= ' '.file_get_contents($file['path']);
+ }
+ else {
+ $group[] = $file;
}
- $currentRequest[] = $src;
}
- return $requests;
+ # Finish Up
+ $result .= ' '.$this->sendFileGroup($group); $group = array();
+
+ # Return result
+ return $result;
}
- protected function _sendRequestFsock ( $data ) {
- $fp = fsockopen('closure-compiler.appspot.com', 80, $errno, $errstr, 30);
-
- if ( $fp ) {
- fputs($fp, "POST /compile HTTP/1.1\r\n");
- fputs($fp, "Host: closure-compiler.appspot.com\r\n");
- fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
- fputs($fp, "Content-length: ". strlen($data) ."\r\n");
- fputs($fp, "Connection: close\r\n\r\n");
- fputs($fp, $data);
+ /**
+ * Process the Response and Return the Result
+ */
+ protected function getResultFromResponse ( $response ) {
+ # Prepare
+ $result = '';
+
+ # Check Response
+ if ( strpos($response, '<?xml') !== 0 ) {
+ # Error
+ throw new Bal_Exception(array(
+ 'Errors occurred when using the Google Closure Service.',
+ 'response' => $response
+ ));
+ }
+
+ # Process Response
+ $responseTree = $this->parseXml($response);
+ $responseValue = $responseTree[0]['value'];
+
+ # Cycle through Responses
+ foreach ( $responseValue as $node ) {
+ # Reset Response
+ $code = $originalSize = $originalGzipSize = $compressedSize = $compressedGzipSize = $compileTime = $warnings = $errors = '';
- $result = '';
- while (!feof($fp)) {
- $result .= fgets($fp, 128);
+ # Handle Tags
+ switch ( $node['tag'] ) {
+ case 'compiledCode':
+ $code = $node['value'];
+ break;
+
+ case 'warnings':
+ $warnings = $node['value'];
+ break;
+
+ case 'serverErrors':
+ case 'errors':
+ $errors = $node['value'];
+ break;
+
+ case 'statistics':
+ foreach ($node['value'] as $stat) {
+ switch ($stat['tag']) {
+ case 'originalSize':
+ case 'originalGzipSize':
+ case 'compressedSize':
+ case 'compressedGzipSize':
+ case 'compileTime':
+ $var = $stat['tag'];
+ $$var = $stat['value'];
+ break;
+
+ default:
+ break;
+ }
+ }
+ break;
}
+
+ # Append the code
+ if ( $code ) {
+ $result .= ' '.$code;
+ }
+ }
+
+ # No errors, but our result is empty - should be an error
+ if ( !$result && !$errors && !$warnings ) {
+ $errors = 'Result is empty';
+ }
+
+ # We have an error
+ if ( $errors ) {
+ $error = $this->flattenResponseDetail($errors);
+ $warning = $this->flattenResponseDetail($warnings);
+
+ # Error
+ throw new Bal_Exception(array(
+ 'Errors occurred when using the Google Closure Service.',
+ 'error' => $error,
+ 'warning' => $warning
+ ));
+ }
- fclose($fp);
+ # Return result
+ return $result;
+ }
+
+ /**
+ * Flatten a Response Detail
+ **/
+ protected function flattenResponseDetail ( $errors ) {
+ $error = '';
+ if ( is_array($errors) ) {
+ foreach ( $errors as $_error ) {
+ $error .= $_error['value'];
+ }
}
else {
- throw new Exception('Could not connect to Google Closure Service: '.$errstr.' ('.$errno.')');
+ $error = $errors;
}
+ return $error;
+ }
- $data = substr($result, (strpos($result, "\r\n\r\n")+4));
-
- if (strpos(strtolower($result), 'transfer-encoding: chunked') !== FALSE) {
- $data = $this->_unchunk($data);
+ /**
+ * Convert a Series of Params to a String ready for sending
+ **/
+ protected function generateParamsString ( $params ) {
+ # Prepare
+ $parts = array();;
+
+ # Convert Params to Parts
+ foreach ( $params as $key => $value) {
+ $parts[] = preg_replace('/_[0-9]$/', '', $key) . '=' . urlencode($value);
}
- return $data;
+ # Generate String
+ $result = implode('&', $parts);
+
+ # Return result
+ return $result;
}
- protected function _sendRequestCurl ( $data ) {
+ /**
+ * Generate a series of Params for Sending from the Group of Files
+ **/
+ protected function generateParamsFromRequestGroup ( $request_group ) {
# Prepare
- $defaults = array(
+ $params = array();
+ $compilationLevel = $this->_compilationLevel;
+
+ # Add Code
+ $params['js_code'] = '';
+ foreach ( $request_group as $file ) {
+ $file_code = file_get_contents($file['path']);
+ $params['js_code'] .= $file_code;
+ if ( !empty($file['compilationlevel']) ) {
+ $compilationLevel = $file['compilationlevel'];
+ }
+ }
+
+ # Add Params
+ $params['compilation_level'] = $compilationLevel;
+ $params['output_format'] = 'xml';
+ $params['warning_level'] = $this->_warningLevel;
+ $params['use_closure_library'] = 'true';
+ $params['output_info_1'] = 'compiled_code';
+ $params['output_info_2'] = 'statistics';
+ $params['output_info_3'] = 'warnings';
+ $params['output_info_4'] = 'errors';
+
+ # Return params
+ return $params;
+ }
+
+ /**
+ * Send the Request via CURL
+ **/
+ protected function sendRequestViaCurl ( $params ) {
+ # Generate Params String
+ $paramsString = $this->generateParamsString($params);
+
+ # Generate Options
+ $options = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_URL => 'closure-compiler.appspot.com/compile',
@@ -108,130 +280,36 @@ protected function _sendRequestCurl ( $data ) {
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 60,
- CURLOPT_POSTFIELDS => $data
+ CURLOPT_POSTFIELDS => $paramsString
);
# Open
- $ch = curl_init();
- curl_setopt_array($ch, $defaults);
+ $channel = curl_init();
+ curl_setopt_array($channel, $options);
# Perform Request
- if ( !$result = curl_exec($ch) ) {
- throw new Exception('Could not connect to Google Closure Service: '.curl_error($ch));
+ if ( !$result = curl_exec($channel) ) {
+ throw new Exception('Could not connect to Google Closure Service: '.curl_error($channel));
}
# Close Channel
- curl_close($ch);
+ curl_close($channel);
# Return result
return $result;
}
- protected function _sendRequests ( ) {
- $requests = array();
- $groups = $this->_getSourceGroups();
- $return = '';
-
- foreach ( $groups as $group ) {
- $data = $this->_getParams($group);
- // $referer = @$_SERVER['HTTP_REFERER'] or '';
-
- $data = $this->_sendRequestCurl($data);
-
- $requests[] = $data;
- }
-
- return $requests;
- }
-
- protected function _performRequests ( ) {
- $return = '';
- $requests = $this->_sendRequests();
-
- foreach ( $requests as $request ) {
- $code = $originalSize = $originalGzipSize = $compressedSize = $compressedGzipSize = $compileTime = $warnings = $errors = '';
- $tree = $this->_parseXml($request);
- $result = $tree[0]['value'];
- foreach ( $result as $node ) {
- switch ( $node['tag'] ) {
- case 'compiledCode':
- $code = $node['value'];
- break;
-
- case 'warnings':
- $warnings = $node['value'];
- break;
-
- case 'serverErrors':
- case 'errors':
- $errors = $node['value'];
- break;
-
- case 'statistics':
- foreach ($node['value'] as $stat) {
- switch ($stat['tag']) {
- case 'originalSize':
- case 'originalGzipSize':
- case 'compressedSize':
- case 'compressedGzipSize':
- case 'compileTime':
- $var = $stat['tag'];
- $$var = $stat['value'];
- break;
-
- default:
- break;
- }
- }
- break;
- }
- }
-
- if ( !$code && !$errors ) {
- $errors = 'Result is empty';
- }
-
- if ( $errors ) {
- $error = '';
- if ( is_array($errors) ) {
- foreach ( $errors as $_error ) {
- $error .= $_error['value'];
- }
- }
- else {
- $error = $errors;
- }
- throw new Exception('Errors occurred when using the Google Closure Service: '.$error);
- }
-
- $return .= $code.' ';
- }
-
- return $return;
- }
-
- protected function _unchunk($data) {
- $fp = 0;
- $outData = '';
- while ($fp < strlen($data)) {
- $rawnum = substr($data, $fp, strpos(substr($data, $fp), "\r\n") + 2);
- $num = hexdec(trim($rawnum));
- $fp += strlen($rawnum);
- $chunk = substr($data, $fp, $num);
- $outData .= $chunk;
- $fp += strlen($chunk);
- }
- return $outData;
- }
-
- protected function _parseXml($data) {
+ /**
+ * Parse a XML Response
+ **/
+ protected function parseXml($data) {
$data = str_replace('&lt;', '---LTLTLTLT---', $data);
$xml = new XMLReader();
$xml->xml($data);
- return $this->_parseXmlHelper($xml);
+ return $this->parseXmlHelper($xml);
}
- protected function _parseXmlHelper($xml) {
+ protected function parseXmlHelper($xml) {
$tree = null;
while( $xml->read() ) {
switch ( $xml->nodeType ) {
@@ -241,7 +319,7 @@ protected function _parseXmlHelper($xml) {
case XMLReader::ELEMENT:
$node = array(
'tag' => $xml->name,
- 'value' => $xml->isEmptyElement ? '' : $this->_parseXmlHelper($xml)
+ 'value' => $xml->isEmptyElement ? '' : $this->parseXmlHelper($xml)
);
if ( $xml->hasAttributes ) {
while ( $xml->moveToNextAttribute() ) {
View
65 lib/Bal/View/Helper/App.php
@@ -263,7 +263,7 @@ public function headLink ( array $options = array() ) {
case 'aloha':
# Preset Urls
- $aloha_scripts_url = $script_url.'/aloha-editor/WebContent';
+ $aloha_scripts_url = $script_url.'/aloha-nightly/compressed';
# Define Files
$aloha_scripts = array(
@@ -355,7 +355,7 @@ public function headScript ( array $options = array() ) {
if ( $bundle )
$headScript = $this->view->getHelper('HeadScriptBundler')
->setCompiler($this->getConfig('compiler.script.code'))
- ->setCompilerPath($this->getConfig('compiler.style.path'))
+ ->setCompilerPath($this->getConfig('compiler.script.path'))
->setCompiledOffset($compiled);
else
$headScript = $this->view->getHelper('HeadScript');
@@ -368,12 +368,12 @@ public function headScript ( array $options = array() ) {
# Modernizr
if ( $modernizr ) {
- $headScript->offsetSetFile($modernizr, $script_url.'/modernizr-1.5.js');
+ $headScript->offsetSetFile($modernizr, $script_url.'/modernizr-1.6.min.js');
}
# jQuery
if ( $jquery ) {
- $headScript->offsetSetFile($jquery, $script_url.'/jquery-1.4.3.js');
+ $headScript->offsetSetFile($jquery, $script_url.'/jquery-1.4.4.min.js');
}
# jQuery UI
@@ -451,68 +451,21 @@ public function headScript ( array $options = array() ) {
case 'aloha':
# Preset Urls
- $aloha_scripts_url = $script_url.'/aloha-editor/WebContent';
+ $aloha_scripts_url = $script_url.'/aloha-nightly/compressed';
$aloha_plugins_url = $script_url.'/aloha-plugins';
# Include Base Script
$headScript->offsetSetScript($editor++, 'window.GENTICS_Aloha_base = "'.$aloha_scripts_url.'/"; window.GENTICS_Aloha_autoloadcss = false;');
# Define Files
- $aloha_scripts = array(
- 'deps/jquery.json-2.2.min.js',
- 'deps/jquery.getUrlParam.js',
- 'deps/prettyPhoto/jquery.prettyPhoto.js',
- 'deps/jquery.cookie.js',
- 'deps/extjs/ext-jquery-adapter-debug.js',
- 'deps/extjs/ext-foundation-debug.js',
- 'deps/extjs/cmp-foundation-debug.js',
- 'deps/extjs/data-foundation-debug.js',
- 'deps/extjs/data-json-debug.js',
- 'deps/extjs/data-list-views-debug.js',
- 'deps/extjs/ext-dd-debug.js',
- 'deps/extjs/window-debug.js',
- 'deps/extjs/resizable-debug.js',
- 'deps/extjs/pkg-buttons-debug.js',
- 'deps/extjs/pkg-tabs-debug.js',
- 'deps/extjs/pkg-tips-debug.js',
- 'deps/extjs/pkg-tree-debug.js',
- 'deps/extjs/pkg-grid-foundation-debug.js',
- 'deps/extjs/pkg-toolbars-debug.js',
- 'deps/extjs/pkg-menu-debug.js',
- 'deps/extjs/pkg-forms-debug.js',
- 'utils/jquery.js',
- 'utils/lang.js',
- 'utils/range.js',
- 'utils/position.js',
- 'utils/dom.js',
- 'core/ext-alohaproxy.js',
- 'core/ext-alohareader.js',
- 'core/ext-alohatreeloader.js',
- 'core/core.js',
- 'core/ui.js',
- 'core/ui-attributefield.js',
- 'core/ui-browser.js',
- 'core/editable.js',
- 'core/ribbon.js',
- 'core/event.js',
- 'core/floatingmenu.js',
- 'core/ierange-m2.js',
- 'core/jquery.aloha.js',
- 'core/log.js',
- 'core/markup.js',
- 'core/message.js',
- 'core/plugin.js',
- 'core/selection.js',
- 'core/sidebar.js',
- 'core/repositorymanager.js',
- 'core/repository.js',
- 'core/repositoryobjects.js',
- 'plugins/eu.iksproject.plugins.Loader/plugin.js',
+ $aloha_scripts = array(
+ 'aloha-ext.js',
+ 'aloha-deps.js',
+ 'aloha-core.js',
'plugins/com.gentics.aloha.plugins.Format/plugin.js',
'plugins/com.gentics.aloha.plugins.Table/plugin.js',
'plugins/com.gentics.aloha.plugins.List/plugin.js',
'plugins/com.gentics.aloha.plugins.Link/plugin.js',
- // causes annoying prompt if content has changed - 'plugins/com.gentics.aloha.plugins.GCN/plugin.js',
'plugins/com.gentics.aloha.plugins.Image/plugin.js'
);
$aloha_plugins = array(
View
7 lib/Bal/View/Helper/HeadLinkBundler.php
@@ -151,7 +151,7 @@ public function toString ($indent = null) {
if ( !empty($item->source) ) {
# Generate File Name
$source = $item->source;
- $filename = md5($source).'.'.$this->_extension;
+ $filename = 'source-'.md5($source).'.'.$this->_extension;
$path = $this->getCachePath().'/'.$filename;
$url = ROOT_URL.$this->getCacheUrl().'/'.$filename;
@@ -195,8 +195,9 @@ public function toString ($indent = null) {
# Hash
$hash = md5($hash);
- $compiledFileUrl = $this->getCacheUrl().'/'.$hash.'.'.$this->_extension;
- $compiledFilePath = $this->getCachePath().'/'.$hash.'.'.$this->_extension;
+ $compiledFileName = 'compiled-'.$hash.'.'.$this->_extension;
+ $compiledFileUrl = $this->getCacheUrl().'/'.$compiledFileName;
+ $compiledFilePath = $this->getCachePath().'/'.$compiledFileName;
# Get last modified time of cache file
if ( is_file($compiledFilePath) ) {
View
106 lib/Bal/View/Helper/HeadScriptBundler.php
@@ -11,6 +11,14 @@ class Bal_View_Helper_HeadScriptBundler extends Zend_View_Helper_HeadScript {
protected $_compiler = 'closure-webservice';
protected $_compilerPath = null;
+ /**
+ * Optional allowed attributes for script tag
+ * @var array
+ */
+ protected $_optionalAttributes = array(
+ 'charset', 'defer', 'language', 'src', 'compress'
+ );
+
# =========================
# Custom: Handling
@@ -39,21 +47,38 @@ protected function getCacheUrl ( ) {
# =========================
# Custom: Compilers
- protected function compileConcat ( $paths, $path ) {
- file_put_contents($path,'');
- foreach ( $paths as $file ) {
- file_put_contents($path,file_get_contents($file),FILE_APPEND);
+ protected function compileConcat ( $files, $output_path ) {
+ file_put_contents($files,'');
+ foreach ( $files as $file ) {
+ $file_path = $file['path'];
+ file_put_contents($output_path,file_get_contents($file_path),FILE_APPEND);
}
}
- protected function compileClosureWebservice ( $paths, $path ) {
+ protected function compileClosureWebservice ( $files, $output_path ) {
$Compiler = new Bal_Service_GoogleClosure();
- $Compiler->compile($paths,$path);
+ $Compiler->compile($files,$output_path);
}
- protected function compileClosureCompiler ( $paths, $path ) {
- $command = 'java -jar '.$this->_compilerPath.' --compilation_level WHITESPACE_ONLY --js_output_file '.$path.' --js '.implode($paths,' --js=');
- $result = system($command);
+ protected function compileClosureCompiler ( $files, $output_path ) {
+ # Check
+ if ( !$this->_compilerPath ) {
+ throw new Exception('Unknown Google Closure Compiler Path');
+ }
+
+ # Prepare Output File
+ file_put_contents($output_path,'');
+
+ # Compile Each File and Append to Output File
+ foreach ( $files as $file ) {
+ $out_path = $file_path = $file['path'];
+ if ( $file['compressed'] ) {
+ $compressed_path = $file['path'].'.compressed';
+ $command = 'java -jar '.$this->_compilerPath.' --js_output_file '.$compressed_path.' --js '.$file_path;
+ $out_path = $compressed_path;
+ }
+ file_put_contents($output_path,file_get_contents($out_path),FILE_APPEND);
+ }
}
# =========================
@@ -74,12 +99,17 @@ public function setCompiledOffset ( $value ) {
return $this;
}
- protected function compile($paths,$path){
+ protected function isMinified ( $path ) {
+ $minified = preg_match('/[\.\/\-](min(ified)?|compressed)[\.\/\-]/i', $path);
+ return $minified ? true : false;
+ }
+
+ protected function compile($files,$path){
$compiler = str_replace(' ','',ucwords(str_replace('-',' ',$this->_compiler)));
$function = 'compile'.$compiler;
if ( method_exists($this,$function) ) {
- $this->$function($paths,$path);
+ $this->$function($files,$path);
}
else {
throw new Exception('Compiler ['.$this->_compiler.']['.$function.'] not supported.');
@@ -94,7 +124,6 @@ public function toString ($indent = null) {
# Prepare
$files = array();
- $paths = array();
$hash = '';
$refresh = false;
$error = false;
@@ -110,14 +139,14 @@ public function toString ($indent = null) {
if ( !empty($item->source) ) {
# Generate File Name
$source = $item->source;
- $filename = md5($source).'.'.$this->_extension;
- $path = $this->getCachePath().'/'.$filename;
+ $filename = 'source-'.md5($source).'.'.$this->_extension;
+ $sourcePath = $this->getCachePath().'/'.$filename;
$url = ROOT_URL.$this->getCacheUrl().'/'.$filename;
# Write to file
- if ( !file_exists($path) ) {
+ if ( !file_exists($sourcePath) ) {
// we can do an if here, as the filename is based on the contents, if the contents has changed the filename would be different
- file_put_contents($path, $source);
+ file_put_contents($sourcePath, $source);
}
}
else {
@@ -133,33 +162,38 @@ public function toString ($indent = null) {
# Determine Original Path
if ( strpos($url,ROOT_URL) === 0 ) {
// We are a local file, so determine the full path from the base url
- $path = DOCUMENT_ROOT.'/'.preg_replace('/\?.*/','',str_replace(ROOT_URL,'',$url));
- if ( !is_file($path) ) {
- $path = null;
+ $sourcePath = DOCUMENT_ROOT.'/'.preg_replace('/\?.*/','',str_replace(ROOT_URL,'',$url));
+ if ( !is_file($sourcePath) ) {
+ $sourcePath = null;
}
}
}
# Determine Cache Path
- $cachePath = $this->getCachePath().'/'.preg_replace('/[^a-zA-Z0-9\.]+/','-',$url);
+ $cachePath = $this->getCachePath().'/cached-'.preg_replace('/[^a-zA-Z0-9\.]+/','-',$url);
# Ensure Correct Path
- $path = str_replace('//','/',$path);
+ $sourcePath = str_replace('//','/',$sourcePath);
# Apply
+ $minified = $this->isMinified($cachePath);
+ $compress = !$minified && (isset($item->attributes['compress']) && $item->attributes['compress'] !== 'false');
$files[$key] = array(
'url' => $url,
- 'path' => $path,
- 'cachePath' => $cachePath
+ 'sourcePath' => $sourcePath,
+ 'cachePath' => $cachePath,
+ 'path' => $cachePath,
+ 'minified' => $minified,
+ 'compress' => $compress
);
- $paths[] = $cachePath;
$hash .= $url;
}
# Hash
$hash = md5($hash);
- $compiledFileUrl = $this->getCacheUrl().'/'.$hash.'.'.$this->_extension;
- $compiledFilePath = $this->getCachePath().'/'.$hash.'.'.$this->_extension;
+ $compiledFileName = 'compiled-'.$hash.'.'.$this->_extension;
+ $compiledFileUrl = $this->getCacheUrl().'/'.$compiledFileName;
+ $compiledFilePath = $this->getCachePath().'/'.$compiledFileName;
# Get last modified time of cache file
if ( is_file($compiledFilePath) ) {
@@ -175,7 +209,7 @@ public function toString ($indent = null) {
foreach ( $files as $key => $file ) {
# Preset
$url = $file['url'];
- $path = $file['path'];
+ $sourcePath = $file['sourcePath'];
$cachePath = $file['cachePath'];
# Determine Cache Modified Time
@@ -188,8 +222,8 @@ public function toString ($indent = null) {
}
# Determine Real Modified Time
- if ( $path ) {
- $filemtime = filemtime($path);
+ if ( $sourcePath ) {
+ $filemtime = filemtime($sourcePath);
}
else {
$filemtime = $cacheFilemtime;
@@ -198,11 +232,11 @@ public function toString ($indent = null) {
# Should we refresh?
if ( $filemtime >= $cacheFilemtime ) {
$refresh = true;
- if ( strstr($url,'?') || !$path ) {
+ if ( strstr($url,'?') || !$sourcePath ) {
$contents = file_get_contents($url);
}
else {
- $contents = file_get_contents($path);
+ $contents = file_get_contents($sourcePath);
}
file_put_contents($cachePath,$contents);
}
@@ -214,9 +248,9 @@ public function toString ($indent = null) {
# Refresh the Cache File
if ( $refresh ) {
try {
- $error = !$this->compile($paths,$compiledFilePath);
+ $error = !$this->compile($files,$compiledFilePath);
if ( $error ) {
- throw new Exception('Compilation failed.');
+ throw new Exception('log-scripts-refreshed-failed');
}
}
catch ( Exception $Exception ) {
@@ -243,8 +277,10 @@ public function toString ($indent = null) {
$result = parent::toString($indent);
# Add Refresh Status
- if ( $refresh ) {
- $result .= "\n<!--[Scripts Bundled + Refreshed]-->\n";
+ if ( $refresh && !$error ) {
+ $Log = Bal_Log::getInstance();
+ $log_details = array();
+ $Log->log(array('log-scripts-refreshed',$log_details),Bal_Log::NOTICE,array('friendly'=>true,'class'=>'success','details'=>$log_details));
}
# Return result
View
3  lib/core/functions/_files.funcs.php
@@ -680,7 +680,8 @@ function get_filename ( $file, $with_extension = true ) {
*/
function get_extension ( $file ) {
$end = strrpos($file, '.');
- if ( $end !== false )
+ $brace = strrpos($file, '/');
+ if ( $end !== false && $end > $brace )
return strtolower(substr($file, $end + 1));
else
return '';
Please sign in to comment.
Something went wrong with that request. Please try again.