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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 6688 - (download) (as text) (annotate)
Sun Jan 30 21:07:51 2011 UTC (2 years, 3 months ago) by david gage
Original Path: branches/dg_dev/webwork2/lib/WeBWorK/ContentGenerator/Instructor/SetMaker2.pm
File size: 68671 byte(s)
debugged reorder, it seems to be working fine now, but keep an eye out for any errors, especially anything having to do with putGlobalProblem

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

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9