1<?php
2
3use ComboStrap\Canonical;
4use ComboStrap\Site;
5use ComboStrap\SiteConfig;
6use ComboStrap\WikiPath;
7use ComboStrap\ExceptionNotFound;
8use ComboStrap\MarkupPath;
9use ComboStrap\PluginUtility;
10
11if (!defined('DOKU_INC')) die();
12
13/**
14 *
15 *
16 */
17class action_plugin_combo_canonical extends DokuWiki_Action_Plugin
18{
19
20    const CONF_CANONICAL_FOR_GA_PAGE_VIEW = "useCanonicalValueForGoogleAnalyticsPageView";
21    const CANONICAL = Canonical::PROPERTY_NAME;
22
23
24    function __construct()
25    {
26        // enable direct access to language strings
27        // ie $this->lang
28        $this->setupLocale();
29    }
30
31    public function register(Doku_Event_Handler $controller)
32    {
33
34        /**
35         * Add canonical to javascript
36         * The {@link jsinfo()} is called in the {@link tpl_metaheaders()}
37         * 'TPL_METAHEADER_OUTPUT' event has already the script with the JSINFO
38         * 'TPL_ACT_RENDER' is triggered just before
39         */
40        $controller->register_hook('TPL_ACT_RENDER', 'AFTER', $this, 'addCanonicalToJavascript', array());
41
42    }
43
44
45    /**
46     * Add the canonical value to JSON
47     * to be able to report only on canonical value and not on path
48     * @param $event
49     * @noinspection SpellCheckingInspection
50     */
51    function addCanonicalToJavascript($event)
52    {
53
54        try {
55            $page = MarkupPath::createFromRequestedPage();
56        } catch (ExceptionNotFound $e) {
57            return;
58        }
59        global $JSINFO;
60        try {
61            $canonical = $page->getCanonical()->toAbsoluteId();
62            $JSINFO[Canonical::PROPERTY_NAME] = $canonical;
63        } catch (ExceptionNotFound $e) {
64            return;
65        }
66
67        if (isset($JSINFO["ga"]) && SiteConfig::getConfValue(self::CONF_CANONICAL_FOR_GA_PAGE_VIEW, 1)) {
68            //
69            // The path portion of a URL. This value should start with a slash (/) character.
70            // As said here
71            // https://developers.google.com/analytics/devguides/collection/analyticsjs/pages#pageview_fields
72            //
73            //
74            // For the modification instructions
75            // https://developers.google.com/analytics/devguides/collection/analyticsjs/pages#pageview_fields
76            $pageViewCanonical = str_replace(WikiPath::NAMESPACE_SEPARATOR_DOUBLE_POINT, "/", $canonical);
77            if ($pageViewCanonical[0] != "/") {
78                $pageViewCanonical = "/$pageViewCanonical";
79            }
80            $JSINFO["ga"]["pageview"] = $pageViewCanonical;
81        }
82
83    }
84
85}
86