Changeset 759162
- Timestamp:
- 08/20/2013 11:35:20 AM (13 years ago)
- Location:
- wp-s3/trunk
- Files:
-
- 2 edited
-
readme.txt (modified) (4 diffs)
-
s3.php (modified) (6 diffs)
Legend:
- Unmodified
- Added
- Removed
-
wp-s3/trunk/readme.txt
r255087 r759162 4 4 Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=FMMYTX4JXJHF8 5 5 Requires at least: 2.3 6 Tested up to: 3.0 7 Stable tag: 1.0 6 Tested up to: 3.6 7 Stable tag: 1.1 8 License: LGPL 9 License URI: http://www.gnu.org/licenses/lgpl.html 10 8 11 9 12 == Description == … … 19 22 7. If anything goes wrong just de-active the plugin and blog should go back to its old state 20 23 24 Theme & Plugin Developers can use these examples to make their theme / plugin assets load from CDN 25 26 To scan a full HTML Block for images, upload to CDN and replace them if uploaded. 27 28 `<?php 29 if(class_exists('S3Plugin')){ 30 $output = S3Plugin::scanForImages($output); 31 } 32 ?>` 33 34 To check if a single media needs to be uploaded to CDN and replaced if uploaded. 35 36 `<?php 37 if(is_singular()){ 38 $attachmentDetails = &get_children( "numberposts=1&post_type=attachment&post_mime_type=image&post_parent=" . get_the_ID() ); 39 if(!empty ($attachmentDetails)){ 40 $attachmentDetails = array_shift($attachmentDetails); 41 $postImage = array_shift(wp_get_attachment_image_src($attachmentDetails->ID,'thumbnail')); 42 if(class_exists('S3Plugin')){ 43 $cdnImageURL = S3Plugin::getCDNURL($postImage); 44 if($cdnImageURL!==FALSE){ 45 $postImage = $cdnImageURL; 46 } 47 } 48 } 49 } 50 ?>` 51 52 53 54 21 55 == Frequently Asked Questions == 22 56 … … 30 64 No. You cannot manage the files in Amazon S3 using this plugin. 31 65 66 = What happens when I check clear cache option in the option? = 67 The plugin will change the upload path prefix and clears all local upload que and cached media files. All the local media files are uploaded again. Please note the files already uploaded by this plugin in S3 has to be deleted manually. Please don't clear cache often, use only there is a plugin update / wordpress update. 68 69 == Screenshots == 70 71 1. Plugin Options page 72 32 73 == Changelog == 74 75 = Version: 1.1 Dated: 2013-08-20 = 76 * Added support for custom origin 77 * Added support for expires headers 78 * Added support for CSS and JS compression 79 * Added support for dynamic cache 80 * Added support for other plugin developers to quickly use plugin to make their assets available from cloud 33 81 34 82 = Version: 1.0 Dated: 20-June-2010 = … … 37 85 == Upgrade Notice == 38 86 No upgrade notices available 39 40 == Screenshots ==41 No screenshots available -
wp-s3/trunk/s3.php
r403637 r759162 6 6 Description: This plugin helps the users to view your blog in a pda and iPhone browser. 7 7 Author: Imthiaz Rafiq 8 Version: 1.1 Alpha8 Version: 1.1 9 9 Author URI: http://imthi.com/ 10 10 */ … … 29 29 var $cronUploadLimit; 30 30 /* 31 * 31 * 32 32 * @var wpdb 33 33 */ … … 38 38 /** 39 39 * 40 * @var S3Plugin 40 * @var S3Plugin 41 41 */ 42 42 protected static $_instance = null; … … 48 48 */ 49 49 public static function getInstance() { 50 if (null === self::$_instance) {51 self::$_instance = new self();52 }53 return self::$_instance;50 if (null === self::$_instance) { 51 self::$_instance = new self(); 52 } 53 return self::$_instance; 54 54 } 55 55 56 56 private function __construct() { 57 global $wpdb;58 59 if (get_option('s3plugin_enabled', 'inactive') == 'active') {60 $this->enabled = TRUE;61 } else {62 $this->enabled = FALSE;63 }64 65 $this->blockDirectory = array('wpcf7_captcha', 'wp-admin');66 $this->blockExtension = array('php', 'htm', 'html');67 68 $this->s3CacheFolder = ABSPATH . 'wp-content' . DIRECTORY_SEPARATOR . 's3temp' . DIRECTORY_SEPARATOR;69 $this->siteURL = untrailingslashit(get_option('siteurl'));70 71 $this->s3AccessKey = get_option('s3plugin_amazon_key_id');72 $this->s3SecretKey = get_option('s3plugin_amazon_secret_key');73 $this->s3BucketName = get_option('s3plugin_amazon_bucket_name');74 $this->s3UseSSL = (bool) get_option('s3plugin_use_ssl', 0);75 $this->s3CompressFiles = (bool) get_option('s3plugin_compress_files', 0);76 $this->s3DirPrefix = get_option('s3plugin_dir_prefix');77 78 $this->s3UseCloudFrontURL = (bool) get_option('s3plugin_use_cloudfrontURL', 0);79 $this->s3CloudFrontURL = untrailingslashit(get_option('s3plugin_cloudfrontURL'));80 81 if ($this->s3UseCloudFrontURL && !empty($this->s3UseCloudFrontURL)) {82 $this->isCloudFrontURLEnabled = TRUE;83 } else {84 $this->isCloudFrontURLEnabled = FALSE;85 }86 87 $this->cronScheduleTime = get_option('s3plugin_cron_interval', 300);88 $this->cronUploadLimit = get_option('s3plugin_cron_limit', 20);89 90 $this->db = $wpdb;91 $this->tabeImageQueue = $wpdb->prefix . 's3_image_queue';92 93 register_activation_hook(plugin_basename(__FILE__), array(94 &$this,95 'activatePlugin'));96 register_deactivation_hook(plugin_basename(__FILE__), array(97 &$this,98 'deactivatePlugin'));99 add_action('admin_menu', array(&$this, 's3AdminMenu'));100 101 add_filter('script_loader_src', array(&$this, 'script_loader_src'), 99);102 add_filter('style_loader_src', array(&$this, 'style_loader_src'), 99);103 104 if (isset($_GET ['page']) && $_GET ['page'] == 's3plugin-options') {105 ob_start();106 }107 108 if ($this->enabled) {109 add_filter('the_content', array(&$this, 'theContent'), 12);110 add_filter('cron_schedules', array(111 &$this,112 'cronSchedules'));113 if (!wp_next_scheduled('s3CronHook')) {114 wp_schedule_event(time(), 's3_cron_schedule', 's3CronHook');115 }116 add_action('s3CronHook', array(&$this, 'executeCron'));117 } else {118 if (wp_next_scheduled('s3CronHook')) {119 wp_clear_scheduled_hook('s3CronHook');120 }121 }57 global $wpdb; 58 59 if (get_option('s3plugin_enabled', 'inactive') == 'active') { 60 $this->enabled = TRUE; 61 } else { 62 $this->enabled = FALSE; 63 } 64 65 $this->blockDirectory = array('wpcf7_captcha', 'wp-admin', 'wp-includes/js', 'wp-includes/css'); 66 $this->blockExtension = array('php', 'htm', 'html'); 67 68 $this->s3CacheFolder = ABSPATH . 'wp-content' . DIRECTORY_SEPARATOR . 's3temp' . DIRECTORY_SEPARATOR; 69 $this->siteURL = untrailingslashit(get_option('siteurl')); 70 71 $this->s3AccessKey = get_option('s3plugin_amazon_key_id'); 72 $this->s3SecretKey = get_option('s3plugin_amazon_secret_key'); 73 $this->s3BucketName = get_option('s3plugin_amazon_bucket_name'); 74 $this->s3UseSSL = (bool) get_option('s3plugin_use_ssl', 0); 75 $this->s3CompressFiles = (bool) get_option('s3plugin_compress_files', 0); 76 $this->s3DirPrefix = get_option('s3plugin_dir_prefix'); 77 78 $this->s3UseCloudFrontURL = (bool) get_option('s3plugin_use_cloudfrontURL', 0); 79 $this->s3CloudFrontURL = untrailingslashit(get_option('s3plugin_cloudfrontURL')); 80 81 if ($this->s3UseCloudFrontURL && !empty($this->s3UseCloudFrontURL)) { 82 $this->isCloudFrontURLEnabled = TRUE; 83 } else { 84 $this->isCloudFrontURLEnabled = FALSE; 85 } 86 87 $this->cronScheduleTime = get_option('s3plugin_cron_interval', 300); 88 $this->cronUploadLimit = get_option('s3plugin_cron_limit', 20); 89 90 $this->db = $wpdb; 91 $this->tabeImageQueue = $wpdb->prefix . 's3_image_queue'; 92 93 register_activation_hook(plugin_basename(__FILE__), array( 94 &$this, 95 'activatePlugin')); 96 register_deactivation_hook(plugin_basename(__FILE__), array( 97 &$this, 98 'deactivatePlugin')); 99 add_action('admin_menu', array(&$this, 's3AdminMenu')); 100 101 add_filter('script_loader_src', array(&$this, 'script_loader_src'), 99); 102 add_filter('style_loader_src', array(&$this, 'style_loader_src'), 99); 103 104 if (isset($_GET ['page']) && $_GET ['page'] == 's3plugin-options') { 105 ob_start(); 106 } 107 108 if ($this->enabled) { 109 add_filter('the_content', array(&$this, 'theContent'), 12); 110 add_filter('cron_schedules', array( 111 &$this, 112 'cronSchedules')); 113 if (!wp_next_scheduled('s3CronHook')) { 114 wp_schedule_event(time(), 's3_cron_schedule', 's3CronHook'); 115 } 116 add_action('s3CronHook', array(&$this, 'executeCron')); 117 } else { 118 if (wp_next_scheduled('s3CronHook')) { 119 wp_clear_scheduled_hook('s3CronHook'); 120 } 121 } 122 122 } 123 123 124 124 private function __clone() { 125 125 126 126 } 127 127 128 128 function s3AdminMenu() { 129 if (function_exists('add_submenu_page')) {130 add_submenu_page('plugins.php', __('Amazon S3'), __('Amazon S3'), 'manage_options', 's3plugin-options', array(131 &$this,132 's3PluginOption'));133 }129 if (function_exists('add_submenu_page')) { 130 add_submenu_page('plugins.php', __('Amazon S3'), __('Amazon S3'), 'manage_options', 's3plugin-options', array( 131 &$this, 132 's3PluginOption')); 133 } 134 134 } 135 135 136 136 function s3PluginOption() { 137 if (isset($_POST ['Submit'])) {138 if (function_exists('current_user_can') && !current_user_can('manage_options')) {139 die(__('Cheatin’ uh?'));140 }141 update_option('s3plugin_amazon_key_id', $_POST ['s3plugin_amazon_key_id']);142 update_option('s3plugin_amazon_secret_key', $_POST ['s3plugin_amazon_secret_key']);143 update_option('s3plugin_amazon_bucket_name', $_POST ['s3plugin_amazon_bucket_name']);144 145 if (isset($_POST ['s3plugin_use_ssl'])) {146 update_option('s3plugin_use_ssl', $_POST ['s3plugin_use_ssl']);147 } else {148 delete_option('s3plugin_use_ssl');149 }150 151 if (isset($_POST ['s3plugin_compress_files'])) {152 update_option('s3plugin_compress_files', $_POST ['s3plugin_compress_files']);153 } else {154 delete_option('s3plugin_compress_files');155 }156 157 if (isset($_POST ['s3plugin_use_cloudfrontURL'])) {158 update_option('s3plugin_use_cloudfrontURL', $_POST ['s3plugin_use_cloudfrontURL']);159 } else {160 delete_option('s3plugin_use_cloudfrontURL');161 }162 163 if (isset($_POST ['s3plugin_clear_cache'])) {164 $this->recursive_remove_directory($this->s3CacheFolder, FALSE);165 $this->db->query("DELETE FROM `{$this->tabeImageQueue}` WHERE 1=1;");166 update_option('s3plugin_dir_prefix', substr(md5(time() + microtime()), 0, 6) . '/');167 }168 169 update_option('s3plugin_cloudfrontURL', $_POST ['s3plugin_cloudfrontURL']);170 171 if ($this->checkS3AccessAndBucket($_POST ['s3plugin_amazon_key_id'], $_POST ['s3plugin_amazon_secret_key'], $useSSL, $_POST ['s3plugin_amazon_bucket_name']) === FALSE) {172 $s3PuginMessage = 'Connection failed. Plugin not active.';173 update_option('s3plugin_enabled', 'inactive');174 } else {175 $s3PuginMessage = 'Settings saved. Plugin is active.';176 update_option('s3plugin_enabled', 'active');177 }178 update_option('s3plugin_cron_interval', $_POST ['s3plugin_cron_interval']);179 update_option('s3plugin_cron_limit', $_POST ['s3plugin_cron_limit']);180 ob_end_clean();181 wp_redirect('plugins.php?page=s3plugin-options&msg=' . urlencode($s3PuginMessage));182 exit();183 }184 include_once ('s3-options.php');137 if (isset($_POST ['Submit'])) { 138 if (function_exists('current_user_can') && !current_user_can('manage_options')) { 139 die(__('Cheatin’ uh?')); 140 } 141 update_option('s3plugin_amazon_key_id', $_POST ['s3plugin_amazon_key_id']); 142 update_option('s3plugin_amazon_secret_key', $_POST ['s3plugin_amazon_secret_key']); 143 update_option('s3plugin_amazon_bucket_name', $_POST ['s3plugin_amazon_bucket_name']); 144 145 if (isset($_POST ['s3plugin_use_ssl'])) { 146 update_option('s3plugin_use_ssl', $_POST ['s3plugin_use_ssl']); 147 } else { 148 delete_option('s3plugin_use_ssl'); 149 } 150 151 if (isset($_POST ['s3plugin_compress_files'])) { 152 update_option('s3plugin_compress_files', $_POST ['s3plugin_compress_files']); 153 } else { 154 delete_option('s3plugin_compress_files'); 155 } 156 157 if (isset($_POST ['s3plugin_use_cloudfrontURL'])) { 158 update_option('s3plugin_use_cloudfrontURL', $_POST ['s3plugin_use_cloudfrontURL']); 159 } else { 160 delete_option('s3plugin_use_cloudfrontURL'); 161 } 162 163 if (isset($_POST ['s3plugin_clear_cache'])) { 164 $this->recursive_remove_directory($this->s3CacheFolder, FALSE); 165 $this->db->query("DELETE FROM `{$this->tabeImageQueue}` WHERE 1=1;"); 166 update_option('s3plugin_dir_prefix', substr(md5(time() + microtime()), 0, 6) . '/'); 167 } 168 169 update_option('s3plugin_cloudfrontURL', $_POST ['s3plugin_cloudfrontURL']); 170 171 if ($this->checkS3AccessAndBucket($_POST ['s3plugin_amazon_key_id'], $_POST ['s3plugin_amazon_secret_key'], $useSSL, $_POST ['s3plugin_amazon_bucket_name']) === FALSE) { 172 $s3PuginMessage = 'Connection failed. Plugin not active.'; 173 update_option('s3plugin_enabled', 'inactive'); 174 } else { 175 $s3PuginMessage = 'Settings saved. Plugin is active.'; 176 update_option('s3plugin_enabled', 'active'); 177 } 178 update_option('s3plugin_cron_interval', $_POST ['s3plugin_cron_interval']); 179 update_option('s3plugin_cron_limit', $_POST ['s3plugin_cron_limit']); 180 ob_end_clean(); 181 wp_redirect('plugins.php?page=s3plugin-options&msg=' . urlencode($s3PuginMessage)); 182 exit(); 183 } 184 include_once ('s3-options.php'); 185 185 } 186 186 187 187 function activatePlugin() { 188 $query = "CREATE TABLE IF NOT EXISTS `{$this->tabeImageQueue}` (188 $query = "CREATE TABLE IF NOT EXISTS `{$this->tabeImageQueue}` ( 189 189 `id` varchar(32) NOT NULL, 190 190 `path` varchar(255) NOT NULL, … … 193 193 PRIMARY KEY (`id`) 194 194 ) ENGINE=MyISAM;"; 195 $this->db->query($query);195 $this->db->query($query); 196 196 } 197 197 198 198 function deactivatePlugin() { 199 199 200 200 } 201 201 202 202 function cronSchedules($param) { 203 return array(204 's3_cron_schedule' => array(205 'interval' => $this->cronScheduleTime, // seconds206 'display' => 'S3 Cron Schedule'));203 return array( 204 's3_cron_schedule' => array( 205 'interval' => $this->cronScheduleTime, // seconds 206 'display' => 'S3 Cron Schedule')); 207 207 } 208 208 209 209 function checkS3AccessAndBucket($accessKey, $secretKey, $useSSL, $bucketName) { 210 include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 's3-php5-curl' . DIRECTORY_SEPARATOR . 'S3.php';211 212 $s3Adapter = new S3($accessKey, $secretKey, $useSSL);213 $availableBuckets = @$s3Adapter->listBuckets();214 if (!empty($availableBuckets) && in_array($bucketName, $availableBuckets) == TRUE) {215 return TRUE;216 }217 return FALSE;210 include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 's3-php5-curl' . DIRECTORY_SEPARATOR . 'S3.php'; 211 212 $s3Adapter = new S3($accessKey, $secretKey, $useSSL); 213 $availableBuckets = @$s3Adapter->listBuckets(); 214 if (!empty($availableBuckets) && in_array($bucketName, $availableBuckets) == TRUE) { 215 return TRUE; 216 } 217 return FALSE; 218 218 } 219 219 220 220 function executeCron() { 221 ignore_user_abort(true);222 set_time_limit(0);223 224 ini_set('display_errors', 1);225 ini_set('log_errors', 1);226 ini_set('error_log', dirname(__FILE__) . '/error_log.txt');227 error_reporting(E_ALL);228 229 print "Hello";230 231 include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 's3-php5-curl' . DIRECTORY_SEPARATOR . 'S3.php';232 233 $s3Adapter = new S3($this->s3AccessKey, $this->s3SecretKey, $this->s3UseSSL);234 $availableBuckets = @$s3Adapter->listBuckets();235 cmVarDebug($availableBuckets);236 237 if (!empty($availableBuckets) && in_array($this->s3BucketName, $availableBuckets) == TRUE) {238 $query = "SELECT * FROM {$this->tabeImageQueue} WHERE status='queue' ORDER BY added LIMIT {$this->cronUploadLimit};";239 $filesToUpload = $this->db->get_results($query, ARRAY_A);240 if (!empty($filesToUpload)) {241 foreach ($filesToUpload as $fileInfo) {242 cmVarDebug($fileInfo);243 $shouldUpload = TRUE;244 $fileStatus = 'error';245 $filePath = ABSPATH . $fileInfo ['path'];246 $fileObjectInfo = $s3Adapter->getObjectInfo($this->s3BucketName, $this->s3DirPrefix . $fileInfo ['path'], TRUE);247 if (!empty($fileObjectInfo)) {248 if ($fileObjectInfo ['size'] != filesize($filePath)) {249 if ($s3Adapter->deleteObject($this->s3BucketName, $this->s3DirPrefix . $fileInfo ['path']) === FALSE) {250 $shouldUpload = FALSE;251 }252 } else {253 $shouldUpload = FALSE;254 $fileStatus = 'done';255 }256 }257 if ($shouldUpload) {258 $fileContentType = $this->getFileType($filePath);259 $fileRequestHeaders = array(260 'Content-Type' => $fileContentType261 );262 $tempFile = '';263 if ($this->s3CompressFiles && ( $fileContentType == 'text/css' || $fileContentType == 'text/javascript')) {264 $fileRequestHeaders['Content-Encoding'] = 'gzip';265 $tempFile = tempnam($this->s3CacheFolder, 'tmp_gzip');266 $gzipFilePointer = fopen($tempFile, "wb+");267 fwrite($gzipFilePointer, gzencode(file_get_contents($filePath), 9));268 fclose($gzipFilePointer);269 $fileResource = $s3Adapter->inputResource(fopen($tempFile, 'rb'), filesize($tempFile));270 } else {271 $fileResource = $s3Adapter->inputResource(fopen($filePath, 'rb'), filesize($filePath));272 }273 if ($s3Adapter->putObject($fileResource, $this->s3BucketName, $this->s3DirPrefix . $fileInfo ['path'], S3::ACL_PUBLIC_READ, array(), $fileRequestHeaders) === TRUE) {274 $fileStatus = 'done';275 }276 if (!empty($tempFile)) {277 @unlink($tempFile);278 }279 }280 print "Processing: {$fileInfo['path']} Status: {$fileStatus}. <br />\n";281 $this->writeToFile($this->getFilePath($fileInfo ['path']), $fileStatus);282 $this->db->update($this->tabeImageQueue, array(283 'status' => $fileStatus), array(284 'id' => $fileInfo ['id']));285 }286 }287 }221 ignore_user_abort(true); 222 set_time_limit(0); 223 224 ini_set('display_errors', 1); 225 ini_set('log_errors', 1); 226 ini_set('error_log', dirname(__FILE__) . '/error_log.txt'); 227 error_reporting(E_ALL); 228 229 print "Hello"; 230 231 include_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 's3-php5-curl' . DIRECTORY_SEPARATOR . 'S3.php'; 232 233 $s3Adapter = new S3($this->s3AccessKey, $this->s3SecretKey, $this->s3UseSSL); 234 $availableBuckets = @$s3Adapter->listBuckets(); 235 varDebug($availableBuckets); 236 237 if (!empty($availableBuckets) && in_array($this->s3BucketName, $availableBuckets) == TRUE) { 238 $query = "SELECT * FROM {$this->tabeImageQueue} WHERE status='queue' ORDER BY added LIMIT {$this->cronUploadLimit};"; 239 $filesToUpload = $this->db->get_results($query, ARRAY_A); 240 if (!empty($filesToUpload)) { 241 foreach ($filesToUpload as $fileInfo) { 242 varDebug($fileInfo); 243 $shouldUpload = TRUE; 244 $fileStatus = 'error'; 245 $filePath = ABSPATH . $fileInfo ['path']; 246 $fileObjectInfo = $s3Adapter->getObjectInfo($this->s3BucketName, $this->s3DirPrefix . $fileInfo ['path'], TRUE); 247 if (!empty($fileObjectInfo)) { 248 if ($fileObjectInfo ['size'] != filesize($filePath)) { 249 if ($s3Adapter->deleteObject($this->s3BucketName, $this->s3DirPrefix . $fileInfo ['path']) === FALSE) { 250 $shouldUpload = FALSE; 251 } 252 } else { 253 $shouldUpload = FALSE; 254 $fileStatus = 'done'; 255 } 256 } 257 if ($shouldUpload) { 258 $fileContentType = $this->getFileType($filePath); 259 $fileRequestHeaders = array( 260 'Content-Type' => $fileContentType 261 ); 262 $tempFile = ''; 263 if ($this->s3CompressFiles && ( $fileContentType == 'text/css' || $fileContentType == 'text/javascript')) { 264 $fileRequestHeaders['Content-Encoding'] = 'gzip'; 265 $tempFile = tempnam($this->s3CacheFolder, 'tmp_gzip'); 266 $gzipFilePointer = fopen($tempFile, "wb+"); 267 fwrite($gzipFilePointer, gzencode(file_get_contents($filePath), 9)); 268 fclose($gzipFilePointer); 269 $fileResource = $s3Adapter->inputResource(fopen($tempFile, 'rb'), filesize($tempFile)); 270 } else { 271 $fileResource = $s3Adapter->inputResource(fopen($filePath, 'rb'), filesize($filePath)); 272 } 273 if ($s3Adapter->putObject($fileResource, $this->s3BucketName, $this->s3DirPrefix . $fileInfo ['path'], S3::ACL_PUBLIC_READ, array(), $fileRequestHeaders) === TRUE) { 274 $fileStatus = 'done'; 275 } 276 if (!empty($tempFile)) { 277 @unlink($tempFile); 278 } 279 } 280 print "Processing: {$fileInfo['path']} Status: {$fileStatus}. <br />\n"; 281 $this->writeToFile($this->getFilePath($fileInfo ['path']), $fileStatus); 282 $this->db->update($this->tabeImageQueue, array( 283 'status' => $fileStatus), array( 284 'id' => $fileInfo ['id'])); 285 } 286 } 287 } 288 288 } 289 289 290 290 function getFileType($file) { 291 $ext = strtolower(pathInfo($file, PATHINFO_EXTENSION));292 static $exts = array(293 'jpg' => 'image/jpeg',294 'gif' => 'image/gif',295 'png' => 'image/png',296 'tif' => 'image/tiff',297 'tiff' => 'image/tiff',298 'ico' => 'image/x-icon',299 'swf' => 'application/x-shockwave-flash',300 'pdf' => 'application/pdf',301 'zip' => 'application/zip',302 'gz' => 'application/x-gzip',303 'tar' => 'application/x-tar',304 'bz' => 'application/x-bzip',305 'bz2' => 'application/x-bzip2',306 'txt' => 'text/plain',307 'asc' => 'text/plain',308 'htm' => 'text/html',309 'html' => 'text/html',310 'css' => 'text/css',311 'js' => 'text/javascript',312 'xml' => 'text/xml',313 'xsl' => 'application/xsl+xml',314 'ogg' => 'application/ogg',315 'mp3' => 'audio/mpeg',316 'wav' => 'audio/x-wav',317 'avi' => 'video/x-msvideo',318 'mpg' => 'video/mpeg',319 'mpeg' => 'video/mpeg',320 'mov' => 'video/quicktime',321 'flv' => 'video/x-flv',322 'php' => 'text/x-php'323 );324 return isset($exts[$ext]) ? $exts[$ext] : 'application/octet-stream';291 $ext = strtolower(pathInfo($file, PATHINFO_EXTENSION)); 292 static $exts = array( 293 'jpg' => 'image/jpeg', 294 'gif' => 'image/gif', 295 'png' => 'image/png', 296 'tif' => 'image/tiff', 297 'tiff' => 'image/tiff', 298 'ico' => 'image/x-icon', 299 'swf' => 'application/x-shockwave-flash', 300 'pdf' => 'application/pdf', 301 'zip' => 'application/zip', 302 'gz' => 'application/x-gzip', 303 'tar' => 'application/x-tar', 304 'bz' => 'application/x-bzip', 305 'bz2' => 'application/x-bzip2', 306 'txt' => 'text/plain', 307 'asc' => 'text/plain', 308 'htm' => 'text/html', 309 'html' => 'text/html', 310 'css' => 'text/css', 311 'js' => 'text/javascript', 312 'xml' => 'text/xml', 313 'xsl' => 'application/xsl+xml', 314 'ogg' => 'application/ogg', 315 'mp3' => 'audio/mpeg', 316 'wav' => 'audio/x-wav', 317 'avi' => 'video/x-msvideo', 318 'mpg' => 'video/mpeg', 319 'mpeg' => 'video/mpeg', 320 'mov' => 'video/quicktime', 321 'flv' => 'video/x-flv', 322 'php' => 'text/x-php' 323 ); 324 return isset($exts[$ext]) ? $exts[$ext] : 'application/octet-stream'; 325 325 } 326 326 327 327 function script_loader_src($scriptURL) { 328 if (!is_admin()) {329 $urlParts = parse_url($scriptURL);330 $justURL = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path'];331 $fileCDNURL = self::getCDNURL($justURL);332 if ($fileCDNURL !== FALSE) {333 if (isset($urlParts['query']) && !empty($urlParts['query'])) {334 return $fileCDNURL . '?' . $urlParts['query'];335 }336 return $fileCDNURL;337 }338 }339 return $scriptURL;328 if (!is_admin()) { 329 $urlParts = parse_url($scriptURL); 330 $justURL = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path']; 331 $fileCDNURL = self::getCDNURL($justURL); 332 if ($fileCDNURL !== FALSE) { 333 if (isset($urlParts['query']) && !empty($urlParts['query'])) { 334 return $fileCDNURL . '?' . $urlParts['query']; 335 } 336 return $fileCDNURL; 337 } 338 } 339 return $scriptURL; 340 340 } 341 341 342 342 function style_loader_src($cssURL) { 343 if (!is_admin()) {344 $urlParts = parse_url($cssURL);345 $justURL = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path'];346 $fileCDNURL = self::getCDNURL($justURL);347 if ($fileCDNURL !== FALSE) {348 if (isset($urlParts['query']) && !empty($urlParts['query'])) {349 return $fileCDNURL . '?' . $urlParts['query'];350 }351 return $fileCDNURL;352 } else {353 $realPath = $this->getRealPath($justURL);354 if (file_exists($realPath)) {355 $cssFolder = dirname($realPath);356 $cssRelatedFiles = $this->scanDirectoryRecursively($cssFolder);357 if (!empty($cssRelatedFiles)) {358 foreach ($cssRelatedFiles as $relatedFile) {359 $queueFiles = self::getCDNURL($this->siteURL . '/' . $relatedFile);360 }361 }362 }363 }364 }365 return $cssURL;343 if (!is_admin()) { 344 $urlParts = parse_url($cssURL); 345 $justURL = $urlParts['scheme'] . '://' . $urlParts['host'] . $urlParts['path']; 346 $fileCDNURL = self::getCDNURL($justURL); 347 if ($fileCDNURL !== FALSE) { 348 if (isset($urlParts['query']) && !empty($urlParts['query'])) { 349 return $fileCDNURL . '?' . $urlParts['query']; 350 } 351 return $fileCDNURL; 352 } else { 353 $realPath = $this->getRealPath($justURL); 354 if (file_exists($realPath)) { 355 $cssFolder = dirname($realPath); 356 $cssRelatedFiles = $this->scanDirectoryRecursively($cssFolder); 357 if (!empty($cssRelatedFiles)) { 358 foreach ($cssRelatedFiles as $relatedFile) { 359 $queueFiles = self::getCDNURL($this->siteURL . '/' . $relatedFile); 360 } 361 } 362 } 363 } 364 } 365 return $cssURL; 366 366 } 367 367 368 368 function scanDirectoryRecursively($directory, $filter=FALSE, $directoryFiles = array()) { 369 369 370 if (substr($directory, -1) == DIRECTORY_SEPARATOR) {371 $directory = substr($directory, 0, -1);372 }373 374 $extensionToInclude = array('css', 'png', 'gif', 'jpg', 'jpeg');375 376 if (!file_exists($directory) || !is_dir($directory)) {377 return FALSE;378 } elseif (is_readable($directory)) {379 $directory_list = opendir($directory);380 while ($file = readdir($directory_list)) {381 if ($file != '.' && $file != '..') {382 $path = $directory . DIRECTORY_SEPARATOR . $file;383 if (is_readable($path)) {384 if (is_dir($path)) {385 $directoryFiles = $this->scanDirectoryRecursively($path, $filter, $directoryFiles);386 } elseif (is_file($path)) {387 $extension = strtolower(end(explode('.', $path)));388 if (in_array($extension, $extensionToInclude)) {389 $directoryFiles[] = str_replace(ABSPATH, '', $path);390 }391 }392 }393 }394 }395 closedir($directory_list);396 return $directoryFiles;397 } else {398 return FALSE;399 }370 if (substr($directory, -1) == DIRECTORY_SEPARATOR) { 371 $directory = substr($directory, 0, -1); 372 } 373 374 $extensionToInclude = array('css', 'png', 'gif', 'jpg', 'jpeg'); 375 376 if (!file_exists($directory) || !is_dir($directory)) { 377 return FALSE; 378 } elseif (is_readable($directory)) { 379 $directory_list = opendir($directory); 380 while ($file = readdir($directory_list)) { 381 if ($file != '.' && $file != '..') { 382 $path = $directory . DIRECTORY_SEPARATOR . $file; 383 if (is_readable($path)) { 384 if (is_dir($path)) { 385 $directoryFiles = $this->scanDirectoryRecursively($path, $filter, $directoryFiles); 386 } elseif (is_file($path)) { 387 $extension = strtolower(end(explode('.', $path))); 388 if (in_array($extension, $extensionToInclude)) { 389 $directoryFiles[] = str_replace(ABSPATH, '', $path); 390 } 391 } 392 } 393 } 394 } 395 closedir($directory_list); 396 return $directoryFiles; 397 } else { 398 return FALSE; 399 } 400 400 } 401 401 402 402 function getRealPath($fileURL) { 403 $relativePath = ltrim(str_replace($this->siteURL, '', $fileURL), '/');404 return ABSPATH . $relativePath;403 $relativePath = ltrim(str_replace($this->siteURL, '', $fileURL), '/'); 404 return ABSPATH . $relativePath; 405 405 } 406 406 407 407 public static function getCDNURL($fileURL) { 408 $instance = self::getInstance();409 $relativePath = ltrim(str_replace($instance->siteURL, '', $fileURL), '/');410 $realPath = trim($instance->getRealPath($fileURL));411 if (empty($realPath)) {412 return FALSE;413 }414 if (file_exists($realPath)) {415 foreach ($instance->blockDirectory as $blokedDirectory) {416 if (stripos($relativePath, $blokedDirectory) !== FALSE) {417 return FALSE;418 }419 }420 $filetype = strtolower(substr(strstr($relativePath, '.'), 1));421 422 foreach ($instance->blockExtension as $blockedExtension) {423 if ($blockedExtension == $filetype) {424 return FALSE;425 }426 }427 $cacheFilePath = $instance->getFilePath($relativePath);428 if (file_exists($cacheFilePath) === TRUE) {429 $fileContents = file_get_contents($cacheFilePath);430 if ($fileContents == 'done') {431 if ($instance->isCloudFrontURLEnabled) {432 return $instance->s3CloudFrontURL . '/' . $instance->s3DirPrefix . $relativePath;433 } else {434 return "http://{$instance->s3BucketName}.s3.amazonaws.com/" . $instance->s3DirPrefix . $relativePath;435 }436 }437 } else {438 $pathHash = md5($relativePath);439 $query = "SELECT count(*) FROM {$instance->tabeImageQueue} WHERE id='{$pathHash}';";440 if ($instance->db->get_var($query) == 0) {441 $insertArray = array(442 'id' => $pathHash,443 'path' => $relativePath,444 'status' => 'queue',445 'added' => current_time('mysql'));446 $instance->db->insert($instance->tabeImageQueue, $insertArray);447 } else {448 $updateArray = array(449 'status' => 'queue',450 'added' => current_time('mysql'));451 $instance->db->update($instance->tabeImageQueue, $updateArray, array(452 'id' => $pathHash));453 }454 $instance->writeToFile($cacheFilePath);455 }456 }457 return FALSE;408 $instance = self::getInstance(); 409 $relativePath = ltrim(str_replace($instance->siteURL, '', $fileURL), '/'); 410 $realPath = trim($instance->getRealPath($fileURL)); 411 if (empty($realPath)) { 412 return FALSE; 413 } 414 if (file_exists($realPath)) { 415 foreach ($instance->blockDirectory as $blokedDirectory) { 416 if (stripos($relativePath, $blokedDirectory) !== FALSE) { 417 return FALSE; 418 } 419 } 420 $filetype = strtolower(substr(strstr($relativePath, '.'), 1)); 421 422 foreach ($instance->blockExtension as $blockedExtension) { 423 if ($blockedExtension == $filetype) { 424 return FALSE; 425 } 426 } 427 $cacheFilePath = $instance->getFilePath($relativePath); 428 if (file_exists($cacheFilePath) === TRUE) { 429 $fileContents = file_get_contents($cacheFilePath); 430 if ($fileContents == 'done') { 431 if ($instance->isCloudFrontURLEnabled) { 432 return $instance->s3CloudFrontURL . '/' . $instance->s3DirPrefix . $relativePath; 433 } else { 434 return "http://{$instance->s3BucketName}.s3.amazonaws.com/" . $instance->s3DirPrefix . $relativePath; 435 } 436 } 437 } else { 438 $pathHash = md5($relativePath); 439 $query = "SELECT count(*) FROM {$instance->tabeImageQueue} WHERE id='{$pathHash}';"; 440 if ($instance->db->get_var($query) == 0) { 441 $insertArray = array( 442 'id' => $pathHash, 443 'path' => $relativePath, 444 'status' => 'queue', 445 'added' => current_time('mysql')); 446 $instance->db->insert($instance->tabeImageQueue, $insertArray); 447 } else { 448 $updateArray = array( 449 'status' => 'queue', 450 'added' => current_time('mysql')); 451 $instance->db->update($instance->tabeImageQueue, $updateArray, array( 452 'id' => $pathHash)); 453 } 454 $instance->writeToFile($cacheFilePath); 455 } 456 } 457 return FALSE; 458 458 } 459 459 460 460 public static function scanForImages($htmlContent) { 461 $instance = self::getInstance();462 $mediaList = $instance->getMediaFromContent($htmlContent);463 if (!empty($mediaList)) {464 foreach ($mediaList as $fileURL) {465 $fileCDNURL = self::getCDNURL($fileURL);466 if ($fileCDNURL !== FALSE) {467 $htmlContent = str_replace($fileURL, $fileCDNURL, $htmlContent);468 }469 }470 }471 return $htmlContent;461 $instance = self::getInstance(); 462 $mediaList = $instance->getMediaFromContent($htmlContent); 463 if (!empty($mediaList)) { 464 foreach ($mediaList as $fileURL) { 465 $fileCDNURL = self::getCDNURL($fileURL); 466 if ($fileCDNURL !== FALSE) { 467 $htmlContent = str_replace($fileURL, $fileCDNURL, $htmlContent); 468 } 469 } 470 } 471 return $htmlContent; 472 472 } 473 473 474 474 function theContent($the_content) { 475 $id = 0;476 $post = &get_post($id);477 if ($post->post_status != 'publish') {478 return $the_content;479 }480 return self::scanForImages($the_content);475 $id = 0; 476 $post = &get_post($id); 477 if ($post->post_status != 'publish') { 478 return $the_content; 479 } 480 return self::scanForImages($the_content); 481 481 } 482 482 483 483 function getMediaFromContent($content) { 484 $regex = '/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i';485 preg_match_all($regex, $content, $matches);486 487 $mediaList = array();488 if (isset($matches [0]) && !empty($matches [0])) {489 $mediaList = $matches [0];490 }491 return $mediaList;484 $regex = '/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i'; 485 preg_match_all($regex, $content, $matches); 486 487 $mediaList = array(); 488 if (isset($matches [0]) && !empty($matches [0])) { 489 $mediaList = $matches [0]; 490 } 491 return $mediaList; 492 492 } 493 493 494 494 function writeToFile($file, $status = 'QUEUE') { 495 $fileDir = dirname($file);496 $this->createDirectory($fileDir);497 file_put_contents($file, $status);495 $fileDir = dirname($file); 496 $this->createDirectory($fileDir); 497 file_put_contents($file, $status); 498 498 } 499 499 500 500 protected function getFilePath($file) { 501 $hash = md5($file);502 $path = $this->s3CacheFolder;503 for ($i = 0; $i < 3; $i++) {504 $path .= substr($hash, 0, $i + 1) . DIRECTORY_SEPARATOR;505 }506 return $path . $hash . '.txt';501 $hash = md5($file); 502 $path = $this->s3CacheFolder; 503 for ($i = 0; $i < 3; $i++) { 504 $path .= substr($hash, 0, $i + 1) . DIRECTORY_SEPARATOR; 505 } 506 return $path . $hash . '.txt'; 507 507 } 508 508 509 509 public static function createDirectory($path, $permission = 0755) { 510 if (!file_exists($path)) {511 S3Plugin::createDirectory(dirname($path), $permission);512 mkdir($path, $permission);513 chmod($path, $permission);514 $handle = @fopen($path . '/index.php', 'w');515 if ($handle) {516 fwrite($handle, '<?php print ":-)"; ?>');517 fclose($handle);518 chmod($path . '/index.php', 0644);519 }520 }510 if (!file_exists($path)) { 511 S3Plugin::createDirectory(dirname($path), $permission); 512 mkdir($path, $permission); 513 chmod($path, $permission); 514 $handle = @fopen($path . '/index.php', 'w'); 515 if ($handle) { 516 fwrite($handle, '<?php print ":-)"; ?>'); 517 fclose($handle); 518 chmod($path . '/index.php', 0644); 519 } 520 } 521 521 } 522 522 523 523 function recursive_remove_directory($directory, $empty=FALSE) { 524 if (substr($directory, -1) == '/') {525 $directory = substr($directory, 0, -1);526 }527 if (!file_exists($directory) || !is_dir($directory)) {528 return FALSE;529 } elseif (is_readable($directory)) {530 $handle = opendir($directory);531 while (FALSE !== ($item = readdir($handle))) {532 if ($item != '.' && $item != '..') {533 $path = $directory . '/' . $item;534 if (is_dir($path)) {535 $this->recursive_remove_directory($path);536 } else {537 unlink($path);538 }539 }540 }541 closedir($handle);542 if ($empty == FALSE) {543 if (!rmdir($directory)) {544 return FALSE;545 }546 }547 }548 return TRUE;524 if (substr($directory, -1) == '/') { 525 $directory = substr($directory, 0, -1); 526 } 527 if (!file_exists($directory) || !is_dir($directory)) { 528 return FALSE; 529 } elseif (is_readable($directory)) { 530 $handle = opendir($directory); 531 while (FALSE !== ($item = readdir($handle))) { 532 if ($item != '.' && $item != '..') { 533 $path = $directory . '/' . $item; 534 if (is_dir($path)) { 535 $this->recursive_remove_directory($path); 536 } else { 537 unlink($path); 538 } 539 } 540 } 541 closedir($handle); 542 if ($empty == FALSE) { 543 if (!rmdir($directory)) { 544 return FALSE; 545 } 546 } 547 } 548 return TRUE; 549 549 } 550 550 … … 559 559 } 560 560 561 function cmVarDebug($var, $echo = true) {561 function varDebug($var, $echo = true) { 562 562 $dump = "<div style=\"border:1px solid #f00;font-family:arial;font-size:12px;font-weight:normal;background:#f0f0f0;text-align:left;padding:3px;\"><pre>" . print_r($var, true) . "</pre></div>"; 563 563 if ($echo) { 564 echo $dump;564 echo $dump; 565 565 } else { 566 return $dump;566 return $dump; 567 567 } 568 568 }
Note: See TracChangeset
for help on using the changeset viewer.