forked from tychay/one-click-child-theme
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathone-click-child-theme.php
686 lines (656 loc) · 21.9 KB
/
one-click-child-theme.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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
<?php
/*
**************************************************************************
Plugin Name: One-Click Child Theme
Plugin URI: http://terrychay.com/wordpress-plugins/one-click-child-theme
Version: 1.6
Description: Easily child theme any theme from wp-admin wp-admin without going into shell or using FTP.
Author: tychay
Author URI: http://terrychay.com/
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: one-click-child-theme
Domain Path: /languages
**************************************************************************/
/* Copyright 2011-2015 terry chay (email : [email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* Performance: One-Click Child Theme is only active in admin page
*/
if (!is_admin()) { return; }
/**
* Load textdomain
*/
function _load_textdomain() {
load_plugin_textdomain( 'one-click-child-theme', false, basename(dirname(__FILE__)) . '/languages' );
}
add_action( 'init', '_load_textdomain' );
/**
* The namespace for the One-Click Child Theme Plugin
*/
class OneClickChildTheme {
/**
* @const string Used for id generation and language text domain.
*/
const _SLUG = 'one-click-child-theme';
/**
* Used for loading in files
* @var string
*/
private $_pluginDir = '';
/**
* This plugin's theme page
*/
private $_themePageUrl = '';
/**
* Theme page name (menu slug)
* @var string
*/
private $_menuId = '';
/**
* action for Create Child form
*/
private $_createChildFormId = '';
/**
* action for Repair Child form
*/
private $_repairChildFormId = '';
/**
* action for Copy Template form
*/
private $_copyTemplateFormId = '';
/**
* action for screenshot generation
*/
private $_mshotSiteFormId = '';
public function __construct() {
$this->_pluginDir = dirname(__FILE__);
$this->_menuId = self::_SLUG . '-page';
$this->_themePageUrl = admin_url('themes.php?page='.$this->_menuId);
$this->_createChildFormId = self::_SLUG.'-create-child';
$this->_repairChildFormId = self::_SLUG.'-repair-child';
$this->_copyTemplateFormId = self::_SLUG.'-copy-template';
$this->_mshotSiteFormId = self::_SLUG.'-mshot-site';
// it has to be buried like this or you get an error:
// "You do not have sufficient permissions to access this page"
add_action( 'admin_menu', array($this,'createAdminMenu') );
// form handling code
add_action( 'admin_post_'.$this->_createChildFormId, array($this,'processCreateForm') );
add_action( 'admin_post_'.$this->_repairChildFormId, array($this,'processRepairChildForm') );
add_action( 'admin_post_'.$this->_copyTemplateFormId, array($this,'processCopyTemplateForm') );
add_action( 'admin_post_'.$this->_mshotSiteFormId, array($this,'processMShotSiteForm') );
// TODO: I could also use the $pagenow global, but is it still there?
if ( basename($_SERVER['PHP_SELF']) == 'themes.php' && !empty($_REQUEST['occt_error']) ) {
add_action( 'admin_notices', array($this,'showErrorNotice'));
}
}
/**
* Handle error and update notices for this theme
*
* There are now four types of notices: success (green), warning (orange), error (red),
* and info (blue).
*
* Put here because there is a redirect between all forms and error notifications and
* add_settings_error() only covers options API errors.
*/
public function showErrorNotice()
{
switch ($_GET['occt_error']) {
case 'child_created': //SUCCESS: child theme created
$type = 'updated'; //fade?
$msg = sprintf(
__('Theme switched! <a href="%s">Click here to edit the child stylesheet</a>.', self::_SLUG),
add_query_arg(
urlencode_deep(array(
'file' => 'style.css',
'theme' => get_stylesheet(),
)),
admin_url('theme-editor.php')
)
);
break;
case 'create_failed': //ERROR: create file failed (probably due to permissions)
$type = 'error';
$msg = sprintf(
__('Failed to create file: %s', self::_SLUG),
esc_html($_GET['filename'])
);
break;
case 'edit_failed': //ERROR: edit file failed (probably do to permissions)
$type = 'error';
$msg = sprintf(
__('Failed to edit file: %s', self::_SLUG),
esc_html($_GET['filename'])
);
break;
case 'repair_success': //SUCCESS: repaired child theme
$type = 'updated fade';
$msg = __('Repaired child theme.', self::_SLUG);
break;
case 'no_template': //ERROR: template file not specified
$type = 'error';
$msg = __('No template file specified.', self::_SLUG);
case 'missing_template': //ERROR: parent theme doesn't have template
$type = 'error';
$msg = sprintf(
__('Template file %s does not exist in parent theme!', self::_SLUG),
esc_html($_GET['filename'])
);
break;
case 'already_template': //ERROR: child theme already has template
$type = 'error';
$msg = sprintf(
__('Template file %s already exists in child theme!', self::_SLUG),
esc_html($_GET['filename'])
);
break;
case 'copy_failed': //ERROR: couldn't duplicate file for some reason
$type = 'error';
$msg = sprintf(
__('Failed to duplicate file %s!', self::_SLUG),
esc_html($_GET['filename'])
);
break;
case 'copy_success': //SUCCESS: template file created
$type = 'updated'; //fade?
$msg = sprintf(
__('<a href="%s">File %s created!</a>', self::_SLUG),
add_query_arg(
urlencode_deep(array(
'file' => $_GET['filename'],
'theme' => get_stylesheet(),
)),
admin_url('theme-editor.php')
),
esc_html($_GET['filename'])
);
break;
case 'delete_failed': //ERROR: couldn't delete file for some reason
$type = 'error';
$msg = sprintf(
__('Failed to delete file %s!', self::_SLUG),
esc_html($_GET['filename'])
);
break;
case 'mshot_404': //ERROR: couldn't find mshot
$type = 'error';
$msg = sprintf(
__('404 File not found at %s!', self::_SLUG),
esc_html($_GET['url'])
);
break;
case 'mshot_mime_wrong': //ERROR: couldn't find mshot
$type = 'error';
$msg = sprintf(
__('Unrecognized mimetype at %s!', self::_SLUG),
esc_html($_GET['url'])
);
break;
case 'mshot_nocreate': //ERROR: couldn't find mshot
$type = 'error';
$msg = sprintf(
__('Failed to create file %s!', self::_SLUG),
esc_html($_GET['filename'])
);
break;
case 'mshot_success': //SUCCESS: screenshot generated
$type = 'updated fade'; //fade?
$msg = __('Successfully changed screenshot.', self::_SLUG);
break;
default: //ERROR: it is a generic error message
$type = 'error';
$msg = esc_html($_GET['occt_error']);
}
printf(
'<div class="%s"><p>%s</p></div>',
$type,
$msg
);
}
/**
* Adds an admin menu for One Click Child Theme in Appearances
*/
public function createAdminMenu() {
add_theme_page(
__('Make a Child Theme', self::_SLUG), //page title
__('Child Theme', self::_SLUG), //menu title
'install_themes', //capability needed to view
$this->_menuId, //menu slug (and page query url)
array( $this, 'showThemePage' ) //callback function
);
}
//
// SHOW THEME PAGE
//
/**
* Show the theme page which has a form allowing you to child theme
* currently selected theme.
*
*/
public function showThemePage()
{
// Form is processed in the admin_post_* hooks
// Handle case where current theme is already a child
if ( is_child_theme() ) {
$this->_showFormAlreadyChild( $this->_child_theme_needs_repair() );
return;
}
// Default behavior: We are not a child theme, but interested in creating one.
// Grab default values from a form fail
$theme_name = ( !empty($_GET['theme_name']) ) ? $_GET['theme_name'] : '';
$description = ( !empty($_GET['description']) ) ? $_GET['description'] : '';
if ( !empty($_GET['author_name']) ) {
$author = $_GET['author_name'];
} else {
global $current_user;
get_currentuserinfo();
$author = $current_user->display_name;
}
// render default behaivor
require $this->_pluginDir.'/templates/create_child_form.php';
}
/**
* Show the "is child already" template.
* @param boolean $child_needs_repair whether or not child theme needs repair
* @todo handle grandchildren
*/
private function _showFormAlreadyChild($child_needs_repair) {
// set template parameters
$current_theme = wp_get_theme();
$child_theme_screenshot_url = ( $screenshot_filename = $this->_scanForScreenshot( get_stylesheet_directory() ) )
? get_stylesheet_directory_uri().'/'.$screenshot_filename
: '';
$mshot_url = $this->_mshotUrl();
// Search for template files.
// Note: since there can be files like {mimetype}.php, we must assume
// that any root level .php files in the template directory are
// templates.
$template_files = glob ( get_template_directory().'/*.php' );
foreach ( $template_files as $index=>$file ) {
$template_files[$index] = basename( $file );
}
// Filter out any files in child already created
$child_theme_dir = get_stylesheet_directory();
foreach ( $template_files as $index=>$filename ) {
if ( file_exists($child_theme_dir.'/'.$filename) ) {
unset($template_files[$index]);
}
}
require $this->_pluginDir.'/templates/is_child_already.php';
}
//
// FORM HANDLING
//
/**
* Handle the create child form.
*/
public function processCreateForm() {
check_admin_referer( $this->_createChildFormId . '-verify' );
$theme_name = $_POST['theme_name'];
$description = ( empty($_POST['description']) )
? ''
: $_POST['description'];
$author_name = ( empty($_POST['author_name']) )
? ''
: $_POST['author_name'];
$result = $this->_make_child_theme( $theme_name, $description, $author_name );
if ( is_wp_error( $result ) ) {
// should show create child form again
$this->_redirect(
$this->_themePageUrl,
$result->get_error_message(),
array(
'theme_name' => $theme_name,
'description' => $description,
'author_name' => $author_name,
)
);
return;
} else {
switch_theme( $result['parent_template'], $result['new_theme'] );
// Redirect to themes page on success
$this->_redirect(
admin_url('themes.php'),
'child_created'
);
}
}
/**
* Handle the repair_child_form form.
*/
public function processRepairChildForm()
{
check_admin_referer( $this->_repairChildFormId . '-verify' );
$child_theme_dir = get_stylesheet_directory();
$functions_file = $child_theme_dir.'/functions.php';
$style_file = $child_theme_dir.'/style.css';
// create functions.php if it doesn't exist yet
if ( !file_exists($functions_file) ) {
if ( !touch($functions_file) ) {
// fixing is hopeless if we can't create the file :-(
$this->_redirect(
$this->_themePageUrl,
'create_failed',
array( 'filename' => $functions_file )
);
return;
}
}
// read in style.css
$style_text = file_get_contents( $style_file );
// prune out old rules
$style_text = preg_replace(
'!@import\s+url\(\s?["\']\.\./.*/style.css["\']\s?\);!ims',
'',
$style_text
);
$style_text = preg_replace(
'!@import\s+url\(\s?["\']'.get_template_directory_uri().'/style.css["\']\s?\);!ims',
'',
$style_text
);
if ( file_put_contents( $style_file, $style_text) === false ) {
$this->_redirect(
$this->_themePageUrl,
'edit_failed',
array( 'filename' => $style_file )
);
return;
}
// modify functions.php to prepend new rules
$functions_text = file_get_contents( $this->_pluginDir.'/templates/functions.php' );
// ^^^ above file has no final carriage return and ending comment so it should
// "smash" the starting '<?php' string in any existing functions.php.
$functions_text .= file_get_contents( $functions_file );
if ( file_put_contents( $functions_file, $functions_text ) === false ) {
$this->_redirect(
$this->_themePageUrl,
'edit_failed',
array( 'filename' => $functions_file )
);
return;
}
$this->_redirect(
$this->_themePageUrl,
'repair_success'
);
}
/**
* Handle the Copy Template form.
*/
public function processCopyTemplateForm() {
check_admin_referer( $this->_copyTemplateFormId . '-verify' );
$filename = ( empty($_POST['filename']) )
? ''
: $_POST['filename'];
if ( !$filename ) {
$this->_redirect(
$this->_themePageUrl,
'no_template'
);
return;
}
$child_theme_dir = get_stylesheet_directory();
$template_dir = get_template_directory();
var_dump('bar');
if ( !file_exists($template_dir.'/'.$filename) ) {
$this->_redirect(
$this->_themePageUrl,
'missing_template',
array( 'filename' => $filename )
);
return;
}
if ( file_exists($child_theme_dir.'/'.$filename) ) {
$this->_redirect(
$this->_themePageUrl,
'already_template',
array( 'filename' => $filename )
);
return;
}
if ( !copy( $template_dir.'/'.$filename, $child_theme_dir.'/'.$filename ) ) {
$this->_redirect(
$this->_themePageUrl,
'copy_failed',
array( 'filename' => $filename )
);
}
$this->_redirect(
$this->_themePageUrl,
'copy_success',
array( 'filename' => $filename )
);
}
/**
* Handle the mshot Screenshot form
*/
public function processMShotSiteForm()
{
check_admin_referer( $this->_mshotSiteFormId . '-verify' );
// delete existing screenshot if it exists
$child_theme_dir = get_stylesheet_directory();
if ( $screenshot_filename = $this->_scanForScreenshot($child_theme_dir) ) {
$screenshot_path = $child_theme_dir.'/'.$screenshot_filename;
if ( !unlink($screenshot_path) ) {
// most likely a directory problem Fail with an error
$this->_redirect(
$this->_themePageUrl,
'delete_failed',
array( 'filename' => $screenshot_path )
);
return;
}
}
$mshot_url = $this->_mshotUrl();
// Get the mshot
$response = wp_remote_get($mshot_url);
if ( $response['code'] == 404 ) {
// The 404 image is gorgeous nowadays, but (if wp.com correctly handled error
// codes for image generation) we'd not let them use it as a theme screenshot.
$this->_redirect(
$this->_themePageUrl,
'mshot_404',
array( 'url' => $mshot_url )
);
}
// Should be 'image/jpeg', but let's hedge our bets
switch ($response['headers']['content-type']) {
case 'image/jpeg':
$screenshot_filename = 'screenshot.jpg';
break;
case 'image/png':
$screenshot_filename = 'screenshot.png';
break;
case 'image/gif':
$screenshot_filename = 'screenshot.gif';
break;
default:
$this->_redirect(
$this->_themePageUrl,
'mshot_mime_wrong',
array( 'url' => $mshot_url )
);
return;
}
$screenshot_path = $child_theme_dir.'/'.$screenshot_filename;
if ( file_put_contents($screenshot_path, $response['body']) === false ) {
$this->_redirect(
$this->_themePageUrl,
'mshot_nocreate',
array( 'filename' => $screenshot_path )
);
return;
}
$this->_redirect(
$this->_themePageUrl,
'mshot_success'
);
}
//
// PRIVATE METHOD
//
/**
* Does the work to make a child theme based on the current theme.
*
* This currently supports the following files:
*
* 1. style.css: Follows the rules outlined in {@link http://codex.wordpress.org/Child_Themes the Codex}
* 2. functions.php: Followed the updated rules outlined in the Codex. Note
* that since WordPress ?.? functions.php hierarchy is automatically
* included.
* 3. rtl.css: right to left language support, if not avaialble in parent, it
* uses TwentyFifteen's rtl
* 4. screenshot.png: screenshot if available in the parent
*
* @author terry chay <[email protected]>
* @author Chris Robinson <http://contempographicdesign.com/> (for screenshot support).
* @return array|WP_Error If successful, it returns a hash contianing
* - new_theme: (directory) name of new theme
* - parent_template: (directory) name of parent template
* - parent_theme: (directory) name of parent theme
* - new_theme_path: full path to the directory cotnaining the new theme
* - new_theme_title: the name of the new theme
*/
private function _make_child_theme( $new_theme_title, $new_theme_description, $new_theme_author ) {
$parent_theme_title = get_current_theme();
$parent_theme_template = get_template(); //Doesn't play nice with the grandkids
$parent_theme_name = get_stylesheet();
$parent_theme_dir = get_stylesheet_directory();
// Turn a theme name into a directory name
$new_theme_name = sanitize_title( $new_theme_title );
$theme_root = get_theme_root();
// Validate theme name
$new_theme_path = $theme_root.'/'.$new_theme_name;
if ( file_exists( $new_theme_path ) ) {
return new WP_Error( 'exists', __( 'Theme directory already exists!', self::_SLUG ) );
}
mkdir( $new_theme_path );
// Make style.css
ob_start();
require $this->_pluginDir.'/templates/child-theme-css.php';
$css = ob_get_clean();
file_put_contents( $new_theme_path.'/style.css', $css );
// "Generate" functions.php
copy( $this->_pluginDir.'/templates/functions.php', $new_theme_path.'/functions.php' );
// RTL support
$rtl_theme = ( file_exists( $parent_theme_dir.'/rtl.css' ) )
? $parent_theme_name
: 'twentyfifteen'; //use the latest default theme rtl file
ob_start();
require $this->_pluginDir.'/templates/rtl-css.php';
$css = ob_get_clean();
file_put_contents( $new_theme_path.'/rtl.css', $css );
// Copy screenshot
if ( $screenshot_filename = $this->_scanForScreenshot( $parent_theme_dir ) ) {
copy(
$parent_theme_dir.'/'.$screenshot_filename,
$new_theme_path.'/'.$screenshot_filename
);
} // removed grandfather screenshot check (use mshot instead, rly)
// Make child theme an allowed theme (network enable theme)
$allowed_themes = get_site_option( 'allowedthemes' );
$allowed_themes[ $new_theme_name ] = true;
update_site_option( 'allowedthemes', $allowed_themes );
return array(
'parent_template' => $parent_theme_template,
'parent_theme' => $parent_theme_name,
'new_theme' => $new_theme_name,
'new_theme_path' => $new_theme_path,
'new_theme_title' => $new_theme_title,
);
}
//
// PRIVATE UTILITY FUNCTIONS
//
/**
* Detect if child theme needs repair.
*
* A child theme needs repair if it is missing a functions.php or the
* style.css still has a rule that points to the parent.
*/
private function _child_theme_needs_repair()
{
$child_theme_dir = get_stylesheet_directory();
if ( !file_exists($child_theme_dir.'/functions.php') ) {
return true;
}
$style_text = file_get_contents( $child_theme_dir.'/style.css' );
// look for relative match (dificult to extract parent theme directory
// so I'll assume any in this path is parent theme)
if ( preg_match(
'!@import\s+url\(\s?["\']\.\./.*/style.css["\']\s?\);!ims',
$style_text
) ) {
return true;
}
// look for absolute match
if ( preg_match(
'!@import\s+url\(\s?["\']'.get_template_directory_uri().'/style.css["\']\s?\);!ims',
$style_text
) ) {
return true;
}
return false;
}
/**
* Handle error redirects (for admin_notices generated by plugin)
*
* Note add_query_arg() is written like shit. Here are it's problems:
*
* 1. doesn't take advantage of built-in parse_url()
* 2. uses urlencode_deep() instead of an array_merge and built-in http_build_query()
* 3. doesn't urlencode() if $arg[0] is an array.
*
* The 3rd one is extremely non-intuitive, but fixing it, would break backward
* compatibility due to double-escaping. I'm hacking around that. :-(
*
* @param string $url The (base) url to redirect to, usually admin_url()
* @param string $error the error code to use
* @param string $args other arguments to add to the query string
* @return null
*/
private function _redirect($url, $error, $args = array()) {
$args['occt_error'] = $error;
$args = urlencode_deep($args);
wp_redirect( add_query_arg( $args, $url ) );
}
/**
* Searches directory for a theme screenshot
*
* @param string $directory directory to search (a theme directory)
* @return string|false 'screenshot.png' (or whatever) or false if there is no screenshot
*/
private function _scanForScreenshot($directory)
{
$screenshots = glob( $directory.'/screenshot.{png,jpg,jpeg,gif}', GLOB_BRACE );
return (empty($screenshots))
? false
: basename($screenshots[0]);
}
/**
* Generate mshot of wordpress homepage.
*
* Recommende image dimensions from https://codex.wordpress.org/Theme_Development#Screenshot
* @todo probably won't work correctly in multisite installs
* @todo remove debugging code
*/
private function _mshotUrl()
{
$scheme = (is_ssl()) ? 'https' : 'http';
return $scheme . '://s.wordpress.com/mshots/v1/'. urlencode(get_site_url()) . '?w=880&h=660';
}
}
new OneClickChildTheme();
// Start this plugin
//add_action( 'admin_init', array('OneClickChildTheme','init'), 12 );