Timthumb Vulnerability Scanner - Version 1.1

Version Description

  • Updated scanner to find really old versions of timthumb.
Download this release

Release Info

Developer peterebutler
Plugin Icon wp plugin Timthumb Vulnerability Scanner
Version 1.1
Comparing to
See all releases

Version 1.1

cg-tvs-admin-panel.php ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div class="wrap">
2
+ <h2>Timthumb Scanner</h2>
3
+ <div class="postbox metabox-holder" style="float:right;width:300px;padding-top:0px">
4
+ <h3 class="hndle" style="text-align:center"><a href="http://codegarage.com/"><img src="<?php echo WP_PLUGIN_URL; ?>/<?php echo basename(dirname(__FILE__)); ?>/locker_logo.png"></a></h3>
5
+ <div class="inside">
6
+ <p><strong>Tired of worrying about your WordPress sites?</strong></p>
7
+ <p><a href="http://codegarage.com" target="_blank" >Locker</a> from <a href="http://codegarage.com/" target="_blank" >Code Garage</a> provides rock solid daily backups and hack monitoring and cleanup (for malicious code and vulnerabilities like this one), as well as personal, one on one support when you need it. Plans start at $15/month for 10 sites.</p>
8
+ <p style="text-align:center;padding-top:15px;"><a href="http://codegarage.com/" target="_blank" class="button-primary">Click here to learn more</a></p>
9
+ </div>
10
+ </div>
11
+ <div style="margin-right:320px;">
12
+ <h4>What's going on here?</h4>
13
+ <p>Here's how this works: When you click "Scan", we'll gather a list of all the files in your wp-content directory, and then we'll scan all of the php files looking for the timthumb script. If we find it, we'll scan it to make sure it's at least version 2 - which is the version that fixed the vulnerability. You'll be notified here of any files that need to be updated.</p>
14
+ <form action="tools.php?page=cg-timthumb-scanner" method="post">
15
+ <input type="hidden" name="cg-action" value="scan">
16
+ <button class="button-secondary">Scan!</button>
17
+ </form>
18
+ <?php if(!empty($message)): ?>
19
+ <div id="message" class="updated">
20
+ <p><?php echo $message; ?></p>
21
+ </div>
22
+ <?php endif; ?>
23
+ <?php if(get_option('cg_tvs_last_checked')): ?>
24
+ <h4>What now?</h4>
25
+ <p>We've now scanned all your themes and plugins, and any instances of the timthumb script are listed below. Problem files (timthumb scripts that are older than version 2.0) are in the "Vulnerable" list, and safe files (Newer than 2.0) are listed in the "Safe" list. "Vulnerable" files can be upgraded to the latest version of timthumb by clicking the "Fix" button next to each file.</p>
26
+ <table class="form-table">
27
+ <tr>
28
+ <th scope="row">Last Scanned:</th>
29
+ <td><?php echo get_option('cg_tvs_last_checked'); ?></td>
30
+ </tr>
31
+ <tr>
32
+ <th scope="row">Vulnerable Timthumb Files:</th>
33
+ <td><?php echo $vulnerable_list_html; ?></td>
34
+ </tr>
35
+ <tr>
36
+ <th scope="row">Safe Timthumb Files:</th>
37
+ <td><?php echo $safe_list_html; ?></td>
38
+ </tr>
39
+ </table>
40
+ <?php endif; ?>
41
+ </div>
42
+ </div>
cg-tvs-filescanner.php ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ class CG_FileScanner{
4
+
5
+ public $BaseDir;
6
+ public $Errors;
7
+ public $Inventory;
8
+ public $VulnerableFiles;
9
+ public $SafeFiles;
10
+
11
+ function __construct($base_dir){
12
+ if(is_file($base_dir) || is_dir($base_dir)){
13
+ $this->BaseDir = $base_dir;
14
+ }else{
15
+ die();
16
+ }
17
+ }
18
+
19
+ function generate_inventory(){
20
+ $this->Inventory = $this->get_dir_contents($this->BaseDir, true);
21
+ }
22
+
23
+ function get_dir_contents($path){
24
+ $inventory = array();
25
+ if(!$dir_handle = @opendir($path)){
26
+ $this->Errors[] = "Couldn't open $path";
27
+ return false;
28
+ }
29
+ while($file = readdir($dir_handle)) {
30
+ if($file == '.' || $file == '..') continue;
31
+ if(is_dir($path.'/'.$file)){
32
+ $inventory = array_merge($inventory, $this->get_dir_contents($path.'/'.$file));
33
+ }else{
34
+ $inventory[] = $path.'/'.$file;
35
+ }
36
+ }
37
+ closedir($dir_handle);
38
+ return $inventory;
39
+ }
40
+
41
+ function file_stat($file){
42
+ $file_info['path'] = $file;
43
+ if(is_dir($file)){
44
+ $file_info['type'] = 'directory';
45
+ }else{
46
+ $file_info['type'] = 'file';
47
+ }
48
+
49
+ $file_info['readable'] = is_readable($file);
50
+ if($this->Type == 'structure'){
51
+ if($file_info['type'] == 'directory'){
52
+ $dir_stat = $this->dir_stat($file);
53
+ $file_info['mtime'] = $dir_stat['mtime'];
54
+ $file_info['child_nodes'] = $dir_stat['child_nodes'];
55
+ $file_info['ctime'] = filectime($file);
56
+ $file_info['atime'] = fileatime($file);
57
+ return $file_info;
58
+ }else{
59
+ return '';
60
+ }
61
+ }
62
+
63
+ if($this->Type != 'index' && $this->Type != 'structure'){
64
+ $file_info['mtime'] = filemtime($file);
65
+ $file_info['ctime'] = filectime($file);
66
+ $file_info['atime'] = fileatime($file);
67
+ $file_info['size'] = filesize($file);
68
+ $file_info['hash'] = md5_file($file);
69
+ }
70
+
71
+ return $file_info;
72
+ }
73
+
74
+ function scan_inventory(){
75
+ $pattern_1 = "Timthumb.*Ben Gillbanks|http\:\/\/code\.google\.com\/p\/timthumb\/";
76
+ $pattern_2 = "define\s*\(\'VERSION\',\s*\'[23456789]\.[0-9]";
77
+
78
+ foreach($this->Inventory as $path){
79
+ $path_parts = pathinfo($path);
80
+ // Don't scan this plugin's files
81
+ if(preg_match("~^".dirname(__FILE__)."~", $path)){
82
+ continue;
83
+ }
84
+ if($path_parts['extension'] == 'php'){
85
+ if($file_handle = @fopen($path, "r")){
86
+ $contents = @fread($file_handle, filesize($path));
87
+ if (preg_match("~$pattern_1~", $contents)){
88
+ // We have a timthumb script. Now check to see if it is version 2.0 or greater.
89
+ if (!preg_match("~$pattern_2~", $contents)){
90
+ $this->VulnerableFiles[] = $path;
91
+ }else{
92
+ $this->SafeFiles[] = $path;
93
+ }
94
+ }
95
+ }
96
+ }
97
+ }
98
+ }
99
+
100
+ }
101
+ ?>
cg-tvs-timthumb-latest.txt ADDED
@@ -0,0 +1,1189 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * TimThumb by Ben Gillbanks and Mark Maunder
4
+ * Based on work done by Tim McDaniels and Darren Hoyt
5
+ * http://code.google.com/p/timthumb/
6
+ *
7
+ * GNU General Public License, version 2
8
+ * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
9
+ *
10
+ * Examples and documentation available on the project homepage
11
+ * http://www.binarymoon.co.uk/projects/timthumb/
12
+ */
13
+
14
+ /*
15
+ -----TimThumb CONFIGURATION-----
16
+ You can either edit the configuration variables manually here, or you can
17
+ create a file called timthumb-config.php and define variables you want
18
+ to customize in there. It will automatically be loaded by timthumb.
19
+ This will save you having to re-edit these variables everytime you download
20
+ a new version of timthumb.
21
+
22
+ */
23
+ define ('VERSION', '2.8'); // Version of this script
24
+ //Load a config file if it exists. Otherwise, use the values below.
25
+ if( file_exists('timthumb-config.php')) require_once('timthumb-config.php');
26
+ if(! defined( 'DEBUG_ON' ) ) define ('DEBUG_ON', false); // Enable debug logging to web server error log (STDERR)
27
+ if(! defined('DEBUG_LEVEL') ) define ('DEBUG_LEVEL', 1); // Debug level 1 is less noisy and 3 is the most noisy
28
+ if(! defined('MEMORY_LIMIT') ) define ('MEMORY_LIMIT', '30M'); // Set PHP memory limit
29
+ if(! defined('BLOCK_EXTERNAL_LEECHERS') ) define ('BLOCK_EXTERNAL_LEECHERS', false); // If the image or webshot is being loaded on an external site, display a red "No Hotlinking" gif.
30
+
31
+ //Image fetching and caching
32
+ if(! defined('ALLOW_EXTERNAL') ) define ('ALLOW_EXTERNAL', TRUE); // Allow image fetching from external websites. Will check against ALLOWED_SITES if ALLOW_ALL_EXTERNAL_SITES is false
33
+ if(! defined('ALLOW_ALL_EXTERNAL_SITES') ) define ('ALLOW_ALL_EXTERNAL_SITES', false); // Less secure.
34
+ if(! defined('FILE_CACHE_ENABLED') ) define ('FILE_CACHE_ENABLED', TRUE); // Should we store resized/modified images on disk to speed things up?
35
+ if(! defined('FILE_CACHE_TIME_BETWEEN_CLEANS')) define ('FILE_CACHE_TIME_BETWEEN_CLEANS', 86400); // How often the cache is cleaned
36
+ if(! defined('FILE_CACHE_MAX_FILE_AGE') ) define ('FILE_CACHE_MAX_FILE_AGE', 86400); // How old does a file have to be to be deleted from the cache
37
+ if(! defined('FILE_CACHE_SUFFIX') ) define ('FILE_CACHE_SUFFIX', '.timthumb.txt'); // What to put at the end of all files in the cache directory so we can identify them
38
+ if(! defined('FILE_CACHE_DIRECTORY') ) define ('FILE_CACHE_DIRECTORY', './cache'); // Directory where images are cached. Left blank it will use the system temporary directory (which is better for security)
39
+ if(! defined('MAX_FILE_SIZE') ) define ('MAX_FILE_SIZE', 10485760); // 10 Megs is 10485760. This is the max internal or external file size that we'll process.
40
+ if(! defined('CURL_TIMEOUT') ) define ('CURL_TIMEOUT', 20); // Timeout duration for Curl. This only applies if you have Curl installed and aren't using PHP's default URL fetching mechanism.
41
+ if(! defined('WAIT_BETWEEN_FETCH_ERRORS') ) define ('WAIT_BETWEEN_FETCH_ERRORS', 3600); //Time to wait between errors fetching remote file
42
+ //Browser caching
43
+ if(! defined('BROWSER_CACHE_MAX_AGE') ) define ('BROWSER_CACHE_MAX_AGE', 864000); // Time to cache in the browser
44
+ if(! defined('BROWSER_CACHE_DISABLE') ) define ('BROWSER_CACHE_DISABLE', false); // Use for testing if you want to disable all browser caching
45
+
46
+ //Image size and defaults
47
+ if(! defined('MAX_WIDTH') ) define ('MAX_WIDTH', 1500); // Maximum image width
48
+ if(! defined('MAX_HEIGHT') ) define ('MAX_HEIGHT', 1500); // Maximum image height
49
+ if(! defined('NOT_FOUND_IMAGE') ) define ('NOT_FOUND_IMAGE', ''); //Image to serve if any 404 occurs
50
+ if(! defined('ERROR_IMAGE') ) define ('ERROR_IMAGE', ''); //Image to serve if an error occurs instead of showing error message
51
+
52
+ //Image compression is enabled if either of these point to valid paths
53
+
54
+ //These are now disabled by default because the file sizes of PNGs (and GIFs) are much smaller than we used to generate.
55
+ //They only work for PNGs. GIFs and JPEGs are not affected.
56
+ if(! defined('OPTIPNG_ENABLED') ) define ('OPTIPNG_ENABLED', false);
57
+ if(! defined('OPTIPNG_PATH') ) define ('OPTIPNG_PATH', '/usr/bin/optipng'); //This will run first because it gives better compression than pngcrush.
58
+ if(! defined('PNGCRUSH_ENABLED') ) define ('PNGCRUSH_ENABLED', false);
59
+ if(! defined('PNGCRUSH_PATH') ) define ('PNGCRUSH_PATH', '/usr/bin/pngcrush'); //This will only run if OPTIPNG_PATH is not set or is not valid
60
+
61
+ /*
62
+ -------====Website Screenshots configuration - BETA====-------
63
+
64
+ If you just want image thumbnails and don't want website screenshots, you can safely leave this as is.
65
+
66
+ If you would like to get website screenshots set up, you will need root access to your own server.
67
+
68
+ Enable ALLOW_ALL_EXTERNAL_SITES so you can fetch any external web page. This is more secure now that we're using a non-web folder for cache.
69
+ Enable BLOCK_EXTERNAL_LEECHERS so that your site doesn't generate thumbnails for the whole Internet.
70
+
71
+ Instructions to get website screenshots enabled on Ubuntu Linux:
72
+
73
+ 1. Install Xvfb with the following command: sudo apt-get install subversion libqt4-webkit libqt4-dev g++ xvfb
74
+ 2. Go to a directory where you can download some code
75
+ 3. Check-out the latest version of CutyCapt with the following command: svn co https://cutycapt.svn.sourceforge.net/svnroot/cutycapt
76
+ 4. Compile CutyCapt by doing: cd cutycapt/CutyCapt
77
+ 5. qmake
78
+ 6. make
79
+ 7. cp CutyCapt /usr/local/bin/
80
+ 8. Test it by running: xvfb-run --server-args="-screen 0, 1024x768x24" CutyCapt --url="http://markmaunder.com/" --out=test.png
81
+ 9. If you get a file called test.png with something in it, it probably worked. Now test the script by accessing it as follows:
82
+ 10. http://yoursite.com/path/to/timthumb.php?src=http://markmaunder.com/&webshot=1
83
+
84
+ Notes on performance:
85
+ The first time a webshot loads, it will take a few seconds.
86
+ From then on it uses the regular timthumb caching mechanism with the configurable options above
87
+ and loading will be very fast.
88
+
89
+ --ADVANCED USERS ONLY--
90
+ If you'd like a slight speedup (about 25%) and you know Linux, you can run the following command which will keep Xvfb running in the background.
91
+ nohup Xvfb :100 -ac -nolisten tcp -screen 0, 1024x768x24 > /dev/null 2>&1 &
92
+ Then set WEBSHOT_XVFB_RUNNING = true below. This will save your server having to fire off a new Xvfb server and shut it down every time a new shot is generated.
93
+ You will need to take responsibility for keeping Xvfb running in case it crashes. (It seems pretty stable)
94
+ You will also need to take responsibility for server security if you're running Xvfb as root.
95
+
96
+
97
+ */
98
+ if(! defined('WEBSHOT_ENABLED') ) define ('WEBSHOT_ENABLED', false); //Beta feature. Adding webshot=1 to your query string will cause the script to return a browser screenshot rather than try to fetch an image.
99
+ if(! defined('WEBSHOT_CUTYCAPT') ) define ('WEBSHOT_CUTYCAPT', '/usr/local/bin/CutyCapt'); //The path to CutyCapt.
100
+ if(! defined('WEBSHOT_XVFB') ) define ('WEBSHOT_XVFB', '/usr/bin/xvfb-run'); //The path to the Xvfb server
101
+ if(! defined('WEBSHOT_SCREEN_X') ) define ('WEBSHOT_SCREEN_X', '1024'); //1024 works ok
102
+ if(! defined('WEBSHOT_SCREEN_Y') ) define ('WEBSHOT_SCREEN_Y', '768'); //768 works ok
103
+ if(! defined('WEBSHOT_COLOR_DEPTH') ) define ('WEBSHOT_COLOR_DEPTH', '24'); //I haven't tested anything besides 24
104
+ if(! defined('WEBSHOT_IMAGE_FORMAT') ) define ('WEBSHOT_IMAGE_FORMAT', 'png'); //png is about 2.5 times the size of jpg but is a LOT better quality
105
+ if(! defined('WEBSHOT_TIMEOUT') ) define ('WEBSHOT_TIMEOUT', '20'); //Seconds to wait for a webshot
106
+ if(! defined('WEBSHOT_USER_AGENT') ) define ('WEBSHOT_USER_AGENT', "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2.18) Gecko/20110614 Firefox/3.6.18"); //I hate to do this, but a non-browser robot user agent might not show what humans see. So we pretend to be Firefox
107
+ if(! defined('WEBSHOT_JAVASCRIPT_ON') ) define ('WEBSHOT_JAVASCRIPT_ON', true); //Setting to false might give you a slight speedup and block ads. But it could cause other issues.
108
+ if(! defined('WEBSHOT_JAVA_ON') ) define ('WEBSHOT_JAVA_ON', false); //Have only tested this as fase
109
+ if(! defined('WEBSHOT_PLUGINS_ON') ) define ('WEBSHOT_PLUGINS_ON', true); //Enable flash and other plugins
110
+ if(! defined('WEBSHOT_PROXY') ) define ('WEBSHOT_PROXY', ''); //In case you're behind a proxy server.
111
+ if(! defined('WEBSHOT_XVFB_RUNNING') ) define ('WEBSHOT_XVFB_RUNNING', false); //ADVANCED: Enable this if you've got Xvfb running in the background.
112
+
113
+
114
+ // If ALLOW_EXTERNAL is true and ALLOW_ALL_EXTERNAL_SITES is false, then external images will only be fetched from these domains and their subdomains.
115
+ if(! isset($ALLOWED_SITES)){
116
+ $ALLOWED_SITES = array (
117
+ 'flickr.com',
118
+ 'picasa.com',
119
+ 'img.youtube.com',
120
+ 'upload.wikimedia.org',
121
+ 'photobucket.com',
122
+ 'imgur.com',
123
+ 'imageshack.us',
124
+ 'tinypic.com'
125
+ );
126
+ }
127
+ // -------------------------------------------------------------
128
+ // -------------- STOP EDITING CONFIGURATION HERE --------------
129
+ // -------------------------------------------------------------
130
+
131
+ timthumb::start();
132
+
133
+ class timthumb {
134
+ protected $src = "";
135
+ protected $is404 = false;
136
+ protected $docRoot = "";
137
+ protected $lastURLError = false;
138
+ protected $localImage = "";
139
+ protected $localImageMTime = 0;
140
+ protected $url = false;
141
+ protected $myHost = "";
142
+ protected $isURL = false;
143
+ protected $cachefile = '';
144
+ protected $errors = array();
145
+ protected $toDeletes = array();
146
+ protected $cacheDirectory = '';
147
+ protected $startTime = 0;
148
+ protected $lastBenchTime = 0;
149
+ protected $cropTop = false;
150
+ protected $salt = "";
151
+ protected $fileCacheVersion = 1; //Generally if timthumb.php is modifed (upgraded) then the salt changes and all cache files are recreated. This is a backup mechanism to force regen.
152
+ protected $filePrependSecurityBlock = "<?php die('Execution denied!'); //"; //Designed to have three letter mime type, space, question mark and greater than symbol appended. 6 bytes total.
153
+ protected static $curlDataWritten = 0;
154
+ protected static $curlFH = false;
155
+ public static function start(){
156
+ $tim = new timthumb();
157
+ $tim->handleErrors();
158
+ $tim->securityChecks();
159
+ if($tim->tryBrowserCache()){
160
+ exit(0);
161
+ }
162
+ $tim->handleErrors();
163
+ if(FILE_CACHE_ENABLED && $tim->tryServerCache()){
164
+ exit(0);
165
+ }
166
+ $tim->handleErrors();
167
+ $tim->run();
168
+ $tim->handleErrors();
169
+ exit(0);
170
+ }
171
+ public function __construct(){
172
+ global $ALLOWED_SITES;
173
+ $this->startTime = microtime(true);
174
+ date_default_timezone_set('UTC');
175
+ $this->debug(1, "Starting new request from " . $this->getIP() . " to " . $_SERVER['REQUEST_URI']);
176
+ $this->calcDocRoot();
177
+ //On windows systems I'm assuming fileinode returns an empty string or a number that doesn't change. Check this.
178
+ $this->salt = @filemtime(__FILE__) . '-' . @fileinode(__FILE__);
179
+ $this->debug(3, "Salt is: " . $this->salt);
180
+ if(FILE_CACHE_DIRECTORY){
181
+ if(! is_dir(FILE_CACHE_DIRECTORY)){
182
+ @mkdir(FILE_CACHE_DIRECTORY);
183
+ if(! is_dir(FILE_CACHE_DIRECTORY)){
184
+ $this->error("Could not create the file cache directory.");
185
+ return false;
186
+ }
187
+ }
188
+ $this->cacheDirectory = FILE_CACHE_DIRECTORY;
189
+ touch($this->cacheDirectory . '/index.html');
190
+ } else {
191
+ $this->cacheDirectory = sys_get_temp_dir();
192
+ }
193
+ //Clean the cache before we do anything because we don't want the first visitor after FILE_CACHE_TIME_BETWEEN_CLEANS expires to get a stale image.
194
+ $this->cleanCache();
195
+
196
+ $this->myHost = preg_replace('/^www\./i', '', $_SERVER['HTTP_HOST']);
197
+ $this->src = $this->param('src');
198
+ $this->url = parse_url($this->src);
199
+ if(strlen($this->src) <= 3){
200
+ $this->error("No image specified");
201
+ return false;
202
+ }
203
+ if(BLOCK_EXTERNAL_LEECHERS && array_key_exists('HTTP_REFERER', $_SERVER) && (! preg_match('/^https?:\/\/(?:www\.)?' . $this->myHost . '(?:$|\/)/i', $_SERVER['HTTP_REFERER']))){
204
+ // base64 encoded red image that says 'no hotlinkers'
205
+ // nothing to worry about! :)
206
+ $imgData = base64_decode("R0lGODlhUAAMAIAAAP8AAP///yH5BAAHAP8ALAAAAABQAAwAAAJpjI+py+0Po5y0OgAMjjv01YUZ\nOGplhWXfNa6JCLnWkXplrcBmW+spbwvaVr/cDyg7IoFC2KbYVC2NQ5MQ4ZNao9Ynzjl9ScNYpneb\nDULB3RP6JuPuaGfuuV4fumf8PuvqFyhYtjdoeFgAADs=");
207
+ header('Content-Type: image/gif');
208
+ header('Content-Length: ' . sizeof($imgData));
209
+ header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
210
+ header("Pragma: no-cache");
211
+ header('Expires: ' . gmdate ('D, d M Y H:i:s', time()));
212
+ echo $imgData;
213
+ return false;
214
+ exit(0);
215
+ }
216
+ if(preg_match('/https?:\/\/(?:www\.)?' . $this->myHost . '(?:$|\/)/i', $this->src)){
217
+ $this->src = preg_replace('/https?:\/\/(?:www\.)?' . $this->myHost . '/i', '', $this->src);
218
+ }
219
+ if(preg_match('/^https?:\/\/[^\/]+/i', $this->src)){
220
+ $this->debug(2, "Is a request for an external URL: " . $this->src);
221
+ $this->isURL = true;
222
+ } else {
223
+ $this->debug(2, "Is a request for an internal file: " . $this->src);
224
+ }
225
+ if($this->isURL && (! ALLOW_EXTERNAL)){
226
+ $this->error("You are not allowed to fetch images from an external website.");
227
+ return false;
228
+ }
229
+ if($this->isURL){
230
+ if(ALLOW_ALL_EXTERNAL_SITES){
231
+ $this->debug(2, "Fetching from all external sites is enabled.");
232
+ } else {
233
+ $this->debug(2, "Fetching only from selected external sites is enabled.");
234
+ $allowed = false;
235
+ foreach($ALLOWED_SITES as $site){
236
+ if (preg_match ('/(?:^|\.)' . $site . '$/i', $this->url['host'])) {
237
+ $this->debug(3, "URL hostname {$this->url['host']} matches $site so allowing.");
238
+ $allowed = true;
239
+ }
240
+ }
241
+ if(! $allowed){
242
+ return $this->error("You may not fetch images from that site. To enable this site in timthumb, you can either add it to \$ALLOWED_SITES and set ALLOW_EXTERNAL=true. Or you can set ALLOW_ALL_EXTERNAL_SITES=true, depending on your security needs.");
243
+ }
244
+ }
245
+ }
246
+
247
+ $cachePrefix = ($this->isURL ? 'timthumb_ext_' : 'timthumb_int_');
248
+ if($this->isURL){
249
+ $this->cachefile = $this->cacheDirectory . '/' . $cachePrefix . md5($this->salt . $_SERVER ['QUERY_STRING'] . $this->fileCacheVersion) . FILE_CACHE_SUFFIX;
250
+ } else {
251
+ $this->localImage = $this->getLocalImagePath($this->src);
252
+ if(! $this->localImage){
253
+ $this->debug(1, "Could not find the local image: {$this->localImage}");
254
+ $this->error("Could not find the internal image you specified.");
255
+ $this->set404();
256
+ return false;
257
+ }
258
+ $this->debug(1, "Local image path is {$this->localImage}");
259
+ $this->localImageMTime = @filemtime($this->localImage);
260
+ //We include the mtime of the local file in case in changes on disk.
261
+ $this->cachefile = $this->cacheDirectory . '/' . $cachePrefix . md5($this->salt . $this->localImageMTime . $_SERVER ['QUERY_STRING'] . $this->fileCacheVersion) . FILE_CACHE_SUFFIX;
262
+ }
263
+ $this->debug(2, "Cache file is: " . $this->cachefile);
264
+
265
+ return true;
266
+ }
267
+ public function __destruct(){
268
+ foreach($this->toDeletes as $del){
269
+ $this->debug(2, "Deleting temp file $del");
270
+ @unlink($del);
271
+ }
272
+ }
273
+ public function run(){
274
+ if($this->isURL){
275
+ if(! ALLOW_EXTERNAL){
276
+ $this->debug(1, "Got a request for an external image but ALLOW_EXTERNAL is disabled so returning error msg.");
277
+ $this->error("You are not allowed to fetch images from an external website.");
278
+ return false;
279
+ }
280
+ $this->debug(3, "Got request for external image. Starting serveExternalImage.");
281
+ if($this->param('webshot')){
282
+ if(WEBSHOT_ENABLED){
283
+ $this->debug(3, "webshot param is set, so we're going to take a webshot.");
284
+ $this->serveWebshot();
285
+ } else {
286
+ $this->error("You added the webshot parameter but webshots are disabled on this server. You need to set WEBSHOT_ENABLED == true to enable webshots.");
287
+ }
288
+ } else {
289
+ $this->debug(3, "webshot is NOT set so we're going to try to fetch a regular image.");
290
+ $this->serveExternalImage();
291
+
292
+ }
293
+ } else {
294
+ $this->debug(3, "Got request for internal image. Starting serveInternalImage()");
295
+ $this->serveInternalImage();
296
+ }
297
+ return true;
298
+ }
299
+ protected function handleErrors(){
300
+ if($this->haveErrors()){
301
+ if(NOT_FOUND_IMAGE && $this->is404()){
302
+ if($this->serveImg(NOT_FOUND_IMAGE)){
303
+ exit(0);
304
+ } else {
305
+ $this->error("Additionally, the 404 image that is configured could not be found or there was an error serving it.");
306
+ }
307
+ }
308
+ if(ERROR_IMAGE){
309
+ if($this->serveImg(ERROR_IMAGE)){
310
+ exit(0);
311
+ } else {
312
+ $this->error("Additionally, the error image that is configured could not be found or there was an error serving it.");
313
+ }
314
+ }
315
+
316
+ $this->serveErrors();
317
+ exit(0);
318
+ }
319
+ return false;
320
+ }
321
+ protected function tryBrowserCache(){
322
+ if(BROWSER_CACHE_DISABLE){ $this->debug(3, "Browser caching is disabled"); return false; }
323
+ if(!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ){
324
+ $this->debug(3, "Got a conditional get");
325
+ $mtime = false;
326
+ //We've already checked if the real file exists in the constructor
327
+ if(! is_file($this->cachefile)){
328
+ //If we don't have something cached, regenerate the cached image.
329
+ return false;
330
+ }
331
+ if($this->localImageMTime){
332
+ $mtime = $this->localImageMTime;
333
+ $this->debug(3, "Local real file's modification time is $mtime");
334
+ } else if(is_file($this->cachefile)){ //If it's not a local request then use the mtime of the cached file to determine the 304
335
+ $mtime = @filemtime($this->cachefile);
336
+ $this->debug(3, "Cached file's modification time is $mtime");
337
+ }
338
+ if(! $mtime){ return false; }
339
+
340
+ $iftime = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
341
+ $this->debug(3, "The conditional get's if-modified-since unixtime is $iftime");
342
+ if($iftime < 1){
343
+ $this->debug(3, "Got an invalid conditional get modified since time. Returning false.");
344
+ return false;
345
+ }
346
+ if($iftime < $mtime){ //Real file or cache file has been modified since last request, so force refetch.
347
+ $this->debug(3, "File has been modified since last fetch.");
348
+ return false;
349
+ } else { //Otherwise serve a 304
350
+ $this->debug(3, "File has not been modified since last get, so serving a 304.");
351
+ header ('HTTP/1.1 304 Not Modified');
352
+ $this->debug(1, "Returning 304 not modified");
353
+ return true;
354
+ }
355
+ }
356
+ return false;
357
+ }
358
+ protected function tryServerCache(){
359
+ $this->debug(3, "Trying server cache");
360
+ if(file_exists($this->cachefile)){
361
+ $this->debug(3, "Cachefile {$this->cachefile} exists");
362
+ if($this->isURL){
363
+ $this->debug(3, "This is an external request, so checking if the cachefile is empty which means the request failed previously.");
364
+ if(filesize($this->cachefile) < 1){
365
+ $this->debug(3, "Found an empty cachefile indicating a failed earlier request. Checking how old it is.");
366
+ //Fetching error occured previously
367
+ if(time() - @filemtime($this->cachefile) > WAIT_BETWEEN_FETCH_ERRORS){
368
+ $this->debug(3, "File is older than " . WAIT_BETWEEN_FETCH_ERRORS . " seconds. Deleting and returning false so app can try and load file.");
369
+ @unlink($this->cachefile);
370
+ return false; //to indicate we didn't serve from cache and app should try and load
371
+ } else {
372
+ $this->debug(3, "Empty cachefile is still fresh so returning message saying we had an error fetching this image from remote host.");
373
+ $this->set404();
374
+ $this->error("An error occured fetching image.");
375
+ return false;
376
+ }
377
+ }
378
+ } else {
379
+ $this->debug(3, "Trying to serve cachefile {$this->cachefile}");
380
+ }
381
+ if($this->serveCacheFile()){
382
+ $this->debug(3, "Succesfully served cachefile {$this->cachefile}");
383
+ return true;
384
+ } else {
385
+ $this->debug(3, "Failed to serve cachefile {$this->cachefile} - Deleting it from cache.");
386
+ //Image serving failed. We can't retry at this point, but lets remove it from cache so the next request recreates it
387
+ @unlink($this->cachefile);
388
+ return true;
389
+ }
390
+ }
391
+ }
392
+ protected function error($err){
393
+ $this->debug(3, "Adding error message: $err");
394
+ $this->errors[] = $err;
395
+ return false;
396
+
397
+ }
398
+ protected function haveErrors(){
399
+ if(sizeof($this->errors) > 0){
400
+ return true;
401
+ }
402
+ return false;
403
+ }
404
+ protected function serveErrors(){
405
+ $html = '<ul>';
406
+ foreach($this->errors as $err){
407
+ $html .= '<li>' . htmlentities($err) . '</li>';
408
+ }
409
+ $html .= '</ul>';
410
+ header ('HTTP/1.1 400 Bad Request');
411
+ echo '<h1>A TimThumb error has occured</h1>The following error(s) occured:<br />' . $html . '<br />';
412
+ echo '<br />Query String : ' . htmlentities ($_SERVER['QUERY_STRING']);
413
+ echo '<br />TimThumb version : ' . VERSION . '</pre>';
414
+ }
415
+ protected function serveInternalImage(){
416
+ $this->debug(3, "Local image path is $this->localImage");
417
+ if(! $this->localImage){
418
+ $this->sanityFail("localImage not set after verifying it earlier in the code.");
419
+ return false;
420
+ }
421
+ $fileSize = filesize($this->localImage);
422
+ if($fileSize > MAX_FILE_SIZE){
423
+ $this->error("The file you specified is greater than the maximum allowed file size.");
424
+ return false;
425
+ }
426
+ if($fileSize <= 0){
427
+ $this->error("The file you specified is <= 0 bytes.");
428
+ return false;
429
+ }
430
+ $this->debug(3, "Calling processImageAndWriteToCache() for local image.");
431
+ if($this->processImageAndWriteToCache($this->localImage)){
432
+ $this->serveCacheFile();
433
+ return true;
434
+ } else {
435
+ return false;
436
+ }
437
+ }
438
+ protected function cleanCache(){
439
+ $this->debug(3, "cleanCache() called");
440
+ $lastCleanFile = $this->cacheDirectory . '/timthumb_cacheLastCleanTime.touch';
441
+
442
+ //If this is a new timthumb installation we need to create the file
443
+ if(! is_file($lastCleanFile)){
444
+ $this->debug(1, "File tracking last clean doesn't exist. Creating $lastCleanFile");
445
+ touch($lastCleanFile);
446
+ return;
447
+ }
448
+ if(@filemtime($lastCleanFile) < (time() - FILE_CACHE_TIME_BETWEEN_CLEANS) ){ //Cache was last cleaned more than 1 day ago
449
+ $this->debug(1, "Cache was last cleaned more than " . FILE_CACHE_TIME_BETWEEN_CLEANS . " seconds ago. Cleaning now.");
450
+ // Very slight race condition here, but worst case we'll have 2 or 3 servers cleaning the cache simultaneously once a day.
451
+ touch($lastCleanFile);
452
+ $files = glob($this->cacheDirectory . '/*' . FILE_CACHE_SUFFIX);
453
+ $timeAgo = time() - FILE_CACHE_MAX_FILE_AGE;
454
+ foreach($files as $file){
455
+ if(@filemtime($file) < $timeAgo){
456
+ $this->debug(3, "Deleting cache file $file older than max age: " . FILE_CACHE_MAX_FILE_AGE . " seconds");
457
+ @unlink($file);
458
+ }
459
+ }
460
+ return true;
461
+ } else {
462
+ $this->debug(3, "Cache was cleaned less than " . FILE_CACHE_TIME_BETWEEN_CLEANS . " seconds ago so no cleaning needed.");
463
+ }
464
+ return false;
465
+ }
466
+ protected function processImageAndWriteToCache($localImage){
467
+ $sData = getimagesize($localImage);
468
+ $origType = $sData[2];
469
+ $mimeType = $sData['mime'];
470
+
471
+ $this->debug(3, "Mime type of image is $mimeType");
472
+ if(! preg_match('/^image\/(?:gif|jpg|jpeg|png)$/i', $mimeType)){
473
+ return $this->error("The image being resized is not a valid gif, jpg or png.");
474
+ }
475
+
476
+ if (!function_exists ('imagecreatetruecolor')) {
477
+ return $this->error('GD Library Error: imagecreatetruecolor does not exist - please contact your webhost and ask them to install the GD library');
478
+ }
479
+
480
+ if (function_exists ('imagefilter') && defined ('IMG_FILTER_NEGATE')) {
481
+ $imageFilters = array (
482
+ 1 => array (IMG_FILTER_NEGATE, 0),
483
+ 2 => array (IMG_FILTER_GRAYSCALE, 0),
484
+ 3 => array (IMG_FILTER_BRIGHTNESS, 1),
485
+ 4 => array (IMG_FILTER_CONTRAST, 1),
486
+ 5 => array (IMG_FILTER_COLORIZE, 4),
487
+ 6 => array (IMG_FILTER_EDGEDETECT, 0),
488
+ 7 => array (IMG_FILTER_EMBOSS, 0),
489
+ 8 => array (IMG_FILTER_GAUSSIAN_BLUR, 0),
490
+ 9 => array (IMG_FILTER_SELECTIVE_BLUR, 0),
491
+ 10 => array (IMG_FILTER_MEAN_REMOVAL, 0),
492
+ 11 => array (IMG_FILTER_SMOOTH, 0),
493
+ );
494
+ }
495
+
496
+ // get standard input properties
497
+ $new_width = (int) abs ($this->param('w', 0));
498
+ $new_height = (int) abs ($this->param('h', 0));
499
+ $zoom_crop = (int) $this->param('zc', 1);
500
+ $quality = (int) abs ($this->param('q', 90));
501
+ $align = $this->cropTop ? 't' : $this->param('a', 'c');
502
+ $filters = $this->param('f', '');
503
+ $sharpen = (bool) $this->param('s', 0);
504
+ $canvas_color = $this->param('cc', 'ffffff');
505
+
506
+ // set default width and height if neither are set already
507
+ if ($new_width == 0 && $new_height == 0) {
508
+ $new_width = 100;
509
+ $new_height = 100;
510
+ }
511
+
512
+ // ensure size limits can not be abused
513
+ $new_width = min ($new_width, MAX_WIDTH);
514
+ $new_height = min ($new_height, MAX_HEIGHT);
515
+
516
+ // set memory limit to be able to have enough space to resize larger images
517
+ $this->setMemoryLimit();
518
+
519
+ // open the existing image
520
+ $image = $this->openImage ($mimeType, $localImage);
521
+ if ($image === false) {
522
+ return $this->error('Unable to open image.');
523
+ }
524
+
525
+ // Get original width and height
526
+ $width = imagesx ($image);
527
+ $height = imagesy ($image);
528
+ $origin_x = 0;
529
+ $origin_y = 0;
530
+
531
+ // generate new w/h if not provided
532
+ if ($new_width && !$new_height) {
533
+ $new_height = floor ($height * ($new_width / $width));
534
+ } else if ($new_height && !$new_width) {
535
+ $new_width = floor ($width * ($new_height / $height));
536
+ }
537
+
538
+ // scale down and add borders
539
+ if ($zoom_crop == 3) {
540
+
541
+ $final_height = $height * ($new_width / $width);
542
+
543
+ if ($final_height > $new_height) {
544
+ $new_width = $width * ($new_height / $height);
545
+ } else {
546
+ $new_height = $final_height;
547
+ }
548
+
549
+ }
550
+
551
+ // create a new true color image
552
+ $canvas = imagecreatetruecolor ($new_width, $new_height);
553
+ imagealphablending ($canvas, false);
554
+
555
+ if (strlen ($canvas_color) < 6) {
556
+ $canvas_color = 'ffffff';
557
+ }
558
+
559
+ $canvas_color_R = hexdec (substr ($canvas_color, 0, 2));
560
+ $canvas_color_G = hexdec (substr ($canvas_color, 2, 2));
561
+ $canvas_color_B = hexdec (substr ($canvas_color, 2, 2));
562
+
563
+ // Create a new transparent color for image
564
+ $color = imagecolorallocatealpha ($canvas, $canvas_color_R, $canvas_color_G, $canvas_color_B, 127);
565
+
566
+ // Completely fill the background of the new image with allocated color.
567
+ imagefill ($canvas, 0, 0, $color);
568
+
569
+ // scale down and add borders
570
+ if ($zoom_crop == 2) {
571
+
572
+ $final_height = $height * ($new_width / $width);
573
+
574
+ if ($final_height > $new_height) {
575
+
576
+ $origin_x = $new_width / 2;
577
+ $new_width = $width * ($new_height / $height);
578
+ $origin_x = round ($origin_x - ($new_width / 2));
579
+
580
+ } else {
581
+
582
+ $origin_y = $new_height / 2;
583
+ $new_height = $final_height;
584
+ $origin_y = round ($origin_y - ($new_height / 2));
585
+
586
+ }
587
+
588
+ }
589
+
590
+ // Restore transparency blending
591
+ imagesavealpha ($canvas, true);
592
+
593
+ if ($zoom_crop > 0) {
594
+
595
+ $src_x = $src_y = 0;
596
+ $src_w = $width;
597
+ $src_h = $height;
598
+
599
+ $cmp_x = $width / $new_width;
600
+ $cmp_y = $height / $new_height;
601
+
602
+ // calculate x or y coordinate and width or height of source
603
+ if ($cmp_x > $cmp_y) {
604
+
605
+ $src_w = round ($width / $cmp_x * $cmp_y);
606
+ $src_x = round (($width - ($width / $cmp_x * $cmp_y)) / 2);
607
+
608
+ } else if ($cmp_y > $cmp_x) {
609
+
610
+ $src_h = round ($height / $cmp_y * $cmp_x);
611
+ $src_y = round (($height - ($height / $cmp_y * $cmp_x)) / 2);
612
+
613
+ }
614
+
615
+ // positional cropping!
616
+ if ($align) {
617
+ if (strpos ($align, 't') !== false) {
618
+ $src_y = 0;
619
+ }
620
+ if (strpos ($align, 'b') !== false) {
621
+ $src_y = $height - $src_h;
622
+ }
623
+ if (strpos ($align, 'l') !== false) {
624
+ $src_x = 0;
625
+ }
626
+ if (strpos ($align, 'r') !== false) {
627
+ $src_x = $width - $src_w;
628
+ }
629
+ }
630
+
631
+ imagecopyresampled ($canvas, $image, $origin_x, $origin_y, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h);
632
+
633
+ } else {
634
+
635
+ // copy and resize part of an image with resampling
636
+ imagecopyresampled ($canvas, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
637
+
638
+ }
639
+
640
+ if ($filters != '' && function_exists ('imagefilter') && defined ('IMG_FILTER_NEGATE')) {
641
+ // apply filters to image
642
+ $filterList = explode ('|', $filters);
643
+ foreach ($filterList as $fl) {
644
+
645
+ $filterSettings = explode (',', $fl);
646
+ if (isset ($imageFilters[$filterSettings[0]])) {
647
+
648
+ for ($i = 0; $i < 4; $i ++) {
649
+ if (!isset ($filterSettings[$i])) {
650
+ $filterSettings[$i] = null;
651
+ } else {
652
+ $filterSettings[$i] = (int) $filterSettings[$i];
653
+ }
654
+ }
655
+
656
+ switch ($imageFilters[$filterSettings[0]][1]) {
657
+
658
+ case 1:
659
+
660
+ imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1]);
661
+ break;
662
+
663
+ case 2:
664
+
665
+ imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2]);
666
+ break;
667
+
668
+ case 3:
669
+
670
+ imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3]);
671
+ break;
672
+
673
+ case 4:
674
+
675
+ imagefilter ($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3], $filterSettings[4]);
676
+ break;
677
+
678
+ default:
679
+
680
+ imagefilter ($canvas, $imageFilters[$filterSettings[0]][0]);
681
+ break;
682
+
683
+ }
684
+ }
685
+ }
686
+ }
687
+
688
+ // sharpen image
689
+ if ($sharpen && function_exists ('imageconvolution')) {
690
+
691
+ $sharpenMatrix = array (
692
+ array (-1,-1,-1),
693
+ array (-1,16,-1),
694
+ array (-1,-1,-1),
695
+ );
696
+
697
+ $divisor = 8;
698
+ $offset = 0;
699
+
700
+ imageconvolution ($canvas, $sharpenMatrix, $divisor, $offset);
701
+
702
+ }
703
+ //Straight from Wordpress core code. Reduces filesize by up to 70% for PNG's
704
+ if ( (IMAGETYPE_PNG == $origType || IMAGETYPE_GIF == $origType) && function_exists('imageistruecolor') && !imageistruecolor( $image ) && imagecolortransparent( $image ) > 0 ){
705
+ imagetruecolortopalette( $canvas, false, imagecolorstotal( $image ) );
706
+ }
707
+
708
+ $imgType = "";
709
+ $tempfile = tempnam($this->cacheDirectory, 'timthumb_tmpimg_');
710
+ if(preg_match('/^image\/(?:jpg|jpeg)$/i', $mimeType)){
711
+ $imgType = 'jpg';
712
+ imagejpeg($canvas, $tempfile, $quality);
713
+ } else if(preg_match('/^image\/png$/i', $mimeType)){
714
+ $imgType = 'png';
715
+ imagepng($canvas, $tempfile, floor($quality * 0.09));
716
+ } else if(preg_match('/^image\/gif$/i', $mimeType)){
717
+ $imgType = 'gif';
718
+ imagegif($canvas, $tempfile);
719
+ } else {
720
+ return $this->sanityFail("Could not match mime type after verifying it previously.");
721
+ }
722
+
723
+ if($imgType == 'png' && OPTIPNG_ENABLED && OPTIPNG_PATH && @is_file(OPTIPNG_PATH)){
724
+ $exec = OPTIPNG_PATH;
725
+ $this->debug(3, "optipng'ing $tempfile");
726
+ $presize = filesize($tempfile);
727
+ $out = `$exec -o1 $tempfile`; //you can use up to -o7 but it really slows things down
728
+ clearstatcache();
729
+ $aftersize = filesize($tempfile);
730
+ $sizeDrop = $presize - $aftersize;
731
+ if($sizeDrop > 0){
732
+ $this->debug(1, "optipng reduced size by $sizeDrop");
733
+ } else if($sizeDrop < 0){
734
+ $this->debug(1, "optipng increased size! Difference was: $sizeDrop");
735
+ } else {
736
+ $this->debug(1, "optipng did not change image size.");
737
+ }
738
+ } else if($imgType == 'png' && PNGCRUSH_ENABLED && PNGCRUSH_PATH && @is_file(PNGCRUSH_PATH)){
739
+ $exec = PNGCRUSH_PATH;
740
+ $tempfile2 = tempnam($this->cacheDirectory, 'timthumb_tmpimg_');
741
+ $this->debug(3, "pngcrush'ing $tempfile to $tempfile2");
742
+ $out = `$exec $tempfile $tempfile2`;
743
+ $todel = "";
744
+ if(is_file($tempfile2)){
745
+ $sizeDrop = filesize($tempfile) - filesize($tempfile2);
746
+ if($sizeDrop > 0){
747
+ $this->debug(1, "pngcrush was succesful and gave a $sizeDrop byte size reduction");
748
+ $todel = $tempfile;
749
+ $tempfile = $tempfile2;
750
+ } else {
751
+ $this->debug(1, "pngcrush did not reduce file size. Difference was $sizeDrop bytes.");
752
+ $todel = $tempfile2;
753
+ }
754
+ } else {
755
+ $this->debug(3, "pngcrush failed with output: $out");
756
+ $todel = $tempfile2;
757
+ }
758
+ @unlink($todel);
759
+ }
760
+
761
+ $this->debug(3, "Rewriting image with security header.");
762
+ $tempfile4 = tempnam($this->cacheDirectory, 'timthumb_tmpimg_');
763
+ $context = stream_context_create ();
764
+ $fp = fopen($tempfile,'r',0,$context);
765
+ file_put_contents($tempfile4, $this->filePrependSecurityBlock . $imgType . ' ?' . '>'); //6 extra bytes, first 3 being image type
766
+ file_put_contents($tempfile4, $fp, FILE_APPEND);
767
+ fclose($fp);
768
+ @unlink($tempfile);
769
+ $this->debug(3, "Locking and replacing cache file.");
770
+ $lockFile = $this->cachefile . '.lock';
771
+ $fh = fopen($lockFile, 'w');
772
+ if(! $fh){
773
+ return $this->error("Could not open the lockfile for writing an image.");
774
+ }
775
+ if(flock($fh, LOCK_EX)){
776
+ @unlink($this->cachefile); //rename generally overwrites, but doing this in case of platform specific quirks. File might not exist yet.
777
+ rename($tempfile4, $this->cachefile);
778
+ flock($fh, LOCK_UN);
779
+ fclose($fh);
780
+ @unlink($lockFile);
781
+ } else {
782
+ fclose($fh);
783
+ @unlink($lockFile);
784
+ @unlink($tempfile4);
785
+ return $this->error("Could not get a lock for writing.");
786
+ }
787
+ $this->debug(3, "Done image replace with security header. Cleaning up and running cleanCache()");
788
+ imagedestroy($canvas);
789
+ imagedestroy($image);
790
+ return true;
791
+ }
792
+ protected function calcDocRoot(){
793
+ $docRoot = @$_SERVER['DOCUMENT_ROOT'];
794
+ if(!isset($docRoot)){
795
+ $this->debug(3, "DOCUMENT_ROOT is not set. This is probably windows. Starting search 1.");
796
+ if(isset($_SERVER['SCRIPT_FILENAME'])){
797
+ $docRoot = str_replace( '\\', '/', substr($_SERVER['SCRIPT_FILENAME'], 0, 0-strlen($_SERVER['PHP_SELF'])));
798
+ $this->debug(3, "Generated docRoot using SCRIPT_FILENAME and PHP_SELF as: $docRoot");
799
+ }
800
+ }
801
+ if(!isset($docRoot)){
802
+ $this->debug(3, "DOCUMENT_ROOT still is not set. Starting search 2.");
803
+ if(isset($_SERVER['PATH_TRANSLATED'])){
804
+ $docRoot = str_replace( '\\', '/', substr(str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED']), 0, 0-strlen($_SERVER['PHP_SELF'])));
805
+ $this->debug(3, "Generated docRoot using PATH_TRANSLATED and PHP_SELF as: $docRoot");
806
+ }
807
+ }
808
+ if($docRoot && $_SERVER['DOCUMENT_ROOT'] != '/'){ $docRoot = preg_replace('/\/$/', '', $docRoot); }
809
+ $this->debug(3, "Doc root is: " . $docRoot);
810
+ $this->docRoot = $docRoot;
811
+
812
+ }
813
+ protected function getLocalImagePath($src){
814
+ $src = preg_replace('/^\//', '', $src); //strip off the leading '/'
815
+ $realDocRoot = realpath($this->docRoot); //See issue 224. Using realpath as a windows fix.
816
+ if(! $this->docRoot){
817
+ $this->debug(3, "We have no document root set, so as a last resort, lets check if the image is in the current dir and serve that.");
818
+ //We don't support serving images outside the current dir if we don't have a doc root for security reasons.
819
+ $file = preg_replace('/^.*?([^\/\\\\]+)$/', '$1', $src); //strip off any path info and just leave the filename.
820
+ if(is_file($file)){
821
+ return realpath($file);
822
+ }
823
+ return $this->error("Could not find your website document root and the file specified doesn't exist in timthumbs directory. We don't support serving files outside timthumb's directory without a document root for security reasons.");
824
+ } //Do not go past this point without docRoot set
825
+
826
+ //Try src under docRoot
827
+ if(file_exists ($this->docRoot . '/' . $src)) {
828
+ $this->debug(3, "Found file as " . $this->docRoot . '/' . $src);
829
+ $real = realpath($this->docRoot . '/' . $src);
830
+ if(strpos($real, $realDocRoot) === 0){
831
+ return $real;
832
+ } else {
833
+ $this->debug(1, "Security block: The file specified occurs outside the document root.");
834
+ //allow search to continue
835
+ }
836
+ }
837
+ //Check absolute paths and then verify the real path is under doc root
838
+ $absolute = realpath('/' . $src);
839
+ if($absolute && file_exists($absolute)){ //realpath does file_exists check, so can probably skip the exists check here
840
+ $this->debug(3, "Found absolute path: $absolute");
841
+ if(! $this->docRoot){ $this->sanityFail("docRoot not set when checking absolute path."); }
842
+ if(strpos($absolute, $realDocRoot) === 0){
843
+ return $absolute;
844
+ } else {
845
+ $this->debug(1, "Security block: The file specified occurs outside the document root.");
846
+ //and continue search
847
+ }
848
+ }
849
+ $base = $this->docRoot;
850
+ foreach (explode('/', str_replace($this->docRoot, '', $_SERVER['SCRIPT_FILENAME'])) as $sub){
851
+ $base .= $sub . '/';
852
+ $this->debug(3, "Trying file as: " . $base . $src);
853
+ if(file_exists($base . $src)){
854
+ $this->debug(3, "Found file as: " . $base . $src);
855
+ $real = realpath($base . $src);
856
+ if(strpos($real, $realDocRoot) === 0){
857
+ return $real;
858
+ } else {
859
+ $this->debug(1, "Security block: The file specified occurs outside the document root.");
860
+ //And continue search
861
+ }
862
+ }
863
+ }
864
+ return false;
865
+ }
866
+ protected function toDelete($name){
867
+ $this->debug(3, "Scheduling file $name to delete on destruct.");
868
+ $this->toDeletes[] = $name;
869
+ }
870
+ protected function serveWebshot(){
871
+ $this->debug(3, "Starting serveWebshot");
872
+ $instr = "Please follow the instructions at http://code.google.com/p/timthumb/ to set your server up for taking website screenshots.";
873
+ if(! is_file(WEBSHOT_CUTYCAPT)){
874
+ return $this->error("CutyCapt is not installed. $instr");
875
+ }
876
+ if(! is_file(WEBSHOT_XVFB)){
877
+ return $this->Error("Xvfb is not installed. $instr");
878
+ }
879
+ $cuty = WEBSHOT_CUTYCAPT;
880
+ $xv = WEBSHOT_XVFB;
881
+ $screenX = WEBSHOT_SCREEN_X;
882
+ $screenY = WEBSHOT_SCREEN_Y;
883
+ $colDepth = WEBSHOT_COLOR_DEPTH;
884
+ $format = WEBSHOT_IMAGE_FORMAT;
885
+ $timeout = WEBSHOT_TIMEOUT * 1000;
886
+ $ua = WEBSHOT_USER_AGENT;
887
+ $jsOn = WEBSHOT_JAVASCRIPT_ON ? 'on' : 'off';
888
+ $javaOn = WEBSHOT_JAVA_ON ? 'on' : 'off';
889
+ $pluginsOn = WEBSHOT_PLUGINS_ON ? 'on' : 'off';
890
+ $proxy = WEBSHOT_PROXY ? ' --http-proxy=' . WEBSHOT_PROXY : '';
891
+ $tempfile = tempnam($this->cacheDirectory, 'timthumb_webshot');
892
+ $url = $this->src;
893
+ if(! preg_match('/^https?:\/\/[a-zA-Z0-9\.\-]+/i', $url)){
894
+ return $this->error("Invalid URL supplied.");
895
+ }
896
+ $url = preg_replace('/[^A-Za-z0-9\-\.\_\~:\/\?\#\[\]\@\!\$\&\'\(\)\*\+\,\;\=]+/', '', $url); //RFC 3986
897
+ //Very important we don't allow injection of shell commands here. URL is between quotes and we are only allowing through chars allowed by a the RFC
898
+ // which AFAIKT can't be used for shell injection.
899
+ if(WEBSHOT_XVFB_RUNNING){
900
+ putenv('DISPLAY=:100.0');
901
+ $command = "$cuty $proxy --max-wait=$timeout --user-agent=\"$ua\" --javascript=$jsOn --java=$javaOn --plugins=$pluginsOn --js-can-open-windows=off --url=\"$url\" --out-format=$format --out=$tempfile";
902
+ } else {
903
+ $command = "$xv --server-args=\"-screen 0, {$screenX}x{$screenY}x{$colDepth}\" $cuty $proxy --max-wait=$timeout --user-agent=\"$ua\" --javascript=$jsOn --java=$javaOn --plugins=$pluginsOn --js-can-open-windows=off --url=\"$url\" --out-format=$format --out=$tempfile";
904
+ }
905
+ $this->debug(3, "Executing command: $command");
906
+ $out = `$command`;
907
+ $this->debug(3, "Received output: $out");
908
+ if(! is_file($tempfile)){
909
+ $this->set404();
910
+ return $this->error("The command to create a thumbnail failed.");
911
+ }
912
+ $this->cropTop = true;
913
+ if($this->processImageAndWriteToCache($tempfile)){
914
+ $this->debug(3, "Image processed succesfully. Serving from cache");
915
+ return $this->serveCacheFile();
916
+ } else {
917
+ return false;
918
+ }
919
+ }
920
+ protected function serveExternalImage(){
921
+ if(! preg_match('/^https?:\/\/[a-zA-Z0-9\-\.]+/i', $this->src)){
922
+ $this->error("Invalid URL supplied.");
923
+ return false;
924
+ }
925
+ $tempfile = tempnam($this->cacheDirectory, 'timthumb');
926
+ $this->debug(3, "Fetching external image into temporary file $tempfile");
927
+ $this->toDelete($tempfile);
928
+ #fetch file here
929
+ if(! $this->getURL($this->src, $tempfile)){
930
+ @unlink($this->cachefile);
931
+ touch($this->cachefile);
932
+ $this->debug(3, "Error fetching URL: " . $this->lastURLError);
933
+ $this->error("Error reading the URL you specified from remote host." . $this->lastURLError);
934
+ return false;
935
+ }
936
+
937
+ $mimeType = $this->getMimeType($tempfile);
938
+ if(! preg_match("/^image\/(?:jpg|jpeg|gif|png)$/i", $mimeType)){
939
+ $this->debug(3, "Remote file has invalid mime type: $mimeType");
940
+ @unlink($this->cachefile);
941
+ touch($this->cachefile);
942
+ $this->error("The remote file is not a valid image.");
943
+ return false;
944
+ }
945
+ if($this->processImageAndWriteToCache($tempfile)){
946
+ $this->debug(3, "Image processed succesfully. Serving from cache");
947
+ return $this->serveCacheFile();
948
+ } else {
949
+ return false;
950
+ }
951
+ }
952
+ public static function curlWrite($h, $d){
953
+ fwrite(self::$curlFH, $d);
954
+ self::$curlDataWritten += strlen($d);
955
+ if(self::$curlDataWritten > MAX_FILE_SIZE){
956
+ return 0;
957
+ } else {
958
+ return strlen($d);
959
+ }
960
+ }
961
+ protected function serveCacheFile(){
962
+ $this->debug(3, "Serving {$this->cachefile}");
963
+ if(! is_file($this->cachefile)){
964
+ $this->error("serveCacheFile called in timthumb but we couldn't find the cached file.");
965
+ return false;
966
+ }
967
+ $fp = fopen($this->cachefile, 'rb');
968
+ if(! $fp){ return $this->error("Could not open cachefile."); }
969
+ fseek($fp, strlen($this->filePrependSecurityBlock), SEEK_SET);
970
+ $imgType = fread($fp, 3);
971
+ fseek($fp, 3, SEEK_CUR);
972
+ if(ftell($fp) != strlen($this->filePrependSecurityBlock) + 6){
973
+ @unlink($this->cachefile);
974
+ return $this->error("The cached image file seems to be corrupt.");
975
+ }
976
+ $imageDataSize = filesize($this->cachefile) - (strlen($this->filePrependSecurityBlock) + 6);
977
+ $this->sendImageHeaders($imgType, $imageDataSize);
978
+ $bytesSent = @fpassthru($fp);
979
+ fclose($fp);
980
+ if($bytesSent > 0){
981
+ return true;
982
+ }
983
+ $content = file_get_contents ($this->cachefile);
984
+ if ($content != FALSE) {
985
+ $content = substr($content, strlen($this->filePrependSecurityBlock) + 6);
986
+ echo $content;
987
+ $this->debug(3, "Served using file_get_contents and echo");
988
+ return true;
989
+ } else {
990
+ $this->error("Cache file could not be loaded.");
991
+ return false;
992
+ }
993
+ }
994
+ protected function sendImageHeaders($mimeType, $dataSize){
995
+ if(! preg_match('/^image\//i', $mimeType)){
996
+ $mimeType = 'image/' . $mimeType;
997
+ }
998
+ if(strtolower($mimeType) == 'image/jpg'){
999
+ $mimeType = 'image/jpeg';
1000
+ }
1001
+ $gmdate_expires = gmdate ('D, d M Y H:i:s', strtotime ('now +10 days')) . ' GMT';
1002
+ $gmdate_modified = gmdate ('D, d M Y H:i:s') . ' GMT';
1003
+ // send content headers then display image
1004
+ header ('Content-Type: ' . $mimeType);
1005
+ header ('Accept-Ranges: none'); //Changed this because we don't accept range requests
1006
+ header ('Last-Modified: ' . $gmdate_modified);
1007
+ header ('Content-Length: ' . $dataSize);
1008
+ if(BROWSER_CACHE_DISABLE){
1009
+ $this->debug(3, "Browser cache is disabled so setting non-caching headers.");
1010
+ header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
1011
+ header("Pragma: no-cache");
1012
+ header('Expires: ' . gmdate ('D, d M Y H:i:s', time()));
1013
+ } else {
1014
+ $this->debug(3, "Browser caching is enabled");
1015
+ header('Cache-Control: max-age=' . BROWSER_CACHE_MAX_AGE . ', must-revalidate');
1016
+ header('Expires: ' . $gmdate_expires);
1017
+ }
1018
+ return true;
1019
+ }
1020
+ protected function securityChecks(){
1021
+ }
1022
+ protected function param($property, $default = ''){
1023
+ if (isset ($_GET[$property])) {
1024
+ return $_GET[$property];
1025
+ } else {
1026
+ return $default;
1027
+ }
1028
+ }
1029
+ protected function openImage($mimeType, $src){
1030
+ switch ($mimeType) {
1031
+ case 'image/jpg': //This isn't a valid mime type so we should probably remove it
1032
+ case 'image/jpeg':
1033
+ $image = imagecreatefromjpeg ($src);
1034
+ break;
1035
+
1036
+ case 'image/png':
1037
+ $image = imagecreatefrompng ($src);
1038
+ break;
1039
+
1040
+ case 'image/gif':
1041
+ $image = imagecreatefromgif ($src);
1042
+ break;
1043
+ }
1044
+
1045
+ return $image;
1046
+ }
1047
+ protected function getIP(){
1048
+ $rem = @$_SERVER["REMOTE_ADDR"];
1049
+ $ff = @$_SERVER["HTTP_X_FORWARDED_FOR"];
1050
+ $ci = @$_SERVER["HTTP_CLIENT_IP"];
1051
+ if(preg_match('/^(?:192\.168|172\.16|10\.|127\.)/', $rem)){
1052
+ if($ff){ return $ff; }
1053
+ if($ci){ return $ci; }
1054
+ return $rem;
1055
+ } else {
1056
+ if($rem){ return $rem; }
1057
+ if($ff){ return $ff; }
1058
+ if($ci){ return $ci; }
1059
+ return "UNKNOWN";
1060
+ }
1061
+ }
1062
+ protected function debug($level, $msg){
1063
+ if(DEBUG_ON && $level <= DEBUG_LEVEL){
1064
+ $execTime = sprintf('%.6f', microtime(true) - $this->startTime);
1065
+ $tick = sprintf('%.6f', 0);
1066
+ if($this->lastBenchTime > 0){
1067
+ $tick = sprintf('%.6f', microtime(true) - $this->lastBenchTime);
1068
+ }
1069
+ $this->lastBenchTime = microtime(true);
1070
+ error_log("TimThumb Debug line " . __LINE__ . " [$execTime : $tick]: $msg");
1071
+ }
1072
+ }
1073
+ protected function sanityFail($msg){
1074
+ return $this->error("There is a problem in the timthumb code. Message: Please report this error at <a href='http://code.google.com/p/timthumb/issues/list'>timthumb's bug tracking page</a>: $msg");
1075
+ }
1076
+ protected function getMimeType($file){
1077
+ $info = getimagesize($file);
1078
+ if(is_array($info) && $info['mime']){
1079
+ return $info['mime'];
1080
+ }
1081
+ return '';
1082
+ }
1083
+ protected function setMemoryLimit(){
1084
+ $inimem = ini_get('memory_limit');
1085
+ $inibytes = timthumb::returnBytes($inimem);
1086
+ $ourbytes = timthumb::returnBytes(MEMORY_LIMIT);
1087
+ if($inibytes < $ourbytes){
1088
+ ini_set ('memory_limit', MEMORY_LIMIT);
1089
+ $this->debug(3, "Increased memory from $inimem to " . MEMORY_LIMIT);
1090
+ } else {
1091
+ $this->debug(3, "Not adjusting memory size because the current setting is " . $inimem . " and our size of " . MEMORY_LIMIT . " is smaller.");
1092
+ }
1093
+ }
1094
+ protected static function returnBytes($size_str){
1095
+ switch (substr ($size_str, -1))
1096
+ {
1097
+ case 'M': case 'm': return (int)$size_str * 1048576;
1098
+ case 'K': case 'k': return (int)$size_str * 1024;
1099
+ case 'G': case 'g': return (int)$size_str * 1073741824;
1100
+ default: return $size_str;
1101
+ }
1102
+ }
1103
+ protected function getURL($url, $tempfile){
1104
+ $this->lastURLError = false;
1105
+ $url = preg_replace('/ /', '%20', $url);
1106
+ if(function_exists('curl_init')){
1107
+ $this->debug(3, "Curl is installed so using it to fetch URL.");
1108
+ self::$curlFH = fopen($tempfile, 'w');
1109
+ if(! self::$curlFH){
1110
+ $this->error("Could not open $tempfile for writing.");
1111
+ return false;
1112
+ }
1113
+ self::$curlDataWritten = 0;
1114
+ $this->debug(3, "Fetching url with curl: $url");
1115
+ $curl = curl_init($url);
1116
+ curl_setopt ($curl, CURLOPT_TIMEOUT, CURL_TIMEOUT);
1117
+ curl_setopt ($curl, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.122 Safari/534.30");
1118
+ curl_setopt ($curl, CURLOPT_RETURNTRANSFER, TRUE);
1119
+ curl_setopt ($curl, CURLOPT_HEADER, 0);
1120
+ curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
1121
+ curl_setopt ($curl, CURLOPT_WRITEFUNCTION, 'timthumb::curlWrite');
1122
+ @curl_setopt ($curl, CURLOPT_FOLLOWLOCATION, true);
1123
+ @curl_setopt ($curl, CURLOPT_MAXREDIRS, 10);
1124
+
1125
+ $curlResult = curl_exec($curl);
1126
+ fclose(self::$curlFH);
1127
+ $httpStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
1128
+ if($httpStatus == 404){
1129
+ $this->set404();
1130
+ }
1131
+ if($curlResult){
1132
+ curl_close($curl);
1133
+ return true;
1134
+ } else {
1135
+ $this->lastURLError = curl_error($curl);
1136
+ curl_close($curl);
1137
+ return false;
1138
+ }
1139
+ } else {
1140
+ $img = @file_get_contents ($url);
1141
+ if($img === false){
1142
+ $err = error_get_last();
1143
+ if(is_array($err) && $err['message']){
1144
+ $this->lastURLError = $err['message'];
1145
+ } else {
1146
+ $this->lastURLError = $err;
1147
+ }
1148
+ if(preg_match('/404/', $this->lastURLError)){
1149
+ $this->set404();
1150
+ }
1151
+
1152
+ return false;
1153
+ }
1154
+ if(! file_put_contents($tempfile, $img)){
1155
+ $this->error("Could not write to $tempfile.");
1156
+ return false;
1157
+ }
1158
+ return true;
1159
+ }
1160
+
1161
+ }
1162
+ protected function serveImg($file){
1163
+ $s = getimagesize($file);
1164
+ if(! ($s && $s['mime'])){
1165
+ return false;
1166
+ }
1167
+ header ('Content-Type: ' . $s['mime']);
1168
+ header ('Content-Length: ' . filesize($file) );
1169
+ header ('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
1170
+ header ("Pragma: no-cache");
1171
+ $bytes = @readfile($file);
1172
+ if($bytes > 0){
1173
+ return true;
1174
+ }
1175
+ $content = @file_get_contents ($file);
1176
+ if ($content != FALSE){
1177
+ echo $content;
1178
+ return true;
1179
+ }
1180
+ return false;
1181
+
1182
+ }
1183
+ protected function set404(){
1184
+ $this->is404 = true;
1185
+ }
1186
+ protected function is404(){
1187
+ return $this->is404;
1188
+ }
1189
+ }
locker_logo.png ADDED
Binary file
readme.txt ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ === Timthumb Vulnerability Scanner ===
2
+ Contributors: peterebutler
3
+ Tags: security, scanning, timthumb, hack
4
+ Requires at least: 3.0
5
+ Tested up to: 3.2.1
6
+ Stable tag: trunk
7
+
8
+ Scans your wp-content directory for vulnerable instances of timthumb.php, and optionally upgrades them to a safe version.
9
+
10
+ == Description ==
11
+
12
+ The recent Timthumb.php vulnerability (discussed [here](http://markmaunder.com/2011/08/02/technical-details-and-scripts-of-the-wordpress-timthumb-php-hack/)) has left scores of unsuspecting bloggers hacked. It's the perfect combination of not so easy to fix for the technically disinclined, and easy to find and exploit for the malicious - resulting in a disastrous number of compromised sites.
13
+
14
+ The Timthumb Vulnerability Scanner plugin will scan your entire wp-content directory for instances of any outdated and insecure version of the timthumb script, and give you the option to automatically upgrade them with a single click. Doing so will protect you fromhackers looking to exploit this particular vulnerability.
15
+
16
+ More info at [CodeGarage](http://codegarage.com/blog/2011/09/wordpress-timthumb-vulnerability-scanner-plugin/).
17
+
18
+
19
+ == Installation ==
20
+
21
+ 1. Upload the `timthumb-vulnerability-scanner to the `/wp-content/plugins/` directory (alternatively, you could use the backend WordPress plugin installer, or install directly from the repository)
22
+ 1. Activate the plugin through the 'Plugins' menu in WordPress
23
+ 1. Visit the "Timthumb Scanner" page under the "Tools" Menu
24
+
25
+ == Frequently Asked Questions ==
26
+
27
+ = What does this look for specifically? =
28
+
29
+ The scanner checks for instances of timthumb that are older than version 2.0.
30
+
31
+ = Where does it look for them? =
32
+
33
+ The entire wp-content directory (even if it's not called wp-content) is scanned, including plugins, themes, and uploads.
34
+
35
+ = I think I've already been hacked - will this clean it up? =
36
+
37
+ No. This plugin exists to make sure your door is locked, not drag the burglers out of your house. If you've already been hacked, all is not lost - there are people out there who will clean up your site for a fee. Look one up instead of just assuming the site is a loss!
38
+
39
+
40
+ == Screenshots ==
41
+
42
+ 1. After clicking "Scan!", you'll be presented with a list of safe files found, and unsafe files found. Clicking "Fix" on any unsafe file will replace it with a safe version of timthumb.
43
+
44
+ == Changelog ==
45
+
46
+ = 1.1 =
47
+ * Updated scanner to find *really* old versions of timthumb.
48
+
49
+ = 1.0 =
50
+ * Initial Commit.
screenshot-1.png ADDED
Binary file
timthumb-vulnerability-scanner.php ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /*
3
+ Plugin Name: TimThumb Vulnerability Scanner
4
+ Plugin URI: http://codegarage.com/blog/2011/09/wordpress-timthumb-vulnerability-scanner-plugin/
5
+ Description: Find all those pesky timthumb.php scripts with vulnerabilities BEFORE you get hacked! Scans your wp-content directory for vulnerable instances of timthumb.php, and optionally upgrades them.
6
+ Author: Peter Butler
7
+ Version: 1.1
8
+ Author URI: http://codegarage.com/
9
+ */
10
+
11
+
12
+ // ==============
13
+ // = ADMIN MENU =
14
+ // ==============
15
+
16
+ add_action('admin_menu', 'cg_tvs_scanner_menu');
17
+
18
+ function cg_tvs_scanner_menu() {
19
+ add_management_page('Timthumb Scanner', 'Timthumb Scanner', 'manage_options', 'cg-timthumb-scanner', 'cg_timthumb_scanner_panel');
20
+ }
21
+
22
+ function cg_timthumb_scanner_panel() {
23
+ if (!current_user_can('manage_options')) {
24
+ wp_die( __('You do not have sufficient permissions to access this page.') );
25
+ }
26
+
27
+ if(isset($_REQUEST['cg-action'])){
28
+ switch($_REQUEST['cg-action']){
29
+ case 'scan':
30
+ include_once 'cg-tvs-filescanner.php';
31
+ $scanner = new CG_FileScanner(WP_CONTENT_DIR);
32
+ $scanner->generate_inventory();
33
+ $scanner->scan_inventory();
34
+ update_option('cg_tvs_last_checked', date("Y-m-d H:i:s"));
35
+ update_option('cg_tvs_vulnerable_files', $scanner->VulnerableFiles);
36
+ update_option('cg_tvs_safe_files', $scanner->SafeFiles);
37
+ case 'fix':
38
+ $nonce = $_GET['_wpnonce'];
39
+ if(wp_verify_nonce($nonce, 'fix_timthumb_file')){
40
+ $fix_path = urldecode($_GET['file']);
41
+ $src_file_path = trailingslashit(dirname(__FILE__)).'cg-tvs-timthumb-latest.txt';
42
+ if(FALSE !== $fr = @fopen($src_file_path, 'r')){
43
+ $latest_src = fread($fr, filesize($src_file_path));
44
+ fclose($fr);
45
+ }else{
46
+ $message = "CAN'T READ TIMTHUMB SOURCE FILE";
47
+ break;
48
+ }
49
+ if(FALSE !== $fw = @fopen($fix_path, 'w')){
50
+ if(fwrite($fw, $latest_src)){
51
+ $message = "File <strong>".basename($fix_path)."</strong> at <em>".$fix_path."</em> successfully upgraded.";
52
+ }else{
53
+ $message = "Unknown file write error.";
54
+ }
55
+ }else{
56
+ $message = "CAN'T OPEN VULNERABLE FILE FOR WRITING";
57
+ break;
58
+ }
59
+ // Re-scan site
60
+ include_once 'cg-tvs-filescanner.php';
61
+ $scanner = new CG_FileScanner(WP_CONTENT_DIR);
62
+ $scanner->generate_inventory();
63
+ $scanner->scan_inventory();
64
+ update_option('cg_tvs_last_checked', date("Y-m-d H:i:s"));
65
+ update_option('cg_tvs_vulnerable_files', $scanner->VulnerableFiles);
66
+ update_option('cg_tvs_safe_files', $scanner->SafeFiles);
67
+ }
68
+ }
69
+ }
70
+
71
+ $vulnerable_files = get_option('cg_tvs_vulnerable_files');
72
+ if(is_array($vulnerable_files) && !empty($vulnerable_files)){
73
+ $vulnerable_list_html = "<ol>\n";
74
+ foreach($vulnerable_files as $file){
75
+ $vulnerable_list_html .= "<li><a href='".wp_nonce_url("tools.php?page=cg-timthumb-scanner&cg-action=fix&file=".urlencode($file), 'fix_timthumb_file')."' class='button-secondary'>Fix</a> <span style='color:red'>".basename($file)."</span> <small>(found at $file)</small></li>\n";
76
+ }
77
+ $vulnerable_list_html .= "</ol>\n";
78
+ }else{
79
+ $vulnerable_list_html = "<span style='color:forestgreen'>No Vulnerabilities Found!</span>";
80
+ }
81
+
82
+ $safe_files = get_option('cg_tvs_safe_files');
83
+ if(is_array($safe_files) && !empty($safe_files)){
84
+ $safe_list_html = "<ol>\n";
85
+ foreach($safe_files as $file){
86
+ $safe_list_html .= "<li><span style='color:forestgreen'>".basename($file)."</span> <small>(found at $file)</small></li>\n";
87
+ }
88
+ $safe_list_html .= "</ol>\n";
89
+ }else{
90
+ $safe_list_html = "<span style='color:forestgreen'>No Up to Date Versions Found!</span>";
91
+ }
92
+ include_once 'cg-tvs-admin-panel.php';
93
+ }
94
+
95
+ // ================
96
+ // = DEACTIVATION =
97
+ // ================
98
+
99
+ register_deactivation_hook( __FILE__, 'cg_tvs_scan_deactivate' );
100
+
101
+ function cg_tvs_scan_deactivate(){
102
+ delete_option('cg_tvs_last_checked');
103
+ delete_option('cg_tvs_vulnerable_files');
104
+ delete_option('cg_tvs_safe_files');
105
+ }