matomo.module 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  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. use Drupal\Component\Serialization\Json;
  12. use Drupal\Component\Utility\Crypt;
  13. use Drupal\Component\Utility\Unicode;
  14. use Drupal\Component\Utility\UrlHelper;
  15. use Drupal\Core\Cache\Cache;
  16. use Drupal\Core\Form\FormStateInterface;
  17. use Drupal\Core\Routing\RouteMatchInterface;
  18. use Drupal\Core\Site\Settings;
  19. use Drupal\Core\Url;
  20. use Drupal\matomo\MatomoInterface;
  21. use Drupal\node\NodeInterface;
  22. use GuzzleHttp\Exception\RequestException;
  23. use Drupal\matomo\Component\Render\MatomoJavaScriptSnippet;
  24. /**
  25. * Implements hook_help().
  26. */
  27. function matomo_help($route_name, RouteMatchInterface $route_match) {
  28. switch ($route_name) {
  29. case 'matomo.admin_settings_form':
  30. 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.', [':pk_url' => 'https://www.matomo.org/']);
  31. }
  32. }
  33. /**
  34. * Implements hook_page_attachments().
  35. *
  36. * Insert JavaScript to the appropriate scope/region of the page.
  37. */
  38. function matomo_page_attachments(array &$page) {
  39. $account = \Drupal::currentUser();
  40. $config = \Drupal::config('matomo.settings');
  41. $id = $config->get('site_id');
  42. $request = \Drupal::request();
  43. // Add module cache tags.
  44. $page['#cache']['tags'] = Cache::mergeTags(isset($page['#cache']['tags']) ? $page['#cache']['tags'] : [], $config->getCacheTags());
  45. // Get page http status code for visibility filtering.
  46. $status = NULL;
  47. if ($exception = $request->attributes->get('exception')) {
  48. $status = $exception->getStatusCode();
  49. }
  50. $trackable_status_codes = [
  51. // "Forbidden" status code.
  52. '403',
  53. // "Not Found" status code.
  54. '404',
  55. ];
  56. // 1. Check if the matomo account number has a valid value.
  57. // 2. Track page views based on visibility value.
  58. // 3. Check if we should track the currently active user's role.
  59. if (preg_match('/^\d{1,}$/', $id) && (_matomo_visibility_pages() || in_array($status, $trackable_status_codes)) && _matomo_visibility_user($account)) {
  60. $url_http = $config->get('url_http');
  61. $url_https = $config->get('url_https');
  62. $set_custom_url = '';
  63. $set_document_title = '';
  64. // Add link tracking.
  65. $link_settings = [];
  66. $link_settings['trackMailto'] = $config->get('track.mailto');
  67. if ((\Drupal::moduleHandler()->moduleExists('colorbox')) && $track_colorbox = $config->get('track.colorbox')) {
  68. $link_settings['trackColorbox'] = $track_colorbox;
  69. }
  70. $page['#attached']['drupalSettings']['matomo'] = $link_settings;
  71. $page['#attached']['library'][] = 'matomo/matomo';
  72. // Matomo can show a tree view of page titles that represents the site
  73. // structure if setDocumentTitle() provides the page titles as a "/"
  74. // delimited list. This may makes it easier to browse through the statistics
  75. // of page titles on larger sites.
  76. if ($config->get('page_title_hierarchy') == TRUE) {
  77. $titles = _matomo_get_hierarchy_titles();
  78. // Remove all empty titles.
  79. $titles = array_filter($titles);
  80. if (!empty($titles)) {
  81. // Encode title, at least to keep "/" intact.
  82. $titles = array_map('rawurlencode', $titles);
  83. $set_document_title = Json::encode(implode('/', $titles));
  84. }
  85. }
  86. // Add messages tracking.
  87. $message_events = '';
  88. if ($message_types = $config->get('track.messages')) {
  89. $message_types = array_values(array_filter($message_types));
  90. $status_heading = [
  91. 'status' => t('Status message'),
  92. 'warning' => t('Warning message'),
  93. 'error' => t('Error message'),
  94. ];
  95. foreach (\Drupal::messenger()->all(NULL, FALSE) as $type => $messages) {
  96. // Track only the selected message types.
  97. if (in_array($type, $message_types)) {
  98. foreach ($messages as $message) {
  99. $message_events .= '_paq.push(["trackEvent", ' . Json::encode(t('Messages')) . ', ' . Json::encode($status_heading[$type]) . ', ' . Json::encode(strip_tags($message)) . ']);';
  100. }
  101. }
  102. }
  103. }
  104. // If this node is a translation of another node, pass the original
  105. // node instead.
  106. if (\Drupal::moduleHandler()->moduleExists('content_translation') && $config->get('translation_set')) {
  107. // Check if we have a node object, it has translation enabled, and its
  108. // language code does not match its source language code.
  109. if ($request->attributes->has('node')) {
  110. $node = $request->attributes->get('node');
  111. if ($node instanceof NodeInterface && \Drupal::service('entity.repository')->getTranslationFromContext($node) !== $node->getUntranslated()) {
  112. $set_custom_url = Json::encode(Url::fromRoute('entity.node.canonical', ['node' => $node->id()], ['language' => $node->getUntranslated()->language()])->toString());
  113. }
  114. }
  115. }
  116. // Track access denied (403) and file not found (404) pages.
  117. if ($status == '403') {
  118. $set_document_title = '"403/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)';
  119. }
  120. elseif ($status == '404') {
  121. $set_document_title = '"404/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)';
  122. }
  123. // #2693595: User has entered an invalid login and clicked on forgot
  124. // password link. This link contains the username or email address and may
  125. // get send to Matomo if we do not override it. Override only if 'name'
  126. // query param exists. Last custom url condition, this need to win.
  127. //
  128. // URLs to protect are:
  129. // - user/password?name=username
  130. // - user/password?name=foo@example.com
  131. if (\Drupal::routeMatch()->getRouteName() == 'user.pass' && $request->query->has('name')) {
  132. $set_custom_url = Json::encode(Url::fromRoute('user.pass')->toString());
  133. }
  134. // Add custom variables.
  135. $matomo_custom_vars = $config->get('custom.variable');
  136. $custom_variable = '';
  137. for ($i = 1; $i < 6; $i++) {
  138. $custom_var_name = !empty($matomo_custom_vars[$i]['name']) ? $matomo_custom_vars[$i]['name'] : '';
  139. if (!empty($custom_var_name)) {
  140. $custom_var_value = !empty($matomo_custom_vars[$i]['value']) ? $matomo_custom_vars[$i]['value'] : '';
  141. $custom_var_scope = !empty($matomo_custom_vars[$i]['scope']) ? $matomo_custom_vars[$i]['scope'] : 'visit';
  142. $types = [];
  143. if ($request->attributes->has('node')) {
  144. $node = $request->attributes->get('node');
  145. if ($node instanceof NodeInterface) {
  146. $types += ['node' => $node];
  147. }
  148. }
  149. $custom_var_name = \Drupal::token()->replace($custom_var_name, $types, ['clear' => TRUE]);
  150. $custom_var_value = \Drupal::token()->replace($custom_var_value, $types, ['clear' => TRUE]);
  151. // Suppress empty custom names and/or variables.
  152. if (!Unicode::strlen(trim($custom_var_name)) || !Unicode::strlen(trim($custom_var_value))) {
  153. continue;
  154. }
  155. // Custom variables names and values are limited to 200 characters in
  156. // length. It is recommended to store values that are as small as
  157. // possible to ensure that the Matomo Tracking request URL doesn't go
  158. // over the URL limit for the webserver or browser.
  159. $custom_var_name = rtrim(substr($custom_var_name, 0, 200));
  160. $custom_var_value = rtrim(substr($custom_var_value, 0, 200));
  161. // Add variables to tracker.
  162. $custom_variable .= '_paq.push(["setCustomVariable", ' . Json::encode($i) . ', ' . Json::encode($custom_var_name) . ', ' . Json::encode($custom_var_value) . ', ' . Json::encode($custom_var_scope) . ']);';
  163. }
  164. }
  165. // Add any custom code snippets if specified.
  166. $codesnippet_before = $config->get('codesnippet.before');
  167. $codesnippet_after = $config->get('codesnippet.after');
  168. // Build tracker code.
  169. // @see https://matomo.org/docs/javascript-tracking/#toc-asynchronous-tracking
  170. $script = 'var _paq = _paq || [];';
  171. $script .= '(function(){';
  172. $script .= 'var u=(("https:" == document.location.protocol) ? "' . UrlHelper::filterBadProtocol($url_https) . '" : "' . UrlHelper::filterBadProtocol($url_http) . '");';
  173. $script .= '_paq.push(["setSiteId", ' . Json::encode($id) . ']);';
  174. $script .= '_paq.push(["setTrackerUrl", u+"piwik.php"]);';
  175. // Track logged in users across all devices.
  176. if ($config->get('track.userid') && $account->isAuthenticated()) {
  177. $script .= '_paq.push(["setUserId", ' . Json::encode(matomo_user_id_hash($account->id())) . ']);';
  178. }
  179. // Set custom url.
  180. if (!empty($set_custom_url)) {
  181. $script .= '_paq.push(["setCustomUrl", ' . $set_custom_url . ']);';
  182. }
  183. // Set custom document title.
  184. if (!empty($set_document_title)) {
  185. $script .= '_paq.push(["setDocumentTitle", ' . $set_document_title . ']);';
  186. }
  187. // Custom file download extensions.
  188. if ($config->get('track.files') && !($config->get('track.files_extensions') == MatomoInterface::MATOMO_TRACKFILES_EXTENSIONS)) {
  189. $script .= '_paq.push(["setDownloadExtensions", ' . Json::encode($config->get('track.files_extensions')) . ']);';
  190. }
  191. // Disable tracking for visitors who have opted out from tracking via DNT
  192. // (Do-Not-Track) header.
  193. if ($config->get('privacy.donottrack')) {
  194. $script .= '_paq.push(["setDoNotTrack", 1]);';
  195. }
  196. // Domain tracking type.
  197. global $cookie_domain;
  198. $domain_mode = $config->get('domain_mode');
  199. // Per RFC 2109, cookie domains must contain at least one dot other than the
  200. // first. For hosts such as 'localhost' or IP Addresses we don't set a
  201. // cookie domain.
  202. if ($domain_mode == 1 && count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
  203. $script .= '_paq.push(["setCookieDomain", ' . Json::encode($cookie_domain) . ']);';
  204. }
  205. // Ordering $custom_variable before $codesnippet_before allows users to add
  206. // custom code snippets that may use deleteCustomVariable() and/or
  207. // getCustomVariable().
  208. if (!empty($custom_variable)) {
  209. $script .= $custom_variable;
  210. }
  211. if (!empty($codesnippet_before)) {
  212. $script .= $codesnippet_before;
  213. }
  214. // Site search tracking support.
  215. // NOTE: It's recommended not to call trackPageView() on the Site Search
  216. // Result page.
  217. if (\Drupal::moduleHandler()->moduleExists('search') && $config->get('track.site_search') && (strpos(\Drupal::routeMatch()->getRouteName(), 'search.view') === 0) && $keys = ($request->query->has('keys') ? trim($request->get('keys')) : '')) {
  218. // Parameters:
  219. // 1. Search keyword searched for. Example: "Banana"
  220. // 2. Search category selected in your search engine. If you do not need
  221. // this, set to false. Example: "Organic Food"
  222. // 3. Number of results on the Search results page. Zero indicates a
  223. // 'No Result Search Keyword'. Set to false if you don't know.
  224. //
  225. // hook_preprocess_search_results() is not executed if search result is
  226. // empty. Make sure the counter is set to 0 if there are no results.
  227. $script .= '_paq.push(["trackSiteSearch", ' . Json::encode($keys) . ', false, (window.matomo_search_results) ? window.matomo_search_results : 0]);';
  228. }
  229. else {
  230. $script .= '_paq.push(["trackPageView"]);';
  231. }
  232. // Add link tracking.
  233. if ($config->get('track.files')) {
  234. // Disable tracking of links with ".no-tracking" and ".colorbox" classes.
  235. $ignore_classes = [
  236. 'no-tracking',
  237. 'colorbox',
  238. ];
  239. // Disable the download & outlink tracking for specific CSS classes.
  240. // Custom code snippets with 'setIgnoreClasses' will override the value.
  241. // @see https://developer.matomo.org/api-reference/tracking-javascript#disable-the-download-amp-outlink-tracking-for-specific-css-classes
  242. $script .= '_paq.push(["setIgnoreClasses", ' . Json::encode($ignore_classes) . ']);';
  243. // Enable download & outlink link tracking.
  244. $script .= '_paq.push(["enableLinkTracking"]);';
  245. }
  246. if (!empty($message_events)) {
  247. $script .= $message_events;
  248. }
  249. if (!empty($codesnippet_after)) {
  250. $script .= $codesnippet_after;
  251. }
  252. $script .= 'var d=document,';
  253. $script .= 'g=d.createElement("script"),';
  254. $script .= 's=d.getElementsByTagName("script")[0];';
  255. $script .= 'g.type="text/javascript";';
  256. $script .= 'g.defer=true;';
  257. $script .= 'g.async=true;';
  258. // Should a local cached copy of the tracking code be used?
  259. if ($config->get('cache') && $url = _matomo_cache($url_http . 'piwik.js')) {
  260. // A dummy query-string is added to filenames, to gain control over
  261. // browser-caching. The string changes on every update or full cache
  262. // flush, forcing browsers to load a new copy of the files, as the
  263. // URL changed.
  264. $query_string = '?' . (\Drupal::state()->get('system.css_js_query_string') ?: '0');
  265. $script .= 'g.src="' . $url . $query_string . '";';
  266. }
  267. else {
  268. $script .= 'g.src=u+"piwik.js";';
  269. }
  270. $script .= 's.parentNode.insertBefore(g,s);';
  271. $script .= '})();';
  272. // Add tracker code.
  273. $page['#attached']['html_head'][] = [
  274. [
  275. '#tag' => 'script',
  276. '#value' => new MatomoJavaScriptSnippet($script),
  277. ],
  278. 'matomo_tracking_script',
  279. ];
  280. }
  281. }
  282. /**
  283. * Generate user id hash to implement USER_ID.
  284. *
  285. * The USER_ID value should be a unique, persistent, and non-personally
  286. * identifiable string identifier that represents a user or signed-in
  287. * account across devices.
  288. *
  289. * @param int $uid
  290. * User id.
  291. *
  292. * @return string
  293. * User id hash.
  294. */
  295. function matomo_user_id_hash($uid) {
  296. return Crypt::hmacBase64($uid, \Drupal::service('private_key')->get() . Settings::getHashSalt());
  297. }
  298. /**
  299. * Implements hook_entity_extra_field_info().
  300. */
  301. function matomo_entity_extra_field_info() {
  302. $extra['user']['user']['form']['matomo'] = [
  303. 'label' => t('Matomo settings'),
  304. 'description' => t('Matomo module form element.'),
  305. 'weight' => 3,
  306. ];
  307. return $extra;
  308. }
  309. /**
  310. * Implements hook_form_FORM_ID_alter().
  311. *
  312. * Allow users to decide if tracking code will be added to pages or not.
  313. */
  314. function matomo_form_user_form_alter(&$form, FormStateInterface $form_state) {
  315. $config = \Drupal::config('matomo.settings');
  316. $account = $form_state->getFormObject()->getEntity();
  317. if ($account->hasPermission('opt-in or out of matomo tracking') && ($visibility_users = $config->get('visibility.user_account_mode')) != 0 && _matomo_visibility_roles($account)) {
  318. $account_data_matomo = \Drupal::service('user.data')->get('matomo', $account->id());
  319. $form['matomo'] = [
  320. '#type' => 'details',
  321. '#title' => t('Matomo settings'),
  322. '#weight' => 3,
  323. '#open' => TRUE,
  324. ];
  325. switch ($visibility_users) {
  326. case 1:
  327. $description = t('Users are tracked by default, but you are able to opt out.');
  328. break;
  329. case 2:
  330. $description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
  331. break;
  332. }
  333. // Disable tracking for visitors who have opted out from tracking via DNT
  334. // (Do-Not-Track) header.
  335. $disabled = FALSE;
  336. if ($config->get('privacy.donottrack') && !empty($_SERVER['HTTP_DNT'])) {
  337. $disabled = TRUE;
  338. // Override settings value.
  339. $account_data_matomo['users'] = FALSE;
  340. $description .= '<span class="admin-missing">';
  341. $description .= ' ' . t('You have opted out from tracking via browser privacy settings.');
  342. $description .= '</span>';
  343. }
  344. // Migrate old piwik settings to matomo.
  345. $account_data_piwik = \Drupal::service('user.data')->get('piwik', $account->id());
  346. if (isset($account_data_piwik['user_account_users'])) {
  347. $account_data_matomo['user_account_users'] = $account_data_piwik['user_account_users'];
  348. }
  349. $form['matomo']['user_account_users'] = [
  350. '#type' => 'checkbox',
  351. '#title' => t('Enable user tracking'),
  352. '#description' => $description,
  353. '#default_value' => isset($account_data_matomo['user_account_users']) ? $account_data_matomo['user_account_users'] : ($visibility_users == 1),
  354. '#disabled' => $disabled,
  355. ];
  356. // hook_user_update() is missing in D8, add custom submit handler.
  357. $form['actions']['submit']['#submit'][] = 'matomo_user_profile_form_submit';
  358. }
  359. }
  360. /**
  361. * Submit callback for user profile form to save the Matomo setting.
  362. */
  363. function matomo_user_profile_form_submit($form, FormStateInterface $form_state) {
  364. $account = $form_state->getFormObject()->getEntity();
  365. if ($account->id() && $form_state->hasValue('user_account_users')) {
  366. \Drupal::service('user.data')->set('matomo', $account->id(), 'user_account_users', (int) $form_state->getValue('user_account_users'));
  367. }
  368. // Remove old piwik setting to complete migration to matomo.
  369. $account_data_piwik = \Drupal::service('user.data')->get('piwik', $account->id());
  370. if (isset($account_data_piwik)) {
  371. \Drupal::service('user.data')->delete('piwik', $account->id());
  372. }
  373. }
  374. /**
  375. * Implements hook_cron().
  376. */
  377. function matomo_cron() {
  378. $config = \Drupal::config('matomo.settings');
  379. $request_time = \Drupal::time()->getRequestTime();
  380. // Regenerate the piwik.js every day.
  381. if ($request_time - \Drupal::state()->get('matomo.last_cache') >= 86400 && $config->get('cache')) {
  382. _matomo_cache($config->get('url_http') . 'piwik.js', TRUE);
  383. \Drupal::state()->set('matomo.last_cache', $request_time);
  384. }
  385. }
  386. /**
  387. * Implements hook_preprocess_item_list__search_results().
  388. *
  389. * Collects and adds the number of search results to the head.
  390. */
  391. function matomo_preprocess_item_list__search_results(&$variables) {
  392. $config = \Drupal::config('matomo.settings');
  393. // Only run on search results list.
  394. if ($config->get('track.site_search')) {
  395. // There is no search result $variable available that hold the number of
  396. // items found. The variable $variables['items'] has the current page items
  397. // only. But the pager item mumber can tell the number of search results.
  398. global $pager_total_items;
  399. $variables['#attached']['html_head'][] = [
  400. [
  401. '#tag' => 'script',
  402. '#value' => 'window.matomo_search_results = ' . intval($pager_total_items[0]) . ';',
  403. '#weight' => JS_LIBRARY - 1,
  404. ],
  405. 'matomo_search_script',
  406. ];
  407. }
  408. }
  409. /**
  410. * Download/Synchronize/Cache tracking code file locally.
  411. *
  412. * @param string $location
  413. * The full URL to the external javascript file.
  414. * @param bool $synchronize
  415. * Synchronize to local cache if remote file has changed.
  416. *
  417. * @return mixed
  418. * The path to the local javascript file on success, boolean FALSE on failure.
  419. */
  420. function _matomo_cache($location, $synchronize = FALSE) {
  421. $path = 'public://matomo';
  422. $file_destination = $path . '/' . basename($location);
  423. if (!file_exists($file_destination) || $synchronize) {
  424. // Download the latest tracking code.
  425. try {
  426. $data = \Drupal::httpClient()
  427. ->get($location)
  428. ->getBody(TRUE);
  429. if (file_exists($file_destination)) {
  430. // Synchronize tracking code and and replace local file if outdated.
  431. $data_hash_local = Crypt::hashBase64(file_get_contents($file_destination));
  432. $data_hash_remote = Crypt::hashBase64($data);
  433. // Check that the files directory is writable.
  434. if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
  435. // Save updated tracking code file to disk.
  436. file_unmanaged_save_data($data, $file_destination, FILE_EXISTS_REPLACE);
  437. // Based on Drupal Core class AssetDumper.
  438. if (extension_loaded('zlib') && \Drupal::config('system.performance')->get('js.gzip')) {
  439. file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE);
  440. }
  441. \Drupal::logger('matomo')->info('Locally cached tracking code file has been updated.');
  442. // Change query-strings on css/js files to enforce reload for all
  443. // users.
  444. _drupal_flush_css_js();
  445. }
  446. }
  447. else {
  448. // Check that the files directory is writable.
  449. if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
  450. // There is no need to flush JS here as core refreshes JS caches
  451. // automatically, if new files are added.
  452. file_unmanaged_save_data($data, $file_destination, FILE_EXISTS_REPLACE);
  453. // Based on Drupal Core class AssetDumper.
  454. if (extension_loaded('zlib') && \Drupal::config('system.performance')->get('js.gzip')) {
  455. file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE);
  456. }
  457. \Drupal::logger('matomo')->info('Locally cached tracking code file has been saved.');
  458. // Return the local JS file path.
  459. return file_url_transform_relative(file_create_url($file_destination));
  460. }
  461. }
  462. }
  463. catch (RequestException $exception) {
  464. watchdog_exception('matomo', $exception);
  465. }
  466. }
  467. else {
  468. // Return the local JS file path.
  469. return file_url_transform_relative(file_create_url($file_destination));
  470. }
  471. }
  472. /**
  473. * Delete cached files and directory.
  474. */
  475. function matomo_clear_js_cache() {
  476. $path = 'public://matomo';
  477. if (file_prepare_directory($path)) {
  478. file_scan_directory($path, '/.*/', ['callback' => 'file_unmanaged_delete']);
  479. \Drupal::service('file_system')->rmdir($path);
  480. // Change query-strings on css/js files to enforce reload for all users.
  481. _drupal_flush_css_js();
  482. \Drupal::logger('matomo')->info('Local cache has been purged.');
  483. }
  484. }
  485. /**
  486. * Tracking visibility check for an user object.
  487. *
  488. * @param object $account
  489. * A user object containing an array of roles to check.
  490. *
  491. * @return bool
  492. * TRUE if the current user is being tracked by Matomo, otherwise FALSE.
  493. */
  494. function _matomo_visibility_user($account) {
  495. $config = \Drupal::config('matomo.settings');
  496. $enabled = FALSE;
  497. // Is current user a member of a role that should be tracked?
  498. if (_matomo_visibility_roles($account)) {
  499. // Use the user's block visibility setting, if necessary.
  500. if (($visibility_user_account_mode = $config->get('visibility.user_account_mode')) != 0) {
  501. $user_data_matomo = \Drupal::service('user.data')->get('matomo', $account->id());
  502. if ($account->id() && isset($user_data_matomo['user_account_users'])) {
  503. $enabled = $user_data_matomo['user_account_users'];
  504. }
  505. else {
  506. $enabled = ($visibility_user_account_mode == 1);
  507. }
  508. }
  509. else {
  510. $enabled = TRUE;
  511. }
  512. }
  513. return $enabled;
  514. }
  515. /**
  516. * Tracking visibility check for user roles.
  517. *
  518. * Based on visibility setting this function returns TRUE if Matomo code should
  519. * be added for the current role and otherwise FALSE.
  520. *
  521. * @param object $account
  522. * A user object containing an array of roles to check.
  523. *
  524. * @return bool
  525. * TRUE if JS code should be added for the current role and otherwise FALSE.
  526. */
  527. function _matomo_visibility_roles($account) {
  528. $config = \Drupal::config('matomo.settings');
  529. $enabled = $visibility_user_role_mode = $config->get('visibility.user_role_mode');
  530. $user_role_roles = $config->get('visibility.user_role_roles');
  531. if (count($user_role_roles) > 0) {
  532. // One or more roles are selected.
  533. foreach (array_values($account->getRoles()) as $user_role) {
  534. // Is the current user a member of one of these roles?
  535. if (in_array($user_role, $user_role_roles)) {
  536. // Current user is a member of a role that should be tracked/excluded
  537. // from tracking.
  538. $enabled = !$visibility_user_role_mode;
  539. break;
  540. }
  541. }
  542. }
  543. else {
  544. // No role is selected for tracking, therefore all roles should be tracked.
  545. $enabled = TRUE;
  546. }
  547. return $enabled;
  548. }
  549. /**
  550. * Tracking visibility check for pages.
  551. *
  552. * Based on visibility setting this function returns TRUE if JS code should
  553. * be added to the current page and otherwise FALSE.
  554. */
  555. function _matomo_visibility_pages() {
  556. static $page_match;
  557. // Cache visibility result if function is called more than once.
  558. if (!isset($page_match)) {
  559. $config = \Drupal::config('matomo.settings');
  560. $visibility_request_path_mode = $config->get('visibility.request_path_mode');
  561. $visibility_request_path_pages = $config->get('visibility.request_path_pages');
  562. // Match path if necessary.
  563. if (!empty($visibility_request_path_pages)) {
  564. // Convert path to lowercase. This allows comparison of the same path
  565. // with different case. Ex: /Page, /page, /PAGE.
  566. $pages = Unicode::strtolower($visibility_request_path_pages);
  567. if ($visibility_request_path_mode < 2) {
  568. // Compare the lowercase path alias (if any) and internal path.
  569. $path = \Drupal::service('path.current')->getPath();
  570. $path_alias = Unicode::strtolower(\Drupal::service('path.alias_manager')->getAliasByPath($path));
  571. $page_match = \Drupal::service('path.matcher')->matchPath($path_alias, $pages) || (($path != $path_alias) && \Drupal::service('path.matcher')->matchPath($path, $pages));
  572. // When $visibility_request_path_mode has a value of 0, the tracking
  573. // code is displayed on all pages except those listed in $pages. When
  574. // set to 1, it is displayed only on those pages listed in $pages.
  575. $page_match = !($visibility_request_path_mode xor $page_match);
  576. }
  577. elseif (\Drupal::moduleHandler()->moduleExists('php')) {
  578. $page_match = php_eval($visibility_request_path_pages);
  579. }
  580. else {
  581. $page_match = FALSE;
  582. }
  583. }
  584. else {
  585. $page_match = TRUE;
  586. }
  587. }
  588. return $page_match;
  589. }
  590. /**
  591. * Get the page titles trail for the current page.
  592. *
  593. * Based on menu_get_active_breadcrumb().
  594. *
  595. * @return array
  596. * All page titles, including current page.
  597. */
  598. function _matomo_get_hierarchy_titles() {
  599. $titles = [];
  600. $path = Url::fromRoute('<current>')->toString();
  601. $config = \Drupal::config('system.site');
  602. $matomo_conf = \Drupal::config('matomo.settings');
  603. // No breadcrumb for the front page.
  604. if (($path === Url::fromUserInput($config->get('page.front'))->toString())) {
  605. return $titles;
  606. }
  607. // Load up the menu tree.
  608. // TODO: Check this is a sane approach.
  609. $menu_tree = \Drupal::menuTree();
  610. $menu_name = \Drupal::config('system.menu.main')->get('id');
  611. // Build the typical default set of menu tree parameters.
  612. $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
  613. // Load the tree based on this set of parameters.
  614. $tree = $menu_tree->load($menu_name, $parameters);
  615. // Transform the tree using the manipulators.
  616. $manipulators = [
  617. // Only show links that are accessible for the current user.
  618. ['callable' => 'menu.default_tree_manipulators:checkAccess'],
  619. // Use the default sorting of menu links.
  620. ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
  621. // Fatten the menu.
  622. ['callable' => 'menu.default_tree_manipulators:flatten'],
  623. ];
  624. $tree = $menu_tree->transform($tree, $manipulators);
  625. if (!empty($tree)) {
  626. foreach ($tree as $menu_item) {
  627. // If the item is in the active trail and we don't have a front page link
  628. // when we have set to exclude home from the breadcrumbs then add the
  629. // title.
  630. if ($menu_item->inActiveTrail && !($matomo_conf->get('page_title_hierarchy_exclude_home') && $menu_item->link->getRouteName() == '<front>')) {
  631. $titles[] = $menu_item->link->getTitle();
  632. }
  633. }
  634. }
  635. return $titles;
  636. }