[ create a new paste ] login | about

Link: http://codepad.org/MJMU4ccK    [ raw code | fork ]

PHP, pasted on Sep 6:
<?php

if(!is_admin()) add_action('wp_print_scripts', 'atom_print_scripts');


function atom_print_scripts(){
  global $wp_scripts, $wp_filesystem;

  if(!is_a($wp_scripts, 'WP_Scripts') || !ATOM_CONCATENATE_JS || Atom::app()->previewMode() || ATOM_DEV_MODE) return;

  // remove admin-bar js if jquery is enabled
  //wp_dequeue_script('admin-bar');

  $scripts = $locales = array();
  $queue = $wp_scripts->queue;
  $wp_scripts->all_deps($queue);   // arrange the list of scripts based on dependencies

  foreach($wp_scripts->to_do as $key => $handle){

    if($wp_scripts->registered[$handle]->ver === null) $ver = '';
    else $ver = $wp_scripts->registered[$handle]->ver ? $wp_scripts->registered[$handle]->ver : $wp_scripts->default_version;

    if(isset($wp_scripts->args[$handle]))
      $ver = $ver ? $ver.'&amp;'. $wp_scripts->args[$handle] : $wp_scripts->args[$handle];

    $src = $wp_scripts->registered[$handle]->src;
    if($locale = $wp_scripts->print_scripts_l10n($handle, false)) $locales[] = $locale;
//    if($locale = $wp_scripts->print_scripts_l10n($handle, false)) continue;

    if(!preg_match('|^https?://|', $src) && ! ($wp_scripts->content_url && 0 === strpos($src, $wp_scripts->content_url)))
      $src = $wp_scripts->base_url.$src;

    if(!empty($ver))
      $src = add_query_arg('ver', $ver, $src);

    $src = esc_url_raw(apply_filters('script_loader_src', $src, $handle));

    $scripts[$handle] = $src;
//    unset($wp_scripts->to_do[$key]);
//    $wp_scripts->done[] = $handle;

  }

  if(empty($scripts)) return;

  if(($cache = get_transient('atom_js_cache')) === false) $cache = array();

  // wp-content/uploads
  $upload_dir = wp_upload_dir();

  $handles = implode(', ', array_keys($scripts));
  $cache_name = ATOM.'-'.md5($handles);
  $cache_file_path = "{$upload_dir['basedir']}/{$cache_name}.js";
  $cache_file_url = "{$upload_dir['baseurl']}/{$cache_name}.js";

  // calculate modified tag
  $hash = 0;
  foreach($scripts as $handle => $script){
    $parts = parse_url($script);
    $file_path = str_replace(site_url('/'), ABSPATH, $parts['scheme'].'://'.$parts['host'].$parts['path']);
    $hash += @filemtime($file_path);
  }

  // decide whether to build cache or not
  if(!isset($cache[$cache_name]) || ($cache[$cache_name] !== $hash) || !is_readable($cache_file_path)){

    require_once(ABSPATH.'wp-admin/includes/file.php');
    if(!WP_Filesystem())  // return and load them normally
      return Atom::app()->addDebugMessage("Failed to initialize WPFS for javascript caching. Your host's \"security settings\" prevent direct file writes...", 1);

    $script_urls = array_values($scripts);
    $url = 'http://closure-compiler.appspot.com/compile?code_url='.array_shift($script_urls);
    foreach($script_urls as $script_url)
      $url .= '&code_url='.urlencode($script_url);

    $compression_options = array(
      'body' => array(
        'compilation_level' => 'SIMPLE_OPTIMIZATIONS',
        'output_format'     => 'json',
        'output_info'       => 'compiled_code',
    ));

    $raw_response = wp_remote_post($url, $compression_options);

    if(!is_wp_error($raw_response) && ($raw_response['response']['code'] == 200))
      $response = json_decode($raw_response['body']);

    if(!empty($response->compiledCode) && empty($response->serverErrors) &&  empty($response->errors)){
      $compressed_js = $response->compiledCode;

      // save file
      if($wp_filesystem->is_writable($upload_dir['basedir']) && $wp_filesystem->put_contents($cache_file_path, "/*\nCache: {$handles}\n*/\n{$compressed_js}", FS_CHMOD_FILE)){
        $saved = true;
        $cache[$cache_name] = $hash;
        set_transient('atom_js_cache', $cache, 60*60*24*30); // 30 day cache
        Atom::app()->addDebugMessage("Javascript cache rebuilt ({$cache_file_url})");

      }else{ // return and load them normally
        return Atom::app()->addDebugMessage("Failed to create javascript cache ({$cache_file_url}). Try reloading again or disable the 'optimize' option to avoid slowdowns.", 1);
      }

    }else{ // return and load them normally
        return Atom::app()->addDebugMessage("Failed to create javascript cache: the Google Closure Compiler service returned error(s). Please disable the 'optimize' option to avoid slowdowns.", 1);
    }

  }

  foreach($scripts as $id => $url)
    foreach($wp_scripts->to_do as $key => $handle)
      if($id == $handle){
        unset($wp_scripts->to_do[$key]);
        $wp_scripts->done[] = $handle;
      }

  echo '<script src="'.$cache_file_url.'"></script>'."\n";

  if(!empty($locales)){
    echo "<script>\n";
    foreach($locales as $locale){
      echo "{$locale}\n";
    }
    echo "</script>\n";
  }


//  Atom::app()->addContextArgs('footer', array('js_cache' => $cache_file_url));
//  wp_enqueue_script(ATOM.'-js-cache', $cache_file_url, array(), false, true);

//  $wp_scripts->reset();
//  return $wp_scripts->done;
}


Create a new paste based on this one


Comments: