[system] / branches / dg_dev / webwork2 / lib / WeBWorK / ContentGenerator / Instructor / SetMaker2.pm Repository:
ViewVC logotype

View of /branches/dg_dev/webwork2/lib/WeBWorK/ContentGenerator/Instructor/SetMaker2.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 6492 - (download) (as text) (annotate)
Sat Nov 6 21:41:11 2010 UTC (2 years, 6 months ago) by david gage
File size: 55673 byte(s)
fixes to labes, added drop to remove functionality, and new template

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9