Improve Piwik to track all requests anonymously

Change-Id: I5c1d96c8f911e6208d8bc024ded799b1a9290c1d
diff --git a/Changes b/Changes
index 4bd7278..8d88e0a 100755
--- a/Changes
+++ b/Changes
@@ -1,5 +1,6 @@
-0.32 2018-12-14
+0.32 2018-12-19
         - Support attachements in metadata fields (#77).
+        - Added ping request option to Piwik.
 
 0.31 2018-11-30
         - Update to Mojolicious >= 8.06.
diff --git a/Makefile.PL b/Makefile.PL
index 155b0c5..3768bdd 100644
--- a/Makefile.PL
+++ b/Makefile.PL
@@ -20,13 +20,14 @@
     'Mojolicious::Plugin::ClosedRedirect' => 0.14,
     'Mojolicious::Plugin::Notifications' => 1.01,
     'Mojolicious::Plugin::MailException' => 0.20,
+    'Mojolicious::Plugin::Util::RandomString' => 0.08,
     'Mojolicious::Plugin::CHI' => 0.20,
     'Mojolicious::Plugin::ClientIP' => 0.01,
     'Cache::FastMmap' => 0,
     'Mojo::JWT' => 0.05,
 
     # Required for bundled plugins
-    'Mojolicious::Plugin::Piwik' => 0.24,
+    'Mojolicious::Plugin::Piwik' => 0.25,
 
     # Currently on GitHub only (github.com/akron)
     'Mojolicious::Plugin::Localize' => 0.20,
diff --git a/lib/Kalamar/Plugin/Piwik.pm b/lib/Kalamar/Plugin/Piwik.pm
index bffbbdb..9b0c909 100644
--- a/lib/Kalamar/Plugin/Piwik.pm
+++ b/lib/Kalamar/Plugin/Piwik.pm
@@ -4,11 +4,29 @@
 sub register {
   my ($plugin, $mojo, $param) = @_;
 
+  # Load parameter from Config file
+  if (my $config_param = $mojo->config('Kalamar')) {
+    if ($config_param->{Piwik}) {
+      $param = {
+        %$param,
+        %{$config_param->{Piwik}}
+      };
+    };
+  };
+
   # Load Piwik if not yet loaded
   unless (exists $mojo->renderer->helpers->{piwik_tag}) {
     $mojo->plugin('Piwik');
   };
 
+  # Add random string plugin
+  $mojo->plugin('Util::RandomString' => {
+    piwik_rand_id => {
+      alphabet => '0123456789abcdef',
+      length   => 16
+    }
+  });
+
   # Add opt-out to FAQ
   $mojo->content_block(
     'faq' => {
@@ -39,6 +57,39 @@
 % }
 SCRIPT
   });
+
+
+  # If all requests should be pinged,
+  # establish this hook
+  if ($param->{ping_requests}) {
+    $mojo->hook(
+      after_render => sub {
+        my $c = shift;
+
+        # Only track valid routes
+        my $route = $c->current_route or return;
+
+        # This won't forward personalized information
+        my $hash = {
+          action_url => $c->url_for->to_abs,
+          action_name => $route,
+          ua => '',
+          urlref => '',
+          send_image => 0,
+          dnt => 0,
+          uid => $c->random_string('piwik_rand_id')
+        };
+
+        # Overrid ping site id
+        if ($param->{ping_site_id}) {
+          $hash->{idsite} = $param->{ping_site_id}
+        };
+
+        # Send track
+        $c->piwik->api_p(Track => $hash)->wait;
+      }
+    );
+  };
 };
 
 
@@ -46,3 +97,13 @@
 
 
 __END__
+
+# Parameters can be loaded from
+# {
+#   Kalamar => {
+#     Piwik => {
+#       ping_requests => 1,
+#       ping_site_id => 12
+#     }
+#   }
+# }