/**
  * Returns headers for file
  *
  * @param array   $file CDN file array
  * @return array
  */
 function _get_headers($file, $block_expires = false)
 {
     $local_path = $file['local_path'];
     $mime_type = Util_Mime::get_mime_type($local_path);
     $last_modified = time();
     $link = $file['original_url'];
     $headers = array('Content-Type' => $mime_type, 'Last-Modified' => Util_Content::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'] = Util_Environment::w3tc_header($this->_config);
         }
         $expires_set = false;
         if (!$block_expires && $this->cache_config[$mime_type]['expires']) {
             $headers['Expires'] = Util_Content::http_date(time() + $this->cache_config[$mime_type]['lifetime']);
             $expires_set = true;
         }
         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' => ($expires_set ? '' : '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' => 'private, must-revalidate'));
                 break;
             case 'cache_maxage':
                 $headers = array_merge($headers, array('Pragma' => 'public', 'Cache-Control' => ($expires_set ? '' : '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();
     $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));
                 }
             }
         }
     }
 }
 /**
  * Get MIME type for file
  *
  * @internal Used to get mime types
  * @param string &$file File path
  * @return string
  */
 public static function __getMimeType(&$file)
 {
     $type = Util_Mime::get_mime_type($file);
     return $type;
 }
 /**
  * Uploads files to CDN
  *
  * @param array   $files
  * @param array   $results
  * @param boolean $force_rewrite
  * @return boolean
  */
 function upload($files, &$results, $force_rewrite = false, $timeout_time = NULL)
 {
     foreach ($files as $file) {
         if (!is_null($timeout_time) && time() > $timeout_time) {
             break;
         }
         $local_path = $file['local_path'];
         $remote_path = $file['remote_path'];
         if (!file_exists($local_path)) {
             $results[] = $this->_get_result($local_path, $remote_path, W3TC_CDN_RESULT_ERROR, 'Source file not found.', $file);
             continue;
         }
         $file_content = file_get_contents($local_path);
         $do_write = true;
         // rewrite is optional, check md5
         if (!$force_rewrite) {
             $object_meta = null;
             try {
                 $object_meta = $this->_api_files->object_get_meta_or_null($this->_container, $remote_path);
             } catch (\Exception $exception) {
                 $results[] = $this->_get_result($local_path, $remote_path, W3TC_CDN_RESULT_ERROR, sprintf('Unable to check object (%s).', $exception->getMessage()), $file);
                 $do_write = false;
             }
             if (is_array($object_meta) && isset($object_meta['etag'])) {
                 $md5_actual = md5($file_content);
                 if ($md5_actual == $object_meta['etag']) {
                     $results[] = $this->_get_result($local_path, $remote_path, W3TC_CDN_RESULT_OK, 'Object up-to-date.', $file);
                     $do_write = false;
                 }
             }
         }
         if ($do_write) {
             try {
                 $this->_api_files->object_create(array('container' => $this->_container, 'name' => $remote_path, 'content_type' => Util_Mime::get_mime_type($local_path), 'content' => $file_content));
                 $results[] = $this->_get_result($local_path, $remote_path, W3TC_CDN_RESULT_OK, 'OK', $file);
             } catch (\Exception $exception) {
                 $results[] = $this->_get_result($local_path, $remote_path, W3TC_CDN_RESULT_ERROR, sprintf('Unable to create object (%s).', $exception->getMessage()), $file);
             }
         }
     }
     return !$this->_is_error($results);
 }