fix events_of_pages()
[ikiwiki/events.git] / events.pm
1 #! /usr/bin/perl
2 # Copyright (C) 2014 Julien Moutinho <julm+ikiwiki+events&autogeree.net>
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 3 of the License,
7 # or (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 package IkiWiki::Plugin::events;
19
20 use strict;
21 use warnings;
22 use IkiWiki 3.00;
23 use Time::Local;
24 use DateTime;
25 use CGI::FormBuilder;
26 #use Data::Dumper;
27
28 sub import {
29 hook(type => "getsetup", id => "events", call => \&getsetup);
30 hook(type => "needsbuild", id => "events", call => \&needsbuild);
31 hook(type => "preprocess", id => "events", call => \&preprocess);
32 hook(type => "sessioncgi", id => "events", call => \&sessioncgi);
33 }
34 sub getsetup () {
35 return
36 { plugin =>
37 { safe => 1
38 , rebuild => undef
39 , section => "widget"
40 }
41 };
42 }
43
44 my $now
45 = DateTime->now
46 ( time_zone => 'local'
47 , locale => $config{locale}
48 )->set_time_zone('floating');
49 my @days = ('01'..'31');
50 my @hours = ('00'..'23');
51 my @minutes = ('00'..'59');
52
53 # update
54 sub set_rendering_expiration ($$) {
55 my ($page, $timestamp) = @_;
56 if (not exists $pagestate{$page}{events}{expiration}
57 or $timestamp < $pagestate{$page}{events}{expiration}) {
58 my $time = DateTime->from_epoch
59 ( epoch => $timestamp
60 , time_zone => 'UTC'
61 , locale => $config{locale}
62 );
63 #debug("events: set_rendering_expiration(): will refresh: page=".$page
64 # . " after: date=".$time->strftime('%Y-%m-%d_%H-%M-%S'));
65 $pagestate{$page}{events}{expiration} = $timestamp;
66 }
67 }
68 sub set_next_rendering (%) {
69 my %params = @_;
70 if ($params{type} eq 'month'
71 and $params{focus}->year() == $now->year()
72 and $params{focus}->month() == $now->month()) {
73 # NOTE: calendar for current month, updates next day
74 my $update = $params{focus}->clone;
75 $update->set_hour(0);
76 $update->set_minute(0);
77 $update->set_second(0);
78 $update->set_nanosecond(0);
79 my $duration = DateTime::Duration->new(days => 1, end_of_month => 'limit');
80 $update->add_duration($duration);
81 set_rendering_expiration($params{destpage}, $update->epoch());
82 #debug("events: will refresh current month: page=".$params{destpage}
83 # . " after: date=".$update->strftime('%Y-%m-%d_%H-%M-%S'));
84 }
85 elsif ($params{type} eq 'month'
86 and (( $params{focus}->year() == $now->year()
87 and $params{focus}->month() > $now->month())
88 or $params{focus}->year() > $now->year())) {
89 # NOTE: calendar for upcoming month, updates 1st of next month
90 my $update = $params{focus}->clone;
91 $update->set_day(1);
92 $update->set_hour(0);
93 $update->set_minute(0);
94 $update->set_second(0);
95 $update->set_nanosecond(0);
96 set_rendering_expiration($params{destpage}, $update->epoch());
97 #debug("events: will refresh upcoming month: page=".$params{destpage}
98 # . " after: date=".$update->strftime('%Y-%m-%d_%H-%M-%S'));
99 }
100 elsif ($params{type} eq 'day'
101 and ($params{focus}->year() == $now->year()
102 and $params{focus}->month() == $now->month()
103 and $params{focus}->day() == $now->day())) {
104 # NOTE: calendar for current day, updates next day
105 my $update = $params{focus}->clone;
106 $update->set_hour(0);
107 $update->set_minute(0);
108 $update->set_second(0);
109 $update->set_nanosecond(0);
110 my $duration = DateTime::Duration->new(days => 1, end_of_month => 'limit');
111 $update->add_duration($duration);
112 set_rendering_expiration($params{destpage}, $update->epoch());
113 #debug("events: will refresh current day: page=".$params{destpage}
114 # . " after: date=".$update->strftime('%Y-%m-%d_%H-%M-%S'));
115 }
116 elsif ($params{type} eq 'day'
117 and (( $params{focus}->year() == $now->year()
118 and ( $params{focus}->month() > $now->month()
119 or ($params{focus}->month() == $now->month()
120 and $params{focus}->day() > $now->day() ))
121 or $params{focus}->year() > $now->year()))) {
122 # NOTE: calendar for upcoming day, updates that day
123 my $update = $params{focus}->clone;
124 $update->set_hour(0);
125 $update->set_minute(0);
126 $update->set_second(0);
127 $update->set_nanosecond(0);
128 set_rendering_expiration($params{destpage}, $update->epoch());
129 #debug("events: will refresh upcoming day: page=".$params{destpage}
130 # . " after: date=".$update->strftime('%Y-%m-%d_%H-%M-%S'));
131 }
132 }
133 sub needsbuild (@) {
134 my $needsbuild = shift;
135 foreach my $page (keys %pagestate) {
136 if (exists $pagestate{$page}{events}{expiration}) {
137 if ($pagestate{$page}{events}{expiration} <= $now->epoch()) {
138 # NOTE: force a rebuild so the calendar shows the current day
139 push @$needsbuild, $pagesources{$page};
140 }
141 if (exists $pagesources{$page}
142 and grep { $_ eq $pagesources{$page} } @$needsbuild) {
143 # NOTE: remove state, will be re-added
144 # if the calendar is still there during the rebuild
145 delete $pagestate{$page}{events};
146 }
147 }
148 }
149 return $needsbuild;
150 }
151
152 # render
153 sub date_of_page ($%) {
154 my ($page, %params) = @_;
155 my $dir = IkiWiki::dirname($page);
156 my ($year, $month, $day, $hour, $hour_begin, $hour_end)
157 = $dir =~ m{
158 .*?
159 /(\d+)
160 (?:/(01|02|03|04|05|06|07|08|09|10|11|12)
161 (?:/(01|02|03|04|05|06|07|08|09|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)
162 (?:/(([0-2][0-9]h[0-5][0-9])
163 (?:-([0-2][0-9]h[0-5][0-9]))?)
164 )?
165 )?
166 )?
167 $
168 }x;
169 my $r =
170 { year => $year
171 , month => $month
172 , day => $day
173 , hour => $hour
174 , hour_begin => $hour_begin
175 , hour_end => $hour_end
176 };
177 #debug("date_of_page: dir=".$dir." ".Dumper($r));
178 return $r;
179 }
180 sub event_of_page ($%) {
181 my ($event, $date, %params) = @_;
182 my $title
183 = exists $pagestate{$event}{meta}{title}
184 ? $pagestate{$event}{meta}{title}
185 : pagetitle(IkiWiki::basename($event));
186 my $hour
187 = $date->{hour};
188 my $link
189 = htmllink
190 ( $params{page}
191 , $params{destpage}
192 , $event
193 , linktext => $title
194 , noimageinline => 1
195 , title => $title );
196 my @tags
197 = sort {lc $a cmp lc $b}
198 (grep {
199 not defined $params{tags}
200 or pagespec_match($_, $params{tags})
201 }
202 (keys %{$IkiWiki::typedlinks{$event}{tag}}));
203 @tags
204 = map {
205 my $tag = $_;
206 my $title
207 = exists $pagestate{$tag}{meta}{title}
208 ? $pagestate{$tag}{meta}{title}
209 : pagetitle(IkiWiki::basename($tag));
210 my $link
211 = htmllink
212 ( $params{page}
213 , $params{destpage}
214 , '/'.$tag
215 , linktext => $title
216 , noimageinline => 1
217 , title => $title );
218 add_depends($params{page}, $event, deptype('content'));
219 #add_depends($params{page}, $tag, deptype('content'));
220 # XXX: much too heavy :\ and midnight refresh may fix it anyway.
221 my $class = qq{$tag};
222 $class =~ s{[^a-zA-Z0-9-]}{_}g;
223 { class => "tag tag-$class"
224 , link => $link }
225 } @tags;
226 my $base = IkiWiki::dirname($event);
227 $base =~ s/[^a-zA-Z0-9-]/_/g;
228 return
229 { hour => $hour
230 , page => $event
231 , date => $date
232 , link => $link
233 , tags => \@tags
234 , base => $base };
235 }
236 sub events_of_pages ($%) {
237 my ($pages, %params) = @_;
238 my @day_events = ();
239 my @hour_events = ();
240 my $pagedir = sub { IkiWiki::basename(IkiWiki::dirname(shift)) };
241 foreach my $page (@$pages) {
242 my $date = date_of_page($page);
243 if (defined $date->{hour}) {
244 push @hour_events, {page=>$page, date=>$date};
245 }
246 else {
247 push @day_events, {page=>$page, date=>$date};
248 }
249 }
250 return
251 map {event_of_page($_->{page}, $_->{date}, %params)}
252 ( (sort {lc IkiWiki::basename($a->{page}) cmp lc IkiWiki::basename($b->{page})} @day_events)
253 , (sort {lc $a->{date}->{hour}.'/'.IkiWiki::basename($a->{page}) cmp lc $b->{date}->{hour}.'/'.IkiWiki::basename($b->{page})} @hour_events) );
254 }
255 sub event_html ($$%) {
256 my ($date, $format, %params) = @_;
257 my $day = sprintf("%02d", $date->day());
258 my $month = sprintf("%02d", $date->month());
259 my $year_html = $date->year();
260 my $month_html
261 = $format->{month_name}
262 ? $date->month_name()
263 : $month;
264 my $day_html
265 = $format->{day_name}
266 ? $date->day_name()." ".$date->day()
267 : $format->{day_abbr}
268 ? $date->day_abbr()." ".$date->day()
269 : $date->day();
270 my $wday_class
271 = "wday-".($date->day_of_week() - 1)
272 . ( ($date->year() == $now->year()
273 and $date->month() == $now->month()
274 and $date->day() == $now->day())
275 ? " today"
276 : "" );
277 my $new_html = "";
278 if (not defined $params{new} or $params{new} ne 'no') {
279 if ($format->{year}) {
280 my $year_page
281 = sprintf
282 ( '%s/%d'
283 , $params{base}
284 , $date->year()
285 );
286 add_depends($params{page}, $year_page, deptype("presence"));
287 if ($pagesources{$year_page}) {
288 $year_html
289 = htmllink
290 ( $params{page}
291 , $params{destpage}
292 , $year_page
293 , linktext => $year_html
294 , noimageinline => 1 );
295 }
296 }
297 if ($format->{month}) {
298 my $month_page
299 = sprintf
300 ( '%s/%d/%02d'
301 , $params{base}
302 , $date->year()
303 , $date->month()
304 );
305 add_depends($params{page}, $month_page, deptype("presence"));
306 if ($pagesources{$month_page}) {
307 $month_html
308 = htmllink
309 ( $params{page}
310 , $params{destpage}
311 , $month_page
312 , linktext => $month_html
313 , noimageinline => 1 );
314 }
315 }
316 if ($format->{day}) {
317 my $day_page
318 = sprintf
319 ( '%s/%d/%02d/%02d'
320 , $params{base}
321 , $date->year()
322 , $date->month()
323 , $date->day()
324 );
325 add_depends($params{page}, $day_page, deptype("presence"));
326 if ($pagesources{$day_page}) {
327 $day_html
328 = htmllink
329 ( $params{page}
330 , $params{destpage}
331 , $day_page
332 , linktext => $day_html
333 , noimageinline => 1 );
334 }
335 }
336 unless ($params{nonew} or not $format->{new}) {
337 $new_html
338 .= qq{<a class='new' href='}
339 . IkiWiki::cgiurl
340 ( base => $params{base}
341 , ($date->day()
342 ?(day => $day):())
343 , (($date->month() or $date->day())
344 ?(month => $month):())
345 , (($date->year() or $date->month() or $date->day())
346 ?(year => $date->year()):())
347 , do => 'newevent'
348 , page => $params{destpage}
349 )
350 . qq{' rel='nofollow'>+</a>};
351 }
352 }
353 return
354 { new => $new_html
355 , day => $day_html
356 , month => $month_html
357 , year => $year_html
358 , wday => $wday_class
359 };
360 }
361 sub preprocess_day (@) {
362 my %params = @_;
363 my @pages
364 = pagespec_match_list
365 ( $params{page}
366 , $params{pages}
367 , deptype => deptype("presence")
368 # NOTE: add presence dependencies to update calendar when pages are added/removed
369 );
370 my $event_html
371 = event_html
372 ( $params{focus}
373 , {day=>1, day_name=>1, new => 1}
374 , %params );
375 my @events
376 = map {
377 my @tags
378 = map {"<li\n class='".$_->{class}."'>".$_->{link}."</li>"}
379 @{$_->{tags}};
380 "<ul\n class='events'><li class='event event-$_->{base}'>"
381 . "<span class='head'>"
382 . (defined $_->{hour} ? "<span class='hour'>$_->{hour}</span>" : "")
383 . "<span class='link'>$_->{link}</span>"
384 . "</span>"
385 . "<ul\n class='tags'>".join("", @tags)."</ul>"
386 . "</li></ul>"
387 }
388 events_of_pages(\@pages, %params);
389 return
390 "<table\n class='wday'>"
391 . "<thead><tr><th><span\n class='head'><span\n class='day'>"
392 . $event_html->{day}
393 . $event_html->{new}
394 . "</span></span></th></tr></thead>"
395 . "<tbody><tr><td\n class='wday $event_html->{wday}'>"
396 . join("", @events)
397 . "</td></tr></tbody>"
398 . "</table>";
399 }
400 sub preprocess_month (@) {
401 my %params = @_;
402 my $one_day = DateTime::Duration->new(days => 1, end_of_month => 'limit');
403 my $day = $params{focus}->clone->set_day(1);
404 my $last_day
405 = DateTime->last_day_of_month
406 ( year => $params{focus}->year()
407 , month => $params{focus}->month() )->day();
408
409 my @pages
410 = pagespec_match_list
411 ( $params{page}
412 , $params{pages}
413 , deptype => deptype("presence")
414 # NOTE: add presence dependencies to update calendar when pages are added/removed
415 );
416
417 my %events_by_day = map {($_=>[])} (1 .. $last_day);
418 foreach my $event (events_of_pages(\@pages, %params)) {
419 push @{$events_by_day{$event->{date}->{day}}}, $event;
420 }
421
422 my $t='<tr>';
423 my $first_wday = $day->clone();
424 my $last_wday = ($params{week_start_day} + 6) % 7;
425 while ($first_wday->day_of_week() - 1 != $params{week_start_day}) {
426 # NOTE: pad the begining
427 $first_wday->subtract_duration($one_day);
428 $t.="<td class='no-wday'></td>";
429 }
430 my $month = $day->month();
431 for (; $day->month() == $month; $day->add_duration($one_day)) {
432 my $event_html
433 = event_html
434 ( $day
435 , {day=>1, day_abbr=>1, new => 1}
436 , %params );
437 $t.= "<td class='wday $event_html->{wday}'>";
438 my @events
439 = map {
440 my @tags
441 = map {"<li\n class='".$_->{class}."'>".$_->{link}."</li>"}
442 @{$_->{tags}};
443 "<li\n class='event event-$_->{base}'>"
444 . "<span class='head'>"
445 . (defined $_->{hour} ? "<span class='hour'>$_->{hour}</span>" : "")
446 . "<span class='link'>$_->{link}</span>"
447 . "</span>"
448 . "<ul class='tags'>".join("", @tags)."</ul>"
449 . "</li>\n"
450 }
451 @{$events_by_day{sprintf('%02d',$day->day())}};
452 $t .=
453 "<span class='head'>"
454 . "<span class='day'>"
455 . $event_html->{day}
456 . $event_html->{new}
457 . "</span>"
458 . "</span>"
459 . "<ul class='events'>".join("", @events)."</ul>";
460 $t.='</td>';
461 if ($day->day_of_week() - 1 == $last_wday) {
462 $t.="</tr>";
463 $t.="<tr>"
464 if ($day->day_of_month() < $last_day);
465 }
466 }
467 while ($day->day_of_week() - 1 != $params{week_start_day}) {
468 # NOTE: pad the end
469 $day->add_duration($one_day);
470 $t.="<td class='no-wday'></td>";
471 }
472 $t.='</tr>';
473 my $event_html
474 = event_html
475 ( $params{focus}
476 , {year=>1, month=>1, month_name=>1}
477 , %params );
478 return
479 "<table class='month'>"
480 . "<thead>"
481 . "<tr>"
482 . "<th colspan='7'>"
483 . "<span class='month'>$event_html->{month}</span>"
484 . " <span class='year'>$event_html->{year}</span>"
485 . "</th>"
486 . "</tr>"
487 . "<tr>"
488 . join ("", map {
489 $_ = "<th><span>".$first_wday->day_name()."</span></th>";
490 $first_wday->add_duration($one_day);
491 $_ } (1..7))
492 . "</tr>"
493 . "</thead>"
494 . "<tbody>$t</tbody></table>";
495 }
496 sub preprocess (@) {
497 my %params = @_;
498 $params{focus} = $now->clone;
499 $params{focus}->set_hour(0);
500 $params{focus}->set_minute(0);
501 $params{focus}->set_second(0);
502 $params{focus}->set_nanosecond(0);
503
504 $params{pages} = "*" unless defined $params{pages};
505 $params{type} = "month" unless defined $params{type};
506 $params{week_start_day} = 0 unless defined $params{week_start_day};
507 $params{week_start_day} = $params{week_start_day} % 7;
508
509 unless (defined $params{base}) {
510 $params{base}
511 = defined $config{events_base}
512 ? $config{events_base}
513 : gettext('Agenda');
514 }
515 if (defined $params{day}) {
516 if ($params{day} =~ m/^([+-])(\d+)$/) {
517 my ($sign, $days) = ($1, $2);
518 my $duration = DateTime::Duration->new(days => $days, end_of_month => 'limit');
519 $params{focus}
520 = $sign eq '+'
521 ? $params{focus}->add_duration($duration)
522 : $params{focus}->subtract_duration($duration);
523 }
524 else {
525 $params{focus}->set(day => $params{day});
526 }
527 }
528 else {
529 #$params{focus}->set(day => 1);
530 }
531 if (defined $params{month}) {
532 if ($params{month} =~ m/^([+-])(\d+)$/) {
533 my ($sign, $months) = ($1, $2);
534 my $duration = DateTime::Duration->new(months => $months, end_of_month => 'limit');
535 $params{focus}
536 = $sign eq '+'
537 ? $params{focus}->add_duration($duration)
538 : $params{focus}->subtract_duration($duration);
539 }
540 else {
541 $params{focus}->set(month => $params{month});
542 }
543 }
544 if (defined $params{year}) {
545 if ($params{year} =~ m/^([+-])(\d+)$/) {
546 my ($sign, $years) = ($1, $2);
547 my $duration = DateTime::Duration->new(years => $years, end_of_month => 'limit');
548 $params{focus}
549 = $sign eq '+'
550 ? $params{focus}->add_duration($duration)
551 : $params{focus}->subtract_duration($duration);
552 }
553 else {
554 $params{focus}->set(year => $params{year});
555 }
556 }
557
558 #debug("events: focus=".$params{focus}->strftime('%Y-%m-%d_%H-%M-%S'));
559 $params{pages} =~ s[%Y][$params{focus}->year()]eg;
560 $params{pages} =~ s[%m][sprintf('%02d', $params{focus}->month())]eg;
561 $params{pages} =~ s[%d][sprintf('%02d', $params{focus}->day())]eg;
562
563 set_next_rendering(%params);
564
565 my $calendar = "";
566 if ($params{type} eq 'month') {
567 $calendar = preprocess_month(%params);
568 }
569 elsif ($params{type} eq 'day') {
570 $calendar = preprocess_day(%params);
571 }
572
573 return "<div class='calendar'>$calendar</div>";
574 }
575
576 # new
577 sub tmpl ($$) {
578 my ($base, $model) = @_;
579 my $page = $base.'/'.'templates/'.$model;
580 my $file = defined srcfile($page, 1) ? '/'.$page : $model;
581 return template($file);
582 }
583 sub date_of_form ($$;%) {
584 my ($form, $prefix, %default) = @_;
585 %default =
586 ( year => 0
587 , month => 1
588 , day => 1
589 , hour => 0
590 , minute => 0
591 , %default
592 );
593 my $date;
594 eval { $date = DateTime->new
595 ( year => ($form->field($prefix.'_year') ne '' ? $form->field($prefix.'_year') : $default{year})
596 , month => ($form->field($prefix.'_month') ne '' ? substr($form->field($prefix.'_month'), 0, 2) : $default{month})
597 , day => ($form->field($prefix.'_day') ne '' ? $form->field($prefix.'_day') : $default{day})
598 , hour => ($form->field($prefix.'_hour') ne '' ? $form->field($prefix.'_hour') : $default{hour})
599 , minute => ($form->field($prefix.'_minute') ne '' ? $form->field($prefix.'_minute') : $default{minute})
600 , second => 0
601 , nanosecond => 0
602 , time_zone => 'local'
603 , locale => $config{locale}
604 )->set_time_zone('floating') };
605 return $date;
606 };
607 sub duration_of_form ($$) {
608 my ($form, $prefix) = @_;
609 my $dur;
610 eval { $dur = DateTime::Duration->new
611 ( years => $form->field($prefix.'_year')
612 , months => $form->field($prefix.'_month')
613 , days => $form->field($prefix.'_day')
614 , weeks => $form->field($prefix.'_week')
615 , hours => $form->field($prefix.'_hour')
616 , minutes => $form->field($prefix.'_minute')
617 , seconds => 0
618 , nanoseconds => 0
619 , end_of_month => 'limit'
620 ) };
621 return $dur;
622 };
623 sub page_of_event ($$$$$) {
624 my ($form, $from_date, $to_date, $name, $base) = @_;
625 my $time = '';
626 if ($form->field('from_hour') ne ''
627 or $form->field('from_minute') ne '') {
628 if ($from_date->hour() == $to_date->hour()
629 and $from_date->minute() == $to_date->minute()) {
630 $time = sprintf('%02dh%02d', $from_date->hour(), $from_date->minute());
631 }
632 else {
633 $time = sprintf('%02dh%02d-%02dh%02d'
634 , $from_date->hour(), $from_date->minute()
635 , $to_date->hour(), $to_date->minute());
636 }
637 }
638 return
639 ( $base
640 . ($base?'/':'').$from_date->year()
641 . '/'.sprintf('%02d', $from_date->month())
642 . '/'.sprintf('%02d', $from_date->day())
643 . '/'. ($time ne '' ? $time . '/' : '')
644 . $name
645 );
646 }
647 sub check_cannewevent ($$$$) {
648 my $dest=shift;
649 my $destfile=shift;
650 my $cgi=shift;
651 my $session=shift;
652
653 # Must be a legal filename.
654 if (IkiWiki::file_pruned($destfile)) {
655 error(sprintf(gettext("illegal name")));
656 }
657 # Must not be a known source file.
658 if (exists $pagesources{$dest}) {
659 error(sprintf(gettext("%s already exists"),
660 htmllink("", "", $dest
661 , linktext => $dest
662 , noimageinline => 1)));
663 }
664 # Must not exist on disk already.
665 if (-l "$config{srcdir}/$destfile" || -e _) {
666 error(sprintf(gettext("%s already exists on disk"), $destfile));
667 }
668
669 # Must be editable.
670 IkiWiki::check_canedit($dest, $cgi, $session);
671
672 my $can_newevent;
673 IkiWiki::run_hooks(can_newevent => sub {
674 return if defined $can_newevent;
675 my $ret=shift->(cgi => $cgi, session => $session, dest => $dest, destfile => $destfile);
676 if (defined $ret) {
677 if ($ret eq "") {
678 $can_newevent=1;
679 }
680 elsif (ref $ret eq 'CODE') {
681 $ret->();
682 $can_newevent=0;
683 }
684 elsif (defined $ret) {
685 error($ret);
686 $can_newevent=0;
687 }
688 }
689 });
690 return defined $can_newevent ? $can_newevent : 1;
691 }
692 sub post_newevent ($$$) {
693 my $cgi=shift;
694 my $session=shift;
695 my $dest=shift;
696
697 IkiWiki::redirect($cgi, urlto($dest));
698 exit;
699 }
700 sub newevent_hook {
701 my %params = @_;
702 my @events = @{$params{events}};
703 my %done = %{$params{done}};
704 my $cgi = $params{cgi};
705 my $session = $params{session};
706 return ()
707 unless @events;
708 my @next;
709 foreach my $event (@events) {
710 unless (exists $done{$event->{page}} && $done{$event->{file}}) {
711 IkiWiki::run_hooks(newevent => sub {
712 push @next, shift->
713 ( cgi => $cgi
714 , event => $event
715 , session => $session
716 );
717 });
718 $done{$event->{page}} = 1;
719 }
720 }
721 push @events, newevent_hook
722 ( cgi => $cgi
723 , done => \%done
724 , events => \@next
725 , session => $session
726 );
727 my %seen; # NOTE: insure unicity
728 return grep { ! $seen{$_->{page}}++ } @events;
729 }
730 sub preview($$$$$) {
731 my ($cgi, $session, $form, $events, $months) = @_;
732 $form->tmpl_param(year => gettext("year"));
733 $form->tmpl_param(month => gettext("month"));
734 $form->tmpl_param(day => gettext("day"));
735 $form->tmpl_param(hour => gettext("hour"));
736 $form->tmpl_param(min => gettext("min"));
737 $form->tmpl_param(dow => gettext("day of week"));
738 $form->tmpl_param(page => gettext("page"));
739 $form->tmpl_param(events => [
740 map {
741 { from_year => $_->{from}->year()
742 , from_month => sprintf('%02d', $_->{from}->month())
743 , from_monthname => $months->{$_->{from}->month()}
744 , from_day => sprintf('%02d', $_->{from}->day())
745 , from_hour => sprintf('%02d', $_->{from}->hour())
746 , from_minute => sprintf('%02d', $_->{from}->minute())
747 , from_dow => $_->{from}->dow()
748 , from_downame => $_->{from}->day_name()
749 , to_year => $_->{to}->year()
750 , to_month => sprintf('%02d', $_->{to}->month())
751 , to_monthname => $months->{$_->{to}->month()}
752 , to_day => sprintf('%02d', $_->{to}->day())
753 , to_hour => sprintf('%02d', $_->{to}->hour())
754 , to_minute => sprintf('%02d', $_->{to}->minute())
755 , to_dow => $_->{to}->dow()
756 , page =>
757 htmllink("", "", $_->{page}
758 , linktext => $_->{page}
759 , noimageinline => 1)
760 }
761 } @$events
762 ]);
763 if (@$events > 0) {
764 my $page = @$events[0];
765 # FROM: editpage.pm
766 my $new = not exists $pagesources{$page};
767 # temporarily record its type
768 my $type = $config{default_pageext};
769 $pagesources{$page} = $page.".".$type if $new;
770 my %wasrendered = map { $_ => 1 } @{$renderedfiles{$page}};
771 my $content = @$events[0]->{content};
772
773 IkiWiki::run_hooks(editcontent => sub {
774 $content = shift->
775 ( cgi => $cgi
776 , content => $content
777 , page => $page
778 , session => $session
779 );
780 });
781 my $preview = IkiWiki::htmlize($page, $page, $type,
782 IkiWiki::linkify($page, $page,
783 IkiWiki::preprocess($page, $page,
784 IkiWiki::filter($page, $page, $content), 0, 1)));
785 IkiWiki::run_hooks(format => sub {
786 $preview = shift->
787 ( content => $preview
788 , page => $page
789 );
790 });
791 $form->tmpl_param("preview", $preview);
792
793 # Previewing may have created files on disk.
794 # Keep a list of these to be deleted later.
795 my %previews = map { $_ => 1 } @{$wikistate{editpage}{previews}};
796 foreach my $f (@{$renderedfiles{$page}}) {
797 $previews{$f} = 1 unless $wasrendered{$f};
798 }
799
800 # Throw out any other state changes made during previewing,
801 # and save the previews list.
802 IkiWiki::loadindex();
803 @{$wikistate{editpage}{previews}} = keys %previews;
804 IkiWiki::saveindex();
805 }
806 else {
807 $form->tmpl_param("preview", gettext("No event"));
808 }
809 }
810 sub create ($$$$$) {
811 my ($event, $cgi, $session, $months, $base) = @_;
812 check_cannewevent
813 ( $event->{page}
814 , $event->{file}
815 , $cgi
816 , $session
817 );
818 my $pageext = $config{default_pageext};
819
820 $config{cgi} = 0; # NOTE: avoid CGI error message
821 eval { writefile($event->{file}, $config{srcdir}, $event->{content}) };
822 if ($config{rcs}) {
823 IkiWiki::rcs_add($event->{file});
824 }
825 # month page
826 my $monthpage =
827 ( $base
828 . ($base?'/':'').$event->{from}->year()
829 . '/'.sprintf('%02d', $event->{from}->month())
830 );
831 my $monthfile = IkiWiki::newpagefile($monthpage, $pageext);
832 if (not exists $pagesources{$monthpage}
833 and not -l $config{srcdir}.'/'.$monthfile
834 and not -e _) {
835 my $tmpl_neweventmonth = tmpl($base, 'neweventmonth.tmpl');
836 $tmpl_neweventmonth->param(base => $base);
837 $tmpl_neweventmonth->param(year => $event->{from}->year());
838 $tmpl_neweventmonth->param(month => sprintf('%02d', $event->{from}->month()));
839 $tmpl_neweventmonth->param(monthname => $months->{$event->{from}->month()});
840 my $content = $tmpl_neweventmonth->output();
841 eval { writefile($monthfile, $config{srcdir}, $content) };
842 if ($config{rcs}) {
843 IkiWiki::rcs_add($monthfile);
844 }
845 }
846 # day page
847 my $daypage =
848 ( $monthpage
849 . '/'.sprintf('%02d', $event->{from}->day())
850 );
851 my $dayfile = IkiWiki::newpagefile($daypage, $pageext);
852 if (not exists $pagesources{$daypage}
853 and not -l $config{srcdir}.'/'.$dayfile
854 and not -e _) {
855 my $tmpl_neweventday = tmpl($base, 'neweventday.tmpl');
856 $tmpl_neweventday->param(base => $base);
857 $tmpl_neweventday->param(year => $event->{from}->year());
858 $tmpl_neweventday->param(month => sprintf('%02d', $event->{from}->month()));
859 $tmpl_neweventday->param(monthname => $months->{$event->{from}->month()});
860 $tmpl_neweventday->param(day => sprintf('%02d', $event->{from}->day()));
861 $tmpl_neweventday->param(dayname => $event->{from}->day_name());
862 my $content = $tmpl_neweventday->output();
863 eval { writefile($dayfile, $config{srcdir}, $content) };
864 if ($config{rcs}) {
865 IkiWiki::rcs_add($dayfile);
866 }
867 }
868 $config{cgi} = 1;
869 }
870 sub sessioncgi ($$) {
871 my ($cgi, $session) = @_;
872 if (defined $cgi->param('do') && $cgi->param('do') eq "newevent") {
873 # TOTRY: decode_cgi_utf8($cgi);
874 my $base = Encode::decode_utf8(URI::Escape::uri_unescape(IkiWiki::possibly_foolish_untaint($cgi->param('base'))));
875 &IkiWiki::check_canedit($base, $cgi, $session);
876 my $page = Encode::decode_utf8(URI::Escape::uri_unescape(IkiWiki::possibly_foolish_untaint($cgi->param('page'))));
877
878 my $now_date = DateTime->now
879 ( time_zone => 'local'
880 , locale => $config{locale}
881 )->set_time_zone('floating');
882 my %dows = map { ($_ => $now_date->{locale}->day_format_wide->[ $_ ]) } (0..6);
883 my %months = map { ($_ => $now_date->{locale}->month_format_wide->[ $_ - 1 ]) } (1..12);
884 my $cgi_date;
885 eval { $cgi_date = DateTime->new
886 ( year => defined $cgi->param("year") ? $cgi->param("year") : $now_date->year()
887 , month => defined $cgi->param("month") ? $cgi->param("month") : $now_date->month()
888 , day => defined $cgi->param("day") ? $cgi->param("day") : $now_date->day()
889 , hour => defined $cgi->param("hour") ? $cgi->param("hour") : $now_date->hour()
890 , minute => defined $cgi->param("minute") ? $cgi->param("minute") : $now_date->minute()
891 , second => 0
892 , nanosecond => 0
893 , time_zone => 'local'
894 , locale => $config{locale}
895 )->set_time_zone('floating') };
896 error(sprintf(gettext("illegal date")))
897 unless $cgi_date;
898
899 my @years = ($cgi_date->year() .. $cgi_date->year()+5);
900 my $week_start_day
901 = (defined $config{week_start_day} and $config{week_start_day} >= 0 and $config{week_start_day} <= 6)
902 ? $config{week_start_day}
903 : 1;
904 my @dow_order = ($week_start_day .. 6, 0 .. $week_start_day-1);
905
906 my $tags = $typedlinks{$page}{tag};
907 my $buttons = [qw{Preview Create}];
908 my ($from_date, $to_date, $end_date, $inc_dur);
909 my $form = CGI::FormBuilder->new
910 ( action => IkiWiki::cgiurl()
911 , charset => "utf-8"
912 , fields => [qw{
913 do base
914 from_date from_year from_month from_day from_hour from_minute
915 to_date to_year to_month to_day to_hour to_minute
916 inc_dur inc_year inc_month inc_week inc_day inc_hour inc_minute
917 end_times end_date end_year end_month end_day end_hour end_minute
918 dom name content
919 }]
920 , header => 0
921 , javascript => 0
922 , messages =>
923 {
924 # form_required_text => 'form_required_text'
925 # , form_invalid_text => 'form_invalid_text'
926 # , form_invalid_file => 'form_invalid_file'
927 # , form_invalid_input => gettext('allowed characters: ').$config{wiki_file_chars}
928 form_invalid_select => gettext('invalid selection')
929 }
930 , method => 'POST'
931 , name => "newevent"
932 , stylesheet => 1
933 , params => $cgi
934 , required => [qw{do base year month day name from_date to_date end_date inc_dur}]
935 , submit => [qw{Preview Create}]
936 , title => gettext("newevent")
937 , template => { template("newevent.tmpl") }
938 , validate =>
939 { from_date => { perl => sub {
940 my (undef, $form) = @_;
941 $from_date = date_of_form($form, 'from')
942 unless defined $from_date;
943 defined $from_date
944 } }
945 , to_date => { perl => sub {
946 my (undef, $form) = @_;
947 $from_date = date_of_form($form, 'from')
948 unless defined $from_date;
949 if (defined $from_date) {
950 $to_date = date_of_form($form, 'to'
951 , year => $from_date->year()
952 , month => $from_date->month()
953 , day => $from_date->day()
954 , hour => $from_date->hour()
955 , minute => $from_date->minute());
956 defined $to_date
957 and (DateTime->compare($from_date, $to_date) <= 0)
958 }
959 else {return 0;}
960 } }
961 , end_date => { perl => sub {
962 my (undef, $form) = @_;
963 if ( $form->field('end_year') ne ''
964 or $form->field('end_month') ne ''
965 or $form->field('end_day') ne '' ) {
966 $from_date = date_of_form($form, 'from')
967 unless defined $from_date;
968 if (defined $from_date) {
969 $end_date = date_of_form($form, 'end'
970 , year => $from_date->year()
971 , month => $from_date->month()
972 , day => $from_date->day()
973 , hour => $from_date->hour()
974 , minute => $from_date->minute());
975 (defined $from_date and defined $end_date
976 and DateTime->compare($from_date, $end_date) <= 0)
977 }
978 else {return 0;}
979 }
980 else {
981 1;
982 }
983 } }
984 , name => '/^.+$/'
985 , base => '/^.*$/'
986 , end_times => sub { $_[0] =~ m/^\d+$/ and $_[0] >= 0 }
987 , inc_year => sub { $_[0] =~ m/^\d+$/ and $_[0] >= 0 }
988 , inc_month => sub { $_[0] =~ m/^\d+$/ and $_[0] >= 0 }
989 , inc_week => sub { $_[0] =~ m/^\d+$/ and $_[0] >= 0 }
990 , inc_day => sub { $_[0] =~ m/^\d+$/ and $_[0] >= 0 }
991 , inc_hour => sub { $_[0] =~ m/^\d+$/ and $_[0] >= 0 }
992 , inc_minute => sub { $_[0] =~ m/^\d+$/ and $_[0] >= 0 }
993 , inc_dur => sub {
994 my (undef, $form) = @_;
995 $inc_dur = duration_of_form($form, 'inc');
996 defined $inc_dur
997 and ($inc_dur->is_positive() or $inc_dur->is_zero());
998 }
999 }
1000 );
1001 $base = $form->field('base') ? $form->field('base') : $base;
1002 $form->title(sprintf(gettext("creating new events"), pagetitle(IkiWiki::basename($page))));
1003 $form->field(name => "do", type => "hidden", value => 'newevent', force => 1);
1004 $form->field(name => "base", type => "hidden", force => 1 , value => $base);
1005 $form->field(name => "from_date", type => "hidden", value => '1', force => 1);
1006 $form->field(name => "to_date", type => "hidden", value => '1', force => 1);
1007 $form->field(name => "end_date", type => "hidden", value => '1', force => 1);
1008 $form->field(name => "inc_dur", type => "hidden", value => '1', force => 1);
1009 $form->field(name => "from_year", type => 'select', value => $cgi_date->year(), options => \@years);
1010 $form->field(name => "from_month", type => 'select'
1011 , value => sprintf("%02d", $cgi_date->month()).' - '.$months{$cgi_date->month()}
1012 , options => [map { sprintf("%02d", $_).' - '.$months{$_} } (1..12)]);
1013 $form->field(name => "from_day", type => 'select'
1014 , value => sprintf("%02d", $cgi_date->day())
1015 , options => \@days);
1016 $form->field(name => "from_hour", type => 'select', value => '', options => \@hours);
1017 $form->field(name => "from_minute", type => 'select', value => '', options => \@minutes);
1018 $form->field(name => "name", type => 'text', size => 60, value => gettext('New event'));
1019 $form->field(name => "to_year", type => 'select', value => '', options => \@years);
1020 $form->field(name => "to_month", type => 'select'
1021 , value => ''
1022 , options => [map { sprintf("%02d", $_).' - '.$months{$_} } (1..12)]);
1023 $form->field(name => "to_day", type => 'select'
1024 , value => ''
1025 , options => \@days);
1026 $form->field(name => "to_hour", type => 'select', value => '', options => \@hours);
1027 $form->field(name => "to_minute", type => 'select', value => '', options => \@minutes);
1028 $form->field(name => "end_year", type => 'select', value => '', options => \@years);
1029 $form->field(name => "end_month", type => 'select', value => ''
1030 , options => [map { sprintf("%02d", $_).' - '.$months{$_} } (1..12)]);
1031 $form->field(name => "end_day", type => 'select', value => '', options => \@days);
1032 $form->field(name => "end_hour", type => 'select', value => '', options => \@hours);
1033 $form->field(name => "end_minute", type => 'select', value => '', options => \@minutes);
1034 $form->field(name => "end_times", type => 'text', value => '0', size => 2);
1035 $form->field(name => "inc_year", type => 'text', value => '0', size => 2);
1036 $form->field(name => "inc_month", type => 'text', value => '0', size => 2);
1037 $form->field(name => "inc_week", type => 'text', value => '0', size => 2);
1038 $form->field(name => "inc_day", type => 'text', value => '0', size => 2);
1039 $form->field(name => "inc_hour", type => 'text', value => '0', size => 2);
1040 $form->field(name => "inc_minute", type => 'text', value => '0', size => 2);
1041 my $tmpl_neweventcontent = tmpl($base, 'neweventcontent.tmpl');
1042 $tmpl_neweventcontent->param(title => gettext('Title of the event'));
1043 $tmpl_neweventcontent->param(tags => [map {{name => $_}} (sort keys %$tags)]);
1044 $form->field(name => "content", type => "textarea", size => 30, rows => 20, cols => 80
1045 , value => $tmpl_neweventcontent->output());
1046 $form->field(name => "dom", type => 'select', multiple => 1, size => 35
1047 , options => [map { my $n = $_; map {($n.' '.$dows{$_})} (0..6)} ('1°', '2°', '3°', '4°', '5°')]);
1048
1049 IkiWiki::decode_form_utf8($form);
1050 IkiWiki::run_hooks(formbuilder_setup => sub {
1051 shift->(form => $form, cgi => $cgi, session => $session, buttons => $buttons);
1052 });
1053 IkiWiki::decode_form_utf8($form);
1054
1055 if (($form->submitted eq 'Create' || $form->submitted eq 'Preview') && $form->validate) {
1056 #IkiWiki::checksessionexpiry($cgi, $session, $cgi->param('sid'));
1057 $base
1058 = $form->field('base')
1059 ? $form->field('base')
1060 : (defined $config{base} ? $config{base} : gettext('Agenda'));
1061 my $end_times
1062 = $form->field('end_times') == 0
1063 ? undef : $form->field('end_times');
1064 my $dom;
1065 foreach ($form->field('dom')) {
1066 $dom = {} if not defined $dom;
1067 $dom->{$_} = 1;
1068 }
1069 my $name = $form->field('name');
1070 $name = IkiWiki::possibly_foolish_untaint(IkiWiki::titlepage($name));
1071 # NOTE: these untaints are safe because of the checks
1072 # performed in check_cannewevent later.
1073 my $content = $form->field('content');
1074 $content =~ s/\r\n/\n/gs;
1075 $content =~ s/\n$//s;
1076
1077 # Queue of event creations to perfom.
1078 my @events = ();
1079 my $events_try = 0;
1080 my $events_max
1081 = defined $config{newevent_max_per_commit}
1082 ? $config{newevent_max_per_commit} : (2 * 365) ;
1083 my $pageext = $config{default_pageext};
1084 while (++$events_try <= $events_max
1085 and (not defined $end_times or --$end_times >= 0)
1086 and (not defined $end_date or DateTime->compare($from_date, $end_date) <= 0)) {
1087 my $dest = page_of_event($form, $from_date, $to_date, $name, $base);
1088 my $week = $from_date->weekday_of_month();
1089 my $day = $now_date->{locale}->day_format_wide->[$from_date->day_of_week()-1];
1090 if (not defined $dom or exists $dom->{"$week° $day"}) {
1091 push @events,
1092 { page => $dest
1093 , file => IkiWiki::newpagefile($dest, $pageext)
1094 , from => $from_date
1095 , to => $to_date
1096 , name => $name
1097 };
1098 }
1099 last unless defined $inc_dur and $inc_dur->is_positive();
1100 $from_date = $from_date->clone->add_duration($inc_dur);
1101 $to_date = $to_date->clone->add_duration($inc_dur);
1102 }
1103 error("events try per commit overflow: $events_max")
1104 unless $events_try <= $events_max;
1105 my $tmpl_neweventpage = tmpl($base, 'neweventpage.tmpl');
1106 my $i = 0;
1107 foreach (@events) {
1108 $tmpl_neweventpage->clear_params();
1109 $tmpl_neweventpage->param(content => $content);
1110 $tmpl_neweventpage->param(page => $_->{page});
1111 $tmpl_neweventpage->param(event => $i);
1112 $tmpl_neweventpage->param("event_first" => 1)
1113 if $i == 0;
1114 $tmpl_neweventpage->param("event_last" => 1)
1115 if $i == @events - 1;
1116 $tmpl_neweventpage->param(events => \@events);
1117 $tmpl_neweventpage->param(from_date => "$_->{from}");
1118 $tmpl_neweventpage->param(name => $_->{name});
1119 $tmpl_neweventpage->param(to_date => "$_->{to}");
1120 $_->{content} = $tmpl_neweventpage->output();
1121 $i++;
1122 }
1123 if ($form->submitted eq 'Create') {
1124 @events = newevent_hook
1125 ( cgi => $cgi
1126 , done => {}
1127 , events => \@events
1128 , session => $session
1129 );
1130 require IkiWiki::Render;
1131 if ($config{rcs}) {
1132 IkiWiki::disable_commit_hook()
1133 }
1134 foreach my $event (@events) {
1135 create($event, $cgi, $session, \%months, $base);
1136 }
1137 if ($config{rcs}) {
1138 IkiWiki::rcs_commit_staged
1139 ( message => sprintf(gettext("new event"))
1140 , session => $session );
1141 IkiWiki::enable_commit_hook();
1142 IkiWiki::rcs_update();
1143 }
1144 IkiWiki::refresh();
1145 IkiWiki::saveindex();
1146
1147 post_newevent($cgi, $session, (defined $events[0] ? $events[0]->{page} : ''));
1148 }
1149 elsif ($form->submitted eq 'Preview') {
1150 preview($cgi, $session, $form, \@events, \%months);
1151 IkiWiki::showform($form, $buttons, $session, $cgi);
1152 }
1153 }
1154 else {
1155 IkiWiki::showform($form, $buttons, $session, $cgi);
1156 }
1157
1158 exit 0;
1159 }
1160 }
1161
1162 1;