Ejemplo n.º 1
1
 /**
  * 
  * @return string
  */
 public static function fileTree()
 {
     $root = JchPlatformPaths::rootPath();
     $dir = urldecode(JchPlatformUtility::get('dir', '', 'string', 'post'));
     $dir = JchPlatformUtility::decrypt($dir);
     $response = '';
     if (file_exists($root . $dir)) {
         $files = scandir($root . $dir);
         natcasesort($files);
         if (count($files) > 2) {
             /* The 2 accounts for . and .. */
             $response .= '<ul class="jqueryFileTree" style="display: none; ">';
             // All dirs
             foreach ($files as $file) {
                 if (file_exists($root . $dir . $file) && $file != '.' && $file != '..' && is_dir($root . $dir . $file)) {
                     $response .= '<li class="directory collapsed"><a href="#" rel="' . JchPlatformUtility::encrypt($dir . $file . '/') . '">' . htmlentities($file) . '</a></li>';
                 }
             }
             // All files
             foreach ($files as $file) {
                 if (file_exists($root . $dir . $file) && $file != '.' && $file != '..' && !is_dir($root . $dir . $file)) {
                     $ext = preg_replace('/^.*\\./', '', $file);
                     $response .= '<li class="file ext_' . $ext . '"><a href="#" rel="' . JchPlatformUtility::encrypt($dir . $file) . '">' . htmlentities($file) . '</a></li>';
                 }
             }
             $response .= '</ul>';
         }
     }
     return $response;
 }
Ejemplo n.º 2
0
 /**
  * 
  * @param type $sPath
  * @return type
  */
 public function getFileContents($sPath, $aPost = array(), $sOrigPath = '')
 {
     if (strpos($sPath, 'http') === 0 || !empty($aPost)) {
         if (!$this->oHttpAdapter->available()) {
             throw new Exception(JchPlatformUtility::translate('No Http Adapter available'));
         }
         try {
             $response = $this->oHttpAdapter->request($sPath, $aPost);
             if ($response === FALSE) {
                 throw new RuntimeException(sprintf(JchPlatformUtility::translate('Failed getting file contents from %s'), $sPath));
             }
         } catch (RuntimeException $ex) {
             JchOptimizelogger::log($sPath . ': ' . $ex->getMessage(), JchPlatformPlugin::getPluginParams());
             $response['code'] = 404;
         } catch (BadFunctionCallException $ex) {
             throw new Exception($ex->getMessage());
         }
         if ($response['code'] >= 400) {
             $sPath = $sOrigPath == '' ? $sPath : $sOrigPath;
             $sContents = $this->notFound($sPath);
         } else {
             $sContents = $response['body'];
         }
     } else {
         if (file_exists($sPath)) {
             $sContents = @file_get_contents($sPath);
         } elseif ($this->oHttpAdapter->available()) {
             $sUriPath = JchPlatformPaths::path2Url($sPath);
             $sContents = $this->getFileContents($sUriPath, array(), $sPath);
         } else {
             $sContents = $this->notFound($sPath);
         }
     }
     return $sContents;
 }
Ejemplo n.º 3
0
 /**
  * Fetches HTML to be sent to browser
  * 
  * @return string
  */
 public function getHtml()
 {
     $sHtml = preg_replace($this->getHeadRegex(), strtr($this->sHeadHtml, array('\\' => '\\\\', '$' => '\\$')), $this->sHtml, 1);
     if (is_null($sHtml) || $sHtml == '') {
         throw new Exception(JchPlatformUtility::translate('Error occured while trying to get html'));
     }
     return $sHtml;
 }
Ejemplo n.º 4
0
 /**
  * 
  * @param type $sLnEnd
  * @param type $bBackend
  */
 public function __construct($params = NULL, $bBackend = false)
 {
     $this->sLnEnd = is_null($params) ? "\n" : JchPlatformUtility::lnEnd();
     $this->params = is_null($params) ? NULL : $params;
     $this->bBackend = $bBackend;
     $e = self::DOUBLE_QUOTE_STRING . '|' . self::SINGLE_QUOTE_STRING . '|' . self::BLOCK_COMMENTS . '|' . self::LINE_COMMENTS;
     $this->e = "(?<!\\\\)(?:{$e})|[\\'\"/]";
     $this->u = '(?<!\\\\)(?:' . self::URI . '|' . $e . ')|[\'\\"/(]';
 }
Ejemplo n.º 5
0
 /**
  * 
  * @param type $sPath
  * @param type $aPost
  * @return type
  * @throws Exception
  */
 public function request($sPath, $aPost = array())
 {
     if (!$this->oHttpAdapter) {
         throw new BadFunctionCallException(JchPlatformUtility::translate('No Http Adapter present'));
     }
     $oUri = JUri::getInstance($sPath);
     $oResponse = $this->oHttpAdapter->request('GET', $oUri, $aPost);
     $return = array('body' => $oResponse->body, 'code' => $oResponse->code);
     return $return;
 }
Ejemplo n.º 6
0
 /**
  * 
  */
 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;
 }
Ejemplo n.º 7
0
 /**
  * 
  * @param type $sPath
  * @param type $aPost
  * @return type
  * @throws Exception
  */
 public function request($sPath, $aPost = null, $aHeaders = null, $sUserAgent = '')
 {
     if (!$this->oHttpAdapter) {
         throw new BadFunctionCallException(JchPlatformUtility::translate('No Http Adapter present'));
     }
     $oUri = JUri::getInstance($sPath);
     $method = !isset($aPost) ? 'GET' : 'POST';
     $oResponse = $this->oHttpAdapter->request($method, $oUri, $aPost, $aHeaders, 10, $sUserAgent);
     $return = array('body' => $oResponse->body, 'code' => $oResponse->code);
     return $return;
 }
Ejemplo n.º 8
0
 /**
  * Static method to initialize the plugin
  * 
  * @param type $params  Plugin parameters
  */
 public static function optimize($oParams, $sHtml)
 {
     if (version_compare(PHP_VERSION, '5.3.0', '<')) {
         throw new Exception(JchPlatformUtility::translate('PHP Version less than 5.3.0. Exiting plugin...'));
     }
     $pcre_version = preg_replace('#(^\\d++\\.\\d++).++$#', '$1', PCRE_VERSION);
     if (version_compare($pcre_version, '7.2', '<')) {
         throw new Exception(JchPlatformUtility::translate('PCRE Version less than 7.2. Exiting plugin...'));
     }
     $JchOptimize = new JchOptimize($oParams);
     return $JchOptimize->process($sHtml);
 }
Ejemplo n.º 9
0
 /**
  * Constructor
  * 
  * @param JRegistry object $params      Plugin parameters
  * @param string  $sHtml                Page HMTL
  */
 public function __construct($oParams, $sHtml, $oFileRetriever)
 {
     $this->params = $oParams;
     $this->sHtml = $sHtml;
     $this->oFileRetriever = $oFileRetriever;
     $this->sLnEnd = JchPlatformUtility::lnEnd();
     $this->sTab = JchPlatformUtility::tab();
     if (!defined('JCH_TEST_MODE')) {
         $oUri = JchPlatformUri::getInstance();
         $this->sFileHash = serialize($this->params->getOptions()) . JCH_VERSION . $oUri->getHost();
     }
     $this->parseHtml();
 }
Ejemplo n.º 10
0
 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.'));
     }
 }
Ejemplo n.º 11
0
 /**
  * 
  * @param type $sPath
  * @return type
  */
 public function getFileContents($sPath, $aPost = null, $aHeader = null, $sOrigPath = '')
 {
     $oHttpAdapter = $this->getHttpAdapter();
     if (strpos($sPath, 'http') === 0) {
         if (!$oHttpAdapter->available()) {
             throw new Exception(JchPlatformUtility::translate('No Http Adapter available'));
         }
         $this->response_code = 0;
         try {
             $response = $oHttpAdapter->request($sPath, $aPost, $aHeader);
             $this->response_code = $response['code'];
             if (!isset($response) || $response === FALSE) {
                 throw new RuntimeException(sprintf(JchPlatformUtility::translate('Failed getting file contents from %s'), $sPath));
             }
         } catch (RuntimeException $ex) {
             JchOptimizelogger::log($sPath . ': ' . $ex->getMessage(), JchPlatformPlugin::getPluginParams());
         } catch (Exception $ex) {
             throw new Exception($sPath . ': ' . $ex->getMessage());
         }
         if ($this->response_code != 200 && !$this->allow_400) {
             $sPath = $sOrigPath == '' ? $sPath : $sOrigPath;
             $sContents = $this->notFound($sPath);
         } else {
             $sContents = $response['body'];
         }
     } else {
         if (file_exists($sPath)) {
             $sContents = @file_get_contents($sPath);
         } elseif ($oHttpAdapter->available()) {
             $sUriPath = JchPlatformPaths::path2Url($sPath);
             $sContents = $this->getFileContents($sUriPath, null, null, $sPath);
         } else {
             $sContents = $this->notFound($sPath);
         }
     }
     return $sContents;
 }
