calendar plugin: Autocreate archive pages if needed
[ikiwiki.git] / IkiWiki / Plugin / calendar.pm
1 #! /usr/bin/perl
2 # Copyright (c) 2006, 2007 Manoj Srivastava <srivasta@debian.org>
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
17
18 require 5.002;
19 package IkiWiki::Plugin::calendar;
20
21 use warnings;
22 use strict;
23 use IkiWiki 3.00;
24 use Time::Local;
25
26 my $time=time;
27 my @now=localtime($time);
28
29 sub import {
30         hook(type => "checkconfig", id => "calendar", call => \&checkconfig);
31         hook(type => "getsetup", id => "calendar", call => \&getsetup);
32         hook(type => "needsbuild", id => "calendar", call => \&needsbuild);
33         hook(type => "preprocess", id => "calendar", call => \&preprocess);
34         hook(type => "scan", id => "calendar", call => \&scan);
35 }
36
37 sub getsetup () {
38         return
39                 plugin => {
40                         safe => 1,
41                         rebuild => undef,
42                         section => "widget",
43                 },
44                 archivebase => {
45                         type => "string",
46                         example => "archives",
47                         description => "base of the archives hierarchy",
48                         safe => 1,
49                         rebuild => 1,
50                 },
51                 archive_pagespec => {
52                         type => "pagespec",
53                         example => "page(posts/*) and !*/Discussion",
54                         description => "PageSpec of pages to include in the archives, if option `calendar_autocreate` is true.",
55                         link => 'ikiwiki/PageSpec',
56                         safe => 1,
57                         rebuild => 0,
58                 },
59                 calendar_autocreate => {
60                         type => "boolean",
61                         example => 1,
62                         description => "autocreate new calendar pages?",
63                         safe => 1,
64                         rebuild => undef,
65                 },
66                 calendar_autocreate_commit => {
67                         type => "boolean",
68                         example => 1,
69                         default => 1,
70                         description => "commit autocreated calendar pages",
71                         safe => 1,
72                         rebuild => 0,
73                 },
74 }
75
76 sub checkconfig () {
77         if (! defined $config{calendar_autocreate}) {
78                 $config{calendar_autocreate} = defined $config{archivebase} || defined $config{calendar_autocreate_commit};
79         }
80         if (! defined $config{calendar_autocreate_commit}) {
81                 $config{calendar_autocreate_commit} = 1;
82         }
83         if (! defined $config{archive_pagespec}) {
84                 $config{archive_pagespec} = '*';
85         }
86         if (! defined $config{archivebase}) {
87                 $config{archivebase} = 'archives';
88         }
89 }
90
91 sub is_leap_year (@) {
92         my %params=@_;
93         return ($params{year} % 4 == 0 && (($params{year} % 100 != 0) || $params{year} % 400 == 0));
94 }
95
96 sub month_days {
97         my %params=@_;
98         my $days_in_month = (31,28,31,30,31,30,31,31,30,31,30,31)[$params{month}-1];
99         if ($params{month} == 2 && is_leap_year(%params)) {
100                 $days_in_month++;
101         }
102         return $days_in_month;
103 }
104
105 sub autocreate {
106         my ($page, $pagefile, $year, $month) = @_;
107         my $message=sprintf(gettext("creating calendar page %s"), $page);
108         debug($message);
109
110         my $template;
111         if (defined $month) {
112                 $template=template("calendarmonth.tmpl");
113         } else {
114                 $template=template("calendaryear.tmpl");
115         }
116         $template->param(year => $year);
117         $template->param(month => $month) if defined $month;
118         $template->param(pagespec => $config{archive_pagespec});
119
120         my $dir = $config{srcdir};
121         if (! $config{calendar_autocreate_commit}) {
122                 $dir = $IkiWiki::Plugin::transient::transientdir;
123         }
124
125         writefile($pagefile, $dir, $template->output);
126         if ($config{rcs} && $config{calendar_autocreate_commit}) {
127                 IkiWiki::disable_commit_hook();
128                 IkiWiki::rcs_add($pagefile);
129                 IkiWiki::rcs_commit_staged(message => $message);
130                 IkiWiki::enable_commit_hook();
131         }
132 }
133
134 sub calendarlink($;$) {
135         my ($year, $month) = @_;
136         if (defined $month) {
137                 return $config{archivebase} . "/" . $year . "/" . $month;
138         } else {
139                 return $config{archivebase} . "/" . $year;
140         }
141 }
142
143 sub gencalendaryear {
144         my $year = shift;
145
146         if ($config{calendar_autocreate}) {
147
148                 # Building year page
149                 my $page = calendarlink($year);
150                 my $pagefile = newpagefile($page, $config{default_pageext});
151                 add_autofile(
152                         $pagefile, "calendar",
153                         sub {return autocreate($page, $pagefile, $year);}
154                 );
155
156                 # Building month pages
157                 foreach my $month (qw{01 02 03 04 05 06 07 08 09 10 11 12}) {
158                         my $page = calendarlink($year, $month);
159                         my $pagefile = newpagefile($page, $config{default_pageext});
160                         add_autofile(
161                                 $pagefile, "calendar",
162                                 sub {return autocreate($page, $pagefile, $year, $month);}
163                         );
164                 }
165
166                 # Filling potential gaps in years (e.g. calendar goes from 2010 to 2014,
167                 # and we just added year 2005. We have to had years 2006 to 2009.
168                 if (not exists $wikistate{calendar}{minyear}) {
169                         $wikistate{calendar}{minyear} = $year;
170                 } elsif ($wikistate{calendar}{minyear} > $year) {
171                         gencalendaryear($year + 1);
172                         $wikistate{calendar}{minyear} -= 1;
173                 }
174                 if (not exists $wikistate{calendar}{maxyear}) {
175                         $wikistate{calendar}{maxyear} = $year;
176                 }
177                 if ($wikistate{calendar}{maxyear} < $year) {
178                         gencalendaryear($year - 1);
179                         $wikistate{calendar}{maxyear} += 1;
180                 }
181         }
182 }
183
184 sub format_month (@) {
185         my %params=@_;
186
187         my %linkcache;
188         foreach my $p (pagespec_match_list($params{page}, 
189                                 "creation_year($params{year}) and creation_month($params{month}) and ($params{pages})",
190                                 # add presence dependencies to update
191                                 # month calendar when pages are added/removed
192                                 deptype => deptype("presence"))) {
193                 my $mtime = $IkiWiki::pagectime{$p};
194                 my @date  = localtime($mtime);
195                 my $mday  = $date[3];
196                 my $month = $date[4] + 1;
197                 my $year  = $date[5] + 1900;
198                 my $mtag  = sprintf("%02d", $month);
199
200                 if (! $linkcache{"$year/$mtag/$mday"}) {
201                         $linkcache{"$year/$mtag/$mday"} = [];
202                 }
203                 push(@{$linkcache{"$year/$mtag/$mday"}}, $p);
204         }
205                 
206         my $pmonth = $params{month} - 1;
207         my $nmonth = $params{month} + 1;
208         my $pyear  = $params{year};
209         my $nyear  = $params{year};
210
211         # Adjust for January and December
212         if ($params{month} == 1) {
213                 $pmonth = 12;
214                 $pyear--;
215         }
216         if ($params{month} == 12) {
217                 $nmonth = 1;
218                 $nyear++;
219         }
220
221         # Add padding.
222         $pmonth=sprintf("%02d", $pmonth);
223         $nmonth=sprintf("%02d", $nmonth);
224
225         my $calendar="\n";
226
227         # When did this month start?
228         my @monthstart = localtime(timelocal(0,0,0,1,$params{month}-1,$params{year}-1900));
229
230         my $future_dom = 0;
231         my $today      = 0;
232         if ($params{year} == $now[5]+1900 && $params{month} == $now[4]+1) {
233                 $future_dom = $now[3]+1;
234                 $today      = $now[3];
235         }
236
237         # Find out month names for this, next, and previous months
238         my $monthabbrev=strftime_utf8("%b", @monthstart);
239         my $monthname=strftime_utf8("%B", @monthstart);
240         my $pmonthname=strftime_utf8("%B", localtime(timelocal(0,0,0,1,$pmonth-1,$pyear-1900)));
241         my $nmonthname=strftime_utf8("%B", localtime(timelocal(0,0,0,1,$nmonth-1,$nyear-1900)));
242
243         my $archivebase = 'archives';
244         $archivebase = $config{archivebase} if defined $config{archivebase};
245         $archivebase = $params{archivebase} if defined $params{archivebase};
246   
247         # Calculate URL's for monthly archives.
248         my ($url, $purl, $nurl)=("$monthname $params{year}",'','');
249         if (exists $pagesources{"$archivebase/$params{year}/$params{month}"}) {
250                 $url = htmllink($params{page}, $params{destpage}, 
251                         "$archivebase/$params{year}/".$params{month},
252                         noimageinline => 1,
253                         linktext => "$monthabbrev $params{year}",
254                         title => $monthname);
255         }
256         add_depends($params{page}, "$archivebase/$params{year}/$params{month}",
257                 deptype("presence"));
258         if (exists $pagesources{"$archivebase/$pyear/$pmonth"}) {
259                 $purl = htmllink($params{page}, $params{destpage}, 
260                         "$archivebase/$pyear/$pmonth",
261                         noimageinline => 1,
262                         linktext => "\&larr;",
263                         title => $pmonthname);
264         }
265         add_depends($params{page}, "$archivebase/$pyear/$pmonth",
266                 deptype("presence"));
267         if (exists $pagesources{"$archivebase/$nyear/$nmonth"}) {
268                 $nurl = htmllink($params{page}, $params{destpage}, 
269                         "$archivebase/$nyear/$nmonth",
270                         noimageinline => 1,
271                         linktext => "\&rarr;",
272                         title => $nmonthname);
273         }
274         add_depends($params{page}, "$archivebase/$nyear/$nmonth",
275                 deptype("presence"));
276
277         # Start producing the month calendar
278         $calendar=<<EOF;
279 <table class="month-calendar">
280         <tr>
281         <th class="month-calendar-arrow">$purl</th>
282         <th class="month-calendar-head" colspan="5">$url</th>
283         <th class="month-calendar-arrow">$nurl</th>
284         </tr>
285         <tr>
286 EOF
287
288         # Suppose we want to start the week with day $week_start_day
289         # If $monthstart[6] == 1
290         my $week_start_day = $params{week_start_day};
291
292         my $start_day = 1 + (7 - $monthstart[6] + $week_start_day) % 7;
293         my %downame;
294         my %dowabbr;
295         for my $dow ($week_start_day..$week_start_day+6) {
296                 my @day=localtime(timelocal(0,0,0,$start_day++,$params{month}-1,$params{year}-1900));
297                 my $downame = strftime_utf8("%A", @day);
298                 my $dowabbr = substr($downame, 0, 1);
299                 $downame{$dow % 7}=$downame;
300                 $dowabbr{$dow % 7}=$dowabbr;
301                 $calendar.= qq{\t\t<th class="month-calendar-day-head $downame" title="$downame">$dowabbr</th>\n};
302         }
303
304         $calendar.=<<EOF;
305         </tr>
306 EOF
307
308         my $wday;
309         # we start with a week_start_day, and skip until we get to the first
310         for ($wday=$week_start_day; $wday != $monthstart[6]; $wday++, $wday %= 7) {
311                 $calendar.=qq{\t<tr>\n} if $wday == $week_start_day;
312                 $calendar.=qq{\t\t<td class="month-calendar-day-noday $downame{$wday}">&nbsp;</td>\n};
313         }
314
315         # At this point, either the first is a week_start_day, in which case
316         # nothing has been printed, or else we are in the middle of a row.
317         for (my $day = 1; $day <= month_days(year => $params{year}, month => $params{month});
318              $day++, $wday++, $wday %= 7) {
319                 # At this point, on a week_start_day, we close out a row,
320                 # and start a new one -- unless it is week_start_day on the
321                 # first, where we do not close a row -- since none was started.
322                 if ($wday == $week_start_day) {
323                         $calendar.=qq{\t</tr>\n} unless $day == 1;
324                         $calendar.=qq{\t<tr>\n};
325                 }
326                 
327                 my $tag;
328                 my $key="$params{year}/$params{month}/$day";
329                 if (defined $linkcache{$key}) {
330                         if ($day == $today) {
331                                 $tag='month-calendar-day-this-day';
332                         }
333                         else {
334                                 $tag='month-calendar-day-link';
335                         }
336                         $calendar.=qq{\t\t<td class="$tag $downame{$wday}">};
337                         $calendar.=qq{<div class='popup'>$day<div class='balloon'>};
338                         # Several postings on this page
339                         $calendar.=qq{<ul>};
340                         foreach my $page (@{$linkcache{$key}}) {
341                                 $calendar.= qq{\n\t\t\t<li>};
342                                 my $title;
343                                 if (exists $pagestate{$page}{meta}{title}) {
344                                         $title = "$pagestate{$page}{meta}{title}";
345                                 }
346                                 else {
347                                         $title = pagetitle(IkiWiki::basename($page));
348                                 }
349                                 $calendar.=htmllink($params{page}, $params{destpage}, 
350                                         $page,
351                                         noimageinline => 1,
352                                         linktext => $title,
353                                         title => $title);
354                                 $calendar.= '</li>';
355                         }
356                         $calendar.=qq{\n\t\t</ul>};
357                         $calendar.=qq{</div></div>};
358                         $calendar.=qq{</td>\n};
359                 }
360                 else {
361                         if ($day == $today) {
362                                 $tag='month-calendar-day-this-day';
363                         }
364                         elsif ($day == $future_dom) {
365                                 $tag='month-calendar-day-future';
366                         }
367                         else {
368                                 $tag='month-calendar-day-nolink';
369                         }
370                         $calendar.=qq{\t\t<td class="$tag $downame{$wday}">$day</td>\n};
371                 }
372         }
373
374         # finish off the week
375         for (; $wday != $week_start_day; $wday++, $wday %= 7) {
376                 $calendar.=qq{\t\t<td class="month-calendar-day-noday $downame{$wday}">&nbsp;</td>\n};
377         }
378         $calendar.=<<EOF;
379         </tr>
380 </table>
381 EOF
382
383         return $calendar;
384 }
385
386 sub format_year (@) {
387         my %params=@_;
388
389         my @post_months;
390         foreach my $p (pagespec_match_list($params{page}, 
391                                 "creation_year($params{year}) and ($params{pages})",
392                                 # add presence dependencies to update
393                                 # year calendar's links to months when
394                                 # pages are added/removed
395                                 deptype => deptype("presence"))) {
396                 my $mtime = $IkiWiki::pagectime{$p};
397                 my @date  = localtime($mtime);
398                 my $month = $date[4] + 1;
399
400                 $post_months[$month]++;
401         }
402                 
403         my $calendar="\n";
404         
405         my $pyear = $params{year}  - 1;
406         my $nyear = $params{year}  + 1;
407
408         my $thisyear = $now[5]+1900;
409         my $future_month = 0;
410         $future_month = $now[4]+1 if $params{year} == $thisyear;
411
412         my $archivebase = 'archives';
413         $archivebase = $config{archivebase} if defined $config{archivebase};
414         $archivebase = $params{archivebase} if defined $params{archivebase};
415
416         # calculate URL's for previous and next years
417         my ($url, $purl, $nurl)=("$params{year}",'','');
418         if (exists $pagesources{"$archivebase/$params{year}"}) {
419                 $url = htmllink($params{page}, $params{destpage}, 
420                         "$archivebase/$params{year}",
421                         noimageinline => 1,
422                         linktext => $params{year},
423                         title => $params{year});
424         }
425         add_depends($params{page}, "$archivebase/$params{year}", deptype("presence"));
426         if (exists $pagesources{"$archivebase/$pyear"}) {
427                 $purl = htmllink($params{page}, $params{destpage}, 
428                         "$archivebase/$pyear",
429                         noimageinline => 1,
430                         linktext => "\&larr;",
431                         title => $pyear);
432         }
433         add_depends($params{page}, "$archivebase/$pyear", deptype("presence"));
434         if (exists $pagesources{"$archivebase/$nyear"}) {
435                 $nurl = htmllink($params{page}, $params{destpage}, 
436                         "$archivebase/$nyear",
437                         noimageinline => 1,
438                         linktext => "\&rarr;",
439                         title => $nyear);
440         }
441         add_depends($params{page}, "$archivebase/$nyear", deptype("presence"));
442
443         # Start producing the year calendar
444         my $m=$params{months_per_row}-2;
445         $calendar=<<EOF;
446 <table class="year-calendar">
447         <tr>
448         <th class="year-calendar-arrow">$purl</th>
449         <th class="year-calendar-head" colspan="$m">$url</th>
450         <th class="year-calendar-arrow">$nurl</th>
451         </tr>
452         <tr>
453                 <th class="year-calendar-subhead" colspan="$params{months_per_row}">Months</th>
454         </tr>
455 EOF
456
457         for (my $month = 1; $month <= 12; $month++) {
458                 my @day=localtime(timelocal(0,0,0,15,$month-1,$params{year}-1900));
459                 my $murl;
460                 my $monthname = strftime_utf8("%B", @day);
461                 my $monthabbr = strftime_utf8("%b", @day);
462                 $calendar.=qq{\t<tr>\n}  if ($month % $params{months_per_row} == 1);
463                 my $tag;
464                 my $mtag=sprintf("%02d", $month);
465                 if ($month == $params{month} && $thisyear == $params{year}) {
466                         $tag = 'year-calendar-this-month';
467                 }
468                 elsif ($pagesources{"$archivebase/$params{year}/$mtag"}) {
469                         $tag = 'year-calendar-month-link';
470                 } 
471                 elsif ($future_month && $month >= $future_month) {
472                         $tag = 'year-calendar-month-future';
473                 } 
474                 else {
475                         $tag = 'year-calendar-month-nolink';
476                 }
477
478                 if ($pagesources{"$archivebase/$params{year}/$mtag"} &&
479                     $post_months[$mtag]) {
480                         $murl = htmllink($params{page}, $params{destpage}, 
481                                 "$archivebase/$params{year}/$mtag",
482                                 noimageinline => 1,
483                                 linktext => $monthabbr,
484                                 title => $monthname);
485                         $calendar.=qq{\t<td class="$tag">};
486                         $calendar.=$murl;
487                         $calendar.=qq{\t</td>\n};
488                 }
489                 else {
490                         $calendar.=qq{\t<td class="$tag">$monthabbr</td>\n};
491                 }
492                 add_depends($params{page}, "$archivebase/$params{year}/$mtag",
493                         deptype("presence"));
494
495                 $calendar.=qq{\t</tr>\n} if ($month % $params{months_per_row} == 0);
496         }
497
498         $calendar.=<<EOF;
499 </table>
500 EOF
501
502         return $calendar;
503 }
504
505 sub setnextchange ($$) {
506         my $page=shift;
507         my $timestamp=shift;
508
509         if (! exists $pagestate{$page}{calendar}{nextchange} ||
510             $pagestate{$page}{calendar}{nextchange} > $timestamp) {
511                 $pagestate{$page}{calendar}{nextchange}=$timestamp;
512         }
513 }
514
515 sub preprocess (@) {
516         my %params=@_;
517
518         my $thisyear=1900 + $now[5];
519         my $thismonth=1 + $now[4];
520
521         $params{pages} = "*"            unless defined $params{pages};
522         $params{type}  = "month"        unless defined $params{type};
523         $params{week_start_day} = 0     unless defined $params{week_start_day};
524         $params{months_per_row} = 3     unless defined $params{months_per_row};
525         $params{year}  = $thisyear      unless defined $params{year};
526         $params{month} = $thismonth     unless defined $params{month};
527
528         my $relativeyear=0;
529         if ($params{year} < 1) {
530                 $relativeyear=1;
531                 $params{year}=$thisyear+$params{year};
532         }
533         my $relativemonth=0;
534         if ($params{month} < 1) {
535                 $relativemonth=1;
536                 my $monthoff=$params{month};
537                 $params{month}=($thismonth+$monthoff) % 12;
538                 $params{month}=12 if $params{month}==0;
539                 my $yearoff=POSIX::ceil(($thismonth-$params{month}) / -12)
540                         - int($monthoff / 12);
541                 $params{year}-=$yearoff;
542         }
543         
544         $params{month} = sprintf("%02d", $params{month});
545         
546         if ($params{type} eq 'month' && $params{year} == $thisyear
547             && $params{month} == $thismonth) {
548                 # calendar for current month, updates next midnight
549                 setnextchange($params{destpage}, ($time
550                         + (60 - $now[0])                # seconds
551                         + (59 - $now[1]) * 60           # minutes
552                         + (23 - $now[2]) * 60 * 60      # hours
553                 ));
554         }
555         elsif ($params{type} eq 'month' &&
556                (($params{year} == $thisyear && $params{month} > $thismonth) ||
557                 $params{year} > $thisyear)) {
558                 # calendar for upcoming month, updates 1st of that month
559                 setnextchange($params{destpage},
560                         timelocal(0, 0, 0, 1, $params{month}-1, $params{year}));
561         }
562         elsif (($params{type} eq 'year' && $params{year} == $thisyear) ||
563                $relativemonth) {
564                 # Calendar for current year updates 1st of next month.
565                 # Any calendar relative to the current month also updates
566                 # then.
567                 if ($thismonth < 12) {
568                         setnextchange($params{destpage},
569                                 timelocal(0, 0, 0, 1, $thismonth+1-1, $params{year}));
570                 }
571                 else {
572                         setnextchange($params{destpage},
573                                 timelocal(0, 0, 0, 1, 1-1, $params{year}+1));
574                 }
575         }
576         elsif ($relativeyear) {
577                 # Any calendar relative to the current year updates 1st
578                 # of next year.
579                 setnextchange($params{destpage},
580                         timelocal(0, 0, 0, 1, 1-1, $thisyear+1));
581         }
582         elsif ($params{type} eq 'year' && $params{year} > $thisyear) {
583                 # calendar for upcoming year, updates 1st of that year
584                 setnextchange($params{destpage},
585                         timelocal(0, 0, 0, 1, 1-1, $params{year}));
586         }
587         else {
588                 # calendar for past month or year, does not need
589                 # to update any more
590                 delete $pagestate{$params{destpage}}{calendar};
591         }
592
593         my $calendar="";
594         if ($params{type} eq 'month') {
595                 $calendar=format_month(%params);
596         }
597         elsif ($params{type} eq 'year') {
598                 $calendar=format_year(%params);
599         }
600
601         return "\n<div><div class=\"calendar\">$calendar</div></div>\n";
602 } #}}
603
604 sub needsbuild (@) {
605         my $needsbuild=shift;
606         foreach my $page (keys %pagestate) {
607                 if (exists $pagestate{$page}{calendar}{nextchange}) {
608                         if ($pagestate{$page}{calendar}{nextchange} <= $time) {
609                                 # force a rebuild so the calendar shows
610                                 # the current day
611                                 push @$needsbuild, $pagesources{$page};
612                         }
613                         if (exists $pagesources{$page} && 
614                             grep { $_ eq $pagesources{$page} } @$needsbuild) {
615                                 # remove state, will be re-added if
616                                 # the calendar is still there during the
617                                 # rebuild
618                                 delete $pagestate{$page}{calendar};
619                         }
620                 }
621         }
622
623         return $needsbuild;
624 }
625
626 sub scan (@) {
627         my %params=@_;
628         my $page=$params{page};
629
630         # Check if year pages have to be generated
631         if (pagespec_match($page, $config{archive_pagespec})) {
632                 my @ctime = localtime($IkiWiki::pagectime{$page});
633                 gencalendaryear($ctime[5]+1900);
634         }
635 }
636
637 1