Introduced Piwik as an optional plugin

Change-Id: I57d6961ac9e922e1a661ea94a5a6c7563688ed0b
diff --git a/lib/Kalamar.pm b/lib/Kalamar.pm
index 83cea41..68b73dc 100644
--- a/lib/Kalamar.pm
+++ b/lib/Kalamar.pm
@@ -5,6 +5,7 @@
 use Mojo::File;
 use Mojo::JSON 'decode_json';
 use Mojo::Util qw/url_escape/;
+use List::Util 'none';
 
 # Minor version - may be patched from package.json
 our $VERSION = '0.30';
@@ -149,7 +150,6 @@
     'ClientIP',                  # Get client IP from X-Forwarded-For
     'ClosedRedirect',            # Redirect with OpenRedirect protection
     'TagHelpers::ContentBlock',  # Flexible content blocks
-    'Piwik'                      # Integrate Piwik/Matomo Analytics
   ) {
     $self->plugin($_);
   };
@@ -171,6 +171,23 @@
     $self->plugin('MailException' => $self->config('MailException'));
   };
 
+  # Load further plugins
+  if (exists $conf->{'plugins'}) {
+    foreach (@{$conf->{'plugins'}}) {
+      $self->plugin('Kalamar::Plugin::' . $_);
+    };
+  };
+
+  # Deprecated Legacy code -
+  # TODO: Remove 2019-02
+  if ($self->config('Piwik') &&
+        none { $_ eq 'Piwik' } @{$conf->{plugins} // []}) {
+    use Data::Dumper;
+    warn Dumper $self->config('Piwik');
+    $self->log->error('Piwik is no longer considered a mandatory plugin');
+    $self->plugin('Piwik');
+  };
+
   # Configure documentation navigation
   my $navi = Mojo::File->new($self->home->child('templates','doc','navigation.json'))->slurp;
   $self->config(navi => decode_json($navi)) if $navi;
diff --git a/lib/Kalamar/Plugin/Piwik.pm b/lib/Kalamar/Plugin/Piwik.pm
new file mode 100644
index 0000000..a4dfb68
--- /dev/null
+++ b/lib/Kalamar/Plugin/Piwik.pm
@@ -0,0 +1,44 @@
+package Kalamar::Plugin::Piwik;
+use Mojo::Base 'Mojolicious::Plugin';
+
+sub register {
+  my ($plugin, $mojo, $param) = @_;
+
+  # Load Piwik if not yet loaded
+  unless (exists $mojo->renderer->helpers->{piwik_tag}) {
+    $mojo->plugin('Piwik');
+  };
+
+  # Add opt-out to FAQ
+  $mojo->content_block(
+    'faq' => {
+      inline => '<section name="piwik-opt-out">' .
+        '<h3><%= loc("Piwik_HowToOptOut", "How can I opt-out?") %></h3>' .
+        '<%= piwik_tag "opt-out" %>' .
+        '</section>'
+      }
+  );
+
+  # Add piwik tag to scripts
+  $mojo->content_block(scripts => {
+    inline => '<%= piwik_tag %>'
+  });
+
+  # Add event handler for korap requests
+  $mojo->content_block(scripts => {
+    inline => <<'SCRIPT'
+%= javascript begin
+window.addEventListener('korapRequest', function(e) {
+  _paq.push(['setReferrerUrl', location.href]);
+  _paq.push(['setCustomUrl', e.detail.url]);
+  _paq.push(['trackPageView'])
+% end
+SCRIPT
+  });
+};
+
+
+1;
+
+
+__END__