matomo.module 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  1. <?php
  2. /**
  3. * @file
  4. * Drupal Module: Matomo
  5. *
  6. * Adds the required Javascript to all your Drupal pages to allow tracking by
  7. * the Matomo statistics package.
  8. *
  9. * @author: Alexander Hass <https://drupal.org/user/85918>
  10. */
  11. /**
  12. * Define the default file extension list that should be tracked as download.
  13. */
  14. 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');
  15. /**
  16. * Define default path exclusion list to remove tracking from admin pages,
  17. * see https://drupal.org/node/34970 for more information.
  18. */
  19. define('MATOMO_PAGES', "admin\nadmin/*\nbatch\nnode/add*\nnode/*/*\nuser/*/*");
  20. /**
  21. * Implements hook_help().
  22. */
  23. function matomo_help($path, $arg) {
  24. switch ($path) {
  25. case 'admin/config/system/matomo':
  26. 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/'));
  27. }
  28. }
  29. /**
  30. * Implements hook_theme().
  31. */
  32. function matomo_theme() {
  33. return array(
  34. 'matomo_admin_custom_var_table' => array(
  35. 'render element' => 'form',
  36. ),
  37. );
  38. }
  39. /**
  40. * Implements hook_permission().
  41. */
  42. function matomo_permission() {
  43. return array(
  44. 'administer matomo' => array(
  45. 'title' => t('Administer Matomo'),
  46. 'description' => t('Perform maintenance tasks for Matomo.'),
  47. ),
  48. 'opt-in or out of matomo tracking' => array(
  49. 'title' => t('Opt-in or out of tracking'),
  50. 'description' => t('Allow users to decide if tracking code will be added to pages or not.'),
  51. ),
  52. 'use php for matomo tracking visibility' => array(
  53. 'title' => t('Use PHP for tracking visibility'),
  54. 'description' => t('Enter PHP code in the field for tracking visibility settings.'),
  55. 'restrict access' => TRUE,
  56. ),
  57. 'add js snippets for matomo' => array(
  58. 'title' => t('Add JavaScript snippets'),
  59. 'description' => 'Enter JavaScript code snippets for advanced Matomo functionality.',
  60. 'restrict access' => TRUE,
  61. ),
  62. );
  63. }
  64. /**
  65. * Implements hook_menu().
  66. */
  67. function matomo_menu() {
  68. $items['admin/config/system/matomo'] = array(
  69. 'title' => 'Matomo Analytics',
  70. 'description' => 'Configure the settings used to generate your Matomo tracking code.',
  71. 'page callback' => 'drupal_get_form',
  72. 'page arguments' => array('matomo_admin_settings_form'),
  73. 'access arguments' => array('administer matomo'),
  74. 'type' => MENU_NORMAL_ITEM,
  75. 'file' => 'matomo.admin.inc',
  76. );
  77. return $items;
  78. }
  79. /**
  80. * Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.
  81. */
  82. function matomo_page_alter(&$page) {
  83. global $user;
  84. $id = variable_get('matomo_site_id', '');
  85. // Get page status code for visibility filtering.
  86. $status = drupal_get_http_header('Status');
  87. $trackable_status_codes = array(
  88. '403 Forbidden',
  89. '404 Not Found',
  90. );
  91. // 1. Check if the matomo account number has a value.
  92. // 2. Track page views based on visibility value.
  93. // 3. Check if we should track the currently active user's role.
  94. if (preg_match('/^\d{1,}$/', $id) && (_matomo_visibility_pages() || in_array($status, $trackable_status_codes)) && _matomo_visibility_user($user)) {
  95. $url_http = variable_get('matomo_url_http', '');
  96. $url_https = variable_get('matomo_url_https', '');
  97. $scope = variable_get('matomo_js_scope', 'header');
  98. $set_custom_url = '';
  99. $set_document_title = '';
  100. // Add link tracking.
  101. $link_settings = array();
  102. $link_settings['trackMailto'] = variable_get('matomo_trackmailto', 1);
  103. if (module_exists('colorbox') && ($track_colorbox = variable_get('matomo_trackcolorbox', 1))) {
  104. $link_settings['trackColorbox'] = $track_colorbox;
  105. }
  106. drupal_add_js(array('matomo' => $link_settings), 'setting');
  107. drupal_add_js(drupal_get_path('module', 'matomo') . '/matomo.js');
  108. // Matomo can show a tree view of page titles that represents the site structure
  109. // if setDocumentTitle() provides the page titles as a "/" delimited list.
  110. // This may makes it easier to browse through the statistics of page titles
  111. // on larger sites.
  112. if (variable_get('matomo_page_title_hierarchy', FALSE) == TRUE) {
  113. $titles = _matomo_get_hierarchy_titles();
  114. if (variable_get('matomo_page_title_hierarchy_exclude_home', TRUE)) {
  115. // Remove the "Home" item from the titles to flatten the tree view.
  116. array_shift($titles);
  117. }
  118. // Remove all empty titles.
  119. $titles = array_filter($titles);
  120. if (!empty($titles)) {
  121. // Encode title, at least to keep "/" intact.
  122. $titles = array_map('rawurlencode', $titles);
  123. $set_document_title = drupal_json_encode(implode('/', $titles));
  124. }
  125. }
  126. // Add messages tracking.
  127. $message_events = '';
  128. if ($message_types = variable_get('matomo_trackmessages', array())) {
  129. $message_types = array_values(array_filter($message_types));
  130. $status_heading = array(
  131. 'status' => t('Status message'),
  132. 'warning' => t('Warning message'),
  133. 'error' => t('Error message'),
  134. );
  135. foreach (drupal_get_messages(NULL, FALSE) as $type => $messages) {
  136. // Track only the selected message types.
  137. if (in_array($type, $message_types)) {
  138. foreach ($messages as $message) {
  139. $message_events .= '_paq.push(["trackEvent", ' . drupal_json_encode(t('Messages')) . ', ' . drupal_json_encode($status_heading[$type]) . ', ' . drupal_json_encode(strip_tags($message)) . ']);';
  140. }
  141. }
  142. }
  143. }
  144. // If this node is a translation of another node, pass the original
  145. // node instead.
  146. if (module_exists('translation') && variable_get('matomo_translation_set', 0)) {
  147. // Check we have a node object, it supports translation, and its
  148. // translated node ID (tnid) doesn't match its own node ID.
  149. $node = menu_get_object();
  150. if ($node && translation_supported_type($node->type) && !empty($node->tnid) && ($node->tnid != $node->nid)) {
  151. $source_node = node_load($node->tnid);
  152. $languages = language_list();
  153. $set_custom_url = drupal_json_encode(url('node/' . $source_node->nid, array('language' => $languages[$source_node->language], 'absolute' => TRUE)));
  154. }
  155. }
  156. // Track access denied (403) and file not found (404) pages.
  157. if ($status == '403 Forbidden') {
  158. $set_document_title = '"403/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)';
  159. }
  160. elseif ($status == '404 Not Found') {
  161. $set_document_title = '"404/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)';
  162. }
  163. // #2693595: User has entered an invalid login and clicked on forgot
  164. // password link. This link contains the username or email address and may
  165. // get send to Matomo if we do not override it. Override only if 'name'
  166. // query param exists. Last custom url condition, this need to win.
  167. //
  168. // URLs to protect are:
  169. // - user/password?name=username
  170. // - user/password?name=foo@example.com
  171. if (arg(0) == 'user' && arg(1) == 'password' && array_key_exists('name', drupal_get_query_parameters())) {
  172. $set_custom_url = drupal_json_encode(url('user/password'));
  173. }
  174. // Add custom variables.
  175. $matomo_custom_vars = variable_get('matomo_custom_var', array());
  176. $custom_variable = '';
  177. for ($i = 1; $i < 6; $i++) {
  178. $custom_var_name = !empty($matomo_custom_vars['slots'][$i]['name']) ? $matomo_custom_vars['slots'][$i]['name'] : '';
  179. if (!empty($custom_var_name)) {
  180. $custom_var_value = !empty($matomo_custom_vars['slots'][$i]['value']) ? $matomo_custom_vars['slots'][$i]['value'] : '';
  181. $custom_var_scope = !empty($matomo_custom_vars['slots'][$i]['scope']) ? $matomo_custom_vars['slots'][$i]['scope'] : 'visit';
  182. $types = array();
  183. $node = menu_get_object();
  184. if (is_object($node)) {
  185. $types += array('node' => $node);
  186. }
  187. $custom_var_name = token_replace($custom_var_name, $types, array('clear' => TRUE));
  188. $custom_var_value = token_replace($custom_var_value, $types, array('clear' => TRUE));
  189. // Suppress empty custom names and/or variables.
  190. if (!drupal_strlen(trim($custom_var_name)) || !drupal_strlen(trim($custom_var_value))) {
  191. continue;
  192. }
  193. // Custom variables names and values are limited to 200 characters in
  194. // length. It is recommended to store values that are as small as
  195. // possible to ensure that the Matomo Tracking request URL doesn't go
  196. // over the URL limit for the webserver or browser.
  197. $custom_var_name = rtrim(substr($custom_var_name, 0, 200));
  198. $custom_var_value = rtrim(substr($custom_var_value, 0, 200));
  199. $custom_var_name = drupal_json_encode($custom_var_name);
  200. $custom_var_value = drupal_json_encode($custom_var_value);
  201. $custom_var_scope = drupal_json_encode($custom_var_scope);
  202. $custom_variable .= "_paq.push(['setCustomVariable', $i, $custom_var_name, $custom_var_value, $custom_var_scope]);";
  203. }
  204. }
  205. // Add any custom code snippets if specified.
  206. $codesnippet_before = variable_get('matomo_codesnippet_before', '');
  207. $codesnippet_after = variable_get('matomo_codesnippet_after', '');
  208. // Build tracker code. See https://matomo.org/docs/javascript-tracking/#toc-asynchronous-tracking
  209. $script = 'var _paq = _paq || [];';
  210. $script .= '(function(){';
  211. $script .= 'var u=(("https:" == document.location.protocol) ? "' . check_url($url_https) . '" : "' . check_url($url_http) . '");';
  212. $script .= '_paq.push(["setSiteId", ' . drupal_json_encode(variable_get('matomo_site_id', '')) . ']);';
  213. $script .= '_paq.push(["setTrackerUrl", u+"piwik.php"]);';
  214. // Track logged in users across all devices.
  215. if (variable_get('matomo_trackuserid', 0) && user_is_logged_in()) {
  216. // The USER_ID value should be a unique, persistent, and non-personally
  217. // identifiable string identifier that represents a user or signed-in
  218. // account across devices.
  219. $script .= '_paq.push(["setUserId", ' . drupal_json_encode(matomo_user_id_hash($user->uid)) . ']);';
  220. }
  221. // Set custom url.
  222. if (!empty($set_custom_url)) {
  223. $script .= '_paq.push(["setCustomUrl", ' . $set_custom_url . ']);';
  224. }
  225. // Set custom document title.
  226. if (!empty($set_document_title)) {
  227. $script .= '_paq.push(["setDocumentTitle", ' . $set_document_title . ']);';
  228. }
  229. // Custom file download extensions.
  230. if ((variable_get('matomo_track', 1)) && !(variable_get('matomo_trackfiles_extensions', MATOMO_TRACKFILES_EXTENSIONS) == MATOMO_TRACKFILES_EXTENSIONS)) {
  231. $script .= '_paq.push(["setDownloadExtensions", ' . drupal_json_encode(variable_get('matomo_trackfiles_extensions', MATOMO_TRACKFILES_EXTENSIONS)) . ']);';
  232. }
  233. // Disable tracking for visitors who have opted out from tracking via DNT (Do-Not-Track) header.
  234. if (variable_get('matomo_privacy_donottrack', 1)) {
  235. $script .= '_paq.push(["setDoNotTrack", 1]);';
  236. }
  237. // Domain tracking type.
  238. global $cookie_domain;
  239. $domain_mode = variable_get('matomo_domain_mode', 0);
  240. // Per RFC 2109, cookie domains must contain at least one dot other than the
  241. // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
  242. if ($domain_mode == 1 && count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
  243. $script .= '_paq.push(["setCookieDomain", ' . drupal_json_encode($cookie_domain) . ']);';
  244. }
  245. // Ordering $custom_variable before $codesnippet_before allows users to add
  246. // custom code snippets that may use deleteCustomVariable() and/or getCustomVariable().
  247. if (!empty($custom_variable)) {
  248. $script .= $custom_variable;
  249. }
  250. if (!empty($codesnippet_before)) {
  251. $script .= $codesnippet_before;
  252. }
  253. // Site search tracking support.
  254. // NOTE: It's recommended not to call trackPageView() on the Site Search Result page.
  255. if (module_exists('search') && variable_get('matomo_site_search', FALSE) && arg(0) == 'search' && $keys = matomo_search_get_keys()) {
  256. // Parameters:
  257. // 1. Search keyword searched for. Example: "Banana"
  258. // 2. Search category selected in your search engine. If you do not need
  259. // this, set to false. Example: "Organic Food"
  260. // 3. Number of results on the Search results page. Zero indicates a
  261. // 'No Result Search Keyword'. Set to false if you don't know.
  262. //
  263. // hook_preprocess_search_results() is not executed if search result is
  264. // empty. Make sure the counter is set to 0 if there are no results.
  265. $script .= '_paq.push(["trackSiteSearch", ' . drupal_json_encode($keys) . ', false, (window.matomo_search_results) ? window.matomo_search_results : 0]);';
  266. }
  267. else {
  268. $script .= '_paq.push(["trackPageView"]);';
  269. }
  270. // Add link tracking.
  271. if (variable_get('matomo_track', 1)) {
  272. // Disable tracking of links with ".no-tracking" and ".colorbox" classes.
  273. $ignore_classes = array(
  274. 'no-tracking',
  275. 'colorbox',
  276. );
  277. // Disable the download & outlink tracking for specific CSS classes.
  278. // Custom code snippets with 'setIgnoreClasses' will override the value.
  279. // https://developer.matomo.org/api-reference/tracking-javascript#disable-the-download-amp-outlink-tracking-for-specific-css-classes
  280. $script .= '_paq.push(["setIgnoreClasses", ' . drupal_json_encode($ignore_classes) . ']);';
  281. // Enable download & outlink link tracking.
  282. $script .= '_paq.push(["enableLinkTracking"]);';
  283. }
  284. if (!empty($message_events)) {
  285. $script .= $message_events;
  286. }
  287. if (!empty($codesnippet_after)) {
  288. $script .= $codesnippet_after;
  289. }
  290. $script .= 'var d=document,';
  291. $script .= 'g=d.createElement("script"),';
  292. $script .= 's=d.getElementsByTagName("script")[0];';
  293. $script .= 'g.type="text/javascript";';
  294. $script .= 'g.defer=true;';
  295. $script .= 'g.async=true;';
  296. // Should a local cached copy of the tracking code be used?
  297. if (variable_get('matomo_cache', 0) && $url = _matomo_cache($url_http . 'piwik.js')) {
  298. // A dummy query-string is added to filenames, to gain control over
  299. // browser-caching. The string changes on every update or full cache
  300. // flush, forcing browsers to load a new copy of the files, as the
  301. // URL changed.
  302. $query_string = '?' . variable_get('css_js_query_string', '0');
  303. $script .= 'g.src="' . $url . $query_string . '";';
  304. }
  305. else {
  306. $script .= 'g.src=u+"piwik.js";';
  307. }
  308. $script .= 's.parentNode.insertBefore(g,s);';
  309. $script .= '})();';
  310. // Add tracker code to scope.
  311. drupal_add_js($script, array('scope' => $scope, 'type' => 'inline'));
  312. }
  313. }
  314. /**
  315. * Generate user id hash to implement USER_ID.
  316. *
  317. * The USER_ID value should be a unique, persistent, and non-personally
  318. * identifiable string identifier that represents a user or signed-in
  319. * account across devices.
  320. *
  321. * @param int $uid
  322. * User id.
  323. *
  324. * @return string
  325. * User id hash.
  326. */
  327. function matomo_user_id_hash($uid) {
  328. return drupal_hmac_base64($uid, drupal_get_private_key() . drupal_get_hash_salt());
  329. }
  330. /**
  331. * Implements hook_field_extra_fields().
  332. */
  333. function matomo_field_extra_fields() {
  334. $extra['user']['user']['form']['matomo'] = array(
  335. 'label' => t('Matomo configuration'),
  336. 'description' => t('Matomo module form element.'),
  337. 'weight' => 3,
  338. );
  339. return $extra;
  340. }
  341. /**
  342. * Implement hook_form_FORM_ID_alter().
  343. *
  344. * Allow users to decide if tracking code will be added to pages or not.
  345. */
  346. function matomo_form_user_profile_form_alter(&$form, &$form_state) {
  347. $account = $form['#user'];
  348. $category = $form['#user_category'];
  349. if ($category == 'account' && user_access('opt-in or out of matomo tracking') && ($custom = variable_get('matomo_custom', 1)) != 0 && _matomo_visibility_roles($account)) {
  350. $form['matomo'] = array(
  351. '#type' => 'fieldset',
  352. '#title' => t('Matomo configuration'),
  353. '#weight' => 3,
  354. '#collapsible' => TRUE,
  355. '#tree' => TRUE
  356. );
  357. switch ($custom) {
  358. case 1:
  359. $description = t('Users are tracked by default, but you are able to opt out.');
  360. break;
  361. case 2:
  362. $description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
  363. break;
  364. }
  365. // Migrate old piwik settings to matomo.
  366. if (isset($account->data['piwik']['custom'])) {
  367. $account->data['matomo']['custom'] = $account->data['piwik']['custom'];
  368. }
  369. $form['matomo']['custom'] = array(
  370. '#type' => 'checkbox',
  371. '#title' => t('Enable user tracking'),
  372. '#description' => $description,
  373. '#default_value' => isset($account->data['matomo']['custom']) ? $account->data['matomo']['custom'] : ($custom == 1),
  374. );
  375. return $form;
  376. }
  377. }
  378. /**
  379. * Implements hook_user_presave().
  380. */
  381. function matomo_user_presave(&$edit, $account, $category) {
  382. if (isset($edit['matomo']['custom'])) {
  383. $edit['data']['matomo']['custom'] = $edit['matomo']['custom'];
  384. }
  385. // Remove old piwik setting to complete migration to matomo.
  386. if (isset($edit['data']['piwik'])) {
  387. unset($edit['data']['piwik']);
  388. }
  389. }
  390. /**
  391. * Implements hook_cron().
  392. */
  393. function matomo_cron() {
  394. // Regenerate the piwik.js every day.
  395. if (REQUEST_TIME - variable_get('matomo_last_cache', 0) >= 86400 && variable_get('matomo_cache', 0)) {
  396. _matomo_cache(variable_get('matomo_url_http', '') . 'piwik.js', TRUE);
  397. variable_set('matomo_last_cache', REQUEST_TIME);
  398. }
  399. }
  400. /**
  401. * Implements hook_preprocess_search_results().
  402. *
  403. * Collects and adds the number of search results to the head.
  404. */
  405. function matomo_preprocess_search_results(&$variables) {
  406. // There is no search result $variable available that hold the number of items
  407. // found. But the pager item mumber can tell the number of search results.
  408. global $pager_total_items;
  409. drupal_add_js('window.matomo_search_results = ' . intval($pager_total_items[0]) . ';', array('type' => 'inline', 'group' => JS_LIBRARY-1));
  410. }
  411. /**
  412. * Download/Synchronize/Cache tracking code file locally.
  413. *
  414. * @param $location
  415. * The full URL to the external javascript file.
  416. * @param $sync_cached_file
  417. * Synchronize tracking code and update if remote file have changed.
  418. * @return mixed
  419. * The path to the local javascript file on success, boolean FALSE on failure.
  420. */
  421. function _matomo_cache($location, $sync_cached_file = FALSE) {
  422. $path = 'public://matomo';
  423. $file_destination = $path . '/' . basename($location);
  424. if (!file_exists($file_destination) || $sync_cached_file) {
  425. // Download the latest tracking code.
  426. $result = drupal_http_request($location);
  427. if ($result->code == 200) {
  428. if (file_exists($file_destination)) {
  429. // Synchronize tracking code and and replace local file if outdated.
  430. $data_hash_local = drupal_hash_base64(file_get_contents($file_destination));
  431. $data_hash_remote = drupal_hash_base64($result->data);
  432. // Check that the files directory is writable.
  433. if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
  434. // Save updated tracking code file to disk.
  435. file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
  436. // Based on Drupal Core drupal_build_css_cache().
  437. if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
  438. file_unmanaged_save_data(gzencode($result->data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE);
  439. }
  440. watchdog('matomo', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO);
  441. // Change query-strings on css/js files to enforce reload for all users.
  442. _drupal_flush_css_js();
  443. }
  444. }
  445. else {
  446. // Check that the files directory is writable.
  447. if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
  448. // There is no need to flush JS here as core refreshes JS caches
  449. // automatically, if new files are added.
  450. file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
  451. if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
  452. file_unmanaged_save_data(gzencode($result->data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE);
  453. }
  454. watchdog('matomo', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);
  455. // Return the local JS file path.
  456. return file_create_url($file_destination);
  457. }
  458. }
  459. }
  460. }
  461. else {
  462. // Return the local JS file path.
  463. return file_create_url($file_destination);
  464. }
  465. }
  466. /**
  467. * Delete cached files and directory.
  468. */
  469. function matomo_clear_js_cache() {
  470. $path = 'public://matomo';
  471. if (file_prepare_directory($path)) {
  472. file_scan_directory($path, '/.*/', array('callback' => 'file_unmanaged_delete'));
  473. drupal_rmdir($path);
  474. // Change query-strings on css/js files to enforce reload for all users.
  475. _drupal_flush_css_js();
  476. watchdog('matomo', 'Local cache has been purged.', array(), WATCHDOG_INFO);
  477. }
  478. }
  479. /**
  480. * Helper function for grabbing search keys. Function is missing in D7.
  481. *
  482. * https://api.drupal.org/api/function/search_get_keys/6
  483. */
  484. function matomo_search_get_keys() {
  485. static $return;
  486. if (!isset($return)) {
  487. // Extract keys as remainder of path
  488. // Note: support old GET format of searches for existing links.
  489. $path = explode('/', $_GET['q'], 3);
  490. $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
  491. $return = count($path) == 3 ? $path[2] : $keys;
  492. }
  493. return $return;
  494. }
  495. /**
  496. * Tracking visibility check for an user object.
  497. *
  498. * @param $account
  499. * A user object containing an array of roles to check.
  500. * @return boolean
  501. * A decision on if the current user is being tracked by Matomo.
  502. */
  503. function _matomo_visibility_user($account) {
  504. $enabled = FALSE;
  505. // Is current user a member of a role that should be tracked?
  506. if (_matomo_visibility_roles($account)) {
  507. // Use the user's block visibility setting, if necessary.
  508. if (($custom = variable_get('matomo_custom', 1)) != 0) {
  509. if ($account->uid && isset($account->data['matomo']['custom'])) {
  510. $enabled = $account->data['matomo']['custom'];
  511. }
  512. else {
  513. $enabled = ($custom == 1);
  514. }
  515. }
  516. else {
  517. $enabled = TRUE;
  518. }
  519. }
  520. return $enabled;
  521. }
  522. /**
  523. * Based on visibility setting this function returns TRUE if GA code should
  524. * be added for the current role and otherwise FALSE.
  525. */
  526. function _matomo_visibility_roles($account) {
  527. $visibility = variable_get('matomo_visibility_roles', 0);
  528. $enabled = $visibility;
  529. $roles = variable_get('matomo_roles', array());
  530. if (array_sum($roles) > 0) {
  531. // One or more roles are selected.
  532. foreach (array_keys($account->roles) as $rid) {
  533. // Is the current user a member of one of these roles?
  534. if (isset($roles[$rid]) && $rid == $roles[$rid]) {
  535. // Current user is a member of a role that should be tracked/excluded from tracking.
  536. $enabled = !$visibility;
  537. break;
  538. }
  539. }
  540. }
  541. else {
  542. // No role is selected for tracking, therefore all roles should be tracked.
  543. $enabled = TRUE;
  544. }
  545. return $enabled;
  546. }
  547. /**
  548. * Based on visibility setting this function returns TRUE if GA code should
  549. * be added to the current page and otherwise FALSE.
  550. */
  551. function _matomo_visibility_pages() {
  552. static $page_match;
  553. // Cache visibility setting in hook_init for hook_footer.
  554. if (!isset($page_match)) {
  555. $visibility = variable_get('matomo_visibility_pages', 0);
  556. $setting_pages = variable_get('matomo_pages', MATOMO_PAGES);
  557. // Match path if necessary.
  558. if (!empty($setting_pages)) {
  559. // Convert path to lowercase. This allows comparison of the same path
  560. // with different case. Ex: /Page, /page, /PAGE.
  561. $pages = drupal_strtolower($setting_pages);
  562. if ($visibility < 2) {
  563. // Convert the Drupal path to lowercase
  564. $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
  565. // Compare the lowercase internal and lowercase path alias (if any).
  566. $page_match = drupal_match_path($path, $pages);
  567. if ($path != $_GET['q']) {
  568. $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
  569. }
  570. // When $visibility has a value of 0, the tracking code is displayed on
  571. // all pages except those listed in $pages. When set to 1, it
  572. // is displayed only on those pages listed in $pages.
  573. $page_match = !($visibility xor $page_match);
  574. }
  575. elseif (module_exists('php')) {
  576. $page_match = php_eval($setting_pages);
  577. }
  578. else {
  579. $page_match = FALSE;
  580. }
  581. }
  582. else {
  583. $page_match = TRUE;
  584. }
  585. }
  586. return $page_match;
  587. }
  588. /**
  589. * Get the page titles trail for the current page.
  590. *
  591. * Based on menu_get_active_breadcrumb().
  592. *
  593. * @return array
  594. * All page titles, including current page.
  595. */
  596. function _matomo_get_hierarchy_titles() {
  597. $titles = array();
  598. // No breadcrumb for the front page.
  599. if (drupal_is_front_page()) {
  600. return $titles;
  601. }
  602. $item = menu_get_item();
  603. if (!empty($item['access'])) {
  604. $active_trail = menu_get_active_trail();
  605. // Allow modules to alter the breadcrumb, if possible, as that is much
  606. // faster than rebuilding an entirely new active trail.
  607. drupal_alter('menu_breadcrumb', $active_trail, $item);
  608. // Remove the tab root (parent) if the current path links to its parent.
  609. // Normally, the tab root link is included in the breadcrumb, as soon as we
  610. // are on a local task or any other child link. However, if we are on a
  611. // default local task (e.g., node/%/view), then we do not want the tab root
  612. // link (e.g., node/%) to appear, as it would be identical to the current
  613. // page. Since this behavior also needs to work recursively (i.e., on
  614. // default local tasks of default local tasks), and since the last non-task
  615. // link in the trail is used as page title (see menu_get_active_title()),
  616. // this condition cannot be cleanly integrated into menu_get_active_trail().
  617. // menu_get_active_trail() already skips all links that link to their parent
  618. // (commonly MENU_DEFAULT_LOCAL_TASK). In order to also hide the parent link
  619. // itself, we always remove the last link in the trail, if the current
  620. // router item links to its parent.
  621. if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
  622. array_pop($active_trail);
  623. }
  624. foreach ($active_trail as $parent) {
  625. $titles[] = $parent['title'];
  626. }
  627. }
  628. return $titles;
  629. }