-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathatd-pictator.php
executable file
·576 lines (472 loc) · 20.1 KB
/
atd-pictator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
<?php
/**
* Plugin Name: Pictator
* Plugin URI: https://github.com/airtightdesign/atd-pictator
* Description: Dynamically alter and cache images requested from the uploads directory.
* Version: 1.0.0
* Author: AirTight Design
* Author URI: http://airtightdesign.com
* License: MIT
*/
class Pictator
{
private static $upload_dir;
private static $htaccess_dst;
private static $cache_dir;
private static $sample_img_src;
private static $sample_img_dst;
private static $docs = 'https://github.com/airtightdesign/atd_pictator';
private static $htaccess_str;
private static $dirname;
// Since we dynamically detect directories (and we are NOT a real part of the wordpress ecosystem)
// these variables have to be computed at runtime. The bottom of this file invokes the init() method.
public static function init()
{
$upload_dir = wp_upload_dir();
self::$upload_dir = $upload_dir['basedir'];
self::$htaccess_dst = self::$upload_dir . '/.htaccess';
self::$cache_dir = dirname(__FILE__) . '/cache';
self::$sample_img_src = dirname(__FILE__) . '/assets/pictator.jpg';
self::$sample_img_dst = self::$upload_dir . '/pictator.jpg';
self::$dirname = basename(dirname(__FILE__));
self::$htaccess_str = "# place this file in wp-content/uploads as '.htaccess'\n" .
"# mod rewrite MUST be enabled for this to work!\n" .
"<IfModule mod_rewrite.c>\n" .
"\tRewriteEngine On\n\n" .
"\t# must have an image extension\n" .
"\tRewriteCond %{REQUEST_URI} \.(gif|jpg|jpeg|png)$\n\n" .
"\t# cannot be a directory\n" .
"\tRewriteCond %{REQUEST_FILENAME} !-d\n\n" .
"\t# must be an existing file\n" .
"\tRewriteCond %{REQUEST_FILENAME} -f\n\n" .
"\tRewriteRule ^(.*)$ {path} [QSA,L]\n\n" .
"</IfModule>";
}
// returns link to the documentation / README
private static function docs_link()
{
return sprintf(
'<a href="%s" target="_blank">View installation instructions.</a>',
self::$docs
);
}
// creates .htaccess file in the uploads directory
public static function plugin_activated()
{
if (version_compare('5.3.0', PHP_VERSION) >= 0) {
self::error("Plugin requires PHP version 5.3.0 or greater.");
}
// attempt to create .htaccess file in uploads directory
if (!self::create_upload_dir()) {
self::error("Unable to create uploads directory.");
}
// attempt to create .htaccess file in uploads directory
if (!self::create_htaccess()) {
self::error("Unable to create .htaccess file. <br>" . self::docs_link());
}
// attempt to create cache directory
if (!self::create_cache_dir()) {
self::destroy_htaccess();
self::error("Unable to create image cache directory.");
}
// attempt to copy lena.jpg to uploads directory as pictator.jpg
if (!self::create_sample_image()) {
self::destroy_htaccess();
self::destroy_cache_dir();
self::error("Unable to create sample image.");
}
}
// deletes .htaccess from the uploads directory
public static function plugin_deactivated()
{
// attempt to destroy the sample image file from uploads directory
if (!self::destroy_sample_image()) {
self::error("Unable to remove sample image file from uploads.");
}
// attempt to destroy the cache directory
if (!self::destroy_cache_dir()) {
self::error("Unable to remove image cache directory.");
}
// attempt to destroy .htaccess file from uploads directory
if (!self::destroy_htaccess()) {
self::error("Unable to remove .htaccess file.");
}
}
// creates an .htaccess file in the uploads directory
private static function create_upload_dir()
{
$success = false;
$upload_dir = self::$upload_dir;
// attempt to create directory
if (!is_dir($upload_dir)) {
mkdir($upload_dir);
}
// set permissions on the directory
if (is_dir($upload_dir)) {
@chmod($upload_dir, 0775);
}
if(is_dir($upload_dir) && is_writable($upload_dir)) {
$success = true;
}
return $success;
}
// creates an .htaccess file in the uploads directory
private static function create_htaccess()
{
$success = false;
$path = '/wp-content/plugins/' . self::$dirname . '/index.php';
$contents = str_replace('{path}', $path, self::$htaccess_str);
$dst = self::$htaccess_dst;
// only copy it if it doesn't already exist
if (!file_exists($dst)) {
file_put_contents($dst, $contents);
}
// if the file exists, we make sure it matches the source file
if(file_exists($dst) && $contents == file_get_contents($dst)) {
$success = true;
}
return $success;
}
// deletes .htaccess from the uploads directory
private static function destroy_htaccess()
{
$dst = self::$htaccess_dst;
// if the file exists, we make sure it matches the source file before deleting it
if (file_exists($dst)) {
self::unlink($dst);
}
return !file_exists($dst);
}
// creates the directory where images will be cached
private static function create_cache_dir()
{
$success = false;
$cache_dir = self::$cache_dir;
// attempt to create directory
if (!is_dir($cache_dir)) {
mkdir($cache_dir);
}
// set permissions on the directory
if (is_dir($cache_dir)) {
@chmod($cache_dir, 0775);
}
if(is_dir($cache_dir) && is_writable($cache_dir)) {
$success = true;
}
return $success;
}
private static function destroy_cache_dir()
{
$cache_dir = self::$cache_dir;
if(file_exists($cache_dir)) {
self::unlink($cache_dir);
}
return !file_exists($cache_dir);
}
// copies a test image to the uploads directory
private static function create_sample_image()
{
$src = self::$sample_img_src;
$dst = self::$sample_img_dst;
// only copy it if it doesn't already exist
if (!file_exists($dst)) {
@copy($src, $dst);
}
// if the file exists, we dangerously assume its correct
return file_exists($dst);
}
// deletes the sample image from the uploads dir
private static function destroy_sample_image()
{
$dst = self::$sample_img_dst;
self::unlink($dst);
return !file_exists($dst);
}
// removes height and width attributes from images inserted into wordpress content already
public static function remove_image_attributes($html) {
$html = preg_replace( '/(width|height)="\d*"\s/', "", $html );
return $html;
}
// clears the cache directory
public static function clear_cache_dir()
{
self::unlink(self::$cache_dir . "/*");
}
// add an admin menu item for the plugin
public static function pictator_menu()
{
add_options_page( 'Pictator Settings', 'Pictator', 'manage_options', 'pictator-settings', array('Pictator', 'pictator_settings') );
}
// settings page, allows for debug enable/disable & cache clearing operations
// also shows sample image file transformations
public static function pictator_settings()
{
if ( !current_user_can( 'manage_options' ) ) {
wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
}
$cache_size = self::dirsize(self::$cache_dir);
$cache_file_count = self::count_files(self::$cache_dir);
?>
<style>
figure {
display: inline-block;
padding: 10px;
margin: 0 8px 8px 0;
text-align: center;
background: #fff;
border-radius: 3px;
border: 1px solid #ccc;
vertical-align: top;
}
figcaption {
word-break: break-all;
}
@supports (display: flex) {
.row {
display: flex;
justify-content: space-between;
}
.block {
width: 49%;
background: #fff;
border-radius: 3px;
border: 1px solid #ccc;
padding: 10px 20px;
margin-bottom: 12px;
box-sizing: border-box;
}
.block-full {
width: 100%;
}
}
</style>
<div class="wrap">
<h2>Pictator Settings</h2>
<?php if (!file_exists(self::$htaccess_dst)) : ?>
<div class="notice notice-error">
<p>The .htaccess file does not exist in <?php echo self::$htaccess_dst; ?>.</p>
</div>
<?php endif; ?>
<?php if (!file_exists(self::$cache_dir)) : ?>
<div class="notice notice-error">
<p>The cache directory at <?php echo self::$cache_dir; ?> does not exist.</p>
</div>
<?php elseif (!is_writable(self::$cache_dir)) : ?>
<div class="notice notice-error">
<p>The cache directory at <?php echo self::$cache_dir; ?> is not writable.</p>
</div>
<?php endif; ?>
<div class="row">
<div class="block block-full">
<h3>Usage</h3>
<p><a href="https://github.com/airtightdesign/pictator#readme" target="_blank">Usage Guide</a></p>
<p>Pictator allows you to use arbitrarily sized images in your css and templates by appending some query parameters to the image source url.</p>
Available Parameters
<pre>
a - the 'action' to perform (resize|crop - defaults to 'resize')
r - the type of resize (contain|widen|heighten|cover)
w - the width
h - the height
x - the x offset
y - the y offset
</pre>
<p><a href="#example-images">Example Images</a></p>
</div>
</div>
<div class="row">
<div class="block">
<h3>Cache Statistics</h3>
<p>
<strong>Total # cache files:</strong>
<span><?php echo $cache_file_count; ?></span>
</p>
<p>
<strong>Total cache filesize:</strong>
<span><?php echo ($cache_size / 1000000); ?> MB</span>
</p>
</div>
<div class="block">
<h3>Clear Cache</h3>
<p>Clears pre-sized image cache. Images will be recreated upon intitial request.</p>
<form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="post">
<input type="hidden" name="action" value="pictator_clear_cache">
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Clear Cache') ?>" />
</p>
</form>
</div>
</div>
<div class="row">
<div class="block">
<h3>Image Processing Method</h3>
<form action="options.php" method="post">
<?php settings_fields('atd-pictator'); ?>
<?php do_settings_sections('atd-pictator'); ?>
<p>Please select a PHP image processing extension to be used when generating new images. (Defaults to GD)</p>
<?php if (extension_loaded('gd')): ?>
<p>
<input type="radio" name="image_library" id="image-method-gd" value="gd" <?php if (get_option('image_library') == 'gd' || get_option('image_library') == '') { echo "checked"; } ?> />
<label for="image-method-gd">GD</label>
</p>
<?php else: ?>
<p>
The PHP GD extension is not currently available.
</p>
<?php endif; ?>
<?php if (extension_loaded('imagick')): ?>
<p>
<input type="radio" name="image_library" id="image-method-imagemagick" value="imagick" <?php if (get_option('image_library') == 'imagick') { echo "checked"; } ?> />
<label for="image-method-imagemagick">ImageMagick (Preferred)</label>
</p>
<?php else: ?>
<p>
The PHP Imagick extension is not currently available.
</p>
<?php endif; ?>
<?php submit_button(); ?>
</form>
</div>
<div class="block">
<h3>Debug Output</h3>
<p>Displays image information in a text overlay on top of the image. This overlay is added to images while a user is logged in to WordPress.</p>
<?php if (get_option('atd_pictator_debug')) : ?>
<form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="post">
<input type="hidden" name="action" value="pictator_disable_debug">
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Disable Debug') ?>" />
</p>
</form>
<?php else: ?>
<form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="post">
<input type="hidden" name="action" value="pictator_enable_debug">
<p class="submit">
<input type="submit" class="button-primary" value="<?php _e('Enable Debug') ?>" />
</p>
</form>
<?php endif; ?>
</div>
</div>
<h3 id="example-images">Example Images</h3>
<div class="cleafix">
<figure>
<img style="vertical-align: top; margin-bottom: 8px" src="/wp-content/uploads/pictator.jpg">
<figcaption>pictator.jpg</figcaption>
</figure>
<figure>
<img style="vertical-align: top; margin-bottom: 8px" src="/wp-content/uploads/pictator.jpg?r=cover&w=200&h=200">
<figcaption>pictator.jpg?r=cover&w=200&h=200</figcaption>
</figure>
<figure>
<img style="vertical-align: top; margin-bottom: 8px" src="/wp-content/uploads/pictator.jpg?w=300&r=widen">
<figcaption>pictator.jpg?w=300&r=widen</figcaption>
</figure>
<figure>
<img style="vertical-align: top; margin-bottom: 8px" src="/wp-content/uploads/pictator.jpg?a=crop&w=200&h=200&x=15&y=50">
<figcaption>pictator.jpg?a=crop&w=200&h=200&x=15&y=50</figcaption>
</figure>
</div>
</div>
<?php
}
// filter function to add 'Settings' link to plugin page
public static function pictator_settings_link($links)
{
$settings_link = '<a href="options-general.php?page=pictator-settings">' . __( 'Settings' ) . '</a>';
array_push( $links, $settings_link );
return $links;
}
// callback for admin-posts.php, clears cache directory
public static function pictator_clear_cache()
{
self::clear_cache_dir();
status_header(200);
wp_redirect(wp_get_referer());
exit;
}
// callback for admin-posts.php, disables debug mode
public static function pictator_disable_debug()
{
update_option('atd_pictator_debug', false);
status_header(200);
wp_redirect(wp_get_referer());
exit;
}
// callback for admin-posts.php, enables debug mode
public static function pictator_enable_debug()
{
update_option('atd_pictator_debug', true);
self::clear_cache_dir();
status_header(200);
wp_redirect(wp_get_referer());
exit;
}
// recursively computes the filesize of a directory by summing the filesizes of its contents recursively
public static function dirsize($path)
{
$bytestotal = 0;
$path = realpath($path);
if ($path !== false) {
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object){
$bytestotal += $object->getSize();
}
}
return $bytestotal;
}
// recursively returns the number of files contained in a directory recursively.
public static function count_files($dir)
{
$size = 0;
foreach(scandir($dir) as $file) {
if (!in_array($file, array('.','..'))) {
if (is_dir(rtrim($dir, '/') . '/' . $file)) {
$size += self::count_files(rtrim($dir, '/') . '/' . $file);
} else {
$size++;
}
}
}
return $size;
}
// re-implementation of the php unlink function, but instead of taking a filename as
// the input, it takes a pattern that will be passed to the glob() function
// This implementation deletes recursively, so USE WITH CAUTION!
public static function unlink($pattern = "*")
{
foreach (glob($pattern) as $file) {
if (is_dir($file)) {
self::unlink($file . "/*");
rmdir($file);
} else {
unlink($file);
}
}
}
public static function error($str)
{
$styling = "color: #444;font-family: -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen-Sans,Ubuntu,Cantarell,'Helvetica Neue',sans-serif;font-size: 13px;";
$output = '<div class="error notice" style="' . $styling . '">';
$output .= '<p>' . $str . '</p>';
$output .= '</div>';
echo $output;
die();
}
}
function register_settings()
{
register_setting('atd-pictator','image_library');
// die('register settings');
}
// this call initializes the path variables
Pictator::init();
register_activation_hook( __FILE__, array('Pictator', 'plugin_activated' ));
register_deactivation_hook( __FILE__, array('Pictator', 'plugin_deactivated' ));
if (is_admin()) {
add_action( 'admin_menu', array('Pictator', 'pictator_menu') );
add_action( 'admin_post_pictator_clear_cache', array('Pictator', 'pictator_clear_cache' ));
add_action( 'admin_post_pictator_disable_debug', array('Pictator', 'pictator_disable_debug' ));
add_action( 'admin_post_pictator_enable_debug', array('Pictator', 'pictator_enable_debug' ));
add_filter( 'post_thumbnail_html', array('Pictator', 'remove_image_attributes'), 10 );
add_filter( 'image_send_to_editor', array('Pictator', 'remove_image_attributes'), 10 );
add_filter( 'plugin_action_links_' . plugin_basename(__FILE__), array('Pictator', 'pictator_settings_link'), 10 );
add_action( 'admin_init', 'register_settings');
}