matomo.module 28 KB

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