2 package IkiWiki::Plugin::google;
4 # Google services plugin. Currently allows the inclusion of a search form
5 # and Google Analytics.
13 hook(type => "getsetup", id => "google", call => \&getsetup);
14 hook(type => "checkconfig", id => "google", call => \&checkconfig);
15 hook(type => "pagetemplate", id => "google", call => \&pagetemplate);
16 hook(type => "format", id => "google", call => \&format);
26 google_sitesearch => {
29 description => "Enable or disable the inclusion of a search form in all pages (default)",
34 google_analytics_account => {
36 example => 'UA-00000-0',
37 description => "Account/Web Property ID to use by default for Google Analytics code",
44 sub sitesearch_enabled() {
45 return 1 unless defined $config{google_sitesearch};
46 return $config{google_sitesearch};
50 # nothing to do if sitesearch is not enabled
51 return unless sitesearch_enabled();
53 if (! length $config{url}) {
54 error(sprintf(gettext("Must specify %s when using the %s plugin"), "url", 'google'));
57 # This is a mass dependency, so if the search form template
58 # changes, every page is rebuilt.
59 add_depends("", "templates/googleform.tmpl");
63 sub pagetemplate (@) {
64 # nothing to do if sitesearch is not enabled
65 return unless sitesearch_enabled();
68 my $page=$params{page};
69 my $template=$params{template};
71 # Add search box to page header.
72 if ($template->query(name => "searchform")) {
73 if (! defined $form) {
74 my $searchform = template("googleform.tmpl", blind_cache => 1);
75 $searchform->param(url => $config{url});
76 $searchform->param(html5 => $config{html5});
77 $form=$searchform->output;
80 $template->param(searchform => $form);
87 # Add Google Analytics' javascript to all pages, if an account is defined
88 if (defined $config{google_analytics_account}) {
89 if (! ($params{content}=~s!^(<body[^>]*>)!$1.ga_js()!em)) {
90 # no <body> tag, probably in preview mode
91 $params{content}=ga_js().$params{content};
94 return $params{content};
99 return $ga_js_cached if defined $ga_js_cached;
101 return unless defined $config{google_analytics_account};
103 my $account = $config{google_analytics_account};
105 # This is Google Analytics' standard javascript snippet to include their
106 # external javascript file, asynchronously.
107 return $ga_js_cached=<<"EOF";
108 <script type="text/javascript">
109 <!--//--><![CDATA[//><!--
110 var _gaq = _gaq || [];
111 _gaq.push(['_setAccount', '$account']);
112 _gaq.push(['_trackPageview']);
115 var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
116 ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
117 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);