* Add taglink preprocessor directive, supporting visible tag links.
[ikiwiki] / IkiWiki / Plugin / tag.pm
1 #!/usr/bin/perl
2 # Ikiwiki tag plugin.
3 package IkiWiki::Plugin::tag;
4
5 use warnings;
6 use strict;
7 use IkiWiki 2.00;
8
9 my %tags;
10
11 sub import { #{{{
12         hook(type => "getopt", id => "tag", call => \&getopt);
13         hook(type => "preprocess", id => "tag", call => \&preprocess_tag, scan => 1);
14         hook(type => "preprocess", id => "taglink", call => \&preprocess_taglink, scan => 1);
15         hook(type => "pagetemplate", id => "tag", call => \&pagetemplate);
16 } # }}}
17
18 sub getopt () { #{{{
19         eval q{use Getopt::Long};
20         error($@) if $@;
21         Getopt::Long::Configure('pass_through');
22         GetOptions("tagbase=s" => \$config{tagbase});
23 } #}}}
24
25 sub tagpage ($) { #{{{
26         my $tag=shift;
27                         
28         if (exists $config{tagbase} &&
29             defined $config{tagbase}) {
30                 $tag=$config{tagbase}."/".$tag;
31         }
32
33         return $tag;
34 } #}}}
35
36 sub preprocess_tag (@) { #{{{
37         if (! @_) {
38                 return "";
39         }
40         my %params=@_;
41         my $page = $params{page};
42         delete $params{page};
43         delete $params{destpage};
44         delete $params{preview};
45
46         foreach my $tag (keys %params) {
47                 $tag=IkiWiki::linkpage($tag);
48                 $tags{$page}{$tag}=1;
49                 # hidden WikiLink
50                 push @{$links{$page}}, tagpage($tag);
51         }
52                 
53         return "";
54 } # }}}
55
56 sub preprocess_taglink (@) { #{{{
57         if (! @_) {
58                 return "";
59         }
60         preprocess_tag(@_);
61         my %params=@_;
62         delete $params{page};
63         delete $params{destpage};
64         delete $params{preview};
65         return join(" ", map { "[[$_]]" } keys %params);
66 } # }}}
67
68 sub pagetemplate (@) { #{{{
69         my %params=@_;
70         my $page=$params{page};
71         my $destpage=$params{destpage};
72         my $template=$params{template};
73
74         $template->param(tags => [
75                 map { 
76                         link => htmllink($page, $destpage, tagpage($_),
77                                         rel => "tag")
78                 }, sort keys %{$tags{$page}}
79         ]) if exists $tags{$page} && %{$tags{$page}} && $template->query(name => "tags");
80
81         if ($template->query(name => "categories")) {
82                 # It's an rss/atom template. Add any categories.
83                 if (exists $tags{$page} && %{$tags{$page}}) {
84                         $template->param(categories => [map { category => $_ },
85                                 sort keys %{$tags{$page}}]);
86                 }
87         }
88 } # }}}
89
90 1