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