/**
  * Return canonical rules
  *
  * @param bool    $cdnftp
  * @return string
  */
 public static function canonical_without_location($cdnftp = false, $add_header_rules)
 {
     $rules = '';
     switch (true) {
         case Util_Environment::is_apache():
         case Util_Environment::is_litespeed():
             $host = $cdnftp ? Util_Environment::home_url_host() : '%{HTTP_HOST}';
             $rules .= "   <IfModule mod_rewrite.c>\n";
             $rules .= "      RewriteEngine On\n";
             $rules .= "      RewriteCond %{HTTPS} !=on\n";
             $rules .= "      RewriteRule .* - [E=CANONICAL:http://{$host}%{REQUEST_URI},NE]\n";
             $rules .= "      RewriteCond %{HTTPS} =on\n";
             $rules .= "      RewriteRule .* - [E=CANONICAL:https://{$host}%{REQUEST_URI},NE]\n";
             $rules .= "   </IfModule>\n";
             $rules .= "   <IfModule mod_headers.c>\n";
             $rules .= '      Header set Link "<%{CANONICAL}e>; rel=\\"canonical\\""' . "\n";
             $rules .= "   </IfModule>\n";
             break;
         case Util_Environment::is_nginx():
             $home = $cdnftp ? Util_Environment::home_url_host() : '$host';
             // nginx overrides all add_header directives when context inherited
             // so add_header rules has to be repeated
             $link_header = '    add_header Link "<$scheme://' . $home . '$uri>; rel=\\"canonical\\"";' . "\n";
             $rules .= $link_header . '    if ($request_uri ~ \\.(ttf|ttc|otf|eot|woff|woff2|font.css)$) {' . "\n    " . $link_header . "    " . str_replace("\n", "\n    ", $add_header_rules) . "    add_header Access-Control-Allow-Origin \"*\";\n" . "    }\n";
             break;
     }
     return $rules;
 }
 public static function get_suggested_home_ip()
 {
     $ip = gethostbyname(Util_Environment::home_url_host());
     // check if it resolves to local IP, means host cant know its real IP
     if (substr($ip, 0, 4) == '127.' || substr($ip, 0, 3) == '10.' || substr($ip, 0, 8) == '192.168.') {
         return '';
     }
     return $ip;
 }
 public function w3tc_ajax_cdn_maxcdn_fsd_configure_zone()
 {
     $api_key = $_REQUEST['api_key'];
     $zone_id = Util_Request::get('zone_id', '');
     $zone = array('name' => Util_Request::get('name'), 'label' => Util_Request::get('name'), 'url' => Util_Request::get('url'), 'use_stale' => 1, 'queries' => 1, 'compress' => 1, 'backend_compress' => 1, 'dns_check' => Util_Request::get('dns_check'), 'ip' => Util_Request::get('ip'));
     $api = \NetDNA::create($api_key);
     try {
         if (empty($zone_id)) {
             $response = $api->create_pull_zone($zone);
             $zone_id = $response['id'];
         } else {
             $response = $api->update_pull_zone($zone_id, $zone);
         }
         $custom_domains = $api->get_custom_domains($zone_id);
         $custom_domain = Util_Request::get('custom_domain');
         $added = false;
         foreach ($custom_domains as $d) {
             if ($d['custom_domain'] == $custom_domain) {
                 $added = true;
                 break;
             }
         }
         if (!$added) {
             $api->create_custom_domain($zone_id, $custom_domain);
         }
     } catch (\Exception $ex) {
         $this->render_intro(array('api_key' => $api_key, 'error_message' => 'Failed to configure custom domain ' . $custom_domain . ': ' . $ex->getMessage()));
         exit;
     }
     $zone_domain = $response['tmp_url'];
     $c = Dispatcher::config();
     $c->set('cdn.maxcdn_fsd.api_key', $api_key);
     $c->set('cdn.maxcdn_fsd.zone_id', $zone_id);
     $c->set('cdn.maxcdn_fsd.zone_domain', $zone_domain);
     $c->save();
     $details = array('name' => $zone['name'], 'home_domain' => Util_Environment::home_url_host(), 'dns_cname_target' => $zone_domain);
     include W3TC_DIR . '/Cdn_MaxCdnFsd_Popup_View_Success.php';
     exit;
 }
    function admin_head()
    {
        if (isset($_GET['page']) && $_GET['page'] == 'w3tc_dashboard') {
            ?>
            <script type="text/javascript">
            jQuery(function() {
                jQuery('#normal-sortables').masonry({
                    itemSelector: '.postbox'
                });
            });
            </script>
            <?php 
        }
        if ($this->_config->get_boolean('common.track_usage') && $this->is_w3tc_page) {
            $current_user = wp_get_current_user();
            $page = Util_Request::get_string('page');
            if ($page == 'w3tc_extensions') {
                $page = 'extensions/' . Util_Request::get_string('extension');
            }
            if (defined('W3TC_DEBUG') && W3TC_DEBUG) {
                $profile = 'UA-2264433-7';
            } else {
                $profile = 'UA-2264433-8';
            }
            ?>
            <script type="text/javascript">
            (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
            })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

            ga('create', '<?php 
            echo $profile;
            ?>
', 'auto');
            ga('set', {
                'dimension1': 'w3-total-cache',
                'dimension2': '<?php 
            echo W3TC_VERSION;
            ?>
',
                'dimension3': '<?php 
            global $wp_version;
            echo $wp_version;
            ?>
',
                'dimension4': 'php<?php 
            echo phpversion();
            ?>
',
                'dimension5': '<?php 
            echo esc_attr($_SERVER["SERVER_SOFTWARE"]);
            ?>
',
                'dimension6': 'mysql<?php 
            global $wpdb;
            echo $wpdb->db_version();
            ?>
',
                'dimension7': '<?php 
            echo Util_Environment::home_url_host();
            ?>
',
                'userId': '<?php 
            echo $current_user->user_email;
            ?>
',
                'page': '<?php 
            echo $page;
            ?>
'
            });

            ga('send', 'pageview');

            </script>
            <?php 
        }
        ?>
        <style type="text/css" media="screen">
        #toplevel_page_w3tc_dashboard .wp-menu-image {
            background: url(<?php 
        echo plugins_url('w3-total-cache/pub/img/w3tc-sprite.png');
        ?>
) no-repeat 0 -32px !important;
        }
        #toplevel_page_w3tc_dashboard:hover .wp-menu-image,
        #toplevel_page_w3tc_dashboard.wp-has-current-submenu .wp-menu-image {
            background-position:0 0 !important;
        }
        #icon-edit.icon32-posts-casestudy {
            background: url(<?php 
        echo plugins_url('w3-total-cache/pub/img/w3tc-sprite.png');
        ?>
) no-repeat;
        }
        /**
        * HiDPI Displays
        */
        @media print,
        (-o-min-device-pixel-ratio: 5/4),
        (-webkit-min-device-pixel-ratio: 1.25),
        (min-resolution: 120dpi) {

            #toplevel_page_w3tc_dashboard .wp-menu-image {
                background-image: url(<?php 
        echo plugins_url('w3-total-cache/pub/img/w3tc-sprite-retina.png');
        ?>
) !important;
                background-size: 30px 64px !important;
            }
            #toplevel_page_w3tc_dashboard:hover .wp-menu-image,
            #toplevel_page_w3tc_dashboard.wp-has-current-submenu .wp-menu-image {
                background-position:0 0 !important;
            }
            #icon-edit.icon32-posts-casestudy {
                background-image: url(<?php 
        echo plugins_url('w3-total-cache/pub/img/w3tc-sprite-retina.png');
        ?>
) !important;
                background-size: 30px 64px !important;
            }
        }
        </style>
        <?php 
    }
 public function w3tc_ajax_cdn_cloudfront_fsd_configure_distribution()
 {
     $access_key = $_REQUEST['access_key'];
     $secret_key = $_REQUEST['secret_key'];
     $distribution_id = Util_Request::get('distribution_id', '');
     $origin_id = rand();
     $distribution = array('Comment' => Util_Request::get('distribution_comment'), 'Origins' => array('Quantity' => 1, 'Items' => array('Origin' => array('Id' => $origin_id, 'DomainName' => Util_Request::get('origin'), 'OriginPath' => '', 'CustomOriginConfig' => array('HTTPPort' => 80, 'HTTPSPort' => 443, 'OriginProtocolPolicy' => 'match-viewer')))), 'Aliases' => array('Quantity' => 1, 'Items' => array('CNAME' => Util_Request::get('alias'))), 'DefaultCacheBehavior' => array('TargetOriginId' => $origin_id, 'ForwardedValues' => array('QueryString' => 'true', 'Cookies' => array('Forward' => 'all'), 'Headers' => array('Quantity' => 1, 'Items' => array('Name' => 'Host'))), 'AllowedMethods' => array('Quantity' => 7, 'Items' => array('Method' => array('GET', 'HEAD', 'OPTIONS', 'PUT', 'POST', 'PATCH', 'DELETE')), 'CachedMethods' => array('Quantity' => 2, 'Items' => array('Method' => array('GET', 'HEAD')))), 'MinTTL' => 0));
     try {
         $api = new Cdn_CloudFrontFsd_Api($access_key, $secret_key);
         if (empty($distribution_id)) {
             $distribution['DefaultCacheBehavior']['TrustedSigners'] = array('Enabled' => 'false', 'Quantity' => 0);
             $distribution['DefaultCacheBehavior']['ViewerProtocolPolicy'] = 'allow-all';
             $response = $api->distribution_create($distribution);
             $distribution_id = $response['Id'];
         } else {
             $response = $api->distribution_update($distribution_id, $distribution);
         }
     } catch (\Exception $ex) {
         $this->render_intro(array('error_message' => 'Failed to configure distribution: ' . $ex->getMessage()));
         exit;
     }
     $distribution_domain = $response['DomainName'];
     $c = Dispatcher::config();
     $c->set('cdn.cloudfront_fsd.access_key', $access_key);
     $c->set('cdn.cloudfront_fsd.secret_key', $secret_key);
     $c->set('cdn.cloudfront_fsd.distribution_id', $distribution_id);
     $c->set('cdn.cloudfront_fsd.distribution_domain', $distribution_domain);
     $c->save();
     $details = array('name' => $distribution['Comment'], 'home_domain' => Util_Environment::home_url_host(), 'dns_cname_target' => $distribution_domain);
     include W3TC_DIR . '/Cdn_CloudFrontFsd_Popup_View_Success.php';
     exit;
 }
 /**
  * Returns server info
  *
  * @return array
  */
 private function get_server_info()
 {
     global $wp_version, $wp_db_version, $wpdb;
     $wordpress_plugins = get_plugins();
     $wordpress_plugins_active = array();
     foreach ($wordpress_plugins as $wordpress_plugin_file => $wordpress_plugin) {
         if (is_plugin_active($wordpress_plugin_file)) {
             $wordpress_plugins_active[$wordpress_plugin_file] = $wordpress_plugin;
         }
     }
     $mysql_version = $wpdb->get_var('SELECT VERSION()');
     $mysql_variables_result = (array) $wpdb->get_results('SHOW VARIABLES', ARRAY_N);
     $mysql_variables = array();
     foreach ($mysql_variables_result as $mysql_variables_row) {
         $mysql_variables[$mysql_variables_row[0]] = $mysql_variables_row[1];
     }
     $server_info = array('w3tc' => array('version' => W3TC_VERSION, 'server' => !empty($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : 'Unknown', 'dir' => W3TC_DIR, 'cache_dir' => W3TC_CACHE_DIR, 'blog_id' => Util_Environment::blog_id(), 'home_domain_root_url' => Util_Environment::home_domain_root_url(), 'home_url_maybe_https' => Util_Environment::home_url_maybe_https(), 'site_path' => Util_Environment::site_path(), 'document_root' => Util_Environment::document_root(), 'site_root' => Util_Environment::site_root(), 'site_url_uri' => Util_Environment::site_url_uri(), 'home_url_host' => Util_Environment::home_url_host(), 'home_url_uri' => Util_Environment::home_url_uri(), 'network_home_url_uri' => Util_Environment::network_home_url_uri(), 'host_port' => Util_Environment::host_port(), 'host' => Util_Environment::host(), 'wp_config_path' => Util_Environment::wp_config_path()), 'wp' => array('version' => $wp_version, 'db_version' => $wp_db_version, 'abspath' => ABSPATH, 'home' => get_option('home'), 'siteurl' => get_option('siteurl'), 'email' => get_option('admin_email'), 'upload_info' => (array) Util_Http::upload_info(), 'theme' => Util_Theme::get_current_theme(), 'wp_cache' => defined('WP_CACHE') && WP_CACHE ? 'true' : 'false', 'plugins' => $wordpress_plugins_active), 'mysql' => array('version' => $mysql_version, 'variables' => $mysql_variables));
     return $server_info;
 }
 private function _create_host($api, $host_name)
 {
     // create simple host
     $services_response = $api->services();
     // select all CDS services since its going to use caching
     $service_ids = array();
     foreach ($services_response['list'] as $s) {
         if (strpos($s['name'], 'CDS') >= 0) {
             $service_ids[] = $s['id'];
         }
     }
     $origins_response = $api->origins();
     $home_domain = Util_Environment::home_url_host();
     $origin_id = 0;
     foreach ($origins_response['list'] as $o) {
         if ($o['hostname'] == $home_domain) {
             $origin_id = $o['id'];
             break;
         }
     }
     if ($origin_id == 0) {
         try {
             $name = preg_replace('/[^0-9a-z]/', '_', $home_domain);
             $origin_response = $api->origin_add(array('name' => $name, 'hostname' => $home_domain, 'path' => '/', 'port' => 80));
             $origin_id = $origin_response['id'];
         } catch (\Exception $ex) {
             throw new \Exception('Can\'t create origin ' . $home_domain . ': ' . $ex->getMessage());
         }
     }
     try {
         // create host
         $host_response = $api->host_add(array('name' => $_REQUEST['host_new'], 'services' => $service_ids));
         $host = $host_response['hashCode'];
     } catch (\Exception $ex) {
         throw new \Exception('Can\'t create new host: ' . $ex->getMessage());
     }
     // configure host
     $scopes_response = $api->configure_scopes($host);
     $scope_id = 0;
     foreach ($scopes_response['list'] as $scope) {
         if ($scope['platform'] == 'CDS') {
             $scope_id = $scope['id'];
         }
     }
     if ($scope_id <= 0) {
         throw new Exception('Cant\'t configure host - scope CDN hasnt been created');
     }
     $configuration = $api->configure_scope_get($host, $scope_id);
     // apply usually optimal default values
     $configuration['cacheControl'] = array(array('maxAge' => 31536000));
     $configuration['compression'] = array('gzip' => 'css,js');
     $configuration['originPullCacheExtension'] = array('expiredCacheExtension' => 86400);
     $configuration['originPullHost'] = array('primary' => $origin_id);
     $configuration['originPullPolicy'] = array(array('expirePolicy' => 'CACHE_CONTROL', 'expireSeconds' => 86400, 'httpHeaders' => 'Access-Control-Allow-Origin'));
     try {
         $configuration_response = $api->configure_scope_set($host, $scope_id, $configuration);
     } catch (\Exception $ex) {
         throw new \Exception('Cant\'t configure host: ' . $ex->getMessage());
     }
     return $host;
 }
 public function w3tc_ajax_cdn_rackspace_service_actualize_done()
 {
     $user_name = $_REQUEST['user_name'];
     $api_key = $_REQUEST['api_key'];
     $access_token = $_REQUEST['access_token'];
     $access_region_descriptor = json_decode(strtr($_REQUEST['access_region_descriptor'], '!^', '"\\'), true);
     $region = $_REQUEST['region'];
     $service_id = $_REQUEST['service_id'];
     $api = new Cdn_RackSpace_Api_Cdn(array('access_token' => $access_token, 'access_region_descriptor' => $access_region_descriptor, 'new_access_required' => ''));
     try {
         $service = $api->service_get($service_id);
         $is_https = false;
         $origin = '';
         if (isset($service['origins']) && $service['origins'][0]['ssl']) {
             $is_https = $service['origins'][0]['ssl'];
             $origin = $service['origins'][0]['origin'];
         }
         $new_origin = Util_Environment::home_url_host();
         if ($origin != $new_origin) {
             $api->service_set($service_id, array(array('op' => 'replace', 'path' => '/origins', 'value' => array(array('origin' => $new_origin, 'port' => $is_https ? 443 : 80, 'ssl' => $is_https, 'hostheadertype' => 'origin', 'rules' => array())))));
         }
     } catch (\Exception $ex) {
         $details = array('user_name' => $user_name, 'api_key' => $api_key, 'error_message' => $ex->getMessage());
         include W3TC_DIR . '/Cdn_RackSpaceCdn_Popup_View_Intro.php';
         exit;
     }
     $this->_save_config();
 }