Ejemplo n.º 12
0
/**
 * Autoloader for plugin classes
 * 
 * @param type $class
 * @return boolean
 */
function loadJchOptimizeClass($sClass)
{
    $class = $sClass;
    $prefix = substr($class, 0, 3);
    // If the class already exists do nothing.
    if (class_exists($class, false)) {
        return true;
    }
    if ($prefix !== 'Jch') {
        return false;
    } else {
        $class = str_replace($prefix, '', $class);
    }
    if (strpos($class, '\\') !== FALSE) {
        $filename = str_replace('Optimize\\', '', $class);
        $file = dirname(__FILE__) . '/libs/' . $filename . '.php';
    } elseif (strpos($class, 'Platform') === 0) {
        $filename = strtolower(str_replace('Platform', '', $class));
        $file = dirname(dirname(__FILE__)) . '/platform/' . $filename . '.php';
    } elseif (strpos($class, 'Interface') === 0) {
        $filename = strtolower(str_replace('Interface', '', $class));
        $file = dirname(__FILE__) . '/interfaces/' . $filename . '.php';
    } else {
        $filename = str_replace('Optimize', '', $class);
        $filename = strtolower($class == 'Optimize' ? 'jchoptimize' : $filename);
        $file = dirname(__FILE__) . '/' . $filename . '.php';
    }
    if (!file_exists($file)) {
        throw new Exception(sprintf(JchPlatformUtility::translate('File not found: %s'), $file));
    } else {
        include_once $file;
        if (!class_exists($sClass) && !interface_exists($sClass)) {
            throw new Exception(sprintf(JchPlatformUtility::translate('Class not found: %s'), $sClass));
        }
    }
}
Ejemplo n.º 13
0
 /**
  * Converts url of background images in css files to absolute path
  * 
  * @param string $sContent
  * @return string
  */
 public function correctUrl($sContent, $aUrl)
 {
     $obj = $this;
     $sCorrectedContent = preg_replace_callback("#(?>[(]?[^('\\\\/\"]*+(?:{$this->e}|/)?)*?(?:(?<=url)\\(\\s*+\\K['\"]?((?<!['\"])[^\\s)]*+|(?<!')[^\"]*+|[^']*+)['\"]?|\\K\$)#i", function ($aMatches) use($aUrl, $obj) {
         return $obj->_correctUrlCB($aMatches, $aUrl);
     }, $sContent);
     if (is_null($sCorrectedContent)) {
         throw new Exception(JchPlatformUtility::translate('Failed correcting urls of background images'));
     }
     $sContent = $sCorrectedContent;
     return $sContent;
 }
Ejemplo n.º 14
0
 /**
  * 
  * @param type $lifetime
  */
 public static function gc($lifetime)
 {
     $wp_filesystem = self::getWpFileSystem();
     if ($wp_filesystem === false) {
         return false;
     }
     $result = true;
     $files = JchPlatformUtility::lsFiles(rtrim(JCH_CACHE_DIR, '/\\'), '.', TRUE);
     $now = time();
     foreach ($files as $file) {
         $time = $wp_filesystem->mtime($file);
         if ($time + $lifetime < $now || empty($time)) {
             $result |= $wp_filesystem->delete($file);
         }
     }
     return $result;
 }
