/** * 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 = w3_upload_info(); $uploads_use_yearmonth_folders = get_option('uploads_use_yearmonth_folders'); $document_root = w3_get_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')) . ')$~'; $import_external = $this->_config->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 = w3_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 (w3_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, '', w3_path($dst)), '/'); if ($upload_subdir) { w3_mkdir($upload_subdir, 0777, $upload_info['basedir']); } $download_result = false; /** * Check if file is remote URL */ if (w3_is_url($src)) { /** * Download file */ if ($import_external) { $download_result = w3_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) { w3_require_once(W3TC_INC_DIR . '/functions/mime.php'); $title = $dst_basename; $guid = ltrim($upload_info['baseurlpath'] . $title, ','); $mime_type = w3_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)); } } } } }
/** * Get MIME type for file * * @internal Used to get mime types * @param string &$file File path * @return string */ public static function __getMimeType(&$file) { w3_require_once(W3TC_INC_DIR . '/functions/mime.php'); $type = w3_get_mime_type($file); return $type; }
/** * Returns headers for file * * @param array $file CDN file array * @return array */ function _get_headers($file) { w3_require_once(W3TC_INC_DIR . '/functions/mime.php'); $local_path = $file['local_path']; $mime_type = w3_get_mime_type($local_path); $last_modified = time(); $link = $file['original_url']; $headers = array('Content-Type' => $mime_type, 'Last-Modified' => w3_http_date($last_modified), 'Access-Control-Allow-Origin' => '*', 'Link' => '<' . $link . '>; rel="canonical"'); if (isset($this->cache_config[$mime_type])) { if ($this->cache_config[$mime_type]['etag']) { $headers['Etag'] = @md5_file($local_path); } if ($this->cache_config[$mime_type]['w3tc']) { $headers['X-Powered-By'] = W3TC_POWERED_BY; } if ($this->cache_config[$mime_type]['expires']) { $headers['Expires'] = w3_http_date(time() + $this->cache_config[$mime_type]['lifetime']); } switch ($this->cache_config[$mime_type]['cache_control']) { case 'cache': $headers = array_merge($headers, array('Pragma' => 'public', 'Cache-Control' => 'public')); break; case 'cache_public_maxage': $headers = array_merge($headers, array('Pragma' => 'public', 'Cache-Control' => ($this->cache_config[$mime_type]['expires'] ? '' : 'max-age=' . $this->cache_config[$mime_type]['lifetime'] . ', ') . 'public')); break; case 'cache_validation': $headers = array_merge($headers, array('Pragma' => 'public', 'Cache-Control' => 'public, must-revalidate, proxy-revalidate')); break; case 'cache_noproxy': $headers = array_merge($headers, array('Pragma' => 'public', 'Cache-Control' => 'public, must-revalidate')); break; case 'cache_maxage': $headers = array_merge($headers, array('Pragma' => 'public', 'Cache-Control' => ($this->cache_config[$mime_type]['expires'] ? '' : 'max-age=' . $this->cache_config[$mime_type]['lifetime'] . ', ') . 'public, must-revalidate, proxy-revalidate')); break; case 'no_cache': $headers = array_merge($headers, array('Pragma' => 'no-cache', 'Cache-Control' => 'max-age=0, private, no-store, no-cache, must-revalidate')); break; } } return $headers; }
/** * Internal check to get the proper mimetype. * * This function would go over the available PHP methods to get * the MIME type. * * By default it will try to use the PHP fileinfo library which is * available from PHP 5.3 or as an PECL extension * (http://pecl.php.net/package/Fileinfo). * * It will get the magic file by default from the system wide file * which is usually available in /usr/share/magic on Unix or try * to use the file specified in the source directory of the API * (share directory). * * if fileinfo is not available it will try to use the internal * mime_content_type function. * * @param string $handle name of file or buffer to guess the type from * @return boolean <kbd>True</kbd> if successful * @throws BadContentTypeException */ function _guess_content_type($handle) { if ($this->content_type) { return; } w3_require_once(W3TC_INC_DIR . '/functions/mime.php'); $this->content_type = w3_get_mime_type($handle); if (!$this->content_type) { throw new BadContentTypeException("Required Content-Type not set"); } return True; }
if (!defined('W3TC_DIR')) { define('W3TC_DIR', WP_PLUGIN_DIR . '/w3tc-transparentcdn'); } if (!@is_dir(W3TC_DIR) || !file_exists(W3TC_DIR . '/inc/define.php')) { @header('X-Robots-Tag: noarchive, noodp, nosnippet'); echo sprintf('<strong>W3 Total Cache Error:</strong> some files appear to be missing or out of place. Please re-install plugin or remove <strong>%s</strong>.', dirname(__FILE__)); } require_once W3TC_DIR . '/inc/define.php'; $attachment_location = filter_var(urldecode($_REQUEST['file']), FILTER_SANITIZE_STRING); $md5 = md5($attachment_location); $nonce = $_REQUEST['nonce']; $stored_nonce = get_site_option('w3tc_support_request') ? get_site_option('w3tc_support_request') : get_option('w3tc_support_request'); $stored_attachment = get_site_option('w3tc_support_request') ? get_site_option('attachment_' . $md5) : get_option('attachment_' . $md5); if (file_exists($attachment_location) && $nonce == $stored_nonce && !empty($stored_nonce) && $stored_attachment == $attachment_location) { w3_require_once(W3TC_INC_DIR . '/functions/mime.php'); $type = w3_get_mime_type($attachment_location); header($_SERVER["SERVER_PROTOCOL"] . " 200 OK"); header("Content-Type: " . $type); header("Content-Length:" . filesize($attachment_location)); header("Content-Disposition: attachment; filename=" . basename($attachment_location)); $file = fopen($attachment_location, 'rb'); if ($file !== false) { fpassthru($file); fclose($file); } w3tc_file_log('success', $attachment_location); die; } elseif ($nonce != $stored_nonce || $stored_attachment != $attachment_location) { header($_SERVER["SERVER_PROTOCOL"] . " 401"); w3tc_file_log('Unauthorized access', $attachment_location); die("Unauthorized access.");
/** * Returns headers for file * * @param string $file * @return array */ function _get_headers($file) { $mime_type = w3_get_mime_type($file); $last_modified = time(); $headers = array('Content-Type' => $mime_type, 'Last-Modified' => w3_http_date($last_modified), 'Access-Control-Allow-Origin' => '*'); if (isset($this->cache_config[$mime_type])) { if ($this->cache_config[$mime_type]['etag']) { $headers['Etag'] = @md5_file($file); } if ($this->cache_config[$mime_type]['w3tc']) { $headers['X-Powered-By'] = W3TC_POWERED_BY; } switch ($this->cache_config[$mime_type]['cache_control']) { case 'cache': $headers = array_merge($headers, array('Pragma' => 'public', 'Cache-Control' => 'public')); break; case 'cache_validation': $headers = array_merge($headers, array('Pragma' => 'public', 'Cache-Control' => 'public, must-revalidate, proxy-revalidate')); break; case 'cache_noproxy': $headers = array_merge($headers, array('Pragma' => 'public', 'Cache-Control' => 'public, must-revalidate')); break; case 'cache_maxage': $headers = array_merge($headers, array('Pragma' => 'public', 'Cache-Control' => 'max-age=' . $this->cache_config[$mime_type]['lifetime'] . ', public, must-revalidate, proxy-revalidate')); break; case 'no_cache': $headers = array_merge($headers, array('Pragma' => 'no-cache', 'Cache-Control' => 'max-age=0, private, no-store, no-cache, must-revalidate')); break; } } return $headers; }
/** * 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(); $site_url = w3_get_site_url(); $upload_info = w3_upload_info(); if ($upload_info) { $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')); $import_external = $this->_config->get_boolean('cdn.import.external'); foreach ($posts as $post) { $matches = null; $post_content = $post->post_content; if (preg_match_all('~(href|src)=[\'"]?([^\'"<>\\s]+)[\'"]?~', $post_content, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { $src = w3_normalize_file($match[2]); if (preg_match('~(' . $regexp . ')$~', $src)) { $src_dir = date('Y/m', strtotime($post->post_date)); $src_base = basename($src); $dst = sprintf('%s/%s/%s', $upload_info['upload_dir'], $src_dir, $src_base); $dst_dir = dirname($dst); $dst_path = ABSPATH . $dst; $dst_url = sprintf('%s%s/%s/%s', $site_url, $upload_info['upload_url'], $src_dir, $src_base); $result = false; $error = ''; $download_result = null; w3_mkdir($dst_dir, 0755, ABSPATH); // file already exists if (!file_exists($dst_path)) { // source is external URL if (w3_is_url($src)) { if ($import_external) { $download_result = $this->download($src, $dst_path); } else { $error = 'External file import is disabled'; } // source is local file not in wp-content/uploads dir } elseif (strstr($src, $upload_info['upload_dir']) === false) { $src_path = ABSPATH . $src; $download_result = @copy($src_path, $dst_path); // file is already in wp-content/uploads dir } else { $error = 'Source file already exists'; } if ($download_result !== null) { if ($download_result) { $title = $src_base; $guid = $upload_info['upload_url'] . '/' . $title; $mime_type = w3_get_mime_type($src_base); $GLOBALS['wp_rewrite'] =& new WP_Rewrite(); $id = wp_insert_attachment(array('post_mime_type' => $mime_type, 'guid' => $guid, 'post_title' => $title, 'post_content' => ''), $dst_path); if (!is_wp_error($id)) { require_once ABSPATH . 'wp-admin/includes/image.php'; wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $dst_path)); $post_content = str_replace($src, $dst_url, $post_content); $result = true; $error = 'OK'; } else { $error = 'Unable to insert attachment'; } } else { $error = 'Unable to download file'; } } } else { $error = 'Destination file already exists'; } $results[] = array('src' => $src, 'dst' => $dst, 'result' => $result, 'error' => $error); } } } if ($post_content != $post->post_content) { wp_update_post(array('ID' => $post->ID, 'post_content' => $post_content)); } } } } }
/** * Internal check to get the proper mimetype. * * This function would go over the available PHP methods to get * the MIME type. * * By default it will try to use the PHP fileinfo library which is * available from PHP 5.3 or as an PECL extension * (http://pecl.php.net/package/Fileinfo). * * It will get the magic file by default from the system wide file * which is usually available in /usr/share/magic on Unix or try * to use the file specified in the source directory of the API * (share directory). * * if fileinfo is not available it will try to use the internal * mime_content_type function. * * @param string $handle name of file or buffer to guess the type from * @return boolean <kbd>True</kbd> if successful * @throws BadContentTypeException */ function _guess_content_type($handle) { if ($this->content_type) { return; } $this->content_type = w3_get_mime_type($handle); if (!$this->content_type) { throw new BadContentTypeException("Required Content-Type not set"); } return True; }
/** * Get MIME type for file * * @internal Used to get mime types * @param string &$file File path * @return string */ public static function __getMimeType(&$file) { $type = w3_get_mime_type($file); return $type; }
/** * Get MIME type for file * * @internal Used to get mime types * @param string &$file File path * @return string */ public static function __getMimeType(&$file) { $type = w3_get_mime_type($file); if (!$type && function_exists('mime_content_type')) { $type = trim(mime_content_type($file)); } return !empty($type) ? $type : 'application/octet-stream'; }