WordPress.org

Plugin Directory

Changeset 606661


Ignore:
Timestamp:
10/01/12 18:52:09 (19 months ago)
Author:
aaroncampbell
Message:

Working pass at 1.3.0

  • Refactored to use settings API - Props danielbachhuber
  • Convert to singleton and instatiate class
  • Convert tracking code field to ID, keeping backwards compat - Props danielbachhuber
  • Custom variable support - Props danielbachhuber
  • Track outgoing links and 404s as events
  • Made the whole plugin translatable
  • Deprecated tracking searches
Location:
wp-google-analytics/trunk
Files:
2 added
3 edited

Legend:

Unmodified
Added
Removed
  • wp-google-analytics/trunk

    • Property svn:ignore
      •  

        old new  
        11.git 
        22.gitignore 
         3README.md 
        34 
  • wp-google-analytics/trunk/readme.txt

    r587850 r606661  
    1515 
    1616* Not log anything in the admin area 
    17 * Log 404 errors as /404/{url}?referrer={referrer} 
    18 * Log searches as /search/{search}?referrer={referrer} 
    19 * Log outgoing links as /outgoing/{url}?referrer={referrer} 
     17* Log 404 errors as events 
     18* Log outgoing links as events 
    2019* Not log any user roles (administrators, editors, authors, etc) 
     20* Use custom variables 
    2121 
    2222== Installation == 
     
    3232this page. 
    3333 
     34= How do I track searches? = 
     35 
     36WP Google Analytics used to help you track site searches before Google Analytics 
     37started doing this natively.  While we still support tracking searches for 
     38backwards compatibility, this feature has been deprecated and will eventually be 
     39removed.  To track searches in Google Analytics follow this 
     40<a href="http://support.google.com/analytics/bin/answer.py?hl=en&answer=1012264">Google support article</a>. 
     41WordPress uses 's' as the query parameter. 
     42 
    3443= Can't I just paste the Google Analytics code into my template file? = 
    3544 
     
    4150 
    4251== Changelog == 
     52 
     53= 1.3.0 = 
     54* Refactored to use settings API - Props danielbachhuber 
     55* Convert to singleton and instatiate class 
     56* Convert tracking code field to ID, keeping backwards compat - Props danielbachhuber 
     57* Custom variable support - Props danielbachhuber 
     58* Track outgoing links and 404s as events 
     59* Made the whole plugin translatable 
     60* Deprecated tracking searches 
    4361 
    4462= 1.2.5 = 
  • wp-google-analytics/trunk/wp-google-analytics.php

    r587850 r606661  
    44 * Plugin URI: http://bluedogwebservices.com/wordpress-plugin/wp-google-analytics/ 
    55 * Description: Lets you use <a href="http://analytics.google.com">Google Analytics</a> to track your WordPress site statistics 
    6  * Version: 1.2.5 
     6 * Version: 1.3-working 
    77 * Author: Aaron D. Campbell 
    88 * Author URI: http://ran.ge/ 
     9 * License: GPLv2 or later 
     10 * Text Domain: wp-google-analytics 
    911 */ 
    1012 
    11 define('WGA_VERSION', '1.2.5'); 
     13define('WGA_VERSION', '1.3-working'); 
    1214 
    1315/*  Copyright 2006  Aaron D. Campbell  (email : wp_plugins@xavisys.com) 
     
    2729    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
    2830*/ 
    29  
    30 //If this is set to true, extra info will be dumped to the browser. 
    31 //ONLY do this if you really need it 
    32 define('WGA_DEBUG', false); 
    3331 
    3432/** 
     
    4038 
    4139    /** 
     40     * @var wpGoogleAnalytics - Static property to hold our singleton instance 
     41     */ 
     42    static $instance = false; 
     43 
     44    static $page_slug = 'wp-google-analytics'; 
     45 
     46    /** 
     47     * This is our constructor, which is private to force the use of get_instance() 
     48     * @return void 
     49     */ 
     50    private function __construct() { 
     51        add_filter( 'init',                     array( $this, 'init_locale' ) ); 
     52        add_action( 'admin_init',               array( $this, 'admin_init' ) ); 
     53        add_action( 'admin_menu',               array( $this, 'admin_menu' ) ); 
     54        add_action( 'get_footer',               array( $this, 'insert_code' ) ); 
     55        add_action( 'wp_enqueue_scripts',       array( $this, 'track_outgoing' ) ); 
     56    } 
     57 
     58    /** 
     59     * Function to instantiate our class and make it a singleton 
     60     */ 
     61    public static function get_instance() { 
     62        if ( !self::$instance ) 
     63            self::$instance = new self; 
     64 
     65        return self::$instance; 
     66    } 
     67 
     68    public function init_locale() { 
     69        load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' ); 
     70    } 
     71 
     72    /** 
    4273     * This adds the options page for this plugin to the Options page 
    4374     */ 
    44     function admin_menu() { 
    45         add_options_page(__('Google Analytics'), __('Google Analytics'), 'manage_options', str_replace("\\", "/", __FILE__), array('wpGoogleAnalytics', 'options')); 
     75    public function admin_menu() { 
     76        add_options_page(__('Google Analytics', 'wp-google-analytics'), __('Google Analytics', 'wp-google-analytics'), 'manage_options', self::$page_slug, array( $this, 'settings_view' ) ); 
     77    } 
     78 
     79    /** 
     80     * Register our settings 
     81     */ 
     82    public function admin_init() { 
     83        register_setting( 'wga', 'wga', array( $this, 'sanitize_general_options' ) ); 
     84 
     85        add_settings_section( 'wga_general', false, '__return_false', 'wga' ); 
     86        add_settings_field( 'code', __( 'Google Analytics tracking ID:', 'wp-google-analytics' ), array( $this, 'field_code' ), 'wga', 'wga_general' ); 
     87        add_settings_field( 'additional_items', __( 'Additional items to log:', 'wp-google-analytics' ), array( $this, 'field_additional_items' ), 'wga', 'wga_general' ); 
     88        add_settings_field( 'do_not_track', __( 'Visits to ignore:', 'wp-google-analytics' ), array( $this, 'field_do_not_track' ), 'wga', 'wga_general' ); 
     89        add_settings_field( 'custom_vars', __( 'Custom variables:', 'wp-google-analytics' ), array( $this, 'field_custom_variables' ), 'wga', 'wga_general' ); 
     90    } 
     91 
     92    /** 
     93     * Where the user adds their Google Analytics code 
     94     */ 
     95    public function field_code() { 
     96        echo '<input name="wga[code]" id="wga-code" type="text" value="' . esc_attr( $this->_get_options( 'code' ) ) . '" />'; 
     97        echo '<p class="description">' . __( 'Paste your Google Analytics tracking ID (e.g. "UA-XXXXXX-X") into the field.', 'wp-google-analytics' ) . '</p>'; 
     98    } 
     99 
     100    /** 
     101     * Option to log additional items 
     102     */ 
     103    public function field_additional_items() { 
     104        $addtl_items = array( 
     105                'log_404s'       => __( 'Log 404 errors as events', 'wp-google-analytics' ), 
     106                'log_searches'   => sprintf( __( 'Log searches as /search/{search}?referrer={referrer} (<a href="%s">deprecated</a>)', 'wp-google-analytics' ), 'http://wordpress.org/extend/plugins/wp-google-analytics/faq/' ), 
     107                'log_outgoing'   => __( 'Log outgoing links as events', 'wp-google-analytics' ), 
     108            ); 
     109        foreach( $addtl_items as $id => $label ) { 
     110            echo '<label for="wga_' . $id . '">'; 
     111            echo '<input id="wga_' . $id . '" type="checkbox" name="wga[' . $id . ']" value="true" ' . checked( 'true', $this->_get_options( $id ), false ) . ' />'; 
     112            echo '&nbsp;&nbsp;' . $label; 
     113            echo '</label><br />'; 
     114        } 
     115    } 
     116 
     117    /** 
     118     * Define custom variables to be included in your tracking code 
     119     */ 
     120    public function field_custom_variables() { 
     121        $custom_vars = $this->_get_options( 'custom_vars' ); 
     122 
     123        $scope_options = array( 
     124                0 => __( 'Default', 'wp-google-analytics' ), 
     125                1 => __( 'Visitor', 'wp-google-analytics' ), 
     126                2 => __( 'Session', 'wp-google-analytics' ), 
     127                3 => __( 'Page', 'wp-google-analytics' ), 
     128            ); 
     129        for ( $i = 1; $i <= 5; $i++ ) { 
     130            $name = ( isset( $custom_vars[$i]['name'] ) ) ? $custom_vars[$i]['name'] : ''; 
     131            $value = ( isset( $custom_vars[$i]['value'] ) ) ? $custom_vars[$i]['value'] : ''; 
     132            $scope = ( isset( $custom_vars[$i]['scope'] ) ) ? $custom_vars[$i]['scope'] : 0; 
     133            echo '<label for="wga_custom_var_' . $i . '_name"><strong>' . $i . ')</strong>&nbsp;' . __( 'Name', 'wp-google-analytics' ) . '&nbsp;'; 
     134            echo '<input id="wga_custom_var_' . $i . '" type="text" name="wga[custom_vars][' . $i . '][name]" value="' . esc_attr( $name ) . '" />'; 
     135            echo '</label>&nbsp;&nbsp;'; 
     136            echo '<label for="wga_custom_var_' . $i . '_value">' . __( 'Value', 'wp-google-analytics' ) . '&nbsp;'; 
     137            echo '<input id="wga_custom_var_' . $i . '" type="text" name="wga[custom_vars][' . $i . '][value]" value="' . esc_attr( $value ) . '" />'; 
     138            echo '</label>&nbsp;&nbsp;'; 
     139            echo '<label for="wga_custom_var_' . $i . '_scope">' . __( 'Scope', 'wp-google-analytics' ) . '&nbsp;'; 
     140            echo '<select id="wga_custom_var_' . $i . '_scope" name="wga[custom_vars][' . $i . '][scope]">'; 
     141            foreach( $scope_options as $key => $label ) { 
     142                echo '<option value="' . $key . '" ' . selected( $scope, $key, false ) . '>'; 
     143                echo $label . '</option>'; 
     144            } 
     145            echo '</select>'; 
     146            echo '</label><br />'; 
     147        } 
     148    } 
     149 
     150    public function field_do_not_track() { 
     151        $do_not_track = array( 
     152                'ignore_admin_area'       => __( 'Do not log anything in the admin area', 'wp-google-analytics' ), 
     153            ); 
     154        global $wp_roles; 
     155        foreach( $wp_roles->roles as $role => $role_info ) { 
     156            $do_not_track['ignore_role_' . $role] = sprintf( __( 'Do not log %s when logged in', 'wp-google-analytics' ), rtrim( $role_info['name'], 's' ) ); 
     157        } 
     158        foreach( $do_not_track as $id => $label ) { 
     159            echo '<label for="wga_' . $id . '">'; 
     160            echo '<input id="wga_' . $id . '" type="checkbox" name="wga[' . $id . ']" value="true" ' . checked( 'true', $this->_get_options( $id ), false ) . ' />'; 
     161            echo '&nbsp;&nbsp;' . $label; 
     162            echo '</label><br />'; 
     163        } 
     164    } 
     165 
     166    /** 
     167     * Sanitize all of the options associated with the plugin 
     168     */ 
     169    public function sanitize_general_options( $in ) { 
     170 
     171        $out = array(); 
     172 
     173        // The actual tracking ID 
     174        if ( preg_match( '#UA-[\d-]+#', $in['code'], $matches ) ) 
     175            $out['code'] = $matches[0]; 
     176        else 
     177            $out['code'] = ''; 
     178 
     179        $checkbox_items = array( 
     180                // Additional items you can track 
     181                'log_404s', 
     182                'log_searches', 
     183                'log_outgoing', 
     184                // Things to ignore 
     185                'ignore_admin_area', 
     186            ); 
     187        global $wp_roles; 
     188        foreach( $wp_roles->roles as $role => $role_info ) { 
     189            $checkbox_items[] = 'ignore_role_' . $role; 
     190        } 
     191        foreach( $checkbox_items as $checkbox_item ) { 
     192            if ( isset( $in[$checkbox_item] ) && 'true' == $in[$checkbox_item] ) 
     193                $out[$checkbox_item] = 'true'; 
     194            else 
     195                $out[$checkbox_item] = 'false'; 
     196        } 
     197 
     198        // Custom variables 
     199        for( $i = 1; $i <= 5; $i++ ) { 
     200            foreach( array( 'name', 'value', 'scope' ) as $key ) { 
     201                if ( isset( $in['custom_vars'][$i][$key] ) ) 
     202                    $out['custom_vars'][$i][$key] = sanitize_text_field( $in['custom_vars'][$i][$key] ); 
     203                else 
     204                    $out['custom_vars'][$i][$key] = ''; 
     205            } 
     206        } 
     207 
     208        return $out; 
    46209    } 
    47210 
     
    49212     * This is used to display the options page for this plugin 
    50213     */ 
    51     function options() { 
    52         /** 
    53          * @var WP_Roles 
    54          */ 
    55         global $wp_roles; 
    56  
    57         //Get our options 
    58         $wga = wpGoogleAnalytics::get_options(); 
    59         //Echo debug info if needed 
    60         if (WGA_DEBUG) { 
    61             echo '<pre>',var_dump($wga),'</pre>'; 
    62         } 
    63         //We will fill $roles with checkboxes to ignore each role 
    64         $roles = ''; 
    65         foreach ($wp_roles->roles as $role=>$role_info) { 
    66             $checked = (isset($role_info['capabilities']['wga_no_track']) && $role_info['capabilities']['wga_no_track'])? ' checked="checked"':''; 
    67             $role_info['name'] .= (strtolower(substr($role_info['name'], -1)) != 's')? 's':''; 
    68             $roles .= "                 <label for='wga_role_{$role}'><input type='checkbox' name='wga-roles[{$role}]' value='true' id='wga_role_{$role}'{$checked} /> ".__("Do not log {$role_info['name']} when logged in")."</label><br />"; 
    69         } 
     214    public function settings_view() { 
    70215?> 
    71216        <div class="wrap"> 
    72             <h2><?php _e('Google Analytics Options') ?></h2> 
     217            <h2><?php _e('Google Analytics Options', 'wp-google-analytics') ?></h2> 
    73218            <form action="options.php" method="post" id="wp_google_analytics"> 
    74                 <?php wp_nonce_field('update-options'); ?> 
    75                 <p>Google Maps for WordPress will allow you to easily add maps to your posts or pages.</p> 
    76                 <table class="form-table"> 
    77                     <tr valign="top"> 
    78                         <th scope="row"> 
    79                             <label for="wga_code"><?php _e('Paste your <a href="http://analytics.google.com">Google Analytics</a> code into the textarea:'); ?></label> 
    80                         </th> 
    81                         <td> 
    82                             <textarea name="wga[code]" id="wga_code" style="width:95%;" rows="10"><?php echo htmlentities($wga['code']); ?></textarea> 
    83                         </td> 
    84                     </tr> 
    85                     <tr valign="top"> 
    86                         <th scope="row"> 
    87                             <?php _e('Additional items to log:') ?> 
    88                         </th> 
    89                         <td> 
    90                             <label for="wga_log_404s"><input type="checkbox" name="wga[log_404s]" value="true" id="wga_log_404s"<?php checked('true', $wga['log_404s']); ?> /> <?php _e('Log 404 errors as /404/{url}?referrer={referrer}'); ?></label><br /> 
    91                             <label for="wga_log_searches"><input type="checkbox" name="wga[log_searches]" value="true" id="wga_log_searches"<?php checked('true', $wga['log_searches']); ?> /> <?php _e('Log searches as /search/{search}?referrer={referrer}'); ?></label><br /> 
    92                             <label for="wga_log_outgoing"><input type="checkbox" name="wga[log_outgoing]" value="true" id="wga_log_outgoing"<?php checked('true', $wga['log_outgoing']); ?> /> <?php _e('Log outgoing links as /outgoing/{url}?referrer={referrer}'); ?></label><br /> 
    93                         </td> 
    94                     </tr> 
    95                     <tr valign="top"> 
    96                         <th scope="row"> 
    97                             <?php _e('Visits to ignore:') ?> 
    98                         </th> 
    99                         <td> 
    100                             <label for="wga_ignore_admin_area"><input type="checkbox" name="wga[ignore_admin_area]" value="true" id="wga_ignore_admin_area"<?php checked('true', $wga['ignore_admin_area']); ?> /> <?php _e('Do not log anything in the admin area'); ?></label><br /> 
    101 <?php echo $roles; ?> 
    102                         </td> 
    103                     </tr> 
    104                 </table> 
    105                 <p class="submit"> 
    106                     <input type="submit" name="Submit" value="<?php _e('Update Options &raquo;'); ?>" /> 
    107                 </p> 
    108                 <input type="hidden" name="action" value="update" /> 
    109                 <input type="hidden" name="page_options" value="wga,wga-roles" /> 
     219                <?php 
     220                    settings_fields( 'wga' ); 
     221                    do_settings_sections( 'wga' ); 
     222                    submit_button( __( 'Update Options', 'wp-google-analytics' ) ); 
     223                ?> 
    110224            </form> 
    111225        </div> 
     
    119233     * @return string - Tracking URL 
    120234     */ 
    121     function get_url($track) { 
     235    private function _get_url($track) { 
    122236        $site_url = ( is_ssl() ? 'https://':'http://' ).$_SERVER['HTTP_HOST']; 
    123237        foreach ($track as $k=>$value) { 
     
    143257 
    144258    /** 
     259     * Maybe output or return, depending on the context 
     260     */ 
     261    private function _output_or_return( $val, $maybe ) { 
     262        if ( $maybe ) 
     263            echo $val . "\r\n"; 
     264        else 
     265            return $val; 
     266    } 
     267 
     268    /** 
    145269     * This injects the Google Analytics code into the footer of the page. 
    146270     * 
    147271     * @param bool[optional] $output - defaults to true, false returns but does NOT echo the code 
    148272     */ 
    149     function insert_code($output=true) { 
     273    public function insert_code( $output = true ) { 
    150274        //If $output is not a boolean false, set it to true (default) 
    151275        $output = ($output !== false); 
    152276 
     277        $tracking_id = $this->_get_options( 'code' ); 
     278        if ( empty( $tracking_id ) ) 
     279            return $this->_output_or_return( '<!-- Your Google Analytics Plugin is missing the tracking ID -->', $output ); 
     280 
    153281        //get our plugin options 
    154         $wga = wpGoogleAnalytics::get_options(); 
     282        $wga = $this->_get_options(); 
    155283        //If the user's role has wga_no_track set to true, return without inserting code 
    156         if (current_user_can('wga_no_track')) { 
    157             $ret = "<!-- Google Analytics Plugin is set to ignore your user role -->\r\n"; 
    158             if ($output) { 
    159                 echo $ret; 
    160             } 
    161             return $ret; 
    162         } 
    163         //If the Google Analytics code has been set 
    164         if ($wga['code'] !== false) { 
    165             //Echo debug info if needed 
    166             if (WGA_DEBUG) { 
    167                 echo '<pre>',var_dump($wga),'</pre>'; 
    168             } 
    169  
    170             //If $admin is true (we're in the admin_area), and we've been told to ignore_admin_area, return without inserting code 
    171             if (is_admin() && (!isset($wga['ignore_admin_area']) || $wga['ignore_admin_area'] != 'false')) { 
    172                 $ret = "<!-- Your Google Analytics Plugin is set to ignore Admin area -->\r\n"; 
    173                 if ($output) { 
    174                     echo $ret; 
    175                 } 
    176                 return $ret; 
    177             } elseif (is_404() && (!isset($wga['log_404s']) || $wga['log_404s'] != 'false')) { 
    178                 //Set track for 404s, if it's a 404, and we are supposed to 
    179                 $track['data'] = $_SERVER['REQUEST_URI']; 
    180                 $track['code'] = '404'; 
    181             } elseif (is_search() && (!isset($wga['log_searches']) || $wga['log_searches'] != 'false')) { 
    182                 //Set track for searches, if it's a search, and we are supposed to 
    183                 $track['data'] = $_REQUEST['s']; 
    184                 $track['code'] = "search"; 
    185             } 
    186  
    187             //If we need to generate a special tracking URL 
    188             if (isset($track)) { 
    189                 //get the tracking URL 
    190                 $track['url'] = wpGoogleAnalytics::get_url($track); 
    191  
    192                 //adjust the code that we output, account for both types of tracking 
    193                 $track['url'] = str_replace('&', '&amp;', $track['url']); 
    194                 $wga['code'] = str_replace("urchinTracker()","urchinTracker('{$track['url']}')", $wga['code']); 
    195                 $wga['code'] = str_replace("pageTracker._trackPageview()","pageTracker._trackPageview('{$track['url']}')", $wga['code']); 
    196  
    197                 //Echo debug info if needed 
    198                 if (WGA_DEBUG) { 
    199                     echo '<pre>',var_dump($track, $site_url),'</pre>'; 
    200                 } 
    201             } 
    202             //output the Google Analytics code 
    203             if ($output) { 
    204                 echo $wga['code']; 
    205             } 
    206             return $wga['code']; 
     284        if ( is_user_logged_in() ) { 
     285            $current_user = wp_get_current_user(); 
     286            $role = array_shift( $current_user->roles ); 
     287            if ( 'true' == $this->_get_options( 'ignore_role_' . $role ) ) 
     288                return $this->_output_or_return( "<!-- Google Analytics Plugin is set to ignore your user role -->", $output ); 
     289        } 
     290 
     291        //If $admin is true (we're in the admin_area), and we've been told to ignore_admin_area, return without inserting code 
     292        if (is_admin() && (!isset($wga['ignore_admin_area']) || $wga['ignore_admin_area'] != 'false')) 
     293            return $this->_output_or_return( "<!-- Your Google Analytics Plugin is set to ignore Admin area -->", $output ); 
     294 
     295        $custom_vars = array( 
     296            "_gaq.push(['_setAccount', '{$tracking_id}']);", 
     297        ); 
     298 
     299        $track = array(); 
     300        if (is_404() && (!isset($wga['log_404s']) || $wga['log_404s'] != 'false')) { 
     301            // This is a 404 and we are supposed to track them 
     302            $custom_vars[] = "_gaq.push( [ '_trackEvent', '404', document.location.href, document.referrer ] );"; 
     303        } elseif (is_search() && (!isset($wga['log_searches']) || $wga['log_searches'] != 'false')) { 
     304            //Set track for searches, if it's a search, and we are supposed to 
     305            $track['data'] = $_REQUEST['s']; 
     306            $track['code'] = "search"; 
     307        } 
     308 
     309        if ( ! empty( $track ) ) { 
     310            $track['url'] = $this->_get_url( $track ); 
     311            //adjust the code that we output, account for both types of tracking 
     312            $track['url'] = esc_js( str_replace( '&', '&amp;', $track['url'] ) ); 
     313            $custom_vars[] = "_gaq.push(['_trackPageview','{$track['url']}']);"; 
    207314        } else { 
    208             //If the Google Analytics code has not been set in admin area, return without inserting code 
    209             $ret = "<!-- You need to set up the Google Analytics Plugin -->\r\n"; 
    210             if ($output) { 
    211                 echo $ret; 
    212             } 
    213             return $ret; 
    214         } 
     315            $custom_vars[] = "_gaq.push(['_trackPageview']);"; 
     316        } 
     317 
     318        // Add custom variables specified by the user 
     319        foreach( $this->_get_options( 'custom_vars', array() ) as $i => $custom_var ) { 
     320            if ( empty( $custom_var['name'] ) || empty( $custom_var['value'] ) ) 
     321                continue; 
     322            $atts = array( 
     323                    "'_setCustomVar'", 
     324                    intval( $i ), 
     325                    "'" . esc_js( $custom_var['name'] ) . "'", 
     326                    "'" . esc_js( $custom_var['value'] ) . "'", 
     327                ); 
     328            if ( $custom_var['scope'] ) 
     329                $atts[] = intval( $custom_var['scope'] ); 
     330            $custom_vars[] = "_gaq.push([" . implode( ', ', $atts ) . "]);"; 
     331        } 
     332 
     333        $async_code = "<script type='text/javascript'> 
     334    var _gaq = _gaq || []; 
     335    %custom_vars% 
     336 
     337    (function() { 
     338        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; 
     339        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; 
     340        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); 
     341    })(); 
     342</script>"; 
     343        $custom_vars_string = implode( "\r\n", $custom_vars ); 
     344        $async_code = str_replace( '%custom_vars%', $custom_vars_string, $async_code ); 
     345 
     346        return $this->_output_or_return( $async_code, $output ); 
     347 
    215348    } 
    216349 
     
    221354     * @return array of options, or option value 
    222355     */ 
    223     function get_options($option = null) { 
     356    private function _get_options( $option = null, $default = false ) { 
     357 
    224358        $o = get_option('wga'); 
     359 
    225360        if (isset($option)) { 
     361 
    226362            if (isset($o[$option])) { 
    227                 return $o[$option]; 
     363                if ( 'code' == $option ) { 
     364                    if ( preg_match( '#UA-[\d-]+#', $o[$option], $matches ) ) 
     365                        return $matches[0]; 
     366                    else 
     367                        return ''; 
     368                } else 
     369                    return $o[$option]; 
    228370            } else { 
    229                 return false; 
     371                if ( 'ignore_role_' == substr( $option, 0, 12 ) ) { 
     372                    global $wp_roles; 
     373                    // Backwards compat for when the tracking information was stored as a cap 
     374                    $maybe_role = str_replace( 'ignore_role_', '', $option ); 
     375                    if ( isset( $wp_roles->roles[$maybe_role] ) ) { 
     376                        if ( isset( $wp_roles->roles[$maybe_role]['capabilities']['wga_no_track'] ) && $wp_roles->roles[$maybe_role]['capabilities']['wga_no_track'] ) 
     377                            return 'true'; 
     378                    } 
     379                    return false; 
     380                } 
     381                return $default; 
    230382            } 
    231383        } else { 
     
    235387 
    236388    /** 
    237      * Start our output buffering with a callback, to grab all links 
    238      * 
    239      * @todo If there is a good way to tell if this is a feed, add a seperate option for tracking outgoings on feeds 
    240      */ 
    241     function start_ob() { 
    242         $log_outgoing = wpGoogleAnalytics::get_options('log_outgoing'); 
    243         // Only start the output buffering if we care, and if it's NOT an XMLRPC REQUEST & NOT a tinyMCE JS file & NOT in the admin section 
    244         if (($log_outgoing == 'true' || $log_outgoing === false) && (!defined('XMLRPC_REQUEST') || !XMLRPC_REQUEST) && !is_admin() && stripos($_SERVER['REQUEST_URI'], 'wp-includes/js/tinymce') === false) { 
    245             ob_start(array('wpGoogleAnalytics', 'get_links')); 
    246         } 
    247     } 
    248  
    249     /** 
    250      * Grab all links on the page.  If the code hasn't been inserted, we want to 
    251      * insert it just before the </body> tag 
    252      * 
    253      * @param string $b - buffer contents 
    254      * @return string - modified buffer contents 
    255      */ 
    256     function get_links($b) { 
    257         $b = preg_replace_callback("/ 
    258             <\s*a                           # anchor tag 
    259                 (?:\s[^>]*)?        # other attibutes that we don't need 
    260                 \s*href\s*=\s*  # href (required) 
    261                 (?: 
    262                     \"([^\"]*)\"    # double quoted link 
    263                 | 
    264                     '([^']*)'           # single quoted link 
    265                 | 
    266                     ([^'\"\s]*)     # unquoted link 
    267                 ) 
    268                 (?:\s[^>]*)?        # other attibutes that we don't need 
    269                 \s*>                        #end of anchor tag 
    270             /isUx", array('wpGoogleAnalytics', 'handle_link'), $b); 
    271         return $b; 
    272     } 
    273  
    274     /** 
    275      * If a link is outgoing, add an onclick that runs some Google JS with a 
    276      * generated URL 
    277      * 
    278      * @param array $m - A match from the preg_replace_callback in self::get_links 
    279      * @return string - modified andchor tag 
    280      */ 
    281     function handle_link($m) { 
    282         $code = wpGoogleAnalytics::get_options('code'); 
    283         //get our site url...used to see if the link is outgoing.  We can't use the wordpress setting, because wordpress might not be running at the document root. 
    284         $site_url = ( is_ssl() ? 'https://':'http://').$_SERVER['HTTP_HOST']; 
    285         $link = array_pop($m); 
    286         //If the link is outgoing, we modify $m[0] (the anchor tag) 
    287         if (preg_match("/^https?:\/\//i", $link) && (strpos(strtolower($link), strtolower($site_url)) !== 0 )) { 
    288             //get our custom link 
    289             $track['data'] = $link; 
    290             $track['code'] = 'outgoing'; 
    291             $track['url'] = wpGoogleAnalytics::get_url($track); 
    292  
    293             // Check which version of the code the user is using, and user proper function 
    294             $function = (strpos($code, 'ga.js') !== false)? 'pageTracker._trackPageview': 'urchinTracker'; 
    295             $onclick = "{$function}('{$track['url']}');"; 
    296  
    297             //If there is already an onclick, add to the beginning of it (adding to the end will not work, because too many people leave off the ; from the last statement) 
    298             if (preg_match("/onclick\s*=\s*(['\"])/iUx",$m[0],$match)) { 
    299                 //If the onclick uses single quotes, we use double...and vice versa 
    300                 if ($match[1] == "'" ) { 
    301                     $onclick = str_replace("'", '"', $onclick); 
    302                 } 
    303                 $m[0] = str_replace($match[0], $match[0].$onclick, $m[0]); 
    304             } else { 
    305                 $m[0] = str_replace('>', " onclick=\"{$onclick}\">", $m[0]); 
    306             } 
    307         } 
    308         //return the anchor tag (modified or not) 
    309         return $m[0]; 
    310     } 
    311  
    312     function updateOption($oldValue, $newValue) { 
    313         /** 
    314          * @var WP_Roles 
    315          */ 
    316         global $wp_roles; 
    317  
    318         //Add/remove wga_no_track capability for each role 
    319         foreach ($wp_roles->roles as $role=>$role_info) { 
    320             if (isset($newValue[$role]) && $newValue[$role] == 'true') { 
    321                 $wp_roles->add_cap($role, 'wga_no_track', true); 
    322             } else { 
    323                 $wp_roles->add_cap($role, 'wga_no_track', false); 
    324             } 
    325         } 
    326     } 
    327  
    328     function activatePlugin() { 
    329         // If the wga-id has not been generated, generate one and store it. 
    330         $o = get_option('wga'); 
    331         if (!isset($o['user_agreed_to_send_system_information'])) { 
    332             $o['user_agreed_to_send_system_information'] = 'true'; 
    333             update_option('wga', $o); 
    334         } 
    335     } 
     389     * If we track outgoing links, this will enqueue our javascript file 
     390     */ 
     391    public function track_outgoing() { 
     392        $wga = $this->_get_options(); 
     393        if ( 'true' == $wga['log_outgoing'] && (!defined('XMLRPC_REQUEST') || !XMLRPC_REQUEST) && ( ! is_admin() || $wga['ignore_admin_area'] == 'false') ) 
     394            wp_enqueue_script( 'wp-google-analytics', plugin_dir_url( __FILE__ ) . 'wp-google-analytics.js', array( 'jquery' ), '0.0.3' ); 
     395    } 
     396 
    336397} 
    337398 
    338 /** 
    339  * Add the necessary hooks 
    340  */ 
    341 add_action('admin_menu', array('wpGoogleAnalytics','admin_menu')); 
    342 add_action('get_footer', array('wpGoogleAnalytics', 'insert_code')); 
    343 add_action('init', array('wpGoogleAnalytics', 'start_ob')); 
    344 add_action('update_option_wga-roles', array('wpGoogleAnalytics', 'updateOption'), null, 2); 
    345 add_action('activate_wp-google-analytics/wp-google-analytics.php', array('wpGoogleAnalytics', 'activatePlugin')); 
    346 ?> 
     399global $wp_google_analytics; 
     400$wp_google_analytics = wpGoogleAnalytics::get_instance(); 
Note: See TracChangeset for help on using the changeset viewer.