Ejemplo n.º 15
0
 /**
  * 
  * @staticvar int $cnt
  * @staticvar int $no
  * @param type $arr
  * @param type $count
  * @param type $optimized
  */
 public static function postStatus($arr, $count = FALSE, $optimized = FALSE)
 {
     if ($arr['total'] == 0) {
         return;
     }
     static $cnt = 0;
     static $no = 0;
     if ($count) {
         $arr['current'] = ++$cnt;
     }
     $arr['optimize'] = $optimized ? ++$no : $no;
     $json = json_encode($arr);
     JchPlatformUtility::write(JCH_PLUGIN_DIR . 'status.json', $json);
 }
Ejemplo n.º 16
0
 /**
  * 
  * @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;
 }
Ejemplo n.º 17
0
 /**
  * 
  * @param type $variable
  * @param type $name
  */
 public static function debug($variable, $name = '')
 {
     $sMessage = $name != '' ? "{$name} = '" . $variable . "'" : $variable;
     JchPlatformUtility::log($sMessage, 'jch-optimize');
 }
Ejemplo n.º 18
0
 /**
  * 
  * @return type
  */
 public static function getCombinedFile()
 {
     $aGet = self::getArray(array('f' => 'alnum', 'd' => 'int', 'i' => 'int', 'type' => 'word'));
     $iLifetime = (int) $aGet['d'] * 24 * 60 * 60;
     $aCache = JchPlatformCache::getCache($aGet['f'], $iLifetime);
     if ($aCache === FALSE) {
         die('File not found');
     }
     $aTimeMFile = JchPlatformUtility::RFC1123DateAdd($aCache['filemtime'], $aGet['d']);
     $sTimeMFile = $aTimeMFile['filemtime'] . ' GMT';
     $sExpiryDate = $aTimeMFile['expiry'] . ' GMT';
     $headers = array();
     if (function_exists('apache_request_headers')) {
         $headers = apache_request_headers();
     }
     if (!empty($headers) && isset($headers['If-Modified-Since']) && strtotime($headers['If-Modified-Since']) == strtotime($sTimeMFile)) {
         // Client's cache IS current, so we just respond '304 Not Modified'.
         header('HTTP/1.1 304 Not Modified');
         header('Connection: close');
         return;
     } else {
         header('Last-Modified: ' . $sTimeMFile);
     }
     $sFile = $aCache['file'][$aGet['i']];
     $sFile = JchOptimizeOutput::getCachedFile($sFile, $iLifetime);
     $aSpriteCss = $aCache['spritecss'];
     if ($aGet['type'] == 'css') {
         if (!empty($aSpriteCss)) {
             $sFile = str_replace($aSpriteCss['needles'], $aSpriteCss['replacements'], $sFile);
         }
         if (!empty($aCache['font-face'])) {
             $sFile = str_replace($aCache['font-face'], '', $sFile);
         }
         $oCssParser = new JchOptimizeCssParser();
         $sFile = $oCssParser->sortImports($sFile);
         if (function_exists('mb_convert_encoding')) {
             $sFile = '@charset "utf-8";' . $sFile;
         }
     }
     if ($aGet['type'] == 'css') {
         header('Content-type: text/css; charset=UTF-8');
     } elseif ($aGet['type'] == 'js') {
         header('Content-type: text/javascript; charset=UTF-8');
     }
     header('Expires: ' . $sExpiryDate);
     header('Cache-Control: Public');
     header('Vary: Accept-Encoding');
     $gzip = TRUE;
     if (isset($_SERVER['HTTP_USER_AGENT'])) {
         /* Facebook User Agent
          * facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)
          * LinkedIn User Agent
          * LinkedInBot/1.0 (compatible; Mozilla/5.0; Jakarta Commons-HttpClient/3.1 +http://www.linkedin.com)
          */
         $pattern = strtolower('/facebookexternalhit|LinkedInBot/x');
         if (preg_match($pattern, strtolower($_SERVER['HTTP_USER_AGENT']))) {
             $gzip = FALSE;
         }
     }
     if (isset($aGet['gz']) && $aGet['gz'] == 'gz' && $gzip) {
         $aSupported = array('x-gzip' => 'gz', 'gzip' => 'gz', 'deflate' => 'deflate');
         if (isset($_SERVER['HTTP_ACCEPT_ENCODING'])) {
             $aAccepted = array_map('trim', (array) explode(',', $_SERVER['HTTP_ACCEPT_ENCODING']));
             $aEncodings = array_intersect($aAccepted, array_keys($aSupported));
         } else {
             $aEncodings = array('gzip');
         }
         if (!empty($aEncodings)) {
             foreach ($aEncodings as $sEncoding) {
                 if ($aSupported[$sEncoding] == 'gz' || $aSupported[$sEncoding] == 'deflate') {
                     $sGzFile = gzencode($sFile, 4, $aSupported[$sEncoding] == 'gz' ? FORCE_GZIP : FORCE_DEFLATE);
                     if ($sGzFile === FALSE) {
                         continue;
                     }
                     header('Content-Encoding: ' . $sEncoding);
                     $sFile = $sGzFile;
                     break;
                 }
             }
         }
     }
     header('Content-Length: ' . strlen($sFile));
     echo $sFile;
 }
