/** * Return full path to log file for module * Path used in priority * 1) W3TC_DEBUG_DIR * 2) WP_DEBUG_LOG * 3) W3TC_CACHE_DIR * * @param unknown $module * @param null $blog_id * @return string */ public static function log_filename($module, $blog_id = null) { if (is_null($blog_id)) { $blog_id = Util_Environment::blog_id(); } $postfix = sprintf('%06d', $blog_id); if (defined('W3TC_BLOG_LEVELS')) { for ($n = 0; $n < W3TC_BLOG_LEVELS; $n++) { $postfix = substr($postfix, strlen($postfix) - 1 - $n, 1) . '/' . $postfix; } } $from_dir = W3TC_CACHE_DIR; if (defined('W3TC_DEBUG_DIR') && W3TC_DEBUG_DIR) { $dir_path = W3TC_DEBUG_DIR; if (!is_dir(W3TC_DEBUG_DIR)) { $from_dir = dirname(W3TC_DEBUG_DIR); } } else { $dir_path = Util_Environment::cache_dir('log'); } $filename = $dir_path . '/' . $postfix . '/' . $module . '.log'; if (!is_dir(dirname($filename))) { Util_File::mkdir_from(dirname($filename), $from_dir); } return $filename; }
public static function get_uri_reservede_words($additional_list = array()) { $uri_reservede_words = array('index', 'list', 'api', 'get', 'post', 'put', 'delete', 'create', 'edit', 'comment', 'like'); $uri_reservede_words = array_merge($uri_reservede_words, array_keys(Module::loaded())); // modules $uri_reservede_words = array_merge($uri_reservede_words, Util_File::get_file_names(APPPATH . 'classes/controller', false, true)); // controller files if ($additional_list) { $uri_reservede_words = array_merge($uri_reservede_words, $additional_list); } return array_unique($uri_reservede_words); }
public static function CreatePdf($contents, $filename) { if (!$contents) { return ''; } $snappy = Lib_Plugins::CreateSnappyPdf(); $snappy->setOption('lowquality', false); $snappy->setOption('margin-top', '31'); $dir = dirname($filename); Util_File::MkDir($dir); $snappy->generateFromHtml($contents, $filename); return file_exists($filename) ? true : false; }
public static function save_from_file_path($file_path, $save_name = '', $is_image = true) { if (!($bin = Util_file::get_encoded_bin_data($file_path, $is_image))) { throw new FuelException('Binary data is invalid.'); } $obj = self::forge(); $filepath = Util_File::get_filepath_from_path($file_path); if (!$save_name) { $save_name = Site_Upload::convert_filepath2filename($filepath); } $obj->name = $save_name; $obj->bin = $bin; return $obj->save(); }
/** * JS * * Either adds the javascript to the group, or returns the script tag. * * @access public * @param mixed The file name, or an array files. * @param array An array of extra attributes * @param string The asset group name * $raw bool If set to true the result css tags will include the file contents directly instead of via a link tag. * $is_minify bool If set to true minify and combine files at only prod env. * @return string */ public static function js($stylesheets = array(), $attr = array(), $group = NULL, $raw = false, $is_minify = false, $is_use_minified_file = false) { if (Fuel::$env == Fuel::PRODUCTION) { if ($is_minify) { foreach ($stylesheets as $stylesheet) { Casset::js($stylesheet, false, $group); } return; } if ($is_use_minified_file) { $stylesheets = Util_File::convert_filename2min($stylesheets); } } return parent::js($stylesheets, $attr, $group, $raw); }
/** * Returns array of files from sizes array * * @param string $attached_file * @param array $sizes * @return array */ function _get_sizes_files($attached_file, $sizes) { $files = array(); $base_dir = Util_File::dirname($attached_file); foreach ((array) $sizes as $size) { if (isset($size['file'])) { if ($base_dir) { $file = $base_dir . '/' . $size['file']; } else { $file = $size['file']; } $files = array_merge($files, $this->get_files_for_upload($file)); } } return $files; }
/** * W3 writable error * * @param string $path * @param string[] $chmod_dirs Directories that should be chmod 777 inorder to write */ public static function throw_on_write_error($path, $chmod_dirs = array()) { $chmods = ''; if ($chmod_dirs) { $chmods = '<ul>'; foreach ($chmod_dirs as $dir) { $chmods .= sprintf(__('<li><strong style="color: #f00;">chmod 777 %s</strong></li>', 'w3-total-cache'), $dir); } } else { $chmods = sprintf('<strong style="color: #f00;">chmod 777 %s</strong>', file_exists($path) ? $path : dirname($path)); } if (Util_File::check_open_basedir($path)) { $error = sprintf(__('<strong>%s</strong> could not be created, please run following command:<br />%s', 'w3-total-cache'), $path, $chmods); } else { $error = sprintf(__('<strong>%s</strong> could not be created, <strong>open_basedir </strong> restriction in effect, please check your php.ini settings:<br /> <strong style="color: #f00;">open_basedir = "%s"</strong>', 'w3-total-cache'), $path, ini_get('open_basedir')); } throw new \Exception($error); }
protected function save_file_bin($tmp_file_path) { switch ($this->options['storage_type']) { case 'db': $storage_save_result = (bool) Model_FileBin::save_from_file_path($tmp_file_path, $this->file->name); break; case 'S3': $storage_save_result = (bool) Site_S3::save($tmp_file_path, null, $this->options['upload_type']); break; case 'normal': default: $storage_save_result = true; break; } if (!$storage_save_result) { Util_File::remove($tmp_file_path); throw new FuelException('Save raw file error to storage.'); } if (!($result = (bool) Util_file::move($tmp_file_path, $this->file->file_path))) { throw new FuelException('Save raw file error.'); } return $storage_save_result && $result; }
/** * @dataProvider get_filename_without_extension_provider */ public function test_get_filename_without_extension($filename = null, $expected = null) { $test = Util_File::get_filename_without_extension($filename); $this->assertEquals($expected, $test); }
<?php echo htmlspecialchars($uploads_dir['path']); ?> : <?php if (!empty($uploads_dir['error'])) { ?> <code><?php _e('Error:', 'w3-total-cache'); ?> <?php echo htmlspecialchars($uploads_dir['error']); ?> </code> <?php } elseif (!Util_File::is_writable_dir($uploads_dir['path'])) { ?> <code><?php _e('Not write-able', 'w3-total-cache'); ?> </code> <?php } else { ?> <code><?php _e('OK', 'w3-total-cache'); ?> </code> <?php } ?>
/** * * * @param Config $config * @return string */ function w3tc_notes($notes) { $c = Dispatcher::config(); $state = Dispatcher::config_state(); $state_master = Dispatcher::config_state_master(); $state_note = Dispatcher::config_state_note(); /** * Check wp-content permissions */ if (!W3TC_WIN && !$state_master->get_boolean('common.hide_note_wp_content_permissions')) { $wp_content_mode = Util_File::get_file_permissions(WP_CONTENT_DIR); if ($wp_content_mode > 0755) { $notes['generic_wp_content_writeable'] = sprintf(__('<strong>%s</strong> is write-able. When finished installing the plugin, change the permissions back to the default: <strong>chmod 755 %s</strong>. Permissions are currently %s. %s', 'w3-total-cache'), WP_CONTENT_DIR, WP_CONTENT_DIR, base_convert(Util_File::get_file_permissions(WP_CONTENT_DIR), 10, 8), Util_Ui::button_hide_note2(array('w3tc_default_config_state_master' => 'y', 'key' => 'common.hide_note_wp_content_permissions', 'value' => 'true'))); } } /** * Check Zlib extension */ if (!$state_master->get_boolean('common.hide_note_no_zlib') && !function_exists('gzencode')) { $notes['no_zlib'] = sprintf(__('Unfortunately the PHP installation is incomplete, the <strong>zlib module is missing</strong>. This is a core PHP module. Notify the server administrator. %s', 'w3-total-cache'), Util_Ui::button_hide_note2(array('w3tc_default_config_state_master' => 'y', 'key' => 'common.hide_note_no_zlib', 'value' => 'true'))); } /** * Check if Zlib output compression is enabled */ if (!$state_master->get_boolean('common.hide_note_zlib_output_compression') && Util_Environment::is_zlib_enabled()) { $notes['zlib_output_compression'] = sprintf(__('Either the PHP configuration, web server configuration or a script in the WordPress installation has <strong>zlib.output_compression</strong> enabled.<br />Please locate and disable this setting to ensure proper HTTP compression behavior. %s', 'w3-total-cache'), Util_Ui::button_hide_note2(array('w3tc_default_config_state_master' => 'y', 'key' => 'common.hide_note_zlib_output_compression', 'value' => 'true'))); } if ($state_master->get_boolean('common.show_note.nginx_restart_required')) { $cf = Dispatcher::component('CacheFlush'); $notes['nginx_restart_required'] = sprintf(__('nginx.conf rules have been updated. Please restart nginx server to provide a consistent user experience. %s', 'w3-total-cache'), Util_Ui::button_hide_note2(array('w3tc_default_config_state_master' => 'y', 'key' => 'common.show_note.nginx_restart_required', 'value' => 'false'))); } /** * Preview mode */ if ($c->is_preview()) { $notes['preview_mode'] = sprintf(__('Preview mode is active: Changed settings will not take effect until preview mode is %s or %s.', 'w3-total-cache'), Util_Ui::button_link(__('deploy', 'w3-total-cache'), Util_Ui::url(array('w3tc_config_preview_deploy' => 'y'))), Util_Ui::button_link(__('disable', 'w3-total-cache'), Util_Ui::url(array('w3tc_config_preview_disable' => 'y')))) . '<br /><span class="description">' . sprintf(__('To preview any changed settings (without deploying): %s', 'w3-total-cache'), Util_Ui::preview_link()) . '</span>'; } /** * Show notification after plugin activate/deactivate */ if ($state_note->get('common.show_note.plugins_updated') && !is_network_admin()) { $texts = array(); if ($c->get_boolean('pgcache.enabled')) { $texts[] = Util_Ui::button_link(__('empty the page cache', 'w3-total-cache'), Util_Ui::url(array('w3tc_flush_posts' => 'y'))); } if ($c->get_boolean('minify.enabled')) { $texts[] = sprintf(__('check the %s to maintain the desired user experience', 'w3-total-cache'), Util_Ui::button_link(__('minify settings', 'w3-total-cache'), Util_Ui::url(array('w3tc_default_config_state_note' => 'y', 'key' => 'common.show_note.plugins_updated', 'value' => 'false')))); } if (count($texts)) { $notes['some_plugins_activated'] = sprintf(__('One or more plugins have been activated or deactivated, please %s. %s', 'w3-total-cache'), implode(__(' and ', 'w3-total-cache'), $texts), Util_Ui::button_hide_note2(array('w3tc_default_config_state_note' => 'y', 'key' => 'common.show_note.plugins_updated', 'value' => 'false'))); } } /** * Show notification when flush_statics needed */ if ($c->get_boolean('browsercache.enabled') && $state_note->get('common.show_note.flush_statics_needed') && !is_network_admin() && !$c->is_preview()) { $notes['flush_statics_needed'] = sprintf(__('The setting change(s) made either invalidate the cached data or modify the behavior of the site. %s now to provide a consistent user experience. %s', 'w3-total-cache'), Util_Ui::button_link('Empty the static files cache', Util_Ui::url(array('w3tc_flush_statics' => 'y'))), Util_Ui::button_hide_note2(array('w3tc_default_config_state_note' => 'y', 'key' => 'common.show_note.flush_statics_needed', 'value' => 'false'))); } /** * Show notification when flush_posts needed */ if ($state_note->get('common.show_note.flush_posts_needed') && !is_network_admin() && !$c->is_preview() && !isset($notes['flush_statics_needed'])) { $cf = Dispatcher::component('CacheFlush'); if ($cf->flushable_posts()) { $notes['flush_posts_needed'] = sprintf(__('The setting change(s) made either invalidate the cached data or modify the behavior of the site. %s now to provide a consistent user experience. %s', 'w3-total-cache'), Util_Ui::button_link('Empty the page cache', Util_Ui::url(array('w3tc_flush_posts' => 'y'))), Util_Ui::button_hide_note2(array('w3tc_default_config_state_note' => 'y', 'key' => 'common.show_note.flush_posts_needed', 'value' => 'false'))); } } return $notes; }
/** * Initializes minifier * * @param string $engine * @return void */ function init($engine) { switch ($engine) { case 'yuijs': Minify_YUICompressor::$tempDir = Util_File::create_tmp_dir(); Minify_YUICompressor::$javaExecutable = $this->_config->get_string('minify.yuijs.path.java'); Minify_YUICompressor::$jarFile = $this->_config->get_string('minify.yuijs.path.jar'); break; case 'yuicss': Minify_YUICompressor::$tempDir = Util_File::create_tmp_dir(); Minify_YUICompressor::$javaExecutable = $this->_config->get_string('minify.yuicss.path.java'); Minify_YUICompressor::$jarFile = $this->_config->get_string('minify.yuicss.path.jar'); break; case 'ccjs': Minify_ClosureCompiler::$tempDir = Util_File::create_tmp_dir(); Minify_ClosureCompiler::$javaExecutable = $this->_config->get_string('minify.ccjs.path.java'); Minify_ClosureCompiler::$jarFile = $this->_config->get_string('minify.ccjs.path.jar'); break; } }
private function fopen_write($key, $group, $mode) { $storage_key = $this->get_item_key($key); $sub_path = $this->_get_path($storage_key); $path = $this->_cache_dir . DIRECTORY_SEPARATOR . ($group ? $group . DIRECTORY_SEPARATOR : '') . $sub_path; $dir = dirname($path); if (!@is_dir($dir)) { if (!Util_File::mkdir_from($dir, W3TC_CACHE_DIR)) { return false; } } $fp = @fopen($path, $mode); return $fp; }
/** * * @param * $p_sKey * @param * $p_sExt * @param * $p_oFileInfo * @param * $p_sDomain * @param int $p_iWidth * @param int $p_iHeight * @return int */ public function getFile($p_sKey, $p_sExt, &$p_oFileInfo, $p_sDomain, $p_iWidth = 0, $p_iHeight = 0, $p_bCrop = false, $p_iWaterMarkPosition = 0, $p_iWaterMarkPath = 0, $p_isDown = false, $p_sBid = Model_FileMeta::BID_DEFAULT) { $iError = 0; do { $aFileInfo = $this->getFileInfo($p_sKey); $bWaterMark = true; if (Model_FileMeta::BID_BANNER == ($aFileInfo['iBID'] & $p_sBid)) { $bWaterMark = false; } if (!$aFileInfo) { $iError = self::FILE_NOT_EXISTS; break; } if ($aFileInfo['sExt'] != $p_sExt) { $iError = self::FILE_EXT_INVAILD; break; } $p_sMimeType = $aFileInfo['sMimeType']; if ($p_isDown) { $aDomainViewType = $this->getAllowedDownloadType($p_sDomain); } else { $aDomainViewType = $this->getAllowedViewType($p_sDomain); } if (!in_array($p_sExt, $aDomainViewType)) { $iError = self::FILE_MIMETYPE_NOT_ALLOWED; break; } $sFilePath = $this->getDestFile($p_sKey); $sFileContent = Util_File::tryReadFile($sFilePath); if (false === $sFileContent) { $iError = self::FILE_NOT_EXISTS; break; } if ($this->isImage($p_sExt)) { $utilImg = Util_ImageFactory::instance('gd'); $aDomainDimension = $this->getAllowedImageDimension($p_sDomain); // 针对图片操作 $imgResource = imagecreatefromstring($sFileContent); if (!$imgResource) { $iError = self::FILE_NOT_EXISTS; break; } /* $sDimensionKey = $p_iWidth . 'x' . $p_iHeight; if ($p_iWidth > 0 && $p_iHeight > 0 && ! array_key_exists($sDimensionKey, $aDomainDimension)) { $iError = self::FILE_IMAGE_DIMENSION_NOT_ALLOWED; break; } */ $sFileContent = $this->resizeImage($imgResource, $p_iWidth, $p_iHeight, $aDomainDimension, $p_sMimeType, $p_bCrop, $bWaterMark, $p_iWaterMarkPosition, $p_iWaterMarkPath); $p_sETag = $utilImg->buildEtagFromImg($sFileContent); $aFileInfo['iSize'] = sizeof($sFileContent); } else { $p_sETag = $p_sKey; } $p_oFileInfo = ['sContent' => $sFileContent, 'sETag' => $p_sETag, 'sExt' => $aFileInfo['sExt'], 'sMimeType' => $p_sMimeType, 'iSize' => $aFileInfo['iSize'], 'sName' => substr($aFileInfo['sName'], 0, strrpos($aFileInfo['sName'], '.'))]; $iError = true; } while (false); return $iError; }
/** * Flush cache based on regex * * @param string $regex */ private function _flush_based_on_regex($regex) { if (Util_Environment::is_wpmu() && !Util_Environment::is_wpmu_subdomain()) { $domain = get_home_url(); $parsed = parse_url($domain); $host = $parsed['host']; $path = isset($parsed['path']) ? '/' . trim($parsed['path'], '/') : ''; $flush_dir = W3TC_CACHE_PAGE_ENHANCED_DIR . '/' . $host . $path; } else { $flush_dir = W3TC_CACHE_PAGE_ENHANCED_DIR . '/' . Util_Environment::host(); } $dir = @opendir($flush_dir); if ($dir) { while (($entry = @readdir($dir)) !== false) { if ($entry == '.' || $entry == '..') { continue; } if (preg_match('/' . $regex . '/', basename($entry))) { Util_File::rmdir($flush_dir . DIRECTORY_SEPARATOR . $entry); } } @closedir($dir); } }
/** * * * @param Util_Environment_Exceptions $exs * @param string $path * @param string $rules * @param string $start * @param string $end * @param array $order */ public static function add_rules($exs, $path, $rules, $start, $end, $order) { if (empty($path)) { return; } $data = @file_get_contents($path); if ($data === false) { $data = ''; } $rules_missing = !empty($rules) && strstr(Util_Rule::clean_rules($data), Util_Rule::clean_rules($rules)) === false; if (!$rules_missing) { return; } $replace_start = strpos($data, $start); $replace_end = strpos($data, $end); if ($replace_start !== false && $replace_end !== false && $replace_start < $replace_end) { $replace_length = $replace_end - $replace_start + strlen($end) + 1; } else { $replace_start = false; $replace_length = 0; $search = $order; foreach ($search as $string => $length) { $replace_start = strpos($data, $string); if ($replace_start !== false) { $replace_start += $length; break; } } } if ($replace_start !== false) { $data = Util_Rule::trim_rules(substr_replace($data, $rules, $replace_start, $replace_length)); } else { $data = Util_Rule::trim_rules($data . $rules); } if (strpos($path, W3TC_CACHE_DIR) === false || Util_Environment::is_nginx()) { try { Util_WpFile::write_to_file($path, $data); } catch (Util_WpFile_FilesystemOperationException $ex) { if ($replace_start !== false) { $exs->push(new Util_WpFile_FilesystemModifyException($ex->getMessage(), $ex->credentials_form(), sprintf(__('Edit file <strong>%s </strong> and replace all lines between and including <strong>%s</strong> and <strong>%s</strong> markers with:', 'w3-total-caceh'), $path, $start, $end), $path, $rules)); } else { $exs->push(new Util_WpFile_FilesystemModifyException($ex->getMessage(), $ex->credentials_form(), sprintf(__('Edit file <strong>%s</strong> and add the following rules above the WordPress directives:', 'w3-total-cache'), $path), $path, $rules)); } return; } } else { if (!@file_exists(dirname($path))) { Util_File::mkdir_from(dirname($path), W3TC_CACHE_DIR); } if (!@file_put_contents($path, $data)) { try { Util_WpFile::delete_folder(dirname($path), '', $_SERVER['REQUEST_URI']); } catch (Util_WpFile_FilesystemOperationException $ex) { $exs->push($ex); return; } } } Util_Rule::after_rules_modified(); }
/** * Creates file for CDN upload. * Needed because minify can handle urls of non-existing files but CDN needs * real file to upload it */ public static function create_file_for_cdn($filename) { $minify_enabled = self::config()->get_boolean('minify.enabled'); if ($minify_enabled) { $minify_document_root = Util_Environment::cache_blog_dir('minify') . '/'; if (!substr($filename, 0, strlen($minify_document_root)) == $minify_document_root) { // unexpected file name return; } $short_filename = substr($filename, strlen($minify_document_root)); $minify = Dispatcher::component('Minify_MinifiedFileRequestHandler'); $data = $minify->process($short_filename, true); if (!file_exists($filename) && isset($data['content']['content'])) { if (!file_exists(dirname($filename))) { Util_File::mkdir_from(dirname($filename), W3TC_CACHE_DIR); } } @file_put_contents($filename, $data['content']['content']); } }
/** * 导出自媒体 */ public function exportAction() { $iType = $this->getParam('type', 1); $sCookieKey = 'media_choose_' . $iType; $aData['aChooseID'] = !empty($_COOKIE[$sCookieKey]) ? explode(',', $_COOKIE[$sCookieKey]) : array(); $aData['aChoose'] = array(); foreach ($aData['aChooseID'] as $k => $v) { $aRow = Model_Media::getDetail($v); $aRow['sTags'] = Model_Media::getTagNames($v['iMediaID']); $aRow['sCitys'] = Model_Media::getCityNames($v['iMediaID']); $aData['aChoose'][] = $aRow; } $aTitle = array(Model_Media::TYPE_WEIXIN => array('sMediaName' => '帐号名称', 'sOpenName' => '公众号', 'iFollowerNum' => '粉丝量', 'iPrice1' => '单图文价格', 'iPrice2' => '第一条价格', 'iPrice3' => '第二条价格', 'iPrice4' => '其它位置价格', 'iReadNum' => '阅读数', 'sIntroduction' => '简介', 'sTags' => '标签', 'sCertifiedText' => '认证', 'sCitys' => '地区'), Model_Media::TYPE_FRIEND => array('sMediaName' => '微信号', 'iFollowerNum' => '好友数', 'iPrice1' => '直发价格', 'iPrice2' => '转发价格'), Model_Media::TYPE_WEIBO => array('sMediaName' => '微博名', 'iFollowerNum' => '好友数', 'iPrice1' => '直发价格', 'iPrice2' => '转发价格')); Util_File::exportCsv('自媒体表-' . date('Ymd') . '.csv', $aData['aChoose'], $aTitle[$iType]); return false; }
private function _w3tc_save_options_process() { $data = array('old_config' => $this->_config, 'response_query_string' => array(), 'response_actions' => array(), 'response_errors' => array(), 'response_notes' => array('config_save')); // if we are on extension settings page - stay on the same page if (Util_Request::get_string('page') == 'w3tc_extensions') { $data['response_query_string']['page'] = Util_Request::get_string('page'); $data['response_query_string']['extension'] = Util_Request::get_string('extension'); $data['response_query_string']['action'] = Util_Request::get_string('action'); } $capability = apply_filters('w3tc_capability_config_save', 'manage_options'); if (!current_user_can($capability)) { wp_die(__('You do not have the rights to perform this action.', 'w3-total-cache')); } /** * Read config * We should use new instance of WP_Config object here */ $config = new Config(); $this->read_request($config); if ($this->_page == 'w3tc_dashboard') { if (Util_Request::get_boolean('maxcdn')) { $config->set('cdn.enabled', true); $config->set('cdn.engine', 'maxcdn'); } } /** * General tab */ if ($this->_page == 'w3tc_general') { $file_nfs = Util_Request::get_boolean('file_nfs'); $file_locking = Util_Request::get_boolean('file_locking'); $config->set('pgcache.file.nfs', $file_nfs); $config->set('minify.file.nfs', $file_nfs); $config->set('dbcache.file.locking', $file_locking); $config->set('objectcache.file.locking', $file_locking); $config->set('pgcache.file.locking', $file_locking); $config->set('minify.file.locking', $file_locking); if (is_network_admin()) { if ($this->_config->get_boolean('common.force_master') !== $config->get_boolean('common.force_master')) { // blogmap is wrong so empty it @unlink(W3TC_CACHE_BLOGMAP_FILENAME); $blogmap_dir = dirname(W3TC_CACHE_BLOGMAP_FILENAME) . '/' . basename(W3TC_CACHE_BLOGMAP_FILENAME, '.php') . '/'; if (@is_dir($blogmap_dir)) { Util_File::rmdir($blogmap_dir); } } } /** * Check permalinks for page cache */ if ($config->get_boolean('pgcache.enabled') && $config->get_string('pgcache.engine') == 'file_generic' && !get_option('permalink_structure')) { $config->set('pgcache.enabled', false); $data['response_errors'][] = 'fancy_permalinks_disabled_pgcache'; } if (!Util_Environment::is_w3tc_pro($this->_config)) { delete_transient('w3tc_license_status'); } } /** * Minify tab */ if ($this->_page == 'w3tc_minify' && !$this->_config->get_boolean('minify.auto')) { $js_groups = array(); $css_groups = array(); $js_files = Util_Request::get_array('js_files'); $css_files = Util_Request::get_array('css_files'); foreach ($js_files as $theme => $templates) { foreach ($templates as $template => $locations) { foreach ((array) $locations as $location => $types) { foreach ((array) $types as $files) { foreach ((array) $files as $file) { if (!empty($file)) { $js_groups[$theme][$template][$location]['files'][] = Util_Environment::normalize_file_minify($file); } } } } } } foreach ($css_files as $theme => $templates) { foreach ($templates as $template => $locations) { foreach ((array) $locations as $location => $files) { foreach ((array) $files as $file) { if (!empty($file)) { $css_groups[$theme][$template][$location]['files'][] = Util_Environment::normalize_file_minify($file); } } } } } $config->set('minify.js.groups', $js_groups); $config->set('minify.css.groups', $css_groups); $js_theme = Util_Request::get_string('js_theme'); $css_theme = Util_Request::get_string('css_theme'); $data['response_query_string']['js_theme'] = $js_theme; $data['response_query_string']['css_theme'] = $css_theme; } /** * Browser Cache tab */ if ($this->_page == 'w3tc_browsercache') { if ($config->get_boolean('browsercache.enabled') && $config->get_boolean('browsercache.no404wp') && !get_option('permalink_structure')) { $config->set('browsercache.no404wp', false); $data['response_errors'][] = 'fancy_permalinks_disabled_browsercache'; } // todo: move to cdn module if (in_array($engine = $this->_config->get_string('cdn.engine'), array('netdna', 'maxcdn'))) { require_once W3TC_LIB_NETDNA_DIR . '/NetDNA.php'; $keys = explode('+', $this->_config->get_string('cdn.' . $engine . '.authorization_key')); if (sizeof($keys) == 3) { list($alias, $consumerkey, $consumersecret) = $keys; try { $api = new \NetDNA($alias, $consumerkey, $consumersecret); $disable_cooker_header = $config->get_boolean('browsercache.other.nocookies') || $config->get_boolean('browsercache.cssjs.nocookies'); $api->update_pull_zone($this->_config->get_string('cdn.' . $engine . '.zone_id'), array('ignore_setcookie_header' => $disable_cooker_header)); } catch (\Exception $ex) { } } } } /** * Mobile tab */ if ($this->_page == 'w3tc_mobile') { $groups = Util_Request::get_array('mobile_groups'); $mobile_groups = array(); $cached_mobile_groups = array(); foreach ($groups as $group => $group_config) { $group = strtolower($group); $group = preg_replace('~[^0-9a-z_]+~', '_', $group); $group = trim($group, '_'); if ($group) { $theme = isset($group_config['theme']) ? trim($group_config['theme']) : 'default'; $enabled = isset($group_config['enabled']) ? (bool) $group_config['enabled'] : true; $redirect = isset($group_config['redirect']) ? trim($group_config['redirect']) : ''; $agents = isset($group_config['agents']) ? explode("\r\n", trim($group_config['agents'])) : array(); $mobile_groups[$group] = array('theme' => $theme, 'enabled' => $enabled, 'redirect' => $redirect, 'agents' => $agents); $cached_mobile_groups[$group] = $agents; } } /** * Allow plugins modify WPSC mobile groups */ $cached_mobile_groups = apply_filters('cached_mobile_groups', $cached_mobile_groups); /** * Merge existent and delete removed groups */ foreach ($mobile_groups as $group => $group_config) { if (isset($cached_mobile_groups[$group])) { $mobile_groups[$group]['agents'] = (array) $cached_mobile_groups[$group]; } else { unset($mobile_groups[$group]); } } /** * Add new groups */ foreach ($cached_mobile_groups as $group => $agents) { if (!isset($mobile_groups[$group])) { $mobile_groups[$group] = array('theme' => '', 'enabled' => true, 'redirect' => '', 'agents' => $agents); } } /** * Allow plugins modify W3TC mobile groups */ $mobile_groups = apply_filters('w3tc_mobile_groups', $mobile_groups); /** * Sanitize mobile groups */ foreach ($mobile_groups as $group => $group_config) { $mobile_groups[$group] = array_merge(array('theme' => '', 'enabled' => true, 'redirect' => '', 'agents' => array()), $group_config); $mobile_groups[$group]['agents'] = array_unique($mobile_groups[$group]['agents']); $mobile_groups[$group]['agents'] = array_map('strtolower', $mobile_groups[$group]['agents']); sort($mobile_groups[$group]['agents']); } $enable_mobile = false; foreach ($mobile_groups as $group_config) { if ($group_config['enabled']) { $enable_mobile = true; break; } } $config->set('mobile.enabled', $enable_mobile); $config->set('mobile.rgroups', $mobile_groups); } /** * Referrer tab */ if ($this->_page == 'w3tc_referrer') { $groups = Util_Request::get_array('referrer_groups'); $referrer_groups = array(); foreach ($groups as $group => $group_config) { $group = strtolower($group); $group = preg_replace('~[^0-9a-z_]+~', '_', $group); $group = trim($group, '_'); if ($group) { $theme = isset($group_config['theme']) ? trim($group_config['theme']) : 'default'; $enabled = isset($group_config['enabled']) ? (bool) $group_config['enabled'] : true; $redirect = isset($group_config['redirect']) ? trim($group_config['redirect']) : ''; $referrers = isset($group_config['referrers']) ? explode("\r\n", trim($group_config['referrers'])) : array(); $referrer_groups[$group] = array('theme' => $theme, 'enabled' => $enabled, 'redirect' => $redirect, 'referrers' => $referrers); } } /** * Allow plugins modify W3TC referrer groups */ $referrer_groups = apply_filters('w3tc_referrer_groups', $referrer_groups); /** * Sanitize mobile groups */ foreach ($referrer_groups as $group => $group_config) { $referrer_groups[$group] = array_merge(array('theme' => '', 'enabled' => true, 'redirect' => '', 'referrers' => array()), $group_config); $referrer_groups[$group]['referrers'] = array_unique($referrer_groups[$group]['referrers']); $referrer_groups[$group]['referrers'] = array_map('strtolower', $referrer_groups[$group]['referrers']); sort($referrer_groups[$group]['referrers']); } $enable_referrer = false; foreach ($referrer_groups as $group_config) { if ($group_config['enabled']) { $enable_referrer = true; break; } } $config->set('referrer.enabled', $enable_referrer); $config->set('referrer.rgroups', $referrer_groups); } /** * CDN tab */ if ($this->_page == 'w3tc_cdn') { $cdn_cnames = Util_Request::get_array('cdn_cnames'); $cdn_domains = array(); foreach ($cdn_cnames as $cdn_cname) { $cdn_cname = trim($cdn_cname); /** * Auto expand wildcard domain to 10 subdomains */ $matches = null; if (preg_match('~^\\*\\.(.*)$~', $cdn_cname, $matches)) { $cdn_domains = array(); for ($i = 1; $i <= 10; $i++) { $cdn_domains[] = sprintf('cdn%d.%s', $i, $matches[1]); } break; } if ($cdn_cname) { $cdn_domains[] = $cdn_cname; } } switch ($this->_config->get_string('cdn.engine')) { case 'ftp': $config->set('cdn.ftp.domain', $cdn_domains); break; case 's3': case 's3_compatible': $config->set('cdn.s3.cname', $cdn_domains); break; case 'cf': $config->set('cdn.cf.cname', $cdn_domains); break; case 'cf2': $config->set('cdn.cf2.cname', $cdn_domains); break; case 'rackspace_cdn': $config->set('cdn.rackspace_cdn.domains', $cdn_domains); break; case 'rscf': $config->set('cdn.rscf.cname', $cdn_domains); break; case 'azure': $config->set('cdn.azure.cname', $cdn_domains); break; case 'mirror': $config->set('cdn.mirror.domain', $cdn_domains); break; case 'maxcdn': $config->set('cdn.maxcdn.domain', $cdn_domains); break; case 'netdna': $config->set('cdn.netdna.domain', $cdn_domains); break; case 'cotendo': $config->set('cdn.cotendo.domain', $cdn_domains); break; case 'edgecast': $config->set('cdn.edgecast.domain', $cdn_domains); break; case 'att': $config->set('cdn.att.domain', $cdn_domains); break; case 'akamai': $config->set('cdn.akamai.domain', $cdn_domains); break; case 'highwinds': $config->set('cdn.highwinds.host.domains', $cdn_domains); break; } } $old_ext_settings = $this->_config->get_array('extensions.settings', array()); $new_ext_settings = $old_ext_settings; $modified = false; $extensions = Extensions_Util::get_extensions($config); foreach ($extensions as $extension => $descriptor) { $request = Util_Request::get_as_array('extensions.settings.' . $extension . '.'); if (count($request) > 0) { if (!isset($new_ext_settings[$extension])) { $new_ext_settings[$extension] = array(); } foreach ($request as $key => $value) { if (!isset($old_ext_settings[$extension]) || !isset($old_ext_settings[$extension][$key]) || $old_ext_settings[$extension][$key] != $value) { $new_ext_settings[$extension][$key] = $value; $modified = true; } } } } if ($modified) { $config->set("extensions.settings", $new_ext_settings); } $data['new_config'] = $config; $data = apply_filters('w3tc_save_options', $data); $config = $data['new_config']; do_action('w3tc_config_ui_save', $config, $this->_config); do_action("w3tc_config_ui_save-{$this->_page}", $config, $this->_config); Util_Admin::config_save($this->_config, $config); if ($this->_page == 'w3tc_cdn') { /** * Handle Set Cookie Domain */ $set_cookie_domain_old = Util_Request::get_boolean('set_cookie_domain_old'); $set_cookie_domain_new = Util_Request::get_boolean('set_cookie_domain_new'); if ($set_cookie_domain_old != $set_cookie_domain_new) { if ($set_cookie_domain_new) { if (!$this->enable_cookie_domain()) { Util_Admin::redirect(array_merge($data['response_query_string'], array('w3tc_error' => 'enable_cookie_domain'))); } } else { if (!$this->disable_cookie_domain()) { Util_Admin::redirect(array_merge($data['response_query_string'], array('w3tc_error' => 'disable_cookie_domain'))); } } } } return array('query_string' => $data['response_query_string'], 'actions' => $data['response_actions'], 'errors' => $data['response_errors'], 'notes' => $data['response_notes']); }
/** * * * @param unknown $folder * @param string $method Which method to use when creating * @param string $url Where to redirect after creation * @param bool|string $context path folder where delete folders resides * @throws Util_WpFile_FilesystemRmdirException */ public static function delete_folder($folder) { if (!@is_dir($folder)) { return; } Util_File::rmdir($folder); if (!@is_dir($folder)) { return; } try { self::request_filesystem_credentials(); } catch (Util_WpFile_FilesystemOperationException $ex) { throw new Util_WpFile_FilesystemRmdirException($ex->getMessage(), $ex->credentials_form(), $folder); } global $wp_filesystem; if (!$wp_filesystem->rmdir($folder)) { throw new Util_WpFile_FilesystemRmdirException(__('FTP credentials don\'t allow to delete folder ', 'w3-total-cache') . '<strong>' . $folder . '</strong>', self::get_filesystem_credentials_form(), $folder); } }
/** * Exports min files to CDN * * @return array */ function get_files_minify() { $files = array(); if ($this->_config->get_boolean('minify.rewrite') && Util_Rule::can_check_rules() && (!$this->_config->get_boolean('minify.auto') || Cdn_Util::is_engine_mirror($this->_config->get_string('cdn.engine')))) { $minify = Dispatcher::component('Minify_Plugin'); $document_root = Util_Environment::document_root(); $minify_root = Util_Environment::cache_blog_dir('minify'); $minify_path = ltrim(str_replace($document_root, '', $minify_root), '/'); $urls = $minify->get_urls(); // in WPMU + network admin (this code used for minify manual only) // common minify files are stored under context of main blog (i.e. 1) // but have urls of 0 blog, so download has to be used if ($this->_config->get_string('minify.engine') == 'file' && !(Util_Environment::is_wpmu() && is_network_admin())) { foreach ($urls as $url) { Util_Http::get($url); } $files = Cdn_Util::search_files($minify_root, $minify_path, '*.css;*.js'); } else { foreach ($urls as $url) { $file = Util_Environment::normalize_file_minify($url); $file = Util_Environment::translate_file($file); if (!Util_Environment::is_url($file)) { $file = $document_root . '/' . $file; $file = ltrim(str_replace($minify_root, '', $file), '/'); $dir = dirname($file); if ($dir) { Util_File::mkdir($dir, 0777, $minify_root); } if (Util_Http::download($url, $minify_root . '/' . $file) !== false) { $files[] = $minify_path . '/' . $file; } } } } } return $files; }
public static function get_filepath_from_file_path($file_path) { return Util_File::get_path_partial($file_path, 3); }
public static function get_prohibited_words_for_name() { return \Site_Util::get_uri_reservede_words(Util_File::get_file_names(APPPATH . 'classes/controller/member', false, true)); }
/** * Writes array item to file * * @param int $tabs * @param string $key * @param mixed $value * @return string */ public static function format_array_entry_as_settings_file_entry($tabs, $key, $value) { $item = str_repeat("\t", $tabs); if (is_numeric($key) && (string) (int) $key === (string) $key) { $item .= sprintf("%d => ", $key); } else { $item .= sprintf("'%s' => ", addcslashes($key, "'\\")); } switch (gettype($value)) { case 'object': case 'array': $item .= "array(\r\n"; foreach ((array) $value as $k => $v) { $item .= Util_File::format_array_entry_as_settings_file_entry($tabs + 1, $k, $v); } $item .= sprintf("%s),\r\n", str_repeat("\t", $tabs)); return $item; case 'integer': $data = (string) $value; break; case 'double': $data = (string) $value; break; case 'boolean': $data = $value ? 'true' : 'false'; break; case 'NULL': $data = 'null'; break; default: case 'string': $data = "'" . addcslashes($value, "'\\") . "'"; break; } $item .= $data . ",\r\n"; return $item; }
/** * Pre-caches external file * * @param string $url * @param string $type * @return string */ function _precache_file($url, $type) { $lifetime = $this->_config->get_integer('minify.lifetime'); $cache_path = sprintf('%s/minify_%s.%s', Util_Environment::cache_blog_dir('minify'), md5($url), $type); if (!file_exists($cache_path) || @filemtime($cache_path) < time() - $lifetime) { if (!@is_dir(dirname($cache_path))) { Util_File::mkdir_from(dirname($cache_path), W3TC_CACHE_DIR); } Util_Http::download($url, $cache_path); } return file_exists($cache_path) ? $this->_get_minify_source($cache_path, $url) : false; }
/** * Imports library * * @param integer $limit * @param integer $offset * @param integer $count * @param integer $total * @param array $results * @return boolean */ function import_library($limit, $offset, &$count, &$total, &$results) { global $wpdb; $count = 0; $total = 0; $results = array(); $upload_info = Util_Http::upload_info(); $uploads_use_yearmonth_folders = get_option('uploads_use_yearmonth_folders'); $document_root = Util_Environment::document_root(); @set_time_limit($this->_config->get_integer('timelimit.cdn_import')); if ($upload_info) { /** * Search for posts with links or images */ $sql = sprintf('SELECT ID, post_content, post_date FROM %sposts WHERE post_status = "publish" AND (post_type = "post" OR post_type = "page") AND (post_content LIKE "%%src=%%" OR post_content LIKE "%%href=%%") ', $wpdb->prefix); if ($limit) { $sql .= sprintf(' LIMIT %d', $limit); if ($offset) { $sql .= sprintf(' OFFSET %d', $offset); } } $posts = $wpdb->get_results($sql); if ($posts) { $count = count($posts); $total = $this->get_import_posts_count(); $regexp = '~(' . $this->get_regexp_by_mask($this->_config->get_string('cdn.import.files')) . ')$~'; $config_state = Dispatcher::config_state(); $import_external = $config_state->get_boolean('cdn.import.external'); foreach ($posts as $post) { $matches = null; $replaced = array(); $attachments = array(); $post_content = $post->post_content; /** * Search for all link and image sources */ if (preg_match_all('~(href|src)=[\'"]?([^\'"<>\\s]+)[\'"]?~', $post_content, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { list($search, $attribute, $origin) = $match; /** * Check if $search is already replaced */ if (isset($replaced[$search])) { continue; } $error = ''; $result = false; $src = Util_Environment::normalize_file_minify($origin); $dst = ''; /** * Check if file exists in the library */ if (stristr($origin, $upload_info['baseurl']) === false) { /** * Check file extension */ $check_src = $src; if (Util_Environment::is_url($check_src)) { $qpos = strpos($check_src, '?'); if ($qpos !== false) { $check_src = substr($check_src, 0, $qpos); } } if (preg_match($regexp, $check_src)) { /** * Check for already uploaded attachment */ if (isset($attachments[$src])) { list($dst, $dst_url) = $attachments[$src]; $result = true; } else { if ($uploads_use_yearmonth_folders) { $upload_subdir = date('Y/m', strtotime($post->post_date)); $upload_dir = sprintf('%s/%s', $upload_info['basedir'], $upload_subdir); $upload_url = sprintf('%s/%s', $upload_info['baseurl'], $upload_subdir); } else { $upload_subdir = ''; $upload_dir = $upload_info['basedir']; $upload_url = $upload_info['baseurl']; } $src_filename = pathinfo($src, PATHINFO_FILENAME); $src_extension = pathinfo($src, PATHINFO_EXTENSION); /** * Get available filename */ for ($i = 0;; $i++) { $dst = sprintf('%s/%s%s%s', $upload_dir, $src_filename, $i ? $i : '', $src_extension ? '.' . $src_extension : ''); if (!file_exists($dst)) { break; } } $dst_basename = basename($dst); $dst_url = sprintf('%s/%s', $upload_url, $dst_basename); $dst_path = ltrim(str_replace($document_root, '', Util_Environment::normalize_path($dst)), '/'); if ($upload_subdir) { Util_File::mkdir($upload_subdir, 0777, $upload_info['basedir']); } $download_result = false; /** * Check if file is remote URL */ if (Util_Environment::is_url($src)) { /** * Download file */ if ($import_external) { $download_result = Util_Http::download($src, $dst); if (!$download_result) { $error = 'Unable to download file'; } } else { $error = 'External file import is disabled'; } } else { /** * Otherwise copy file from local path */ $src_path = $document_root . '/' . urldecode($src); if (file_exists($src_path)) { $download_result = @copy($src_path, $dst); if (!$download_result) { $error = 'Unable to copy file'; } } else { $error = 'Source file doesn\'t exists'; } } /** * Check if download or copy was successful */ if ($download_result) { $title = $dst_basename; $guid = ltrim($upload_info['baseurlpath'] . $title, ','); $mime_type = Util_Mime::get_mime_type($dst); $GLOBALS['wp_rewrite'] = new WP_Rewrite(); /** * Insert attachment */ $id = wp_insert_attachment(array('post_mime_type' => $mime_type, 'guid' => $guid, 'post_title' => $title, 'post_content' => '', 'post_parent' => $post->ID), $dst); if (!is_wp_error($id)) { /** * Generate attachment metadata and upload to CDN */ require_once ABSPATH . 'wp-admin/includes/image.php'; wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $dst)); $attachments[$src] = array($dst, $dst_url); $result = true; } else { $error = 'Unable to insert attachment'; } } } /** * If attachment was successfully created then replace links */ if ($result) { $replace = sprintf('%s="%s"', $attribute, $dst_url); // replace $search with $replace $post_content = str_replace($search, $replace, $post_content); $replaced[$search] = $replace; $error = 'OK'; } } else { $error = 'File type rejected'; } } else { $error = 'File already exists in the media library'; } /** * Add new entry to the log file */ $results[] = array('src' => $src, 'dst' => $dst_path, 'result' => $result, 'error' => $error); } } /** * If post content was chenged then update DB */ if ($post_content != $post->post_content) { wp_update_post(array('ID' => $post->ID, 'post_content' => $post_content)); } } } } }
public function save() { $data = array('version' => $this->_data['version']); if ($this->is_master()) { foreach ($this->_data as $key => $value) { $data[$key] = $this->_data[$key]; } } else { // write only overwrited keys $master = new ConfigCompiler(0, $this->_preview); $master->load(); foreach ($this->_data as $key => $value) { if (!ConfigCompiler::child_key_sealed($key, $master->_data, $this->_data)) { $data[$key] = $this->_data[$key]; } } } $filename = Config::util_config_filename($this->_blog_id, $this->_preview); if (defined('JSON_PRETTY_PRINT')) { $config = json_encode($data, JSON_PRETTY_PRINT); } else { // for older php versions $config = json_encode($data); } Util_File::file_put_contents_atomic($filename, $config); }
/** * Test minifier action * * @return void */ function w3tc_test_minifier() { $engine = Util_Request::get_string('engine'); $path_java = Util_Request::get_string('path_java'); $path_jar = Util_Request::get_string('path_jar'); $result = false; $error = ''; if ($engine != 'googleccjs') { if (!$path_java) { $error = __('Empty JAVA executable path.', 'w3-total-cache'); } elseif (!$path_jar) { $error = __('Empty JAR file path.', 'w3-total-cache'); } } if (empty($error)) { switch ($engine) { case 'yuijs': Minify_YUICompressor::$tempDir = Util_File::create_tmp_dir(); Minify_YUICompressor::$javaExecutable = $path_java; Minify_YUICompressor::$jarFile = $path_jar; $result = Minify_YUICompressor::testJs($error); break; case 'yuicss': Minify_YUICompressor::$tempDir = Util_File::create_tmp_dir(); Minify_YUICompressor::$javaExecutable = $path_java; Minify_YUICompressor::$jarFile = $path_jar; $result = Minify_YUICompressor::testCss($error); break; case 'ccjs': Minify_ClosureCompiler::$tempDir = Util_File::create_tmp_dir(); Minify_ClosureCompiler::$javaExecutable = $path_java; Minify_ClosureCompiler::$jarFile = $path_jar; $result = Minify_ClosureCompiler::test($error); break; case 'googleccjs': $result = Minify_JS_ClosureCompiler::test($error); break; default: $error = __('Invalid engine.', 'w3-total-cache'); break; } } $response = array('result' => $result, 'error' => $error); echo json_encode($response); }
/** * 检查文件是否真的是图片文件 * * @param * $filename * @param null $file_mime_type * @param null $mime_type_list * * @return bool */ public static function isRealImage($filename, $file_mime_type = null, $mime_type_list = null) { // Detect mime content type $mime_type = false; if (!$mime_type_list) { $mime_type_list = array('image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png'); } $mime_type = Util_File::getMimeType($filename); if ($file_mime_type && (empty($mime_type) || $mime_type == 'regular file' || $mime_type == 'text/plain')) { $mime_type = $file_mime_type; } // For each allowed MIME type, we are looking for it inside the current MIME type foreach ($mime_type_list as $type) { if (strstr($mime_type, $type)) { return true; } } return false; }
/** * 添加邮件中的图片 * * @param string $p_sName * @param string $p_sPath */ function addBodyImage($p_sName, $p_sPath) { $oFInfo = finfo_open(); $sMimeType = finfo_file($oFInfo, $p_sPath, FILEINFO_MIME_TYPE); finfo_close($oFInfo); $this->_aMailImage[] = array('oContent' => Util_File::tryReadFile($p_sPath), 'sName' => $p_sName, 'sMimeType' => $sMimeType, 'sCID' => md5(uniqid(microtime(true)))); }