A suggestion to simply extract/merge this functionality from/with another plugin.
[ikiwiki] / IkiWiki / Plugin / relativedate.pm
1 #!/usr/bin/perl
2 package IkiWiki::Plugin::relativedate;
3
4 use warnings;
5 no warnings 'redefine';
6 use strict;
7 use IkiWiki 3.00;
8 use POSIX;
9 use Encode;
10
11 sub import {
12         add_underlay("javascript");
13         hook(type => "getsetup", id => "relativedate", call => \&getsetup);
14         hook(type => "format", id => "relativedate", call => \&format);
15         inject(name => "IkiWiki::displaytime", call => \&mydisplaytime);
16 }
17
18 sub getsetup () {
19         return
20                 plugin => {
21                         safe => 1,
22                         rebuild => 1,
23                 },
24 }
25
26 sub format (@) {
27         my %params=@_;
28
29         if (! ($params{content}=~s!^(<body>)!$1.include_javascript($params{page})!em)) {
30                 # no </body> tag, probably in preview mode
31                 $params{content}=include_javascript($params{page}, 1).$params{content};
32         }
33         return $params{content};
34 }
35
36 sub include_javascript ($;$) {
37         my $page=shift;
38         my $absolute=shift;
39         
40         return '<script src="'.urlto("ikiwiki.js", $page, $absolute).
41                 '" type="text/javascript" charset="utf-8"></script>'."\n".
42                 '<script src="'.urlto("relativedate.js", $page, $absolute).
43                 '" type="text/javascript" charset="utf-8"></script>';
44 }
45
46 sub mydisplaytime ($;$) {
47         my $time=shift;
48         my $format=shift;
49
50         # This needs to be in a form that can be parsed by javascript.
51         # Being fairly human readable is also nice, as it will be exposed
52         # as the title if javascript is not available.
53         my $gmtime=decode_utf8(POSIX::strftime("%a, %d %b %Y %H:%M:%S %z",
54                         localtime($time)));
55
56         return '<span class="relativedate" title="'.$gmtime.'">'.
57                 IkiWiki::formattime($time, $format).'</span>';
58 }
59
60 1