Ejemplo n.º 19
0
 /**
  * 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 static function minifyHtml($sHtml, $oParams)
 {
     JCH_DEBUG ? JchPlatformProfiler::mark('beforeMinifyHtml plgSystem (JCH Optimize)') : null;
     $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');
     }
     $aOptions['minify_level'] = $oParams->get('html_minify_level', 2);
     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;
 }
Ejemplo n.º 20
0
 /**
  * 
  * @param type $message
  * @param type $category
  */
 public static function log($message, $priority, $filename)
 {
     $file = JchPlatformUtility::getLogsPath() . '/jch-optimize.log';
     error_log($message . "\n", 3, $file);
 }
Ejemplo n.º 21
0
 /**
  * Uses regex to find css declarations containing background images to include in sprite
  * 
  * @param string $sCss  Aggregated css file
  * @return array        Array of css declarations and image urls to replace with sprite
  */
 public function processCssUrls($sCss, $bBackend = FALSE)
 {
     //JCH_DEBUG ? JchPlatformProfiler::mark('beforeProcessCssUrls plgSystem (JCH Optimize)') : null;
     $params = $this->params;
     $aRegexStart = array();
     $aRegexStart[0] = '
                     #(?:{
                             (?=\\s*+(?>[^}\\s:]++[:\\s]++)*?url\\(
                                     (?=[^)]+\\.(?:png|gif|jpe?g))
                             ([^)]+)\\))';
     $aRegexStart[1] = '
                     (?=\\s*+(?>[^}\\s:]++[:\\s]++)*?no-repeat)';
     $aRegexStart[2] = '
                     (?(?=\\s*(?>[^};]++[;\\s]++)*?background(?:-position)?\\s*+:\\s*+(?:[^;}\\s]++[^}\\S]++)*?
                             (?<p>(?:[tblrc](?:op|ottom|eft|ight|enter)|-?[0-9]+(?:%|[c-x]{2})?))(?:\\s+(?&p))?)
                                     (?=\\s*(?>[^};]++[;\\s]++)*?background(?:-position)?\\s*+:\\s*+(?>[^;}\\s]++[\\s]++)*?
                                             (?:left|top|0(?:%|[c-x]{2})?)\\s+(?:left|top|0(?:%|[c-x]{2})?)
                                     )
                     )';
     $sRegexMiddle = '   
                     [^{}]++} )';
     $sRegexEnd = '#isx';
     $aIncludeImages = JchOptimize::getArray($params->get('csg_include_images'));
     $aExcludeImages = JchOptimize::getArray($params->get('csg_exclude_images'));
     $sIncImagesRegex = '';
     if (!empty($aIncludeImages[0])) {
         foreach ($aIncludeImages as &$sImage) {
             $sImage = preg_quote($sImage, '#');
         }
         $sIncImagesRegex .= '
                             |(?:{
                                     (?=\\s*+(?>[^}\\s:]++[:\\s]++)*?url';
         $sIncImagesRegex .= ' (?=[^)]* [/(](?:' . implode('|', $aIncludeImages) . ')\\))';
         $sIncImagesRegex .= '\\(([^)]+)\\)
                                     )
                                     [^{}]++ })';
     }
     $sExImagesRegex = '';
     if (!empty($aExcludeImages[0])) {
         $sExImagesRegex .= '(?=\\s*+(?>[^}\\s:]++[:\\s]++)*?url\\(
                                                     [^)]++  (?<!';
         foreach ($aExcludeImages as &$sImage) {
             $sImage = preg_quote($sImage, '#');
         }
         $sExImagesRegex .= implode('|', $aExcludeImages) . ')\\)
                                                     )';
     }
     $sRegexStart = implode('', $aRegexStart);
     $sRegex = $sRegexStart . $sExImagesRegex . $sRegexMiddle . $sIncImagesRegex . $sRegexEnd;
     if (preg_match_all($sRegex, $sCss, $aMatches) === FALSE) {
         throw new Exception(JchPlatformUtility::translate('Error occurred matching for images to sprite'));
     }
     if (isset($aMatches[3])) {
         $total = count($aMatches[1]);
         for ($i = 0; $i < $total; $i++) {
             $aMatches[1][$i] = trim($aMatches[1][$i]) ? $aMatches[1][$i] : $aMatches[3][$i];
         }
     }
     if ($bBackend) {
         $aImages = array();
         $aImagesMatches = array();
         $aImgRegex = array();
         $aImgRegex[0] = $aRegexStart[0];
         $aImgRegex[2] = $aRegexStart[1];
         $aImgRegex[4] = $sRegexMiddle;
         $aImgRegex[5] = $sRegexEnd;
         $sImgRegex = implode('', $aImgRegex);
         if (preg_match_all($sImgRegex, $sCss, $aImagesMatches) === FALSE) {
             throw new Exception(JchPlatformUtility::translate('Error occurred matching for images to include'));
         }
         $aImagesMatches[0] = array_diff($aImagesMatches[0], $aMatches[0]);
         $aImagesMatches[1] = array_diff($aImagesMatches[1], $aMatches[1]);
         $oCssSpriteGen = new CssSpriteGen($this->getImageLibrary(), $this->params, $bBackend);
         $aImages['include'] = $oCssSpriteGen->CreateSprite($aImagesMatches[1]);
         $aImages['exclude'] = $oCssSpriteGen->CreateSprite($aMatches[1]);
         return $aImages;
     }
     //JCH_DEBUG ? JchPlatformProfiler::mark('afterProcessCssUrls plgSystem (JCH Optimize)') : null;
     return $aMatches;
 }
