diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/googleanalytics.admin.inc b/googleanalytics.admin.inc index cd2d9dd..d922ed0 100644 --- a/googleanalytics.admin.inc +++ b/googleanalytics.admin.inc @@ -5,6 +5,7 @@ * Administrative page callbacks for the googleanalytics module. */ + /** * Implementation of hook_admin_settings() for module settings configuration. */ @@ -12,23 +13,34 @@ function googleanalytics_admin_settings_form(&$form_state) { $form['account'] = array( '#type' => 'fieldset', '#title' => t('General settings'), - '#collapsible' => FALSE, ); $form['account']['googleanalytics_account'] = array( + '#title' => t('Web Property ID(s)'), '#type' => 'textfield', - '#title' => t('Web Property ID'), - '#default_value' => variable_get('googleanalytics_account', 'UA-'), - '#size' => 15, - '#maxlength' => 20, + '#default_value' => variable_get('googleanalytics_account', 'G-'), + '#size' => 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, register your site with Google Analytics, or if you already have registered your site, go to your Google Analytics Settings page to see the ID next to every site profile. Find more information in the documentation.', array('@analytics' => 'http://www.google.com/analytics/', '@webpropertyid' => url('https://developers.google.com/analytics/resources/concepts/gaConceptsAccounts', array('fragment' => 'webProperty')))), + '#description' => t('This ID is unique to each site you want to track separately, and is in the form G-XXXXXXX, UA-xxxxxxx-yy, DC-XXXXXXX, or AW-XXXXXXX. To get a Web Property ID, register your site with Google Analytics, or if you already have registered your site, go to your Google Analytics Settings page to see the ID next to every site profile. Find more information in the documentation. If you want to track with multiple IDs (for example, using both GA4 and UA for legacy tracking) seperate them with commas.', array('@analytics' => 'https://marketingplatform.google.com/about/analytics/', '@webpropertyid' => url('https://support.google.com/analytics/answer/10089681', array('fragment' => 'webProperty')))), ); - $form['domain_tracking'] = array( + $form['account']['googleanalytics_premium'] = array( + '#type' => 'checkbox', + '#title' => t('Analytics 360 (Premium) account'), + '#description' => t('If you are a Google Analytics 360 (Premium) customer, you can use up to 200 instead of 20 custom dimensions and metrics.'), + '#default_value' => variable_get('googleanalytics_premium', FALSE), + ); + + // Visibility settings. + $form['tracking_title'] = array( + '#type' => 'item', + '#title' => t('Tracking scope'), + ); + + + $form['tracking']['domain_tracking'] = array( '#type' => 'fieldset', '#title' => t('Domains'), - '#collapsible' => TRUE, ); global $cookie_domain; @@ -56,7 +68,7 @@ function googleanalytics_admin_settings_form(&$form_state) { } } - $form['domain_tracking']['googleanalytics_domain_mode'] = array( + $form['tracking']['domain_tracking']['googleanalytics_domain_mode'] = array( '#type' => 'radios', '#title' => t('What are you tracking?'), '#options' => array( @@ -67,29 +79,29 @@ function googleanalytics_admin_settings_form(&$form_state) { '#default_value' => variable_get('googleanalytics_domain_mode', 0), ); - $form['domain_tracking']['googleanalytics_cross_domains'] = array( + $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 Show separate domain names in Tracking Multiple Domains.', array('@url' => 'https://support.google.com/analytics/answer/1034342')), + '#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 Show separate domain names in Tracking Multiple Domains.', array('@url' => 'https://support.google.com/analytics/answer/10071811')), ); // Page specific visibility configurations. - $form['page_vis_settings'] = array( + $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, ); - $php_access = user_access('use PHP for tracking visibility'); - $visibility = variable_get('googleanalytics_visibility', 0); - $pages = variable_get('googleanalytics_pages', GOOGLEANALYTICS_PAGES); - if ($visibility == 2 && !$php_access) { - $form['page_vis_settings'] = array(); - $form['page_vis_settings']['googleanalytics_visibility'] = array('#type' => 'value', '#value' => 2); - $form['page_vis_settings']['googleanalytics_pages'] = array('#type' => 'value', '#value' => $pages); + $form['tracking']['page_vis_settings'] = array(); + $form['tracking']['page_vis_settings']['googleanalytics_visibility_pages'] = array('#type' => 'value', '#value' => 2); + $form['tracking']['page_vis_settings']['googleanalytics_pages'] = array('#type' => 'value', '#value' => $pages); } else { $options = array( @@ -106,31 +118,30 @@ function googleanalytics_admin_settings_form(&$form_state) { else { $title = t('Pages'); } - $form['page_vis_settings']['googleanalytics_visibility'] = array( + $form['tracking']['page_vis_settings']['googleanalytics_visibility_pages'] = array( '#type' => 'radios', '#title' => t('Add tracking to specific pages'), '#options' => $options, '#default_value' => $visibility, ); - $form['page_vis_settings']['googleanalytics_pages'] = array( + $form['tracking']['page_vis_settings']['googleanalytics_pages'] = array( '#type' => 'textarea', '#title' => $title, '#default_value' => $pages, '#description' => $description, - '#wysiwyg' => FALSE, '#rows' => 10, ); } // Render the role overview. - $form['role_vis_settings'] = array( + $form['tracking']['role_vis_settings'] = array( '#type' => 'fieldset', '#title' => t('Roles'), '#collapsible' => TRUE, '#collapsed' => TRUE, ); - $form['role_vis_settings']['googleanalytics_visibility_roles'] = array( + $form['tracking']['role_vis_settings']['googleanalytics_visibility_roles'] = array( '#type' => 'radios', '#title' => t('Add tracking for specific roles'), '#options' => array( @@ -145,7 +156,7 @@ function googleanalytics_admin_settings_form(&$form_state) { foreach ($roles as $rid => $name) { $role_options[$rid] = $name; } - $form['role_vis_settings']['googleanalytics_roles'] = array( + $form['tracking']['role_vis_settings']['googleanalytics_roles'] = array( '#type' => 'checkboxes', '#title' => t('Roles'), '#default_value' => variable_get('googleanalytics_roles', array()), @@ -154,15 +165,12 @@ function googleanalytics_admin_settings_form(&$form_state) { ); // Standard tracking configurations. - $form['user_vis_settings'] = array( + $form['tracking']['user_vis_settings'] = array( '#type' => 'fieldset', '#title' => t('Users'), - '#collapsible' => TRUE, - '#collapsed' => TRUE, ); - - $t_permission = array('%permission' => t('opt-in or out of tracking')); - $form['user_vis_settings']['googleanalytics_custom'] = array( + $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( @@ -172,49 +180,60 @@ function googleanalytics_admin_settings_form(&$form_state) { ), '#default_value' => variable_get('googleanalytics_custom', 0), ); - $form['user_vis_settings']['googleanalytics_trackuserid'] = array( + $form['tracking']['user_vis_settings']['googleanalytics_trackuserid'] = array( '#type' => 'checkbox', '#title' => t('Track User ID'), '#default_value' => variable_get('googleanalytics_trackuserid', 0), - '#description' => t('User ID enables the analysis of groups of sessions, across devices, using a unique, persistent, and non-personally identifiable ID string representing a user. Learn more about the benefits of using User ID.', array('@url' => 'https://support.google.com/analytics/answer/3123663')), + '#description' => t('User ID enables the analysis of groups of sessions, across devices, using a unique, persistent, and non-personally identifiable ID string representing a user. Learn more about the benefits of using User ID.', array('@url' => 'https://support.google.com/analytics/answer/9213390')), ); // Link specific configurations. - $form['linktracking'] = array( + $form['tracking']['linktracking'] = array( '#type' => 'fieldset', '#title' => t('Links and downloads'), - '#collapsible' => TRUE, - '#collapsed' => TRUE, ); - $form['linktracking']['googleanalytics_trackoutgoing'] = array( + $form['tracking']['linktracking']['googleanalytics_trackoutbound'] = array( '#type' => 'checkbox', '#title' => t('Track clicks on outbound links'), - '#default_value' => variable_get('googleanalytics_trackoutgoing', 1), + '#default_value' => variable_get('googleanalytics_trackoutbound', 1), ); - $form['linktracking']['googleanalytics_trackmailto'] = array( + $form['tracking']['linktracking']['googleanalytics_trackmailto'] = array( '#type' => 'checkbox', '#title' => t('Track clicks on mailto links'), '#default_value' => variable_get('googleanalytics_trackmailto', 1), ); - $form['linktracking']['googleanalytics_trackfiles'] = array( + $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['linktracking']['googleanalytics_trackfiles_extensions'] = array( - '#type' => 'textfield', + $form['tracking']['linktracking']['googleanalytics_trackfiles_extensions'] = array( '#title' => t('List of download file extensions'), + '#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' => 500, ); - $form['linktracking']['googleanalytics_tracklinkid'] = array( + + $colorbox_dependencies = '
'; + $colorbox_dependencies .= t('Requires: !module-list', array('!module-list' => (module_exists('colorbox') ? t('@module (enabled)', array('@module' => 'Colorbox')) : t('@module (disabled)', array('@module' => 'Colorbox'))))); + $colorbox_dependencies .= '
'; + + $form['tracking']['linktracking']['googleanalytics_trackcolorbox'] = array( + '#type' => 'checkbox', + '#title' => t('Track content in colorbox modal dialogs'), + '#default_value' => variable_get('googleanalytics_trackcolorbox', 1), + '#description' => t('Enable to track the content shown in colorbox modal windows.') . $colorbox_dependencies, + '#disabled' => (module_exists('colorbox') ? FALSE : TRUE), + ); + + $form['tracking']['linktracking']['googleanalytics_tracklinkid'] = array( '#type' => 'checkbox', '#title' => t('Track enhanced link attribution'), '#default_value' => variable_get('googleanalytics_tracklinkid', 0), '#description' => t('Enhanced Link Attribution improves the accuracy of your In-Page Analytics report by automatically differentiating between multiple links to the same URL on a single page by using link element IDs. Enable enhanced link attribution in the Admin UI of your Google Analytics account.', array('@url' => 'https://support.google.com/analytics/answer/2558867')), ); - $form['linktracking']['googleanalytics_trackurlfragments'] = array( + $form['tracking']['linktracking']['googleanalytics_trackurlfragments'] = array( '#type' => 'checkbox', '#title' => t('Track changing URL fragments as pageviews'), '#default_value' => variable_get('googleanalytics_trackurlfragments', 0), @@ -222,13 +241,11 @@ function googleanalytics_admin_settings_form(&$form_state) { ); // Message specific configurations. - $form['messagetracking'] = array( + $form['tracking']['messagetracking'] = array( '#type' => 'fieldset', '#title' => t('Messages'), - '#collapsible' => TRUE, - '#collapsed' => TRUE, ); - $form['messagetracking']['googleanalytics_trackmessages'] = array( + $form['tracking']['messagetracking']['googleanalytics_trackmessages'] = array( '#type' => 'checkboxes', '#title' => t('Track messages of type'), '#default_value' => variable_get('googleanalytics_trackmessages', array()), @@ -240,54 +257,50 @@ function googleanalytics_admin_settings_form(&$form_state) { ), ); - $form['search_and_advertising'] = array( + $form['tracking']['search_and_advertising'] = array( '#type' => 'fieldset', '#title' => t('Search and Advertising'), - '#collapsible' => TRUE, - '#collapsed' => TRUE, ); - $site_search_dependencies = '
'; - $site_search_dependencies .= t('Depends on: !dependencies', array('!dependencies' => (module_exists('search') ? t('@module (enabled)', array('@module' => 'Search')) : t('@module (disabled)', array('@module' => 'Search'))))); + $site_search_dependencies = '
'; + $site_search_dependencies .= t('Requires: !module-list', array('!module-list' => (module_exists('search') ? t('@module (enabled)', array('@module' => 'Search')) : t('@module (disabled)', array('@module' => 'Search'))))); $site_search_dependencies .= '
'; - $form['search_and_advertising']['googleanalytics_site_search'] = array( + $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 search. For more information see Setting Up Site Search for a Profile.', array('@url' => url('http://support.google.com/analytics/bin/answer.py', array('query' => array('answer' => '1012264'))))) . $site_search_dependencies, + '#description' => t('If checked, internal search keywords are tracked. You must configure your Google account to use the internal query parameter search. For more information see Setting Up Site Search for a Profile.', array('@url' => 'https://support.google.com/analytics/answer/9216061')) . $site_search_dependencies, '#default_value' => variable_get('googleanalytics_site_search', FALSE), '#disabled' => (module_exists('search') ? FALSE : TRUE), ); - $form['search_and_advertising']['googleanalytics_trackadsense'] = array( + $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['search_and_advertising']['googleanalytics_trackdoubleclick'] = array( + $form['tracking']['search_and_advertising']['googleanalytics_trackdoubleclick'] = array( '#type' => 'checkbox', '#title' => t('Track display features'), - '#description' => t('The display features plugin can be used to enable Display Advertising Features in Google Analytics, such as Remarketing, Demographics and Interest Reporting, and more. Learn more about Display Advertising Features in Google Analytics. If you choose this option you will need to update your privacy policy.', array('@displayfeatures' => 'https://support.google.com/analytics/answer/3450482', '@privacy' => url('https://support.google.com/analytics/answer/2700409'))), + '#description' => t('The display features plugin can be used to enable Display Advertising Features in Google Analytics, such as Remarketing, Demographics and Interest Reporting, and more. Learn more about Display Advertising Features in Google Analytics. If you choose this option you will need to update your privacy policy.', array('@displayfeatures' => 'https://support.google.com/analytics/answer/3450482', '@privacy' => 'https://support.google.com/analytics/answer/2700409')), '#default_value' => variable_get('googleanalytics_trackdoubleclick', FALSE), ); // Privacy specific configurations. - $form['privacy'] = array( + $form['tracking']['privacy'] = array( '#type' => 'fieldset', '#title' => t('Privacy'), - '#collapsible' => TRUE, - '#collapsed' => TRUE, ); - $form['privacy']['googleanalytics_tracker_anonymizeip'] = array( + $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.'), + '#title' => t('Anonymize visitors IP address (UA only)'), + '#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. This option has no effect in GA4, as all data is anonymized. 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', 1), ); - $form['privacy']['googleanalytics_privacy_donottrack'] = array( + $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 Do-Not-Track 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/')), + '#description' => t('If enabled and your server receives the Do-Not-Track 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' => 'https://www.eff.org/issues/do-not-track')), '#default_value' => variable_get('googleanalytics_privacy_donottrack', 1), ); @@ -304,39 +317,50 @@ function googleanalytics_admin_settings_form(&$form_state) { $googleanalytics_custom_dimension = variable_get('googleanalytics_custom_dimension', array()); - // Google Analytics supports up to 20 custom dimensions. - for ($i = 1; $i <= 20; $i++) { - // TODO: '#default_value' is currently broken, see http://drupal.org/node/410926. + // Standard Google Analytics accounts support up to 20 custom dimensions, + // premium accounts support up to 200 custom dimensions. + $limit = (variable_get('googleanalytics_premium', FALSE)) ? 200 : 20; + for ($i = 1; $i <= $limit; $i++) { $form['googleanalytics_custom_dimension']['indexes'][$i]['index'] = array( - //'#default_value' => $i, + '#default_value' => $i, '#description' => t('Index number'), '#disabled' => TRUE, '#size' => 1, + '#title' => t('Custom dimension index #@index', array('@index' => $i)), + '#title_display' => 'invisible', + '#type' => 'textfield', + ); + $form['googleanalytics_custom_dimension']['indexes'][$i]['name'] = array( + '#default_value' => isset($googleanalytics_custom_dimension[$i]['name']) ? $googleanalytics_custom_dimension[$i]['name'] : '', + '#description' => t('The custom dimension name.'), + '#maxlength' => 255, + '#title' => t('Custom dimension name #@index', array('@index' => $i)), + '#title_display' => 'invisible', '#type' => 'textfield', - '#value' => $i, ); $form['googleanalytics_custom_dimension']['indexes'][$i]['value'] = array( '#default_value' => isset($googleanalytics_custom_dimension[$i]['value']) ? $googleanalytics_custom_dimension[$i]['value'] : '', '#description' => t('The custom dimension value.'), '#maxlength' => 255, + '#title' => t('Custom dimension value #@index', array('@index' => $i)), '#type' => 'textfield', + '#element_validate' => array('googleanalytics_token_element_validate'), + '#token_types' => array('node'), ); if (module_exists('token')) { - $form['googleanalytics_custom_dimension']['indexes'][$i]['value']['#element_validate'][] = 'googleanalytics_token_element_validate'; $form['googleanalytics_custom_dimension']['indexes'][$i]['value']['#element_validate'][] = 'token_element_validate'; - $form['googleanalytics_custom_dimension']['indexes'][$i]['value']['#token_types'][] = 'node'; - $form['googleanalytics_custom_dimension']['indexes'][$i]['value']['#token_types'][] = 'user'; } } $form['googleanalytics_custom_dimension']['googleanalytics_description'] = array( '#type' => 'item', - '#description' => t('You can supplement Google Analytics\' basic IP address tracking of visitors by segmenting users based on custom dimensions. Section 7 of the Google Analytics terms of service 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, userid, 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')), + '#description' => t('You can supplement Google Analytics\' basic IP address tracking of visitors by segmenting users based on custom dimensions. Section 7 of the Google Analytics terms of service 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, userid, 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' => 'https://www.google.com/analytics/terms/gb.html')), ); if (module_exists('token')) { $form['googleanalytics_custom_dimension']['googleanalytics_token_tree'] = array( '#theme' => 'token_tree', - '#token_types' => array('node', 'user'), + '#token_types' => array('node'), + '#dialog' => TRUE, ); } @@ -344,7 +368,7 @@ function googleanalytics_admin_settings_form(&$form_state) { $form['googleanalytics_custom_metric'] = array( '#collapsed' => TRUE, '#collapsible' => TRUE, - '#description' => t('You can add Google Analytics Custom Metrics here. You must have already configured your custom metrics in the Google Analytics Management Interface. You may use tokens. 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/analyticsjs/custom-dims-mets', '@setup_documentation' => 'https://support.google.com/analytics/answer/2709829')), + '#description' => t('You can add Google Analytics Custom Metrics here. You must have already configured your custom metrics in the Google Analytics Management Interface. You may use tokens. Global and user tokens are always available; on node pages, node tokens are also available.', array('@custom_var_documentation' => 'https://support.google.com/analytics/answer/9216061', '@setup_documentation' => 'https://support.google.com/analytics/answer/12229021?hl=en&ref_topic=9756175')), '#theme' => 'googleanalytics_admin_custom_var_table', '#title' => t('Custom metrics'), '#tree' => TRUE, @@ -353,45 +377,52 @@ function googleanalytics_admin_settings_form(&$form_state) { $googleanalytics_custom_metric = variable_get('googleanalytics_custom_metric', array()); - // Google Analytics supports up to 20 custom metrics. - for ($i = 1; $i <= 20; $i++) { - // TODO: '#default_value' is currently broken, see http://drupal.org/node/410926. + // Standard Google Analytics accounts support up to 20 custom metrics, + // premium accounts support up to 200 custom metrics. + for ($i = 1; $i <= $limit; $i++) { $form['googleanalytics_custom_metric']['indexes'][$i]['index'] = array( - //'#default_value' => $i, + '#default_value' => $i, '#description' => t('Index number'), '#disabled' => TRUE, '#size' => 1, + '#title' => t('Custom metric index #@index', array('@index' => $i)), + '#type' => 'textfield', + ); + $form['googleanalytics_custom_metric']['indexes'][$i]['name'] = array( + '#default_value' => isset($googleanalytics_custom_metric[$i]['name']) ? $googleanalytics_custom_metric[$i]['name'] : '', + '#description' => t('The custom metric name.'), + '#maxlength' => 255, + '#title' => t('Custom metric name #@index', array('@index' => $i)), + '#title_display' => 'invisible', '#type' => 'textfield', - '#value' => $i, ); $form['googleanalytics_custom_metric']['indexes'][$i]['value'] = array( '#default_value' => isset($googleanalytics_custom_metric[$i]['value']) ? $googleanalytics_custom_metric[$i]['value'] : '', '#description' => t('The custom metric value.'), '#maxlength' => 255, + '#title' => t('Custom metric value #@index', array('@index' => $i)), '#type' => 'textfield', + '#element_validate' => array('googleanalytics_token_element_validate'), + '#token_types' => array('node'), ); if (module_exists('token')) { - $form['googleanalytics_custom_metric']['indexes'][$i]['value']['#element_validate'][] = 'googleanalytics_token_element_validate'; $form['googleanalytics_custom_metric']['indexes'][$i]['value']['#element_validate'][] = 'token_element_validate'; - $form['googleanalytics_custom_metric']['indexes'][$i]['value']['#token_types'][] = 'node'; - $form['googleanalytics_custom_metric']['indexes'][$i]['value']['#token_types'][] = 'user'; } } $form['googleanalytics_custom_metric']['googleanalytics_description'] = array( '#type' => 'item', - '#description' => t('You can supplement Google Analytics\' basic IP address tracking of visitors by segmenting users based on custom metrics. Section 7 of the Google Analytics terms of service 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, userid, 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')), + '#description' => t('You can supplement Google Analytics\' basic IP address tracking of visitors by segmenting users based on custom metrics. Section 7 of the Google Analytics terms of service 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, userid, 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' => 'https://www.google.com/analytics/terms/gb.html')), ); if (module_exists('token')) { $form['googleanalytics_custom_metric']['googleanalytics_token_tree'] = array( '#theme' => 'token_tree', - '#token_types' => array('node', 'user'), + '#token_types' => array('node'), + '#dialog' => TRUE, ); } // Advanced feature configurations. - $user_access_add_js_snippets = !user_access('add JS snippets for google analytics'); - $user_access_add_js_snippets_permission_warning = $user_access_add_js_snippets ? ' ' . t('This field has been disabled because you do not have sufficient permissions to edit it.') . '' : ''; $form['advanced'] = array( '#type' => 'fieldset', '#title' => t('Advanced settings'), @@ -405,10 +436,6 @@ function googleanalytics_admin_settings_form(&$form_state) { '#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), ); - if (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PRIVATE) { - $form['advanced']['googleanalytics_cache']['#disabled'] = TRUE; - $form['advanced']['googleanalytics_cache']['#description'] .= ' '. t('Public file transfers must be enabled to allow local caching.', array('@url' => url('admin/settings/file-system', array('query' => drupal_get_destination())))); - } // Allow for tracking of the originating node when viewing translation sets. if (module_exists('translation')) { @@ -419,19 +446,22 @@ function googleanalytics_admin_settings_form(&$form_state) { '#default_value' => variable_get('googleanalytics_translation_set', 0), ); } + + $user_access_add_js_snippets = !user_access('add JS snippets for google analytics'); + $user_access_add_js_snippets_permission_warning = $user_access_add_js_snippets ? ' ' . t('This field has been disabled because you do not have sufficient permissions to edit it.') . '' : ''; $form['advanced']['codesnippet'] = array( '#type' => 'fieldset', '#title' => t('Custom JavaScript code'), '#collapsible' => TRUE, '#collapsed' => TRUE, - '#description' => t('You can add custom Google Analytics code snippets here. These will be added to every page that Google Analytics appears on. Before you add custom code to the below textarea\'s you should read Google Analytics Tracking Code - Functional Overview and the Google Analytics Tracking API documentation. Do not include the <script> tags, 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/')), + '#description' => t('You can add custom Google Analytics code snippets here. These will be added every time tracking is in effect. Before you add your custom code, you should read the Google Analytics Tracking Code - Functional Overview and the Google Analytics Tracking API documentation. Do not include the <script> tags, and always end your code with a semicolon (;).', array('@snippets' => 'https://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/analyticsjs/method-reference')), ); $form['advanced']['codesnippet']['googleanalytics_codesnippet_create'] = array( '#type' => 'textarea', '#title' => t('Create only fields'), '#default_value' => _googleanalytics_get_name_value_string(variable_get('googleanalytics_codesnippet_create', array())), '#rows' => 5, - '#description' => t('Enter one value per line, in the format name|value. Settings in this textarea will be added to ga("create", "UA-XXXX-Y", {"name":"value"});. For more information, read create only fields documentation in the Analytics.js field reference.', array('@url' => 'https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#create')), + '#description' => t('Enter one value per line, in the format name|value. Settings in this textarea will be added to gtag("config", "G-XXXX-Y", {"name":"value"});. For more information, read create only fields documentation in the Analytics.js field reference.', array('@url' => 'https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#create')), '#element_validate' => array('googleanalytics_validate_create_field_values'), ); $form['advanced']['codesnippet']['googleanalytics_codesnippet_before'] = array( @@ -440,8 +470,7 @@ function googleanalytics_admin_settings_form(&$form_state) { '#default_value' => variable_get('googleanalytics_codesnippet_before', ''), '#disabled' => $user_access_add_js_snippets, '#rows' => 5, - '#wysiwyg' => FALSE, - '#description' => t('Code in this textarea will be added before ga("send", "pageview");.') . $user_access_add_js_snippets_permission_warning, + '#description' => t('Code in this textarea will be added before gtag("event", "page_view");.') . $user_access_add_js_snippets_permission_warning, ); $form['advanced']['codesnippet']['googleanalytics_codesnippet_after'] = array( '#type' => 'textarea', @@ -449,8 +478,7 @@ function googleanalytics_admin_settings_form(&$form_state) { '#default_value' => variable_get('googleanalytics_codesnippet_after', ''), '#disabled' => $user_access_add_js_snippets, '#rows' => 5, - '#wysiwyg' => FALSE, - '#description' => t('Code in this textarea will be added after ga("send", "pageview");. This is useful if you\'d like to track a site in two accounts.') . $user_access_add_js_snippets_permission_warning, + '#description' => t('Code in this textarea will be added after gtag("event", "page_view");. This is useful if you\'d like to track a site in two accounts.') . $user_access_add_js_snippets_permission_warning, ); $form['advanced']['googleanalytics_debug'] = array( '#type' => 'checkbox', @@ -462,43 +490,30 @@ function googleanalytics_admin_settings_form(&$form_state) { return system_settings_form($form); } +/** + * Implements _form_validate(). + */ function googleanalytics_admin_settings_form_validate($form, &$form_state) { // Trim custom dimensions and metrics. foreach ($form_state['values']['googleanalytics_custom_dimension']['indexes'] as $dimension) { + $form_state['values']['googleanalytics_custom_dimension']['indexes'][$dimension['index']]['name'] = trim($dimension['name']); $form_state['values']['googleanalytics_custom_dimension']['indexes'][$dimension['index']]['value'] = trim($dimension['value']); // Remove empty values from the array. if (!drupal_strlen($form_state['values']['googleanalytics_custom_dimension']['indexes'][$dimension['index']]['value'])) { unset($form_state['values']['googleanalytics_custom_dimension']['indexes'][$dimension['index']]); } - - // If token module is not available, block tokens with personally identifying - // information with an "ugly" value check. Normally the values are validated - // via '#element_validate' functions that are not available without token module. - if (!module_exists('token')) { - if (_googleanalytics_contains_forbidden_token($dimension['value'])) { - form_set_error('googleanalytics_custom_dimension][indexes][' . $dimension['index'] . '][value', t('The dimension #@index is using forbidden tokens with personal identifying information.', array('@index' => $dimension['index']))); - } - } } $form_state['values']['googleanalytics_custom_dimension'] = $form_state['values']['googleanalytics_custom_dimension']['indexes']; foreach ($form_state['values']['googleanalytics_custom_metric']['indexes'] as $metric) { + $form_state['values']['googleanalytics_custom_metric']['indexes'][$metric['index']]['name'] = trim($metric['name']); $form_state['values']['googleanalytics_custom_metric']['indexes'][$metric['index']]['value'] = trim($metric['value']); // Remove empty values from the array. if (!drupal_strlen($form_state['values']['googleanalytics_custom_metric']['indexes'][$metric['index']]['value'])) { unset($form_state['values']['googleanalytics_custom_metric']['indexes'][$metric['index']]); } - - // If token module is not available, block tokens with personally identifying - // information with an "ugly" value check. Normally the values are validated - // via '#element_validate' functions that are not available without token module. - if (!module_exists('token')) { - if (_googleanalytics_contains_forbidden_token($metric['value'])) { - form_set_error('googleanalytics_custom_dimension][indexes][' . $metric['index'] . '][value', t('The metric #@index is using forbidden tokens with personal identifying information.', array('@index' => $metric['index']))); - } - } } $form_state['values']['googleanalytics_custom_metric'] = $form_state['values']['googleanalytics_custom_metric']['indexes']; @@ -513,8 +528,11 @@ function googleanalytics_admin_settings_form_validate($form, &$form_state) { // 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+-\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.')); + $account_parts = array_filter(array_map("trim", explode(",", $form_state['values']['googleanalytics_account']))); + foreach ($account_parts as $account) { + if (!_google_analytics_valid_property_id($account)) { + form_set_error('googleanalytics_account', t('A valid Web Property ID is case sensitive and formatted like UA-xxxxxxx-yy, G-XXXXXXX, DC-XXXXXXX, or AW-XXXXXXX.')); + } } // If multiple top-level domains has been selected, a domain names list is required. @@ -557,6 +575,7 @@ function theme_googleanalytics_admin_custom_var_table($form) { $header = array( array('data' => t('Index')), + array('data' => t('Name')), array('data' => t('Value')), ); @@ -565,6 +584,7 @@ function theme_googleanalytics_admin_custom_var_table($form) { $rows[] = array( 'data' => array( drupal_render($form['indexes'][$id]['index']), + drupal_render($form['indexes'][$id]['name']), drupal_render($form['indexes'][$id]['value']), ), ); @@ -602,28 +622,28 @@ function googleanalytics_token_element_validate(&$element, &$form_state) { } $tokens = token_scan($value); - $title = empty($element['#title']) ? $element['#parents'][0] : $element['#title']; - $invalid_tokens = _googleanalytics_get_forbidden_tokens($tokens); if ($invalid_tokens) { - form_error($element, t('The %element-title is using the following forbidden tokens with personal identifying information: @invalid-tokens.', array('%element-title' => $title, '@invalid-tokens' => implode(', ', $invalid_tokens)))); + form_error($element, t('The %element-title is using the following forbidden tokens with personal identifying information: @invalid-tokens.', array('%element-title' => $element['#title'], '@invalid-tokens' => implode(', ', $invalid_tokens)))); } return $element; } +/** + * @param array $value + * An array of token values. + * + * @return array + * A unique array of invalid tokens. + */ function _googleanalytics_get_forbidden_tokens($value) { $invalid_tokens = array(); $value_tokens = is_string($value) ? token_scan($value) : $value; - // For porting/compatibility reasons with _googleanalytics_contains_forbidden_token() - // the leading and trailing token separator need to be added to every value. - $value_tokens = token_prepare_tokens($value_tokens); - - foreach ($value_tokens as $token) { - // If token is forbidden, add it to invalid tokens array. - if (_googleanalytics_contains_forbidden_token($token)) { - $invalid_tokens[] = $token; + foreach ($value_tokens as $tokens) { + if (array_filter($tokens, '_googleanalytics_contains_forbidden_token')) { + $invalid_tokens = array_merge($invalid_tokens, array_values($tokens)); } } @@ -634,8 +654,9 @@ function _googleanalytics_get_forbidden_tokens($value) { /** * Validate if a string contains forbidden tokens not allowed by privacy rules. * - * @param $token_string + * @param string $token_string * A string with one or more tokens to be validated. + * * @return boolean * TRUE if blacklisted token has been found, otherwise FALSE. */ @@ -652,22 +673,38 @@ function _googleanalytics_contains_forbidden_token($token_string) { // // TODO: If someone have better ideas, share them, please! $token_blacklist = array( - 'author-uid]', - 'author-name', - 'author-mail', - 'author-homepage]', - '[user-name]', - '[user-id]', - '[user-mail]', - // [user] tokens - '[user]', - '[user-raw]', - '[uid]', - '[mail]', - '[account-url]', - '[account-edit]', - // realname module - '[realname', + ':author]', + ':author:edit-url]', + ':author:url]', + ':author:path]', + ':current-user]', + ':current-user:original]', + ':fid]', + ':mail]', + ':name]', + ':uid]', + ':one-time-login-url]', + ':owner]', + ':owner:cancel-url]', + ':owner:edit-url]', + ':owner:url]', + ':owner:path]', + 'user:cancel-url]', + 'user:edit-url]', + 'user:url]', + 'user:path]', + 'user:picture]', + // addressfield_tokens.module + ':first-name]', + ':last-name]', + ':name-line]', + ':mc-address]', + ':thoroughfare]', + ':premise]', + // realname.module + ':name-raw]', + // token.module + ':ip-address]', ); return preg_match('/' . implode('|', array_map('preg_quote', $token_blacklist)) . '/i', $token_string); @@ -756,16 +793,18 @@ function _googleanalytics_validate_create_field_name($name) { // List of supported field names: // https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#create $create_only_fields = array( - 'clientId', - 'userId', - 'sampleRate', - 'siteSpeedSampleRate', - 'alwaysSendReferrer', 'allowAnchor', + 'alwaysSendReferrer', + 'clientId', 'cookieName', 'cookieDomain', 'cookieExpires', 'legacyCookieDomain', + 'legacyHistoryImport', + 'sampleRate', + 'siteSpeedSampleRate', + 'storage', + 'useAmpClientId', ); if ($name == 'name') { @@ -774,6 +813,9 @@ function _googleanalytics_validate_create_field_name($name) { if ($name == 'allowLinker') { return t('Create only field name %name is a disallowed field name. Please select Multiple top-level domains under What are you tracking to enable cross domain tracking.', array('%name' => $name)); } + if ($name == 'userId') { + return t('Create only field name %name is a disallowed field name. Please enable Track User ID under Tracking scope > Users.', array('%name' => $name)); + } if (!in_array($name, $create_only_fields)) { return t('Create only field name %name is an unknown field name. Field names are case sensitive. Please see create only fields documentation for supported field names.', array('%name' => $name, '@url' => 'https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#create')); } diff --git a/googleanalytics.debug.js b/googleanalytics.debug.js index ad64174..ae4cfaf 100644 --- a/googleanalytics.debug.js +++ b/googleanalytics.debug.js @@ -1,3 +1,4 @@ +(function ($) { Drupal.googleanalytics = {}; @@ -9,14 +10,14 @@ $(document).ready(function() { console.group("Running Google Analytics for Drupal."); console.info("Event '%s' has been detected.", event.type); - // Catch only the first parent link of a clicked element. - $(event.target).parents("a:first,area:first").andSelf().filter("a,area").each(function() { + // Catch the closest surrounding link of a clicked element. + $(event.target).closest("a,area").each(function() { console.info("Closest element '%o' has been found. URL '%s' extracted.", this, this.href); // Is the clicked URL internal? if (Drupal.googleanalytics.isInternal(this.href)) { // Skip 'click' tracking, if custom tracking events are bound. - if ($(this).is('.colorbox')) { + if ($(this).is('.colorbox') && (Drupal.settings.googleanalytics.trackColorbox)) { // Do nothing here. The custom event will handle all tracking. console.info("Click on .colorbox item has been detected."); } @@ -24,21 +25,18 @@ $(document).ready(function() { else if (Drupal.settings.googleanalytics.trackDownload && Drupal.googleanalytics.isDownload(this.href)) { // Download link clicked. console.info("Download url '%s' has been found. Tracked download as extension '%s'.", Drupal.googleanalytics.getPageUrl(this.href), Drupal.googleanalytics.getDownloadExtension(this.href).toUpperCase()); - ga("send", { - "hitType": "event", - "eventCategory": "Downloads", - "eventAction": Drupal.googleanalytics.getDownloadExtension(this.href).toUpperCase(), - "eventLabel": Drupal.googleanalytics.getPageUrl(this.href), - "transport": "beacon" + gtag('event', Drupal.googleanalytics.getDownloadExtension(this.href).toUpperCase(), { + event_category: 'Downloads', + event_label: Drupal.googleanalytics.getPageUrl(this.href), + transport_type: 'beacon' }); } else if (Drupal.googleanalytics.isInternalSpecial(this.href)) { // Keep the internal URL for Google Analytics website overlay intact. console.info("Click on internal special link '%s' has been tracked.", Drupal.googleanalytics.getPageUrl(this.href)); - ga("send", { - "hitType": "pageview", - "page": Drupal.googleanalytics.getPageUrl(this.href), - "transport": "beacon" + gtag('config', Drupal.settings.googleanalytics.account, { + page_path: Drupal.googleanalytics.getPageUrl(this.href), + transport_type: 'beacon' }); } else { @@ -50,24 +48,20 @@ $(document).ready(function() { if (Drupal.settings.googleanalytics.trackMailto && $(this).is("a[href^='mailto:'],area[href^='mailto:']")) { // Mailto link clicked. console.info("Click on e-mail '%s' has been tracked.", this.href.substring(7)); - ga("send", { - "hitType": "event", - "eventCategory": "Mails", - "eventAction": "Click", - "eventLabel": this.href.substring(7), - "transport": "beacon" + gtag('event', 'Click', { + event_category: 'Mails', + event_label: this.href.substring(7), + transport_type: 'beacon' }); } else if (Drupal.settings.googleanalytics.trackOutbound && this.href.match(/^\w+:\/\//i)) { if (Drupal.settings.googleanalytics.trackDomainMode !== 2 || (Drupal.settings.googleanalytics.trackDomainMode === 2 && !Drupal.googleanalytics.isCrossDomain(this.hostname, Drupal.settings.googleanalytics.trackCrossDomains))) { // External link clicked / No top-level cross domain clicked. console.info("Outbound link '%s' has been tracked.", this.href); - ga("send", { - "hitType": "event", - "eventCategory": "Outbound links", - "eventAction": "Click", - "eventLabel": this.href, - "transport": "beacon" + gtag('event', 'Click', { + event_category: 'Outbound links', + event_label: this.href, + transport_type: 'beacon' }); } else { @@ -84,25 +78,25 @@ $(document).ready(function() { if (Drupal.settings.googleanalytics.trackUrlFragments) { window.onhashchange = function() { console.info("Track URL '%s' as pageview. Hash '%s' has changed.", location.pathname + location.search + location.hash, location.hash); - ga("send", { - "hitType": "pageview", - "page": location.pathname + location.search + location.hash + gtag('config', Drupal.settings.googleanalytics.account, { + page_path: location.pathname + location.search + location.hash }); }; } // Colorbox: This event triggers when the transition has completed and the // newly loaded content has been revealed. - $(document).bind("cbox_complete", function () { - var href = $.colorbox.element().attr("href"); - if (href) { - console.info("Colorbox transition to url '%s' has been tracked.", Drupal.googleanalytics.getPageUrl(href)); - ga("send", { - "hitType": "pageview", - "page": Drupal.googleanalytics.getPageUrl(href) - }); - } - }); + if (Drupal.settings.googleanalytics.trackColorbox) { + $(document).bind("cbox_complete", function () { + var href = $.colorbox.element().attr("href"); + if (href) { + console.info("Colorbox transition to url '%s' has been tracked.", Drupal.googleanalytics.getPageUrl(href)); + gtag('config', Drupal.settings.googleanalytics.account, { + page_path: Drupal.googleanalytics.getPageUrl(href) + }); + } + }); + } }); @@ -119,7 +113,7 @@ $(document).ready(function() { Drupal.googleanalytics.isCrossDomain = function (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, + * `null` or `undefined`, https://bugs.jquery.com/ticket/10076, * https://github.com/jquery/jquery/commit/a839af034db2bd934e4d4fa6758a3fed8de74174 * * @todo: Remove/Refactor in D8 @@ -178,8 +172,8 @@ Drupal.googleanalytics.isInternalSpecial = function (url) { * Extract the relative internal URL from an absolute internal URL. * * Examples: - * - http://mydomain.com/node/1 -> /node/1 - * - http://example.com/foo/bar -> http://example.com/foo/bar + * - https://mydomain.com/node/1 -> /node/1 + * - https://example.com/foo/bar -> https://example.com/foo/bar * * @param string url * The web url to check. @@ -206,3 +200,5 @@ Drupal.googleanalytics.getDownloadExtension = function (url) { var extension = extractDownloadextension.exec(url); return (extension === null) ? '' : extension[1]; }; + +})(jQuery); diff --git a/googleanalytics.gtag-shim.js b/googleanalytics.gtag-shim.js new file mode 100644 index 0000000..0502a65 --- /dev/null +++ b/googleanalytics.gtag-shim.js @@ -0,0 +1,33 @@ +window.ga = window.ga || function() { + var type = arguments[0]; + if (type === 'create') { + gtag('config', arguments[1], arguments[2]); + } else if (type === 'set') { + gtag('set', arguments[1], arguments[2]); + } else if (type === 'require') { + // Anything needed in `require` is bundled into Google Tag. + } + else if (type === 'send') { + if (typeof arguments[1] === 'object') { + gtag('event', arguments[1].eventAction, { + event_category: arguments[1].eventCategory, + event_label: arguments[1].eventLabel, + transport_type: arguments[1].transport || 'beacon', + }) + } + else if (arguments[1] === 'pageview') { + gtag('event', 'page_view'); + } + else if (arguments.length === 2) { + gtag('event', arguments[1]); + } + else { + gtag('event', arguments[3] || '', { + event_category: arguments[2] || '', + event_label: arguments[4] || '', + }) + } + } else { + gtag(arguments); + } +} diff --git a/googleanalytics.info b/googleanalytics.info index faab735..22bfe50 100644 --- a/googleanalytics.info +++ b/googleanalytics.info @@ -2,3 +2,4 @@ name = Google Analytics description = Allows your site to be tracked by Google Analytics by adding a Javascript tracking code to every page. core = 6.x package = Statistics + diff --git a/googleanalytics.install b/googleanalytics.install index 9e69c59..edf8a28 100644 --- a/googleanalytics.install +++ b/googleanalytics.install @@ -5,8 +5,12 @@ * Installation file for Google Analytics module. */ +/** + * Implements hook_uninstall(). + */ function googleanalytics_uninstall() { variable_del('googleanalytics_account'); + variable_del('googleanalytics_premium'); variable_del('googleanalytics_cache'); variable_del('googleanalytics_codesnippet_create'); variable_del('googleanalytics_codesnippet_before'); @@ -22,6 +26,7 @@ function googleanalytics_uninstall() { variable_del('googleanalytics_roles'); variable_del('googleanalytics_site_search'); variable_del('googleanalytics_trackadsense'); + variable_del('googleanalytics_trackcolorbox'); variable_del('googleanalytics_trackdoubleclick'); variable_del('googleanalytics_tracker_anonymizeip'); variable_del('googleanalytics_trackfiles'); @@ -32,8 +37,10 @@ function googleanalytics_uninstall() { variable_del('googleanalytics_trackmailto'); variable_del('googleanalytics_trackmessages'); variable_del('googleanalytics_trackoutgoing'); + variable_del('googleanalytics_trackoutbound'); variable_del('googleanalytics_translation_set'); variable_del('googleanalytics_visibility'); + variable_del('googleanalytics_visibility_pages'); variable_del('googleanalytics_visibility_roles'); variable_del('googleanalytics_privacy_donottrack'); @@ -54,13 +61,14 @@ function googleanalytics_disable() { */ function googleanalytics_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( - 'title' => t('Google Analytics module'), - 'description' => t('Google Analytics module has not been configured yet. Please configure its settings from the Google Analytics settings page.', array('@url' => url('admin/settings/googleanalytics'))), + if (!_google_analytics_valid_property_id(variable_get('googleanalytics_account', 'UA-'))) { + $requirements['googleanalytics_account'] = array( + 'title' => $t('Google Analytics module'), + 'description' => $t('Google Analytics module has not been configured yet. Please configure its settings from the Google Analytics settings page.', array('@url' => url('admin/settings/googleanalytics'))), 'severity' => REQUIREMENT_WARNING, 'value' => t('Not configured'), ); @@ -80,42 +88,23 @@ function googleanalytics_requirements($phase) { return $requirements; } - -function googleanalytics_update_1() { - $ret = array(); - - $result = db_query("SELECT * FROM {role}"); - while ($role = db_fetch_object($result)) { - // can't use empty spaces in varname - $role_varname = str_replace(' ', '_', $role->name); - variable_set('googleanalytics_track_'. $role->rid, !variable_get("googleanalytics_track_{$role_varname}", FALSE)); - variable_del("googleanalytics_track_{$role_varname}"); - } - variable_set('googleanalytics_track__user1', FALSE); - - return $ret; -} - /** - * Upgrade old extension variable to new and use old name as enabled/disabled flag. + * Upgrade old extension variable to new and use old name as enabled/disabled + * flag. */ function googleanalytics_update_6000() { - $ret = array(); - 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); - $ret[] = array('success' => TRUE, 'query' => 'Updated download tracking settings.'); - return $ret; + return t('Updated download tracking file extensions.'); } function googleanalytics_update_6001() { - $ret = array(); - variable_set('googleanalytics_visibility', 0); - // Remove tracking from all administrative pages, see http://drupal.org/node/34970. + // Remove tracking from all administrative pages, see: + // https://drupal.org/node/34970. $pages = array( 'admin*', 'user*', @@ -123,28 +112,27 @@ function googleanalytics_update_6001() { 'node/*/*', ); variable_set('googleanalytics_pages', implode("\n", $pages)); - $ret[] = array('success' => TRUE, 'query' => 'Added page tracking to every page except the listed pages: '. implode(', ', $pages)); - return $ret; + 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. + * Upgrade role settings and per user tracking settings of "User 1" and remove + * outdated tracking variables. */ function googleanalytics_update_6002() { - $ret = array(); - - // Upgrade enabled/disabled roles to new logic (correct for upgrades from 5.x-1.4 and 6.x-1.0). + // 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; - $ret[] = array('success' => TRUE, 'query' => 'Enabled page tracking for role: '. $name); + $messages[] = t('Enabled page tracking for role: @name.', array('@name' => $name)); } else { - $ret[] = array('success' => TRUE, 'query' => 'Disabled page tracking for role: '. $name); + $messages[] = t('Disabled page tracking for role: @name.', array('@name' => $name)); } } variable_set('googleanalytics_roles', $roles); diff --git a/googleanalytics.js b/googleanalytics.js index a7ce047..08bc540 100644 --- a/googleanalytics.js +++ b/googleanalytics.js @@ -1,3 +1,4 @@ +(function ($) { Drupal.googleanalytics = {}; @@ -7,56 +8,53 @@ $(document).ready(function() { // clicks on all elements. $(document.body).bind("mousedown keyup touchstart", function(event) { - // Catch only the first parent link of a clicked element. - $(event.target).parents("a:first,area:first").andSelf().filter("a,area").each(function() { + // Catch the closest surrounding link of a clicked element. + $(event.target).closest("a,area").each(function() { // Is the clicked URL internal? if (Drupal.googleanalytics.isInternal(this.href)) { // Skip 'click' tracking, if custom tracking events are bound. - if ($(this).is('.colorbox')) { + if ($(this).is('.colorbox') && (Drupal.settings.googleanalytics.trackColorbox)) { // Do nothing here. The custom event will handle all tracking. //console.info("Click on .colorbox item has been detected."); } // Is download tracking activated and the file extension configured for download tracking? else if (Drupal.settings.googleanalytics.trackDownload && Drupal.googleanalytics.isDownload(this.href)) { // Download link clicked. - ga("send", { - "hitType": "event", - "eventCategory": "Downloads", - "eventAction": Drupal.googleanalytics.getDownloadExtension(this.href).toUpperCase(), - "eventLabel": Drupal.googleanalytics.getPageUrl(this.href), - "transport": "beacon" + gtag('event', Drupal.googleanalytics.getDownloadExtension(this.href).toUpperCase(), { + event_category: 'Downloads', + event_label: Drupal.googleanalytics.getPageUrl(this.href), + transport_type: 'beacon' }); } else if (Drupal.googleanalytics.isInternalSpecial(this.href)) { // Keep the internal URL for Google Analytics website overlay intact. - ga("send", { - "hitType": "pageview", - "page": Drupal.googleanalytics.getPageUrl(this.href), - "transport": "beacon" + // @todo: May require tracking ID + var target = this; + $.each(Drupal.settings.googleanalytics.account, function () { + gtag('config', this, { + page_path: Drupal.googleanalytics.getPageUrl(target.href), + transport_type: 'beacon' + }); }); } } else { if (Drupal.settings.googleanalytics.trackMailto && $(this).is("a[href^='mailto:'],area[href^='mailto:']")) { // Mailto link clicked. - ga("send", { - "hitType": "event", - "eventCategory": "Mails", - "eventAction": "Click", - "eventLabel": this.href.substring(7), - "transport": "beacon" + gtag('event', 'Click', { + event_category: 'Mails', + event_label: this.href.substring(7), + transport_type: 'beacon' }); } else if (Drupal.settings.googleanalytics.trackOutbound && this.href.match(/^\w+:\/\//i)) { if (Drupal.settings.googleanalytics.trackDomainMode !== 2 || (Drupal.settings.googleanalytics.trackDomainMode === 2 && !Drupal.googleanalytics.isCrossDomain(this.hostname, Drupal.settings.googleanalytics.trackCrossDomains))) { // External link clicked / No top-level cross domain clicked. - ga("send", { - "hitType": "event", - "eventCategory": "Outbound links", - "eventAction": "Click", - "eventLabel": this.href, - "transport": "beacon" + gtag('event', 'Click', { + event_category: 'Outbound links', + event_label: this.href, + transport_type: 'beacon' }); } } @@ -67,24 +65,28 @@ $(document).ready(function() { // Track hash changes as unique pageviews, if this option has been enabled. if (Drupal.settings.googleanalytics.trackUrlFragments) { window.onhashchange = function() { - ga("send", { - "hitType": "pageview", - "page": location.pathname + location.search + location.hash + $.each(Drupal.settings.googleanalytics.account, function () { + gtag('config', this, { + page_path: location.pathname + location.search + location.hash + }); }); }; } // Colorbox: This event triggers when the transition has completed and the // newly loaded content has been revealed. - $(document).bind("cbox_complete", function () { - var href = $.colorbox.element().attr("href"); - if (href) { - ga("send", { - "hitType": "pageview", - "page": Drupal.googleanalytics.getPageUrl(href) - }); - } - }); + if (Drupal.settings.googleanalytics.trackColorbox) { + $(document).bind("cbox_complete", function () { + var href = $.colorbox.element().attr("href"); + if (href) { + $.each(Drupal.settings.googleanalytics.account, function () { + gtag('config', this, { + page_path: Drupal.googleanalytics.getPageUrl(href) + }); + }); + } + }); + } }); @@ -101,7 +103,7 @@ $(document).ready(function() { Drupal.googleanalytics.isCrossDomain = function (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, + * `null` or `undefined`, https://bugs.jquery.com/ticket/10076, * https://github.com/jquery/jquery/commit/a839af034db2bd934e4d4fa6758a3fed8de74174 * * @todo: Remove/Refactor in D8 @@ -160,8 +162,8 @@ Drupal.googleanalytics.isInternalSpecial = function (url) { * Extract the relative internal URL from an absolute internal URL. * * Examples: - * - http://mydomain.com/node/1 -> /node/1 - * - http://example.com/foo/bar -> http://example.com/foo/bar + * - https://mydomain.com/node/1 -> /node/1 + * - https://example.com/foo/bar -> https://example.com/foo/bar * * @param string url * The web url to check. @@ -188,3 +190,5 @@ Drupal.googleanalytics.getDownloadExtension = function (url) { var extension = extractDownloadextension.exec(url); return (extension === null) ? '' : extension[1]; }; + +})(jQuery); diff --git a/googleanalytics.module b/googleanalytics.module index 94d24cc..9b8dbca 100644 --- a/googleanalytics.module +++ b/googleanalytics.module @@ -7,7 +7,7 @@ * Adds the required Javascript to all your Drupal pages to allow tracking by * the Google Analytics statistics package. * - * @author: Alexander Hass + * @author: Alexander Hass */ /** @@ -17,7 +17,7 @@ define('GOOGLEANALYTICS_TRACKFILES_EXTENSIONS', '7z|aac|arc|arj|asf|asx|avi|bin| /** * Define default path exclusion list to remove tracking from admin pages, - * see http://drupal.org/node/34970 for more information. + * see https://drupal.org/node/34970 for more information. */ define('GOOGLEANALYTICS_PAGES', "admin\nadmin/*\nbatch\nnode/add*\nnode/*/*\nuser/*/*"); @@ -36,7 +36,7 @@ function googleanalytics_api() { function googleanalytics_help($path, $arg) { switch ($path) { case 'admin/settings/googleanalytics': - return t('Google Analytics is a free (registration required) website traffic and marketing effectiveness service.', array('@ga_url' => 'http://www.google.com/analytics/')); + return t('Google Analytics is a free (registration required) website traffic and marketing effectiveness service.', array('@ga_url' => 'https://marketingplatform.google.com/analytics/')); } } @@ -103,14 +103,16 @@ function googleanalytics_add_js(&$vars, $hook) { // 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 (preg_match('/^UA-\d+-\d+$/', $id) && (_googleanalytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _googleanalytics_visibility_user($user)) { + if (_google_analytics_valid_property_id($id) && (_googleanalytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _googleanalytics_visibility_user($user)) { + + $id_list = array_filter(array_map("trim", explode(",", $id))); $debug = variable_get('googleanalytics_debug', 0); $url_custom = ''; // Add link tracking. - $link_settings = array(); - if ($track_outbound = variable_get('googleanalytics_trackoutgoing', 1)) { + $link_settings = array('account' => $id_list); + if ($track_outbound = variable_get('googleanalytics_trackoutbound', 1)) { $link_settings['trackOutbound'] = $track_outbound; } if ($track_mailto = variable_get('googleanalytics_trackmailto', 1)) { @@ -120,8 +122,11 @@ function googleanalytics_add_js(&$vars, $hook) { $link_settings['trackDownload'] = $track_download; $link_settings['trackDownloadExtensions'] = $trackfiles_extensions; } + if (module_exists('colorbox') && ($track_colorbox = variable_get('googleanalytics_trackcolorbox', 1))) { + $link_settings['trackColorbox'] = $track_colorbox; + } if ($track_domain_mode = variable_get('googleanalytics_domain_mode', 0)) { - $link_settings['trackDomainMode'] = $track_domain_mode; + $link_settings['trackDomainMode'] = (int) $track_domain_mode; } if ($track_cross_domains = variable_get('googleanalytics_cross_domains', '')) { $link_settings['trackCrossDomains'] = preg_split('/(\r\n?|\n)/', $track_cross_domains); @@ -132,11 +137,11 @@ function googleanalytics_add_js(&$vars, $hook) { } if (!empty($link_settings)) { - drupal_add_js(array('googleanalytics' => $link_settings), 'setting'); + drupal_add_js(array('googleanalytics' => $link_settings), 'setting', 'header'); // Add debugging code. if ($debug) { - drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.debug.js'); + drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.debug.js', 'module', 'header'); // Add the JS test in development to the page. //drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.test.js'); } @@ -160,17 +165,20 @@ function googleanalytics_add_js(&$vars, $hook) { if (in_array($type, $message_types)) { foreach ($messages as $message) { // @todo: Track as exceptions? - $message_events .= 'ga("send", "event", ' . drupal_to_js(t('Messages')) . ', ' . drupal_to_js($status_heading[$type]) . ', ' . drupal_to_js(strip_tags($message)) . ');'; + $event = array(); + $event['event_category'] = t('Messages'); + $event['event_label'] = strip_tags((string) $message); + $message_events .= 'gtag("event", ' . json_encode($status_heading[$type]) . ', ' . json_encode($event) . ');'; } } } } // Site search tracking support. - if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = search_get_keys()) { + if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = googleanalytics_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_to_js(url('search/'. arg(1), array('query' => 'search='. drupal_urlencode($keys)))) . ' : ' . drupal_to_js(url('search/'. arg(1), array('query' => 'search=no-results:'. drupal_urlencode($keys) .'&cat=no-results'))); + $url_custom = '(window.googleanalytics_search_results) ? ' . json_encode(url('search/' . arg(1), array('query' => array('search' => $keys)))) . ' : ' . json_encode(url('search/' . arg(1), array('query' => array('search' => 'no-results:' . $keys, 'cat' => 'no-results')))); } // If this node is a translation of another node, pass the original @@ -179,43 +187,56 @@ function googleanalytics_add_js(&$vars, $hook) { // 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(); - if ($node && translation_supported_type($node->type) && isset($node->tnid) && ($node->tnid != $node->nid)) { + if ($node && translation_supported_type($node->type) && !empty($node->tnid) && ($node->tnid != $node->nid)) { $source_node = node_load($node->tnid); $languages = language_list(); - $url_custom = drupal_to_js(url('node/'. $source_node->nid, array('language' => $languages[$source_node->language]))); + $url_custom = json_encode(url('node/' . $source_node->nid, array('language' => $languages[$source_node->language]))); } } + global $base_path; + // Track access denied (403) and file not found (404) pages. if ($status == '403 Forbidden') { - // See http://www.google.com/support/analytics/bin/answer.py?answer=86927 - $url_custom = '"/403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer'; + // See https://www.google.com/support/analytics/bin/answer.py?answer=86927 + $url_custom = '"' . $base_path . '403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer'; } elseif ($status == '404 Not Found') { - $url_custom = '"/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer'; + $url_custom = '"' . $base_path . '404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer'; + } + + // #2693595: User has entered an invalid login and clicked on forgot + // password link. This link contains the username or email address and may + // get send to Google if we do not override it. Override only if 'name' + // query param exists. Last custom url condition, this need to win. + // + // URLs to protect are: + // - user/password?name=username + // - user/password?name=foo@example.com + if (arg(0) == 'user' && arg(1) == 'password' && array_key_exists('name', _googleanalytics_get_query_parameters())) { + $url_custom = '"' . $base_path . 'user/password"'; } // Add custom dimensions and metrics. - $custom_var = ''; + $custom_vars = array(); foreach (array('dimension', 'metric') as $googleanalytics_custom_type) { $googleanalytics_custom_vars = variable_get('googleanalytics_custom_' . $googleanalytics_custom_type, array()); // Are there dimensions or metrics configured? if (!empty($googleanalytics_custom_vars)) { // Add all the configured variables to the content. foreach ($googleanalytics_custom_vars as $googleanalytics_custom_var) { - if (module_exists('token')) { - $types = array('global' => NULL, 'user' => $user); + // Suppress empty values. + if (!drupal_strlen(trim($googleanalytics_custom_var['value']))) { + continue; + } + + // Replace tokens in values. + $types = array(); $node = menu_get_object(); if (is_object($node)) { $types += array('node' => $node); } - $googleanalytics_custom_var['value'] = token_replace_multiple($googleanalytics_custom_var['value'], $types, '[', ']', array('clear' => TRUE)); - } - - // Suppress empty custom names and/or variables. - if (!drupal_strlen(trim($googleanalytics_custom_var['value']))) { - continue; - } + $googleanalytics_custom_var['value'] = token_replace($googleanalytics_custom_var['value'], $types, array('clear' => TRUE)); // Per documentation the max length of a dimension is 150 bytes. // A metric has no length limitation. It's not documented if this @@ -229,44 +250,35 @@ function googleanalytics_add_js(&$vars, $hook) { if ($googleanalytics_custom_type == 'metric') { settype($googleanalytics_custom_var['value'], 'float'); }; - $custom_var .= 'ga("set", ' . drupal_to_js($googleanalytics_custom_type . $googleanalytics_custom_var['index']) . ', ' . drupal_to_js($googleanalytics_custom_var['value']) . ');'; + + // Build the arrays of values. + $custom_vars[$googleanalytics_custom_var['name']] = $googleanalytics_custom_var['value']; } } } // Build tracker code. - $script = '(function(i,s,o,g,r,a,m){'; - $script .= 'i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){'; - $script .= '(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),'; - $script .= 'm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)'; - $script .= '})(window,document,"script",'; - - // Which version of the tracking library should be used? - $library_tracker_url = '//www.google-analytics.com/' . ($debug ? 'analytics_debug.js' : 'analytics.js'); - $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)) { - // 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. - $query_string = '?' . substr(variable_get('css_js_query_string', '0'), 0, 1); - - $script .= '"' . $url . $query_string . '"'; - } - else { - $script .= '"' . $library_tracker_url . '"'; + $script = 'window.dataLayer = window.dataLayer || [];'; + $script .= 'function gtag(){dataLayer.push(arguments)};'; + + // Include the shim if configured to do so, when migrating from UA to GA4 tags. + if (variable_get('googleanalytics_force_shim', FALSE)) { + $script .= PHP_EOL . file_get_contents(__DIR__ . '/googleanalytics.gtag-shim.js') . PHP_EOL; } - $script .= ',"ga");'; + + $script .= 'gtag("js", new Date());'; + // Developer ID for Drupal provided by Google. + $script .= 'gtag("set", "developer_id.dMDhkMT", true);'; // Add any custom code snippets if specified. $codesnippet_create = variable_get('googleanalytics_codesnippet_create', array()); $codesnippet_before = variable_get('googleanalytics_codesnippet_before', ''); $codesnippet_after = variable_get('googleanalytics_codesnippet_after', ''); - // Build the create only fields list. - $create_only_fields = array('cookieDomain' => 'auto'); + // Build the arguments fields list. + // https://developers.google.com/analytics/devguides/collection/gtagjs/sending-data + $create_only_fields = array('groups' => 'default'); + $create_only_fields = array_merge($custom_vars, $create_only_fields); $create_only_fields = array_merge($create_only_fields, $codesnippet_create); // Domain tracking type. @@ -277,63 +289,58 @@ function googleanalytics_add_js(&$vars, $hook) { // 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. if ($domain_mode == 1 && count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) { - $create_only_fields = array_merge($create_only_fields, array('cookieDomain' => $cookie_domain)); - $googleanalytics_adsense_script .= 'window.google_analytics_domain_name = ' . drupal_to_js($cookie_domain) . ';'; + $create_only_fields = array_merge($create_only_fields, array('cookie_domain' => $cookie_domain)); + $googleanalytics_adsense_script .= 'window.google_analytics_domain_name = ' . json_encode($cookie_domain) . ';'; } elseif ($domain_mode == 2) { - // Cross Domain tracking. 'autoLinker' need to be enabled in 'create'. - $create_only_fields = array_merge($create_only_fields, array('allowLinker' => TRUE)); + // Cross Domain tracking + // https://developers.google.com/analytics/devguides/collection/gtagjs/cross-domain + $create_only_fields['linker'] = array( + 'domains' => $link_settings['trackCrossDomains'], + ); $googleanalytics_adsense_script .= 'window.google_analytics_domain_name = "none";'; } // Track logged in users across all devices. if (variable_get('googleanalytics_trackuserid', 0) && user_is_logged_in()) { - // The USER_ID value should be a unique, persistent, and non-personally - // identifiable string identifier that represents a user or signed-in - // account across devices. - $create_only_fields['userId'] = _googleanalytics_hmac_base64($user->uid, drupal_get_private_key() . _googleanalytics_get_hash_salt()); + $create_only_fields['user_id'] = google_analytics_user_id_hash($user->uid); } - // Create a tracker. - $script .= 'ga("create", ' . drupal_to_js($id) . ', ' . drupal_to_js($create_only_fields) .');'; + if (variable_get('googleanalytics_tracker_anonymizeip', 1)) { + $create_only_fields['anonymize_ip'] = TRUE; + } - // Prepare Adsense tracking. - $googleanalytics_adsense_script .= 'window.google_analytics_uacct = ' . drupal_to_js($id) . ';'; + if (!empty($url_custom)) { + $create_only_fields['page_path'] = 'PLACEHOLDER_URL_CUSTOM'; + } // Add enhanced link attribution after 'create', but before 'pageview' send. - // @see https://support.google.com/analytics/answer/2558867 + // @see https://developers.google.com/analytics/devguides/collection/gtagjs/enhanced-link-attribution if (variable_get('googleanalytics_tracklinkid', 0)) { - $script .= 'ga("require", "linkid", "linkid.js");'; + $create_only_fields['link_attribution'] = TRUE; } // Add display features after 'create', but before 'pageview' send. - // @see https://support.google.com/analytics/answer/2444872 + // @see https://developers.google.com/analytics/devguides/collection/gtagjs/display-features if (variable_get('googleanalytics_trackdoubleclick', 0)) { - $script .= 'ga("require", "displayfeatures");'; - } - - // Domain tracking type. - if ($domain_mode == 2) { - // Cross Domain tracking - // https://developers.google.com/analytics/devguides/collection/upgrade/reference/gajs-analyticsjs#cross-domain - $script .= 'ga("require", "linker");'; - $script .= 'ga("linker:autoLink", ' . drupal_to_js($link_settings['trackCrossDomains']) . ');'; + $create_only_fields['allow_ad_personalization_signals'] = FALSE; } - if (variable_get('googleanalytics_tracker_anonymizeip', 1)) { - $script .= 'ga("set", "anonymizeIp", true);'; - } + // Convert array to JSON format. + $arguments_json = json_encode($create_only_fields); + // drupal_json_encode() cannot convert every data type properly. + $arguments_json = str_replace('"PLACEHOLDER_URL_CUSTOM"', $url_custom, $arguments_json); - if (!empty($custom_var)) { - $script .= $custom_var; - } + // Create a tracker. if (!empty($codesnippet_before)) { $script .= $codesnippet_before; } - if (!empty($url_custom)) { - $script .= 'ga("set", "page", ' . $url_custom . ');'; + foreach ($id_list as $id) { + $script .= 'gtag("config", ' . json_encode($id) . ', ' . $arguments_json . ');'; } - $script .= 'ga("send", "pageview");'; + + // Prepare Adsense tracking. + $googleanalytics_adsense_script .= 'window.google_analytics_uacct = ' . json_encode($id_list[0]) . ';'; if (!empty($message_events)) { $script .= $message_events; @@ -346,11 +353,59 @@ function googleanalytics_add_js(&$vars, $hook) { // Custom tracking. Prepend before all other JavaScript. // @TODO: https://support.google.com/adsense/answer/98142 // sounds like it could be appended to $script. - drupal_add_js($googleanalytics_adsense_script, 'inline', 'header'); + $script = $googleanalytics_adsense_script . $script; } - drupal_add_js($script, 'inline', 'header'); + // Prepend tracking library directly before script code. + if ($debug) { + // Debug script has highest priority to load. + // @FIXME: Cannot find the debug URL!??? + $library = 'https://www.googletagmanager.com/gtag/js?id=' . $id_list[0]; + } + elseif (variable_get('googleanalytics_cache', 0) && $url = _googleanalytics_cache('https://www.googletagmanager.com/gtag/js')) { + // Should a local cached copy of gtag.js be used? + $query_string = '?' . variable_get('css_js_query_string', '0'); + $library = $url . $query_string; + } + else { + // Fallback to default. + $library = 'https://www.googletagmanager.com/gtag/js?id=' . $id_list[0]; + } + + drupal_set_html_head(''); + drupal_set_html_head(""); + //drupal_add_js($script, 'inline' , 'header'); } + } + +/** + * Generate user id hash to implement USER_ID. + * + * The USER_ID value should be a unique, persistent, and non-personally + * identifiable string identifier that represents a user or signed-in + * account across devices. + * + * @param int $uid + * User id. + * + * @return string + * User id hash. + */ +function google_analytics_user_id_hash($uid) { + return drupal_hmac_base64($uid, drupal_get_private_key() . _googleanalytics_get_hash_salt()); +} + +/** + * Implements hook_field_extra_fields(). + */ +function googleanalytics_field_extra_fields() { + $extra['user']['user']['form']['googleanalytics'] = array( + 'label' => t('Google Analytics configuration'), + 'description' => t('Google Analytics module form element.'), + 'weight' => 3, + ); + + return $extra; } /** @@ -577,7 +632,7 @@ function _googleanalytics_visibility_pages() { // Cache visibility setting in googleanalytics_add_js. if (!isset($page_match)) { - $visibility = variable_get('googleanalytics_visibility', 0); + $visibility = variable_get('googleanalytics_visibility_pages', 0); $setting_pages = variable_get('googleanalytics_pages', GOOGLEANALYTICS_PAGES); // Match path if necessary. @@ -625,6 +680,20 @@ function _googleanalytics_visibility_header($account) { return TRUE; } +/** + * Validate Google Analytics property IDs. + * + * @param string $property_id + * Property ID to validate. + * @return int|bool + * Whether property ID is valid. + */ +function _google_analytics_valid_property_id($property_id) { + $regex = '/^(?:(UA|G|AW|DC)-[\w-]+)(?:,\s*(?:(UA|G|AW|DC)-[\w-]+))*$/'; + return !empty($property_id) && preg_match($regex, $property_id); +} + + /** * Backport of https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_get_hash_salt/7 * @@ -704,3 +773,44 @@ function googleanalytics_token_values($type, $object = NULL, $options = array()) return $tokens; } } + +/** + * @param array|NULL $query + * @param array $exclude + * @param $parent + * @return array|null + * + * Backport of drupal_get_query_parameters() from Drupal 7 + * + */ +function _googleanalytics_get_query_parameters(array $query = NULL, array $exclude = array( + 'q', +), $parent = '') { + + // Set defaults, if none given. + if (!isset($query)) { + $query = $_GET; + } + + // If $exclude is empty, there is nothing to filter. + if (empty($exclude)) { + return $query; + } + elseif (!$parent) { + $exclude = array_flip($exclude); + } + $params = array(); + foreach ($query as $key => $value) { + $string_key = $parent ? $parent . '[' . $key . ']' : $key; + if (isset($exclude[$string_key])) { + continue; + } + if (is_array($value)) { + $params[$key] = drupal_get_query_parameters($value, $exclude, $string_key); + } + else { + $params[$key] = $value; + } + } + return $params; +} diff --git a/googleanalytics.test b/googleanalytics.test index 3a5840c..273b23c 100644 --- a/googleanalytics.test +++ b/googleanalytics.test @@ -6,6 +6,13 @@ */ class GoogleAnalyticsBasicTest extends DrupalWebTestCase { + /** + * User without permissions to edit snippets. + * + * @var \StdClass + */ + protected $noSnippetUser; + public static function getInfo() { return array( 'name' => 'Google Analytics basic tests', @@ -20,41 +27,69 @@ class GoogleAnalyticsBasicTest extends DrupalWebTestCase { $permissions = array( 'access administration pages', 'administer google analytics', + 'administer modules', 'administer site configuration', ); // User to set up google_analytics. + $this->noSnippetUser = $this->drupalCreateUser($permissions); + $permissions[] = 'add JS snippets for google analytics'; $this->admin_user = $this->drupalCreateUser($permissions); $this->drupalLogin($this->admin_user); } function testGoogleAnalyticsConfiguration() { + // Check if Configure link is available on 'Modules' page. + // Requires 'administer modules' permission. + $this->drupalGet('admin/modules'); + $this->assertRaw('admin/config/system/googleanalytics', '[testGoogleAnalyticsConfiguration]: Configure link from Modules page to Google Analytics Settings page exists.'); + // Check if Configure link is available on 'Status Reports' page. NOTE: Link is only shown without UA code configured. // Requires 'administer site configuration' permission. $this->drupalGet('admin/reports/status'); - $this->assertRaw('admin/settings/googleanalytics', '[testGoogleAnalyticsConfiguration]: Configure link from Status Reports page to Google Analytics Settings page exists.'); + $this->assertRaw('admin/config/system/googleanalytics', '[testGoogleAnalyticsConfiguration]: Configure link from Status Reports page to Google Analytics Settings page exists.'); // Check for setting page's presence. - $this->drupalGet('admin/settings/googleanalytics'); + $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/settings/googleanalytics', $edit, t('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.'); + $this->drupalPost('admin/config/system/googleanalytics', $edit, t('Save configuration')); + $this->assertRaw(t('A valid Web Property ID is case sensitive and formatted like UA-xxxxxxx-yy, G-XXXXXXX, DC-XXXXXXX, or AW-XXXXXXX.'), '[testGoogleAnalyticsConfiguration]: Invalid Web Property ID number validated.'); + + // User should have access to code snippets. + $this->assertFieldByName('googleanalytics_codesnippet_create'); + $this->assertFieldByName('googleanalytics_codesnippet_before'); + $this->assertFieldByName('googleanalytics_codesnippet_after'); + $this->assertNoFieldByXPath("//textarea[@name='googleanalytics_codesnippet_create' and @disabled='disabled']", NULL, '"Create only fields" is enabled.'); + $this->assertNoFieldByXPath("//textarea[@name='googleanalytics_codesnippet_before' and @disabled='disabled']", NULL, '"Code snippet (before)" is enabled.'); + $this->assertNoFieldByXPath("//textarea[@name='googleanalytics_codesnippet_after' and @disabled='disabled']", NULL, '"Code snippet (after)" is enabled.'); + + // Login as user without JS permissions. + $this->drupalLogin($this->noSnippetUser); + $this->drupalGet('admin/config/system/googleanalytics'); + + // User should *not* have access to snippets, but create fields. + $this->assertFieldByName('googleanalytics_codesnippet_create'); + $this->assertFieldByName('googleanalytics_codesnippet_before'); + $this->assertFieldByName('googleanalytics_codesnippet_after'); + $this->assertNoFieldByXPath("//textarea[@name='googleanalytics_codesnippet_create' and @disabled='disabled']", NULL, '"Create only fields" is enabled.'); + $this->assertFieldByXPath("//textarea[@name='googleanalytics_codesnippet_before' and @disabled='disabled']", NULL, '"Code snippet (before)" is disabled.'); + $this->assertFieldByXPath("//textarea[@name='googleanalytics_codesnippet_after' and @disabled='disabled']", NULL, '"Code snippet (after)" is disabled.'); } function testGoogleAnalyticsPageVisibility() { // Verify that no tracking code is embedded into the webpage; if there is // only the module installed, but UA code not configured. See #2246991. $this->drupalGet(''); - $this->assertNoRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsPageVisibility]: Tracking code is not displayed without UA code configured.'); + $this->assertNoRaw('https://www.googletagmanager.com/gtag/js?id=', '[testGoogleAnalyticsPageVisibility]: Tracking code is not displayed without UA code configured.'); $ua_code = 'UA-123456-1'; variable_set('googleanalytics_account', $ua_code); // Show tracking on "every page except the listed pages". - variable_set('googleanalytics_visibility', 0); + variable_set('googleanalytics_visibility_pages', 0); // Disable tracking on "admin*" pages only. variable_set('googleanalytics_pages', "admin\nadmin/*"); // Enable tracking only for authenticated users only. @@ -67,17 +102,17 @@ class GoogleAnalyticsBasicTest extends DrupalWebTestCase { // 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/settings/googleanalytics'); + $this->drupalGet('admin/config/system/googleanalytics'); // Checking for tracking code URI here, as $ua_code is displayed in the form. - $this->assertNoRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsPageVisibility]: Tracking code is not displayed on admin subpage.'); + $this->assertNoRaw('https://www.googletagmanager.com/gtag/js?id=', '[testGoogleAnalyticsPageVisibility]: Tracking code is not displayed on admin subpage.'); // Test whether tracking code display is properly flipped. - variable_set('googleanalytics_visibility', 1); + variable_set('googleanalytics_visibility_pages', 1); $this->drupalGet('admin'); $this->assertRaw($ua_code, '[testGoogleAnalyticsPageVisibility]: Tracking code is displayed on admin page.'); - $this->drupalGet('admin/settings/googleanalytics'); + $this->drupalGet('admin/config/system/googleanalytics'); // Checking for tracking code URI here, as $ua_code is displayed in the form. - $this->assertRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsPageVisibility]: Tracking code is displayed on admin subpage.'); + $this->assertRaw('https://www.googletagmanager.com/gtag/js?id=', '[testGoogleAnalyticsPageVisibility]: Tracking code is displayed on admin subpage.'); $this->drupalGet(''); $this->assertNoRaw($ua_code, '[testGoogleAnalyticsPageVisibility]: Tracking code is NOT displayed on front page.'); @@ -87,35 +122,37 @@ class GoogleAnalyticsBasicTest extends DrupalWebTestCase { $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', 0); + variable_set('googleanalytics_visibility_pages', 0); // Enable tracking code for all user roles. variable_set('googleanalytics_roles', array()); + $base_path = base_path(); + // 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.'); + $this->assertRaw($base_path . '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.'); + $this->assertRaw($base_path . '404.html', '[testGoogleAnalyticsPageVisibility]: 404 Not Found tracking code shown on non-existent page.'); // DNT Tests: // Enable system internal page cache 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.'); + $this->assertRaw('gtag("config", "' . $ua_code . '",', '[testGoogleAnalyticsDNTVisibility]: DNT header send from client, but page caching is enabled and tracker cannot removed.'); // DNT works only with system internal page cache for anonymous users disabled. variable_set('cache', 0); $this->drupalGet(''); - $this->assertRaw('ga("send", "pageview");', '[testGoogleAnalyticsDNTVisibility]: Tracking is enabled without DNT header.'); + $this->assertRaw('gtag("config", "' . $ua_code . '",', '[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.'); + $this->assertNoRaw('gtag("config", "' . $ua_code . '",', '[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.'); + $this->assertRaw('gtag("config", "' . $ua_code . '",', '[testGoogleAnalyticsDNTVisibility]: DNT feature is disabled, DNT header from browser has been ignored.'); } function testGoogleAnalyticsTrackingCode() { @@ -123,81 +160,80 @@ class GoogleAnalyticsBasicTest extends DrupalWebTestCase { variable_set('googleanalytics_account', $ua_code); // Show tracking code on every page except the listed pages. - variable_set('googleanalytics_visibility', 0); + 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: - + + + - */ // Test whether tracking code uses latest JS. variable_set('googleanalytics_cache', 0); $this->drupalGet(''); - $this->assertRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsTrackingCode]: Latest tracking code used.'); + $this->assertRaw('https://www.googletagmanager.com/gtag/js', '[testGoogleAnalyticsTrackingCode]: Latest tracking code used.'); // Test whether anonymize visitors IP address feature has been enabled. variable_set('googleanalytics_tracker_anonymizeip', 0); $this->drupalGet(''); - $this->assertNoRaw('ga("set", "anonymizeIp", true);', '[testGoogleAnalyticsTrackingCode]: Anonymize visitors IP address not found on frontpage.'); + $this->assertNoRaw('"anonymize_ip":true', '[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", true);', '[testGoogleAnalyticsTrackingCode]: Anonymize visitors IP address found on frontpage.'); + $this->assertRaw('"anonymize_ip":true', '[testGoogleAnalyticsTrackingCode]: Anonymize visitors IP address found on frontpage.'); + variable_set('googleanalytics_tracker_anonymizeip', 0); // Test if track Enhanced Link Attribution is enabled. variable_set('googleanalytics_tracklinkid', 1); $this->drupalGet(''); - $this->assertRaw('ga("require", "linkid", "linkid.js");', '[testGoogleAnalyticsTrackingCode]: Tracking code for Enhanced Link Attribution is enabled.'); + $this->assertRaw('"link_attribution":true', '[testGoogleAnalyticsTrackingCode]: Tracking code for Enhanced Link Attribution is enabled.'); // Test if track Enhanced Link Attribution is disabled. variable_set('googleanalytics_tracklinkid', 0); $this->drupalGet(''); - $this->assertNoRaw('ga("require", "linkid", "linkid.js");', '[testGoogleAnalyticsTrackingCode]: Tracking code for Enhanced Link Attribution is not enabled.'); + $this->assertNoRaw('"link_attribution":true', '[testGoogleAnalyticsTrackingCode]: Tracking code for Enhanced Link Attribution is not enabled.'); // Test if tracking of User ID is enabled. variable_set('googleanalytics_trackuserid', 1); $this->drupalGet(''); - $this->assertRaw(', { "cookieDomain": "auto", "userId": "', '[testGoogleAnalyticsTrackingCode]: Tracking code for User ID is enabled.'); + $this->assertRaw('"user_id":"', '[testGoogleAnalyticsTrackingCode]: Tracking code for User ID is enabled.'); // Test if tracking of User ID is disabled. variable_set('googleanalytics_trackuserid', 0); $this->drupalGet(''); - $this->assertNoRaw(', { "cookieDomain": "auto", "userId": "', '[testGoogleAnalyticsTrackingCode]: Tracking code for User ID is disabled.'); + $this->assertNoRaw('"user_id":"', '[testGoogleAnalyticsTrackingCode]: Tracking code for User ID is disabled.'); // Test if tracking of url fragments is enabled. variable_set('googleanalytics_trackurlfragments', 1); $this->drupalGet(''); - $this->assertRaw('ga("set", "page", location.pathname + location.search + location.hash);', '[testGoogleAnalyticsTrackingCode]: Tracking code for url fragments is enabled.'); + $this->assertRaw('"page_path":location.pathname + location.search + location.hash});', '[testGoogleAnalyticsTrackingCode]: Tracking code for url fragments is enabled.'); // Test if tracking of url fragments is disabled. variable_set('googleanalytics_trackurlfragments', 0); $this->drupalGet(''); - $this->assertNoRaw('ga("set", "page", location.pathname + location.search + location.hash);', '[testGoogleAnalyticsTrackingCode]: Tracking code for url fragments is not enabled.'); + $this->assertNoRaw('"page_path":location.pathname + location.search + location.hash});', '[testGoogleAnalyticsTrackingCode]: Tracking code for url fragments is not enabled.'); // Test if track display features is enabled. variable_set('googleanalytics_trackdoubleclick', 1); $this->drupalGet(''); - $this->assertRaw('ga("require", "displayfeatures");', '[testGoogleAnalyticsTrackingCode]: Tracking code for display features is enabled.'); + $this->assertRaw('"allow_ad_personalization_signals":false', '[testGoogleAnalyticsTrackingCode]: Tracking code for display features is enabled.'); // Test if track display features is disabled. variable_set('googleanalytics_trackdoubleclick', 0); $this->drupalGet(''); - $this->assertNoRaw('ga("require", "displayfeatures");', '[testGoogleAnalyticsTrackingCode]: Tracking code for display features is not enabled.'); + $this->assertNoRaw('"allow_ad_personalization_signals":false', '[testGoogleAnalyticsTrackingCode]: Tracking code for display features is not enabled.'); // Test whether single domain tracking is active. $this->drupalGet(''); - $this->assertRaw('{ "cookieDomain": "auto" }', '[testGoogleAnalyticsTrackingCode]: Single domain tracking is active.'); + $this->assertRaw('{"groups":"default"}', '[testGoogleAnalyticsTrackingCode]: Single domain tracking is active.'); // Enable "One domain with multiple subdomains". variable_set('googleanalytics_domain_mode', 1); @@ -207,53 +243,54 @@ class GoogleAnalyticsBasicTest extends DrupalWebTestCase { // 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('{ "cookieDomain": "' . $cookie_domain . '" }', '[testGoogleAnalyticsTrackingCode]: One domain with multiple subdomains is active on real host.'); + $this->assertRaw('{"cookieDomain":"' . $cookie_domain . '"}', '[testGoogleAnalyticsTrackingCode]: One domain with multiple subdomains is active on real host.'); } else { // Special cases, Localhost and IP addresses don't show '_setDomainName'. - $this->assertNoRaw('{ "cookieDomain": "' . $cookie_domain . '" }', '[testGoogleAnalyticsTrackingCode]: One domain with multiple subdomains may be active on localhost (test result is not reliable).'); + $this->assertNoRaw('{"cookieDomain":"' . $cookie_domain . '"}', '[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("create", "' . $ua_code . '", { "cookieDomain": "auto", "allowLinker": true', '[testGoogleAnalyticsTrackingCode]: "allowLinker" has been found. Cross domain tracking is active.'); - $this->assertRaw('ga("require", "linker");', '[testGoogleAnalyticsTrackingCode]: Require linker has been found. Cross domain tracking is active.'); - $this->assertRaw('ga("linker:autoLink", [ "www.example.com", "www.example.net" ]);', '[testGoogleAnalyticsTrackingCode]: "linker:autoLink" has been 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.'); + $this->assertRaw('gtag("config", "' . $ua_code . '", {"groups":"default","linker":', '[testGoogleAnalyticsTrackingCode]: "allowLinker" has been found. Cross domain tracking is active.'); + $this->assertRaw('gtag("config", "' . $ua_code . '", {"groups":"default","linker":{"domains":["www.example.com","www.example.net"]}});', '[testGoogleAnalyticsTrackingCode]: "linker:autoLink" has been found. Cross domain tracking is active.'); + $this->assertRaw('"trackDomainMode":2,', '[testGoogleAnalyticsTrackingCode]: Domain mode value is of type integer.'); + $this->assertRaw('"trackCrossDomains":["www.example.com","www.example.net"]', '[testGoogleAnalyticsTrackingCode]: Cross domain tracking with www.example.com and www.example.net is active.'); variable_set('googleanalytics_domain_mode', 0); // Test whether debugging script has been enabled. variable_set('googleanalytics_debug', 1); $this->drupalGet(''); - $this->assertRaw('//www.google-analytics.com/analytics_debug.js', '[testGoogleAnalyticsTrackingCode]: Google debugging script has been enabled.'); + // @FIXME + //$this->assertRaw('https://www.google-analytics.com/analytics_debug.js'); // Check if text and link is shown on 'Status Reports' page. // Requires 'administer site configuration' permission. $this->drupalGet('admin/reports/status'); - $this->assertRaw(t('Google Analytics module has debugging enabled. Please disable debugging setting in production sites from the Google Analytics settings page.', array('@url' => url('admin/settings/googleanalytics'))), '[testGoogleAnalyticsConfiguration]: Debugging enabled is shown on Status Reports page.'); + $this->assertRaw(t('Google Analytics module has debugging enabled. Please disable debugging setting in production sites from the Google Analytics settings page.', array('@url' => url('admin/config/system/googleanalytics'))), '[testGoogleAnalyticsConfiguration]: Debugging enabled is shown on Status Reports page.'); // Test whether debugging script has been disabled. variable_set('googleanalytics_debug', 0); $this->drupalGet(''); - $this->assertRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsTrackingCode]: Google debugging script has been disabled.'); + $this->assertRaw('https://www.googletagmanager.com/gtag/js?id=', '[testGoogleAnalyticsTrackingCode]: Google debugging script has been disabled.'); // Test whether the CREATE and BEFORE and AFTER code is added to the tracker. $codesnippet_create = array( - 'cookieDomain' => 'foo.example.com', - 'cookieName' => 'myNewName', - 'cookieExpires' => 20000, - 'allowAnchor' => TRUE, - 'sampleRate' => 4.3, + 'cookie_domain' => 'foo.example.com', + 'cookie_name' => 'myNewName', + 'cookie_expires' => 20000, + 'sample_rate' => 4.3, ); variable_set('googleanalytics_codesnippet_create', $codesnippet_create); - variable_set('googleanalytics_codesnippet_before', 'ga("set", "forceSSL", true);'); - variable_set('googleanalytics_codesnippet_after', 'ga("create", "UA-123456-3", { "name": "newTracker" });ga("newTracker.send", "pageview");'); + variable_set('googleanalytics_codesnippet_before', 'gtag("set", {"currency":"USD"});'); + variable_set('googleanalytics_codesnippet_after', 'gtag("config", "UA-123456-3", {"groups":"default"});if(1 == 1 && 2 < 3 && 2 > 1){console.log("Google Analytics: Custom condition works.");}'); $this->drupalGet(''); - $this->assertRaw('ga("create", "' . $ua_code . '", { "cookieDomain": "foo.example.com", "cookieName": "myNewName", "cookieExpires": 20000, "allowAnchor": true, "sampleRate": 4.3 });', '[testGoogleAnalyticsTrackingCode]: Create only fields have been found.'); - $this->assertRaw('ga("set", "forceSSL", true);', '[testGoogleAnalyticsTrackingCode]: Before codesnippet will force http pages to also send all beacons using https.'); - $this->assertRaw('ga("create", "UA-123456-3", { "name": "newTracker" });', '[testGoogleAnalyticsTrackingCode]: After codesnippet with "newTracker" tracker has been found.'); + $this->assertRaw('gtag("config", "' . $ua_code . '", {"groups":"default","cookie_domain":"foo.example.com","cookie_name":"myNewName","cookie_expires":20000,"sample_rate":4.3});', '[testGoogleAnalyticsTrackingCode]: Create only fields have been found.'); + $this->assertRaw('gtag("set", {"currency":"USD"});', '[testGoogleAnalyticsTrackingCode]: Before codesnippet will force http pages to also send all beacons using https.'); + $this->assertRaw('gtag("config", "UA-123456-3", {"groups":"default"});', '[testGoogleAnalyticsTrackingCode]: After codesnippet with "newTracker" tracker has been found.'); + $this->assertRaw('if(1 == 1 && 2 < 3 && 2 > 1){console.log("Google Analytics: Custom condition works.");}', '[testGoogleAnalyticsTrackingCode]: After codesnippet with "newTracker" tracker has been found.'); } } @@ -278,6 +315,7 @@ class GoogleAnalyticsCustomDimensionsAndMetricsTest extends DrupalWebTestCase { // User to set up google_analytics. $this->admin_user = $this->drupalCreateUser($permissions); + $this->drupalLogin($this->admin_user); } function testGoogleAnalyticsCustomDimensions() { @@ -288,31 +326,40 @@ class GoogleAnalyticsCustomDimensionsAndMetricsTest extends DrupalWebTestCase { $googleanalytics_custom_dimension = array( 1 => array( 'index' => 1, + 'name' => 'foo1', 'value' => 'Bar 1', ), 2 => array( 'index' => 2, + 'name' => 'foo2', 'value' => 'Bar 2', ), 3 => array( 'index' => 3, + 'name' => 'foo3', 'value' => 'Bar 3', ), 4 => array( 'index' => 4, + 'name' => 'foo4', 'value' => 'Bar 4', ), 5 => array( 'index' => 5, + 'name' => 'foo5', 'value' => 'Bar 5', ), ); variable_set('googleanalytics_custom_dimension', $googleanalytics_custom_dimension); $this->drupalGet(''); + $custom_vars = array(); foreach ($googleanalytics_custom_dimension as $dimension) { - $this->assertRaw('ga("set", ' . drupal_to_js('dimension' . $dimension['index']) . ', ' . drupal_to_js($dimension['value']) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Dimension #' . $dimension['index'] . ' is shown.'); + $custom_vars[$dimension['name']] = $dimension['value']; } + $custom_vars['groups'] = 'default'; + $custom_vars['anonymize_ip'] = TRUE; + $this->assertRaw('gtag("config", ' . drupal_json_encode($ua_code) . ', ' . drupal_json_encode($custom_vars) . ');'); // Test whether tokens are replaced in custom dimension values. $site_slogan = $this->randomName(16); @@ -321,19 +368,23 @@ class GoogleAnalyticsCustomDimensionsAndMetricsTest extends DrupalWebTestCase { $googleanalytics_custom_dimension = array( 1 => array( 'index' => 1, - 'value' => 'Value: [site-slogan]', + 'name' => 'site_slogan', + 'value' => 'Value: [site:slogan]', ), 2 => array( 'index' => 2, + 'name' => 'machine_name', 'value' => $this->randomName(16), ), 3 => array( 'index' => 3, + 'name' => 'foo3', 'value' => '', ), // #2300701: Custom dimensions and custom metrics not outputed on zero value. 4 => array( 'index' => 4, + 'name' => 'bar4', 'value' => '0', ), ); @@ -341,10 +392,11 @@ class GoogleAnalyticsCustomDimensionsAndMetricsTest extends DrupalWebTestCase { $this->verbose('
' . print_r($googleanalytics_custom_dimension, TRUE) . '
'); $this->drupalGet(''); - $this->assertRaw('ga("set", ' . drupal_to_js('dimension1') . ', ' . drupal_to_js("Value: $site_slogan") . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Tokens have been replaced in dimension value.'); - $this->assertRaw('ga("set", ' . drupal_to_js('dimension2') . ', ' . drupal_to_js($googleanalytics_custom_dimension['2']['value']) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Random value is shown.'); - $this->assertNoRaw('ga("set", ' . drupal_to_js('dimension3') . ', ' . drupal_to_js('') . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Empty value is not shown.'); - $this->assertRaw('ga("set", ' . drupal_to_js('dimension4') . ', ' . drupal_to_js('0') . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Value 0 is shown.'); + $this->assertRaw(drupal_json_encode($googleanalytics_custom_dimension['1']['name']) . ':' . drupal_json_encode("Value: $site_slogan"), '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Tokens have been replaced in dimension value.'); + $this->assertRaw(drupal_json_encode($googleanalytics_custom_dimension['2']['name']) . ':' . drupal_json_encode($googleanalytics_custom_dimension['2']['value']), '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Random machine_name value is shown.'); + $this->assertNoRaw(drupal_json_encode($googleanalytics_custom_dimension['3']['name']) . ':', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Empty value name is not shown.'); + $this->assertNoRaw(drupal_json_encode($googleanalytics_custom_dimension['3']['name']) . ':' . drupal_json_encode(''), '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Empty value is not shown.'); + $this->assertRaw(drupal_json_encode($googleanalytics_custom_dimension['4']['name']) . ':' . drupal_json_encode('0'), '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Value 0 is shown.'); } function testGoogleAnalyticsCustomMetrics() { @@ -355,22 +407,27 @@ class GoogleAnalyticsCustomDimensionsAndMetricsTest extends DrupalWebTestCase { $googleanalytics_custom_metric = array( 1 => array( 'index' => 1, + 'name' => 'foo1', 'value' => '6', ), 2 => array( 'index' => 2, + 'name' => 'foo2', 'value' => '8000', ), 3 => array( 'index' => 3, + 'name' => 'foo3', 'value' => '7.8654', ), 4 => array( 'index' => 4, + 'name' => 'foo4', 'value' => '1123.4', ), 5 => array( 'index' => 5, + 'name' => 'foo5', 'value' => '5,67', ), ); @@ -378,27 +435,35 @@ class GoogleAnalyticsCustomDimensionsAndMetricsTest extends DrupalWebTestCase { variable_set('googleanalytics_custom_metric', $googleanalytics_custom_metric); $this->drupalGet(''); + $custom_vars = array(); foreach ($googleanalytics_custom_metric as $metric) { - $this->assertRaw('ga("set", ' . drupal_to_js('metric' . $metric['index']) . ', ' . drupal_to_js((float) $metric['value']) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Metric #' . $metric['index'] . ' is shown.'); + $custom_vars[$metric['name']] = (float) $metric['value']; } + $custom_vars['groups'] = 'default'; + $custom_vars['anonymize_ip'] = TRUE; + $this->assertRaw('gtag("config", ' . drupal_json_encode($ua_code) . ', ' . drupal_json_encode($custom_vars) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Metric config is shown.'); // Test whether tokens are replaced in custom metric values. $googleanalytics_custom_metric = array( 1 => array( 'index' => 1, - 'value' => '[site-date-raw]', + 'name' => 'bar1', + 'value' => '[current-user:roles:count]', ), 2 => array( 'index' => 2, + 'name' => 'bar2', 'value' => mt_rand(), ), 3 => array( 'index' => 3, + 'name' => 'bar3', 'value' => '', ), // #2300701: Custom dimensions and custom metrics not outputed on zero value. 4 => array( 'index' => 4, + 'name' => 'bar4', 'value' => '0', ), ); @@ -406,11 +471,81 @@ class GoogleAnalyticsCustomDimensionsAndMetricsTest extends DrupalWebTestCase { $this->verbose('
' . print_r($googleanalytics_custom_metric, TRUE) . '
'); $this->drupalGet(''); - $this->assertRaw('ga("set", ' . drupal_to_js('metric1') . ', ', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Tokens have been replaced in metric value.'); - $this->assertRaw('ga("set", ' . drupal_to_js('metric2') . ', ' . drupal_to_js($googleanalytics_custom_metric['2']['value']) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Random value is shown.'); - $this->assertNoRaw('ga("set", ' . drupal_to_js('metric3') . ', ' . drupal_to_js('') . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Empty value is not shown.'); - $this->assertRaw('ga("set", ' . drupal_to_js('metric4') . ', ' . drupal_to_js(0) . ');', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Value 0 is shown.'); + $this->assertRaw(drupal_json_encode($googleanalytics_custom_metric['1']['name']) . ':' . drupal_json_encode((int) token_replace($googleanalytics_custom_metric['1']['value'], array(), array('clear' => TRUE))), '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Tokens have been replaced in metric value.'); + $this->assertRaw(drupal_json_encode($googleanalytics_custom_metric['2']['name']) . ':' . drupal_json_encode($googleanalytics_custom_metric['2']['value']), '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Random value is shown.'); + $this->assertNoRaw(drupal_json_encode($googleanalytics_custom_metric['3']['name']) . ':', '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Empty value is not shown.'); + $this->assertRaw(drupal_json_encode($googleanalytics_custom_metric['4']['name']) . ':' . drupal_json_encode(0), '[testGoogleAnalyticsCustomDimensionsAndMetrics]: Value 0 is shown.'); + } + + /** + * Tests if Custom Dimensions token form validation works. + */ + public function testGoogleAnalyticsCustomDimensionsTokenFormValidation() { + $ua_code = 'UA-123456-1'; + + // Check form validation. + $edit['googleanalytics_account'] = $ua_code; + $edit['googleanalytics_custom_dimension[indexes][1][value]'] = '[current-user:name]'; + $edit['googleanalytics_custom_dimension[indexes][2][value]'] = '[current-user:edit-url]'; + $edit['googleanalytics_custom_dimension[indexes][3][value]'] = '[user:name]'; + $edit['googleanalytics_custom_dimension[indexes][4][value]'] = '[term:name]'; + $edit['googleanalytics_custom_dimension[indexes][5][value]'] = '[term:tid]'; + + $this->drupalPost('admin/config/system/googleanalytics', $edit, t('Save configuration')); + + $this->assertRaw(t('The %element-title is using the following forbidden tokens with personal identifying information: @invalid-tokens.', array('%element-title' => t('Custom dimension value #@index', array('@index' => 1)), '@invalid-tokens' => implode(', ', array('[current-user:name]'))))); + $this->assertRaw(t('The %element-title is using the following forbidden tokens with personal identifying information: @invalid-tokens.', array('%element-title' => t('Custom dimension value #@index', array('@index' => 2)), '@invalid-tokens' => implode(', ', array('[current-user:edit-url]'))))); + $this->assertRaw(t('The %element-title is using the following forbidden tokens with personal identifying information: @invalid-tokens.', array('%element-title' => t('Custom dimension value #@index', array('@index' => 3)), '@invalid-tokens' => implode(', ', array('[user:name]'))))); + // BUG #2037595 + //$this->assertNoRaw(t('The %element-title is using the following forbidden tokens with personal identifying information: @invalid-tokens.', array('%element-title' => t('Custom dimension value #@index', array('@index' => 4)), '@invalid-tokens' => implode(', ', array('[term:name]'))))); + //$this->assertNoRaw(t('The %element-title is using the following forbidden tokens with personal identifying information: @invalid-tokens.', array('%element-title' => t('Custom dimension value #@index', array('@index' => 5)), '@invalid-tokens' => implode(', ', array('[term:tid]'))))); + } +} + +/** + * Test custom url functionality of Google Analytics module. + */ +class GoogleAnalyticsCustomUrls extends DrupalWebTestCase { + + public static function getInfo() { + return array( + 'name' => 'Google Analytics custom url tests', + 'description' => 'Test custom url 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); + } + + /** + * Tests if user password page urls are overridden. + */ + public function testGoogleAnalyticsUserPasswordPage() { + $base_path = base_path(); + $ua_code = 'UA-123456-4'; + variable_set('googleanalytics_account', $ua_code); + variable_set('googleanalytics_tracker_anonymizeip', 0); + + $this->drupalGet('user/password', array('query' => array('name' => 'foo'))); + $this->assertRaw('gtag("config", ' . drupal_json_encode($ua_code) . ', {"groups":"default","page_path":"' . $base_path . 'user/password"});'); + + $this->drupalGet('user/password', array('query' => array('name' => 'foo@example.com'))); + $this->assertRaw('gtag("config", ' . drupal_json_encode($ua_code) . ', {"groups":"default","page_path":"' . $base_path . 'user/password"});'); + + $this->drupalGet('user/password'); + $this->assertNoRaw('"page_path":"' . $base_path . 'user/password"});'); } + } class GoogleAnalyticsStatusMessagesTest extends DrupalWebTestCase { @@ -443,14 +578,14 @@ class GoogleAnalyticsStatusMessagesTest extends DrupalWebTestCase { variable_set('googleanalytics_trackmessages', array('error' => 'error')); $this->drupalPost('user/login', array(), t('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.'); + $this->assertRaw('gtag("event", "Error message", {"event_category":"Messages","event_label":"Username field is required."});', '[testGoogleAnalyticsStatusMessages]: Event message "Username field is required." is shown.'); + $this->assertRaw('gtag("event", "Error message", {"event_category":"Messages","event_label":"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 message with html tags and link.', 'error'); + //drupal_set_message('Example error message with html tags and link.', '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.'); @@ -588,51 +723,45 @@ class GoogleAnalyticsSearchTest extends DrupalWebTestCase { // Enable site search support. variable_set('googleanalytics_site_search', 1); + variable_set('googleanalytics_tracker_anonymizeip', 0); // Search for random string. $search = array(); $search['keys'] = $this->randomName(8); // Create a node to search for. + $langcode = LANGUAGE_NONE; $edit = array(); $edit['title'] = 'This is a test title'; - $edit['body'] = 'This test content contains ' . $search['keys'] . ' string.'; + $edit["body[$langcode][0][value]"] = 'This test content contains ' . $search['keys'] . ' string.'; // Fire a search, it's expected to get 0 results. $this->drupalPost('search/node', $search, t('Search')); - $this->assertRaw('ga("set", "page", (window.googleanalytics_search_results) ?', '[testGoogleAnalyticsSearch]: Search results tracker is displayed.'); - // D6 special! D7 and D8 will show it with value 0. - $this->assertNoRaw('window.googleanalytics_search_results = 0;', '[testGoogleAnalyticsSearch]: Search yielded no results.'); + $this->assertRaw('gtag("config", ' . drupal_json_encode($ua_code) . ', {"groups":"default","page_path":(window.googleanalytics_search_results) ?', '[testGoogleAnalyticsSearch]: Search results tracker is displayed.'); + $this->assertRaw('window.googleanalytics_search_results = 0;', '[testGoogleAnalyticsSearch]: Search yielded no results.'); // Save the node. $this->drupalPost('node/add/page', $edit, t('Save')); - $this->assertRaw(t('@type %title has been created.', array('@type' => 'Page', '%title' => $edit['title'])), t('Node was created.')); + $this->assertText(t('@type @title has been created.', array('@type' => 'Basic page', '@title' => $edit['title'])), 'Node was created.'); // Index the node or it cannot found. - $this->GoogleAnalyticsCronRun(); + $this->cronRun(); $this->drupalPost('search/node', $search, t('Search')); - $this->assertRaw('ga("set", "page", (window.googleanalytics_search_results) ?', '[testGoogleAnalyticsSearch]: Search results tracker is displayed.'); + $this->assertRaw('gtag("config", ' . drupal_json_encode($ua_code) . ', {"groups":"default","page_path":(window.googleanalytics_search_results) ?', '[testGoogleAnalyticsSearch]: Search results tracker is displayed.'); $this->assertRaw('window.googleanalytics_search_results = 1;', '[testGoogleAnalyticsSearch]: One search result found.'); $this->drupalPost('node/add/page', $edit, t('Save')); - $this->assertRaw(t('@type %title has been created.', array('@type' => 'Page', '%title' => $edit['title'])), t('Node was created.')); + $this->assertText(t('@type @title has been created.', array('@type' => 'Basic page', '@title' => $edit['title'])), 'Node was created.'); // Index the node or it cannot found. - $this->GoogleAnalyticsCronRun(); + $this->cronRun(); $this->drupalPost('search/node', $search, t('Search')); - $this->assertRaw('ga("set", "page", (window.googleanalytics_search_results) ?', '[testGoogleAnalyticsSearch]: Search results tracker is displayed.'); + $this->assertRaw('gtag("config", ' . drupal_json_encode($ua_code) . ', {"groups":"default","page_path":(window.googleanalytics_search_results) ?', '[testGoogleAnalyticsSearch]: Search results tracker is displayed.'); $this->assertRaw('window.googleanalytics_search_results = 2;', '[testGoogleAnalyticsSearch]: Two search results found.'); } - /** - * Backport of simpletest D7 $this->cronRun(). - */ - protected function GoogleAnalyticsCronRun() { - $this->drupalGet($GLOBALS['base_url'] . '/cron.php', array('external' => TRUE)); - } - } class GoogleAnalyticsPhpFilterTest extends DrupalWebTestCase { @@ -670,9 +799,9 @@ class GoogleAnalyticsPhpFilterTest extends DrupalWebTestCase { $edit = array(); $edit['googleanalytics_account'] = $ua_code; - $edit['googleanalytics_visibility'] = 2; + $edit['googleanalytics_visibility_pages'] = 2; $edit['googleanalytics_pages'] = ''; - $this->drupalPost('admin/settings/googleanalytics', $edit, t('Save configuration')); + $this->drupalPost('admin/config/system/googleanalytics', $edit, t('Save configuration')); // Compare saved setting with posted setting. $googleanalytics_pages = variable_get('googleanalytics_pages', $this->randomName(8)); @@ -681,23 +810,23 @@ class GoogleAnalyticsPhpFilterTest extends DrupalWebTestCase { // Check tracking code visibility. variable_set('googleanalytics_pages', ''); $this->drupalGet(''); - $this->assertRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsPhpFilter]: Tracking is displayed on frontpage page.'); + $this->assertRaw('https://www.googletagmanager.com/gtag/js?id=', '[testGoogleAnalyticsPhpFilter]: Tracking is displayed on frontpage page.'); $this->drupalGet('admin'); - $this->assertRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsPhpFilter]: Tracking is displayed on admin page.'); + $this->assertRaw('https://www.googletagmanager.com/gtag/js?id=', '[testGoogleAnalyticsPhpFilter]: Tracking is displayed on admin page.'); variable_set('googleanalytics_pages', ''); $this->drupalGet(''); - $this->assertNoRaw('//www.google-analytics.com/analytics.js', '[testGoogleAnalyticsPhpFilter]: Tracking is not displayed on frontpage page.'); + $this->assertNoRaw('https://www.googletagmanager.com/gtag/js?id=', '[testGoogleAnalyticsPhpFilter]: Tracking is not displayed on frontpage page.'); // Test administration form. variable_set('googleanalytics_pages', ''); - $this->drupalGet('admin/settings/googleanalytics'); + $this->drupalGet('admin/config/system/googleanalytics'); $this->assertRaw(t('Pages on which this PHP code returns TRUE (experts only)'), '[testGoogleAnalyticsPhpFilter]: Permission to administer PHP for tracking visibility.'); $this->assertRaw(check_plain(''), '[testGoogleAnalyticsPhpFilter]: PHP code snippted is displayed.'); // Login the delegated user and check if fields are visible. $this->drupalLogin($this->delegated_admin_user); - $this->drupalGet('admin/settings/googleanalytics'); + $this->drupalGet('admin/config/system/googleanalytics'); $this->assertNoRaw(t('Pages on which this PHP code returns TRUE (experts only)'), '[testGoogleAnalyticsPhpFilter]: No permission to administer PHP for tracking visibility.'); $this->assertNoRaw(check_plain(''), '[testGoogleAnalyticsPhpFilter]: No permission to view PHP code snippted.'); @@ -706,10 +835,10 @@ class GoogleAnalyticsPhpFilterTest extends DrupalWebTestCase { $edit = array(); $edit['googleanalytics_account'] = $ua_code; - $this->drupalPost('admin/settings/googleanalytics', $edit, t('Save configuration')); + $this->drupalPost('admin/config/system/googleanalytics', $edit, t('Save configuration')); // Compare saved setting with posted setting. - $googleanalytics_visibility_pages = variable_get('googleanalytics_visibility', 0); + $googleanalytics_visibility_pages = variable_get('googleanalytics_visibility_pages', 0); $googleanalytics_pages = variable_get('googleanalytics_pages', $this->randomName(8)); $this->assertEqual(2, $googleanalytics_visibility_pages, '[testGoogleAnalyticsPhpFilter]: Pages on which this PHP code returns TRUE is selected.'); $this->assertEqual('', $googleanalytics_pages, '[testGoogleAnalyticsPhpFilter]: PHP code snippet is intact.'); diff --git a/googleanalytics.test.js b/googleanalytics.test.js index 762214c..f22d6f1 100644 --- a/googleanalytics.test.js +++ b/googleanalytics.test.js @@ -1,3 +1,5 @@ +(function ($) { + /** * This file is for developers only. * @@ -75,7 +77,7 @@ $(document).ready(function() { Drupal.googleanalytics.test.assertTrue(Drupal.googleanalytics.isInternal(base_url + Drupal.settings.basePath + 'node/1?foo=bar'), "Link '" + base_url + Drupal.settings.basePath + "node/1?foo=bar' has been detected as internal link."); Drupal.googleanalytics.test.assertTrue(Drupal.googleanalytics.isInternal(base_url + Drupal.settings.basePath + 'node/1?foo=bar#foo'), "Link '" + base_url + Drupal.settings.basePath + "node/1?foo=bar#foo' has been detected as internal link."); Drupal.googleanalytics.test.assertTrue(Drupal.googleanalytics.isInternal(base_url + Drupal.settings.basePath + 'go/foo'), "Link '" + base_url + Drupal.settings.basePath + "go/foo' has been detected as internal link."); - Drupal.googleanalytics.test.assertFalse(Drupal.googleanalytics.isInternal('http://example.com/node/3'), "Link 'http://example.com/node/3' has been detected as external link."); + Drupal.googleanalytics.test.assertFalse(Drupal.googleanalytics.isInternal('https://example.com/node/3'), "Link 'https://example.com/node/3' has been detected as external link."); console.groupEnd(); console.group("Test 'isInternalSpecial':"); @@ -84,9 +86,11 @@ $(document).ready(function() { console.groupEnd(); console.group("Test 'getPageUrl':"); - Drupal.googleanalytics.test.assertSame(base_path, Drupal.googleanalytics.getPageUrl(base_url + Drupal.settings.basePath + 'node/1'), "Absolute internal URL '" + Drupal.settings.basePath + "node/1' has been extracted from full qualified url '" + base_url + base_path + "'."); - Drupal.googleanalytics.test.assertSame(base_path, Drupal.googleanalytics.getPageUrl(Drupal.settings.basePath + 'node/1'), "Absolute internal URL '" + Drupal.settings.basePath + "node/1' has been extracted from absolute url '" + base_path + "'."); - Drupal.googleanalytics.test.assertSame('http://example.com/node/2', Drupal.googleanalytics.getPageUrl('http://example.com/node/2'), "Full qualified external url 'http://example.com/node/2' has been extracted."); + Drupal.google_analytics.test.assertSame(base_path, Drupal.google_analytics.getPageUrl(window.location.href), "Absolute internal URL '" + base_path + "' has been extracted from full qualified url '" + window.location.href + "'."); + Drupal.google_analytics.test.assertSame(base_path, Drupal.google_analytics.getPageUrl(base_path), "Absolute internal URL '" + base_path + "' has been extracted from absolute url '" + base_path + "'."); + //Drupal.googleanalytics.test.assertSame(base_path, Drupal.googleanalytics.getPageUrl(base_url + Drupal.settings.basePath + 'node/1'), "Absolute internal URL '" + Drupal.settings.basePath + "node/1' has been extracted from full qualified url '" + base_url + base_path + "'."); + //Drupal.googleanalytics.test.assertSame(base_path, Drupal.googleanalytics.getPageUrl(Drupal.settings.basePath + 'node/1'), "Absolute internal URL '" + Drupal.settings.basePath + "node/1' has been extracted from absolute url '" + base_path + "'."); + Drupal.googleanalytics.test.assertSame('https://example.com/node/2', Drupal.googleanalytics.getPageUrl('https://example.com/node/2'), "Full qualified external url 'https://example.com/node/2' has been extracted."); Drupal.googleanalytics.test.assertSame('//example.com/node/2', Drupal.googleanalytics.getPageUrl('//example.com/node/2'), "Full qualified external url '//example.com/node/2' has been extracted."); console.groupEnd(); @@ -103,9 +107,9 @@ $(document).ready(function() { if (Drupal.settings.googleanalytics.trackCrossDomains) { console.dir(Drupal.settings.googleanalytics.trackCrossDomains); Drupal.googleanalytics.test.assertTrue(Drupal.googleanalytics.isCrossDomain('example.com', Drupal.settings.googleanalytics.trackCrossDomains), "URL 'example.com' has been found in cross domain list."); - Drupal.googleanalytics.test.assertTrue(Drupal.googleanalytics.isCrossDomain('example.net', Drupal.settings.googleanalytics.trackCrossDomains), "URL 'example.com' has been found in cross domain list."); + Drupal.googleanalytics.test.assertTrue(Drupal.googleanalytics.isCrossDomain('example.net', Drupal.settings.googleanalytics.trackCrossDomains), "URL 'example.net' has been found in cross domain list."); Drupal.googleanalytics.test.assertFalse(Drupal.googleanalytics.isCrossDomain('www.example.com', Drupal.settings.googleanalytics.trackCrossDomains), "URL 'www.example.com' not found in cross domain list."); - Drupal.googleanalytics.test.assertFalse(Drupal.googleanalytics.isCrossDomain('www.example.net', Drupal.settings.googleanalytics.trackCrossDomains), "URL 'www.example.com' not found in cross domain list."); + Drupal.googleanalytics.test.assertFalse(Drupal.googleanalytics.isCrossDomain('www.example.net', Drupal.settings.googleanalytics.trackCrossDomains), "URL 'www.example.net' not found in cross domain list."); } else { console.warn('Cross domain tracking is not enabled. Tests skipped.'); @@ -113,3 +117,5 @@ $(document).ready(function() { console.groupEnd(); }); + +})(jQuery); diff --git a/googleanalytics.tokens.inc b/googleanalytics.tokens.inc new file mode 100644 index 0000000..0ab195c --- /dev/null +++ b/googleanalytics.tokens.inc @@ -0,0 +1,55 @@ + t('User role names'), + 'description' => t('The role names the user account is a member of as comma separated list.'), + 'needs-data' => 'user', + ); + $user['role-ids'] = array( + 'name' => t('User role ids'), + 'description' => t('The role ids the user account is a member of as comma separated list.'), + 'needs-data' => 'user', + ); + + return array( + 'tokens' => array('user' => $user), + ); +} + +/** + * Implements hook_tokens(). + */ +function googleanalytics_tokens($type, $tokens, array $data = array(), array $options = array()) { + $sanitize = !empty($options['sanitize']); + $replacements = array(); + + if ($type == 'user' && !empty($data['user']->roles)) { + $account = $data['user']; + + foreach ($tokens as $name => $original) { + switch ($name) { + // Basic user account information. + case 'role-names': + $names = implode(',', $account->roles); + $replacements[$original] = $sanitize ? check_plain($names) : $names; + break; + + case 'role-ids': + $ids = implode(',', array_keys($account->roles)); + $replacements[$original] = $sanitize ? check_plain($ids) : $ids; + break; + } + } + } + + return $replacements; +} diff --git a/googleanalytics.variable.inc b/googleanalytics.variable.inc new file mode 100644 index 0000000..62a30e6 --- /dev/null +++ b/googleanalytics.variable.inc @@ -0,0 +1,55 @@ + 'string', + 'title' => t('Web Property ID', array(), $options), + 'default' => 'UA-', + 'description' => t('This ID is unique to each site you want to track separately, and is in the form UA-xxxxxxx-yy, G-XXXXXXX, DC-XXXXXXX, or AW-XXXXXXX. To get a Web Property ID, register your site with Google Analytics, or if you already have registered your site, go to your Google Analytics Settings page to see the ID next to every site profile. Find more information in the documentation.', array('@analytics' => 'https://marketingplatform.google.com/about/analytics/', '@webpropertyid' => url('https://developers.google.com/analytics/resources/concepts/gaConceptsAccounts', array('fragment' => 'webProperty'))), $options), + 'required' => TRUE, + 'group' => 'googleanalytics', + 'localize' => TRUE, + 'multidomain' => TRUE, + 'validate callback' => 'googleanalytics_validate_googleanalytics_account', + ); + + return $variables; +} + +/** + * Implements hook_variable_group_info(). + */ +function googleanalytics_variable_group_info() { + $groups['googleanalytics'] = array( + 'title' => t('Google Analytics'), + 'description' => t('Configure tracking behavior to get insights into your website traffic and marketing effectiveness.'), + 'access' => 'administer google analytics', + 'path' => array('admin/config/system/googleanalytics'), + ); + + return $groups; +} + +/** + * Validate Web Property ID variable. + * + * @param array $variable + * + * @return string + */ +function googleanalytics_validate_googleanalytics_account($variable) { + // Replace all type of dashes (n-dash, m-dash, minus) with the normal dashes. + $variable['value'] = str_replace(array('–', '—', '−'), '-', $variable['value']); + + if (!_google_analytics_valid_property_id($variable['value'])) { + return t('A valid Web Property ID is case sensitive and formatted like UA-xxxxxxx-yy, G-XXXXXXX, DC-XXXXXXX, or AW-XXXXXXX.'); + } +}