[system] / branches / rel-2-3-dev / webwork2 / lib / WeBWorK / ContentGenerator / Instructor / SetMaker.pm Repository:
ViewVC logotype

View of /branches/rel-2-3-dev/webwork2/lib/WeBWorK/ContentGenerator/Instructor/SetMaker.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 4451 - (download) (as text) (annotate)
Wed Sep 6 16:26:11 2006 UTC (6 years, 8 months ago) by sh002i
File size: 48188 byte(s)
backport (sh002i): fixed bug #1057 -- read_set_def was getting the wrong
param passed to it.

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9