piwik.module 27 KB

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