[system] / trunk / webwork-modperl / lib / WeBWorK / ContentGenerator / Instructor / SetMaker.pm Repository:
ViewVC logotype

View of /trunk/webwork-modperl/lib/WeBWorK/ContentGenerator/Instructor/SetMaker.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 5932 - (download) (as text) (annotate)
Thu Oct 9 02:18:38 2008 UTC (4 years, 7 months ago) by gage
File size: 50227 byte(s)
Forward ports from rel-2-4-patches

    1 ################################################################################
    2 # WeBWorK Online Homework Delivery System
    3 # Copyright © 2000-2007 The WeBWorK Project, http://openwebwork.sf.net/
    4 # $CVSHeader: webwork2/lib/WeBWorK/ContentGenerator/Instructor/SetMaker.pm,v 1.85 2008/07/01 13:18:52 glarose Exp $
    5 #
    6 # This program is free software; you can redistribute it and/or modify it under
    7 # the terms of either: (a) the GNU General Public License as published by the
    8 # Free Software Foundation; either version 2, or (at your option) any later
    9 # version, or (b) the "Artistic License" which comes with this package.
   10 #
   11 # This program is distributed in the hope that it will be useful, but WITHOUT
   12 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
   13 # FOR A PARTICULAR PURPOSE.  See either the GNU General Public License or the
   14 # Artistic License for more details.
   15 ################################################################################
   16 
   17 
   18 package WeBWorK::ContentGenerator::Instructor::SetMaker;
   19 use base qw(WeBWorK::ContentGenerator::Instructor);
   20 
   21 =head1 NAME
   22 
   23 WeBWorK::ContentGenerator::Instructor::SetMaker - Make homework sets.
   24 
   25 =cut
   26 
   27 use strict;
   28 use warnings;
   29 
   30 
   31 #use CGI qw(-nosticky);
   32 use WeBWorK::CGI;
   33 use WeBWorK::Debug;
   34 use WeBWorK::Form;
   35 use WeBWorK::Utils qw(readDirectory max sortByName);
   36 use WeBWorK::Utils::Tasks qw(renderProblems);
   37 use File::Find;
   38 
   39 require WeBWorK::Utils::ListingDB;
   40 
   41 use constant SHOW_HINTS_DEFAULT => 0;
   42 use constant SHOW_SOLUTIONS_DEFAULT => 0;
   43 use constant MAX_SHOW_DEFAULT => 20;
   44 use constant NO_LOCAL_SET_STRING => 'No sets in this course yet';
   45 use constant SELECT_SET_STRING => 'Select a Set from this Course';
   46 use constant SELECT_LOCAL_STRING => 'Select a Problem Collection';
   47 use constant MY_PROBLEMS => '  My Problems  ';
   48 use constant MAIN_PROBLEMS => '  Unclassified Problems  ';
   49 use constant CREATE_SET_BUTTON => 'Create New Set';
   50 use constant ALL_CHAPTERS => 'All Chapters';
   51 use constant ALL_SUBJECTS => 'All Subjects';
   52 use constant ALL_SECTIONS => 'All Sections';
   53 use constant ALL_TEXTBOOKS => 'All Textbooks';
   54 
   55 use constant LIB2_DATA => {
   56   'dbchapter' => {name => 'library_chapters', all => 'All Chapters'},
   57   'dbsection' =>  {name => 'library_sections', all =>'All Sections' },
   58   'dbsubject' =>  {name => 'library_subjects', all => 'All Subjects' },
   59   'textbook' =>  {name => 'library_textbook', all =>  'All Textbooks'},
   60   'textchapter' => {name => 'library_textchapter', all => 'All Chapters'},
   61   'textsection' => {name => 'library_textsection', all => 'All Sections'},
   62   'keywords' =>  {name => 'library_keywords', all => '' },
   63   };
   64 
   65 ## Flags for operations on files
   66 
   67 use constant ADDED => 1;
   68 use constant HIDDEN => (1 << 1);
   69 use constant SUCCESS => (1 << 2);
   70 
   71 ##  for additional problib buttons
   72 my %problib;  ## filled in in global.conf
   73 my %ignoredir = (
   74   '.' => 1, '..' => 1, 'Library' => 1, 'CVS' => 1, 'tmpEdit' => 1,
   75   'headers' => 1, 'macros' => 1, 'email' => 1, '.svn' => 1,
   76 );
   77 
   78 sub prepare_activity_entry {
   79   my $self=shift;
   80   my $r = $self->r;
   81   my $user = $self->r->param('user') || 'NO_USER';
   82   return("In SetMaker as user $user");
   83 }
   84 
   85 ## This is for searching the disk for directories containing pg files.
   86 ## to make the recursion work, this returns an array where the first
   87 ## item is the number of pg files in the directory.  The second is a
   88 ## list of directories which contain pg files.
   89 ##
   90 ## If a directory contains only one pg file and the directory name
   91 ## is the same as the file name, then the directory is considered
   92 ## to be part of the parent directory (it is probably in a separate
   93 ## directory only because it has auxiliary files that want to be
   94 ## kept together with the pg file).
   95 ##
   96 ## If a directory has a file named "=library-ignore", it is never
   97 ## included in the directory menu.  If a directory contains a file
   98 ## called "=library-combine-up", then its pg are included with those
   99 ## in the parent directory (and the directory does not appear in the
  100 ## menu).  If it has a file called "=library-no-combine" then it is
  101 ## always listed as a separate directory even if it contains only one
  102 ## pg file.
  103 
  104 sub get_library_sets {
  105   my $top = shift; my $dir = shift;
  106   # ignore directories that give us an error
  107   my @lis = eval { readDirectory($dir) };
  108   if ($@) {
  109     warn $@;
  110     return (0);
  111   }
  112   return (0) if grep /^=library-ignore$/, @lis;
  113 
  114   my @pgfiles = grep { m/\.pg$/ and (not m/(Header|-text)\.pg$/) and -f "$dir/$_"} @lis;
  115   my $pgcount = scalar(@pgfiles);
  116   my $pgname = $dir; $pgname =~ s!.*/!!; $pgname .= '.pg';
  117   my $combineUp = ($pgcount == 1 && $pgname eq $pgfiles[0] && !(grep /^=library-no-combine$/, @lis));
  118 
  119   my @pgdirs;
  120   my @dirs = grep {!$ignoredir{$_} and -d "$dir/$_"} @lis;
  121   if ($top == 1) {@dirs = grep {!$problib{$_}} @dirs}
  122   foreach my $subdir (@dirs) {
  123     my @results = get_library_sets(0, "$dir/$subdir");
  124     $pgcount += shift @results; push(@pgdirs,@results);
  125   }
  126 
  127   return ($pgcount, @pgdirs) if $top || $combineUp || grep /^=library-combine-up$/, @lis;
  128   return (0,@pgdirs,$dir);
  129 }
  130 
  131 sub get_library_pgs {
  132   my $top = shift; my $base = shift; my $dir = shift;
  133   my @lis = readDirectory("$base/$dir");
  134   return () if grep /^=library-ignore$/, @lis;
  135   return () if !$top && grep /^=library-no-combine$/, @lis;
  136 
  137   my @pgs = grep { m/\.pg$/ and (not m/(Header|-text)\.pg$/) and -f "$base/$dir/$_"} @lis;
  138   my $others = scalar(grep { (!m/\.pg$/ || m/(Header|-text)\.pg$/) &&
  139                               !m/(\.(tmp|bak)|~)$/ && -f "$base/$dir/$_" } @lis);
  140 
  141   my @dirs = grep {!$ignoredir{$_} and -d "$base/$dir/$_"} @lis;
  142   if ($top == 1) {@dirs = grep {!$problib{$_}} @dirs}
  143   foreach my $subdir (@dirs) {push(@pgs, get_library_pgs(0,"$base/$dir",$subdir))}
  144 
  145   return () unless $top || (scalar(@pgs) == 1 && $others) || grep /^=library-combine-up$/, @lis;
  146   return (map {"$dir/$_"} @pgs);
  147 }
  148 
  149 sub list_pg_files {
  150   my ($templates,$dir) = @_;
  151   my $top = ($dir eq '.')? 1 : 2;
  152   my @pgs = get_library_pgs($top,$templates,$dir);
  153   return sortByName(undef,@pgs);
  154 }
  155 
  156 ## Search for set definition files
  157 
  158 sub get_set_defs {
  159   my $topdir = shift;
  160   my @found_set_defs;
  161   # get_set_defs_wanted is a closure over @found_set_defs
  162   my $get_set_defs_wanted = sub {
  163     #my $fn = $_;
  164     #my $fdir = $File::Find::dir;
  165     #return() if($fn !~ /^set.*\.def$/);
  166     ##return() if(not -T $fn);
  167     #push @found_set_defs, "$fdir/$fn";
  168     push @found_set_defs, $_ if m|/set[^/]*\.def$|;
  169   };
  170   find({ wanted => $get_set_defs_wanted, follow_fast=>1, no_chdir=>1}, $topdir);
  171   map { $_ =~ s|^$topdir/?|| } @found_set_defs;
  172   return @found_set_defs;
  173 }
  174 
  175 ## Try to make reading of set defs more flexible.  Additional strategies
  176 ## for fixing a path can be added here.
  177 
  178 sub munge_pg_file_path {
  179   my $self = shift;
  180   my $pg_path = shift;
  181   my $path_to_set_def = shift;
  182   my $end_path = $pg_path;
  183   # if the path is ok, don't fix it
  184   return($pg_path) if(-e $self->r->ce->{courseDirs}{templates}."/$pg_path");
  185   # if we have followed a link into a self contained course to get
  186   # to the set.def file, we need to insert the start of the path to
  187   # the set.def file
  188   $end_path = "$path_to_set_def/$pg_path";
  189   return($end_path) if(-e $self->r->ce->{courseDirs}{templates}."/$end_path");
  190   # if we got this far, this path is bad, but we let it produce
  191   # an error so the user knows there is a troublesome path in the
  192   # set.def file.
  193   return($pg_path);
  194 }
  195 
  196 ## Read a set definition file.  This could be abstracted since it happens
  197 ## elsewhere.  Here we don't have to process so much of the file.
  198 
  199 sub read_set_def {
  200   my $self = shift;
  201   my $r = $self->r;
  202   my $filePathOrig = shift;
  203   my $filePath = $r->ce->{courseDirs}{templates}."/$filePathOrig";
  204   $filePathOrig =~ s/set.*\.def$//;
  205   $filePathOrig =~ s|/$||;
  206   $filePathOrig = "." if ($filePathOrig !~ /\S/);
  207   my @pg_files = ();
  208   my ($line, $got_to_pgs, $name, @rest) = ("", 0, "");
  209   if ( open (SETFILENAME, "$filePath") )    {
  210     while($line = <SETFILENAME>) {
  211       chomp($line);
  212       $line =~ s|(#.*)||; # don't read past comments
  213       if($got_to_pgs) {
  214         unless ($line =~ /\S/) {next;} # skip blank lines
  215         ($name,@rest) = split (/\s*,\s*/,$line);
  216         $name =~ s/\s*//g;
  217         push @pg_files, $name;
  218       } else {
  219         $got_to_pgs = 1 if ($line =~ /problemList\s*=/);
  220       }
  221     }
  222   } else {
  223     $self->addbadmessage("Cannot open $filePath");
  224   }
  225   # This is where we would potentially munge the pg file paths
  226   # One possibility
  227   @pg_files = map { $self->munge_pg_file_path($_, $filePathOrig) } @pg_files;
  228   return(@pg_files);
  229 }
  230 
  231 ## go through past page getting a list of identifiers for the problems
  232 ## and whether or not they are selected, and whether or not they should
  233 ## be hidden
  234 
  235 sub get_past_problem_files {
  236   my $r = shift;
  237   my @found=();
  238   my $count =1;
  239   while (defined($r->param("filetrial$count"))) {
  240     my $val = 0;
  241     $val |= ADDED if($r->param("trial$count"));
  242     $val |= HIDDEN if($r->param("hideme$count"));
  243     push @found, [$r->param("filetrial$count"), $val];
  244     $count++;
  245   }
  246   return(\@found);
  247 }
  248 
  249 #### For adding new problems
  250 
  251 sub add_selected {
  252   my $self = shift;
  253   my $db = shift;
  254   my $setName = shift;
  255   my @past_problems = @{$self->{past_problems}};
  256   my @selected = @past_problems;
  257   my (@path, $file, $selected, $freeProblemID);
  258   # DBFIXME count would work just as well
  259   $freeProblemID = max($db->listGlobalProblems($setName)) + 1;
  260   my $addedcount=0;
  261 
  262   for $selected (@selected) {
  263     if($selected->[1] & ADDED) {
  264       $file = $selected->[0];
  265       my $problemRecord = $self->addProblemToSet(setName => $setName,
  266         sourceFile => $file, problemID => $freeProblemID);
  267       $freeProblemID++;
  268       $self->assignProblemToAllSetUsers($problemRecord);
  269       $selected->[1] |= SUCCESS;
  270       $addedcount++;
  271     }
  272   }
  273   return($addedcount);
  274 }
  275 
  276 
  277 ############# List of sets of problems in templates directory
  278 
  279 sub get_problem_directories {
  280   my $ce = shift;
  281   my $lib = shift;
  282   my $source = $ce->{courseDirs}{templates};
  283   my $main = MY_PROBLEMS; my $isTop = 1;
  284   if ($lib) {$source .= "/$lib"; $main = MAIN_PROBLEMS; $isTop = 2}
  285   my @all_problem_directories = get_library_sets($isTop, $source);
  286   my $includetop = shift @all_problem_directories;
  287   my $j;
  288   for ($j=0; $j<scalar(@all_problem_directories); $j++) {
  289     $all_problem_directories[$j] =~ s|^$ce->{courseDirs}->{templates}/?||;
  290   }
  291   @all_problem_directories = sortByName(undef, @all_problem_directories);
  292   unshift @all_problem_directories, $main if($includetop);
  293   return (\@all_problem_directories);
  294 }
  295 
  296 ############# Everyone has a view problems line.  Abstract it
  297 sub view_problems_line {
  298   my $internal_name = shift;
  299   my $label = shift;
  300   my $r = shift; # so we can get parameter values
  301   my $result = CGI::submit(-name=>"$internal_name", -value=>$label);
  302 
  303   my %display_modes = %{WeBWorK::PG::DISPLAY_MODES()};
  304   my @active_modes = grep { exists $display_modes{$_} }
  305     @{$r->ce->{pg}->{displayModes}};
  306   push @active_modes, 'None';
  307   # We have our own displayMode since its value may be None, which is illegal
  308   # in other modules.
  309   my $mydisplayMode = $r->param('mydisplayMode') || $r->ce->{pg}->{options}->{displayMode};
  310   $result .= '&nbsp;Display&nbsp;Mode:&nbsp;'.CGI::popup_menu(-name=> 'mydisplayMode',
  311                                                               -values=>\@active_modes,
  312                                                               -default=> $mydisplayMode);
  313   # Now we give a choice of the number of problems to show
  314   my $defaultMax = $r->param('max_shown') || MAX_SHOW_DEFAULT;
  315   $result .= '&nbsp;Max. Shown:&nbsp'.
  316     CGI::popup_menu(-name=> 'max_shown',
  317                     -values=>[5,10,15,20,25,30,50,'All'],
  318                     -default=> $defaultMax);
  319   # Option of whether to show hints and solutions
  320   my $defaultHints = $r->param('showHints') || SHOW_HINTS_DEFAULT;
  321   $result .= "&nbsp;".CGI::checkbox(-name=>"showHints",-checked=>$defaultHints,-label=>"Hints");
  322   my $defaultSolutions = $r->param('showSolutions') || SHOW_SOLUTIONS_DEFAULT;
  323   $result .= "&nbsp;".CGI::checkbox(-name=>"showSolutions",-checked=>$defaultSolutions,-label=>"Solutions");
  324 
  325   return($result);
  326 }
  327 
  328 
  329 ### The browsing panel has three versions
  330 #####  Version 1 is local problems
  331 sub browse_local_panel {
  332   my $self = shift;
  333   my $library_selected = shift;
  334   my $lib = shift || ''; $lib =~ s/^browse_//;
  335   my $name = ($lib eq '')? 'Local' : $problib{$lib};
  336 
  337   my $list_of_prob_dirs= get_problem_directories($self->r->ce,$lib);
  338   if(scalar(@$list_of_prob_dirs) == 0) {
  339     $library_selected = "Found no directories containing problems";
  340     unshift @{$list_of_prob_dirs}, $library_selected;
  341   } else {
  342     my $default_value = SELECT_LOCAL_STRING;
  343     if (not $library_selected or $library_selected eq $default_value) {
  344       unshift @{$list_of_prob_dirs},  $default_value;
  345       $library_selected = $default_value;
  346     }
  347   }
  348   debug("library is $lib and sets are $library_selected");
  349   my $view_problem_line = view_problems_line('view_local_set', 'View Problems', $self->r);
  350   my @popup_menu_args = (
  351     -name => 'library_sets',
  352     -values => $list_of_prob_dirs,
  353     -default => $library_selected,
  354   );
  355   # make labels without the $lib prefix -- reduces the width of the popup menu
  356   if (length($lib)) {
  357     my %labels = map { my($l)=$_=~/^$lib\/(.*)$/;$_=>$l } @$list_of_prob_dirs;
  358     push @popup_menu_args, -labels => \%labels;
  359   }
  360   print CGI::Tr({}, CGI::td({-class=>"InfoPanel", -align=>"left"}, "$name Problems: ",
  361                   CGI::popup_menu(@popup_menu_args),
  362                   CGI::br(),
  363                   $view_problem_line,
  364   ));
  365 }
  366 
  367 #####  Version 2 is local homework sets
  368 sub browse_mysets_panel {
  369   my $self = shift;
  370   my $library_selected = shift;
  371   my $list_of_local_sets = shift;
  372   my $default_value = "Select a Homework Set";
  373 
  374   if(scalar(@$list_of_local_sets) == 0) {
  375     $list_of_local_sets = [NO_LOCAL_SET_STRING];
  376   } elsif (not $library_selected or $library_selected eq $default_value) {
  377     unshift @{$list_of_local_sets},  $default_value;
  378     $library_selected = $default_value;
  379   }
  380 
  381   my $view_problem_line = view_problems_line('view_mysets_set', 'View Problems', $self->r);
  382   print CGI::Tr({},
  383     CGI::td({-class=>"InfoPanel", -align=>"left"}, "Browse from: ",
  384     CGI::popup_menu(-name=> 'library_sets',
  385                     -values=>$list_of_local_sets,
  386                     -default=> $library_selected),
  387     CGI::br(),
  388     $view_problem_line
  389   ));
  390 }
  391 
  392 #####  Version 3 is the problem library
  393 #
  394 # This comes in 3 forms, problem library version 1, and for version 2 there
  395 # is the basic, and the advanced interfaces.  This function checks what we are
  396 # supposed to do, or aborts if the problem library has not been installed.
  397 
  398 sub browse_library_panel {
  399   my $self=shift;
  400   my $r = $self->r;
  401   my $ce = $r->ce;
  402 
  403   # See if the problem library is installed
  404   my $libraryRoot = $r->{ce}->{problemLibrary}->{root};
  405 
  406   unless($libraryRoot) {
  407     print CGI::Tr(CGI::td(CGI::div({class=>'ResultsWithError', align=>"center"},
  408       "The problem library has not been installed.")));
  409     return;
  410   }
  411   # Test if the Library directory link exists.  If not, try to make it
  412   unless(-d "$ce->{courseDirs}->{templates}/Library") {
  413     unless(symlink($libraryRoot, "$ce->{courseDirs}->{templates}/Library")) {
  414       my $msg =  <<"HERE";
  415 You are missing the directory <code>templates/Library</code>, which is needed
  416 for the Problem Library to function.  It should be a link pointing to
  417 <code>$libraryRoot</code>, which you set in <code>conf/global.conf</code>.
  418 I tried to make the link for you, but that failed.  Check the permissions
  419 in your <code>templates</code> directory.
  420 HERE
  421       $self->addbadmessage($msg);
  422     }
  423   }
  424 
  425   # Now check what version we are supposed to use
  426   my $libraryVersion = $r->{ce}->{problemLibrary}->{version} || 1;
  427   if($libraryVersion == 1) {
  428     return $self->browse_library_panel1;
  429   } elsif($libraryVersion == 2) {
  430     return $self->browse_library_panel2 if($self->{library_basic}==1);
  431     return $self->browse_library_panel2adv;
  432   } else {
  433     print CGI::Tr(CGI::td(CGI::div({class=>'ResultsWithError', align=>"center"},
  434       "The problem library version is set to an illegal value.")));
  435     return;
  436   }
  437 }
  438 
  439 sub browse_library_panel1 {
  440   my $self = shift;
  441   my $r = $self->r;
  442   my $ce = $r->ce;
  443 
  444   my @chaps = WeBWorK::Utils::ListingDB::getAllChapters($r->{ce});
  445   unshift @chaps, LIB2_DATA->{dbchapter}{all};
  446   my $chapter_selected = $r->param('library_chapters') || LIB2_DATA->{dbchapter}->{all};
  447 
  448   my @sects=();
  449   if ($chapter_selected ne LIB2_DATA->{dbchapter}{all}) {
  450     @sects = WeBWorK::Utils::ListingDB::getAllSections($r->{ce}, $chapter_selected);
  451   }
  452 
  453   unshift @sects, ALL_SECTIONS;
  454   my $section_selected =  $r->param('library_sections') || LIB2_DATA->{dbsection}{all};
  455 
  456   my $view_problem_line = view_problems_line('lib_view', 'View Problems', $self->r);
  457 
  458   print CGI::Tr(CGI::td({-class=>"InfoPanel", -align=>"left"},
  459     CGI::start_table(),
  460       CGI::Tr({},
  461         CGI::td(["Chapter:",
  462           CGI::popup_menu(-name=> 'library_chapters',
  463                           -values=>\@chaps,
  464                           -default=> $chapter_selected,
  465                           -onchange=>"submit();return true"
  466           ),
  467           CGI::submit(-name=>"lib_select_chapter", -value=>"Update Section List")])),
  468       CGI::Tr({},
  469         CGI::td("Section:"),
  470         CGI::td({-colspan=>2},
  471           CGI::popup_menu(-name=> 'library_sections',
  472                           -values=>\@sects,
  473                           -default=> $section_selected
  474       ))),
  475 
  476       CGI::Tr(CGI::td({-colspan=>3}, $view_problem_line)),
  477       CGI::end_table(),
  478     ));
  479 }
  480 
  481 sub browse_library_panel2 {
  482   my $self = shift;
  483   my $r = $self->r;
  484   my $ce = $r->ce;
  485 
  486   my @subjs = WeBWorK::Utils::ListingDB::getAllDBsubjects($r);
  487   unshift @subjs, LIB2_DATA->{dbsubject}{all};
  488 
  489   my @chaps = WeBWorK::Utils::ListingDB::getAllDBchapters($r);
  490   unshift @chaps, LIB2_DATA->{dbchapter}{all};
  491 
  492   my @sects=();
  493   @sects = WeBWorK::Utils::ListingDB::getAllDBsections($r);
  494   unshift @sects, LIB2_DATA->{dbsection}{all};
  495 
  496   my $subject_selected = $r->param('library_subjects') || LIB2_DATA->{dbsubject}{all};
  497   my $chapter_selected = $r->param('library_chapters') || LIB2_DATA->{dbchapter}{all};
  498   my $section_selected =  $r->param('library_sections') || LIB2_DATA->{dbsection}{all};
  499 
  500   my $view_problem_line = view_problems_line('lib_view', 'View Problems', $self->r);
  501 
  502   my $count_line = WeBWorK::Utils::ListingDB::countDBListings($r);
  503   if($count_line==0) {
  504     $count_line = "There are no matching pg files";
  505   } else {
  506     $count_line = "There are $count_line matching WeBWorK problem files";
  507   }
  508 
  509   print CGI::Tr({},
  510       CGI::td({-class=>"InfoPanel", -align=>"left"},
  511     CGI::hidden(-name=>"library_is_basic", -default=>1,-override=>1),
  512     CGI::start_table({-width=>"100%"}),
  513     CGI::Tr({},
  514       CGI::td(["Subject:",
  515         CGI::popup_menu(-name=> 'library_subjects',
  516                       -values=>\@subjs,
  517                       -default=> $subject_selected,
  518                        -onchange=>"submit();return true"
  519         )]),
  520       CGI::td({-colspan=>2, -align=>"right"},
  521         CGI::submit(-name=>"lib_select_subject", -value=>"Update Chapter/Section Lists"))
  522     ),
  523     CGI::Tr({},
  524       CGI::td(["Chapter:",
  525         CGI::popup_menu(-name=> 'library_chapters',
  526                       -values=>\@chaps,
  527                       -default=> $chapter_selected,
  528                        -onchange=>"submit();return true"
  529         )]),
  530       CGI::td({-colspan=>2, -align=>"right"},
  531           CGI::submit(-name=>"library_advanced", -value=>"Advanced Search"))
  532     ),
  533     CGI::Tr({},
  534       CGI::td(["Section:",
  535       CGI::popup_menu(-name=> 'library_sections',
  536                   -values=>\@sects,
  537                   -default=> $section_selected,
  538               -onchange=>"submit();return true"
  539         )]),
  540      ),
  541      CGI::Tr(CGI::td({-colspan=>3}, $view_problem_line)),
  542      CGI::Tr(CGI::td({-colspan=>3, -align=>"center"}, $count_line)),
  543      CGI::end_table(),
  544    ));
  545 
  546 }
  547 
  548 sub browse_library_panel2adv {
  549   my $self = shift;
  550   my $r = $self->r;
  551   my $ce = $r->ce;
  552   my $right_button_style = "width: 18ex";
  553 
  554   my @subjs = WeBWorK::Utils::ListingDB::getAllDBsubjects($r);
  555   if(! grep { $_ eq $r->param('library_subjects') } @subjs) {
  556     $r->param('library_subjects', '');
  557   }
  558   unshift @subjs, LIB2_DATA->{dbsubject}{all};
  559 
  560   my @chaps = WeBWorK::Utils::ListingDB::getAllDBchapters($r);
  561   if(! grep { $_ eq $r->param('library_chapters') } @chaps) {
  562     $r->param('library_chapters', '');
  563   }
  564   unshift @chaps, LIB2_DATA->{dbchapter}{all};
  565 
  566   my @sects = WeBWorK::Utils::ListingDB::getAllDBsections($r);
  567   if(! grep { $_ eq $r->param('library_sections') } @sects) {
  568     $r->param('library_sections', '');
  569   }
  570   unshift @sects, LIB2_DATA->{dbsection}{all};
  571 
  572   my $texts = WeBWorK::Utils::ListingDB::getDBTextbooks($r);
  573   my @textarray = map { $_->[0] }  @{$texts};
  574   my %textlabels = ();
  575   for my $ta (@{$texts}) {
  576     $textlabels{$ta->[0]} = $ta->[1]." by ".$ta->[2]." (edition ".$ta->[3].")";
  577   }
  578   if(! grep { $_ eq $r->param('library_textbook') } @textarray) {
  579     $r->param('library_textbook', '');
  580   }
  581   unshift @textarray, LIB2_DATA->{textbook}{all};
  582   my $atb = LIB2_DATA->{textbook}{all}; $textlabels{$atb} = LIB2_DATA->{textbook}{all};
  583 
  584   my $textchap_ref = WeBWorK::Utils::ListingDB::getDBTextbooks($r, 'textchapter');
  585   my @textchaps = map { $_->[0] } @{$textchap_ref};
  586   if(! grep { $_ eq $r->param('library_textchapter') } @textchaps) {
  587     $r->param('library_textchapter', '');
  588   }
  589   unshift @textchaps, LIB2_DATA->{textchapter}{all};
  590 
  591   my $textsec_ref = WeBWorK::Utils::ListingDB::getDBTextbooks($r, 'textsection');
  592   my @textsecs = map { $_->[0] } @{$textsec_ref};
  593   if(! grep { $_ eq $r->param('library_textsection') } @textsecs) {
  594     $r->param('library_textsection', '');
  595   }
  596   unshift @textsecs, LIB2_DATA->{textsection}{all};
  597 
  598   my %selected = ();
  599   for my $j (qw( dbsection dbchapter dbsubject textbook textchapter textsection )) {
  600     $selected{$j} = $r->param(LIB2_DATA->{$j}{name}) || LIB2_DATA->{$j}{all};
  601   }
  602 
  603   my $text_popup = CGI::popup_menu(-name => 'library_textbook',
  604                    -values =>\@textarray,
  605                    -labels => \%textlabels,
  606                    -default=>$selected{textbook},
  607                    -onchange=>"submit();return true");
  608 
  609 
  610   my $library_keywords = $r->param('library_keywords') || '';
  611 
  612   my $view_problem_line = view_problems_line('lib_view', 'View Problems', $self->r);
  613 
  614   my $count_line = WeBWorK::Utils::ListingDB::countDBListings($r);
  615   if($count_line==0) {
  616     $count_line = "There are no matching pg files";
  617   } else {
  618     $count_line = "There are $count_line matching WeBWorK problem files";
  619   }
  620 
  621   print CGI::Tr({},
  622     CGI::td({-class=>"InfoPanel", -align=>"left"},
  623     CGI::hidden(-name=>"library_is_basic", -default=>2,-override=>1),
  624     CGI::start_table({-width=>"100%"}),
  625     # Html done by hand since it is temporary
  626     CGI::Tr(CGI::td({-colspan=>4, -align=>"center"}, 'All Selected Constraints Joined by "And"')),
  627     CGI::Tr({},
  628       CGI::td(["Subject:",
  629         CGI::popup_menu(-name=> 'library_subjects',
  630                       -values=>\@subjs,
  631                       -default=> $selected{dbsubject},
  632                        -onchange=>"submit();return true"
  633         )]),
  634       CGI::td({-colspan=>2, -align=>"right"},
  635         CGI::submit(-name=>"lib_select_subject", -value=>"Update Menus",
  636           -style=> $right_button_style))),
  637     CGI::Tr({},
  638       CGI::td(["Chapter:",
  639         CGI::popup_menu(-name=> 'library_chapters',
  640                       -values=>\@chaps,
  641                       -default=> $selected{dbchapter},
  642                        -onchange=>"submit();return true"
  643         )]),
  644       CGI::td({-colspan=>2, -align=>"right"},
  645           CGI::submit(-name=>"library_reset", -value=>"Reset",
  646           -style=>$right_button_style))
  647     ),
  648     CGI::Tr({},
  649       CGI::td(["Section:",
  650       CGI::popup_menu(-name=> 'library_sections',
  651                   -values=>\@sects,
  652                   -default=> $selected{dbsection},
  653               -onchange=>"submit();return true"
  654         )]),
  655       CGI::td({-colspan=>2, -align=>"right"},
  656           CGI::submit(-name=>"library_basic", -value=>"Basic Search",
  657           -style=>$right_button_style))
  658      ),
  659      CGI::Tr({},
  660       CGI::td(["Textbook:", $text_popup]),
  661      ),
  662      CGI::Tr({},
  663       CGI::td(["Text chapter:",
  664       CGI::popup_menu(-name=> 'library_textchapter',
  665                   -values=>\@textchaps,
  666                   -default=> $selected{textchapter},
  667               -onchange=>"submit();return true"
  668         )]),
  669      ),
  670      CGI::Tr({},
  671       CGI::td(["Text section:",
  672       CGI::popup_menu(-name=> 'library_textsection',
  673                   -values=>\@textsecs,
  674                   -default=> $selected{textsection},
  675               -onchange=>"submit();return true"
  676         )]),
  677      ),
  678      CGI::Tr({},
  679          CGI::td("Keywords:"),CGI::td({-colspan=>2},
  680        CGI::textfield(-name=>"library_keywords",
  681               -default=>$library_keywords,
  682               -override=>1,
  683               -size=>40))),
  684      CGI::Tr(CGI::td({-colspan=>3}, $view_problem_line)),
  685      CGI::Tr(CGI::td({-colspan=>3, -align=>"center"}, $count_line)),
  686      CGI::end_table(),
  687    ));
  688 
  689 }
  690 
  691 
  692 #####  Version 4 is the set definition file panel
  693 
  694 sub browse_setdef_panel {
  695   my $self = shift;
  696   my $r = $self->r;
  697   my $ce = $r->ce;
  698   my $library_selected = shift;
  699   my $default_value = "Select a Set Definition File";
  700   # in the following line, the parens after sort are important. if they are
  701   # omitted, sort will interpret get_set_defs as the name of the comparison
  702   # function, and ($ce->{courseDirs}{templates}) as a single element list to
  703   # be sorted. *barf*
  704   my @list_of_set_defs = sort(get_set_defs($ce->{courseDirs}{templates}));
  705   if(scalar(@list_of_set_defs) == 0) {
  706     @list_of_set_defs = (NO_LOCAL_SET_STRING);
  707   } elsif (not $library_selected or $library_selected eq $default_value) {
  708     unshift @list_of_set_defs, $default_value;
  709     $library_selected = $default_value;
  710   }
  711   my $view_problem_line = view_problems_line('view_setdef_set', 'View Problems', $self->r);
  712   my $popupetc = CGI::popup_menu(-name=> 'library_sets',
  713                                 -values=>\@list_of_set_defs,
  714                                 -default=> $library_selected).
  715     CGI::br().  $view_problem_line;
  716   if($list_of_set_defs[0] eq NO_LOCAL_SET_STRING) {
  717     $popupetc = "there are no set definition files in this course to look at."
  718   }
  719   print CGI::Tr(CGI::td({-class=>"InfoPanel", -align=>"left"}, "Browse from: ",
  720     $popupetc
  721   ));
  722 }
  723 
  724 sub make_top_row {
  725   my $self = shift;
  726   my $r = $self->r;
  727   my $ce = $r->ce;
  728   my %data = @_;
  729 
  730   my $list_of_local_sets = $data{all_db_sets};
  731   my $have_local_sets = scalar(@$list_of_local_sets);
  732   my $browse_which = $data{browse_which};
  733   my $library_selected = $self->{current_library_set};
  734   my $set_selected = $r->param('local_sets');
  735   my (@dis1, @dis2, @dis3, @dis4) = ();
  736   @dis1 =  (-disabled=>1) if($browse_which eq 'browse_npl_library');
  737   @dis2 =  (-disabled=>1) if($browse_which eq 'browse_local');
  738   @dis3 =  (-disabled=>1) if($browse_which eq 'browse_mysets');
  739   @dis4 =  (-disabled=>1) if($browse_which eq 'browse_setdefs');
  740 
  741   ##  Make buttons for additional problem libraries
  742   my $libs = '';
  743   foreach my $lib (sort(keys(%problib))) {
  744     $libs .= ' '. CGI::submit(-name=>"browse_$lib", -value=>$problib{$lib},
  745                                  ($browse_which eq "browse_$lib")? (-disabled=>1): ())
  746       if (-d "$ce->{courseDirs}{templates}/$lib");
  747   }
  748   $libs = CGI::br()."or Problems from".$libs if $libs ne '';
  749 
  750   my $these_widths = "width: 25ex";
  751 
  752   if($have_local_sets ==0) {
  753     $list_of_local_sets = [NO_LOCAL_SET_STRING];
  754   } elsif (not defined($set_selected) or $set_selected eq ""
  755     or $set_selected eq SELECT_SET_STRING) {
  756     unshift @{$list_of_local_sets}, SELECT_SET_STRING;
  757     $set_selected = SELECT_SET_STRING;
  758   }
  759   my $myjs = 'document.mainform.selfassign.value=confirm("Should I assign the new set to you now?\nUse OK for yes and Cancel for no.");true;';
  760 
  761   print CGI::Tr(CGI::td({-class=>"InfoPanel", -align=>"left"}, "Add problems to ",
  762     CGI::b("Target Set: "),
  763     CGI::popup_menu(-name=> 'local_sets',
  764             -values=>$list_of_local_sets,
  765             -default=> $set_selected,
  766             -override=>1),
  767     CGI::submit(-name=>"edit_local", -value=>"Edit Target Set"),
  768     CGI::hidden(-name=>"selfassign", -default=>0,-override=>1).
  769     CGI::br(),
  770     CGI::br(),
  771     CGI::submit(-name=>"new_local_set", -value=>"Create a New Set in This Course:",
  772     -onclick=>$myjs
  773     ),
  774     "  ",
  775     CGI::textfield(-name=>"new_set_name",
  776              -default=>"Name for new set here",
  777              -override=>1, -size=>30),
  778   ));
  779 
  780   print CGI::Tr(CGI::td({-bgcolor=>"black"}));
  781 
  782   # Tidy this list up since it is used in two different places
  783   if ($list_of_local_sets->[0] eq SELECT_SET_STRING) {
  784     shift @{$list_of_local_sets};
  785   }
  786 
  787   print CGI::Tr(CGI::td({-class=>"InfoPanel", -align=>"center"},
  788     "Browse ",
  789     CGI::submit(-name=>"browse_npl_library", -value=>"National Problem Library", -style=>$these_widths, @dis1),
  790     CGI::submit(-name=>"browse_local", -value=>"Local Problems", -style=>$these_widths, @dis2),
  791     CGI::submit(-name=>"browse_mysets", -value=>"From This Course", -style=>$these_widths, @dis3),
  792     CGI::submit(-name=>"browse_setdefs", -value=>"Set Definition Files", -style=>$these_widths, @dis4),
  793     $libs,
  794   ));
  795 
  796   #print CGI::Tr(CGI::td({-bgcolor=>"black"}));
  797   print CGI::hr();
  798 
  799   if ($browse_which eq 'browse_local') {
  800     $self->browse_local_panel($library_selected);
  801   } elsif ($browse_which eq 'browse_mysets') {
  802     $self->browse_mysets_panel($library_selected, $list_of_local_sets);
  803   } elsif ($browse_which eq 'browse_npl_library') {
  804     $self->browse_library_panel();
  805   } elsif ($browse_which eq 'browse_setdefs') {
  806     $self->browse_setdef_panel($library_selected);
  807   } else { ## handle other problem libraries
  808     $self->browse_local_panel($library_selected,$browse_which);
  809   }
  810 
  811   print CGI::Tr(CGI::td({-bgcolor=>"black"}));
  812 
  813   print CGI::Tr({},
  814           CGI::td({-class=>"InfoPanel", -align=>"center"},
  815           CGI::start_table({-border=>"0"}),
  816             CGI::Tr({}, CGI::td({ -align=>"center"},
  817              CGI::submit(-name=>"select_all", -style=>$these_widths,
  818                   -value=>"Mark All For Adding"),
  819              CGI::submit(-name=>"select_none", -style=>$these_widths,
  820                   -value=>"Clear All Marks"),
  821          )),
  822     CGI::Tr({},
  823      CGI::td({},
  824       CGI::submit(-name=>"update", -style=>$these_widths. "; font-weight:bold",
  825                   -value=>"Update Set"),
  826         CGI::submit(-name=>"rerandomize",
  827                     -style=>$these_widths,
  828                     -value=>"Rerandomize"),
  829         CGI::submit(-name=>"cleardisplay",
  830                 -style=>$these_widths,
  831                 -value=>"Clear Problem Display")
  832   )),
  833   CGI::end_table()));
  834 }
  835 
  836 sub make_data_row {
  837   my $self = shift;
  838   my $sourceFileName = shift;
  839   my $pg = shift;
  840   my $cnt = shift;
  841   my $mark = shift || 0;
  842 
  843   $sourceFileName =~ s|^./||; # clean up top ugliness
  844 
  845   my $urlpath = $self->r->urlpath;
  846   my $db = $self->r->db;
  847 
  848   ## to set up edit and try links elegantly we want to know if
  849   ##    any target set is a gateway assignment or not
  850   my $localSet = $self->r->param('local_sets');
  851   my $setRecord;
  852   if ( defined($localSet) && $localSet ne SELECT_SET_STRING &&
  853        $localSet ne NO_LOCAL_SET_STRING ) {
  854     $setRecord = $db->getGlobalSet( $localSet );
  855   }
  856   my $isGatewaySet = ( defined($setRecord) &&
  857            $setRecord->assignment_type =~ /gateway/ );
  858 
  859   my $problem_output = $pg->{flags}->{error_flag} ?
  860     CGI::div({class=>"ResultsWithError"}, CGI::em("This problem produced an error"))
  861     : CGI::div({class=>"RenderSolo"}, $pg->{body_text});
  862   $problem_output .= $pg->{flags}->{comment} if($pg->{flags}->{comment});
  863 
  864 
  865   #if($self->{r}->param('browse_which') ne 'browse_npl_library') {
  866   my $problem_seed = $self->{'problem_seed'} || 1234;
  867   my $edit_link = CGI::a({href=>$self->systemLink(
  868      $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::PGProblemEditor",
  869         courseID =>$urlpath->arg("courseID"),
  870         setID=>"Undefined_Set",
  871         problemID=>"1"),
  872       params=>{sourceFilePath => "$sourceFileName", problemSeed=> $problem_seed}
  873       ), target=>"WW_Editor"}, "Edit it" );
  874 
  875   my $displayMode = $self->r->param("mydisplayMode");
  876   $displayMode = $self->r->ce->{pg}->{options}->{displayMode}
  877     if not defined $displayMode or $displayMode eq "None";
  878   my $module = ( $isGatewaySet ) ? "GatewayQuiz" : "Problem";
  879   my %pathArgs = ( courseID =>$urlpath->arg("courseID"),
  880       setID=>"Undefined_Set" );
  881   $pathArgs{problemID} = "1" if ( ! $isGatewaySet );
  882 
  883   my $try_link = CGI::a({href=>$self->systemLink(
  884     $urlpath->newFromModule("WeBWorK::ContentGenerator::$module",
  885       %pathArgs ),
  886       params =>{
  887         effectiveUser => scalar($self->r->param('user')),
  888         editMode => "SetMaker",
  889         problemSeed=> $problem_seed,
  890         sourceFilePath => "$sourceFileName",
  891         displayMode => $displayMode,
  892       }
  893     ), target=>"WW_View"}, "Try it");
  894 
  895   my %add_box_data = ( -name=>"trial$cnt",-value=>1,-label=>"Add this problem to the target set on the next update");
  896   if($mark & SUCCESS) {
  897     $add_box_data{ -label } .= " (just added this problem)";
  898   } elsif($mark & ADDED) {
  899     $add_box_data{ -checked } = 1;
  900   }
  901 
  902   my $inSet = ($self->{isInSet}{$sourceFileName})?
  903       CGI::span({-style=>"float:right; text-align: right"},
  904         CGI::i(CGI::b("(This problem is in the target set)"))) : "";
  905 
  906   print CGI::Tr({-align=>"left"}, CGI::td(
  907     CGI::div({-style=>"background-color: #DDDDDD; margin: 0px auto"},
  908       CGI::span({-style=>"float:left ; text-align: left"},"File name: $sourceFileName "),
  909       CGI::span({-style=>"float:right ; text-align: right"}, $edit_link, " ", $try_link)
  910     ), CGI::br(),
  911     CGI::checkbox(-name=>"hideme$cnt",-value=>1,-label=>"Don't show this problem on the next update",-override=>1),
  912     CGI::br(),
  913     $inSet,
  914     CGI::checkbox((%add_box_data),-override=>1),
  915     CGI::hidden(-name=>"filetrial$cnt", -default=>$sourceFileName,-override=>1).
  916     CGI::p($problem_output),
  917   ));
  918 }
  919 
  920 sub clear_default {
  921   my $r = shift;
  922   my $param = shift;
  923   my $default = shift;
  924   my $newvalue = $r->param($param) || '';
  925   $newvalue = '' if($newvalue eq $default);
  926   $r->param($param, $newvalue);
  927 }
  928 
  929 sub pre_header_initialize {
  930   my ($self) = @_;
  931   my $r = $self->r;
  932   ## For all cases, lets set some things
  933   $self->{error}=0;
  934   my $ce = $r->ce;
  935   my $db = $r->db;
  936   my $maxShown = $r->param('max_shown') || MAX_SHOW_DEFAULT;
  937   $maxShown = 10000000 if($maxShown eq 'All'); # let's hope there aren't more
  938   my $library_basic = $r->param('library_is_basic') || 1;
  939   $self->{problem_seed} = $r->param('problem_seed') || 1234;
  940   ## Fix some parameters
  941   for my $key (keys(%{ LIB2_DATA() })) {
  942     clear_default($r, LIB2_DATA->{$key}->{name}, LIB2_DATA->{$key}->{all} );
  943   }
  944     ##  Grab library sets to display from parameters list.  We will modify this
  945     ##  as we go through the if/else tree
  946     $self->{current_library_set} =  $r->param('library_sets');
  947 
  948   ##  These directories will have individual buttons
  949   %problib = %{$ce->{courseFiles}{problibs}} if $ce->{courseFiles}{problibs};
  950 
  951   my $userName = $r->param('user');
  952   my $user = $db->getUser($userName); # checked
  953   die "record for user $userName (real user) does not exist."
  954     unless defined $user;
  955   my $authz = $r->authz;
  956   unless ($authz->hasPermissions($userName, "modify_problem_sets")) {
  957     return(""); # Error message already produced in the body
  958   }
  959 
  960   ## Now one action we have to deal with here
  961   if ($r->param('edit_local')) {
  962     my $urlpath = $r->urlpath;
  963     my $db = $r->db;
  964     my $checkset = $db->getGlobalSet($r->param('local_sets'));
  965     if (not defined($checkset)) {
  966       $self->{error} = 1;
  967       $self->addbadmessage('You need to select a "Target Set" before you can edit it.');
  968     } else {
  969       my $page = $urlpath->newFromModule('WeBWorK::ContentGenerator::Instructor::ProblemSetDetail', setID=>$r->param('local_sets'), courseID=>$urlpath->arg("courseID"));
  970       my $url = $self->systemLink($page);
  971       $self->reply_with_redirect($url);
  972     }
  973   }
  974 
  975   ## Next, lots of set up so that errors can be reported with message()
  976 
  977   ############# List of problems we have already printed
  978 
  979   $self->{past_problems} = get_past_problem_files($r);
  980   # if we don't end up reusing problems, this will be wiped out
  981   # if we do redisplay the same problems, we must adjust this accordingly
  982   my @past_marks = map {$_->[1]} @{$self->{past_problems}};
  983   my $none_shown = scalar(@{$self->{past_problems}})==0;
  984   my @pg_files=();
  985   my $use_previous_problems = 1;
  986   my $first_shown = $r->param('first_shown') || 0;
  987   my $last_shown = $r->param('last_shown');
  988   if (not defined($last_shown)) {
  989     $last_shown = -1;
  990   }
  991   my @all_past_list = (); # these are include requested, but not shown
  992   my $j = 0;
  993   while (defined($r->param("all_past_list$j"))) {
  994     push @all_past_list, $r->param("all_past_list$j");
  995     $j++;
  996   }
  997 
  998   ############# Default of which problem selector to display
  999 
 1000   my $browse_which = $r->param('browse_which') || 'browse_npl_library';
 1001 
 1002 
 1003 
 1004   ## check for problem lib buttons
 1005   my $browse_lib = '';
 1006   foreach my $lib (keys %problib) {
 1007     if ($r->param("browse_$lib")) {
 1008       $browse_lib = "browse_$lib";
 1009       last;
 1010     }
 1011   }
 1012 
 1013   ########### Start the logic through if elsif elsif ...
 1014     debug("browse_lib", $r->param("$browse_lib"));
 1015     debug("browse_npl_library", $r->param("browse_npl_library"));
 1016     debug("browse_mysets", $r->param("browse_mysets"));
 1017     debug("browse_setdefs", $r->param("browse_setdefs"));
 1018   ##### Asked to browse certain problems
 1019   if ($browse_lib ne '') {
 1020     $browse_which = $browse_lib;
 1021     $self->{current_library_set} = "";
 1022     $use_previous_problems = 0; @pg_files = (); ## clear old problems
 1023   } elsif ($r->param('browse_npl_library')) {
 1024     $browse_which = 'browse_npl_library';
 1025     $self->{current_library_set} = "";
 1026     $use_previous_problems = 0; @pg_files = (); ## clear old problems
 1027   } elsif ($r->param('browse_local')) {
 1028     $browse_which = 'browse_local';
 1029     #$self->{current_library_set} = "";
 1030     $use_previous_problems = 0; @pg_files = (); ## clear old problems
 1031   } elsif ($r->param('browse_mysets')) {
 1032     $browse_which = 'browse_mysets';
 1033     $self->{current_library_set} = "";
 1034     $use_previous_problems = 0; @pg_files = (); ## clear old problems
 1035   } elsif ($r->param('browse_setdefs')) {
 1036     $browse_which = 'browse_setdefs';
 1037     $self->{current_library_set} = "";
 1038     $use_previous_problems = 0; @pg_files = (); ## clear old problems
 1039 
 1040     ##### Change the seed value
 1041 
 1042   } elsif ($r->param('rerandomize')) {
 1043     $self->{problem_seed}= 1+$self->{problem_seed};
 1044     #$r->param('problem_seed', $problem_seed);
 1045     $self->addbadmessage('Changing the problem seed for display, but there are no problems showing.') if $none_shown;
 1046 
 1047     ##### Clear the display
 1048 
 1049   } elsif ($r->param('cleardisplay')) {
 1050     @pg_files = ();
 1051     $use_previous_problems=0;
 1052     $self->addbadmessage('The display was already cleared.') if $none_shown;
 1053 
 1054     ##### View problems selected from the local list
 1055 
 1056   } elsif ($r->param('view_local_set')) {
 1057 
 1058     my $set_to_display = $self->{current_library_set};
 1059     if (not defined($set_to_display) or $set_to_display eq SELECT_LOCAL_STRING or $set_to_display eq "Found no directories containing problems") {
 1060       $self->addbadmessage('You need to select a set to view.');
 1061     } else {
 1062       $set_to_display = '.' if $set_to_display eq MY_PROBLEMS;
 1063       $set_to_display = substr($browse_which,7) if $set_to_display eq MAIN_PROBLEMS;
 1064       @pg_files = list_pg_files($ce->{courseDirs}->{templates},
 1065         "$set_to_display");
 1066       $use_previous_problems=0;
 1067     }
 1068 
 1069     ##### View problems selected from the a set in this course
 1070 
 1071   } elsif ($r->param('view_mysets_set')) {
 1072 
 1073     my $set_to_display = $self->{current_library_set};
 1074     debug("set_to_display is $set_to_display");
 1075     if (not defined($set_to_display)
 1076         or $set_to_display eq "Select a Homework Set"
 1077         or $set_to_display eq NO_LOCAL_SET_STRING) {
 1078       $self->addbadmessage("You need to select a set from this course to view.");
 1079     } else {
 1080       # DBFIXME don't use ID list, use an iterator
 1081       my @problemList = $db->listGlobalProblems($set_to_display);
 1082       my $problem;
 1083       @pg_files=();
 1084       for $problem (@problemList) {
 1085         my $problemRecord = $db->getGlobalProblem($set_to_display, $problem); # checked
 1086         die "global $problem for set $set_to_display not found." unless
 1087           $problemRecord;
 1088         push @pg_files, $problemRecord->source_file;
 1089 
 1090       }
 1091       @pg_files = sortByName(undef,@pg_files);
 1092       $use_previous_problems=0;
 1093     }
 1094 
 1095     ##### View from the library database
 1096 
 1097   } elsif ($r->param('lib_view')) {
 1098 
 1099     @pg_files=();
 1100     my @dbsearch = WeBWorK::Utils::ListingDB::getSectionListings($r);
 1101     my ($result, $tolibpath);
 1102     for $result (@dbsearch) {
 1103       $tolibpath = "Library/$result->{path}/$result->{filename}";
 1104 
 1105       ## Too clunky!!!!
 1106       push @pg_files, $tolibpath;
 1107     }
 1108     $use_previous_problems=0;
 1109 
 1110     ##### View a set from a set*.def
 1111 
 1112   } elsif ($r->param('view_setdef_set')) {
 1113 
 1114     my $set_to_display = $self->{current_library_set};
 1115     debug("set_to_display is $set_to_display");
 1116     if (not defined($set_to_display)
 1117         or $set_to_display eq "Select a Set Definition File"
 1118         or $set_to_display eq NO_LOCAL_SET_STRING) {
 1119       $self->addbadmessage("You need to select a set definition file to view.");
 1120     } else {
 1121       @pg_files= $self->read_set_def($set_to_display);
 1122     }
 1123     $use_previous_problems=0;
 1124 
 1125     ##### Edit the current local homework set
 1126 
 1127   } elsif ($r->param('edit_local')) { ## Jump to set edit page
 1128 
 1129     ; # already handled
 1130 
 1131 
 1132     ##### Make a new local homework set
 1133 
 1134   } elsif ($r->param('new_local_set')) {
 1135     if ($r->param('new_set_name') !~ /^[\w .-]*$/) {
 1136       $self->addbadmessage("The name ".$r->param('new_set_name')." is not a valid set name.  Use only letters, digits, -, _, and .");
 1137     } else {
 1138       my $newSetName = $r->param('new_set_name');
 1139       # if we want to munge the input set name, do it here
 1140       $newSetName =~ s/\s/_/g;
 1141       debug("local_sets was ", $r->param('local_sets'));
 1142       $r->param('local_sets',$newSetName);  ## use of two parameter param
 1143       debug("new value of local_sets is ", $r->param('local_sets'));
 1144       my $newSetRecord   = $db->getGlobalSet($newSetName);
 1145       if (defined($newSetRecord)) {
 1146               $self->addbadmessage("The set name $newSetName is already in use.
 1147               Pick a different name if you would like to start a new set.");
 1148       } else {      # Do it!
 1149         # DBFIXME use $db->newGlobalSet
 1150         $newSetRecord = $db->{set}->{record}->new();
 1151         $newSetRecord->set_id($newSetName);
 1152         $newSetRecord->set_header("");
 1153         $newSetRecord->hardcopy_header("");
 1154         $newSetRecord->open_date(time()+60*60*24*7); # in one week
 1155         $newSetRecord->due_date(time()+60*60*24*7*2); # in two weeks
 1156         $newSetRecord->answer_date(time()+60*60*24*7*3); # in three weeks
 1157         eval {$db->addGlobalSet($newSetRecord)};
 1158         if ($@) {
 1159           $self->addbadmessage("Problem creating set $newSetName<br> $@");
 1160         } else {
 1161           $self->addgoodmessage("Set $newSetName has been created.");
 1162           my $selfassign = $r->param('selfassign') || "";
 1163           $selfassign = "" if($selfassign =~ /false/i); # deal with javascript false
 1164           if($selfassign) {
 1165             $self->assignSetToUser($userName, $newSetRecord);
 1166             $self->addgoodmessage("Set $newSetName was assigned to $userName.");
 1167           }
 1168         }
 1169       }
 1170     }
 1171 
 1172     ##### Add selected problems to the current local set
 1173 
 1174   } elsif ($r->param('update')) {
 1175     ## first handle problems to be added before we hide them
 1176     my($localSet, @selected);
 1177 
 1178     @pg_files = grep {($_->[1] & ADDED) != 0 } @{$self->{past_problems}};
 1179     @selected = map {$_->[0]} @pg_files;
 1180 
 1181     my @action_files = grep {$_->[1] > 0 } @{$self->{past_problems}};
 1182     # There are now good reasons to do an update without selecting anything.
 1183     #if(scalar(@action_files) == 0) {
 1184     #  $self->addbadmessage('Update requested, but no problems were marked.');
 1185     #}
 1186 
 1187     if (scalar(@selected)>0) {  # if some are to be added, they need a place to go
 1188       $localSet = $r->param('local_sets');
 1189       if (not defined($localSet) or
 1190           $localSet eq SELECT_SET_STRING or
 1191                 $localSet eq NO_LOCAL_SET_STRING) {
 1192         $self->addbadmessage('You are trying to add problems to something,
 1193         but you did not select a "Target Set" name as a target.');
 1194       } else {
 1195         my $newSetRecord  = $db->getGlobalSet($localSet);
 1196         if (not defined($newSetRecord)) {
 1197           $self->addbadmessage("You are trying to add problems to $localSet,
 1198           but that set does not seem to exist!  I bet you used your \"Back\" button.");
 1199         } else {
 1200           my $addcount = add_selected($self, $db, $localSet);
 1201           if($addcount > 0) {
 1202             $self->addgoodmessage("Added $addcount problem".(($addcount>1)?'s':'').
 1203               " to $localSet.");
 1204           }
 1205         }
 1206       }
 1207     }
 1208     ## now handle problems to be hidden
 1209 
 1210     ## only keep the ones which are not hidden
 1211     @pg_files = grep {($_->[1] & HIDDEN) ==0 } @{$self->{past_problems}};
 1212     @past_marks = map {$_->[1]} @pg_files;
 1213     @pg_files = map {$_->[0]} @pg_files;
 1214     @all_past_list = (@all_past_list[0..($first_shown-1)],
 1215           @pg_files,
 1216           @all_past_list[($last_shown+1)..(scalar(@all_past_list)-1)]);
 1217     $last_shown = $first_shown+$maxShown -1; debug("last_shown 3: ", $last_shown);
 1218     $last_shown = (scalar(@all_past_list)-1) if($last_shown>=scalar(@all_past_list)); debug("last_shown 4: ", $last_shown);
 1219 
 1220   } elsif ($r->param('next_page')) {
 1221     $first_shown = $last_shown+1;
 1222     $last_shown = $first_shown+$maxShown-1; debug("last_shown 5: ", $last_shown);
 1223     $last_shown = (scalar(@all_past_list)-1) if($last_shown>=scalar(@all_past_list)); debug("last_shown 6: ", $last_shown);
 1224     @past_marks = ();
 1225   } elsif ($r->param('prev_page')) {
 1226     $last_shown = $first_shown-1;
 1227     $first_shown = $last_shown - $maxShown+1;
 1228 
 1229     $first_shown = 0 if($first_shown<0);
 1230     @past_marks = ();
 1231 
 1232   } elsif ($r->param('select_all')) {
 1233     @past_marks = map {1} @past_marks;
 1234   } elsif ($r->param('library_basic')) {
 1235     $library_basic = 1;
 1236     for my $jj (qw(textchapter textsection textbook)) {
 1237       $r->param('library_'.$jj,'');
 1238     }
 1239   } elsif ($r->param('library_advanced')) {
 1240     $library_basic = 2;
 1241   } elsif ($r->param('library_reset')) {
 1242     for my $jj (qw(chapters sections subjects textbook keywords)) {
 1243       $r->param('library_'.$jj,'');
 1244     }
 1245   } elsif ($r->param('select_none')) {
 1246     @past_marks = ();
 1247   } else {
 1248     ##### No action requested, probably our first time here
 1249   }       ##### end of the if elsif ...
 1250 
 1251 
 1252   ############# List of local sets
 1253 
 1254   # DBFIXME sorting in database, please!
 1255   my @all_db_sets = $db->listGlobalSets;
 1256   @all_db_sets = sortByName(undef, @all_db_sets);
 1257 
 1258   if ($use_previous_problems) {
 1259     @pg_files = @all_past_list;
 1260   } else {
 1261     $first_shown = 0;
 1262     $last_shown = scalar(@pg_files)<$maxShown ? scalar(@pg_files) : $maxShown;
 1263     $last_shown--;    # to make it an array index
 1264     @past_marks = ();
 1265   }
 1266   ############# Now store data in self for retreival by body
 1267   $self->{first_shown} = $first_shown;
 1268   $self->{last_shown} = $last_shown;
 1269   $self->{browse_which} = $browse_which;
 1270   #$self->{problem_seed} = $problem_seed;
 1271   $self->{pg_files} = \@pg_files;
 1272   $self->{past_marks} = \@past_marks;
 1273   $self->{all_db_sets} = \@all_db_sets;
 1274   $self->{library_basic} = $library_basic;
 1275   debug("past_marks is ", join(" ", @{$self->{past_marks}}));
 1276 }
 1277 
 1278 
 1279 sub title {
 1280   return "Library Browser";
 1281 }
 1282 
 1283 # hide view options panel since it distracts from SetMaker's built-in view options
 1284 sub options {
 1285   return "";
 1286 }
 1287 
 1288 sub body {
 1289   my ($self) = @_;
 1290 
 1291   my $r = $self->r;
 1292   my $ce = $r->ce;    # course environment
 1293   my $db = $r->db;    # database
 1294   my $j;      # garden variety counter
 1295 
 1296   my $userName = $r->param('user');
 1297 
 1298   my $user = $db->getUser($userName); # checked
 1299   die "record for user $userName (real user) does not exist."
 1300     unless defined $user;
 1301 
 1302   ### Check that this is a professor
 1303   my $authz = $r->authz;
 1304   unless ($authz->hasPermissions($userName, "modify_problem_sets")) {
 1305     print "User $userName returned " .
 1306       $authz->hasPermissions($user, "modify_problem_sets") .
 1307   " for permission";
 1308     return(CGI::div({class=>'ResultsWithError'},
 1309     CGI::em("You are not authorized to access the Instructor tools.")));
 1310   }
 1311 
 1312   my $showHints = $r->param('showHints');
 1313   my $showSolutions = $r->param('showSolutions');
 1314 
 1315   ##########  Extract information computed in pre_header_initialize
 1316 
 1317   my $first_shown = $self->{first_shown};
 1318   my $last_shown = $self->{last_shown};
 1319   my $browse_which = $self->{browse_which};
 1320   my $problem_seed = $self->{problem_seed}||1234;
 1321   my @pg_files = @{$self->{pg_files}};
 1322   my @all_db_sets = @{$self->{all_db_sets}};
 1323 
 1324   my @pg_html;
 1325   if ($last_shown >= $first_shown) {
 1326     @pg_html = renderProblems(
 1327       r=> $r,
 1328       user => $user,
 1329       problem_list => [@pg_files[$first_shown..$last_shown]],
 1330       displayMode => $r->param('mydisplayMode'),
 1331       showHints => $showHints,
 1332       showSolutions => $showSolutions,
 1333     );
 1334   }
 1335 
 1336   my %isInSet;
 1337   my $setName = $r->param("local_sets");
 1338   if ($setName) {
 1339     # DBFIXME where clause, iterator
 1340     # DBFIXME maybe instead of hashing here, query when checking source files?
 1341     # DBFIXME definitely don't need to be making full record objects
 1342     # DBFIXME SELECT source_file FROM whatever_problem WHERE set_id=? GROUP BY source_file ORDER BY NULL;
 1343     # DBFIXME (and stick result directly into hash)
 1344     foreach my $problem ($db->listGlobalProblems($setName)) {
 1345       my $problemRecord = $db->getGlobalProblem($setName, $problem);
 1346       $isInSet{$problemRecord->source_file} = 1;
 1347     }
 1348   }
 1349   $self->{isInSet} = \%isInSet;
 1350 
 1351   ##########  Top part
 1352   print CGI::start_form({-method=>"POST", -action=>$r->uri, -name=>'mainform'}),
 1353     $self->hidden_authen_fields,
 1354       '<div align="center">',
 1355   CGI::start_table({-border=>2});
 1356   $self->make_top_row('all_db_sets'=>\@all_db_sets,
 1357          'browse_which'=> $browse_which);
 1358   print CGI::hidden(-name=>'browse_which', -value=>$browse_which,-override=>1),
 1359     CGI::hidden(-name=>'problem_seed', -value=>$problem_seed, -override=>1);
 1360   for ($j = 0 ; $j < scalar(@pg_files) ; $j++) {
 1361     print CGI::hidden(-name=>"all_past_list$j", -value=>$pg_files[$j],-override=>1);
 1362   }
 1363 
 1364   print CGI::hidden(-name=>'first_shown', -value=>$first_shown,-override=>1);
 1365 
 1366   print CGI::hidden(-name=>'last_shown', -value=>$last_shown, -override=>1);
 1367 
 1368 
 1369   ########## Now print problems
 1370   my $jj;
 1371   for ($jj=0; $jj<scalar(@pg_html); $jj++) {
 1372     $pg_files[$jj] =~ s|^$ce->{courseDirs}->{templates}/?||;
 1373     $self->make_data_row($pg_files[$jj+$first_shown], $pg_html[$jj], $jj+1, $self->{past_marks}->[$jj]);
 1374     #$self->make_data_row($pg_files[$jj+$first_shown], $pg_html[$jj], $jj+1, $self->{past_marks}->[$jj+$first_shown]); #MEG
 1375   }
 1376 
 1377   ########## Finish things off
 1378   print CGI::end_table();
 1379   print '</div>';
 1380   #  if($first_shown>0 or (1+$last_shown)<scalar(@pg_files)) {
 1381   my ($next_button, $prev_button) = ("", "");
 1382   if ($first_shown > 0) {
 1383     $prev_button = CGI::submit(-name=>"prev_page", -style=>"width:15ex",
 1384              -value=>"Previous page");
 1385   }
 1386   if ((1+$last_shown)<scalar(@pg_files)) {
 1387     $next_button = CGI::submit(-name=>"next_page", -style=>"width:15ex",
 1388              -value=>"Next page");
 1389   }
 1390   if (scalar(@pg_files)>0) {
 1391     print CGI::p(($first_shown+1)."-".($last_shown+1)." of ".scalar(@pg_files).
 1392       " shown.", $prev_button, " ", $next_button,
 1393       CGI::submit(-name=>"update", -style=>"width:15ex; font-weight:bold",
 1394           -value=>"Update Set"));
 1395   }
 1396   #  }
 1397   print CGI::endform(), "\n";
 1398 
 1399   return "";
 1400 }
 1401 
 1402 =head1 AUTHOR
 1403 
 1404 Written by John Jones, jj (at) asu.edu.
 1405 
 1406 =cut
 1407 
 1408 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9