Autoptimize - Version 2.7.0

Version Description

  • Integration of critical CSS power-up.
  • New option to ensure missing autoptimized files are served with fallback JS/ CSS.
  • Batch of misc. smaller improvements & fixes, more info in the GitHub commit log.
Download this release

Release Info

Developer futtta
Plugin Icon 128x128 Autoptimize
Version 2.7.0
Comparing to
See all releases

Code changes from version 2.6.2 to 2.7.0

Files changed (35) hide show
  1. autoptimize.php +2 -2
  2. classes/autoptimizeCache.php +53 -6
  3. classes/autoptimizeConfig.php +17 -11
  4. classes/autoptimizeCriticalCSSBase.php +186 -0
  5. classes/autoptimizeCriticalCSSCore.php +580 -0
  6. classes/autoptimizeCriticalCSSCron.php +829 -0
  7. classes/autoptimizeCriticalCSSEnqueue.php +282 -0
  8. classes/autoptimizeCriticalCSSSettings.php +310 -39
  9. classes/autoptimizeCriticalCSSSettingsAjax.php +352 -0
  10. classes/autoptimizeExtra.php +14 -2
  11. classes/autoptimizeHTML.php +5 -1
  12. classes/autoptimizeImages.php +25 -10
  13. classes/autoptimizeMain.php +68 -15
  14. classes/autoptimizeScripts.php +329 -140
  15. classes/autoptimizeStyles.php +317 -162
  16. classes/autoptimizeUtils.php +2 -2
  17. classes/critcss-inc/admin_settings_adv.php +145 -0
  18. classes/critcss-inc/admin_settings_debug.php +81 -0
  19. classes/critcss-inc/admin_settings_explain.php +46 -0
  20. classes/critcss-inc/admin_settings_impexp.js.php +68 -0
  21. classes/critcss-inc/admin_settings_key.php +57 -0
  22. classes/critcss-inc/admin_settings_queue.js.php +218 -0
  23. classes/critcss-inc/admin_settings_queue.php +92 -0
  24. classes/critcss-inc/admin_settings_rules.js.php +373 -0
  25. classes/critcss-inc/admin_settings_rules.php +207 -0
  26. classes/critcss-inc/css/admin_styles.css +253 -0
  27. classes/critcss-inc/css/ao-tablesorter/asc.gif +0 -0
  28. classes/critcss-inc/css/ao-tablesorter/bg.gif +0 -0
  29. classes/critcss-inc/css/ao-tablesorter/desc.gif +0 -0
  30. classes/critcss-inc/css/ao-tablesorter/style.css +40 -0
  31. classes/critcss-inc/js/admin_settings.js +11 -0
  32. classes/critcss-inc/js/jquery.tablesorter.min.js +4 -0
  33. classes/critcss-inc/js/md5.min.js +2 -0
  34. classes/external/js/lazysizes.min.js +2 -2
  35. readme.txt +34 -12
autoptimize.php CHANGED
@@ -3,7 +3,7 @@
3
  * Plugin Name: Autoptimize
4
  * Plugin URI: https://autoptimize.com/
5
  * Description: Makes your site faster by optimizing CSS, JS, Images, Google fonts and more.
6
- * Version: 2.6.2
7
  * Author: Frank Goossens (futtta)
8
  * Author URI: https://autoptimize.com/
9
  * Text Domain: autoptimize
@@ -20,7 +20,7 @@ if ( ! defined( 'ABSPATH' ) ) {
20
  exit;
21
  }
22
 
23
- define( 'AUTOPTIMIZE_PLUGIN_VERSION', '2.6.2' );
24
 
25
  // plugin_dir_path() returns the trailing slash!
26
  define( 'AUTOPTIMIZE_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
3
  * Plugin Name: Autoptimize
4
  * Plugin URI: https://autoptimize.com/
5
  * Description: Makes your site faster by optimizing CSS, JS, Images, Google fonts and more.
6
+ * Version: 2.7.0
7
  * Author: Frank Goossens (futtta)
8
  * Author URI: https://autoptimize.com/
9
  * Text Domain: autoptimize
20
  exit;
21
  }
22
 
23
+ define( 'AUTOPTIMIZE_PLUGIN_VERSION', '2.7.0' );
24
 
25
  // plugin_dir_path() returns the trailing slash!
26
  define( 'AUTOPTIMIZE_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
classes/autoptimizeCache.php CHANGED
@@ -40,15 +40,20 @@ class autoptimizeCache
40
  */
41
  public function __construct( $md5, $ext = 'php' )
42
  {
 
 
 
 
 
43
  $this->cachedir = AUTOPTIMIZE_CACHE_DIR;
44
  $this->nogzip = AUTOPTIMIZE_CACHE_NOGZIP;
45
  if ( ! $this->nogzip ) {
46
- $this->filename = AUTOPTIMIZE_CACHEFILE_PREFIX . $md5 . '.php';
47
  } else {
48
  if ( in_array( $ext, array( 'js', 'css' ) ) ) {
49
- $this->filename = $ext . '/' . AUTOPTIMIZE_CACHEFILE_PREFIX . $md5 . '.' . $ext;
50
  } else {
51
- $this->filename = AUTOPTIMIZE_CACHEFILE_PREFIX . $md5 . '.' . $ext;
52
  }
53
  }
54
  }
@@ -128,6 +133,10 @@ class autoptimizeCache
128
  }
129
  }
130
  }
 
 
 
 
131
  }
132
 
133
  /**
@@ -589,7 +598,7 @@ class autoptimizeCache
589
  </IfModule>';
590
  }
591
 
592
- if ( self::do_fallback() ) {
593
  $content .= "\nErrorDocument 404 " . trailingslashit( parse_url( content_url(), PHP_URL_PATH ) ) . 'autoptimize_404_handler.php';
594
  }
595
  @file_put_contents( $htaccess, $content ); // @codingStandardsIgnoreLine
@@ -628,12 +637,50 @@ class autoptimizeCache
628
 
629
  /**
630
  * Tells if AO should try to avoid 404's by creating fallback filesize
631
- * and create a php 404 handler and tell .htaccess to redirect to said handler.
 
 
632
  *
633
  * Return bool
634
  */
635
  public static function do_fallback() {
636
- return apply_filters( 'autoptimize_filter_cache_do_fallback', false );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
637
  }
638
 
639
  /**
40
  */
41
  public function __construct( $md5, $ext = 'php' )
42
  {
43
+ $_min_ext = '';
44
+ if ( apply_filters( 'autoptimize_filter_cache_url_add_min_ext', false ) ) {
45
+ $_min_ext = '.min';
46
+ }
47
+
48
  $this->cachedir = AUTOPTIMIZE_CACHE_DIR;
49
  $this->nogzip = AUTOPTIMIZE_CACHE_NOGZIP;
50
  if ( ! $this->nogzip ) {
51
+ $this->filename = AUTOPTIMIZE_CACHEFILE_PREFIX . $md5 . $_min_ext . '.php';
52
  } else {
53
  if ( in_array( $ext, array( 'js', 'css' ) ) ) {
54
+ $this->filename = $ext . '/' . AUTOPTIMIZE_CACHEFILE_PREFIX . $md5 . $_min_ext . '.' . $ext;
55
  } else {
56
+ $this->filename = AUTOPTIMIZE_CACHEFILE_PREFIX . $md5 . $_min_ext . '.' . $ext;
57
  }
58
  }
59
  }
133
  }
134
  }
135
  }
136
+
137
+ // Provide 3rd party action hook for every cache file that is created.
138
+ // This hook can for example be used to inject a copy of the created cache file to a other domain.
139
+ do_action( 'autoptimize_action_cache_file_created', $this->cachedir . $this->filename );
140
  }
141
 
142
  /**
598
  </IfModule>';
599
  }
600
 
601
+ if ( self::do_fallback() === true ) {
602
  $content .= "\nErrorDocument 404 " . trailingslashit( parse_url( content_url(), PHP_URL_PATH ) ) . 'autoptimize_404_handler.php';
603
  }
604
  @file_put_contents( $htaccess, $content ); // @codingStandardsIgnoreLine
637
 
638
  /**
639
  * Tells if AO should try to avoid 404's by creating fallback filesize
640
+ * and create a php 404 handler and tell .htaccess to redirect to said handler
641
+ * and hook into WordPress to redirect 404 to said handler as well. NGINX users
642
+ * are smart enough to get this working, no? ;-)
643
  *
644
  * Return bool
645
  */
646
  public static function do_fallback() {
647
+ static $_do_fallback = null;
648
+
649
+ if ( null === $_do_fallback ) {
650
+ $_do_fallback = (bool) apply_filters( 'autoptimize_filter_cache_do_fallback', autoptimizeOptionWrapper::get_option( 'autoptimize_cache_fallback', '' ) );
651
+ }
652
+
653
+ return $_do_fallback;
654
+ }
655
+
656
+ /**
657
+ * Hooks into template_redirect, will act on 404-ing requests for
658
+ * Autoptimized files and redirects to the fallback CSS/ JS if available
659
+ * and 410'ing ("Gone") if fallback not available.
660
+ */
661
+ public static function wordpress_notfound_fallback() {
662
+ $original_request = strtok( $_SERVER['REQUEST_URI'], '?' );
663
+ if ( strpos( $original_request, wp_basename( WP_CONTENT_DIR ) . AUTOPTIMIZE_CACHE_CHILD_DIR ) !== false && is_404() ) {
664
+ // make sure this is not considered a 404.
665
+ global $wp_query;
666
+ $wp_query->is_404 = false;
667
+
668
+ // set fallback path.
669
+ $js_or_css = pathinfo( $original_request, PATHINFO_EXTENSION );
670
+ $fallback_path = AUTOPTIMIZE_CACHE_DIR . $js_or_css . '/autoptimize_fallback.' . $js_or_css;
671
+
672
+ // set fallback URL.
673
+ $fallback_target = preg_replace( '/(.*)_(?:[a-z0-9]{32})\.(js|css)$/', '${1}_fallback.${2}', $original_request );
674
+
675
+ // redirect to fallback if possible.
676
+ if ( $original_request !== $fallback_target && file_exists( $fallback_path ) ) {
677
+ // redirect to fallback.
678
+ wp_redirect( $fallback_target, 302 );
679
+ } else {
680
+ // return HTTP 410 (gone) reponse.
681
+ status_header( 410 );
682
+ }
683
+ }
684
  }
685
 
686
  /**
classes/autoptimizeConfig.php CHANGED
@@ -180,9 +180,10 @@ input[type=url]:invalid {color: red; border-color:red;} .form-table th{font-weig
180
 
181
  <div class="wrap">
182
 
183
- <?php if ( defined( 'AUTOPTIMIZE_LEGACY_MINIFIERS' ) ) { ?>
184
- <div class="notice-error notice"><p>
185
- <?php _e( "You are using the (no longer supported) AUTOPTIMIZE_LEGACY_MINIFIERS constant. Ensure your site is working properly and remove the constant, it doesn't do anything any more.", 'autoptimize' ); ?>
 
186
  </p></div>
187
  <?php } ?>
188
 
@@ -302,12 +303,10 @@ echo ' <i>' . __( '(deprecated)', 'autoptimize' ) . '</i>';
302
  <td><label class="cb_label"><input type="checkbox" name="autoptimize_css_defer" id="autoptimize_css_defer" <?php echo autoptimizeOptionWrapper::get_option( 'autoptimize_css_defer' ) ? 'checked="checked" ' : ''; ?>/>
303
  <?php
304
  _e( 'Inline "above the fold CSS" while loading the main autoptimized CSS only after page load. <a href="http://wordpress.org/plugins/autoptimize/faq/" target="_blank">Check the FAQ</a> for more info.', 'autoptimize' );
305
- if ( ! autoptimizeUtils::is_plugin_active( 'autoptimize-criticalcss/ao_criticss_aas.php' ) ) {
306
- echo ' ';
307
- $critcss_install_url = network_admin_url() . 'plugin-install.php?s=autoptimize+criticalcss&tab=search&type=term';
308
- // translators: links to plugin install screen with "autoptimize critical CSS" search.
309
- echo sprintf( __( 'This can be fully automated for different types of pages with the %s.', 'autoptimize' ), '<a href="' . $critcss_install_url . '">Autoptimize CriticalCSS Power-Up</a>' );
310
- }
311
  ?>
312
  </label></td>
313
  </tr>
@@ -318,7 +317,7 @@ if ( ! autoptimizeUtils::is_plugin_active( 'autoptimize-criticalcss/ao_criticss_
318
  <tr valign="top" class="css_sub css_aggregate">
319
  <th scope="row"><?php _e( 'Inline all CSS?', 'autoptimize' ); ?></th>
320
  <td><label class="cb_label"><input type="checkbox" id="autoptimize_css_inline" name="autoptimize_css_inline" <?php echo autoptimizeOptionWrapper::get_option( 'autoptimize_css_inline' ) ? 'checked="checked" ' : ''; ?>/>
321
- <?php _e( 'Inlining all CSS can improve performance for sites with a low pageviews/ visitor-rate, but may slow down performance otherwise.', 'autoptimize' ); ?></label></td>
322
  </tr>
323
  <tr valign="top" class="css_sub">
324
  <th scope="row"><?php _e( 'Exclude CSS from Autoptimize:', 'autoptimize' ); ?></th>
@@ -407,9 +406,14 @@ echo __( 'A comma-separated list of CSS you want to exclude from being optimized
407
  <td><label class="cb_label"><input type="checkbox" name="autoptimize_minify_excluded" <?php echo autoptimizeOptionWrapper::get_option( 'autoptimize_minify_excluded', '1' ) ? 'checked="checked" ' : ''; ?>/>
408
  <?php _e( 'When aggregating JS or CSS, excluded files that are not minified (based on filename) are by default minified by Autoptimize despite being excluded. Uncheck this option if anything breaks despite excluding.', 'autoptimize' ); ?></label></td>
409
  </tr>
 
 
 
 
 
410
  <tr valign="top">
411
  <th scope="row"><?php _e( 'Also optimize for logged in editors/ administrators?', 'autoptimize' ); ?></th>
412
- <td><label class="cb_label"><input type="checkbox" name="autoptimize_optimize_logged" <?php echo get_option( 'autoptimize_optimize_logged', '1' ) ? 'checked="checked" ' : ''; ?>/>
413
  <?php _e( 'By default Autoptimize is also active for logged on editors/ administrators, uncheck this option if you don\'t want Autoptimize to optimize when logged in e.g. to use a pagebuilder.', 'autoptimize' ); ?></label></td>
414
  </tr>
415
  <?php
@@ -679,6 +683,7 @@ echo __( 'A comma-separated list of CSS you want to exclude from being optimized
679
  register_setting( 'autoptimize', 'autoptimize_optimize_logged' );
680
  register_setting( 'autoptimize', 'autoptimize_optimize_checkout' );
681
  register_setting( 'autoptimize', 'autoptimize_minify_excluded' );
 
682
  }
683
 
684
  public function setmeta( $links, $file = null )
@@ -738,6 +743,7 @@ echo __( 'A comma-separated list of CSS you want to exclude from being optimized
738
  'autoptimize_optimize_logged' => 1,
739
  'autoptimize_optimize_checkout' => 0,
740
  'autoptimize_minify_excluded' => 1,
 
741
  );
742
 
743
  return $config;
180
 
181
  <div class="wrap">
182
 
183
+ <!-- Temporary nudge to disable aoccss power-up. -->
184
+ <?php if ( autoptimizeUtils::is_plugin_active( 'autoptimize-criticalcss/ao_criticss_aas.php' ) ) { ?>
185
+ <div class="notice-info notice"><p>
186
+ <?php _e( 'Autoptimize now includes the criticalcss.com integration that was previously part of the separate power-up. If you want you can simply disable the power-up and Autoptimize will take over immediately.', 'autoptimize' ); ?>
187
  </p></div>
188
  <?php } ?>
189
 
303
  <td><label class="cb_label"><input type="checkbox" name="autoptimize_css_defer" id="autoptimize_css_defer" <?php echo autoptimizeOptionWrapper::get_option( 'autoptimize_css_defer' ) ? 'checked="checked" ' : ''; ?>/>
304
  <?php
305
  _e( 'Inline "above the fold CSS" while loading the main autoptimized CSS only after page load. <a href="http://wordpress.org/plugins/autoptimize/faq/" target="_blank">Check the FAQ</a> for more info.', 'autoptimize' );
306
+ echo ' ';
307
+ $critcss_settings_url = get_admin_url( null, 'options-general.php?page=ao_critcss' );
308
+ // translators: links "autoptimize critical CSS" tab.
309
+ echo sprintf( __( 'This can be fully automated for different types of pages on the %s tab.', 'autoptimize' ), '<a href="' . $critcss_settings_url . '">CriticalCSS</a>' );
 
 
310
  ?>
311
  </label></td>
312
  </tr>
317
  <tr valign="top" class="css_sub css_aggregate">
318
  <th scope="row"><?php _e( 'Inline all CSS?', 'autoptimize' ); ?></th>
319
  <td><label class="cb_label"><input type="checkbox" id="autoptimize_css_inline" name="autoptimize_css_inline" <?php echo autoptimizeOptionWrapper::get_option( 'autoptimize_css_inline' ) ? 'checked="checked" ' : ''; ?>/>
320
+ <?php _e( 'Inlining all CSS is an easy way to stop the CSS from being render-blocking, but is generally not recommended because the size of the HTML increases significantly. Additionally it might push meta-tags down to a position where e.g. Facebook and Whatsapp will not find them any more, breaking thumbnails when sharing.', 'autoptimize' ); ?></label></td>
321
  </tr>
322
  <tr valign="top" class="css_sub">
323
  <th scope="row"><?php _e( 'Exclude CSS from Autoptimize:', 'autoptimize' ); ?></th>
406
  <td><label class="cb_label"><input type="checkbox" name="autoptimize_minify_excluded" <?php echo autoptimizeOptionWrapper::get_option( 'autoptimize_minify_excluded', '1' ) ? 'checked="checked" ' : ''; ?>/>
407
  <?php _e( 'When aggregating JS or CSS, excluded files that are not minified (based on filename) are by default minified by Autoptimize despite being excluded. Uncheck this option if anything breaks despite excluding.', 'autoptimize' ); ?></label></td>
408
  </tr>
409
+ <tr valign="top">
410
+ <th scope="row"><?php _e( 'Experimental: enable 404 fallbacks.', 'autoptimize' ); ?></th>
411
+ <td><label class="cb_label"><input type="checkbox" name="autoptimize_cache_fallback" <?php echo autoptimizeOptionWrapper::get_option( 'autoptimize_cache_fallback', '' ) ? 'checked="checked" ' : ''; ?>/>
412
+ <?php _e( 'Sometimes Autoptimized JS/ CSS is referenced in cached HTML but is already removed, resulting in broken sites. This experimental feature tries to redirect those not-found files to "fallback"-versions, keeping the page/ site somewhat intact. In some cases this will require extra web-server level configuration to ensure <code>wp-content/autoptimize_404_handler.php</code> is set to handle 404\'s in <code>wp-content/cache/autoptimize</code>.', 'autoptimize' ); ?></label></td>
413
+ </tr>
414
  <tr valign="top">
415
  <th scope="row"><?php _e( 'Also optimize for logged in editors/ administrators?', 'autoptimize' ); ?></th>
416
+ <td><label class="cb_label"><input type="checkbox" name="autoptimize_optimize_logged" <?php echo autoptimizeOptionWrapper::get_option( 'autoptimize_optimize_logged', '1' ) ? 'checked="checked" ' : ''; ?>/>
417
  <?php _e( 'By default Autoptimize is also active for logged on editors/ administrators, uncheck this option if you don\'t want Autoptimize to optimize when logged in e.g. to use a pagebuilder.', 'autoptimize' ); ?></label></td>
418
  </tr>
419
  <?php
683
  register_setting( 'autoptimize', 'autoptimize_optimize_logged' );
684
  register_setting( 'autoptimize', 'autoptimize_optimize_checkout' );
685
  register_setting( 'autoptimize', 'autoptimize_minify_excluded' );
686
+ register_setting( 'autoptimize', 'autoptimize_cache_fallback' );
687
  }
688
 
689
  public function setmeta( $links, $file = null )
743
  'autoptimize_optimize_logged' => 1,
744
  'autoptimize_optimize_checkout' => 0,
745
  'autoptimize_minify_excluded' => 1,
746
+ 'autoptimize_cache_fallback' => '',
747
  );
748
 
749
  return $config;
classes/autoptimizeCriticalCSSBase.php ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Critical CSS base file (initializes all ccss files).
4
+ */
5
+
6
+ if ( ! defined( 'ABSPATH' ) ) {
7
+ exit;
8
+ }
9
+
10
+ class autoptimizeCriticalCSSBase {
11
+ /**
12
+ * Main plugin filepath.
13
+ * Used for activation/deactivation/uninstall hooks.
14
+ *
15
+ * @var string
16
+ */
17
+ protected $filepath = null;
18
+
19
+ public function __construct()
20
+ {
21
+ // define constant, but only once.
22
+ if ( ! defined( 'AO_CCSS_DIR' ) ) {
23
+ // Define plugin version.
24
+ define( 'AO_CCSS_VER', 'AO_' . AUTOPTIMIZE_PLUGIN_VERSION );
25
+
26
+ // Define a constant with the directory to store critical CSS in.
27
+ if ( is_multisite() ) {
28
+ $blog_id = get_current_blog_id();
29
+ define( 'AO_CCSS_DIR', WP_CONTENT_DIR . '/uploads/ao_ccss/' . $blog_id . '/' );
30
+ } else {
31
+ define( 'AO_CCSS_DIR', WP_CONTENT_DIR . '/uploads/ao_ccss/' );
32
+ }
33
+
34
+ // Define support files locations.
35
+ define( 'AO_CCSS_LOCK', AO_CCSS_DIR . 'queue.lock' );
36
+ define( 'AO_CCSS_LOG', AO_CCSS_DIR . 'queuelog.html' );
37
+ define( 'AO_CCSS_DEBUG', AO_CCSS_DIR . 'queue.json' );
38
+
39
+ // Define constants for criticalcss.com base path and API endpoints.
40
+ // fixme: AO_CCSS_URL should be read from the autoptimize availability json stored as option.
41
+ define( 'AO_CCSS_URL', 'https://criticalcss.com' );
42
+ define( 'AO_CCSS_API', AO_CCSS_URL . '/api/premium/' );
43
+ }
44
+
45
+ $this->filepath = __FILE__;
46
+
47
+ $this->setup();
48
+ $this->load_requires();
49
+ }
50
+
51
+ public function setup()
52
+ {
53
+ // get all options.
54
+ $all_options = $this->fetch_options();
55
+ foreach ( $all_options as $option => $value ) {
56
+ ${$option} = $value;
57
+ }
58
+
59
+ // make sure the 10 minutes cron schedule is added.
60
+ add_filter( 'cron_schedules', array( $this, 'ao_ccss_interval' ) );
61
+
62
+ // check if we need to upgrade.
63
+ $this->check_upgrade();
64
+
65
+ // make sure ao_ccss_queue is scheduled OK if an API key is set.
66
+ if ( isset( $ao_ccss_key ) && ! empty( $ao_ccss_key ) && ! wp_next_scheduled( 'ao_ccss_queue' ) ) {
67
+ wp_schedule_event( time(), apply_filters( 'ao_ccss_queue_schedule', 'ao_ccss' ), 'ao_ccss_queue' );
68
+ }
69
+ }
70
+
71
+ public function load_requires() {
72
+ // Required libs, core is always needed.
73
+ $criticalcss_core = new autoptimizeCriticalCSSCore();
74
+
75
+ if ( defined( 'DOING_CRON' ) || is_admin() ) {
76
+ // TODO: also include if overridden somehow to force queue processing to be executed?
77
+ $criticalcss_cron = new autoptimizeCriticalCSSCron();
78
+ }
79
+
80
+ if ( is_admin() ) {
81
+ $criticalcss_settings = new autoptimizeCriticalCSSSettings();
82
+ } else {
83
+ // enqueuing only done when not wp-admin.
84
+ $criticalcss_enqueue = new autoptimizeCriticalCSSEnqueue();
85
+ }
86
+ }
87
+
88
+ public static function fetch_options() {
89
+ // Get options.
90
+ $autoptimize_ccss_options['ao_css_defer'] = get_option( 'autoptimize_css_defer' );
91
+ $autoptimize_ccss_options['ao_css_defer_inline'] = get_option( 'autoptimize_css_defer_inline' );
92
+ $autoptimize_ccss_options['ao_ccss_rules_raw'] = get_option( 'autoptimize_ccss_rules', false );
93
+ $autoptimize_ccss_options['ao_ccss_additional'] = get_option( 'autoptimize_ccss_additional' );
94
+ $autoptimize_ccss_options['ao_ccss_queue_raw'] = get_option( 'autoptimize_ccss_queue', false );
95
+ $autoptimize_ccss_options['ao_ccss_viewport'] = get_option( 'autoptimize_ccss_viewport', false );
96
+ $autoptimize_ccss_options['ao_ccss_finclude'] = get_option( 'autoptimize_ccss_finclude', false );
97
+ $autoptimize_ccss_options['ao_ccss_rlimit'] = get_option( 'autoptimize_ccss_rlimit', '5' );
98
+ $autoptimize_ccss_options['ao_ccss_noptimize'] = get_option( 'autoptimize_ccss_noptimize', false );
99
+ $autoptimize_ccss_options['ao_ccss_debug'] = get_option( 'autoptimize_ccss_debug', false );
100
+ $autoptimize_ccss_options['ao_ccss_key'] = get_option( 'autoptimize_ccss_key' );
101
+ $autoptimize_ccss_options['ao_ccss_keyst'] = get_option( 'autoptimize_ccss_keyst' );
102
+ $autoptimize_ccss_options['ao_ccss_loggedin'] = get_option( 'autoptimize_ccss_loggedin', '1' );
103
+ $autoptimize_ccss_options['ao_ccss_forcepath'] = get_option( 'autoptimize_ccss_forcepath', '1' );
104
+ $autoptimize_ccss_options['ao_ccss_servicestatus'] = get_option( 'autoptimize_service_availablity' );
105
+ $autoptimize_ccss_options['ao_ccss_deferjquery'] = get_option( 'autoptimize_ccss_deferjquery', false );
106
+ $autoptimize_ccss_options['ao_ccss_domain'] = get_option( 'autoptimize_ccss_domain' );
107
+
108
+ if ( strpos( $autoptimize_ccss_options['ao_ccss_domain'], 'http' ) === false && strpos( $autoptimize_ccss_options['ao_ccss_domain'], 'uggc' ) === 0 ) {
109
+ $autoptimize_ccss_options['ao_ccss_domain'] = str_rot13( $autoptimize_ccss_options['ao_ccss_domain'] );
110
+ } elseif ( strpos( $autoptimize_ccss_options['ao_ccss_domain'], 'http' ) !== false ) {
111
+ // not rot13'ed yet, do so now (goal; avoid migration plugins change the bound domain).
112
+ update_option( 'autoptimize_ccss_domain', str_rot13( $autoptimize_ccss_options['ao_ccss_domain'] ) );
113
+ }
114
+
115
+ // Setup the rules array.
116
+ if ( empty( $autoptimize_ccss_options['ao_ccss_rules_raw'] ) ) {
117
+ $autoptimize_ccss_options['ao_ccss_rules']['paths'] = array();
118
+ $autoptimize_ccss_options['ao_ccss_rules']['types'] = array();
119
+ } else {
120
+ $autoptimize_ccss_options['ao_ccss_rules'] = json_decode( $autoptimize_ccss_options['ao_ccss_rules_raw'], true );
121
+ }
122
+
123
+ // Setup the queue array.
124
+ if ( empty( $autoptimize_ccss_options['ao_ccss_queue_raw'] ) ) {
125
+ $autoptimize_ccss_options['ao_ccss_queue'] = array();
126
+ } else {
127
+ $autoptimize_ccss_options['ao_ccss_queue'] = json_decode( $autoptimize_ccss_options['ao_ccss_queue_raw'], true );
128
+ }
129
+
130
+ // Override API key if constant is defined.
131
+ if ( defined( 'AUTOPTIMIZE_CRITICALCSS_API_KEY' ) ) {
132
+ $autoptimize_ccss_options['ao_ccss_key'] = AUTOPTIMIZE_CRITICALCSS_API_KEY;
133
+ }
134
+
135
+ return $autoptimize_ccss_options;
136
+ }
137
+
138
+ public function on_upgrade() {
139
+ // Create the cache directory if it doesn't exist already.
140
+ if ( ! file_exists( AO_CCSS_DIR ) ) {
141
+ mkdir( AO_CCSS_DIR, 0755, true );
142
+ }
143
+
144
+ // Create a scheduled event for the queue.
145
+ if ( ! wp_next_scheduled( 'ao_ccss_queue' ) ) {
146
+ wp_schedule_event( time(), apply_filters( 'ao_ccss_queue_schedule', 'ao_ccss' ), 'ao_ccss_queue' );
147
+ }
148
+
149
+ // Create a scheduled event for log maintenance.
150
+ if ( ! wp_next_scheduled( 'ao_ccss_maintenance' ) ) {
151
+ wp_schedule_event( time(), 'twicedaily', 'ao_ccss_maintenance' );
152
+ }
153
+ }
154
+
155
+ public function check_upgrade() {
156
+ $db_version = get_option( 'autoptimize_ccss_version', '' );
157
+ if ( AO_CCSS_VER !== $db_version ) {
158
+ // check schedules & re-schedule if needed.
159
+ $this->on_upgrade();
160
+ // and update db_version.
161
+ update_option( 'autoptimize_ccss_version', AO_CCSS_VER );
162
+ }
163
+ }
164
+
165
+ public function ao_ccss_interval( $schedules ) {
166
+ // Let interval be configurable.
167
+ if ( ! defined( 'AO_CCSS_DEBUG_INTERVAL' ) ) {
168
+ $intsec = 600;
169
+ } else {
170
+ $intsec = AO_CCSS_DEBUG_INTERVAL;
171
+ if ( $intsec >= 120 ) {
172
+ $inttxt = $intsec / 60 . ' minutes';
173
+ } else {
174
+ $inttxt = $intsec . ' second(s)';
175
+ }
176
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Using custom WP-Cron interval of ' . $inttxt, 3 );
177
+ }
178
+
179
+ // Attach interval to schedule.
180
+ $schedules['ao_ccss'] = array(
181
+ 'interval' => $intsec,
182
+ 'display' => __( 'Autoptimize CriticalCSS' ),
183
+ );
184
+ return $schedules;
185
+ }
186
+ }
classes/autoptimizeCriticalCSSCore.php ADDED
@@ -0,0 +1,580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Critical CSS Core logic:
4
+ * gets called by AO core, checks the rules and if a matching rule is found returns the associated CCSS.
5
+ */
6
+
7
+ if ( ! defined( 'ABSPATH' ) ) {
8
+ exit;
9
+ }
10
+
11
+ class autoptimizeCriticalCSSCore {
12
+ public function __construct()
13
+ {
14
+ // fetch all options at once and populate them individually explicitely as globals.
15
+ $all_options = autoptimizeCriticalCSSBase::fetch_options();
16
+ foreach ( $all_options as $_option => $_value ) {
17
+ global ${$_option};
18
+ ${$_option} = $_value;
19
+ }
20
+
21
+ $this->run();
22
+ }
23
+
24
+ public function run() {
25
+ global $ao_css_defer;
26
+ global $ao_ccss_deferjquery;
27
+ global $ao_ccss_key;
28
+
29
+ // add all filters to do CCSS if key present.
30
+ if ( $ao_css_defer && isset( $ao_ccss_key ) && ! empty( $ao_ccss_key ) ) {
31
+ // Set AO behavior: disable minification to avoid double minifying and caching.
32
+ add_filter( 'autoptimize_filter_css_critcss_minify', '__return_false' );
33
+ add_filter( 'autoptimize_filter_css_defer_inline', array( $this, 'ao_ccss_frontend' ), 10, 1 );
34
+
35
+ // Add the action to enqueue jobs for CriticalCSS cron.
36
+ add_action( 'autoptimize_action_css_hash', array( 'autoptimizeCriticalCSSEnqueue', 'ao_ccss_enqueue' ), 10, 1 );
37
+
38
+ // conditionally add the filter to defer jquery and others.
39
+ if ( $ao_ccss_deferjquery ) {
40
+ add_filter( 'autoptimize_html_after_minify', array( $this, 'ao_ccss_defer_jquery' ), 11, 1 );
41
+ }
42
+
43
+ // Order paths by length, as longest ones have greater priority in the rules.
44
+ if ( ! empty( $ao_ccss_rules['paths'] ) ) {
45
+ $keys = array_map( 'strlen', array_keys( $ao_ccss_rules['paths'] ) );
46
+ array_multisort( $keys, SORT_DESC, $ao_ccss_rules['paths'] );
47
+ }
48
+
49
+ // Add an array with default WordPress's conditional tags
50
+ // NOTE: these tags are sorted.
51
+ global $ao_ccss_types;
52
+ $ao_ccss_types = $this->get_ao_ccss_core_types();
53
+
54
+ // Extend conditional tags on plugin initalization.
55
+ add_action( apply_filters( 'autoptimize_filter_ccss_extend_types_hook', 'init' ), array( $this, 'ao_ccss_extend_types' ) );
56
+ }
57
+ }
58
+
59
+ public function ao_ccss_frontend( $inlined ) {
60
+ // Apply CriticalCSS to frontend pages
61
+ // Attach types and settings arrays.
62
+ global $ao_ccss_types;
63
+ global $ao_ccss_rules;
64
+ global $ao_ccss_additional;
65
+ global $ao_ccss_loggedin;
66
+ global $ao_ccss_debug;
67
+ global $ao_ccss_keyst;
68
+ $no_ccss = '';
69
+
70
+ // Only if keystatus is OK and option to add CCSS for logged on users is on or user is not logged in.
71
+ if ( ( $ao_ccss_keyst && 2 == $ao_ccss_keyst ) && ( $ao_ccss_loggedin || ! is_user_logged_in() ) ) {
72
+ // Check for a valid CriticalCSS based on path to return its contents.
73
+ $req_path = strtok( urldecode( $_SERVER['REQUEST_URI'] ), '?' );
74
+ if ( ! empty( $ao_ccss_rules['paths'] ) ) {
75
+ foreach ( $ao_ccss_rules['paths'] as $path => $rule ) {
76
+ // explicit match OR partial match if MANUAL rule.
77
+ if ( $req_path == $path || ( false == $rule['hash'] && false != $rule['file'] && strpos( $req_path, str_replace( site_url(), '', $path ) ) !== false ) ) {
78
+ if ( file_exists( AO_CCSS_DIR . $rule['file'] ) ) {
79
+ $_ccss_contents = file_get_contents( AO_CCSS_DIR . $rule['file'] );
80
+ if ( 'none' != $_ccss_contents ) {
81
+ if ( $ao_ccss_debug ) {
82
+ $_ccss_contents = '/* PATH: ' . $path . ' hash: ' . $rule['hash'] . ' file: ' . $rule['file'] . ' */ ' . $_ccss_contents;
83
+ }
84
+ return apply_filters( 'autoptimize_filter_ccss_core_ccss', $_ccss_contents . $ao_ccss_additional );
85
+ } else {
86
+ $no_ccss = 'none';
87
+ }
88
+ }
89
+ }
90
+ }
91
+ }
92
+
93
+ // Check for a valid CriticalCSS based on conditional tags to return its contents.
94
+ if ( ! empty( $ao_ccss_rules['types'] ) && 'none' !== $no_ccss ) {
95
+ // order types-rules by the order of the original $ao_ccss_types array so as not to depend on the order in which rules were added.
96
+ $ao_ccss_rules['types'] = array_replace( array_intersect_key( array_flip( $ao_ccss_types ), $ao_ccss_rules['types'] ), $ao_ccss_rules['types'] );
97
+ $is_front_page = is_front_page();
98
+
99
+ foreach ( $ao_ccss_rules['types'] as $type => $rule ) {
100
+ if ( in_array( $type, $ao_ccss_types ) && file_exists( AO_CCSS_DIR . $rule['file'] ) ) {
101
+ $_ccss_contents = file_get_contents( AO_CCSS_DIR . $rule['file'] );
102
+ if ( $is_front_page && 'is_front_page' == $type ) {
103
+ if ( 'none' != $_ccss_contents ) {
104
+ if ( $ao_ccss_debug ) {
105
+ $_ccss_contents = '/* TYPES: ' . $type . ' hash: ' . $rule['hash'] . ' file: ' . $rule['file'] . ' */ ' . $_ccss_contents;
106
+ }
107
+ return apply_filters( 'autoptimize_filter_ccss_core_ccss', $_ccss_contents . $ao_ccss_additional );
108
+ } else {
109
+ $no_ccss = 'none';
110
+ }
111
+ } elseif ( strpos( $type, 'custom_post_' ) === 0 && ! $is_front_page ) {
112
+ if ( get_post_type( get_the_ID() ) === substr( $type, 12 ) ) {
113
+ if ( 'none' != $_ccss_contents ) {
114
+ if ( $ao_ccss_debug ) {
115
+ $_ccss_contents = '/* TYPES: ' . $type . ' hash: ' . $rule['hash'] . ' file: ' . $rule['file'] . ' */ ' . $_ccss_contents;
116
+ }
117
+ return apply_filters( 'autoptimize_filter_ccss_core_ccss', $_ccss_contents . $ao_ccss_additional );
118
+ } else {
119
+ $no_ccss = 'none';
120
+ }
121
+ }
122
+ } elseif ( 0 === strpos( $type, 'template_' ) && ! $is_front_page ) {
123
+ if ( is_page_template( substr( $type, 9 ) ) ) {
124
+ if ( 'none' != $_ccss_contents ) {
125
+ if ( $ao_ccss_debug ) {
126
+ $_ccss_contents = '/* TYPES: ' . $type . ' hash: ' . $rule['hash'] . ' file: ' . $rule['file'] . ' */ ' . $_ccss_contents;
127
+ }
128
+ return apply_filters( 'autoptimize_filter_ccss_core_ccss', $_ccss_contents . $ao_ccss_additional );
129
+ } else {
130
+ $no_ccss = 'none';
131
+ }
132
+ }
133
+ } elseif ( ! $is_front_page ) {
134
+ // all "normal" conditional tags, core + woo + buddypress + edd + bbpress
135
+ // but we have to remove the prefix for the non-core ones for them to function.
136
+ $type = str_replace( array( 'woo_', 'bp_', 'bbp_', 'edd_' ), '', $type );
137
+ if ( function_exists( $type ) && call_user_func( $type ) ) {
138
+ if ( 'none' != $_ccss_contents ) {
139
+ if ( $ao_ccss_debug ) {
140
+ $_ccss_contents = '/* TYPES: ' . $type . ' hash: ' . $rule['hash'] . ' file: ' . $rule['file'] . ' */ ' . $_ccss_contents;
141
+ }
142
+ return apply_filters( 'autoptimize_filter_ccss_core_ccss', $_ccss_contents . $ao_ccss_additional );
143
+ } else {
144
+ $no_ccss = 'none';
145
+ }
146
+ }
147
+ }
148
+ }
149
+ }
150
+ }
151
+ }
152
+
153
+ // Finally, inline the default CriticalCSS if any or else the entire CSS for the page
154
+ // This also applies to logged in users if the option to add CCSS for logged in users has been disabled.
155
+ if ( ! empty( $inlined ) && 'none' !== $no_ccss ) {
156
+ return apply_filters( 'autoptimize_filter_ccss_core_ccss', $inlined . $ao_ccss_additional );
157
+ } else {
158
+ add_filter( 'autoptimize_filter_css_inline', '__return_true' );
159
+ return;
160
+ }
161
+ }
162
+
163
+ public function ao_ccss_defer_jquery( $in ) {
164
+ // try to defer all JS (main goal being jquery.js as AO by default does not aggregate that).
165
+ if ( ( ! is_user_logged_in() || $ao_ccss_loggedin ) && preg_match_all( '#<script.*>(.*)</script>#Usmi', $in, $matches, PREG_SET_ORDER ) ) {
166
+ foreach ( $matches as $match ) {
167
+ if ( ( ! preg_match( '/<script.* type\s?=.*>/', $match[0] ) || preg_match( '/type\s*=\s*[\'"]?(?:text|application)\/(?:javascript|ecmascript)[\'"]?/i', $match[0] ) ) && '' !== $match[1] && ( false !== strpos( $match[1], 'jQuery' ) || false !== strpos( $match[1], '$' ) ) ) {
168
+ // inline js that requires jquery, wrap deferring JS around it to defer it.
169
+ $new_match = 'var aoDeferInlineJQuery=function(){' . $match[1] . '}; if (document.readyState === "loading") {document.addEventListener("DOMContentLoaded", aoDeferInlineJQuery);} else {aoDeferInlineJQuery();}';
170
+ $in = str_replace( $match[1], $new_match, $in );
171
+ } elseif ( '' === $match[1] && false !== strpos( $match[0], 'src=' ) && false === strpos( $match[0], 'defer' ) ) {
172
+ // linked non-aggregated JS, defer it.
173
+ $new_match = str_replace( '<script ', '<script defer ', $match[0] );
174
+ $in = str_replace( $match[0], $new_match, $in );
175
+ }
176
+ }
177
+ }
178
+ return $in;
179
+ }
180
+
181
+ public function ao_ccss_extend_types() {
182
+ // Extend contidional tags
183
+ // Attach the conditional tags array.
184
+ global $ao_ccss_types;
185
+
186
+ // in some cases $ao_ccss_types is empty and/or not an array, this should work around that problem.
187
+ if ( empty( $ao_ccss_types ) || ! is_array( $ao_ccss_types ) ) {
188
+ $ao_ccss_types = get_ao_ccss_core_types();
189
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Empty types array in extend, refetching array with core conditionals.', 3 );
190
+ }
191
+
192
+ // Custom Post Types.
193
+ $cpts = get_post_types(
194
+ array(
195
+ 'public' => true,
196
+ '_builtin' => false,
197
+ ),
198
+ 'names',
199
+ 'and'
200
+ );
201
+ foreach ( $cpts as $cpt ) {
202
+ array_unshift( $ao_ccss_types, 'custom_post_' . $cpt );
203
+ }
204
+
205
+ // Templates.
206
+ $templates = wp_get_theme()->get_page_templates();
207
+ foreach ( $templates as $tplfile => $tplname ) {
208
+ array_unshift( $ao_ccss_types, 'template_' . $tplfile );
209
+ }
210
+
211
+ // bbPress tags.
212
+ if ( function_exists( 'is_bbpress' ) ) {
213
+ $ao_ccss_types = array_merge(
214
+ array(
215
+ 'bbp_is_bbpress',
216
+ 'bbp_is_favorites',
217
+ 'bbp_is_forum_archive',
218
+ 'bbp_is_replies_created',
219
+ 'bbp_is_reply_edit',
220
+ 'bbp_is_reply_move',
221
+ 'bbp_is_search',
222
+ 'bbp_is_search_results',
223
+ 'bbp_is_single_forum',
224
+ 'bbp_is_single_reply',
225
+ 'bbp_is_single_topic',
226
+ 'bbp_is_single_user',
227
+ 'bbp_is_single_user_edit',
228
+ 'bbp_is_single_view',
229
+ 'bbp_is_subscriptions',
230
+ 'bbp_is_topic_archive',
231
+ 'bbp_is_topic_edit',
232
+ 'bbp_is_topic_merge',
233
+ 'bbp_is_topic_split',
234
+ 'bbp_is_topic_tag',
235
+ 'bbp_is_topic_tag_edit',
236
+ 'bbp_is_topics_created',
237
+ 'bbp_is_user_home',
238
+ 'bbp_is_user_home_edit',
239
+ ), $ao_ccss_types
240
+ );
241
+ }
242
+
243
+ // BuddyPress tags.
244
+ if ( function_exists( 'is_buddypress' ) ) {
245
+ $ao_ccss_types = array_merge(
246
+ array(
247
+ 'bp_is_activation_page',
248
+ 'bp_is_activity',
249
+ 'bp_is_blogs',
250
+ 'bp_is_buddypress',
251
+ 'bp_is_change_avatar',
252
+ 'bp_is_create_blog',
253
+ 'bp_is_friend_requests',
254
+ 'bp_is_friends',
255
+ 'bp_is_friends_activity',
256
+ 'bp_is_friends_screen',
257
+ 'bp_is_group_admin_page',
258
+ 'bp_is_group_create',
259
+ 'bp_is_group_forum',
260
+ 'bp_is_group_forum_topic',
261
+ 'bp_is_group_home',
262
+ 'bp_is_group_invites',
263
+ 'bp_is_group_leave',
264
+ 'bp_is_group_members',
265
+ 'bp_is_group_single',
266
+ 'bp_is_groups',
267
+ 'bp_is_messages',
268
+ 'bp_is_messages_compose_screen',
269
+ 'bp_is_messages_conversation',
270
+ 'bp_is_messages_inbox',
271
+ 'bp_is_messages_sentbox',
272
+ 'bp_is_my_activity',
273
+ 'bp_is_my_blogs',
274
+ 'bp_is_notices',
275
+ 'bp_is_profile_edit',
276
+ 'bp_is_register_page',
277
+ 'bp_is_settings_component',
278
+ 'bp_is_user',
279
+ 'bp_is_user_profile',
280
+ 'bp_is_wire',
281
+ ), $ao_ccss_types
282
+ );
283
+ }
284
+
285
+ // Easy Digital Downloads (EDD) tags.
286
+ if ( function_exists( 'edd_is_checkout' ) ) {
287
+ $ao_ccss_types = array_merge(
288
+ array(
289
+ 'edd_is_checkout',
290
+ 'edd_is_failed_transaction_page',
291
+ 'edd_is_purchase_history_page',
292
+ 'edd_is_success_page',
293
+ ), $ao_ccss_types
294
+ );
295
+ }
296
+
297
+ // WooCommerce tags.
298
+ if ( class_exists( 'WooCommerce' ) ) {
299
+ $ao_ccss_types = array_merge(
300
+ array(
301
+ 'woo_is_account_page',
302
+ 'woo_is_cart',
303
+ 'woo_is_checkout',
304
+ 'woo_is_product',
305
+ 'woo_is_product_category',
306
+ 'woo_is_product_tag',
307
+ 'woo_is_shop',
308
+ 'woo_is_wc_endpoint_url',
309
+ 'woo_is_woocommerce',
310
+ ), $ao_ccss_types
311
+ );
312
+ }
313
+ }
314
+
315
+ public function get_ao_ccss_core_types() {
316
+ global $ao_ccss_types;
317
+ if ( empty( $ao_ccss_types ) || ! is_array( $ao_ccss_types ) ) {
318
+ return array(
319
+ 'is_404',
320
+ 'is_archive',
321
+ 'is_author',
322
+ 'is_category',
323
+ 'is_front_page',
324
+ 'is_home',
325
+ 'is_page',
326
+ 'is_post',
327
+ 'is_search',
328
+ 'is_attachment',
329
+ 'is_single',
330
+ 'is_sticky',
331
+ 'is_paged',
332
+ );
333
+ } else {
334
+ return $ao_ccss_types;
335
+ }
336
+ }
337
+
338
+ public static function ao_ccss_key_status( $render ) {
339
+ // Provide key status
340
+ // Get key and key status.
341
+ global $ao_ccss_key;
342
+ global $ao_ccss_keyst;
343
+ $self = new self();
344
+ $key = $ao_ccss_key;
345
+ $key_status = $ao_ccss_keyst;
346
+
347
+ // Prepare returned variables.
348
+ $key_return = array();
349
+ $status = false;
350
+
351
+ if ( $key && 2 == $key_status ) {
352
+ // Key exists and its status is valid.
353
+ // Set valid key status.
354
+ $status = 'valid';
355
+ $status_msg = __( 'Valid' );
356
+ $color = '#46b450'; // Green.
357
+ $message = null;
358
+ } elseif ( $key && 1 == $key_status ) {
359
+ // Key exists but its validation has failed.
360
+ // Set invalid key status.
361
+ $status = 'invalid';
362
+ $status_msg = __( 'Invalid' );
363
+ $color = '#dc3232'; // Red.
364
+ $message = __( 'Your API key is invalid. Please enter a valid <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> key.', 'autoptimize' );
365
+ } elseif ( $key && ! $key_status ) {
366
+ // Key exists but it has no valid status yet
367
+ // Perform key validation.
368
+ $key_check = $self->ao_ccss_key_validation( $key );
369
+
370
+ // Key is valid, set valid status.
371
+ if ( $key_check ) {
372
+ $status = 'valid';
373
+ $status_msg = __( 'Valid' );
374
+ $color = '#46b450'; // Green.
375
+ $message = null;
376
+ } else {
377
+ // Key is invalid, set invalid status.
378
+ $status = 'invalid';
379
+ $status_msg = __( 'Invalid' );
380
+ $color = '#dc3232'; // Red.
381
+ if ( get_option( 'autoptimize_ccss_keyst' ) == 1 ) {
382
+ $message = __( 'Your API key is invalid. Please enter a valid <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> key.', 'autoptimize' );
383
+ } else {
384
+ $message = __( 'Something went wrong when checking your API key, make sure you server can communicate with https://criticalcss.com and/ or try again later.', 'autoptimize' );
385
+ }
386
+ }
387
+ } else {
388
+ // No key nor status
389
+ // Set no key status.
390
+ $status = 'nokey';
391
+ $status_msg = __( 'None' );
392
+ $color = '#ffb900'; // Yellow.
393
+ $message = __( 'Please enter a valid <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> API key to start.', 'autoptimize' );
394
+ }
395
+
396
+ // Fill returned values.
397
+ $key_return['status'] = $status;
398
+ // Provide rendering information if required.
399
+ if ( $render ) {
400
+ $key_return['stmsg'] = $status_msg;
401
+ $key_return['color'] = $color;
402
+ $key_return['msg'] = $message;
403
+ }
404
+
405
+ // Return key status.
406
+ return $key_return;
407
+ }
408
+
409
+ public function ao_ccss_key_validation( $key ) {
410
+ // POST a dummy job to criticalcss.com to check for key validation
411
+ // Prepare home URL for the request.
412
+ $src_url = get_home_url();
413
+ $src_url = apply_filters( 'autoptimize_filter_ccss_cron_srcurl', $src_url );
414
+
415
+ // Prepare the request.
416
+ $url = esc_url_raw( AO_CCSS_API . 'generate' );
417
+ $args = array(
418
+ 'headers' => array(
419
+ 'User-Agent' => 'Autoptimize CriticalCSS Power-Up v' . AO_CCSS_VER,
420
+ 'Content-type' => 'application/json; charset=utf-8',
421
+ 'Authorization' => 'JWT ' . $key,
422
+ 'Connection' => 'close',
423
+ ),
424
+ // Body must be JSON.
425
+ 'body' => json_encode(
426
+ array(
427
+ 'url' => $src_url,
428
+ 'aff' => 1,
429
+ 'aocssv' => AO_CCSS_VER,
430
+ )
431
+ ),
432
+ );
433
+
434
+ // Dispatch the request and store its response code.
435
+ $req = wp_safe_remote_post( $url, $args );
436
+ $code = wp_remote_retrieve_response_code( $req );
437
+ $body = json_decode( wp_remote_retrieve_body( $req ), true );
438
+
439
+ if ( 200 == $code ) {
440
+ // Response is OK.
441
+ // Set key status as valid and log key check.
442
+ update_option( 'autoptimize_ccss_keyst', 2 );
443
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: API key is valid, updating key status', 3 );
444
+
445
+ // extract job-id from $body and put it in the queue as a P job
446
+ // but only if no jobs and no rules!
447
+ global $ao_ccss_queue;
448
+ global $ao_ccss_rules;
449
+
450
+ if ( 0 == count( $ao_ccss_queue ) && 0 == count( $ao_ccss_rules['types'] ) && 0 == count( $ao_ccss_rules['paths'] ) ) {
451
+ if ( 'JOB_QUEUED' == $body['job']['status'] || 'JOB_ONGOING' == $body['job']['status'] ) {
452
+ $jprops['ljid'] = 'firstrun';
453
+ $jprops['rtarget'] = 'types|is_front_page';
454
+ $jprops['ptype'] = 'is_front_page';
455
+ $jprops['hashes'][] = 'dummyhash';
456
+ $jprops['hash'] = 'dummyhash';
457
+ $jprops['file'] = null;
458
+ $jprops['jid'] = $body['job']['id'];
459
+ $jprops['jqstat'] = $body['job']['status'];
460
+ $jprops['jrstat'] = null;
461
+ $jprops['jvstat'] = null;
462
+ $jprops['jctime'] = microtime( true );
463
+ $jprops['jftime'] = null;
464
+ $ao_ccss_queue['/'] = $jprops;
465
+ $ao_ccss_queue_raw = json_encode( $ao_ccss_queue );
466
+ update_option( 'autoptimize_ccss_queue', $ao_ccss_queue_raw, false );
467
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Created P job for is_front_page based on API key check response.', 3 );
468
+ }
469
+ }
470
+ return true;
471
+ } elseif ( 401 == $code ) {
472
+ // Response is unauthorized
473
+ // Set key status as invalid and log key check.
474
+ update_option( 'autoptimize_ccss_keyst', 1 );
475
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: API key is invalid, updating key status', 3 );
476
+ return false;
477
+ } else {
478
+ // Response unkown
479
+ // Log key check attempt.
480
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: could not check API key status, this is a service error, body follows if any...', 2 );
481
+ if ( ! empty( $body ) ) {
482
+ autoptimizeCriticalCSSCore::ao_ccss_log( print_r( $body, true ), 2 );
483
+ }
484
+ if ( is_wp_error( $req ) ) {
485
+ autoptimizeCriticalCSSCore::ao_ccss_log( $req->get_error_message(), 2 );
486
+ }
487
+ return false;
488
+ }
489
+ }
490
+
491
+ public static function ao_ccss_viewport() {
492
+ // Get viewport size
493
+ // Attach viewport option.
494
+ global $ao_ccss_viewport;
495
+
496
+ // Prepare viewport array.
497
+ $viewport = array();
498
+
499
+ // Viewport Width.
500
+ if ( ! empty( $ao_ccss_viewport['w'] ) ) {
501
+ $viewport['w'] = $ao_ccss_viewport['w'];
502
+ } else {
503
+ $viewport['w'] = '';
504
+ }
505
+
506
+ // Viewport Height.
507
+ if ( ! empty( $ao_ccss_viewport['h'] ) ) {
508
+ $viewport['h'] = $ao_ccss_viewport['h'];
509
+ } else {
510
+ $viewport['h'] = '';
511
+ }
512
+
513
+ return $viewport;
514
+ }
515
+
516
+ public static function ao_ccss_check_contents( $ccss ) {
517
+ // Perform basic exploit avoidance and CSS validation.
518
+ if ( ! empty( $ccss ) ) {
519
+ // Try to avoid code injection.
520
+ $blacklist = array( '#!/', 'function(', '<script', '<?php' );
521
+ foreach ( $blacklist as $blacklisted ) {
522
+ if ( strpos( $ccss, $blacklisted ) !== false ) {
523
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Critical CSS received contained blacklisted content.', 2 );
524
+ return false;
525
+ }
526
+ }
527
+
528
+ // Check for most basics CSS structures.
529
+ $pinklist = array( '{', '}', ':' );
530
+ foreach ( $pinklist as $needed ) {
531
+ if ( false === strpos( $ccss, $needed ) && 'none' !== $ccss ) {
532
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Critical CSS received did not seem to contain real CSS.', 2 );
533
+ return false;
534
+ }
535
+ }
536
+ }
537
+
538
+ // Return true if file critical CSS is sane.
539
+ return true;
540
+ }
541
+
542
+ public static function ao_ccss_log( $msg, $lvl ) {
543
+ // Commom logging facility
544
+ // Attach debug option.
545
+ global $ao_ccss_debug;
546
+
547
+ // Prepare log levels, where accepted $lvl are:
548
+ // 1: II (for info)
549
+ // 2: EE (for error)
550
+ // 3: DD (for debug)
551
+ // Default: UU (for unkown).
552
+ $level = false;
553
+ switch ( $lvl ) {
554
+ case 1:
555
+ $level = 'II';
556
+ break;
557
+ case 2:
558
+ $level = 'EE';
559
+ break;
560
+ case 3:
561
+ // Output debug messages only if debug mode is enabled.
562
+ if ( $ao_ccss_debug ) {
563
+ $level = 'DD';
564
+ }
565
+ break;
566
+ default:
567
+ $level = 'UU';
568
+ }
569
+
570
+ // Prepare and write a log message if there's a valid level.
571
+ if ( $level ) {
572
+
573
+ // Prepare message.
574
+ $message = date( 'c' ) . ' - [' . $level . '] ' . htmlentities( $msg ) . '<br>';
575
+
576
+ // Write message to log file.
577
+ error_log( $message, 3, AO_CCSS_LOG );
578
+ }
579
+ }
580
+ }
classes/autoptimizeCriticalCSSCron.php ADDED
@@ -0,0 +1,829 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Critical CSS Cron logic:
4
+ * processes the queue, submitting jobs to criticalcss.com and retrieving generated CSS from criticalcss.com and saving rules.
5
+ */
6
+
7
+ if ( ! defined( 'ABSPATH' ) ) {
8
+ exit;
9
+ }
10
+
11
+ class autoptimizeCriticalCSSCron {
12
+ public function __construct()
13
+ {
14
+ // fetch all options at once and populate them individually explicitely as globals.
15
+ $all_options = autoptimizeCriticalCSSBase::fetch_options();
16
+ foreach ( $all_options as $_option => $_value ) {
17
+ global ${$_option};
18
+ ${$_option} = $_value;
19
+ }
20
+
21
+ // Add queue control to a registered event.
22
+ add_action( 'ao_ccss_queue', array( $this, 'ao_ccss_queue_control' ) );
23
+ // Add cleaning job to a registered event.
24
+ add_action( 'ao_ccss_maintenance', array( $this, 'ao_ccss_cleaning' ) );
25
+ }
26
+
27
+ public function ao_ccss_queue_control() {
28
+ // The queue execution backend.
29
+ global $ao_ccss_key;
30
+ if ( ! isset( $ao_ccss_key ) || empty( $ao_ccss_key ) ) {
31
+ // no key set, not processing the queue!
32
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'No key set, so not processing queue.', 3 );
33
+ return;
34
+ }
35
+
36
+ /**
37
+ * Provide a debug facility for the queue
38
+ * This debug facility provides a way to easily force some queue behaviors useful for development and testing.
39
+ * To enable this feature, create the file AO_CCSS_DIR . 'queue.json' with a JSON object like the one bellow:
40
+ *
41
+ * {"enable":bool,"htcode":int,"status":0|"str","resultStatus ":0|"str","validationStatus":0|"str"}
42
+ *
43
+ * Where values are:
44
+ * - enable : 0 or 1, enable or disable this debug facility straight from the file
45
+ * - htcode : 0 or any HTTP reponse code (e.g. 2xx, 4xx, 5xx) to force API responses
46
+ * - status : 0 or a valid value for 'status' (see 'Generating critical css - Job Status Types' in spec docs)
47
+ * - resultStatus : 0 or a valid value for 'resultStatus' (see 'Appendix - Result status types' in the spec docs)
48
+ * - validationStatus: 0 or a valid value for 'validationStatus' (see 'Appendix - Validation status types' in the spec docs)
49
+ *
50
+ * When properly set, queue will always finish a job with the declared settings above regardless of the real API responses.
51
+ */
52
+ $queue_debug = false;
53
+ if ( file_exists( AO_CCSS_DEBUG ) ) {
54
+ $qdobj_raw = file_get_contents( AO_CCSS_DEBUG );
55
+ $qdobj = json_decode( $qdobj_raw, true );
56
+ if ( $qdobj ) {
57
+ if ( 1 === $qdobj['enable'] ) {
58
+ $queue_debug = true;
59
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Queue operating in debug mode with the following settings: <' . $qdobj_raw . '>', 3 );
60
+ }
61
+ }
62
+ }
63
+
64
+ // Set some default values for $qdobj to avoid function call warnings.
65
+ if ( ! $queue_debug ) {
66
+ $qdobj['htcode'] = false;
67
+ }
68
+
69
+ // Check if queue is already running.
70
+ $queue_lock = false;
71
+ if ( file_exists( AO_CCSS_LOCK ) ) {
72
+ $queue_lock = true;
73
+ }
74
+
75
+ // Proceed with the queue if it's not already running.
76
+ if ( ! $queue_lock ) {
77
+
78
+ // Log queue start and create the lock file.
79
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Queue control started', 3 );
80
+ if ( touch( AO_CCSS_LOCK ) ) {
81
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Queue control locked', 3 );
82
+ }
83
+
84
+ // Attach required variables.
85
+ global $ao_ccss_queue;
86
+ global $ao_ccss_rlimit;
87
+
88
+ // Initialize job counters.
89
+ $jc = 1;
90
+ $jr = 1;
91
+ $jt = count( $ao_ccss_queue );
92
+
93
+ // Sort queue by ascending job status (e.g. ERROR, JOB_ONGOING, JOB_QUEUED, NEW...).
94
+ array_multisort( array_column( $ao_ccss_queue, 'jqstat' ), $ao_ccss_queue ); // @codingStandardsIgnoreLine
95
+
96
+ // Iterates over the entire queue.
97
+ foreach ( $ao_ccss_queue as $path => $jprops ) {
98
+ // Prepare flags and target rule.
99
+ $update = false;
100
+ $deljob = false;
101
+ $rule_update = false;
102
+ $oldccssfile = false;
103
+ $trule = explode( '|', $jprops['rtarget'] );
104
+
105
+ // Log job count.
106
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Processing job ' . $jc . ' of ' . $jt . ' with id <' . $jprops['ljid'] . '> and status <' . $jprops['jqstat'] . '>', 3 );
107
+
108
+ // Process NEW jobs.
109
+ if ( 'NEW' == $jprops['jqstat'] ) {
110
+
111
+ // Log the new job.
112
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Found NEW job with local ID <' . $jprops['ljid'] . '>, starting its queue processing', 3 );
113
+
114
+ // Compare job and rule hashes (if any).
115
+ $hash = $this->ao_ccss_diff_hashes( $jprops['ljid'], $jprops['hash'], $jprops['hashes'], $jprops['rtarget'] );
116
+
117
+ // If job hash is new or different of a previous one.
118
+ if ( $hash ) {
119
+ // Set job hash.
120
+ $jprops['hash'] = $hash;
121
+
122
+ // If this is not the first job, wait 15 seconds before process next job due criticalcss.com API limits.
123
+ if ( $jr > 1 ) {
124
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Waiting 15 seconds due to criticalcss.com API limits', 3 );
125
+ sleep( 15 );
126
+ }
127
+
128
+ // Dispatch the job generate request and increment request count.
129
+ $apireq = $this->ao_ccss_api_generate( $path, $queue_debug, $qdobj['htcode'] );
130
+ $jr++;
131
+
132
+ // NOTE: All the following conditions maps to the ones in admin_settings_queue.js.php.
133
+ if ( 'JOB_QUEUED' == $apireq['job']['status'] || 'JOB_ONGOING' == $apireq['job']['status'] ) {
134
+ // SUCCESS: request has a valid result.
135
+ // Update job properties.
136
+ $jprops['jid'] = $apireq['job']['id'];
137
+ $jprops['jqstat'] = $apireq['job']['status'];
138
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> generate request successful, remote id <' . $jprops['jid'] . '>, status now is <' . $jprops['jqstat'] . '>', 3 );
139
+ } elseif ( 'STATUS_JOB_BAD' == $apireq['job']['status'] ) {
140
+ // ERROR: concurrent requests
141
+ // Update job properties.
142
+ $jprops['jid'] = $apireq['job']['id'];
143
+ $jprops['jqstat'] = $apireq['job']['status'];
144
+ $jprops['jrstat'] = $apireq['error'];
145
+ $jprops['jvstat'] = 'NONE';
146
+ $jprops['jftime'] = microtime( true );
147
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Concurrent requests when processing job id <' . $jprops['ljid'] . '>, job status is now <' . $jprops['jqstat'] . '>', 3 );
148
+ } elseif ( 'INVALID_JWT_TOKEN' == $apireq['errorCode'] ) {
149
+ // ERROR: key validation
150
+ // Update job properties.
151
+ $jprops['jqstat'] = $apireq['errorCode'];
152
+ $jprops['jrstat'] = $apireq['error'];
153
+ $jprops['jvstat'] = 'NONE';
154
+ $jprops['jftime'] = microtime( true );
155
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'API key validation error when processing job id <' . $jprops['ljid'] . '>, job status is now <' . $jprops['jqstat'] . '>', 3 );
156
+ } elseif ( empty( $apireq ) ) {
157
+ // ERROR: no response
158
+ // Update job properties.
159
+ $jprops['jqstat'] = 'NO_RESPONSE';
160
+ $jprops['jrstat'] = 'NONE';
161
+ $jprops['jvstat'] = 'NONE';
162
+ $jprops['jftime'] = microtime( true );
163
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> request has no response, status now is <' . $jprops['jqstat'] . '>', 3 );
164
+ } else {
165
+ // UNKNOWN: unhandled generate exception
166
+ // Update job properties.
167
+ $jprops['jqstat'] = 'JOB_UNKNOWN';
168
+ $jprops['jrstat'] = 'NONE';
169
+ $jprops['jvstat'] = 'NONE';
170
+ $jprops['jftime'] = microtime( true );
171
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> generate request has an UNKNOWN condition, status now is <' . $jprops['jqstat'] . '>, check log messages above for more information', 2 );
172
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job response was: ' . json_encode( $apireq ), 3 );
173
+ }
174
+ } else {
175
+ // SUCCESS: Job hash is equal to a previous one, so it's done
176
+ // Update job status and finish time.
177
+ $jprops['jqstat'] = 'JOB_DONE';
178
+ $jprops['jftime'] = microtime( true );
179
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> requires no further processing, status now is <' . $jprops['jqstat'] . '>', 3 );
180
+ }
181
+
182
+ // Set queue update flag.
183
+ $update = true;
184
+
185
+ } elseif ( 'JOB_QUEUED' == $jprops['jqstat'] || 'JOB_ONGOING' == $jprops['jqstat'] ) {
186
+ // Process QUEUED and ONGOING jobs
187
+ // Log the pending job.
188
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Found PENDING job with local ID <' . $jprops['ljid'] . '>, continuing its queue processing', 3 );
189
+
190
+ // If this is not the first job, wait 15 seconds before process next job due criticalcss.com API limits.
191
+ if ( $jr > 1 ) {
192
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Waiting 15 seconds due to criticalcss.com API limits', 3 );
193
+ sleep( 15 );
194
+ }
195
+
196
+ // Dispatch the job result request and increment request count.
197
+ $apireq = $this->ao_ccss_api_results( $jprops['jid'], $queue_debug, $qdobj['htcode'] );
198
+ $jr++;
199
+
200
+ // NOTE: All the following condigitons maps to the ones in admin_settings_queue.js.php
201
+ // Replace API response values if queue debugging is enabled and some value is set.
202
+ if ( $queue_debug ) {
203
+ if ( $qdobj['status'] ) {
204
+ $apireq['status'] = $qdobj['status'];
205
+ }
206
+ if ( $qdobj['resultStatus'] ) {
207
+ $apireq['resultStatus'] = $qdobj['resultStatus'];
208
+ }
209
+ if ( $qdobj['validationStatus'] ) {
210
+ $apireq['validationStatus'] = $qdobj['validationStatus'];
211
+ }
212
+ }
213
+
214
+ if ( 'JOB_QUEUED' == $apireq['status'] || 'JOB_ONGOING' == $apireq['status'] ) {
215
+ // SUCCESS: request has a valid result
216
+ // Process a PENDING job
217
+ // Update job properties.
218
+ $jprops['jqstat'] = $apireq['status'];
219
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> result request successful, remote id <' . $jprops['jid'] . '>, status <' . $jprops['jqstat'] . '> unchanged', 3 );
220
+ } elseif ( 'JOB_DONE' == $apireq['status'] ) {
221
+ // Process a DONE job
222
+ // New resultStatus from ccss.com "HTML_404", consider as "GOOD" for now.
223
+ if ( 'HTML_404' == $apireq['resultStatus'] ) {
224
+ $apireq['resultStatus'] = 'GOOD';
225
+ }
226
+
227
+ if ( 'GOOD' == $apireq['resultStatus'] && 'GOOD' == $apireq['validationStatus'] ) {
228
+ // SUCCESS: GOOD job with GOOD validation
229
+ // Update job properties.
230
+ $jprops['file'] = $this->ao_ccss_save_file( $apireq['css'], $trule, false );
231
+ $jprops['jqstat'] = $apireq['status'];
232
+ $jprops['jrstat'] = $apireq['resultStatus'];
233
+ $jprops['jvstat'] = $apireq['validationStatus'];
234
+ $jprops['jftime'] = microtime( true );
235
+ $rule_update = true;
236
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> result request successful, remote id <' . $jprops['jid'] . '>, status <' . $jprops['jqstat'] . '>, file saved <' . $jprops['file'] . '>', 3 );
237
+ } elseif ( 'GOOD' == $apireq['resultStatus'] && ( 'WARN' == $apireq['validationStatus'] || 'BAD' == $apireq['validationStatus'] || 'SCREENSHOT_WARN_BLANK' == $apireq['validationStatus'] ) ) {
238
+ // SUCCESS: GOOD job with WARN or BAD validation
239
+ // Update job properties.
240
+ $jprops['file'] = $this->ao_ccss_save_file( $apireq['css'], $trule, true );
241
+ $jprops['jqstat'] = $apireq['status'];
242
+ $jprops['jrstat'] = $apireq['resultStatus'];
243
+ $jprops['jvstat'] = $apireq['validationStatus'];
244
+ $jprops['jftime'] = microtime( true );
245
+ $rule_update = true;
246
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> result request successful, remote id <' . $jprops['jid'] . '>, status <' . $jprops['jqstat'] . ', file saved <' . $jprops['file'] . '> but requires REVIEW', 3 );
247
+ } elseif ( 'GOOD' != $apireq['resultStatus'] && ( 'GOOD' != $apireq['validationStatus'] || 'WARN' != $apireq['validationStatus'] || 'BAD' != $apireq['validationStatus'] || 'SCREENSHOT_WARN_BLANK' != $apireq['validationStatus'] ) ) {
248
+ // ERROR: no GOOD, WARN or BAD results
249
+ // Update job properties.
250
+ $jprops['jqstat'] = $apireq['status'];
251
+ $jprops['jrstat'] = $apireq['resultStatus'];
252
+ $jprops['jvstat'] = $apireq['validationStatus'];
253
+ $jprops['jftime'] = microtime( true );
254
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> result request successful but job FAILED, status now is <' . $jprops['jqstat'] . '>', 3 );
255
+ $apireq['css'] = '/* critical css removed for DEBUG logging purposes */';
256
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job response was: ' . json_encode( $apireq ), 3 );
257
+ } else {
258
+ // UNKNOWN: unhandled JOB_DONE exception
259
+ // Update job properties.
260
+ $jprops['jqstat'] = 'JOB_UNKNOWN';
261
+ $jprops['jrstat'] = $apireq['resultStatus'];
262
+ $jprops['jvstat'] = $apireq['validationStatus'];
263
+ $jprops['jftime'] = microtime( true );
264
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> result request successful but job is UNKNOWN, status now is <' . $jprops['jqstat'] . '>', 2 );
265
+ $apireq['css'] = '/* critical css removed for DEBUG logging purposes */';
266
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job response was: ' . json_encode( $apireq ), 3 );
267
+ }
268
+ } elseif ( 'JOB_FAILED' == $apireq['job']['status'] || 'STATUS_JOB_BAD' == $apireq['job']['status'] ) {
269
+ // ERROR: failed job
270
+ // Update job properties.
271
+ $jprops['jqstat'] = $apireq['job']['status'];
272
+ if ( $apireq['error'] ) {
273
+ $jprops['jrstat'] = $apireq['job']['error'];
274
+ } else {
275
+ }
276
+ $jprops['jvstat'] = 'NONE';
277
+ $jprops['jftime'] = microtime( true );
278
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> result request successful but job FAILED, status now is <' . $jprops['jqstat'] . '>', 3 );
279
+ } elseif ( 'This css no longer exists. Please re-generate it.' == $apireq['error'] ) {
280
+ // ERROR: CSS doesn't exist
281
+ // Update job properties.
282
+ $jprops['jqstat'] = 'NO_CSS';
283
+ $jprops['jrstat'] = $apireq['error'];
284
+ $jprops['jvstat'] = 'NONE';
285
+ $jprops['jftime'] = microtime( true );
286
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> result request successful but job FAILED, status now is <' . $jprops['jqstat'] . '>', 3 );
287
+ } elseif ( empty( $apireq ) ) {
288
+ // ERROR: no response
289
+ // Update job properties.
290
+ $jprops['jqstat'] = 'NO_RESPONSE';
291
+ $jprops['jrstat'] = 'NONE';
292
+ $jprops['jvstat'] = 'NONE';
293
+ $jprops['jftime'] = microtime( true );
294
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> request has no response, status now is <' . $jprops['jqstat'] . '>', 3 );
295
+ } else {
296
+ // UNKNOWN: unhandled results exception
297
+ // Update job properties.
298
+ $jprops['jqstat'] = 'JOB_UNKNOWN';
299
+ $jprops['jrstat'] = 'NONE';
300
+ $jprops['jvstat'] = 'NONE';
301
+ $jprops['jftime'] = microtime( true );
302
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> result request has an UNKNOWN condition, status now is <' . $jprops['jqstat'] . '>, check log messages above for more information', 2 );
303
+ }
304
+
305
+ // Set queue update flag.
306
+ $update = true;
307
+ }
308
+
309
+ // Mark DONE jobs for removal.
310
+ if ( 'JOB_DONE' == $jprops['jqstat'] ) {
311
+ $update = true;
312
+ $deljob = true;
313
+ }
314
+
315
+ // Persist updated queue object.
316
+ if ( $update ) {
317
+ if ( ! $deljob ) {
318
+ // Update properties of a NEW or PENDING job...
319
+ $ao_ccss_queue[ $path ] = $jprops;
320
+ } else {
321
+ // ...or remove the DONE job.
322
+ unset( $ao_ccss_queue[ $path ] );
323
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> is DONE and was removed from the queue', 3 );
324
+ }
325
+
326
+ // Update queue object.
327
+ $ao_ccss_queue_raw = json_encode( $ao_ccss_queue );
328
+ update_option( 'autoptimize_ccss_queue', $ao_ccss_queue_raw, false );
329
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Queue updated by job id <' . $jprops['ljid'] . '>', 3 );
330
+
331
+ // Update target rule.
332
+ if ( $rule_update ) {
333
+ $this->ao_ccss_rule_update( $jprops['ljid'], $jprops['rtarget'], $jprops['file'], $jprops['hash'] );
334
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $jprops['ljid'] . '> updated the target rule <' . $jprops['rtarget'] . '>', 3 );
335
+ }
336
+ } else {
337
+ // Or log no queue action.
338
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Nothing to do on this job', 3 );
339
+ }
340
+
341
+ // Break the loop if request limit is set and was reached.
342
+ if ( $ao_ccss_rlimit && $ao_ccss_rlimit == $jr ) {
343
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'The limit of ' . $ao_ccss_rlimit . ' request(s) to criticalcss.com was reached, queue control must finish now', 3 );
344
+ break;
345
+ }
346
+
347
+ // Increment job counter.
348
+ $jc++;
349
+ }
350
+
351
+ // Remove the lock file and log the queue end.
352
+ if ( file_exists( AO_CCSS_LOCK ) ) {
353
+ unlink( AO_CCSS_LOCK );
354
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Queue control unlocked', 3 );
355
+ }
356
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Queue control finished', 3 );
357
+
358
+ // Log that queue is locked.
359
+ } else {
360
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Queue is already running, skipping the attempt to run it again', 3 );
361
+ }
362
+ }
363
+
364
+ public function ao_ccss_diff_hashes( $ljid, $hash, $hashes, $rule ) {
365
+ // Compare job hashes
366
+ // STEP 1: update job hashes.
367
+ if ( 1 == count( $hashes ) ) {
368
+ // Job with a single hash
369
+ // Set job hash.
370
+ $hash = $hashes[0];
371
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $ljid . '> updated with SINGLE hash <' . $hash . '>', 3 );
372
+ } else {
373
+ // Job with multiple hashes
374
+ // Loop through hashes to concatenate them.
375
+ $nhash = '';
376
+ foreach ( $hashes as $shash ) {
377
+ $nhash .= $shash;
378
+ }
379
+
380
+ // Set job hash.
381
+ $hash = md5( $nhash );
382
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $ljid . '> updated with a COMPOSITE hash <' . $hash . '>', 3 );
383
+ }
384
+
385
+ // STEP 2: compare job to existing jobs to prevent double submission for same type+hash.
386
+ global $ao_ccss_queue;
387
+
388
+ foreach ( $ao_ccss_queue as $queue_item ) {
389
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Comparing <' . $rule . $hash . '> with <' . $queue_item['rtarget'] . $queue_item['hash'] . '>', 3 );
390
+ if ( $queue_item['hash'] == $hash && $queue_item['rtarget'] == $rule && in_array( $queue_item['jqstat'], array( 'JOB_QUEUED', 'JOB_ONGOING', 'JOB_DONE' ) ) ) {
391
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $ljid . '> matches the already pending job <' . $queue_item['ljid'] . '>', 3 );
392
+ return false;
393
+ }
394
+ }
395
+
396
+ // STEP 3: compare job and existing rule (if any) hashes
397
+ // Attach required arrays.
398
+ global $ao_ccss_rules;
399
+
400
+ // Prepare rule variables.
401
+ $trule = explode( '|', $rule );
402
+ $srule = $ao_ccss_rules[ $trule[0] ][ $trule[1] ];
403
+
404
+ // Check if a MANUAL rule exist and return false.
405
+ if ( ! empty( $srule ) && ( 0 == $srule['hash'] && 0 != $srule['file'] ) ) {
406
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $ljid . '> matches the MANUAL rule <' . $trule[0] . '|' . $trule[1] . '>', 3 );
407
+ return false;
408
+ } elseif ( ! empty( $srule ) ) {
409
+ // Check if an AUTO rule exist.
410
+ if ( $hash === $srule['hash'] && is_file( AO_CCSS_DIR . $srule['file'] ) && 0 != filesize( AO_CCSS_DIR . $srule['file'] ) ) {
411
+ // Check if job hash matches rule, if the CCSS file exists said file is not empty and return FALSE is so.
412
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $ljid . '> with hash <' . $hash . '> MATCH the one in rule <' . $trule[0] . '|' . $trule[1] . '>', 3 );
413
+ return false;
414
+ } else {
415
+ // Or return the new hash if they differ.
416
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $ljid . '> with hash <' . $hash . '> DOES NOT MATCH the one in rule <' . $trule[0] . '|' . $trule[1] . '> or rule\'s CCSS file was invalid.', 3 );
417
+ return $hash;
418
+ }
419
+ } else {
420
+ // Or just return the hash if no rule exist yet.
421
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job id <' . $ljid . '> with hash <' . $hash . '> has no rule yet', 3 );
422
+ return $hash;
423
+ }
424
+ }
425
+
426
+ public function ao_ccss_api_generate( $path, $debug, $dcode ) {
427
+ // POST jobs to criticalcss.com and return responses
428
+ // Get key and key status.
429
+ global $ao_ccss_key;
430
+ global $ao_ccss_keyst;
431
+ $key = $ao_ccss_key;
432
+ $key_status = $ao_ccss_keyst;
433
+
434
+ // Prepare full URL to request.
435
+ global $ao_ccss_noptimize;
436
+
437
+ $site_host = get_site_url();
438
+ $site_path = parse_url( $site_host, PHP_URL_PATH );
439
+
440
+ if ( ! empty( $site_path ) ) {
441
+ $site_host = str_replace( $site_path, '', $site_host );
442
+ }
443
+
444
+ // Logic to bind to one domain to avoid site clones of sites would
445
+ // automatically begin spawning requests to criticalcss.com which has
446
+ // a per domain cost.
447
+ global $ao_ccss_domain;
448
+ if ( empty( $ao_ccss_domain ) ) {
449
+ // first request being done, update option to allow future requests are only allowed if from same domain.
450
+ update_option( 'autoptimize_ccss_domain', str_rot13( $site_host ) );
451
+ } elseif ( trim( $ao_ccss_domain, '\'"' ) !== 'none' && parse_url( $site_host, PHP_URL_HOST ) !== parse_url( $ao_ccss_domain, PHP_URL_HOST ) && apply_filters( 'autoptimize_filter_ccss_bind_domain', true ) ) {
452
+ // not the same domain, log as error and return without posting to criticalcss.com.
453
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Request for domain ' . $site_host . ' does not match bound domain ' . $ao_ccss_domain . ' so not proceeding.', 2 );
454
+ return false;
455
+ }
456
+
457
+ $src_url = $site_host . $path;
458
+
459
+ // Avoid AO optimizations if required by config or avoid lazyload if lazyload is active in AO.
460
+ if ( ! empty( $ao_ccss_noptimize ) ) {
461
+ $src_url .= '?ao_noptirocket=1';
462
+ } elseif ( class_exists( 'autoptimizeImages', false ) && autoptimizeImages::should_lazyload_wrapper() ) {
463
+ $src_url .= '?ao_nolazy=1';
464
+ }
465
+
466
+ $src_url = apply_filters( 'autoptimize_filter_ccss_cron_srcurl', $src_url );
467
+
468
+ // Initialize request body.
469
+ $body = array();
470
+ $body['url'] = $src_url;
471
+ $body['aff'] = 1;
472
+ $body['aocssv'] = AO_CCSS_VER;
473
+
474
+ // Prepare and add viewport size to the body if available.
475
+ $viewport = autoptimizeCriticalCSSCore::ao_ccss_viewport();
476
+ if ( ! empty( $viewport['w'] ) && ! empty( $viewport['h'] ) ) {
477
+ $body['width'] = $viewport['w'];
478
+ $body['height'] = $viewport['h'];
479
+ }
480
+
481
+ // Prepare and add forceInclude to the body if available.
482
+ global $ao_ccss_finclude;
483
+ $finclude = $this->ao_ccss_finclude( $ao_ccss_finclude );
484
+ if ( ! empty( $finclude ) ) {
485
+ $body['forceInclude'] = $finclude;
486
+ }
487
+
488
+ // Body must be json and log it.
489
+ $body = json_encode( $body );
490
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: POST generate request body is ' . $body, 3 );
491
+
492
+ // Prepare the request.
493
+ $url = esc_url_raw( AO_CCSS_API . 'generate?aover=' . AO_CCSS_VER );
494
+ $args = array(
495
+ 'headers' => array(
496
+ 'User-Agent' => 'Autoptimize v' . AO_CCSS_VER,
497
+ 'Content-type' => 'application/json; charset=utf-8',
498
+ 'Authorization' => 'JWT ' . $key,
499
+ 'Connection' => 'close',
500
+ ),
501
+ 'body' => $body,
502
+ );
503
+
504
+ // Dispatch the request and store its response code.
505
+ $req = wp_safe_remote_post( $url, $args );
506
+ $code = wp_remote_retrieve_response_code( $req );
507
+ $body = json_decode( wp_remote_retrieve_body( $req ), true );
508
+
509
+ if ( $debug && $dcode ) {
510
+ // If queue debug is active, change response code.
511
+ $code = $dcode;
512
+ }
513
+
514
+ if ( 200 == $code ) {
515
+ // Response code is OK.
516
+ // Workaround criticalcss.com non-RESTful reponses.
517
+ if ( 'JOB_QUEUED' == $body['job']['status'] || 'JOB_ONGOING' == $body['job']['status'] || 'STATUS_JOB_BAD' == $body['job']['status'] ) {
518
+ // Log successful and return encoded request body.
519
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: POST generate request for path <' . $src_url . '> replied successfully', 3 );
520
+
521
+ // This code also means the key is valid, so cache key status for 24h if not already cached.
522
+ if ( ( ! $key_status || 2 != $key_status ) && $key ) {
523
+ update_option( 'autoptimize_ccss_keyst', 2 );
524
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: API key is valid, updating key status', 3 );
525
+ }
526
+
527
+ // Return the request body.
528
+ return $body;
529
+ } else {
530
+ // Log successful requests with invalid reponses.
531
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: POST generate request for path <' . $src_url . '> replied with code <' . $code . '> and an UNKNOWN error condition, body follows...', 2 );
532
+ autoptimizeCriticalCSSCore::ao_ccss_log( print_r( $body, true ), 2 );
533
+ return $body;
534
+ }
535
+ } else {
536
+ // Response code is anything else.
537
+ // Log failed request with a valid response code and return body.
538
+ if ( $code ) {
539
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: POST generate request for path <' . $src_url . '> replied with error code <' . $code . '>, body follows...', 2 );
540
+ autoptimizeCriticalCSSCore::ao_ccss_log( print_r( $body, true ), 2 );
541
+
542
+ if ( 401 == $code ) {
543
+ // If request is unauthorized, also clear key status.
544
+ update_option( 'autoptimize_ccss_keyst', 1 );
545
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: API key is invalid, updating key status', 3 );
546
+ }
547
+
548
+ // Return the request body.
549
+ return $body;
550
+ } else {
551
+ // Log failed request with no response and return false.
552
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: POST generate request for path <' . $src_url . '> has no response, this could be a service timeout', 2 );
553
+ if ( is_wp_error( $req ) ) {
554
+ autoptimizeCriticalCSSCore::ao_ccss_log( $req->get_error_message(), 2 );
555
+ }
556
+
557
+ return false;
558
+ }
559
+ }
560
+ }
561
+
562
+ public function ao_ccss_api_results( $jobid, $debug, $dcode ) {
563
+ // GET jobs from criticalcss.com and return responses
564
+ // Get key.
565
+ global $ao_ccss_key;
566
+ $key = $ao_ccss_key;
567
+
568
+ // Prepare the request.
569
+ $url = AO_CCSS_API . 'results?resultId=' . $jobid;
570
+ $args = array(
571
+ 'headers' => array(
572
+ 'User-Agent' => 'Autoptimize CriticalCSS Power-Up v' . AO_CCSS_VER,
573
+ 'Authorization' => 'JWT ' . $key,
574
+ 'Connection' => 'close',
575
+ ),
576
+ );
577
+
578
+ // Dispatch the request and store its response code.
579
+ $req = wp_safe_remote_get( $url, $args );
580
+ $code = wp_remote_retrieve_response_code( $req );
581
+ $body = json_decode( wp_remote_retrieve_body( $req ), true );
582
+
583
+ if ( $debug && $dcode ) {
584
+ // If queue debug is active, change response code.
585
+ $code = $dcode;
586
+ }
587
+
588
+ if ( 200 == $code ) {
589
+ // Response code is OK.
590
+ if ( is_array( $body ) && ( array_key_exists( 'status', $body ) || array_key_exists( 'job', $body ) ) && ( 'JOB_QUEUED' == $body['status'] || 'JOB_ONGOING' == $body['status'] || 'JOB_DONE' == $body['status'] || 'JOB_FAILED' == $body['status'] || 'JOB_UNKNOWN' == $body['status'] || 'STATUS_JOB_BAD' == $body['job']['status'] ) ) {
591
+ // Workaround criticalcss.com non-RESTful reponses
592
+ // Log successful and return encoded request body.
593
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: GET results request for remote job id <' . $jobid . '> replied successfully', 3 );
594
+ return $body;
595
+ } elseif ( is_array( $body ) && ( array_key_exists( 'error', $body ) && 'This css no longer exists. Please re-generate it.' == $body['error'] ) ) {
596
+ // Handle no CSS reply
597
+ // Log no CSS error and return encoded request body.
598
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: GET results request for remote job id <' . $jobid . '> replied successfully but the CSS for it does not exist anymore', 3 );
599
+ return $body;
600
+ } else {
601
+ // Log failed request and return false.
602
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: GET results request for remote job id <' . $jobid . '> replied with code <' . $code . '> and an UNKNOWN error condition, body follows...', 2 );
603
+ autoptimizeCriticalCSSCore::ao_ccss_log( print_r( $body, true ), 2 );
604
+ return false;
605
+ }
606
+ } else {
607
+ // Response code is anything else
608
+ // Log failed request with a valid response code and return body.
609
+ if ( $code ) {
610
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: GET results request for remote job id <' . $jobid . '> replied with error code <' . $code . '>, body follows...', 2 );
611
+ autoptimizeCriticalCSSCore::ao_ccss_log( print_r( $body, true ), 2 );
612
+ if ( 401 == $code ) {
613
+ // If request is unauthorized, also clear key status.
614
+ update_option( 'autoptimize_ccss_keyst', 1 );
615
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: API key is invalid, updating key status', 3 );
616
+ }
617
+
618
+ // Return the request body.
619
+ return $body;
620
+ } else {
621
+ // Log failed request with no response and return false.
622
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'criticalcss.com: GET results request for remote job id <' . $jobid . '> has no response, this could be a service timeout', 2 );
623
+ return false;
624
+ }
625
+ }
626
+ }
627
+
628
+ public function ao_ccss_save_file( $ccss, $target, $review ) {
629
+ // Save critical CSS into the filesystem and return its filename
630
+ // Prepare review mark.
631
+ if ( $review ) {
632
+ $rmark = '_R';
633
+ } else {
634
+ $rmark = '';
635
+ }
636
+
637
+ // Prepare target rule, filename and content.
638
+ $filename = false;
639
+ $content = $ccss;
640
+
641
+ if ( autoptimizeCriticalCSSCore::ao_ccss_check_contents( $content ) ) {
642
+ // Sanitize content, set filename and try to save file.
643
+ $file = AO_CCSS_DIR . 'ccss_' . md5( $ccss . $target[1] ) . $rmark . '.css';
644
+ $status = file_put_contents( $file, $content, LOCK_EX );
645
+ $filename = pathinfo( $file, PATHINFO_BASENAME );
646
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Critical CSS file for the rule <' . $target[0] . '|' . $target[1] . '> was saved as <' . $filename . '>, size in bytes is <' . $status . '>', 3 );
647
+
648
+ if ( ! $status ) {
649
+ // If file has not been saved, reset filename.
650
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Critical CSS file <' . $filename . '> could not be not saved', 2 );
651
+ $filename = false;
652
+ return $filename;
653
+ }
654
+ } else {
655
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Critical CSS received did not pass content check', 2 );
656
+ return $filename;
657
+ }
658
+
659
+ // Remove old critical CSS if a previous one existed in the rule and if that file exists in filesystem
660
+ // NOTE: out of scope critical CSS file removal (issue #5)
661
+ // Attach required arrays.
662
+ global $ao_ccss_rules;
663
+
664
+ // Prepare rule variables.
665
+ $srule = $ao_ccss_rules[ $target[0] ][ $target[1] ];
666
+ $oldfile = $srule['file'];
667
+
668
+ if ( $oldfile && $oldfile !== $filename ) {
669
+ $delfile = AO_CCSS_DIR . $oldfile;
670
+ if ( file_exists( $delfile ) ) {
671
+ $unlinkst = unlink( $delfile );
672
+ if ( $unlinkst ) {
673
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'A previous critical CSS file <' . $oldfile . '> was removed for the rule <' . $target[0] . '|' . $target[1] . '>', 3 );
674
+ }
675
+ }
676
+ }
677
+
678
+ // Return filename or false.
679
+ return $filename;
680
+ }
681
+
682
+ public function ao_ccss_rule_update( $ljid, $srule, $file, $hash ) {
683
+ // Update or create a rule
684
+ // Attach required arrays.
685
+ global $ao_ccss_rules;
686
+
687
+ // Prepare rule variables.
688
+ $trule = explode( '|', $srule );
689
+ $rule = $ao_ccss_rules[ $trule[0] ][ $trule[1] ];
690
+ $action = false;
691
+ $rtype = '';
692
+
693
+ if ( 0 === $rule['hash'] && 0 !== $rule['file'] ) {
694
+ // manual rule, don't ever overwrite.
695
+ $action = 'NOT UPDATED';
696
+ $rtype = 'MANUAL';
697
+ } elseif ( 0 === $rule['hash'] && 0 === $rule['file'] ) {
698
+ // If this is an user created AUTO rule with no hash and file yet, update its hash and filename
699
+ // Set rule hash, file and action flag.
700
+ $rule['hash'] = $hash;
701
+ $rule['file'] = $file;
702
+ $action = 'UPDATED';
703
+ $rtype = 'AUTO';
704
+ } elseif ( 0 !== $rule['hash'] && ctype_alnum( $rule['hash'] ) ) {
705
+ // If this is an genuine AUTO rule, update its hash and filename
706
+ // Set rule hash, file and action flag.
707
+ $rule['hash'] = $hash;
708
+ $rule['file'] = $file;
709
+ $action = 'UPDATED';
710
+ $rtype = 'AUTO';
711
+ } else {
712
+ // If rule doesn't exist, create an AUTO rule
713
+ // AUTO rules were only for types, but will now also work for paths.
714
+ if ( 'types' == $trule[0] || 'paths' == $trule[0] ) {
715
+ // Set rule hash and file and action flag.
716
+ $rule['hash'] = $hash;
717
+ $rule['file'] = $file;
718
+ $action = 'CREATED';
719
+ $rtype = 'AUTO';
720
+ } else {
721
+ // Log that no rule was created.
722
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Exception, no AUTO rule created', 3 );
723
+ }
724
+ }
725
+
726
+ if ( $action ) {
727
+ // If a rule creation/update is required, persist updated rules object.
728
+ $ao_ccss_rules[ $trule[0] ][ $trule[1] ] = $rule;
729
+ $ao_ccss_rules_raw = json_encode( $ao_ccss_rules );
730
+ update_option( 'autoptimize_ccss_rules', $ao_ccss_rules_raw );
731
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Target rule <' . $srule . '> of type <' . $rtype . '> was ' . $action . ' for job id <' . $ljid . '>', 3 );
732
+ } else {
733
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'No rule action required', 3 );
734
+ }
735
+ }
736
+
737
+ function ao_ccss_finclude( $finclude_raw ) {
738
+ // Prepare forceInclude object.
739
+ if ( ! empty( $finclude_raw ) ) {
740
+ // If there are any content
741
+ // Convert raw string into arra and initialize the returning object.
742
+ $fincludes = explode( ',', $finclude_raw );
743
+ $finclude = array();
744
+
745
+ // Interacts over every rule.
746
+ $i = 0;
747
+ foreach ( $fincludes as $include ) {
748
+ // Trim leading and trailing whitespaces.
749
+ $include = trim( $include );
750
+
751
+ if ( substr( $include, 0, 2 ) === '//' ) {
752
+ // Regex rule
753
+ // Format value as required.
754
+ $include = str_replace( '//', '/', $include );
755
+ $include = $include . '/i';
756
+
757
+ // Store regex object.
758
+ $finclude[ $i ]['type'] = 'RegExp';
759
+ $finclude[ $i ]['value'] = $include;
760
+ } else {
761
+ // Simple value rule.
762
+ $finclude[ $i ]['value'] = $include;
763
+ }
764
+
765
+ $i++;
766
+ }
767
+
768
+ // Return forceInclude object.
769
+ return $finclude;
770
+ } else {
771
+ // Or just return false if empty.
772
+ return false;
773
+ }
774
+ }
775
+
776
+ public static function ao_ccss_cleaning() {
777
+ // Perform plugin maintenance
778
+ // Truncate log file >= 1MB .
779
+ if ( file_exists( AO_CCSS_LOG ) ) {
780
+ if ( filesize( AO_CCSS_LOG ) >= 1048576 ) {
781
+ $logfile = fopen( AO_CCSS_LOG, 'w' );
782
+ fclose( $logfile );
783
+ }
784
+ }
785
+
786
+ // Remove lock file.
787
+ if ( file_exists( AO_CCSS_LOCK ) ) {
788
+ unlink( AO_CCSS_LOCK );
789
+ }
790
+
791
+ // Make sure queue processing is scheduled, recreate if not.
792
+ if ( ! wp_next_scheduled( 'ao_ccss_queue' ) ) {
793
+ wp_schedule_event( time(), apply_filters( 'ao_ccss_queue_schedule', 'ao_ccss' ), 'ao_ccss_queue' );
794
+ }
795
+
796
+ // Queue cleaning.
797
+ global $ao_ccss_queue;
798
+ $queue_purge_threshold = 100;
799
+ $queue_purge_age = 24 * 60 * 60;
800
+ $queue_length = count( $ao_ccss_queue );
801
+ $timestamp_yesterday = microtime( true ) - $queue_purge_age;
802
+ $remove_old_new = false;
803
+ $queue_altered = false;
804
+
805
+ if ( $queue_length > $queue_purge_threshold ) {
806
+ $remove_old_new = true;
807
+ }
808
+
809
+ foreach ( $ao_ccss_queue as $path => $job ) {
810
+ if ( ( $remove_old_new && 'NEW' == $job['jqstat'] && $job['jctime'] < $timestamp_yesterday ) || in_array( $job['jqstat'], array( 'JOB_FAILED', 'STATUS_JOB_BAD', 'NO_CSS', 'NO_RESPONSE' ) ) ) {
811
+ unset( $ao_ccss_queue[ $path ] );
812
+ $queue_altered = true;
813
+ }
814
+ }
815
+
816
+ // save queue to options!
817
+ if ( $queue_altered ) {
818
+ $ao_ccss_queue_raw = json_encode( $ao_ccss_queue );
819
+ update_option( 'autoptimize_ccss_queue', $ao_ccss_queue_raw, false );
820
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Queue cleaning done.', 3 );
821
+ }
822
+
823
+ // re-check key if invalid.
824
+ global $ao_ccss_keyst;
825
+ if ( 1 == $ao_ccss_keyst ) {
826
+ $this->ao_ccss_api_generate( '', '', '' );
827
+ }
828
+ }
829
+ }
classes/autoptimizeCriticalCSSEnqueue.php ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Critical CSS job enqueue logic.
4
+ */
5
+
6
+ if ( ! defined( 'ABSPATH' ) ) {
7
+ exit;
8
+ }
9
+
10
+ class autoptimizeCriticalCSSEnqueue {
11
+ public function __construct()
12
+ {
13
+ // fetch all options at once and populate them individually explicitely as globals.
14
+ $all_options = autoptimizeCriticalCSSBase::fetch_options();
15
+ foreach ( $all_options as $_option => $_value ) {
16
+ global ${$_option};
17
+ ${$_option} = $_value;
18
+ }
19
+ }
20
+
21
+ public static function ao_ccss_enqueue( $hash ) {
22
+ $self = new self();
23
+ // Get key status.
24
+ $key = autoptimizeCriticalCSSCore::ao_ccss_key_status( false );
25
+
26
+ // Queue is available to anyone...
27
+ $enqueue = true;
28
+
29
+ // ... which are not the ones below.
30
+ if ( is_user_logged_in() || is_feed() || is_404() || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) || $self->ao_ccss_ua() || 'nokey' == $key['status'] || 'invalid' == $key['status'] ) {
31
+ $enqueue = false;
32
+ autoptimizeCriticalCSSCore::ao_ccss_log( "Job queuing is not available for WordPress's logged in users, feeds, error pages, ajax calls, to criticalcss.com itself or when a valid API key is not found", 3 );
33
+ }
34
+
35
+ if ( $enqueue ) {
36
+ // Continue if queue is available
37
+ // Attach required arrays/ vars.
38
+ global $ao_ccss_rules;
39
+ global $ao_ccss_queue_raw;
40
+ global $ao_ccss_queue;
41
+ global $ao_ccss_forcepath;
42
+
43
+ // Get request path and page type, and initialize the queue update flag.
44
+ $req_path = strtok( $_SERVER['REQUEST_URI'], '?' );
45
+ $req_type = $self->ao_ccss_get_type();
46
+ $job_qualify = false;
47
+ $target_rule = false;
48
+ $rule_properties = false;
49
+ $queue_update = false;
50
+
51
+ // Match for paths in rules.
52
+ foreach ( $ao_ccss_rules['paths'] as $path => $props ) {
53
+
54
+ // Prepare rule target and log.
55
+ $target_rule = 'paths|' . $path;
56
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Qualifying path <' . $req_path . '> for job submission by rule <' . $target_rule . '>', 3 );
57
+
58
+ // Path match
59
+ // -> exact match needed for AUTO rules
60
+ // -> partial match OK for MANUAL rules (which have empty hash and a file with CCSS).
61
+ if ( $path === $req_path || ( false == $props['hash'] && false != $props['file'] && preg_match( '|' . $path . '|', $req_path ) ) ) {
62
+
63
+ // There's a path match in the rule, so job QUALIFIES with a path rule match.
64
+ $job_qualify = true;
65
+ $rule_properties = $props;
66
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Path <' . $req_path . '> QUALIFIED for job submission by rule <' . $target_rule . '>', 3 );
67
+
68
+ // Stop processing other path rules.
69
+ break;
70
+ }
71
+ }
72
+
73
+ // Match for types in rules if no path rule matches and if we're not enforcing paths.
74
+ if ( ! $job_qualify && ( ! $ao_ccss_forcepath || ! in_array( $req_type, apply_filters( 'autoptimize_filter_ccss_coreenqueue_forcepathfortype', array( 'is_page' ) ) ) ) ) {
75
+ foreach ( $ao_ccss_rules['types'] as $type => $props ) {
76
+
77
+ // Prepare rule target and log.
78
+ $target_rule = 'types|' . $type;
79
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Qualifying page type <' . $req_type . '> on path <' . $req_path . '> for job submission by rule <' . $target_rule . '>', 3 );
80
+
81
+ if ( $req_type == $type ) {
82
+ // Type match.
83
+ // There's a type match in the rule, so job QUALIFIES with a type rule match.
84
+ $job_qualify = true;
85
+ $rule_properties = $props;
86
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Page type <' . $req_type . '> on path <' . $req_path . '> QUALIFIED for job submission by rule <' . $target_rule . '>', 3 );
87
+
88
+ // Stop processing other type rules.
89
+ break;
90
+ }
91
+ }
92
+ }
93
+
94
+ if ( $job_qualify && false == $rule_properties['hash'] && false != $rule_properties['file'] ) {
95
+ // If job qualifies but rule hash is false and file isn't false (MANUAL rule), job does not qualify despite what previous evaluations says.
96
+ $job_qualify = false;
97
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job submission DISQUALIFIED by MANUAL rule <' . $target_rule . '> with hash <' . $rule_properties['hash'] . '> and file <' . $rule_properties['file'] . '>', 3 );
98
+ } elseif ( ! $job_qualify && empty( $rule_properties ) ) {
99
+ // But if job does not qualify and rule properties are set, job qualifies as there is no matching rule for it yet
100
+ // Fill-in the new target rule.
101
+ $job_qualify = true;
102
+
103
+ // Should we switch to path-base AUTO-rules? Conditions:
104
+ // 1. forcepath option has to be enabled (off by default)
105
+ // 2. request type should be (by default, but filterable) one of is_page (removed for now: woo_is_product or woo_is_product_category).
106
+ if ( $ao_ccss_forcepath && in_array( $req_type, apply_filters( 'autoptimize_filter_ccss_coreenqueue_forcepathfortype', array( 'is_page' ) ) ) ) {
107
+ if ( '/' !== $req_path ) {
108
+ $target_rule = 'paths|' . $req_path;
109
+ } else {
110
+ // Exception; we don't want a path-based rule for "/" as that messes things up, hard-switch this to a type-based is_front_page rule.
111
+ $target_rule = 'types|' . 'is_front_page';
112
+ }
113
+ } else {
114
+ $target_rule = 'types|' . $req_type;
115
+ }
116
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job submission QUALIFIED by MISSING rule for page type <' . $req_type . '> on path <' . $req_path . '>, new rule target is <' . $target_rule . '>', 3 );
117
+ } else {
118
+ // Or just log a job qualified by a matching rule.
119
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job submission QUALIFIED by AUTO rule <' . $target_rule . '> with hash <' . $rule_properties['hash'] . '> and file <' . $rule_properties['file'] . '>', 3 );
120
+ }
121
+
122
+ // Submit job.
123
+ if ( $job_qualify ) {
124
+ if ( ! array_key_exists( $req_path, $ao_ccss_queue ) ) {
125
+ // This is a NEW job
126
+ // Merge job into the queue.
127
+ $ao_ccss_queue[ $req_path ] = $self->ao_ccss_define_job(
128
+ $req_path,
129
+ $target_rule,
130
+ $req_type,
131
+ $hash,
132
+ null,
133
+ null,
134
+ null,
135
+ null,
136
+ true
137
+ );
138
+ // Set update flag.
139
+ $queue_update = true;
140
+ } else {
141
+ // This is an existing job
142
+ // The job is still NEW, most likely this is extra CSS file for the same page that needs a hash.
143
+ if ( 'NEW' == $ao_ccss_queue[ $req_path ]['jqstat'] ) {
144
+ // Add hash if it's not already in the job.
145
+ if ( ! in_array( $hash, $ao_ccss_queue[ $req_path ]['hashes'] ) ) {
146
+ // Push new hash to its array and update flag.
147
+ $queue_update = array_push( $ao_ccss_queue[ $req_path ]['hashes'], $hash );
148
+
149
+ // Log job update.
150
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Hashes UPDATED on local job id <' . $ao_ccss_queue[ $req_path ]['ljid'] . '>, job status NEW, target rule <' . $ao_ccss_queue[ $req_path ]['rtarget'] . '>, hash added: ' . $hash, 3 );
151
+
152
+ // Return from here as the hash array is already updated.
153
+ return true;
154
+ }
155
+ } elseif ( 'NEW' != $ao_ccss_queue[ $req_path ]['jqstat'] && 'JOB_QUEUED' != $ao_ccss_queue[ $req_path ]['jqstat'] && 'JOB_ONGOING' != $ao_ccss_queue[ $req_path ]['jqstat'] ) {
156
+ // Allow requeuing jobs that are not NEW, JOB_QUEUED or JOB_ONGOING
157
+ // Merge new job keeping some previous job values.
158
+ $ao_ccss_queue[ $req_path ] = $self->ao_ccss_define_job(
159
+ $req_path,
160
+ $target_rule,
161
+ $req_type,
162
+ $hash,
163
+ $ao_ccss_queue[ $req_path ]['file'],
164
+ $ao_ccss_queue[ $req_path ]['jid'],
165
+ $ao_ccss_queue[ $req_path ]['jrstat'],
166
+ $ao_ccss_queue[ $req_path ]['jvstat'],
167
+ false
168
+ );
169
+ // Set update flag.
170
+ $queue_update = true;
171
+ }
172
+ }
173
+
174
+ if ( $queue_update ) {
175
+ // Persist the job to the queue and return.
176
+ $ao_ccss_queue_raw = json_encode( $ao_ccss_queue );
177
+ update_option( 'autoptimize_ccss_queue', $ao_ccss_queue_raw, false );
178
+ return true;
179
+ } else {
180
+ // Or just return false if no job was added.
181
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'A job for path <' . $req_path . '> already exist with NEW or PENDING status, skipping job creation', 3 );
182
+ return false;
183
+ }
184
+ }
185
+ }
186
+ }
187
+
188
+ public function ao_ccss_get_type() {
189
+ // Get the type of a page
190
+ // Attach the conditional tags array.
191
+ global $ao_ccss_types;
192
+
193
+ // By default, a page type is false.
194
+ $page_type = false;
195
+
196
+ // Iterates over the array to match a type.
197
+ foreach ( $ao_ccss_types as $type ) {
198
+ if ( strpos( $type, 'custom_post_' ) !== false ) {
199
+ // Match custom post types.
200
+ if ( get_post_type( get_the_ID() ) === substr( $type, 12 ) ) {
201
+ $page_type = $type;
202
+ break;
203
+ }
204
+ } elseif ( strpos( $type, 'template_' ) !== false ) {
205
+ // If templates; don't break, templates become manual-only rules.
206
+ } else {
207
+ // Match all other existing types
208
+ // but remove prefix to be able to check if the function exists & returns true.
209
+ $_type = str_replace( array( 'woo_', 'bp_', 'bbp_', 'edd_' ), '', $type );
210
+ if ( function_exists( $_type ) && call_user_func( $_type ) ) {
211
+ // Make sure we only return is_front_page (and is_home) for one page, not for the "paged frontpage" (/page/2 ..).
212
+ if ( ( 'is_front_page' !== $_type && 'is_home' !== $_type ) || ! is_paged() ) {
213
+ $page_type = $type;
214
+ break;
215
+ }
216
+ }
217
+ }
218
+ }
219
+
220
+ // Return the page type.
221
+ return $page_type;
222
+ }
223
+
224
+ public function ao_ccss_define_job( $path, $target, $type, $hash, $file, $jid, $jrstat, $jvstat, $create ) {
225
+ // Define a job entry to be created or updated
226
+ // Define commom job properties.
227
+ $path = array();
228
+ $path['ljid'] = $this->ao_ccss_job_id();
229
+ $path['rtarget'] = $target;
230
+ $path['ptype'] = $type;
231
+ $path['hashes'] = array( $hash );
232
+ $path['hash'] = $hash;
233
+ $path['file'] = $file;
234
+ $path['jid'] = $jid;
235
+ $path['jqstat'] = 'NEW';
236
+ $path['jrstat'] = $jrstat;
237
+ $path['jvstat'] = $jvstat;
238
+ $path['jctime'] = microtime( true );
239
+ $path['jftime'] = null;
240
+
241
+ // Set operation requested.
242
+ if ( $create ) {
243
+ $operation = 'CREATED';
244
+ } else {
245
+ $operation = 'UPDATED';
246
+ }
247
+
248
+ // Log job creation.
249
+ autoptimizeCriticalCSSCore::ao_ccss_log( 'Job ' . $operation . ' with local job id <' . $path['ljid'] . '> for target rule <' . $target . '>', 3 );
250
+
251
+ return $path;
252
+ }
253
+
254
+ public function ao_ccss_job_id( $length = 6 ) {
255
+ // Generate random strings for the local job ID
256
+ // Based on https://stackoverflow.com/a/4356295 .
257
+ $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
258
+ $characters_length = strlen( $characters );
259
+ $random_string = 'j-';
260
+ for ( $i = 0; $i < $length; $i++ ) {
261
+ $random_string .= $characters[ rand( 0, $characters_length - 1 ) ];
262
+ }
263
+ return $random_string;
264
+ }
265
+
266
+ public function ao_ccss_ua() {
267
+ // Check for criticalcss.com user agent.
268
+ $agent = '';
269
+ if ( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
270
+ $agent = $_SERVER['HTTP_USER_AGENT'];
271
+ }
272
+
273
+ // Check for UA and return TRUE when criticalcss.com is the detected UA, false when not.
274
+ $rtn = strpos( $agent, AO_CCSS_URL );
275
+ if ( 0 === $rtn ) {
276
+ $rtn = true;
277
+ } else {
278
+ $rtn = false;
279
+ }
280
+ return ( $rtn );
281
+ }
282
+ }
classes/autoptimizeCriticalCSSSettings.php CHANGED
@@ -1,6 +1,6 @@
1
  <?php
2
  /**
3
- * Temporary options page for AO26, will integrate CCSS functionality in next release.
4
  */
5
 
6
  if ( ! defined( 'ABSPATH' ) ) {
@@ -23,19 +23,22 @@ class autoptimizeCriticalCSSSettings {
23
 
24
  protected function enabled()
25
  {
26
- return apply_filters( 'autoptimize_filter_show_criticalcsss_tabs', true );
27
  }
28
 
29
  public function run()
30
  {
31
  if ( $this->enabled() ) {
32
  add_filter( 'autoptimize_filter_settingsscreen_tabs', array( $this, 'add_critcss_tabs' ), 10, 1 );
33
- }
 
 
 
 
 
 
34
 
35
- if ( is_multisite() && is_network_admin() && autoptimizeOptionWrapper::is_ao_active_for_network() ) {
36
- add_action( 'network_admin_menu', array( $this, 'add_critcss_admin_menu' ) );
37
- } else {
38
- add_action( 'admin_menu', array( $this, 'add_critcss_admin_menu' ) );
39
  }
40
  }
41
 
@@ -48,50 +51,318 @@ class autoptimizeCriticalCSSSettings {
48
 
49
  public function add_critcss_admin_menu()
50
  {
51
- if ( $this->enabled() ) {
52
- add_submenu_page( null, 'Critical CSS', 'Critical CSS', 'manage_options', 'ao_critcss', array( $this, 'ao_criticalcsssettings_page' ) );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  }
 
 
 
 
 
 
 
 
 
 
 
54
  }
55
 
56
  public function ao_criticalcsssettings_page()
57
  {
58
- ?>
59
- <style>
60
- .ao_settings_div {background: white;border: 1px solid #ccc;padding: 1px 15px;margin: 15px 10px 10px 0;}
61
- .ao_settings_div .form-table th {font-weight: normal;}
62
- </style>
63
- <script>document.title = "Autoptimize: <?php _e( 'Critical CSS', 'autoptimize' ); ?> " + document.title;</script>
64
- <div class="wrap">
65
- <h1><?php _e( 'Autoptimize Settings', 'autoptimize' ); ?></h1>
66
- <?php echo autoptimizeConfig::ao_admin_tabs(); ?>
67
- <div class="ao_settings_div">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  <?php
69
- $ccss_explanation = '';
70
-
71
- // get the HTML with the explanation of what critical CSS is.
72
- if ( $this->settings_screen_do_remote_http ) {
73
- $ccss_explanation = get_transient( 'ccss_explain_ao26' );
74
- if ( empty( $ccss_explanation ) ) {
75
- $ccss_expl_resp = wp_remote_get( 'https://misc.optimizingmatters.com/autoptimize_ccss_explain_ao26.html?ao_ver=' . AUTOPTIMIZE_PLUGIN_VERSION );
76
- if ( ! is_wp_error( $ccss_expl_resp ) ) {
77
- if ( '200' == wp_remote_retrieve_response_code( $ccss_expl_resp ) ) {
78
- $ccss_explanation = wp_kses_post( wp_remote_retrieve_body( $ccss_expl_resp ) );
79
- set_transient( 'ccss_explain_ao26', $ccss_explanation, WEEK_IN_SECONDS );
 
 
 
 
 
 
 
 
 
 
 
80
  }
81
  }
 
 
 
82
  }
83
  }
 
 
 
 
84
 
85
- // placeholder text in case HTML is empty.
86
- if ( empty( $ccss_explanation ) ) {
87
- $ccss_explanation = '<h2>Fix render-blocking CSS!</h2><p>Significantly improve your first-paint times by making CSS non-render-blocking.</p><br /><a href="./plugin-install.php?s=autoptimize+criticalcss&tab=search&type=term" class="button">Install the "Autoptimize Critical CSS Power-Up"!</a>';
 
 
 
 
 
88
  }
 
89
 
90
- // and echo it.
91
- echo $ccss_explanation . '<p>&nbsp;</p>';
92
- ?>
93
- </div>
94
- </div>
95
- <?php
96
  }
97
  }
1
  <?php
2
  /**
3
+ * Critical CSS Options page.
4
  */
5
 
6
  if ( ! defined( 'ABSPATH' ) ) {
23
 
24
  protected function enabled()
25
  {
26
+ return apply_filters( 'autoptimize_filter_show_criticalcss_tabs', true );
27
  }
28
 
29
  public function run()
30
  {
31
  if ( $this->enabled() ) {
32
  add_filter( 'autoptimize_filter_settingsscreen_tabs', array( $this, 'add_critcss_tabs' ), 10, 1 );
33
+ add_action( 'admin_enqueue_scripts', array( $this, 'admin_assets' ) );
34
+
35
+ if ( $this->is_multisite_network_admin() && autoptimizeOptionWrapper::is_ao_active_for_network() ) {
36
+ add_action( 'network_admin_menu', array( $this, 'add_critcss_admin_menu' ) );
37
+ } else {
38
+ add_action( 'admin_menu', array( $this, 'add_critcss_admin_menu' ) );
39
+ }
40
 
41
+ $criticalcss_ajax = new autoptimizeCriticalCSSSettingsAjax();
 
 
 
42
  }
43
  }
44
 
51
 
52
  public function add_critcss_admin_menu()
53
  {
54
+ // Register settings.
55
+ register_setting( 'ao_ccss_options_group', 'autoptimize_css_defer_inline' );
56
+ register_setting( 'ao_ccss_options_group', 'autoptimize_ccss_rules' );
57
+ register_setting( 'ao_ccss_options_group', 'autoptimize_ccss_additional' );
58
+ register_setting( 'ao_ccss_options_group', 'autoptimize_ccss_queue' );
59
+ register_setting( 'ao_ccss_options_group', 'autoptimize_ccss_viewport' );
60
+ register_setting( 'ao_ccss_options_group', 'autoptimize_ccss_finclude' );
61
+ register_setting( 'ao_ccss_options_group', 'autoptimize_ccss_rlimit' );
62
+ register_setting( 'ao_ccss_options_group', 'autoptimize_ccss_noptimize' );
63
+ register_setting( 'ao_ccss_options_group', 'autoptimize_ccss_debug' );
64
+ register_setting( 'ao_ccss_options_group', 'autoptimize_ccss_key' );
65
+ register_setting( 'ao_ccss_options_group', 'autoptimize_ccss_keyst' );
66
+ register_setting( 'ao_ccss_options_group', 'autoptimize_ccss_loggedin' );
67
+ register_setting( 'ao_ccss_options_group', 'autoptimize_ccss_forcepath' );
68
+ register_setting( 'ao_ccss_options_group', 'autoptimize_ccss_deferjquery' );
69
+ register_setting( 'ao_ccss_options_group', 'autoptimize_ccss_domain' );
70
+
71
+ // And add submenu-page.
72
+ add_submenu_page( null, 'Critical CSS', 'Critical CSS', 'manage_options', 'ao_critcss', array( $this, 'ao_criticalcsssettings_page' ) );
73
+ }
74
+
75
+ public function admin_assets( $hook ) {
76
+ // Return if plugin is not hooked.
77
+ if ( 'settings_page_ao_critcss' != $hook && 'admin_page_ao_critcss' != $hook ) {
78
+ return;
79
  }
80
+
81
+ // Stylesheets to add.
82
+ wp_enqueue_style( 'wp-jquery-ui-dialog' );
83
+ wp_enqueue_style( 'ao-tablesorter', plugins_url( 'critcss-inc/css/ao-tablesorter/style.css', __FILE__ ) );
84
+ wp_enqueue_style( 'ao-ccss-admin-css', plugins_url( 'critcss-inc/css/admin_styles.css', __FILE__ ) );
85
+
86
+ // Scripts to add.
87
+ wp_enqueue_script( 'jquery-ui-dialog', array( 'jquery' ) );
88
+ wp_enqueue_script( 'md5', plugins_url( 'critcss-inc/js/md5.min.js', __FILE__ ), null, null, true );
89
+ wp_enqueue_script( 'tablesorter', plugins_url( 'critcss-inc/js/jquery.tablesorter.min.js', __FILE__ ), array( 'jquery' ), null, true );
90
+ wp_enqueue_script( 'ao-ccss-admin-license', plugins_url( 'critcss-inc/js/admin_settings.js', __FILE__ ), array( 'jquery' ), null, true );
91
  }
92
 
93
  public function ao_criticalcsssettings_page()
94
  {
95
+ // these are not OO yet, simply require for now.
96
+ require_once( 'critcss-inc/admin_settings_rules.php' );
97
+ require_once( 'critcss-inc/admin_settings_queue.php' );
98
+ require_once( 'critcss-inc/admin_settings_key.php' );
99
+ require_once( 'critcss-inc/admin_settings_adv.php' );
100
+ require_once( 'critcss-inc/admin_settings_explain.php' );
101
+
102
+ // fetch all options at once and populate them individually explicitely as globals.
103
+ $all_options = autoptimizeCriticalCSSBase::fetch_options();
104
+ foreach ( $all_options as $_option => $_value ) {
105
+ global ${$_option};
106
+ ${$_option} = $_value;
107
+ }
108
+ ?>
109
+ <div class="wrap">
110
+ <div id="autoptimize_main">
111
+ <div id="ao_title_and_button">
112
+ <h1><?php _e( 'Autoptimize Settings', 'autoptimize' ); ?></h1>
113
+ </div>
114
+
115
+ <?php
116
+ // Print AO settings tabs.
117
+ echo autoptimizeConfig::ao_admin_tabs();
118
+
119
+ // Make sure dir to write ao_ccss exists and is writable.
120
+ if ( ! is_dir( AO_CCSS_DIR ) ) {
121
+ $mkdirresp = @mkdir( AO_CCSS_DIR, 0775, true ); // @codingStandardsIgnoreLine
122
+ $fileresp = file_put_contents( AO_CCSS_DIR . 'index.html', '<html><head><meta name="robots" content="noindex, nofollow"></head><body>Generated by <a href="http://wordpress.org/extend/plugins/autoptimize/" rel="nofollow">Autoptimize</a></body></html>' );
123
+ if ( ( ! $mkdirresp ) || ( ! $fileresp ) ) {
124
+ ?>
125
+ <div class="notice-error notice"><p>
126
+ <?php
127
+ _e( 'Could not create the required directory. Make sure the webserver can write to the wp-content directory.', 'autoptimize' );
128
+ ?>
129
+ </p></div>
130
+ <?php
131
+ }
132
+ }
133
+
134
+ // Check for Autoptimize.
135
+ if ( ! empty( $ao_ccss_key ) && ! $ao_css_defer ) {
136
+ ?>
137
+ <div class="notice-error notice"><p>
138
+ <?php
139
+ _e( "Oops! Please <strong>activate the \"Inline and Defer CSS\" option</strong> on Autoptimize's main settings page to use this power-up.", 'autoptimize' );
140
+ ?>
141
+ </p></div>
142
+ <?php
143
+ return;
144
+ }
145
+
146
+ // check if WordPress cron is disabled and warn if so.
147
+ if ( ! empty( $ao_ccss_key ) && defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON && PAnD::is_admin_notice_active( 'i-know-about-disable-cron-forever' ) ) {
148
+ ?>
149
+ <div data-dismissible="i-know-about-disable-cron-forever" class="notice-warning notice is-dismissible"><p>
150
+ <?php
151
+ _e( 'WordPress cron (for task scheduling) seems to be disabled. Have a look at <a href="https://wordpress.org/plugins/autoptimize-criticalcss/faq/" target="_blank">the FAQ</a> or the info in the Job Queue instructions if all jobs remain in "N" status and no rules are created.', 'autoptimize' );
152
+ ?>
153
+ </p></div>
154
+ <?php
155
+ }
156
+
157
+ // warn if it looks as though the queue processing job looks isn't running
158
+ // but store result in transient as to not to have to go through 2 arrays each and every time.
159
+ $_warn_cron = get_transient( 'ao_ccss_cronwarning' );
160
+ if ( ! empty( $ao_ccss_key ) && false === $_warn_cron ) {
161
+ $_jobs_all_new = true;
162
+ $_oldest_job_timestamp = microtime( true ); // now.
163
+ $_jobs_too_old = true;
164
+
165
+ // go over queue array.
166
+ if ( empty( $ao_ccss_queue ) ) {
167
+ // no jobs, then no warning.
168
+ $_jobs_all_new = false;
169
+ } else {
170
+ foreach ( $ao_ccss_queue as $job ) {
171
+ if ( $job['jctime'] < $_oldest_job_timestamp ) {
172
+ // we need to catch the oldest job's timestamp.
173
+ $_oldest_job_timestamp = $job['jctime'];
174
+ }
175
+
176
+ if ( 'NEW' !== $job['jqstat'] && 'firstrun' !== $job['ljid'] ) {
177
+ // we have a non-"NEW" job which is not our pending firstrun job either, break the loop.
178
+ $_jobs_all_new = false;
179
+ break;
180
+ }
181
+ }
182
+ }
183
+
184
+ // is the oldest job too old (4h)?
185
+ if ( $_oldest_job_timestamp > microtime( true ) - 60 * 60 * 4 ) {
186
+ $_jobs_too_old = false;
187
+ }
188
+
189
+ if ( $_jobs_all_new && ! $this->ao_ccss_has_autorules() && $_jobs_too_old ) {
190
+ $_warn_cron = 'on';
191
+ $_transient_multiplier = 1; // store for 1 hour.
192
+ } else {
193
+ $_warn_cron = 'off';
194
+ $_transient_multiplier = 4; // store for 4 hours.
195
+ }
196
+ // and set transient.
197
+ set_transient( 'ao_ccss_cronwarning', $_warn_cron, $_transient_multiplier * HOUR_IN_SECONDS );
198
+ }
199
+
200
+ if ( ! empty( $ao_ccss_key ) && 'on' == $_warn_cron && PAnD::is_admin_notice_active( 'i-know-about-cron-1' ) ) {
201
+ ?>
202
+ <div data-dismissible="i-know-about-cron-1" class="notice-warning notice is-dismissible"><p>
203
+ <?php
204
+ _e( 'It looks like there might be a problem with WordPress cron (task scheduling). Have a look at <a href="https://wordpress.org/plugins/autoptimize-criticalcss/faq/" target="_blank">the FAQ</a> or the info in the Job Queue instructions if all jobs remain in "N" status and no rules are created.', 'autoptimize' );
205
+ ?>
206
+ </p></div>
207
+ <?php
208
+ } elseif ( ! empty( $ao_ccss_key ) && '2' == $ao_ccss_keyst && 'on' != $_warn_cron && ! $this->ao_ccss_has_autorules() ) {
209
+ ?>
210
+ <div class="notice-success notice"><p>
211
+ <?php
212
+ _e( 'Great, Autoptimize will now automatically start creating new critical CSS rules, you should see those appearing below in the next couple of hours.', 'autoptimize' );
213
+ ?>
214
+ </p></div>
215
+ <?php
216
+ }
217
+
218
+ // warn if service is down.
219
+ if ( ! empty( $ao_ccss_key ) && ! empty( $ao_ccss_servicestatus ) && is_array( $ao_ccss_servicestatus ) && 'down' === $ao_ccss_servicestatus['critcss']['status'] ) {
220
+ ?>
221
+ <div class="notice-warning notice"><p>
222
+ <?php
223
+ _e( 'The critical CSS service has been reported to be down. Although no new rules will be created for now, this does not prevent existing rules from being applied.', 'autoptimize' );
224
+ ?>
225
+ </p></div>
226
+ <?php
227
+ }
228
+
229
+ // Settings Form.
230
+ ?>
231
+ <form id="settings" method="post" action="options.php">
232
+ <?php
233
+ settings_fields( 'ao_ccss_options_group' );
234
+
235
+ // Get API key status.
236
+ $key = autoptimizeCriticalCSSCore::ao_ccss_key_status( true );
237
+
238
+ if ( $this->is_multisite_network_admin() ) {
239
+ ?>
240
+ <ul id="key-panel">
241
+ <li class="itemDetail">
242
+ <?php
243
+ // translators: the placesholder is for a line of code in wp-config.php.
244
+ echo sprintf( __( '<p>Critical CSS settings cannot be set at network level as critical CSS is specific to each sub-site.</p><p>You can however provide the critical CSS API key for use by all sites by adding this your wp-config.php as %s</p>', 'autoptimize' ), '<br/><code>define(\'AUTOPTIMIZE_CRITICALCSS_API_KEY\', \'eyJhbGmorestringsherexHa7MkOQFtDFkZgLmBLe-LpcHx4\');</code>' );
245
+ ?>
246
+ </li>
247
+ </ul>
248
+ <?php
249
+ } else {
250
+ if ( 'valid' == $key['status'] ) {
251
+ // If key status is valid, render other panels.
252
+ // Render rules section.
253
+ ao_ccss_render_rules();
254
+ // Render queue section.
255
+ ao_ccss_render_queue();
256
+ // Render advanced panel.
257
+ ao_ccss_render_adv();
258
+ } else {
259
+ // But if key is other than valid, add hidden fields to persist settings when submitting form
260
+ // Show explanation of why and how to get a API key.
261
+ ao_ccss_render_explain();
262
+
263
+ // Get viewport size.
264
+ $viewport = autoptimizeCriticalCSSCore::ao_ccss_viewport();
265
+
266
+ // Add hidden fields.
267
+ echo "<input class='hidden' name='autoptimize_ccss_rules' value='" . $ao_ccss_rules_raw . "'>";
268
+ echo "<input class='hidden' name='autoptimize_ccss_queue' value='" . $ao_ccss_queue_raw . "'>";
269
+ echo '<input class="hidden" name="autoptimize_ccss_viewport[w]" value="' . $viewport['w'] . '">';
270
+ echo '<input class="hidden" name="autoptimize_ccss_viewport[h]" value="' . $viewport['h'] . '">';
271
+ echo '<input class="hidden" name="autoptimize_ccss_finclude" value="' . $ao_ccss_finclude . '">';
272
+ echo '<input class="hidden" name="autoptimize_ccss_rlimit" value="' . $ao_ccss_rlimit . '">';
273
+ echo '<input class="hidden" name="autoptimize_ccss_debug" value="' . $ao_ccss_debug . '">';
274
+ echo '<input class="hidden" name="autoptimize_ccss_noptimize" value="' . $ao_ccss_noptimize . '">';
275
+ echo '<input class="hidden" name="autoptimize_css_defer_inline" value="' . esc_attr( $ao_css_defer_inline ) . '">';
276
+ echo '<input class="hidden" name="autoptimize_ccss_loggedin" value="' . $ao_ccss_loggedin . '">';
277
+ echo '<input class="hidden" name="autoptimize_ccss_forcepath" value="' . $ao_ccss_forcepath . '">';
278
+ }
279
+ // Render key panel unconditionally.
280
+ ao_ccss_render_key( $ao_ccss_key, $key['status'], $key['stmsg'], $key['msg'], $key['color'] );
281
+ ?>
282
+ <p class="submit left">
283
+ <input type="submit" class="button-primary" value="<?php _e( 'Save Changes', 'autoptimize' ); ?>" />
284
+ </p>
285
+ <?php
286
+ }
287
+ ?>
288
+ </form>
289
+ <script>
290
+ jQuery("form#settings").submit(function(){
291
+ var input = jQuery("#autoptimize_ccss_domain");
292
+ input.val(rot(input.val(), 13));
293
+ });
294
+ // rot JS from http://stackoverflow.com/a/617685/987044 .
295
+ function rot(domainstring, itype) {
296
+ return domainstring.toString().replace(/[a-zA-Z]/g, function (letter) {
297
+ return String.fromCharCode((letter <= 'Z' ? 90 : 122) >= (letter = letter.charCodeAt(0) + itype) ? letter : letter - 26);
298
+ });
299
+ }
300
+ </script>
301
+ <form id="importSettingsForm"<?php if ( $this->is_multisite_network_admin() ) { echo ' class="hidden"'; } ?>>
302
+ <span id="exportSettings" class="button-secondary"><?php _e( 'Export Settings', 'autoptimize' ); ?></span>
303
+ <input class="button-secondary" id="importSettings" type="button" value="<?php _e( 'Import Settings', 'autoptimize' ); ?>" onclick="upload();return false;" />
304
+ <input class="button-secondary" id="settingsfile" name="settingsfile" type="file" />
305
+ </form>
306
+ <div id="importdialog"></div>
307
+ </div><!-- /#autoptimize_main -->
308
+ </div><!-- /#wrap -->
309
+ <?php
310
+ if ( ! $this->is_multisite_network_admin() ) {
311
+ // Include debug panel if debug mode is enable.
312
+ if ( $ao_ccss_debug ) {
313
+ ?>
314
+ <div id="debug">
315
+ <?php
316
+ // Include debug panel.
317
+ include( 'critcss-inc/admin_settings_debug.php' );
318
+ ?>
319
+ </div><!-- /#debug -->
320
  <?php
321
+ }
322
+ echo '<script>';
323
+ include( 'critcss-inc/admin_settings_rules.js.php' );
324
+ include( 'critcss-inc/admin_settings_queue.js.php' );
325
+ include( 'critcss-inc/admin_settings_impexp.js.php' );
326
+ echo '</script>';
327
+ }
328
+ }
329
+
330
+ public static function ao_ccss_has_autorules() {
331
+ static $_has_auto_rules = null;
332
+
333
+ if ( null === $_has_auto_rules ) {
334
+ global $ao_ccss_rules;
335
+ $_has_auto_rules = false;
336
+ if ( ! empty( $ao_ccss_rules ) ) {
337
+ foreach ( array( 'types', 'paths' ) as $_typat ) {
338
+ foreach ( $ao_ccss_rules[ $_typat ] as $rule ) {
339
+ if ( ! empty( $rule['hash'] ) ) {
340
+ // we have at least one AUTO job, so all is fine.
341
+ $_has_auto_rules = true;
342
+ break;
343
  }
344
  }
345
+ if ( $_has_auto_rules ) {
346
+ break;
347
+ }
348
  }
349
  }
350
+ }
351
+
352
+ return $_has_auto_rules;
353
+ }
354
 
355
+ public function is_multisite_network_admin() {
356
+ static $_multisite_network_admin = null;
357
+
358
+ if ( null === $_multisite_network_admin ) {
359
+ if ( is_multisite() && is_network_admin() ) {
360
+ $_multisite_network_admin = true;
361
+ } else {
362
+ $_multisite_network_admin = false;
363
  }
364
+ }
365
 
366
+ return $_multisite_network_admin;
 
 
 
 
 
367
  }
368
  }
classes/autoptimizeCriticalCSSSettingsAjax.php ADDED
@@ -0,0 +1,352 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Critical CSS settings AJAX logic.
4
+ */
5
+
6
+ if ( ! defined( 'ABSPATH' ) ) {
7
+ exit;
8
+ }
9
+
10
+ class autoptimizeCriticalCSSSettingsAjax {
11
+ public function __construct()
12
+ {
13
+ // fetch all options at once and populate them individually explicitely as globals.
14
+ $all_options = autoptimizeCriticalCSSBase::fetch_options();
15
+ foreach ( $all_options as $_option => $_value ) {
16
+ global ${$_option};
17
+ ${$_option} = $_value;
18
+ }
19
+ $this->run();
20
+ }
21
+
22
+ public function run() {
23
+ // add filters.
24
+ add_action( 'wp_ajax_fetch_critcss', array( $this, 'critcss_fetch_callback' ) );
25
+ add_action( 'wp_ajax_save_critcss', array( $this, 'critcss_save_callback' ) );
26
+ add_action( 'wp_ajax_rm_critcss', array( $this, 'critcss_rm_callback' ) );
27
+ add_action( 'wp_ajax_rm_critcss_all', array( $this, 'critcss_rm_all_callback' ) );
28
+ add_action( 'wp_ajax_ao_ccss_export', array( $this, 'ao_ccss_export_callback' ) );
29
+ add_action( 'wp_ajax_ao_ccss_import', array( $this, 'ao_ccss_import_callback' ) );
30
+ }
31
+
32
+ public function critcss_fetch_callback() {
33
+ // Ajax handler to obtain a critical CSS file from the filesystem.
34
+ // Check referer.
35
+ check_ajax_referer( 'fetch_critcss_nonce', 'critcss_fetch_nonce' );
36
+
37
+ // Initialize error flag.
38
+ $error = true;
39
+
40
+ // Allow no content for MANUAL rules (as they may not exist just yet).
41
+ if ( current_user_can( 'manage_options' ) && empty( $_POST['critcssfile'] ) ) {
42
+ $content = '';
43
+ $error = false;
44
+ } elseif ( current_user_can( 'manage_options' ) && $this->critcss_check_filename( $_POST['critcssfile'] ) ) {
45
+ // Or check user permissios and filename.
46
+ // Set file path and obtain its content.
47
+ $critcssfile = AO_CCSS_DIR . strip_tags( $_POST['critcssfile'] );
48
+ if ( file_exists( $critcssfile ) ) {
49
+ $content = file_get_contents( $critcssfile );
50
+ $error = false;
51
+ }
52
+ }
53
+
54
+ // Prepare response.
55
+ if ( $error ) {
56
+ $response['code'] = '500';
57
+ $response['string'] = 'Error reading file ' . $critcssfile . '.';
58
+ } else {
59
+ $response['code'] = '200';
60
+ $response['string'] = $content;
61
+ }
62
+
63
+ // Dispatch respose.
64
+ echo json_encode( $response );
65
+
66
+ // Close ajax request.
67
+ wp_die();
68
+ }
69
+
70
+ public function critcss_save_callback() {
71
+ $error = false;
72
+ $status = false;
73
+ $response = array();
74
+
75
+ // Ajax handler to write a critical CSS to the filesystem
76
+ // Check referer.
77
+ check_ajax_referer( 'save_critcss_nonce', 'critcss_save_nonce' );
78
+
79
+ // Allow empty contents for MANUAL rules (as they are fetched later).
80
+ if ( current_user_can( 'manage_options' ) && empty( $_POST['critcssfile'] ) ) {
81
+ $critcssfile = false;
82
+ $status = true;
83
+ } elseif ( current_user_can( 'manage_options' ) && $this->critcss_check_filename( $_POST['critcssfile'] ) ) {
84
+ // Or check user permissios and filename
85
+ // Set critical CSS content.
86
+ $critcsscontents = stripslashes( $_POST['critcsscontents'] );
87
+
88
+ // If there is content and it's valid, write the file.
89
+ if ( $critcsscontents && autoptimizeCriticalCSSCore::ao_ccss_check_contents( $critcsscontents ) ) {
90
+ // Set file path and status.
91
+ $critcssfile = AO_CCSS_DIR . strip_tags( $_POST['critcssfile'] );
92
+ $status = file_put_contents( $critcssfile, $critcsscontents, LOCK_EX );
93
+ // Or set as error.
94
+ } else {
95
+ $error = true;
96
+ }
97
+ // Or just set an error.
98
+ } else {
99
+ $error = true;
100
+ }
101
+
102
+ // Prepare response.
103
+ if ( ! $status || $error ) {
104
+ $response['code'] = '500';
105
+ $response['string'] = 'Error saving file ' . $critcssfile . '.';
106
+ } else {
107
+ $response['code'] = '200';
108
+ if ( $critcssfile ) {
109
+ $response['string'] = 'File ' . $critcssfile . ' saved.';
110
+ } else {
111
+ $response['string'] = 'Empty content do not need to be saved.';
112
+ }
113
+ }
114
+
115
+ // Dispatch respose.
116
+ echo json_encode( $response );
117
+
118
+ // Close ajax request.
119
+ wp_die();
120
+ }
121
+
122
+
123
+ public function critcss_rm_callback() {
124
+ // Ajax handler to delete a critical CSS from the filesystem
125
+ // Check referer.
126
+ check_ajax_referer( 'rm_critcss_nonce', 'critcss_rm_nonce' );
127
+
128
+ // Initialize error and status flags.
129
+ $error = true;
130
+ $status = false;
131
+
132
+ // Allow no file for MANUAL rules (as they may not exist just yet).
133
+ if ( current_user_can( 'manage_options' ) && empty( $_POST['critcssfile'] ) ) {
134
+ $error = false;
135
+ } elseif ( current_user_can( 'manage_options' ) && $this->critcss_check_filename( $_POST['critcssfile'] ) ) {
136
+ // Or check user permissios and filename
137
+ // Set file path and delete it.
138
+ $critcssfile = AO_CCSS_DIR . strip_tags( $_POST['critcssfile'] );
139
+ if ( file_exists( $critcssfile ) ) {
140
+ $status = unlink( $critcssfile );
141
+ $error = false;
142
+ }
143
+ }
144
+
145
+ // Prepare response.
146
+ if ( $error ) {
147
+ $response['code'] = '500';
148
+ $response['string'] = 'Error removing file ' . $critcssfile . '.';
149
+ } else {
150
+ $response['code'] = '200';
151
+ if ( $status ) {
152
+ $response['string'] = 'File ' . $critcssfile . ' removed.';
153
+ } else {
154
+ $response['string'] = 'No file to be removed.';
155
+ }
156
+ }
157
+
158
+ // Dispatch respose.
159
+ echo json_encode( $response );
160
+
161
+ // Close ajax request.
162
+ wp_die();
163
+ }
164
+
165
+ public function critcss_rm_all_callback() {
166
+ // Ajax handler to delete a critical CSS from the filesystem
167
+ // Check referer.
168
+ check_ajax_referer( 'rm_critcss_all_nonce', 'critcss_rm_all_nonce' );
169
+
170
+ // Initialize error and status flags.
171
+ $error = true;
172
+ $status = false;
173
+
174
+ // Remove all ccss files on filesystem.
175
+ if ( current_user_can( 'manage_options' ) ) {
176
+ if ( file_exists( AO_CCSS_DIR ) && is_dir( AO_CCSS_DIR ) ) {
177
+ array_map( 'unlink', glob( AO_CCSS_DIR . 'ccss_*.css', GLOB_BRACE ) );
178
+ $error = false;
179
+ $status = true;
180
+ }
181
+ }
182
+
183
+ // Prepare response.
184
+ if ( $error ) {
185
+ $response['code'] = '500';
186
+ $response['string'] = 'Error removing all critical CSS files.';
187
+ } else {
188
+ $response['code'] = '200';
189
+ if ( $status ) {
190
+ $response['string'] = 'Critical CSS Files removed.';
191
+ } else {
192
+ $response['string'] = 'No file removed.';
193
+ }
194
+ }
195
+
196
+ // Dispatch respose.
197
+ echo json_encode( $response );
198
+
199
+ // Close ajax request.
200
+ wp_die();
201
+ }
202
+
203
+ public function ao_ccss_export_callback() {
204
+ // Ajax handler export settings
205
+ // Check referer.
206
+ check_ajax_referer( 'ao_ccss_export_nonce', 'ao_ccss_export_nonce' );
207
+
208
+ if ( ! class_exists( 'ZipArchive' ) ) {
209
+ $response['code'] = '500';
210
+ $response['msg'] = 'PHP ZipArchive not present, cannot create zipfile';
211
+ echo json_encode( $response );
212
+ wp_die();
213
+ }
214
+
215
+ // Init array, get options and prepare the raw object.
216
+ $settings = array();
217
+ $settings['rules'] = get_option( 'autoptimize_ccss_rules' );
218
+ $settings['additional'] = get_option( 'autoptimize_ccss_additional' );
219
+ $settings['viewport'] = get_option( 'autoptimize_ccss_viewport' );
220
+ $settings['finclude'] = get_option( 'autoptimize_ccss_finclude' );
221
+ $settings['rlimit'] = get_option( 'autoptimize_ccss_rlimit' );
222
+ $settings['noptimize'] = get_option( 'autoptimize_ccss_noptimize' );
223
+ $settings['debug'] = get_option( 'autoptimize_ccss_debug' );
224
+ $settings['key'] = get_option( 'autoptimize_ccss_key' );
225
+
226
+ // Initialize error flag.
227
+ $error = true;
228
+
229
+ // Check user permissions.
230
+ if ( current_user_can( 'manage_options' ) ) {
231
+ // Prepare settings file path and content.
232
+ $exportfile = AO_CCSS_DIR . 'settings.json';
233
+ $contents = json_encode( $settings );
234
+ $status = file_put_contents( $exportfile, $contents, LOCK_EX );
235
+ $error = false;
236
+ }
237
+
238
+ // Prepare archive.
239
+ $zipfile = AO_CCSS_DIR . date( 'Ymd-H\hi' ) . '_ao_ccss_settings.zip';
240
+ $file = pathinfo( $zipfile, PATHINFO_BASENAME );
241
+ $zip = new ZipArchive();
242
+ $ret = $zip->open( $zipfile, ZipArchive::CREATE );
243
+ if ( true !== $ret ) {
244
+ $error = true;
245
+ } else {
246
+ $zip->addFile( AO_CCSS_DIR . 'settings.json', 'settings.json' );
247
+ if ( file_exists( AO_CCSS_DIR . 'queue.json' ) ) {
248
+ $zip->addFile( AO_CCSS_DIR . 'queue.json', 'queue.json' );
249
+ }
250
+ $options = array(
251
+ 'add_path' => './',
252
+ 'remove_all_path' => true,
253
+ );
254
+ $zip->addGlob( AO_CCSS_DIR . '*.css', 0, $options );
255
+ $zip->close();
256
+ }
257
+
258
+ // Prepare response.
259
+ if ( ! $status || $error ) {
260
+ $response['code'] = '500';
261
+ $response['msg'] = 'Error saving file ' . $file . ', code: ' . $ret;
262
+ } else {
263
+ $response['code'] = '200';
264
+ $response['msg'] = 'File ' . $file . ' saved.';
265
+ $response['file'] = $file;
266
+ }
267
+
268
+ // Dispatch respose.
269
+ echo json_encode( $response );
270
+
271
+ // Close ajax request.
272
+ wp_die();
273
+ }
274
+
275
+ public function ao_ccss_import_callback() {
276
+ // Ajax handler import settings
277
+ // Check referer.
278
+ check_ajax_referer( 'ao_ccss_import_nonce', 'ao_ccss_import_nonce' );
279
+
280
+ // Initialize error flag.
281
+ $error = false;
282
+
283
+ // Process an uploaded file with no errors.
284
+ if ( ! $_FILES['file']['error'] ) {
285
+ // Save file to the cache directory.
286
+ $zipfile = AO_CCSS_DIR . $_FILES['file']['name'];
287
+ move_uploaded_file( $_FILES['file']['tmp_name'], $zipfile );
288
+
289
+ // Extract archive.
290
+ $zip = new ZipArchive;
291
+ if ( $zip->open( $zipfile ) === true ) {
292
+ $zip->extractTo( AO_CCSS_DIR );
293
+ $zip->close();
294
+ } else {
295
+ $error = 'extracting';
296
+ }
297
+
298
+ if ( ! $error ) {
299
+ // Archive extraction ok, continue settings importing
300
+ // Settings file.
301
+ $importfile = AO_CCSS_DIR . 'settings.json';
302
+
303
+ if ( file_exists( $importfile ) ) {
304
+ // Get settings and turn them into an object.
305
+ $settings = json_decode( file_get_contents( $importfile ), true );
306
+
307
+ // Update options.
308
+ update_option( 'autoptimize_ccss_rules', $settings['rules'] );
309
+ update_option( 'autoptimize_ccss_additional', $settings['additional'] );
310
+ update_option( 'autoptimize_ccss_viewport', $settings['viewport'] );
311
+ update_option( 'autoptimize_ccss_finclude', $settings['finclude'] );
312
+ update_option( 'autoptimize_ccss_rlimit', $settings['rlimit'] );
313
+ update_option( 'autoptimize_ccss_noptimize', $settings['noptimize'] );
314
+ update_option( 'autoptimize_ccss_debug', $settings['debug'] );
315
+ update_option( 'autoptimize_ccss_key', $settings['key'] );
316
+ } else {
317
+ // Settings file doesn't exist, update error flag.
318
+ $error = 'settings file does not exist';
319
+ }
320
+ }
321
+ }
322
+
323
+ // Prepare response.
324
+ if ( $error ) {
325
+ $response['code'] = '500';
326
+ $response['msg'] = 'Error importing settings: ' . $error;
327
+ } else {
328
+ $response['code'] = '200';
329
+ $response['msg'] = 'Settings imported successfully';
330
+ }
331
+
332
+ // Dispatch respose.
333
+ echo json_encode( $response );
334
+
335
+ // Close ajax request.
336
+ wp_die();
337
+ }
338
+
339
+ public function critcss_check_filename( $filename ) {
340
+ // Try to avoid directory traversal when reading/writing/deleting critical CSS files.
341
+ if ( strpos( $filename, 'ccss_' ) !== 0 ) {
342
+ return false;
343
+ } elseif ( substr( $filename, -4, 4 ) !== '.css' ) {
344
+ return false;
345
+ } elseif ( sanitize_file_name( $filename ) !== $filename ) {
346
+ // Use WordPress core's sanitize_file_name to see if anything fishy is going on.
347
+ return false;
348
+ } else {
349
+ return true;
350
+ }
351
+ }
352
+ }
classes/autoptimizeExtra.php CHANGED
@@ -64,7 +64,7 @@ class autoptimizeExtra
64
  }
65
  add_filter( 'autoptimize_filter_settingsscreen_tabs', array( $this, 'add_extra_tab' ) );
66
  } else {
67
- $this->run_on_frontend();
68
  }
69
  }
70
 
@@ -142,8 +142,16 @@ class autoptimizeExtra
142
  return $merged;
143
  }
144
 
145
- protected function run_on_frontend()
146
  {
 
 
 
 
 
 
 
 
147
  $options = $this->options;
148
 
149
  // Disable emojis if specified.
@@ -227,6 +235,10 @@ class autoptimizeExtra
227
  if ( ! preg_match( '/rel=["\']dns-prefetch["\']/', $matches[0][ $i ] ) ) {
228
  // Get fonts name.
229
  $font = str_replace( array( '%7C', '%7c' ), '|', $font );
 
 
 
 
230
  $font = explode( 'family=', $font );
231
  $font = ( isset( $font[1] ) ) ? explode( '&', $font[1] ) : array();
232
  // Add font to $fonts[$i] but make sure not to pollute with an empty family!
64
  }
65
  add_filter( 'autoptimize_filter_settingsscreen_tabs', array( $this, 'add_extra_tab' ) );
66
  } else {
67
+ add_action( 'wp', array( $this, 'run_on_frontend' ) );
68
  }
69
  }
70
 
142
  return $merged;
143
  }
144
 
145
+ public function run_on_frontend()
146
  {
147
+ // only run the Extra optimizations on frontend if general conditions
148
+ // for optimizations are met, this to ensure e.g. removing querystrings
149
+ // is not done when optimizing for logged in users is off, breaking
150
+ // some pagebuilders (Divi & Elementor).
151
+ if ( false === autoptimizeMain::should_buffer() ) {
152
+ return;
153
+ }
154
+
155
  $options = $this->options;
156
 
157
  // Disable emojis if specified.
235
  if ( ! preg_match( '/rel=["\']dns-prefetch["\']/', $matches[0][ $i ] ) ) {
236
  // Get fonts name.
237
  $font = str_replace( array( '%7C', '%7c' ), '|', $font );
238
+ if ( strpos( $font, 'fonts.googleapis.com/css2' ) !== false ) {
239
+ // (Somewhat) change Google Fonts APIv2 syntax back to v1.
240
+ $font = str_replace( array( 'wght@', 'wght%40', ';', '%3B' ), array( '', '', ',', ',' ), $font );
241
+ }
242
  $font = explode( 'family=', $font );
243
  $font = ( isset( $font[1] ) ) ? explode( '&', $font[1] ) : array();
244
  // Add font to $fonts[$i] but make sure not to pollute with an empty family!
classes/autoptimizeHTML.php CHANGED
@@ -16,7 +16,11 @@ class autoptimizeHTML extends autoptimizeBase
16
  */
17
  private $keepcomments = false;
18
 
19
- /** @var bool */
 
 
 
 
20
  private $forcexhtml = false;
21
 
22
  /**
16
  */
17
  private $keepcomments = false;
18
 
19
+ /**
20
+ * Whether to force xhtml compatibility.
21
+ *
22
+ * @var bool
23
+ */
24
  private $forcexhtml = false;
25
 
26
  /**
classes/autoptimizeImages.php CHANGED
@@ -111,6 +111,10 @@ class autoptimizeImages
111
  public function run_on_frontend() {
112
  if ( ! $this->should_run() ) {
113
  if ( $this->should_lazyload() ) {
 
 
 
 
114
  add_filter(
115
  'autoptimize_html_after_minify',
116
  array( $this, 'filter_lazyload_images' ),
@@ -159,6 +163,10 @@ class autoptimizeImages
159
  }
160
 
161
  if ( $this->should_lazyload() ) {
 
 
 
 
162
  add_action(
163
  'wp_footer',
164
  array( $this, 'add_lazyload_js_footer' ),
@@ -545,7 +553,7 @@ class autoptimizeImages
545
  }
546
 
547
  // do lazyload stuff.
548
- if ( $this->should_lazyload( $in ) ) {
549
  // first do lpiq placeholder logic.
550
  if ( strpos( $url, $this->get_imgopt_host() ) === 0 ) {
551
  // if all img src have been replaced during srcset, we have to extract the
@@ -738,11 +746,11 @@ class autoptimizeImages
738
  $_get_size = $this->get_size_from_tag( $tag );
739
  $width = $_get_size['width'];
740
  $height = $_get_size['height'];
741
- if ( false === $width ) {
742
- $widht = 210; // default width for SVG placeholder.
743
  }
744
- if ( false === $height ) {
745
- $heigth = $width / 3 * 2; // if no height, base it on width using the 3/2 aspect ratio.
746
  }
747
 
748
  // insert the actual lazyload stuff.
@@ -783,16 +791,21 @@ class autoptimizeImages
783
  $lazysizes_js = str_replace( AUTOPTIMIZE_WP_SITE_URL, $cdn_url, $lazysizes_js );
784
  }
785
 
 
 
 
 
 
786
  // Adds lazyload CSS & JS to footer, using echo because wp_enqueue_script seems not to support pushing attributes (async).
787
  echo apply_filters( 'autoptimize_filter_imgopt_lazyload_cssoutput', '<style>.lazyload,.lazyloading{opacity:0;}.lazyloaded{opacity:1;transition:opacity 300ms;}</style><noscript><style>.lazyload{display:none;}</style></noscript>' );
788
- echo apply_filters( 'autoptimize_filter_imgopt_lazyload_jsconfig', '<script' . $noptimize_flag . '>window.lazySizesConfig=window.lazySizesConfig||{};window.lazySizesConfig.loadMode=1;</script>' );
789
- echo apply_filters( 'autoptimize_filter_imgopt_lazyload_js', '<script async' . $noptimize_flag . ' src=\'' . $lazysizes_js . '\'></script>' );
790
 
791
  // And add webp detection and loading JS.
792
  if ( $this->should_webp() ) {
793
  $_webp_detect = "function c_webp(A){var n=new Image;n.onload=function(){var e=0<n.width&&0<n.height;A(e)},n.onerror=function(){A(!1)},n.src='data:image/webp;base64,UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA=='}function s_webp(e){window.supportsWebP=e}c_webp(s_webp);";
794
  $_webp_load = "document.addEventListener('lazybeforeunveil',function({target:c}){supportsWebP&&['data-src','data-srcset'].forEach(function(a){attr=c.getAttribute(a),null!==attr&&c.setAttribute(a,attr.replace(/\/client\//,'/client/to_webp,'))})});";
795
- echo apply_filters( 'autoptimize_filter_imgopt_webp_js', '<script' . $noptimize_flag . '>' . $_webp_detect . $_webp_load . '</script>' );
796
  }
797
  }
798
 
@@ -928,9 +941,11 @@ class autoptimizeImages
928
  }
929
 
930
  public function maybe_fix_missing_quotes( $tag_in ) {
931
- // W3TC's Minify_HTML class removes quotes around attribute value, this re-adds them for the class attribute only so we can safely add the lazyload class.
932
  if ( file_exists( WP_PLUGIN_DIR . '/w3-total-cache/w3-total-cache.php' ) && class_exists( 'Minify_HTML' ) && apply_filters( 'autoptimize_filter_imgopt_fixquotes', true ) ) {
933
- return preg_replace( '/class\s?=([^("|\')]*)(\s|>)/U', 'class=\'$1\'$2', $tag_in );
 
 
934
  } else {
935
  return $tag_in;
936
  }
111
  public function run_on_frontend() {
112
  if ( ! $this->should_run() ) {
113
  if ( $this->should_lazyload() ) {
114
+ add_filter(
115
+ 'wp_lazy_loading_enabled',
116
+ '__return_false'
117
+ );
118
  add_filter(
119
  'autoptimize_html_after_minify',
120
  array( $this, 'filter_lazyload_images' ),
163
  }
164
 
165
  if ( $this->should_lazyload() ) {
166
+ add_filter(
167
+ 'wp_lazy_loading_enabled',
168
+ '__return_false'
169
+ );
170
  add_action(
171
  'wp_footer',
172
  array( $this, 'add_lazyload_js_footer' ),
553
  }
554
 
555
  // do lazyload stuff.
556
+ if ( $this->should_lazyload( $in ) && ! empty( $url ) ) {
557
  // first do lpiq placeholder logic.
558
  if ( strpos( $url, $this->get_imgopt_host() ) === 0 ) {
559
  // if all img src have been replaced during srcset, we have to extract the
746
  $_get_size = $this->get_size_from_tag( $tag );
747
  $width = $_get_size['width'];
748
  $height = $_get_size['height'];
749
+ if ( false === $width || empty( $width ) ) {
750
+ $width = 210; // default width for SVG placeholder.
751
  }
752
+ if ( false === $height || empty( $height ) ) {
753
+ $height = $width / 3 * 2; // if no height, base it on width using the 3/2 aspect ratio.
754
  }
755
 
756
  // insert the actual lazyload stuff.
791
  $lazysizes_js = str_replace( AUTOPTIMIZE_WP_SITE_URL, $cdn_url, $lazysizes_js );
792
  }
793
 
794
+ $type_js = '';
795
+ if ( apply_filters( 'autoptimize_filter_cssjs_addtype', false ) ) {
796
+ $type_js = ' type="text/javascript"';
797
+ }
798
+
799
  // Adds lazyload CSS & JS to footer, using echo because wp_enqueue_script seems not to support pushing attributes (async).
800
  echo apply_filters( 'autoptimize_filter_imgopt_lazyload_cssoutput', '<style>.lazyload,.lazyloading{opacity:0;}.lazyloaded{opacity:1;transition:opacity 300ms;}</style><noscript><style>.lazyload{display:none;}</style></noscript>' );
801
+ echo apply_filters( 'autoptimize_filter_imgopt_lazyload_jsconfig', '<script' . $type_js . $noptimize_flag . '>window.lazySizesConfig=window.lazySizesConfig||{};window.lazySizesConfig.loadMode=1;</script>' );
802
+ echo apply_filters( 'autoptimize_filter_imgopt_lazyload_js', '<script async' . $type_js . $noptimize_flag . ' src=\'' . $lazysizes_js . '\'></script>' );
803
 
804
  // And add webp detection and loading JS.
805
  if ( $this->should_webp() ) {
806
  $_webp_detect = "function c_webp(A){var n=new Image;n.onload=function(){var e=0<n.width&&0<n.height;A(e)},n.onerror=function(){A(!1)},n.src='data:image/webp;base64,UklGRhoAAABXRUJQVlA4TA0AAAAvAAAAEAcQERGIiP4HAA=='}function s_webp(e){window.supportsWebP=e}c_webp(s_webp);";
807
  $_webp_load = "document.addEventListener('lazybeforeunveil',function({target:c}){supportsWebP&&['data-src','data-srcset'].forEach(function(a){attr=c.getAttribute(a),null!==attr&&c.setAttribute(a,attr.replace(/\/client\//,'/client/to_webp,'))})});";
808
+ echo apply_filters( 'autoptimize_filter_imgopt_webp_js', '<script' . $type_js . $noptimize_flag . '>' . $_webp_detect . $_webp_load . '</script>' );
809
  }
810
  }
811
 
941
  }
942
 
943
  public function maybe_fix_missing_quotes( $tag_in ) {
944
+ // W3TC's Minify_HTML class removes quotes around attribute value, this re-adds them for the class and width/height attributes so we can lazyload properly.
945
  if ( file_exists( WP_PLUGIN_DIR . '/w3-total-cache/w3-total-cache.php' ) && class_exists( 'Minify_HTML' ) && apply_filters( 'autoptimize_filter_imgopt_fixquotes', true ) ) {
946
+ $tag_out = preg_replace( '/class\s?=([^("|\')]*)(\s|>)/U', 'class=\'$1\'$2', $tag_in );
947
+ $tag_out = preg_replace( '/\s(width|height)=(?:"|\')?([^\s"\'>]*)(?:"|\')?/', ' $1=\'$2\'', $tag_out );
948
+ return $tag_out;
949
  } else {
950
  return $tag_in;
951
  }
classes/autoptimizeMain.php CHANGED
@@ -59,9 +59,10 @@ class autoptimizeMain
59
 
60
  add_action( 'autoptimize_setup_done', array( $this, 'version_upgrades_check' ) );
61
  add_action( 'autoptimize_setup_done', array( $this, 'check_cache_and_run' ) );
62
- add_action( 'autoptimize_setup_done', array( $this, 'maybe_run_ao_extra' ) );
63
- add_action( 'autoptimize_setup_done', array( $this, 'maybe_run_partners_tab' ) );
64
- add_action( 'autoptimize_setup_done', array( $this, 'maybe_run_criticalcss_tab' ) );
 
65
 
66
  add_action( 'init', array( $this, 'load_textdomain' ) );
67
  add_action( 'admin_init', array( 'PAnD', 'init' ) );
@@ -71,12 +72,9 @@ class autoptimizeMain
71
  add_action( 'init', 'autoptimizeOptionWrapper::check_multisite_on_saving_options' );
72
  }
73
 
74
- register_activation_hook( $this->filepath, array( $this, 'on_activate' ) );
75
- }
76
-
77
- public function on_activate()
78
- {
79
  register_uninstall_hook( $this->filepath, 'autoptimizeMain::on_uninstall' );
 
80
  }
81
 
82
  public function load_textdomain()
@@ -216,11 +214,18 @@ class autoptimizeMain
216
  }
217
  }
218
 
219
- public function maybe_run_criticalcss_tab()
 
 
 
 
 
 
 
 
220
  {
221
- // Loads criticalcss tab code if in admin (and not in admin-ajax.php)!
222
- if ( autoptimizeConfig::is_admin_and_not_ajax() && ! autoptimizeUtils::is_plugin_active( 'autoptimize-criticalcss/ao_criticss_aas.php' ) ) {
223
- new autoptimizeCriticalCSSSettings();
224
  }
225
  }
226
 
@@ -348,7 +353,7 @@ class autoptimizeMain
348
  // If setting says not to optimize cart/checkout.
349
  if ( false === $ao_noptimize && 'on' !== autoptimizeOptionWrapper::get_option( 'autoptimize_optimize_checkout', 'off' ) ) {
350
  // Checking for woocommerce, easy digital downloads and wp ecommerce...
351
- foreach ( array( 'is_checkout', 'is_cart', 'edd_is_checkout', 'wpsc_is_cart', 'wpsc_is_checkout' ) as $func ) {
352
  if ( function_exists( $func ) && $func() ) {
353
  $ao_noptimize = true;
354
  break;
@@ -558,12 +563,29 @@ class autoptimizeMain
558
  'autoptimize_imgopt_launched',
559
  'autoptimize_imgopt_settings',
560
  'autoptimize_minify_excluded',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
561
  );
562
 
563
  if ( ! is_multisite() ) {
564
  foreach ( $delete_options as $del_opt ) {
565
  delete_option( $del_opt );
566
  }
 
567
  } else {
568
  global $wpdb;
569
  $blog_ids = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" );
@@ -573,12 +595,43 @@ class autoptimizeMain
573
  foreach ( $delete_options as $del_opt ) {
574
  delete_option( $del_opt );
575
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
576
  }
577
  switch_to_blog( $original_blog_id );
 
 
578
  }
 
 
579
 
580
- if ( wp_get_schedule( 'ao_cachechecker' ) ) {
581
- wp_clear_scheduled_hook( 'ao_cachechecker' );
 
 
 
 
582
  }
583
  }
584
 
59
 
60
  add_action( 'autoptimize_setup_done', array( $this, 'version_upgrades_check' ) );
61
  add_action( 'autoptimize_setup_done', array( $this, 'check_cache_and_run' ) );
62
+ add_action( 'autoptimize_setup_done', array( $this, 'maybe_run_ao_extra' ), 15 );
63
+ add_action( 'autoptimize_setup_done', array( $this, 'maybe_run_partners_tab' ), 20 );
64
+ add_action( 'autoptimize_setup_done', array( $this, 'maybe_run_criticalcss' ), 11 );
65
+ add_action( 'autoptimize_setup_done', array( $this, 'maybe_run_notfound_fallback' ), 10 );
66
 
67
  add_action( 'init', array( $this, 'load_textdomain' ) );
68
  add_action( 'admin_init', array( 'PAnD', 'init' ) );
72
  add_action( 'init', 'autoptimizeOptionWrapper::check_multisite_on_saving_options' );
73
  }
74
 
75
+ // register uninstall & deactivation hooks.
 
 
 
 
76
  register_uninstall_hook( $this->filepath, 'autoptimizeMain::on_uninstall' );
77
+ register_deactivation_hook( $this->filepath, 'autoptimizeMain::on_deactivation' );
78
  }
79
 
80
  public function load_textdomain()
214
  }
215
  }
216
 
217
+ public function maybe_run_criticalcss()
218
+ {
219
+ // Loads criticalcss if the power-up is not active and if the filter returns true.
220
+ if ( apply_filters( 'autoptimize_filter_criticalcss_active', true ) && ! autoptimizeUtils::is_plugin_active( 'autoptimize-criticalcss/ao_criticss_aas.php' ) ) {
221
+ new autoptimizeCriticalCSSBase();
222
+ }
223
+ }
224
+
225
+ public function maybe_run_notfound_fallback()
226
  {
227
+ if ( autoptimizeCache::do_fallback() ) {
228
+ add_action( 'template_redirect', array( 'autoptimizeCache', 'wordpress_notfound_fallback' ) );
 
229
  }
230
  }
231
 
353
  // If setting says not to optimize cart/checkout.
354
  if ( false === $ao_noptimize && 'on' !== autoptimizeOptionWrapper::get_option( 'autoptimize_optimize_checkout', 'off' ) ) {
355
  // Checking for woocommerce, easy digital downloads and wp ecommerce...
356
+ foreach ( array( 'is_checkout', 'is_cart', 'is_account_page', 'edd_is_checkout', 'wpsc_is_cart', 'wpsc_is_checkout' ) as $func ) {
357
  if ( function_exists( $func ) && $func() ) {
358
  $ao_noptimize = true;
359
  break;
563
  'autoptimize_imgopt_launched',
564
  'autoptimize_imgopt_settings',
565
  'autoptimize_minify_excluded',
566
+ 'autoptimize_cache_fallback',
567
+ 'autoptimize_ccss_rules',
568
+ 'autoptimize_ccss_additional',
569
+ 'autoptimize_ccss_queue',
570
+ 'autoptimize_ccss_viewport',
571
+ 'autoptimize_ccss_finclude',
572
+ 'autoptimize_ccss_rlimit',
573
+ 'autoptimize_ccss_noptimize',
574
+ 'autoptimize_ccss_debug',
575
+ 'autoptimize_ccss_key',
576
+ 'autoptimize_ccss_keyst',
577
+ 'autoptimize_ccss_version',
578
+ 'autoptimize_ccss_loggedin',
579
+ 'autoptimize_ccss_forcepath',
580
+ 'autoptimize_ccss_deferjquery',
581
+ 'autoptimize_ccss_domain',
582
  );
583
 
584
  if ( ! is_multisite() ) {
585
  foreach ( $delete_options as $del_opt ) {
586
  delete_option( $del_opt );
587
  }
588
+ autoptimizeMain::remove_cronjobs();
589
  } else {
590
  global $wpdb;
591
  $blog_ids = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" );
595
  foreach ( $delete_options as $del_opt ) {
596
  delete_option( $del_opt );
597
  }
598
+ autoptimizeMain::remove_cronjobs();
599
+ }
600
+ switch_to_blog( $original_blog_id );
601
+ }
602
+
603
+ // Remove AO CCSS cached files and directory.
604
+ $ao_ccss_dir = WP_CONTENT_DIR . '/uploads/ao_ccss/';
605
+ if ( file_exists( $ao_ccss_dir ) && is_dir( $ao_ccss_dir ) ) {
606
+ // fixme: should check for subdirs when in multisite and remove contents of those as well.
607
+ array_map( 'unlink', glob( AO_CCSS_DIR . '*.{css,html,json,log,zip,lock}', GLOB_BRACE ) );
608
+ rmdir( AO_CCSS_DIR );
609
+ }
610
+ }
611
+
612
+ public static function on_deactivation()
613
+ {
614
+ if ( is_multisite() && is_network_admin() ) {
615
+ global $wpdb;
616
+ $blog_ids = $wpdb->get_col( "SELECT blog_id FROM $wpdb->blogs" );
617
+ $original_blog_id = get_current_blog_id();
618
+ foreach ( $blog_ids as $blog_id ) {
619
+ switch_to_blog( $blog_id );
620
+ autoptimizeMain::remove_cronjobs();
621
  }
622
  switch_to_blog( $original_blog_id );
623
+ } else {
624
+ autoptimizeMain::remove_cronjobs();
625
  }
626
+ autoptimizeCache::clearall();
627
+ }
628
 
629
+ public static function remove_cronjobs() {
630
+ // Remove scheduled events.
631
+ foreach ( array( 'ao_cachechecker', 'ao_ccss_queue', 'ao_ccss_maintenance' ) as $_event ) {
632
+ if ( wp_get_schedule( $_event ) ) {
633
+ wp_clear_scheduled_hook( $_event );
634
+ }
635
  }
636
  }
637
 
classes/autoptimizeScripts.php CHANGED
@@ -1,4 +1,7 @@
1
  <?php
 
 
 
2
 
3
  if ( ! defined( 'ABSPATH' ) ) {
4
  exit;
@@ -6,60 +9,212 @@ if ( ! defined( 'ABSPATH' ) ) {
6
 
7
  class autoptimizeScripts extends autoptimizeBase
8
  {
 
 
 
 
 
 
9
  private $scripts = array();
10
- private $move = array(
 
 
 
 
 
 
11
  'first' => array(),
12
- 'last' => array()
13
  );
14
 
 
 
 
 
 
15
  private $dontmove = array(
16
- 'document.write','html5.js','show_ads.js','google_ad','histats.com/js','statcounter.com/counter/counter.js',
17
- 'ws.amazon.com/widgets','media.fastclick.net','/ads/','comment-form-quicktags/quicktags.php','edToolbar',
18
- 'intensedebate.com','scripts.chitika.net/','_gaq.push','jotform.com/','admin-bar.min.js','GoogleAnalyticsObject',
19
- 'plupload.full.min.js','syntaxhighlighter','adsbygoogle','gist.github.com','_stq','nonce','post_id','data-noptimize'
20
- ,'logHuman'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  );
22
- private $domove = array(
23
- 'gaJsHost','load_cmc','jd.gallery.transitions.js','swfobject.embedSWF(','tiny_mce.js','tinyMCEPreInit.go'
 
 
 
 
 
 
 
 
 
 
 
24
  );
 
 
 
 
 
 
25
  private $domovelast = array(
26
- 'addthis.com','/afsonline/show_afs_search.js','disqus.js','networkedblogs.com/getnetworkwidget','infolinks.com/js/',
27
- 'jd.gallery.js.php','jd.gallery.transitions.js','swfobject.embedSWF(','linkwithin.com/widget.js','tiny_mce.js','tinyMCEPreInit.go'
 
 
 
 
 
 
 
 
 
28
  );
 
 
 
 
 
 
29
  public $cdn_url = '';
30
 
31
- private $aggregate = true;
32
- private $trycatch = false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  private $alreadyminified = false;
34
- private $forcehead = true;
35
- private $include_inline = false;
36
- private $jscode = '';
37
- private $url = '';
38
- private $restofcontent = '';
39
- private $md5hash = '';
40
- private $whitelist = '';
41
- private $jsremovables = array();
42
- private $inject_min_late = '';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  private $minify_excluded = true;
44
 
45
- // Reads the page and collects script tags.
 
 
 
 
46
  public function read( $options )
47
  {
48
- $noptimizeJS = apply_filters( 'autoptimize_filter_js_noptimize', false, $this->content );
49
- if ( $noptimizeJS ) {
50
  return false;
51
  }
52
 
53
  // only optimize known good JS?
54
- $whitelistJS = apply_filters( 'autoptimize_filter_js_whitelist', '', $this->content );
55
- if ( ! empty( $whitelistJS ) ) {
56
- $this->whitelist = array_filter( array_map( 'trim', explode( ',', $whitelistJS ) ) );
57
  }
58
 
59
  // is there JS we should simply remove?
60
- $removableJS = apply_filters( 'autoptimize_filter_js_removables', '', $this->content );
61
- if ( !empty( $removableJS ) ) {
62
- $this->jsremovables = array_filter( array_map( 'trim', explode( ',', $removableJS ) ) );
63
  }
64
 
65
  // only header?
@@ -98,22 +253,23 @@ class autoptimizeScripts extends autoptimizeBase
98
  $this->minify_excluded = apply_filters( 'autoptimize_filter_js_minify_excluded', $this->minify_excluded, '' );
99
 
100
  // get extra exclusions settings or filter.
101
- $excludeJS = $options['js_exclude'];
102
- $excludeJS = apply_filters( 'autoptimize_filter_js_exclude', $excludeJS, $this->content );
103
-
104
- if ( '' !== $excludeJS ) {
105
- if ( is_array( $excludeJS ) ) {
106
- if ( ( $removeKeys = array_keys( $excludeJS, 'remove' ) ) !== false ) {
107
- foreach ( $removeKeys as $removeKey ) {
108
- unset( $excludeJS[$removeKey] );
109
- $this->jsremovables[] = $removeKey;
 
110
  }
111
  }
112
- $exclJSArr = array_keys( $excludeJS );
113
  } else {
114
- $exclJSArr = array_filter( array_map( 'trim', explode( ',', $excludeJS ) ) );
115
  }
116
- $this->dontmove = array_merge( $exclJSArr, $this->dontmove );
117
  }
118
 
119
  // Should we add try-catch?
@@ -134,19 +290,19 @@ class autoptimizeScripts extends autoptimizeBase
134
  $this->cdn_url = $options['cdn_url'];
135
 
136
  // noptimize me.
137
- $this->content = $this->hide_noptimize($this->content);
138
 
139
  // Save IE hacks.
140
- $this->content = $this->hide_iehacks($this->content);
141
 
142
  // comments.
143
- $this->content = $this->hide_comments($this->content);
144
 
145
  // Get script files.
146
  if ( preg_match_all( '#<script.*</script>#Usmi', $this->content, $matches ) ) {
147
- foreach( $matches[0] as $tag ) {
148
  // only consider script aggregation for types whitelisted in should_aggregate-function.
149
- $should_aggregate = $this->should_aggregate($tag);
150
  if ( ! $should_aggregate ) {
151
  $tag = '';
152
  continue;
@@ -154,27 +310,27 @@ class autoptimizeScripts extends autoptimizeBase
154
 
155
  if ( preg_match( '#<script[^>]*src=("|\')([^>]*)("|\')#Usmi', $tag, $source ) ) {
156
  // non-inline script.
157
- if ( $this->isremovable($tag, $this->jsremovables) ) {
158
  $this->content = str_replace( $tag, '', $this->content );
159
  continue;
160
  }
161
 
162
- $origTag = null;
163
- $url = current( explode( '?', $source[2], 2 ) );
164
- $path = $this->getpath($url);
165
- if ( false !== $path && preg_match( '#\.js$#', $path ) && $this->ismergeable($tag) ) {
166
  // ok to optimize, add to array.
167
  $this->scripts[] = $path;
168
  } else {
169
- $origTag = $tag;
170
- $newTag = $tag;
171
 
172
  // non-mergeable script (excluded or dynamic or external).
173
- if ( is_array( $excludeJS ) ) {
174
  // should we add flags?
175
- foreach ( $excludeJS as $exclTag => $exclFlags) {
176
- if ( false !== strpos( $origTag, $exclTag ) && in_array( $exclFlags, array( 'async', 'defer' ) ) ) {
177
- $newTag = str_replace( '<script ', '<script ' . $exclFlags . ' ', $newTag );
178
  }
179
  }
180
  }
@@ -186,25 +342,28 @@ class autoptimizeScripts extends autoptimizeBase
186
  $consider_minified_array = apply_filters( 'autoptimize_filter_js_consider_minified', false );
187
  if ( ( false === $this->aggregate && str_replace( $this->dontmove, '', $path ) === $path ) || ( true === $this->aggregate && ( false === $consider_minified_array || str_replace( $consider_minified_array, '', $path ) === $path ) ) ) {
188
  $minified_url = $this->minify_single( $path );
189
- // replace orig URL with minified URL from cache if so.
190
  if ( ! empty( $minified_url ) ) {
191
- $newTag = str_replace( $url, $minified_url, $newTag );
 
 
 
 
192
  }
193
  }
194
  }
195
 
196
- if ( $this->ismovable($newTag) ) {
197
  // can be moved, flags and all.
198
- if ( $this->movetolast($newTag) ) {
199
- $this->move['last'][] = $newTag;
200
  } else {
201
- $this->move['first'][] = $newTag;
202
  }
203
  } else {
204
  // cannot be moved, so if flag was added re-inject altered tag immediately.
205
- if ( $origTag !== $newTag ) {
206
- $this->content = str_replace( $origTag, $newTag, $this->content );
207
- $origTag = '';
208
  }
209
  // and forget about the $tag (not to be touched any more).
210
  $tag = '';
@@ -212,23 +371,23 @@ class autoptimizeScripts extends autoptimizeBase
212
  }
213
  } else {
214
  // Inline script.
215
- if ( $this->isremovable($tag, $this->jsremovables) ) {
216
  $this->content = str_replace( $tag, '', $this->content );
217
  continue;
218
  }
219
 
220
  // unhide comments, as javascript may be wrapped in comment-tags for old times' sake.
221
- $tag = $this->restore_comments($tag);
222
- if ( $this->ismergeable($tag) && $this->include_inline ) {
223
- preg_match( '#<script.*>(.*)</script>#Usmi', $tag , $code );
224
- $code = preg_replace('#.*<!\[CDATA\[(?:\s*\*/)?(.*)(?://|/\*)\s*?\]\]>.*#sm', '$1', $code[1] );
225
- $code = preg_replace('/(?:^\\s*<!--\\s*|\\s*(?:\\/\\/)?\\s*-->\\s*$)/', '', $code );
226
  $this->scripts[] = 'INLINE;' . $code;
227
  } else {
228
  // Can we move this?
229
  $autoptimize_js_moveable = apply_filters( 'autoptimize_js_moveable', '', $tag );
230
- if ( $this->ismovable($tag) || '' !== $autoptimize_js_moveable ) {
231
- if ( $this->movetolast($tag) || 'last' === $autoptimize_js_moveable ) {
232
  $this->move['last'][] = $tag;
233
  } else {
234
  $this->move['first'][] = $tag;
@@ -239,17 +398,17 @@ class autoptimizeScripts extends autoptimizeBase
239
  }
240
  }
241
  // Re-hide comments to be able to do the removal based on tag from $this->content.
242
- $tag = $this->hide_comments($tag);
243
  }
244
 
245
- //Remove the original script tag.
246
  $this->content = str_replace( $tag, '', $this->content );
247
  }
248
 
249
  return true;
250
  }
251
 
252
- // No script files, great ;-)
253
  return false;
254
  }
255
 
@@ -265,15 +424,19 @@ class autoptimizeScripts extends autoptimizeBase
265
  *
266
  * @link https://developer.mozilla.org/en/docs/Web/HTML/Element/script#attr-type
267
  *
268
- * @param string $tag
269
  * @return bool
270
  */
271
- public function should_aggregate($tag)
272
  {
 
 
 
 
273
  // We're only interested in the type attribute of the <script> tag itself, not any possible
274
  // inline code that might just contain the 'type=' string...
275
  $tag_parts = array();
276
- preg_match( '#<(script[^>]*)>#i', $tag, $tag_parts);
277
  $tag_without_contents = null;
278
  if ( ! empty( $tag_parts[1] ) ) {
279
  $tag_without_contents = $tag_parts[1];
@@ -294,13 +457,19 @@ class autoptimizeScripts extends autoptimizeBase
294
  return $should_aggregate;
295
  }
296
 
297
- //Joins and optimizes JS
 
 
298
  public function minify()
299
  {
300
  foreach ( $this->scripts as $script ) {
301
- // TODO/FIXME: some duplicate code here, can be reduced/simplified
 
 
 
 
302
  if ( preg_match( '#^INLINE;#', $script ) ) {
303
- // Inline script
304
  $script = preg_replace( '#^INLINE;#', '', $script );
305
  $script = rtrim( $script, ";\n\t\r" ) . ';';
306
  // Add try-catch?
@@ -309,12 +478,12 @@ class autoptimizeScripts extends autoptimizeBase
309
  }
310
  $tmpscript = apply_filters( 'autoptimize_js_individual_script', $script, '' );
311
  if ( has_filter( 'autoptimize_js_individual_script' ) && ! empty( $tmpscript ) ) {
312
- $script = $tmpscript;
313
  $this->alreadyminified = true;
314
  }
315
  $this->jscode .= "\n" . $script;
316
  } else {
317
- // External script
318
  if ( false !== $script && file_exists( $script ) && is_readable( $script ) ) {
319
  $scriptsrc = file_get_contents( $script );
320
  $scriptsrc = preg_replace( '/\x{EF}\x{BB}\x{BF}/', '', $scriptsrc );
@@ -325,21 +494,19 @@ class autoptimizeScripts extends autoptimizeBase
325
  }
326
  $tmpscriptsrc = apply_filters( 'autoptimize_js_individual_script', $scriptsrc, $script );
327
  if ( has_filter( 'autoptimize_js_individual_script' ) && ! empty( $tmpscriptsrc ) ) {
328
- $scriptsrc = $tmpscriptsrc;
329
  $this->alreadyminified = true;
330
- } else if ( $this->can_inject_late($script) ) {
331
- $scriptsrc = self::build_injectlater_marker($script, md5($scriptsrc));
332
  }
333
  $this->jscode .= "\n" . $scriptsrc;
334
- }/*else{
335
- //Couldn't read JS. Maybe getpath isn't working?
336
- }*/
337
  }
338
  }
339
 
340
- // Check for already-minified code
341
  $this->md5hash = md5( $this->jscode );
342
- $ccheck = new autoptimizeCache($this->md5hash, 'js');
343
  if ( $ccheck->check() ) {
344
  $this->jscode = $ccheck->retrieve();
345
  return true;
@@ -367,34 +534,38 @@ class autoptimizeScripts extends autoptimizeBase
367
  return true;
368
  }
369
 
370
- // Caches the JS in uncompressed, deflated and gzipped form.
 
 
371
  public function cache()
372
  {
373
- $cache = new autoptimizeCache($this->md5hash, 'js');
374
  if ( ! $cache->check() ) {
375
- // Cache our code
376
- $cache->cache($this->jscode, 'text/javascript');
377
  }
378
  $this->url = AUTOPTIMIZE_CACHE_URL . $cache->getname();
379
- $this->url = $this->url_replace_cdn($this->url);
380
  }
381
 
382
- // Returns the content
 
 
383
  public function getcontent()
384
  {
385
- // Restore the full content
386
  if ( ! empty( $this->restofcontent ) ) {
387
- $this->content .= $this->restofcontent;
388
  $this->restofcontent = '';
389
  }
390
 
391
- // Add the scripts taking forcehead/ deferred (default) into account
392
  if ( $this->forcehead ) {
393
- $replaceTag = array( '</head>', 'before' );
394
- $defer = '';
395
  } else {
396
- $replaceTag = array( '</body>', 'before' );
397
- $defer = 'defer ';
398
  }
399
 
400
  $defer = apply_filters( 'autoptimize_filter_js_defer', $defer );
@@ -406,14 +577,14 @@ class autoptimizeScripts extends autoptimizeBase
406
  $bodyreplacementpayload = '<script ' . $type_js . $defer . 'src="' . $this->url . '"></script>';
407
  $bodyreplacementpayload = apply_filters( 'autoptimize_filter_js_bodyreplacementpayload', $bodyreplacementpayload );
408
 
409
- $bodyreplacement = implode( '', $this->move['first'] );
410
  $bodyreplacement .= $bodyreplacementpayload;
411
  $bodyreplacement .= implode( '', $this->move['last'] );
412
 
413
- $replaceTag = apply_filters( 'autoptimize_filter_js_replacetag', $replaceTag );
414
 
415
  if ( strlen( $this->jscode ) > 0 ) {
416
- $this->inject_in_html( $bodyreplacement, $replaceTag );
417
  }
418
 
419
  // Restore comments.
@@ -429,84 +600,96 @@ class autoptimizeScripts extends autoptimizeBase
429
  return $this->content;
430
  }
431
 
432
- // Checks against the white- and blacklists
433
- private function ismergeable($tag)
 
 
 
 
434
  {
435
- if ( ! $this->aggregate ) {
436
  return false;
437
  }
438
 
439
  if ( ! empty( $this->whitelist ) ) {
440
  foreach ( $this->whitelist as $match ) {
441
- if (false !== strpos( $tag, $match ) ) {
442
  return true;
443
  }
444
  }
445
- // no match with whitelist
446
  return false;
447
  } else {
448
- foreach($this->domove as $match) {
449
  if ( false !== strpos( $tag, $match ) ) {
450
- // Matched something
451
  return false;
452
  }
453
  }
454
 
455
- if ( $this->movetolast($tag) ) {
456
  return false;
457
  }
458
 
459
- foreach( $this->dontmove as $match ) {
460
  if ( false !== strpos( $tag, $match ) ) {
461
- // Matched something
462
  return false;
463
  }
464
  }
465
 
466
- // If we're here it's safe to merge
467
  return true;
468
  }
469
  }
470
 
471
- // Checks agains the blacklist
472
- private function ismovable($tag)
 
 
 
 
473
  {
474
- if ( true !== $this->include_inline || apply_filters( 'autoptimize_filter_js_unmovable', true ) ) {
475
  return false;
476
  }
477
 
478
  foreach ( $this->domove as $match ) {
479
  if ( false !== strpos( $tag, $match ) ) {
480
- // Matched something
481
  return true;
482
  }
483
  }
484
 
485
- if ( $this->movetolast($tag) ) {
486
  return true;
487
  }
488
 
489
  foreach ( $this->dontmove as $match ) {
490
  if ( false !== strpos( $tag, $match ) ) {
491
- // Matched something
492
  return false;
493
  }
494
  }
495
 
496
- // If we're here it's safe to move
497
  return true;
498
  }
499
 
500
- private function movetolast($tag)
501
  {
 
 
 
 
502
  foreach ( $this->domovelast as $match ) {
503
  if ( false !== strpos( $tag, $match ) ) {
504
- // Matched, return true
505
  return true;
506
  }
507
  }
508
 
509
- // Should be in 'first'
510
  return false;
511
  }
512
 
@@ -514,22 +697,22 @@ class autoptimizeScripts extends autoptimizeBase
514
  * Determines wheter a <script> $tag can be excluded from minification (as already minified) based on:
515
  * - inject_min_late being active
516
  * - filename ending in `min.js`
517
- * - filename matching `js/jquery/jquery.js` (wordpress core jquery, is minified)
518
  * - filename matching one passed in the consider minified filter
519
  *
520
- * @param string $jsPath
521
  * @return bool
522
  */
523
- private function can_inject_late($jsPath) {
524
  $consider_minified_array = apply_filters( 'autoptimize_filter_js_consider_minified', false );
525
  if ( true !== $this->inject_min_late ) {
526
- // late-inject turned off
527
  return false;
528
- } else if ( ( false === strpos( $jsPath, 'min.js' ) ) && ( false === strpos( $jsPath, 'wp-includes/js/jquery/jquery.js' ) ) && ( str_replace( $consider_minified_array, '', $jsPath ) === $jsPath ) ) {
529
- // file not minified based on filename & filter
530
  return false;
531
  } else {
532
- // phew, all is safe, we can late-inject
533
  return true;
534
  }
535
  }
@@ -548,7 +731,7 @@ class autoptimizeScripts extends autoptimizeBase
548
  * Minifies a single local js file and returns its (cached) url.
549
  *
550
  * @param string $filepath Filepath.
551
- * @param bool $cache_miss Optional. Force a cache miss. Default false.
552
  *
553
  * @return bool|string Url pointing to the minified js file or false.
554
  */
@@ -567,6 +750,12 @@ class autoptimizeScripts extends autoptimizeBase
567
  // If not in cache already, minify...
568
  if ( ! $cache->check() || $cache_miss ) {
569
  $contents = trim( JSMin::minify( $contents ) );
 
 
 
 
 
 
570
  // Store in cache.
571
  $cache->cache( $contents, 'text/javascript' );
572
  }
1
  <?php
2
+ /**
3
+ * Class for JS optimization.
4
+ */
5
 
6
  if ( ! defined( 'ABSPATH' ) ) {
7
  exit;
9
 
10
  class autoptimizeScripts extends autoptimizeBase
11
  {
12
+
13
+ /**
14
+ * Stores founds scripts.
15
+ *
16
+ * @var array
17
+ */
18
  private $scripts = array();
19
+
20
+ /**
21
+ * Stores to be moved JS.
22
+ *
23
+ * @var array
24
+ */
25
+ private $move = array(
26
  'first' => array(),
27
+ 'last' => array(),
28
  );
29
 
30
+ /**
31
+ * List of not to be moved JS.
32
+ *
33
+ * @var array
34
+ */
35
  private $dontmove = array(
36
+ 'document.write',
37
+ 'html5.js',
38
+ 'show_ads.js',
39
+ 'google_ad',
40
+ 'histats.com/js',
41
+ 'statcounter.com/counter/counter.js',
42
+ 'ws.amazon.com/widgets',
43
+ 'media.fastclick.net',
44
+ '/ads/',
45
+ 'comment-form-quicktags/quicktags.php',
46
+ 'edToolbar',
47
+ 'intensedebate.com',
48
+ 'scripts.chitika.net/',
49
+ '_gaq.push',
50
+ 'jotform.com/',
51
+ 'admin-bar.min.js',
52
+ 'GoogleAnalyticsObject',
53
+ 'plupload.full.min.js',
54
+ 'syntaxhighlighter',
55
+ 'adsbygoogle',
56
+ 'gist.github.com',
57
+ '_stq',
58
+ 'nonce',
59
+ 'post_id',
60
+ 'data-noptimize',
61
+ 'logHuman',
62
  );
63
+
64
+ /**
65
+ * List of to be moved JS.
66
+ *
67
+ * @var array
68
+ */
69
+ private $domove = array(
70
+ 'gaJsHost',
71
+ 'load_cmc',
72
+ 'jd.gallery.transitions.js',
73
+ 'swfobject.embedSWF(',
74
+ 'tiny_mce.js',
75
+ 'tinyMCEPreInit.go',
76
  );
77
+
78
+ /**
79
+ * List of JS that can be moved last (not used any more).
80
+ *
81
+ * @var array
82
+ */
83
  private $domovelast = array(
84
+ 'addthis.com',
85
+ '/afsonline/show_afs_search.js',
86
+ 'disqus.js',
87
+ 'networkedblogs.com/getnetworkwidget',
88
+ 'infolinks.com/js/',
89
+ 'jd.gallery.js.php',
90
+ 'jd.gallery.transitions.js',
91
+ 'swfobject.embedSWF(',
92
+ 'linkwithin.com/widget.js',
93
+ 'tiny_mce.js',
94
+ 'tinyMCEPreInit.go',
95
  );
96
+
97
+ /**
98
+ * Setting CDN base URL.
99
+ *
100
+ * @var string
101
+ */
102
  public $cdn_url = '';
103
 
104
+ /**
105
+ * Setting; aggregate or not.
106
+ *
107
+ * @var bool
108
+ */
109
+ private $aggregate = true;
110
+
111
+ /**
112
+ * Setting; try/catch wrapping or not.
113
+ *
114
+ * @var bool
115
+ */
116
+ private $trycatch = false;
117
+
118
+ /**
119
+ * State; is JS already minified.
120
+ *
121
+ * @var bool
122
+ */
123
  private $alreadyminified = false;
124
+
125
+ /**
126
+ * Setting; force JS in head or not.
127
+ *
128
+ * @var bool
129
+ */
130
+ private $forcehead = true;
131
+
132
+ /**
133
+ * Setting; aggregate inline JS or not.
134
+ *
135
+ * @var bool
136
+ */
137
+ private $include_inline = false;
138
+
139
+ /**
140
+ * State; holds JS code.
141
+ *
142
+ * @var string
143
+ */
144
+ private $jscode = '';
145
+
146
+ /**
147
+ * State; holds URL of JS-file.
148
+ *
149
+ * @var string
150
+ */
151
+ private $url = '';
152
+
153
+ /**
154
+ * State; stores rest of HTML if (old) option "only in head" is on.
155
+ *
156
+ * @var string
157
+ */
158
+ private $restofcontent = '';
159
+
160
+ /**
161
+ * State; holds md5-hash.
162
+ *
163
+ * @var string
164
+ */
165
+ private $md5hash = '';
166
+
167
+ /**
168
+ * Setting (filter); whitelist of to be aggregated JS.
169
+ *
170
+ * @var string
171
+ */
172
+ private $whitelist = '';
173
+
174
+ /**
175
+ * Setting (filter); holds JS that should be removed.
176
+ *
177
+ * @var array
178
+ */
179
+ private $jsremovables = array();
180
+
181
+ /**
182
+ * Setting (filter); can we inject already minified files after the
183
+ * unminified aggregate JS has been minified.
184
+ *
185
+ * @var bool
186
+ */
187
+ private $inject_min_late = true;
188
+
189
+ /**
190
+ * Setting; should excluded JS be minified (if not already).
191
+ *
192
+ * @var bool
193
+ */
194
  private $minify_excluded = true;
195
 
196
+ /**
197
+ * Reads the page and collects script tags.
198
+ *
199
+ * @param array $options all options.
200
+ */
201
  public function read( $options )
202
  {
203
+ $noptimize_js = apply_filters( 'autoptimize_filter_js_noptimize', false, $this->content );
204
+ if ( $noptimize_js ) {
205
  return false;
206
  }
207
 
208
  // only optimize known good JS?
209
+ $whitelist_js = apply_filters( 'autoptimize_filter_js_whitelist', '', $this->content );
210
+ if ( ! empty( $whitelist_js ) ) {
211
+ $this->whitelist = array_filter( array_map( 'trim', explode( ', ', $whitelist_js ) ) );
212
  }
213
 
214
  // is there JS we should simply remove?
215
+ $removable_js = apply_filters( 'autoptimize_filter_js_removables', '', $this->content );
216
+ if ( ! empty( $removable_js ) ) {
217
+ $this->jsremovables = array_filter( array_map( 'trim', explode( ', ', $removable_js ) ) );
218
  }
219
 
220
  // only header?
253
  $this->minify_excluded = apply_filters( 'autoptimize_filter_js_minify_excluded', $this->minify_excluded, '' );
254
 
255
  // get extra exclusions settings or filter.
256
+ $exclude_js = $options['js_exclude'];
257
+ $exclude_js = apply_filters( 'autoptimize_filter_js_exclude', $exclude_js, $this->content );
258
+
259
+ if ( '' !== $exclude_js ) {
260
+ if ( is_array( $exclude_js ) ) {
261
+ $remove_keys = array_keys( $exclude_js, 'remove' );
262
+ if ( false !== $remove_keys ) {
263
+ foreach ( $remove_keys as $remove_key ) {
264
+ unset( $exclude_js[ $remove_key ] );
265
+ $this->jsremovables[] = $remove_key;
266
  }
267
  }
268
+ $excl_js_arr = array_keys( $exclude_js );
269
  } else {
270
+ $excl_js_arr = array_filter( array_map( 'trim', explode( ', ', $exclude_js ) ) );
271
  }
272
+ $this->dontmove = array_merge( $excl_js_arr, $this->dontmove );
273
  }
274
 
275
  // Should we add try-catch?
290
  $this->cdn_url = $options['cdn_url'];
291
 
292
  // noptimize me.
293
+ $this->content = $this->hide_noptimize( $this->content );
294
 
295
  // Save IE hacks.
296
+ $this->content = $this->hide_iehacks( $this->content );
297
 
298
  // comments.
299
+ $this->content = $this->hide_comments( $this->content );
300
 
301
  // Get script files.
302
  if ( preg_match_all( '#<script.*</script>#Usmi', $this->content, $matches ) ) {
303
+ foreach ( $matches[0] as $tag ) {
304
  // only consider script aggregation for types whitelisted in should_aggregate-function.
305
+ $should_aggregate = $this->should_aggregate( $tag );
306
  if ( ! $should_aggregate ) {
307
  $tag = '';
308
  continue;
310
 
311
  if ( preg_match( '#<script[^>]*src=("|\')([^>]*)("|\')#Usmi', $tag, $source ) ) {
312
  // non-inline script.
313
+ if ( $this->isremovable( $tag, $this->jsremovables ) ) {
314
  $this->content = str_replace( $tag, '', $this->content );
315
  continue;
316
  }
317
 
318
+ $orig_tag = null;
319
+ $url = current( explode( '?', $source[2], 2 ) );
320
+ $path = $this->getpath( $url );
321
+ if ( false !== $path && preg_match( '#\.js$#', $path ) && $this->ismergeable( $tag ) ) {
322
  // ok to optimize, add to array.
323
  $this->scripts[] = $path;
324
  } else {
325
+ $orig_tag = $tag;
326
+ $new_tag = $tag;
327
 
328
  // non-mergeable script (excluded or dynamic or external).
329
+ if ( is_array( $exclude_js ) ) {
330
  // should we add flags?
331
+ foreach ( $exclude_js as $excl_tag => $excl_flags ) {
332
+ if ( false !== strpos( $orig_tag, $excl_tag ) && in_array( $excl_flags, array( 'async', 'defer' ) ) ) {
333
+ $new_tag = str_replace( '<script ', '<script ' . $excl_flags . ' ', $new_tag );
334
  }
335
  }
336
  }
342
  $consider_minified_array = apply_filters( 'autoptimize_filter_js_consider_minified', false );
343
  if ( ( false === $this->aggregate && str_replace( $this->dontmove, '', $path ) === $path ) || ( true === $this->aggregate && ( false === $consider_minified_array || str_replace( $consider_minified_array, '', $path ) === $path ) ) ) {
344
  $minified_url = $this->minify_single( $path );
 
345
  if ( ! empty( $minified_url ) ) {
346
+ // Replace original URL with minified URL from cache.
347
+ $new_tag = str_replace( $url, $minified_url, $new_tag );
348
+ } else {
349
+ // Remove the original script tag, because cache content is empty.
350
+ $new_tag = '';
351
  }
352
  }
353
  }
354
 
355
+ if ( $this->ismovable( $new_tag ) ) {
356
  // can be moved, flags and all.
357
+ if ( $this->movetolast( $new_tag ) ) {
358
+ $this->move['last'][] = $new_tag;
359
  } else {
360
+ $this->move['first'][] = $new_tag;
361
  }
362
  } else {
363
  // cannot be moved, so if flag was added re-inject altered tag immediately.
364
+ if ( ( '' !== $new_tag && $orig_tag !== $new_tag ) || ( '' === $new_tag && apply_filters( 'autoptimize_filter_js_remove_empty_files', false ) ) ) {
365
+ $this->content = str_replace( $orig_tag, $new_tag, $this->content );
366
+ $orig_tag = '';
367
  }
368
  // and forget about the $tag (not to be touched any more).
369
  $tag = '';
371
  }
372
  } else {
373
  // Inline script.
374
+ if ( $this->isremovable( $tag, $this->jsremovables ) ) {
375
  $this->content = str_replace( $tag, '', $this->content );
376
  continue;
377
  }
378
 
379
  // unhide comments, as javascript may be wrapped in comment-tags for old times' sake.
380
+ $tag = $this->restore_comments( $tag );
381
+ if ( $this->ismergeable( $tag ) && $this->include_inline ) {
382
+ preg_match( '#<script.*>(.*)</script>#Usmi', $tag, $code );
383
+ $code = preg_replace( '#.*<!\[CDATA\[(?:\s*\*/)?(.*)(?://|/\*)\s*?\]\]>.*#sm', '$1', $code[1] );
384
+ $code = preg_replace( '/(?:^\\s*<!--\\s*|\\s*(?:\\/\\/)?\\s*-->\\s*$)/', '', $code );
385
  $this->scripts[] = 'INLINE;' . $code;
386
  } else {
387
  // Can we move this?
388
  $autoptimize_js_moveable = apply_filters( 'autoptimize_js_moveable', '', $tag );
389
+ if ( $this->ismovable( $tag ) || '' !== $autoptimize_js_moveable ) {
390
+ if ( $this->movetolast( $tag ) || 'last' === $autoptimize_js_moveable ) {
391
  $this->move['last'][] = $tag;
392
  } else {
393
  $this->move['first'][] = $tag;
398
  }
399
  }
400
  // Re-hide comments to be able to do the removal based on tag from $this->content.
401
+ $tag = $this->hide_comments( $tag );
402
  }
403
 
404
+ // Remove the original script tag.
405
  $this->content = str_replace( $tag, '', $this->content );
406
  }
407
 
408
  return true;
409
  }
410
 
411
+ // No script files, great ;-) .
412
  return false;
413
  }
414
 
424
  *
425
  * @link https://developer.mozilla.org/en/docs/Web/HTML/Element/script#attr-type
426
  *
427
+ * @param string $tag Script node & child(ren).
428
  * @return bool
429
  */
430
+ public function should_aggregate( $tag )
431
  {
432
+ if ( empty( $tag ) ) {
433
+ return false;
434
+ }
435
+
436
  // We're only interested in the type attribute of the <script> tag itself, not any possible
437
  // inline code that might just contain the 'type=' string...
438
  $tag_parts = array();
439
+ preg_match( '#<(script[^>]*)>#i', $tag, $tag_parts );
440
  $tag_without_contents = null;
441
  if ( ! empty( $tag_parts[1] ) ) {
442
  $tag_without_contents = $tag_parts[1];
457
  return $should_aggregate;
458
  }
459
 
460
+ /**
461
+ * Joins and optimizes JS.
462
+ */
463
  public function minify()
464
  {
465
  foreach ( $this->scripts as $script ) {
466
+ if ( empty( $script ) ) {
467
+ continue;
468
+ }
469
+
470
+ // TODO/FIXME: some duplicate code here, can be reduced/simplified.
471
  if ( preg_match( '#^INLINE;#', $script ) ) {
472
+ // Inline script.
473
  $script = preg_replace( '#^INLINE;#', '', $script );
474
  $script = rtrim( $script, ";\n\t\r" ) . ';';
475
  // Add try-catch?
478
  }
479
  $tmpscript = apply_filters( 'autoptimize_js_individual_script', $script, '' );
480
  if ( has_filter( 'autoptimize_js_individual_script' ) && ! empty( $tmpscript ) ) {
481
+ $script = $tmpscript;
482
  $this->alreadyminified = true;
483
  }
484
  $this->jscode .= "\n" . $script;
485
  } else {
486
+ // External script.
487
  if ( false !== $script && file_exists( $script ) && is_readable( $script ) ) {
488
  $scriptsrc = file_get_contents( $script );
489
  $scriptsrc = preg_replace( '/\x{EF}\x{BB}\x{BF}/', '', $scriptsrc );
494
  }
495
  $tmpscriptsrc = apply_filters( 'autoptimize_js_individual_script', $scriptsrc, $script );
496
  if ( has_filter( 'autoptimize_js_individual_script' ) && ! empty( $tmpscriptsrc ) ) {
497
+ $scriptsrc = $tmpscriptsrc;
498
  $this->alreadyminified = true;
499
+ } elseif ( $this->can_inject_late( $script ) ) {
500
+ $scriptsrc = self::build_injectlater_marker( $script, md5( $scriptsrc ) );
501
  }
502
  $this->jscode .= "\n" . $scriptsrc;
503
+ }
 
 
504
  }
505
  }
506
 
507
+ // Check for already-minified code.
508
  $this->md5hash = md5( $this->jscode );
509
+ $ccheck = new autoptimizeCache( $this->md5hash, 'js' );
510
  if ( $ccheck->check() ) {
511
  $this->jscode = $ccheck->retrieve();
512
  return true;
534
  return true;
535
  }
536
 
537
+ /**
538
+ * Caches the JS in uncompressed, deflated and gzipped form.
539
+ */
540
  public function cache()
541
  {
542
+ $cache = new autoptimizeCache( $this->md5hash, 'js' );
543
  if ( ! $cache->check() ) {
544
+ // Cache our code.
545
+ $cache->cache( $this->jscode, 'text/javascript' );
546
  }
547
  $this->url = AUTOPTIMIZE_CACHE_URL . $cache->getname();
548
+ $this->url = $this->url_replace_cdn( $this->url );
549
  }
550
 
551
+ /**
552
+ * Returns the content.
553
+ */
554
  public function getcontent()
555
  {
556
+ // Restore the full content.
557
  if ( ! empty( $this->restofcontent ) ) {
558
+ $this->content .= $this->restofcontent;
559
  $this->restofcontent = '';
560
  }
561
 
562
+ // Add the scripts taking forcehead/ deferred (default) into account.
563
  if ( $this->forcehead ) {
564
+ $replace_tag = array( '</head>', 'before' );
565
+ $defer = '';
566
  } else {
567
+ $replace_tag = array( '</body>', 'before' );
568
+ $defer = 'defer ';
569
  }
570
 
571
  $defer = apply_filters( 'autoptimize_filter_js_defer', $defer );
577
  $bodyreplacementpayload = '<script ' . $type_js . $defer . 'src="' . $this->url . '"></script>';
578
  $bodyreplacementpayload = apply_filters( 'autoptimize_filter_js_bodyreplacementpayload', $bodyreplacementpayload );
579
 
580
+ $bodyreplacement = implode( '', $this->move['first'] );
581
  $bodyreplacement .= $bodyreplacementpayload;
582
  $bodyreplacement .= implode( '', $this->move['last'] );
583
 
584
+ $replace_tag = apply_filters( 'autoptimize_filter_js_replacetag', $replace_tag );
585
 
586
  if ( strlen( $this->jscode ) > 0 ) {
587
+ $this->inject_in_html( $bodyreplacement, $replace_tag );
588
  }
589
 
590
  // Restore comments.
600
  return $this->content;
601
  }
602
 
603
+ /**
604
+ * Checks against the white- and blacklists.
605
+ *
606
+ * @param string $tag JS tag.
607
+ */
608
+ private function ismergeable( $tag )
609
  {
610
+ if ( empty( $tag ) || ! $this->aggregate ) {
611
  return false;
612
  }
613
 
614
  if ( ! empty( $this->whitelist ) ) {
615
  foreach ( $this->whitelist as $match ) {
616
+ if ( false !== strpos( $tag, $match ) ) {
617
  return true;
618
  }
619
  }
620
+ // No match with whitelist.
621
  return false;
622
  } else {
623
+ foreach ( $this->domove as $match ) {
624
  if ( false !== strpos( $tag, $match ) ) {
625
+ // Matched something.
626
  return false;
627
  }
628
  }
629
 
630
+ if ( $this->movetolast( $tag ) ) {
631
  return false;
632
  }
633
 
634
+ foreach ( $this->dontmove as $match ) {
635
  if ( false !== strpos( $tag, $match ) ) {
636
+ // Matched something.
637
  return false;
638
  }
639
  }
640
 
641
+ // If we're here it's safe to merge.
642
  return true;
643
  }
644
  }
645
 
646
+ /**
647
+ * Checks agains the blacklist.
648
+ *
649
+ * @param string $tag tag to check for blacklist (exclusions).
650
+ */
651
+ private function ismovable( $tag )
652
  {
653
+ if ( empty( $tag ) || true !== $this->include_inline || apply_filters( 'autoptimize_filter_js_unmovable', true ) ) {
654
  return false;
655
  }
656
 
657
  foreach ( $this->domove as $match ) {
658
  if ( false !== strpos( $tag, $match ) ) {
659
+ // Matched something.
660
  return true;
661
  }
662
  }
663
 
664
+ if ( $this->movetolast( $tag ) ) {
665
  return true;
666
  }
667
 
668
  foreach ( $this->dontmove as $match ) {
669
  if ( false !== strpos( $tag, $match ) ) {
670
+ // Matched something.
671
  return false;
672
  }
673
  }
674
 
675
+ // If we're here it's safe to move.
676
  return true;
677
  }
678
 
679
+ private function movetolast( $tag )
680
  {
681
+ if ( empty( $tag ) ) {
682
+ return false;
683
+ }
684
+
685
  foreach ( $this->domovelast as $match ) {
686
  if ( false !== strpos( $tag, $match ) ) {
687
+ // Matched, return true.
688
  return true;
689
  }
690
  }
691
 
692
+ // Should be in 'first'.
693
  return false;
694
  }
695
 
697
  * Determines wheter a <script> $tag can be excluded from minification (as already minified) based on:
698
  * - inject_min_late being active
699
  * - filename ending in `min.js`
700
+ * - filename matching `js/jquery/jquery.js` (WordPress core jquery, is minified)
701
  * - filename matching one passed in the consider minified filter
702
  *
703
+ * @param string $js_path Path to JS file.
704
  * @return bool
705
  */
706
+ private function can_inject_late( $js_path ) {
707
  $consider_minified_array = apply_filters( 'autoptimize_filter_js_consider_minified', false );
708
  if ( true !== $this->inject_min_late ) {
709
+ // late-inject turned off.
710
  return false;
711
+ } elseif ( ( false === strpos( $js_path, 'min.js' ) ) && ( false === strpos( $js_path, 'wp-includes/js/jquery/jquery.js' ) ) && ( str_replace( $consider_minified_array, '', $js_path ) === $js_path ) ) {
712
+ // file not minified based on filename & filter.
713
  return false;
714
  } else {
715
+ // phew, all is safe, we can late-inject.
716
  return true;
717
  }
718
  }
731
  * Minifies a single local js file and returns its (cached) url.
732
  *
733
  * @param string $filepath Filepath.
734
+ * @param bool $cache_miss Optional. Force a cache miss. Default false.
735
  *
736
  * @return bool|string Url pointing to the minified js file or false.
737
  */
750
  // If not in cache already, minify...
751
  if ( ! $cache->check() || $cache_miss ) {
752
  $contents = trim( JSMin::minify( $contents ) );
753
+
754
+ // Check if minified cache content is empty.
755
+ if ( empty( $contents ) ) {
756
+ return false;
757
+ }
758
+
759
  // Store in cache.
760
  $cache->cache( $contents, 'text/javascript' );
761
  }
classes/autoptimizeStyles.php CHANGED
@@ -13,59 +13,169 @@ class autoptimizeStyles extends autoptimizeBase
13
 
14
  /**
15
  * Font-face regex-fu from HamZa at: https://stackoverflow.com/a/21395083
16
- * ~
17
- * @font-face\s* # Match @font-face and some spaces
18
- * ( # Start group 1
19
- * \{ # Match {
20
- * (?: # A non-capturing group
21
- * [^{}]+ # Match anything except {} one or more times
22
- * | # Or
23
- * (?1) # Recurse/rerun the expression of group 1
24
- * )* # Repeat 0 or more times
25
- * \} # Match }
26
- * ) # End group 1
27
- * ~xs';
28
  */
29
  const FONT_FACE_REGEX = '~@font-face\s*(\{(?:[^{}]+|(?1))*\})~xsi'; // added `i` flag for case-insensitivity.
30
 
31
- private $css = array();
32
- private $csscode = array();
33
- private $url = array();
34
- private $restofcontent = '';
35
- private $datauris = false;
36
- private $hashmap = array();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  private $alreadyminified = false;
38
- private $aggregate = true;
39
- private $inline = false;
40
- private $defer = false;
41
- private $defer_inline = false;
42
- private $whitelist = '';
43
- private $cssinlinesize = '';
44
- private $cssremovables = array();
45
- private $include_inline = false;
46
- private $inject_min_late = '';
47
- private $dontmove = array();
48
- private $options = array();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  private $minify_excluded = true;
50
 
51
- // public $cdn_url; // Used all over the place implicitly, so will have to be either public or protected :/ .
 
 
 
 
 
52
 
53
- // Reads the page and collects style tags.
 
 
 
 
54
  public function read( $options )
55
  {
56
- $noptimizeCSS = apply_filters( 'autoptimize_filter_css_noptimize', false, $this->content );
57
- if ( $noptimizeCSS ) {
58
  return false;
59
  }
60
 
61
- $whitelistCSS = apply_filters( 'autoptimize_filter_css_whitelist', '', $this->content );
62
- if ( ! empty( $whitelistCSS ) ) {
63
- $this->whitelist = array_filter( array_map( 'trim', explode( ',', $whitelistCSS ) ) );
64
  }
65
 
66
- $removableCSS = apply_filters( 'autoptimize_filter_css_removables', '' );
67
- if ( ! empty( $removableCSS ) ) {
68
- $this->cssremovables = array_filter( array_map( 'trim', explode( ',', $removableCSS ) ) );
69
  }
70
 
71
  $this->cssinlinesize = apply_filters( 'autoptimize_filter_css_inlinesize', 256 );
@@ -95,9 +205,9 @@ class autoptimizeStyles extends autoptimizeBase
95
  }
96
 
97
  // List of CSS strings which are excluded from autoptimization.
98
- $excludeCSS = apply_filters( 'autoptimize_filter_css_exclude', $options['css_exclude'], $this->content );
99
- if ( '' !== $excludeCSS ) {
100
- $this->dontmove = array_filter( array_map( 'trim', explode( ',', $excludeCSS ) ) );
101
  } else {
102
  $this->dontmove = array();
103
  }
@@ -131,15 +241,18 @@ class autoptimizeStyles extends autoptimizeBase
131
  }
132
  $this->minify_excluded = apply_filters( 'autoptimize_filter_css_minify_excluded', $this->minify_excluded, '' );
133
 
 
 
 
134
  // noptimize me.
135
  $this->content = $this->hide_noptimize( $this->content );
136
 
137
  // Exclude (no)script, as those may contain CSS which should be left as is.
138
  $this->content = $this->replace_contents_with_marker_if_exists(
139
- 'SCRIPT',
140
- '<script',
141
- '#<(?:no)?script.*?<\/(?:no)?script>#is',
142
- $this->content
143
  );
144
 
145
  // Save IE hacks.
@@ -159,9 +272,8 @@ class autoptimizeStyles extends autoptimizeBase
159
  if ( false !== strpos( $tag, 'media=' ) ) {
160
  preg_match( '#media=(?:"|\')([^>]*)(?:"|\')#Ui', $tag, $medias );
161
  $medias = explode( ',', $medias[1] );
162
- $media = array();
163
  foreach ( $medias as $elem ) {
164
- /* $media[] = current(explode(' ',trim($elem),2)); */
165
  if ( empty( $elem ) ) {
166
  $elem = 'all';
167
  }
@@ -173,6 +285,11 @@ class autoptimizeStyles extends autoptimizeBase
173
  $media = array( 'all' );
174
  }
175
 
 
 
 
 
 
176
  $media = apply_filters( 'autoptimize_filter_css_tagmedia', $media, $tag );
177
 
178
  if ( preg_match( '#<link.*href=("|\')(.*)("|\')#Usmi', $tag, $source ) ) {
@@ -186,7 +303,7 @@ class autoptimizeStyles extends autoptimizeBase
186
  } else {
187
  // Link is dynamic (.php etc).
188
  $new_tag = $this->optionally_defer_excluded( $tag, 'none' );
189
- if ( $new_tag !== '' && $new_tag !== $tag ) {
190
  $this->content = str_replace( $tag, $new_tag, $this->content );
191
  }
192
  $tag = '';
@@ -200,7 +317,7 @@ class autoptimizeStyles extends autoptimizeBase
200
  $tag = $this->hide_comments( $tag );
201
 
202
  if ( $this->include_inline ) {
203
- $code = preg_replace( '#^.*<!\[CDATA\[(?:\s*\*/)?(.*)(?://|/\*)\s*?\]\]>.*$#sm', '$1', $code[1] );
204
  $this->css[] = array( $media, 'INLINE;' . $code );
205
  } else {
206
  $tag = '';
@@ -226,15 +343,20 @@ class autoptimizeStyles extends autoptimizeBase
226
  if ( ! empty( $minified_url ) ) {
227
  // Replace orig URL with cached minified URL.
228
  $new_tag = str_replace( $url, $minified_url, $tag );
 
 
 
229
  }
230
  }
231
  }
232
 
233
- // Optionally defer (preload) non-aggregated CSS.
234
- $new_tag = $this->optionally_defer_excluded( $new_tag, $url );
 
 
235
 
236
  // And replace!
237
- if ( $new_tag !== '' && $new_tag !== $tag ) {
238
  $this->content = str_replace( $tag, $new_tag, $this->content );
239
  }
240
  }
@@ -259,34 +381,36 @@ class autoptimizeStyles extends autoptimizeBase
259
  private function optionally_defer_excluded( $tag, $url = '' )
260
  {
261
  // Defer single CSS if "inline & defer" is ON and there is inline CSS.
262
- if ( $this->defer && ! empty( $this->defer_inline ) ) {
263
  // Get/ set (via filter) the JS to be triggers onload of the preloaded CSS.
264
  $_preload_onload = apply_filters(
265
  'autoptimize_filter_css_preload_onload',
266
  "this.onload=null;this.rel='stylesheet'",
267
  $url
268
  );
 
269
  // Adapt original <link> element for CSS to be preloaded and add <noscript>-version for fallback.
270
  $new_tag = '<noscript>' . autoptimizeUtils::remove_id_from_node( $tag ) . '</noscript>' . str_replace(
271
  array(
272
  "rel='stylesheet'",
273
  'rel="stylesheet"',
274
  ),
275
- "rel='preload' as='style' onload=\"" . $_preload_onload . "\"",
276
  $tag
277
  );
278
- } else {
279
- $new_tag = $tag;
280
  }
281
 
282
- return $new_tag;
 
283
  }
284
 
285
  /**
286
  * Checks if the local file referenced by $path is a valid
287
  * candidate for being inlined into a data: URI
288
  *
289
- * @param string $path
290
  * @return boolean
291
  */
292
  private function is_datauri_candidate( $path )
@@ -344,7 +468,7 @@ class autoptimizeStyles extends autoptimizeBase
344
  // Again, skip doing certain stuff repeatedly when loop-called.
345
  if ( null === $exclude_list ) {
346
  $exclude_list = apply_filters( 'autoptimize_filter_css_datauri_exclude', '' );
347
- $no_datauris = array_filter( array_map( 'trim', explode( ',', $exclude_list ) ) );
348
  }
349
 
350
  $matched = false;
@@ -377,18 +501,18 @@ class autoptimizeStyles extends autoptimizeBase
377
  }
378
  }
379
 
380
- $hash = md5( $path );
381
  $check = new autoptimizeCache( $hash, 'img' );
382
  if ( $check->check() ) {
383
  // we have the base64 image in cache.
384
- $headAndData = $check->retrieve();
385
- $_base64data = explode( ';base64,', $headAndData );
386
- $base64data = $_base64data[1];
387
  unset( $_base64data );
388
  } else {
389
  // It's an image and we don't have it in cache, get the type by extension.
390
  $exploded_path = explode( '.', $path );
391
- $type = end( $exploded_path );
392
 
393
  switch ( $type ) {
394
  case 'jpg':
@@ -412,23 +536,26 @@ class autoptimizeStyles extends autoptimizeBase
412
  }
413
 
414
  // Encode the data.
415
- $base64data = base64_encode( file_get_contents( $path ) );
416
- $headAndData = $dataurihead . $base64data;
417
 
418
  // Save in cache.
419
- $check->cache( $headAndData, 'text/plain' );
420
  }
421
  unset( $check );
422
 
423
- return array( 'full' => $headAndData, 'base64data' => $base64data );
 
 
 
424
  }
425
 
426
  /**
427
  * Given an array of key/value pairs to replace in $string,
428
  * it does so by replacing the longest-matching strings first.
429
  *
430
- * @param string $string
431
- * @param array $replacements
432
  *
433
  * @return string
434
  */
@@ -484,7 +611,7 @@ class autoptimizeStyles extends autoptimizeBase
484
  $replacement_url = $this->url_replace_cdn( $url );
485
  // Prepare replacements array.
486
  $replacements[ $url_src_matches[1][ $count ] ] = str_replace(
487
- $original_url, $replacement_url, $url_src_matches[1][$count]
488
  );
489
  }
490
  }
@@ -500,7 +627,7 @@ class autoptimizeStyles extends autoptimizeBase
500
  * Also does CDN replacement of any font-urls within those declarations if the `autoptimize_filter_css_fonts_cdn`
501
  * filter is used.
502
  *
503
- * @param string $code
504
  * @return string
505
  */
506
  public function hide_fontface_and_maybe_cdn( $code )
@@ -522,7 +649,7 @@ class autoptimizeStyles extends autoptimizeBase
522
 
523
  // Replace declaration with its base64 encoded string.
524
  $replacement = self::build_marker( 'FONTFACE', $full_match );
525
- $code = str_replace( $match_search, $replacement, $code );
526
  }
527
  }
528
 
@@ -533,7 +660,7 @@ class autoptimizeStyles extends autoptimizeBase
533
  * Restores original @font-face declarations that have been "hidden"
534
  * using `hide_fontface_and_maybe_cdn()`.
535
  *
536
- * @param string $code
537
  * @return string
538
  */
539
  public function restore_fontface( $code )
@@ -541,7 +668,12 @@ class autoptimizeStyles extends autoptimizeBase
541
  return $this->restore_marked_content( 'FONTFACE', $code );
542
  }
543
 
544
- // Re-write (and/or inline) referenced assets.
 
 
 
 
 
545
  public function rewrite_assets( $code )
546
  {
547
  // Handle @font-face rules by hiding and processing them separately.
@@ -559,7 +691,8 @@ class autoptimizeStyles extends autoptimizeBase
559
 
560
  // Re-write (and/or inline) URLs to point them to the CDN host.
561
  $url_src_matches = array();
562
- $imgreplace = array();
 
563
  // Matches and captures anything specified within the literal `url()` and excludes those containing data: URIs.
564
  preg_match_all( self::ASSETS_REGEX, $code, $url_src_matches );
565
  if ( is_array( $url_src_matches ) && ! empty( $url_src_matches ) ) {
@@ -581,15 +714,15 @@ class autoptimizeStyles extends autoptimizeBase
581
  if ( ! $excluded ) {
582
  $is_datauri_candidate = $this->is_datauri_candidate( $ipath );
583
  if ( $is_datauri_candidate ) {
584
- $datauri = $this->build_or_get_datauri_image( $ipath );
585
- $base64data = $datauri['base64data'];
586
  // Add it to the list for replacement.
587
  $imgreplace[ $url_src_matches[1][ $count ] ] = str_replace(
588
- $original_url,
589
- $datauri['full'],
590
- $url_src_matches[1][$count]
591
  );
592
- $inlined = true;
593
  }
594
  }
595
  }
@@ -602,9 +735,9 @@ class autoptimizeStyles extends autoptimizeBase
602
  */
603
  if ( ! $inlined && ( ! empty( $this->cdn_url ) || has_filter( 'autoptimize_filter_base_replace_cdn' ) ) ) {
604
  // Just do the "simple" CDN replacement.
605
- $replacement_url = $this->url_replace_cdn( $url );
606
  $imgreplace[ $url_src_matches[1][ $count ] ] = str_replace(
607
- $original_url, $replacement_url, $url_src_matches[1][$count]
608
  );
609
  }
610
  }
@@ -618,32 +751,34 @@ class autoptimizeStyles extends autoptimizeBase
618
  return $code;
619
  }
620
 
621
- // Joins and optimizes CSS.
 
 
622
  public function minify()
623
  {
624
  foreach ( $this->css as $group ) {
625
  list( $media, $css ) = $group;
626
  if ( preg_match( '#^INLINE;#', $css ) ) {
627
  // <style>.
628
- $css = preg_replace( '#^INLINE;#', '', $css );
629
- $css = self::fixurls( ABSPATH . 'index.php', $css ); // ABSPATH already contains a trailing slash.
630
  $tmpstyle = apply_filters( 'autoptimize_css_individual_style', $css, '' );
631
  if ( has_filter( 'autoptimize_css_individual_style' ) && ! empty( $tmpstyle ) ) {
632
- $css = $tmpstyle;
633
  $this->alreadyminified = true;
634
  }
635
  } else {
636
  // <link>
637
  if ( false !== $css && file_exists( $css ) && is_readable( $css ) ) {
638
- $cssPath = $css;
639
- $css = self::fixurls( $cssPath, file_get_contents( $cssPath ) );
640
- $css = preg_replace( '/\x{EF}\x{BB}\x{BF}/', '', $css );
641
- $tmpstyle = apply_filters( 'autoptimize_css_individual_style', $css, $cssPath );
642
  if ( has_filter( 'autoptimize_css_individual_style' ) && ! empty( $tmpstyle ) ) {
643
- $css = $tmpstyle;
644
  $this->alreadyminified = true;
645
- } elseif ( $this->can_inject_late( $cssPath, $css ) ) {
646
- $css = self::build_injectlater_marker( $cssPath, md5( $css ) );
647
  }
648
  } else {
649
  // Couldn't read CSS. Maybe getpath isn't working?
@@ -653,10 +788,10 @@ class autoptimizeStyles extends autoptimizeBase
653
 
654
  foreach ( $media as $elem ) {
655
  if ( ! empty( $css ) ) {
656
- if ( ! isset( $this->csscode[$elem] ) ) {
657
- $this->csscode[$elem] = '';
658
  }
659
- $this->csscode[$elem] .= "\n/*FILESTART*/" . $css;
660
  }
661
  }
662
  }
@@ -671,13 +806,13 @@ class autoptimizeStyles extends autoptimizeBase
671
  // If same code.
672
  if ( $sum === $md5sum ) {
673
  // Add the merged code.
674
- $medianame = $med . ', ' . $media;
675
- $this->csscode[$medianame] = $code;
676
- $md5list[$medianame] = $md5list[$med];
677
- unset( $this->csscode[$med], $this->csscode[$media], $md5list[$med] );
678
  }
679
  }
680
- $md5list[$medianame] = $md5sum;
681
  }
682
  unset( $tmpcss );
683
 
@@ -692,18 +827,18 @@ class autoptimizeStyles extends autoptimizeBase
692
  while ( preg_match_all( '#@import +(?:url)?(?:(?:\((["\']?)(?:[^"\')]+)\1\)|(["\'])(?:[^"\']+)\2)(?:[^,;"\']+(?:,[^,;"\']+)*)?)(?:;)#mi', $thiscss_nocomments, $matches ) ) {
693
  foreach ( $matches[0] as $import ) {
694
  if ( $this->isremovable( $import, $this->cssremovables ) ) {
695
- $thiscss = str_replace( $import, '', $thiscss );
696
  $import_ok = true;
697
  } else {
698
- $url = trim( preg_replace( '#^.*((?:https?:|ftp:)?//.*\.css).*$#', '$1', trim( $import ) ), " \t\n\r\0\x0B\"'" );
699
- $path = $this->getpath( $url );
700
  $import_ok = false;
701
  if ( file_exists( $path ) && is_readable( $path ) ) {
702
- $code = addcslashes( self::fixurls( $path, file_get_contents( $path ) ), "\\" );
703
- $code = preg_replace( '/\x{EF}\x{BB}\x{BF}/', '', $code );
704
  $tmpstyle = apply_filters( 'autoptimize_css_individual_style', $code, '' );
705
  if ( has_filter( 'autoptimize_css_individual_style' ) && ! empty( $tmpstyle ) ) {
706
- $code = $tmpstyle;
707
  $this->alreadyminified = true;
708
  } elseif ( $this->can_inject_late( $path, $code ) ) {
709
  $code = self::build_injectlater_marker( $path, md5( $code ) );
@@ -712,7 +847,7 @@ class autoptimizeStyles extends autoptimizeBase
712
  if ( ! empty( $code ) ) {
713
  $tmp_thiscss = preg_replace( '#(/\*FILESTART\*/.*)' . preg_quote( $import, '#' ) . '#Us', '/*FILESTART2*/' . $code . '$1', $thiscss );
714
  if ( ! empty( $tmp_thiscss ) ) {
715
- $thiscss = $tmp_thiscss;
716
  $import_ok = true;
717
  unset( $tmp_thiscss );
718
  }
@@ -750,8 +885,8 @@ class autoptimizeStyles extends autoptimizeBase
750
  do_action( 'autoptimize_action_css_hash', $hash );
751
  $ccheck = new autoptimizeCache( $hash, 'css' );
752
  if ( $ccheck->check() ) {
753
- $code = $ccheck->retrieve();
754
- $this->hashmap[md5( $code )] = $hash;
755
  continue;
756
  }
757
  unset( $ccheck );
@@ -772,7 +907,7 @@ class autoptimizeStyles extends autoptimizeBase
772
  unset( $tmp_code );
773
  }
774
 
775
- $this->hashmap[md5( $code )] = $hash;
776
  }
777
 
778
  unset( $code );
@@ -798,27 +933,35 @@ class autoptimizeStyles extends autoptimizeBase
798
  return $code;
799
  }
800
 
801
- // Caches the CSS in uncompressed, deflated and gzipped form.
 
 
802
  public function cache()
803
  {
804
  // CSS cache.
805
  foreach ( $this->csscode as $media => $code ) {
806
- $md5 = $this->hashmap[md5( $code )];
 
 
 
 
807
  $cache = new autoptimizeCache( $md5, 'css' );
808
  if ( ! $cache->check() ) {
809
  // Cache our code.
810
  $cache->cache( $code, 'text/css' );
811
  }
812
- $this->url[$media] = AUTOPTIMIZE_CACHE_URL . $cache->getname();
813
  }
814
  }
815
 
816
- // Returns the content.
 
 
817
  public function getcontent()
818
  {
819
  // Restore the full content (only applies when "autoptimize_filter_css_justhead" filter is true).
820
  if ( ! empty( $this->restofcontent ) ) {
821
- $this->content .= $this->restofcontent;
822
  $this->restofcontent = '';
823
  }
824
 
@@ -829,34 +972,34 @@ class autoptimizeStyles extends autoptimizeBase
829
  }
830
 
831
  // Inject the new stylesheets.
832
- $replaceTag = array( '<title', 'before' );
833
- $replaceTag = apply_filters( 'autoptimize_filter_css_replacetag', $replaceTag, $this->content );
834
 
835
  if ( $this->inline ) {
836
  foreach ( $this->csscode as $media => $code ) {
837
- $this->inject_in_html( '<style ' . $type_css . 'media="' . $media . '">' . $code . '</style>', $replaceTag );
838
  }
839
  } else {
840
  if ( $this->defer ) {
841
- $preloadCssBlock = '';
842
  $inlined_ccss_block = '';
843
- $noScriptCssBlock = "<noscript id=\"aonoscrcss\">";
844
 
845
  $defer_inline_code = $this->defer_inline;
846
  if ( ! empty( $defer_inline_code ) ) {
847
  if ( apply_filters( 'autoptimize_filter_css_critcss_minify', true ) ) {
848
- $iCssHash = md5( $defer_inline_code );
849
- $iCssCache = new autoptimizeCache( $iCssHash, 'css' );
850
- if ( $iCssCache->check() ) {
851
  // we have the optimized inline CSS in cache.
852
- $defer_inline_code = $iCssCache->retrieve();
853
  } else {
854
  $cssmin = new autoptimizeCSSmin();
855
  $tmp_code = trim( $cssmin->run( $defer_inline_code ) );
856
 
857
  if ( ! empty( $tmp_code ) ) {
858
  $defer_inline_code = $tmp_code;
859
- $iCssCache->cache( $defer_inline_code, 'text/css' );
860
  unset( $tmp_code );
861
  }
862
  }
@@ -872,24 +1015,24 @@ class autoptimizeStyles extends autoptimizeBase
872
 
873
  // Add the stylesheet either deferred (import at bottom) or normal links in head.
874
  if ( $this->defer ) {
875
- $preloadOnLoad = autoptimizeConfig::get_ao_css_preload_onload();
876
 
877
- $preloadCssBlock .= '<link rel="preload" as="style" media="' . $media . '" href="' . $url . '" onload="' . $preloadOnLoad . '" />';
878
- $noScriptCssBlock .= '<link ' . $type_css . 'media="' . $media . '" href="' . $url . '" rel="stylesheet" />';
879
  } else {
880
- if ( strlen( $this->csscode[$media] ) > $this->cssinlinesize ) {
881
- $this->inject_in_html( '<link ' . $type_css . 'media="' . $media . '" href="' . $url . '" rel="stylesheet" />', $replaceTag );
882
- } elseif ( strlen( $this->csscode[$media] ) > 0 ) {
883
- $this->inject_in_html( '<style ' . $type_css . 'media="' . $media . '">' . $this->csscode[$media] . '</style>', $replaceTag );
884
  }
885
  }
886
  }
887
 
888
  if ( $this->defer ) {
889
- $preload_polyfill = autoptimizeConfig::get_ao_css_preload_polyfill();
890
- $noScriptCssBlock .= '</noscript>';
891
  // Inject inline critical CSS, the preloaded full CSS and the noscript-CSS.
892
- $this->inject_in_html( $inlined_ccss_block . $preloadCssBlock . $noScriptCssBlock, $replaceTag );
893
 
894
  // Adds preload polyfill at end of body tag.
895
  $this->inject_in_html(
@@ -915,6 +1058,12 @@ class autoptimizeStyles extends autoptimizeBase
915
  return $this->content;
916
  }
917
 
 
 
 
 
 
 
918
  static function fixurls( $file, $code )
919
  {
920
  // Switch all imports to the url() syntax.
@@ -923,7 +1072,7 @@ class autoptimizeStyles extends autoptimizeBase
923
  if ( preg_match_all( self::ASSETS_REGEX, $code, $matches ) ) {
924
  $file = str_replace( WP_ROOT_DIR, '/', $file );
925
  /**
926
- * rollback as per https://github.com/futtta/autoptimize/issues/94
927
  * $file = str_replace( AUTOPTIMIZE_WP_CONTENT_NAME, '', $file );
928
  */
929
  $dir = dirname( $file ); // Like /themes/expound/css.
@@ -939,25 +1088,25 @@ class autoptimizeStyles extends autoptimizeBase
939
  $replace = array();
940
  foreach ( $matches[1] as $k => $url ) {
941
  // Remove quotes.
942
- $url = trim( $url, " \t\n\r\0\x0B\"'" );
943
- $noQurl = trim( $url, "\"'" );
944
- if ( $url !== $noQurl ) {
945
- $removedQuotes = true;
946
  } else {
947
- $removedQuotes = false;
948
  }
949
 
950
- if ( '' === $noQurl ) {
951
  continue;
952
  }
953
 
954
- $url = $noQurl;
955
  if ( '/' === $url[0] || preg_match( '#^(https?://|ftp://|data:)#i', $url ) ) {
956
  // URL is protocol-relative, host-relative or something we don't touch.
957
  continue;
958
- } else {
959
- // Relative URL.
960
- /**
961
  * rollback as per https://github.com/futtta/autoptimize/issues/94
962
  * $newurl = preg_replace( '/https?:/', '', str_replace( ' ', '%20', AUTOPTIMIZE_WP_CONTENT_URL . str_replace( '//', '/', $dir . '/' . $url ) ) );
963
  */
@@ -969,13 +1118,13 @@ class autoptimizeStyles extends autoptimizeBase
969
  * We must do this, or different css classes referencing the same bg image (but
970
  * different parts of it, say, in sprites and such) loose their stuff...
971
  */
972
- $hash = md5( $url . $matches[2][$k] );
973
- $code = str_replace( $matches[0][$k], $hash, $code );
974
 
975
- if ( $removedQuotes ) {
976
- $replace[$hash] = "url('" . $newurl . "')" . $matches[2][$k];
977
  } else {
978
- $replace[$hash] = 'url(' . $newurl . ')' . $matches[2][$k];
979
  }
980
  }
981
  }
@@ -1015,13 +1164,13 @@ class autoptimizeStyles extends autoptimizeBase
1015
  }
1016
  }
1017
 
1018
- private function can_inject_late( $cssPath, $css )
1019
  {
1020
- $consider_minified_array = apply_filters( 'autoptimize_filter_css_consider_minified', false, $cssPath );
1021
  if ( true !== $this->inject_min_late ) {
1022
  // late-inject turned off.
1023
  return false;
1024
- } elseif ( ( false === strpos( $cssPath, 'min.css' ) ) && ( str_replace( $consider_minified_array, '', $cssPath ) === $cssPath ) ) {
1025
  // file not minified based on filename & filter.
1026
  return false;
1027
  } elseif ( false !== strpos( $css, '@import' ) ) {
@@ -1030,7 +1179,7 @@ class autoptimizeStyles extends autoptimizeBase
1030
  } elseif ( ( false !== strpos( $css, '@font-face' ) ) && ( apply_filters( 'autoptimize_filter_css_fonts_cdn', false ) === true ) && ( ! empty( $this->cdn_url ) ) ) {
1031
  // don't late-inject CSS with font-src's if fonts are set to be CDN'ed.
1032
  return false;
1033
- } elseif ( ( ( $this->datauris == true ) || ( ! empty( $this->cdn_url ) ) ) && preg_match( '#background[^;}]*url\(#Ui', $css ) ) {
1034
  // don't late-inject CSS with images if CDN is set OR if image inlining is on.
1035
  return false;
1036
  } else {
@@ -1072,6 +1221,12 @@ class autoptimizeStyles extends autoptimizeBase
1072
  // Now minify...
1073
  $cssmin = new autoptimizeCSSmin();
1074
  $contents = trim( $cssmin->run( $contents ) );
 
 
 
 
 
 
1075
  // Store in cache.
1076
  $cache->cache( $contents, 'text/css' );
1077
  }
@@ -1103,12 +1258,12 @@ class autoptimizeStyles extends autoptimizeBase
1103
 
1104
  public function setOption( $name, $value )
1105
  {
1106
- $this->options[$name] = $value;
1107
- $this->$name = $value;
1108
  }
1109
 
1110
  public function getOption( $name )
1111
  {
1112
- return $this->options[$name];
1113
  }
1114
  }
13
 
14
  /**
15
  * Font-face regex-fu from HamZa at: https://stackoverflow.com/a/21395083
 
 
 
 
 
 
 
 
 
 
 
 
16
  */
17
  const FONT_FACE_REGEX = '~@font-face\s*(\{(?:[^{}]+|(?1))*\})~xsi'; // added `i` flag for case-insensitivity.
18
 
19
+ /**
20
+ * Store CSS.
21
+ *
22
+ * @var array
23
+ */
24
+ private $css = array();
25
+
26
+ /**
27
+ * To store CSS code
28
+ *
29
+ * @var array
30
+ */
31
+ private $csscode = array();
32
+
33
+ /**
34
+ * To store urls
35
+ *
36
+ * @var array
37
+ */
38
+ private $url = array();
39
+
40
+ /**
41
+ * String to store rest of content (when old setting "only in head" is used)
42
+ *
43
+ * @var string
44
+ */
45
+ private $restofcontent = '';
46
+
47
+ /**
48
+ * Setting to change small images to inline CSS
49
+ *
50
+ * @var bool
51
+ */
52
+ private $datauris = false;
53
+
54
+ /**
55
+ * Array to store hashmap
56
+ *
57
+ * @var array
58
+ */
59
+ private $hashmap = array();
60
+
61
+ /**
62
+ * Flag to indicate if CSS is already minified
63
+ *
64
+ * @var bool
65
+ */
66
  private $alreadyminified = false;
67
+
68
+ /**
69
+ * Setting if CSS should be aggregated
70
+ *
71
+ * @var bool
72
+ */
73
+ private $aggregate = true;
74
+
75
+ /**
76
+ * Setting if all CSS should be inlined
77
+ *
78
+ * @var bool
79
+ */
80
+ private $inline = false;
81
+
82
+ /**
83
+ * Setting if CSS should be deferred
84
+ *
85
+ * @var bool
86
+ */
87
+ private $defer = false;
88
+
89
+ /**
90
+ * Setting for to be inlined CSS.
91
+ *
92
+ * @var string
93
+ */
94
+ private $defer_inline = '';
95
+
96
+ /**
97
+ * Setting for whitelist of what should be aggregated.
98
+ *
99
+ * @var string
100
+ */
101
+ private $whitelist = '';
102
+
103
+ /**
104
+ * Setting (only filter) for size under which CSS should be inlined instead of linked.
105
+ *
106
+ * @var string
107
+ */
108
+ private $cssinlinesize = '';
109
+
110
+ /**
111
+ * Setting (only filter) of CSS that can be removed.
112
+ *
113
+ * @var array
114
+ */
115
+ private $cssremovables = array();
116
+
117
+ /**
118
+ * Setting: should inline CSS be aggregated.
119
+ *
120
+ * @var bool
121
+ */
122
+ private $include_inline = false;
123
+
124
+ /**
125
+ * Setting (only filter) if minified CSS can be injected after minificatoin of aggregated CSS.
126
+ *
127
+ * @var bool
128
+ */
129
+ private $inject_min_late = true;
130
+
131
+ /**
132
+ * Holds all exclusions.
133
+ *
134
+ * @var array
135
+ */
136
+ private $dontmove = array();
137
+
138
+ /**
139
+ * Holds all options.
140
+ *
141
+ * @var array
142
+ */
143
+ private $options = array();
144
+
145
+ /**
146
+ * Setting; should excluded CSS-files be minified.
147
+ *
148
+ * @var bool
149
+ */
150
  private $minify_excluded = true;
151
 
152
+ /**
153
+ * Setting (filter only); should all media-attributes be forced to "all".
154
+ *
155
+ * @var bool
156
+ */
157
+ private $media_force_all = false;
158
 
159
+ /**
160
+ * Reads the page and collects style tags.
161
+ *
162
+ * @param array $options all options.
163
+ */
164
  public function read( $options )
165
  {
166
+ $noptimize_css = apply_filters( 'autoptimize_filter_css_noptimize', false, $this->content );
167
+ if ( $noptimize_css ) {
168
  return false;
169
  }
170
 
171
+ $whitelist_css = apply_filters( 'autoptimize_filter_css_whitelist', '', $this->content );
172
+ if ( ! empty( $whitelist_css ) ) {
173
+ $this->whitelist = array_filter( array_map( 'trim', explode( ',', $whitelist_css ) ) );
174
  }
175
 
176
+ $removable_css = apply_filters( 'autoptimize_filter_css_removables', '' );
177
+ if ( ! empty( $removable_css ) ) {
178
+ $this->cssremovables = array_filter( array_map( 'trim', explode( ',', $removable_css ) ) );
179
  }
180
 
181
  $this->cssinlinesize = apply_filters( 'autoptimize_filter_css_inlinesize', 256 );
205
  }
206
 
207
  // List of CSS strings which are excluded from autoptimization.
208
+ $exclude_css = apply_filters( 'autoptimize_filter_css_exclude', $options['css_exclude'], $this->content );
209
+ if ( '' !== $exclude_css ) {
210
+ $this->dontmove = array_filter( array_map( 'trim', explode( ',', $exclude_css ) ) );
211
  } else {
212
  $this->dontmove = array();
213
  }
241
  }
242
  $this->minify_excluded = apply_filters( 'autoptimize_filter_css_minify_excluded', $this->minify_excluded, '' );
243
 
244
+ // should we force all media-attributes to all?
245
+ $this->media_force_all = apply_filters( 'autoptimize_filter_css_tagmedia_forceall', false );
246
+
247
  // noptimize me.
248
  $this->content = $this->hide_noptimize( $this->content );
249
 
250
  // Exclude (no)script, as those may contain CSS which should be left as is.
251
  $this->content = $this->replace_contents_with_marker_if_exists(
252
+ 'SCRIPT',
253
+ '<script',
254
+ '#<(?:no)?script.*?<\/(?:no)?script>#is',
255
+ $this->content
256
  );
257
 
258
  // Save IE hacks.
272
  if ( false !== strpos( $tag, 'media=' ) ) {
273
  preg_match( '#media=(?:"|\')([^>]*)(?:"|\')#Ui', $tag, $medias );
274
  $medias = explode( ',', $medias[1] );
275
+ $media = array();
276
  foreach ( $medias as $elem ) {
 
277
  if ( empty( $elem ) ) {
278
  $elem = 'all';
279
  }
285
  $media = array( 'all' );
286
  }
287
 
288
+ // forcing media attribute to all to merge all in one file.
289
+ if ( $this->media_force_all ) {
290
+ $media = array( 'all' );
291
+ }
292
+
293
  $media = apply_filters( 'autoptimize_filter_css_tagmedia', $media, $tag );
294
 
295
  if ( preg_match( '#<link.*href=("|\')(.*)("|\')#Usmi', $tag, $source ) ) {
303
  } else {
304
  // Link is dynamic (.php etc).
305
  $new_tag = $this->optionally_defer_excluded( $tag, 'none' );
306
+ if ( '' !== $new_tag && $new_tag !== $tag ) {
307
  $this->content = str_replace( $tag, $new_tag, $this->content );
308
  }
309
  $tag = '';
317
  $tag = $this->hide_comments( $tag );
318
 
319
  if ( $this->include_inline ) {
320
+ $code = preg_replace( '#^.*<!\[CDATA\[(?:\s*\*/)?(.*)(?://|/\*)\s*?\]\]>.*$#sm', '$1', $code[1] );
321
  $this->css[] = array( $media, 'INLINE;' . $code );
322
  } else {
323
  $tag = '';
343
  if ( ! empty( $minified_url ) ) {
344
  // Replace orig URL with cached minified URL.
345
  $new_tag = str_replace( $url, $minified_url, $tag );
346
+ } else {
347
+ // Remove the original style tag, because cache content is empty.
348
+ $new_tag = '';
349
  }
350
  }
351
  }
352
 
353
+ if ( '' !== $new_tag ) {
354
+ // Optionally defer (preload) non-aggregated CSS.
355
+ $new_tag = $this->optionally_defer_excluded( $new_tag, $url );
356
+ }
357
 
358
  // And replace!
359
+ if ( ( '' !== $new_tag && $new_tag !== $tag ) || ( '' === $new_tag && apply_filters( 'autoptimize_filter_css_remove_empty_files', false ) ) ) {
360
  $this->content = str_replace( $tag, $new_tag, $this->content );
361
  }
362
  }
381
  private function optionally_defer_excluded( $tag, $url = '' )
382
  {
383
  // Defer single CSS if "inline & defer" is ON and there is inline CSS.
384
+ if ( ! empty( $tag ) && $this->defer && ! empty( $this->defer_inline ) && apply_filters( 'autoptimize_filter_css_defer_excluded', true, $tag ) ) {
385
  // Get/ set (via filter) the JS to be triggers onload of the preloaded CSS.
386
  $_preload_onload = apply_filters(
387
  'autoptimize_filter_css_preload_onload',
388
  "this.onload=null;this.rel='stylesheet'",
389
  $url
390
  );
391
+
392
  // Adapt original <link> element for CSS to be preloaded and add <noscript>-version for fallback.
393
  $new_tag = '<noscript>' . autoptimizeUtils::remove_id_from_node( $tag ) . '</noscript>' . str_replace(
394
  array(
395
  "rel='stylesheet'",
396
  'rel="stylesheet"',
397
  ),
398
+ "rel='preload' as='style' onload=\"" . $_preload_onload . '"',
399
  $tag
400
  );
401
+
402
+ return $new_tag;
403
  }
404
 
405
+ // Return unchanged $tag.
406
+ return $tag;
407
  }
408
 
409
  /**
410
  * Checks if the local file referenced by $path is a valid
411
  * candidate for being inlined into a data: URI
412
  *
413
+ * @param string $path image path.
414
  * @return boolean
415
  */
416
  private function is_datauri_candidate( $path )
468
  // Again, skip doing certain stuff repeatedly when loop-called.
469
  if ( null === $exclude_list ) {
470
  $exclude_list = apply_filters( 'autoptimize_filter_css_datauri_exclude', '' );
471
+ $no_datauris = array_filter( array_map( 'trim', explode( ',', $exclude_list ) ) );
472
  }
473
 
474
  $matched = false;
501
  }
502
  }
503
 
504
+ $hash = md5( $path );
505
  $check = new autoptimizeCache( $hash, 'img' );
506
  if ( $check->check() ) {
507
  // we have the base64 image in cache.
508
+ $head_and_data = $check->retrieve();
509
+ $_base64data = explode( ';base64,', $head_and_data );
510
+ $base64data = $_base64data[1];
511
  unset( $_base64data );
512
  } else {
513
  // It's an image and we don't have it in cache, get the type by extension.
514
  $exploded_path = explode( '.', $path );
515
+ $type = end( $exploded_path );
516
 
517
  switch ( $type ) {
518
  case 'jpg':
536
  }
537
 
538
  // Encode the data.
539
+ $base64data = base64_encode( file_get_contents( $path ) );
540
+ $head_and_data = $dataurihead . $base64data;
541
 
542
  // Save in cache.
543
+ $check->cache( $head_and_data, 'text/plain' );
544
  }
545
  unset( $check );
546
 
547
+ return array(
548
+ 'full' => $head_and_data,
549
+ 'base64data' => $base64data,
550
+ );
551
  }
552
 
553
  /**
554
  * Given an array of key/value pairs to replace in $string,
555
  * it does so by replacing the longest-matching strings first.
556
  *
557
+ * @param string $string string in which to replace.
558
+ * @param array $replacements to be replaced strings and replacement.
559
  *
560
  * @return string
561
  */
611
  $replacement_url = $this->url_replace_cdn( $url );
612
  // Prepare replacements array.
613
  $replacements[ $url_src_matches[1][ $count ] ] = str_replace(
614
+ $original_url, $replacement_url, $url_src_matches[1][ $count ]
615
  );
616
  }
617
  }
627
  * Also does CDN replacement of any font-urls within those declarations if the `autoptimize_filter_css_fonts_cdn`
628
  * filter is used.
629
  *
630
+ * @param string $code HTML being processed to hide fonts.
631
  * @return string
632
  */
633
  public function hide_fontface_and_maybe_cdn( $code )
649
 
650
  // Replace declaration with its base64 encoded string.
651
  $replacement = self::build_marker( 'FONTFACE', $full_match );
652
+ $code = str_replace( $match_search, $replacement, $code );
653
  }
654
  }
655
 
660
  * Restores original @font-face declarations that have been "hidden"
661
  * using `hide_fontface_and_maybe_cdn()`.
662
  *
663
+ * @param string $code HTML being processed to unhide fonts.
664
  * @return string
665
  */
666
  public function restore_fontface( $code )
668
  return $this->restore_marked_content( 'FONTFACE', $code );
669
  }
670
 
671
+ /**
672
+ * Re-write (and/or inline) referenced assets.
673
+ *
674
+ * @param string $code HTML being processed rewrite assets.
675
+ * @return string
676
+ */
677
  public function rewrite_assets( $code )
678
  {
679
  // Handle @font-face rules by hiding and processing them separately.
691
 
692
  // Re-write (and/or inline) URLs to point them to the CDN host.
693
  $url_src_matches = array();
694
+ $imgreplace = array();
695
+
696
  // Matches and captures anything specified within the literal `url()` and excludes those containing data: URIs.
697
  preg_match_all( self::ASSETS_REGEX, $code, $url_src_matches );
698
  if ( is_array( $url_src_matches ) && ! empty( $url_src_matches ) ) {
714
  if ( ! $excluded ) {
715
  $is_datauri_candidate = $this->is_datauri_candidate( $ipath );
716
  if ( $is_datauri_candidate ) {
717
+ $datauri = $this->build_or_get_datauri_image( $ipath );
718
+ $base64data = $datauri['base64data'];
719
  // Add it to the list for replacement.
720
  $imgreplace[ $url_src_matches[1][ $count ] ] = str_replace(
721
+ $original_url,
722
+ $datauri['full'],
723
+ $url_src_matches[1][ $count ]
724
  );
725
+ $inlined = true;
726
  }
727
  }
728
  }
735
  */
736
  if ( ! $inlined && ( ! empty( $this->cdn_url ) || has_filter( 'autoptimize_filter_base_replace_cdn' ) ) ) {
737
  // Just do the "simple" CDN replacement.
738
+ $replacement_url = $this->url_replace_cdn( $url );
739
  $imgreplace[ $url_src_matches[1][ $count ] ] = str_replace(
740
+ $original_url, $replacement_url, $url_src_matches[1][ $count ]
741
  );
742
  }
743
  }
751
  return $code;
752
  }
753
 
754
+ /**
755
+ * Joins and optimizes CSS.
756
+ */
757
  public function minify()
758
  {
759
  foreach ( $this->css as $group ) {
760
  list( $media, $css ) = $group;
761
  if ( preg_match( '#^INLINE;#', $css ) ) {
762
  // <style>.
763
+ $css = preg_replace( '#^INLINE;#', '', $css );
764
+ $css = self::fixurls( ABSPATH . 'index.php', $css ); // ABSPATH already contains a trailing slash.
765
  $tmpstyle = apply_filters( 'autoptimize_css_individual_style', $css, '' );
766
  if ( has_filter( 'autoptimize_css_individual_style' ) && ! empty( $tmpstyle ) ) {
767
+ $css = $tmpstyle;
768
  $this->alreadyminified = true;
769
  }
770
  } else {
771
  // <link>
772
  if ( false !== $css && file_exists( $css ) && is_readable( $css ) ) {
773
+ $css_path = $css;
774
+ $css = self::fixurls( $css_path, file_get_contents( $css_path ) );
775
+ $css = preg_replace( '/\x{EF}\x{BB}\x{BF}/', '', $css );
776
+ $tmpstyle = apply_filters( 'autoptimize_css_individual_style', $css, $css_path );
777
  if ( has_filter( 'autoptimize_css_individual_style' ) && ! empty( $tmpstyle ) ) {
778
+ $css = $tmpstyle;
779
  $this->alreadyminified = true;
780
+ } elseif ( $this->can_inject_late( $css_path, $css ) ) {
781
+ $css = self::build_injectlater_marker( $css_path, md5( $css ) );
782
  }
783
  } else {
784
  // Couldn't read CSS. Maybe getpath isn't working?
788
 
789
  foreach ( $media as $elem ) {
790
  if ( ! empty( $css ) ) {
791
+ if ( ! isset( $this->csscode[ $elem ] ) ) {
792
+ $this->csscode[ $elem ] = '';
793
  }
794
+ $this->csscode[ $elem ] .= "\n/*FILESTART*/" . $css;
795
  }
796
  }
797
  }
806
  // If same code.
807
  if ( $sum === $md5sum ) {
808
  // Add the merged code.
809
+ $medianame = $med . ', ' . $media;
810
+ $this->csscode[ $medianame ] = $code;
811
+ $md5list[ $medianame ] = $md5list[ $med ];
812
+ unset( $this->csscode[ $med ], $this->csscode[ $media ], $md5list[ $med ] );
813
  }
814
  }
815
+ $md5list[ $medianame ] = $md5sum;
816
  }
817
  unset( $tmpcss );
818
 
827
  while ( preg_match_all( '#@import +(?:url)?(?:(?:\((["\']?)(?:[^"\')]+)\1\)|(["\'])(?:[^"\']+)\2)(?:[^,;"\']+(?:,[^,;"\']+)*)?)(?:;)#mi', $thiscss_nocomments, $matches ) ) {
828
  foreach ( $matches[0] as $import ) {
829
  if ( $this->isremovable( $import, $this->cssremovables ) ) {
830
+ $thiscss = str_replace( $import, '', $thiscss );
831
  $import_ok = true;
832
  } else {
833
+ $url = trim( preg_replace( '#^.*((?:https?:|ftp:)?//.*\.css).*$#', '$1', trim( $import ) ), " \t\n\r\0\x0B\"'" );
834
+ $path = $this->getpath( $url );
835
  $import_ok = false;
836
  if ( file_exists( $path ) && is_readable( $path ) ) {
837
+ $code = addcslashes( self::fixurls( $path, file_get_contents( $path ) ), '\\' );
838
+ $code = preg_replace( '/\x{EF}\x{BB}\x{BF}/', '', $code );
839
  $tmpstyle = apply_filters( 'autoptimize_css_individual_style', $code, '' );
840
  if ( has_filter( 'autoptimize_css_individual_style' ) && ! empty( $tmpstyle ) ) {
841
+ $code = $tmpstyle;
842
  $this->alreadyminified = true;
843
  } elseif ( $this->can_inject_late( $path, $code ) ) {
844
  $code = self::build_injectlater_marker( $path, md5( $code ) );
847
  if ( ! empty( $code ) ) {
848
  $tmp_thiscss = preg_replace( '#(/\*FILESTART\*/.*)' . preg_quote( $import, '#' ) . '#Us', '/*FILESTART2*/' . $code . '$1', $thiscss );
849
  if ( ! empty( $tmp_thiscss ) ) {
850
+ $thiscss = $tmp_thiscss;
851
  $import_ok = true;
852
  unset( $tmp_thiscss );
853
  }
885
  do_action( 'autoptimize_action_css_hash', $hash );
886
  $ccheck = new autoptimizeCache( $hash, 'css' );
887
  if ( $ccheck->check() ) {
888
+ $code = $ccheck->retrieve();
889
+ $this->hashmap[ md5( $code ) ] = $hash;
890
  continue;
891
  }
892
  unset( $ccheck );
907
  unset( $tmp_code );
908
  }
909
 
910
+ $this->hashmap[ md5( $code ) ] = $hash;
911
  }
912
 
913
  unset( $code );
933
  return $code;
934
  }
935
 
936
+ /**
937
+ * Caches the CSS in uncompressed, deflated and gzipped form.
938
+ */
939
  public function cache()
940
  {
941
  // CSS cache.
942
  foreach ( $this->csscode as $media => $code ) {
943
+ if ( empty( $code ) ) {
944
+ continue;
945
+ }
946
+
947
+ $md5 = $this->hashmap[ md5( $code ) ];
948
  $cache = new autoptimizeCache( $md5, 'css' );
949
  if ( ! $cache->check() ) {
950
  // Cache our code.
951
  $cache->cache( $code, 'text/css' );
952
  }
953
+ $this->url[ $media ] = AUTOPTIMIZE_CACHE_URL . $cache->getname();
954
  }
955
  }
956
 
957
+ /**
958
+ * Returns the content.
959
+ */
960
  public function getcontent()
961
  {
962
  // Restore the full content (only applies when "autoptimize_filter_css_justhead" filter is true).
963
  if ( ! empty( $this->restofcontent ) ) {
964
+ $this->content .= $this->restofcontent;
965
  $this->restofcontent = '';
966
  }
967
 
972
  }
973
 
974
  // Inject the new stylesheets.
975
+ $replace_tag = array( '<title', 'before' );
976
+ $replace_tag = apply_filters( 'autoptimize_filter_css_replacetag', $replace_tag, $this->content );
977
 
978
  if ( $this->inline ) {
979
  foreach ( $this->csscode as $media => $code ) {
980
+ $this->inject_in_html( '<style ' . $type_css . 'media="' . $media . '">' . $code . '</style>', $replace_tag );
981
  }
982
  } else {
983
  if ( $this->defer ) {
984
+ $preload_css_block = '';
985
  $inlined_ccss_block = '';
986
+ $noscript_css_block = '<noscript id="aonoscrcss">';
987
 
988
  $defer_inline_code = $this->defer_inline;
989
  if ( ! empty( $defer_inline_code ) ) {
990
  if ( apply_filters( 'autoptimize_filter_css_critcss_minify', true ) ) {
991
+ $icss_hash = md5( $defer_inline_code );
992
+ $icss_cache = new autoptimizeCache( $icss_hash, 'css' );
993
+ if ( $icss_cache->check() ) {
994
  // we have the optimized inline CSS in cache.
995
+ $defer_inline_code = $icss_cache->retrieve();
996
  } else {
997
  $cssmin = new autoptimizeCSSmin();
998
  $tmp_code = trim( $cssmin->run( $defer_inline_code ) );
999
 
1000
  if ( ! empty( $tmp_code ) ) {
1001
  $defer_inline_code = $tmp_code;
1002
+ $icss_cache->cache( $defer_inline_code, 'text/css' );
1003
  unset( $tmp_code );
1004
  }
1005
  }
1015
 
1016
  // Add the stylesheet either deferred (import at bottom) or normal links in head.
1017
  if ( $this->defer ) {
1018
+ $preload_onload = autoptimizeConfig::get_ao_css_preload_onload();
1019
 
1020
+ $preload_css_block .= '<link rel="preload" as="style" media="' . $media . '" href="' . $url . '" onload="' . $preload_onload . '" />';
1021
+ $noscript_css_block .= '<link ' . $type_css . 'media="' . $media . '" href="' . $url . '" rel="stylesheet" />';
1022
  } else {
1023
+ if ( strlen( $this->csscode[ $media ] ) > $this->cssinlinesize ) {
1024
+ $this->inject_in_html( '<link ' . $type_css . 'media="' . $media . '" href="' . $url . '" rel="stylesheet" />', $replace_tag );
1025
+ } elseif ( strlen( $this->csscode[ $media ] ) > 0 ) {
1026
+ $this->inject_in_html( '<style ' . $type_css . 'media="' . $media . '">' . $this->csscode[ $media ] . '</style>', $replace_tag );
1027
  }
1028
  }
1029
  }
1030
 
1031
  if ( $this->defer ) {
1032
+ $preload_polyfill = autoptimizeConfig::get_ao_css_preload_polyfill();
1033
+ $noscript_css_block .= '</noscript>';
1034
  // Inject inline critical CSS, the preloaded full CSS and the noscript-CSS.
1035
+ $this->inject_in_html( $inlined_ccss_block . $preload_css_block . $noscript_css_block, $replace_tag );
1036
 
1037
  // Adds preload polyfill at end of body tag.
1038
  $this->inject_in_html(
1058
  return $this->content;
1059
  }
1060
 
1061
+ /**
1062
+ * Make sure URL's are absolute iso relative to original CSS location.
1063
+ *
1064
+ * @param string $file filename of optimized CSS-file.
1065
+ * @param string $code CSS-code in which to fix URL's.
1066
+ */
1067
  static function fixurls( $file, $code )
1068
  {
1069
  // Switch all imports to the url() syntax.
1072
  if ( preg_match_all( self::ASSETS_REGEX, $code, $matches ) ) {
1073
  $file = str_replace( WP_ROOT_DIR, '/', $file );
1074
  /**
1075
+ * Rollback as per https://github.com/futtta/autoptimize/issues/94
1076
  * $file = str_replace( AUTOPTIMIZE_WP_CONTENT_NAME, '', $file );
1077
  */
1078
  $dir = dirname( $file ); // Like /themes/expound/css.
1088
  $replace = array();
1089
  foreach ( $matches[1] as $k => $url ) {
1090
  // Remove quotes.
1091
+ $url = trim( $url, " \t\n\r\0\x0B\"'" );
1092
+ $no_q_url = trim( $url, "\"'" );
1093
+ if ( $url !== $no_q_url ) {
1094
+ $removed_quotes = true;
1095
  } else {
1096
+ $removed_quotes = false;
1097
  }
1098
 
1099
+ if ( '' === $no_q_url ) {
1100
  continue;
1101
  }
1102
 
1103
+ $url = $no_q_url;
1104
  if ( '/' === $url[0] || preg_match( '#^(https?://|ftp://|data:)#i', $url ) ) {
1105
  // URL is protocol-relative, host-relative or something we don't touch.
1106
  continue;
1107
+ } else { // Relative URL.
1108
+
1109
+ /*
1110
  * rollback as per https://github.com/futtta/autoptimize/issues/94
1111
  * $newurl = preg_replace( '/https?:/', '', str_replace( ' ', '%20', AUTOPTIMIZE_WP_CONTENT_URL . str_replace( '//', '/', $dir . '/' . $url ) ) );
1112
  */
1118
  * We must do this, or different css classes referencing the same bg image (but
1119
  * different parts of it, say, in sprites and such) loose their stuff...
1120
  */
1121
+ $hash = md5( $url . $matches[2][ $k ] );
1122
+ $code = str_replace( $matches[0][ $k ], $hash, $code );
1123
 
1124
+ if ( $removed_quotes ) {
1125
+ $replace[ $hash ] = "url('" . $newurl . "')" . $matches[2][ $k ];
1126
  } else {
1127
+ $replace[ $hash ] = 'url(' . $newurl . ')' . $matches[2][ $k ];
1128
  }
1129
  }
1130
  }
1164
  }
1165
  }
1166
 
1167
+ private function can_inject_late( $css_path, $css )
1168
  {
1169
+ $consider_minified_array = apply_filters( 'autoptimize_filter_css_consider_minified', false, $css_path );
1170
  if ( true !== $this->inject_min_late ) {
1171
  // late-inject turned off.
1172
  return false;
1173
+ } elseif ( ( false === strpos( $css_path, 'min.css' ) ) && ( str_replace( $consider_minified_array, '', $css_path ) === $css_path ) ) {
1174
  // file not minified based on filename & filter.
1175
  return false;
1176
  } elseif ( false !== strpos( $css, '@import' ) ) {
1179
  } elseif ( ( false !== strpos( $css, '@font-face' ) ) && ( apply_filters( 'autoptimize_filter_css_fonts_cdn', false ) === true ) && ( ! empty( $this->cdn_url ) ) ) {
1180
  // don't late-inject CSS with font-src's if fonts are set to be CDN'ed.
1181
  return false;
1182
+ } elseif ( ( ( true == $this->datauris ) || ( ! empty( $this->cdn_url ) ) ) && preg_match( '#background[^;}]*url\(#Ui', $css ) ) {
1183
  // don't late-inject CSS with images if CDN is set OR if image inlining is on.
1184
  return false;
1185
  } else {
1221
  // Now minify...
1222
  $cssmin = new autoptimizeCSSmin();
1223
  $contents = trim( $cssmin->run( $contents ) );
1224
+
1225
+ // Check if minified cache content is empty.
1226
+ if ( empty( $contents ) ) {
1227
+ return false;
1228
+ }
1229
+
1230
  // Store in cache.
1231
  $cache->cache( $contents, 'text/css' );
1232
  }
1258
 
1259
  public function setOption( $name, $value )
1260
  {
1261
+ $this->options[ $name ] = $value;
1262
+ $this->$name = $value;
1263
  }
1264
 
1265
  public function getOption( $name )
1266
  {
1267
+ return $this->options[ $name ];
1268
  }
1269
  }
classes/autoptimizeUtils.php CHANGED
@@ -59,7 +59,7 @@ class autoptimizeUtils
59
  * @param string $string String.
60
  * @param string|null $encoding Encoding.
61
  *
62
- * @return int Number of charcters or bytes in given $string
63
  * (characters if/when supported, bytes otherwise).
64
  */
65
  public static function strlen( $string, $encoding = null )
@@ -204,7 +204,7 @@ class autoptimizeUtils
204
  }
205
 
206
  /**
207
- * When siteurl contans a path other than '/' and the CDN URL does not have
208
  * a path or it's path is '/', this will modify the CDN URL's path component
209
  * to match that of the siteurl.
210
  * This is to support "magic" CDN urls that worked that way before v2.4...
59
  * @param string $string String.
60
  * @param string|null $encoding Encoding.
61
  *
62
+ * @return int Number of characters or bytes in given $string
63
  * (characters if/when supported, bytes otherwise).
64
  */
65
  public static function strlen( $string, $encoding = null )
204
  }
205
 
206
  /**
207
+ * When siteurl contains a path other than '/' and the CDN URL does not have
208
  * a path or it's path is '/', this will modify the CDN URL's path component
209
  * to match that of the siteurl.
210
  * This is to support "magic" CDN urls that worked that way before v2.4...
classes/critcss-inc/admin_settings_adv.php ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Contains the function to render the advanced panel.
4
+ */
5
+
6
+ /**
7
+ * Function to render the advanced panel.
8
+ */
9
+ function ao_ccss_render_adv() {
10
+ // Attach required globals.
11
+ global $ao_ccss_debug;
12
+ global $ao_ccss_finclude;
13
+ global $ao_ccss_rlimit;
14
+ global $ao_ccss_noptimize;
15
+ global $ao_ccss_loggedin;
16
+ global $ao_ccss_forcepath;
17
+ global $ao_ccss_deferjquery;
18
+ global $ao_ccss_domain;
19
+
20
+ // In case domain is not set yet (done in cron.php).
21
+ if ( empty( $ao_ccss_domain ) ) {
22
+ $ao_ccss_domain = get_site_url();
23
+ }
24
+
25
+ // Get viewport size.
26
+ $viewport = autoptimizeCriticalCSSCore::ao_ccss_viewport();
27
+ ?>
28
+ <ul id="adv-panel">
29
+ <li class="itemDetail">
30
+ <h2 class="itemTitle fleft"><?php _e( 'Advanced Settings', 'autoptimize' ); ?></h2>
31
+ <button type="button" class="toggle-btn">
32
+ <span class="toggle-indicator dashicons dashicons-arrow-up dashicons-arrow-down"></span>
33
+ </button>
34
+ <div class="collapsible hidden">
35
+ <table id="key" class="form-table">
36
+ <tr>
37
+ <th scope="row">
38
+ <?php _e( 'Viewport Size', 'autoptimize' ); ?>
39
+ </th>
40
+ <td>
41
+ <label for="autoptimize_ccss_vw"><?php _e( 'Width', 'autoptimize' ); ?>:</label> <input type="number" id="autoptimize_ccss_vw" name="autoptimize_ccss_viewport[w]" min="800" max="4096" placeholder="1400" value="<?php echo $viewport['w']; ?>" />&nbsp;&nbsp;
42
+ <label for="autoptimize_ccss_vh"><?php _e( 'Height', 'autoptimize' ); ?>:</label> <input type="number" id="autoptimize_ccss_vh" name="autoptimize_ccss_viewport[h]" min="600" max="2160" placeholder="1080" value="<?php echo $viewport['h']; ?>" />
43
+ <p class="notes">
44
+ <?php _e( '<a href="https://criticalcss.com/account/api-keys?aff=1" target="_blank">criticalcss.com</a> default viewport size is 1400x1080 pixels (width x height). You can change this size by typing a desired width and height values above. Allowed value ranges are from 800 to 4096 for width and from 600 to 2160 for height.', 'autoptimize' ); ?>
45
+ </p>
46
+ </td>
47
+ </tr>
48
+ <tr>
49
+ <th scope="row">
50
+ <?php _e( 'Force Include CSS selectors', 'autoptimize' ); ?>
51
+ </th>
52
+ <td>
53
+ <textarea id="autoptimize_ccss_finclude" name="autoptimize_ccss_finclude" rows='3' maxlenght='500' style="width:100%;" placeholder="<?php _e( '.button-special,//#footer', 'autoptimize' ); ?>"><?php echo trim( $ao_ccss_finclude ); ?></textarea>
54
+ <p class="notes">
55
+ <?php _e( 'Force include CSS selectors can be used to style dynamic content that is not part of the HTML that is seen during the Critical CSS generation. To use this feature, add comma separated values with both simple strings and/or regular expressions to match the desired selectors. Regular expressions must be preceeded by two forward slashes. For instance: <code>.button-special,//#footer</code>. In this example <code>.button-special</code> will match <code>.button-special</code> selector only, while <code>//#footer</code> will match <code>#footer</code>, <code>#footer-address</code> and <code>#footer-phone</code> selectors in case they exist.<br />Do take into account that changing this setting will only affect new/ updated rules, so you might want to remove old rules and clear your page cache to expedite the forceIncludes becoming used.', 'autoptimize' ); ?>
56
+ </p>
57
+ </td>
58
+ </tr>
59
+ <tr>
60
+ <th scope="row">
61
+ <?php _e( 'Request Limit', 'autoptimize' ); ?>
62
+ </th>
63
+ <td>
64
+ <input type="number" id="autoptimize_ccss_rlimit" name="autoptimize_ccss_rlimit" min="1" max="240" placeholder="0" value="<?php echo $ao_ccss_rlimit; ?>" />
65
+ <p class="notes">
66
+ <?php _e( 'Certain hosting services impose hard limitations to background processes on either execution time, requests made from your server to any third party services, or both. This could lead to a faulty operation of the queue background process triggered by WP-Cron. If automated rules are not being created, you may be facing this limitation from your hosting provider. In that case, set the request limit to a reasonable number between 1 and 240. The queue fire a request to <a href="https://criticalcss.com/account/api-keys?aff=1" target="_blank">criticalcss.com</a> on every 15 seconds (due to service limitations). If your hosting provider allows a 60 seconds time span to background processes runtime, set this value to 3 or 4 so the queue can operate within the boundaries. The maximum value of 240 allows enough requests for one hour long. To disable this limit and to let requests be made at will, just delete any values in this setting (a grey 0 will show).', 'autoptimize' ); ?>
67
+ </p>
68
+ </td>
69
+ </tr>
70
+ <tr>
71
+ <th scope="row">
72
+ <?php _e( 'Fetch Original CSS', 'autoptimize' ); ?>
73
+ </th>
74
+ <td>
75
+ <input type="checkbox" id="autoptimize_ccss_noptimize" name="autoptimize_ccss_noptimize" value="1" <?php checked( 1 == $ao_ccss_noptimize ); ?>>
76
+ <p class="notes">
77
+ <?php _e( 'In some (rare) cases the generation of critical CSS works better with the original CSS instead of the Autoptimized one, this option enables that behavior.', 'autoptimize' ); ?>
78
+ </p>
79
+ </td>
80
+ </tr>
81
+ <tr>
82
+ <th scope="row">
83
+ <?php _e( 'Add CCSS for logged in users?', 'autoptimize' ); ?>
84
+ </th>
85
+ <td>
86
+ <input type="checkbox" id="autoptimize_ccss_loggedin" name="autoptimize_ccss_loggedin" value="1" <?php checked( 1 == $ao_ccss_loggedin ); ?>>
87
+ <p class="notes">
88
+ <?php _e( 'Critical CSS is generated by criticalcss.com from your pages as seen be "anonymous visitor", disable this option if you don\'t want the "visitor" critical CSS to be used for logged on users.', 'autoptimize' ); ?>
89
+ </p>
90
+ </td>
91
+ </tr>
92
+ <tr>
93
+ <th scope="row">
94
+ <?php _e( 'Force path-based rules to be generated for pages?', 'autoptimize' ); ?>
95
+ </th>
96
+ <td>
97
+ <input type="checkbox" id="autoptimize_ccss_forcepath" name="autoptimize_ccss_forcepath" value="1" <?php checked( 1 == $ao_ccss_forcepath ); ?>>
98
+ <p class="notes">
99
+ <?php _e( 'By default for each page a separate rule is generated. If your pages have (semi-)identical above the fold look and feel and you want to keep the rules lean, you can disable that so one rule is created to all pages.', 'autoptimize' ); ?>
100
+ </p>
101
+ </td>
102
+ </tr>
103
+ <tr>
104
+ <th scope="row">
105
+ <?php _e( 'Defer jQuery and other non-aggregated JS-files?', 'autoptimize' ); ?>
106
+ </th>
107
+ <td>
108
+ <input type="checkbox" id="autoptimize_ccss_deferjquery" name="autoptimize_ccss_deferjquery" value="1" <?php checked( 1 == $ao_ccss_deferjquery ); ?>>
109
+ <p class="notes">
110
+ <?php _e( 'Defer all non-aggregated JS, including jQuery and inline JS to fix remaining render-blocking issues. Make sure to test your site thoroughly when activating this option!', 'autoptimize' ); ?>
111
+ </p>
112
+ </td>
113
+ </tr>
114
+ <tr>
115
+ <th scope="row">
116
+ <?php _e( 'Bound domain', 'autoptimize' ); ?>
117
+ </th>
118
+ <td>
119
+ <input type="text" id="autoptimize_ccss_domain" name="autoptimize_ccss_domain" style="width:100%;" placeholder="<?php _e( 'Don\'t leave this empty, put e.g. https://example.net/ or simply \'none\' to disable domain binding.', 'autoptimize' ); ?>" value="<?php echo trim( $ao_ccss_domain ); ?>">
120
+ <p class="notes">
121
+ <?php _e( 'Only requests from this domain will be sent for Critical CSS generation (pricing is per domain/ month).', 'autoptimize' ); ?>
122
+ </p>
123
+ </td>
124
+ </tr>
125
+ <tr>
126
+ <th scope="row">
127
+ <?php _e( 'Debug Mode', 'autoptimize' ); ?>
128
+ </th>
129
+ <td>
130
+ <input type="checkbox" id="autoptimize_ccss_debug" name="autoptimize_ccss_debug" value="1" <?php checked( 1 == $ao_ccss_debug ); ?>>
131
+ <p class="notes">
132
+ <?php
133
+ _e( '<strong>CAUTION! Only use debug mode on production/live environments for ad-hoc troubleshooting and remember to turn it back off after</strong>, as this generates a lot of log-data.<br />Check the box above to enable Autoptimize CriticalCSS Power-Up debug mode. It provides debug facilities in this screen, to the browser console and to this file: ', 'autoptimize' );
134
+ echo '<code>' . AO_CCSS_LOG . '</code>';
135
+ ?>
136
+ </p>
137
+ </td>
138
+ </tr>
139
+ </table>
140
+ </div>
141
+ </li>
142
+ </ul>
143
+ <?php
144
+ }
145
+ ?>
classes/critcss-inc/admin_settings_debug.php ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Debug panel.
4
+ */
5
+
6
+ // Attach wpdb() object.
7
+ global $wpdb;
8
+
9
+ // Query AO's options.
10
+ $ao_options = $wpdb->get_results('
11
+ SELECT option_name AS name,
12
+ option_value AS value
13
+ FROM ' . $wpdb->options . '
14
+ WHERE option_name LIKE "autoptimize_%%"
15
+ ORDER BY name
16
+ ', ARRAY_A);
17
+
18
+ // Query AO's transients.
19
+ $ao_trans = $wpdb->get_results('
20
+ SELECT option_name AS name,
21
+ option_value AS value
22
+ FROM ' . $wpdb->options . '
23
+ WHERE option_name LIKE "_transient_autoptimize_%%"
24
+ OR option_name LIKE "_transient_timeout_autoptimize_%%"
25
+ ', ARRAY_A);
26
+
27
+ // Render debug panel if there's something to show.
28
+ if ( $ao_options || $ao_trans ) {
29
+ ?>
30
+ <!-- BEGIN: Settings Debug -->
31
+ <ul>
32
+ <li class="itemDetail">
33
+ <h2 class="itemTitle"><?php _e( 'Debug Information', 'autoptimize' ); ?></h2>
34
+
35
+ <?php
36
+ // Render options.
37
+ if ( $ao_options ) {
38
+ ?>
39
+ <h4><?php _e( 'Options', 'autoptimize' ); ?>:</h4>
40
+ <table class="form-table debug">
41
+ <?php
42
+ foreach ( $ao_options as $option ) {
43
+ ?>
44
+ <tr>
45
+ <th scope="row">
46
+ <?php echo $option['name']; ?>
47
+ </th>
48
+ <td>
49
+ <?php
50
+ if ( 'autoptimize_ccss_queue' == $option['name'] || 'autoptimize_ccss_rules' == $option['name'] ) {
51
+ $value = print_r( json_decode( $option['value'], true ), true );
52
+ if ( $value ) {
53
+ echo "Raw JSON:\n<pre>" . $option['value'] . "</pre>\n\nDecoded JSON:\n<pre>" . $value . '</pre>';
54
+ } else {
55
+ echo 'Empty';
56
+ }
57
+ } else {
58
+ echo $option['value'];
59
+ }
60
+ ?>
61
+ </td>
62
+ </tr>
63
+ <?php
64
+ }
65
+ ?>
66
+ </table>
67
+ <hr />
68
+ <?php
69
+ }
70
+ // Render WP-Cron intervals and scheduled events.
71
+ ?>
72
+ <h4><?php _e( 'WP-Cron Intervals', 'autoptimize' ); ?>:</h4>
73
+ <pre><?php print_r( wp_get_schedules() ); ?></pre>
74
+ <hr />
75
+ <h4><?php _e( 'WP-Cron Scheduled Events', 'autoptimize' ); ?>:</h4>
76
+ <pre><?php print_r( _get_cron_array() ); ?></pre>
77
+ </li>
78
+ </ul>
79
+ <!-- END: Settings Debug -->
80
+ <?php
81
+ }
classes/critcss-inc/admin_settings_explain.php ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Explain what CCSS is (visible if no API key is stored).
4
+ */
5
+
6
+ /**
7
+ * Actual function that explains.
8
+ */
9
+ function ao_ccss_render_explain() {
10
+ ?>
11
+ <style>
12
+ .ao_settings_div {background: white;border: 1px solid #ccc;padding: 1px 15px;margin: 15px 10px 10px 0;}
13
+ .ao_settings_div .form-table th {font-weight: normal;}
14
+ </style>
15
+ <script>document.title = "Autoptimize: <?php _e( 'Critical CSS', 'autoptimize' ); ?> " + document.title;</script>
16
+ <ul id="explain-panel">
17
+ <div class="ao_settings_div">
18
+ <?php
19
+ $ccss_explanation = '';
20
+
21
+ // get the HTML with the explanation of what critical CSS is.
22
+ if ( apply_filters( 'autoptimize_settingsscreen_remotehttp', true ) ) {
23
+ $ccss_explanation = get_transient( 'ao_ccss_explain' );
24
+ if ( empty( $ccss_explanation ) ) {
25
+ $ccss_expl_resp = wp_remote_get( 'https://misc.optimizingmatters.com/autoptimize_ccss_explain.html?ao_ver=' . AUTOPTIMIZE_PLUGIN_VERSION );
26
+ if ( ! is_wp_error( $ccss_expl_resp ) ) {
27
+ if ( '200' == wp_remote_retrieve_response_code( $ccss_expl_resp ) ) {
28
+ $ccss_explanation = wp_kses_post( wp_remote_retrieve_body( $ccss_expl_resp ) );
29
+ set_transient( 'ao_ccss_explain', $ccss_explanation, WEEK_IN_SECONDS );
30
+ }
31
+ }
32
+ }
33
+ }
34
+
35
+ // placeholder text in case HTML is empty.
36
+ if ( empty( $ccss_explanation ) ) {
37
+ $ccss_explanation = '<h2>Fix render-blocking CSS!</h2><p>Significantly improve your first-paint times by making CSS non-render-blocking.</p><p>The next step is to sign up at <a href="https://criticalcss.com/?aff=1" target="_blank">https://criticalcss.com</a> (this is a premium service, priced 2 GBP/month for membership and 5 GBP/month per domain) <strong>and get the API key, which you can copy from <a href="https://criticalcss.com/account/api-keys?aff=1" target="_blank">the API-keys page</a></strong> and paste below.</p><p>If you have any questions or need support, head on over to <a href="https://wordpress.org/support/plugin/autoptimize" target="_blank">our support forum</a> and we\'ll help you get up and running in no time!</p>';
38
+ }
39
+
40
+ // and echo it.
41
+ echo $ccss_explanation;
42
+ ?>
43
+ </div>
44
+ </ul>
45
+ <?php
46
+ }
classes/critcss-inc/admin_settings_impexp.js.php ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Javascript to import and export AO CCSS settings.
4
+ */
5
+
6
+ ?>
7
+ // Export and download settings
8
+ function exportSettings( idToEdit ) {
9
+ console.log('Exporting...');
10
+ var data = {
11
+ 'action': 'ao_ccss_export',
12
+ 'ao_ccss_export_nonce': '<?php echo wp_create_nonce( 'ao_ccss_export_nonce' ); ?>',
13
+ };
14
+
15
+ jQuery.post(ajaxurl, data, function(response) {
16
+ response_array=JSON.parse(response);
17
+ if (response_array['code'] == 200) {
18
+ <?php
19
+ if ( is_multisite() ) {
20
+ $blog_id = '/' . get_current_blog_id() . '/';
21
+ } else {
22
+ $blog_id = '/';
23
+ }
24
+ ?>
25
+ export_url = '<?php echo content_url(); ?>/uploads/ao_ccss' + '<?php echo $blog_id; ?>' + response_array['file'];
26
+ msg = "Download export-file from: <a href=\"" + export_url + "\" target=\"_blank\">"+ export_url + "</a>";
27
+ } else {
28
+ msg = response_array['msg'];
29
+ }
30
+ jQuery("#importdialog").html(msg);
31
+ jQuery("#importdialog").dialog({
32
+ autoOpen: true,
33
+ height: 210,
34
+ width: 700,
35
+ title: "<?php _e( 'Export settings result', 'autoptimize' ); ?>",
36
+ modal: true,
37
+ buttons: {
38
+ OK: function() {
39
+ jQuery( this ).dialog( "close" );
40
+ }
41
+ }
42
+ });
43
+ });
44
+ }
45
+
46
+ // Upload and import settings
47
+ function upload(){
48
+ var fd = new FormData();
49
+ var file = jQuery(document).find('#settingsfile');
50
+ var settings_file = file[0].files[0];
51
+ fd.append('file', settings_file);
52
+ fd.append('action', 'ao_ccss_import');
53
+ fd.append('ao_ccss_import_nonce', '<?php echo wp_create_nonce( 'ao_ccss_import_nonce' ); ?>');
54
+
55
+ jQuery.ajax({
56
+ url: ajaxurl,
57
+ type: 'POST',
58
+ data: fd,
59
+ contentType: false,
60
+ processData: false,
61
+ success: function(response) {
62
+ response_array=JSON.parse(response);
63
+ if (response_array['code'] == 200) {
64
+ window.location.reload();
65
+ }
66
+ }
67
+ });
68
+ }
classes/critcss-inc/admin_settings_key.php ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Render key panel.
4
+ */
5
+
6
+ /**
7
+ * Function that renders key panel.
8
+ *
9
+ * @param string $key API Key.
10
+ * @param string $status API Key status.
11
+ * @param string $status_msg Status message.
12
+ * @param string $message Message.
13
+ * @param string $color Color to highlight message in.
14
+ */
15
+ function ao_ccss_render_key( $key, $status, $status_msg, $message, $color ) {
16
+ if ( defined( 'AUTOPTIMIZE_CRITICALCSS_API_KEY' ) ) {
17
+ $key = __( 'API key provided by your host/ WordPress administrator, no need to enter anything here. In case of problems with the API key, contact your host/ WordPress administrator.', 'autoptimize' );
18
+ }
19
+ ?>
20
+ <ul id="key-panel">
21
+ <li class="itemDetail">
22
+ <h2 class="itemTitle fleft"><?php _e( 'API Key', 'autoptimize' ); ?>: <span style="color:<?php echo $color; ?>;"><?php echo $status_msg; ?></span></h2>
23
+ <button type="button" class="toggle-btn">
24
+ <?php if ( 'valid' != $status ) { ?>
25
+ <span class="toggle-indicator dashicons dashicons-arrow-up"></span>
26
+ <?php } else { ?>
27
+ <span class="toggle-indicator dashicons dashicons-arrow-up dashicons-arrow-down"></span>
28
+ <?php } ?>
29
+ </button>
30
+ <?php if ( 'valid' != $status ) { ?>
31
+ <div class="collapsible">
32
+ <?php } else { ?>
33
+ <div class="collapsible hidden">
34
+ <?php } ?>
35
+ <?php if ( 'valid' != $status ) { ?>
36
+ <div style="clear:both;padding:2px 10px;border-left:solid;border-left-width:5px;border-left-color:<?php echo $color; ?>;background-color:white;">
37
+ <p><?php echo $message; ?></p>
38
+ </div>
39
+ <?php } ?>
40
+ <table id="key" class="form-table">
41
+ <tr>
42
+ <th scope="row">
43
+ <?php _e( 'Your API Key', 'autoptimize' ); ?>
44
+ </th>
45
+ <td>
46
+ <textarea id="autoptimize_ccss_key" name="autoptimize_ccss_key" rows='3' style="width:100%;" placeholder="<?php _e( 'Please enter your criticalcss.com API key here.', 'autoptimize' ); ?>"><?php echo trim( $key ); ?></textarea>
47
+ <p class="notes">
48
+ <?php _e( 'Enter your <a href="https://criticalcss.com/account/api-keys?aff=1" target="_blank">criticalcss.com</a> API key above. The key is revalidated every time a new job is sent to it.<br />To obtain your API key, go to <a href="https://criticalcss.com/account/api-keys?aff=1" target="_blank">criticalcss.com</a> > Account > API Keys.<br />Requests to generate a critical CSS via the API are priced at £5 per domain per month.<br /><strong>Not sure yet? With the <a href="https://criticalcss.com/faq/?aff=1#trial" target="_blank">30 day free trial</a>, you have nothing to lose!</strong>', 'autoptimize' ); ?>
49
+ </p>
50
+ </td>
51
+ </tr>
52
+ </table>
53
+ </div>
54
+ </li>
55
+ </ul>
56
+ <?php
57
+ }
classes/critcss-inc/admin_settings_queue.js.php ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * JS code to manage queue.
4
+ */
5
+
6
+ ?>
7
+ // Hide object text box
8
+ var queueOriginEl = document.getElementById('ao-ccss-queue' );
9
+ if (queueOriginEl) {
10
+ queueOriginEl.style.display = 'none';
11
+
12
+ // Get queue object and call table renderer
13
+ jQuery(document).ready(function() {
14
+ // Instance and parse queue object
15
+ var aoCssQueueRaw = document.getElementById('ao-ccss-queue').value;
16
+ var aoCssQueue = aoCssQueueRaw.indexOf('{"') === 0 ?
17
+ JSON.parse(aoCssQueueRaw) :
18
+ "";
19
+ var aoCssQueueLog = aoCssQueue === "" ?
20
+ "empty" :
21
+ aoCssQueue;
22
+ <?php
23
+ if ( $ao_ccss_debug ) {
24
+ echo "console.log( 'Queue Object:', aoCssQueueLog );\n";
25
+ }
26
+ ?>
27
+
28
+ // hook up "remove all jobs" button to the JS action.
29
+ jQuery("#removeAllJobs").click(function(){removeAllJobs();});
30
+
31
+ // Render queue table
32
+ drawQueueTable(aoCssQueue);
33
+
34
+ // Make queue table sortable if there are any elements
35
+ var queueBodyEl = jQuery('#queue > tr').length;
36
+ if (queueBodyEl > 0) {
37
+ jQuery('#queue-tbl').tablesorter({
38
+ sortList: [[0,0]],
39
+ headers: {6: {sorter: false}}
40
+ });
41
+ }
42
+ });
43
+ }
44
+
45
+ // Render the queue in a table
46
+ function drawQueueTable(queue) {
47
+ jQuery('#queue').empty();
48
+ rowNumber=0;
49
+ jQuery.each(queue, function(path, keys) {
50
+ // Prepare commom job values
51
+ ljid = keys.ljid;
52
+ targetArr = keys.rtarget.split('|' );
53
+ target = targetArr[1];
54
+ type = keys.ptype;
55
+ ctime = EpochToDate(keys.jctime);
56
+ rbtn = false;
57
+ dbtn = false;
58
+ hbtn = false;
59
+
60
+ // Prepare job statuses
61
+ if (keys.jqstat === 'NEW') {
62
+ // Status: NEW (N, sort order 1)
63
+ status = '<span class="hidden">1</span>N';
64
+ statusClass = 'new';
65
+ title = '<?php _e( 'New', 'autoptimize' ); ?> (' + ljid + ')';
66
+ buttons = '<?php _e( 'None', 'autoptimize' ); ?>';
67
+ } else if (keys.jqstat === 'JOB_QUEUED' || keys.jqstat === 'JOB_ONGOING') {
68
+ // Status: PENDING (P, sort order 2)
69
+ status = '<span class="hidden">2</span>P';
70
+ statusClass = 'pending';
71
+ title = '<?php _e( 'PENDING', 'autoptimize' ); ?> (' + ljid + ')';
72
+ buttons = '<?php _e( 'None', 'autoptimize' ); ?>';
73
+ } else if (keys.jqstat === 'JOB_DONE' && keys.jrstat === 'GOOD' && (keys.jvstat === 'WARN' || keys.jvstat === 'BAD')) {
74
+ // Status: REVIEW (R, sort order 5)
75
+ status = '<span class="hidden">5</span>R';
76
+ statusClass = 'review';
77
+ title = "<?php _e( 'REVIEW', 'autoptimize' ); ?> (" + ljid + ")\n<?php _e( 'Info from criticalcss.com:', 'autoptimize' ); ?>\n<?php _e( '- Job ID: ', 'autoptimize' ); ?>" + keys.jid + "\n<?php _e( '- Status: ', 'autoptimize' ); ?>" + keys.jqstat + "\n<?php _e( '- Result: ', 'autoptimize' ); ?>" + keys.jrstat + "\n<?php _e( '- Validation: ', 'autoptimize' ); ?>" + keys.jvstat;
78
+ buttons = '<span class="button-secondary" id="' + ljid + '_remove" title="<?php _e( 'Delete Job', 'autoptimize' ); ?>"><span class="dashicons dashicons-trash"></span></span>';
79
+ dbtn = true;
80
+ } else if (keys.jqstat === 'JOB_DONE') {
81
+ // Status: DONE (D, sort order 6)
82
+ status = '<span class="hidden">6</span>D';
83
+ statusClass = 'done';
84
+ title = '<?php _e( 'DONE', 'autoptimize' ); ?> (' + ljid + ')';
85
+ buttons = '<span class="button-secondary" id="' + ljid + '_remove" title="<?php _e( 'Delete Job', 'autoptimize' ); ?>"><span class="dashicons dashicons-trash"></span></span>';
86
+ dbtn = true;
87
+ } else if (keys.jqstat === 'JOB_FAILED' || keys.jqstat === 'STATUS_JOB_BAD' || keys.jqstat === 'INVALID_JWT_TOKEN' || keys.jqstat === 'NO_CSS' || keys.jqstat === 'NO_RESPONSE') {
88
+ // Status: ERROR (E, sort order 4)
89
+ status = '<span class="hidden">4</span>E';
90
+ statusClass = 'error';
91
+ title = "<?php _e( 'ERROR', 'autoptimize' ); ?> (" + ljid + ")\n<?php _e( 'Info from criticalcss.com:', 'autoptimize' ); ?>\n<?php _e( '- Job ID: ', 'autoptimize' ); ?>" + keys.jid + "\n<?php _e( '- Status: ', 'autoptimize' ); ?>" + keys.jqstat + "\n<?php _e( '- Result: ', 'autoptimize' ); ?>" + keys.jrstat + "\n<?php _e( '- Validation: ', 'autoptimize' ); ?>" + keys.jvstat;
92
+ buttons = '<span class="button-secondary" id="' + ljid + '_retry" title="<?php _e( 'Retry Job', 'autoptimize' ); ?>"><span class="dashicons dashicons-update"></span></span><span class="button-secondary to-right" id="' + ljid + '_remove" title="<?php _e( 'Delete Job', 'autoptimize' ); ?>"><span class="dashicons dashicons-trash"></span></span><span class="button-secondary to-right" id="' + ljid + '_help" title="<?php _e( 'Get Help', 'autoptimize' ); ?>"><span class="dashicons dashicons-sos"></span></span>';
93
+ rbtn = true;
94
+ dbtn = true;
95
+ hbtn = true;
96
+ } else {
97
+ // Status: UNKNOWN (U, sort order 5)
98
+ status = '<span class="hidden">5</span>U';
99
+ statusClass = 'unknown';
100
+ title = "<?php _e( 'UNKNOWN', 'autoptimize' ); ?> (" + ljid + ")\n<?php _e( 'Info from criticalcss.com:', 'autoptimize' ); ?>\n<?php _e( '- Job ID: ', 'autoptimize' ); ?>" + keys.jid + "\n<?php _e( '- Status: ', 'autoptimize' ); ?>" + keys.jqstat + "\n<?php _e( '- Result: ', 'autoptimize' ); ?>" + keys.jrstat + "\n<?php _e( '- Validation: ', 'autoptimize' ); ?>" + keys.jvstat;
101
+ buttons = '<span class="button-secondary" id="' + ljid + '_remove" title="<?php _e( 'Delete Job', 'autoptimize' ); ?>"><span class="dashicons dashicons-trash"></span></span><span class="button-secondary to-right" id="' + ljid + '_help" title="<?php _e( 'Get Help', 'autoptimize' ); ?>"><span class="dashicons dashicons-sos"></span></span>';
102
+ dbtn = true;
103
+ hbtn = true;
104
+ }
105
+
106
+ // Prepare job finish time
107
+ if (keys.jftime === null) {
108
+ ftime = '<?php _e( 'N/A', 'autoptimize' ); ?>';
109
+ } else {
110
+ ftime = EpochToDate(keys.jftime);
111
+ }
112
+
113
+ // Append job entry
114
+ jQuery("#queue").append("<tr id='" + ljid + "' class='job " + statusClass + "'><td class='status'><span class='badge " + statusClass + "' title='<?php _e( 'Job status is ', 'autoptimize' ); ?>" + title + "'>" + status + "</span></td><td>" + target.replace(/(woo_|template_|custom_post_|edd_|bp_|bbp_)/,'') + "</td><td>" + path + "</td><td>" + type.replace(/(woo_|template_|custom_post_|edd_|bp_|bbp_)/,'') + "</td><td>" + ctime + "</td><td>" + ftime + "</td><td class='btn'>" + buttons + "</td></tr>");
115
+
116
+ // Attach button actions
117
+ if (rbtn) {
118
+ jQuery('#' + ljid + '_retry').click(function(){retryJob(queue, this.id, path);});
119
+ }
120
+ if (dbtn) {
121
+ jQuery('#' + ljid + '_remove').click(function(){delJob(queue, this.id, path);});
122
+ }
123
+ if (hbtn) {
124
+ jQuery('#' + ljid + '_help').click(function(){jid=this.id.split('_' );window.open('https://criticalcss.com/faq?aoid=' + jid[0], '_blank' );});
125
+ }
126
+ });
127
+ }
128
+
129
+ // Delete a job from the queue
130
+ function delJob(queue, jid, jpath) {
131
+ jid = jid.split('_' );
132
+ jQuery('#queue-confirm-rm').dialog({
133
+ resizable: false,
134
+ height: 180,
135
+ modal: true,
136
+ buttons: {
137
+ <?php _e( 'Delete', 'autoptimize' ); ?>: function() {
138
+ delete queue[jpath];
139
+ updateQueue(queue);
140
+ jQuery(this).dialog('close' );
141
+ },
142
+ <?php _e( 'Cancel', 'autoptimize' ); ?>: function() {
143
+ jQuery(this).dialog('close' );
144
+ }
145
+ }
146
+ });
147
+ }
148
+
149
+ function removeAllJobs() {
150
+ jQuery( "#queue-confirm-rm-all" ).dialog({
151
+ resizable: false,
152
+ height:235,
153
+ modal: true,
154
+ buttons: {
155
+ "<?php _e( 'Delete all jobs?', 'autoptimize' ); ?>": function() {
156
+ queue=[];
157
+ updateQueue(queue);
158
+ jQuery( this ).dialog( "close" );
159
+ },
160
+ "<?php _e( 'Cancel', 'autoptimize' ); ?>": function() {
161
+ jQuery( this ).dialog( "close" );
162
+ }
163
+ }
164
+ });
165
+ }
166
+
167
+ // Retry jobs with error
168
+ function retryJob(queue, jid, jpath) {
169
+ jid = jid.split('_' );
170
+ jQuery('#queue-confirm-retry').dialog({
171
+ resizable: false,
172
+ height: 180,
173
+ modal: true,
174
+ buttons: {
175
+ <?php _e( 'Retry', 'autoptimize' ); ?>: function() {
176
+ <?php
177
+ if ( $ao_ccss_debug ) {
178
+ echo "console.log( 'SHOULD retry job:', jid[0], jpath );\n";
179
+ }
180
+ ?>
181
+ queue[jpath].jid = null;
182
+ queue[jpath].jqstat = 'NEW';
183
+ queue[jpath].jrstat = null;
184
+ queue[jpath].jvstat = null;
185
+ queue[jpath].jctime = (new Date).getTime() / 1000;
186
+ queue[jpath].jftime = null;
187
+ updateQueue(queue);
188
+ jQuery(this).dialog('close' );
189
+ },
190
+ <?php _e( 'Cancel', 'autoptimize' ); ?>: function() {
191
+ jQuery(this).dialog('close' );
192
+ }
193
+ }
194
+ });
195
+ }
196
+
197
+ // Refresh queue
198
+ function updateQueue(queue) {
199
+ document.getElementById('ao-ccss-queue').value=JSON.stringify(queue);
200
+ drawQueueTable(queue);
201
+ jQuery('#unSavedWarning').show();
202
+ document.getElementById('ao_title_and_button').scrollIntoView();
203
+ <?php
204
+ if ( $ao_ccss_debug ) {
205
+ echo "console.log('Updated Queue Object:', queue);\n";
206
+ }
207
+ ?>
208
+ }
209
+
210
+ // Convert epoch to date for job times
211
+ function EpochToDate(epoch) {
212
+ if (epoch < 10000000000)
213
+ epoch *= 1000;
214
+ var epoch = epoch + (new Date().getTimezoneOffset() * -1); //for timeZone
215
+ var sdate = new Date(epoch);
216
+ var ldate = sdate.toLocaleString();
217
+ return ldate;
218
+ }
classes/critcss-inc/admin_settings_queue.php ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Render the queue panel.
4
+ */
5
+
6
+ /**
7
+ * Function to render the queue panel.
8
+ */
9
+ function ao_ccss_render_queue() {
10
+ // Attach required arrays.
11
+ global $ao_ccss_queue;
12
+
13
+ // Prepare the queue object.
14
+ if ( empty( $ao_ccss_queue ) ) {
15
+ $ao_ccss_queue = '';
16
+ } else {
17
+ $ao_ccss_queue = json_encode( $ao_ccss_queue );
18
+ }
19
+ ?>
20
+
21
+ <ul id="queue-panel">
22
+ <li class="itemDetail">
23
+ <h2 class="itemTitle fleft"><?php _e( 'Job Queue', 'autoptimize' ); ?></h2>
24
+ <button type="button" class="toggle-btn">
25
+ <span class="toggle-indicator dashicons dashicons-arrow-up dashicons-arrow-down"></span>
26
+ </button>
27
+ <?php
28
+ if ( autoptimizeCriticalCSSSettings::ao_ccss_has_autorules() ) {
29
+ $_queue_visibility = 'hidden';
30
+ } else {
31
+ $_queue_visibility = 'visible';
32
+ }
33
+ ?>
34
+ <div class="collapsible <?php echo $_queue_visibility; ?>">
35
+ <!-- BEGIN Queue dialogs -->
36
+ <!-- Retry dialog -->
37
+ <div id="queue-confirm-retry" title="<?php _e( 'Retry Job', 'autoptimize' ); ?>" class="hidden">
38
+ <p><?php _e( 'Are you sure you want to retry this job?', 'autoptimize' ); ?></p>
39
+ </div>
40
+
41
+ <!-- Remove dialog -->
42
+ <div id="queue-confirm-rm" title="<?php _e( 'Delete Job', 'autoptimize' ); ?>" class="hidden">
43
+ <p><?php _e( 'Are you sure you want to delete this job?', 'autoptimize' ); ?></p>
44
+ </div>
45
+
46
+ <!-- Remove all dialog -->
47
+ <div id="queue-confirm-rm-all" title="<?php _e( 'Delete all jobs', 'autoptimize' ); ?>" class="hidden">
48
+ <p><?php _e( 'This will delete all jobs, are you sure?', 'autoptimize' ); ?></p>
49
+ </div>
50
+ <!-- END Queue dialogs -->
51
+
52
+ <!-- BEGIN Queue UI -->
53
+ <div class="howto">
54
+ <div class="title-wrap">
55
+ <h4 class="title"><?php _e( 'How To Use Autoptimize CriticalCSS Power-Up Queue', 'autoptimize' ); ?></h4>
56
+ <p class="subtitle"><?php _e( 'Click the side arrow to toggle instructions', 'autoptimize' ); ?></p>
57
+ </div>
58
+ <button type="button" class="toggle-btn">
59
+ <span class="toggle-indicator dashicons dashicons-arrow-up dashicons-arrow-down"></span>
60
+ </button>
61
+ <div class="howto-wrap hidden">
62
+ <p><?php _e( 'TL;DR:<br /><strong>Queue runs every 10 minutes.</strong> Job statuses are <span class="badge new">N</span> for NEW, <span class="badge pending">P</span> for PENDING, <span class="badge error">E</span> for ERROR and <span class="badge unknown">U</span> for UNKOWN.', 'autoptimize' ); ?></p>
63
+ <ol>
64
+ <li><?php _e( 'The queue operates <strong>automatically, asynchronously and on regular intervals of 10 minutes.</strong> To view updated queue status, refresh this page.', 'autoptimize' ); ?></li>
65
+ <li><?php _e( 'When the conditions to create a job are met (i.e. user not logged in, no matching <span class="badge manual">MANUAL</span> rule or CSS files has changed for an <span class="badge auto">AUTO</span> rule), a <span class="badge new">N</span> job is created in the queue.', 'autoptimize' ); ?></li>
66
+ <li><?php _e( "Autoptimize CriticalCSS Power-Up constantly query the queue for <span class='badge new'>N</span> jobs. When it finds one, gears spins and jobs becomes <span class='badge pending'>P</span> while they are running and <a href='https://criticalcss.com/?aff=1' target='_blank'>criticalcss.com</a> doesn't return a result.", 'autoptimize' ); ?></li>
67
+ <li><?php _e( 'As soon as <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> returns a valid critical CSS file, the job is then finished and removed from the queue.', 'autoptimize' ); ?></li>
68
+ <li><?php _e( 'When things go wrong, a job is marked as <span class="badge error">E</span>. You can retry faulty jobs, delete them or get in touch with <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> for assistance.', 'autoptimize' ); ?></li>
69
+ <li><?php _e( 'Sometimes an unknown condition can happen. In this case, the job status becomes <span class="badge unknown">U</span> and you may want to ask <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> for help or just delete it.', 'autoptimize' ); ?></li>
70
+ <li><?php _e( 'To get more information about jobs statuses, specially the ones with <span class="badge error">E</span> and <span class="badge unknown">U</span> status, hover your mouse in the status badge of that job. This information might be crucial when contacting <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> for assistance.', 'autoptimize' ); ?></li>
71
+ <li><?php _e( '<strong>A word about WordPress cron:</strong> Autoptimize CriticalCSS Power-Up watch the queue by using WordPress Cron (or WP-Cron for short.) It <a href="https://www.smashingmagazine.com/2013/10/schedule-events-using-wordpress-cron/#limitations-of-wordpress-cron-and-solutions-to-fix-em" target="_blank">could be faulty</a> on very light or very heavy loads. If your site receives just a few or thousands visits a day, it might be a good idea to <a href="https://developer.wordpress.org/plugins/cron/hooking-into-the-system-task-scheduler/" target="_blank">turn WP-Cron off and use your system task scheduler</a> to fire it instead.', 'autoptimize' ); ?></li>
72
+ </ol>
73
+ </div>
74
+ </div>
75
+ <table id="queue-tbl" class="queue tablesorter" cellspacing="0">
76
+ <thead>
77
+ <tr><th class="status"><?php _e( 'Status', 'autoptimize' ); ?></th><th><?php _e( 'Target Rule', 'autoptimize' ); ?></th><th><?php _e( 'Page Path', 'autoptimize' ); ?></th><th><?php _e( 'Page Type', 'autoptimize' ); ?></th><th><?php _e( 'Creation Date', 'autoptimize' ); ?></th><th><?php _e( 'Finish Date', 'autoptimize' ); ?></th><th class="btn"><?php _e( 'Actions', 'autoptimize' ); ?></th></tr>
78
+ </thead>
79
+ <tbody id="queue"></tbody>
80
+ </table>
81
+ <input class="hidden" type="text" id="ao-ccss-queue" name="autoptimize_ccss_queue" value='<?php echo( $ao_ccss_queue ); ?>'>
82
+ <div class="submit jobs-btn">
83
+ <div class="alignright">
84
+ <span id="removeAllJobs" class="button-secondary" style="color:red;"><?php _e( 'Remove all jobs', 'autoptimize' ); ?></span>
85
+ </div>
86
+ </div>
87
+ </div>
88
+ <!-- END Queue UI -->
89
+ </li>
90
+ </ul>
91
+ <?php
92
+ }
classes/critcss-inc/admin_settings_rules.js.php ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Outputs JS code for the rules panel.
4
+ */
5
+
6
+ if ( $ao_ccss_debug ) {
7
+ echo "console.log('[WARN] Autoptimize CriticalCSS Power-Up is in DEBUG MODE!');\n";
8
+ echo "console.log('[WARN] Avoid using debug mode on production/live environments unless for ad-hoc troubleshooting purposes and make sure to disable it after!');\n";
9
+ }
10
+ ?>
11
+
12
+ var rulesOriginEl = document.getElementById("critCssOrigin");
13
+ var deferInlineEl = document.getElementById("autoptimize_css_defer_inline");
14
+ var additionalEl = document.getElementById("autoptimize_ccss_additional");
15
+ if (rulesOriginEl)
16
+ rulesOriginEl.style.display = 'none';
17
+ if (deferInlineEl)
18
+ deferInlineEl.style.display = 'none';
19
+ if (additionalEl)
20
+ additionalEl.style.display = 'none';
21
+
22
+ if (rulesOriginEl) {
23
+ jQuery(document).ready(function() {
24
+ critCssArray=JSON.parse(document.getElementById("critCssOrigin").value);
25
+ <?php
26
+ if ( $ao_ccss_debug ) {
27
+ echo "console.log('Rules Object:', critCssArray);\n";
28
+ }
29
+ ?>
30
+ drawTable(critCssArray);
31
+ jQuery("#addCritCssButton").click(function(){addEditRow();});
32
+ jQuery("#editDefaultButton").click(function(){editDefaultCritCss();});
33
+ jQuery("#editAdditionalButton").click(function(){editAdditionalCritCss();});
34
+ jQuery("#removeAllRules").click(function(){removeAllRules();});
35
+ });
36
+ }
37
+
38
+ function drawTable(critCssArray) {
39
+ jQuery("#rules-list").empty();
40
+ jQuery.each(critCssArray,function(k,v) {
41
+ if (k=="paths") {
42
+ kstring="<?php _e( 'Path Based Rules', 'autoptimize' ); ?>";
43
+ } else {
44
+ kstring="<?php _e( 'Conditional Tags, Custom Post Types and Page Templates Rules', 'autoptimize' ); ?>";
45
+ }
46
+ if (!(jQuery.isEmptyObject(v))) {
47
+ jQuery("#rules-list").append("<tr><td colspan='5'><h4>" + kstring + "</h4></td></tr>");
48
+ jQuery("#rules-list").append("<tr class='header "+k+"Rule'><th><?php _e( 'Type', 'autoptimize' ); ?></th><th><?php _e( 'Target', 'autoptimize' ); ?></th><th><?php _e( 'Critical CSS File', 'autoptimize' ); ?></th><th colspan='2'><?php _e( 'Actions', 'autoptimize' ); ?></th></tr>");
49
+ }
50
+ nodeNumber=0;
51
+ jQuery.each(v,function(i,nv){
52
+ nodeNumber++;
53
+ nodeId=k + "_" + nodeNumber;
54
+ hash=nv.hash;
55
+ file=nv.file;
56
+ filest=nv.file;
57
+ if (file == 0) {
58
+ file='<?php _e( 'To be fetched from criticalcss.com in the next queue run...', 'autoptimize' ); ?>';
59
+ }
60
+ if (nv.hash === 0 && filest != 0) {
61
+ type='<?php _e( 'MANUAL', 'autoptimize' ); ?>';
62
+ typeClass = 'manual';
63
+ } else {
64
+ type='<?php _e( 'AUTO', 'autoptimize' ); ?>';
65
+ typeClass = 'auto';
66
+ }
67
+ if (file && typeof file == 'string') {
68
+ rmark=file.split('_');
69
+ if (rmark[2] || rmark[2] == 'R.css') {
70
+ rmark = '<span class="badge review rule">R</span>'
71
+ } else {
72
+ rmark = '';
73
+ }
74
+ }
75
+ jQuery("#rules-list").append("<tr class='rule "+k+"Rule'><td class='type'><span class='badge " + typeClass + "'>" + type + "</span>" + rmark + "</td><td class='target'>" + i.replace(/(woo_|template_|custom_post_|edd_|bp_|bbp_)/,'') + "</td><td class='file'>" + file + "</td><td class='btn edit'><span class=\"button-secondary\" id=\"" + nodeId + "_edit\"><?php _e( 'Edit', 'autoptimize' ); ?></span></td><td class='btn delete'><span class=\"button-secondary\" id=\"" + nodeId + "_remove\"><?php _e( 'Remove', 'autoptimize' ); ?></span></td></tr>");
76
+ jQuery("#" + nodeId + "_edit").click(function(){addEditRow(this.id);});
77
+ jQuery("#" + nodeId + "_remove").click(function(){confirmRemove(this.id);});
78
+ })
79
+ });
80
+ }
81
+
82
+ function confirmRemove(idToRemove) {
83
+ jQuery( "#confirm-rm" ).dialog({
84
+ resizable: false,
85
+ height:235,
86
+ modal: true,
87
+ buttons: {
88
+ "<?php _e( 'Delete', 'autoptimize' ); ?>": function() {
89
+ removeRow(idToRemove);
90
+ updateAfterChange();
91
+ jQuery( this ).dialog( "close" );
92
+ },
93
+ "<?php _e( 'Cancel', 'autoptimize' ); ?>": function() {
94
+ jQuery( this ).dialog( "close" );
95
+ }
96
+ }
97
+ });
98
+ }
99
+
100
+ function removeAllRules() {
101
+ jQuery( "#confirm-rm-all" ).dialog({
102
+ resizable: false,
103
+ height:235,
104
+ modal: true,
105
+ buttons: {
106
+ "<?php _e( 'Delete All', 'autoptimize' ); ?>": function() {
107
+ critCssArray={'paths':[],'types':[]};
108
+ drawTable(critCssArray);
109
+ updateAfterChange();
110
+ removeAllCcssFilesOnServer();
111
+ jQuery( this ).dialog( "close" );
112
+ },
113
+ "<?php _e( 'Cancel', 'autoptimize' ); ?>": function() {
114
+ jQuery( this ).dialog( "close" );
115
+ }
116
+ }
117
+ });
118
+ }
119
+
120
+ function removeRow(idToRemove) {
121
+ splits=idToRemove.split(/_/);
122
+ crit_type=splits[0];
123
+ crit_item=splits[1];
124
+ crit_key=Object.keys(critCssArray[crit_type])[crit_item-1];
125
+ crit_file=critCssArray[crit_type][crit_key].file;
126
+ delete critCssArray[crit_type][crit_key];
127
+
128
+ var data = {
129
+ 'action': 'rm_critcss',
130
+ 'critcss_rm_nonce': '<?php echo wp_create_nonce( 'rm_critcss_nonce' ); ?>',
131
+ 'cachebustingtimestamp': new Date().getTime(),
132
+ 'critcssfile': crit_file
133
+ };
134
+
135
+ jQuery.ajaxSetup({
136
+ async: false
137
+ });
138
+
139
+ jQuery.post(ajaxurl, data, function(response) {
140
+ response_array=JSON.parse(response);
141
+ if (response_array["code"]!=200) {
142
+ // not displaying notice, as the end result is OK; the file isn't there
143
+ // displayNotice(response_array["string"]);
144
+ }
145
+ });
146
+ }
147
+
148
+ function removeAllCcssFilesOnServer() {
149
+ var data = {
150
+ 'action': 'rm_critcss_all',
151
+ 'critcss_rm_all_nonce': '<?php echo wp_create_nonce( 'rm_critcss_all_nonce' ); ?>',
152
+ 'cachebustingtimestamp': new Date().getTime()
153
+ };
154
+
155
+ jQuery.ajaxSetup({
156
+ async: false
157
+ });
158
+
159
+ jQuery.post(ajaxurl, data, function(response) {
160
+ response_array=JSON.parse(response);
161
+ if (response_array["code"]!=200) {
162
+ // not displaying notice, as the end result is OK; the file isn't there
163
+ // displayNotice(response_array["string"]);
164
+ }
165
+ });
166
+ }
167
+
168
+ function addEditRow(idToEdit) {
169
+ resetForm();
170
+ if (idToEdit) {
171
+ dialogTitle="<?php _e( 'Edit Critical CSS Rule', 'autoptimize' ); ?>";
172
+
173
+ splits=idToEdit.split(/_/);
174
+ crit_type=splits[0];
175
+ crit_item=splits[1];
176
+ crit_key=Object.keys(critCssArray[crit_type])[crit_item-1];
177
+ crit_file=critCssArray[crit_type][crit_key].file;
178
+
179
+ jQuery("#critcss_addedit_id").val(idToEdit);
180
+ jQuery("#critcss_addedit_type").val(crit_type);
181
+ jQuery("#critcss_addedit_file").val(crit_file);
182
+ jQuery("#critcss_addedit_css").attr("placeholder", "<?php _e( 'Loading critical CSS...', 'autoptimize' ); ?>");
183
+ jQuery("#critcss_addedit_type").attr("disabled",true);
184
+
185
+ if (crit_type==="paths") {
186
+ jQuery("#critcss_addedit_path").val(crit_key);
187
+ jQuery("#critcss_addedit_path_wrapper").show();
188
+ jQuery("#critcss_addedit_pagetype_wrapper").hide();
189
+ } else {
190
+ jQuery("#critcss_addedit_pagetype").val(crit_key);
191
+ jQuery("#critcss_addedit_pagetype_wrapper").show();
192
+ jQuery("#critcss_addedit_path_wrapper").hide();
193
+ }
194
+
195
+ var data = {
196
+ 'action': 'fetch_critcss',
197
+ 'critcss_fetch_nonce': '<?php echo wp_create_nonce( 'fetch_critcss_nonce' ); ?>',
198
+ 'cachebustingtimestamp': new Date().getTime(),
199
+ 'critcssfile': crit_file
200
+ };
201
+
202
+ jQuery.post(ajaxurl, data, function(response) {
203
+ response_array=JSON.parse(response);
204
+ if (response_array["code"]==200) {
205
+ jQuery("#critcss_addedit_css").val(response_array["string"]);
206
+ } else {
207
+ jQuery("#critcss_addedit_css").attr("placeholder", "").focus();
208
+ }
209
+ });
210
+ } else {
211
+ dialogTitle="<?php _e( 'Add Critical CSS Rule', 'autotimize' ); ?>";
212
+
213
+ // default: paths, hide content type field
214
+ jQuery("#critcss_addedit_type").val("paths");
215
+ jQuery("#critcss_addedit_pagetype_wrapper").hide();
216
+
217
+ // event handler on type to switch display
218
+ jQuery("#critcss_addedit_type").on('change', function (e) {
219
+ if(this.value==="types") {
220
+ jQuery("#critcss_addedit_pagetype_wrapper").show();
221
+ jQuery("#critcss_addedit_path_wrapper").hide();
222
+ jQuery("#critcss_addedit_css").attr("placeholder", "<?php _e( 'For type based rules, paste your specific and minified critical CSS here and hit submit to save. If you want to create a rule to exclude from critical CSS injection, enter \"none\".', 'autoptimize' ); ?>");
223
+ } else {
224
+ jQuery("#critcss_addedit_path_wrapper").show();
225
+ jQuery("#critcss_addedit_pagetype_wrapper").hide();
226
+ jQuery("#critcss_addedit_css").attr("placeholder", "<?php _e( 'For path based rules, paste your specific and minified critical CSS here or leave this empty to fetch it from criticalcss.com and hit submit to save. If you want to create a rule to exclude from critical CSS injection, enter \"none\"', 'autoptimize' ); ?>");
227
+ }
228
+ });
229
+ }
230
+
231
+ jQuery("#addEditCritCss").dialog({
232
+ autoOpen: true,
233
+ height: 500,
234
+ width: 700,
235
+ title: dialogTitle,
236
+ modal: true,
237
+ buttons: {
238
+ "<?php _e( 'Submit', 'autoptimize' ); ?>": function() {
239
+ rpath = jQuery("#critcss_addedit_path").val();
240
+ rtype = jQuery("#critcss_addedit_pagetype option:selected").val();
241
+ rccss = jQuery("#critcss_addedit_css").val();
242
+ console.log('rpath: ' + rpath, 'rtype: ' + rtype, 'rccss: ' + rccss);
243
+ if (rpath === '' && rtype === '') {
244
+ alert('<?php _e( "RULE VALIDATION ERROR!\\n\\nBased on your rule type, you SHOULD set a path or conditional tag.", 'autoptimize' ); ?>');
245
+ } else if (rtype !== '' && rccss == '') {
246
+ alert('<?php _e( "RULE VALIDATION ERROR!\\n\\nType based rules REQUIRES a minified critical CSS.", 'autoptimize' ); ?>');
247
+ } else {
248
+ saveEditCritCss();
249
+ jQuery(this).dialog('close');
250
+ }
251
+ },
252
+ "<?php _e( 'Cancel', 'autoptimize' ); ?>": function() {
253
+ resetForm();
254
+ jQuery(this).dialog("close");
255
+ }
256
+ }
257
+ });
258
+ }
259
+
260
+ function editDefaultCritCss(){
261
+ document.getElementById("dummyDefault").value=document.getElementById("autoptimize_css_defer_inline").value;
262
+ jQuery("#default_critcss_wrapper").dialog({
263
+ autoOpen: true,
264
+ height: 505,
265
+ width: 700,
266
+ title: "<?php _e( 'Default Critical CSS', 'autoptimize' ); ?>",
267
+ modal: true,
268
+ buttons: {
269
+ "<?php _e( 'Submit', 'autoptimize' ); ?>": function() {
270
+ document.getElementById("autoptimize_css_defer_inline").value=document.getElementById("dummyDefault").value;
271
+ jQuery("#unSavedWarning").show();
272
+ jQuery("#default_critcss_wrapper").dialog( "close" );
273
+ },
274
+ "<?php _e( 'Cancel', 'autoptimize' ); ?>": function() {
275
+ jQuery("#default_critcss_wrapper").dialog( "close" );
276
+ }
277
+ }
278
+ });
279
+ }
280
+
281
+ function editAdditionalCritCss(){
282
+ document.getElementById("dummyAdditional").value=document.getElementById("autoptimize_ccss_additional").value;
283
+ jQuery("#additional_critcss_wrapper").dialog({
284
+ autoOpen: true,
285
+ height: 505,
286
+ width: 700,
287
+ title: "<?php _e( 'Additional Critical CSS', 'autoptimize' ); ?>",
288
+ modal: true,
289
+ buttons: {
290
+ "<?php _e( 'Submit', 'autoptimize' ); ?>": function() {
291
+ document.getElementById("autoptimize_ccss_additional").value=document.getElementById("dummyAdditional").value;
292
+ jQuery("#unSavedWarning").show();
293
+ jQuery("#additional_critcss_wrapper").dialog( "close" );
294
+ },
295
+ "<?php _e( 'Cancel', 'autoptimize' ); ?>": function() {
296
+ jQuery("#additional_critcss_wrapper").dialog( "close" );
297
+ }
298
+ }
299
+ });
300
+ }
301
+
302
+ function saveEditCritCss(){
303
+ critcssfile=jQuery("#critcss_addedit_file").val();
304
+ critcsscontents=jQuery("#critcss_addedit_css").val();
305
+ critcsstype=jQuery("#critcss_addedit_type").val();
306
+ critcssid=jQuery("#critcss_addedit_id").val();
307
+
308
+ if (critcssid) {
309
+ // this was an "edit" action, so remove original
310
+ // will also remove the file, but that will get rewritten anyway
311
+ removeRow(critcssid);
312
+ }
313
+ if (critcsstype==="types") {
314
+ critcsstarget=jQuery("#critcss_addedit_pagetype").val();
315
+ } else {
316
+ critcsstarget=jQuery("#critcss_addedit_path").val();
317
+ }
318
+
319
+ if (!critcssfile && !critcsscontents) {
320
+ critcssfile=0;
321
+ } else if (!critcssfile && critcsscontents) {
322
+ critcssfile="ccss_" + md5(critcsscontents+critcsstarget) + ".css";
323
+ }
324
+
325
+ // Compose the rule object
326
+ critCssArray[critcsstype][critcsstarget]={};
327
+ critCssArray[critcsstype][critcsstarget].hash=0;
328
+ critCssArray[critcsstype][critcsstarget].file=critcssfile;
329
+
330
+ <?php
331
+ if ( $ao_ccss_debug ) {
332
+ echo "console.log('[RULE PROPERTIES] Type:', critcsstype, ', Target:', critcsstarget, ', Hash:', 0, ', File:', critcssfile);";
333
+ }
334
+ ?>
335
+
336
+ updateAfterChange();
337
+
338
+ var data = {
339
+ 'action': 'save_critcss',
340
+ 'critcss_save_nonce': '<?php echo wp_create_nonce( 'save_critcss_nonce' ); ?>',
341
+ 'critcssfile': critcssfile,
342
+ 'critcsscontents': critcsscontents
343
+ };
344
+
345
+ jQuery.post(ajaxurl, data, function(response) {
346
+ response_array=JSON.parse(response);
347
+ if (response_array["code"]!=200) {
348
+ displayNotice(response_array["string"]);
349
+ }
350
+ });
351
+ }
352
+
353
+ function updateAfterChange() {
354
+ document.getElementById("critCssOrigin").value=JSON.stringify(critCssArray);
355
+ drawTable(critCssArray);
356
+ jQuery("#unSavedWarning").show();
357
+ document.getElementById('ao_title_and_button').scrollIntoView();
358
+ }
359
+
360
+ function displayNotice(textIn) {
361
+ jQuery('<div class="error notice is-dismissable"><p>'+textIn+'</p></div>').insertBefore("#unSavedWarning");
362
+ }
363
+
364
+ function resetForm() {
365
+ jQuery("#critcss_addedit_css").attr("placeholder", "<?php _e( 'For path based rules, paste your specific and minified critical CSS here or leave this empty to fetch it from criticalcss.com and hit submit to save. If you want to create a rule to exclude from critical CSS injection, enter \"none\"', 'autoptimize' ); ?>");
366
+ jQuery("#critcss_addedit_type").attr("disabled",false);
367
+ jQuery("#critcss_addedit_path_wrapper").show();
368
+ jQuery("#critcss_addedit_id").val("");
369
+ jQuery("#critcss_addedit_path").val("");
370
+ jQuery("#critcss_addedit_file").val("");
371
+ jQuery("#critcss_addedit_pagetype").val("");
372
+ jQuery("#critcss_addedit_css").val("");
373
+ }
classes/critcss-inc/admin_settings_rules.php ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Render the rules panel.
4
+ */
5
+
6
+ /**
7
+ * Main function to render the rules panel.
8
+ */
9
+ function ao_ccss_render_rules() {
10
+ // Attach required arrays.
11
+ global $ao_ccss_rules;
12
+ global $ao_ccss_types;
13
+ ?>
14
+ <ul id="rules-panel">
15
+ <li class="itemDetail">
16
+ <h2 class="itemTitle"><?php _e( 'Rules', 'autoptimize' ); ?></h2>
17
+
18
+ <!-- BEGIN Rule dialogs -->
19
+ <!-- Unsaved dialog -->
20
+ <div id="unSavedWarning" class="hidden updated settings-error notice notice-warning is-dismissible">
21
+ <p><?php _e( "<strong>Rules or Queue changed!</strong> Don't forget to save your changes!", 'autoptimize' ); ?></p>
22
+ </div>
23
+
24
+ <!-- Create/edit rule dialog -->
25
+ <div id="addEditCritCss" class="hidden">
26
+ <table class="form-table rules">
27
+ <tr id="critcss_addedit_type_wrapper">
28
+ <th scope="row">
29
+ <?php _e( 'Rule Type', 'autoptimize' ); ?>
30
+ </th>
31
+ <td>
32
+ <select id="critcss_addedit_type" style="width:100%;">
33
+ <option value="paths"><?php _e( 'Path', 'autoptimize' ); ?></option>
34
+ <option value="types"><?php _e( 'Conditional Tag', 'autoptimize' ); ?></option>
35
+ </select>
36
+ </td>
37
+ </tr>
38
+ <tr id="critcss_addedit_path_wrapper">
39
+ <th scope="row">
40
+ <?php _e( 'String in Path', 'autoptimize' ); ?>
41
+ </th>
42
+ <td>
43
+ <input type="text" id="critcss_addedit_path" placeholder="<?php _e( "Enter a part of the URL that identifies the page(s) you're targetting.", 'autoptimize' ); ?>" style="width:100%;" value="">
44
+ </td>
45
+ </tr>
46
+ <tr id="critcss_addedit_pagetype_wrapper">
47
+ <th scope="row">
48
+ <?php _e( 'Conditional Tag, Custom Post Type or Page Template', 'autoptimize' ); ?>
49
+ </th>
50
+ <td>
51
+ <select id="critcss_addedit_pagetype" style="width:100%;">
52
+ <option value="" disabled selected><?php _e( 'Select from the list below...', 'autoptimize' ); ?></option>
53
+ <optgroup label="<?php _e( 'Standard Conditional Tags', 'autoptimize' ); ?>">
54
+ <?php
55
+ // Render grouped simple conditional tags.
56
+ foreach ( $ao_ccss_types as $ctag ) {
57
+ $optgrp = substr( $ctag, 0, 3 );
58
+ if ( substr( $ctag, 0, 3 ) === 'is_' ) {
59
+ echo '<option value="' . $ctag . '">' . $ctag . '</option>';
60
+ }
61
+ $prevgrp = substr( $ctag, 0, 3 );
62
+ }
63
+
64
+ // Render grouped custom post types, templates and specific conditional tags.
65
+ foreach ( $ao_ccss_types as $type ) {
66
+ $optgrp = substr( $type, 0, 3 );
67
+
68
+ // Option groups labels.
69
+ if ( $optgrp !== $prevgrp && 'is_' !== $optgrp ) {
70
+ ?>
71
+ </optgroup>
72
+ <?php
73
+ if ( substr( $type, 0, 12 ) === 'custom_post_' ) {
74
+ ?>
75
+ <optgroup label="<?php _e( 'Custom Post Types', 'autoptimize' ); ?>">
76
+ <?php
77
+ } elseif ( substr( $type, 0, 9 ) === 'template_' ) {
78
+ ?>
79
+ <optgroup label="<?php _e( 'Page Templates', 'autoptimize' ); ?>">
80
+ <?php
81
+ } elseif ( substr( $type, 0, 4 ) === 'bbp_' ) {
82
+ ?>
83
+ <optgroup label="<?php _e( 'BBPress Conditional Tags', 'autoptimize' ); ?>">
84
+ <?php
85
+ } elseif ( substr( $type, 0, 3 ) === 'bp_' ) {
86
+ ?>
87
+ <optgroup label="<?php _e( 'BuddyPress Conditional Tags', 'autoptimize' ); ?>">
88
+ <?php
89
+ } elseif ( substr( $type, 0, 4 ) === 'edd_' ) {
90
+ ?>
91
+ <optgroup label="<?php _e( 'Easy Digital Downloads Conditional Tags', 'autoptimize' ); ?>">
92
+ <?php
93
+ } elseif ( substr( $type, 0, 4 ) === 'woo_' ) {
94
+ ?>
95
+ <optgroup label="<?php _e( 'WooCommerce Conditional Tags', 'autoptimize' ); ?>">
96
+ <?php
97
+ }
98
+ }
99
+
100
+ // Options.
101
+ if ( 'is_' !== $optgrp ) {
102
+ // Remove prefix from custom post types, templates and some specific conditional tags.
103
+ if ( substr( $type, 0, 12 ) === 'custom_post_' ) {
104
+ $_type = str_replace( 'custom_post_', '', $type );
105
+ } elseif ( substr( $type, 0, 9 ) === 'template_' ) {
106
+ $_type = str_replace( 'template_', '', $type );
107
+ } elseif ( 'bbp_is_bbpress' == $type ) {
108
+ $_type = str_replace( 'bbp_', '', $type );
109
+ } elseif ( 'bp_is_buddypress' == $type ) {
110
+ $_type = str_replace( 'bp_', '', $type );
111
+ } elseif ( substr( $type, 0, 4 ) === 'woo_' ) {
112
+ $_type = str_replace( 'woo_', '', $type );
113
+ } elseif ( substr( $type, 0, 4 ) === 'edd_' ) {
114
+ $_type = str_replace( 'edd_', '', $type );
115
+ } else {
116
+ $_type = $type;
117
+ }
118
+
119
+ echo '<option value="' . $type . '">' . $_type . '</option>';
120
+ $prevgrp = $optgrp;
121
+ }
122
+ }
123
+ ?>
124
+ </optgroup>
125
+ </select>
126
+ </td>
127
+ </tr>
128
+ <tr>
129
+ <th scope="row">
130
+ <?php _e( 'Custom Critical CSS', 'autoptimize' ); ?>
131
+ </th>
132
+ <td>
133
+ <textarea id="critcss_addedit_css" rows="13" cols="10" style="width:100%;" placeholder="<?php _e( 'Paste your specific critical CSS here and hit submit to save.', 'autoptimize' ); ?>"></textarea>
134
+ <input type="hidden" id="critcss_addedit_file">
135
+ <input type="hidden" id="critcss_addedit_id">
136
+ </td>
137
+ </tr>
138
+ </table>
139
+ </div>
140
+
141
+ <!-- Remove dialog -->
142
+ <div id="confirm-rm" title="<?php _e( 'Delete Rule', 'autoptimize' ); ?>" class="hidden">
143
+ <p><?php _e( 'This Critical CSS rule will be deleted immediately and cannot be recovered.<br /><br /><strong>Are you sure?</strong>', 'autoptimize' ); ?></p>
144
+ </div>
145
+
146
+ <!-- Remove All dialog -->
147
+ <div id="confirm-rm-all" title="<?php _e( 'Delete all Rules and Jobs', 'autoptimize' ); ?>" class="hidden">
148
+ <p><?php _e( 'All Critical CSS rules will be deleted immediately and cannot be recovered.<br /><br /><strong>Are you sure?</strong>', 'autoptimize' ); ?></p>
149
+ </div>
150
+
151
+ <!-- Add/edit default critical CSS dialog -->
152
+ <div id="default_critcss_wrapper" class="hidden">
153
+ <textarea id="dummyDefault" rows="19" cols="10" style="width:100%;" placeholder="<?php _e( 'Paste your MINIFIED default critical CSS here and hit submit to save. This is the critical CSS to be used for every page NOT MATCHING any rule.', 'autoptimize' ); ?>"></textarea>
154
+ </div>
155
+
156
+ <!-- Add/edit additional critical CSS dialog -->
157
+ <div id="additional_critcss_wrapper" class="hidden">
158
+ <textarea id="dummyAdditional" rows="19" cols="10" style="width:100%;" placeholder="<?php _e( 'Paste your MINIFIED additional critical CSS here and hit submit to save. This is the CSS to be added AT THE END of every critical CSS provided by a matching rule, or the default one.', 'autoptimize' ); ?>"></textarea>
159
+ </div>
160
+
161
+ <!-- Wrapper for in screen notices -->
162
+ <div id="rules-notices"></div>
163
+ <!-- END Rule add/edit dialogs -->
164
+
165
+ <!-- BEGIN Rules UI -->
166
+ <div class="howto">
167
+ <div class="title-wrap">
168
+ <h4 class="title"><?php _e( 'How To Use Autoptimize CriticalCSS Power-Up Rules', 'autoptimize' ); ?></h4>
169
+ <p class="subtitle"><?php _e( 'Click the side arrow to toggle instructions', 'autoptimize' ); ?></p>
170
+ </div>
171
+ <button type="button" class="toggle-btn">
172
+ <span class="toggle-indicator dashicons dashicons-arrow-up dashicons-arrow-down"></span>
173
+ </button>
174
+ <div class="howto-wrap hidden">
175
+ <p><?php _e( "TL;DR:<br />Critical CSS files from <span class='badge auto'>AUTO</span> <strong>rules are updated automatically</strong> while from <span class='badge manual'>MANUAL</span> <strong>rules are not.</strong>", 'autoptimize' ); ?></p>
176
+ <ol>
177
+ <li><?php _e( 'When a valid <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> API key is in place, Autoptimize CriticalCSS Power-Up starts to operate <strong>automatically</strong>.', 'autoptimize' ); ?></li>
178
+ <li><?php _e( 'Upon a request to any of the frontend pages made by a <strong>not logged in user</strong>, it will <strong>asynchronously</strong> fetch and update the critical CSS from <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> for conditional tags you have on your site (e.g. is_page, is_single, is_archive etc.)', 'autoptimize' ); ?></li>
179
+ <li><?php _e( 'These requests also creates an <span class="badge auto">AUTO</span> rule for you. The critical CSS files from <span class="badge auto">AUTO</span> <strong>rules are updated automatically</strong> when a CSS file in your theme or frontend plugins changes.', 'autoptimize' ); ?></li>
180
+ <li><?php _e( 'If you want to make any fine tunning in the critical CSS file of an <span class="badge auto">AUTO</span> rule, click on "Edit" button of that rule, change what you need, submit and save it. The rule you\'ve just edited becomes a <span class="badge manual">MANUAL</span> rule then.', 'autoptimize' ); ?></li>
181
+ <li><?php _e( 'You can create <span class="badge manual">MANUAL</span> rules for specific page paths (URL). Longer, more specific paths have higher priority over shorter ones, which in turn have higher priority over <span class="badge auto">AUTO</span> rules. Also, critical CSS files from <span class="badge manual">MANUAL</span> <strong>rules are NEVER updated automatically.</strong>', 'autoptimize' ); ?></li>
182
+ <li><?php _e( 'You can also create an <span class="badge auto">AUTO</span> rule for a path by leaving its critical CSS content empty. The critical CSS for that path will be automatically fetched from <a href="https://criticalcss.com/?aff=1" target="_blank">criticalcss.com</a> for you and updated whenever it changes.', 'autoptimize' ); ?></li>
183
+ <li><?php _e( "If you see an <span class='badge auto'>AUTO</span> rule with a <span class='badge review'>R</span> besides it (R is after REVIEW), it means that the fetched critical CSS for that rule is not 100% garanteed to work according to <a href='https://criticalcss.com/?aff=1' target='_blank'>criticalcss.com</a> analysis. It's advised that you edit and review that rule to make any required adjustments.", 'autoptimize' ); ?></li>
184
+ <li><?php _e( 'At any time you can delete an <span class="badge auto">AUTO</span> or <span class="badge manual">MANUAL</span> rule by cliking on "Remove" button of the desired rule and saving your changes.', 'autoptimize' ); ?></li>
185
+ </ol>
186
+ </div>
187
+ </div>
188
+ <textarea id="autoptimize_css_defer_inline" name="autoptimize_css_defer_inline" rows="19" cols="10" style="width:100%;"><?php echo get_option( 'autoptimize_css_defer_inline', '' ); ?></textarea>
189
+ <textarea id="autoptimize_ccss_additional" name="autoptimize_ccss_additional" rows="19" cols="10" style="width:100%;"><?php echo get_option( 'autoptimize_ccss_additional', '' ); ?></textarea>
190
+ <table class="rules-list" cellspacing="0"><tbody id="rules-list"></tbody></table>
191
+ <input class="hidden" type="text" id="critCssOrigin" name="autoptimize_ccss_rules" value='<?php echo ( json_encode( $ao_ccss_rules, JSON_FORCE_OBJECT ) ); ?>'>
192
+ <div class="submit rules-btn">
193
+ <div class="alignleft">
194
+ <span id="addCritCssButton" class="button-secondary"><?php _e( 'Add New Rule', 'autoptimize' ); ?></span>
195
+ <span id="editDefaultButton" class="button-secondary"><?php _e( 'Edit Default Rule CSS', 'autoptimize' ); ?></span>
196
+ <span id="editAdditionalButton" class="button-secondary"><?php _e( 'Add CSS To All Rules', 'autoptimize' ); ?></span>
197
+ </div>
198
+ <div class="alignright">
199
+ <span id="removeAllRules" class="button-secondary" style="color:red;"><?php _e( 'Remove all rules', 'autoptimize' ); ?></span>
200
+ </div>
201
+ </div>
202
+ <!-- END Rules UI -->
203
+ </li>
204
+ </ul>
205
+ <?php
206
+ }
207
+ ?>
classes/critcss-inc/css/admin_styles.css ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* form */
2
+ .itemTitle {
3
+ margin: 0;
4
+ }
5
+ .itemTitle.fleft {
6
+ float: left;
7
+ }
8
+ .toggle-btn {
9
+ float: right;
10
+ position: relative;
11
+ top: -10px;
12
+ width: 36px;
13
+ height: 36px;
14
+ margin: 0;
15
+ padding: 0;
16
+ border: 0;
17
+ background: 0 0;
18
+ cursor: pointer;
19
+ outline: none;
20
+ }
21
+ .toggle-indicator {
22
+ color: #72777c;
23
+ display: inline-block;
24
+ -webkit-font-smoothing: antialiased;
25
+ -moz-osx-font-smoothing: grayscale;
26
+ text-decoration: none!important;
27
+ outline: none;
28
+ }
29
+ .itemDetail {
30
+ background: #fff;
31
+ border: 1px solid #ccc;
32
+ padding: 15px;
33
+ margin: 15px 10px 10px 0;
34
+ min-height: 15px;
35
+ word-break: break-word;
36
+ }
37
+ .collapsible {
38
+ clear: both;
39
+ }
40
+ .howto {
41
+ margin: 10px 0 0;
42
+ padding: 2px 10px;
43
+ min-height: 45px;
44
+ font-style: normal;
45
+ border-left: solid;
46
+ border-left-width: 5px;
47
+ border-left-color: #00a0d2;
48
+ background-color: white;
49
+ }
50
+ .howto .title-wrap {
51
+ float: left;
52
+ margin: 5px 0 15px;
53
+ }
54
+ .howto .title {
55
+ margin: 0;
56
+ }
57
+ .howto .subtitle {
58
+ margin: 0;
59
+ padding: 0;
60
+ font-weight: 100;
61
+ font-style: italic;
62
+ color: #72777c;
63
+ }
64
+ .howto .toggle-btn {
65
+ top: -4px;
66
+ left: 10px;
67
+ }
68
+ .howto-wrap {
69
+ clear: both;
70
+ width: 100%;
71
+ }
72
+ .form-table {
73
+ margin-top: 20px;
74
+ }
75
+ .form-table tr {
76
+ vertical-align: top;
77
+ }
78
+ .form-table p.notes,
79
+ .form-table p code {
80
+ font-size: 12px !important;
81
+ }
82
+ .form-table p.notes {
83
+ color: #666;
84
+ }
85
+ .form-table.rules {
86
+ margin-top: 0;
87
+ }
88
+ .form-table.rules th {
89
+ width: 175px;
90
+ }
91
+ .ui-dialog .form-table.rules th,
92
+ .ui-dialog .form-table.rules td {
93
+ padding: 5px 0px;
94
+ }
95
+ .rules-list {
96
+ width: 100%;
97
+ margin-bottom: 10px;
98
+ }
99
+ .rules-list tr.header th {
100
+ background-color: #f1f1f1;
101
+ }
102
+ .rules-list tbody .rule:nth-child(even) td {
103
+ background-color: #f9f9f9;
104
+ }
105
+ #rules-list,
106
+ #queue {
107
+ margin-bottom: 20px;
108
+ }
109
+ #rules-list h4 {
110
+ margin: 20px 0 10px;
111
+ font-size: 1.2em;
112
+ }
113
+ #rules-list .header th,
114
+ #rules-list .rule td {
115
+ padding: 4px;
116
+ }
117
+ #rules-list .rule td {
118
+ margin: 0;
119
+ border-bottom: 1px solid #ccc;
120
+ }
121
+ #rules-list .type {
122
+ width: 80px;
123
+ }
124
+ #rules-list .btn {
125
+ width: 55px;
126
+ }
127
+ #rules-list .rule td.btn {
128
+ width: 70px;
129
+ padding: 4px 0 4px 2px;
130
+ }
131
+ .badge {
132
+ padding: 0 5px;
133
+ color: #fff;
134
+ background-color: #00a0d2;
135
+ border-radius: 5px;
136
+ font-size: .8em;
137
+ font-weight: bold;
138
+ text-align: center;
139
+ }
140
+ .badge.manual {
141
+ background-color: #46b450;
142
+ }
143
+ #rules-list .btn span {
144
+ width: 67px;
145
+ text-align: center;
146
+ }
147
+ p.rules-btn {
148
+ margin: 20px 0 0;
149
+ padding: 0;
150
+ }
151
+ .queue {
152
+ table-layout: fixed;
153
+ border-collapse: collapse;
154
+ }
155
+ .queue .job td {
156
+ border-bottom: 1px solid #ccc;
157
+ }
158
+ .queue .status,
159
+ .queue .job td.status {
160
+ width: 45px;
161
+ }
162
+ .queue td.status {
163
+ text-align: center;
164
+ }
165
+ .queue .badge {
166
+ border-radius: 3px;
167
+ cursor: default;
168
+ }
169
+ .badge.new {
170
+ background-color: #666;
171
+ }
172
+ .badge.pending {
173
+ background-color: #00a0d2;
174
+ }
175
+ .badge.done {
176
+ background-color: #46b450;
177
+ }
178
+ .badge.review {
179
+ background-color: #ffb900;
180
+ }
181
+ .badge.review.rule {
182
+ margin-left: 2px;
183
+ }
184
+ .badge.error {
185
+ background-color: #dc3232;
186
+ }
187
+ .badge.unknown {
188
+ color: #666;
189
+ background-color: #ccc;
190
+ }
191
+ .queue .btn {
192
+ width: 86px;
193
+ }
194
+ .queue .button-secondary {
195
+ line-height: 17px;
196
+ height: 19px;
197
+ padding: 0 2px;
198
+ font-size: 8pt;
199
+ }
200
+ .queue .button-secondary.to-right {
201
+ margin-left: 2px;
202
+ }
203
+ .queue .button-secondary a {
204
+ color: #555;
205
+ text-decoration: none;
206
+ }
207
+ .queue .button-secondary a:hover {
208
+ color: #23282d;
209
+ }
210
+ .queue .button-secondary .dashicons {
211
+ position: relative;
212
+ top: 1px;
213
+ font-size: 15px;
214
+ }
215
+ p.submit.left {
216
+ float: left;
217
+ }
218
+ #importSettingsForm {
219
+ float: right;
220
+ text-align: left;
221
+ max-width: 100%;
222
+ margin-top: 20px;
223
+ padding-top: 10px;
224
+ position: relative;
225
+ overflow: hidden;
226
+ }
227
+ #settingsfile {
228
+ padding: 0 2px;
229
+ }
230
+ #settingsfile {
231
+ padding: 0 2px;
232
+ }
233
+
234
+ /* debug block */
235
+ #debug {
236
+ clear: both;
237
+ }
238
+ #debug .debug th,
239
+ #debug .debug td {
240
+ padding: 5px 10px;
241
+ font-size: 13px;
242
+ }
243
+ #debug pre {
244
+ margin: 0 0 1em;
245
+ font-size: 12px;
246
+ -moz-tab-size: 4;
247
+ -o-tab-size: 4;
248
+ tab-size: 4;
249
+ white-space: pre-wrap;
250
+ }
251
+ #explain-panel p {
252
+ font-size:120%
253
+ }
classes/critcss-inc/css/ao-tablesorter/asc.gif ADDED
Binary file
classes/critcss-inc/css/ao-tablesorter/bg.gif ADDED
Binary file
classes/critcss-inc/css/ao-tablesorter/desc.gif ADDED
Binary file
classes/critcss-inc/css/ao-tablesorter/style.css ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* tables */
2
+ table.tablesorter {
3
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
4
+ margin: 30px 0 5px;
5
+ font-size: 8pt;
6
+ width: 100%;
7
+ text-align: left;
8
+ }
9
+ table.tablesorter thead tr th,
10
+ table.tablesorter tfoot tr th {
11
+ background-color: #f1f1f1;
12
+ font-size: 8pt;
13
+ padding: 2px;
14
+ }
15
+ table.tablesorter thead tr .header {
16
+ background-image: url(bg.gif);
17
+ background-repeat: no-repeat;
18
+ background-position: center right;
19
+ cursor: pointer;
20
+ }
21
+ table.tablesorter tbody td {
22
+ color: #444;
23
+ padding: 4px;
24
+ background-color: #fff;
25
+ vertical-align: middle;
26
+ }
27
+ table.tablesorter tbody tr.even td,
28
+ table.tablesorter tbody tr:nth-child(even) td {
29
+ background-color: #f9f9f9;
30
+ }
31
+ table.tablesorter thead tr .headerSortUp {
32
+ background-image: url(asc.gif);
33
+ }
34
+ table.tablesorter thead tr .headerSortDown {
35
+ background-image: url(desc.gif);
36
+ }
37
+ table.tablesorter thead tr .headerSortDown,
38
+ table.tablesorter thead tr .headerSortUp {
39
+ background-color: #ccc;
40
+ }
classes/critcss-inc/js/admin_settings.js ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ // Toggle button control for collapsible elements
2
+ jQuery(".toggle-btn").click(function () {
3
+ $header = jQuery(this);
4
+ $content = $header.next();
5
+ $content.slideToggle(250, "swing", function () {
6
+ jQuery("span.toggle-indicator", $header).toggleClass('dashicons-arrow-down');
7
+ });
8
+ });
9
+
10
+ // Attach an event to export buttons
11
+ jQuery("#exportSettings").click(function(){exportSettings();});
classes/critcss-inc/js/jquery.tablesorter.min.js ADDED
@@ -0,0 +1,4 @@
 
 
 
 
1
+
2
+ (function($){$.extend({tablesorter:new
3
+ function(){var parsers=[],widgets=[];this.defaults={cssHeader:"header",cssAsc:"headerSortUp",cssDesc:"headerSortDown",cssChildRow:"expand-child",sortInitialOrder:"asc",sortMultiSortKey:"shiftKey",sortForce:null,sortAppend:null,sortLocaleCompare:true,textExtraction:"simple",parsers:{},widgets:[],widgetZebra:{css:["even","odd"]},headers:{},widthFixed:false,cancelSelection:true,sortList:[],headerList:[],dateFormat:"us",decimal:'/\.|\,/g',onRenderHeader:null,selectorHeaders:'thead th',debug:false};function benchmark(s,d){log(s+","+(new Date().getTime()-d.getTime())+"ms");}this.benchmark=benchmark;function log(s){if(typeof console!="undefined"&&typeof console.debug!="undefined"){console.log(s);}else{alert(s);}}function buildParserCache(table,$headers){if(table.config.debug){var parsersDebug="";}if(table.tBodies.length==0)return;var rows=table.tBodies[0].rows;if(rows[0]){var list=[],cells=rows[0].cells,l=cells.length;for(var i=0;i<l;i++){var p=false;if($.metadata&&($($headers[i]).metadata()&&$($headers[i]).metadata().sorter)){p=getParserById($($headers[i]).metadata().sorter);}else if((table.config.headers[i]&&table.config.headers[i].sorter)){p=getParserById(table.config.headers[i].sorter);}if(!p){p=detectParserForColumn(table,rows,-1,i);}if(table.config.debug){parsersDebug+="column:"+i+" parser:"+p.id+"\n";}list.push(p);}}if(table.config.debug){log(parsersDebug);}return list;};function detectParserForColumn(table,rows,rowIndex,cellIndex){var l=parsers.length,node=false,nodeValue=false,keepLooking=true;while(nodeValue==''&&keepLooking){rowIndex++;if(rows[rowIndex]){node=getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex);nodeValue=trimAndGetNodeText(table.config,node);if(table.config.debug){log('Checking if value was empty on row:'+rowIndex);}}else{keepLooking=false;}}for(var i=1;i<l;i++){if(parsers[i].is(nodeValue,table,node)){return parsers[i];}}return parsers[0];}function getNodeFromRowAndCellIndex(rows,rowIndex,cellIndex){return rows[rowIndex].cells[cellIndex];}function trimAndGetNodeText(config,node){return $.trim(getElementText(config,node));}function getParserById(name){var l=parsers.length;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==name.toLowerCase()){return parsers[i];}}return false;}function buildCache(table){if(table.config.debug){var cacheTime=new Date();}var totalRows=(table.tBodies[0]&&table.tBodies[0].rows.length)||0,totalCells=(table.tBodies[0].rows[0]&&table.tBodies[0].rows[0].cells.length)||0,parsers=table.config.parsers,cache={row:[],normalized:[]};for(var i=0;i<totalRows;++i){var c=$(table.tBodies[0].rows[i]),cols=[];if(c.hasClass(table.config.cssChildRow)){cache.row[cache.row.length-1]=cache.row[cache.row.length-1].add(c);continue;}cache.row.push(c);for(var j=0;j<totalCells;++j){cols.push(parsers[j].format(getElementText(table.config,c[0].cells[j]),table,c[0].cells[j]));}cols.push(cache.normalized.length);cache.normalized.push(cols);cols=null;};if(table.config.debug){benchmark("Building cache for "+totalRows+" rows:",cacheTime);}return cache;};function getElementText(config,node){var text="";if(!node)return"";if(!config.supportsTextContent)config.supportsTextContent=node.textContent||false;if(config.textExtraction=="simple"){if(config.supportsTextContent){text=node.textContent;}else{if(node.childNodes[0]&&node.childNodes[0].hasChildNodes()){text=node.childNodes[0].innerHTML;}else{text=node.innerHTML;}}}else{if(typeof(config.textExtraction)=="function"){text=config.textExtraction(node);}else{text=$(node).text();}}return text;}function appendToTable(table,cache){if(table.config.debug){var appendTime=new Date()}var c=cache,r=c.row,n=c.normalized,totalRows=n.length,checkCell=(n[0].length-1),tableBody=$(table.tBodies[0]),rows=[];for(var i=0;i<totalRows;i++){var pos=n[i][checkCell];rows.push(r[pos]);if(!table.config.appender){var l=r[pos].length;for(var j=0;j<l;j++){tableBody[0].appendChild(r[pos][j]);}}}if(table.config.appender){table.config.appender(table,rows);}rows=null;if(table.config.debug){benchmark("Rebuilt table:",appendTime);}applyWidget(table);setTimeout(function(){$(table).trigger("sortEnd");},0);};function buildHeaders(table){if(table.config.debug){var time=new Date();}var meta=($.metadata)?true:false;var header_index=computeTableHeaderCellIndexes(table);$tableHeaders=$(table.config.selectorHeaders,table).each(function(index){this.column=header_index[this.parentNode.rowIndex+"-"+this.cellIndex];this.order=formatSortingOrder(table.config.sortInitialOrder);this.count=this.order;if(checkHeaderMetadata(this)||checkHeaderOptions(table,index))this.sortDisabled=true;if(checkHeaderOptionsSortingLocked(table,index))this.order=this.lockedOrder=checkHeaderOptionsSortingLocked(table,index);if(!this.sortDisabled){var $th=$(this).addClass(table.config.cssHeader);if(table.config.onRenderHeader)table.config.onRenderHeader.apply($th);}table.config.headerList[index]=this;});if(table.config.debug){benchmark("Built headers:",time);log($tableHeaders);}return $tableHeaders;};function computeTableHeaderCellIndexes(t){var matrix=[];var lookup={};var thead=t.getElementsByTagName('THEAD')[0];var trs=thead.getElementsByTagName('TR');for(var i=0;i<trs.length;i++){var cells=trs[i].cells;for(var j=0;j<cells.length;j++){var c=cells[j];var rowIndex=c.parentNode.rowIndex;var cellId=rowIndex+"-"+c.cellIndex;var rowSpan=c.rowSpan||1;var colSpan=c.colSpan||1
4
+ var firstAvailCol;if(typeof(matrix[rowIndex])=="undefined"){matrix[rowIndex]=[];}for(var k=0;k<matrix[rowIndex].length+1;k++){if(typeof(matrix[rowIndex][k])=="undefined"){firstAvailCol=k;break;}}lookup[cellId]=firstAvailCol;for(var k=rowIndex;k<rowIndex+rowSpan;k++){if(typeof(matrix[k])=="undefined"){matrix[k]=[];}var matrixrow=matrix[k];for(var l=firstAvailCol;l<firstAvailCol+colSpan;l++){matrixrow[l]="x";}}}}return lookup;}function checkCellColSpan(table,rows,row){var arr=[],r=table.tHead.rows,c=r[row].cells;for(var i=0;i<c.length;i++){var cell=c[i];if(cell.colSpan>1){arr=arr.concat(checkCellColSpan(table,headerArr,row++));}else{if(table.tHead.length==1||(cell.rowSpan>1||!r[row+1])){arr.push(cell);}}}return arr;};function checkHeaderMetadata(cell){if(($.metadata)&&($(cell).metadata().sorter===false)){return true;};return false;}function checkHeaderOptions(table,i){if((table.config.headers[i])&&(table.config.headers[i].sorter===false)){return true;};return false;}function checkHeaderOptionsSortingLocked(table,i){if((table.config.headers[i])&&(table.config.headers[i].lockedOrder))return table.config.headers[i].lockedOrder;return false;}function applyWidget(table){var c=table.config.widgets;var l=c.length;for(var i=0;i<l;i++){getWidgetById(c[i]).format(table);}}function getWidgetById(name){var l=widgets.length;for(var i=0;i<l;i++){if(widgets[i].id.toLowerCase()==name.toLowerCase()){return widgets[i];}}};function formatSortingOrder(v){if(typeof(v)!="Number"){return(v.toLowerCase()=="desc")?1:0;}else{return(v==1)?1:0;}}function isValueInArray(v,a){var l=a.length;for(var i=0;i<l;i++){if(a[i][0]==v){return true;}}return false;}function setHeadersCss(table,$headers,list,css){$headers.removeClass(css[0]).removeClass(css[1]);var h=[];$headers.each(function(offset){if(!this.sortDisabled){h[this.column]=$(this);}});var l=list.length;for(var i=0;i<l;i++){h[list[i][0]].addClass(css[list[i][1]]);}}function fixColumnWidth(table,$headers){var c=table.config;if(c.widthFixed){var colgroup=$('<colgroup>');$("tr:first td",table.tBodies[0]).each(function(){colgroup.append($('<col>').css('width',$(this).width()));});$(table).prepend(colgroup);};}function updateHeaderSortCount(table,sortList){var c=table.config,l=sortList.length;for(var i=0;i<l;i++){var s=sortList[i],o=c.headerList[s[0]];o.count=s[1];o.count++;}}function multisort(table,sortList,cache){if(table.config.debug){var sortTime=new Date();}var dynamicExp="var sortWrapper = function(a,b) {",l=sortList.length;for(var i=0;i<l;i++){var c=sortList[i][0];var order=sortList[i][1];var s=(table.config.parsers[c].type=="text")?((order==0)?makeSortFunction("text","asc",c):makeSortFunction("text","desc",c)):((order==0)?makeSortFunction("numeric","asc",c):makeSortFunction("numeric","desc",c));var e="e"+i;dynamicExp+="var "+e+" = "+s;dynamicExp+="if("+e+") { return "+e+"; } ";dynamicExp+="else { ";}var orgOrderCol=cache.normalized[0].length-1;dynamicExp+="return a["+orgOrderCol+"]-b["+orgOrderCol+"];";for(var i=0;i<l;i++){dynamicExp+="}; ";}dynamicExp+="return 0; ";dynamicExp+="}; ";if(table.config.debug){benchmark("Evaling expression:"+dynamicExp,new Date());}eval(dynamicExp);cache.normalized.sort(sortWrapper);if(table.config.debug){benchmark("Sorting on "+sortList.toString()+" and dir "+order+" time:",sortTime);}return cache;};function makeSortFunction(type,direction,index){var a="a["+index+"]",b="b["+index+"]";if(type=='text'&&direction=='asc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+a+" < "+b+") ? -1 : 1 )));";}else if(type=='text'&&direction=='desc'){return"("+a+" == "+b+" ? 0 : ("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : ("+b+" < "+a+") ? -1 : 1 )));";}else if(type=='numeric'&&direction=='asc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+a+" - "+b+"));";}else if(type=='numeric'&&direction=='desc'){return"("+a+" === null && "+b+" === null) ? 0 :("+a+" === null ? Number.POSITIVE_INFINITY : ("+b+" === null ? Number.NEGATIVE_INFINITY : "+b+" - "+a+"));";}};function makeSortText(i){return"((a["+i+"] < b["+i+"]) ? -1 : ((a["+i+"] > b["+i+"]) ? 1 : 0));";};function makeSortTextDesc(i){return"((b["+i+"] < a["+i+"]) ? -1 : ((b["+i+"] > a["+i+"]) ? 1 : 0));";};function makeSortNumeric(i){return"a["+i+"]-b["+i+"];";};function makeSortNumericDesc(i){return"b["+i+"]-a["+i+"];";};function sortText(a,b){if(table.config.sortLocaleCompare)return a.localeCompare(b);return((a<b)?-1:((a>b)?1:0));};function sortTextDesc(a,b){if(table.config.sortLocaleCompare)return b.localeCompare(a);return((b<a)?-1:((b>a)?1:0));};function sortNumeric(a,b){return a-b;};function sortNumericDesc(a,b){return b-a;};function getCachedSortType(parsers,i){return parsers[i].type;};this.construct=function(settings){return this.each(function(){if(!this.tHead||!this.tBodies)return;var $this,$document,$headers,cache,config,shiftDown=0,sortOrder;this.config={};config=$.extend(this.config,$.tablesorter.defaults,settings);$this=$(this);$.data(this,"tablesorter",config);$headers=buildHeaders(this);this.config.parsers=buildParserCache(this,$headers);cache=buildCache(this);var sortCSS=[config.cssDesc,config.cssAsc];fixColumnWidth(this);$headers.click(function(e){var totalRows=($this[0].tBodies[0]&&$this[0].tBodies[0].rows.length)||0;if(!this.sortDisabled&&totalRows>0){$this.trigger("sortStart");var $cell=$(this);var i=this.column;this.order=this.count++%2;if(this.lockedOrder)this.order=this.lockedOrder;if(!e[config.sortMultiSortKey]){config.sortList=[];if(config.sortForce!=null){var a=config.sortForce;for(var j=0;j<a.length;j++){if(a[j][0]!=i){config.sortList.push(a[j]);}}}config.sortList.push([i,this.order]);}else{if(isValueInArray(i,config.sortList)){for(var j=0;j<config.sortList.length;j++){var s=config.sortList[j],o=config.headerList[s[0]];if(s[0]==i){o.count=s[1];o.count++;s[1]=o.count%2;}}}else{config.sortList.push([i,this.order]);}};setTimeout(function(){setHeadersCss($this[0],$headers,config.sortList,sortCSS);appendToTable($this[0],multisort($this[0],config.sortList,cache));},1);return false;}}).mousedown(function(){if(config.cancelSelection){this.onselectstart=function(){return false};return false;}});$this.bind("update",function(){var me=this;setTimeout(function(){me.config.parsers=buildParserCache(me,$headers);cache=buildCache(me);},1);}).bind("updateCell",function(e,cell){var config=this.config;var pos=[(cell.parentNode.rowIndex-1),cell.cellIndex];cache.normalized[pos[0]][pos[1]]=config.parsers[pos[1]].format(getElementText(config,cell),cell);}).bind("sorton",function(e,list){$(this).trigger("sortStart");config.sortList=list;var sortList=config.sortList;updateHeaderSortCount(this,sortList);setHeadersCss(this,$headers,sortList,sortCSS);appendToTable(this,multisort(this,sortList,cache));}).bind("appendCache",function(){appendToTable(this,cache);}).bind("applyWidgetId",function(e,id){getWidgetById(id).format(this);}).bind("applyWidgets",function(){applyWidget(this);});if($.metadata&&($(this).metadata()&&$(this).metadata().sortlist)){config.sortList=$(this).metadata().sortlist;}if(config.sortList.length>0){$this.trigger("sorton",[config.sortList]);}applyWidget(this);});};this.addParser=function(parser){var l=parsers.length,a=true;for(var i=0;i<l;i++){if(parsers[i].id.toLowerCase()==parser.id.toLowerCase()){a=false;}}if(a){parsers.push(parser);};};this.addWidget=function(widget){widgets.push(widget);};this.formatFloat=function(s){var i=parseFloat(s);return(isNaN(i))?0:i;};this.formatInt=function(s){var i=parseInt(s);return(isNaN(i))?0:i;};this.isDigit=function(s,config){return/^[-+]?\d*$/.test($.trim(s.replace(/[,.']/g,'')));};this.clearTableBody=function(table){if($.browser.msie){function empty(){while(this.firstChild)this.removeChild(this.firstChild);}empty.apply(table.tBodies[0]);}else{table.tBodies[0].innerHTML="";}};}});$.fn.extend({tablesorter:$.tablesorter.construct});var ts=$.tablesorter;ts.addParser({id:"text",is:function(s){return true;},format:function(s){return $.trim(s.toLocaleLowerCase());},type:"text"});ts.addParser({id:"digit",is:function(s,table){var c=table.config;return $.tablesorter.isDigit(s,c);},format:function(s){return $.tablesorter.formatFloat(s);},type:"numeric"});ts.addParser({id:"currency",is:function(s){return/^[£$€?.]/.test(s);},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/[£$€]/g),""));},type:"numeric"});ts.addParser({id:"ipAddress",is:function(s){return/^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);},format:function(s){var a=s.split("."),r="",l=a.length;for(var i=0;i<l;i++){var item=a[i];if(item.length==2){r+="0"+item;}else{r+=item;}}return $.tablesorter.formatFloat(r);},type:"numeric"});ts.addParser({id:"url",is:function(s){return/^(https?|ftp|file):\/\/$/.test(s);},format:function(s){return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//),''));},type:"text"});ts.addParser({id:"isoDate",is:function(s){return/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);},format:function(s){return $.tablesorter.formatFloat((s!="")?new Date(s.replace(new RegExp(/-/g),"/")).getTime():"0");},type:"numeric"});ts.addParser({id:"percent",is:function(s){return/\%$/.test($.trim(s));},format:function(s){return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g),""));},type:"numeric"});ts.addParser({id:"usLongDate",is:function(s){return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));},format:function(s){return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"shortDate",is:function(s){return/\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);},format:function(s,table){var c=table.config;s=s.replace(/\-/g,"/");if(c.dateFormat=="us"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$1/$2");}else if (c.dateFormat == "pt") {s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$2/$1");} else if(c.dateFormat=="uk"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/,"$3/$2/$1");}else if(c.dateFormat=="dd/mm/yy"||c.dateFormat=="dd-mm-yy"){s=s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/,"$1/$2/$3");}return $.tablesorter.formatFloat(new Date(s).getTime());},type:"numeric"});ts.addParser({id:"time",is:function(s){return/^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);},format:function(s){return $.tablesorter.formatFloat(new Date("2000/01/01 "+s).getTime());},type:"numeric"});ts.addParser({id:"metadata",is:function(s){return false;},format:function(s,table,cell){var c=table.config,p=(!c.parserMetadataName)?'sortValue':c.parserMetadataName;return $(cell).metadata()[p];},type:"numeric"});ts.addWidget({id:"zebra",format:function(table){if(table.config.debug){var time=new Date();}var $tr,row=-1,odd;$("tr:visible",table.tBodies[0]).each(function(i){$tr=$(this);if(!$tr.hasClass(table.config.cssChildRow))row++;odd=(row%2==0);$tr.removeClass(table.config.widgetZebra.css[odd?0:1]).addClass(table.config.widgetZebra.css[odd?1:0])});if(table.config.debug){$.tablesorter.benchmark("Applying Zebra widget",time);}}});})(jQuery);
classes/critcss-inc/js/md5.min.js ADDED
@@ -0,0 +1,2 @@
 
 
1
+ !function(n){"use strict";function t(n,t){var r=(65535&n)+(65535&t);return(n>>16)+(t>>16)+(r>>16)<<16|65535&r}function r(n,t){return n<<t|n>>>32-t}function e(n,e,o,u,c,f){return t(r(t(t(e,n),t(u,f)),c),o)}function o(n,t,r,o,u,c,f){return e(t&r|~t&o,n,t,u,c,f)}function u(n,t,r,o,u,c,f){return e(t&o|r&~o,n,t,u,c,f)}function c(n,t,r,o,u,c,f){return e(t^r^o,n,t,u,c,f)}function f(n,t,r,o,u,c,f){return e(r^(t|~o),n,t,u,c,f)}function i(n,r){n[r>>5]|=128<<r%32,n[14+(r+64>>>9<<4)]=r;var e,i,a,d,h,l=1732584193,g=-271733879,v=-1732584194,m=271733878;for(e=0;e<n.length;e+=16)i=l,a=g,d=v,h=m,g=f(g=f(g=f(g=f(g=c(g=c(g=c(g=c(g=u(g=u(g=u(g=u(g=o(g=o(g=o(g=o(g,v=o(v,m=o(m,l=o(l,g,v,m,n[e],7,-680876936),g,v,n[e+1],12,-389564586),l,g,n[e+2],17,606105819),m,l,n[e+3],22,-1044525330),v=o(v,m=o(m,l=o(l,g,v,m,n[e+4],7,-176418897),g,v,n[e+5],12,1200080426),l,g,n[e+6],17,-1473231341),m,l,n[e+7],22,-45705983),v=o(v,m=o(m,l=o(l,g,v,m,n[e+8],7,1770035416),g,v,n[e+9],12,-1958414417),l,g,n[e+10],17,-42063),m,l,n[e+11],22,-1990404162),v=o(v,m=o(m,l=o(l,g,v,m,n[e+12],7,1804603682),g,v,n[e+13],12,-40341101),l,g,n[e+14],17,-1502002290),m,l,n[e+15],22,1236535329),v=u(v,m=u(m,l=u(l,g,v,m,n[e+1],5,-165796510),g,v,n[e+6],9,-1069501632),l,g,n[e+11],14,643717713),m,l,n[e],20,-373897302),v=u(v,m=u(m,l=u(l,g,v,m,n[e+5],5,-701558691),g,v,n[e+10],9,38016083),l,g,n[e+15],14,-660478335),m,l,n[e+4],20,-405537848),v=u(v,m=u(m,l=u(l,g,v,m,n[e+9],5,568446438),g,v,n[e+14],9,-1019803690),l,g,n[e+3],14,-187363961),m,l,n[e+8],20,1163531501),v=u(v,m=u(m,l=u(l,g,v,m,n[e+13],5,-1444681467),g,v,n[e+2],9,-51403784),l,g,n[e+7],14,1735328473),m,l,n[e+12],20,-1926607734),v=c(v,m=c(m,l=c(l,g,v,m,n[e+5],4,-378558),g,v,n[e+8],11,-2022574463),l,g,n[e+11],16,1839030562),m,l,n[e+14],23,-35309556),v=c(v,m=c(m,l=c(l,g,v,m,n[e+1],4,-1530992060),g,v,n[e+4],11,1272893353),l,g,n[e+7],16,-155497632),m,l,n[e+10],23,-1094730640),v=c(v,m=c(m,l=c(l,g,v,m,n[e+13],4,681279174),g,v,n[e],11,-358537222),l,g,n[e+3],16,-722521979),m,l,n[e+6],23,76029189),v=c(v,m=c(m,l=c(l,g,v,m,n[e+9],4,-640364487),g,v,n[e+12],11,-421815835),l,g,n[e+15],16,530742520),m,l,n[e+2],23,-995338651),v=f(v,m=f(m,l=f(l,g,v,m,n[e],6,-198630844),g,v,n[e+7],10,1126891415),l,g,n[e+14],15,-1416354905),m,l,n[e+5],21,-57434055),v=f(v,m=f(m,l=f(l,g,v,m,n[e+12],6,1700485571),g,v,n[e+3],10,-1894986606),l,g,n[e+10],15,-1051523),m,l,n[e+1],21,-2054922799),v=f(v,m=f(m,l=f(l,g,v,m,n[e+8],6,1873313359),g,v,n[e+15],10,-30611744),l,g,n[e+6],15,-1560198380),m,l,n[e+13],21,1309151649),v=f(v,m=f(m,l=f(l,g,v,m,n[e+4],6,-145523070),g,v,n[e+11],10,-1120210379),l,g,n[e+2],15,718787259),m,l,n[e+9],21,-343485551),l=t(l,i),g=t(g,a),v=t(v,d),m=t(m,h);return[l,g,v,m]}function a(n){var t,r="",e=32*n.length;for(t=0;t<e;t+=8)r+=String.fromCharCode(n[t>>5]>>>t%32&255);return r}function d(n){var t,r=[];for(r[(n.length>>2)-1]=void 0,t=0;t<r.length;t+=1)r[t]=0;var e=8*n.length;for(t=0;t<e;t+=8)r[t>>5]|=(255&n.charCodeAt(t/8))<<t%32;return r}function h(n){return a(i(d(n),8*n.length))}function l(n,t){var r,e,o=d(n),u=[],c=[];for(u[15]=c[15]=void 0,o.length>16&&(o=i(o,8*n.length)),r=0;r<16;r+=1)u[r]=909522486^o[r],c[r]=1549556828^o[r];return e=i(u.concat(d(t)),512+8*t.length),a(i(c.concat(e),640))}function g(n){var t,r,e="";for(r=0;r<n.length;r+=1)t=n.charCodeAt(r),e+="0123456789abcdef".charAt(t>>>4&15)+"0123456789abcdef".charAt(15&t);return e}function v(n){return unescape(encodeURIComponent(n))}function m(n){return h(v(n))}function p(n){return g(m(n))}function s(n,t){return l(v(n),v(t))}function C(n,t){return g(s(n,t))}function A(n,t,r){return t?r?s(t,n):C(t,n):r?m(n):p(n)}"function"==typeof define&&define.amd?define(function(){return A}):"object"==typeof module&&module.exports?module.exports=A:n.md5=A}(this);
2
+ //# sourceMappingURL=md5.min.js.map
classes/external/js/lazysizes.min.js CHANGED
@@ -1,3 +1,3 @@
1
- /*! lazysizes + ls unveilhooks - v5.2.0 */
2
  !function(a,b){var c=b(a,a.document,Date);a.lazySizes=c,"object"==typeof module&&module.exports&&(module.exports=c)}("undefined"!=typeof window?window:{},function(a,b,c){"use strict";var d,e;if(function(){var b,c={lazyClass:"lazyload",loadedClass:"lazyloaded",loadingClass:"lazyloading",preloadClass:"lazypreload",errorClass:"lazyerror",autosizesClass:"lazyautosizes",srcAttr:"data-src",srcsetAttr:"data-srcset",sizesAttr:"data-sizes",minSize:40,customMedia:{},init:!0,expFactor:1.5,hFac:.8,loadMode:2,loadHidden:!0,ricTimeout:0,throttleDelay:125};e=a.lazySizesConfig||a.lazysizesConfig||{};for(b in c)b in e||(e[b]=c[b])}(),!b||!b.getElementsByClassName)return{init:function(){},cfg:e,noSupport:!0};var f=b.documentElement,g=a.HTMLPictureElement,h="addEventListener",i="getAttribute",j=a[h].bind(a),k=a.setTimeout,l=a.requestAnimationFrame||k,m=a.requestIdleCallback,n=/^picture$/i,o=["load","error","lazyincluded","_lazyloaded"],p={},q=Array.prototype.forEach,r=function(a,b){return p[b]||(p[b]=new RegExp("(\\s|^)"+b+"(\\s|$)")),p[b].test(a[i]("class")||"")&&p[b]},s=function(a,b){r(a,b)||a.setAttribute("class",(a[i]("class")||"").trim()+" "+b)},t=function(a,b){var c;(c=r(a,b))&&a.setAttribute("class",(a[i]("class")||"").replace(c," "))},u=function(a,b,c){var d=c?h:"removeEventListener";c&&u(a,b),o.forEach(function(c){a[d](c,b)})},v=function(a,c,e,f,g){var h=b.createEvent("Event");return e||(e={}),e.instance=d,h.initEvent(c,!f,!g),h.detail=e,a.dispatchEvent(h),h},w=function(b,c){var d;!g&&(d=a.picturefill||e.pf)?(c&&c.src&&!b[i]("srcset")&&b.setAttribute("srcset",c.src),d({reevaluate:!0,elements:[b]})):c&&c.src&&(b.src=c.src)},x=function(a,b){return(getComputedStyle(a,null)||{})[b]},y=function(a,b,c){for(c=c||a.offsetWidth;c<e.minSize&&b&&!a._lazysizesWidth;)c=b.offsetWidth,b=b.parentNode;return c},z=function(){var a,c,d=[],e=[],f=d,g=function(){var b=f;for(f=d.length?e:d,a=!0,c=!1;b.length;)b.shift()();a=!1},h=function(d,e){a&&!e?d.apply(this,arguments):(f.push(d),c||(c=!0,(b.hidden?k:l)(g)))};return h._lsFlush=g,h}(),A=function(a,b){return b?function(){z(a)}:function(){var b=this,c=arguments;z(function(){a.apply(b,c)})}},B=function(a){var b,d=0,f=e.throttleDelay,g=e.ricTimeout,h=function(){b=!1,d=c.now(),a()},i=m&&g>49?function(){m(h,{timeout:g}),g!==e.ricTimeout&&(g=e.ricTimeout)}:A(function(){k(h)},!0);return function(a){var e;(a=!0===a)&&(g=33),b||(b=!0,e=f-(c.now()-d),e<0&&(e=0),a||e<9?i():k(i,e))}},C=function(a){var b,d,e=99,f=function(){b=null,a()},g=function(){var a=c.now()-d;a<e?k(g,e-a):(m||f)(f)};return function(){d=c.now(),b||(b=k(g,e))}},D=function(){var g,m,o,p,y,D,F,G,H,I,J,K,L=/^img$/i,M=/^iframe$/i,N="onscroll"in a&&!/(gle|ing)bot/.test(navigator.userAgent),O=0,P=0,Q=0,R=-1,S=function(a){Q--,(!a||Q<0||!a.target)&&(Q=0)},T=function(a){return null==K&&(K="hidden"==x(b.body,"visibility")),K||!("hidden"==x(a.parentNode,"visibility")&&"hidden"==x(a,"visibility"))},U=function(a,c){var d,e=a,g=T(a);for(G-=c,J+=c,H-=c,I+=c;g&&(e=e.offsetParent)&&e!=b.body&&e!=f;)(g=(x(e,"opacity")||1)>0)&&"visible"!=x(e,"overflow")&&(d=e.getBoundingClientRect(),g=I>d.left&&H<d.right&&J>d.top-1&&G<d.bottom+1);return g},V=function(){var a,c,h,j,k,l,n,o,q,r,s,t,u=d.elements;if((p=e.loadMode)&&Q<8&&(a=u.length)){for(c=0,R++;c<a;c++)if(u[c]&&!u[c]._lazyRace)if(!N||d.prematureUnveil&&d.prematureUnveil(u[c]))ba(u[c]);else if((o=u[c][i]("data-expand"))&&(l=1*o)||(l=P),r||(r=!e.expand||e.expand<1?f.clientHeight>500&&f.clientWidth>500?500:370:e.expand,d._defEx=r,s=r*e.expFactor,t=e.hFac,K=null,P<s&&Q<1&&R>2&&p>2&&!b.hidden?(P=s,R=0):P=p>1&&R>1&&Q<6?r:O),q!==l&&(D=innerWidth+l*t,F=innerHeight+l,n=-1*l,q=l),h=u[c].getBoundingClientRect(),(J=h.bottom)>=n&&(G=h.top)<=F&&(I=h.right)>=n*t&&(H=h.left)<=D&&(J||I||H||G)&&(e.loadHidden||T(u[c]))&&(m&&Q<3&&!o&&(p<3||R<4)||U(u[c],l))){if(ba(u[c]),k=!0,Q>9)break}else!k&&m&&!j&&Q<4&&R<4&&p>2&&(g[0]||e.preloadAfterLoad)&&(g[0]||!o&&(J||I||H||G||"auto"!=u[c][i](e.sizesAttr)))&&(j=g[0]||u[c]);j&&!k&&ba(j)}},W=B(V),X=function(a){var b=a.target;if(b._lazyCache)return void delete b._lazyCache;S(a),s(b,e.loadedClass),t(b,e.loadingClass),u(b,Z),v(b,"lazyloaded")},Y=A(X),Z=function(a){Y({target:a.target})},$=function(a,b){try{a.contentWindow.location.replace(b)}catch(c){a.src=b}},_=function(a){var b,c=a[i](e.srcsetAttr);(b=e.customMedia[a[i]("data-media")||a[i]("media")])&&a.setAttribute("media",b),c&&a.setAttribute("srcset",c)},aa=A(function(a,b,c,d,f){var g,h,j,l,m,p;(m=v(a,"lazybeforeunveil",b)).defaultPrevented||(d&&(c?s(a,e.autosizesClass):a.setAttribute("sizes",d)),h=a[i](e.srcsetAttr),g=a[i](e.srcAttr),f&&(j=a.parentNode,l=j&&n.test(j.nodeName||"")),p=b.firesLoad||"src"in a&&(h||g||l),m={target:a},s(a,e.loadingClass),p&&(clearTimeout(o),o=k(S,2500),u(a,Z,!0)),l&&q.call(j.getElementsByTagName("source"),_),h?a.setAttribute("srcset",h):g&&!l&&(M.test(a.nodeName)?$(a,g):a.src=g),f&&(h||l)&&w(a,{src:g})),a._lazyRace&&delete a._lazyRace,t(a,e.lazyClass),z(function(){var b=a.complete&&a.naturalWidth>1;p&&!b||(b&&s(a,"ls-is-cached"),X(m),a._lazyCache=!0,k(function(){"_lazyCache"in a&&delete a._lazyCache},9)),"lazy"==a.loading&&Q--},!0)}),ba=function(a){if(!a._lazyRace){var b,c=L.test(a.nodeName),d=c&&(a[i](e.sizesAttr)||a[i]("sizes")),f="auto"==d;(!f&&m||!c||!a[i]("src")&&!a.srcset||a.complete||r(a,e.errorClass)||!r(a,e.lazyClass))&&(b=v(a,"lazyunveilread").detail,f&&E.updateElem(a,!0,a.offsetWidth),a._lazyRace=!0,Q++,aa(a,b,f,d,c))}},ca=C(function(){e.loadMode=3,W()}),da=function(){3==e.loadMode&&(e.loadMode=2),ca()},ea=function(){if(!m){if(c.now()-y<999)return void k(ea,999);m=!0,e.loadMode=3,W(),j("scroll",da,!0)}};return{_:function(){y=c.now(),d.elements=b.getElementsByClassName(e.lazyClass),g=b.getElementsByClassName(e.lazyClass+" "+e.preloadClass),j("scroll",W,!0),j("resize",W,!0),j("pageshow",function(a){if(a.persisted){var c=b.querySelectorAll("."+e.loadingClass);c.length&&c.forEach&&l(function(){c.forEach(function(a){a.complete&&ba(a)})})}}),a.MutationObserver?new MutationObserver(W).observe(f,{childList:!0,subtree:!0,attributes:!0}):(f[h]("DOMNodeInserted",W,!0),f[h]("DOMAttrModified",W,!0),setInterval(W,999)),j("hashchange",W,!0),["focus","mouseover","click","load","transitionend","animationend"].forEach(function(a){b[h](a,W,!0)}),/d$|^c/.test(b.readyState)?ea():(j("load",ea),b[h]("DOMContentLoaded",W),k(ea,2e4)),d.elements.length?(V(),z._lsFlush()):W()},checkElems:W,unveil:ba,_aLSL:da}}(),E=function(){var a,c=A(function(a,b,c,d){var e,f,g;if(a._lazysizesWidth=d,d+="px",a.setAttribute("sizes",d),n.test(b.nodeName||""))for(e=b.getElementsByTagName("source"),f=0,g=e.length;f<g;f++)e[f].setAttribute("sizes",d);c.detail.dataAttr||w(a,c.detail)}),d=function(a,b,d){var e,f=a.parentNode;f&&(d=y(a,f,d),e=v(a,"lazybeforesizes",{width:d,dataAttr:!!b}),e.defaultPrevented||(d=e.detail.width)&&d!==a._lazysizesWidth&&c(a,f,e,d))},f=function(){var b,c=a.length;if(c)for(b=0;b<c;b++)d(a[b])},g=C(f);return{_:function(){a=b.getElementsByClassName(e.autosizesClass),j("resize",g)},checkElems:g,updateElem:d}}(),F=function(){!F.i&&b.getElementsByClassName&&(F.i=!0,E._(),D._())};return k(function(){e.init&&F()}),d={cfg:e,autoSizer:E,loader:D,init:F,uP:w,aC:s,rC:t,hC:r,fire:v,gW:y,rAF:z}});
3
- !function(a,b){var c=function(){b(a.lazySizes),a.removeEventListener("lazyunveilread",c,!0)};b=b.bind(null,a,a.document),"object"==typeof module&&module.exports?b(require("lazysizes")):a.lazySizes?c():a.addEventListener("lazyunveilread",c,!0)}(window,function(a,b,c){"use strict";function d(a,c){if(!g[a]){var d=b.createElement(c?"link":"script"),e=b.getElementsByTagName("script")[0];c?(d.rel="stylesheet",d.href=a):d.src=a,g[a]=!0,g[d.src||d.href]=!0,e.parentNode.insertBefore(d,e)}}var e,f,g={};b.addEventListener&&(f=/\(|\)|\s|'/,e=function(a,c){var d=b.createElement("img");d.onload=function(){d.onload=null,d.onerror=null,d=null,c()},d.onerror=d.onload,d.src=a,d&&d.complete&&d.onload&&d.onload()},addEventListener("lazybeforeunveil",function(a){if(a.detail.instance==c){var b,g,h,i;if(!a.defaultPrevented){var j=a.target;if("none"==j.preload&&(j.preload=j.getAttribute("data-preload")||"auto"),null!=j.getAttribute("data-autoplay"))if(j.getAttribute("data-expand")&&!j.autoplay)try{j.play()}catch(a){}else requestAnimationFrame(function(){j.setAttribute("data-expand","-10"),c.aC(j,c.cfg.lazyClass)});b=j.getAttribute("data-link"),b&&d(b,!0),b=j.getAttribute("data-script"),b&&d(b),b=j.getAttribute("data-require"),b&&(c.cfg.requireJs?c.cfg.requireJs([b]):d(b)),h=j.getAttribute("data-bg"),h&&(a.detail.firesLoad=!0,g=function(){j.style.backgroundImage="url("+(f.test(h)?JSON.stringify(h):h)+")",a.detail.firesLoad=!1,c.fire(j,"_lazyloaded",{},!0,!0)},e(h,g)),i=j.getAttribute("data-poster"),i&&(a.detail.firesLoad=!0,g=function(){j.poster=i,a.detail.firesLoad=!1,c.fire(j,"_lazyloaded",{},!0,!0)},e(i,g))}}},!1))});
1
+ /*! lazysizes + ls unveilhooks - v5.2.0 (incl. ls-uvh data-link fix) */
2
  !function(a,b){var c=b(a,a.document,Date);a.lazySizes=c,"object"==typeof module&&module.exports&&(module.exports=c)}("undefined"!=typeof window?window:{},function(a,b,c){"use strict";var d,e;if(function(){var b,c={lazyClass:"lazyload",loadedClass:"lazyloaded",loadingClass:"lazyloading",preloadClass:"lazypreload",errorClass:"lazyerror",autosizesClass:"lazyautosizes",srcAttr:"data-src",srcsetAttr:"data-srcset",sizesAttr:"data-sizes",minSize:40,customMedia:{},init:!0,expFactor:1.5,hFac:.8,loadMode:2,loadHidden:!0,ricTimeout:0,throttleDelay:125};e=a.lazySizesConfig||a.lazysizesConfig||{};for(b in c)b in e||(e[b]=c[b])}(),!b||!b.getElementsByClassName)return{init:function(){},cfg:e,noSupport:!0};var f=b.documentElement,g=a.HTMLPictureElement,h="addEventListener",i="getAttribute",j=a[h].bind(a),k=a.setTimeout,l=a.requestAnimationFrame||k,m=a.requestIdleCallback,n=/^picture$/i,o=["load","error","lazyincluded","_lazyloaded"],p={},q=Array.prototype.forEach,r=function(a,b){return p[b]||(p[b]=new RegExp("(\\s|^)"+b+"(\\s|$)")),p[b].test(a[i]("class")||"")&&p[b]},s=function(a,b){r(a,b)||a.setAttribute("class",(a[i]("class")||"").trim()+" "+b)},t=function(a,b){var c;(c=r(a,b))&&a.setAttribute("class",(a[i]("class")||"").replace(c," "))},u=function(a,b,c){var d=c?h:"removeEventListener";c&&u(a,b),o.forEach(function(c){a[d](c,b)})},v=function(a,c,e,f,g){var h=b.createEvent("Event");return e||(e={}),e.instance=d,h.initEvent(c,!f,!g),h.detail=e,a.dispatchEvent(h),h},w=function(b,c){var d;!g&&(d=a.picturefill||e.pf)?(c&&c.src&&!b[i]("srcset")&&b.setAttribute("srcset",c.src),d({reevaluate:!0,elements:[b]})):c&&c.src&&(b.src=c.src)},x=function(a,b){return(getComputedStyle(a,null)||{})[b]},y=function(a,b,c){for(c=c||a.offsetWidth;c<e.minSize&&b&&!a._lazysizesWidth;)c=b.offsetWidth,b=b.parentNode;return c},z=function(){var a,c,d=[],e=[],f=d,g=function(){var b=f;for(f=d.length?e:d,a=!0,c=!1;b.length;)b.shift()();a=!1},h=function(d,e){a&&!e?d.apply(this,arguments):(f.push(d),c||(c=!0,(b.hidden?k:l)(g)))};return h._lsFlush=g,h}(),A=function(a,b){return b?function(){z(a)}:function(){var b=this,c=arguments;z(function(){a.apply(b,c)})}},B=function(a){var b,d=0,f=e.throttleDelay,g=e.ricTimeout,h=function(){b=!1,d=c.now(),a()},i=m&&g>49?function(){m(h,{timeout:g}),g!==e.ricTimeout&&(g=e.ricTimeout)}:A(function(){k(h)},!0);return function(a){var e;(a=!0===a)&&(g=33),b||(b=!0,e=f-(c.now()-d),e<0&&(e=0),a||e<9?i():k(i,e))}},C=function(a){var b,d,e=99,f=function(){b=null,a()},g=function(){var a=c.now()-d;a<e?k(g,e-a):(m||f)(f)};return function(){d=c.now(),b||(b=k(g,e))}},D=function(){var g,m,o,p,y,D,F,G,H,I,J,K,L=/^img$/i,M=/^iframe$/i,N="onscroll"in a&&!/(gle|ing)bot/.test(navigator.userAgent),O=0,P=0,Q=0,R=-1,S=function(a){Q--,(!a||Q<0||!a.target)&&(Q=0)},T=function(a){return null==K&&(K="hidden"==x(b.body,"visibility")),K||!("hidden"==x(a.parentNode,"visibility")&&"hidden"==x(a,"visibility"))},U=function(a,c){var d,e=a,g=T(a);for(G-=c,J+=c,H-=c,I+=c;g&&(e=e.offsetParent)&&e!=b.body&&e!=f;)(g=(x(e,"opacity")||1)>0)&&"visible"!=x(e,"overflow")&&(d=e.getBoundingClientRect(),g=I>d.left&&H<d.right&&J>d.top-1&&G<d.bottom+1);return g},V=function(){var a,c,h,j,k,l,n,o,q,r,s,t,u=d.elements;if((p=e.loadMode)&&Q<8&&(a=u.length)){for(c=0,R++;c<a;c++)if(u[c]&&!u[c]._lazyRace)if(!N||d.prematureUnveil&&d.prematureUnveil(u[c]))ba(u[c]);else if((o=u[c][i]("data-expand"))&&(l=1*o)||(l=P),r||(r=!e.expand||e.expand<1?f.clientHeight>500&&f.clientWidth>500?500:370:e.expand,d._defEx=r,s=r*e.expFactor,t=e.hFac,K=null,P<s&&Q<1&&R>2&&p>2&&!b.hidden?(P=s,R=0):P=p>1&&R>1&&Q<6?r:O),q!==l&&(D=innerWidth+l*t,F=innerHeight+l,n=-1*l,q=l),h=u[c].getBoundingClientRect(),(J=h.bottom)>=n&&(G=h.top)<=F&&(I=h.right)>=n*t&&(H=h.left)<=D&&(J||I||H||G)&&(e.loadHidden||T(u[c]))&&(m&&Q<3&&!o&&(p<3||R<4)||U(u[c],l))){if(ba(u[c]),k=!0,Q>9)break}else!k&&m&&!j&&Q<4&&R<4&&p>2&&(g[0]||e.preloadAfterLoad)&&(g[0]||!o&&(J||I||H||G||"auto"!=u[c][i](e.sizesAttr)))&&(j=g[0]||u[c]);j&&!k&&ba(j)}},W=B(V),X=function(a){var b=a.target;if(b._lazyCache)return void delete b._lazyCache;S(a),s(b,e.loadedClass),t(b,e.loadingClass),u(b,Z),v(b,"lazyloaded")},Y=A(X),Z=function(a){Y({target:a.target})},$=function(a,b){try{a.contentWindow.location.replace(b)}catch(c){a.src=b}},_=function(a){var b,c=a[i](e.srcsetAttr);(b=e.customMedia[a[i]("data-media")||a[i]("media")])&&a.setAttribute("media",b),c&&a.setAttribute("srcset",c)},aa=A(function(a,b,c,d,f){var g,h,j,l,m,p;(m=v(a,"lazybeforeunveil",b)).defaultPrevented||(d&&(c?s(a,e.autosizesClass):a.setAttribute("sizes",d)),h=a[i](e.srcsetAttr),g=a[i](e.srcAttr),f&&(j=a.parentNode,l=j&&n.test(j.nodeName||"")),p=b.firesLoad||"src"in a&&(h||g||l),m={target:a},s(a,e.loadingClass),p&&(clearTimeout(o),o=k(S,2500),u(a,Z,!0)),l&&q.call(j.getElementsByTagName("source"),_),h?a.setAttribute("srcset",h):g&&!l&&(M.test(a.nodeName)?$(a,g):a.src=g),f&&(h||l)&&w(a,{src:g})),a._lazyRace&&delete a._lazyRace,t(a,e.lazyClass),z(function(){var b=a.complete&&a.naturalWidth>1;p&&!b||(b&&s(a,"ls-is-cached"),X(m),a._lazyCache=!0,k(function(){"_lazyCache"in a&&delete a._lazyCache},9)),"lazy"==a.loading&&Q--},!0)}),ba=function(a){if(!a._lazyRace){var b,c=L.test(a.nodeName),d=c&&(a[i](e.sizesAttr)||a[i]("sizes")),f="auto"==d;(!f&&m||!c||!a[i]("src")&&!a.srcset||a.complete||r(a,e.errorClass)||!r(a,e.lazyClass))&&(b=v(a,"lazyunveilread").detail,f&&E.updateElem(a,!0,a.offsetWidth),a._lazyRace=!0,Q++,aa(a,b,f,d,c))}},ca=C(function(){e.loadMode=3,W()}),da=function(){3==e.loadMode&&(e.loadMode=2),ca()},ea=function(){if(!m){if(c.now()-y<999)return void k(ea,999);m=!0,e.loadMode=3,W(),j("scroll",da,!0)}};return{_:function(){y=c.now(),d.elements=b.getElementsByClassName(e.lazyClass),g=b.getElementsByClassName(e.lazyClass+" "+e.preloadClass),j("scroll",W,!0),j("resize",W,!0),j("pageshow",function(a){if(a.persisted){var c=b.querySelectorAll("."+e.loadingClass);c.length&&c.forEach&&l(function(){c.forEach(function(a){a.complete&&ba(a)})})}}),a.MutationObserver?new MutationObserver(W).observe(f,{childList:!0,subtree:!0,attributes:!0}):(f[h]("DOMNodeInserted",W,!0),f[h]("DOMAttrModified",W,!0),setInterval(W,999)),j("hashchange",W,!0),["focus","mouseover","click","load","transitionend","animationend"].forEach(function(a){b[h](a,W,!0)}),/d$|^c/.test(b.readyState)?ea():(j("load",ea),b[h]("DOMContentLoaded",W),k(ea,2e4)),d.elements.length?(V(),z._lsFlush()):W()},checkElems:W,unveil:ba,_aLSL:da}}(),E=function(){var a,c=A(function(a,b,c,d){var e,f,g;if(a._lazysizesWidth=d,d+="px",a.setAttribute("sizes",d),n.test(b.nodeName||""))for(e=b.getElementsByTagName("source"),f=0,g=e.length;f<g;f++)e[f].setAttribute("sizes",d);c.detail.dataAttr||w(a,c.detail)}),d=function(a,b,d){var e,f=a.parentNode;f&&(d=y(a,f,d),e=v(a,"lazybeforesizes",{width:d,dataAttr:!!b}),e.defaultPrevented||(d=e.detail.width)&&d!==a._lazysizesWidth&&c(a,f,e,d))},f=function(){var b,c=a.length;if(c)for(b=0;b<c;b++)d(a[b])},g=C(f);return{_:function(){a=b.getElementsByClassName(e.autosizesClass),j("resize",g)},checkElems:g,updateElem:d}}(),F=function(){!F.i&&b.getElementsByClassName&&(F.i=!0,E._(),D._())};return k(function(){e.init&&F()}),d={cfg:e,autoSizer:E,loader:D,init:F,uP:w,aC:s,rC:t,hC:r,fire:v,gW:y,rAF:z}});
3
+ !function(a,b){var c=function(){b(a.lazySizes),a.removeEventListener("lazyunveilread",c,!0)};b=b.bind(null,a,a.document),"object"==typeof module&&module.exports?b(require("lazysizes")):a.lazySizes?c():a.addEventListener("lazyunveilread",c,!0)}(window,function(a,b,c){'use strict';function d(a,c){if(!h[a]){var d=b.createElement(c?"link":"script"),e=b.getElementsByTagName("script")[0];c?(d.rel="stylesheet",d.href=a):d.src=a,h[a]=!0,h[d.src||d.href]=!0,e.parentNode.insertBefore(d,e)}}var f,g,h={};b.addEventListener&&(g=/\(|\)|\s|'/,f=function(a,c){var d=b.createElement("img");d.onload=function(){d.onload=null,d.onerror=null,d=null,c()},d.onerror=d.onload,d.src=a,d&&d.complete&&d.onload&&d.onload()},addEventListener("lazybeforeunveil",function(a){if(a.detail.instance==c){var b,e,h,i;if(!a.defaultPrevented){var j=a.target;if("none"==j.preload&&(j.preload=j.getAttribute("data-preload")||"auto"),null!=j.getAttribute("data-autoplay"))if(j.getAttribute("data-expand")&&!j.autoplay)try{j.play()}catch(a){}else requestAnimationFrame(function(){j.setAttribute("data-expand","-10"),c.aC(j,c.cfg.lazyClass)});b=j.getAttribute("data-link"),b&&"img"!=j.tagName.toLowerCase()&&d(b,!0),b=j.getAttribute("data-script"),b&&d(b),b=j.getAttribute("data-require"),b&&(c.cfg.requireJs?c.cfg.requireJs([b]):d(b)),h=j.getAttribute("data-bg"),h&&(a.detail.firesLoad=!0,e=function(){j.style.backgroundImage="url("+(g.test(h)?JSON.stringify(h):h)+")",a.detail.firesLoad=!1,c.fire(j,"_lazyloaded",{},!0,!0)},f(h,e)),i=j.getAttribute("data-poster"),i&&(a.detail.firesLoad=!0,e=function(){j.poster=i,a.detail.firesLoad=!1,c.fire(j,"_lazyloaded",{},!0,!0)},f(i,e))}}},!1))});
readme.txt CHANGED
@@ -2,17 +2,17 @@
2
  Contributors: futtta, optimizingmatters, zytzagoo, turl
3
  Tags: optimize, minify, performance, pagespeed, images, lazy-load, google fonts
4
  Donate link: http://blog.futtta.be/2013/10/21/do-not-donate-to-me/
5
- Requires at least: 4.4
6
  Tested up to: 5.4
7
  Requires PHP: 5.6
8
- Stable tag: 2.6.2
9
 
10
  Autoptimize speeds up your website by optimizing JS, CSS, images (incl. lazy-load), HTML and Google Fonts, asyncing JS, removing emoji cruft and more.
11
 
12
  == Description ==
13
 
14
  Autoptimize makes optimizing your site really easy. It can aggregate, minify and cache scripts and styles, injects CSS in the page head by default but can also inline critical CSS and defer the aggregated full CSS, moves and defers scripts to the footer and minifies HTML. You can optimize and lazy-load images, optimize Google Fonts, async non-aggregated JavaScript, remove WordPress core emoji cruft and more. As such it can improve your site's performance even when already on HTTP/2! There is extensive API available to enable you to tailor Autoptimize to each and every site's specific needs.
15
- If you consider performance important, you really should use one of the many caching plugins to do page caching. Some good candidates to complement Autoptimize that way are e.g. [WP Super Cache](http://wordpress.org/plugins/wp-super-cache/), [HyperCache](http://wordpress.org/plugins/hyper-cache/), [Comet Cache](https://wordpress.org/plugins/comet-cache/) or [KeyCDN's Cache Enabler](https://wordpress.org/plugins/cache-enabler).
16
 
17
  > <strong>Premium Support</strong><br>
18
  > We provide great [Autoptimize Pro Support and Web Performance Optimization services](https://autoptimize.com/), check out our offering on [https://autoptimize.com/](https://autoptimize.com/)!
@@ -63,7 +63,7 @@ There's no easy solution for that as "above the fold" depends on where the fold
63
 
64
  = Or should you inline all CSS? =
65
 
66
- The short answer: probably not. Although inlining all CSS will make the CSS non-render blocking, it will result in your base HTML-page getting significantly bigger thus requiring more "roundtrip times". Moreover when considering multiple pages being requested in a browsing session the inline CSS is sent over each time, whereas when not inlined it would be served from cache.
67
 
68
  = My cache is getting huge, doesn't Autoptimize purge the cache? =
69
 
@@ -84,7 +84,7 @@ Moreover don't worry if your cache never is down to 0 files/ 0KB, as Autoptimize
84
 
85
  = My site looks broken when I purge Autoptimize's cache! =
86
 
87
- When clearing AO's cache, no page cache should contain pages (HTML) that refers to the removed optimized CSS/ JS. Although for that purpose there is integretion between Autoptimize and some page caches, this integration does not cover 100% of setups so you might need to purge your page cache manually.
88
 
89
  = Can I still use Cloudflare's Rocket Loader? =
90
 
@@ -94,7 +94,7 @@ At the moment (June 2017) it seems RocketLoader might break AO's "inline & defer
94
 
95
  = I tried Autoptimize but my Google Pagespeed Scored barely improved =
96
 
97
- Autoptimize is not a simple "fix my Pagespeed-problems" plugin; it "only" aggregates & minifies (local) JS & CSS and images and allows for some nice extra's as removing Google Fonts and deferring the loading of the CSS. As such Autoptimize will allow you to improve your performance (load time measured in seconds) and will probably also help you tackle some specific Pagespeed warnings. If you want to improve further, you will probably also have to look into e.g. page caching and your webserver configuration, which will improve real performance (again, load time as measured by e.g. https://webpagetest.org) and your "performance best practise" pagespeed ratings.
98
 
99
  = What can I do with the API? =
100
 
@@ -151,7 +151,7 @@ Make sure you're not running other HTML, CSS or JS minification plugins (BWP min
151
 
152
  = But I still have blank autoptimized CSS or JS-files! =
153
 
154
- If you are running Apache, the htaccess file written by Autoptimize can in some cases conflict with the AllowOverrides settings of your Apache configuration (as is the case with the default configuration of some Ubuntu installations), which results in "internal server errors" on the autoptimize CSS- and JS-files. This can be solved by [setting AllowOverrides to All](http://httpd.apache.org/docs/2.4/mod/core.html#allowoverride).
155
 
156
  = Can't log in on domain mapped multisites =
157
 
@@ -218,7 +218,7 @@ This new option in Autoptimize 2.3 removes the inline CSS, inline JS and linked
218
 
219
  = Is "remove query strings" useful? =
220
 
221
- Although some online performance assessement tools will single out "query strings for static files" as an issue for performance, in general the impact of these is almost non-existant. As such Autoptimize, since version 2.3, allows you to have the query string (or more precisely the "ver"-parameter) removed, but ticking "remove query strings from static resources" will have little or no impact of on your site's performance as measured in (milli-)seconds.
222
 
223
  = (How) should I optimize Google Fonts? =
224
 
@@ -251,10 +251,6 @@ As from AO 2.4 AO "listens" to page cache purges to clear its own cache. You can
251
  `
252
  add_filter('autoptimize_filter_main_hookpagecachepurge','__return_false');`
253
 
254
- = Why can't I upgrade from 2.3.4 to 2.4.0 (or higher)? =
255
-
256
- Main reason (apart from occasional hickups that seem to be inherent to plugin upgrades) is that AO 2.4 requires you to be running PHP 5.3 or higher. And let's face it; you should actually be running PHP 7.x if you value performance (and security and support), no?
257
-
258
  = Some of the non-ASCII characters get lost after optimization =
259
 
260
  By default AO uses non multibyte-safe string methods, but if your PHP has the mbstring extension you can enable multibyte-safe string functions with this filter;
@@ -262,6 +258,27 @@ By default AO uses non multibyte-safe string methods, but if your PHP has the mb
262
  `
263
  add_filter('autoptimize_filter_main_use_mbstring', '__return_true');`
264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  = Where can I get help? =
266
 
267
  You can get help on the [wordpress.org support forum](http://wordpress.org/support/plugin/autoptimize). If you are 100% sure this your problem cannot be solved using Autoptimize configuration and that you in fact discovered a bug in the code, you can [create an issue on GitHub](https://github.com/futtta/autoptimize/issues). If you're looking for premium support, check out our [Autoptimize Pro Support and Web Performance Optimization services](http://autoptimize.com/).
@@ -278,6 +295,11 @@ Just [fork Autoptimize on Github](https://github.com/futtta/autoptimize) and cod
278
 
279
  == Changelog ==
280
 
 
 
 
 
 
281
  = 2.6.2 =
282
  * auto-exclude images from lazyload when they have `loading="eager"` attribute.
283
  * bugfix: don't take querystring into account when deciding as-value for preloaded resources.
2
  Contributors: futtta, optimizingmatters, zytzagoo, turl
3
  Tags: optimize, minify, performance, pagespeed, images, lazy-load, google fonts
4
  Donate link: http://blog.futtta.be/2013/10/21/do-not-donate-to-me/
5
+ Requires at least: 4.9
6
  Tested up to: 5.4
7
  Requires PHP: 5.6
8
+ Stable tag: 2.7.0
9
 
10
  Autoptimize speeds up your website by optimizing JS, CSS, images (incl. lazy-load), HTML and Google Fonts, asyncing JS, removing emoji cruft and more.
11
 
12
  == Description ==
13
 
14
  Autoptimize makes optimizing your site really easy. It can aggregate, minify and cache scripts and styles, injects CSS in the page head by default but can also inline critical CSS and defer the aggregated full CSS, moves and defers scripts to the footer and minifies HTML. You can optimize and lazy-load images, optimize Google Fonts, async non-aggregated JavaScript, remove WordPress core emoji cruft and more. As such it can improve your site's performance even when already on HTTP/2! There is extensive API available to enable you to tailor Autoptimize to each and every site's specific needs.
15
+ If you consider performance important, you really should use one of the many caching plugins to do page caching. Some good candidates to complement Autoptimize that way are e.g. [KeyCDN's Cache Enabler](https://wordpress.org/plugins/cache-enabler) or [WP Super Cache](http://wordpress.org/plugins/wp-super-cache/).
16
 
17
  > <strong>Premium Support</strong><br>
18
  > We provide great [Autoptimize Pro Support and Web Performance Optimization services](https://autoptimize.com/), check out our offering on [https://autoptimize.com/](https://autoptimize.com/)!
63
 
64
  = Or should you inline all CSS? =
65
 
66
+ The short answer: probably not. Although inlining all CSS will make the CSS non-render blocking, it will result in your base HTML-page getting significantly bigger thus requiring more "roundtrip times". Moreover when considering multiple pages being requested in a browsing session the inline CSS is sent over each time, whereas when not inlined it would be served from cache. Finally the inlined CSS will push the meta-tags in the HTML down to a position where Facebook or Whatsapp might not look for it any more, breaking e.g. thumbnails when sharing on these platforms.
67
 
68
  = My cache is getting huge, doesn't Autoptimize purge the cache? =
69
 
84
 
85
  = My site looks broken when I purge Autoptimize's cache! =
86
 
87
+ When clearing AO's cache, no page cache should contain pages (HTML) that refers to the removed optimized CSS/ JS. Although for that purpose there is integration between Autoptimize and some page caches, this integration does not cover 100% of setups so you might need to purge your page cache manually.
88
 
89
  = Can I still use Cloudflare's Rocket Loader? =
90
 
94
 
95
  = I tried Autoptimize but my Google Pagespeed Scored barely improved =
96
 
97
+ Autoptimize is not a simple "fix my Pagespeed-problems" plugin; it "only" aggregates & minifies (local) JS & CSS and images and allows for some nice extra's as removing Google Fonts and deferring the loading of the CSS. As such Autoptimize will allow you to improve your performance (load time measured in seconds) and will probably also help you tackle some specific Pagespeed warnings. If you want to improve further, you will probably also have to look into e.g. page caching and your webserver configuration, which will improve real performance (again, load time as measured by e.g. https://webpagetest.org) and your "performance best practice" pagespeed ratings.
98
 
99
  = What can I do with the API? =
100
 
151
 
152
  = But I still have blank autoptimized CSS or JS-files! =
153
 
154
+ If you are running Apache, the .htaccess file written by Autoptimize can in some cases conflict with the AllowOverrides settings of your Apache configuration (as is the case with the default configuration of some Ubuntu installations), which results in "internal server errors" on the autoptimize CSS- and JS-files. This can be solved by [setting AllowOverrides to All](http://httpd.apache.org/docs/2.4/mod/core.html#allowoverride).
155
 
156
  = Can't log in on domain mapped multisites =
157
 
218
 
219
  = Is "remove query strings" useful? =
220
 
221
+ Although some online performance assessment tools will single out "query strings for static files" as an issue for performance, in general the impact of these is almost non-existant. As such Autoptimize, since version 2.3, allows you to have the query string (or more precisely the "ver"-parameter) removed, but ticking "remove query strings from static resources" will have little or no impact of on your site's performance as measured in (milli-)seconds.
222
 
223
  = (How) should I optimize Google Fonts? =
224
 
251
  `
252
  add_filter('autoptimize_filter_main_hookpagecachepurge','__return_false');`
253
 
 
 
 
 
254
  = Some of the non-ASCII characters get lost after optimization =
255
 
256
  By default AO uses non multibyte-safe string methods, but if your PHP has the mbstring extension you can enable multibyte-safe string functions with this filter;
258
  `
259
  add_filter('autoptimize_filter_main_use_mbstring', '__return_true');`
260
 
261
+ = I can't get Critical CSS working =
262
+
263
+ Check [the FAQ on the (legacy) "power-up" here](https://wordpress.org/plugins/autoptimize-criticalcss/#faq), this info will be integrated in this FAQ at a later date.
264
+
265
+ = Do I still need the Critical CSS power-up when I have Autoptimize 2.7? =
266
+
267
+ When both Autoptimize 2.7 and the separate Critical CSS power-up are installed and active, the power-up will handle the critical CSS part. When you disable the power-up, the integrated critical CSS code in Autoptimize 2.7 will take over.
268
+
269
+ = What does "enable 404 fallbacks" do? Why would I need this? =
270
+
271
+ Autoptimize caches aggregated & optimized CSS/ JS and links to those cached files are stored in the HTML, which will be stored in a page cache (which can be a plugin, can be at host level, can be at 3rd party, in the Google cache, in a browser). If there is HTML in a page cache that links to Autoptimized CSS/ JS that has been removed in the mean time (when the cache was cleared) then the page from cache will not look/ work as expected as the CSS or JS were not found (a 404 error).
272
+
273
+ This (new, experimental) setting aims to prevent things from breaking by serving "fallback" CSS or JS. The fallback-files are copies of the first Autoptimized CSS & JS files created after the cache was emptied and as such will based on the homepage. This means that the CSS/ JS migth not apply 100% on other pages, but at least the impact of missing CSS/ JS will be lessened (often significantly).
274
+
275
+ When the option is enabled, Autoptimize adds an `ErrorDocument 404` to the .htaccess (as used by Apache) and will also hook into WordPress core `template_redirect` to capture 404's handled by Wordpress. When using NGINX something like below should work (I'm not an NGINX specialist, but it does work for me);
276
+
277
+ `
278
+ location ~* /wp-content/cache/autoptimize/.*\.(js|css)$ {
279
+ try_files $uri $uri/ /wp-content/autoptimize_404_handler.php;
280
+ }`
281
+
282
  = Where can I get help? =
283
 
284
  You can get help on the [wordpress.org support forum](http://wordpress.org/support/plugin/autoptimize). If you are 100% sure this your problem cannot be solved using Autoptimize configuration and that you in fact discovered a bug in the code, you can [create an issue on GitHub](https://github.com/futtta/autoptimize/issues). If you're looking for premium support, check out our [Autoptimize Pro Support and Web Performance Optimization services](http://autoptimize.com/).
295
 
296
  == Changelog ==
297
 
298
+ = 2.7.0 =
299
+ * Integration of critical CSS power-up.
300
+ * New option to ensure missing autoptimized files are served with fallback JS/ CSS.
301
+ * Batch of misc. smaller improvements & fixes, more info in the [GitHub commit log](https://github.com/futtta/autoptimize/commits/beta).
302
+
303
  = 2.6.2 =
304
  * auto-exclude images from lazyload when they have `loading="eager"` attribute.
305
  * bugfix: don't take querystring into account when deciding as-value for preloaded resources.