[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 6487 - (download) (as text) (annotate)
Thu Nov 4 20:03:53 2010 UTC (2 years, 7 months ago) by david gage
File size: 55822 byte(s)
added library browser 2 that allows for drag and drop adding to selected problem sets, more to come :)

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9