Ejemplo n.º 22
0
 /**
  * 
  * @return type
  */
 public static function getUtilityIcons()
 {
     $aButtons = array();
     $aButtons[1]['link'] = JchPlatformPaths::adminController('browsercaching');
     $aButtons[1]['icon'] = 'fa-globe';
     $aButtons[1]['color'] = '#51A351';
     $aButtons[1]['text'] = JchPlatformUtility::translate('Leverage browser caching');
     $aButtons[1]['script'] = '';
     $aButtons[1]['class'] = 'enabled';
     $aButtons[1]['tooltip'] = JchPlatformUtility::translate('Use this button to add codes to your htaccess file to leverage browser caching.');
     $aButtons[3]['link'] = JchPlatformPaths::adminController('filepermissions');
     $aButtons[3]['icon'] = 'fa-file-text';
     $aButtons[3]['color'] = '#166BEC';
     $aButtons[3]['text'] = JchPlatformUtility::translate('Fix file permissions');
     $aButtons[3]['script'] = '';
     $aButtons[3]['class'] = 'enabled';
     $aButtons[3]['tooltip'] = JchPlatformUtility::translate('If your site has lost CSS formatting after enabling the plugin, the problem could be that the plugin files were installed with incorrect file permissions so the browser cannot access the cached combined file. Click here to correct the plugin\'s file permissions.');
     $aButtons[5]['link'] = JchPlatformPaths::adminController('cleancache');
     $aButtons[5]['icon'] = 'fa-times-circle';
     $aButtons[5]['color'] = '#C0110A';
     $aButtons[5]['text'] = JchPlatformUtility::translate('Clean Cache');
     $aButtons[5]['script'] = '';
     $aButtons[5]['class'] = 'enabled';
     $aButtons[5]['tooltip'] = JchPlatformUtility::translate('Click this button to clean the plugin\'s cache and page cache. If you have edited any CSS or javascript files you need to clean the cache so the changes can be visible.');
     return $aButtons;
 }
Ejemplo n.º 23
0
 /**
  * 
  * @param type $image
  * @return type
  */
 public static function prepareImageUrl($image)
 {
     return array('path' => JchPlatformUtility::encrypt($image));
 }
