$value ) { if ( strpos( strtolower( $value ), strtolower( $site_url ) ) === 0 ) { $track[ $k ] = substr( $track[ $k ], strlen( $site_url ) ); } if ( 'data' === $k ) { $track[ $k ] = preg_replace( '/^https?:\/\/|^\/+/i', '', $track[ $k ] ); } // This way we don't lose search data. if ( 'data' === $k && 'search' === $track['code'] ) { $track[ $k ] = rawurlencode( $track[ $k ] ); } else { $track[ $k ] = preg_replace( '/[^a-z0-9\.\/\+\?=-]+/i', '_', $track[ $k ] ); } $track[ $k ] = trim( $track[ $k ], '_' ); } $char = ( strpos( $track['data'], '?' ) === false ) ? '?' : '&'; return str_replace( "'", "\'", "/{$track['code']}/{$track['data']}{$char}referer=" . rawurlencode( isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : '' ) ); // Input var okay. } /** * Maybe output or return, depending on the context */ private function _output_or_return( $val, $maybe ) { if ( $maybe ) { echo $val . "\r\n"; } else { return $val; } } /** * This injects the Google Analytics code into the footer of the page. * * @param bool[optional] $output - defaults to true, false returns but does NOT echo the code. */ public function insert_code( $output = true ) { // If $output is not a boolean false, set it to true (default). $output = ( false !== $output); $tracking_id = $this->_get_tracking_code(); if ( empty( $tracking_id ) ) { return $this->_output_or_return( '', $output ); } // If we're in the admin_area, return without inserting code. if ( is_admin() ) { return $this->_output_or_return( '', $output ); } $custom_vars = array( "_gaq.push(['_setAccount', '{$tracking_id}']);", ); $track = array(); if ( is_404() ) { // This is a 404 and we are supposed to track them. $custom_vars[] = "_gaq.push( [ '_trackEvent', '404', document.location.href, document.referrer ] );"; } elseif ( is_search() ) { // Set track for searches, if it's a search, and we are supposed to. $track['data'] = sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ); // Input var okay. $track['code'] = 'search'; } if ( ! empty( $track ) ) { $track['url'] = $this->_get_url( $track ); // adjust the code that we output, account for both types of tracking. $track['url'] = esc_js( str_replace( '&', '&', $track['url'] ) ); $custom_vars[] = "_gaq.push(['_trackPageview','{$track['url']}']);"; } else { $custom_vars[] = "_gaq.push(['_trackPageview']);"; } $async_code = " "; $custom_vars_string = implode( "\r\n", $custom_vars ); $async_code = str_replace( '%custom_vars%', $custom_vars_string, $async_code ); return $this->_output_or_return( $async_code, $output ); } /** * Used to get the tracking code option * * @return tracking code option value. */ private function _get_tracking_code() { $o = get_option( 'jetpack_wga' ); if ( isset( $o['code'] ) && preg_match( '#UA-[\d-]+#', $o['code'], $matches ) ) { return $o['code']; } return ''; } } global $jetpack_google_analytics; $jetpack_google_analytics = Jetpack_Google_Analytics::get_instance();