new commit

This commit is contained in:
Bachir Soussi Chiadmi 2021-03-15 13:28:36 +01:00
parent 04c585f500
commit be8ccebfac
13 changed files with 3035 additions and 56 deletions

View File

@ -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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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.
<signature of Ty Coon>, 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.

View File

@ -0,0 +1,95 @@
Module: Matomo Analytics
Author: Alexander Hass <https://www.hass.de/>
Description
===========
Adds the Matomo tracking system to your website.
Requirements
============
* Matomo installation
* Matomo website account
Installation
============
* Copy the 'matomo' module directory in to your Drupal
sites/all/modules directory as usual.
Usage
=====
In the settings page enter your Matomo website ID.
You will also need to define what user roles should be tracked.
Simply tick the roles you would like to monitor.
All pages will now have the required JavaScript added to the
HTML footer can confirm this by viewing the page source from
your browser.
Custom variables
=================
One example for custom variables tracking is the "User roles" tracking. Enter
the below configuration data into the custom variables settings form under
admin/config/system/matomo.
Slot: 1
Name: User roles
Value: [current-user:matomo-role-names]
Scope: Visitor
Slot: 1
Name: User ids
Value: [current-user:matomo-role-ids]
Scope: Visitor
More details about custom variables can be found in the Matomo API documentation
at https://matomo.org/docs/javascript-tracking/#toc-custom-variables.
Advanced Settings
=================
You can include additional JavaScript snippets in the advanced
textarea. These can be found on various blog posts, or on the
official Matomo pages. Support is not provided for any customisations
you include.
To speed up page loading you may also cache the matomo.js
file locally. You need to make sure the site file system is in public
download mode.
Known issues
============
Drupal requirements (https://drupal.org/requirements) tell you to configure
PHP with "session.save_handler = user", but your Matomo installation may
not work with this configuration and gives you a server error 500.
1. You are able to workaround with the PHP default in your php.ini:
[Session]
session.save_handler = files
2. With Apache you may overwrite the PHP setting for the Matomo directory only.
If Matomo is installed in /matomo you are able to create a .htaccess file in
this directory with the below code:
# PHP 4, Apache 1.
<IfModule mod_php4.c>
php_value session.save_handler files
</IfModule>
# PHP 4, Apache 2.
<IfModule sapi_apache2.c>
php_value session.save_handler files
</IfModule>
# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
php_value session.save_handler files
</IfModule>

View File

@ -0,0 +1,640 @@
<?php
/**
* @file
* Administrative page callbacks for the matomo module.
*/
/**
* Implements hook_admin_settings() for configuring the module.
*/
function matomo_admin_settings_form($form_state) {
$form['account'] = array(
'#type' => 'fieldset',
'#title' => t('General settings'),
);
$form['account']['matomo_site_id'] = array(
'#type' => 'textfield',
'#title' => t('Matomo site ID'),
'#default_value' => variable_get('matomo_site_id', ''),
'#size' => 15,
'#maxlength' => 20,
'#required' => TRUE,
'#description' => t('The user account number is unique to the websites domain. Click the <strong>Settings</strong> link in your Matomo account, then the <strong>Websites</strong> tab and enter the appropriate site <strong>ID</strong> into this field.'),
);
$form['account']['matomo_url_http'] = array(
'#type' => 'textfield',
'#title' => t('Matomo HTTP URL'),
'#default_value' => variable_get('matomo_url_http', ''),
'#size' => 80,
'#maxlength' => 255,
'#required' => TRUE,
'#description' => t('The URL to your Matomo base directory. Example: "http://www.example.com/matomo/".'),
);
$form['account']['matomo_url_https'] = array(
'#type' => 'textfield',
'#title' => t('Matomo HTTPS URL'),
'#default_value' => variable_get('matomo_url_https', ''),
'#size' => 80,
'#maxlength' => 255,
'#description' => t('The URL to your Matomo base directory with SSL certificate installed. Required if you track a SSL enabled website. Example: "https://www.example.com/matomo/".'),
);
// Required for automated form save testing only.
$form['account']['matomo_url_skiperror'] = array(
'#type' => 'hidden',
'#default_value' => FALSE,
);
// Visibility settings.
$form['tracking_title'] = array(
'#type' => 'item',
'#title' => t('Tracking scope'),
);
$form['tracking'] = array(
'#type' => 'vertical_tabs',
'#attached' => array(
'js' => array(drupal_get_path('module', 'matomo') . '/matomo.admin.js'),
),
);
$form['tracking']['domain_tracking'] = array(
'#type' => 'fieldset',
'#title' => t('Domains'),
);
global $cookie_domain;
$multiple_sub_domains = array();
foreach (array('www', 'app', 'shop') as $subdomain) {
if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
$multiple_sub_domains[] = $subdomain . $cookie_domain;
}
// IP addresses or localhost.
else {
$multiple_sub_domains[] = $subdomain . '.example.com';
}
}
$form['tracking']['domain_tracking']['matomo_domain_mode'] = array(
'#type' => 'radios',
'#title' => t('What are you tracking?'),
'#options' => array(
0 => t('A single domain (default)') . '<div class="description">' . t('Domain: @domain', array('@domain' => $_SERVER['HTTP_HOST'])) . '</div>',
1 => t('One domain with multiple subdomains') . '<div class="description">' . t('Examples: @domains', array('@domains' => implode(', ', $multiple_sub_domains))) . '</div>',
),
'#default_value' => variable_get('matomo_domain_mode', 0),
);
// Page specific visibility configurations.
$php_access = user_access('use php for matomo tracking visibility');
$visibility = variable_get('matomo_visibility_pages', 0);
$pages = variable_get('matomo_pages', MATOMO_PAGES);
$form['tracking']['page_vis_settings'] = array(
'#type' => 'fieldset',
'#title' => t('Pages'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
if ($visibility == 2 && !$php_access) {
$form['tracking']['page_vis_settings'] = array();
$form['tracking']['page_vis_settings']['matomo_visibility_pages'] = array('#type' => 'value', '#value' => 2);
$form['tracking']['page_vis_settings']['matomo_pages'] = array('#type' => 'value', '#value' => $pages);
}
else {
$options = array(
t('Every page except the listed pages'),
t('The listed pages only')
);
$description = t("Specify pages by using their paths. Enter one path per line. The '*' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page.", array('%blog' => 'blog', '%blog-wildcard' => 'blog/*', '%front' => '<front>'));
if (module_exists('php') && $php_access) {
$options[] = t('Pages on which this PHP code returns <code>TRUE</code> (experts only)');
$title = t('Pages or PHP code');
$description .= ' ' . t('If the PHP option is chosen, enter PHP code between %php. Note that executing incorrect PHP code can break your Drupal site.', array('%php' => '<?php ?>'));
}
else {
$title = t('Pages');
}
$form['tracking']['page_vis_settings']['matomo_visibility_pages'] = array(
'#type' => 'radios',
'#title' => t('Add tracking to specific pages'),
'#options' => $options,
'#default_value' => $visibility,
);
$form['tracking']['page_vis_settings']['matomo_pages'] = array(
'#type' => 'textarea',
'#title' => $title,
'#title_display' => 'invisible',
'#default_value' => $pages,
'#description' => $description,
'#rows' => 10,
);
}
// Render the role overview.
$form['tracking']['role_vis_settings'] = array(
'#type' => 'fieldset',
'#title' => t('Roles'),
);
$form['tracking']['role_vis_settings']['matomo_visibility_roles'] = array(
'#type' => 'radios',
'#title' => t('Add tracking for specific roles'),
'#options' => array(
t('Add to the selected roles only'),
t('Add to every role except the selected ones'),
),
'#default_value' => variable_get('matomo_visibility_roles', 0),
);
$role_options = array_map('check_plain', user_roles());
$form['tracking']['role_vis_settings']['matomo_roles'] = array(
'#type' => 'checkboxes',
'#title' => t('Roles'),
'#default_value' => variable_get('matomo_roles', array()),
'#options' => $role_options,
'#description' => t('If none of the roles are selected, all users will be tracked. If a user has any of the roles checked, that user will be tracked (or excluded, depending on the setting above).'),
);
// Standard tracking configurations.
$form['tracking']['user_vis_settings'] = array(
'#type' => 'fieldset',
'#title' => t('Users'),
);
$t_permission = array('%permission' => t('Opt-in or out of tracking'));
$form['tracking']['user_vis_settings']['matomo_custom'] = array(
'#type' => 'radios',
'#title' => t('Allow users to customize tracking on their account page'),
'#options' => array(
0 => t('No customization allowed'),
1 => t('Tracking on by default, users with %permission permission can opt out', $t_permission),
2 => t('Tracking off by default, users with %permission permission can opt in', $t_permission)
),
'#default_value' => variable_get('matomo_custom', 1),
);
$form['tracking']['user_vis_settings']['matomo_trackuserid'] = array(
'#type' => 'checkbox',
'#title' => t('Track User ID'),
'#default_value' => variable_get('matomo_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. <a href="@url">Learn more about the benefits of using User ID</a>.', array('@url' => 'https://matomo.org/docs/user-id/')),
);
// Link specific configurations.
$form['tracking']['linktracking'] = array(
'#type' => 'fieldset',
'#title' => t('Links and downloads'),
);
$form['tracking']['linktracking']['matomo_trackmailto'] = array(
'#type' => 'checkbox',
'#title' => t('Track clicks on mailto links'),
'#default_value' => variable_get('matomo_trackmailto', 1),
);
$form['tracking']['linktracking']['matomo_track'] = array(
'#type' => 'checkbox',
'#title' => t('Track clicks on outbound links and downloads (clicks on file links) for the following extensions'),
'#default_value' => variable_get('matomo_track', 1),
);
$form['tracking']['linktracking']['matomo_trackfiles_extensions'] = array(
'#title' => t('List of download file extensions'),
'#title_display' => 'invisible',
'#type' => 'textfield',
'#default_value' => variable_get('matomo_trackfiles_extensions', MATOMO_TRACKFILES_EXTENSIONS),
'#description' => t('A file extension list separated by the | character that will be tracked when clicked. Regular expressions are supported. For example: !extensions', array('!extensions' => MATOMO_TRACKFILES_EXTENSIONS)),
'#maxlength' => 500,
'#states' => array(
'enabled' => array(
':input[name="matomo_track"]' => array('checked' => TRUE),
),
# Note: Form required marker is not visible as title is invisible.
'required' => array(
':input[name="matomo_track"]' => array('checked' => TRUE),
),
),
);
$colorbox_dependencies = '<div class="admin-requirements">';
$colorbox_dependencies .= t('Requires: !module-list', array('!module-list' => (module_exists('colorbox') ? t('@module (<span class="admin-enabled">enabled</span>)', array('@module' => 'Colorbox')) : t('@module (<span class="admin-disabled">disabled</span>)', array('@module' => 'Colorbox')))));
$colorbox_dependencies .= '</div>';
$form['tracking']['linktracking']['matomo_trackcolorbox'] = array(
'#type' => 'checkbox',
'#title' => t('Track content in colorbox modal dialogs'),
'#default_value' => variable_get('matomo_trackcolorbox', 1),
'#description' => t('Enable to track the content shown in colorbox modal windows.') . $colorbox_dependencies,
'#disabled' => (module_exists('colorbox') ? FALSE : TRUE),
);
// Message specific configurations.
$form['tracking']['messagetracking'] = array(
'#type' => 'fieldset',
'#title' => t('Messages'),
);
$form['tracking']['messagetracking']['matomo_trackmessages'] = array(
'#type' => 'checkboxes',
'#title' => t('Track messages of type'),
'#default_value' => variable_get('matomo_trackmessages', array()),
'#description' => t('This will track the selected message types shown to users. Tracking of form validation errors may help you identifying usability issues in your site. Every message is tracked as one individual event. Messages from excluded pages cannot be tracked.'),
'#options' => array(
'status' => t('Status message'),
'warning' => t('Warning message'),
'error' => t('Error message'),
),
);
$form['tracking']['search'] = array(
'#type' => 'fieldset',
'#title' => t('Search'),
);
$site_search_dependencies = '<div class="admin-requirements">';
$site_search_dependencies .= t('Requires: !module-list', array('!module-list' => (module_exists('search') ? t('@module (<span class="admin-enabled">enabled</span>)', array('@module' => 'Search')) : t('@module (<span class="admin-disabled">disabled</span>)', array('@module' => 'Search')))));
$site_search_dependencies .= '</div>';
$form['tracking']['search']['matomo_site_search'] = array(
'#type' => 'checkbox',
'#title' => t('Track internal search'),
'#description' => t('If checked, internal search keywords are tracked.') . $site_search_dependencies,
'#default_value' => variable_get('matomo_site_search', FALSE),
'#disabled' => (module_exists('search') ? FALSE : TRUE),
);
// Privacy specific configurations.
$form['tracking']['privacy'] = array(
'#type' => 'fieldset',
'#title' => t('Privacy'),
);
$form['tracking']['privacy']['matomo_privacy_donottrack'] = array(
'#type' => 'checkbox',
'#title' => t('Universal web tracking opt-out'),
'#description' => t('If enabled and your Matomo server receives the <a href="@donottrack">Do-Not-Track</a> header from the client browser, the Matomo server will not track the user. 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.', array('@donottrack' => 'https://www.eff.org/issues/do-not-track')),
'#default_value' => variable_get('matomo_privacy_donottrack', 1),
);
// Matomo page title tree view settings.
$form['page_title_hierarchy'] = array(
'#type' => 'fieldset',
'#title' => t('Page titles hierarchy'),
'#description' => t('This functionality enables a dynamically expandable tree view of your site page titles in your Matomo statistics. See in Matomo statistics under <em>Actions</em> > <em>Page titles</em>.'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['page_title_hierarchy']['matomo_page_title_hierarchy'] = array(
'#type' => 'checkbox',
'#title' => t("Show page titles as hierarchy like breadcrumbs"),
'#description' => t('By default Matomo tracks the current page title and shows you a flat list of the most popular titles. This enables a breadcrumbs like tree view.'),
'#default_value' => variable_get('matomo_page_title_hierarchy', FALSE),
);
$form['page_title_hierarchy']['matomo_page_title_hierarchy_exclude_home'] = array(
'#type' => 'checkbox',
'#title' => t('Hide home page from hierarchy'),
'#description' => t('If enabled, the "Home" item will be removed from the hierarchy to flatten the structure in the Matomo statistics. Hits to the home page will still be counted, but for other pages the hierarchy will start at level Home+1.'),
'#default_value' => variable_get('matomo_page_title_hierarchy_exclude_home', TRUE),
);
$form['matomo_custom_var'] = array(
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#description' => t('You can add Matomos <a href="!custom_var_documentation">Custom Variables</a> here. These will be added to every page that Matomo tracking code appears on. Custom variable names and values are limited to 200 characters in length. Keep the names and values as short as possible and expect long values to get trimmed. You may use tokens in custom variable names and values. Global and user tokens are always available; on node pages, node tokens are also available.', array('!custom_var_documentation' => 'https://matomo.org/docs/custom-variables/')),
'#theme' => 'matomo_admin_custom_var_table',
'#title' => t('Custom variables'),
'#tree' => TRUE,
'#type' => 'fieldset',
);
$matomo_custom_vars = variable_get('matomo_custom_var', array());
// Matomo supports up to 5 custom variables.
for ($i = 1; $i < 6; $i++) {
$form['matomo_custom_var']['slots'][$i]['slot'] = array(
'#default_value' => $i,
'#description' => t('Slot number'),
'#disabled' => TRUE,
'#size' => 1,
'#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
'#title_display' => 'invisible',
'#type' => 'textfield',
);
$form['matomo_custom_var']['slots'][$i]['name'] = array(
'#default_value' => !empty($matomo_custom_vars['slots'][$i]['name']) ? $matomo_custom_vars['slots'][$i]['name'] : '',
'#description' => t('The custom variable name.'),
'#maxlength' => 100,
'#size' => 20,
'#title' => t('Custom variable name #@slot', array('@slot' => $i)),
'#title_display' => 'invisible',
'#type' => 'textfield',
);
$form['matomo_custom_var']['slots'][$i]['value'] = array(
'#default_value' => !empty($matomo_custom_vars['slots'][$i]['value']) ? $matomo_custom_vars['slots'][$i]['value'] : '',
'#description' => t('The custom variable value.'),
'#maxlength' => 255,
'#title' => t('Custom variable value #@slot', array('@slot' => $i)),
'#title_display' => 'invisible',
'#type' => 'textfield',
'#element_validate' => array('matomo_token_element_validate'),
'#token_types' => array('node'),
);
if (module_exists('token')) {
$form['matomo_custom_var']['slots'][$i]['value']['#element_validate'][] = 'token_element_validate';
}
$form['matomo_custom_var']['slots'][$i]['scope'] = array(
'#default_value' => !empty($matomo_custom_vars['slots'][$i]['scope']) ? $matomo_custom_vars['slots'][$i]['scope'] : 'visit',
'#description' => t('The scope for the custom variable.'),
'#title' => t('Custom variable slot #@slot', array('@slot' => $i)),
'#title_display' => 'invisible',
'#type' => 'select',
'#options' => array(
'visit' => t('Visit'),
'page' => t('Page'),
),
);
}
$form['matomo_custom_var']['matomo_custom_var_description'] = array(
'#type' => 'item',
'#description' => t('You can supplement Matomos\' basic IP address tracking of visitors by segmenting users based on custom variables. Make sure you will not associate (or permit any third party to associate) any data gathered from your websites (or such third parties\' websites) with any personally identifying information from any source as part of your use (or such third parties\' use) of the Matomo\' service.'),
);
$form['matomo_custom_var']['matomo_custom_var_token_tree'] = array(
'#theme' => 'token_tree',
'#token_types' => array('node'),
'#dialog' => TRUE,
);
// Advanced feature configurations.
$form['advanced'] = array(
'#type' => 'fieldset',
'#title' => t('Advanced settings'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['advanced']['matomo_cache'] = array(
'#type' => 'checkbox',
'#title' => t('Locally cache tracking code file'),
'#description' => t('If checked, the tracking code file is retrieved from your Matomo site and cached locally. It is updated daily to ensure updates to tracking code are reflected in the local copy.'),
'#default_value' => variable_get('matomo_cache', 0),
);
// Allow for tracking of the originating node when viewing translation sets.
if (module_exists('translation')) {
$form['advanced']['matomo_translation_set'] = array(
'#type' => 'checkbox',
'#title' => t('Track translation sets as one unit'),
'#description' => t('When a node is part of a translation set, record statistics for the originating node instead. This allows for a translation set to be treated as a single unit.'),
'#default_value' => variable_get('matomo_translation_set', 0),
);
}
// Code snippet settings.
$user_access_add_js_snippets = !user_access('add js snippets for matomo');
$user_access_add_js_snippets_permission_warning = $user_access_add_js_snippets ? ' <em>' . t('This field has been disabled because you do not have sufficient permissions to edit it.') . '</em>' : '';
$form['advanced']['codesnippet'] = array(
'#type' => 'fieldset',
'#title' => t('Custom JavaScript code'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#description' => t('You can add custom Matomo <a href="@snippets">code snippets</a> here. These will be added to every page that Matomo appears on. <strong>Do not include the &lt;script&gt; tags</strong>, and always end your code with a semicolon (;).', array('@snippets' => 'https://matomo.org/docs/javascript-tracking/'))
);
$form['advanced']['codesnippet']['matomo_codesnippet_before'] = array(
'#type' => 'textarea',
'#title' => t('Code snippet (before)'),
'#default_value' => variable_get('matomo_codesnippet_before', ''),
'#disabled' => $user_access_add_js_snippets,
'#rows' => 5,
'#description' => t('Code in this textarea will be added <strong>before</strong> _paq.push(["trackPageView"]).')
);
$form['advanced']['codesnippet']['matomo_codesnippet_after'] = array(
'#type' => 'textarea',
'#title' => t('Code snippet (after)'),
'#default_value' => variable_get('matomo_codesnippet_after', ''),
'#disabled' => $user_access_add_js_snippets,
'#rows' => 5,
'#description' => t('Code in this textarea will be added <strong>after</strong> _paq.push(["trackPageView"]). This is useful if you\'d like to track a site in two accounts.')
);
$form['advanced']['matomo_js_scope'] = array(
'#type' => 'select',
'#title' => t('JavaScript scope'),
'#description' => t("Matomo recommends adding the tracking code to the header for performance reasons."),
'#options' => array(
'footer' => t('Footer'),
'header' => t('Header'),
),
'#default_value' => variable_get('matomo_js_scope', 'header'),
);
return system_settings_form($form);
}
function matomo_admin_settings_form_validate($form, &$form_state) {
// Custom variables validation.
foreach ($form_state['values']['matomo_custom_var']['slots'] as $custom_var) {
$form_state['values']['matomo_custom_var']['slots'][$custom_var['slot']]['name'] = trim($custom_var['name']);
$form_state['values']['matomo_custom_var']['slots'][$custom_var['slot']]['value'] = trim($custom_var['value']);
// Validate empty names/values.
if (empty($custom_var['name']) && !empty($custom_var['value'])) {
form_set_error("matomo_custom_var][slots][" . $custom_var['slot'] . "][name", t('The custom variable @slot-number requires a <em>Name</em> if a <em>Value</em> has been provided.', array('@slot-number' => $custom_var['slot'])));
}
elseif (!empty($custom_var['name']) && empty($custom_var['value'])) {
form_set_error("matomo_custom_var][slots][" . $custom_var['slot'] . "][value", t('The custom variable @slot-number requires a <em>Value</em> if a <em>Name</em> has been provided.', array('@slot-number' => $custom_var['slot'])));
}
}
// Trim some text area values.
$form_state['values']['matomo_site_id'] = trim($form_state['values']['matomo_site_id']);
$form_state['values']['matomo_pages'] = trim($form_state['values']['matomo_pages']);
$form_state['values']['matomo_codesnippet_before'] = trim($form_state['values']['matomo_codesnippet_before']);
$form_state['values']['matomo_codesnippet_after'] = trim($form_state['values']['matomo_codesnippet_after']);
if (!preg_match('/^\d{1,}$/', $form_state['values']['matomo_site_id'])) {
form_set_error('matomo_site_id', t('A valid Matomo site ID is an integer only.'));
}
$matomo_url = $form_state['values']['matomo_url_http'];
if ('/' != drupal_substr($matomo_url, -1, 1)) {
$matomo_url = $matomo_url . '/';
$form_state['values']['matomo_url_http'] = $matomo_url;
}
$url = $matomo_url . 'piwik.php';
$result = drupal_http_request($url);
if ($result->code != 200 && $form_state['values']['matomo_url_skiperror'] == FALSE) {
form_set_error('matomo_url_http', t('The validation of "@url" failed with error "@error" (HTTP code @code).', array('@url' => check_url($url), '@error' => $result->error, '@code' => $result->code)));
}
if (!empty($form_state['values']['matomo_url_https'])) {
$matomo_url = $form_state['values']['matomo_url_https'];
if ('/' != drupal_substr($matomo_url, -1, 1)) {
$matomo_url = $matomo_url . '/';
$form_state['values']['matomo_url_https'] = $matomo_url;
}
$url = $matomo_url . 'piwik.php';
$result = drupal_http_request($url);
if ($result->code != 200 && $form_state['values']['matomo_url_skiperror'] == FALSE) {
form_set_error('matomo_url_https', t('The validation of "@url" failed with error "@error" (HTTP code @code).', array('@url' => check_url($url), '@error' => $result->error, '@code' => $result->code)));
}
}
// Delete obsolete local cache file.
if (empty($form_state['values']['matomo_cache']) && $form['advanced']['matomo_cache']['#default_value']) {
matomo_clear_js_cache();
}
// This is for the Newbie's who cannot read a text area description.
if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['matomo_codesnippet_before'])) {
form_set_error('matomo_codesnippet_before', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
}
if (preg_match('/(.*)<\/?script(.*)>(.*)/i', $form_state['values']['matomo_codesnippet_after'])) {
form_set_error('matomo_codesnippet_after', t('Do not include the &lt;script&gt; tags in the javascript code snippets.'));
}
}
/**
* Layout for the custom variables table in the admin settings form.
*
* @param array $variables
* An array contains the form elements.
*
* @return string
* The rendered output.
*/
function theme_matomo_admin_custom_var_table($variables) {
$form = $variables['form'];
$header = array(
array('data' => t('Slot')),
array('data' => t('Name')),
array('data' => t('Value')),
array('data' => t('Scope')),
);
$rows = array();
foreach (element_children($form['slots']) as $key => $id) {
$rows[] = array(
'data' => array(
drupal_render($form['slots'][$id]['slot']),
drupal_render($form['slots'][$id]['name']),
drupal_render($form['slots'][$id]['value']),
drupal_render($form['slots'][$id]['scope']),
),
);
}
$output = theme('table', array('header' => $header, 'rows' => $rows));
$output .= drupal_render($form['matomo_custom_var_description']);
$output .= drupal_render($form['matomo_custom_var_token_tree']);
return $output;
}
/**
* Validate a form element that should have tokens in it.
*
* For example:
* @code
* $form['my_node_text_element'] = array(
* '#type' => 'textfield',
* '#title' => t('Some text to token-ize that has a node context.'),
* '#default_value' => 'The title of this node is [node:title].',
* '#element_validate' => array('matomo_token_element_validate'),
* );
* @endcode
*/
function matomo_token_element_validate(&$element, &$form_state) {
$value = isset($element['#value']) ? $element['#value'] : $element['#default_value'];
if (!drupal_strlen($value)) {
// Empty value needs no further validation since the element should depend
// on using the '#required' FAPI property.
return $element;
}
$tokens = token_scan($value);
$invalid_tokens = _matomo_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' => $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 _matomo_get_forbidden_tokens($value) {
$invalid_tokens = array();
$value_tokens = is_string($value) ? token_scan($value) : $value;
foreach ($value_tokens as $type => $tokens) {
if (array_filter($tokens, '_matomo_contains_forbidden_token')) {
$invalid_tokens = array_merge($invalid_tokens, array_values($tokens));
}
}
array_unique($invalid_tokens);
return $invalid_tokens;
}
/**
* Validate if a string contains forbidden tokens not allowed by privacy rules.
*
* @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.
*/
function _matomo_contains_forbidden_token($token_string) {
// List of strings in tokens with personal identifying information not allowed
// for privacy reasons. See section 8.1 of the Google Analytics terms of use
// for more detailed information.
//
// This list can never ever be complete. For this reason it tries to use a
// regex and may kill a few other valid tokens, but it's the only way to
// protect users as much as possible from admins with illegal ideas.
//
// User tokens are not prefixed with colon to catch 'current-user' and 'user'.
//
// TODO: If someone have better ideas, share them, please!
$token_blacklist = array(
':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);
}

View File

@ -0,0 +1,120 @@
(function ($) {
/**
* Provide the summary information for the tracking settings vertical tabs.
*/
Drupal.behaviors.trackingSettingsSummary = {
attach: function (context) {
// Make sure this behavior is processed only if drupalSetSummary is defined.
if (typeof jQuery.fn.drupalSetSummary == 'undefined') {
return;
}
$('fieldset#edit-domain-tracking', context).drupalSetSummary(function (context) {
var $radio = $('input[name="matomo_domain_mode"]:checked', context);
if ($radio.val() == 0) {
return Drupal.t('A single domain');
}
else if ($radio.val() == 1) {
return Drupal.t('One domain with multiple subdomains');
}
});
$('fieldset#edit-page-vis-settings', context).drupalSetSummary(function (context) {
var $radio = $('input[name="matomo_visibility_pages"]:checked', context);
if ($radio.val() == 0) {
if (!$('textarea[name="matomo_pages"]', context).val()) {
return Drupal.t('Not restricted');
}
else {
return Drupal.t('All pages with exceptions');
}
}
else {
return Drupal.t('Restricted to certain pages');
}
});
$('fieldset#edit-role-vis-settings', context).drupalSetSummary(function (context) {
var vals = [];
$('input[type="checkbox"]:checked', context).each(function () {
vals.push($.trim($(this).next('label').text()));
});
if (!vals.length) {
return Drupal.t('Not restricted');
}
else if ($('input[name="matomo_visibility_roles"]:checked', context).val() == 1) {
return Drupal.t('Excepted: @roles', {'@roles' : vals.join(', ')});
}
else {
return vals.join(', ');
}
});
$('fieldset#edit-user-vis-settings', context).drupalSetSummary(function (context) {
var $radio = $('input[name="matomo_custom"]:checked', context);
if ($radio.val() == 0) {
return Drupal.t('Not customizable');
}
else if ($radio.val() == 1) {
return Drupal.t('On by default with opt out');
}
else {
return Drupal.t('Off by default with opt in');
}
});
$('fieldset#edit-linktracking', context).drupalSetSummary(function (context) {
var vals = [];
if ($('input#edit-matomo-trackmailto', context).is(':checked')) {
vals.push(Drupal.t('Mailto links'));
}
if ($('input#edit-matomo-track', context).is(':checked')) {
vals.push(Drupal.t('Outbound links'));
vals.push(Drupal.t('Downloads'));
}
if ($('input#edit-matomo-trackcolorbox', context).is(':checked')) {
vals.push(Drupal.t('Colorbox'));
}
if (!vals.length) {
return Drupal.t('Not tracked');
}
return Drupal.t('@items enabled', {'@items' : vals.join(', ')});
});
$('fieldset#edit-messagetracking', context).drupalSetSummary(function (context) {
var vals = [];
$('input[type="checkbox"]:checked', context).each(function () {
vals.push($.trim($(this).next('label').text()));
});
if (!vals.length) {
return Drupal.t('Not tracked');
}
return Drupal.t('@items enabled', {'@items' : vals.join(', ')});
});
$('fieldset#edit-search', context).drupalSetSummary(function (context) {
var vals = [];
if ($('input#edit-matomo-site-search', context).is(':checked')) {
vals.push(Drupal.t('Site search'));
}
if (!vals.length) {
return Drupal.t('Not tracked');
}
return Drupal.t('@items enabled', {'@items' : vals.join(', ')});
});
$('fieldset#edit-privacy', context).drupalSetSummary(function (context) {
var vals = [];
if ($('input#edit-matomo-privacy-donottrack', context).is(':checked')) {
vals.push(Drupal.t('Universal web tracking opt-out'));
}
if (!vals.length) {
return Drupal.t('No privacy');
}
return Drupal.t('@items enabled', {'@items' : vals.join(', ')});
});
}
};
})(jQuery);

View File

@ -0,0 +1,13 @@
name = "Matomo Analytics"
description = Adds Matomo javascript tracking code to all your site's pages.
core = 7.x
package = Statistics
configure = admin/config/system/matomo
files[] = matomo.test
test_dependencies[] = token
; Information added by Drupal.org packaging script on 2019-01-31
version = "7.x-2.12"
core = "7.x"
project = "matomo"
datestamp = "1548968889"

View File

@ -0,0 +1,102 @@
<?php
/**
* @file
* Installation file for Matomo Analytics module.
*/
function matomo_install() {
// Remove tracking from all administrative pages, see https://drupal.org/node/34970.
variable_set('matomo_visibility_roles', 0);
variable_set('matomo_visibility_pages', 0);
$pages = array(
'admin',
'admin/*',
'batch',
'node/add*',
'node/*/*',
'user/*/*',
);
variable_set('matomo_pages', implode("\n", $pages));
// Make the default install more user and GDPR friendly.
user_role_grant_permissions(DRUPAL_AUTHENTICATED_RID, array('opt-in or out of matomo tracking'));
drupal_set_message(t('Module %module granted %permission permission to authenticated users.', array('%module' => 'Matomo Analytics', '%permission' => t('Opt-in or out of tracking'))), 'status');
}
function matomo_uninstall() {
variable_del('matomo_cache');
variable_del('matomo_codesnippet_before');
variable_del('matomo_codesnippet_after');
variable_del('matomo_custom');
variable_del('matomo_custom_var');
variable_del('matomo_domain_mode');
variable_del('matomo_js_scope');
variable_del('matomo_last_cache');
variable_del('matomo_page_title_hierarchy');
variable_del('matomo_page_title_hierarchy_exclude_home');
variable_del('matomo_pages');
variable_del('matomo_privacy_donottrack');
variable_del('matomo_roles');
variable_del('matomo_site_id');
variable_del('matomo_site_search');
variable_del('matomo_trackcolorbox');
variable_del('matomo_trackmailto');
variable_del('matomo_track'); // interrims solution
variable_del('matomo_trackfiles_extensions');
variable_del('matomo_trackmessages');
variable_del('matomo_trackuserid');
variable_del('matomo_translation_set');
variable_del('matomo_url_http');
variable_del('matomo_url_https');
variable_del('matomo_visibility_pages');
variable_del('matomo_visibility_roles');
// Remove backup variables if exits. Remove this code in D8.
variable_del('matomo_codesnippet_before_backup_7202');
variable_del('matomo_codesnippet_after_backup_7202');
}
/**
* Remove cache directory if module is disabled (or uninstalled).
*/
function matomo_disable() {
matomo_clear_js_cache();
}
/**
* Implementation of hook_requirements().
*/
function matomo_requirements($phase) {
$requirements = array();
$t = get_t();
switch ($phase) {
case 'runtime':
// Module cannot validate matomo URL without external HTTP requests.
if (variable_get('drupal_http_request_fails', TRUE) && !system_check_http_request()) {
$requirements['matomo_http_requests'] = array(
'title' => $t('HTTP request status'),
'value' => $t('Fails'),
'severity' => REQUIREMENT_ERROR,
'description' => $t('Your system or network configuration does not allow Drupal to access web pages, resulting in reduced functionality. This could be due to your webserver configuration or PHP settings, and should be resolved in order to download information about available updates, fetch aggregator feeds, sign in via OpenID, or use other network-dependent services.'),
);
}
// Raise warning if Matomo user account has not been set yet.
if (!preg_match('/^\d{1,}$/', variable_get('matomo_site_id', ''))) {
$requirements['matomo'] = array(
'title' => $t('Matomo module'),
'description' => $t('Matomo module has not been configured yet. Please configure its settings from the <a href="@url">Matomo settings page</a>.', array('@url' => url('admin/config/system/matomo'))),
'severity' => REQUIREMENT_WARNING,
'value' => $t('Not configured'),
);
}
break;
}
return $requirements;
}
/**
* NOTE: Next update need to be 7206 or updates for 'dev' users may break.
*/

View File

@ -0,0 +1,34 @@
(function ($) {
$(document).ready(function() {
// Attach mousedown, keyup, touchstart events to document only and catch
// clicks on all elements.
$(document.body).bind("mousedown keyup touchstart", function(event) {
// Catch the closest surrounding link of a clicked element.
$(event.target).closest("a,area").each(function() {
if (Drupal.settings.matomo.trackMailto && $(this).is("a[href^='mailto:'],area[href^='mailto:']")) {
// Mailto link clicked.
_paq.push(["trackEvent", "Mails", "Click", this.href.substring(7)]);
}
});
});
// Colorbox: This event triggers when the transition has completed and the
// newly loaded content has been revealed.
if (Drupal.settings.matomo.trackColorbox) {
$(document).bind("cbox_complete", function () {
var href = $.colorbox.element().attr("href");
if (href) {
_paq.push(["setCustomUrl", href]);
_paq.push(["trackPageView"]);
}
});
}
});
})(jQuery);

View File

@ -0,0 +1,725 @@
<?php
/**
* @file
* Drupal Module: Matomo
*
* Adds the required Javascript to all your Drupal pages to allow tracking by
* the Matomo statistics package.
*
* @author: Alexander Hass <https://drupal.org/user/85918>
*/
/**
* Define the default file extension list that should be tracked as download.
*/
define('MATOMO_TRACKFILES_EXTENSIONS', '7z|aac|arc|arj|asf|asx|avi|bin|csv|doc(x|m)?|dot(x|m)?|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt(x|m)?|pot(x|m)?|pps(x|m)?|ppam|sld(x|m)?|thmx|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls(x|m|b)?|xlt(x|m)|xlam|xml|z|zip');
/**
* Define default path exclusion list to remove tracking from admin pages,
* see https://drupal.org/node/34970 for more information.
*/
define('MATOMO_PAGES', "admin\nadmin/*\nbatch\nnode/add*\nnode/*/*\nuser/*/*");
/**
* Implements hook_help().
*/
function matomo_help($path, $arg) {
switch ($path) {
case 'admin/config/system/matomo':
return t('<a href="@pk_url">Matomo Analytics</a> is an open source (GPL license) web analytics software. It gives interesting reports on your website visitors, your popular pages, the search engines keywords they used, the language they speak... and so much more. Matomo aims to be an open source alternative to Google Analytics.', array('@pk_url' => 'https://www.matomo.org/'));
}
}
/**
* Implements hook_theme().
*/
function matomo_theme() {
return array(
'matomo_admin_custom_var_table' => array(
'render element' => 'form',
),
);
}
/**
* Implements hook_permission().
*/
function matomo_permission() {
return array(
'administer matomo' => array(
'title' => t('Administer Matomo'),
'description' => t('Perform maintenance tasks for Matomo.'),
),
'opt-in or out of matomo tracking' => array(
'title' => t('Opt-in or out of tracking'),
'description' => t('Allow users to decide if tracking code will be added to pages or not.'),
),
'use php for matomo tracking visibility' => array(
'title' => t('Use PHP for tracking visibility'),
'description' => t('Enter PHP code in the field for tracking visibility settings.'),
'restrict access' => TRUE,
),
'add js snippets for matomo' => array(
'title' => t('Add JavaScript snippets'),
'description' => 'Enter JavaScript code snippets for advanced Matomo functionality.',
'restrict access' => TRUE,
),
);
}
/**
* Implements hook_menu().
*/
function matomo_menu() {
$items['admin/config/system/matomo'] = array(
'title' => 'Matomo Analytics',
'description' => 'Configure the settings used to generate your Matomo tracking code.',
'page callback' => 'drupal_get_form',
'page arguments' => array('matomo_admin_settings_form'),
'access arguments' => array('administer matomo'),
'type' => MENU_NORMAL_ITEM,
'file' => 'matomo.admin.inc',
);
return $items;
}
/**
* Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.
*/
function matomo_page_alter(&$page) {
global $user;
$id = variable_get('matomo_site_id', '');
// Get page status code for visibility filtering.
$status = drupal_get_http_header('Status');
$trackable_status_codes = array(
'403 Forbidden',
'404 Not Found',
);
// 1. Check if the matomo account number has a value.
// 2. Track page views based on visibility value.
// 3. Check if we should track the currently active user's role.
if (preg_match('/^\d{1,}$/', $id) && (_matomo_visibility_pages() || in_array($status, $trackable_status_codes)) && _matomo_visibility_user($user)) {
$url_http = variable_get('matomo_url_http', '');
$url_https = variable_get('matomo_url_https', '');
$scope = variable_get('matomo_js_scope', 'header');
$set_custom_url = '';
$set_document_title = '';
// Add link tracking.
$link_settings = array();
$link_settings['trackMailto'] = variable_get('matomo_trackmailto', 1);
if (module_exists('colorbox') && ($track_colorbox = variable_get('matomo_trackcolorbox', 1))) {
$link_settings['trackColorbox'] = $track_colorbox;
}
drupal_add_js(array('matomo' => $link_settings), 'setting');
drupal_add_js(drupal_get_path('module', 'matomo') . '/matomo.js');
// Matomo can show a tree view of page titles that represents the site structure
// if setDocumentTitle() provides the page titles as a "/" delimited list.
// This may makes it easier to browse through the statistics of page titles
// on larger sites.
if (variable_get('matomo_page_title_hierarchy', FALSE) == TRUE) {
$titles = _matomo_get_hierarchy_titles();
if (variable_get('matomo_page_title_hierarchy_exclude_home', TRUE)) {
// Remove the "Home" item from the titles to flatten the tree view.
array_shift($titles);
}
// Remove all empty titles.
$titles = array_filter($titles);
if (!empty($titles)) {
// Encode title, at least to keep "/" intact.
$titles = array_map('rawurlencode', $titles);
$set_document_title = drupal_json_encode(implode('/', $titles));
}
}
// Add messages tracking.
$message_events = '';
if ($message_types = variable_get('matomo_trackmessages', array())) {
$message_types = array_values(array_filter($message_types));
$status_heading = array(
'status' => t('Status message'),
'warning' => t('Warning message'),
'error' => t('Error message'),
);
foreach (drupal_get_messages(NULL, FALSE) as $type => $messages) {
// Track only the selected message types.
if (in_array($type, $message_types)) {
foreach ($messages as $message) {
$message_events .= '_paq.push(["trackEvent", ' . drupal_json_encode(t('Messages')) . ', ' . drupal_json_encode($status_heading[$type]) . ', ' . drupal_json_encode(strip_tags($message)) . ']);';
}
}
}
}
// If this node is a translation of another node, pass the original
// node instead.
if (module_exists('translation') && variable_get('matomo_translation_set', 0)) {
// 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) && !empty($node->tnid) && ($node->tnid != $node->nid)) {
$source_node = node_load($node->tnid);
$languages = language_list();
$set_custom_url = drupal_json_encode(url('node/' . $source_node->nid, array('language' => $languages[$source_node->language], 'absolute' => TRUE)));
}
}
// Track access denied (403) and file not found (404) pages.
if ($status == '403 Forbidden') {
$set_document_title = '"403/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)';
}
elseif ($status == '404 Not Found') {
$set_document_title = '"404/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(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 Matomo 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', drupal_get_query_parameters())) {
$set_custom_url = drupal_json_encode(url('user/password'));
}
// Add custom variables.
$matomo_custom_vars = variable_get('matomo_custom_var', array());
$custom_variable = '';
for ($i = 1; $i < 6; $i++) {
$custom_var_name = !empty($matomo_custom_vars['slots'][$i]['name']) ? $matomo_custom_vars['slots'][$i]['name'] : '';
if (!empty($custom_var_name)) {
$custom_var_value = !empty($matomo_custom_vars['slots'][$i]['value']) ? $matomo_custom_vars['slots'][$i]['value'] : '';
$custom_var_scope = !empty($matomo_custom_vars['slots'][$i]['scope']) ? $matomo_custom_vars['slots'][$i]['scope'] : 'visit';
$types = array();
$node = menu_get_object();
if (is_object($node)) {
$types += array('node' => $node);
}
$custom_var_name = token_replace($custom_var_name, $types, array('clear' => TRUE));
$custom_var_value = token_replace($custom_var_value, $types, array('clear' => TRUE));
// Suppress empty custom names and/or variables.
if (!drupal_strlen(trim($custom_var_name)) || !drupal_strlen(trim($custom_var_value))) {
continue;
}
// Custom variables names and values are limited to 200 characters in
// length. It is recommended to store values that are as small as
// possible to ensure that the Matomo Tracking request URL doesn't go
// over the URL limit for the webserver or browser.
$custom_var_name = rtrim(substr($custom_var_name, 0, 200));
$custom_var_value = rtrim(substr($custom_var_value, 0, 200));
$custom_var_name = drupal_json_encode($custom_var_name);
$custom_var_value = drupal_json_encode($custom_var_value);
$custom_var_scope = drupal_json_encode($custom_var_scope);
$custom_variable .= "_paq.push(['setCustomVariable', $i, $custom_var_name, $custom_var_value, $custom_var_scope]);";
}
}
// Add any custom code snippets if specified.
$codesnippet_before = variable_get('matomo_codesnippet_before', '');
$codesnippet_after = variable_get('matomo_codesnippet_after', '');
// Build tracker code. See https://matomo.org/docs/javascript-tracking/#toc-asynchronous-tracking
$script = 'var _paq = _paq || [];';
$script .= '(function(){';
$script .= 'var u=(("https:" == document.location.protocol) ? "' . check_url($url_https) . '" : "' . check_url($url_http) . '");';
$script .= '_paq.push(["setSiteId", ' . drupal_json_encode(variable_get('matomo_site_id', '')) . ']);';
$script .= '_paq.push(["setTrackerUrl", u+"piwik.php"]);';
// Track logged in users across all devices.
if (variable_get('matomo_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.
$script .= '_paq.push(["setUserId", ' . drupal_json_encode(matomo_user_id_hash($user->uid)) . ']);';
}
// Set custom url.
if (!empty($set_custom_url)) {
$script .= '_paq.push(["setCustomUrl", ' . $set_custom_url . ']);';
}
// Set custom document title.
if (!empty($set_document_title)) {
$script .= '_paq.push(["setDocumentTitle", ' . $set_document_title . ']);';
}
// Custom file download extensions.
if ((variable_get('matomo_track', 1)) && !(variable_get('matomo_trackfiles_extensions', MATOMO_TRACKFILES_EXTENSIONS) == MATOMO_TRACKFILES_EXTENSIONS)) {
$script .= '_paq.push(["setDownloadExtensions", ' . drupal_json_encode(variable_get('matomo_trackfiles_extensions', MATOMO_TRACKFILES_EXTENSIONS)) . ']);';
}
// Disable tracking for visitors who have opted out from tracking via DNT (Do-Not-Track) header.
if (variable_get('matomo_privacy_donottrack', 1)) {
$script .= '_paq.push(["setDoNotTrack", 1]);';
}
// Domain tracking type.
global $cookie_domain;
$domain_mode = variable_get('matomo_domain_mode', 0);
// 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))) {
$script .= '_paq.push(["setCookieDomain", ' . drupal_json_encode($cookie_domain) . ']);';
}
// Ordering $custom_variable before $codesnippet_before allows users to add
// custom code snippets that may use deleteCustomVariable() and/or getCustomVariable().
if (!empty($custom_variable)) {
$script .= $custom_variable;
}
if (!empty($codesnippet_before)) {
$script .= $codesnippet_before;
}
// Site search tracking support.
// NOTE: It's recommended not to call trackPageView() on the Site Search Result page.
if (module_exists('search') && variable_get('matomo_site_search', FALSE) && arg(0) == 'search' && $keys = matomo_search_get_keys()) {
// Parameters:
// 1. Search keyword searched for. Example: "Banana"
// 2. Search category selected in your search engine. If you do not need
// this, set to false. Example: "Organic Food"
// 3. Number of results on the Search results page. Zero indicates a
// 'No Result Search Keyword'. Set to false if you don't know.
//
// 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.
$script .= '_paq.push(["trackSiteSearch", ' . drupal_json_encode($keys) . ', false, (window.matomo_search_results) ? window.matomo_search_results : 0]);';
}
else {
$script .= '_paq.push(["trackPageView"]);';
}
// Add link tracking.
if (variable_get('matomo_track', 1)) {
// Disable tracking of links with ".no-tracking" and ".colorbox" classes.
$ignore_classes = array(
'no-tracking',
'colorbox',
);
// Disable the download & outlink tracking for specific CSS classes.
// Custom code snippets with 'setIgnoreClasses' will override the value.
// https://developer.matomo.org/api-reference/tracking-javascript#disable-the-download-amp-outlink-tracking-for-specific-css-classes
$script .= '_paq.push(["setIgnoreClasses", ' . drupal_json_encode($ignore_classes) . ']);';
// Enable download & outlink link tracking.
$script .= '_paq.push(["enableLinkTracking"]);';
}
if (!empty($message_events)) {
$script .= $message_events;
}
if (!empty($codesnippet_after)) {
$script .= $codesnippet_after;
}
$script .= 'var d=document,';
$script .= 'g=d.createElement("script"),';
$script .= 's=d.getElementsByTagName("script")[0];';
$script .= 'g.type="text/javascript";';
$script .= 'g.defer=true;';
$script .= 'g.async=true;';
// Should a local cached copy of the tracking code be used?
if (variable_get('matomo_cache', 0) && $url = _matomo_cache($url_http . 'piwik.js')) {
// 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 = '?' . variable_get('css_js_query_string', '0');
$script .= 'g.src="' . $url . $query_string . '";';
}
else {
$script .= 'g.src=u+"piwik.js";';
}
$script .= 's.parentNode.insertBefore(g,s);';
$script .= '})();';
// Add tracker code to scope.
drupal_add_js($script, array('scope' => $scope, 'type' => 'inline'));
}
}
/**
* 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 matomo_user_id_hash($uid) {
return drupal_hmac_base64($uid, drupal_get_private_key() . drupal_get_hash_salt());
}
/**
* Implements hook_field_extra_fields().
*/
function matomo_field_extra_fields() {
$extra['user']['user']['form']['matomo'] = array(
'label' => t('Matomo configuration'),
'description' => t('Matomo module form element.'),
'weight' => 3,
);
return $extra;
}
/**
* Implement hook_form_FORM_ID_alter().
*
* Allow users to decide if tracking code will be added to pages or not.
*/
function matomo_form_user_profile_form_alter(&$form, &$form_state) {
$account = $form['#user'];
$category = $form['#user_category'];
if ($category == 'account' && user_access('opt-in or out of matomo tracking') && ($custom = variable_get('matomo_custom', 1)) != 0 && _matomo_visibility_roles($account)) {
$form['matomo'] = array(
'#type' => 'fieldset',
'#title' => t('Matomo configuration'),
'#weight' => 3,
'#collapsible' => TRUE,
'#tree' => TRUE
);
switch ($custom) {
case 1:
$description = t('Users are tracked by default, but you are able to opt out.');
break;
case 2:
$description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
break;
}
// Migrate old piwik settings to matomo.
if (isset($account->data['piwik']['custom'])) {
$account->data['matomo']['custom'] = $account->data['piwik']['custom'];
}
$form['matomo']['custom'] = array(
'#type' => 'checkbox',
'#title' => t('Enable user tracking'),
'#description' => $description,
'#default_value' => isset($account->data['matomo']['custom']) ? $account->data['matomo']['custom'] : ($custom == 1),
);
return $form;
}
}
/**
* Implements hook_user_presave().
*/
function matomo_user_presave(&$edit, $account, $category) {
if (isset($edit['matomo']['custom'])) {
$edit['data']['matomo']['custom'] = $edit['matomo']['custom'];
}
// Remove old piwik setting to complete migration to matomo.
if (isset($edit['data']['piwik'])) {
unset($edit['data']['piwik']);
}
}
/**
* Implements hook_cron().
*/
function matomo_cron() {
// Regenerate the piwik.js every day.
if (REQUEST_TIME - variable_get('matomo_last_cache', 0) >= 86400 && variable_get('matomo_cache', 0)) {
_matomo_cache(variable_get('matomo_url_http', '') . 'piwik.js', TRUE);
variable_set('matomo_last_cache', REQUEST_TIME);
}
}
/**
* Implements hook_preprocess_search_results().
*
* Collects and adds the number of search results to the head.
*/
function matomo_preprocess_search_results(&$variables) {
// There is no search result $variable available that hold the number of items
// found. But the pager item mumber can tell the number of search results.
global $pager_total_items;
drupal_add_js('window.matomo_search_results = ' . intval($pager_total_items[0]) . ';', array('type' => 'inline', 'group' => JS_LIBRARY-1));
}
/**
* Download/Synchronize/Cache tracking code file locally.
*
* @param $location
* The full URL to the external javascript file.
* @param $sync_cached_file
* Synchronize tracking code and update if remote file have changed.
* @return mixed
* The path to the local javascript file on success, boolean FALSE on failure.
*/
function _matomo_cache($location, $sync_cached_file = FALSE) {
$path = 'public://matomo';
$file_destination = $path . '/' . basename($location);
if (!file_exists($file_destination) || $sync_cached_file) {
// Download the latest tracking code.
$result = drupal_http_request($location);
if ($result->code == 200) {
if (file_exists($file_destination)) {
// Synchronize tracking code and and replace local file if outdated.
$data_hash_local = drupal_hash_base64(file_get_contents($file_destination));
$data_hash_remote = drupal_hash_base64($result->data);
// Check that the files directory is writable.
if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
// Save updated tracking code file to disk.
file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
// Based on Drupal Core drupal_build_css_cache().
if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
file_unmanaged_save_data(gzencode($result->data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE);
}
watchdog('matomo', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO);
// Change query-strings on css/js files to enforce reload for all users.
_drupal_flush_css_js();
}
}
else {
// Check that the files directory is writable.
if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
// There is no need to flush JS here as core refreshes JS caches
// automatically, if new files are added.
file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
file_unmanaged_save_data(gzencode($result->data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE);
}
watchdog('matomo', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);
// Return the local JS file path.
return file_create_url($file_destination);
}
}
}
}
else {
// Return the local JS file path.
return file_create_url($file_destination);
}
}
/**
* Delete cached files and directory.
*/
function matomo_clear_js_cache() {
$path = 'public://matomo';
if (file_prepare_directory($path)) {
file_scan_directory($path, '/.*/', array('callback' => 'file_unmanaged_delete'));
drupal_rmdir($path);
// Change query-strings on css/js files to enforce reload for all users.
_drupal_flush_css_js();
watchdog('matomo', 'Local cache has been purged.', array(), WATCHDOG_INFO);
}
}
/**
* Helper function for grabbing search keys. Function is missing in D7.
*
* https://api.drupal.org/api/function/search_get_keys/6
*/
function matomo_search_get_keys() {
static $return;
if (!isset($return)) {
// Extract keys as remainder of path
// Note: support old GET format of searches for existing links.
$path = explode('/', $_GET['q'], 3);
$keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
$return = count($path) == 3 ? $path[2] : $keys;
}
return $return;
}
/**
* Tracking visibility check for an user object.
*
* @param $account
* A user object containing an array of roles to check.
* @return boolean
* A decision on if the current user is being tracked by Matomo.
*/
function _matomo_visibility_user($account) {
$enabled = FALSE;
// Is current user a member of a role that should be tracked?
if (_matomo_visibility_roles($account)) {
// Use the user's block visibility setting, if necessary.
if (($custom = variable_get('matomo_custom', 1)) != 0) {
if ($account->uid && isset($account->data['matomo']['custom'])) {
$enabled = $account->data['matomo']['custom'];
}
else {
$enabled = ($custom == 1);
}
}
else {
$enabled = TRUE;
}
}
return $enabled;
}
/**
* Based on visibility setting this function returns TRUE if GA code should
* be added for the current role and otherwise FALSE.
*/
function _matomo_visibility_roles($account) {
$visibility = variable_get('matomo_visibility_roles', 0);
$enabled = $visibility;
$roles = variable_get('matomo_roles', array());
if (array_sum($roles) > 0) {
// One or more roles are selected.
foreach (array_keys($account->roles) as $rid) {
// Is the current user a member of one of these roles?
if (isset($roles[$rid]) && $rid == $roles[$rid]) {
// Current user is a member of a role that should be tracked/excluded from tracking.
$enabled = !$visibility;
break;
}
}
}
else {
// No role is selected for tracking, therefore all roles should be tracked.
$enabled = TRUE;
}
return $enabled;
}
/**
* Based on visibility setting this function returns TRUE if GA code should
* be added to the current page and otherwise FALSE.
*/
function _matomo_visibility_pages() {
static $page_match;
// Cache visibility setting in hook_init for hook_footer.
if (!isset($page_match)) {
$visibility = variable_get('matomo_visibility_pages', 0);
$setting_pages = variable_get('matomo_pages', MATOMO_PAGES);
// Match path if necessary.
if (!empty($setting_pages)) {
// Convert path to lowercase. This allows comparison of the same path
// with different case. Ex: /Page, /page, /PAGE.
$pages = drupal_strtolower($setting_pages);
if ($visibility < 2) {
// Convert the Drupal path to lowercase
$path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
// Compare the lowercase internal and lowercase path alias (if any).
$page_match = drupal_match_path($path, $pages);
if ($path != $_GET['q']) {
$page_match = $page_match || drupal_match_path($_GET['q'], $pages);
}
// When $visibility has a value of 0, the tracking code is displayed on
// all pages except those listed in $pages. When set to 1, it
// is displayed only on those pages listed in $pages.
$page_match = !($visibility xor $page_match);
}
elseif (module_exists('php')) {
$page_match = php_eval($setting_pages);
}
else {
$page_match = FALSE;
}
}
else {
$page_match = TRUE;
}
}
return $page_match;
}
/**
* Get the page titles trail for the current page.
*
* Based on menu_get_active_breadcrumb().
*
* @return array
* All page titles, including current page.
*/
function _matomo_get_hierarchy_titles() {
$titles = array();
// No breadcrumb for the front page.
if (drupal_is_front_page()) {
return $titles;
}
$item = menu_get_item();
if (!empty($item['access'])) {
$active_trail = menu_get_active_trail();
// Allow modules to alter the breadcrumb, if possible, as that is much
// faster than rebuilding an entirely new active trail.
drupal_alter('menu_breadcrumb', $active_trail, $item);
// Remove the tab root (parent) if the current path links to its parent.
// Normally, the tab root link is included in the breadcrumb, as soon as we
// are on a local task or any other child link. However, if we are on a
// default local task (e.g., node/%/view), then we do not want the tab root
// link (e.g., node/%) to appear, as it would be identical to the current
// page. Since this behavior also needs to work recursively (i.e., on
// default local tasks of default local tasks), and since the last non-task
// link in the trail is used as page title (see menu_get_active_title()),
// this condition cannot be cleanly integrated into menu_get_active_trail().
// menu_get_active_trail() already skips all links that link to their parent
// (commonly MENU_DEFAULT_LOCAL_TASK). In order to also hide the parent link
// itself, we always remove the last link in the trail, if the current
// router item links to its parent.
if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
array_pop($active_trail);
}
foreach ($active_trail as $parent) {
$titles[] = $parent['title'];
}
}
return $titles;
}

View File

@ -0,0 +1,586 @@
<?php
/**
* @file
* Test file for Matomo module.
*/
class MatomoBasicTest extends DrupalWebTestCase {
/**
* User without permissions to edit snippets.
*
* @var \StdClass
*/
protected $noSnippetUser;
public static function getInfo() {
return array(
'name' => t('Matomo basic tests'),
'description' => t('Test basic functionality of Matomo module.'),
'group' => 'Matomo',
);
}
function setUp() {
parent::setUp('matomo');
$permissions = array(
'access administration pages',
'administer matomo',
);
// User to set up matomo.
$this->noSnippetUser = $this->drupalCreateUser($permissions);
$permissions[] = 'add js snippets for matomo';
$this->admin_user = $this->drupalCreateUser($permissions);
$this->drupalLogin($this->admin_user);
}
function testMatomoConfiguration() {
// Check for setting page's presence.
$this->drupalGet('admin/config/system/matomo');
$this->assertRaw(t('Matomo site ID'), '[testMatomoConfiguration]: Settings page displayed.');
// Check for account code validation.
$edit['matomo_site_id'] = $this->randomName(2);
$this->drupalPost('admin/config/system/matomo', $edit, 'Save configuration');
$this->assertRaw(t('A valid Matomo site ID is an integer only.'), '[testMatomoConfiguration]: Invalid Matomo site ID number validated.');
// User should have access to code snippets.
$this->assertFieldByName('matomo_codesnippet_before');
$this->assertFieldByName('matomo_codesnippet_after');
$this->assertNoFieldByXPath("//textarea[@name='matomo_codesnippet_before' and @disabled='disabled']", NULL, '"Code snippet (before)" is enabled.');
$this->assertNoFieldByXPath("//textarea[@name='matomo_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/matomo');
// User should *not* have access to snippets, but create fields.
$this->assertFieldByName('matomo_codesnippet_before');
$this->assertFieldByName('matomo_codesnippet_after');
$this->assertFieldByXPath("//textarea[@name='matomo_codesnippet_before' and @disabled='disabled']", NULL, '"Code snippet (before)" is disabled.');
$this->assertFieldByXPath("//textarea[@name='matomo_codesnippet_after' and @disabled='disabled']", NULL, '"Code snippet (after)" is disabled.');
}
function testMatomoPageVisibility() {
$ua_code = '1';
variable_set('matomo_site_id', $ua_code);
variable_get('matomo_url_http', 'http://example.com/matomo/');
variable_get('matomo_url_https', 'https://example.com/matomo/');
// Show tracking on "every page except the listed pages".
variable_set('matomo_visibility_pages', 0);
// Disable tracking one "admin*" pages only.
variable_set('matomo_pages', "admin\nadmin/*");
// Enable tracking only for authenticated users only.
variable_set('matomo_roles', array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID));
// Check tracking code visibility.
$this->drupalGet('');
$this->assertRaw('/matomo/matomo.js', '[testMatomoPageVisibility]: Custom tracking script is is displayed for authenticated users.');
$this->assertRaw('u+"piwik.php"', '[testMatomoPageVisibility]: Tracking code is displayed for authenticated users.');
// Test whether tracking code is not included on pages to omit.
$this->drupalGet('admin');
$this->assertNoRaw('u+"piwik.php"', '[testMatomoPageVisibility]: Tracking code is not displayed on admin page.');
$this->drupalGet('admin/config/system/matomo');
// Checking for tracking code URI here, as $ua_code is displayed in the form.
$this->assertNoRaw('u+"piwik.php"', '[testMatomoPageVisibility]: Tracking code is not displayed on admin subpage.');
// Test whether tracking code display is properly flipped.
variable_set('matomo_visibility_pages', 1);
$this->drupalGet('admin');
$this->assertRaw('u+"piwik.php"', '[testMatomoPageVisibility]: Tracking code is displayed on admin page.');
$this->drupalGet('admin/config/system/matomo');
// Checking for tracking code URI here, as $ua_code is displayed in the form.
$this->assertRaw('u+"piwik.php"', '[testMatomoPageVisibility]: Tracking code is displayed on admin subpage.');
$this->drupalGet('');
$this->assertNoRaw('u+"piwik.php"', '[testMatomoPageVisibility]: Tracking code is NOT displayed on front page.');
// Test whether tracking code is not display for anonymous.
$this->drupalLogout();
$this->drupalGet('');
$this->assertNoRaw('u+"piwik.php"', '[testMatomoPageVisibility]: Tracking code is NOT displayed for anonymous.');
// Switch back to every page except the listed pages.
variable_set('matomo_visibility_pages', 0);
// Enable tracking code for all user roles.
variable_set('matomo_roles', array());
// Test whether 403 forbidden tracking code is shown if user has no access.
$this->drupalGet('admin');
$this->assertRaw('403/URL = "', '[testMatomoPageVisibility]: 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/URL = "', '[testMatomoPageVisibility]: 404 Not Found tracking code shown on non-existent page.');
}
function testMatomoTrackingCode() {
$ua_code = '2';
variable_set('matomo_site_id', $ua_code);
variable_get('matomo_url_http', 'http://example.com/matomo/');
variable_get('matomo_url_https', 'https://example.com/matomo/');
// Show tracking code on every page except the listed pages.
variable_set('matomo_visibility_pages', 0);
// Enable tracking code for all user roles.
variable_set('matomo_roles', array());
/* Sample JS code as added to page:
<script type="text/javascript">
var _paq = _paq || [];
(function(){
var u=(("https:" == document.location.protocol) ? "https://{$MATOMO_URL}" : "http://{$MATOMO_URL}");
_paq.push(['setSiteId', {$IDSITE}]);
_paq.push(['setTrackerUrl', u+'piwik.php']);
_paq.push(['trackPageView']);
var d=document,
g=d.createElement('script'),
s=d.getElementsByTagName('script')[0];
g.type='text/javascript';
g.defer=true;
g.async=true;
g.src=u+'matomo.js';
s.parentNode.insertBefore(g,s);
})();
</script>
*/
// Test whether tracking code uses latest JS.
variable_set('matomo_cache', 0);
$this->drupalGet('');
$this->assertRaw('u+"piwik.php"', '[testMatomoTrackingCode]: Latest tracking code used.');
// Test if tracking of User ID is enabled.
variable_set('matomo_trackuserid', 1);
$this->drupalGet('');
$this->assertRaw('_paq.push(["setUserId", ', '[testMatomoTrackingCode]: Tracking code for User ID is enabled.');
// Test if tracking of User ID is disabled.
variable_set('matomo_trackuserid', 0);
$this->drupalGet('');
$this->assertNoRaw('_paq.push(["setUserId", ', '[testMatomoTrackingCode]: Tracking code for User ID is disabled.');
// Test whether single domain tracking is active.
$this->drupalGet('');
$this->assertNoRaw('_paq.push(["setCookieDomain"', '[testMatomoTrackingCode]: Single domain tracking is active.');
// Enable "One domain with multiple subdomains".
variable_set('matomo_domain_mode', 1);
$this->drupalGet('');
// Test may run on localhost, an ipaddress or real domain name.
// TODO: Workaround to run tests successfully. This feature cannot tested reliable.
global $cookie_domain;
if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
$this->assertRaw('_paq.push(["setCookieDomain"', '[testMatomoTrackingCode]: One domain with multiple subdomains is active on real host.');
}
else {
// Special cases, Localhost and IP addresses don't show 'setCookieDomain'.
$this->assertNoRaw('_paq.push(["setCookieDomain"', '[testMatomoTrackingCode]: One domain with multiple subdomains may be active on localhost (test result is not reliable).');
}
// Test whether the BEFORE and AFTER code is added to the tracker.
variable_set('matomo_codesnippet_before', '_paq.push(["setLinkTrackingTimer", 250]);');
variable_set('matomo_codesnippet_after', '_paq.push(["t2.setSiteId", 2]);_gaq.push(["t2.trackPageView"]);');
$this->drupalGet('');
$this->assertRaw('setLinkTrackingTimer', '[testMatomoTrackingCode]: Before codesnippet has been found with "setLinkTrackingTimer" set.');
$this->assertRaw('t2.trackPageView', '[testMatomoTrackingCode]: After codesnippet with "t2" tracker has been found.');
}
}
class MatomoCustomVariablesTest extends DrupalWebTestCase {
public static function getInfo() {
return array(
'name' => t('Matomo Custom Variables tests'),
'description' => t('Test custom variables functionality of Matomo module.'),
'group' => 'Matomo',
'dependencies' => array('token'),
);
}
function setUp() {
parent::setUp('matomo', 'token');
$permissions = array(
'access administration pages',
'administer matomo',
);
// User to set up matomo.
$this->admin_user = $this->drupalCreateUser($permissions);
}
function testMatomoCustomVariables() {
$ua_code = '3';
variable_set('matomo_site_id', $ua_code);
// Basic test if the feature works.
$custom_vars = array(
'slots' => array(
1 => array(
'slot' => 1,
'name' => 'Foo 1',
'value' => 'Bar 1',
'scope' => 3,
),
2 => array(
'slot' => 2,
'name' => 'Foo 2',
'value' => 'Bar 2',
'scope' => 2,
),
3 => array(
'slot' => 3,
'name' => 'Foo 3',
'value' => 'Bar 3',
'scope' => 3,
),
4 => array(
'slot' => 4,
'name' => 'Foo 4',
'value' => 'Bar 4',
'scope' => 2,
),
5 => array(
'slot' => 5,
'name' => 'Foo 5',
'value' => 'Bar 5',
'scope' => 1,
),
)
);
variable_set('matomo_custom_var', $custom_vars);
$this->drupalGet('');
foreach ($custom_vars['slots'] as $slot) {
$this->assertRaw("_paq.push(['setCustomVariable', " . $slot['slot'] . ", \"" . $slot['name'] . "\", \"" . $slot['value'] . "\", " . $slot['scope'] . "]);", '[testMatomoCustomVariables]: setCustomVariable ' . $slot['slot'] . ' is shown.');
}
// Test whether tokens are replaced in custom variable names.
$site_slogan = $this->randomName(16);
variable_set('site_slogan', $site_slogan);
$custom_vars = array(
'slots' => array(
1 => array(
'slot' => 1,
'name' => 'Name: [site:slogan]',
'value' => 'Value: [site:slogan]',
'scope' => 3,
),
2 => array(
'slot' => 2,
'name' => '',
'value' => $this->randomName(16),
'scope' => 1,
),
3 => array(
'slot' => 3,
'name' => $this->randomName(16),
'value' => '',
'scope' => 2,
),
4 => array(
'slot' => 4,
'name' => '',
'value' => '',
'scope' => 3,
),
5 => array(
'slot' => 5,
'name' => '',
'value' => '',
'scope' => 3,
),
)
);
variable_set('matomo_custom_var', $custom_vars);
$this->verbose('<pre>' . print_r($custom_vars, TRUE) . '</pre>');
$this->drupalGet('');
$this->assertRaw("_paq.push(['setCustomVariable', 1, \"Name: $site_slogan\", \"Value: $site_slogan\", 3]", '[testMatomoCustomVariables]: Tokens have been replaced in custom variable.');
$this->assertNoRaw("_paq.push(['setCustomVariable', 2,", '[testMatomoCustomVariables]: Value with empty name is not shown.');
$this->assertNoRaw("_paq.push(['setCustomVariable', 3,", '[testMatomoCustomVariables]: Name with empty value is not shown.');
$this->assertNoRaw("_paq.push(['setCustomVariable', 4,", '[testMatomoCustomVariables]: Empty name and value is not shown.');
$this->assertNoRaw("_paq.push(['setCustomVariable', 5,", '[testMatomoCustomVariables]: Empty name and value is not shown.');
}
}
/**
* Test custom url functionality of Matomo module.
*/
class MatomoCustomUrls extends DrupalWebTestCase {
public static function getInfo() {
return array(
'name' => 'Matomo custom url tests',
'description' => 'Test custom url functionality of Matomo module.',
'group' => 'Matomo',
);
}
function setUp() {
parent::setUp('matomo');
$permissions = array(
'access administration pages',
'administer matomo',
);
// User to set up matomo.
$this->admin_user = $this->drupalCreateUser($permissions);
}
/**
* Tests if user password page urls are overridden.
*/
public function testMatomoUserPasswordPage() {
$base_path = base_path();
$ua_code = '1';
variable_set('matomo_site_id', $ua_code);
variable_get('matomo_url_http', 'http://example.com/matomo/');
variable_get('matomo_url_https', 'https://example.com/matomo/');
$this->drupalGet('user/password', array('query' => array('name' => 'foo')));
$this->assertRaw('_paq.push(["setCustomUrl", ' . drupal_json_encode(url('user/password')) . ']);');
$this->drupalGet('user/password', array('query' => array('name' => 'foo@example.com')));
$this->assertRaw('_paq.push(["setCustomUrl", ' . drupal_json_encode(url('user/password')) . ']);');
$this->drupalGet('user/password');
$this->assertNoRaw('_paq.push(["setCustomUrl", "', '[testMatomoCustomUrls]: Custom url not set.');
}
}
class MatomoStatusMessagesTest extends DrupalWebTestCase {
public static function getInfo() {
return array(
'name' => 'Matomo status messages tests',
'description' => 'Test status messages functionality of Matomo module.',
'group' => 'Matomo',
);
}
function setUp() {
parent::setUp('matomo');
$permissions = array(
'access administration pages',
'administer matomo',
);
// User to set up matomo.
$this->admin_user = $this->drupalCreateUser($permissions);
}
function testMatomoStatusMessages() {
$ua_code = '1';
variable_set('matomo_site_id', $ua_code);
// Enable logging of errors only.
variable_set('matomo_trackmessages', array('error' => 'error'));
$this->drupalPost('user/login', array(), t('Log in'));
$this->assertRaw('_paq.push(["trackEvent", "Messages", "Error message", "Username field is required."]);', '[testMatomoStatusMessages]: trackEvent "Username field is required." is shown.');
$this->assertRaw('_paq.push(["trackEvent", "Messages", "Error message", "Password field is required."]);', '[testMatomoStatusMessages]: trackEvent "Password field is required." is shown.');
// @todo: investigate why drupal_set_message() fails.
//drupal_set_message('Example status message.', 'status');
//drupal_set_message('Example warning message.', 'warning');
//drupal_set_message('Example error message.', 'error');
//drupal_set_message('Example error <em>message</em> with html tags and <a href="https://example.com/">link</a>.', 'error');
//$this->drupalGet('');
//$this->assertNoRaw('_paq.push(["trackEvent", "Messages", "Status message", "Example status message."]);', '[testMatomoStatusMessages]: Example status message is not enabled for tracking.');
//$this->assertNoRaw('_paq.push(["trackEvent", "Messages", "Warning message", "Example warning message."]);', '[testMatomoStatusMessages]: Example warning message is not enabled for tracking.');
//$this->assertRaw('_paq.push(["trackEvent", "Messages", "Error message", "Example error message."]);', '[testMatomoStatusMessages]: Example error message is shown.');
//$this->assertRaw('_paq.push(["trackEvent", "Messages", "Error message", "Example error message with html tags and link."]);', '[testMatomoStatusMessages]: HTML has been stripped successful from Example error message with html tags and link.');
}
}
class MatomoRolesTest extends DrupalWebTestCase {
public static function getInfo() {
return array(
'name' => t('Matomo role tests'),
'description' => t('Test roles functionality of Matomo module.'),
'group' => 'Matomo',
);
}
function setUp() {
parent::setUp('matomo');
$permissions = array(
'access administration pages',
'administer matomo',
);
// User to set up matomo.
$this->admin_user = $this->drupalCreateUser($permissions);
}
function testMatomoRolesTracking() {
$ua_code = '1';
variable_set('matomo_site_id', $ua_code);
variable_get('matomo_url_http', 'http://example.com/matomo/');
variable_get('matomo_url_https', 'https://example.com/matomo/');
// Test if the default settings are working as expected.
// Add to the selected roles only.
variable_set('matomo_visibility_roles', 0);
// Enable tracking for all users.
variable_set('matomo_roles', array());
// Check tracking code visibility.
$this->drupalGet('');
$this->assertRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is displayed for anonymous users on frontpage with default settings.');
$this->drupalGet('admin');
$this->assertRaw('"403/URL = "', '[testMatomoRoleVisibility]: 403 Forbidden tracking code is displayed for anonymous users in admin section with default settings.');
$this->drupalLogin($this->admin_user);
$this->drupalGet('');
$this->assertRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is displayed for authenticated users on frontpage with default settings.');
$this->drupalGet('admin');
$this->assertNoRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is NOT displayed for authenticated users in admin section with default settings.');
// Test if the non-default settings are working as expected.
// Enable tracking only for authenticated users.
variable_set('matomo_roles', array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID));
$this->drupalGet('');
$this->assertRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is displayed for authenticated users only on frontpage.');
$this->drupalLogout();
$this->drupalGet('');
$this->assertNoRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is NOT displayed for anonymous users on frontpage.');
// Add to every role except the selected ones.
variable_set('matomo_visibility_roles', 1);
// Enable tracking for all users.
variable_set('matomo_roles', array());
// Check tracking code visibility.
$this->drupalGet('');
$this->assertRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is added to every role and displayed for anonymous users.');
$this->drupalGet('admin');
$this->assertRaw('"403/URL = "', '[testMatomoRoleVisibility]: 403 Forbidden tracking code is shown for anonymous users if every role except the selected ones is selected.');
$this->drupalLogin($this->admin_user);
$this->drupalGet('');
$this->assertRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is added to every role and displayed on frontpage for authenticated users.');
$this->drupalGet('admin');
$this->assertNoRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is added to every role and NOT displayed in admin section for authenticated users.');
// Disable tracking for authenticated users.
variable_set('matomo_roles', array(DRUPAL_AUTHENTICATED_RID => DRUPAL_AUTHENTICATED_RID));
$this->drupalGet('');
$this->assertNoRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is NOT displayed on frontpage for excluded authenticated users.');
$this->drupalGet('admin');
$this->assertNoRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is NOT displayed in admin section for excluded authenticated users.');
$this->drupalLogout();
$this->drupalGet('');
$this->assertRaw('u+"piwik.php"', '[testMatomoRoleVisibility]: Tracking code is displayed on frontpage for included anonymous users.');
}
}
class MatomoPhpFilterTest extends DrupalWebTestCase {
public static function getInfo() {
return array(
'name' => 'Matomo php filter tests',
'description' => 'Test php filter functionality of Matomo module.',
'group' => 'Matomo',
);
}
function setUp() {
parent::setUp('matomo', 'php');
// Administrator with all permissions.
$permissions_admin_user = array(
'access administration pages',
'administer matomo',
'use php for matomo tracking visibility',
);
$this->admin_user = $this->drupalCreateUser($permissions_admin_user);
// Administrator who cannot configure tracking visibility with PHP.
$permissions_delegated_admin_user = array(
'access administration pages',
'administer matomo',
);
$this->delegated_admin_user = $this->drupalCreateUser($permissions_delegated_admin_user);
}
function testMatomoPhpFilter() {
$ua_code = '1';
$this->drupalLogin($this->admin_user);
$edit = array();
$edit['matomo_site_id'] = $ua_code;
$edit['matomo_url_http'] = 'http://example.com/matomo/';
$edit['matomo_url_https'] = 'https://example.com/matomo/';
$edit['matomo_url_skiperror'] = TRUE; // Required for testing only.
$edit['matomo_visibility_pages'] = 2;
$edit['matomo_pages'] = '<?php return 0; ?>';
$this->drupalPost('admin/config/system/matomo', $edit, t('Save configuration'));
// Compare saved setting with posted setting.
$matomo_pages = variable_get('matomo_pages', $this->randomName(8));
$this->assertEqual('<?php return 0; ?>', $matomo_pages, '[testMatomoPhpFilter]: PHP code snippet is intact.');
// Check tracking code visibility.
variable_set('matomo_pages', '<?php return TRUE; ?>');
$this->drupalGet('');
$this->assertRaw('u+"piwik.php"', '[testMatomoPhpFilter]: Tracking is displayed on frontpage page.');
$this->drupalGet('admin');
$this->assertRaw('u+"piwik.php"', '[testMatomoPhpFilter]: Tracking is displayed on admin page.');
variable_set('matomo_pages', '<?php return FALSE; ?>');
$this->drupalGet('');
$this->assertNoRaw('u+"piwik.php"', '[testMatomoPhpFilter]: Tracking is not displayed on frontpage page.');
// Test administration form.
variable_set('matomo_pages', '<?php return TRUE; ?>');
$this->drupalGet('admin/config/system/matomo');
$this->assertRaw(t('Pages on which this PHP code returns <code>TRUE</code> (experts only)'), '[testMatomoPhpFilter]: Permission to administer PHP for tracking visibility.');
$this->assertRaw(check_plain('<?php return TRUE; ?>'), '[testMatomoPhpFilter]: PHP code snippted is displayed.');
// Login the delegated user and check if fields are visible.
$this->drupalLogin($this->delegated_admin_user);
$this->drupalGet('admin/config/system/matomo');
$this->assertNoRaw(t('Pages on which this PHP code returns <code>TRUE</code> (experts only)'), '[testMatomoPhpFilter]: No permission to administer PHP for tracking visibility.');
$this->assertNoRaw(check_plain('<?php return TRUE; ?>'), '[testMatomoPhpFilter]: No permission to view PHP code snippted.');
// Set a different value and verify that this is still the same after the post.
variable_set('matomo_pages', '<?php return 0; ?>');
$edit = array();
$edit['matomo_site_id'] = $ua_code;
$edit['matomo_url_http'] = 'http://example.com/matomo/';
$edit['matomo_url_https'] = 'https://example.com/matomo/';
$edit['matomo_url_skiperror'] = TRUE; // Required for testing only.
$this->drupalPost('admin/config/system/matomo', $edit, t('Save configuration'));
// Compare saved setting with posted setting.
$matomo_visibility_pages = variable_get('matomo_visibility_pages', 0);
$matomo_pages = variable_get('matomo_pages', $this->randomName(8));
$this->assertEqual(2, $matomo_visibility_pages, '[testMatomoPhpFilter]: Pages on which this PHP code returns TRUE is selected.');
$this->assertEqual('<?php return 0; ?>', $matomo_pages, '[testMatomoPhpFilter]: PHP code snippet is intact.');
}
}

