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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 6727 - (download) (as text) (annotate)
Thu Mar 10 01:32:38 2011 UTC (2 years, 2 months ago) by gage
File size: 75173 byte(s)
merge from dev_dg


    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 SetMaker2 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     #print "found this problem to be reordered: ".$problemRecord."\n";
  338     push @problems, $problemRecord;
  339     $index = $index + 1;
  340   }
  341   #then change their info
  342   my @setUsers = $db->listSetUsers($setID);
  343   my $user;
  344   $index = 1;
  345   foreach my $problem (@problems) {
  346     $problem->problem_id($index);
  347     die "global $problem not found." unless $problem;
  348     #print "problem to be reordered: ".$problem."\n";
  349     $db->putGlobalProblem($problem);
  350 
  351     #need to deal with users?
  352     foreach $user (@setUsers) {
  353       my $prob1 = $db->getUserProblem($user, $setID, $index); #checked
  354       die " problem $index for set $setID and effective user $user not found" unless $prob1;
  355       $prob1->problem_id($index);
  356       $db->putUserProblem($prob1);
  357     }
  358     $index = $index + 1;
  359   }
  360 }
  361 
  362 ############# List of sets of problems in templates directory
  363 
  364 sub get_problem_directories {
  365   my $ce = shift;
  366   my $lib = shift;
  367   my $source = $ce->{courseDirs}{templates};
  368   my $main = MY_PROBLEMS; my $isTop = 1;
  369   if ($lib) {$source .= "/$lib"; $main = MAIN_PROBLEMS; $isTop = 2}
  370   my @all_problem_directories = get_library_sets($isTop, $source);
  371   my $includetop = shift @all_problem_directories;
  372   my $j;
  373   for ($j=0; $j<scalar(@all_problem_directories); $j++) {
  374     $all_problem_directories[$j] =~ s|^$ce->{courseDirs}->{templates}/?||;
  375   }
  376   @all_problem_directories = sortByName(undef, @all_problem_directories);
  377   unshift @all_problem_directories, $main if($includetop);
  378   return (\@all_problem_directories);
  379 }
  380 
  381 ############# Everyone has a view problems line.  Abstract it
  382 sub view_problems_line {
  383   my $internal_name = shift;
  384   my $label = shift;
  385   my $r = shift; # so we can get parameter values
  386   my $self = shift;
  387   my $urlpath = $r->urlpath;
  388   my $getProblemPath = $self->systemLink($urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::GetLibrarySetProblems", courseID =>$urlpath->arg("courseID")));
  389   my $result = "<span><button type='button' onclick='viewProblems(\"$internal_name\" ,\"mainform\", \"".$getProblemPath."\", \"view_problems_spinner\");'>$label</button><img id='view_problems_spinner' style='display:none;' src='/webwork2_files/images/ajax-loader-small.gif'></img></span>";
  390   #$result .= CGI::hidden(-name=>"$internal_name");
  391   my %display_modes = %{WeBWorK::PG::DISPLAY_MODES()};
  392   my @active_modes = grep { exists $display_modes{$_} }
  393     @{$r->ce->{pg}->{displayModes}};
  394   push @active_modes, 'None';
  395   # We have our own displayMode since its value may be None, which is illegal
  396   # in other modules.
  397   my $mydisplayMode = $r->param('mydisplayMode') || $r->ce->{pg}->{options}->{displayMode};
  398   $result .= '&nbsp;Display&nbsp;Mode:&nbsp;'.CGI::popup_menu(-name=> 'mydisplayMode',
  399                                                               -values=>\@active_modes,
  400                                                               -default=> $mydisplayMode);
  401   # Now we give a choice of the number of problems to show
  402   my $defaultMax = $r->param('max_shown') || MAX_SHOW_DEFAULT;
  403   $result .= '&nbsp;Max. Shown:&nbsp'.
  404     CGI::popup_menu(-name=> 'max_shown',
  405                     -values=>[5,10,15,20,25,30,50,'All'],
  406                     -default=> $defaultMax);
  407   # Option of whether to show hints and solutions
  408   my $defaultHints = $r->param('showHints') || SHOW_HINTS_DEFAULT;
  409   $result .= "&nbsp;".CGI::checkbox(-name=>"showHints",-checked=>$defaultHints,-label=>"Hints");
  410   my $defaultSolutions = $r->param('showSolutions') || SHOW_SOLUTIONS_DEFAULT;
  411   $result .= "&nbsp;".CGI::checkbox(-name=>"showSolutions",-checked=>$defaultSolutions,-label=>"Solutions");
  412 
  413   return($result);
  414 }
  415 
  416 
  417 ### The browsing panel has three versions
  418 #####  Version 1 is local problems
  419 sub browse_local_panel {
  420   my $self = shift;
  421   my $library_selected = shift;
  422   my $lib = shift || ''; $lib =~ s/^browse_//;
  423   my $name = ($lib eq '')? 'Local' : $problib{$lib};
  424 
  425   my $list_of_prob_dirs= get_problem_directories($self->r->ce,$lib);
  426   if(scalar(@$list_of_prob_dirs) == 0) {
  427     $library_selected = "Found no directories containing problems";
  428     unshift @{$list_of_prob_dirs}, $library_selected;
  429   } else {
  430     my $default_value = SELECT_LOCAL_STRING;
  431     if (not $library_selected or $library_selected eq $default_value) {
  432       unshift @{$list_of_prob_dirs},  $default_value;
  433       $library_selected = $default_value;
  434     }
  435   }
  436   debug("library is $lib and sets are $library_selected");
  437   my $view_problem_line = view_problems_line('view_local_set', 'View Problems', $self->r, $self);
  438   my @popup_menu_args = (
  439     -size => 4,
  440     -name => 'library_sets',
  441     -values => $list_of_prob_dirs,
  442     -default => $library_selected,
  443   );
  444   # make labels without the $lib prefix -- reduces the width of the popup menu
  445   if (length($lib)) {
  446     my %labels = map { my($l)=$_=~/^$lib\/(.*)$/;$_=>$l } @$list_of_prob_dirs;
  447     push @popup_menu_args, -labels => \%labels;
  448   }
  449   print CGI::div({-class=>"InfoPanel", -align=>"left"}, "<p style='margin-bottom:0'>$name Problems: </p>",
  450                   CGI::popup_menu(@popup_menu_args),
  451                   CGI::br(),
  452                   $view_problem_line,
  453   );
  454 }
  455 
  456 #####  Version 2 is local homework sets
  457 sub browse_mysets_panel {
  458   my $self = shift;
  459   my $library_selected = shift;
  460   my $list_of_local_sets = shift;
  461   my $remember_local_set = shift;
  462   my $default_value = "Select a Homework Set";
  463 
  464   if(scalar(@$list_of_local_sets) == 0) {
  465     $list_of_local_sets = [NO_LOCAL_SET_STRING];
  466   } elsif (not $library_selected or $library_selected eq $default_value) {
  467     unshift @{$list_of_local_sets},  $default_value;
  468     $library_selected = $default_value;
  469   }
  470 
  471   my $view_problem_line = view_problems_line('view_mysets_set', 'View Problems', $self->r, $self);
  472 
  473   my $urlpath = $self->r->urlpath;
  474   my $getProblemPath = $self->systemLink($urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::GetTargetSetProblems", courseID =>$urlpath->arg("courseID")));
  475   print CGI::div({-class=>"InfoPanel", -align=>"left"},
  476     CGI::submit(-name=>"update", -style=>"width: 25ex; font-weight:bold;",
  477 
  478                   -value=>"Update Set"),
  479     '<span>',
  480     CGI::popup_menu(-name=> 'myset_sets',
  481                     -onchange=>"viewSet(\'mainform\', \'$getProblemPath\', \'view_set_spinner\');",
  482                     -values=>$list_of_local_sets,
  483                     -default=> $library_selected),
  484     "<img id='view_set_spinner' style='display:none;' src='/webwork2_files/images/ajax-loader-small.gif'></img></span>",
  485     "<button type='button' onclick='document.getElementById(\"create_new_set\").style.display = \"block\";'>+</button>",
  486     CGI::hidden(-name=> 'local_sets', -value=>$remember_local_set),
  487     CGI::br(),
  488     "<span>",
  489     #'<button type="button" onclick="viewSet(\'mainform\', \'/webwork2/myTestCourse/instructor/setmaker2/\');">View Set</button>',
  490     #CGI::submit(-name=>"view_mysets_set", -value=>"View Set"),
  491     "<span id='problem_counter' style='float:right;'>0</span>",
  492     "</span>"
  493   );
  494 }
  495 
  496 #####  Version 2.1 is local homework sets
  497 sub edit_mysets_panel {
  498   my $self = shift;
  499   my $library_selected = shift;
  500   my $list_of_local_sets = shift;
  501   my $default_value = "Select a Homework Set";
  502 
  503   if(scalar(@$list_of_local_sets) == 0) {
  504     $list_of_local_sets = [NO_LOCAL_SET_STRING];
  505   } elsif (not $library_selected or $library_selected eq $default_value) {
  506     unshift @{$list_of_local_sets},  $default_value;
  507     $library_selected = $default_value;
  508   }
  509 
  510   my $view_problem_line = view_problems_line('edit_mysets_set', 'View Problems', $self->r, $self);
  511   print CGI::Tr({},
  512     CGI::td({-class=>"InfoPanel", -align=>"left"}, "<p style='margin-bottom:0;'>Browse from:</p>",
  513     CGI::popup_menu(-name=> 'library_sets',
  514                     -size=> 4,
  515                     -values=>$list_of_local_sets,
  516                     -default=> $library_selected),
  517     CGI::br(),
  518     $view_problem_line
  519   ));
  520 }
  521 
  522 #####  Version 3 is the problem library
  523 #
  524 # This comes in 3 forms, problem library version 1, and for version 2 there
  525 # is the basic, and the advanced interfaces.  This function checks what we are
  526 # supposed to do, or aborts if the problem library has not been installed.
  527 
  528 sub browse_library_panel {
  529   my $self=shift;
  530   my $r = $self->r;
  531   my $ce = $r->ce;
  532 
  533   # See if the problem library is installed
  534   my $libraryRoot = $r->{ce}->{problemLibrary}->{root};
  535 
  536   unless($libraryRoot) {
  537     print CGI::div({class=>'ResultsWithError', align=>"center"},
  538       "The problem library has not been installed.");
  539     return;
  540   }
  541   # Test if the Library directory link exists.  If not, try to make it
  542   unless(-d "$ce->{courseDirs}->{templates}/Library") {
  543     unless(symlink($libraryRoot, "$ce->{courseDirs}->{templates}/Library")) {
  544       my $msg =  <<"HERE";
  545 You are missing the directory <code>templates/Library</code>, which is needed
  546 for the Problem Library to function.  It should be a link pointing to
  547 <code>$libraryRoot</code>, which you set in <code>conf/global.conf</code>.
  548 I tried to make the link for you, but that failed.  Check the permissions
  549 in your <code>templates</code> directory.
  550 HERE
  551       $self->addbadmessage($msg);
  552     }
  553   }
  554 
  555   # Now check what version we are supposed to use
  556   my $libraryVersion = $r->{ce}->{problemLibrary}->{version} || 1;
  557   if($libraryVersion == 1) {
  558     return $self->browse_library_panel1;
  559   } elsif($libraryVersion == 2) {
  560     return $self->browse_library_panel2 if($self->{library_basic}==1);
  561     return $self->browse_library_panel2adv;
  562   } else {
  563     print CGI::div({class=>'ResultsWithError', align=>"center"},
  564       "The problem library version is set to an illegal value.");
  565     return;
  566   }
  567 }
  568 
  569 sub browse_library_panel1 {
  570   my $self = shift;
  571   my $r = $self->r;
  572   my $ce = $r->ce;
  573 
  574   my @chaps = WeBWorK::Utils::ListingDB::getAllChapters($r->{ce});
  575   unshift @chaps, LIB2_DATA->{dbchapter}{all};
  576   my $chapter_selected = $r->param('library_chapters') || LIB2_DATA->{dbchapter}->{all};
  577 
  578   my @sects=();
  579   if ($chapter_selected ne LIB2_DATA->{dbchapter}{all}) {
  580     @sects = WeBWorK::Utils::ListingDB::getAllSections($r->{ce}, $chapter_selected);
  581   }
  582 
  583   unshift @sects, ALL_SECTIONS;
  584   my $section_selected =  $r->param('library_sections') || LIB2_DATA->{dbsection}{all};
  585 
  586   my $view_problem_line = view_problems_line('lib_view', 'View Problems', $self->r, $self);
  587 
  588   print CGI::div({-class=>"InfoPanel", -align=>"left"},
  589         CGI::div(["Chapter:",
  590           CGI::popup_menu(-name=> 'library_chapters',
  591                           -size=>4,
  592                           -values=>\@chaps,
  593                           -default=> $chapter_selected,
  594                           -onchange=>"updateLibCategories(\'mainform\', \'".$r->uri."\')"
  595           ),
  596           CGI::submit(-name=>"lib_select_chapter", -value=>"Update Section List")]),
  597         CGI::div("Section:",
  598           CGI::popup_menu(-name=> 'library_sections',
  599                           -values=>\@sects,
  600                           -default=> $section_selected
  601       )),
  602       CGI::div($view_problem_line)
  603     );
  604 }
  605 
  606 sub browse_library_panel2 {
  607   my $self = shift;
  608   my $r = $self->r;
  609   my $ce = $r->ce;
  610 
  611   my @subjs = WeBWorK::Utils::ListingDB::getAllDBsubjects($r);
  612   unshift @subjs, LIB2_DATA->{dbsubject}{all};
  613 
  614   my @chaps = WeBWorK::Utils::ListingDB::getAllDBchapters($r);
  615   unshift @chaps, LIB2_DATA->{dbchapter}{all};
  616 
  617   my @sects=();
  618   @sects = WeBWorK::Utils::ListingDB::getAllDBsections($r);
  619   unshift @sects, LIB2_DATA->{dbsection}{all};
  620 
  621   my $subject_selected = $r->param('library_subjects') || LIB2_DATA->{dbsubject}{all};
  622   my $chapter_selected = $r->param('library_chapters') || LIB2_DATA->{dbchapter}{all};
  623   my $section_selected =  $r->param('library_sections') || LIB2_DATA->{dbsection}{all};
  624 
  625   my $view_problem_line = view_problems_line('lib_view', 'View Problems', $self->r, $self);
  626 
  627   my $count_line = WeBWorK::Utils::ListingDB::countDBListings($r);
  628   if($count_line==0) {
  629     $count_line = "There are no matching pg files";
  630   } else {
  631     $count_line = "There are $count_line matching WeBWorK problem files";
  632   }
  633 
  634   print CGI::div({-class=>"InfoPanel", -align=>"left"},
  635     CGI::hidden(-name=>"library_is_basic", -default=>1,-override=>1),
  636     CGI::div({-style=>"float:left;"},"<p style='margin-bottom:0'>Subject:</p>",
  637         CGI::popup_menu(-name=> 'library_subjects',
  638                       -size=>4,
  639                       -values=>\@subjs,
  640                       -default=> $subject_selected,
  641                        -onchange=>"updateLibCategories(\'mainform\', \'".$r->uri."\')"
  642     )),
  643     CGI::div({-style=>"float:left;"},"<p style='margin-bottom:0'>Chapter:</p>",
  644       CGI::popup_menu(-name=> 'library_chapters',
  645                       -size=>4,
  646                       -values=>\@chaps,
  647                       -default=> $chapter_selected,
  648                        -onchange=>"updateLibCategories(\'mainform\', \'".$r->uri."\')"
  649     )),
  650     CGI::div({-style=>"float:left;"},"<p style='margin-bottom:0'>Section:</p>",
  651       CGI::popup_menu(-name=> 'library_sections',
  652                   -size=>4,
  653                   -values=>\@sects,
  654                   -default=> $section_selected,
  655               -onchange=>"updateLibCategories(\'mainform\', \'".$r->uri."\')"
  656     )),
  657     CGI::div({-colspan=>2, -align=>"right"},
  658       CGI::submit(-name=>"library_advanced", -value=>"Advanced Search")),
  659     CGI::div({-colspan=>2, -align=>"right"},
  660       CGI::submit(-name=>"lib_select_subject", -value=>"Update Chapter/Section Lists")),
  661     '<div style="clear:both;"></div>',
  662     CGI::div({-colspan=>3}, $view_problem_line),
  663     CGI::div({-colspan=>3, -align=>"center"}, $count_line)
  664    );
  665 
  666 }
  667 
  668 sub browse_library_panel2adv {
  669   my $self = shift;
  670   my $r = $self->r;
  671   my $ce = $r->ce;
  672   my $right_button_style = "width: 18ex";
  673 
  674   my @subjs = WeBWorK::Utils::ListingDB::getAllDBsubjects($r);
  675   if(! grep { $_ eq $r->param('library_subjects') } @subjs) {
  676     $r->param('library_subjects', '');
  677   }
  678   unshift @subjs, LIB2_DATA->{dbsubject}{all};
  679 
  680   my @chaps = WeBWorK::Utils::ListingDB::getAllDBchapters($r);
  681   if(! grep { $_ eq $r->param('library_chapters') } @chaps) {
  682     $r->param('library_chapters', '');
  683   }
  684   unshift @chaps, LIB2_DATA->{dbchapter}{all};
  685 
  686   my @sects = WeBWorK::Utils::ListingDB::getAllDBsections($r);
  687   if(! grep { $_ eq $r->param('library_sections') } @sects) {
  688     $r->param('library_sections', '');
  689   }
  690   unshift @sects, LIB2_DATA->{dbsection}{all};
  691 
  692   my $texts = WeBWorK::Utils::ListingDB::getDBTextbooks($r);
  693   my @textarray = map { $_->[0] }  @{$texts};
  694   my %textlabels = ();
  695   for my $ta (@{$texts}) {
  696     $textlabels{$ta->[0]} = $ta->[1]." by ".$ta->[2]." (edition ".$ta->[3].")";
  697   }
  698   if(! grep { $_ eq $r->param('library_textbook') } @textarray) {
  699     $r->param('library_textbook', '');
  700   }
  701   unshift @textarray, LIB2_DATA->{textbook}{all};
  702   my $atb = LIB2_DATA->{textbook}{all}; $textlabels{$atb} = LIB2_DATA->{textbook}{all};
  703 
  704   my $textchap_ref = WeBWorK::Utils::ListingDB::getDBTextbooks($r, 'textchapter');
  705   my @textchaps = map { $_->[0] } @{$textchap_ref};
  706   if(! grep { $_ eq $r->param('library_textchapter') } @textchaps) {
  707     $r->param('library_textchapter', '');
  708   }
  709   unshift @textchaps, LIB2_DATA->{textchapter}{all};
  710 
  711   my $textsec_ref = WeBWorK::Utils::ListingDB::getDBTextbooks($r, 'textsection');
  712   my @textsecs = map { $_->[0] } @{$textsec_ref};
  713   if(! grep { $_ eq $r->param('library_textsection') } @textsecs) {
  714     $r->param('library_textsection', '');
  715   }
  716   unshift @textsecs, LIB2_DATA->{textsection}{all};
  717 
  718   my %selected = ();
  719   for my $j (qw( dbsection dbchapter dbsubject textbook textchapter textsection )) {
  720     $selected{$j} = $r->param(LIB2_DATA->{$j}{name}) || LIB2_DATA->{$j}{all};
  721   }
  722 
  723   my $text_popup = CGI::popup_menu(-name => 'library_textbook',
  724                    -size => 4,
  725                    -values =>\@textarray,
  726                    -labels => \%textlabels,
  727                    -default=>$selected{textbook},
  728                    -onchange=>"updateLibCategories(\'mainform\', \'".$r->uri."\')");
  729 
  730 
  731   my $library_keywords = $r->param('library_keywords') || '';
  732 
  733   my $view_problem_line = view_problems_line('lib_view', 'View Problems', $self->r, $self);
  734 
  735   my $count_line = WeBWorK::Utils::ListingDB::countDBListings($r);
  736   if($count_line==0) {
  737     $count_line = "There are no matching pg files";
  738   } else {
  739     $count_line = "There are $count_line matching WeBWorK problem files";
  740   }
  741 
  742   print CGI::div({-class=>"InfoPanel", -align=>"left"},
  743     CGI::hidden(-name=>"library_is_basic", -default=>2,-override=>1),
  744     # Html done by hand since it is temporary
  745     CGI::div({-colspan=>4, -align=>"center"}, 'All Selected Constraints Joined by "And"'),
  746       CGI::div(["Subject:",
  747         CGI::popup_menu(-name=> 'library_subjects',
  748                       -size => 4,
  749                       -values=>\@subjs,
  750                       -default=> $selected{dbsubject},
  751                        -onchange=>"updateLibCategories(\'mainform\', \'".$r->uri."\')"
  752         )]),
  753       CGI::div({-colspan=>2, -align=>"right"},
  754         CGI::submit(-name=>"lib_select_subject", -value=>"Update Menus",
  755           -style=> $right_button_style)),
  756       CGI::div(["Chapter:",
  757         CGI::popup_menu(-name=> 'library_chapters',
  758                       -size => 4,
  759                       -values=>\@chaps,
  760                       -default=> $selected{dbchapter},
  761                        -onchange=>"updateLibCategories(\'mainform\', \'".$r->uri."\')"
  762         )]),
  763       CGI::div({-colspan=>2, -align=>"right"},
  764           CGI::submit(-name=>"library_reset", -value=>"Reset",
  765           -style=>$right_button_style)),
  766       CGI::div(["Section:",
  767       CGI::popup_menu(-name=> 'library_sections',
  768                   -size => 4,
  769                   -values=>\@sects,
  770                   -default=> $selected{dbsection},
  771               -onchange=>"updateLibCategories(\'mainform\', \'".$r->uri."\')"
  772         )]),
  773       CGI::div({-colspan=>2, -align=>"right"},
  774           CGI::submit(-name=>"library_basic", -value=>"Basic Search",
  775           -style=>$right_button_style)),
  776       CGI::div(["Textbook:", $text_popup]),
  777       CGI::div(["Text chapter:",
  778       CGI::popup_menu(-name=> 'library_textchapter',
  779                   -size => 4,
  780                   -values=>\@textchaps,
  781                   -default=> $selected{textchapter},
  782               -onchange=>"updateLibCategories(\'mainform\', \'".$r->uri."\')"
  783         )]),
  784       CGI::div(["Text section:",
  785       CGI::popup_menu(-name=> 'library_textsection',
  786                   -size => 4,
  787                   -values=>\@textsecs,
  788                   -default=> $selected{textsection},
  789               -onchange=>"updateLibCategories(\'mainform\', \'".$r->uri."\')"
  790         )]),
  791          CGI::div("Keywords:"),CGI::div({-colspan=>2},
  792        CGI::textfield(-name=>"library_keywords",
  793               -default=>$library_keywords,
  794               -override=>1,
  795               -size=>40)),
  796       CGI::div({-colspan=>3}, $view_problem_line),
  797       CGI::div({-colspan=>3, -align=>"center"}, $count_line)
  798    );
  799 
  800 }
  801 
  802 
  803 #####  Version 4 is the set definition file panel
  804 
  805 sub browse_setdef_panel {
  806   my $self = shift;
  807   my $r = $self->r;
  808   my $ce = $r->ce;
  809   my $library_selected = shift;
  810   my $default_value = "Select a Set Definition File";
  811   # in the following line, the parens after sort are important. if they are
  812   # omitted, sort will interpret get_set_defs as the name of the comparison
  813   # function, and ($ce->{courseDirs}{templates}) as a single element list to
  814   # be sorted. *barf*
  815   my @list_of_set_defs = sort(get_set_defs($ce->{courseDirs}{templates}));
  816   if(scalar(@list_of_set_defs) == 0) {
  817     @list_of_set_defs = (NO_LOCAL_SET_STRING);
  818   } elsif (not $library_selected or $library_selected eq $default_value) {
  819     unshift @list_of_set_defs, $default_value;
  820     $library_selected = $default_value;
  821   }
  822   my $view_problem_line = view_problems_line('view_setdef_set', 'View Problems', $self->r, $self);
  823   my $popupetc = CGI::popup_menu(-size=> 4,
  824                                 -name=> 'library_sets',
  825                                 -values=>\@list_of_set_defs,
  826                                 -default=> $library_selected).
  827     CGI::br().  $view_problem_line;
  828   if($list_of_set_defs[0] eq NO_LOCAL_SET_STRING) {
  829     $popupetc = "there are no set definition files in this course to look at."
  830   }
  831   print CGI::div({-class=>"InfoPanel", -align=>"left"}, "<p style='margin-bottom:0;'>Browse from:</p>",
  832     $popupetc
  833   );
  834 }
  835 
  836 sub make_mysets_row {
  837   my $self = shift;
  838   my $r = $self->r;
  839   my $ce = $r->ce;
  840   my %data = @_;
  841 
  842   my $list_of_local_sets = $data{all_db_sets};
  843   my $have_local_sets = scalar(@$list_of_local_sets);
  844   my $browse_which = 'browse_mysets';
  845   my $library_selected = $self->{current_myset_set};
  846   my $set_selected = $r->param('myset_sets');
  847   my $remember_local_set = $r->param('local_sets');
  848 
  849   ##  Make buttons for additional problem libraries
  850   #my $libs = '';
  851   #foreach my $lib (sort(keys(%problib))) {
  852   # $libs .= ' '. CGI::submit(-name=>"browse_$lib", -value=>$problib{$lib},
  853   #                              ($browse_which eq "browse_$lib")? (-disabled=>1): ())
  854   #   if (-d "$ce->{courseDirs}{templates}/$lib");
  855   #}
  856   #$libs = CGI::br()."or Problems from".$libs if $libs ne '';
  857 
  858   my $these_widths = "width: 25ex";
  859 
  860 
  861   #if($have_local_sets ==0) {
  862   # $list_of_local_sets = [NO_LOCAL_SET_STRING];
  863   #} elsif (not defined($set_selected) or $set_selected eq ""
  864   #  or $set_selected eq SELECT_SET_STRING) {
  865   # unshift @{$list_of_local_sets}, SELECT_SET_STRING;
  866   # $set_selected = SELECT_SET_STRING;
  867   #}
  868   my $myjs = 'document.getElementById(\"create_new_set\").style.display = \"none\";document.mainform.selfassign.value=confirm("Should I assign the new set to you now?\nUse OK for yes and Cancel for no.");true;';
  869   ## edited this, as a demo for the current set problem list
  870   print CGI::div({-id=>"create_new_set", -class=>"InfoPanel shadowed"},
  871       CGI::hidden(-name=>"selfassign", -default=>0,-override=>1).
  872     CGI::submit(-name=>"new_local_set", -value=>"Create a New Set in This Course:",
  873     -onclick=>"document.mainform.selfassign.value=1"      # $myjs
  874     ),
  875     "  ",
  876     CGI::textfield(-name=>"new_set_name",
  877              -default=>"Name for new set here",
  878              -override=>1, -size=>30),
  879     '<button type="button" onclick="document.getElementById(\'create_new_set\').style.display = \'none\';">Cancel</button>',
  880   );
  881   # Tidy this list up since it is used in two different places
  882   #if ($list_of_local_sets->[0] eq SELECT_SET_STRING) {
  883   # shift @{$list_of_local_sets};
  884   #}
  885 
  886   #print CGI::div(CGI::div({-bgcolor=>"black"}));
  887   #print CGI::hr();
  888 
  889   #$self->browse_mysets_panel($library_selected, $list_of_local_sets, $remember_local_set);
  890 }
  891 
  892 sub make_top_row {
  893   my $self = shift;
  894   my $r = $self->r;
  895   my $ce = $r->ce;
  896   my %data = @_;
  897 
  898   my $list_of_local_sets = $data{all_db_sets};
  899   my $have_local_sets = scalar(@$list_of_local_sets);
  900   my $browse_which = $data{browse_which};
  901   my $library_selected = $self->{current_library_set};
  902   my $set_selected = $r->param('local_sets');
  903   my (@dis1, @dis2, @dis3, @dis4) = ();
  904   @dis1 =  (-disabled=>1) if($browse_which eq 'browse_npl_library');
  905   @dis2 =  (-disabled=>1) if($browse_which eq 'browse_local');
  906   @dis3 =  (-disabled=>1) if($browse_which eq 'edit_mysets');
  907   @dis4 =  (-disabled=>1) if($browse_which eq 'browse_setdefs');
  908 
  909   ##  Make buttons for additional problem libraries
  910   #my $libs = '';
  911   #foreach my $lib (sort(keys(%problib))) {
  912   # $libs .= ' '. CGI::submit(-name=>"browse_$lib", -value=>$problib{$lib},
  913   #                              ($browse_which eq "browse_$lib")? (-disabled=>1): ())
  914   #   if (-d "$ce->{courseDirs}{templates}/$lib");
  915   #}
  916   #$libs = CGI::br()."or Problems from".$libs if $libs ne '';
  917 
  918   my $these_widths = "width: 25ex";
  919 
  920   if($have_local_sets ==0) {
  921     $list_of_local_sets = [NO_LOCAL_SET_STRING];
  922   } elsif (not defined($set_selected) or $set_selected eq ""
  923     or $set_selected eq SELECT_SET_STRING) {
  924     unshift @{$list_of_local_sets}, SELECT_SET_STRING;
  925     $set_selected = SELECT_SET_STRING;
  926   }
  927 
  928   # Tidy this list up since it is used in two different places
  929   if ($list_of_local_sets->[0] eq SELECT_SET_STRING) {
  930     shift @{$list_of_local_sets};
  931   }
  932 
  933   #print CGI::div({-class=>"InfoPanel"},
  934   # "Browse ",
  935   # CGI::submit(-name=>"browse_npl_library", -value=>"National Problem Library", -style=>$these_widths, @dis1),
  936   # CGI::submit(-name=>"browse_local", -value=>"Local Problems", -style=>$these_widths, @dis2),
  937   # CGI::submit(-name=>"edit_mysets", -value=>"From This Course", -style=>$these_widths, @dis3),
  938   # CGI::submit(-name=>"browse_setdefs", -value=>"Set Definition Files", -style=>$these_widths, @dis4),
  939   # $libs,
  940   #);
  941 
  942   #if ($browse_which eq 'browse_local') {
  943   # $self->browse_local_panel($library_selected);
  944   #} elsif ($browse_which eq 'edit_mysets') {
  945   # $self->edit_mysets_panel($library_selected, $list_of_local_sets);
  946   #} elsif ($browse_which eq 'browse_npl_library') {
  947   # $self->browse_library_panel();
  948   #} elsif ($browse_which eq 'browse_setdefs') {
  949   # $self->browse_setdef_panel($library_selected);
  950   #} else { ## handle other problem libraries
  951   # $self->browse_local_panel($library_selected,$browse_which);
  952   #}
  953 
  954   print CGI::div({-class=>"InfoPanel"},
  955     '<span class="js_action_span" onclick="selectAll();">all</span>
  956     <span style="margin-left:10px;" class="js_action_span" onclick="selectNone();">none</span>
  957     <span style="margin-left:10px;" class="js_action_span" onclick="rerandomize();">Rerandomize</span>
  958     <span style="margin-left:10px;" class="js_action_span" onclick="cleardisplay();">Clear Problem Display</span>'
  959     );#,
  960     #CGI::div({},
  961     #    CGI::submit(-name=>"rerandomize",
  962     #                -style=>$these_widths,
  963     #                -value=>"Rerandomize"),
  964     #    CGI::submit(-name=>"cleardisplay",
  965     #            -style=>$these_widths,
  966     #            -value=>"Clear Problem Display"),
  967     #);
  968 
  969     print "<div class='inforPanel' style='float:left;'>
  970       <p style='margin-bottom:0'>Browse:</p>
  971       <select id='library_selector' size=4 onchange='changeLibrary(\"mainform\", \"".$r->uri."\", this)'>";
  972       foreach my $lib (sort(keys(%problib))) {
  973         print "<option value=\'browse_$lib\'>".$problib{$lib}."</option>"
  974       }
  975         print "<option value=\'browse_npl_library\'>National Problem Library</option>
  976               <option value=\'browse_local\'>Local Problems</option>
  977               <option value=\'edit_mysets\'>From this Course</option>
  978               <option value=\'browse_setdefs\'>Set Definition Files</option>";
  979   print "</select>
  980         </div>";
  981 
  982 }
  983 
  984 sub make_data_row {
  985   my $self = shift;
  986   my $sourceFileName = shift;
  987   my $pg = shift;
  988   my $cnt = shift;
  989   my $mark = shift || 0;
  990 
  991   $sourceFileName =~ s|^./||; # clean up top ugliness
  992 
  993   my $urlpath = $self->r->urlpath;
  994   my $db = $self->r->db;
  995 
  996   ## to set up edit and try links elegantly we want to know if
  997   ##    any target set is a gateway assignment or not
  998   my $localSet = $self->r->param('local_sets');
  999   my $setRecord;
 1000   if ( defined($localSet) && $localSet ne SELECT_SET_STRING &&
 1001        $localSet ne NO_LOCAL_SET_STRING ) {
 1002     $setRecord = $db->getGlobalSet( $localSet );
 1003   }
 1004   my $isGatewaySet = ( defined($setRecord) &&
 1005            $setRecord->assignment_type =~ /gateway/ );
 1006 
 1007   my $problem_output = $pg->{flags}->{error_flag} ?
 1008     CGI::div({class=>"ResultsWithError"}, CGI::em("This problem produced an error"))
 1009     : CGI::div({class=>"RenderSolo"}, $pg->{body_text});
 1010   $problem_output .= $pg->{flags}->{comment} if($pg->{flags}->{comment});
 1011 
 1012 
 1013   #if($self->{r}->param('browse_which') ne 'browse_npl_library') {
 1014   my $problem_seed = $self->{'problem_seed'} || 1234;
 1015   my $edit_link = CGI::a({href=>$self->systemLink(
 1016      $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::PGProblemEditor",
 1017         courseID =>$urlpath->arg("courseID"),
 1018         setID=>"Undefined_Set",
 1019         problemID=>"1"),
 1020       params=>{sourceFilePath => "$sourceFileName", problemSeed=> $problem_seed}
 1021       ), target=>"WW_Editor"}, "Edit it" );
 1022 
 1023   my $displayMode = $self->r->param("mydisplayMode");
 1024   $displayMode = $self->r->ce->{pg}->{options}->{displayMode}
 1025     if not defined $displayMode or $displayMode eq "None";
 1026   my $module = ( $isGatewaySet ) ? "GatewayQuiz" : "Problem";
 1027   my %pathArgs = ( courseID =>$urlpath->arg("courseID"),
 1028       setID=>"Undefined_Set" );
 1029   $pathArgs{problemID} = "1" if ( ! $isGatewaySet );
 1030 
 1031   my $try_link = CGI::a({href=>$self->systemLink(
 1032     $urlpath->newFromModule("WeBWorK::ContentGenerator::$module",
 1033       %pathArgs ),
 1034       params =>{
 1035         effectiveUser => scalar($self->r->param('user')),
 1036         editMode => "SetMaker",
 1037         problemSeed=> $problem_seed,
 1038         sourceFilePath => "$sourceFileName",
 1039         displayMode => $displayMode,
 1040       }
 1041     ), target=>"WW_View"}, "Try it");
 1042 
 1043   my %add_box_data = ( -id=>"trial$cnt", -class=>"add_problem_checkbox" ,-name=>"trial$cnt",-value=>1,-label=>"Add this problem to the target set on the next update");
 1044   #allow for a move command from one problem set to anoter
 1045   my $move_box_data;
 1046   if($self->r->param('edit_mysets_set')){
 1047     $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");
 1048   }
 1049   else{
 1050     $move_box_data = "";
 1051   }
 1052   if($mark & SUCCESS) {
 1053     $add_box_data{ -label } .= " (just added this problem)";
 1054   } elsif($mark & ADDED) {
 1055     $add_box_data{ -checked } = 1;
 1056   }
 1057 
 1058   if(!($self->{isInSet}{$sourceFileName})){
 1059 
 1060     print CGI::div({-class=>"problem libraryProblem", -align=>"left", -draggable=>"true", -href=>"#", -id=>"$cnt"},
 1061       CGI::p({},"File name: $sourceFileName "),
 1062       CGI::p({}, $edit_link, " ", $try_link),
 1063       CGI::p(CGI::checkbox(-id=>"hideme$cnt", -name=>"hideme$cnt",-value=>1,-label=>"Don't show this problem on the next update",-override=>1)),
 1064       CGI::p(CGI::checkbox((%add_box_data),-override=>1)),
 1065       CGI::p($move_box_data),
 1066       CGI::hidden(-id=>"filetrial$cnt", -name=>"filetrial$cnt", -default=>$sourceFileName,-override=>1).
 1067       CGI::p($problem_output)
 1068     );
 1069   }
 1070   else{
 1071     print CGI::div({-class=>"problem libraryProblem used", -align=>"left", -draggable=>"true", -href=>"#", -id=>"$cnt"},
 1072       CGI::p({},"File name: $sourceFileName "),
 1073       CGI::p({}, $edit_link, " ", $try_link),
 1074       CGI::p(CGI::checkbox(-id=>"hideme$cnt", -name=>"hideme$cnt",-value=>1,-label=>"Don't show this problem on the next update",-override=>1)),
 1075       CGI::p(CGI::checkbox((%add_box_data),-override=>1)),
 1076       CGI::p($move_box_data),
 1077       CGI::hidden(-id=>"filetrial$cnt", -name=>"filetrial$cnt", -default=>$sourceFileName,-override=>1).
 1078       CGI::p($problem_output),
 1079       CGI::b("(This problem is in the target set)")
 1080     );
 1081   }
 1082 }
 1083 
 1084 sub make_myset_data_row {
 1085   my $self = shift;
 1086   my $sourceFileName = shift;
 1087   my $pg = shift;
 1088   my $cnt = shift;
 1089   my $mark = shift || 0;
 1090 
 1091   $sourceFileName =~ s|^./||; # clean up top ugliness
 1092 
 1093   my $urlpath = $self->r->urlpath;
 1094   my $db = $self->r->db;
 1095 
 1096   ## to set up edit and try links elegantly we want to know if
 1097   ##    any target set is a gateway assignment or not
 1098   my $localSet = $self->r->param('local_sets');
 1099   my $setRecord;
 1100   if ( defined($localSet) && $localSet ne SELECT_SET_STRING &&
 1101        $localSet ne NO_LOCAL_SET_STRING ) {
 1102     $setRecord = $db->getGlobalSet( $localSet );
 1103   }
 1104   my $isGatewaySet = ( defined($setRecord) &&
 1105            $setRecord->assignment_type =~ /gateway/ );
 1106 
 1107   my $problem_output = $pg->{flags}->{error_flag} ?
 1108     CGI::div({class=>"ResultsWithError"}, CGI::em("This problem produced an error"))
 1109     : CGI::div({class=>"RenderSolo"}, $pg->{body_text});
 1110   $problem_output .= $pg->{flags}->{comment} if($pg->{flags}->{comment});
 1111 
 1112 
 1113   #if($self->{r}->param('browse_which') ne 'browse_npl_library') {
 1114   my $problem_seed = $self->{'problem_seed'} || 1234;
 1115   my $edit_link = CGI::a({href=>$self->systemLink(
 1116      $urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::PGProblemEditor",
 1117         courseID =>$urlpath->arg("courseID"),
 1118         setID=>"Undefined_Set",
 1119         problemID=>"1"),
 1120       params=>{sourceFilePath => "$sourceFileName", problemSeed=> $problem_seed}
 1121       ), target=>"WW_Editor"}, "Edit it" );
 1122 
 1123   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");
 1124 
 1125   my $displayMode = $self->r->param("mydisplayMode");
 1126   $displayMode = $self->r->ce->{pg}->{options}->{displayMode}
 1127     if not defined $displayMode or $displayMode eq "None";
 1128   my $module = ( $isGatewaySet ) ? "GatewayQuiz" : "Problem";
 1129   my %pathArgs = ( courseID =>$urlpath->arg("courseID"),
 1130       setID=>"Undefined_Set" );
 1131   $pathArgs{problemID} = "1" if ( ! $isGatewaySet );
 1132 
 1133   my $try_link = CGI::a({href=>$self->systemLink(
 1134     $urlpath->newFromModule("WeBWorK::ContentGenerator::$module",
 1135       %pathArgs ),
 1136       params =>{
 1137         effectiveUser => scalar($self->r->param('user')),
 1138         editMode => "SetMaker",
 1139         problemSeed=> $problem_seed,
 1140         sourceFilePath => "$sourceFileName",
 1141         displayMode => $displayMode,
 1142       }
 1143     ), target=>"WW_View"}, "Try it");
 1144 
 1145   print CGI::div({-class=>"problem myProblem", -draggable=>"true", -href=>"#", -id=>("$cnt".'myset')},
 1146     CGI::p({},"File name: $sourceFileName "),
 1147     CGI::p({}, $edit_link, " ", $try_link),
 1148     CGI::p(CGI::checkbox((%delete_box_data),-override=>1)),
 1149     CGI::hidden(-id=>"filetrial$cnt".'myset', -name=>"mysetfiletrial$cnt", -default=>$sourceFileName,-override=>1),
 1150     CGI::p($problem_output),
 1151   );
 1152 }
 1153 
 1154 sub clear_default {
 1155   my $r = shift;
 1156   my $param = shift;
 1157   my $default = shift;
 1158   my $newvalue = $r->param($param) || '';
 1159   $newvalue = '' if($newvalue eq $default);
 1160   $r->param($param, $newvalue);
 1161 }
 1162 
 1163 sub pre_header_initialize {
 1164   my ($self) = @_;
 1165   my $r = $self->r;
 1166   ## For all cases, lets set some things
 1167   $self->{error}=0;
 1168   my $ce = $r->ce;
 1169   my $db = $r->db;
 1170   my $maxShown = $r->param('max_shown') || MAX_SHOW_DEFAULT;
 1171   $maxShown = 10000000 if($maxShown eq 'All'); # let's hope there aren't more
 1172   my $library_basic = $r->param('library_is_basic') || 1;
 1173   $self->{problem_seed} = $r->param('problem_seed') || 1234;
 1174   ## Fix some parameters
 1175   for my $key (keys(%{ LIB2_DATA() })) {
 1176     clear_default($r, LIB2_DATA->{$key}->{name}, LIB2_DATA->{$key}->{all} );
 1177   }
 1178     ##  Grab library sets to display from parameters list.  We will modify this
 1179     ##  as we go through the if/else tree
 1180     $self->{current_library_set} =  $r->param('library_sets');
 1181     $self->{current_myset_set} = $r->param('myset_sets');
 1182     if (not defined($self->{current_myset_set})
 1183     or $self->{current_myset_set} eq "Select a Homework Set"
 1184     or $self->{current_myset_set} eq NO_LOCAL_SET_STRING) {
 1185       my @all_db_sets = $db->listGlobalSets;
 1186       @all_db_sets = sortByName(undef, @all_db_sets);
 1187       $self->{current_myset_set} = shift(@all_db_sets);
 1188     }
 1189 
 1190   ##  These directories will have individual buttons
 1191   %problib = %{$ce->{courseFiles}{problibs}} if $ce->{courseFiles}{problibs};
 1192 
 1193   my $userName = $r->param('user');
 1194   my $user = $db->getUser($userName); # checked
 1195   die "record for user $userName (real user) does not exist."
 1196     unless defined $user;
 1197   my $authz = $r->authz;
 1198   unless ($authz->hasPermissions($userName, "modify_problem_sets")) {
 1199     return(""); # Error message already produced in the body
 1200   }
 1201 
 1202   ## Now one action we have to deal with here
 1203   if ($r->param('edit_local')) {
 1204     my $urlpath = $r->urlpath;
 1205     my $db = $r->db;
 1206     my $checkset = $db->getGlobalSet($r->param('local_sets'));
 1207     if (not defined($checkset)) {
 1208       $self->{error} = 1;
 1209       $self->addbadmessage('You need to select a "Target Set" before you can edit it.');
 1210     } else {
 1211       my $page = $urlpath->newFromModule('WeBWorK::ContentGenerator::Instructor::ProblemSetDetail', setID=>$r->param('local_sets'), courseID=>$urlpath->arg("courseID"));
 1212       my $url = $self->systemLink($page);
 1213       $self->reply_with_redirect($url);
 1214     }
 1215   }
 1216 
 1217   ## Next, lots of set up so that errors can be reported with message()
 1218 
 1219   ############# List of problems we have already printed
 1220 
 1221   $self->{past_problems} = get_past_problem_files($r);
 1222   # if we don't end up reusing problems, this will be wiped out
 1223   # if we do redisplay the same problems, we must adjust this accordingly
 1224   my @past_marks = map {$_->[1]} @{$self->{past_problems}};
 1225   my $none_shown = scalar(@{$self->{past_problems}})==0;
 1226   my @pg_files=();
 1227   my @myset_files=();
 1228   my $use_previous_problems = 1;
 1229   my $first_shown = $r->param('first_shown') || 0;
 1230   my $last_shown = $r->param('last_shown');
 1231   if (not defined($last_shown)) {
 1232     $last_shown = -1;
 1233   }
 1234   my @all_past_list = (); # these are include requested, but not shown
 1235   my $j = 0;
 1236   while (defined($r->param("all_past_list$j"))) {
 1237     push @all_past_list, $r->param("all_past_list$j");
 1238     $j++;
 1239   }
 1240 
 1241   ############# Default of which problem selector to display
 1242 
 1243   my $browse_which = $r->param('browse_which') || 'browse_npl_library';
 1244   my $gridded = $r->param('gridify') || 'false';
 1245 
 1246 
 1247 
 1248   ## check for problem lib buttons
 1249   my $browse_lib = '';
 1250   foreach my $lib (keys %problib) {
 1251     if ($r->param("browse_$lib")) {
 1252       $browse_lib = "browse_$lib";
 1253       last;
 1254     }
 1255   }
 1256 
 1257 
 1258   ########### Start the logic through if elsif elsif ...
 1259     debug("browse_lib", $r->param("$browse_lib"));
 1260     debug("browse_npl_library", $r->param("browse_npl_library"));
 1261     debug("edit_mysets", $r->param("edit_mysets"));
 1262     debug("browse_setdefs", $r->param("browse_setdefs"));
 1263   ##### Asked to browse certain problems
 1264   if ($browse_lib ne '') {
 1265     $browse_which = $browse_lib;
 1266     $self->{current_library_set} = "";
 1267     $use_previous_problems = 0; @pg_files = (); ## clear old problems
 1268   } elsif ($r->param('browse_npl_library')) {
 1269     $browse_which = 'browse_npl_library';
 1270     $self->{current_library_set} = "";
 1271     $use_previous_problems = 0; @pg_files = (); ## clear old problems
 1272   } elsif ($r->param('browse_local')) {
 1273     $browse_which = 'browse_local';
 1274     #$self->{current_library_set} = "";
 1275     $use_previous_problems = 0; @pg_files = (); ## clear old problems
 1276   } elsif ($r->param('edit_mysets')) {
 1277     $browse_which = 'edit_mysets';
 1278     $self->{current_library_set} = "";
 1279     $use_previous_problems = 0; @pg_files = (); ## clear old problems
 1280   } elsif ($r->param('browse_setdefs')) {
 1281     $browse_which = 'browse_setdefs';
 1282     $self->{current_library_set} = "";
 1283     $use_previous_problems = 0; @pg_files = (); ## clear old problems
 1284 
 1285     ##### Change the seed value
 1286 
 1287   } elsif ($r->param('rerandomize')) {
 1288     $self->{problem_seed}= 1+$self->{problem_seed};
 1289     #$r->param('problem_seed', $problem_seed);
 1290     $self->addbadmessage('Changing the problem seed for display, but there are no problems showing.') if $none_shown;
 1291 
 1292     ##### Clear the display
 1293 
 1294   } elsif ($r->param('cleardisplay')) {
 1295     @pg_files = ();
 1296     $use_previous_problems=0;
 1297     $self->addbadmessage('The display was already cleared.') if $none_shown;
 1298 
 1299     ##### View problems selected from the local list
 1300 
 1301   } elsif ($r->param('view_local_set')) {
 1302 
 1303     my $set_to_display = $self->{current_library_set};
 1304     if (not defined($set_to_display) or $set_to_display eq SELECT_LOCAL_STRING or $set_to_display eq "Found no directories containing problems") {
 1305       $self->addbadmessage('You need to select a set to view.');
 1306     } else {
 1307       $set_to_display = '.' if $set_to_display eq MY_PROBLEMS;
 1308       $set_to_display = substr($browse_which,7) if $set_to_display eq MAIN_PROBLEMS;
 1309       @pg_files = list_pg_files($ce->{courseDirs}->{templates},
 1310         "$set_to_display");
 1311       $use_previous_problems=0;
 1312     }
 1313 
 1314     ##### View problems selected from the a set in this course
 1315   } elsif ($r->param('edit_mysets_set')){
 1316 
 1317     my $set_to_display = $self->{current_library_set};
 1318       debug("set_to_display is $set_to_display");
 1319       if (not defined($set_to_display)
 1320           or $set_to_display eq "Select a Homework Set"
 1321           or $set_to_display eq NO_LOCAL_SET_STRING) {
 1322         $self->addbadmessage("You need to select a set from this course to view.");
 1323       } else {
 1324         # DBFIXME don't use ID list, use an iterator
 1325         my @problemList = $db->listGlobalProblems($set_to_display);
 1326         my $problem;
 1327         @pg_files=();
 1328         for $problem (@problemList) {
 1329           my $problemRecord = $db->getGlobalProblem($set_to_display, $problem); # checked
 1330           die "global $problem for set $set_to_display not found." unless
 1331             $problemRecord;
 1332           push @pg_files, $problemRecord->source_file;
 1333 
 1334         }
 1335         @pg_files = sortByName(undef,@pg_files);
 1336         $use_previous_problems=0;
 1337       }
 1338 
 1339     ##### View from the library database
 1340 
 1341   } elsif ($r->param('lib_view')) {
 1342     @pg_files=();
 1343     my @dbsearch = WeBWorK::Utils::ListingDB::getSectionListings($r);
 1344     my ($result, $tolibpath);
 1345     for $result (@dbsearch) {
 1346       $tolibpath = "Library/$result->{path}/$result->{filename}";
 1347 
 1348       ## Too clunky!!!!
 1349       push @pg_files, $tolibpath;
 1350     }
 1351     $use_previous_problems=0;
 1352 
 1353     ##### View a set from a set*.def
 1354 
 1355   } elsif ($r->param('view_setdef_set')) {
 1356 
 1357     my $set_to_display = $self->{current_library_set};
 1358     debug("set_to_display is $set_to_display");
 1359     if (not defined($set_to_display)
 1360         or $set_to_display eq "Select a Set Definition File"
 1361         or $set_to_display eq NO_LOCAL_SET_STRING) {
 1362       $self->addbadmessage("You need to select a set definition file to view.");
 1363     } else {
 1364       @pg_files= $self->read_set_def($set_to_display);
 1365     }
 1366     $use_previous_problems=0;
 1367 
 1368     ##### Edit the current local homework set
 1369 
 1370   } elsif ($r->param('edit_local')) { ## Jump to set edit page
 1371 
 1372     ; # already handled
 1373 
 1374 
 1375     ##### Make a new local homework set
 1376 
 1377   } elsif ($r->param('new_local_set')) {
 1378     if ($r->param('new_set_name') !~ /^[\w .-]*$/) {
 1379       $self->addbadmessage("The name ".$r->param('new_set_name')." is not a valid set name.  Use only letters, digits, -, _, and .");
 1380     } else {
 1381       my $newSetName = $r->param('new_set_name');
 1382       # if we want to munge the input set name, do it here
 1383       $newSetName =~ s/\s/_/g;
 1384       debug("local_sets was ", $r->param('local_sets'));
 1385       $r->param('local_sets',$newSetName);  ## use of two parameter param
 1386       debug("new value of local_sets is ", $r->param('local_sets'));
 1387       my $newSetRecord   = $db->getGlobalSet($newSetName);
 1388       if (defined($newSetRecord)) {
 1389               $self->addbadmessage("The set name $newSetName is already in use.
 1390               Pick a different name if you would like to start a new set.");
 1391       } else {      # Do it!
 1392         # DBFIXME use $db->newGlobalSet
 1393         $newSetRecord = $db->{set}->{record}->new();
 1394         $newSetRecord->set_id($newSetName);
 1395         $newSetRecord->set_header("");
 1396         $newSetRecord->hardcopy_header("");
 1397         $newSetRecord->open_date(time()+60*60*24*7); # in one week
 1398         $newSetRecord->due_date(time()+60*60*24*7*2); # in two weeks
 1399         $newSetRecord->answer_date(time()+60*60*24*7*3); # in three weeks
 1400         eval {$db->addGlobalSet($newSetRecord)};
 1401         if ($@) {
 1402           $self->addbadmessage("Problem creating set $newSetName<br> $@");
 1403         } else {
 1404           $self->addgoodmessage("Set $newSetName has been created.");
 1405           my $selfassign = $r->param('selfassign') || "";
 1406           $selfassign = "" if($selfassign =~ /false/i); # deal with javascript false
 1407           if($selfassign) {
 1408             $self->assignSetToUser($userName, $newSetRecord);
 1409             $self->addgoodmessage("Set $newSetName was assigned to $userName.");
 1410           }
 1411         }
 1412       }
 1413     }
 1414 
 1415     ##### Add selected problems to the current local set
 1416 
 1417   } elsif ($r->param('update')) {
 1418     $self->addgoodmessage("the update param exists");
 1419     ## first handle problems to be added before we hide them
 1420     my($localSet, @selected);
 1421 
 1422     my @add_pg_files = grep {(($_->[1] & ADDED)) != 0 } @{$self->{past_problems}};
 1423     my @add_selected = map {$_->[0]} @add_pg_files;
 1424 
 1425     my @delete_pg_files = grep {(($_->[1] & DELETED)) != 0} @{$self->{past_problems}};
 1426     my @delete_selected = map {$_->[0]} @delete_pg_files;
 1427 
 1428     my @move_pg_files = grep {(($_->[1] & MOVED)) != 0} @{$self->{past_problems}};
 1429     my @move_selected = map {$_->[0]} @move_pg_files;
 1430 
 1431     my @action_files = grep {$_->[1] > 0 } @{$self->{past_problems}};
 1432     # There are now good reasons to do an update without selecting anything.
 1433     #if(scalar(@action_files) == 0) {
 1434     #  $self->addbadmessage('Update requested, but no problems were marked.');
 1435     #}
 1436 
 1437     if (scalar(@add_selected)>0) {  # if some are to be added, they need a place to go
 1438       $localSet = $r->param('myset_sets');
 1439       if (not defined($localSet) or
 1440           $localSet eq SELECT_SET_STRING or
 1441                 $localSet eq NO_LOCAL_SET_STRING) {
 1442         $self->addbadmessage('You are trying to add problems to something,
 1443         but you did not select a "Target Set" name as a target.');
 1444       } else {
 1445         my $newSetRecord  = $db->getGlobalSet($localSet);
 1446         if (not defined($newSetRecord)) {
 1447           $self->addbadmessage("You are trying to add problems to $localSet,
 1448           but that set does not seem to exist!  I bet you used your \"Back\" button.");
 1449         } else {
 1450           my $addcount = add_selected($self, $db, $localSet);
 1451           if($addcount > 0) {
 1452             $self->addgoodmessage("Added $addcount problem".(($addcount>1)?'s':'').
 1453               " to $localSet.");
 1454           }
 1455         }
 1456       }
 1457     }
 1458     if (scalar(@delete_selected)>0) { # if some are to be added, they need a place to go
 1459       $localSet = $r->param('myset_sets');
 1460       if (not defined($localSet) or
 1461           $localSet eq SELECT_SET_STRING or
 1462                 $localSet eq NO_LOCAL_SET_STRING) {
 1463         $self->addbadmessage('You are trying to add problems to something,
 1464         but you did not select a "Target Set" name as a target.');
 1465       } else {
 1466         my $newSetRecord  = $db->getGlobalSet($localSet);
 1467         if (not defined($newSetRecord)) {
 1468           $self->addbadmessage("You are trying to delete problems to $localSet,
 1469           but that set does not seem to exist!  I bet you used your \"Back\" button.");
 1470         } else {
 1471           my $deletecount = delete_selected($self, $db, $localSet);
 1472           if($deletecount > 0) {
 1473             $self->addgoodmessage("Deleted $deletecount problem".(($deletecount>1)?'s':'').
 1474               " to $localSet.");
 1475           }
 1476         }
 1477       }
 1478     }
 1479     if (scalar(@move_selected)>0) { # if some are to be added, they need a place to go
 1480       $localSet = $r->param('myset_sets');
 1481       my $otherSet = $self->{current_library_set};
 1482       if (not defined($localSet) or not defined($otherSet) or
 1483           $localSet eq SELECT_SET_STRING or
 1484                 $localSet eq NO_LOCAL_SET_STRING) {
 1485         $self->addbadmessage('You are trying to add problems to something,
 1486         but you did not select a "Target Set" name as a target.');
 1487       } else {
 1488         my $newSetRecord  = $db->getGlobalSet($localSet);
 1489         my $otherNewSetRecord = $db->getGlobalSet($otherSet);
 1490         if (not defined($newSetRecord) or not defined($otherNewSetRecord)) {
 1491           $self->addbadmessage("You are trying to move problems from $otherSet to $localSet,
 1492           but that set does not seem to exist!  I bet you used your \"Back\" button.");
 1493         } else {
 1494           my $addcount = add_selected($self, $db, $localSet);
 1495           my $deletecount = delete_selected($self, $db, $otherSet);
 1496           if($addcount > 0 && $deletecount > 0) {
 1497             $self->addgoodmessage("Moved $addcount problem".(($addcount>1)?'s':'').
 1498               " from $otherSet to $localSet.");
 1499           }
 1500         }
 1501       }
 1502     }
 1503     ## now handle problems to be hidden
 1504 
 1505     ## only keep the ones which are not hidden
 1506     @pg_files = grep {($_->[1] & HIDDEN) ==0 } @{$self->{past_problems}};
 1507     @pg_files = grep {(($_->[1] & DELETED)) != 0 } @pg_files;
 1508     @past_marks = map {$_->[1]} @pg_files;
 1509     @pg_files = map {$_->[0]} @pg_files;
 1510     @all_past_list = (@all_past_list[0..($first_shown-1)],
 1511           @pg_files,
 1512           @all_past_list[($last_shown+1)..(scalar(@all_past_list)-1)]);
 1513     $last_shown = $first_shown+$maxShown -1; debug("last_shown 3: ", $last_shown);
 1514     $last_shown = (scalar(@all_past_list)-1) if($last_shown>=scalar(@all_past_list)); debug("last_shown 4: ", $last_shown);
 1515 
 1516     #want to reorder in addition to anything else
 1517     if ($r->param('isReordered')){
 1518     #this might work, i'm not sure if this is the right ID
 1519       reorderProblems($self, $db, $r->param('myset_sets'), $r);
 1520     }
 1521 
 1522   } elsif ($r->param('next_page')) {
 1523     $first_shown = $last_shown+1;
 1524     $last_shown = $first_shown+$maxShown-1; debug("last_shown 5: ", $last_shown);
 1525     $last_shown = (scalar(@all_past_list)-1) if($last_shown>=scalar(@all_past_list)); debug("last_shown 6: ", $last_shown);
 1526     $self->addgoodmessage("It sees the next_page parameter, last shown is: $last_shown and first shown is: $first_shown");
 1527     @past_marks = ();
 1528   } elsif ($r->param('prev_page')) {
 1529     $last_shown = $first_shown-1;
 1530     $first_shown = $last_shown - $maxShown+1;
 1531 
 1532     $first_shown = 0 if($first_shown<0);
 1533     @past_marks = ();
 1534 
 1535   } elsif ($r->param('select_all')) {
 1536     @past_marks = map {1} @past_marks;
 1537   } elsif ($r->param('library_basic')) {
 1538     $library_basic = 1;
 1539     for my $jj (qw(textchapter textsection textbook)) {
 1540       $r->param('library_'.$jj,'');
 1541     }
 1542   } elsif ($r->param('library_advanced')) {
 1543     $library_basic = 2;
 1544   } elsif ($r->param('library_reset')) {
 1545     for my $jj (qw(chapters sections subjects textbook keywords)) {
 1546       $r->param('library_'.$jj,'');
 1547     }
 1548   } elsif ($r->param('select_none')) {
 1549     @past_marks = ();
 1550   } else {
 1551     #nothing
 1552   }       ##### end of the if elsif ...
 1553 
 1554   #I'm worried this will break something
 1555   my $default_set = $self->{current_myset_set};
 1556     #debug("set_to_display is $default_set");
 1557     if (not defined($default_set)
 1558       or $default_set eq "Select a Homework Set"
 1559       or $default_set eq NO_LOCAL_SET_STRING) {
 1560       $self->addbadmessage("You need to select a set from this course to view.");
 1561     } else {
 1562       # DBFIXME don't use ID list, use an iterator
 1563       my @problemList = $db->listGlobalProblems($default_set);
 1564       my $problem;
 1565       @myset_files=();
 1566       for $problem (@problemList) {
 1567         my $problemRecord = $db->getGlobalProblem($default_set, $problem); # checked
 1568         die "global $problem for set $default_set not found." unless
 1569           $problemRecord;
 1570         push @myset_files, $problemRecord->source_file;
 1571 
 1572       }
 1573       #@myset_files = sortByName(undef,@myset_files);
 1574     }
 1575 
 1576   ############# List of local sets
 1577 
 1578   # DBFIXME sorting in database, please!
 1579   my @all_db_sets = $db->listGlobalSets;
 1580   @all_db_sets = sortByName(undef, @all_db_sets);
 1581 
 1582   if ($use_previous_problems) {
 1583     @pg_files = @all_past_list;
 1584   } else {
 1585     $first_shown = 0;
 1586     $last_shown = scalar(@pg_files)<$maxShown ? scalar(@pg_files) : $maxShown;
 1587     $last_shown--;    # to make it an array index
 1588     @past_marks = ();
 1589   }
 1590   ############# Now store data in self for retreival by body
 1591   $self->{first_shown} = $first_shown;
 1592   $self->{last_shown} = $last_shown;
 1593   $self->{browse_which} = $browse_which;
 1594   $self->{gridded} = $gridded;
 1595   #$self->{problem_seed} = $problem_seed;
 1596   $self->{pg_files} = \@pg_files;
 1597   $self->{myset_files} = \@myset_files;
 1598   $self->{past_marks} = \@past_marks;
 1599   $self->{all_db_sets} = \@all_db_sets;
 1600   $self->{library_basic} = $library_basic;
 1601   debug("past_marks is ", join(" ", @{$self->{past_marks}}));
 1602 }
 1603 
 1604 
 1605 sub title {
 1606   return "Library Browser v2";
 1607 }
 1608 
 1609 # hide view options panel since it distracts from SetMaker's built-in view options
 1610 sub options {
 1611   return "";
 1612 }
 1613 
 1614 sub head {
 1615   print '<script src="/webwork2_files/js/dnd.js"></script>';
 1616   print '<script src="/webwork2_files/js/problem_grid.js"></script>';
 1617   print '<script src="/webwork2_files/js/form_builder.js"></script>';
 1618   #my ($self) = @_;
 1619   #my $r = $self->r;
 1620   #start a timer to save people's stuff idk if people want this
 1621   #print "<script> setInterval('saveChanges(\"mainform\", \"".$r->uri."\")', 680000); </script>";
 1622   print '<link rel="stylesheet" type="text/css" href="/webwork2_files/css/setmaker2.css" />';
 1623   print '<script>window.addEventListener("load", setup, false);</script>';
 1624   return "";
 1625 }
 1626 
 1627 sub body {
 1628   my ($self) = @_;
 1629 
 1630   my $r = $self->r;
 1631   my $ce = $r->ce;    # course environment
 1632   my $db = $r->db;    # database
 1633   my $j;      # garden variety counter
 1634 
 1635   my $userName = $r->param('user');
 1636 
 1637   my $user = $db->getUser($userName); # checked
 1638   die "record for user $userName (real user) does not exist."
 1639     unless defined $user;
 1640 
 1641   ### Check that this is a professor
 1642   my $authz = $r->authz;
 1643   unless ($authz->hasPermissions($userName, "modify_problem_sets")) {
 1644     print "User $userName returned " .
 1645       $authz->hasPermissions($user, "modify_problem_sets") .
 1646   " for permission";
 1647     return(CGI::div({class=>'ResultsWithError'},
 1648     CGI::em("You are not authorized to access the Instructor tools.")));
 1649   }
 1650 
 1651   my $showHints = $r->param('showHints');
 1652   my $showSolutions = $r->param('showSolutions');
 1653 
 1654   ##########  Extract information computed in pre_header_initialize
 1655 
 1656   my $first_shown = $self->{first_shown};
 1657   my $last_shown = $self->{last_shown};
 1658   my $browse_which = $self->{browse_which};
 1659   my $gridded = $self->{gridded};
 1660   my $problem_seed = $self->{problem_seed}||1234;
 1661   my @pg_files = @{$self->{pg_files}};
 1662   my @myset_files =@{$self->{myset_files}};
 1663   my @all_db_sets = @{$self->{all_db_sets}};
 1664 
 1665   my $displayModePlaceholder;
 1666   if (not defined($r->param('mydisplayMode'))){
 1667     $displayModePlaceholder = "images";
 1668   }
 1669   else{
 1670     $displayModePlaceholder = $r->param('mydisplayMode');
 1671   }
 1672 
 1673   my @pg_html;
 1674   if ($last_shown >= $first_shown) {
 1675     @pg_html = renderProblems(
 1676       r=> $r,
 1677       user => $user,
 1678       problem_list => [@pg_files[$first_shown..$last_shown]],
 1679       displayMode => $displayModePlaceholder,
 1680       showHints => $showHints,
 1681       showSolutions => $showSolutions,
 1682     );
 1683   }
 1684   my @myset_html;
 1685 
 1686   @myset_html = renderProblems(
 1687     r=> $r,
 1688     user => $user,
 1689     problem_list => [@myset_files],
 1690     displayMode => $displayModePlaceholder,
 1691     showHints => $showHints,
 1692     showSolutions => $showSolutions,
 1693   );
 1694 
 1695   my %isInSet;
 1696   my $setName = $r->param("myset_sets");
 1697   if ($setName) {
 1698     # DBFIXME where clause, iterator
 1699     # DBFIXME maybe instead of hashing here, query when checking source files?
 1700     # DBFIXME definitely don't need to be making full record objects
 1701     # DBFIXME SELECT source_file FROM whatever_problem WHERE set_id=? GROUP BY source_file ORDER BY NULL;
 1702     # DBFIXME (and stick result directly into hash)
 1703     foreach my $problem ($db->listGlobalProblems($setName)) {
 1704       my $problemRecord = $db->getGlobalProblem($setName, $problem);
 1705       $isInSet{$problemRecord->source_file} = 1;
 1706     }
 1707   }
 1708   $self->{isInSet} = \%isInSet;
 1709   my $jj;
 1710   ##########  Loading Screen
 1711   print '<div id="loading"></div>';
 1712 
 1713   ##########  Top part
 1714   print '<span><button id="gridifyButton" onclick="gridify();">Gridify!!</button>';
 1715   print '<span>Hover Magnification: <button type="button" onclick="increaseMagnification();">+</button><span id="magnification">1</span><button type="button" onclick="decreaseMagnification();">-</button></span></span>';
 1716   print '<button type="button" onclick="toggleHelp(this);" value="false">?</button>';
 1717   print '<div id="help" style="display:none;position:absolute;z-index:1500;background:white;" class="shadowed">',
 1718           '<h1>What can you do?</h1>',
 1719           '<p>Drag a problem from the library to the target set to add.</p>',
 1720           '<p>Drag a problem set off the target set to remove.</p>',
 1721           '<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>',
 1722           '<h1>Legend</h1>',
 1723           '<p><div class="problem" style="width:16px;height:16px;border:solid 1px;"></div><span>Normal problem</span></p>',
 1724           '<p><div class="used" style="width:16px;height:16px;border:solid 1px;"></div><span>Problem already in set</span></p>',
 1725           '<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>',
 1726           '<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>',
 1727           '<p><div class="ResultsWithError" style="width:16px;height:16px;border:solid 1px;"></div><span>Errors</span></p>',
 1728         '</div>';
 1729         #'<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>',
 1730   print '<span><button type="button" style="float:right;" onclick="saveChanges(\'mainform\', \''.$r->uri.'\', \'save_changes_spinner\');">save changes</button><img id="save_changes_spinner" style="display:none;float:right;" src="/webwork2_files/images/ajax-loader-small.gif"></img></span>';
 1731   print '<div id="editor-form">';
 1732     print CGI::start_form({-id=>"mainform", -method=>"POST", -action=>$r->uri, -name=>'mainform'}),
 1733       $self->hidden_authen_fields;
 1734 
 1735       #print '<div id="control_panel">';
 1736         #print '<div id="myset_control" class="mysets control">';
 1737 
 1738         #some work for the moved controls
 1739         my $list_of_local_sets = $self->{all_db_sets};
 1740         my $have_local_sets = scalar(@$list_of_local_sets);
 1741         my $library_selected = $self->{current_library_set};
 1742         my $set_selected = $r->param('local_sets');
 1743 
 1744         if($have_local_sets ==0) {
 1745           $list_of_local_sets = [NO_LOCAL_SET_STRING];
 1746         } elsif (not defined($set_selected) or $set_selected eq ""
 1747           or $set_selected eq SELECT_SET_STRING) {
 1748           unshift @{$list_of_local_sets}, SELECT_SET_STRING;
 1749           $set_selected = SELECT_SET_STRING;
 1750         }
 1751 
 1752         # Tidy this list up since it is used in two different places
 1753         if ($list_of_local_sets->[0] eq SELECT_SET_STRING) {
 1754           shift @{$list_of_local_sets};
 1755         }
 1756         #print '</div>';
 1757 
 1758       #print '</div>';
 1759       print '<div style="clear:both;padding:0px;margin:0px;"></div>';
 1760       #########  Table of mysets problems
 1761       print '<div id="problem_container">';
 1762         print '<div id="mysets_problems_box" class="mysets">';
 1763         print '<h1>Target Set</h1>';
 1764         print '<div class="setSelector">';
 1765                 #work for moved controlls
 1766                 $list_of_local_sets = $self->{all_db_sets};
 1767                 $have_local_sets = scalar(@$list_of_local_sets);
 1768                 $library_selected = $self->{current_myset_set};
 1769                 $set_selected = $r->param('myset_sets');
 1770                 my $remember_local_set = $r->param('local_sets');
 1771 
 1772                 my $these_widths = "width: 25ex";
 1773 
 1774                 if($have_local_sets ==0) {
 1775                   $list_of_local_sets = [NO_LOCAL_SET_STRING];
 1776                 } elsif (not defined($set_selected) or $set_selected eq ""
 1777                 or $set_selected eq SELECT_SET_STRING) {
 1778                   unshift @{$list_of_local_sets}, SELECT_SET_STRING;
 1779                   $set_selected = SELECT_SET_STRING;
 1780                 }
 1781                 # Tidy this list up since it is used in two different places
 1782                 if ($list_of_local_sets->[0] eq SELECT_SET_STRING) {
 1783                   shift @{$list_of_local_sets};
 1784                 }
 1785 
 1786                 $self->browse_mysets_panel($library_selected, $list_of_local_sets, $remember_local_set);
 1787                 $self->make_mysets_row('all_db_sets'=>\@all_db_sets);
 1788         print '</div>';
 1789         print '<div id="mysets_problems" class="problemList">';
 1790           for ($jj=0; $jj<scalar(@myset_html); $jj++) {
 1791             $myset_files[$jj] =~ s|^$ce->{courseDirs}->{templates}/?||;
 1792             $self->make_myset_data_row($myset_files[$jj], $myset_html[$jj], $jj+1, $self->{past_marks}->[$jj]);
 1793           }
 1794       print '</div>';
 1795       print '<p><button type="button" onclick="increasMysetsAcross();">+</button><span id="mysetsAcross">1</span><button type="button" onclick="decreaseMysetsAcross();">-</button><span> problems across</span></p>';
 1796         print '</div>';
 1797         print '<div id="size_slider"><p>||</p></div>';
 1798 
 1799         #some work for the moved controls
 1800         $list_of_local_sets = $self->{all_db_sets};
 1801         $have_local_sets = scalar(@$list_of_local_sets);
 1802         $library_selected = $self->{current_library_set};
 1803         $set_selected = $r->param('local_sets');
 1804 
 1805         if($have_local_sets ==0) {
 1806           $list_of_local_sets = [NO_LOCAL_SET_STRING];
 1807         } elsif (not defined($set_selected) or $set_selected eq ""
 1808           or $set_selected eq SELECT_SET_STRING) {
 1809           unshift @{$list_of_local_sets}, SELECT_SET_STRING;
 1810           $set_selected = SELECT_SET_STRING;
 1811         }
 1812 
 1813         # Tidy this list up since it is used in two different places
 1814         if ($list_of_local_sets->[0] eq SELECT_SET_STRING) {
 1815           shift @{$list_of_local_sets};
 1816         }
 1817 
 1818         print '<div id="setmaker_library_box" class="setmaker_library">';
 1819           print '<h1>Library</h1>';
 1820           print '<div class="setSelector">';
 1821             ###########################################
 1822             # Library repository controls
 1823             ###########################################
 1824             print '<div id="setmaker_library" class="control">';
 1825               $self->make_top_row('all_db_sets'=>\@all_db_sets, 'browse_which'=> $browse_which);
 1826               print '<div id="library_categories">';
 1827                 #misplaced controlls
 1828                 if ($browse_which eq 'browse_local') {
 1829                   $self->browse_local_panel($library_selected);
 1830                 } elsif ($browse_which eq 'edit_mysets') {
 1831                   $self->edit_mysets_panel($library_selected, $list_of_local_sets);
 1832                 } elsif ($browse_which eq 'browse_npl_library') {
 1833                   $self->browse_library_panel();
 1834                 } elsif ($browse_which eq 'browse_setdefs') {
 1835                   $self->browse_setdef_panel($library_selected);
 1836                 } else { ## handle other problem libraries
 1837                   $self->browse_local_panel($library_selected,$browse_which);
 1838                 }
 1839               print '</div>';
 1840             print '</div>';
 1841             ###########################################
 1842           print '</div>';
 1843 
 1844           print '<div class="setSelectorLib">';#what is this?
 1845           print '</div>';
 1846           #hidden inputs for memeory
 1847           #remember gridify
 1848           print '<div id="setmaker_library_data">';
 1849           print CGI::hidden(-id=>'pastGridded', -name=>'gridify', -value=>$gridded, -override=>1);
 1850           print CGI::hidden(-id=>'isReordered', -name=>'isReordered', -vale=>0 ,-override=>0);
 1851           print CGI::hidden(-name=>'browse_which', -value=>$browse_which,-override=>1),
 1852           CGI::hidden(-name=>'problem_seed', -value=>$problem_seed, -override=>1);
 1853           for ($j = 0 ; $j < scalar(@pg_files) ; $j++) {
 1854             print CGI::hidden(-name=>"all_past_list$j", -value=>$pg_files[$j],-override=>1);
 1855           }
 1856           print CGI::hidden(-name=>'first_shown', -value=>$first_shown,-override=>1);
 1857           print CGI::hidden(-name=>'last_shown', -value=>$last_shown, -override=>1);
 1858           print '<div id="setmaker_library_problems" class="problemList">';
 1859           ########## Now print problems
 1860             for ($jj=0; $jj<scalar(@pg_html); $jj++) {
 1861               $pg_files[$jj] =~ s|^$ce->{courseDirs}->{templates}/?||;
 1862               $self->make_data_row($pg_files[$jj+$first_shown], $pg_html[$jj], $jj+1,         $self->{past_marks}->[$jj]);
 1863             }
 1864           print '</div>';
 1865           print '<p><button type="button" onclick="increaseLibAcross();">+</button><span id="libAcross">4</span><button type="button" onclick="decreaseLibAcross();">-</button><span> problems across</span></p>';
 1866           ########## Finish things off
 1867           my ($next_button, $prev_button) = ("", "");
 1868           if ($first_shown > 0) {
 1869             #$prev_button = CGI::submit(-name=>"prev_page", -style=>"width:15ex", -value=>"Previous page");
 1870             my $urlpath = $r->urlpath;
 1871             my $getProblemPath = $self->systemLink($urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::GetLibrarySetProblems", courseID =>$urlpath->arg("courseID")));
 1872             $prev_button = "<span><button type='button' onclick='viewProblems(\"prev_page\" ,\"mainform\", \"".$getProblemPath."\", \"prev_spinner\");'>Previous page</button><img id='prev_spinner' style='display:none;' src='/webwork2_files/images/ajax-loader-small.gif'></img></span>";
 1873           }
 1874           if ((1+$last_shown)<scalar(@pg_files)) {
 1875             #$next_button = CGI::submit(-name=>"next_page", -style=>"width:15ex", -value=>"Next page");
 1876             my $urlpath = $r->urlpath;
 1877             my $getProblemPath = $self->systemLink($urlpath->newFromModule("WeBWorK::ContentGenerator::Instructor::GetLibrarySetProblems", courseID =>$urlpath->arg("courseID")));
 1878             $next_button = "<span><button type='button' onclick='viewProblems(\"next_page\" ,\"mainform\", \"".$getProblemPath."\", \"next_spinner\");'>Next page</button><img id='next_spinner' style='display:none;' src='/webwork2_files/images/ajax-loader-small.gif'></img></span>";
 1879           }
 1880           if (scalar(@pg_files)>0) {
 1881             print CGI::p(($first_shown+1)."-".($last_shown+1)." of ".scalar(@pg_files)." shown.", $prev_button, " ", $next_button,
 1882             '<span><button type="button" style="float:right;" onclick="saveChanges(\'mainform\', \''.$r->uri.'\', \'save_changes_spinner2\');">save changes</button><img id="save_changes_spinner2" style="display:none;float:right;" src="/webwork2_files/images/ajax-loader-small.gif"></img></span>');
 1883           }
 1884           #close setmaker_library_data
 1885           print '</div>';
 1886           #close setmaker_library
 1887         print '</div>';
 1888       #close problem_container
 1889       print '</div>';
 1890     print CGI::endform(), "\n";
 1891     #close form-editor
 1892   print '</div>';
 1893   print '<div style="clear:both;"></div>';
 1894   #  if($first_shown>0 or (1+$last_shown)<scalar(@pg_files)) {
 1895 
 1896   #  }
 1897 
 1898 
 1899   return "";
 1900 }
 1901 
 1902 =head1 AUTHOR
 1903 
 1904 Written by John Jones, jj (at) asu.edu.
 1905 Edited by David Gage
 1906 
 1907 =cut
 1908 
 1909 1;

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9