add bse_nightly.pl to run a list of BSE background tasks (which are
[bse.git] / site / cgi-bin / modules / BSE / Edit / Article.pm
CommitLineData
ca9aa2bf
TC
1package BSE::Edit::Article;
2use strict;
ca9aa2bf 3use base qw(BSE::Edit::Base);
b553afa2 4use BSE::Util::Tags qw(tag_error_img);
41f10371 5use BSE::Util::SQL qw(now_sqldate now_sqldatetime);
b553afa2 6use BSE::Util::Valid qw/valid_date/;
9168c88c 7use BSE::Permissions;
d09682dd
TC
8use DevHelp::HTML qw(:default popup_menu);
9use BSE::Arrows;
ab2cd916
TC
10use BSE::CfgInfo qw(custom_class admin_base_url cfg_image_dir);
11use BSE::Util::Iterate;
f2bf0d11 12use BSE::Template;
e63c3728 13use BSE::Util::ContentType qw(content_type);
4b69925d 14use constant MAX_FILE_DISPLAYNAME_LENGTH => 255;
ca9aa2bf 15
58baa27b
TC
16=head1 NAME
17
18 BSE::Edit::Article - editing functionality for BSE articles
19
20=head1 DESCRIPTION
21
22Provides the base article editing functionality.
23
24This is badly organized and documented.
25
26=head1 METHODS
27
28=over
29
30=cut
31
74b21f6d
TC
32sub not_logged_on {
33 my ($self, $req) = @_;
34
9b3a5df0 35 if ($req->is_ajax) {
74b21f6d 36 # AJAX/Prototype request
9b3a5df0
TC
37 return $req->json_content
38 (
39 {
40 message => "Access forbidden: user not logged on",
41 errors => {},
42 }
43 );
44 }
45 elsif ($req->cgi->param('_service')) {
74b21f6d
TC
46 return
47 {
48 content => 'Access Forbidden: login timed out',
49 headers => [
50 "Status: 403", # forbidden
51 ],
52 };
53 }
54 else {
55 BSE::Template->get_refresh($req->url('logon'), $req->cfg);
56 }
57}
58
ca9aa2bf 59sub article_dispatch {
9168c88c
TC
60 my ($self, $req, $article, $articles) = @_;
61
62 BSE::Permissions->check_logon($req)
fc186852 63 or return $self->not_logged_on($req);
9168c88c
TC
64
65 my $cgi = $req->cgi;
ca9aa2bf
TC
66 my $action;
67 my %actions = $self->article_actions;
68 for my $check (keys %actions) {
69 if ($cgi->param($check) || $cgi->param("$check.x")) {
70 $action = $check;
71 last;
72 }
73 }
74 my @extraargs;
75 unless ($action) {
76 ($action, @extraargs) = $self->other_article_actions($cgi);
77 }
78 $action ||= 'edit';
79 my $method = $actions{$action};
9168c88c 80 return $self->$method($req, $article, $articles, @extraargs);
ca9aa2bf
TC
81}
82
83sub noarticle_dispatch {
9168c88c 84 my ($self, $req, $articles) = @_;
ca9aa2bf 85
9168c88c
TC
86 BSE::Permissions->check_logon($req)
87 or return BSE::Template->get_refresh($req->url('logon'), $req->cfg);
88
89 my $cgi = $req->cgi;
ca9aa2bf
TC
90 my $action = 'add';
91 my %actions = $self->noarticle_actions;
92 for my $check (keys %actions) {
93 if ($cgi->param($check) || $cgi->param("$check.x")) {
94 $action = $check;
95 last;
96 }
97 }
98 my $method = $actions{$action};
9168c88c 99 return $self->$method($req, $articles);
ca9aa2bf
TC
100}
101
ca9aa2bf
TC
102sub article_actions {
103 my ($self) = @_;
104
105 return
106 (
107 edit => 'edit_form',
108 save => 'save',
109 add_stepkid => 'add_stepkid',
110 del_stepkid => 'del_stepkid',
111 save_stepkids => 'save_stepkids',
112 add_stepparent => 'add_stepparent',
113 del_stepparent => 'del_stepparent',
114 save_stepparents => 'save_stepparents',
115 artimg => 'save_image_changes',
116 addimg => 'add_image',
b95fc3a0
TC
117 a_edit_image => 'req_edit_image',
118 a_save_image => 'req_save_image',
6473c56f 119 remove => 'remove',
ca9aa2bf
TC
120 showimages => 'show_images',
121 process => 'save_image_changes',
122 removeimg => 'remove_img',
123 moveimgup => 'move_img_up',
124 moveimgdown => 'move_img_down',
125 filelist => 'filelist',
126 fileadd => 'fileadd',
127 fileswap => 'fileswap',
128 filedel => 'filedel',
129 filesave => 'filesave',
b2a9e505
TC
130 a_edit_file => 'req_edit_file',
131 a_save_file => 'req_save_file',
4010d92e
TC
132 hide => 'hide',
133 unhide => 'unhide',
ab2cd916 134 a_thumb => 'req_thumb',
74b21f6d
TC
135 a_ajax_get => 'req_ajax_get',
136 a_ajax_save_body => 'req_ajax_save_body',
137 a_ajax_set => 'req_ajax_set',
36e373a9 138 a_filemeta => 'req_filemeta',
ca9aa2bf
TC
139 );
140}
141
142sub other_article_actions {
143 my ($self, $cgi) = @_;
144
145 for my $param ($cgi->param) {
146 if ($param =~ /^removeimg_(\d+)(\.x)?$/) {
147 return ('removeimg', $1 );
148 }
149 }
150
151 return;
152}
153
154sub noarticle_actions {
155 return
156 (
157 add => 'add_form',
158 save => 'save_new',
159 );
160}
161
162sub get_parent {
163 my ($self, $parentid, $articles) = @_;
164
165 if ($parentid == -1) {
166 return
167 {
168 id => -1,
169 title=>'All Sections',
170 level => 0,
171 listed => 0,
172 parentid => undef,
173 };
174 }
175 else {
176 return $articles->getByPkey($parentid);
177 }
178}
179
180sub tag_hash {
181 my ($object, $args) = @_;
182
183 my $value = $object->{$args};
184 defined $value or $value = '';
7b81711b
TC
185 if ($value =~ /\cJ/ && $value =~ /\cM/) {
186 $value =~ tr/\cM//d;
187 }
77804754 188 escape_html($value);
ca9aa2bf
TC
189}
190
62533efa
TC
191sub tag_hash_mbcs {
192 my ($object, $args) = @_;
193
194 my $value = $object->{$args};
195 defined $value or $value = '';
196 if ($value =~ /\cJ/ && $value =~ /\cM/) {
197 $value =~ tr/\cM//d;
198 }
199 escape_html($value, '<>&"');
200}
201
ca9aa2bf
TC
202sub tag_art_type {
203 my ($level, $cfg) = @_;
204
77804754 205 escape_html($cfg->entry('level names', $level, 'Article'));
ca9aa2bf
TC
206}
207
208sub tag_if_new {
209 my ($article) = @_;
210
211 !$article->{id};
212}
213
214sub reparent_updown {
215 return 1;
216}
217
218sub should_be_catalog {
219 my ($self, $article, $parent, $articles) = @_;
220
221 if ($article->{parentid} && (!$parent || $parent->{id} != $article->{parentid})) {
222 $parent = $articles->getByPkey($article->{id});
223 }
224
6430ee52 225 my $shopid = $self->cfg->entryErr('articles', 'shop');
ca9aa2bf
TC
226
227 return $article->{parentid} && $parent &&
228 ($article->{parentid} == $shopid ||
229 $parent->{generator} eq 'Generate::Catalog');
230}
231
232sub possible_parents {
9168c88c 233 my ($self, $article, $articles, $req) = @_;
ca9aa2bf
TC
234
235 my %labels;
236 my @values;
237
6430ee52 238 my $shopid = $self->cfg->entryErr('articles', 'shop');
ca9aa2bf
TC
239 my @parents = $articles->getBy('level', $article->{level}-1);
240 @parents = grep { $_->{generator} eq 'Generate::Article'
241 && $_->{id} != $shopid } @parents;
9168c88c
TC
242
243 # user can only select parent they can add to
244 @parents = grep $req->user_can('edit_add_child', $_), @parents;
ca9aa2bf
TC
245
246 @values = ( map {$_->{id}} @parents );
247 %labels = ( map { $_->{id} => "$_->{title} ($_->{id})" } @parents );
248
9168c88c 249 if ($article->{level} == 1 && $req->user_can('edit_add_child')) {
ca9aa2bf
TC
250 push @values, -1;
251 $labels{-1} = "No parent - this is a section";
252 }
253
254 if ($article->{id} && $self->reparent_updown($article)) {
255 # we also list the siblings and grandparent (if any)
256 my @siblings = grep $_->{id} != $article->{id} && $_->{id} != $shopid,
257 $articles->getBy(parentid => $article->{parentid});
9168c88c 258 @siblings = grep $req->user_can('edit_add_child', $_), @siblings;
ca9aa2bf
TC
259 push @values, map $_->{id}, @siblings;
260 @labels{map $_->{id}, @siblings} =
261 map { "-- move down a level -- $_->{title} ($_->{id})" } @siblings;
262
263 if ($article->{parentid} != -1) {
264 my $parent = $articles->getByPkey($article->{parentid});
265 if ($parent->{parentid} != -1) {
266 my $gparent = $articles->getByPkey($parent->{parentid});
9168c88c
TC
267 if ($req->user_can('edit_add_child', $gparent)) {
268 push @values, $gparent->{id};
269 $labels{$gparent->{id}} =
270 "-- move up a level -- $gparent->{title} ($gparent->{id})";
271 }
ca9aa2bf
TC
272 }
273 else {
9168c88c
TC
274 if ($req->user_can('edit_add_child')) {
275 push @values, -1;
276 $labels{-1} = "-- move up a level -- become a section";
277 }
ca9aa2bf
TC
278 }
279 }
280 }
281
282 return (\@values, \%labels);
283}
284
285sub tag_list {
9168c88c 286 my ($self, $article, $articles, $cgi, $req, $what) = @_;
ca9aa2bf
TC
287
288 if ($what eq 'listed') {
289 my @values = qw(0 1);
290 my %labels = ( 0=>"No", 1=>"Yes");
291 if ($article->{level} <= 2) {
292 $labels{2} = "In Sections, but not menu";
293 push(@values, 2);
294 }
295 else {
296 $labels{2} = "In content, but not menus";
297 push(@values, 2);
298 }
d09682dd
TC
299 return popup_menu(-name=>'listed',
300 -values=>\@values,
301 -labels=>\%labels,
302 -default=>$article->{listed});
ca9aa2bf
TC
303 }
304 else {
9168c88c 305 my ($values, $labels) = $self->possible_parents($article, $articles, $req);
ca9aa2bf
TC
306 my $html;
307 if (defined $article->{parentid}) {
d09682dd
TC
308 $html = popup_menu(-name=>'parentid',
309 -values=> $values,
310 -labels => $labels,
311 -default => $article->{parentid},
312 -override=>1);
ca9aa2bf
TC
313 }
314 else {
d09682dd
TC
315 $html = popup_menu(-name=>'parentid',
316 -values=> $values,
317 -labels => $labels,
318 -override=>1);
ca9aa2bf
TC
319 }
320
321 # munge the html - we display a default value, so we need to wrap the
322 # default <select /> around this one
323 $html =~ s!^<select[^>]+>|</select>!!gi;
324 return $html;
325 }
326}
327
328sub tag_checked {
329 my ($arg, $acts, $funcname, $templater) = @_;
330 my ($func, $args) = split ' ', $arg, 2;
331 return $templater->perform($acts, $func, $args) ? 'checked' : '';
332}
333
334sub iter_get_images {
daee3409 335 my ($self, $article) = @_;
ca9aa2bf
TC
336
337 $article->{id} or return;
daee3409 338 $self->get_images($article);
ca9aa2bf
TC
339}
340
341sub iter_get_kids {
342 my ($article, $articles) = @_;
343
15fb10f2 344 my @children;
ca9aa2bf
TC
345 $article->{id} or return;
346 if (UNIVERSAL::isa($article, 'Article')) {
15fb10f2 347 @children = $article->children;
ca9aa2bf
TC
348 }
349 elsif ($article->{id}) {
15fb10f2 350 @children = $articles->children($article->{id});
ca9aa2bf 351 }
15fb10f2
TC
352
353 return sort { $b->{displayOrder} <=> $a->{displayOrder} } @children;
ca9aa2bf
TC
354}
355
356sub tag_if_have_child_type {
357 my ($level, $cfg) = @_;
358
359 defined $cfg->entry("level names", $level+1);
360}
361
362sub tag_is {
363 my ($args, $acts, $isname, $templater) = @_;
364
365 my ($func, $funcargs) = split ' ', $args, 2;
366 return $templater->perform($acts, $func, $funcargs) ? 'Yes' : 'No';
367}
368
caa7299c
TC
369sub default_template {
370 my ($self, $article, $cfg, $templates) = @_;
371
372 if ($article->{parentid}) {
373 my $template = $cfg->entry("children of $article->{parentid}", "template");
374 return $template
375 if $template && grep $_ eq $template, @$templates;
376 }
377 if ($article->{level}) {
378 my $template = $cfg->entry("level $article->{level}", "template");
379 return $template
380 if $template && grep $_ eq $template, @$templates;
381 }
382 return $templates->[0];
383}
384
ca9aa2bf
TC
385sub tag_templates {
386 my ($self, $article, $cfg, $cgi) = @_;
387
388 my @templates = sort $self->templates($article);
389 my $default;
390 if ($article->{template} && grep $_ eq $article->{template}, @templates) {
391 $default = $article->{template};
392 }
393 else {
caa7299c
TC
394 my @options;
395 $default = $self->default_template($article, $cfg, \@templates);
ca9aa2bf 396 }
d09682dd
TC
397 return popup_menu(-name=>'template',
398 -values=>\@templates,
399 -default=>$default,
400 -override=>1);
ca9aa2bf
TC
401}
402
403sub title_images {
404 my ($self, $article) = @_;
405
406 my @title_images;
6430ee52 407 my $imagedir = cfg_image_dir($self->cfg);
ca9aa2bf
TC
408 if (opendir TITLE_IMAGES, "$imagedir/titles") {
409 @title_images = sort
410 grep -f "$imagedir/titles/$_" && /\.(gif|jpeg|jpg|png)$/i,
411 readdir TITLE_IMAGES;
412 closedir TITLE_IMAGES;
413 }
414
415 @title_images;
416}
417
418sub tag_title_images {
419 my ($self, $article, $cfg, $cgi) = @_;
420
421 my @images = $self->title_images($article);
422 my @values = ( '', @images );
423 my %labels = ( '' => 'None', map { $_ => $_ } @images );
424 return $cgi->
425 popup_menu(-name=>'titleImage',
426 -values=>\@values,
427 -labels=>\%labels,
428 -default=>$article->{id} ? $article->{titleImage} : '',
429 -override=>1);
430}
431
432sub base_template_dirs {
433 return ( "common" );
434}
435
436sub template_dirs {
437 my ($self, $article) = @_;
438
439 my @dirs = $self->base_template_dirs;
440 if (my $parentid = $article->{parentid}) {
441 my $section = "children of $parentid";
6430ee52 442 if (my $dirs = $self->cfg->entry($section, 'template_dirs')) {
ca9aa2bf
TC
443 push @dirs, split /,/, $dirs;
444 }
445 }
446 if (my $id = $article->{id}) {
447 my $section = "article $id";
448 if (my $dirs = $self->{cfg}->entry($section, 'template_dirs')) {
449 push @dirs, split /,/, $dirs;
450 }
451 }
caa7299c
TC
452 if ($article->{level}) {
453 push @dirs, $article->{level};
454 my $dirs = $self->{cfg}->entry("level $article->{level}", 'template_dirs');
455 push @dirs, split /,/, $dirs if $dirs;
456 }
ca9aa2bf
TC
457
458 @dirs;
459}
460
461sub templates {
462 my ($self, $article) = @_;
463
464 my @dirs = $self->template_dirs($article);
465 my @templates;
918735d1
TC
466 my @basedirs = BSE::Template->template_dirs($self->{cfg});
467 for my $basedir (@basedirs) {
468 for my $dir (@dirs) {
469 my $path = File::Spec->catdir($basedir, $dir);
470 if (-d $path) {
471 if (opendir TEMPLATE_DIR, $path) {
472 push(@templates, sort map "$dir/$_",
473 grep -f "$path/$_" && /\.(tmpl|html)$/i, readdir TEMPLATE_DIR);
474 closedir TEMPLATE_DIR;
475 }
ca9aa2bf
TC
476 }
477 }
478 }
918735d1
TC
479
480 # eliminate any dups, and order it nicely
481 my %seen;
482 @templates = sort { lc($a) cmp lc($b) }
483 grep !$seen{$_}++, @templates;
484
ca9aa2bf
TC
485 return (@templates, $self->extra_templates($article));
486}
487
488sub extra_templates {
489 my ($self, $article) = @_;
490
aefcabcb 491 my $basedir = $self->{cfg}->entryVar('paths', 'templates');
ca9aa2bf
TC
492 my @templates;
493 if (my $id = $article->{id}) {
494 push @templates, 'index.tmpl'
495 if $id == 1 && -f "$basedir/index.html";
496 push @templates, 'index2.tmpl'
497 if $id == 2 && -f "$basedir/index2.html";
498 my $shopid = $self->{cfg}->entryErr('articles', 'shop');
499 push @templates, "shop_sect.tmpl"
500 if $id == $shopid && -f "$basedir/shop_sect.tmpl";
501 my $section = "article $id";
502 my $extras = $self->{cfg}->entry($section, 'extra_templates');
503 push @templates, grep /\.(tmpl|html)$/i, split /,/, $extras
504 if $extras;
505 }
506
507 @templates;
508}
509
510sub edit_parent {
511 my ($article) = @_;
512
513 return '' unless $article->{id} && $article->{id} != -1;
514 return <<HTML;
515<a href="$ENV{SCRIPT_NAME}?id=$article->{parentid}">Edit parent</a> |
516HTML
517}
518
519sub iter_allkids {
520 my ($article) = @_;
521
522 return unless $article->{id} && $article->{id} > 0;
523 $article->allkids;
524}
525
526sub _load_step_kids {
527 my ($article, $step_kids) = @_;
528
529 my @stepkids = OtherParents->getBy(parentId=>$article->{id}) if $article->{id};
530 %$step_kids = map { $_->{childId} => $_ } @stepkids;
ca9aa2bf
TC
531 $step_kids->{loaded} = 1;
532}
533
534sub tag_if_step_kid {
535 my ($article, $allkids, $rallkid_index, $step_kids) = @_;
536
537 _load_step_kids($article, $step_kids) unless $step_kids->{loaded};
538
539 my $kid = $allkids->[$$rallkid_index]
540 or return;
541 exists $step_kids->{$kid->{id}};
542}
543
544sub tag_step_kid {
545 my ($article, $allkids, $rallkid_index, $step_kids, $arg) = @_;
546
547 _load_step_kids($article, $step_kids) unless $step_kids->{loaded};
548
549 my $kid = $allkids->[$$rallkid_index]
550 or return '';
f0543260
TC
551 my $step_kid = $step_kids->{$kid->{id}}
552 or return '';
553 #use Data::Dumper;
554 #print STDERR "found kid (want $arg): ", Dumper($kid), Dumper($step_kid);
555 escape_html($step_kid->{$arg});
ca9aa2bf
TC
556}
557
558sub tag_move_stepkid {
8b0b2f34
TC
559 my ($self, $cgi, $req, $article, $allkids, $rallkids_index, $arg,
560 $acts, $funcname, $templater) = @_;
31a26b52
TC
561
562 $req->user_can(edit_reorder_children => $article)
563 or return '';
ca9aa2bf 564
aefcabcb
TC
565 @$allkids > 1 or return '';
566
8b0b2f34
TC
567 my ($img_prefix, $urladd) = DevHelp::Tags->get_parms($arg, $acts, $templater);
568 $img_prefix = '' unless defined $img_prefix;
569 $urladd = '' unless defined $urladd;
570
ca9aa2bf 571 my $cgi_uri = $self->{cfg}->entry('uri', 'cgi', '/cgi-bin');
ca9aa2bf
TC
572 my $url = $ENV{SCRIPT_NAME} . "?id=$article->{id}";
573 if ($cgi->param('_t')) {
574 $url .= "&_t=".$cgi->param('_t');
575 }
8b0b2f34 576 $url .= $urladd;
ca9aa2bf 577 $url .= "#step";
d09682dd 578 my $down_url = '';
ca9aa2bf 579 if ($$rallkids_index < $#$allkids) {
d09682dd 580 $down_url = "$cgi_uri/admin/move.pl?stepparent=$article->{id}&d=swap&id=$allkids->[$$rallkids_index]{id}&other=$allkids->[$$rallkids_index+1]{id}";
aefcabcb 581 }
d09682dd 582 my $up_url = '';
ca9aa2bf 583 if ($$rallkids_index > 0) {
d09682dd 584 $up_url = "$cgi_uri/admin/move.pl?stepparent=$article->{id}&d=swap&id=$allkids->[$$rallkids_index]{id}&other=$allkids->[$$rallkids_index-1]{id}";
ca9aa2bf 585 }
d09682dd
TC
586
587 return make_arrows($req->cfg, $down_url, $up_url, $url, $img_prefix);
ca9aa2bf
TC
588}
589
590sub possible_stepkids {
31a26b52
TC
591 my ($req, $article, $articles, $stepkids) = @_;
592
593 $req->user_can(edit_stepkid_add => $article)
594 or return;
ca9aa2bf 595
147e99e8
TC
596 $article->{id} == -1
597 and return;
598
31a26b52 599 my @possible = sort { lc $a->{title} cmp lc $b->{title} }
147e99e8
TC
600 $article->possible_stepchildren;
601 if ($req->access_control && $req->cfg->entry('basic', 'access_filter_steps', 0)) {
602 @possible = grep $req->user_can(edit_stepparent_add => $_->{id}), @possible;
31a26b52
TC
603 }
604 return @possible;
ca9aa2bf
TC
605}
606
ca9aa2bf 607sub tag_possible_stepkids {
31a26b52 608 my ($step_kids, $req, $article, $possstepkids, $articles, $cgi) = @_;
ca9aa2bf
TC
609
610 _load_step_kids($article, $step_kids) unless $step_kids->{loaded};
31a26b52 611 @$possstepkids = possible_stepkids($req, $article, $articles, $step_kids)
ca9aa2bf
TC
612 unless @$possstepkids;
613 my %labels = map { $_->{id} => "$_->{title} ($_->{id})" } @$possstepkids;
614 return
d09682dd
TC
615 popup_menu(-name=>'stepkid',
616 -values=> [ map $_->{id}, @$possstepkids ],
617 -labels => \%labels);
ca9aa2bf
TC
618}
619
620sub tag_if_possible_stepkids {
31a26b52 621 my ($step_kids, $req, $article, $possstepkids, $articles, $cgi) = @_;
ca9aa2bf
TC
622
623 _load_step_kids($article, $step_kids) unless $step_kids->{loaded};
31a26b52 624 @$possstepkids = possible_stepkids($req, $article, $articles, $step_kids)
ca9aa2bf
TC
625 unless @$possstepkids;
626
627 @$possstepkids;
628}
629
630sub iter_get_stepparents {
631 my ($article) = @_;
632
633 return unless $article->{id} && $article->{id} > 0;
634
635 OtherParents->getBy(childId=>$article->{id});
636}
637
638sub tag_ifStepParents {
639 my ($args, $acts, $funcname, $templater) = @_;
640
641 return $templater->perform($acts, 'ifStepparents', '');
642}
643
644sub tag_stepparent_targ {
645 my ($article, $targs, $rindex, $arg) = @_;
646
647 if ($article->{id} && $article->{id} > 0 && !@$targs) {
648 @$targs = $article->step_parents;
649 }
77804754 650 escape_html($targs->[$$rindex]{$arg});
ca9aa2bf
TC
651}
652
653sub tag_move_stepparent {
8b0b2f34
TC
654 my ($self, $cgi, $req, $article, $stepparents, $rindex, $arg,
655 $acts, $funcname, $templater) = @_;
31a26b52
TC
656
657 $req->user_can(edit_reorder_stepparents => $article)
658 or return '';
ca9aa2bf 659
aefcabcb
TC
660 @$stepparents > 1 or return '';
661
8b0b2f34
TC
662 my ($img_prefix, $urladd) = DevHelp::Tags->get_parms($arg, $acts, $templater);
663 $img_prefix = '' unless defined $img_prefix;
664 $urladd = '' unless defined $urladd;
665
ca9aa2bf
TC
666 my $cgi_uri = $self->{cfg}->entry('uri', 'cgi', '/cgi-bin');
667 my $images_uri = $self->{cfg}->entry('uri', 'images', '/images');
668 my $html = '';
669 my $url = $ENV{SCRIPT_NAME} . "?id=$article->{id}";
670 if ($cgi->param('_t')) {
671 $url .= "&_t=".$cgi->param('_t');
672 }
8b0b2f34 673 $url .= $urladd;
ca9aa2bf 674 $url .= "#stepparents";
d794b180 675 my $blank = qq!<img src="$images_uri/trans_pixel.gif" width="17" height="13" border="0" align="absbottom" alt="" />!;
d09682dd 676 my $down_url = '';
ca9aa2bf 677 if ($$rindex < $#$stepparents) {
d09682dd 678 $down_url = "$cgi_uri/admin/move.pl?stepchild=$article->{id}&id=$stepparents->[$$rindex]{parentId}&d=swap&other=$stepparents->[$$rindex+1]{parentId}";
aefcabcb 679 }
d09682dd 680 my $up_url = '';
ca9aa2bf 681 if ($$rindex > 0) {
d09682dd 682 $up_url = "$cgi_uri/admin/move.pl?stepchild=$article->{id}&id=$stepparents->[$$rindex]{parentId}&d=swap&other=$stepparents->[$$rindex-1]{parentId}";
aefcabcb 683 }
d09682dd
TC
684
685 return make_arrows($req->cfg, $down_url, $up_url, $url, $img_prefix);
ca9aa2bf
TC
686}
687
de193691
TC
688sub _stepparent_possibles {
689 my ($req, $article, $articles, $targs) = @_;
690
691 $req->user_can(edit_stepparent_add => $article)
692 or return;
693
147e99e8
TC
694 $article->{id} == -1
695 and return;
696
de193691
TC
697 @$targs = $article->step_parents unless @$targs;
698 my %targs = map { $_->{id}, 1 } @$targs;
147e99e8
TC
699 my @possibles = $article->possible_stepparents;
700 if ($req->access_control && $req->cfg->entry('basic', 'access_filter_steps', 0)) {
701 @possibles = grep $req->user_can(edit_stepkid_add => $_->{id}), @possibles;
de193691
TC
702 }
703 @possibles = sort { lc $a->{title} cmp lc $b->{title} } @possibles;
704
705 return @possibles;
706}
707
ca9aa2bf 708sub tag_if_stepparent_possibles {
31a26b52 709 my ($req, $article, $articles, $targs, $possibles) = @_;
ca9aa2bf 710
de193691
TC
711 if ($article->{id} && $article->{id} > 0 && !@$possibles) {
712 @$possibles = _stepparent_possibles($req, $article, $articles, $targs);
ca9aa2bf
TC
713 }
714 scalar @$possibles;
715}
716
717sub tag_stepparent_possibles {
31a26b52 718 my ($cgi, $req, $article, $articles, $targs, $possibles) = @_;
ca9aa2bf 719
de193691
TC
720 if ($article->{id} && $article->{id} > 0 && !@$possibles) {
721 @$possibles = _stepparent_possibles($req, $article, $articles, $targs);
ca9aa2bf 722 }
d09682dd
TC
723 popup_menu(-name=>'stepparent',
724 -values => [ map $_->{id}, @$possibles ],
725 -labels => { map { $_->{id}, "$_->{title} ($_->{id})" }
726 @$possibles });
ca9aa2bf
TC
727}
728
729sub iter_files {
9366cd70
TC
730 my ($self, $article) = @_;
731
732 return $self->get_files($article);
733}
734
735sub get_files {
736 my ($self, $article) = @_;
ca9aa2bf
TC
737
738 return unless $article->{id} && $article->{id} > 0;
739
740 return $article->files;
741}
742
743sub tag_edit_parent {
744 my ($article) = @_;
745
746 return '' unless $article->{id} && $article->{id} != -1;
747
748 return <<HTML;
749<a href="$ENV{SCRIPT_NAME}?id=$article->{parentid}">Edit parent</a> |
750HTML
751}
752
753sub tag_if_children {
754 my ($args, $acts, $funcname, $templater) = @_;
755
756 return $templater->perform($acts, 'ifChildren', '');
757}
758
759sub tag_movechild {
8b0b2f34
TC
760 my ($self, $req, $article, $kids, $rindex, $arg,
761 $acts, $funcname, $templater) = @_;
abf5bbc6
TC
762
763 $req->user_can('edit_reorder_children', $article)
764 or return '';
ca9aa2bf 765
aefcabcb
TC
766 @$kids > 1 or return '';
767
ca9aa2bf
TC
768 $$rindex >=0 && $$rindex < @$kids
769 or return '** movechild can only be used in the children iterator **';
770
8b0b2f34
TC
771 my ($img_prefix, $urladd) = DevHelp::Tags->get_parms($arg, $acts, $templater);
772 $img_prefix = '' unless defined $img_prefix;
773 $urladd = '' unless defined $urladd;
774
ca9aa2bf
TC
775 my $cgi_uri = $self->{cfg}->entry('uri', 'cgi', '/cgi-bin');
776 my $images_uri = $self->{cfg}->entry('uri', 'images', '/images');
41f10371 777 my $urlbase = admin_base_url($req->cfg);
d09682dd 778 my $refresh_url = "$urlbase$ENV{SCRIPT_NAME}?id=$article->{id}";
cc9019d1
TC
779 my $t = $req->cgi->param('_t');
780 if ($t && $t =~ /^\w+$/) {
d09682dd 781 $refresh_url .= "&_t=$t";
cc9019d1 782 }
d09682dd
TC
783
784 $refresh_url .= $urladd;
785
ca9aa2bf 786 my $id = $kids->[$$rindex]{id};
d09682dd 787 my $down_url = '';
ca9aa2bf 788 if ($$rindex < $#$kids) {
d09682dd 789 $down_url = "$cgi_uri/admin/move.pl?id=$id&d=down&edit=1&all=1";
ca9aa2bf 790 }
d09682dd 791 my $up_url = '';
ca9aa2bf 792 if ($$rindex > 0) {
d09682dd 793 $up_url = "$cgi_uri/admin/move.pl?id=$id&d=up&edit=1&all=1"
ca9aa2bf 794 }
ca9aa2bf 795
d09682dd 796 return make_arrows($req->cfg, $down_url, $up_url, $refresh_url, $img_prefix);
ca9aa2bf
TC
797}
798
799sub tag_edit_link {
f2bf0d11 800 my ($cfg, $article, $args, $acts, $funcname, $templater) = @_;
ca9aa2bf
TC
801 my ($which, $name) = split / /, $args, 2;
802 $name ||= 'Edit';
803 my $gen_class;
804 if ($acts->{$which}
805 && ($gen_class = $templater->perform($acts, $which, 'generator'))) {
806 eval "use $gen_class";
807 unless ($@) {
f2bf0d11 808 my $gen = $gen_class->new(top => $article, cfg => $cfg);
ca9aa2bf
TC
809 my $link = $gen->edit_link($templater->perform($acts, $which, 'id'));
810 return qq!<a href="$link">$name</a>!;
811 }
812 }
813 return '';
814}
815
816sub tag_imgmove {
8b0b2f34
TC
817 my ($req, $article, $rindex, $images, $arg,
818 $acts, $funcname, $templater) = @_;
abf5bbc6
TC
819
820 $req->user_can(edit_images_reorder => $article)
821 or return '';
ca9aa2bf 822
aefcabcb
TC
823 @$images > 1 or return '';
824
ca9aa2bf
TC
825 $$rindex >= 0 && $$rindex < @$images
826 or return '** imgmove can only be used in image iterator **';
827
8b0b2f34
TC
828 my ($img_prefix, $urladd) = DevHelp::Tags->get_parms($arg, $acts, $templater);
829 $img_prefix = '' unless defined $img_prefix;
830 $urladd = '' unless defined $urladd;
831
41f10371 832 my $urlbase = admin_base_url($req->cfg);
cc9019d1
TC
833 my $url = "$urlbase$ENV{SCRIPT_NAME}?id=$article->{id}";
834 my $t = $req->cgi->param('_t');
835 if ($t && $t =~ /^\w+$/) {
836 $url .= "&_t=$t";
837 }
838 $url .= $urladd;
8b0b2f34 839
ca9aa2bf 840 my $image = $images->[$$rindex];
d09682dd 841 my $down_url;
ca9aa2bf 842 if ($$rindex < $#$images) {
d09682dd 843 $down_url = "$ENV{SCRIPT_NAME}?id=$article->{id}&moveimgdown=1&imageid=$image->{id}";
ca9aa2bf 844 }
d09682dd
TC
845 my $up_url = '';
846 if ($$rindex > 0) {
847 $up_url = "$ENV{SCRIPT_NAME}?id=$article->{id}&moveimgup=1&imageid=$image->{id}";
ca9aa2bf 848 }
d09682dd 849 return make_arrows($req->cfg, $down_url, $up_url, $url, $img_prefix);
ca9aa2bf
TC
850}
851
852sub tag_movefiles {
8b0b2f34
TC
853 my ($self, $req, $article, $files, $rindex, $arg,
854 $acts, $funcname, $templater) = @_;
abf5bbc6
TC
855
856 $req->user_can('edit_files_reorder', $article)
857 or return '';
ca9aa2bf 858
aefcabcb
TC
859 @$files > 1 or return '';
860
8b0b2f34
TC
861 my ($img_prefix, $urladd) = DevHelp::Tags->get_parms($arg, $acts, $templater);
862 $img_prefix = '' unless defined $img_prefix;
863 $urladd = '' unless defined $urladd;
864
ca9aa2bf
TC
865 $$rindex >= 0 && $$rindex < @$files
866 or return '** movefiles can only be used in the files iterator **';
867
41f10371 868 my $urlbase = admin_base_url($req->cfg);
9063386f
TC
869 my $url = "$urlbase$ENV{SCRIPT_NAME}?id=$article->{id}$urladd";
870 my $t = $req->cgi->param('_t');
871 if ($t && $t =~ /^\w+$/) {
872 $url .= "&_t=$t";
873 }
d09682dd
TC
874
875 my $down_url = "";
ca9aa2bf 876 if ($$rindex < $#$files) {
d09682dd 877 $down_url = "$ENV{SCRIPT_NAME}?fileswap=1&amp;id=$article->{id}&amp;file1=$files->[$$rindex]{id}&amp;file2=$files->[$$rindex+1]{id}";
ca9aa2bf 878 }
d09682dd 879 my $up_url = "";
ca9aa2bf 880 if ($$rindex > 0) {
d09682dd 881 $up_url = "$ENV{SCRIPT_NAME}?fileswap=1&amp;id=$article->{id}&amp;file1=$files->[$$rindex]{id}&amp;file2=$files->[$$rindex-1]{id}";
ca9aa2bf 882 }
d09682dd
TC
883
884 return make_arrows($req->cfg, $down_url, $up_url, $url, $img_prefix);
ca9aa2bf
TC
885}
886
887sub tag_old {
888 my ($article, $cgi, $args, $acts, $funcname, $templater) = @_;
889
890 my ($col, $func, $funcargs) = split ' ', $args, 3;
891 my $value = $cgi->param($col);
892 if (defined $value) {
77804754 893 return escape_html($value);
ca9aa2bf
TC
894 }
895 else {
896 if ($func) {
897 return $templater->perform($acts, $func, $funcargs);
898 }
899 else {
900 $value = $article->{$args};
901 defined $value or $value = '';
77804754 902 return escape_html($value);
ca9aa2bf
TC
903 }
904 }
905}
906
08123550
TC
907sub iter_admin_users {
908 require BSE::TB::AdminUsers;
909
910 BSE::TB::AdminUsers->all;
911}
912
913sub iter_admin_groups {
914 require BSE::TB::AdminGroups;
915
916 BSE::TB::AdminGroups->all;
917}
918
9168c88c
TC
919sub tag_if_field_perm {
920 my ($req, $article, $field) = @_;
921
abf5bbc6
TC
922 unless ($field =~ /^\w+$/) {
923 print STDERR "Bad fieldname '$field'\n";
924 return;
925 }
9168c88c 926 if ($article->{id}) {
abf5bbc6 927 return $req->user_can("edit_field_edit_$field", $article);
9168c88c
TC
928 }
929 else {
4010d92e 930 #print STDERR "adding, always successful\n";
abf5bbc6 931 return 1;
9168c88c
TC
932 }
933}
934
935sub tag_default {
936 my ($self, $req, $article, $args, $acts, $funcname, $templater) = @_;
937
938 my ($col, $func, $funcargs) = split ' ', $args, 3;
939 if ($article->{id}) {
940 if ($func) {
941 return $templater->perform($acts, $func, $funcargs);
942 }
943 else {
944 my $value = $article->{$args};
945 defined $value or $value = '';
b1d01e52 946 return escape_html($value, '<>&"');
9168c88c
TC
947 }
948 }
949 else {
950 my $value = $self->default_value($req, $article, $col);
0ec4ac8a 951 defined $value or $value = '';
b1d01e52 952 return escape_html($value, '<>&"');
9168c88c
TC
953 }
954}
955
918735d1
TC
956sub iter_flags {
957 my ($self) = @_;
958
959 $self->flags;
960}
961
962sub tag_if_flag_set {
963 my ($article, $arg, $acts, $funcname, $templater) = @_;
964
965 my @args = DevHelp::Tags->get_parms($arg, $acts, $templater);
966 @args or return;
967
968 return index($article->{flags}, $args[0]) >= 0;
969}
970
8b0b2f34
TC
971sub iter_crumbs {
972 my ($article, $articles) = @_;
973
974 my @crumbs;
975 my $temp = $article;
976 defined($temp->{parentid}) or return;
977 while ($temp->{parentid} > 0
978 and my $crumb = $articles->getByPkey($temp->{parentid})) {
979 unshift @crumbs, $crumb;
980 $temp = $crumb;
981 }
982
983 @crumbs;
984}
985
986sub tag_typename {
987 my ($args, $acts, $funcname, $templater) = @_;
988
989 exists $acts->{$args} or return "** need an article name **";
990 my $generator = $templater->perform($acts, $args, 'generator');
991
992 $generator =~ /^(?:BSE::)?Generate::(\w+)$/
993 or return "** invalid generator $generator **";
994
995 return $1;
996}
997
ab2cd916
TC
998sub _get_thumbs_class {
999 my ($self) = @_;
1000
1001 $self->{cfg}->entry('editor', 'allow_thumb', 0)
1002 or return;
1003
1004 my $class = $self->{cfg}->entry('editor', 'thumbs_class')
1005 or return;
1006
1007 (my $filename = "$class.pm") =~ s!::!/!g;
1008 eval { require $filename; };
1009 if ($@) {
1010 print STDERR "** Error loading thumbs_class $class ($filename): $@\n";
1011 return;
1012 }
1013 my $obj;
1014 eval { $obj = $class->new($self->{cfg}) };
1015 if ($@) {
1016 print STDERR "** Error creating thumbs objects $class: $@\n";
1017 return;
1018 }
1019
1020 return $obj;
1021}
1022
1023sub tag_thumbimage {
1024 my ($cfg, $thumbs_obj, $current_image, $args) = @_;
1025
6a8a6ac5
TC
1026 $thumbs_obj or return '';
1027
ab2cd916
TC
1028 $$current_image or return '** no current image **';
1029
1030 my $imagedir = cfg_image_dir($cfg);
1031
1032 my $filename = "$imagedir/$$current_image->{image}";
1033 -e $filename or return "** image file missing **";
1034
f40af7e2
TC
1035 defined $args && $args =~ /\S/
1036 or $args = "editor";
ab2cd916 1037
195977cd 1038 my $image = $$current_image;
f40af7e2
TC
1039 return $image->thumb
1040 (
1041 geo => $args,
1042 cfg => $cfg,
1043 );
1044}
ab2cd916 1045
8aa7eb30
TC
1046sub tag_file_display {
1047 my ($self, $files, $file_index) = @_;
1048
1049 $$file_index >= 0 && $$file_index < @$files
1050 or return "* file_display only usable inside a files iterator *";
1051 my $file = $files->[$$file_index];
1052
1053 my $disp_type = $self->cfg->entry("editor", "file_display", "");
1054
1055 return $file->inline
1056 (
1057 cfg => $self->cfg,
1058 field => $disp_type,
1059 );
1060}
1061
f40af7e2
TC
1062sub tag_image {
1063 my ($self, $cfg, $rcurrent, $args) = @_;
ab2cd916 1064
f40af7e2
TC
1065 my $im = $$rcurrent
1066 or return '';
195977cd 1067
f40af7e2
TC
1068 my ($align, $rest) = split ' ', $args, 2;
1069
1070 if ($align && exists $im->{$align}) {
1071 if ($align eq 'src') {
1072 return escape_html($im->image_url($self->{cfg}));
1073 }
1074 else {
1075 return escape_html($im->{$align});
1076 }
1077 }
1078 else {
1079 return $im->formatted
1080 (
1081 cfg => $cfg,
1082 align => $align,
1083 extras => $rest,
1084 );
1085 }
ab2cd916
TC
1086}
1087
ca9aa2bf
TC
1088sub low_edit_tags {
1089 my ($self, $acts, $request, $article, $articles, $msg, $errors) = @_;
1090
1091 my $cgi = $request->cgi;
ab2cd916 1092 my $show_full = $cgi->param('f_showfull');
16ac5598 1093 $msg ||= join "\n", map escape_html($_), $cgi->param('message'), $cgi->param('m');
e63c3728 1094 $msg ||= $request->message($errors);
abf5bbc6
TC
1095 my $parent;
1096 if ($article->{id}) {
1097 if ($article->{parentid} > 0) {
1098 $parent = $article->parent;
1099 }
1100 else {
1101 $parent = { title=>"No parent - this is a section", id=>-1 };
1102 }
1103 }
1104 else {
1105 $parent = { title=>"How did we get here?", id=>0 };
1106 }
62533efa
TC
1107 my $cfg = $self->{cfg};
1108 my $mbcs = $cfg->entry('html', 'mbcs', 0);
1109 my $tag_hash = $mbcs ? \&tag_hash_mbcs : \&tag_hash;
ab2cd916
TC
1110 my $thumbs_obj_real = $self->_get_thumbs_class();
1111 my $thumbs_obj = $show_full ? undef : $thumbs_obj_real;
ca9aa2bf
TC
1112 my @images;
1113 my $image_index;
ab2cd916 1114 my $current_image;
ca9aa2bf
TC
1115 my @children;
1116 my $child_index;
1117 my %stepkids;
ca9aa2bf
TC
1118 my @allkids;
1119 my $allkid_index;
1120 my @possstepkids;
1121 my @stepparents;
1122 my $stepparent_index;
1123 my @stepparent_targs;
1124 my @stepparentpossibles;
1125 my @files;
1126 my $file_index;
c2096d67
TC
1127 my @groups;
1128 my $current_group;
ab2cd916 1129 my $it = BSE::Util::Iterate->new;
ca9aa2bf
TC
1130 return
1131 (
58baa27b 1132 $request->admin_tags,
62533efa 1133 article => [ $tag_hash, $article ],
ca9aa2bf 1134 old => [ \&tag_old, $article, $cgi ],
9168c88c 1135 default => [ \&tag_default, $self, $request, $article ],
ca9aa2bf
TC
1136 articleType => [ \&tag_art_type, $article->{level}, $cfg ],
1137 parentType => [ \&tag_art_type, $article->{level}-1, $cfg ],
918735d1 1138 ifNew => [ \&tag_if_new, $article ],
9168c88c 1139 list => [ \&tag_list, $self, $article, $articles, $cgi, $request ],
ca9aa2bf
TC
1140 script => $ENV{SCRIPT_NAME},
1141 level => $article->{level},
1142 checked => \&tag_checked,
ab2cd916 1143 $it->make_iterator
daee3409 1144 ([ \&iter_get_images, $self, $article ], 'image', 'images', \@images,
ab2cd916 1145 \$image_index, undef, \$current_image),
f40af7e2 1146 image => [ tag_image => $self, $cfg, \$current_image ],
ab2cd916
TC
1147 thumbimage => [ \&tag_thumbimage, $cfg, $thumbs_obj, \$current_image ],
1148 ifThumbs => defined($thumbs_obj),
1149 ifCanThumbs => defined($thumbs_obj_real),
abf5bbc6 1150 imgmove => [ \&tag_imgmove, $request, $article, \$image_index, \@images ],
ca9aa2bf
TC
1151 message => $msg,
1152 DevHelp::Tags->make_iterator2
1153 ([ \&iter_get_kids, $article, $articles ],
1154 'child', 'children', \@children, \$child_index),
1155 ifchildren => \&tag_if_children,
1156 childtype => [ \&tag_art_type, $article->{level}+1, $cfg ],
1157 ifHaveChildType => [ \&tag_if_have_child_type, $article->{level}, $cfg ],
abf5bbc6
TC
1158 movechild => [ \&tag_movechild, $self, $request, $article, \@children,
1159 \$child_index],
ca9aa2bf
TC
1160 is => \&tag_is,
1161 templates => [ \&tag_templates, $self, $article, $cfg, $cgi ],
1162 titleImages => [ \&tag_title_images, $self, $article, $cfg, $cgi ],
1163 editParent => [ \&tag_edit_parent, $article ],
1164 DevHelp::Tags->make_iterator2
1165 ([ \&iter_allkids, $article ], 'kid', 'kids', \@allkids, \$allkid_index),
1166 ifStepKid =>
1167 [ \&tag_if_step_kid, $article, \@allkids, \$allkid_index, \%stepkids ],
1168 stepkid => [ \&tag_step_kid, $article, \@allkids, \$allkid_index,
1169 \%stepkids ],
1170 movestepkid =>
31a26b52
TC
1171 [ \&tag_move_stepkid, $self, $cgi, $request, $article, \@allkids,
1172 \$allkid_index ],
ca9aa2bf 1173 possible_stepkids =>
31a26b52
TC
1174 [ \&tag_possible_stepkids, \%stepkids, $request, $article,
1175 \@possstepkids, $articles, $cgi ],
ca9aa2bf 1176 ifPossibles =>
31a26b52
TC
1177 [ \&tag_if_possible_stepkids, \%stepkids, $request, $article,
1178 \@possstepkids, $articles, $cgi ],
ca9aa2bf
TC
1179 DevHelp::Tags->make_iterator2
1180 ( [ \&iter_get_stepparents, $article ], 'stepparent', 'stepparents',
1181 \@stepparents, \$stepparent_index),
1182 ifStepParents => \&tag_ifStepParents,
1183 stepparent_targ =>
1184 [ \&tag_stepparent_targ, $article, \@stepparent_targs,
1185 \$stepparent_index ],
1186 movestepparent =>
31a26b52 1187 [ \&tag_move_stepparent, $self, $cgi, $request, $article, \@stepparents,
ca9aa2bf
TC
1188 \$stepparent_index ],
1189 ifStepparentPossibles =>
31a26b52
TC
1190 [ \&tag_if_stepparent_possibles, $request, $article, $articles,
1191 \@stepparent_targs, \@stepparentpossibles, ],
ca9aa2bf 1192 stepparent_possibles =>
31a26b52 1193 [ \&tag_stepparent_possibles, $cgi, $request, $article, $articles,
ca9aa2bf
TC
1194 \@stepparent_targs, \@stepparentpossibles, ],
1195 DevHelp::Tags->make_iterator2
9366cd70 1196 ([ iter_files => $self, $article ], 'file', 'files', \@files, \$file_index ),
abf5bbc6
TC
1197 movefiles =>
1198 [ \&tag_movefiles, $self, $request, $article, \@files, \$file_index ],
d745f64f
TC
1199 $it->make
1200 (
1201 code => [ iter_file_metas => $self, \@files, \$file_index ],
1202 plural => "file_metas",
1203 single => "file_meta",
1204 nocache => 1,
1205 ),
8aa7eb30 1206 file_display => [ tag_file_display => $self, \@files, \$file_index ],
08123550
TC
1207 DevHelp::Tags->make_iterator2
1208 (\&iter_admin_users, 'iadminuser', 'adminusers'),
1209 DevHelp::Tags->make_iterator2
1210 (\&iter_admin_groups, 'iadmingroup', 'admingroups'),
f2bf0d11 1211 edit => [ \&tag_edit_link, $cfg, $article ],
62533efa 1212 error => [ $tag_hash, $errors ],
b553afa2 1213 error_img => [ \&tag_error_img, $cfg, $errors ],
9168c88c 1214 ifFieldPerm => [ \&tag_if_field_perm, $request, $article ],
62533efa 1215 parent => [ $tag_hash, $parent ],
918735d1
TC
1216 DevHelp::Tags->make_iterator2
1217 ([ \&iter_flags, $self ], 'flag', 'flags' ),
1218 ifFlagSet => [ \&tag_if_flag_set, $article ],
8b0b2f34
TC
1219 DevHelp::Tags->make_iterator2
1220 ([ \&iter_crumbs, $article, $articles ], 'crumb', 'crumbs' ),
1221 typename => \&tag_typename,
c2096d67
TC
1222 $it->make_iterator([ \&iter_groups, $request ],
1223 'group', 'groups', \@groups, undef, undef,
1224 \$current_group),
e63c3728
TC
1225 $it->make_iterator([ iter_image_stores => $self],
1226 'image_store', 'image_stores'),
1227 $it->make_iterator([ iter_file_stores => $self],
1228 'file_store', 'file_stores'),
c2096d67 1229 ifGroupRequired => [ \&tag_ifGroupRequired, $article, \$current_group ],
ca9aa2bf
TC
1230 );
1231}
1232
e63c3728
TC
1233sub iter_image_stores {
1234 my ($self) = @_;
1235
1236 my $mgr = $self->_image_manager;
1237
1238 return map +{ name => $_->name, description => $_->description },
1239 $mgr->all_stores;
1240}
1241
1242sub _file_manager {
1243 my ($self) = @_;
1244
7646d96e 1245 require BSE::TB::ArticleFiles;
e63c3728 1246
7646d96e 1247 return BSE::TB::ArticleFiles->file_manager($self->cfg);
e63c3728
TC
1248}
1249
1250sub iter_file_stores {
1251 my ($self) = @_;
1252
7646d96e
TC
1253 require BSE::TB::ArticleFiles;
1254 my $mgr = $self->_file_manager($self->cfg);
e63c3728
TC
1255
1256 return map +{ name => $_->name, description => $_->description },
1257 $mgr->all_stores;
1258}
1259
c2096d67
TC
1260sub iter_groups {
1261 my ($req) = @_;
1262
1263 require BSE::TB::SiteUserGroups;
1264 BSE::TB::SiteUserGroups->admin_and_query_groups($req->cfg);
1265}
1266
1267sub tag_ifGroupRequired {
1268 my ($article, $rgroup) = @_;
1269
1270 $$rgroup or return 0;
1271
1272 $article->is_accessible_to($$rgroup);
1273}
1274
ca9aa2bf
TC
1275sub edit_template {
1276 my ($self, $article, $cgi) = @_;
1277
1278 my $base = $article->{level};
1279 my $t = $cgi->param('_t');
1280 if ($t && $t =~ /^\w+$/) {
1281 $base = $t;
1282 }
1283 return $self->{cfg}->entry('admin templates', $base,
1284 "admin/edit_$base");
1285}
1286
1287sub add_template {
1288 my ($self, $article, $cgi) = @_;
1289
1290 $self->edit_template($article, $cgi);
1291}
1292
1293sub low_edit_form {
1294 my ($self, $request, $article, $articles, $msg, $errors) = @_;
1295
1296 my $cgi = $request->cgi;
1297 my %acts;
1298 %acts = $self->low_edit_tags(\%acts, $request, $article, $articles, $msg,
1299 $errors);
1300 my $template = $article->{id} ?
1301 $self->edit_template($article, $cgi) : $self->add_template($article, $cgi);
1302
f2bf0d11 1303 return $request->response($template, \%acts);
ca9aa2bf
TC
1304}
1305
1306sub edit_form {
1307 my ($self, $request, $article, $articles, $msg, $errors) = @_;
1308
1309 return $self->low_edit_form($request, $article, $articles, $msg, $errors);
1310}
1311
1312sub add_form {
9168c88c 1313 my ($self, $req, $articles, $msg, $errors) = @_;
ca9aa2bf
TC
1314
1315 my $level;
9168c88c 1316 my $cgi = $req->cgi;
ca9aa2bf
TC
1317 my $parentid = $cgi->param('parentid');
1318 if ($parentid) {
1319 if ($parentid =~ /^\d+$/) {
1320 if (my $parent = $self->get_parent($parentid, $articles)) {
1321 $level = $parent->{level}+1;
1322 }
1323 else {
1324 $parentid = undef;
1325 }
1326 }
1327 elsif ($parentid eq "-1") {
1328 $level = 1;
1329 }
1330 }
1331 unless (defined $level) {
1332 $level = $cgi->param('level');
1333 undef $level unless defined $level && $level =~ /^\d+$/
1334 && $level > 0 && $level < 100;
1335 defined $level or $level = 3;
1336 }
1337
1338 my %article;
1339 my @cols = Article->columns;
1340 @article{@cols} = ('') x @cols;
1341 $article{id} = '';
1342 $article{parentid} = $parentid;
1343 $article{level} = $level;
1344 $article{body} = '<maximum of 64Kb>';
1345 $article{listed} = 1;
1346 $article{generator} = $self->generator;
1347
9168c88c 1348 my ($values, $labels) = $self->possible_parents(\%article, $articles, $req);
1b02d672
TC
1349 unless (@$values) {
1350 require BSE::Edit::Site;
1351 my $site = BSE::Edit::Site->new(cfg=>$req->cfg, db=> BSE::DB->single);
1352 return $site->edit_sections($req, $articles,
1353 "You can't add children to any article at that level");
1354 }
9168c88c
TC
1355
1356 return $self->low_edit_form($req, \%article, $articles, $msg, $errors);
ca9aa2bf
TC
1357}
1358
1359sub generator { 'Generate::Article' }
1360
331fd099
TC
1361sub typename {
1362 my ($self) = @_;
1363
1364 my $gen = $self->generator;
1365
1366 ($gen =~ /(\w+)$/)[0] || 'Article';
1367}
1368
ca9aa2bf 1369sub _validate_common {
b553afa2 1370 my ($self, $data, $articles, $errors, $article) = @_;
ca9aa2bf 1371
918735d1
TC
1372# if (defined $data->{parentid} && $data->{parentid} =~ /^(?:-1|\d+)$/) {
1373# unless ($data->{parentid} == -1 or
1374# $articles->getByPkey($data->{parentid})) {
1375# $errors->{parentid} = "Selected parent article doesn't exist";
1376# }
1377# }
1378# else {
1379# $errors->{parentid} = "You need to select a valid parent";
1380# }
1381 if (exists $data->{title} && $data->{title} !~ /\S/) {
1382 $errors->{title} = "Please enter a title";
ca9aa2bf
TC
1383 }
1384
1385 if (exists $data->{template} && $data->{template} =~ /\.\./) {
1386 $errors->{template} = "Please only select templates from the list provided";
1387 }
c76e86ea
TC
1388 if (exists $data->{linkAlias}
1389 && length $data->{linkAlias}) {
90ee1626 1390 unless ($data->{linkAlias} =~ /\A[a-zA-Z0-9-_]+\z/
c76e86ea
TC
1391 && $data->{linkAlias} =~ /[A-Za-z]/) {
1392 $errors->{linkAlias} = "Link alias must contain only alphanumerics and contain at least one letter";
1393 }
1394 }
ca9aa2bf
TC
1395}
1396
1397sub validate {
918735d1 1398 my ($self, $data, $articles, $errors) = @_;
ca9aa2bf
TC
1399
1400 $self->_validate_common($data, $articles, $errors);
c76e86ea
TC
1401 if (!$errors->{linkAlias} && defined $data->{linkAlias} && length $data->{linkAlias}) {
1402 my $other = $articles->getBy(linkAlias => $data->{linkAlias});
1403 $other
1404 and $errors->{linkAlias} =
1405 "Duplicate link alias - already used by article $other->{id}";
1406 }
331fd099
TC
1407 custom_class($self->{cfg})
1408 ->article_validate($data, undef, $self->typename, $errors);
ca9aa2bf
TC
1409
1410 return !keys %$errors;
1411}
1412
1413sub validate_old {
918735d1 1414 my ($self, $article, $data, $articles, $errors) = @_;
ca9aa2bf 1415
b553afa2 1416 $self->_validate_common($data, $articles, $errors, $article);
331fd099
TC
1417 custom_class($self->{cfg})
1418 ->article_validate($data, $article, $self->typename, $errors);
ca9aa2bf 1419
b553afa2
TC
1420 if (exists $data->{release} && !valid_date($data->{release})) {
1421 $errors->{release} = "Invalid release date";
1422 }
1423
c76e86ea
TC
1424 if (!$errors->{linkAlias}
1425 && defined $data->{linkAlias}
1426 && length $data->{linkAlias}
1427 && $data->{linkAlias} ne $article->{linkAlias}) {
1428 my $other = $articles->getBy(linkAlias => $data->{linkAlias});
90ee1626 1429 $other && $other->{id} != $article->{id}
c76e86ea
TC
1430 and $errors->{linkAlias} = "Duplicate link alias - already used by article $other->{id}";
1431 }
1432
ca9aa2bf
TC
1433 return !keys %$errors;
1434}
1435
1436sub validate_parent {
1437 1;
1438}
1439
1440sub fill_new_data {
1441 my ($self, $req, $data, $articles) = @_;
1442
331fd099
TC
1443 custom_class($self->{cfg})
1444 ->article_fill_new($data, $self->typename);
1445
ca9aa2bf
TC
1446 1;
1447}
1448
95989433
TC
1449sub link_path {
1450 my ($self, $article) = @_;
1451
1452 # check the config for the article and any of its ancestors
1453 my $work_article = $article;
1454 my $path = $self->{cfg}->entry('article uris', $work_article->{id});
1455 while (!$path) {
1456 last if $work_article->{parentid} == -1;
1457 $work_article = $work_article->parent;
1458 $path = $self->{cfg}->entry('article uris', $work_article->{id});
1459 }
1460 return $path if $path;
1461
1462 $self->default_link_path($article);
1463}
1464
1465sub default_link_path {
1466 my ($self, $article) = @_;
1467
1468 $self->{cfg}->entry('uri', 'articles', '/a');
1469}
1470
ca9aa2bf
TC
1471sub make_link {
1472 my ($self, $article) = @_;
1473
efcc5a30 1474 if ($article->is_dynamic) {
b873a8fa 1475 return "/cgi-bin/page.pl?page=$article->{id}&title=".escape_uri($article->{title});
efcc5a30
TC
1476 }
1477
95989433 1478 my $article_uri = $self->link_path($article);
ca9aa2bf
TC
1479 my $link = "$article_uri/$article->{id}.html";
1480 my $link_titles = $self->{cfg}->entryBool('basic', 'link_titles', 0);
1481 if ($link_titles) {
1482 (my $extra = lc $article->{title}) =~ tr/a-z0-9/_/sc;
d7538448 1483 $link .= "/" . $extra . "_html";
ca9aa2bf
TC
1484 }
1485
1486 $link;
1487}
1488
1489sub save_new {
1490 my ($self, $req, $articles) = @_;
1491
1492 my $cgi = $req->cgi;
1493 my %data;
1494 my $table_object = $self->table_object($articles);
1495 my @columns = $table_object->rowClass->columns;
1496 $self->save_thumbnail($cgi, undef, \%data);
1497 for my $name (@columns) {
9168c88c
TC
1498 $data{$name} = $cgi->param($name)
1499 if defined $cgi->param($name);
ca9aa2bf 1500 }
918735d1 1501 $data{flags} = join '', sort $cgi->param('flags');
ca9aa2bf
TC
1502
1503 my $msg;
1504 my %errors;
718a070d
TC
1505 if (!defined $data{parentid} || $data{parentid} eq '') {
1506 $errors{parentid} = "Please select a parent";
1507 }
1508 elsif ($data{parentid} !~ /^(?:-1|\d+)$/) {
1509 $errors{parentid} = "Invalid parent selection (template bug)";
1510 }
918735d1 1511 $self->validate(\%data, $articles, \%errors)
ca9aa2bf
TC
1512 or return $self->add_form($req, $articles, $msg, \%errors);
1513
1514 my $parent;
1515 if ($data{parentid} > 0) {
1516 $parent = $articles->getByPkey($data{parentid}) or die;
9168c88c
TC
1517 $req->user_can('edit_add_child', $parent)
1518 or return $self->add_form($req, $articles,
1519 "You cannot add a child to that article");
1520 for my $name (@columns) {
1521 if (exists $data{$name} &&
1522 !$req->user_can("edit_add_field_$name", $parent)) {
1523 delete $data{$name};
1524 }
1525 }
ca9aa2bf 1526 }
9168c88c
TC
1527 else {
1528 $req->user_can('edit_add_child')
1529 or return $self->add_form($req, $articles,
1530 "You cannot create a top-level article");
1531 for my $name (@columns) {
1532 if (exists $data{$name} &&
1533 !$req->user_can("edit_add_field_$name")) {
1534 delete $data{$name};
1535 }
1536 }
1537 }
1538
ca9aa2bf
TC
1539 $self->validate_parent(\%data, $articles, $parent, \$msg)
1540 or return $self->add_form($req, $articles, $msg);
1541
ca9aa2bf 1542 my $level = $parent ? $parent->{level}+1 : 1;
0ec4ac8a 1543 $data{level} = $level;
9168c88c 1544 $data{displayOrder} = time;
ca9aa2bf
TC
1545 $data{link} ||= '';
1546 $data{admin} ||= '';
ca9aa2bf 1547 $data{generator} = $self->generator;
41f10371 1548 $data{lastModified} = now_sqldatetime();
ca9aa2bf
TC
1549 $data{listed} = 1 unless defined $data{listed};
1550
9604a90c
TC
1551# Added by adrian
1552 $data{pageTitle} = '' unless defined $data{pageTitle};
1553 my $user = $req->getuser;
1554 $data{createdBy} = $user ? $user->{logon} : '';
1555 $data{lastModifiedBy} = $user ? $user->{logon} : '';
1556 $data{created} = now_sqldatetime();
12bcb7ac
TC
1557# end adrian
1558
efcc5a30
TC
1559 $data{force_dynamic} = 0;
1560 $data{cached_dynamic} = 0;
1561 $data{inherit_siteuser_rights} = 1;
9604a90c 1562
12bcb7ac
TC
1563# Added by adrian
1564 $data{metaDescription} = '' unless defined $data{metaDescription};
1565 $data{metaKeywords} = '' unless defined $data{metaKeywords};
1566# end adrian
1567
0ec4ac8a 1568 $self->fill_new_data($req, \%data, $articles);
c76e86ea 1569 for my $col (qw(titleImage imagePos template keyword menu titleAlias linkAlias)) {
0ec4ac8a
TC
1570 defined $data{$col}
1571 or $data{$col} = $self->default_value($req, \%data, $col);
1572 }
1573
c2096d67
TC
1574 for my $col (qw/force_dynamic inherit_siteuser_rights/) {
1575 if ($req->user_can("edit_add_field_$col", $parent)
1576 && $cgi->param("save_$col")) {
1577 $data{$col} = $cgi->param($col) ? 1 : 0;
1578 }
1579 else {
1580 $data{$col} = $self->default_value($req, \%data, $col);
1581 }
1582 }
1583
718a070d
TC
1584 for my $col (qw(release expire)) {
1585 $data{$col} = sql_date($data{$col});
1586 }
1587
0ec4ac8a 1588 # these columns are handled a little differently
d7538448 1589 for my $col (qw(release expire threshold summaryLength )) {
0ec4ac8a
TC
1590 $data{$col}
1591 or $data{$col} = $self->default_value($req, \%data, $col);
1592 }
1593
ca9aa2bf
TC
1594 shift @columns;
1595 my $article = $table_object->add(@data{@columns});
1596
1597 # we now have an id - generate the links
1598
a319d280 1599 $article->update_dynamic($self->{cfg});
ca9aa2bf
TC
1600 my $cgi_uri = $self->{cfg}->entry('uri', 'cgi', '/cgi-bin');
1601 $article->setAdmin("$cgi_uri/admin/admin.pl?id=$article->{id}");
1602 $article->setLink($self->make_link($article));
1603 $article->save();
1604
caa7299c
TC
1605 use Util 'generate_article';
1606 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
1607
8b0b2f34
TC
1608 my $r = $cgi->param('r');
1609 if ($r) {
1610 $r .= ($r =~ /\?/) ? '&' : '?';
1611 $r .= "id=$article->{id}";
1612 }
1613 else {
41f10371
TC
1614
1615 $r = admin_base_url($req->cfg) . $article->{admin};
8b0b2f34
TC
1616 }
1617 return BSE::Template->get_refresh($r, $self->{cfg});
1618
ca9aa2bf
TC
1619}
1620
1621sub fill_old_data {
0d5ccc7f 1622 my ($self, $req, $article, $data) = @_;
ca9aa2bf 1623
4010d92e
TC
1624 if (exists $data->{body}) {
1625 $data->{body} =~ s/\x0D\x0A/\n/g;
1626 $data->{body} =~ tr/\r/\n/;
1627 }
ca9aa2bf 1628 for my $col (Article->columns) {
331fd099 1629 next if $col =~ /^custom/;
ca9aa2bf
TC
1630 $article->{$col} = $data->{$col}
1631 if exists $data->{$col} && $col ne 'id' && $col ne 'parentid';
1632 }
331fd099
TC
1633 custom_class($self->{cfg})
1634 ->article_fill_old($article, $data, $self->typename);
ca9aa2bf
TC
1635
1636 return 1;
1637}
1638
1639sub save {
1640 my ($self, $req, $article, $articles) = @_;
4010d92e
TC
1641
1642 $req->user_can(edit_save => $article)
1643 or return $self->edit_form($req, $article, $articles,
1644 "You don't have access to save this article");
efcc5a30
TC
1645
1646 my $old_dynamic = $article->is_dynamic;
ca9aa2bf
TC
1647 my $cgi = $req->cgi;
1648 my %data;
1649 for my $name ($article->columns) {
1650 $data{$name} = $cgi->param($name)
abf5bbc6
TC
1651 if defined($cgi->param($name)) and $name ne 'id' && $name ne 'parentid'
1652 && $req->user_can("edit_field_edit_$name", $article);
ca9aa2bf 1653 }
12b42a0b
TC
1654
1655# Added by adrian
1656# checks editor lastModified against record lastModified
1657 if ($self->{cfg}->entry('editor', 'check_modified')) {
1658 if ($article->{lastModified} ne $cgi->param('lastModified')) {
1659 my $whoModified = '';
1660 my $timeModified = ampm_time($article->{lastModified});
1661 if ($article->{lastModifiedBy}) {
1662 $whoModified = "by '$article->{lastModifiedBy}'";
1663 }
1664 print STDERR "non-matching lastModified, article not saved\n";
1665 my $msg = "Article changes not saved, this article was modified $whoModified at $timeModified since this editor was loaded";
1666 return $self->edit_form($req, $article, $articles, $msg);
1667 }
1668 }
1669# end adrian
1670
918735d1
TC
1671 # possibly this needs tighter error checking
1672 $data{flags} = join '', sort $cgi->param('flags')
1673 if $req->user_can("edit_field_edit_flags", $article);
ca9aa2bf
TC
1674 my %errors;
1675 $self->validate_old($article, \%data, $articles, \%errors)
1676 or return $self->edit_form($req, $article, $articles, undef, \%errors);
abf5bbc6
TC
1677 $self->save_thumbnail($cgi, $article, \%data)
1678 if $req->user_can('edit_field_edit_thumbImage', $article);
ca9aa2bf
TC
1679 $self->fill_old_data($req, $article, \%data);
1680 if (exists $article->{template} &&
1681 $article->{template} =~ m|\.\.|) {
1682 my $msg = "Please only select templates from the list provided";
1683 return $self->edit_form($req, $article, $articles, $msg);
1684 }
12b42a0b 1685
ca9aa2bf
TC
1686 # reparenting
1687 my $newparentid = $cgi->param('parentid');
abf5bbc6
TC
1688 if ($newparentid && $req->user_can('edit_field_edit_parentid', $article)) {
1689 if ($newparentid == $article->{parentid}) {
1690 # nothing to do
1691 }
1692 elsif ($newparentid != -1) {
1693 print STDERR "Reparenting...\n";
1694 my $newparent = $articles->getByPkey($newparentid);
1695 if ($newparent) {
1696 if ($newparent->{level} != $article->{level}-1) {
1697 # the article cannot become a child of itself or one of it's
1698 # children
1699 if ($article->{id} == $newparentid
1700 || $self->is_descendant($article->{id}, $newparentid, $articles)) {
1701 my $msg = "Cannot become a child of itself or of a descendant";
1702 return $self->edit_form($req, $article, $articles, $msg);
1703 }
1704 my $shopid = $self->{cfg}->entryErr('articles', 'shop');
1705 if ($self->is_descendant($article->{id}, $shopid, $articles)) {
1706 my $msg = "Cannot become a descendant of the shop";
1707 return $self->edit_form($req, $article, $articles, $msg);
1708 }
1709 my $msg;
1710 $self->reparent($article, $newparentid, $articles, \$msg)
1711 or return $self->edit_form($req, $article, $articles, $msg);
ca9aa2bf 1712 }
abf5bbc6
TC
1713 else {
1714 # stays at the same level, nothing special
1715 $article->{parentid} = $newparentid;
ca9aa2bf 1716 }
ca9aa2bf 1717 }
abf5bbc6
TC
1718 # else ignore it
1719 }
1720 else {
1721 # becoming a section
1722 my $msg;
1723 $self->reparent($article, -1, $articles, \$msg)
1724 or return $self->edit_form($req, $article, $articles, $msg);
ca9aa2bf 1725 }
ca9aa2bf
TC
1726 }
1727
abf5bbc6 1728 $article->{listed} = $cgi->param('listed')
63e99d77 1729 if defined $cgi->param('listed') &&
abf5bbc6
TC
1730 $req->user_can('edit_field_edit_listed', $article);
1731 $article->{release} = sql_date($cgi->param('release'))
1732 if defined $cgi->param('release') &&
1733 $req->user_can('edit_field_edit_release', $article);
1734
1735 $article->{expire} = sql_date($cgi->param('expire')) || $Constants::D_99
1736 if defined $cgi->param('expire') &&
1737 $req->user_can('edit_field_edit_expire', $article);
41f10371 1738 $article->{lastModified} = now_sqldatetime();
c2096d67
TC
1739 for my $col (qw/force_dynamic inherit_siteuser_rights/) {
1740 if ($req->user_can("edit_field_edit_$col", $article)
1741 && $cgi->param("save_$col")) {
1742 $article->{$col} = $cgi->param($col) ? 1 : 0;
1743 }
1744 }
1745
1746# Added by adrian
1747 my $user = $req->getuser;
1748 $article->{lastModifiedBy} = $user ? $user->{logon} : '';
1749# end adrian
1750
1751 my @save_group_ids = $cgi->param('save_group_id');
1752 if ($req->user_can('edit_field_edit_group_id')
1753 && @save_group_ids) {
1754 require BSE::TB::SiteUserGroups;
1755 my %groups = map { $_->{id} => $_ }
1756 BSE::TB::SiteUserGroups->admin_and_query_groups($self->{cfg});
1757 my %set = map { $_ => 1 } $cgi->param('group_id');
1758 my %current = map { $_ => 1 } $article->group_ids;
1759
1760 for my $group_id (@save_group_ids) {
1761 $groups{$group_id} or next;
1762 if ($current{$group_id} && !$set{$group_id}) {
1763 $article->remove_group_id($group_id);
1764 }
1765 elsif (!$current{$group_id} && $set{$group_id}) {
1766 $article->add_group_id($group_id);
1767 }
1768 }
efcc5a30
TC
1769 }
1770
63e99d77 1771 my $old_link = $article->{link};
efcc5a30
TC
1772 # this need to go last
1773 $article->update_dynamic($self->{cfg});
95989433
TC
1774 if ($article->{link} &&
1775 !$self->{cfg}->entry('protect link', $article->{id})) {
1776 my $article_uri = $self->make_link($article);
95989433 1777 $article->setLink($article_uri);
ca9aa2bf
TC
1778 }
1779
1780 $article->save();
caa7299c 1781
63e99d77 1782 # fix the kids too
efcc5a30 1783 my @extra_regen;
63e99d77
TC
1784 @extra_regen = $self->update_child_dynamic($article, $articles, $req);
1785
1786 if ($article->is_dynamic || $old_dynamic) {
1787 if (!$old_dynamic and $old_link) {
1788 unlink $article->link_to_filename($self->{cfg}, $old_link);
1789 }
16901a2a
TC
1790 elsif (!$article->is_dynamic) {
1791 unlink $article->cached_filename($self->{cfg});
1792 }
efcc5a30
TC
1793 }
1794
caa7299c 1795 use Util 'generate_article';
efcc5a30
TC
1796 if ($Constants::AUTO_GENERATE) {
1797 generate_article($articles, $article);
1798 for my $regen_id (@extra_regen) {
1799 my $regen = $articles->getByPkey($regen_id);
63e99d77 1800 Util::generate_low($articles, $regen, $self->{cfg});
efcc5a30
TC
1801 }
1802 }
caa7299c 1803
8b0b2f34 1804 return $self->refresh($article, $cgi, undef, 'Article saved');
ca9aa2bf
TC
1805}
1806
efcc5a30
TC
1807sub update_child_dynamic {
1808 my ($self, $article, $articles, $req) = @_;
1809
1810 my $cfg = $req->cfg;
1811 my @stack = $article->children;
1812 my @regen;
1813 while (@stack) {
1814 my $workart = pop @stack;
1815 my $old_dynamic = $workart->is_dynamic; # before update
63e99d77 1816 my $old_link = $workart->{link};
3e37b5ba
TC
1817 my $editor;
1818 ($editor, $workart) = $self->article_class($workart, $articles, $cfg);
1819
efcc5a30
TC
1820 $workart->update_dynamic($cfg);
1821 if ($old_dynamic != $workart->is_dynamic) {
1822 # update the link
1823 if ($article->{link} && !$cfg->entry('protect link', $workart->{id})) {
efcc5a30
TC
1824 my $uri = $editor->make_link($workart);
1825 $workart->setLink($uri);
63e99d77 1826
8f84f3f1
TC
1827 !$old_dynamic && $old_link
1828 and unlink $workart->link_to_filename($cfg, $old_link);
1829 $workart->is_dynamic
16901a2a 1830 or unlink $workart->cached_filename($cfg);
efcc5a30
TC
1831 }
1832
1833 # save dynamic cache change and link if that changed
1834 $workart->save;
1835 }
1836 push @stack, $workart->children;
1837 push @regen, $workart->{id};
1838 }
1839
1840 @regen;
1841}
1842
ca9aa2bf
TC
1843sub sql_date {
1844 my $str = shift;
1845 my ($year, $month, $day);
1846
1847 # look for a date
1848 if (($day, $month, $year) = ($str =~ m!(\d+)/(\d+)/(\d+)!)) {
1849 $year += 2000 if $year < 100;
1850
1851 return sprintf("%04d-%02d-%02d", $year, $month, $day);
1852 }
1853 return undef;
1854}
1855
12b42a0b
TC
1856# Added by adrian
1857# Converts 24hr time to 12hr AM/PM time
1858sub ampm_time {
1859 my $str = shift;
1860 my ($hour, $minute, $second, $ampm);
1861
1862 # look for a time
1863 if (($hour, $minute, $second) = ($str =~ m!(\d+):(\d+):(\d+)!)) {
1864 if ($hour > 12) {
1865 $hour -= 12;
1866 $ampm = 'PM';
1867 }
1868 else {
c2096d67 1869 $hour = 12 if $hour == 0;
12b42a0b
TC
1870 $ampm = 'AM';
1871 }
1872 return sprintf("%02d:%02d:%02d $ampm", $hour, $minute, $second);
1873 }
1874 return undef;
1875}
1876# end adrian
1877
ca9aa2bf
TC
1878sub reparent {
1879 my ($self, $article, $newparentid, $articles, $rmsg) = @_;
1880
1881 my $newlevel;
1882 if ($newparentid == -1) {
1883 $newlevel = 1;
1884 }
1885 else {
1886 my $parent = $articles->getByPkey($newparentid);
1887 unless ($parent) {
1888 $$rmsg = "Cannot get new parent article";
1889 return;
1890 }
1891 $newlevel = $parent->{level} + 1;
1892 }
1893 # the caller will save this one
1894 $article->{parentid} = $newparentid;
1895 $article->{level} = $newlevel;
1896 $article->{displayOrder} = time;
1897
1898 my @change = ( [ $article->{id}, $newlevel ] );
1899 while (@change) {
1900 my $this = shift @change;
1901 my ($art, $level) = @$this;
1902
1903 my @kids = $articles->getBy(parentid=>$art);
1904 push @change, map { [ $_->{id}, $level+1 ] } @kids;
1905
1906 for my $kid (@kids) {
1907 $kid->{level} = $level+1;
1908 $kid->save;
1909 }
1910 }
1911
1912 return 1;
1913}
1914
1915# tests if $desc is a descendant of $art
1916# where both are article ids
1917sub is_descendant {
1918 my ($self, $art, $desc, $articles) = @_;
1919
1920 my @check = ($art);
1921 while (@check) {
1922 my $parent = shift @check;
1923 $parent == $desc and return 1;
1924 my @kids = $articles->getBy(parentid=>$parent);
1925 push @check, map $_->{id}, @kids;
1926 }
1927
1928 return 0;
1929}
1930
1931sub save_thumbnail {
1932 my ($self, $cgi, $original, $newdata) = @_;
1933
1934 unless ($original) {
1935 @$newdata{qw/thumbImage thumbWidth thumbHeight/} = ('', 0, 0);
1936 }
ab2cd916 1937 my $imagedir = cfg_image_dir($self->{cfg});
ca9aa2bf
TC
1938 if ($cgi->param('remove_thumb') && $original && $original->{thumbImage}) {
1939 unlink("$imagedir/$original->{thumbImage}");
1940 @$newdata{qw/thumbImage thumbWidth thumbHeight/} = ('', 0, 0);
1941 }
1942 my $image = $cgi->param('thumbnail');
1943 if ($image && -s $image) {
1944 # where to put it...
1945 my $name = '';
1946 $image =~ /([\w.-]+)$/ and $name = $1;
1947 my $filename = time . "_" . $name;
1948
1949 use Fcntl;
1950 my $counter = "";
1951 $filename = time . '_' . $counter . '_' . $name
1952 until sysopen( OUTPUT, "$imagedir/$filename",
1953 O_WRONLY| O_CREAT| O_EXCL)
1954 || ++$counter > 100;
1955
1956 fileno(OUTPUT) or die "Could not open image file: $!";
1957 binmode OUTPUT;
1958 my $buffer;
1959
1960 #no strict 'refs';
1961
1962 # read the image in from the browser and output it to our
1963 # output filehandle
1964 print STDERR "\$image ",ref $image,"\n";
1965 seek $image, 0, 0;
1966 print OUTPUT $buffer while sysread $image, $buffer, 1024;
1967
1968 close OUTPUT
1969 or die "Could not close image output file: $!";
1970
1971 use Image::Size;
1972
1973 if ($original && $original->{thumbImage}) {
1974 #unlink("$imagedir/$original->{thumbImage}");
1975 }
1976 @$newdata{qw/thumbWidth thumbHeight/} = imgsize("$imagedir/$filename");
1977 $newdata->{thumbImage} = $filename;
1978 }
1979}
1980
1981sub child_types {
1982 my ($self, $article) = @_;
1983
1984 my $shopid = $self->{cfg}->entryErr('articles', 'shop');
1985 if ($article && $article->{id} && $article->{id} == $shopid) {
1986 return ( 'BSE::Edit::Catalog' );
1987 }
1988 return ( 'BSE::Edit::Article' );
1989}
1990
1991sub add_stepkid {
1992 my ($self, $req, $article, $articles) = @_;
1993
31a26b52
TC
1994 $req->user_can(edit_stepkid_add => $article)
1995 or return $self->edit_form($req, $article, $articles,
1996 "You don't have access to add step children to this article");
1997
ca9aa2bf
TC
1998 my $cgi = $req->cgi;
1999 require 'BSE/Admin/StepParents.pm';
2000 eval {
2001 my $childId = $cgi->param('stepkid');
2002 defined $childId
2003 or die "No stepkid supplied to add_stepkid";
2004 $childId =~ /^\d+$/
2005 or die "Invalid stepkid supplied to add_stepkid";
2006 my $child = $articles->getByPkey($childId)
2007 or die "Article $childId not found";
31a26b52
TC
2008
2009 $req->user_can(edit_stepparent_add => $child)
2010 or die "You don't have access to add a stepparent to that article\n";
ca9aa2bf
TC
2011
2012 use BSE::Util::Valid qw/valid_date/;
2013 my $release = $cgi->param('release');
2014 valid_date($release) or $release = undef;
2015 my $expire = $cgi->param('expire');
2016 valid_date($expire) or $expire = undef;
2017
2018 my $newentry =
2019 BSE::Admin::StepParents->add($article, $child, $release, $expire);
2020 };
2021 if ($@) {
2022 return $self->edit_form($req, $article, $articles, $@);
2023 }
a0a8147b
TC
2024
2025 use Util 'generate_article';
2026 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
2027
8b0b2f34 2028 return $self->refresh($article, $cgi, 'step', 'Stepchild added');
ca9aa2bf
TC
2029}
2030
2031sub del_stepkid {
2032 my ($self, $req, $article, $articles) = @_;
2033
31a26b52
TC
2034 $req->user_can(edit_stepkid_delete => $article)
2035 or return $self->edit_form($req, $article, $articles,
2036 "You don't have access to delete stepchildren from this article");
2037
ca9aa2bf
TC
2038 my $cgi = $req->cgi;
2039 require 'BSE/Admin/StepParents.pm';
2040 eval {
2041 my $childId = $cgi->param('stepkid');
2042 defined $childId
2043 or die "No stepkid supplied to add_stepkid";
2044 $childId =~ /^\d+$/
2045 or die "Invalid stepkid supplied to add_stepkid";
2046 my $child = $articles->getByPkey($childId)
2047 or die "Article $childId not found";
31a26b52
TC
2048
2049 $req->user_can(edit_stepparent_delete => $child)
2050 or die "You cannot remove stepparents from that article\n";
ca9aa2bf
TC
2051
2052 BSE::Admin::StepParents->del($article, $child);
2053 };
2054
2055 if ($@) {
2056 return $self->edit_form($req, $article, $articles, $@);
2057 }
a0a8147b
TC
2058 use Util 'generate_article';
2059 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
2060
8b0b2f34 2061 return $self->refresh($article, $cgi, 'step', 'Stepchild deleted');
ca9aa2bf
TC
2062}
2063
2064sub save_stepkids {
2065 my ($self, $req, $article, $articles) = @_;
2066
31a26b52
TC
2067 $req->user_can(edit_stepkid_save => $article)
2068 or return $self->edit_form($req, $article, $articles,
2069 "No access to save stepkid data for this article");
2070
ca9aa2bf
TC
2071 my $cgi = $req->cgi;
2072 require 'BSE/Admin/StepParents.pm';
2073 my @stepcats = OtherParents->getBy(parentId=>$article->{id});
2074 my %stepcats = map { $_->{parentId}, $_ } @stepcats;
2075 my %datedefs = ( release => '2000-01-01', expire=>'2999-12-31' );
2076 for my $stepcat (@stepcats) {
31a26b52
TC
2077 $req->user_can(edit_stepparent_save => $stepcat->{childId})
2078 or next;
ca9aa2bf
TC
2079 for my $name (qw/release expire/) {
2080 my $date = $cgi->param($name.'_'.$stepcat->{childId});
2081 if (defined $date) {
2082 if ($date eq '') {
2083 $date = $datedefs{$name};
2084 }
2085 elsif (valid_date($date)) {
2086 use BSE::Util::SQL qw/date_to_sql/;
2087 $date = date_to_sql($date);
2088 }
2089 else {
2090 return $self->refresh($article, $cgi, '', "Invalid date '$date'");
2091 }
2092 $stepcat->{$name} = $date;
2093 }
2094 }
2095 eval {
2096 $stepcat->save();
2097 };
2098 $@ and return $self->refresh($article, $cgi, '', $@);
2099 }
a0a8147b
TC
2100 use Util 'generate_article';
2101 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
2102
8b0b2f34 2103 return $self->refresh($article, $cgi, 'step', 'Stepchild information saved');
ca9aa2bf
TC
2104}
2105
2106sub add_stepparent {
2107 my ($self, $req, $article, $articles) = @_;
2108
31a26b52
TC
2109 $req->user_can(edit_stepparent_add => $article)
2110 or return $self->edit_form($req, $article, $articles,
2111 "You don't have access to add stepparents to this article");
2112
ca9aa2bf
TC
2113 my $cgi = $req->cgi;
2114 require 'BSE/Admin/StepParents.pm';
2115 eval {
2116 my $step_parent_id = $cgi->param('stepparent');
2117 defined($step_parent_id)
2118 or die "No stepparent supplied to add_stepparent";
2119 int($step_parent_id) eq $step_parent_id
2120 or die "Invalid stepcat supplied to add_stepcat";
2121 my $step_parent = $articles->getByPkey($step_parent_id)
31a26b52
TC
2122 or die "Parent $step_parent_id not found\n";
2123
2124 $req->user_can(edit_stepkid_add => $step_parent)
2125 or die "You don't have access to add a stepkid to that article\n";
ca9aa2bf
TC
2126
2127 my $release = $cgi->param('release');
2128 defined $release
2129 or $release = "01/01/2000";
2130 use BSE::Util::Valid qw/valid_date/;
2131 $release eq '' or valid_date($release)
2132 or die "Invalid release date";
2133 my $expire = $cgi->param('expire');
2134 defined $expire
2135 or $expire = '31/12/2999';
2136 $expire eq '' or valid_date($expire)
2137 or die "Invalid expire data";
2138
2139 my $newentry =
2140 BSE::Admin::StepParents->add($step_parent, $article, $release, $expire);
2141 };
2142 $@ and return $self->refresh($article, $cgi, 'step', $@);
2143
a0a8147b
TC
2144 use Util 'generate_article';
2145 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
2146
8b0b2f34 2147 return $self->refresh($article, $cgi, 'stepparents', 'Stepparent added');
ca9aa2bf
TC
2148}
2149
2150sub del_stepparent {
2151 my ($self, $req, $article, $articles) = @_;
2152
31a26b52
TC
2153 $req->user_can(edit_stepparent_delete => $article)
2154 or return $self->edit_form($req, $article, $articles,
2155 "You cannot remove stepparents from that article");
2156
ca9aa2bf
TC
2157 my $cgi = $req->cgi;
2158 require 'BSE/Admin/StepParents.pm';
2159 my $step_parent_id = $cgi->param('stepparent');
2160 defined($step_parent_id)
2161 or return $self->refresh($article, $cgi, 'stepparents',
2162 "No stepparent supplied to add_stepcat");
2163 int($step_parent_id) eq $step_parent_id
2164 or return $self->refresh($article, $cgi, 'stepparents',
2165 "Invalid stepparent supplied to add_stepparent");
2166 my $step_parent = $articles->getByPkey($step_parent_id)
2167 or return $self->refresh($article, $cgi, 'stepparent',
2168 "Stepparent $step_parent_id not found");
2169
31a26b52
TC
2170 $req->user_can(edit_stepkid_delete => $step_parent)
2171 or die "You don't have access to remove the stepkid from that article\n";
2172
ca9aa2bf
TC
2173 eval {
2174 BSE::Admin::StepParents->del($step_parent, $article);
2175 };
2176 $@ and return $self->refresh($article, $cgi, 'stepparents', $@);
2177
a0a8147b
TC
2178 use Util 'generate_article';
2179 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
2180
8b0b2f34 2181 return $self->refresh($article, $cgi, 'stepparents', 'Stepparent deleted');
ca9aa2bf
TC
2182}
2183
2184sub save_stepparents {
2185 my ($self, $req, $article, $articles) = @_;
2186
31a26b52
TC
2187 $req->user_can(edit_stepparent_save => $article)
2188 or return $self->edit_form($req, $article, $articles,
2189 "No access to save stepparent data for this artice");
2190
ca9aa2bf
TC
2191 my $cgi = $req->cgi;
2192
2193 require 'BSE/Admin/StepParents.pm';
2194 my @stepparents = OtherParents->getBy(childId=>$article->{id});
2195 my %stepparents = map { $_->{parentId}, $_ } @stepparents;
2196 my %datedefs = ( release => '2000-01-01', expire=>'2999-12-31' );
2197 for my $stepparent (@stepparents) {
31a26b52
TC
2198 $req->user_can(edit_stepkid_save => $stepparent->{parentId})
2199 or next;
ca9aa2bf
TC
2200 for my $name (qw/release expire/) {
2201 my $date = $cgi->param($name.'_'.$stepparent->{parentId});
2202 if (defined $date) {
2203 if ($date eq '') {
2204 $date = $datedefs{$name};
2205 }
2206 elsif (valid_date($date)) {
2207 use BSE::Util::SQL qw/date_to_sql/;
2208 $date = date_to_sql($date);
2209 }
2210 else {
2211 return $self->refresh($article, $cgi, "Invalid date '$date'");
2212 }
2213 $stepparent->{$name} = $date;
2214 }
2215 }
2216 eval {
2217 $stepparent->save();
2218 };
2219 $@ and return $self->refresh($article, $cgi, '', $@);
2220 }
2221
a0a8147b
TC
2222 use Util 'generate_article';
2223 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
2224
8b0b2f34
TC
2225 return $self->refresh($article, $cgi, 'stepparents',
2226 'Stepparent information saved');
ca9aa2bf
TC
2227}
2228
58baa27b 2229sub refresh_url {
ca9aa2bf
TC
2230 my ($self, $article, $cgi, $name, $message, $extras) = @_;
2231
8b0b2f34 2232 my $url = $cgi->param('r');
16ac5598
TC
2233 if ($url) {
2234 if ($url !~ /[?&](m|message)=/ && $message) {
2235 # add in messages if none in the provided refresh
2236 my @msgs = ref $message ? @$message : $message;
2237 for my $msg (@msgs) {
2238 $url .= "&m=" . CGI::escape($msg);
2239 }
2240 }
2241 }
2242 else {
41f10371 2243 my $urlbase = admin_base_url($self->{cfg});
8b0b2f34 2244 $url = "$urlbase$ENV{SCRIPT_NAME}?id=$article->{id}";
16ac5598
TC
2245 if ($message) {
2246 my @msgs = ref $message ? @$message : $message;
2247 for my $msg (@msgs) {
2248 $url .= "&m=" . CGI::escape($msg);
2249 }
2250 }
8b0b2f34
TC
2251 if ($cgi->param('_t')) {
2252 $url .= "&_t=".CGI::escape($cgi->param('_t'));
2253 }
2254 $url .= $extras if defined $extras;
2255 my $cgiextras = $cgi->param('e');
2256 $url .= "#$name" if $name;
ca9aa2bf 2257 }
ca9aa2bf 2258
58baa27b
TC
2259 return $url;
2260}
2261
2262sub refresh {
2263 my ($self, $article, $cgi, $name, $message, $extras) = @_;
2264
2265 my $url = $self->refresh_url($article, $cgi, $name, $message, $extras);
2266
ca9aa2bf
TC
2267 return BSE::Template->get_refresh($url, $self->{cfg});
2268}
2269
2270sub show_images {
918735d1 2271 my ($self, $req, $article, $articles, $msg, $errors) = @_;
ca9aa2bf
TC
2272
2273 my %acts;
918735d1 2274 %acts = $self->low_edit_tags(\%acts, $req, $article, $articles, $msg, $errors);
ca9aa2bf
TC
2275 my $template = 'admin/article_img';
2276
4d764c34 2277 return $req->dyn_response($template, \%acts);
ca9aa2bf
TC
2278}
2279
2280sub save_image_changes {
2281 my ($self, $req, $article, $articles) = @_;
2282
abf5bbc6 2283 $req->user_can(edit_images_save => $article)
cc9019d1 2284 or return $self->edit_form($req, $article, $articles,
abf5bbc6
TC
2285 "You don't have access to save image information for this article");
2286
b95fc3a0
TC
2287 my $image_dir = cfg_image_dir($req->cfg);
2288
ca9aa2bf
TC
2289 my $cgi = $req->cgi;
2290 my $image_pos = $cgi->param('imagePos');
2291 if ($image_pos
2292 && $image_pos =~ /^(?:tl|tr|bl|br)$/
2293 && $image_pos ne $article->{imagePos}) {
2294 $article->{imagePos} = $image_pos;
2295 $article->save;
2296 }
daee3409 2297 my @images = $self->get_images($article);
4772671f
TC
2298
2299 @images or
2300 return $self->refresh($article, $cgi, undef, 'No images to save information for');
ca9aa2bf 2301
b95fc3a0
TC
2302 my %changes;
2303 my %errors;
2304 my %names;
e63c3728 2305 my %old_images;
8326f275 2306 my @new_images;
b95fc3a0
TC
2307 for my $image (@images) {
2308 my $id = $image->{id};
2309
2310 my $alt = $cgi->param("alt$id");
2311 if ($alt ne $image->{alt}) {
2312 $changes{$id}{alt} = $alt;
ca9aa2bf 2313 }
b95fc3a0
TC
2314
2315 my $url = $cgi->param("url$id");
2316 if (defined $url && $url ne $image->{url}) {
2317 $changes{$id}{url} = $url;
ca9aa2bf 2318 }
b95fc3a0
TC
2319
2320 my $name = $cgi->param("name$id");
2321 if (defined $name && $name ne $image->{name}) {
547a26ad
TC
2322 if ($name eq '') {
2323 if ($article->{id} > 0) {
2324 $changes{$id}{name} = '';
2325 }
2326 else {
2327 $errors{"name$id"} = "Identifiers are required for global images";
2328 }
2d83755d
TC
2329 }
2330 elsif ($name =~ /^[a-z_]\w*$/i) {
b95fc3a0
TC
2331 my $msg;
2332 if ($self->validate_image_name($name, \$msg)) {
2333 # check for duplicates after the loop
2334 push @{$names{lc $name}}, $image->{id}
2335 if length $name;
2336 $changes{$id}{name} = $name;
4772671f
TC
2337 }
2338 else {
b95fc3a0 2339 $errors{"name$id"} = $msg;
4772671f
TC
2340 }
2341 }
b95fc3a0
TC
2342 else {
2343 $errors{"name$id"} = 'Image name must be empty or alphanumeric and unique to the article';
2344 }
2345 }
2346 else {
2347 push @{$names{lc $image->{name}}}, $image->{id}
2348 if length $image->{name};
2349 }
2350
2351 my $filename = $cgi->param("image$id");
2352 if (defined $filename && length $filename) {
2353 my $in_fh = $cgi->upload("image$id");
2354 if ($in_fh) {
2355 # work out where to put it
2356 require DevHelp::FileUpload;
daee3409 2357 my $msg;
b95fc3a0
TC
2358 my ($image_name, $out_fh) = DevHelp::FileUpload->make_img_filename
2359 ($image_dir, $filename . '', \$msg);
2360 if ($image_name) {
2361 local $/ = \8192;
2362 my $data;
2363 while ($data = <$in_fh>) {
2364 print $out_fh $data;
2365 }
2366 close $out_fh;
2367
2368 my $full_filename = "$image_dir/$image_name";
2369 require Image::Size;
2370 my ($width, $height, $type) = Image::Size::imgsize($full_filename);
2371 if ($width) {
e63c3728
TC
2372 $old_images{$id} =
2373 {
2374 image => $image->{image},
2375 storage => $image->{storage}
2376 };
8326f275
TC
2377 push @new_images, $image_name;
2378
b95fc3a0 2379 $changes{$id}{image} = $image_name;
e63c3728
TC
2380 $changes{$id}{storage} = 'local';
2381 $changes{$id}{src} = "/images/$image_name";
b95fc3a0
TC
2382 $changes{$id}{width} = $width;
2383 $changes{$id}{height} = $height;
5d1b1cbb 2384 $changes{$id}{ftype} = $self->_image_ftype($type);
b95fc3a0
TC
2385 }
2386 else {
2387 $errors{"image$id"} = $type;
2388 }
2389 }
2390 else {
2391 $errors{"image$id"} = $msg;
2392 }
2393 }
2394 else {
2395 # problem uploading
2396 $errors{"image$id"} = "No image file received";
2397 }
2398 }
2399 }
2400 # look for duplicate names
2401 for my $name (keys %names) {
2402 if (@{$names{$name}} > 1) {
2403 for my $id (@{$names{$name}}) {
2404 $errors{"name$id"} = 'Image name must be unique to the article';
daee3409 2405 }
4772671f
TC
2406 }
2407 }
8326f275
TC
2408 if (keys %errors) {
2409 # remove files that won't be stored because validation failed
2410 unlink map "$image_dir/$_", @new_images;
2411
2412 return $self->edit_form($req, $article, $articles, undef,
2413 \%errors);
2414 }
b95fc3a0 2415
e63c3728
TC
2416 my $mgr = $self->_image_manager($req->cfg);
2417 $req->flash('Image information saved');
2418 my $changes_found = 0;
2419 my $auto_store = $cgi->param('auto_storage');
2420 for my $image (@images) {
2421 my $id = $image->{id};
2422
2423 if ($changes{$id}) {
2424 my $changes = $changes{$id};
2425 ++$changes_found;
2426
2427 for my $field (keys %$changes) {
2428 $image->{$field} = $changes->{$field};
b95fc3a0 2429 }
ca9aa2bf
TC
2430 $image->save;
2431 }
a0a8147b 2432
e63c3728
TC
2433 my $old_storage = $image->{storage};
2434 my $new_storage = $auto_store ? '' : $cgi->param("storage$id");
2435 defined $new_storage or $new_storage = $image->{storage};
2436 $new_storage = $mgr->select_store($image->{image}, $new_storage, $image);
2437 if ($new_storage ne $old_storage) {
2438 eval {
2439 $image->{src} = $mgr->store($image->{image}, $new_storage, $image);
2440 $image->{storage} = $new_storage;
2441 $image->save;
2442 };
2443
2444 if ($old_storage ne 'local') {
2445 $mgr->unstore($image->{image}, $old_storage);
2446 }
2447 }
2448 }
2449
2450 # delete any image files that were replaced
2451 for my $old_image (values %old_images) {
2452 my ($image, $storage) = @$old_image{qw/image storage/};
2453 if ($storage ne 'local') {
2454 $mgr->unstore($image->{image}, $storage);
2455 }
2456 unlink "$image_dir/$image";
2457 }
2458
2459 if ($changes_found) {
b95fc3a0
TC
2460 use Util 'generate_article';
2461 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
2462 }
e63c3728
TC
2463
2464 return $self->refresh($article, $cgi);
ca9aa2bf
TC
2465}
2466
58baa27b
TC
2467=item _service_error
2468
2469This function is called on various errors.
2470
2471If a _service parameter was supplied, returns text like:
2472
2473=over
2474
2475Result: failure
2476
2477Field-Error: I<field-name1> - I<message1>
2478
2479Field-Error: I<field-name2> - I<message2>
2480
2481=back
2482
2483If the request is detected as an ajax request or a _ parameter is
2484supplied, return JSON like:
2485
2486 { error: I<message> }
2487
2488Otherwise display the normal edit page with the error.
2489
2490=cut
2491
dbcd12e5 2492sub _service_error {
bf87e97c 2493 my ($self, $req, $article, $articles, $msg, $error) = @_;
dbcd12e5
TC
2494
2495 if ($req->cgi->param('_service')) {
2496 my $body = '';
2497 $body .= "Result: failure\n";
2498 if (ref $error) {
2499 for my $field (keys %$error) {
2500 my $text = $error->{$field};
2501 $text =~ tr/\n/ /;
2502 $body .= "Field-Error: $field - $text\n";
2503 }
2504 my $text = join ('/', values %$error);
2505 $text =~ tr/\n/ /;
2506 $body .= "Error: $text\n";
2507 }
58baa27b
TC
2508 elsif ($msg) {
2509 $body .= "Error: $msg\n";
2510 }
dbcd12e5
TC
2511 else {
2512 $body .= "Error: $error\n";
2513 }
2514 return
2515 {
2516 type => 'text/plain',
2517 content => $body,
2518 };
2519 }
58baa27b
TC
2520 elsif ((() = $req->cgi->param('_')) ||
2521 (defined $ENV{HTTP_X_REQUESTED_WITH}
2522 && $ENV{HTTP_X_REQUESTED_WITH} =~ /XMLHttpRequest/)) {
9b3a5df0
TC
2523 $error ||= {};
2524 my $result = { errors => $error };
2525 $msg and $result->{message} = $msg;
2526 return $req->json_content($result);
58baa27b 2527 }
dbcd12e5 2528 else {
bf87e97c 2529 return $self->edit_form($req, $article, $articles, $msg, $error);
dbcd12e5
TC
2530 }
2531}
2532
2533sub _service_success {
2534 my ($self, $results) = @_;
2535
2536 my $body = "Result: success\n";
2537 for my $field (keys %$results) {
2538 $body .= "$field: $results->{$field}\n";
2539 }
2540 return
2541 {
2542 type => 'text/plain',
2543 content => $body,
2544 };
2545}
2546
5d1b1cbb
TC
2547sub _image_ftype {
2548 my ($self, $type) = @_;
2549
2550 if ($type eq 'CWS' || $type eq 'SWF') {
2551 return "flash";
2552 }
2553
2554 return "img";
2555}
2556
bf87e97c
TC
2557sub do_add_image {
2558 my ($self, $cfg, $article, $image, %opts) = @_;
ca9aa2bf 2559
bf87e97c
TC
2560 my $errors = $opts{errors}
2561 or die "No errors parameter";
ca9aa2bf 2562
bf87e97c 2563 my $imageref = $opts{name};
d794b180 2564 if (defined $imageref && $imageref ne '') {
4772671f
TC
2565 if ($imageref =~ /^[a-z_]\w+$/i) {
2566 # make sure it's unique
daee3409 2567 my @images = $self->get_images($article);
4772671f
TC
2568 for my $img (@images) {
2569 if (defined $img->{name} && lc $img->{name} eq lc $imageref) {
bf87e97c 2570 $errors->{name} = 'Image name must be unique to the article';
4772671f
TC
2571 last;
2572 }
2573 }
2574 }
2575 else {
bf87e97c 2576 $errors->{name} = 'Image name must be empty or alphanumeric beginning with an alpha character';
4772671f
TC
2577 }
2578 }
2579 else {
2580 $imageref = '';
2581 }
bf87e97c 2582 unless ($errors->{name}) {
d09682dd
TC
2583 my $workmsg;
2584 $self->validate_image_name($imageref, \$workmsg)
bf87e97c 2585 or $errors->{name} = $workmsg;
daee3409 2586 }
4772671f 2587
4772671f
TC
2588 if ($image) {
2589 if (-z $image) {
bf87e97c 2590 $errors->{image} = 'Image file is empty';
4772671f 2591 }
ca9aa2bf 2592 }
4772671f 2593 else {
bf87e97c 2594 $errors->{image} = 'Please enter an image filename';
ca9aa2bf 2595 }
bf87e97c
TC
2596 keys %$errors
2597 and return;
4772671f 2598
bf87e97c 2599 my $imagename = $opts{filename} || $image;
ca9aa2bf
TC
2600 $imagename .= ''; # force it into a string
2601 my $basename = '';
bf87e97c 2602 $imagename =~ tr/ //d;
ca9aa2bf
TC
2603 $imagename =~ /([\w.-]+)$/ and $basename = $1;
2604
2605 # create a filename that we hope is unique
2606 my $filename = time. '_'. $basename;
2607
2608 # for the sysopen() constants
2609 use Fcntl;
2610
bf87e97c 2611 my $imagedir = cfg_image_dir($cfg);
ca9aa2bf
TC
2612 # loop until we have a unique filename
2613 my $counter="";
2614 $filename = time. '_' . $counter . '_' . $basename
2615 until sysopen( OUTPUT, "$imagedir/$filename", O_WRONLY| O_CREAT| O_EXCL)
2616 || ++$counter > 100;
2617
2618 fileno(OUTPUT) or die "Could not open image file: $!";
2619
2620 # for OSs with special text line endings
2621 binmode OUTPUT;
2622
2623 my $buffer;
2624
2625 no strict 'refs';
2626
2627 # read the image in from the browser and output it to our output filehandle
2628 print OUTPUT $buffer while read $image, $buffer, 1024;
2629
2630 # close and flush
2631 close OUTPUT
2632 or die "Could not close image file $filename: $!";
2633
2634 use Image::Size;
2635
2636
f40af7e2 2637 my($width,$height, $type) = imgsize("$imagedir/$filename");
ca9aa2bf 2638
bf87e97c 2639 my $alt = $opts{alt};
ca9aa2bf 2640 defined $alt or $alt = '';
bf87e97c 2641 my $url = $opts{url};
ca9aa2bf
TC
2642 defined $url or $url = '';
2643 my %image =
2644 (
2645 articleId => $article->{id},
2646 image => $filename,
2647 alt=>$alt,
2648 width=>$width,
2649 height => $height,
2650 url => $url,
2651 displayOrder=>time,
4772671f 2652 name => $imageref,
e63c3728
TC
2653 storage => 'local',
2654 src => '/images/' . $filename,
5d1b1cbb 2655 ftype => $self->_image_ftype($type),
ca9aa2bf 2656 );
f40af7e2
TC
2657 require BSE::TB::Images;
2658 my @cols = BSE::TB::Image->columns;
ca9aa2bf 2659 shift @cols;
f40af7e2 2660 my $imageobj = BSE::TB::Images->add(@image{@cols});
a0a8147b 2661
bf87e97c 2662 my $storage = $opts{storage};
e63c3728 2663 defined $storage or $storage = 'local';
bf87e97c 2664 my $image_manager = $self->_image_manager($cfg);
e63c3728
TC
2665 local $SIG{__DIE__};
2666 eval {
2667 my $src;
2668 $storage = $image_manager->select_store($filename, $storage, $imageobj);
2669 $src = $image_manager->store($filename, $storage, $imageobj);
2670
2671 if ($src) {
2672 $imageobj->{src} = $src;
2673 $imageobj->{storage} = $storage;
2674 $imageobj->save;
2675 }
2676 };
2677 if ($@) {
bf87e97c 2678 $errors->{flash} = $@;
e63c3728
TC
2679 }
2680
bf87e97c
TC
2681 return $imageobj;
2682}
2683
2684sub add_image {
2685 my ($self, $req, $article, $articles) = @_;
2686
2687 $req->user_can(edit_images_add => $article)
2688 or return $self->_service_error($req, $article, $articles,
2689 "You don't have access to add new images to this article");
2690
2691 my $cgi = $req->cgi;
2692 my %errors;
2693 my $imageobj =
2694 $self->do_add_image
2695 (
2696 $req->cfg,
2697 $article,
2698 scalar($cgi->param('image')),
2699 name => scalar($cgi->param('name')),
2700 alt => scalar($cgi->param('altIn')),
2701 url => scalar($cgi->param('url')),
2702 storage => scalar($cgi->param('storage')),
2703 errors => \%errors,
2704 );
2705
2706 $imageobj
2707 or return $self->_service_error($req, $article, $articles, undef, \%errors);
2708
2709 # typically a soft failure from the storage
2710 $errors{flash}
2711 and $req->flash($errors{flash});
2712
a0a8147b
TC
2713 use Util 'generate_article';
2714 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
2715
dbcd12e5
TC
2716 if ($cgi->param('_service')) {
2717 return $self->_service_success
2718 (
2719 {
2720 image => $imageobj->{id},
2721 },
2722 );
2723 }
2724 else {
2725 return $self->refresh($article, $cgi, undef, 'New image added');
2726 }
ca9aa2bf
TC
2727}
2728
e63c3728
TC
2729sub _image_manager {
2730 my ($self) = @_;
2731
2732 require BSE::StorageMgr::Images;
2733
2734 return BSE::StorageMgr::Images->new(cfg => $self->cfg);
2735}
2736
ca9aa2bf
TC
2737# remove an image
2738sub remove_img {
2739 my ($self, $req, $article, $articles, $imageid) = @_;
2740
abf5bbc6 2741 $req->user_can(edit_images_delete => $article)
cc9019d1 2742 or return $self->edit_form($req, $article, $articles,
abf5bbc6
TC
2743 "You don't have access to delete images from this article");
2744
ca9aa2bf
TC
2745 $imageid or die;
2746
daee3409 2747 my @images = $self->get_images($article);
ca9aa2bf
TC
2748 my ($image) = grep $_->{id} == $imageid, @images
2749 or return $self->show_images($req, $article, $articles, "No such image");
e63c3728
TC
2750
2751 if ($image->{storage} ne 'local') {
2752 my $mgr = $self->_image_manager($req->cfg);
2753 $mgr->unstore($image->{image}, $image->{storage});
2754 }
2755
ab2cd916 2756 my $imagedir = cfg_image_dir($req->cfg);
6473c56f 2757 unlink "$imagedir$image->{image}";
ca9aa2bf
TC
2758 $image->remove;
2759
a0a8147b
TC
2760 use Util 'generate_article';
2761 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
2762
cc9019d1 2763 return $self->refresh($article, $req->cgi, undef, 'Image removed');
ca9aa2bf
TC
2764}
2765
2766sub move_img_up {
2767 my ($self, $req, $article, $articles) = @_;
2768
abf5bbc6 2769 $req->user_can(edit_images_reorder => $article)
cc9019d1 2770 or return $self->edit_form($req, $article, $articles,
abf5bbc6
TC
2771 "You don't have access to reorder images in this article");
2772
ca9aa2bf 2773 my $imageid = $req->cgi->param('imageid');
daee3409 2774 my @images = $self->get_images($article);
ca9aa2bf 2775 my ($imgindex) = grep $images[$_]{id} == $imageid, 0..$#images
cc9019d1 2776 or return $self->edit_form($req, $article, $articles, "No such image");
ca9aa2bf 2777 $imgindex > 0
cc9019d1 2778 or return $self->edit_form($req, $article, $articles, "Image is already at the top");
ca9aa2bf
TC
2779 my ($to, $from) = @images[$imgindex-1, $imgindex];
2780 ($to->{displayOrder}, $from->{displayOrder}) =
2781 ($from->{displayOrder}, $to->{displayOrder});
2782 $to->save;
2783 $from->save;
2784
a0a8147b
TC
2785 use Util 'generate_article';
2786 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
2787
cc9019d1 2788 return $self->refresh($article, $req->cgi, undef, 'Image moved');
ca9aa2bf
TC
2789}
2790
2791sub move_img_down {
2792 my ($self, $req, $article, $articles) = @_;
2793
abf5bbc6 2794 $req->user_can(edit_images_reorder => $article)
cc9019d1 2795 or return $self->edit_form($req, $article, $articles,
abf5bbc6
TC
2796 "You don't have access to reorder images in this article");
2797
ca9aa2bf 2798 my $imageid = $req->cgi->param('imageid');
daee3409 2799 my @images = $self->get_images($article);
ca9aa2bf 2800 my ($imgindex) = grep $images[$_]{id} == $imageid, 0..$#images
cc9019d1 2801 or return $self->edit_form($req, $article, $articles, "No such image");
ca9aa2bf 2802 $imgindex < $#images
cc9019d1 2803 or return $self->edit_form($req, $article, $articles, "Image is already at the end");
ca9aa2bf
TC
2804 my ($to, $from) = @images[$imgindex+1, $imgindex];
2805 ($to->{displayOrder}, $from->{displayOrder}) =
2806 ($from->{displayOrder}, $to->{displayOrder});
2807 $to->save;
2808 $from->save;
2809
a0a8147b
TC
2810 use Util 'generate_article';
2811 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
2812
cc9019d1 2813 return $self->refresh($article, $req->cgi, undef, 'Image moved');
ca9aa2bf
TC
2814}
2815
ab2cd916
TC
2816sub req_thumb {
2817 my ($self, $req, $article) = @_;
2818
2819 my $cgi = $req->cgi;
2820 my $cfg = $req->cfg;
2821 my $im_id = $cgi->param('im');
2822 my $image;
2823 if (defined $im_id && $im_id =~ /^\d+$/) {
6a8a6ac5 2824 ($image) = grep $_->{id} == $im_id, $self->get_images($article);
ab2cd916
TC
2825 }
2826 my $thumb_obj = $self->_get_thumbs_class();
2827 my ($data, $type);
2828 if ($image && $thumb_obj) {
195977cd
TC
2829 my $geometry_id = $cgi->param('g');
2830 defined $geometry_id or $geometry_id = 'editor';
dbcd12e5 2831 my $geometry = $cfg->entry('thumb geometries', $geometry_id, 'scale(200x200)');
ab2cd916
TC
2832 my $imagedir = $cfg->entry('paths', 'images', $Constants::IMAGEDIR);
2833
195977cd 2834 my $error;
6430ee52
TC
2835 ($data, $type) = $thumb_obj->thumb_data
2836 (
2837 filename => "$imagedir/$image->{image}",
2838 geometry => $geometry,
2839 error => \$error
2840 )
d9f8d6b9
TC
2841 or return
2842 {
2843 type => 'text/plain',
2844 content => 'Error: '.$error
2845 };
ab2cd916
TC
2846 }
2847
2848 if ($type && $data) {
2849
2850 return
2851 {
2852 type => $type,
2853 content => $data,
2854 headers => [
2855 "Content-Length: ".length($data),
2856 "Cache-Control: max-age=3600",
2857 ],
2858 };
2859 }
2860 else {
2861 # grab the nothumb image
2862 my $uri = $cfg->entry('editor', 'default_thumbnail', '/images/admin/nothumb.png');
2863 my $filebase = $Constants::CONTENTBASE;
2864 if (open IMG, "<$filebase/$uri") {
2865 binmode IMG;
2866 my $data = do { local $/; <IMG> };
2867 close IMG;
2868 my $type = $uri =~ /\.(\w+)$/ ? $1 : 'png';
2869 return
2870 {
2871 type => "image/$type",
2872 content => $data,
2873 headers => [ "Content-Length: ".length($data) ],
2874 };
2875 }
2876 else {
2877 return
2878 {
2879 type=>"text/html",
2880 content => "<html><body>Cannot make thumb or default image</body></html>",
2881 };
2882 }
2883 }
2884}
2885
b95fc3a0
TC
2886sub req_edit_image {
2887 my ($self, $req, $article, $articles, $errors) = @_;
2888
2889 my $cgi = $req->cgi;
2890
2891 my $id = $cgi->param('image_id');
2892
7303cf10 2893 my ($image) = grep $_->{id} == $id, $self->get_images($article)
b95fc3a0
TC
2894 or return $self->edit_form($req, $article, $articles,
2895 "No such image");
2896 $req->user_can(edit_images_save => $article)
2897 or return $self->edit_form($req, $article, $articles,
2898 "You don't have access to save image information for this article");
2899
2900 my %acts;
2901 %acts =
2902 (
2903 $self->low_edit_tags(\%acts, $req, $article, $articles, undef,
2904 $errors),
2905 eimage => [ \&tag_hash, $image ],
7303cf10 2906 error_img => [ \&tag_error_img, $req->cfg, $errors ],
b95fc3a0
TC
2907 );
2908
2909 return $req->response('admin/image_edit', \%acts);
2910}
2911
2912sub req_save_image {
2913 my ($self, $req, $article, $articles) = @_;
2914
2915 my $cgi = $req->cgi;
2916
2917 my $id = $cgi->param('image_id');
2918
7303cf10 2919 my @images = $self->get_images($article);
b95fc3a0
TC
2920 my ($image) = grep $_->{id} == $id, @images
2921 or return $self->edit_form($req, $article, $articles,
2922 "No such image");
2923 $req->user_can(edit_images_save => $article)
2924 or return $self->edit_form($req, $article, $articles,
2925 "You don't have access to save image information for this article");
2926
2927 my $image_dir = cfg_image_dir($req->cfg);
2928
e63c3728
TC
2929 my $old_storage = $image->{storage};
2930
b95fc3a0
TC
2931 my %errors;
2932 my $delete_file;
2933 my $alt = $cgi->param('alt');
2934 defined $alt and $image->{alt} = $alt;
2935 my $url = $cgi->param('url');
2936 defined $url and $image->{url} = $url;
2937 my @other_images = grep $_->{id} != $id, @images;
2938 my $name = $cgi->param('name');
2939 if (defined $name) {
2940 if (length $name) {
2941 if ($name !~ /^[a-z_]\w*$/i) {
2942 $errors{name} = 'Image name must be empty or alphanumeric and unique to the article';
2943 }
2944 elsif (grep $name eq $_->{name}, @other_images) {
2945 $errors{name} = 'Image name must be unique to the article';
2946 }
2947 else {
2948 $image->{name} = $name;
2949 }
2950 }
2d83755d 2951 else {
547a26ad
TC
2952 if ($article->{id} == -1) {
2953 $errors{name} = "Identifiers are required for global images";
2954 }
2955 else {
2956 $image->{name} = '';
2957 }
2d83755d 2958 }
b95fc3a0
TC
2959 }
2960 my $filename = $cgi->param('image');
2961 if (defined $filename && length $filename) {
2962 my $in_fh = $cgi->upload('image');
2963 if ($in_fh) {
2964 require DevHelp::FileUpload;
2965 my $msg;
2966 my ($image_name, $out_fh) = DevHelp::FileUpload->make_img_filename
2967 ($image_dir, $filename . '', \$msg);
2968 if ($image_name) {
2969 {
2970 local $/ = \8192;
2971 my $data;
2972 while ($data = <$in_fh>) {
2973 print $out_fh $data;
2974 }
2975 close $out_fh;
2976 }
2977
2978 my $full_filename = "$image_dir/$image_name";
2979 require Image::Size;
2980 my ($width, $height, $type) = Image::Size::imgsize($full_filename);
2981 if ($width) {
2982 $delete_file = $image->{image};
2983 $image->{image} = $image_name;
2984 $image->{width} = $width;
2985 $image->{height} = $height;
e63c3728
TC
2986 $image->{storage} = 'local'; # not on the remote store yet
2987 $image->{src} = '/images/' . $image_name;
5d1b1cbb 2988 $image->{ftype} = $self->_image_ftype($type);
b95fc3a0
TC
2989 }
2990 else {
2991 $errors{image} = $type;
2992 }
2993 }
2994 else {
2995 $errors{image} = $msg;
2996 }
2997 }
2998 else {
2999 $errors{image} = "No image file received";
3000 }
3001 }
3002 keys %errors
3003 and return $self->req_edit_image($req, $article, $articles, \%errors);
3004
e63c3728
TC
3005 my $new_storage = $cgi->param('storage');
3006 defined $new_storage or $new_storage = $image->{storage};
b95fc3a0 3007 $image->save;
e63c3728
TC
3008 my $mgr = $self->_image_manager($req->cfg);
3009 if ($delete_file) {
3010 if ($old_storage ne 'local') {
3011 $mgr->unstore($delete_file, $old_storage);
3012 }
3013 unlink "$image_dir/$delete_file";
3014 }
3015 $req->flash("Image saved");
3016 eval {
3017 $new_storage =
3018 $mgr->select_store($image->{image}, $new_storage);
3019 if ($image->{storage} ne $new_storage) {
3020 # handles both new images (which sets storage to local) and changing
3021 # the storage for old images
3022 my $old_storage = $image->{storage};
3023 my $src = $mgr->store($image->{image}, $new_storage, $image);
3024 $image->{src} = $src;
3025 $image->{storage} = $new_storage;
3026 $image->save;
3027 }
3028 };
3029 $@ and $req->flash("There was a problem adding it to the new storage: $@");
3030 if ($image->{storage} ne $old_storage && $old_storage ne 'local') {
3031 eval {
3032 $mgr->unstore($image->{image}, $old_storage);
3033 };
3034 $@ and $req->flash("There was a problem removing if from the old storage: $@");
3035 }
b95fc3a0 3036
e63c3728 3037 return $self->refresh($article, $cgi);
b95fc3a0
TC
3038}
3039
ca9aa2bf
TC
3040sub get_article {
3041 my ($self, $articles, $article) = @_;
3042
3043 return $article;
3044}
3045
3046sub table_object {
3047 my ($self, $articles) = @_;
3048
3049 $articles;
3050}
3051
ca9aa2bf 3052sub _refresh_filelist {
8b0b2f34 3053 my ($self, $req, $article, $msg) = @_;
ca9aa2bf 3054
cc9019d1 3055 return $self->refresh($article, $req->cgi, undef, $msg);
ca9aa2bf
TC
3056}
3057
3058sub filelist {
918735d1 3059 my ($self, $req, $article, $articles, $msg, $errors) = @_;
ca9aa2bf
TC
3060
3061 my %acts;
918735d1 3062 %acts = $self->low_edit_tags(\%acts, $req, $article, $articles, $msg, $errors);
ca9aa2bf
TC
3063 my $template = 'admin/filelist';
3064
3065 return BSE::Template->get_response($template, $req->cfg, \%acts);
3066}
3067
4b69925d
TC
3068my %file_fields =
3069 (
3070 file =>
3071 {
3072 maxlength => MAX_FILE_DISPLAYNAME_LENGTH,
3073 description => 'Filename'
3074 },
3075 description =>
3076 {
3077 rules => 'dh_one_line',
3078 maxlength => 255,
3079 description => 'Description',
3080 },
3081 name =>
3082 {
3083 description => 'Identifier',
3084 maxlength => 80,
3085 },
6430ee52
TC
3086 category =>
3087 {
3088 description => "Category",
3089 maxlength => 20,
3090 },
4b69925d
TC
3091 );
3092
ca9aa2bf
TC
3093sub fileadd {
3094 my ($self, $req, $article, $articles) = @_;
3095
abf5bbc6 3096 $req->user_can(edit_files_add => $article)
cc9019d1 3097 or return $self->edit_form($req, $article, $articles,
abf5bbc6
TC
3098 "You don't have access to add files to this article");
3099
ca9aa2bf
TC
3100 my %file;
3101 my $cgi = $req->cgi;
6430ee52
TC
3102 require BSE::TB::ArticleFiles;
3103 my @cols = BSE::TB::ArticleFile->columns;
ca9aa2bf
TC
3104 shift @cols;
3105 for my $col (@cols) {
3106 if (defined $cgi->param($col)) {
3107 $file{$col} = $cgi->param($col);
3108 }
3109 }
c5286ebe
TC
3110
3111 my %errors;
ca9aa2bf 3112
4b69925d
TC
3113 $req->validate(errors => \%errors,
3114 fields => \%file_fields,
3115 section => $article->{id} == -1 ? 'Global File Validation' : 'Article File Validation');
7646d96e 3116
ca9aa2bf
TC
3117 # build a filename
3118 my $file = $cgi->param('file');
3119 unless ($file) {
c5286ebe 3120 $errors{file} = 'Please enter a filename';
ca9aa2bf 3121 }
c5286ebe
TC
3122 if ($file && -z $file) {
3123 $errors{file} = 'File is empty';
ca9aa2bf 3124 }
7646d96e
TC
3125
3126 $file{forSale} = 0 + exists $file{forSale};
3127 $file{articleId} = $article->{id};
3128 $file{download} = 0 + exists $file{download};
3129 $file{requireUser} = 0 + exists $file{requireUser};
3130 $file{hide_from_list} = 0 + exists $file{hide_from_list};
3131 $file{category} ||= '';
c5286ebe
TC
3132
3133 defined $file{name} or $file{name} = '';
9366cd70
TC
3134 if ($article->{id} == -1 && $file{name} eq '') {
3135 $errors{name} = 'Identifier is required for global files';
3136 }
3137 if (!$errors{name} && length $file{name} && $file{name} !~/^\w+$/) {
c5286ebe
TC
3138 $errors{name} = "Identifier must be a single word";
3139 }
3140 if (!$errors{name} && length $file{name}) {
9366cd70 3141 my @files = $self->get_files($article);
c5286ebe
TC
3142 if (grep lc $_->{name} eq lc $file{name}, @files) {
3143 $errors{name} = "Duplicate file identifier $file{name}";
3144 }
3145 }
3146
3147 keys %errors
3148 and return $self->edit_form($req, $article, $articles, undef, \%errors);
ca9aa2bf
TC
3149
3150 my $basename = '';
6a8a205a
TC
3151 my $workfile = $file;
3152 $workfile =~ s![^\w.:/\\-]+!_!g;
3153 $workfile =~ tr/_/_/s;
3154 $workfile =~ /([ \w.-]+)$/ and $basename = $1;
f0543260 3155 $basename =~ tr/ /_/;
7646d96e
TC
3156 $file{displayName} = $basename;
3157 $file{file} = $file;
ca9aa2bf 3158
7646d96e
TC
3159 local $SIG{__DIE__};
3160 my $fileobj =
3161 eval {
3162 $article->add_file($self->cfg, %file);
3163 };
4b69925d 3164
7646d96e
TC
3165 $fileobj
3166 or return $self->edit_form($req, $article, $articles, $@);
4b69925d 3167
7646d96e 3168 $req->flash("New file added");
ca9aa2bf 3169
cf34aa90 3170 my $storage = $cgi->param("storage") || "";
7646d96e
TC
3171 eval {
3172 my $msg;
ca9aa2bf 3173
7646d96e 3174 $article->apply_storage($self->cfg, $fileobj, $storage, \$msg);
ca9aa2bf 3175
7646d96e
TC
3176 $msg and $req->flash($msg);
3177 };
3178 $@
3179 and $req->flash($@);
ca9aa2bf 3180
7646d96e 3181# my $downloadPath = $self->{cfg}->entryVar('paths', 'downloads');
ca9aa2bf 3182
ca9aa2bf 3183
7646d96e
TC
3184# unless ($file{contentType}) {
3185# unless ($file =~ /\.([^.]+)$/) {
3186# $file{contentType} = "application/octet-stream";
3187# }
3188# unless ($file{contentType}) {
3189# $file{contentType} = content_type($self->cfg, $file);
3190# }
3191# }
ca9aa2bf 3192
ca9aa2bf 3193
7646d96e
TC
3194# # if the user supplies a really long filename, it can overflow the
3195# # filename field
ca9aa2bf 3196
7646d96e
TC
3197# my $work_filename = $basename;
3198# if (length $work_filename > 60) {
3199# $work_filename = substr($work_filename, -60);
3200# }
ca9aa2bf 3201
7646d96e 3202# my $filename = time. '_'. $work_filename;
ca9aa2bf 3203
7646d96e
TC
3204# # for the sysopen() constants
3205# use Fcntl;
e63c3728 3206
7646d96e
TC
3207# # loop until we have a unique filename
3208# my $counter="";
3209# $filename = time. '_' . $counter . '_' . $work_filename
3210# until sysopen( OUTPUT, "$downloadPath/$filename",
3211# O_WRONLY| O_CREAT| O_EXCL)
3212# || ++$counter > 100;
e63c3728 3213
7646d96e 3214# fileno(OUTPUT) or die "Could not open file: $!";
6430ee52 3215
7646d96e
TC
3216# # for OSs with special text line endings
3217# binmode OUTPUT;
e63c3728 3218
7646d96e
TC
3219# my $buffer;
3220
3221# no strict 'refs';
3222
3223# # read the image in from the browser and output it to our output filehandle
3224# print OUTPUT $buffer while read $file, $buffer, 8192;
3225
3226# # close and flush
3227# close OUTPUT
3228# or die "Could not close file $filename: $!";
3229
3230# use BSE::Util::SQL qw/now_datetime/;
3231# $file{filename} = $filename;
3232# $file{displayName} = $basename;
3233# $file{sizeInBytes} = -s $file;
3234# $file{displayOrder} = time;
3235# $file{whenUploaded} = now_datetime();
3236# $file{storage} = 'local';
3237# $file{src} = '';
3238# $file{file_handler} = "";
3239
3240# require BSE::TB::ArticleFiles;
3241# my $fileobj = BSE::TB::ArticleFiles->add(@file{@cols});
3242
3243# my $storage = $cgi->param('storage');
3244# defined $storage or $storage = 'local';
3245# my $file_manager = $self->_file_manager($req->cfg);
3246
3247# local $SIG{__DIE__};
3248# eval {
3249# my $src;
3250# $storage = $self->_select_filestore($req, $file_manager, $storage, $fileobj);
3251# $src = $file_manager->store($filename, $storage, $fileobj);
3252
3253# if ($src) {
3254# $fileobj->{src} = $src;
3255# $fileobj->{storage} = $storage;
3256# $fileobj->save;
3257# }
3258# };
3259# if ($@) {
3260# $req->flash($@);
3261# }
3262
3263# $fileobj->set_handler($req->cfg);
3264# $fileobj->save;
6430ee52 3265
a0a8147b
TC
3266 use Util 'generate_article';
3267 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
3268
e63c3728 3269 $self->_refresh_filelist($req, $article);
ca9aa2bf
TC
3270}
3271
3272sub fileswap {
3273 my ($self, $req, $article, $articles) = @_;
3274
abf5bbc6 3275 $req->user_can('edit_files_reorder', $article)
cc9019d1 3276 or return $self->edit_form($req, $article, $articles,
abf5bbc6
TC
3277 "You don't have access to reorder files in this article");
3278
ca9aa2bf
TC
3279 my $cgi = $req->cgi;
3280 my $id1 = $cgi->param('file1');
3281 my $id2 = $cgi->param('file2');
3282
3283 if ($id1 && $id2) {
9366cd70 3284 my @files = $self->get_files($article);
ca9aa2bf
TC
3285
3286 my ($file1) = grep $_->{id} == $id1, @files;
3287 my ($file2) = grep $_->{id} == $id2, @files;
3288
3289 if ($file1 && $file2) {
3290 ($file1->{displayOrder}, $file2->{displayOrder})
3291 = ($file2->{displayOrder}, $file1->{displayOrder});
3292 $file1->save;
3293 $file2->save;
3294 }
3295 }
3296
a0a8147b
TC
3297 use Util 'generate_article';
3298 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
3299
9063386f 3300 $self->refresh($article, $req->cgi, undef, 'File moved');
ca9aa2bf
TC
3301}
3302
3303sub filedel {
3304 my ($self, $req, $article, $articles) = @_;
3305
abf5bbc6 3306 $req->user_can('edit_files_delete', $article)
cc9019d1
TC
3307 or return $self->edit_form($req, $article, $articles,
3308 "You don't have access to delete files from this article");
abf5bbc6 3309
ca9aa2bf
TC
3310 my $cgi = $req->cgi;
3311 my $fileid = $cgi->param('file');
3312 if ($fileid) {
9366cd70 3313 my @files = $self->get_files($article);
ca9aa2bf
TC
3314
3315 my ($file) = grep $_->{id} == $fileid, @files;
3316
3317 if ($file) {
e63c3728 3318 if ($file->{storage} ne 'local') {
7646d96e 3319 my $mgr = $self->_file_manager($self->cfg);
81ad8108 3320 $mgr->unstore($file->{filename}, $file->{storage});
e63c3728
TC
3321 }
3322
16901a2a 3323 $file->remove($req->cfg);
ca9aa2bf
TC
3324 }
3325 }
3326
a0a8147b
TC
3327 use Util 'generate_article';
3328 generate_article($articles, $article) if $Constants::AUTO_GENERATE;
3329
8b0b2f34 3330 $self->_refresh_filelist($req, $article, 'File deleted');
ca9aa2bf
TC
3331}
3332
3333sub filesave {
abf5bbc6 3334 my ($self, $req, $article, $articles) = @_;
ca9aa2bf 3335
abf5bbc6 3336 $req->user_can('edit_files_save', $article)
cc9019d1 3337 or return $self->edit_form($req, $article, $articles,
abf5bbc6 3338 "You don't have access to save file information for this article");
9366cd70 3339 my @files = $self->get_files($article);
ca9aa2bf 3340
6430ee52 3341 my $download_path = BSE::TB::ArticleFiles->download_path($self->{cfg});
8326f275 3342
ca9aa2bf 3343 my $cgi = $req->cgi;
b95fc3a0
TC
3344 my %names;
3345 my %errors;
8326f275
TC
3346 my @old_files;
3347 my @new_files;
e63c3728 3348 my %store_anyway;
6430ee52 3349 my @content_changed;
ca9aa2bf 3350 for my $file (@files) {
b8e8b584 3351 my $id = $file->{id};
b95fc3a0
TC
3352 my $desc = $cgi->param("description_$id");
3353 defined $desc and $file->{description} = $desc;
3354 my $type = $cgi->param("contentType_$id");
e63c3728
TC
3355 if (defined $type and $type ne $file->{contentType}) {
3356 ++$store_anyway{$id};
3357 $file->{contentType} = $type;
3358 }
b95fc3a0
TC
3359 my $notes = $cgi->param("notes_$id");
3360 defined $notes and $file->{notes} = $notes;
6430ee52
TC
3361 my $category = $cgi->param("category_$id");
3362 defined $category and $file->{category} = $category;
b95fc3a0
TC
3363 my $name = $cgi->param("name_$id");
3364 if (defined $name) {
3365 $file->{name} = $name;
3366 if (length $name) {
3367 if ($name =~ /^\w+$/) {
b2a9e505 3368 push @{$names{$name}}, $id;
b95fc3a0
TC
3369 }
3370 else {
3371 $errors{"name_$id"} = "Invalid file identifier $name";
3372 }
c5286ebe 3373 }
9366cd70
TC
3374 elsif ($article->{id} == -1) {
3375 $errors{"name_$id"} = "Identifier is required for global files";
3376 }
b95fc3a0
TC
3377 }
3378 else {
3379 push @{$names{$file->{name}}}, $id
3380 if length $file->{name};
3381 }
3382 if ($cgi->param('save_file_flags')) {
e63c3728
TC
3383 my $download = 0 + defined $cgi->param("download_$id");
3384 if ($download != $file->{download}) {
3385 ++$store_anyway{$file->{id}};
3386 $file->{download} = $download;
3387 }
b8e8b584
TC
3388 $file->{forSale} = 0 + defined $cgi->param("forSale_$id");
3389 $file->{requireUser} = 0 + defined $cgi->param("requireUser_$id");
3390 $file->{hide_from_list} = 0 + defined $cgi->param("hide_from_list_$id");
ca9aa2bf 3391 }
8326f275
TC
3392
3393 my $filex = $cgi->param("file_$id");
3394 my $in_fh = $cgi->upload("file_$id");
3395 if (defined $filex && length $filex) {
4b69925d
TC
3396 if (length $filex <= MAX_FILE_DISPLAYNAME_LENGTH) {
3397 if ($in_fh) {
3398 if (-s $in_fh) {
3399 require DevHelp::FileUpload;
3400 my $msg;
3401 my ($file_name, $out_fh) = DevHelp::FileUpload->make_img_filename
3402 ($download_path, $filex . '', \$msg);
3403 if ($file_name) {
3404 {
3405 local $/ = \8192;
3406 my $data;
3407 while ($data = <$in_fh>) {
3408 print $out_fh $data;
3409 }
3410 close $out_fh;
8326f275 3411 }
4b69925d
TC
3412 my $display_name = $filex;
3413 $display_name =~ s!.*[\\:/]!!;
3414 $display_name =~ s/[^\w._-]+/_/g;
3415 my $full_name = "$download_path/$file_name";
e63c3728 3416 push @old_files, [ $file->{filename}, $file->{storage} ];
4b69925d
TC
3417 push @new_files, $file_name;
3418
3419 $file->{filename} = $file_name;
e63c3728 3420 $file->{storage} = 'local';
4b69925d
TC
3421 $file->{sizeInBytes} = -s $full_name;
3422 $file->{whenUploaded} = now_datetime();
3423 $file->{displayName} = $display_name;
6430ee52 3424 push @content_changed, $file;
4b69925d
TC
3425 }
3426 else {
3427 $errors{"file_$id"} = $msg;