Ejemplo n.º 24
0
 /**
  * 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 static function minifyHtml($sHtml, $oParams)
 {
     JCH_DEBUG ? JchPlatformProfiler::start('MinifyHtml') : null;
     if ($oParams->get('html_minify', 0)) {
         $aOptions = array();
         if ($oParams->get('css_minify', 0)) {
             $aOptions['cssMinifier'] = array('JchOptimize\\CSS_Optimize', 'optimize');
         }
         if ($oParams->get('js_minify', 0)) {
             $aOptions['jsMinifier'] = array('JchOptimize\\JS_Optimize', 'optimize');
         }
         $aOptions['minify_level'] = $oParams->get('html_minify_level', 2);
         $sHtmlMin = HTML_Optimize::optimize($sHtml, $aOptions);
         if ($sHtmlMin == '') {
             JchOptimizeLogger::log(JchPlatformUtility::translate('Error while minifying HTML'), $oParams);
             $sHtmlMin = $sHtml;
         }
         $sHtml = $sHtmlMin;
         JCH_DEBUG ? JchPlatformProfiler::stop('MinifyHtml', TRUE) : null;
     }
     return $sHtml;
 }
Ejemplo n.º 25
0
 /**
  * Use generated id to cache aggregated file
  *
  * @param string $sType           css or js
  * @param string $sLink           Url for aggregated file
  */
 protected function combineFiles($aLinks, $sId, $sType)
 {
     //JCH_DEBUG ? JchPlatformProfiler::mark('beforeProcessLink plgSystem (JCH Optimize)') : null;
     $aArgs = array($aLinks, $sType, $this->oParser);
     $oCombiner = new JchOptimizeCombiner($this->params);
     $aFunction = array(&$oCombiner, 'getContents');
     $bCached = $this->loadCache($aFunction, $aArgs, $sId);
     if ($bCached === FALSE) {
         throw new Exception(JchPlatformUtility::translate('Error creating cache file'));
     }
     return $bCached;
     //JCH_DEBUG ? JchPlatformProfiler::mark('afterProcessLink plgSystem (JCH Optimize)') : null;
 }
Ejemplo n.º 26
0
 /**
  * Get the search area to be used..head section or body
  * 
  * @param type $sHead   
  * @return type
  */
 public function getBodyHtml()
 {
     //JCH_DEBUG ? JchPlatformProfiler::mark('beforeGetSearchArea plgSystem (JCH Optimize)') : null;
     if ($this->sBodyHtml == '') {
         if (preg_match($this->getBodyRegex(), $this->sHtml, $aBodyMatches) === FALSE || empty($aBodyMatches)) {
             throw new Exception(JchPlatformUtility::translate('Error occurred while trying to match for search area.' . ' Check your template for open and closing body tags'));
         }
         $this->sBodyHtml = $aBodyMatches[0];
     }
     //JCH_DEBUG ? JchPlatformProfiler::mark('afterGetSearchArea plgSystem (JCH Optimize)') : null;
     return $this->sBodyHtml;
 }
Ejemplo n.º 27
0
 /**
  * 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;
 }
Ejemplo n.º 28
0
 /**
  * 
  * @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;
 }
Ejemplo n.º 29
0
 /**
  * 
  */
 public static function menuId()
 {
     return JchPlatformUtility::get('Itemid');
 }
Ejemplo n.º 30
0
 /**
  * Converts url of background images in css files to absolute path
  * 
  * @param string $sContent
  * @return string
  */
 public function correctUrl($sContent)
 {
     $sCorrectedContent = preg_replace_callback("#{$this->l}|{$this->b}|url\\(\\s*+\\K['\"]?((?(?<=['\"])[^'\"\\)]++|(?>(?:(?<=\\\\)[\\s)])?[^\\s)]*+)*?(?=(?<!\\\\)[\\s)])))['\"]?#i", array(__CLASS__, '_correctUrlCB'), $sContent);
     if (is_null($sCorrectedContent)) {
         throw new Exception(JchPlatformUtility::translate('Failed correcting urls of background images'));
     }
     $sContent = $sCorrectedContent;
     return $sContent;
 }