This repository has been archived by the owner on Sep 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathheadjs-loader.php
435 lines (386 loc) · 16.3 KB
/
headjs-loader.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
<?php
/**
Plugin Name: Head JS Loader
Plugin URI: http://wordpress.org/extend/plugins/headjs-loader/
Description: A plugin to load <a href="http://headjs.com" target="_BLANK">Head JS</a> in Wordpress.
Version: 0.3
Author: ChuckMac
Author URI: https://www.chuckmac.info
Text Domain: headjs-loader
*/
/**
* @license http://www.gnu.org/licenses/gpl.html GNU General Public License
*/
if (!class_exists('headJS_loader')) {
/*
* headJS_loader is the class that handles ALL of the plugin functionality.
* It helps us avoid name collisions
* http://codex.wordpress.org/Writing_a_Plugin#Avoiding_Function_Name_Collisions
* @package headJS_loader
*/
class headJS_loader {
var $pluginName = 'headJS_loader';
var $headJSVersion = '1.03';
var $scriptsUsed = array();
var $stylesUsed = array();
var $adminOptions = array();
var $ignoreScripts = array();
var $ignoreStyles = array();
/**
* Initializes the plugin
*/
function headJS_loader() {
add_action('init', array($this,'headJS_init'));
}
/*
* Sets up all actions and hooks necessary.
*/
function headJS_init() {
/* Grab our setup vars to use throughout */
$this->adminOptions = $this->headjs_admin_options();
/* No need to run on admin / rss / xmlrpc */
if (!is_admin() && !is_feed() && !defined('XMLRPC_REQUEST')) {
/* Setup our array of scripts to ignore */
$this->adminOptions['headjs_ignore'] = str_replace("\r\n","\n", $this->adminOptions['headjs_ignore']);
$this->ignoreScripts = explode("\n", $this->adminOptions['headjs_ignore']);
/* Setup our array of styles to ignore */
$this->adminOptions['headjs_css_ignore'] = str_replace("\r\n","\n", $this->adminOptions['headjs_css_ignore']);
$this->ignoreStyles = explode("\n", $this->adminOptions['headjs_css_ignore']);
/* Add the rest of our actions to filter the frontend */
add_action('init', array($this, 'headjs_pre_content'), 99998);
add_action('wp_print_scripts', array($this, 'headjs_inspect_scripts'));
add_action('wp_print_styles', array($this, 'headjs_inspect_styles'));
add_action('wp_footer', array($this, 'headjs_post_content'));
}
/* Load the admin menu */
elseif (is_admin()) {
add_action('admin_menu', array($this,'headjs_admin'));
add_filter('plugin_action_links', array($this, 'headjs_admin_link_plugin_settings'), 10, 2);
}
}
/**
* Check what scripts are enqueued properly, grab the source, then deenqueue it
*/
function headjs_inspect_scripts() {
global $wp_scripts;
if(!empty($wp_scripts)) {
$scripts = $wp_scripts->queue;
$wp_scripts->all_deps( $scripts );
$headjs_queue = $wp_scripts->to_do;
foreach( $headjs_queue as $handle ) {
/* check if script should be ignored */
if(!in_array( $wp_scripts->registered[$handle]->src, $this->ignoreScripts )) {
$this->scriptsUsed[$handle] = $wp_scripts->registered[$handle]->src;
wp_deregister_script($handle);
wp_dequeue_script($handle);
}
}
}
}
/**
* Check what styles are enqueued properly, grab the source, then deenqueue it
*/
function headjs_inspect_styles() {
global $wp_styles;
if(!empty($wp_styles)) {
$wp_styles->all_deps( $wp_styles->queue );
foreach($wp_styles->to_do as $handle){
/* check if script should be ignored */
if(!in_array( $wp_styles->registered[$handle]->src, $this->ignoreStyles )) {
$this->stylesUsed[$handle] = $wp_styles->registered[$handle]->src;
wp_deregister_style($handle);
wp_dequeue_style($handle);
}
}
}
}
/**
* Buffer the output so we can play with it.
*/
function headjs_pre_content() {
ob_start(array($this, 'headjs_modify_buffer'));
/* Variable for sanity checking */
$this->buffer_started = true;
}
/**
* Modify the buffer. Search for any js tags in it and replace them
* with Head JS calls for scripts not enqueued properly.
*
* @return string buffer
*/
function headjs_modify_buffer($buffer) {
$script_array = array();
/* Look for any script tags in the buffer */
preg_match_all('/<script([^>]*?)>(.*)<\/script>/Uis', $buffer, $script_tags_match);
if (!empty($script_tags_match[0])) {
foreach ($script_tags_match[0] as $script_tag) {
preg_match_all('/<script([^>]*?)>(.*)<\/script>/i', $buffer, $script_tags_match);
if (strpos(strtolower($script_tag), 'text/javascript') !== false) {
/* Pull out any scripts that are not enqueued properly */
preg_match('/<script([^>]*?)src=[\'"]([^\'"]+)([^>]*?)>/', $script_tag, $src_match);
if (!empty ($src_match[2])) {
if (!in_array( $src_match[2], $this->ignoreScripts)) {
/* Remove the script tags */
$buffer = str_replace($script_tag, '', $buffer);
/* Save the script location */
$script_array[] = $src_match[2];
}
} elseif ($this->adminOptions['wrap_inline_js'] == 'true') {
/* Add head.ready function to inline javascript */
$new_js = preg_replace('/<script([^>]*?)>/', "<script$1>\nhead.ready(function (){\n", $script_tag);
$new_js = str_replace('</script>', "\n}); // end head.ready\n</script>", $new_js);
$buffer = str_replace($script_tag, $new_js, $buffer);
}
} elseif ($this->adminOptions['wrap_inline_js'] == 'true') {
/* Add head.ready function to inline javascript */
$new_js = preg_replace('/<script([^>]*?)>/', "<script$1>\nhead.ready(function (){\n", $script_tag);
$new_js = str_replace('</script>', "\n}); // end head.ready\n</script>", $new_js);
$buffer = str_replace($script_tag, $new_js, $buffer);
}
}
}
/* Sort out the Head JS */
$headJSfile = $this->headjs_location();
$headJS = '<script type=\'text/javascript\' src=\'' . $headJSfile . '\'></script>';
$i=0;
$css_files = '';
/* Load the enqueued styles */
if (!empty($this->stylesUsed)) {
foreach ($this->stylesUsed as $style_name => $style_location) {
if ($i != 0) { $css_files .= ",\n "; }
$css_files .= '"' . $style_location . '"';
/* Loading with names was not working in dev environment, possibly fix this later */
//$css_files .= '{'. $style_name . ': "' . $style_location . '"}';
$i++;
}
}
$js_files = '';
/* Load the enqueued scripts */
if (!empty($this->scriptsUsed)) {
foreach ($this->scriptsUsed as $script_name => $script_location) {
if ($i != 0) { $js_files .= ",\n "; }
$js_files .= '"' . $script_location . '"';
/* Loading with names was not working in dev environment, possibly fix this later */
//$js_files .= '{'. $script_name . ': "' . $script_location . '"}';
$i++;
}
}
/* Load the other scraped scripts */
if (!empty($script_array)) {
$script_array = array_unique($script_array);
foreach ($script_array as $script_location) {
if ($i != 0) { $js_files .= ",\n "; }
$js_files .= '"' . $script_location . '"';
$i++;
}
}
/* Wrap what we want to load in script tag / head.load function */
if ( (!empty($script_array)) || (!empty($this->scriptsUsed)) || (!empty($this->stylesUsed)) ) {
$headJSqueue = "\n<script type='text/javascript'>\nhead.load(\n " . $css_files . $js_files . "\n);\n</script>";
}
/* Use noscript tags for css incase someone doesn't have js enabled */
if ( !empty($this->stylesUsed) ) {
$headJSqueue .= "\n<noscript>\n";
foreach ($this->stylesUsed as $style_name => $style_location) {
$headJSqueue .= "<link rel='stylesheet' id='$style_name' href='$style_location' type='text/css' media='all' />\n";
}
$headJSqueue .= "</noscript>\n";
}
/* Load HeadJS depending on the options settings */
if ($this->adminOptions['headjs_location'] == 'start_head') {
$buffer = preg_replace('/<head([^>]*?)>/', "<head$1>\n$headJS\n", $buffer);
} elseif ($this->adminOptions['headjs_location'] == 'after_title') {
$buffer = str_replace('</title>', "</title>\n" . $headJS, $buffer);
} elseif ($this->adminOptions['headjs_location'] == 'before_head') {
$buffer = str_replace('</head>', $headJS . "\n</head>", $buffer);
} elseif ($this->adminOptions['headjs_location'] == 'in_footer') {
$buffer = str_replace('</body>', $headJS . "\n</body>", $buffer);
}
/* Write HeadJS queue before the end of head */
$buffer = str_replace('</head>', $headJSqueue . "\n</head>", $buffer);
return $buffer;
}
/**
* After we are done modifying the contents, flush everything out to the screen.
*/
function headjs_post_content() {
// sanity checking
if ($this->buffer_started) {
ob_end_flush();
}
}
/*
* Return the location of the headJS file to use
*/
function headjs_location() {
$headJSLocations = array(
'cdn_headjs' => '//cdnjs.cloudflare.com/ajax/libs/headjs/1.0.3/head.min.js',
'local_headjs' => plugins_url('/js/head.min.js', __FILE__ ),
'cdn_headjs_core' => '//cdnjs.cloudflare.com/ajax/libs/headjs/1.0.3/head.core.min.js',
'local_headjs_core' => plugins_url('/js/head.core.min.js', __FILE__ ),
'cdn_headjs_asset' => 'http://cdnjs.cloudflare.com/ajax/libs/headjs/1.0.3/head.load.min.js',
'local_headjs_asset' => plugins_url('/js/head.load.min.js', __FILE__ ),
'custom_headjs' => $this->adminOptions['custom_location']
);
return $headJSLocations[$this->adminOptions['headjs_type']];
}
/**
* Add to the admin settings menu
*/
function headjs_admin() {
add_options_page('HeadJS Loader', 'HeadJS Loader', 'manage_options', basename(__FILE__), array($this, 'headjs_admin_panel'));
}
/**
* Add our admin page
*/
function headjs_admin_panel() {
$headjsUpdated = $this->headjs_admin_update_options();
//$this->adminOptions = $this->headjs_admin_options();
$headjsTypes = array(
'cdn_headjs' => __('CDN HeadJS (<a href="http://cdnjs.com/" target="_BLANK">Cloudflare</a>)', $this->pluginName),
'local_headjs' => __('Local HeadJS', $this->pluginName),
'cdn_headjs_core' => __('CDN HeadJS Core (<a href="http://cdnjs.com/" target="_BLANK">Cloudflare</a>) [Responsive Design & Feature Detection Only]', $this->pluginName),
'local_headjs_core' => __('Local HeadJS [Responsive Design & Feature Detection Only]', $this->pluginName),
'cdn_headjs_asset' => __('CDN HeadJS Load (<a href="http://cdnjs.com/" target="_BLANK">Cloudflare</a>) [Asset Loader Only]', $this->pluginName),
'local_headjs_asset' => __('Local HeadJS [Asset Loader Only]', $this->pluginName),
'custom_headjs' => __('Load from custom location', $this->pluginName)
);
?>
<div class=wrap>
<?php echo $headjsUpdated; ?>
<script type="text/javascript">
jQuery(document).ready(function(){
if (jQuery('input[value=custom_headjs]:checked').length == 0){
jQuery('#head_js_custom_location').hide();
}
});
jQuery(function() {
jQuery('input[name=headjs_type]').click(function() {
if (jQuery('input[value=custom_headjs]:checked').length == 0){
jQuery('#head_js_custom_location').hide();
} else {
jQuery('#head_js_custom_location').show();
}
});
});
</script>
<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
<h2><?php _e('HeadJS Loader', $this->pluginName) ?></h2>
<p><?php _e('For more information on the different versions of HeadJS please visit their homepage at', $this->pluginName) ?> <a href="http://headjs.com" target="_BLANK" title="HeadJS">http://headjs.com</a></p>
<h3><?php _e('Select the headJS file you would like to use:', $this->pluginName) ?></h3>
<?php foreach ($headjsTypes as $id => $value) { ?>
<p><input type="radio" name="headjs_type" id="<?php echo $id; ?>" value="<?php echo $id; ?>" <?php if ($this->adminOptions['headjs_type'] == $id) { echo 'checked="checked" '; }?>/>
<label for="<?php echo $id; ?>"><?php echo $value; ?></label></p>
<?php } ?>
<div id="head_js_custom_location">
<label for="custom_location"><?php _e('Custom Location URL', $this->pluginName) ?> : </label>
<input type="text" name="custom_location" id="custom_location" value="<?php echo $this->adminOptions['custom_location'];?>" />
</div>
<br />
<h3><?php _e('Other Options:', $this->pluginName) ?></h3>
<p>
<input type="checkbox" name="wrap_inline_js" id="wrap_inline_js" value="true" <?php if ($this->adminOptions['wrap_inline_js'] == 'true') { echo 'checked="checked" '; }?>/>
<label for="wrap_inline_js"><?php _e('Wrap inline javascript with head.ready function', $this->pluginName) ?></label>
</p>
<p>
<select name="headjs_location" id="headjs_location">
<option value="start_head"<?php if ($this->adminOptions['headjs_location'] == 'start_head') { echo ' selected'; }?>>
<?php _e('After <head> tag', $this->pluginName) ?>
</option>
<option value="after_title"<?php if ($this->adminOptions['headjs_location'] == 'after_title') { echo ' selected'; }?>>
<?php _e('After </title> tag', $this->pluginName) ?>
</option>
<option value="before_head"<?php if ($this->adminOptions['headjs_location'] == 'before_head') { echo ' selected'; }?>>
<?php _e('Before </head> tag', $this->pluginName) ?>
</option>
<option value="in_footer"<?php if ($this->adminOptions['headjs_location'] == 'in_footer') { echo ' selected'; }?>>
<?php _e('Before </body> tag', $this->pluginName) ?>
</option>
</select>
<label for="headjs_location"><?php _e('Where to place HeadJS script', $this->pluginName) ?></label>
</p>
<p>
<label for="headjs_ignore" style="vertical-align: top;"><?php _e('JS Files to ignore:', $this->pluginName) ?></label>
<textarea name="headjs_ignore" id="headjs_ignore" cols="60" rows="5"><?php echo $this->adminOptions['headjs_ignore']; ?></textarea>
</p>
<p>
<label for="headjs_css_ignore" style="vertical-align: top;"><?php _e('CSS Files to ignore:', $this->pluginName) ?></label>
<textarea name="headjs_css_ignore" id="headjs_css_ignore" cols="60" rows="5"><?php echo $this->adminOptions['headjs_css_ignore']; ?></textarea>
</p>
<div class="submit"><input type="submit" class="button-primary" name="update_headjsSettings" value="<?php _e('Update Settings', $this->pluginName) ?>" /></div>
</form>
</div>
<?php
}
/*
* Returns an array of our admin options
*/
function headjs_admin_options() {
$headjsAdminOptions = array(
'headjs_type' => 'cdn_headjs',
'custom_location' => 'http://',
'wrap_inline_js' => 'true',
'headjs_location' => 'start_head',
'headjs_ignore' => '',
'headjs_css_ignore' => ''
);
$this->adminOptions = get_option($this->pluginName);
if (!empty($this->adminOptions)) {
foreach ($this->adminOptions as $key => $option)
$headjsAdminOptions[$key] = $option;
}
update_option($this->pluginName, $headjsAdminOptions);
return $headjsAdminOptions;
}
/*
* Check if we need to update our options, and execute if so
*/
function headjs_admin_update_options() {
$return = '';
/* If form is submitted, update options */
if (isset($_POST['update_headjsSettings'])) {
if (isset($_POST['headjs_type'])) {
$this->adminOptions['headjs_type'] = $_POST['headjs_type'];
}
if (isset($_POST['custom_location'])) {
$this->adminOptions['custom_location'] = apply_filters('content_save_pre', $_POST['custom_location']);
}
if (isset($_POST['wrap_inline_js'])) {
$this->adminOptions['wrap_inline_js'] = $_POST['wrap_inline_js'];
} else {
$this->adminOptions['wrap_inline_js'] = false;
}
if (isset($_POST['headjs_location'])) {
$this->adminOptions['headjs_location'] = $_POST['headjs_location'];
}
if (isset($_POST['headjs_ignore'])) {
$this->adminOptions['headjs_ignore'] = $_POST['headjs_ignore'];
}
if (isset($_POST['headjs_css_ignore'])) {
$this->adminOptions['headjs_css_ignore'] = $_POST['headjs_css_ignore'];
}
update_option($this->pluginName, $this->adminOptions);
$return = '<div class="updated"><p><strong>' . __("Settings Updated.", $this->pluginName) . '</strong></p></div>';
}
return $return;
}
/*
* Create a link to our settings page on the plugin page
*/
function headjs_admin_link_plugin_settings($links, $file) {
$this_plugin = plugin_basename(__FILE__);
if ($file == $this_plugin) {
$settings_link = '<a href="' . get_bloginfo('wpurl') . '/wp-admin/admin.php?page=' . basename($this_plugin) .'">Settings</a>';
array_unshift($links, $settings_link);
}
return $links;
}
} // class headJS_loader
} // if !class_exists('headJS_loader')
/*
* Instantiate our class
*/
if (class_exists('headJS_loader')) {
$headJS_loader = new headJS_loader();
}
?>