View File

@ -0,0 +1,55 @@
<?php
/**
* @file
* Builds placeholder replacement tokens for user-related data.
*/
/**
* Implements hook_token_info().
*/
function matomo_token_info() {
$user['matomo-role-names'] = array(
'name' => t('User role names'),
'description' => t('The role names the user account is a member of as comma separated list.'),
'needs-data' => 'user',
);
$user['matomo-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 matomo_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 'matomo-role-names':
$names = implode(',', $account->roles);
$replacements[$original] = $sanitize ? check_plain($names) : $names;
break;
case 'matomo-role-ids':
$ids = implode(',', array_keys($account->roles));
$replacements[$original] = $sanitize ? check_plain($ids) : $ids;
break;
}
}
}
return $replacements;
}

View File

@ -0,0 +1,52 @@
<?php
/**
* @file
* Definition of variables for Variable API module.
*/
/**
* Implements hook_variable_info().
*/
function matomo_variable_info($options) {
$variables['matomo_site_id'] = array(
'type' => 'string',
'title' => t('Matomo site ID', array(), $options),
'default' => '',
'description' => t('The user account number is unique to the websites domain. Click the <strong>Settings</strong> link in your Matomo account, then the <strong>Websites</strong> tab and enter the appropriate site <strong>ID</strong> into this field.'),
'required' => TRUE,
'group' => 'matomo',
'localize' => TRUE,
'multidomain' => TRUE,
'validate callback' => 'matomo_validate_matomo_site_id',
);
return $variables;
}
/**
* Implements hook_variable_group_info().
*/
function matomo_variable_group_info() {
$groups['matomo'] = array(
'title' => t('Matomo'),
'description' => t('Configure tracking behavior to get insights into your website traffic and marketing effectiveness.'),
'access' => 'administer matomo',
'path' => array('admin/config/system/matomo'),
);
return $groups;
}
/**
* Validate Matomo site ID variable.
*
* @param array $variable
*
* @return string
*/
function matomo_validate_matomo_site_id($variable) {
if (!preg_match('/^\d{1,}$/', $variable['value'])) {
return t('A valid Matomo site ID is an integer only.');
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

View File

@ -740,49 +740,56 @@ body.front {
}
#logos-partenaires-home {
display: block;
width: 90px;
// height: 450px;
position: relative;
// width: 90px;
height: 80px;
text-indent: -999px;
overflow: hidden;
margin-top: -18px;
background: url(../img/logos/rect1729.png) no-repeat top center;
background-size: contain;
padding-top: 60px;
border: 1px solid #000;
&>a{
// margin-top: -18px;
// background: url(../img/logos/MIN_gouvernement_2020.png) no-repeat top center;
// background-size: contain;
// padding-top: 60px;
// border: 1px solid #000;
&>a, &>span{
display:block;
width:100%;
width:90px;
height:100%;
text-indent: -999px;
overflow: hidden;
margin: 0;
padding: 0;
background-size: contain;
background-repeat: no-repeat;
background-position: center;
background-color: white;
border-top: 1px solid #000;
background-position: top;
// background-color: white;
// border-top: 1px solid #000;
}
}
#logos-partenaires-home #ministere-eco {
height: 55px;
background-image: url(../img/logos/rect1926.png);
}
#logos-partenaires-home #ministere-territoires {
height: 80px;
background-image: url(../img/logos/logos_4ministres_2018_v2-territoires.png);
}
#logos-partenaires-home #ministere-culture {
height: 40px;
background-image: url(../img/logos/rect1930.png);
span#gouv{
background-image: url(../img/logos/MIN_gouvernement_2020.png);
float: left;
}
// #logos-partenaires-home #ministere-eco {
// height: 55px;
// background-image: url(../img/logos/rect1926.png);
// }
// #logos-partenaires-home #ministere-territoires {
// height: 80px;
// background-image: url(../img/logos/logos_4ministres_2018_v2-territoires.png);
// }
// #logos-partenaires-home #ministere-culture {
// height: 40px;
// background-image: url(../img/logos/rect1930.png);
// }
// #logos-partenaires-home #ministere-recherche {
// height: 75px;
// background-image: url(../img/logos/logo_recherche.png);
// }
#logos-partenaires-home #ministere-puca {
float: right;
height: 80px;
background-image: url(../img/logos/logos-partenaires_04.png);
}
@ -793,11 +800,35 @@ body.front {
.col-logo {
// margin-top: 20px;
margin-left: 50px;
// margin-left: 50px;
>.inside{
display: flex;
flex-direction: row;
align-items: flex-end;
>.panel-pane{
flex-basis: auto;
}
}
.panel-separator{ display: none;}
.pane-blockify-blockify-logo{
width:30%;
#logo{
padding-left:14px;
}
}
.home-logos-popsu{
width:70%;
.clearfix{
height: 100%;
display: flex;
flex-direction: row;
align-items: flex-end;
}
}
}
.col-intro {
width: 700px;
margin: -18px 0 0 134px;
margin: -15px 0 0 84px;
// background-color: #fff;
.panel-pane {
padding: 10px 15px;
@ -857,7 +888,7 @@ body.front {
}
.popsu-homepage .panels-flexible-row-popsu-homepage-2 {
padding: 2.5em 0 0 0;
padding: 4em 0 0 0;
}
}
@ -1027,19 +1058,19 @@ body.logged-in #content-tabs ul.tabs.primary {
grid-column: 3;
}
.views-field-title {
font-size: 18px;
line-height: 16px;
font-size: 16px;
line-height: 14px;
padding: 10px 10px 0 10px;
font-family: OpenSansSemiBold,verdana,arial,helvetica,sans-serif;
}
.views-field-field-popsu-actu-date {
font-size: 18px;
line-height: 19px;
font-size: 16px;
line-height: 14px;
padding: 2px 10px 0 10px;
}
.views-field-field-popsu-actu-body {
font-size: 13px;
line-height: 18px;
line-height: 14px;
padding: 0px 10px 10px 10px;
}
.views-field-field-popsu-actu-body a {
@ -1351,18 +1382,22 @@ body.logged-in #content-tabs ul.tabs.primary {
/* Mayence */
#point-nid-964.placement-carte {
margin-left: 370px;
margin-top: 290px;
margin-top: 295px;
.map-title {
padding-bottom: 20px;
// padding-left: 28px;
// padding-top: 1px;
}
}
/* Montpellier */
#point-nid-883.placement-carte {
margin-left: 232px; /* 117 */
margin-top: 580px; /* 94 */
margin-left: 185px; /* 117 */
margin-top: 610px; /* 94 */
.map-title {
background-position: top left;
background-position: top right;
padding-bottom: 10px;
padding-left: 28px;
padding-top: 1px;
padding-right: 0px;
padding-top: 25px;
}
}
/* Montréal */
@ -1382,8 +1417,14 @@ body.logged-in #content-tabs ul.tabs.primary {
}
/* Nantes */
#point-nid-868.placement-carte {
margin-left: 100px;
margin-top: 356px;
margin-left: 40px;
margin-top: 380px;
.map-title {
background-position: top right;
padding-bottom: 10px;
padding-right: 35px;
padding-top: 7px;
}
}
/* Nime */
#point-nid-965.placement-carte {
@ -1398,13 +1439,25 @@ body.logged-in #content-tabs ul.tabs.primary {
}
/* Orléans */
#point-nid-1120.placement-carte {
margin-left: 200px;
margin-top: 350px;
margin-left: 165px;
margin-top: 370px;
.map-title {
background-position: top right;
padding-bottom: 10px;
padding-right: 25px;
padding-top: 1px;
}
}
/* Paris */
#point-nid-885.placement-carte {
margin-left: 230px;
margin-top: 314px;
margin-left: 200px;
margin-top: 335px;
.map-title {
background-position: top right;
padding-bottom: 10px;
padding-right: 25px;
padding-top: 1px;
}
}
/* Rennes */
#point-nid-886.placement-carte {
@ -1473,8 +1526,14 @@ body.logged-in #content-tabs ul.tabs.primary {
}
/* Toulouse */
#point-nid-890.placement-carte {
margin-left: 139px;
margin-top: 531px;
margin-left: 90px;
margin-top: 550px;
.map-title {
background-position: center right;
padding-bottom: 7px;
padding-right: 30px;
padding-top: 7px;
}
}
/* Turin */
#point-nid-891.placement-carte {
@ -1488,8 +1547,14 @@ body.logged-in #content-tabs ul.tabs.primary {
}
/* Clermont-ferrand */
#point-nid-1094.placement-carte {
margin-left: 160px;
margin-top: 430px;
margin-left: 80px;
margin-top: 450px;
.map-title {
background-position: top right;
padding-bottom: 10px;
padding-right: 25px;
padding-top: 1px;
}
}
/* Rouen */
#point-nid-1099.placement-carte {
@ -1498,8 +1563,14 @@ body.logged-in #content-tabs ul.tabs.primary {
}
/* Nice */
#point-nid-1098.placement-carte {
margin-left: 368px;
margin-top: 575px;
margin-left: 370px;
margin-top: 595px;
.map-title {
background-position: top left;
padding-bottom: 10px;
padding-left: 25px;
padding-top: 1px;
}
}
/* Metz */
#point-nid-1097.placement-carte {
@ -1513,8 +1584,14 @@ body.logged-in #content-tabs ul.tabs.primary {
}
/* Brest */
#point-nid-1093.placement-carte {
margin-left: 32px;
margin-top: 286px;
margin-left: -10px;
margin-top: 310px;
.map-title {
background-position: top right;
padding-bottom: 10px;
padding-right: 25px;
padding-top: 1px;
}
}
/* Nancy */
#point-nid-1102.placement-carte {
@ -1563,7 +1640,7 @@ body.logged-in #content-tabs ul.tabs.primary {
/* Isle-sur-la-Sorgue */
#point-nid-1145.placement-carte {
margin-left: 270px; /* 117 */
margin-top: 562px; /* 94 */
margin-top: 560px; /* 94 */
.map-title {
background-position: top left;
padding-bottom: 10px;
@ -1593,8 +1670,149 @@ body.logged-in #content-tabs ul.tabs.primary {
padding-top: 1px;
}
}
/* Tournus */
#point-nid-1246.placement-carte {
margin-left: 225px;
margin-top: 440px;
.map-title {
background-position: top right;
padding-bottom: 10px;
padding-right: 20px;
padding-top: 1px;
}
}
/* Villers-semeuse */
#point-nid-1244.placement-carte {
margin-left: 280px;
margin-top: 280px;
.map-title {
background-position: top left;
padding-bottom: 0;
padding-left: 23px;
padding-top: 0px;
}
}
/* Xertigny */
#point-nid-1245.placement-carte {
margin-left: 275px;
margin-top: 365px;
.map-title {
background-position: top right;
padding-bottom: 10px;
padding-right: 25px;
padding-top: 1px;
}
}
/* Roscoff */
#point-nid-1239.placement-carte {
margin-left: 50px;
margin-top: 300px;
.map-title {
background-position: top left;
padding-bottom: 0px;
padding-left: 25px;
padding-top: 1px;
}
}
/* Magny-en-Vexin */
#point-nid-1243.placement-carte {
margin-left: 220px;
margin-top: 315px;
.map-title {
background-position: bottom left;
padding-bottom: 15px;
padding-left: 20px;
padding-top: 0px;
}
}
/* Longuenée-en-Anjou */
#point-nid-1242.placement-carte {
margin-left: 120px;
margin-top: 350px;
.map-title {
background-position: bottom left;
padding-bottom: 13px;
padding-left: 22px;
padding-top: 1px;
}
}
/* Digne-les-Bains */
#point-nid-1248.placement-carte {
margin-left: 330px; /* -55 */
margin-top: 578px; /* -172 */
.map-title {
background-position: top left;
padding-bottom: 10px;
padding-left: 28px;
padding-top: 1px;
}
}
/* Vire */
#point-nid-1240.placement-carte {
margin-left: 120px;
margin-top: 315px;
.map-title {
background-position: top right;
padding-bottom: 10px;
padding-right: 22px;
padding-top: 0px;
}
}
/* Nozay */
#point-nid-1241.placement-carte {
margin-left: 55px;
margin-top: 355px;
.map-title {
background-position: top right;
padding-bottom: 0px;
padding-right: 25px;
padding-top: 0px;
}
}
/* Lodève */
#point-nid-1249.placement-carte {
margin-left: 180px; /* 117 */
margin-top: 575px; /* 94 */
.map-title {
background-position: top right;
padding-bottom: 0px;
padding-right: 20px;
padding-top: 0px;
}
}
/* Foix */
#point-nid-1250.placement-carte {
margin-left: 135px; /* 117 */
margin-top: 575px; /* 94 */
.map-title {
background-position: top right;
padding-bottom: 0px;
padding-right: 20px;
padding-top: 0px;
}
}
/* Arvieu */
#point-nid-1251.placement-carte {
margin-left: 160px;
margin-top: 530px;
.map-title {
background-position: top right;
padding-bottom: 0px;
padding-right: 23px;
padding-top: 0px;
}
}
/* Ambert */
#point-nid-1247.placement-carte {
margin-left: 185px; /* -55 */
margin-top: 470px; /* -172 */
.map-title {
background-position: top right;
padding-bottom: 10px;
padding-right: 25px;
padding-top: 1px;
}
}