/** * Optimize website by aggregating css and js * */ public function process($sHtml) { JCH_DEBUG ? JchPlatformProfiler::start('Process', TRUE) : null; JCH_DEBUG ? JchPlatformProfiler::start('LoadClass') : null; loadJchOptimizeClass(array('JchOptimizeBase', 'JchOptimizeParser', 'JchOptimizeFileRetriever', 'JchOptimizeLinkBuilder', 'JchOptimizeHelper')); JCH_DEBUG ? JchPlatformProfiler::stop('LoadClass', TRUE) : null; try { $oParser = new JchOptimizeParser($this->params, $sHtml, JchOptimizeFileRetriever::getInstance()); $oLinkBuilder = new JchOptimizeLinkBuilder($oParser); $oLinkBuilder->insertJchLinks(); $oParser->runCookieLessDomain(); $oParser->lazyLoadImages(); $this->params->set('isXhtml', $oLinkBuilder->isXhtml()); $this->params->set('isHtml5', $oParser->isHtml5()); $sOptimizedHtml = JchOptimizeHelper::minifyHtml($oParser->getHtml(), $this->params); } catch (Exception $ex) { JchOptimizeLogger::log($ex->getMessage(), $this->params); $sOptimizedHtml = $sHtml; } spl_autoload_unregister('loadJchOptimizeClass'); JCH_DEBUG ? JchPlatformProfiler::stop('Process', TRUE) : null; JCH_DEBUG ? JchPlatformProfiler::attachProfiler($sOptimizedHtml) : null; if (version_compare(PHP_VERSION, '7', '>=')) { ini_set('pcre.jit', $this->jit); } return $sOptimizedHtml; }
/** * * @return boolean * @throws Exception */ public function onAfterRender() { $app = JFactory::getApplication(); $config = JFactory::getConfig(); $user = JFactory::getUser(); if ($app->getName() != 'site' || JFactory::getDocument()->getType() != 'html' || $app->input->get('jchbackend', '', 'int') == 1 || $config->get('offline') && $user->guest || $this->isEditorLoaded()) { return FALSE; } if ($this->params->get('log', 0)) { error_reporting(E_ALL & ~E_NOTICE); } $sHtml = $app->getBody(); if ($app->input->get('jchbackend') == '2') { echo $sHtml; while (@ob_end_flush()) { } exit; } if (!defined('JCH_VERSION')) { define('JCH_VERSION', '5.0.5'); } try { loadJchOptimizeClass('JchOptimize'); $sOptimizedHtml = JchOptimize::optimize($this->params, $sHtml); } catch (Exception $ex) { JchOptimizeLogger::log($ex->getMessage(), JchPlatformSettings::getInstance($this->params)); $sOptimizedHtml = $sHtml; } $app->setBody($sOptimizedHtml); }
/** * Optimize website by aggregating css and js * */ public function process($sHtml) { JCH_DEBUG ? JchPlatformProfiler::mark('beforeProcess plgSystem (JCH Optimize)') : null; loadJchOptimizeClass(array('JchOptimizeBase', 'JchOptimizeParser', 'JchOptimizeFileRetriever', 'JchOptimizeLinkBuilder', 'JchOptimizeHelper')); JCH_DEBUG ? JchPlatformProfiler::mark('afterLoadClass plgSystem (JCH Optimize)') : null; try { $oParser = new JchOptimizeParser($this->params, $sHtml, JchOptimizeFileRetriever::getInstance()); $oLinkBuilder = new JchOptimizeLinkBuilder($oParser); $oLinkBuilder->insertJchLinks(); $sOptimizedHtml = JchOptimizeHelper::minifyHtml($oParser->getHtml(), $this->params); } catch (Exception $ex) { JchOptimizeLogger::log($ex->getMessage(), $this->params); $sOptimizedHtml = $sHtml; } spl_autoload_unregister('loadJchOptimizeClass'); JCH_DEBUG ? JchPlatformProfiler::mark('afterProcess plgSystem (JCH Optimize)') : null; return $sOptimizedHtml; }
function jchoptimize($sHtml) { $options = get_option('jch_options'); try { $sOptimizedHtml = JchOptimize::optimize($options, $sHtml); } catch (Exception $e) { JchOptimizeLogger::log($e->getMessage(), JchPlatformSettings::getInstance($options)); $sOptimizedHtml = $sHtml; } return $sOptimizedHtml; }
/** * */ public function getAdminObject($oParser) { JCH_DEBUG ? JchPlatformProfiler::start('GetAdminObject') : null; try { $oAdmin = new JchOptimizeAdmin($this->params); $oAdmin->getAdminLinks($oParser, JchPlatformUtility::menuId()); } catch (Exception $ex) { JchOptimizeLogger::log($ex->getMessage(), $this->params); } JCH_DEBUG ? JchPlatformProfiler::stop('GetAdminObject', TRUE) : null; }
/** * * @param type $params */ public static function saveSettings($params) { $oPlugin = JchPlatformPlugin::getPlugin(); $oPlugin->params = $params->toArray(); $oData = new JRegistry($oPlugin); $aData = $oData->toArray(); $oController = new JControllerLegacy(); $oController->addModelPath(JPATH_ADMINISTRATOR . '/components/com_plugins/models', 'PluginsModel'); $oPluginModel = $oController->getModel('Plugin', 'PluginsModel'); if ($oPluginModel->save($aData) === FALSE) { JchOptimizeLogger::log(JText::sprintf('JLIB_APPLICATION_ERROR_SAVE_FAILED', $oPluginModel->getError()), $params); } }
/** * * @return string|boolean */ public function getImageLibrary() { if (!extension_loaded('exif')) { JchOptimizeLogger::log('EXIF extension not loaded', $this->params); return FALSE; } if (extension_loaded('imagick')) { $sImageLibrary = 'imagick'; } else { if (!extension_loaded('gd')) { JchOptimizeLogger::log('No image manipulation library installed', $this->params); return FALSE; } $sImageLibrary = 'gd'; } return $sImageLibrary; }
public function getOriginalHtml() { JCH_DEBUG ? JchPlatformProfiler::mark('beforeGetHtml') : null; $url = home_url() . '/?jchbackend=1'; try { $oFileRetriever = JchOptimizeFileRetriever::getInstance(); $response = $oFileRetriever->getFileContents($url); if ($oFileRetriever->response_code != 200) { throw new Exception(JchPlatformUtility::translate('Failed fetching front end HTML with response code ' . $oFileRetriever->response_code)); } JCH_DEBUG ? JchPlatformProfiler::mark('afterGetHtml') : null; return $response; } catch (Exception $e) { JchOptimizeLogger::log($url . ': ' . $e->getMessage(), $this->params); JCH_DEBUG ? JchPlatformProfiler::mark('afterGetHtml)') : null; throw new RunTimeException(_('Load or refresh the front-end site first then refresh this page ' . 'to populate the multi select exclude lists.')); } }
/** * * @return type * @throws type */ public static function optimizeImages(JchPlatformSettings $params) { $root = JchPlatformPaths::rootPath(); set_time_limit(0); $dir = JchPlatformUtility::get('dir', '', 'string'); $current = JchPlatformUtility::get('current', '0', 'int'); $optimize = JchPlatformUtility::get('optimize', '0', 'int'); $dir = JchPlatformUtility::decrypt($dir); $arr = array('total' => 0, 'current' => $current, 'optimize' => $optimize, 'message' => ''); $files = array(); if (is_dir($root . $dir)) { //$files = glob($root . $dir . '*.{gif,jpg,png}', GLOB_BRACE); if ($dh = opendir($root . $dir)) { while (($file = readdir($dh)) !== false) { if (preg_match('#\\.(?:gif|jpg|png)$#i', $file)) { $files[] = $root . $dir . $file; } } closedir($dh); } $arr['total'] = count($files); } else { $files = array($dir); } try { $smushitclass = 'JchOptimize\\SmushIt'; $smushit = new $smushitclass($files[$arr['current']], 0x2); $opfiles = $smushit->get(); if (copy($opfiles[0]->destination, $opfiles[0]->source)) { $arr['optimize']++; $arr['message'] = $opfiles[0]->source . ':Optimized!'; } else { throw Exception($opfiles[0]->source . ': Could not copy optimized image'); } } catch (Exception $e) { $arr['message'] = $e->getMessage(); } $arr['current']++; $arr['log_path'] = JchPlatformUtility::getLogsPath(); JchOptimizeLogger::logInfo($arr['message'], 'INFO'); return json_encode($arr); }
/** * * @return boolean * @throws Exception */ public function onAfterRender() { if (JDEBUG && $this->params->get('debug', 0)) { global $_PROFILER; $_PROFILER->mark('beforeOnAfterRender plgSystem (JCH Optimize)'); } $app = JFactory::getApplication(); $config = JFactory::getConfig(); $user = JFactory::getUser(); if ($app->getName() != 'site' || JFactory::getDocument()->getType() != 'html' || $app->input->get('jchbackend', '', 'int') == 1 || $config->get('offline') && $user->guest || class_exists('JEditor', FALSE)) { return FALSE; } if ($this->params->get('log', 0)) { error_reporting(E_ALL & ~E_NOTICE); } if (version_compare(JVERSION, '3.2.3', '>=')) { $sHtml = $app->getBody(); } else { $sHtml = JResponse::getBody(); } if ($app->input->get('jchbackend') == '2') { echo $sHtml; while (@ob_end_flush()) { } exit; } try { loadJchOptimizeClass('JchOptimize'); $sOptimizedHtml = JchOptimize::optimize($this->params, $sHtml); } catch (Exception $ex) { JchOptimizeLogger::log($ex->getMessage(), JchPlatformSettings::getInstance($this->params)); $sOptimizedHtml = $sHtml; } if (version_compare(JVERSION, '3.2.3', '>=')) { $app->setBody($sOptimizedHtml); } else { JResponse::setBody($sOptimizedHtml); } if (JDEBUG && $this->params->get('debug', 0)) { $_PROFILER->mark('afterOnAfterRender plgSystem (JCH Optimize)'); } }
/** * Optimize website by aggregating css and js * */ public function process($sHtml) { JCH_DEBUG ? JchPlatformProfiler::start('Process', TRUE) : null; JCH_DEBUG ? JchPlatformProfiler::start('LoadClass') : null; loadJchOptimizeClass(array('JchOptimizeBase', 'JchOptimizeParser', 'JchOptimizeFileRetriever', 'JchOptimizeLinkBuilder', 'JchOptimizeHelper')); JCH_DEBUG ? JchPlatformProfiler::stop('LoadClass', TRUE) : null; try { $oParser = new JchOptimizeParser($this->params, $sHtml, JchOptimizeFileRetriever::getInstance()); $oLinkBuilder = new JchOptimizeLinkBuilder($oParser); $oLinkBuilder->insertJchLinks(); $this->params->set('xhtml', $oLinkBuilder->isXhtml()); $sOptimizedHtml = JchOptimizeHelper::minifyHtml($oParser->getHtml(), $this->params); } catch (Exception $ex) { JchOptimizeLogger::log($ex->getMessage(), $this->params); $sOptimizedHtml = $sHtml; } spl_autoload_unregister('loadJchOptimizeClass'); JCH_DEBUG ? JchPlatformProfiler::stop('Process', TRUE) : null; JCH_DEBUG ? JchPlatformProfiler::attachProfiler($sOptimizedHtml) : null; return $sOptimizedHtml; }
/** * * @param type $sPath * @return type * @throws Exception */ protected function getContentsWithCurl($sPath) { $rCh = $this->getCurlResource(); curl_setopt($rCh, CURLOPT_HEADER, 0); curl_setopt($rCh, CURLOPT_URL, $sPath); curl_setopt($rCh, CURLOPT_RETURNTRANSFER, 1); curl_setopt($rCh, CURLOPT_AUTOREFERER, TRUE); curl_setopt($rCh, CURLOPT_SSL_VERIFYPEER, TRUE); curl_setopt($rCh, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($rCh, CURLOPT_CAINFO, JPATH_PLUGINS . '/system/jch_optimize/assets/cacert.pem'); @curl_setopt($rCh, CURLOPT_FOLLOWLOCATION, TRUE); $sHtml = curl_exec($rCh); if ($sHtml === FALSE || trim($sHtml) == '') { if ($this->params->get('log', 0)) { JchOptimizeLogger::log(JText::_(sprintf('Curl failed with error #%d: %s ' . 'fetching contents from %s', curl_errno($rCh), curl_error($rCh), $sPath))); } if ($this->bAllowFopenUrl) { $sHtml = $this->getContents($sPath); } else { throw new Exception(curl_error($rCh), curl_errno($rCh)); } } return $sHtml; }
/** * * @param type $url * @param array $params */ public static function postAsync($url, $params, array $posts) { foreach ($posts as $key => &$val) { if (is_array($val)) { $val = implode(',', $val); } $post_params[] = $key . '=' . urlencode($val); } $post_string = implode('&', $post_params); $parts = parse_url($url); if (isset($parts['scheme']) && $parts['scheme'] == 'https') { $protocol = 'ssl://'; $default_port = 443; } else { $protocol = ''; $default_port = 80; } $fp = fsockopen($protocol . $parts['host'], isset($parts['port']) ? $parts['port'] : $default_port, $errno, $errstr, 1); if (!$fp) { JchOptimizeLogger::log($errno . ': ' . $errstr, $params); } else { $out = "POST " . $parts['path'] . '?' . $parts['query'] . " HTTP/1.1\r\n"; $out .= "Host: " . $parts['host'] . "\r\n"; $out .= "Content-Type: application/x-www-form-urlencoded\r\n"; $out .= "Content-Length: " . strlen($post_string) . "\r\n"; $out .= "Connection: Close\r\n\r\n"; if (isset($post_string)) { $out .= $post_string; } JchOptimizeLogger::debug($out, 'out'); fwrite($fp, $out); fclose($fp); } }
/** * Resolves @imports in css files, fetching contents of these files and adding them to the aggregated file * * @param string $sContent * @return string */ protected function replaceImports($sContent) { if ($this->params->get('pro_replaceImports', '1')) { $oCssParser = $this->oCssParser; $u = $oCssParser->u; $sImportFileContents = preg_replace_callback("#(?>@?[^@'\"/]*+(?:{$u}|/|\\()?)*?\\K(?:@import\\s*+(?:url\\()?['\"]?([^\\)'\"]+)['\"]?(?:\\))?\\s*+([^;]*);|\\K\$)#", array(__CLASS__, 'getImportFileContents'), $sContent); if (is_null($sImportFileContents)) { JchOptimizeLogger::log('The plugin failed to get the contents of the file that was imported into the document by the "@import" rule', $this->params); return $sContent; } $sContent = $sImportFileContents; } else { $sContent = parent::replaceImports($sContent); } return $sContent; }
/** * Insert url of aggregated file in html * * @param string $sNewLink Url of aggregated file */ protected function replaceLink($sNewLink, $sType, $iCnt = '') { $sSearchArea = $this->oParser->getSearchArea(); if ($sType == 'css') { $sSearchArea = str_replace('</title>', $sNewLink, $sSearchArea); } if ($sType == 'js') { switch ($this->params->get('bottom_js', 1)) { case 0: //First found javascript tag $sSearchArea = preg_replace('#<JCH_SCRIPT>#', $sNewLink, $sSearchArea, 1); $sSearchArea = str_replace('<JCH_SCRIPT>', '', $sSearchArea); break; case 2: //Last found javascript tag $iCnt--; $sSearchArea = preg_replace('#<JCH_SCRIPT>#', '', $sSearchArea, $iCnt); $sSearchArea = str_replace('<JCH_SCRIPT>', $sNewLink, $sSearchArea); break; case 1: //Bottom of page $sSearchArea = str_replace('<JCH_SCRIPT>', '', $sSearchArea); $sSearchArea = str_replace('</body>', $sNewLink, $sSearchArea); $this->oParser->sHtml = str_replace('</body>', $sNewLink, $this->oParser->sHtml); break; default: JchOptimizeLogger::log(JText::_('Unknown value for position javascript type parameter')); $sSearchArea = preg_replace('#<JCH_SCRIPT>#', $sNewLink, $sSearchArea, 1); $sSearchArea = str_replace('<JCH_SCRIPT>', '', $sSearchArea); break; } } $this->oParser->setSearchArea($sSearchArea); }
/** * * @return type * @throws type */ public static function optimizeImages(JchPlatformSettings $params) { error_reporting(0); $root = JchPlatformPaths::rootPath(); set_time_limit(0); $dir = JchPlatformUtility::get('dir', '', 'string'); $current = JchPlatformUtility::get('current', '0', 'int'); $optimize = JchPlatformUtility::get('optimize', '0', 'int'); $dir = JchPlatformUtility::decrypt($dir); $arr = array('total' => 0, 'current' => $current, 'optimize' => $optimize, 'message' => ''); $files = array(); if (is_dir($root . $dir)) { //$files = glob($root . $dir . '*.{gif,jpg,png}', GLOB_BRACE); if ($dh = opendir($root . $dir)) { while (($file = readdir($dh)) !== false) { if (preg_match('#\\.(?:gif|jpe?g|png)$#i', $file)) { $files[] = $root . $dir . $file; } } closedir($dh); } $arr['total'] = count($files); } else { $files = array($dir); } // try // { // $smushitclass = 'JchOptimize\SmushIt'; // $smushit = new $smushitclass($files[$arr['current']], 0x02); // // $opfiles = $smushit->get(); // // if (copy($opfiles[0]->destination, $opfiles[0]->source)) // { // $arr['optimize'] ++; // $arr['message'] = $opfiles[0]->source . ':Optimized!'; // } // else // { // throw new Exception($opfiles[0]->source . ': Could not copy optimized image'); // } // } // catch (Exception $e) // { // $arr['message'] = $e->getMessage(); // } $kraken = new JchOptimize\Kraken($params->get('kraken_api_key'), $params->get('kraken_api_secret')); $options = array("file" => $files[$arr['current']], "wait" => true, "lossy" => $params->get('kraken_optimization_level', 0) ? TRUE : FALSE); if ($params->get('kraken_quality', 0)) { $options['quality'] = (int) $params->get('kraken_quality'); } try { $data = $kraken->upload($options); } catch (Exception $ex) { $data = array('success' => FALSE, 'error' => $ex->getMessage()); } $file = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $files[$arr['current']]); if (isset($data['success'])) { if ($data['success']) { if ($data['saved_bytes'] == 0) { $arr['message'] = $file . ': This image can not be optimized any further.'; } elseif (self::copy($data['kraked_url'], $file)) { $arr['optimize']++; $arr['message'] = $file . ': Optimized! You saved ' . $data['saved_bytes'] . ' bytes.'; } else { $arr['message'] = $file . ': Could not copy optimized file.' . ' ' . $msg; } } else { $arr['message'] = $file . ': ' . $data['error']; } } else { $arr['message'] = $file . ': Unrecognizable response from server'; } $arr['current']++; $arr['log_path'] = JchPlatformUtility::getLogsPath(); try { JchOptimizeLogger::logInfo($arr['message'], 'INFO'); } catch (Exception $e) { } return json_encode($arr); }
/** * * @return type */ public function lazyLoadImages() { if ($this->params->get('pro_lazyload', '0')) { JCH_DEBUG ? JchPlatformProfiler::start('LazyLoadImages') : null; $sLazyLoadBodyHtml = preg_replace($this->getLazyLoadRegex(), '$1src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="$3" ' . 'data-jchll="true"$4<noscript>$1$2$4</noscript>', $this->getBodyHtml()); if (is_null($sLazyLoadBodyHtml)) { JchOptimizeLogger::log('Lazy load images function failed', $this->params); return; } if (preg_match($this->getBodyRegex(), $sLazyLoadBodyHtml, $aBodyMatches) === FALSE || empty($aBodyMatches)) { JchOptimizeLogger::log('Failed retrieving body in lazy load images function', $this->params); return; } $this->sBodyHtml = $aBodyMatches[0]; JCH_DEBUG ? JchPlatformProfiler::stop('LazyLoadImages', TRUE) : null; } }
/** * Sorts @import and @charset as according to w3C <http://www.w3.org/TR/CSS2/cascade.html> Section 6.3 * * @param string $sCss Combined css * @return string CSS with @import and @charset properly sorted * @todo replace @imports with media queries */ public function sortImports($sCss) { $sCssMediaImports = preg_replace_callback('#@media\\s([^{]++)({(?>[^{}]++|(?2))*+})#i', array(__CLASS__, '_sortImportsCB'), $sCss); if (is_null($sCssMediaImports)) { if ($this->params->get('log', 0)) { JchOptimizeLogger::log('Failed matching for imports within media queries in css'); } return $sCss; } $sCss = $sCssMediaImports; $sCss = $this->removeAtRules($sCss, '#@(?:import|charset)[^;}]++(?:;|.(?=\\}))#i'); return $sCss; }
/** * If parameter is set will minify HTML before sending to browser; * Inline CSS and JS will also be minified if respective parameters are set * * @return string Optimized HTML * @throws Exception */ public function minifyHtml($sHtml) { JCH_DEBUG ? JchPlatformProfiler::mark('beforeMinifyHtml plgSystem (JCH Optimize)') : null; $oParams = $this->params; $aOptions = array(); if ($oParams->get('css_minify', 0)) { $aOptions['cssMinifier'] = array('JchOptimize\\CSS_Optimize', 'process'); } if ($oParams->get('js_minify', 0)) { $aOptions['jsMinifier'] = array('JchOptimize\\JS_Optimize', 'minify'); } if ($oParams->get('html_minify', 0)) { $sHtmlMin = HTML_Optimize::minify($sHtml, $aOptions); if ($sHtmlMin == '') { JchOptimizeLogger::log(JchPlatformUtility::translate('Error while minifying HTML'), $oParams); $sHtmlMin = $sHtml; } $sHtml = $sHtmlMin; } JCH_DEBUG ? JchPlatformProfiler::mark('afterMinifyHtml plgSystem (JCH Optimize)') : null; return $sHtml; }
/** * * @return type */ public function lazyLoadImages() { if ($this->params->get('pro_lazyload', '0')) { JCH_DEBUG ? JchPlatformProfiler::start('LazyLoadImages') : null; $sLazyLoadBodyHtml = preg_replace($this->getLazyLoadRegex(), 'data-src="$1" src="' . JchOptimizeHelper::cookieLessDomain($this->params) . JchPlatformPaths::imageFolder() . 'placeholder.gif" data-jchll="true"', $this->getBodyHtml()); if (is_null($sLazyLoadBodyHtml)) { JchOptimizeLogger::log(JchPlatformUtility::translate('Lazy load images function failed'), $this->params); return; } if (preg_match($this->getBodyRegex(), $sLazyLoadBodyHtml, $aBodyMatches) === FALSE || empty($aBodyMatches)) { JchOptimizeLogger::log(JchPlatformUtility::translate('Failed retrieving body in lazy load images function'), $this->params); return; } $this->sBodyHtml = $aBodyMatches[0]; JCH_DEBUG ? JchPlatformProfiler::stop('LazyLoadImages', TRUE) : null; } }
/** * Resolves @imports in css files, fetching contents of these files and adding them to the aggregated file * * @param string $sContent * @return string */ protected function replaceImports($sContent) { if ($this->params->get('pro_replaceImports', '1')) { $oCssParser = $this->oCssParser; $u = $oCssParser->u; $sImportFileContents = preg_replace_callback("#(?>@?[^@'\"/]*+(?:{$u}|/|\\()?)*?\\K(?:@import url\\((?=[^\\)]+\\.(?:css|php))([^\\)]+)\\)([^;]*);|\\K\$)#", array(__CLASS__, 'getImportFileContents'), $sContent); if (is_null($sImportFileContents)) { JchOptimizeLogger::log(JchPlatformUtility::translate('Failed getting @import file contents'), $this->params); return $sContent; } $sContent = $sImportFileContents; } else { $sContent = parent::replaceImports($sContent); } return $sContent; }
public function getSupportedFormats() { $aImageTypes = array(); try { $oImagick = new Imagick(); $aImageFormats = $oImagick->queryFormats(); } catch (ImagickException $e) { JchOptimizeLogger::log($e->getMessage(), $this->params); } // store supported formats for populating drop downs etc later if (in_array('PNG', $aImageFormats)) { $aImageTypes[] = 'PNG'; $this->aSpriteFormats[] = 'PNG'; } if (in_array('GIF', $aImageFormats)) { $aImageTypes[] = 'GIF'; $this->aSpriteFormats[] = 'GIF'; } if (in_array('JPG', $aImageFormats) || in_array('JPEG', $aImageFormats)) { $aImageTypes[] = 'JPG'; } return $aImageTypes; }
/** * * @param type $sContent * @param type $sUrl */ protected function minifyContent($sContent, $sType, $aUrl) { if ($this->params->get($sType . '_minify', 0)) { $sUrl = $this->prepareFileUrl($aUrl, $sType); $sMinifiedContent = trim($sType == 'css' ? CSS_Optimize::optimize($sContent) : JS_Optimize::optimize($sContent)); if (is_null($sMinifiedContent) || $sMinifiedContent == '') { JchOptimizeLogger::log(sprintf('Error occurred trying to minify: %s', $sUrl), $this->params); $sMinifiedContent = $sContent; } return $sMinifiedContent; } return $sContent; }
/** * * @return type */ public function processLinks() { try { $oParser = $this->getParser(); $aLinks = $oParser->getReplacedFiles(); } catch (Exception $ex) { $GLOBALS['bTextArea'] = TRUE; if ($this->getParams()->get('log', 0)) { JchOptimizeLogger::log($ex->getMessage()); } throw new Exception(JText::_('Failed fetching links for the multiselect exclude options. ' . 'Will render textareas instead.')); } return $aLinks; }
/** * * @return type * @throws type */ public static function optimizeImages() { error_reporting(0); $root = JchPlatformPaths::rootPath(); set_time_limit(0); $dir_array = JchPlatformUtility::get('dir', '', 'array'); $subdirs = JchPlatformUtility::get('subdirs', '', 'array'); $params = (object) JchPlatformUtility::get('params', '', 'array'); $task = JchPlatformUtility::get('task', '0', 'string'); $dir = rtrim(JchPlatformUtility::decrypt($dir_array['path']), '/\\'); if ($task == 'getfiles') { $files = array(); if (count(array_filter($subdirs))) { foreach ($subdirs as $subdir) { $subdir = rtrim(JchPlatformUtility::decrypt($subdir), '/\\'); $files = array_merge($files, self::getImageFiles($root . $subdir, TRUE)); } } if (!empty($files)) { $files = array_map(function ($v) { return JchOptimizeHelper::prepareImageUrl($v); }, $files); } $data = array('files' => $files, 'log_path' => JchPlatformUtility::getLogsPath()); return new JchOptimizeJson($data); } $file = $dir; $data = array(); $oJchio = new JchOptimize\ImageOptimizer($params->pro_downloadid, $params->hidden_api_secret); $options = array("file" => $file, "lossy" => true); if (!empty($dir_array['width']) || !empty($dir_array['height'])) { $options['resize']['width'] = (int) (!empty($dir_array['width']) ? $dir_array['width'] : 0); $options['resize']['height'] = (int) (!empty($dir_array['height']) ? $dir_array['height'] : 0); } if ($params->kraken_backup || !empty($options['resize'])) { $backup_file = self::getBackupFilename($file); self::copy($file, $backup_file); } $message = ''; $file = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $file); try { $response = $oJchio->upload($options); if (isset($response->success)) { if ($response->success) { if (self::copy($response->data->kraked_url, $file)) { $message .= 'Optimized! You saved ' . $response->data->saved_bytes . ' bytes.'; } else { $data = new Exception('Could not copy optimized file.', 404); } } else { $data = new Exception($response->message, $response->code); } } else { JchOptimizeLogger::logInfo($response, 'Server error'); $data = new Exception('Unrecognizable response from server', 500); } } catch (Exception $e) { $data = $e; } $respond = new JchOptimizeJson($data, $message); if ($respond->success || $respond->code == 404) { $respond->message = $file . ': ' . $respond->message; } try { JchOptimizeLogger::logInfo($respond->message, 'INFO'); } catch (Exception $e) { } return $respond; }
/** * Callback function used to remove urls of css and js files in head tags * * @param array $aMatches Array of all matches * @return string Returns the url if excluded, empty string otherwise */ protected function replaceScripts($aMatches) { if ((!isset($aMatches[1]) || trim($aMatches[1]) == '') && (!isset($aMatches[3]) || trim($aMatches[3]) == '')) { return $aMatches[0]; } $sType = $this->aCallbackArgs['type']; $sEditor = JchOptimizeHelper::getEditorName(); $sUrl = $aMatches[1]; $sFile = isset($aMatches[2]) ? $aMatches[2] : ''; $sDeclaration = isset($aMatches[3]) ? $aMatches[3] : ''; $aExcludes = array(); $sPath = ''; //global $_PROFILER; if (isset($this->aCallbackArgs['excludes'])) { $aExcludes = $this->aCallbackArgs['excludes']; } $aExcludes['script'] = array_map(function ($sScript) { return stripslashes($sScript); }, $aExcludes['script']); $aExcludes['script'] = array_merge($aExcludes['script'], array('document.write', 'var mapconfig90')); $aExcludes['js'] = array_merge($aExcludes['js'], array('.com/maps/api/js', '.com/jsapi', '.com/uds', 'plugin_googlemap3', '.com/recaptcha/api')); if ($sUrl != '') { $sPath .= JchOptimizeHelper::getFilePath($sUrl); } $sMedia = ''; if ($sType == 'css' && preg_match('#media=(?(?=["\'])(?:["\']([^"\']+))|(\\w+))#i', $aMatches[0], $aMediaTypes) > 0) { $sMedia .= $aMediaTypes[1] ? $aMediaTypes[1] : $aMediaTypes[2]; } //JCH_DEBUG ? $_PROFILER->mark('beforeReplaceScript - ' . $sFile . ' plgSystem (JCH Optimize)') : null; switch (TRUE) { case isset($aExcludes['if']) && in_array($aMatches[0], $aExcludes['if']): case $sUrl != '' && !empty($aExcludes[$sType]) && JchOptimizeHelper::findExcludes($aExcludes[$sType], $sUrl): case $sEditor == 'artofeditor' && $sFile == 'ckeditor.js': case $sType == 'js' && $sUrl != '' && $this->isEditorsExcluded($sUrl): case $sUrl != '' && $this->isUrlFopenAllowed($sUrl): case $sUrl != '' && preg_match('#^https#', $sUrl) && !extension_loaded('openssl'): case $sUrl != '' && preg_match('#^data:#', $sUrl): case $sDeclaration != '' && JchOptimizeHelper::findExcludes($aExcludes['script'], $sDeclaration, TRUE): //JCH_DEBUG ? $_PROFILER->mark('afterReplaceScript - ' . $sFile . ' plgSystem (JCH Optimize)') : null; return $aMatches[0]; case $sUrl == '' && trim($sDeclaration) != '': $content = str_replace(array('<!--', '-->'), '', $sDeclaration); $this->aLinks[$sType][] = array('content' => $content, 'match' => $aMatches[0]); //JCH_DEBUG ? $_PROFILER->mark('afterReplaceScript - ' . $sFile . ' plgSystem (JCH Optimize)') : null; return ''; case $this->aCallbackArgs['type'] == 'js': $this->aCallbackArgs['counter']++; $this->aLinks[$sType][] = array('url' => $sUrl, 'file' => $sFile, 'match' => $aMatches[0], 'path' => $sPath); //JCH_DEBUG ? $_PROFILER->mark('afterReplaceScript - ' . $sFile . ' plgSystem (JCH Optimize)') : null; return '<JCH_SCRIPT>'; case $this->aCallbackArgs['type'] == 'css': $this->aLinks[$sType][] = array('url' => $sUrl, 'file' => $sFile, 'media' => $sMedia, 'match' => $aMatches[0], 'path' => $sPath); //JCH_DEBUG ? $_PROFILER->mark('afterReplaceScript - ' . $sFile . ' plgSystem (JCH Optimize)') : null; return ''; default: JchOptimizeLogger::log(JText::_('Unknown match type')); return $aMatches[0]; } }
/** * * @param type $aUrlArray * @param type $params * @return type */ public static function getImages($aUrlArray, $params) { $oCombiner = new JchOptimizeCombiner($params, TRUE); $oCssParser = new JchOptimizeCssParser($oCombiner->sLnEnd, $oCombiner->bBackend); try { $sCss = $oCombiner->combineFiles($aUrlArray, 'css', $oCssParser); $oSpriteGenerator = new JchOptimizeSpriteGenerator($params); $aMatches = $oSpriteGenerator->processCssUrls($sCss, TRUE); } catch (Exception $Ex) { $GLOBALS['bTextArea'] = TRUE; if ($oCombiner->params->get('log', '0')) { JchOptimizeLogger::log($Ex->getMessage()); } throw new Exception(JText::_('Failed fetching images for the multiselect exclude options in sprite generator. ' . 'Will render textareas instead.')); } return $aMatches; }
/** * * @param type $sContent * @param type $sUrl */ protected function minifyContent($sContent, $sType, $aUrl) { if ($this->params->get($sType . '_minify', 0) && preg_match('#\\s++#', trim($sContent))) { $sUrl = $this->prepareFileUrl($aUrl, $sType); $sMinifiedContent = trim($sType == 'css' ? CSS_Optimize::optimize($sContent) : JS_Optimize::optimize($sContent)); if (is_null($sMinifiedContent) || $sMinifiedContent == '') { JchOptimizeLogger::log(sprintf(JchPlatformUtility::translate('Error occurred trying to minify: %s'), $aUrl['url']), $this->params); $sMinifiedContent = $sContent; } return $sMinifiedContent; } return $sContent; }
/** * * @param type $sContent * @param type $sUrl */ protected function minifyContent($sContent, $sType, $aUrl) { if ($this->params->get($sType . '_minify', 0) && preg_match('#\\s++#', trim($sContent))) { $sUrl = isset($aUrl['url']) ? $aUrl['url'] : ($sType == 'css' ? 'Style' : 'Script') . ' Declaration'; JCH_DEBUG ? JchPlatformProfiler::mark('beforeMinifyContent - "' . $sUrl . '" plgSystem (JCH Optimize)') : null; $sMinifiedContent = trim($sType == 'css' ? CSS_Optimize::process($sContent) : JS_Optimize::minify($sContent)); if (is_null($sMinifiedContent) || $sMinifiedContent == '') { JchOptimizeLogger::log(sprintf(JchPlatformUtility::translate('Error occurred trying to minify: %s'), $aUrl['url']), $this->params); $sMinifiedContent = $sContent; } JCH_DEBUG ? JchPlatformProfiler::mark('afterMinifyContent - "' . $sUrl . '" plgSystem (JCH Optimize)') : null; return $sMinifiedContent; } return $sContent; }
/** * If parameter is set will minify HTML before sending to browser; * Inline CSS and JS will also be minified if respective parameters are set * * @return string Optimized HTML * @throws Exception */ public function minifyHtml($sHtml) { global $_PROFILER, $oParams; JCH_DEBUG ? $_PROFILER->mark('beforeMinifyHtml plgSystem (JCH Optimize)') : null; $aOptions = array(); if ($oParams->get('css_minify', 0)) { $aOptions['cssMinifier'] = array('JchOptimize\\Minify_CSSi', 'process'); } if ($oParams->get('js_minify', 0)) { $aOptions['jsMinifier'] = array('JchOptimize\\JSMinRegex', 'minify'); } if ($oParams->get('html_minify', 0)) { $sHtmlMin = Minify_HTMLi::minify($sHtml, $aOptions); if ($sHtmlMin == '') { if ($oParams->get('log', 0)) { JchOptimizeLogger::log(JText::_('Error while minifying HTML')); } return $sHtml; } $sHtml = $sHtmlMin; } JCH_DEBUG ? $_PROFILER->mark('afterMinifyHtml plgSystem (JCH Optimize)') : null; return $sHtml; }