From cadea1b54a8b42987e64778af1637f198f271add Sat, 6 Apr 2013 00:33:18 +0200
From: hass <hass@85918.no-reply.drupal.org>
Date: Sat, 6 Apr 2013 00:32:55 +0200
Subject: [PATCH] D8 Upgrade

diff --git a/config/google_analytics.settings.yml b/config/google_analytics.settings.yml
new file mode 100644
index 0000000..c26e9ee
--- /dev/null
+++ b/config/google_analytics.settings.yml
@@ -0,0 +1,29 @@
+account: 'UA-'
+domain_mode: '0'
+cross_domains: ''
+visibility:
+  pages_enabled: '0'
+  pages: 'admin\nadmin/*\nbatch\nnode/add*\nnode/*/*\nuser/*/*'
+  roles_enabled: '0'
+  roles:
+  custom: '0'
+track:
+  outbound: '1'
+  mailto: '1'
+  files: '1'
+  files_extensions: '7z|aac|arc|arj|asf|asx|avi|bin|csv|doc|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls|xml|z|zip'
+  messages:
+  site_search: '0'
+  adsense: '0'
+  doubleclick: '0'
+privacy:
+  anonymizeip: '1'
+  donottrack: '1'
+codesnippet:
+  before: ''
+  after: ''
+translation_set: '0'
+js_scope: 'header'
+cache: '0'
+last_cache: '0'
+custom_var:
diff --git a/google_analytics.admin.inc b/google_analytics.admin.inc
index 95716b3..0fd28c2 100644
--- a/google_analytics.admin.inc
+++ b/google_analytics.admin.inc
@@ -6,470 +6,6 @@
  */
 
 /**
- * Implements hook_admin_settings() for module settings configuration.
- */
-function googleanalytics_admin_settings_form($form_state) {
-  $form['account'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('General settings'),
-  );
-
-  $form['account']['googleanalytics_account'] = array(
-    '#title' => t('Web Property ID'),
-    '#type' => 'textfield',
-    '#default_value' => variable_get('googleanalytics_account', 'UA-'),
-    '#size' => 15,
-    '#maxlength' => 20,
-    '#required' => TRUE,
-    '#description' => t('This ID is unique to each site you want to track separately, and is in the form of UA-xxxxxxx-yy. To get a Web Property ID, <a href="@analytics">register your site with Google Analytics</a>, or if you already have registered your site, go to your Google Analytics Settings page to see the ID next to every site profile. <a href="@webpropertyid">Find more information in the documentation</a>.', array('@analytics' => 'http://www.google.com/analytics/', '@webpropertyid' => url('https://developers.google.com/analytics/resources/concepts/gaConceptsAccounts', array('fragment' => 'webProperty')))),
-  );
-
-  // Visibility settings.
-  $form['tracking_title'] = array(
-    '#type' => 'item',
-    '#title' => t('Tracking scope'),
-  );
-  $form['tracking'] = array(
-    '#type' => 'vertical_tabs',
-    '#attached' => array(
-      'js' => array(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.admin.js'),
-    ),
-  );
-
-  $form['tracking']['domain_tracking'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Domains'),
-  );
-
-  global $cookie_domain;
-  $multiple_sub_domains = array();
-  foreach (array('www', 'app', 'shop') as $subdomain) {
-    if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
-      $multiple_sub_domains[] = $subdomain . $cookie_domain;
-    }
-    // IP addresses or localhost.
-    else {
-      $multiple_sub_domains[] = $subdomain . '.example.com';
-    }
-  }
-
-  $multiple_toplevel_domains = array();
-  foreach (array('.com', '.net', '.org') as $tldomain) {
-    $host = $_SERVER['HTTP_HOST'];
-    $domain = substr($host, 0, strrpos($host, '.'));
-    if (count(explode('.', $host)) > 2 && !is_numeric(str_replace('.', '', $host))) {
-      $multiple_toplevel_domains[] = $domain . $tldomain;
-    }
-    // IP addresses or localhost
-    else {
-      $multiple_toplevel_domains[] = 'www.example' . $tldomain;
-    }
-  }
-
-  $form['tracking']['domain_tracking']['googleanalytics_domain_mode'] = array(
-    '#type' => 'radios',
-    '#title' => t('What are you tracking?'),
-    '#options' => array(
-      0 => t('A single domain (default)') . '<div class="description">' . t('Domain: @domain', array('@domain' => $_SERVER['HTTP_HOST'])) . '</div>',
-      1 => t('One domain with multiple subdomains') . '<div class="description">' . t('Examples: @domains', array('@domains' => implode(', ', $multiple_sub_domains))) . '</div>',
-      2 => t('Multiple top-level domains') . '<div class="description">' . t('Examples: @domains', array('@domains' => implode(', ', $multiple_toplevel_domains))) . '</div>',
-    ),
-    '#default_value' => variable_get('googleanalytics_domain_mode', 0),
-  );
-  $form['tracking']['domain_tracking']['googleanalytics_cross_domains'] = array(
-    '#title' => t('List of top-level domains'),
-    '#type' => 'textarea',
-    '#default_value' => variable_get('googleanalytics_cross_domains', ''),
-    '#description' => t('If you selected "Multiple top-level domains" above, enter all related top-level domains. Add one domain per line. By default, the data in your reports only includes the path and name of the page, and not the domain name. For more information see section <em>Show separate domain names</em> in <a href="@url">Tracking Multiple Domains</a>.', array('@url' => url('http://support.google.com/analytics/bin/answer.py', array('query' => array('answer' => '1034342'))))),
-  );
-
-  // Page specific visibility configurations.
-  $php_access = user_access('use PHP for tracking visibility');
-  $visibility = variable_get('googleanalytics_visibility_pages', 0);
-  $pages = variable_get('googleanalytics_pages', GOOGLEANALYTICS_PAGES);
-
-  $form['tracking']['page_vis_settings'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Pages'),
-    '#collapsible' => TRUE,
-    '#collapsed' => TRUE,
-  );
-
-  if ($visibility == 2 && !$php_access) {
-    $form['tracking']['page_vis_settings'] = array();
-    $form['tracking']['page_vis_settings']['visibility'] = array('#type' => 'value', '#value' => 2);
-    $form['tracking']['page_vis_settings']['pages'] = array('#type' => 'value', '#value' => $pages);
-  }
-  else {
-    $options = array(
-      t('Every page except the listed pages'),
-      t('The listed pages only'),
-    );
-    $description = t("Specify pages by using their paths. Enter one path per line. The '*' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page.", array('%blog' => 'blog', '%blog-wildcard' => 'blog/*', '%front' => '<front>'));
-
-    if (module_exists('php') && $php_access) {
-      $options[] = t('Pages on which this PHP code returns <code>TRUE</code> (experts only)');
-      $title = t('Pages or PHP code');
-      $description .= ' ' . t('If the PHP option is chosen, enter PHP code between %php. Note that executing incorrect PHP code can break your Drupal site.', array('%php' => '<?php ?>'));
-    }
-    else {
-      $title = t('Pages');
-    }
-    $form['tracking']['page_vis_settings']['googleanalytics_visibility_pages'] = array(
-      '#type' => 'radios',
-      '#title' => t('Add tracking to specific pages'),
-      '#options' => $options,
-      '#default_value' => $visibility,
-    );
-    $form['tracking']['page_vis_settings']['googleanalytics_pages'] = array(
-      '#type' => 'textarea',
-      '#title' => $title,
-      '#title_display' => 'invisible',
-      '#default_value' => $pages,
-      '#description' => $description,
-      '#rows' => 10,
-    );
-  }
-
-  // Render the role overview.
-  $form['tracking']['role_vis_settings'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Roles'),
-  );
-
-  $form['tracking']['role_vis_settings']['googleanalytics_visibility_roles'] = array(
-    '#type' => 'radios',
-    '#title' => t('Add tracking for specific roles'),
-    '#options' => array(
-      t('Add to the selected roles only'),
-      t('Add to every role except the selected ones'),
-    ),
-    '#default_value' => variable_get('googleanalytics_visibility_roles', 0),
-  );
-
-  $role_options = array_map('check_plain', user_roles());
-  $form['tracking']['role_vis_settings']['googleanalytics_roles'] = array(
-    '#type' => 'checkboxes',
-    '#title' => t('Roles'),
-    '#default_value' => variable_get('googleanalytics_roles', array()),
-    '#options' => $role_options,
-    '#description' => t('If none of the roles are selected, all users will be tracked. If a user has any of the roles checked, that user will be tracked (or excluded, depending on the setting above).'),
-  );
-
-  // Standard tracking configurations.
-  $form['tracking']['user_vis_settings'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Users'),
-  );
-  $t_permission = array('%permission' => t('opt-in or out of tracking'));
-  $form['tracking']['user_vis_settings']['googleanalytics_custom'] = array(
-    '#type' => 'radios',
-    '#title' => t('Allow users to customize tracking on their account page'),
-    '#options' => array(
-      t('No customization allowed'),
-      t('Tracking on by default, users with %permission permission can opt out', $t_permission),
-      t('Tracking off by default, users with %permission permission can opt in', $t_permission),
-    ),
-    '#default_value' => variable_get('googleanalytics_custom', 0),
-  );
-
-  // Link specific configurations.
-  $form['tracking']['linktracking'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Links and downloads'),
-  );
-  $form['tracking']['linktracking']['googleanalytics_trackoutbound'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Track clicks on outbound links'),
-    '#default_value' => variable_get('googleanalytics_trackoutbound', 1),
-  );
-  $form['tracking']['linktracking']['googleanalytics_trackmailto'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Track clicks on mailto links'),
-    '#default_value' => variable_get('googleanalytics_trackmailto', 1),
-  );
-  $form['tracking']['linktracking']['googleanalytics_trackfiles'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Track downloads (clicks on file links) for the following extensions'),
-    '#default_value' => variable_get('googleanalytics_trackfiles', 1),
-  );
-  $form['tracking']['linktracking']['googleanalytics_trackfiles_extensions'] = array(
-    '#title' => t('List of download file extensions'),
-    '#title_display' => 'invisible',
-    '#type' => 'textfield',
-    '#default_value' => variable_get('googleanalytics_trackfiles_extensions', GOOGLEANALYTICS_TRACKFILES_EXTENSIONS),
-    '#description' => t('A file extension list separated by the | character that will be tracked as download when clicked. Regular expressions are supported. For example: !extensions', array('!extensions' => GOOGLEANALYTICS_TRACKFILES_EXTENSIONS)),
-    '#maxlength' => 255,
-  );
-
-  // Message specific configurations.
-  $form['tracking']['messagetracking'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Messages'),
-  );
-  $form['tracking']['messagetracking']['googleanalytics_trackmessages'] = array(
-    '#type' => 'checkboxes',
-    '#title' => t('Track messages of type'),
-    '#default_value' => variable_get('googleanalytics_trackmessages', array()),
-    '#description' => t('This will track the selected message types shown to users. Tracking of form validation errors may help you identifying usability issues in your site. For each visit (user session), a maximum of approximately 500 combined GATC requests (both events and page views) can be tracked. Every message is tracked as one individual event. Note that - as the number of events in a session approaches the limit - additional events might not be tracked. Messages from excluded pages cannot tracked.'),
-    '#options' => array(
-      'status' => t('Status message'),
-      'warning' => t('Warning message'),
-      'error' => t('Error message'),
-    ),
-  );
-
-  // Google already have many translations, if not - they display a note to change the language.
-  global $language;
-  $form['tracking']['search_and_advertising'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Search and Advertising'),
-  );
-
-  $site_search_dependencies = '<div class="admin-requirements">';
-  $site_search_dependencies .= t('Requires: !module-list', array('!module-list' => (module_exists('search') ? t('@module (<span class="admin-enabled">enabled</span>)', array('@module' => 'Search')) : t('@module (<span class="admin-disabled">disabled</span>)', array('@module' => 'Search')))));
-  $site_search_dependencies .= '</div>';
-
-  $form['tracking']['search_and_advertising']['googleanalytics_site_search'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Track internal search'),
-    '#description' => t('If checked, internal search keywords are tracked. You must configure your Google account to use the internal query parameter <strong>search</strong>. For more information see <a href="@url">Setting Up Site Search for a Profile</a>.', array('@url' => url('http://support.google.com/analytics/bin/answer.py', array('query' => array('answer' => '1012264'))))) . $site_search_dependencies,
-    '#default_value' => variable_get('googleanalytics_site_search', FALSE),
-    '#disabled' => (module_exists('search') ? FALSE : TRUE),
-  );
-  /* @todo: not supported, https://support.google.com/analytics/bin/answer.py?hl=en&hlrm=de&answer=2795983
-  $form['tracking']['search_and_advertising']['googleanalytics_trackadsense'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Track AdSense ads'),
-    '#description' => t('If checked, your AdSense ads will be tracked in your Google Analytics account.'),
-    '#default_value' => variable_get('googleanalytics_trackadsense', FALSE),
-  );
-  $form['tracking']['search_and_advertising']['googleanalytics_trackdoubleclick'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Track DoubleClick data'),
-    '#description' => t('If checked, the alternative Google <a href="@doubleclick">DoubleClick data tracking</a> is used to enable AdWords remarketing features. If you choose this option you will need to <a href="@privacy">update your privacy policy</a>.', array('@doubleclick' => url('http://support.google.com/analytics/bin/answer.py', array('query' => array('answer' => '2444872'))), '@privacy' => url('http://support.google.com/analytics/bin/answer.py', array('query' => array('answer' => '2636405'))))),
-    '#default_value' => variable_get('googleanalytics_trackdoubleclick', FALSE),
-  ); */
-
-  // Privacy specific configurations.
-  $form['tracking']['privacy'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Privacy'),
-  );
-  $form['tracking']['privacy']['googleanalytics_tracker_anonymizeip'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Anonymize visitors IP address'),
-    '#description' => t('Tell Google Analytics to anonymize the information sent by the tracker objects by removing the last octet of the IP address prior to its storage. Note that this will slightly reduce the accuracy of geographic reporting. In some countries it is not allowed to collect personally identifying information for privacy reasons and this setting may help you to comply with the local laws.'),
-    '#default_value' => variable_get('googleanalytics_tracker_anonymizeip', 0),
-  );
-  $form['tracking']['privacy']['googleanalytics_privacy_donottrack'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Universal web tracking opt-out'),
-    '#description' => t('If enabled and your server receives the <a href="@donottrack">Do-Not-Track</a> header from the client browser, the Google Analytics module will not embed any tracking code into your site. Compliance with Do Not Track could be purely voluntary, enforced by industry self-regulation, or mandated by state or federal law. Please accept your visitors privacy. If they have opt-out from tracking and advertising, you should accept their personal decision. This feature is currently limited to logged in users and disabled page caching.', array('@donottrack' => 'http://donottrack.us/')),
-    '#default_value' => variable_get('googleanalytics_privacy_donottrack', 1),
-  );
-
-  // Custom variables.
-  /* @todo: Update to custom dimensions.
-  $form['googleanalytics_custom_var'] = array(
-    '#collapsed' => TRUE,
-    '#collapsible' => TRUE,
-    '#description' => t('You can add Google Analytics <a href="@custom_var_documentation">Custom Variables</a> here. These will be added to every page that Google Analytics tracking code appears on. Google Analytics will only accept custom variables if the <em>name</em> and <em>value</em> combined are less than 128 bytes after URL encoding. Keep the names as short as possible and expect long values to get trimmed. You may use tokens in custom variable names and values. Global and user tokens are always available; on node pages, node tokens are also available.', array('@custom_var_documentation' => 'https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCustomVariables')),
-    '#theme' => 'googleanalytics_admin_custom_var_table',
-    '#title' => t('Custom variables'),
-    '#tree' => TRUE,
-    '#type' => 'fieldset',
-  );
-
-  $googleanalytics_custom_vars = variable_get('googleanalytics_custom_var', array());
-
-  // Google Analytics supports up to 5 custom variables.
-  for ($i = 1; $i < 6; $i++) {
-    $form['googleanalytics_custom_var']['slots'][$i]['slot'] = array(
-      '#default_value' => $i,
-      '#description' => t('Slot number'),
-      '#disabled' => TRUE,
-      '#size' => 1,
-      '#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
-      '#title_display' => 'invisible',
-      '#type' => 'textfield',
-    );
-    $form['googleanalytics_custom_var']['slots'][$i]['name'] = array(
-      '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['name']) ? $googleanalytics_custom_vars['slots'][$i]['name'] : '',
-      '#description' => t('The custom variable name.'),
-      '#maxlength' => 255,
-      '#size' => 20,
-      '#title' => t('Custom variable name #@slot', array('@slot' => $i)),
-      '#title_display' => 'invisible',
-      '#type' => 'textfield',
-      '#element_validate' => array('googleanalytics_token_element_validate'),
-      '#token_types' => array('node'),
-    );
-    $form['googleanalytics_custom_var']['slots'][$i]['value'] = array(
-      '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['value']) ? $googleanalytics_custom_vars['slots'][$i]['value'] : '',
-      '#description' => t('The custom variable value.'),
-      '#maxlength' => 255,
-      '#title' => t('Custom variable value #@slot', array('@slot' => $i)),
-      '#title_display' => 'invisible',
-      '#type' => 'textfield',
-      '#element_validate' => array('googleanalytics_token_element_validate'),
-      '#token_types' => array('node'),
-    );
-    if (module_exists('token')) {
-      $form['googleanalytics_custom_var']['slots'][$i]['name']['#element_validate'][] = 'token_element_validate';
-      $form['googleanalytics_custom_var']['slots'][$i]['value']['#element_validate'][] = 'token_element_validate';
-    }
-    $form['googleanalytics_custom_var']['slots'][$i]['scope'] = array(
-      '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['scope']) ? $googleanalytics_custom_vars['slots'][$i]['scope'] : 3,
-      '#description' => t('The scope for the custom variable.'),
-      '#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
-      '#title_display' => 'invisible',
-      '#type' => 'select',
-      '#options' => array(
-        1 => t('Visitor'),
-        2 => t('Session'),
-        3 => t('Page'),
-      ),
-    );
-  }
-
-  $form['googleanalytics_custom_var']['googleanalytics_custom_var_description'] = array(
-    '#type' => 'item',
-    '#description' => t('You can supplement Google Analytics\' basic IP address tracking of visitors by segmenting users based on custom variables. Section 7 of the <a href="@ga_tos">Google Analytics terms of service</a> requires that You will not (and will not allow any third party to) use the Service to track, collect or upload any data that personally identifies an individual (such as a name, email address or billing information), or other data which can be reasonably linked to such information by Google. You will have and abide by an appropriate Privacy Policy and will comply with all applicable laws and regulations relating to the collection of information from Visitors. You must post a Privacy Policy and that Privacy Policy must provide notice of Your use of cookies that are used to collect traffic data, and You must not circumvent any privacy features (e.g., an opt-out) that are part of the Service.', array('@ga_tos' => 'http://www.google.com/analytics/terms/gb.html')),
-  );
-  $form['googleanalytics_custom_var']['googleanalytics_custom_var_token_tree'] = array(
-    '#theme' => 'token_tree',
-    '#token_types' => array('node'),
-    '#dialog' => TRUE,
-  ); */
-
-
-  // Advanced feature configurations.
-  $form['advanced'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Advanced settings'),
-    '#collapsible' => TRUE,
-    '#collapsed' => TRUE,
-  );
-
-  $form['advanced']['googleanalytics_cache'] = array(
-    '#type' => 'checkbox',
-    '#title' => t('Locally cache tracking code file'),
-    '#description' => t("If checked, the tracking code file is retrieved from Google Analytics and cached locally. It is updated daily from Google's servers to ensure updates to tracking code are reflected in the local copy. Do not activate this until after Google Analytics has confirmed that site tracking is working!"),
-    '#default_value' => variable_get('googleanalytics_cache', 0),
-  );
-
-  // Allow for tracking of the originating node when viewing translation sets.
-  if (module_exists('translation')) {
-    $form['advanced']['googleanalytics_translation_set'] = array(
-      '#type' => 'checkbox',
-      '#title' => t('Track translation sets as one unit'),
-      '#description' => t('When a node is part of a translation set, record statistics for the originating node instead. This allows for a translation set to be treated as a single unit.'),
-      '#default_value' => variable_get('googleanalytics_translation_set', 0),
-    );
-  }
-
-  // @todo: Update urls once they are available.
-  $form['advanced']['codesnippet'] = array(
-    '#type' => 'fieldset',
-    '#title' => t('Custom JavaScript code'),
-    '#collapsible' => TRUE,
-    '#collapsed' => TRUE,
-    '#description' => t('You can add custom Google Analytics <a href="@snippets">code snippets</a> here. These will be added every time tracking is in effect. Before you add your custom code, you should read the <a href="@ga_concepts_overview">Google Analytics Tracking Code - Functional Overview</a> and the <a href="@ga_js_api">Google Analytics Tracking API</a> documentation. <strong>Do not include the &lt;script&gt; tags</strong>, and always end your code with a semicolon (;).', array('@snippets' => 'http://drupal.org/node/248699', '@ga_concepts_overview' => 'https://developers.google.com/analytics/resources/concepts/gaConceptsTrackingOverview', '@ga_js_api' => 'https://developers.google.com/analytics/devguides/collection/gajs/methods/')),
-  );
-  $form['advanced']['codesnippet']['googleanalytics_codesnippet_before'] = array(
-    '#type' => 'textarea',
-    '#title' => t('Code snippet (before)'),
-    '#default_value' => variable_get('googleanalytics_codesnippet_before', ''),
-    '#rows' => 5,
-    '#description' => t("Code in this textarea will be added <strong>before</strong> <code>ga('send', 'pageview');</code>."),
-  );
-  $form['advanced']['codesnippet']['googleanalytics_codesnippet_after'] = array(
-    '#type' => 'textarea',
-    '#title' => t('Code snippet (after)'),
-    '#default_value' => variable_get('googleanalytics_codesnippet_after', ''),
-    '#rows' => 5,
-    '#description' => t("Code in this textarea will be added <strong>after</strong> <code>ga('send', 'pageview');</code>. This is useful if you'd like to track a site in two accounts."),
-  );
-
-  $form['advanced']['googleanalytics_js_scope'] = array(
-    '#type' => 'select',
-    '#title' => t('JavaScript scope'),
-    '#description' => t('Google recommends adding the external JavaScript files to the header for performance reasons. If <em>Multiple top-level domains</em> has been selected, this setting will be forced to header.'),
-    '#options' => array(
-      'footer' => t('Footer'),
-      'header' => t('Header'),
-    ),
-    '#default_value' => variable_get('googleanalytics_js_scope', 'header'),
-    '#disabled' => (variable_get('googleanalytics_domain_mode', 0) == 2) ? TRUE : FALSE,
-  );
-
-  return system_settings_form($form);
-}
-
-/**
- * Implements _form_validate().
- */
-function googleanalytics_admin_settings_form_validate($form, &$form_state) {
-  // Custom variables validation.
-  /* @todo: upgrade to custom dimensions
-  foreach ($form_state['values']['googleanalytics_custom_var']['slots'] as $custom_var) {
-    $form_state['values']['googleanalytics_custom_var']['slots'][$custom_var['slot']]['name'] = trim($custom_var['name']);
-    $form_state['values']['googleanalytics_custom_var']['slots'][$custom_var['slot']]['value'] = trim($custom_var['value']);
-
-    // Validate empty names/values.
-    if (empty($custom_var['name']) && !empty($custom_var['value'])) {
-      form_set_error("googleanalytics_custom_var][slots][" . $custom_var['slot'] . "][name", t('The custom variable @slot-number requires a <em>Name</em> if a <em>Value</em> has been provided.', array('@slot-number' =>  $custom_var['slot'])));
-    }
-    elseif (!empty($custom_var['name']) && empty($custom_var['value'])) {
-      form_set_error("googleanalytics_custom_var][slots][" . $custom_var['slot'] . "][value", t('The custom variable @slot-number requires a <em>Value</em> if a <em>Name</em> has been provided.', array('@slot-number' =>  $custom_var['slot'])));
-    }
-  } */
-
-  // Trim some text values.
-  $form_state['values']['googleanalytics_account'] = trim($form_state['values']['googleanalytics_account']);
-  $form_state['values']['googleanalytics_pages'] = trim($form_state['values']['googleanalytics_pages']);
-  $form_state['values']['googleanalytics_cross_domains'] = trim($form_state['values']['googleanalytics_cross_domains']);
-  $form_state['values']['googleanalytics_codesnippet_before'] = trim($form_state['values']['googleanalytics_codesnippet_before']);
-  $form_state['values']['googleanalytics_codesnippet_after'] = trim($form_state['values']['googleanalytics_codesnippet_after']);
-
-  // Replace all type of dashes (n-dash, m-dash, minus) with the normal dashes.
-  $form_state['values']['googleanalytics_account'] = str_replace(array('–', '—', '?'), '-', $form_state['values']['googleanalytics_account']);
-
-  if (!preg_match('/^UA-\d{4,}-\d+$/', $form_state['values']['googleanalytics_account'])) {
-    form_set_error('googleanalytics_account', t('A valid Google Analytics Web Property ID is case sensitive and formatted like UA-xxxxxxx-yy.'));
-  }
-
-  // If multiple top-level domains has been selected, a domain names list is required.
-  if ($form_state['values']['googleanalytics_domain_mode'] == 2 && empty($form_state['values']['googleanalytics_cross_domains'])) {
-    form_set_error('googleanalytics_cross_domains', t('A list of top-level domains is required if <em>Multiple top-level domains</em> has been selected.'));
-  }
-  // Clear obsolete local cache if cache has been disabled.
-  if (empty($form_state['values']['googleanalytics_cache']) && $form['advanced']['googleanalytics_cache']['#default_value']) {
-    googleanalytics_clear_js_cache();
-  }
-
-  // This is for the Newbie's who cannot read a text area description.
-  if (stristr($form_state['values']['googleanalytics_codesnippet_before'], 'google-analytics.com/analytics.js')) {
-    form_set_error('googleanalytics_codesnippet_before', t('Do not add the tracker code provided by Google into the javascript code snippets! This module already builds the tracker code based on your Google Analytics account number and settings.'));
-  }
-  if (stristr($form_state['values']['googleanalytics_codesnippet_after'], 'google-analytics.com/analytics.js')) {
-    form_set_error('googleanalytics_codesnippet_after', t('Do not add the tracker code provided by Google into the javascript code snippets! This module already builds the tracker code based on your Google Analytics account number and settings.'));
-  }
-  if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['googleanalytics_codesnippet_before'])) {
-    form_set_error('googleanalytics_codesnippet_before', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
-  }
-  if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['googleanalytics_codesnippet_after'])) {
-    form_set_error('googleanalytics_codesnippet_after', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
-  }
-
-  // Header section must be forced for multiple top-level domains.
-  if ($form_state['values']['googleanalytics_domain_mode'] == 2) {
-    $form_state['values']['googleanalytics_js_scope'] = 'header';
-  }
-}
-
-/**
  * Layout for the custom variables table in the admin settings form.
  */
 function theme_googleanalytics_admin_custom_var_table($variables) {
diff --git a/google_analytics.install b/google_analytics.install
index b3dd83b..c01ac87 100644
--- a/google_analytics.install
+++ b/google_analytics.install
@@ -8,50 +8,41 @@
 /**
  * Implements hook_install().
  */
-function googleanalytics_install() {
-  // By German laws it's always best to enable the anonymizing of IP addresses.
-  // NOTE: If this is also an important default setting in other countries, please let us know!
-  $countries = array(
-    'DE',
-  );
-  if (in_array(variable_get('site_default_country', ''), $countries)) {
-    variable_set('googleanalytics_tracker_anonymizeip', 1);
-  }
-}
+function google_analytics_install() {
+  // Migrate settings from previous Google Analytics version.
+  update_variables_to_config('google_analytics.settings', array(
+    'googleanalytics_account' => 'account',
+    'googleanalytics_cache' => 'cache',
+    'googleanalytics_codesnippet_before' => 'codesnippet.before',
+    'googleanalytics_codesnippet_after' => 'codesnippet.after',
+    'googleanalytics_cross_domains' => 'cross_domains',
+    //'googleanalytics_custom_var' => 'custom_var',
+    'googleanalytics_domain_mode' => 'domain_mode',
+    'googleanalytics_js_scope' => 'js_scope',
+    'googleanalytics_last_cache' => 'last_cache',
+    'googleanalytics_pages' => 'visibility.pages',
+    'googleanalytics_roles' => 'visibility.roles',
+    'googleanalytics_site_search' => 'track.site_search',
+    'googleanalytics_trackadsense' => 'track.adsense',
+    'googleanalytics_trackdoubleclick' => 'track.doubleclick',
+    'googleanalytics_tracker_anonymizeip' => 'privacy.anonymizeip',
+    'googleanalytics_trackfiles' => 'track.files',
+    'googleanalytics_trackfiles_extensions' => 'track.files_extensions',
+    'googleanalytics_trackmailto' => 'track.mailto',
+    'googleanalytics_trackoutbound' => 'track.outbound',
+    'googleanalytics_translation_set' => 'translation_set',
+    'googleanalytics_visibility_pages' => 'visibility.pages_enabled',
+    'googleanalytics_visibility_roles' => 'visibility.roles_enabled',
+    'googleanalytics_privacy_donottrack' => 'privacy.donottrack',
+  ));
 
-/**
- * Implements hook_uninstall().
- */
-function googleanalytics_uninstall() {
-  variable_del('googleanalytics_account');
-  variable_del('googleanalytics_cache');
-  variable_del('googleanalytics_codesnippet_before');
-  variable_del('googleanalytics_codesnippet_after');
-  variable_del('googleanalytics_cross_domains');
-  variable_del('googleanalytics_custom');
-  variable_del('googleanalytics_custom_var');
-  variable_del('googleanalytics_domain_mode');
-  variable_del('googleanalytics_js_scope');
-  variable_del('googleanalytics_last_cache');
-  variable_del('googleanalytics_pages');
-  variable_del('googleanalytics_roles');
-  variable_del('googleanalytics_site_search');
-  variable_del('googleanalytics_trackadsense'); // @todo
-  variable_del('googleanalytics_trackdoubleclick'); // @todo
-  variable_del('googleanalytics_tracker_anonymizeip');
-  variable_del('googleanalytics_trackfiles');
-  variable_del('googleanalytics_trackfiles_extensions');
-  variable_del('googleanalytics_trackmailto');
-  variable_del('googleanalytics_trackoutbound');
-  variable_del('googleanalytics_translation_set');
-  variable_del('googleanalytics_visibility_pages');
-  variable_del('googleanalytics_visibility_roles');
-  variable_del('googleanalytics_privacy_donottrack');
+  // Remove the 'googleanalytics' directory and cached files.
+  file_unmanaged_delete_recursive('public://googleanalytics');
 
-  // Remove backup variables if exist. Remove this code in D8.
-  variable_del('googleanalytics_codesnippet_after_backup_6300');
-  variable_del('googleanalytics_codesnippet_before_backup_6300');
-  variable_del('googleanalytics_segmentation');
+  // Remove backup variables if exist. No migration required.
+  update_variable_del('googleanalytics_codesnippet_after_backup_6300');
+  update_variable_del('googleanalytics_codesnippet_before_backup_6300');
+  update_variable_del('googleanalytics_segmentation');
 }
 
 /**
@@ -59,23 +50,24 @@
  *
  * Remove cache directory if module is disabled (or uninstalled).
  */
-function googleanalytics_disable() {
+function google_analytics_disable() {
   googleanalytics_clear_js_cache();
 }
 
 /**
  * Implements hook_requirements().
  */
-function googleanalytics_requirements($phase) {
+function google_analytics_requirements($phase) {
   $requirements = array();
   $t = get_t();
 
   if ($phase == 'runtime') {
     // Raise warning if Google user account has not been set yet.
-    if (!preg_match('/^UA-\d{4,}-\d+$/', variable_get('googleanalytics_account', 'UA-'))) {
-      $requirements['googleanalytics'] = array(
+    $config = config('google_analytics.settings');
+    if (!preg_match('/^UA-\d{4,}-\d+$/', $config->get('account'))) {
+      $requirements['google_analytics'] = array(
         'title' => $t('Google Analytics module'),
-        'description' => $t('Google Analytics module has not been configured yet. Please configure its settings from the <a href="@url">Google Analytics settings page</a>.', array('@url' => url('admin/config/system/googleanalytics'))),
+        'description' => $t('Google Analytics module has not been configured yet. Please configure its settings from the <a href="@url">Google Analytics settings page</a>.', array('@url' => url('admin/config/system/google_analytics'))),
         'severity' => REQUIREMENT_WARNING,
         'value' => $t('Not configured'),
       );
@@ -86,235 +78,18 @@
 }
 
 /**
- * Upgrade old extension variable to new and use old name as enabled/disabled flag.
- */
-function googleanalytics_update_6000() {
-  variable_set('googleanalytics_trackfiles_extensions', variable_get('googleanalytics_trackfiles', '7z|aac|avi|csv|doc|exe|flv|gif|gz|jpe?g|js|mp(3|4|e?g)|mov|pdf|phps|png|ppt|rar|sit|tar|torrent|txt|wma|wmv|xls|xml|zip'));
-  $trackfiles = variable_get('googleanalytics_trackfiles', '7z|aac|avi|csv|doc|exe|flv|gif|gz|jpe?g|js|mp(3|4|e?g)|mov|pdf|phps|png|ppt|rar|sit|tar|torrent|txt|wma|wmv|xls|xml|zip') ? TRUE : FALSE;
-  variable_set('googleanalytics_trackfiles', $trackfiles);
-
-  return t('Updated download tracking file extensions.');
-}
-
-function googleanalytics_update_6001() {
-  variable_set('googleanalytics_visibility', 0);
-
-  // Remove tracking from all administrative pages, see http://drupal.org/node/34970.
-  $pages = array(
-    'admin*',
-    'user*',
-    'node/add*',
-    'node/*/*',
-  );
-  variable_set('googleanalytics_pages', implode("\n", $pages));
-
-  return t('Added page tracking to every page except the listed pages: @pages.', array('@pages' => implode(', ', $pages)));
-}
-
-/**
- * Upgrade role settings and per user tracking settings
- * of "User 1" and remove outdated tracking variables.
- */
-function googleanalytics_update_6002() {
-  // Upgrade enabled/disabled roles to new logic (correct for upgrades from 5.x-1.4 and 6.x-1.0).
-  $roles = array();
-  $messages = array();
-  foreach (user_roles() as $rid => $name) {
-    if (variable_get('googleanalytics_track_' . $rid, FALSE)) {
-      // Role ID is activated for user tracking.
-      $roles[$rid] = $rid;
-      $messages[] = t('Enabled page tracking for role: @name.', array('@name' => $name));
-    }
-    else {
-      $messages[] = t('Disabled page tracking for role: @name.', array('@name' => $name));
-    }
-  }
-  variable_set('googleanalytics_roles', $roles);
-
-  // Upgrade disabled tracking of "user 1" to new logic.
-  if (!$track_user1 = variable_get('googleanalytics_track__user1', 1)) {
-    variable_set('googleanalytics_custom', 1);
-
-    // Load user 1 object, set appropriate value and save new user settings back.
-    $account = user_load(1);
-    $account = user_save($account, array('data' => array('googleanalytics' => array('custom' => 0))), 'account');
-    $messages[] = t('Disabled user specific page tracking for site administrator.');
-  }
-
-  // Delete outdated tracking settings.
-  db_delete('variable')
-    ->condition('name', db_like('googleanalytics_track_') . '%', 'LIKE')
-    ->execute();
-
-  return implode(', ', $messages);
-}
-
-/**
- * #262468: Clear menu cache to solve stale menu data in 5.x-1.5 and 6.x-1.1
- */
-function googleanalytics_update_6003() {
-  menu_rebuild();
-  return t('Menu has been rebuild.');
-}
-
-/**
- * Change visibility setting for path "user/*".
- */
-function googleanalytics_update_6004() {
-  // Original pages setting.
-  $pages = array(
-    'admin*',
-    'user*',
-    'node/add*',
-    'node/*/*',
-  );
-
-  $diff = array_diff($pages, preg_split('/(\r\n?|\n)/', variable_get('googleanalytics_pages', implode("\n", $pages))));
-  if (empty($diff)) {
-    // No diff to original settings found. Update with new settings.
-    $pages = array(
-      'admin*',
-      'user/*/*',
-      'node/add*',
-      'node/*/*',
-    );
-    variable_set('googleanalytics_pages', implode("\n", $pages));
-    return t('Path visibility filter setting changed from "user*" to "user/*/*".');
-  }
-  else {
-    return t('Custom path visibility filter setting found. Update skipped!');
-  }
-}
-
-/**
- * Change visibility setting for path "admin*".
- */
-function googleanalytics_update_6005() {
-  // Original pages setting.
-  $pages = array(
-    'admin*',
-    'user/*/*',
-    'node/add*',
-    'node/*/*',
-  );
-
-  $diff = array_diff($pages, preg_split('/(\r\n?|\n)/', variable_get('googleanalytics_pages', implode("\n", $pages))));
-  if (empty($diff)) {
-    // No diff to original settings found. Update with new settings.
-    $pages = array(
-      'admin',
-      'admin/*',
-      'user/*/*',
-      'node/add*',
-      'node/*/*',
-    );
-    variable_set('googleanalytics_pages', implode("\n", $pages));
-    return t('Path visibility filter setting changed from "admin*" to "admin" and "admin/*".');
-  }
-  else {
-    return t('Custom path visibility filter setting found. Update skipped!');
-  }
-}
-
-/**
- * Upgrade custom javascript settings.
- */
-function googleanalytics_update_6006() {
-  variable_set('googleanalytics_codesnippet_before', variable_get('googleanalytics_codesnippet', ''));
-  variable_del('googleanalytics_codesnippet');
-
-  return t('Upgraded custom javascript codesnippet setting.');
-}
-
-/**
- * Remove "User identifier" and "User name" from segmentation fields.
- *
- * This is a data protection and privacy law change. For more information see Google Analytics
- * terms of use section 8.1 (http://www.google.com/analytics/en-GB/tos.html).
- */
-function googleanalytics_update_6007() {
-  $profile_fields = variable_get('googleanalytics_segmentation', array());
-  unset($profile_fields['uid']);
-  unset($profile_fields['name']);
-  variable_set('googleanalytics_segmentation', $profile_fields);
-
-  return t('Removed "User identifier" and "User name" from segmentation fields.');
-}
-
-/**
- * Remove outdated legacy support variables and files.
- */
-function googleanalytics_update_6200() {
-  $path = 'public://googleanalytics';
-  if (file_exists($path)) {
-    file_unmanaged_delete($path . '/urchin.js');
-  }
-  variable_del('googleanalytics_legacy_version');
-
-  return t('Removed outdated legacy tracker stuff.');
-}
-
-/**
- * Update list of default file extensions.
- */
-function googleanalytics_update_6201() {
-  if (variable_get('googleanalytics_trackfiles_extensions', '') == '7z|aac|avi|csv|doc|exe|flv|gif|gz|jpe?g|js|mp(3|4|e?g)|mov|pdf|phps|png|ppt|rar|sit|tar|torrent|txt|wma|wmv|xls|xml|zip') {
-    variable_set('googleanalytics_trackfiles_extensions', '7z|aac|arc|arj|asf|asx|avi|bin|csv|doc|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls|xml|z|zip');
-  }
-
-  return t('The default extensions for download tracking have been updated.');
-}
-
-/**
- * Try to update Google Analytics custom code snippet to async version.
- */
-function googleanalytics_update_6300() {
-  $messages = array();
-
-  // TODO: Backup synchronous code snippets. Remove variables in D8.
-  variable_set('googleanalytics_codesnippet_before_backup_6300', variable_get('googleanalytics_codesnippet_before', ''));
-  variable_set('googleanalytics_codesnippet_after_backup_6300', variable_get('googleanalytics_codesnippet_after', ''));
-
-  // Upgrade of BEFORE code snippet.
-  $code_before = variable_get('googleanalytics_codesnippet_before', '');
-  if (!empty($code_before)) {
-    // No value, e.g. _setLocalRemoteServerMode()
-    $code_before = preg_replace('/(.*)pageTracker\.(\w+)\(\);(.*)/i', '$1_gaq.push(["$2"]);$3', $code_before);
-    // One value, e.g. _setCookiePath()
-    $code_before = preg_replace('/(.*)pageTracker\.(\w+)\(("|\'?)(\w+)("|\'?)\);(.*)/i', '$1_gaq.push(["$2", $3$4$5]);$6', $code_before);
-    // Multiple values e.g. _trackEvent()
-    $code_before = preg_replace('/(.*)pageTracker\.(\w+)\((.*)\);(.*)/i', '$1_gaq.push(["$2", $3]);$4', $code_before);
-
-    variable_set('googleanalytics_codesnippet_before', $code_before);
-
-    drupal_set_message(Database::getConnection()->prefixTables("<strong>Attempted</strong> to upgrade Google Analytics custom 'before' code snippet. Backup of previous code snippet has been saved in database table '{variable}' as 'googleanalytics_codesnippet_before_backup_6300'. Please consult Google's <a href='https://developers.google.com/analytics/devguides/collection/gajs/'>Asynchronous Tracking Usage Guide</a> if the upgrade was successfully."), 'warning');
-    $messages[] = t('Upgraded custom "before" code snippet.');
-  }
-
-  // Upgrade of AFTER code snippet.
-  // We cannot update this code snippet automatically. Show message that the upgrade has been skipped.
-  $code_after = variable_get('googleanalytics_codesnippet_after', '');
-  if (!empty($code_after)) {
-    drupal_set_message(Database::getConnection()->prefixTables("Automatic upgrade of Google Analytics custom 'after' code snippet has been skipped. Backup of previous code snippet has been saved in database table '{variable}' as 'googleanalytics_codesnippet_after_backup_6300'. You need to manually upgrade the custom 'after' code snippet."), 'error');
-    $messages[] = t('Skipped custom "after" code snippet.');
-  }
-
-  return empty($messages) ? t('No custom code snipped found. Nothing to do.') : implode(' ', $messages);
-}
-
-/**
  * Run D6 -> D7 upgrades.
  */
 function googleanalytics_update_7000() {
   // Update JavaScript scope to 'header'.
-  variable_set('googleanalytics_js_scope', 'header');
+  update_variable_set('googleanalytics_js_scope', 'header');
   $messages[] = t('Google tracking code has been moved to header.');
 
   // Upgrade D6 token placeholder to D7. update_6301 is not required.
   $googleanalytics_custom_vars = variable_get('googleanalytics_custom_var', array());
   if (!empty($googleanalytics_custom_vars['slots'][1]) && $googleanalytics_custom_vars['slots'][1]['name'] == 'User roles' && $googleanalytics_custom_vars['slots'][1]['value'] = '[user-role-names]') {
     $googleanalytics_custom_vars['slots'][1]['value'] = '[current-user:role-names]';
-    variable_set('googleanalytics_custom_var', $googleanalytics_custom_vars);
+    update_variable_set('googleanalytics_custom_var', $googleanalytics_custom_vars);
     $messages[] = t("The D6 token placeholder [user-role-names] used in the custom variable 'User roles' has been replaced with [current-user:role-names].");
   }
 
@@ -329,8 +104,8 @@
   $countries = array(
     'DE',
   );
-  if (in_array(variable_get('site_default_country', ''), $countries)) {
-    variable_set('googleanalytics_tracker_anonymizeip', 1);
+  if (in_array(update_variable_get('site_default_country', ''), $countries)) {
+    update_variable_set('googleanalytics_tracker_anonymizeip', 1);
     return t('The default country in your regional settings is Germany. Anonymizing of IP addresses has been enabled for privacy reasons.');
   }
   else {
@@ -344,19 +119,19 @@
 function googleanalytics_update_7002() {
 
   // Read previous segmentation settings.
-  $segmentation = variable_get('googleanalytics_segmentation', array());
+  $segmentation = update_variable_get('googleanalytics_segmentation', array());
 
   // If this is an upgrade from D6 the slot 1 may not empty.
   if (empty($googleanalytics_custom_vars['slots'][1]) && in_array('roles', $segmentation)) {
     // Upgrade previous segmentation settings to new custom variables settings.
-    $googleanalytics_custom_vars = variable_get('googleanalytics_custom_var', array());
+    $googleanalytics_custom_vars = update_variable_get('googleanalytics_custom_var', array());
 
     $googleanalytics_custom_vars['slots'][1]['slot'] = 1;
     $googleanalytics_custom_vars['slots'][1]['name'] = 'User roles';
     $googleanalytics_custom_vars['slots'][1]['value'] = '[current-user:role-names]';
     $googleanalytics_custom_vars['slots'][1]['scope'] = 1; // Sets the scope to visitor-level.
 
-    variable_set('googleanalytics_custom_var', $googleanalytics_custom_vars);
+    update_variable_set('googleanalytics_custom_var', $googleanalytics_custom_vars);
     return t('The deprecated profile segmentation setting for "User roles" has been added to custom variables. You need to deselect all selected profile fields in <a href="@admin">Google Analytics settings</a> and upgrade other profile fields manually or you may loose tracking data in future! See Google Analytics <a href="@customvar">Custom Variables</a> for more information.', array('@customvar' => 'https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCustomVariables', '@admin' => url('admin/config/system/googleanalytics')));
   }
   else {
@@ -368,8 +143,8 @@
  * Rename googleanalytics_trackoutgoing variable to googleanalytics_trackoutbound.
  */
 function googleanalytics_update_7003() {
-  variable_set('googleanalytics_trackoutbound', variable_get('googleanalytics_trackoutgoing', 1));
-  variable_del('googleanalytics_trackoutgoing');
+  update_variable_set('googleanalytics_trackoutbound', update_variable_get('googleanalytics_trackoutgoing', 1));
+  update_variable_del('googleanalytics_trackoutgoing');
 
   return t('Renamed "googleanalytics_trackoutgoing" settings variable to googleanalytics_trackoutbound.');
 }
@@ -378,8 +153,8 @@
  * Rename googleanalytics_visibility variable to googleanalytics_visibility_pages for consistency.
  */
 function googleanalytics_update_7004() {
-  variable_set('googleanalytics_visibility_pages', variable_get('googleanalytics_visibility', 1));
-  variable_del('googleanalytics_visibility');
+  update_variable_set('googleanalytics_visibility_pages', update_variable_get('googleanalytics_visibility', 1));
+  update_variable_del('googleanalytics_visibility');
 
   return t('Renamed "googleanalytics_visibility" settings variable to googleanalytics_visibility_pages.');
 }
@@ -397,7 +172,7 @@
     'node/*/*',
   );
 
-  $diff = array_diff($pages, preg_split('/(\r\n?|\n)/', variable_get('googleanalytics_pages', implode("\n", $pages))));
+  $diff = array_diff($pages, preg_split('/(\r\n?|\n)/', update_variable_get('googleanalytics_pages', implode("\n", $pages))));
   if (empty($diff)) {
     // No diff to previous settings found. Update with new settings.
     $pages = array(
@@ -408,7 +183,7 @@
       'node/*/*',
       'user/*/*',
     );
-    variable_set('googleanalytics_pages', implode("\n", $pages));
+    update_variable_set('googleanalytics_pages', implode("\n", $pages));
     return t('Added "batch" to path visibility filter setting.');
   }
   else {
@@ -420,16 +195,16 @@
  * Delete obsolete trackOutboundAsPageview variable.
  */
 function googleanalytics_update_7006() {
-  variable_del('googleanalytics_trackoutboundaspageview');
+  update_variable_del('googleanalytics_trackoutboundaspageview');
 
   return t('Deleted obsolete trackOutboundAsPageview variable.');
 }
 
 /**
-* Delete obsolete googleanalytics_trackpageloadtime variable.
-*/
+ * Delete obsolete googleanalytics_trackpageloadtime variable.
+ */
 function googleanalytics_update_7007() {
-  variable_del('googleanalytics_trackpageloadtime');
+  update_variable_del('googleanalytics_trackpageloadtime');
 
   return t('Deleted obsolete googleanalytics_trackpageloadtime variable.');
 }
diff --git a/google_analytics.js b/google_analytics.js
index 374fd47..24f5cac 100644
--- a/google_analytics.js
+++ b/google_analytics.js
@@ -3,34 +3,34 @@
 $(document).ready(function() {
 
   // Expression to check for absolute internal links.
-  var isInternal = new RegExp("^(https?):\/\/" + window.location.host, "i");
+  var Google_Analytics.isInternal = new RegExp("^(https?):\/\/" + window.location.host, "i");
 
   // Attach onclick event to document only and catch clicks on all elements.
   $(document.body).click(function(event) {
     // Catch the closest surrounding link of a clicked element.
     $(event.target).closest("a,area").each(function() {
 
-      var ga = Drupal.settings.googleanalytics;
+      var ga = Drupal.settings.google_analytics;
       // Expression to check for special links like gotwo.module /go/* links.
-      var isInternalSpecial = new RegExp("(\/go\/.*)$", "i");
+      var Google_Analytics.isInternalSpecial = new RegExp("(\/go\/.*)$", "i");
       // Expression to check for download links.
-      var isDownload = new RegExp("\\.(" + ga.trackDownloadExtensions + ")$", "i");
+      var Google_Analytics.isDownload = new RegExp("\\.(" + ga.trackDownloadExtensions + ")$", "i");
 
       // Is the clicked URL internal?
-      if (isInternal.test(this.href)) {
+      if (Google_Analytics.isInternal.test(this.href)) {
         // Skip 'click' tracking, if custom tracking events are bound.
         if ($(this).is('.colorbox')) {
           // Do nothing here. The custom event will handle all tracking.
         }
         // Is download tracking activated and the file extension configured for download tracking?
-        else if (ga.trackDownload && isDownload.test(this.href)) {
+        else if (ga.trackDownload && Google_Analytics.isDownload.test(this.href)) {
           // Download link clicked.
-          var extension = isDownload.exec(this.href);
-          ga("send", "event", "Downloads", extension[1].toUpperCase(), this.href.replace(isInternal, ''));
+          var extension = Google_Analytics.isDownload.exec(this.href);
+          ga("send", "event", "Downloads", extension[1].toUpperCase(), this.href.replace(Google_Analytics.isInternal, ''));
         }
-        else if (isInternalSpecial.test(this.href)) {
+        else if (Google_Analytics.isInternalSpecial.test(this.href)) {
           // Keep the internal URL for Google Analytics website overlay intact.
-          ga("send", "pageview", { page: this.href.replace(isInternal, '')});
+          ga("send", "pageview", { page: this.href.replace(Google_Analytics.isInternal, '')});
         }
       }
       else {
@@ -39,7 +39,7 @@
           ga("send", "event", "Mails", "Click", this.href.substring(7));
         }
         else if (ga.trackOutbound && this.href.match(/^\w+:\/\//i)) {
-          if (ga.trackDomainMode == 2 && isCrossDomain($(this).attr('hostname'), ga.trackCrossDomains)) {
+          if (ga.trackDomainMode == 2 && Google_Analytics.isCrossDomain($(this).attr('hostname'), ga.trackCrossDomains)) {
             // Top-level cross domain clicked. document.location is handled by _link internally.
             event.preventDefault();
             // @todo: unknown upgrade path
@@ -60,7 +60,7 @@
   $(document).bind("cbox_complete", function() {
     var href = $.colorbox.element().attr("href");
     if (href) {
-      ga("send", "pageview", { page: href.replace(isInternal, '') });
+      ga("send", "pageview", { page: href.replace(Google_Analytics.isInternal, '') });
     }
   });
 
@@ -76,20 +76,8 @@
  *
  * @return boolean
  */
-function isCrossDomain(hostname, crossDomains) {
-  /**
-   * jQuery < 1.6.3 bug: $.inArray crushes IE6 and Chrome if second argument is
-   * `null` or `undefined`, http://bugs.jquery.com/ticket/10076,
-   * https://github.com/jquery/jquery/commit/a839af034db2bd934e4d4fa6758a3fed8de74174
-   *
-   * @todo: Remove/Refactor in D8
-   */
-  if (!crossDomains) {
-    return false;
-  }
-  else {
-    return $.inArray(hostname, crossDomains) > -1 ? true : false;
-  }
+function Google_Analytics.isCrossDomain(hostname, crossDomains) {
+  return $.inArray(hostname, crossDomains) > -1 ? true : false;
 }
 
 })(jQuery);
diff --git a/google_analytics.module b/google_analytics.module
index 1042c31..454a4a2 100644
--- a/google_analytics.module
+++ b/google_analytics.module
@@ -10,12 +10,16 @@
  * @author: Alexander Hass <http://drupal.org/user/85918>
  */
 
+use Guzzle\Http\Exception\RequestException;
+
 /**
+ * @TODO: remove after admin.inc is upgraded.
  * Define the default file extension list that should be tracked as download.
  */
 define('GOOGLEANALYTICS_TRACKFILES_EXTENSIONS', '7z|aac|arc|arj|asf|asx|avi|bin|csv|doc|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls|xml|z|zip');
 
 /**
+ * @TODO: remove after admin.inc is upgraded.
  * Define default path exclusion list to remove tracking from admin pages,
  * see http://drupal.org/node/34970 for more information.
  */
@@ -24,7 +28,7 @@
 /**
  * Implements hook_help().
  */
-function googleanalytics_help($path, $arg) {
+function google_analytics_help($path, $arg) {
   switch ($path) {
     case 'admin/config/system/googleanalytics':
       return t('<a href="@ga_url">Google Analytics</a> is a free (registration required) website traffic and marketing effectiveness service.', array('@ga_url' => 'http://www.google.com/analytics/'));
@@ -34,7 +38,7 @@
 /**
  * Implements hook_theme().
  */
-function googleanalytics_theme() {
+function google_analytics_theme() {
   return array(
     'googleanalytics_admin_custom_var_table' => array(
       'render element' => 'form',
@@ -45,7 +49,7 @@
 /**
  * Implements hook_permission().
  */
-function googleanalytics_permission() {
+function google_analytics_permission() {
   return array(
     'administer google analytics' => array(
       'title' => t('Administer Google Analytics'),
@@ -66,15 +70,13 @@
 /**
  * Implements hook_menu().
  */
-function googleanalytics_menu() {
-  $items['admin/config/system/googleanalytics'] = array(
+function google_analytics_menu() {
+  $items['admin/config/system/google_analytics'] = array(
     'title' => 'Google Analytics',
     'description' => 'Configure tracking behavior to get insights into your website traffic and marketing effectiveness.',
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('googleanalytics_admin_settings_form'),
+    'route_name' => 'google_analytics_settings',
     'access arguments' => array('administer google analytics'),
     'type' => MENU_NORMAL_ITEM,
-    'file' => 'googleanalytics.admin.inc',
   );
 
   return $items;
@@ -83,10 +85,11 @@
 /**
  * Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.
  */
-function googleanalytics_page_alter(&$page) {
+function google_analytics_page_alter(&$page) {
   global $user;
 
-  $id = variable_get('googleanalytics_account', '');
+  $config = config('google_analytics.settings');
+  $id = $config->get('account');
 
   // Get page status code for visibility filtering.
   $status = drupal_get_http_header('Status');
@@ -99,39 +102,35 @@
   // 2. Track page views based on visibility value.
   // 3. Check if we should track the currently active user's role.
   // 4. Ignore pages visibility filter for 404 or 403 status codes.
-  if (!empty($id) && (_googleanalytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _googleanalytics_visibility_user($user)) {
-
-    // We allow different scopes. Default to 'header' but allow user to override if they really need to.
-    // @todo: footer may no longer suppored
-    $scope = variable_get('googleanalytics_js_scope', 'header');
+  if (!empty($id) && (_google_analytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _google_analytics_visibility_user($user)) {
 
     // Add link tracking.
     $link_settings = array();
-    if ($track_outbound = variable_get('googleanalytics_trackoutbound', 1)) {
+    if ($track_outbound = $config->get('track.outbound')) {
       $link_settings['trackOutbound'] = $track_outbound;
     }
-    if ($track_mailto = variable_get('googleanalytics_trackmailto', 1)) {
+    if ($track_mailto = $config->get('track.mailto')) {
       $link_settings['trackMailto'] = $track_mailto;
     }
-    if (($track_download = variable_get('googleanalytics_trackfiles', 1)) && ($trackfiles_extensions = variable_get('googleanalytics_trackfiles_extensions', GOOGLEANALYTICS_TRACKFILES_EXTENSIONS))) {
+    if (($track_download = $config->get('track.files')) && ($trackfiles_extensions = $config->get('track.files_extensions'))) {
       $link_settings['trackDownload'] = $track_download;
       $link_settings['trackDownloadExtensions'] = $trackfiles_extensions;
     }
-    if ($track_domain_mode = variable_get('googleanalytics_domain_mode', 0)) {
+    if ($track_domain_mode = $config->get('domain_mode')) {
       $link_settings['trackDomainMode'] = $track_domain_mode;
     }
-    if ($track_cross_domains = variable_get('googleanalytics_cross_domains', '')) {
+    if ($track_cross_domains = $config->get('cross_domains')) {
       $link_settings['trackCrossDomains'] = preg_split('/(\r\n?|\n)/', $track_cross_domains);
     }
 
     if (!empty($link_settings)) {
-      drupal_add_js(array('googleanalytics' => $link_settings), 'setting');
-      drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.js');
+      drupal_add_js(array('google_analytics' => $link_settings), 'setting');
+      drupal_add_js(drupal_get_path('module', 'google_analytics') . '/google_analytics.js');
     }
 
     // Add messages tracking.
     $message_events = '';
-    if ($message_types = variable_get('googleanalytics_trackmessages', array())) {
+    if ($message_types = $config->get('track.messages')) {
       $message_types = array_values(array_filter($message_types));
       $status_heading = array(
         'status' => t('Status message'),
@@ -152,7 +151,7 @@
 
     // Site search tracking support.
     $url_custom = '';
-    if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = googleanalytics_search_get_keys()) {
+    if (module_exists('search') && $config->get('track.site_search') && arg(0) == 'search' && $keys = google_analytics_search_get_keys()) {
       // hook_preprocess_search_results() is not executed if search result is
       // empty. Make sure the counter is set to 0 if there are no results.
       $url_custom = '(window.googleanalytics_search_results) ? ' . drupal_json_encode(url('search/' . arg(1), array('query' => array('search' => $keys)))) . ' : ' . drupal_json_encode(url('search/' . arg(1), array('query' => array('search' => 'no-results:' . $keys, 'cat' => 'no-results'))));
@@ -160,7 +159,7 @@
 
     // If this node is a translation of another node, pass the original
     // node instead.
-    if (module_exists('translation') && variable_get('googleanalytics_translation_set', 0)) {
+    if (module_exists('translation') && $config->get('translation_set')) {
       // Check we have a node object, it supports translation, and its
       // translated node ID (tnid) doesn't match its own node ID.
       $node = menu_get_object();
@@ -181,8 +180,8 @@
     }
 
     // Add any custom code snippets if specified.
-    $codesnippet_before = variable_get('googleanalytics_codesnippet_before', '');
-    $codesnippet_after = variable_get('googleanalytics_codesnippet_after', '');
+    $codesnippet_before = $config->get('codesnippet.before');
+    $codesnippet_after = $config->get('codesnippet.after');
 
     // Add custom variables.
     /* @todo: Needs upgrade to custom dimensions
@@ -238,11 +237,12 @@
     $library_cache_url = 'http:' . $library_tracker_url;
 
     // Should a local cached copy of analytics.js be used?
-    if (variable_get('googleanalytics_cache', 0) && $url = _googleanalytics_cache($library_cache_url)) {
+    if ($config->get('cache') && $url = _google_analytics_cache($library_cache_url)) {
       // A dummy query-string is added to filenames, to gain control over
       // browser-caching. The string changes on every update or full cache
       // flush, forcing browsers to load a new copy of the files, as the
       // URL changed.
+      // @FIXME config namespace?
       $query_string = '?' . variable_get('css_js_query_string', '0');
 
       $script .= '"' . $url . $query_string . '"';
@@ -255,7 +255,7 @@
     // Create a tracker.
     $script .= 'ga("create", ' . drupal_json_encode($id) . ');';
 
-    if (variable_get('googleanalytics_tracker_anonymizeip', 0)) {
+    if ($config->get('privacy.anonymizeip')) {
       $script .= 'ga("set", "anonymizeIp", 1);';
     }
 
@@ -264,7 +264,7 @@
 
     // Domain tracking type.
     global $cookie_domain;
-    $domain_mode = variable_get('googleanalytics_domain_mode', 0);
+    $domain_mode = $config->get('domain_mode');
 
     // Per RFC 2109, cookie domains must contain at least one dot other than the
     // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
@@ -298,21 +298,21 @@
     }
 
     // @TODO: not available yet, comming soon per Google.
-    //if (variable_get('googleanalytics_trackadsense', FALSE)) {
+    //if ($config->get('track.adsense')) {
       // Custom tracking. Prepend before all other JavaScript.
       // @TODO: http://support.google.com/adsense/bin/answer.py?answer=98142
       // sounds like it could be appended to $script.
       //drupal_add_js($googleanalytics_adsense_script, array('type' => 'inline', 'group' => JS_LIBRARY-1));
     //}
 
-    drupal_add_js($script, array('scope' => $scope, 'type' => 'inline'));
+    drupal_add_js($script, array('scope' => $config->get('js_scope'), 'type' => 'inline'));
   }
 }
 
 /**
  * Implements hook_field_extra_fields().
  */
-function googleanalytics_field_extra_fields() {
+function google_analytics_field_extra_fields() {
   $extra['user']['user']['form']['googleanalytics'] = array(
     'label' => t('Google Analytics configuration'),
     'description' => t('Google Analytics module form element.'),
@@ -327,7 +327,8 @@
  *
  * Allow users to decide if tracking code will be added to pages or not.
  */
-function googleanalytics_form_user_profile_form_alter(&$form, &$form_state) {
+function google_analytics_form_user_profile_form_alter(&$form, &$form_state) {
+  // @TODO
   $account = $form['#user'];
   $category = $form['#user_category'];
 
@@ -378,20 +379,25 @@
 /**
  * Implements hook_user_presave().
  */
-function googleanalytics_user_presave(&$edit, $account, $category) {
-  if (isset($edit['googleanalytics']['custom'])) {
-    $edit['data']['googleanalytics']['custom'] = $edit['googleanalytics']['custom'];
+function google_analytics_user_presave(&$edit, $account, $category) {
+  // @todo: Upgrade path for name change 'googleanalytics' -> 'google_analytics'?
+  if (isset($edit['google_analytics']['custom'])) {
+    $edit['data']['google_analytics']['custom'] = $edit['google_analytics']['custom'];
   }
 }
 
 /**
  * Implements hook_cron().
  */
-function googleanalytics_cron() {
+function google_analytics_cron() {
+  $config = config('google_analytics.settings');
+
   // Regenerate the tracking code file every day.
-  if (REQUEST_TIME - variable_get('googleanalytics_last_cache', 0) >= 86400 && variable_get('googleanalytics_cache', 0)) {
-    _googleanalytics_cache('http://www.google-analytics.com/analytics.js', TRUE);
-    variable_set('googleanalytics_last_cache', REQUEST_TIME);
+  if (REQUEST_TIME - $config->get('last_cache') >= 86400 && $config->get('cache')) {
+    _google_analytics_cache('http://www.google-analytics.com/analytics.js', TRUE);
+    config('google_analytics.settings')
+      ->set('last_cache', REQUEST_TIME)
+      ->save();
   }
 }
 
@@ -400,7 +406,7 @@
  *
  * Collects and adds the number of search results to the head.
  */
-function googleanalytics_preprocess_search_results(&$variables) {
+function google_analytics_preprocess_search_results(&$variables) {
   // There is no search result $variable available that hold the number of items
   // found. But the pager item mumber can tell the number of search results.
   global $pager_total_items;
@@ -413,7 +419,7 @@
  *
  * http://api.drupal.org/api/function/search_get_keys/6
  */
-function googleanalytics_search_get_keys() {
+function google_analytics_search_get_keys() {
   static $return;
   if (!isset($return)) {
     // Extract keys as remainder of path
@@ -435,41 +441,47 @@
  * @return mixed
  *   The path to the local javascript file on success, boolean FALSE on failure.
  */
-function _googleanalytics_cache($location, $sync_cached_file = FALSE) {
-  $path = 'public://googleanalytics';
+function _google_analytics_cache($location, $sync_cached_file = FALSE) {
+  $path = 'public://google_analytics';
   $file_destination = $path . '/' . basename($location);
 
   if (!file_exists($file_destination) || $sync_cached_file) {
     // Download the latest tracking code.
-    $result = drupal_http_request($location);
+    try {
+      $data = Drupal::httpClient()
+        ->get($location)
+        ->send()
+        ->getBody(TRUE);
 
-    if ($result->code == 200) {
-      if (file_exists($file_destination)) {
-        // Synchronize tracking code and and replace local file if outdated.
-        $data_hash_local = drupal_hash_base64(file_get_contents($file_destination));
-        $data_hash_remote = drupal_hash_base64($result->data);
-        // Check that the files directory is writable.
-        if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
-          // Save updated tracking code file to disk.
-          file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
-          watchdog('googleanalytics', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO);
-
-          // Change query-strings on css/js files to enforce reload for all users.
-          _drupal_flush_css_js();
-        }
-      }
-      else {
-        // Check that the files directory is writable.
-        if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
-          // There is no need to flush JS here as core refreshes JS caches
-          // automatically, if new files are added.
-          file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
-          watchdog('googleanalytics', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);
-
-          // Return the local JS file path.
-          return file_create_url($file_destination);
-        }
-      }
+      if (file_exists($file_destination)) {
+        // Synchronize tracking code and and replace local file if outdated.
+        $data_hash_local = drupal_hash_base64(file_get_contents($file_destination));
+        $data_hash_remote = drupal_hash_base64($data);
+        // Check that the files directory is writable.
+        if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
+          // Save updated tracking code file to disk.
+          file_unmanaged_save_data($data, $file_destination, FILE_EXISTS_REPLACE);
+          watchdog('google_analytics', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO);
+
+          // Change query-strings on css/js files to enforce reload for all users.
+          _drupal_flush_css_js();
+        }
+      }
+      else {
+        // Check that the files directory is writable.
+        if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
+          // There is no need to flush JS here as core refreshes JS caches
+          // automatically, if new files are added.
+          file_unmanaged_save_data($data, $file_destination, FILE_EXISTS_REPLACE);
+          watchdog('google_analytics', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);
+
+          // Return the local JS file path.
+          return file_create_url($file_destination);
+        }
+      }
+    }
+    catch (RequestException $exception) {
+      watchdog_exception('google_analytics', $exception);
     }
   }
   else {
@@ -481,8 +493,8 @@
 /**
  * Delete cached files and directory.
  */
-function googleanalytics_clear_js_cache() {
-  $path = 'public://googleanalytics';
+function google_analytics_clear_js_cache() {
+  $path = 'public://google_analytics';
   if (file_prepare_directory($path)) {
     file_scan_directory($path, '/.*/', array('callback' => 'file_unmanaged_delete'));
     drupal_rmdir($path);
@@ -490,7 +502,7 @@
     // Change query-strings on css/js files to enforce reload for all users.
     _drupal_flush_css_js();
 
-    watchdog('googleanalytics', 'Local cache has been purged.', array(), WATCHDOG_INFO);
+    watchdog('google_analytics', 'Local cache has been purged.', array(), WATCHDOG_INFO);
   }
 }
 
@@ -502,17 +514,17 @@
  * @return boolean
  *   A decision on if the current user is being tracked by Google Analytics.
  */
-function _googleanalytics_visibility_user($account) {
-
+function _google_analytics_visibility_user($account) {
+  $config = config('google_analytics.settings');
   $enabled = FALSE;
 
   // Is current user a member of a role that should be tracked?
-  if (_googleanalytics_visibility_header($account) && _googleanalytics_visibility_roles($account)) {
+  if (_google_analytics_visibility_header($account) && _google_analytics_visibility_roles($account)) {
 
     // Use the user's block visibility setting, if necessary.
-    if (($custom = variable_get('googleanalytics_custom', 0)) != 0) {
-      if ($account->uid && isset($account->data['googleanalytics']['custom'])) {
-        $enabled = $account->data['googleanalytics']['custom'];
+    if (($custom = $config->get('visibility.custom')) != 0) {
+      if ($account->uid && isset($account->data['google_analytics']['custom'])) {
+        $enabled = $account->data['google_analytics']['custom'];
       }
       else {
         $enabled = ($custom == 1);
@@ -531,11 +543,10 @@
  * Based on visibility setting this function returns TRUE if GA code should
  * be added for the current role and otherwise FALSE.
  */
-function _googleanalytics_visibility_roles($account) {
-
-  $visibility = variable_get('googleanalytics_visibility_roles', 0);
-  $enabled = $visibility;
-  $roles = variable_get('googleanalytics_roles', array());
+function _google_analytics_visibility_roles($account) {
+  $config = config('google_analytics.settings');
+  $enabled = $visibility = $config->get('visibility.roles_enabled');
+  $roles = (array) $config->get('visibility.roles');
 
   if (array_sum($roles) > 0) {
     // One or more roles are selected.
@@ -560,14 +571,14 @@
  * Based on visibility setting this function returns TRUE if GA code should
  * be added to the current page and otherwise FALSE.
  */
-function _googleanalytics_visibility_pages() {
+function _google_analytics_visibility_pages() {
   static $page_match;
 
   // Cache visibility result if function is called more than once.
   if (!isset($page_match)) {
-
-    $visibility = variable_get('googleanalytics_visibility_pages', 0);
-    $setting_pages = variable_get('googleanalytics_pages', GOOGLEANALYTICS_PAGES);
+    $config = config('google_analytics.settings');
+    $visibility = $config->get('visibility.pages_enabled');
+    $setting_pages = $config->get('visibility.pages');
 
     // Match path if necessary.
     if (!empty($setting_pages)) {
@@ -575,12 +586,12 @@
       // with different case. Ex: /Page, /page, /PAGE.
       $pages = drupal_strtolower($setting_pages);
       if ($visibility < 2) {
-        // Convert the Drupal path to lowercase
-        $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
+        // Convert the Drupal path to lowercase.
+        $path = drupal_strtolower(drupal_container()->get('path.alias_manager')->getPathAlias(current_path()));
         // Compare the lowercase internal and lowercase path alias (if any).
         $page_match = drupal_match_path($path, $pages);
-        if ($path != $_GET['q']) {
-          $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
+        if ($path != current_path()) {
+          $page_match = $page_match || drupal_match_path(current_path(), $pages);
         }
         // When $visibility has a value of 0, the tracking code is displayed on
         // all pages except those listed in $pages. When set to 1, it
@@ -606,9 +617,11 @@
  * Based on headers send by clients this function returns TRUE if GA code should
  * be added to the current page and otherwise FALSE.
  */
-function _googleanalytics_visibility_header($account) {
+function _google_analytics_visibility_header($account) {
+  $config = config('google_analytics.settings');
+  $visibility = $config->get('visibility.pages_enabled');
 
-  if (($account->uid || variable_get('cache', 0) == 0) && variable_get('googleanalytics_privacy_donottrack', 1) && !empty($_SERVER['HTTP_DNT'])) {
+  if (($account->uid || $config->get('cache') == 0) && $config->get('privacy.donottrack') && !empty($_SERVER['HTTP_DNT'])) {
     // Disable tracking if caching is disabled or a visitors is logged in and
     // have opted out from tracking via DNT (Do-Not-Track) header.
     return FALSE;
diff --git a/google_analytics.routing.yml b/google_analytics.routing.yml
new file mode 100644
index 0000000..5cc660e
--- /dev/null
+++ b/google_analytics.routing.yml
@@ -0,0 +1,6 @@
+google_analytics_settings:
+  pattern: '/admin/config/system/google_analytics'
+  defaults:
+    _form: 'Drupal\google_analytics\Google_AnalyticsSettingsForm'
+  requirements:
+    _permission: 'administer google analytics'
diff --git a/lib/Drupal/google_analytics/Google_AnalyticsSettingsForm.php b/lib/Drupal/google_analytics/Google_AnalyticsSettingsForm.php
new file mode 100644
index 0000000..70b27cc
--- /dev/null
+++ b/lib/Drupal/google_analytics/Google_AnalyticsSettingsForm.php
@@ -0,0 +1,527 @@
+<?php
+/**
+ * @file
+ * Contains \Drupal\google_analytics\Google_AnalyticsSettingsForm.
+ */
+
+namespace Drupal\google_analytics;
+
+use Drupal\system\SystemConfigFormBase;
+
+/**
+ * Configure Google_Analytics settings for this site.
+ */
+class Google_AnalyticsSettingsForm extends SystemConfigFormBase {
+
+  /**
+   * Implements \Drupal\Core\Form\FormInterface::getFormID().
+   */
+  public function getFormID() {
+    return 'google_analytics_admin_settings';
+  }
+
+  /**
+   * Implements \Drupal\Core\Form\FormInterface::buildForm().
+   */
+  public function buildForm(array $form, array &$form_state) {
+    $config = $this->configFactory->get('google_analytics.settings');
+
+    $form['general'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('General settings'),
+    );
+
+    $form['general']['google_analytics_account'] = array(
+      '#title' => t('Web Property ID'),
+      '#type' => 'textfield',
+      '#default_value' => $config->get('account'),
+      '#size' => 15,
+      '#maxlength' => 20,
+      '#required' => TRUE,
+      '#description' => t('This ID is unique to each site you want to track separately, and is in the form of UA-xxxxxxx-yy. To get a Web Property ID, <a href="@analytics">register your site with Google Analytics</a>, or if you already have registered your site, go to your Google Analytics Settings page to see the ID next to every site profile. <a href="@webpropertyid">Find more information in the documentation</a>.', array('@analytics' => 'http://www.google.com/analytics/', '@webpropertyid' => url('https://developers.google.com/analytics/resources/concepts/gaConceptsAccounts', array('fragment' => 'webProperty')))),
+    );
+
+    // Visibility settings.
+    $form['tracking_title'] = array(
+      '#type' => 'item',
+      '#title' => t('Tracking scope'),
+    );
+    $form['tracking'] = array(
+      '#type' => 'vertical_tabs',
+      '#attached' => array(
+        'js' => array(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.admin.js'),
+      ),
+    );
+
+    $form['tracking']['domain_tracking'] = array(
+        '#type' => 'fieldset',
+        '#title' => t('Domains'),
+    );
+
+    global $cookie_domain;
+    $multiple_sub_domains = array();
+    foreach (array('www', 'app', 'shop') as $subdomain) {
+      if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
+        $multiple_sub_domains[] = $subdomain . $cookie_domain;
+      }
+      // IP addresses or localhost.
+      else {
+        $multiple_sub_domains[] = $subdomain . '.example.com';
+      }
+    }
+
+    $multiple_toplevel_domains = array();
+    foreach (array('.com', '.net', '.org') as $tldomain) {
+      $host = $_SERVER['HTTP_HOST'];
+      $domain = substr($host, 0, strrpos($host, '.'));
+      if (count(explode('.', $host)) > 2 && !is_numeric(str_replace('.', '', $host))) {
+        $multiple_toplevel_domains[] = $domain . $tldomain;
+      }
+      // IP addresses or localhost
+      else {
+        $multiple_toplevel_domains[] = 'www.example' . $tldomain;
+      }
+    }
+
+    $form['tracking']['domain_tracking']['google_analytics_domain_mode'] = array(
+      '#type' => 'radios',
+      '#title' => t('What are you tracking?'),
+      '#options' => array(
+        0 => t('A single domain (default)') . '<div class="description">' . t('Domain: @domain', array('@domain' => $_SERVER['HTTP_HOST'])) . '</div>',
+        1 => t('One domain with multiple subdomains') . '<div class="description">' . t('Examples: @domains', array('@domains' => implode(', ', $multiple_sub_domains))) . '</div>',
+        2 => t('Multiple top-level domains') . '<div class="description">' . t('Examples: @domains', array('@domains' => implode(', ', $multiple_toplevel_domains))) . '</div>',
+      ),
+      '#default_value' => $config->get('domain_mode'),
+    );
+    $form['tracking']['domain_tracking']['google_analytics_cross_domains'] = array(
+      '#title' => t('List of top-level domains'),
+      '#type' => 'textarea',
+      '#default_value' => $config->get('cross_domains'),
+      '#description' => t('If you selected "Multiple top-level domains" above, enter all related top-level domains. Add one domain per line. By default, the data in your reports only includes the path and name of the page, and not the domain name. For more information see section <em>Show separate domain names</em> in <a href="@url">Tracking Multiple Domains</a>.', array('@url' => url('http://support.google.com/analytics/bin/answer.py', array('query' => array('answer' => '1034342'))))),
+    );
+
+    // Page specific visibility configurations.
+    $php_access = user_access('use PHP for tracking visibility');
+    $visibility = $config->get('visibility.pages_enabled');
+    $pages = $config->get('visibility.pages');
+
+    $form['tracking']['page_vis_settings'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Pages'),
+      '#collapsible' => TRUE,
+      '#collapsed' => TRUE,
+    );
+
+    if ($visibility == 2 && !$php_access) {
+      $form['tracking']['page_vis_settings'] = array();
+      $form['tracking']['page_vis_settings']['visibility'] = array('#type' => 'value', '#value' => 2);
+      $form['tracking']['page_vis_settings']['pages'] = array('#type' => 'value', '#value' => $pages);
+    }
+    else {
+      $options = array(
+        t('Every page except the listed pages'),
+        t('The listed pages only'),
+      );
+      $description = t("Specify pages by using their paths. Enter one path per line. The '*' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page.", array('%blog' => 'blog', '%blog-wildcard' => 'blog/*', '%front' => '<front>'));
+
+      if (module_exists('php') && $php_access) {
+        $options[] = t('Pages on which this PHP code returns <code>TRUE</code> (experts only)');
+        $title = t('Pages or PHP code');
+        $description .= ' ' . t('If the PHP option is chosen, enter PHP code between %php. Note that executing incorrect PHP code can break your Drupal site.', array('%php' => '<?php ?>'));
+      }
+      else {
+        $title = t('Pages');
+      }
+      $form['tracking']['page_vis_settings']['google_analytics_visibility_pages'] = array(
+        '#type' => 'radios',
+        '#title' => t('Add tracking to specific pages'),
+        '#options' => $options,
+        '#default_value' => $visibility,
+      );
+      $form['tracking']['page_vis_settings']['google_analytics_pages'] = array(
+        '#type' => 'textarea',
+        '#title' => $title,
+        '#title_display' => 'invisible',
+        '#default_value' => $pages,
+        '#description' => $description,
+        '#rows' => 10,
+      );
+    }
+
+    // Render the role overview.
+    $form['tracking']['role_vis_settings'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Roles'),
+    );
+
+    $form['tracking']['role_vis_settings']['google_analytics_visibility_roles'] = array(
+      '#type' => 'radios',
+      '#title' => t('Add tracking for specific roles'),
+      '#options' => array(
+        t('Add to the selected roles only'),
+        t('Add to every role except the selected ones'),
+      ),
+      '#default_value' => $config->get('visibility.roles_enabled'), // @FIXME rename variable
+    );
+
+    $role_options = array_map('check_plain', user_roles());
+    $form['tracking']['role_vis_settings']['google_analytics_roles'] = array(
+      '#type' => 'checkboxes',
+      '#title' => t('Roles'),
+      '#default_value' => $config->get('visibility.roles'),
+      '#options' => $role_options,
+      '#description' => t('If none of the roles are selected, all users will be tracked. If a user has any of the roles checked, that user will be tracked (or excluded, depending on the setting above).'),
+    );
+
+    // Standard tracking configurations.
+    $form['tracking']['user_vis_settings'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Users'),
+    );
+    $t_permission = array('%permission' => t('opt-in or out of tracking'));
+    $form['tracking']['user_vis_settings']['google_analytics_custom'] = array(
+      '#type' => 'radios',
+      '#title' => t('Allow users to customize tracking on their account page'),
+      '#options' => array(
+        t('No customization allowed'),
+        t('Tracking on by default, users with %permission permission can opt out', $t_permission),
+        t('Tracking off by default, users with %permission permission can opt in', $t_permission),
+      ),
+      '#default_value' => $config->get('visibility.custom'),
+    );
+
+    // Link specific configurations.
+    $form['tracking']['linktracking'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Links and downloads'),
+    );
+    $form['tracking']['linktracking']['google_analytics_trackoutbound'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Track clicks on outbound links'),
+      '#default_value' => $config->get('track.outbound'),
+    );
+    $form['tracking']['linktracking']['google_analytics_trackmailto'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Track clicks on mailto links'),
+      '#default_value' => $config->get('track.mailto'),
+    );
+    $form['tracking']['linktracking']['google_analytics_trackfiles'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Track downloads (clicks on file links) for the following extensions'),
+      '#default_value' => $config->get('track.files'),
+    );
+    $form['tracking']['linktracking']['google_analytics_trackfiles_extensions'] = array(
+      '#title' => t('List of download file extensions'),
+      '#title_display' => 'invisible',
+      '#type' => 'textfield',
+      '#default_value' => $config->get('track.files_extensions'),
+      '#description' => t('A file extension list separated by the | character that will be tracked as download when clicked. Regular expressions are supported. For example: !extensions', array('!extensions' => GOOGLEANALYTICS_TRACKFILES_EXTENSIONS)),
+      '#maxlength' => 255,
+    );
+
+    // Message specific configurations.
+    $form['tracking']['messagetracking'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Messages'),
+    );
+    $form['tracking']['messagetracking']['google_analytics_trackmessages'] = array(
+      '#type' => 'checkboxes',
+      '#title' => t('Track messages of type'),
+      '#default_value' => $config->get('track.messages'),
+      '#description' => t('This will track the selected message types shown to users. Tracking of form validation errors may help you identifying usability issues in your site. For each visit (user session), a maximum of approximately 500 combined GATC requests (both events and page views) can be tracked. Every message is tracked as one individual event. Note that - as the number of events in a session approaches the limit - additional events might not be tracked. Messages from excluded pages cannot tracked.'),
+      '#options' => array(
+        'status' => t('Status message'),
+        'warning' => t('Warning message'),
+        'error' => t('Error message'),
+      ),
+    );
+
+    // Google already have many translations, if not - they display a note to change the language.
+    global $language;
+    $form['tracking']['search_and_advertising'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Search and Advertising'),
+    );
+
+    $site_search_dependencies = '<div class="admin-requirements">';
+    $site_search_dependencies .= t('Requires: !module-list', array('!module-list' => (module_exists('search') ? t('@module (<span class="admin-enabled">enabled</span>)', array('@module' => 'Search')) : t('@module (<span class="admin-disabled">disabled</span>)', array('@module' => 'Search')))));
+    $site_search_dependencies .= '</div>';
+
+    $form['tracking']['search_and_advertising']['google_analytics_site_search'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Track internal search'),
+      '#description' => t('If checked, internal search keywords are tracked. You must configure your Google account to use the internal query parameter <strong>search</strong>. For more information see <a href="@url">Setting Up Site Search for a Profile</a>.', array('@url' => url('http://support.google.com/analytics/bin/answer.py', array('query' => array('answer' => '1012264'))))) . $site_search_dependencies,
+      '#default_value' => $config->get('track.site_search'),
+      '#disabled' => (module_exists('search') ? FALSE : TRUE),
+    );
+    /* @todo: not supported, https://support.google.com/analytics/bin/answer.py?hl=en&hlrm=de&answer=2795983
+     $form['tracking']['search_and_advertising']['google_analytics_trackadsense'] = array(
+       '#type' => 'checkbox',
+       '#title' => t('Track AdSense ads'),
+       '#description' => t('If checked, your AdSense ads will be tracked in your Google Analytics account.'),
+       '#default_value' => $config->get('track.adsense'),
+    );
+    $form['tracking']['search_and_advertising']['google_analytics_trackdoubleclick'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Track DoubleClick data'),
+      '#description' => t('If checked, the alternative Google <a href="@doubleclick">DoubleClick data tracking</a> is used to enable AdWords remarketing features. If you choose this option you will need to <a href="@privacy">update your privacy policy</a>.', array('@doubleclick' => url('http://support.google.com/analytics/bin/answer.py', array('query' => array('answer' => '2444872'))), '@privacy' => url('http://support.google.com/analytics/bin/answer.py', array('query' => array('answer' => '2636405'))))),
+      '#default_value' => $config->get('track.doubleclick'),
+    ); */
+
+    // Privacy specific configurations.
+    $form['tracking']['privacy'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Privacy'),
+    );
+    $form['tracking']['privacy']['google_analytics_tracker_anonymizeip'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Anonymize visitors IP address'),
+      '#description' => t('Tell Google Analytics to anonymize the information sent by the tracker objects by removing the last octet of the IP address prior to its storage. Note that this will slightly reduce the accuracy of geographic reporting. In some countries it is not allowed to collect personally identifying information for privacy reasons and this setting may help you to comply with the local laws.'),
+      '#default_value' => $config->get('privacy.anonymizeip'),
+    );
+    $form['tracking']['privacy']['google_analytics_privacy_donottrack'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Universal web tracking opt-out'),
+      '#description' => t('If enabled and your server receives the <a href="@donottrack">Do-Not-Track</a> header from the client browser, the Google Analytics module will not embed any tracking code into your site. Compliance with Do Not Track could be purely voluntary, enforced by industry self-regulation, or mandated by state or federal law. Please accept your visitors privacy. If they have opt-out from tracking and advertising, you should accept their personal decision. This feature is currently limited to logged in users and disabled page caching.', array('@donottrack' => 'http://donottrack.us/')),
+      '#default_value' => $config->get('privacy.donottrack'),
+    );
+
+    // Custom variables.
+    /* @todo: Update to custom dimensions.
+     $form['google_analytics_custom_var'] = array(
+       '#collapsed' => TRUE,
+       '#collapsible' => TRUE,
+       '#description' => t('You can add Google Analytics <a href="@custom_var_documentation">Custom Variables</a> here. These will be added to every page that Google Analytics tracking code appears on. Google Analytics will only accept custom variables if the <em>name</em> and <em>value</em> combined are less than 128 bytes after URL encoding. Keep the names as short as possible and expect long values to get trimmed. You may use tokens in custom variable names and values. Global and user tokens are always available; on node pages, node tokens are also available.', array('@custom_var_documentation' => 'https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCustomVariables')),
+       '#theme' => 'googleanalytics_admin_custom_var_table',
+       '#title' => t('Custom variables'),
+       '#tree' => TRUE,
+       '#type' => 'fieldset',
+     );
+
+    $googleanalytics_custom_vars = $config->get('custom_var');
+
+    // Google Analytics supports up to 5 custom variables.
+    for ($i = 1; $i < 6; $i++) {
+      $form['google_analytics_custom_var']['slots'][$i]['slot'] = array(
+        '#default_value' => $i,
+        '#description' => t('Slot number'),
+        '#disabled' => TRUE,
+        '#size' => 1,
+        '#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
+        '#title_display' => 'invisible',
+        '#type' => 'textfield',
+      );
+      $form['google_analytics_custom_var']['slots'][$i]['name'] = array(
+        '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['name']) ? $googleanalytics_custom_vars['slots'][$i]['name'] : '',
+        '#description' => t('The custom variable name.'),
+        '#maxlength' => 255,
+        '#size' => 20,
+        '#title' => t('Custom variable name #@slot', array('@slot' => $i)),
+        '#title_display' => 'invisible',
+        '#type' => 'textfield',
+        '#element_validate' => array('googleanalytics_token_element_validate'),
+        '#token_types' => array('node'),
+      );
+      $form['google_analytics_custom_var']['slots'][$i]['value'] = array(
+        '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['value']) ? $googleanalytics_custom_vars['slots'][$i]['value'] : '',
+        '#description' => t('The custom variable value.'),
+        '#maxlength' => 255,
+        '#title' => t('Custom variable value #@slot', array('@slot' => $i)),
+        '#title_display' => 'invisible',
+        '#type' => 'textfield',
+        '#element_validate' => array('googleanalytics_token_element_validate'),
+        '#token_types' => array('node'),
+      );
+      if (module_exists('token')) {
+        $form['google_analytics_custom_var']['slots'][$i]['name']['#element_validate'][] = 'token_element_validate';
+        $form['google_analytics_custom_var']['slots'][$i]['value']['#element_validate'][] = 'token_element_validate';
+      }
+      $form['google_analytics_custom_var']['slots'][$i]['scope'] = array(
+        '#default_value' => !empty($googleanalytics_custom_vars['slots'][$i]['scope']) ? $googleanalytics_custom_vars['slots'][$i]['scope'] : 3,
+        '#description' => t('The scope for the custom variable.'),
+        '#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
+        '#title_display' => 'invisible',
+        '#type' => 'select',
+        '#options' => array(
+          1 => t('Visitor'),
+          2 => t('Session'),
+          3 => t('Page'),
+        ),
+      );
+    }
+
+    $form['google_analytics_custom_var']['google_analytics_custom_var_description'] = array(
+      '#type' => 'item',
+      '#description' => t('You can supplement Google Analytics\' basic IP address tracking of visitors by segmenting users based on custom variables. Section 7 of the <a href="@ga_tos">Google Analytics terms of service</a> requires that You will not (and will not allow any third party to) use the Service to track, collect or upload any data that personally identifies an individual (such as a name, email address or billing information), or other data which can be reasonably linked to such information by Google. You will have and abide by an appropriate Privacy Policy and will comply with all applicable laws and regulations relating to the collection of information from Visitors. You must post a Privacy Policy and that Privacy Policy must provide notice of Your use of cookies that are used to collect traffic data, and You must not circumvent any privacy features (e.g., an opt-out) that are part of the Service.', array('@ga_tos' => 'http://www.google.com/analytics/terms/gb.html')),
+    );
+    $form['google_analytics_custom_var']['google_analytics_custom_var_token_tree'] = array(
+      '#theme' => 'token_tree',
+      '#token_types' => array('node'),
+      '#dialog' => TRUE,
+    ); */
+
+
+    // Advanced feature configurations.
+    $form['advanced'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Advanced settings'),
+      '#collapsible' => TRUE,
+      '#collapsed' => TRUE,
+    );
+
+    $form['advanced']['google_analytics_cache'] = array(
+      '#type' => 'checkbox',
+      '#title' => t('Locally cache tracking code file'),
+      '#description' => t("If checked, the tracking code file is retrieved from Google Analytics and cached locally. It is updated daily from Google's servers to ensure updates to tracking code are reflected in the local copy. Do not activate this until after Google Analytics has confirmed that site tracking is working!"),
+      '#default_value' => $config->get('cache'),
+    );
+
+    // Allow for tracking of the originating node when viewing translation sets.
+    if (module_exists('translation')) {
+      $form['advanced']['google_analytics_translation_set'] = array(
+        '#type' => 'checkbox',
+        '#title' => t('Track translation sets as one unit'),
+        '#description' => t('When a node is part of a translation set, record statistics for the originating node instead. This allows for a translation set to be treated as a single unit.'),
+        '#default_value' => $config->get('translation_set'),
+      );
+    }
+
+    // @todo: Update urls once they are available.
+    $form['advanced']['codesnippet'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Custom JavaScript code'),
+      '#collapsible' => TRUE,
+      '#collapsed' => TRUE,
+      '#description' => t('You can add custom Google Analytics <a href="@snippets">code snippets</a> here. These will be added every time tracking is in effect. Before you add your custom code, you should read the <a href="@ga_concepts_overview">Google Analytics Tracking Code - Functional Overview</a> and the <a href="@ga_js_api">Google Analytics Tracking API</a> documentation. <strong>Do not include the &lt;script&gt; tags</strong>, and always end your code with a semicolon (;).', array('@snippets' => 'http://drupal.org/node/248699', '@ga_concepts_overview' => 'https://developers.google.com/analytics/resources/concepts/gaConceptsTrackingOverview', '@ga_js_api' => 'https://developers.google.com/analytics/devguides/collection/gajs/methods/')),
+    );
+    $form['advanced']['codesnippet']['google_analytics_codesnippet_before'] = array(
+      '#type' => 'textarea',
+      '#title' => t('Code snippet (before)'),
+      '#default_value' => $config->get('codesnippet.before'),
+      '#rows' => 5,
+      '#description' => t("Code in this textarea will be added <strong>before</strong> <code>ga('send', 'pageview');</code>."),
+    );
+    $form['advanced']['codesnippet']['google_analytics_codesnippet_after'] = array(
+      '#type' => 'textarea',
+      '#title' => t('Code snippet (after)'),
+      '#default_value' => $config->get('codesnippet.after'),
+      '#rows' => 5,
+      '#description' => t("Code in this textarea will be added <strong>after</strong> <code>ga('send', 'pageview');</code>. This is useful if you'd like to track a site in two accounts."),
+    );
+
+    $form['advanced']['google_analytics_js_scope'] = array(
+      '#type' => 'select',
+      '#title' => t('JavaScript scope'),
+      '#description' => t('Google recommends adding the external JavaScript files to the header for performance reasons. If <em>Multiple top-level domains</em> has been selected, this setting will be forced to header.'),
+      '#options' => array(
+        'footer' => t('Footer'),
+        'header' => t('Header'),
+      ),
+      '#default_value' => $config->get('js_scope'),
+      '#disabled' => ($config->get('domain_mode') == 2) ? TRUE : FALSE,
+    );
+
+    return parent::buildForm($form, $form_state);
+  }
+
+  /**
+   * Implements \Drupal\Core\Form\FormInterface::validateForm().
+   */
+  public function validateForm(array &$form, array &$form_state) {
+    parent::validateForm($form, $form_state);
+
+    // Custom variables validation.
+    /* @todo: upgrade to custom dimensions
+    foreach ($form_state['values']['google_analytics_custom_var']['slots'] as $custom_var) {
+      $form_state['values']['google_analytics_custom_var']['slots'][$custom_var['slot']]['name'] = trim($custom_var['name']);
+      $form_state['values']['google_analytics_custom_var']['slots'][$custom_var['slot']]['value'] = trim($custom_var['value']);
+
+      // Validate empty names/values.
+      if (empty($custom_var['name']) && !empty($custom_var['value'])) {
+        form_set_error("googleanalytics_custom_var][slots][" . $custom_var['slot'] . "][name", t('The custom variable @slot-number requires a <em>Name</em> if a <em>Value</em> has been provided.', array('@slot-number' =>  $custom_var['slot'])));
+      }
+      elseif (!empty($custom_var['name']) && empty($custom_var['value'])) {
+        form_set_error("googleanalytics_custom_var][slots][" . $custom_var['slot'] . "][value", t('The custom variable @slot-number requires a <em>Value</em> if a <em>Name</em> has been provided.', array('@slot-number' =>  $custom_var['slot'])));
+      }
+    } */
+
+    // Trim some text values.
+    $form_state['values']['google_analytics_account'] = trim($form_state['values']['google_analytics_account']);
+    $form_state['values']['google_analytics_pages'] = trim($form_state['values']['google_analytics_pages']);
+    $form_state['values']['google_analytics_cross_domains'] = trim($form_state['values']['google_analytics_cross_domains']);
+    $form_state['values']['google_analytics_codesnippet_before'] = trim($form_state['values']['google_analytics_codesnippet_before']);
+    $form_state['values']['google_analytics_codesnippet_after'] = trim($form_state['values']['google_analytics_codesnippet_after']);
+
+    // Replace all type of dashes (n-dash, m-dash, minus) with the normal dashes.
+    $form_state['values']['google_analytics_account'] = str_replace(array('–', '—', '?'), '-', $form_state['values']['google_analytics_account']);
+
+    if (!preg_match('/^UA-\d{4,}-\d+$/', $form_state['values']['google_analytics_account'])) {
+      form_set_error('google_analytics_account', t('A valid Google Analytics Web Property ID is case sensitive and formatted like UA-xxxxxxx-yy.'));
+    }
+
+    // If multiple top-level domains has been selected, a domain names list is required.
+    if ($form_state['values']['google_analytics_domain_mode'] == 2 && empty($form_state['values']['google_analytics_cross_domains'])) {
+      form_set_error('google_analytics_cross_domains', t('A list of top-level domains is required if <em>Multiple top-level domains</em> has been selected.'));
+    }
+    // Clear obsolete local cache if cache has been disabled.
+    if (empty($form_state['values']['google_analytics_cache']) && $form['advanced']['google_analytics_cache']['#default_value']) {
+      googleanalytics_clear_js_cache();
+    }
+
+    // This is for the Newbie's who cannot read a text area description.
+    if (stristr($form_state['values']['google_analytics_codesnippet_before'], 'google-analytics.com/analytics.js')) {
+      form_set_error('google_analytics_codesnippet_before', t('Do not add the tracker code provided by Google into the javascript code snippets! This module already builds the tracker code based on your Google Analytics account number and settings.'));
+    }
+    if (stristr($form_state['values']['google_analytics_codesnippet_after'], 'google-analytics.com/analytics.js')) {
+      form_set_error('google_analytics_codesnippet_after', t('Do not add the tracker code provided by Google into the javascript code snippets! This module already builds the tracker code based on your Google Analytics account number and settings.'));
+    }
+    if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['google_analytics_codesnippet_before'])) {
+      form_set_error('google_analytics_codesnippet_before', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
+    }
+    if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['google_analytics_codesnippet_after'])) {
+      form_set_error('google_analytics_codesnippet_after', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
+    }
+
+    // Header section must be forced for multiple top-level domains.
+    if ($form_state['values']['google_analytics_domain_mode'] == 2) {
+      $form_state['values']['google_analytics_js_scope'] = 'header';
+    }
+  }
+
+  /**
+   * Implements \Drupal\Core\Form\FormInterface::submitForm().
+   */
+  public function submitForm(array &$form, array &$form_state) {
+    $values = $form_state['values'];
+
+    $config = $this->configFactory->get('google_analytics.settings');
+    $config
+      ->set('account', $values['google_analytics_account']),
+      ->set('cross_domains', $values['googleanalytics_cross_domains']),
+      ->set('custom_var', $values['googleanalytics_custom_var']),
+      ->set('codesnippet.before', $values['googleanalytics_codesnippet_before']),
+      ->set('codesnippet.after', $values['googleanalytics_codesnippet_after']),
+      ->set('domain_mode', $values['googleanalytics_domain_mode']),
+      ->set('track.files', $values['googleanalytics_trackfiles']),
+      ->set('track.files_extensions', $values['googleanalytics_trackfiles_extensions']),
+      ->set('track.mailto', $values['googleanalytics_trackmailto']),
+      ->set('track.outbound', $values['googleanalytics_trackmailto']),
+      ->set('track.site_search', $values['googleanalytics_site_search']),
+      ->set('track.adsense', $values['googleanalytics_trackadsense']),
+      ->set('track.doubleclick', $values['googleanalytics_trackdoubleclick']),
+      ->set('privacy.anonymizeip', $values['googleanalytics_tracker_anonymizeip']),
+      ->set('privacy.donottrack', $values['googleanalytics_privacy_donottrack']),
+      ->set('translation_set', $values['googleanalytics_translation_set']),
+      ->set('js_scope', $values['googleanalytics_js_scope']),
+      ->set('cache', $values['googleanalytics_cache']),
+      ->set('last_cache', $values['googleanalytics_last_cache']),
+      ->set('visibility.pages_enabled', $values['googleanalytics_visibility_pages']),
+      ->set('visibility.pages', $values['googleanalytics_pages']),
+      ->set('visibility.roles_enabled', $values['googleanalytics_visibility_roles']),
+      ->set('visibility.roles', $values['googleanalytics_roles']),
+      ->save();
+
+    parent::submitForm($form, $form_state);
+  }
+
+}
diff --git a/lib/Drupal/google_analytics/Tests/Google_AnalyticsBasicTest.php b/lib/Drupal/google_analytics/Tests/Google_AnalyticsBasicTest.php
new file mode 100644
index 0000000..d71d6cd
--- /dev/null
+++ b/lib/Drupal/google_analytics/Tests/Google_AnalyticsBasicTest.php
@@ -0,0 +1,438 @@
+<?php
+
+/**
+ * @file
+ * Test file for Google Analytics module.
+ */
+class Google_AnalyticsBasicTest extends DrupalWebTestCase {
+
+  public static function getInfo() {
+    return array(
+      'name' => t('Google Analytics basic tests'),
+      'description' => t('Test basic functionality of Google Analytics module.'),
+      'group' => 'Google Analytics',
+    );
+  }
+
+  function setUp() {
+    parent::setUp('googleanalytics');
+
+    $permissions = array(
+      'access administration pages',
+      'administer google analytics',
+    );
+
+    // User to set up google_analytics.
+    $this->admin_user = $this->drupalCreateUser($permissions);
+    $this->drupalLogin($this->admin_user);
+  }
+
+  function testGoogleAnalyticsConfiguration() {
+    // Check for setting page's presence.
+    $this->drupalGet('admin/config/system/googleanalytics');
+    $this->assertRaw(t('Web Property ID'), '[testGoogleAnalyticsConfiguration]: Settings page displayed.');
+
+    // Check for account code validation.
+    $edit['googleanalytics_account'] = $this->randomName(2);
+    $this->drupalPost('admin/config/system/googleanalytics', $edit, 'Save configuration');
+    $this->assertRaw(t('A valid Google Analytics Web Property ID is case sensitive and formatted like UA-xxxxxxx-yy.'), '[testGoogleAnalyticsConfiguration]: Invalid Web Property ID number validated.');
+  }
+
+  function testGoogleAnalyticsPageVisibility() {
+    $ua_code = 'UA-123456-1';
+    variable_set('googleanalytics_account', $ua_code);
+
+    // Show tracking on "every page except the listed pages".
+    variable_set('googleanalytics_visibility_pages', 0);
+    // Disable tracking one "admin*" pages only.
+    variable_set('googleanalytics_pages', "admin\nadmin/*");
+    // Enable tracking only for authenticated users only.
+    variable_set('googleanalytics_roles', array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID));
+
+    // Check tracking code visibility.
+    $this->drupalGet('');
+    $this->assertRaw($ua_code, '[testGoogleAnalyticsPageVisibility]: Tracking code is displayed for authenticated users.');
+
+    // Test whether tracking code is not included on pages to omit.
+    $this->drupalGet('admin');
+    $this->assertNoRaw($ua_code, '[testGoogleAnalyticsPageVisibility]: Tracking code is not displayed on admin page.');
+    $this->drupalGet('admin/config/system/googleanalytics');
+    // Checking for tracking code URI here, as $ua_code is displayed in the form.
+    $this->assertNoRaw('google-analytics.com/analytics.js', '[testGoogleAnalyticsPageVisibility]: Tracking code is not displayed on admin subpage.');
+
+    // Test whether tracking code display is properly flipped.
+    variable_set('googleanalytics_visibility_pages', 1);
+    $this->drupalGet('admin');
+    $this->assertRaw($ua_code, '[testGoogleAnalyticsPageVisibility]: Tracking code is displayed on admin page.');
+    $this->drupalGet('admin/config/system/googleanalytics');
+    // Checking for tracking code URI here, as $ua_code is displayed in the form.
+    $this->assertRaw('google-analytics.com/analytics.js', '[testGoogleAnalyticsPageVisibility]: Tracking code is displayed on admin subpage.');
+    $this->drupalGet('');
+    $this->assertNoRaw($ua_code, '[testGoogleAnalyticsPageVisibility]: Tracking code is NOT displayed on front page.');
+
+    // Test whether tracking code is not display for anonymous.
+    $this->drupalLogout();
+    $this->drupalGet('');
+    $this->assertNoRaw($ua_code, '[testGoogleAnalyticsPageVisibility]: Tracking code is NOT displayed for anonymous.');
+
+    // Switch back to every page except the listed pages.
+    variable_set('googleanalytics_visibility_pages', 0);
+    // Enable tracking code for all user roles.
+    variable_set('googleanalytics_roles', array());
+
+    // Test whether 403 forbidden tracking code is shown if user has no access.
+    $this->drupalGet('admin');
+    $this->assertRaw('/403.html', '[testGoogleAnalyticsPageVisibility]: 403 Forbidden tracking code shown if user has no access.');
+
+    // Test whether 404 not found tracking code is shown on non-existent pages.
+    $this->drupalGet($this->randomName(64));
+    $this->assertRaw('/404.html', '[testGoogleAnalyticsPageVisibility]: 404 Not Found tracking code shown on non-existent page.');
+
+    // DNT Tests:
+    // Enable caching of pages for anonymous users.
+    variable_set('cache', 1);
+    // Test whether DNT headers will fail to disable embedding of tracking code.
+    $this->drupalGet('', array(), array('DNT: 1'));
+    $this->assertRaw('ga("send", "pageview");', '[testGoogleAnalyticsDNTVisibility]: DNT header send from client, but page caching is enabled and tracker cannot removed.');
+    // DNT works only with caching of pages for anonymous users disabled.
+    variable_set('cache', 0);
+    $this->drupalGet('');
+    $this->assertRaw('ga("send", "pageview");', '[testGoogleAnalyticsDNTVisibility]: Tracking is enabled without DNT header.');
+    // Test whether DNT header is able to remove the tracking code.
+    $this->drupalGet('', array(), array('DNT: 1'));
+    $this->assertNoRaw('ga("send", "pageview");', '[testGoogleAnalyticsDNTVisibility]: DNT header received from client. Tracking has been disabled by browser.');
+    // Disable DNT feature and see if tracker is still embedded.
+    variable_set('googleanalytics_privacy_donottrack', 0);
+    $this->drupalGet('', array(), array('DNT: 1'));
+    $this->assertRaw('ga("send", "pageview");', '[testGoogleAnalyticsDNTVisibility]: DNT feature is disabled, DNT header from browser has been ignored.');
+  }
+
+  function testGoogleAnalyticsTrackingCode() {
+    $ua_code = 'UA-123456-2';
+    variable_set('googleanalytics_account', $ua_code);
+
+    // Show tracking code on every page except the listed pages.
+    variable_set('googleanalytics_visibility_pages', 0);
+    // Enable tracking code for all user roles.
+    variable_set('googleanalytics_roles', array());
+
+    /* Sample JS code as added to page:
+    <script type="text/javascript" src="/sites/all/modules/google_analytics/googleanalytics.js?w"></script>
+    <script>
+    (function(q,u,i,c,k){window['GoogleAnalyticsObject']=q;
+    window[q]=window[q]||function(){(window[q].q=window[q].q||[]).push(arguments)},
+    window[q].l=1*new Date();c=i.createElement(u),k=i.getElementsByTagName(u)[0];
+    c.async=true;c.src='//www.google-analytics.com/analytics.js';
+    k.parentNode.insertBefore(c,k)})('ga','script',document);
+    ga('create', 'UA-123456-7');
+    ga('send', 'pageview');
+    </script>
+    <!-- End Google Analytics -->
+    */
+
+    // Test whether tracking code uses latest JS.
+    variable_set('googleanalytics_cache', 0);
+    $this->drupalGet('');
+    $this->assertRaw('google-analytics.com/analytics.js', '[testGoogleAnalyticsTrackingCode]: Latest tracking code used.');
+
+    // Test whether anonymize visitors IP address feature has been enabled.
+    $this->drupalGet('');
+    $this->assertNoRaw('ga("set", "anonymizeIp", 1);', '[testGoogleAnalyticsTrackingCode]: Anonymize visitors IP address not found on frontpage.');
+    // Enable anonymizing of IP addresses.
+    variable_set('googleanalytics_tracker_anonymizeip', 1);
+    $this->drupalGet('');
+    $this->assertRaw('ga("set", "anonymizeIp", 1);', '[testGoogleAnalyticsTrackingCode]: Anonymize visitors IP address found on frontpage.');
+
+    // Test whether single domain tracking is active.
+    $this->drupalGet('');
+    $this->assertNoRaw('ga("set", "cookieDomain",', '[testGoogleAnalyticsTrackingCode]: Single domain tracking is active.');
+
+    // Enable "One domain with multiple subdomains".
+    variable_set('googleanalytics_domain_mode', 1);
+    $this->drupalGet('');
+
+    // Test may run on localhost, an ipaddress or real domain name.
+    // TODO: Workaround to run tests successfully. This feature cannot tested reliable.
+    global $cookie_domain;
+    if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
+      $this->assertRaw('ga("set", "cookieDomain",', '[testGoogleAnalyticsTrackingCode]: One domain with multiple subdomains is active on real host.');
+    }
+    else {
+      // Special cases, Localhost and IP addresses don't show '_setDomainName'.
+      $this->assertNoRaw('ga("set", "cookieDomain",', '[testGoogleAnalyticsTrackingCode]: One domain with multiple subdomains may be active on localhost (test result is not reliable).');
+    }
+
+    // Enable "Multiple top-level domains" tracking.
+    variable_set('googleanalytics_domain_mode', 2);
+    variable_set('googleanalytics_cross_domains', "www.example.com\nwww.example.net");
+    $this->drupalGet('');
+    $this->assertRaw('ga("set", "cookieDomain", "none");', '[testGoogleAnalyticsTrackingCode]: _setDomainName: "none" found. Cross domain tracking is active.');
+    $this->assertRaw('ga("set", "allowLinker", true);', '[testGoogleAnalyticsTrackingCode]: _setAllowLinker: true found. Cross domain tracking is active.');
+    $this->assertRaw('"trackCrossDomains":["www.example.com","www.example.net"]', '[testGoogleAnalyticsTrackingCode]: Cross domain tracking with www.example.com and www.example.net is active.');
+
+    // Test whether the BEFORE and AFTER code is added to the tracker.
+    // @todo: review detectFlash once API docs are available.
+    variable_set('googleanalytics_codesnippet_before', 'ga("set", "detectFlash", false);');
+    variable_set('googleanalytics_codesnippet_after', 'ga("create", "UA-123456-3", {name: "newTracker"});ga("newTracker.send", "pageview");');
+    $this->drupalGet('');
+    $this->assertRaw('ga("set", "detectFlash", false);', '[testGoogleAnalyticsTrackingCode]: Before codesnippet has been found with "Flash" detection disabled.');
+    $this->assertRaw('ga("create", "UA-123456-3", {name: "newTracker"});', '[testGoogleAnalyticsTrackingCode]: After codesnippet with "newTracker" tracker has been found.');
+  }
+}
+
+/* @todo: upgrade to custom dimensions
+class GoogleAnalyticsCustomVariablesTest extends DrupalWebTestCase {
+
+  public static function getInfo() {
+    return array(
+      'name' => t('Google Analytics Custom Variables tests'),
+      'description' => t('Test custom variables functionality of Google Analytics module.'),
+      'group' => 'Google Analytics',
+      'dependencies' => array('token'),
+    );
+  }
+
+  function setUp() {
+    parent::setUp('googleanalytics', 'token');
+
+    $permissions = array(
+      'access administration pages',
+      'administer google analytics',
+    );
+
+    // User to set up google_analytics.
+    $this->admin_user = $this->drupalCreateUser($permissions);
+  }
+
+  function testGoogleAnalyticsCustomVariables() {
+    $ua_code = 'UA-123456-3';
+    variable_set('googleanalytics_account', $ua_code);
+
+    // Basic test if the feature works.
+    $custom_vars = array(
+      'slots' => array(
+        1 => array(
+          'slot' => 1,
+          'name' => 'Foo 1',
+          'value' => 'Bar 1',
+          'scope' => 3,
+        ),
+        2 => array(
+          'slot' => 2,
+          'name' => 'Foo 2',
+          'value' => 'Bar 2',
+          'scope' => 2,
+        ),
+        3 => array(
+          'slot' => 3,
+          'name' => 'Foo 3',
+          'value' => 'Bar 3',
+          'scope' => 3,
+        ),
+        4 => array(
+          'slot' => 4,
+          'name' => 'Foo 4',
+          'value' => 'Bar 4',
+          'scope' => 2,
+        ),
+        5 => array(
+          'slot' => 5,
+          'name' => 'Foo 5',
+          'value' => 'Bar 5',
+          'scope' => 1,
+        ),
+      )
+    );
+    variable_set('googleanalytics_custom_var', $custom_vars);
+    $this->drupalGet('');
+
+    foreach ($custom_vars['slots'] as $slot) {
+      $this->assertRaw("ga('set', 'customvar', " . $slot['slot'] . ", \"" . $slot['name'] . "\", \"" . $slot['value'] . "\", " . $slot['scope'] . ");", '[testGoogleAnalyticsCustomVariables]: _setCustomVar ' . $slot['slot'] . ' is shown.');
+    }
+
+    // Test whether tokens are replaced in custom variable names.
+    $site_slogan = $this->randomName(16);
+    variable_set('site_slogan', $site_slogan);
+
+    $custom_vars = array(
+      'slots' => array(
+        1 => array(
+          'slot' => 1,
+          'name' => 'Name: [site:slogan]',
+          'value' => 'Value: [site:slogan]',
+          'scope' => 3,
+        ),
+        2 => array(
+          'slot' => 2,
+          'name' => '',
+          'value' => $this->randomName(16),
+          'scope' => 1,
+        ),
+        3 => array(
+          'slot' => 3,
+          'name' => $this->randomName(16),
+          'value' => '',
+          'scope' => 2,
+        ),
+        4 => array(
+          'slot' => 4,
+          'name' => '',
+          'value' => '',
+          'scope' => 3,
+        ),
+        5 => array(
+          'slot' => 5,
+          'name' => '',
+          'value' => '',
+          'scope' => 3,
+        ),
+      )
+    );
+    variable_set('googleanalytics_custom_var', $custom_vars);
+    $this->verbose('<pre>' . print_r($custom_vars, TRUE) . '</pre>');
+
+    $this->drupalGet('');
+    $this->assertRaw("ga('set', 'customvar', 1, \"Name: $site_slogan\", \"Value: $site_slogan\", 3);", '[testGoogleAnalyticsCustomVariables]: Tokens have been replaced in custom variable.');
+    $this->assertNoRaw("ga('set', 'customvar', 2,", '[testGoogleAnalyticsCustomVariables]: Value with empty name is not shown.');
+    $this->assertNoRaw("ga('set', 'customvar', 3,", '[testGoogleAnalyticsCustomVariables]: Name with empty value is not shown.');
+    $this->assertNoRaw("ga('set', 'customvar', 4,", '[testGoogleAnalyticsCustomVariables]: Empty name and value is not shown.');
+    $this->assertNoRaw("ga('set', 'customvar', 5,", '[testGoogleAnalyticsCustomVariables]: Empty name and value is not shown.');
+  }
+} */
+
+class GoogleAnalyticsStatusMessagesTest extends DrupalWebTestCase {
+
+  public static function getInfo() {
+    return array(
+      'name' => t('Google Analytics status messages tests'),
+      'description' => t('Test status messages functionality of Google Analytics module.'),
+      'group' => 'Google Analytics',
+    );
+  }
+
+  function setUp() {
+    parent::setUp('googleanalytics');
+
+    $permissions = array(
+      'access administration pages',
+      'administer google analytics',
+    );
+
+    // User to set up google_analytics.
+    $this->admin_user = $this->drupalCreateUser($permissions);
+  }
+
+  function testGoogleAnalyticsStatusMessages() {
+    $ua_code = 'UA-123456-4';
+    variable_set('googleanalytics_account', $ua_code);
+
+    // Enable logging of errors only.
+    variable_set('googleanalytics_trackmessages', array('error' => 'error'));
+
+    $this->drupalPost('user/login', array(), 'Log in');
+    $this->assertRaw('ga("send", "event", "Messages", "Error message", "Username field is required.");', '[testGoogleAnalyticsStatusMessages]: Event message "Username field is required." is shown.');
+    $this->assertRaw('ga("send", "event", "Messages", "Error message", "Password field is required.");', '[testGoogleAnalyticsStatusMessages]: Event message "Password field is required." is shown.');
+
+    // @todo: investigate why drupal_set_message() fails.
+    //drupal_set_message('Example status message.', 'status');
+    //drupal_set_message('Example warning message.', 'warning');
+    //drupal_set_message('Example error message.', 'error');
+    //drupal_set_message('Example error <em>message</em> with html tags and <a href="http://example.com/">link</a>.', 'error');
+    //$this->drupalGet('');
+    //$this->assertNoRaw('ga("send", "event", "Messages", "Status message", "Example status message.");', '[testGoogleAnalyticsStatusMessages]: Example status message is not enabled for tracking.');
+    //$this->assertNoRaw('ga("send", "event", "Messages", "Warning message", "Example warning message.");', '[testGoogleAnalyticsStatusMessages]: Example warning message is not enabled for tracking.');
+    //$this->assertRaw('ga("send", "event", "Messages", "Error message", "Example error message.");', '[testGoogleAnalyticsStatusMessages]: Example error message is shown.');
+    //$this->assertRaw('ga("send", "event", "Messages", "Error message", "Example error message with html tags and link.");', '[testGoogleAnalyticsStatusMessages]: HTML has been stripped successful from Example error message with html tags and link.');
+  }
+}
+
+class GoogleAnalyticsRolesTest extends DrupalWebTestCase {
+
+  public static function getInfo() {
+    return array(
+      'name' => t('Google Analytics role tests'),
+      'description' => t('Test roles functionality of Google Analytics module.'),
+      'group' => 'Google Analytics',
+    );
+  }
+
+  function setUp() {
+    parent::setUp('googleanalytics');
+
+    $permissions = array(
+      'access administration pages',
+      'administer google analytics',
+    );
+
+    // User to set up google_analytics.
+    $this->admin_user = $this->drupalCreateUser($permissions);
+  }
+
+  function testGoogleAnalyticsRolesTracking() {
+    $ua_code = 'UA-123456-4';
+    variable_set('googleanalytics_account', $ua_code);
+
+    // Test if the default settings are working as expected.
+
+    // Add to the selected roles only.
+    variable_set('googleanalytics_visibility_roles', 0);
+    // Enable tracking for all users.
+    variable_set('googleanalytics_roles', array());
+
+    // Check tracking code visibility.
+    $this->drupalGet('');
+    $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is displayed for anonymous users on frontpage with default settings.');
+    $this->drupalGet('admin');
+    $this->assertRaw('/403.html', '[testGoogleAnalyticsRoleVisibility]: 403 Forbidden tracking code is displayed for anonymous users in admin section with default settings.');
+
+    $this->drupalLogin($this->admin_user);
+
+    $this->drupalGet('');
+    $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is displayed for authenticated users on frontpage with default settings.');
+    $this->drupalGet('admin');
+    $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is NOT displayed for authenticated users in admin section with default settings.');
+
+    // Test if the non-default settings are working as expected.
+
+    // Enable tracking only for authenticated users.
+    variable_set('googleanalytics_roles', array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID));
+
+    $this->drupalGet('');
+    $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is displayed for authenticated users only on frontpage.');
+
+    $this->drupalLogout();
+    $this->drupalGet('');
+    $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is NOT displayed for anonymous users on frontpage.');
+
+    // Add to every role except the selected ones.
+    variable_set('googleanalytics_visibility_roles', 1);
+    // Enable tracking for all users.
+    variable_set('googleanalytics_roles', array());
+
+    // Check tracking code visibility.
+    $this->drupalGet('');
+    $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is added to every role and displayed for anonymous users.');
+    $this->drupalGet('admin');
+    $this->assertRaw('/403.html', '[testGoogleAnalyticsRoleVisibility]: 403 Forbidden tracking code is shown for anonymous users if every role except the selected ones is selected.');
+
+    $this->drupalLogin($this->admin_user);
+
+    $this->drupalGet('');
+    $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is added to every role and displayed on frontpage for authenticated users.');
+    $this->drupalGet('admin');
+    $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is added to every role and NOT displayed in admin section for authenticated users.');
+
+    // Disable tracking for authenticated users.
+    variable_set('googleanalytics_roles', array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID));
+
+    $this->drupalGet('');
+    $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is NOT displayed on frontpage for excluded authenticated users.');
+    $this->drupalGet('admin');
+    $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is NOT displayed in admin section for excluded authenticated users.');
+
+    $this->drupalLogout();
+    $this->drupalGet('');
+    $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is displayed on frontpage for included anonymous users.');
+  }
+
+}
diff --git a/lib/Drupal/google_analytics/Tests/Google_AnalyticsCustomVariablesTest.php b/lib/Drupal/google_analytics/Tests/Google_AnalyticsCustomVariablesTest.php
new file mode 100644
index 0000000..44f5d8e
--- /dev/null
+++ b/lib/Drupal/google_analytics/Tests/Google_AnalyticsCustomVariablesTest.php
@@ -0,0 +1,125 @@
+<?php
+
+/**
+ * @file
+ * Test file for Google Analytics module.
+ */
+/* @todo: upgrade to custom dimensions
+class Google_AnalyticsCustomVariablesTest extends DrupalWebTestCase {
+
+  public static function getInfo() {
+    return array(
+      'name' => t('Google Analytics Custom Variables tests'),
+      'description' => t('Test custom variables functionality of Google Analytics module.'),
+      'group' => 'Google Analytics',
+      'dependencies' => array('token'),
+    );
+  }
+
+  function setUp() {
+    parent::setUp('googleanalytics', 'token');
+
+    $permissions = array(
+      'access administration pages',
+      'administer google analytics',
+    );
+
+    // User to set up google_analytics.
+    $this->admin_user = $this->drupalCreateUser($permissions);
+  }
+
+  function testGoogleAnalyticsCustomVariables() {
+    $ua_code = 'UA-123456-3';
+    variable_set('googleanalytics_account', $ua_code);
+
+    // Basic test if the feature works.
+    $custom_vars = array(
+      'slots' => array(
+        1 => array(
+          'slot' => 1,
+          'name' => 'Foo 1',
+          'value' => 'Bar 1',
+          'scope' => 3,
+        ),
+        2 => array(
+          'slot' => 2,
+          'name' => 'Foo 2',
+          'value' => 'Bar 2',
+          'scope' => 2,
+        ),
+        3 => array(
+          'slot' => 3,
+          'name' => 'Foo 3',
+          'value' => 'Bar 3',
+          'scope' => 3,
+        ),
+        4 => array(
+          'slot' => 4,
+          'name' => 'Foo 4',
+          'value' => 'Bar 4',
+          'scope' => 2,
+        ),
+        5 => array(
+          'slot' => 5,
+          'name' => 'Foo 5',
+          'value' => 'Bar 5',
+          'scope' => 1,
+        ),
+      )
+    );
+    variable_set('googleanalytics_custom_var', $custom_vars);
+    $this->drupalGet('');
+
+    foreach ($custom_vars['slots'] as $slot) {
+      $this->assertRaw("ga('set', 'customvar', " . $slot['slot'] . ", \"" . $slot['name'] . "\", \"" . $slot['value'] . "\", " . $slot['scope'] . ");", '[testGoogleAnalyticsCustomVariables]: _setCustomVar ' . $slot['slot'] . ' is shown.');
+    }
+
+    // Test whether tokens are replaced in custom variable names.
+    $site_slogan = $this->randomName(16);
+    variable_set('site_slogan', $site_slogan);
+
+    $custom_vars = array(
+      'slots' => array(
+        1 => array(
+          'slot' => 1,
+          'name' => 'Name: [site:slogan]',
+          'value' => 'Value: [site:slogan]',
+          'scope' => 3,
+        ),
+        2 => array(
+          'slot' => 2,
+          'name' => '',
+          'value' => $this->randomName(16),
+          'scope' => 1,
+        ),
+        3 => array(
+          'slot' => 3,
+          'name' => $this->randomName(16),
+          'value' => '',
+          'scope' => 2,
+        ),
+        4 => array(
+          'slot' => 4,
+          'name' => '',
+          'value' => '',
+          'scope' => 3,
+        ),
+        5 => array(
+          'slot' => 5,
+          'name' => '',
+          'value' => '',
+          'scope' => 3,
+        ),
+      )
+    );
+    variable_set('googleanalytics_custom_var', $custom_vars);
+    $this->verbose('<pre>' . print_r($custom_vars, TRUE) . '</pre>');
+
+    $this->drupalGet('');
+    $this->assertRaw("ga('set', 'customvar', 1, \"Name: $site_slogan\", \"Value: $site_slogan\", 3);", '[testGoogleAnalyticsCustomVariables]: Tokens have been replaced in custom variable.');
+    $this->assertNoRaw("ga('set', 'customvar', 2,", '[testGoogleAnalyticsCustomVariables]: Value with empty name is not shown.');
+    $this->assertNoRaw("ga('set', 'customvar', 3,", '[testGoogleAnalyticsCustomVariables]: Name with empty value is not shown.');
+    $this->assertNoRaw("ga('set', 'customvar', 4,", '[testGoogleAnalyticsCustomVariables]: Empty name and value is not shown.');
+    $this->assertNoRaw("ga('set', 'customvar', 5,", '[testGoogleAnalyticsCustomVariables]: Empty name and value is not shown.');
+  }
+} */
diff --git a/lib/Drupal/google_analytics/Tests/Google_AnalyticsRolesTest.php b/lib/Drupal/google_analytics/Tests/Google_AnalyticsRolesTest.php
new file mode 100644
index 0000000..d91f8b1
--- /dev/null
+++ b/lib/Drupal/google_analytics/Tests/Google_AnalyticsRolesTest.php
@@ -0,0 +1,96 @@
+<?php
+
+/**
+ * @file
+ * Test file for Google Analytics module.
+ */
+class Google_AnalyticsRolesTest extends DrupalWebTestCase {
+
+  public static function getInfo() {
+    return array(
+      'name' => t('Google Analytics role tests'),
+      'description' => t('Test roles functionality of Google Analytics module.'),
+      'group' => 'Google Analytics',
+    );
+  }
+
+  function setUp() {
+    parent::setUp('googleanalytics');
+
+    $permissions = array(
+      'access administration pages',
+      'administer google analytics',
+    );
+
+    // User to set up google_analytics.
+    $this->admin_user = $this->drupalCreateUser($permissions);
+  }
+
+  function testGoogleAnalyticsRolesTracking() {
+    $ua_code = 'UA-123456-4';
+    variable_set('googleanalytics_account', $ua_code);
+
+    // Test if the default settings are working as expected.
+
+    // Add to the selected roles only.
+    variable_set('googleanalytics_visibility_roles', 0);
+    // Enable tracking for all users.
+    variable_set('googleanalytics_roles', array());
+
+    // Check tracking code visibility.
+    $this->drupalGet('');
+    $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is displayed for anonymous users on frontpage with default settings.');
+    $this->drupalGet('admin');
+    $this->assertRaw('/403.html', '[testGoogleAnalyticsRoleVisibility]: 403 Forbidden tracking code is displayed for anonymous users in admin section with default settings.');
+
+    $this->drupalLogin($this->admin_user);
+
+    $this->drupalGet('');
+    $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is displayed for authenticated users on frontpage with default settings.');
+    $this->drupalGet('admin');
+    $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is NOT displayed for authenticated users in admin section with default settings.');
+
+    // Test if the non-default settings are working as expected.
+
+    // Enable tracking only for authenticated users.
+    variable_set('googleanalytics_roles', array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID));
+
+    $this->drupalGet('');
+    $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is displayed for authenticated users only on frontpage.');
+
+    $this->drupalLogout();
+    $this->drupalGet('');
+    $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is NOT displayed for anonymous users on frontpage.');
+
+    // Add to every role except the selected ones.
+    variable_set('googleanalytics_visibility_roles', 1);
+    // Enable tracking for all users.
+    variable_set('googleanalytics_roles', array());
+
+    // Check tracking code visibility.
+    $this->drupalGet('');
+    $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is added to every role and displayed for anonymous users.');
+    $this->drupalGet('admin');
+    $this->assertRaw('/403.html', '[testGoogleAnalyticsRoleVisibility]: 403 Forbidden tracking code is shown for anonymous users if every role except the selected ones is selected.');
+
+    $this->drupalLogin($this->admin_user);
+
+    $this->drupalGet('');
+    $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is added to every role and displayed on frontpage for authenticated users.');
+    $this->drupalGet('admin');
+    $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is added to every role and NOT displayed in admin section for authenticated users.');
+
+    // Disable tracking for authenticated users.
+    variable_set('googleanalytics_roles', array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID));
+
+    $this->drupalGet('');
+    $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is NOT displayed on frontpage for excluded authenticated users.');
+    $this->drupalGet('admin');
+    $this->assertNoRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is NOT displayed in admin section for excluded authenticated users.');
+
+    $this->drupalLogout();
+    $this->drupalGet('');
+    $this->assertRaw($ua_code, '[testGoogleAnalyticsRoleVisibility]: Tracking code is displayed on frontpage for included anonymous users.');
+  }
+
+}
diff --git a/lib/Drupal/google_analytics/Tests/Google_AnalyticsStatusMessagesTest.php b/lib/Drupal/google_analytics/Tests/Google_AnalyticsStatusMessagesTest.php
new file mode 100644
index 0000000..0e24ca0
--- /dev/null
+++ b/lib/Drupal/google_analytics/Tests/Google_AnalyticsStatusMessagesTest.php
@@ -0,0 +1,51 @@
+<?php
+
+/**
+ * @file
+ * Test file for Google Analytics module.
+ */
+class Google_AnalyticsStatusMessagesTest extends DrupalWebTestCase {
+
+  public static function getInfo() {
+    return array(
+      'name' => t('Google Analytics status messages tests'),
+      'description' => t('Test status messages functionality of Google Analytics module.'),
+      'group' => 'Google Analytics',
+    );
+  }
+
+  function setUp() {
+    parent::setUp('googleanalytics');
+
+    $permissions = array(
+      'access administration pages',
+      'administer google analytics',
+    );
+
+    // User to set up google_analytics.
+    $this->admin_user = $this->drupalCreateUser($permissions);
+  }
+
+  function testGoogleAnalyticsStatusMessages() {
+    $ua_code = 'UA-123456-4';
+    variable_set('googleanalytics_account', $ua_code);
+
+    // Enable logging of errors only.
+    variable_set('googleanalytics_trackmessages', array('error' => 'error'));
+
+    $this->drupalPost('user/login', array(), 'Log in');
+    $this->assertRaw('ga("send", "event", "Messages", "Error message", "Username field is required.");', '[testGoogleAnalyticsStatusMessages]: Event message "Username field is required." is shown.');
+    $this->assertRaw('ga("send", "event", "Messages", "Error message", "Password field is required.");', '[testGoogleAnalyticsStatusMessages]: Event message "Password field is required." is shown.');
+
+    // @todo: investigate why drupal_set_message() fails.
+    //drupal_set_message('Example status message.', 'status');
+    //drupal_set_message('Example warning message.', 'warning');
+    //drupal_set_message('Example error message.', 'error');
+    //drupal_set_message('Example error <em>message</em> with html tags and <a href="http://example.com/">link</a>.', 'error');
+    //$this->drupalGet('');
+    //$this->assertNoRaw('ga("send", "event", "Messages", "Status message", "Example status message.");', '[testGoogleAnalyticsStatusMessages]: Example status message is not enabled for tracking.');
+    //$this->assertNoRaw('ga("send", "event", "Messages", "Warning message", "Example warning message.");', '[testGoogleAnalyticsStatusMessages]: Example warning message is not enabled for tracking.');
+    //$this->assertRaw('ga("send", "event", "Messages", "Error message", "Example error message.");', '[testGoogleAnalyticsStatusMessages]: Example error message is shown.');
+    //$this->assertRaw('ga("send", "event", "Messages", "Error message", "Example error message with html tags and link.");', '[testGoogleAnalyticsStatusMessages]: HTML has been stripped successful from Example error message with html tags and link.');
+  }
+}
